From cc5d963d01864c9255e8ee4c3bb7c3456df978d0 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 23 Apr 2021 12:00:19 +0200 Subject: [PATCH 001/770] Porting reconstruction code --- .../ZDC/include/DataFormatsZDC/RecEvent.h | 35 +- .../ZDC/base/include/ZDCBase/Constants.h | 18 + Detectors/ZDC/reconstruction/CMakeLists.txt | 4 + .../include/ZDCReconstruction/DigiReco.h | 63 +++ .../include/ZDCReconstruction/RecoParamZDC.h | 50 ++ .../ZDCReconstruction/ZDCIntegrationParam.h | 42 ++ .../include/ZDCReconstruction/ZDCTDCParam.h | 40 ++ Detectors/ZDC/reconstruction/src/DigiReco.cxx | 429 ++++++++++++++++++ .../ZDC/reconstruction/src/RecoParamZDC.cxx | 24 + .../src/ZDCIntegrationParam.cxx | 49 ++ .../ZDC/reconstruction/src/ZDCTDCParam.cxx | 47 ++ 11 files changed, 790 insertions(+), 11 deletions(-) create mode 100644 Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h create mode 100644 Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h create mode 100644 Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCIntegrationParam.h create mode 100644 Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h create mode 100644 Detectors/ZDC/reconstruction/src/DigiReco.cxx create mode 100644 Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx create mode 100644 Detectors/ZDC/reconstruction/src/ZDCIntegrationParam.cxx create mode 100644 Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h index 1b70cb64e731b..a9350727c74d0 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h @@ -27,18 +27,31 @@ namespace zdc { struct RecEvent { - using TDCChannel = std::array; - + //using TDCChannel = std::array; + //using TDCAmplitude = std::array; + //using TDCChannel = std::vector; + //using TDCAmplitude = std::vector; o2::InteractionRecord ir; - uint32_t flags; /// reconstruction flags - std::array energyZEM; /// signal in the electromagnetic ZDCs - std::array energyZNA; /// reco E in 5 ZNA sectors + sum - std::array energyZNC; /// reco E in 5 ZNC sectors + sum - std::array energyZPA; /// reco E in 5 ZPA sectors + sum - std::array energyZPC; /// reco E in 5 ZPC sectors + sum - math_utils::Point2D centroidZNA; /// centroid coordinates for ZNA - math_utils::Point2D centroidZNC; /// centroid coordinates for ZNC - std::array tdcChannels; /// At most MaxTDCValues Values in ns per TDC channel + uint32_t flags; /// reconstruction flags +// std::array energyZEM; /// signal in the electromagnetic ZDCs +// std::array energyZNA; /// reco E in 5 ZNA sectors + sum +// std::array energyZNC; /// reco E in 5 ZNC sectors + sum +// std::array energyZPA; /// reco E in 5 ZPA sectors + sum +// std::array energyZPC; /// reco E in 5 ZPC sectors + sum + float energyZEM[NChannelsZEM]; /// signal in the electromagnetic ZDCs + float energyZNA[NChannelsZN]; /// reco E in 5 ZNA sectors + sum + float energyZNC[NChannelsZN]; /// reco E in 5 ZNC sectors + sum + float energyZPA[NChannelsZP]; /// reco E in 5 ZPA sectors + sum + float energyZPC[NChannelsZP]; /// reco E in 5 ZPC sectors + sum + math_utils::Point2D centroidZNA; /// centroid coordinates for ZNA + math_utils::Point2D centroidZNC; /// centroid coordinates for ZNC + //std::array tdcChannels; /// At most MaxTDCValues Values in ns per TDC channel + //std::array tdcAmplitudes; /// At most MaxTDCValues Values in ns per TDC channel + int16_t tdcChannels[NTDCChannels][MaxTDCValues]; /// TdcChannels + float tdcAmplitudes[NTDCChannels][MaxTDCValues]; /// TdcAmplitudes + std::array pattern; /// Pattern of TDC + Short_t fired[NTDCChannels][NTimeBinsPerBC] = {0}; /// Position at which the trigger algorithm is fired + float inter[NTDCChannels][NTimeBinsPerBC * TSN] = {0}; /// Interpolated samples void print() const; diff --git a/Detectors/ZDC/base/include/ZDCBase/Constants.h b/Detectors/ZDC/base/include/ZDCBase/Constants.h index c834344b2d071..b773bfda76383 100644 --- a/Detectors/ZDC/base/include/ZDCBase/Constants.h +++ b/Detectors/ZDC/base/include/ZDCBase/Constants.h @@ -63,6 +63,11 @@ constexpr int ADCMin = -2048, ADCMax = 2047, ADCRange = 4096; // 12 bit ADC constexpr int MaxTDCValues = 5; // max number of TDC values to store in reconstructed event constexpr int NTDCChannels = 10; // max number of TDC values to store in reconstructed event +// Parameters of interpolating function +constexpr int TSL = 6; // number of zeros on the right (and on the left) of central peak +constexpr int TSN = 200; // Number of interpolated points between each pair = TSN-1 +constexpr int TSNS = 96; // Number of interpolated points per ns +constexpr int NTS = 2 * TSL * TSN + 1; //Tapered sinc function array size enum TDCChannelID { TDCZNAC, TDCZNAS, @@ -155,6 +160,19 @@ constexpr std::string_view ChannelNames[] = { "ZPC4", "ZPCS"}; +const int TDCSignal[NTDCChannels] = { + IdZNAC, // TDCZNAC + IdZNASum, // TDCZNAS + IdZPAC, // TDCZPAC + IdZPASum, // TDCZPAS + IdZEM1, // TDCZEM1 + IdZEM2, // TDCZEM2 + IdZNCC, // TDCZNCC + IdZNCSum, // TDCZNCS + IdZPCC, // TDCZPCC + IdZPCSum // TDCZPCS +}; + // paths to CCDB objects // TODO: eventually these paths should be retrieved from NameConfigurator class // TODO: we would better use "constexpr string_view" here, but it makes sense only if diff --git a/Detectors/ZDC/reconstruction/CMakeLists.txt b/Detectors/ZDC/reconstruction/CMakeLists.txt index cf9a288d2bc57..cde859dd602ce 100644 --- a/Detectors/ZDC/reconstruction/CMakeLists.txt +++ b/Detectors/ZDC/reconstruction/CMakeLists.txt @@ -11,8 +11,12 @@ o2_add_library(ZDCReconstruction SOURCES src/CTFCoder.cxx src/CTFHelper.cxx + src/DigiReco.cxx + src/RecoParamZDC.cxx + src/ZDCTDCParam.cxx PUBLIC_LINK_LIBRARIES O2::ZDCBase O2::DataFormatsZDC + O2::ZDCSimulation O2::DetectorsRaw AliceO2::InfoLogger O2::rANS diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h new file mode 100644 index 0000000000000..14c342387a8f2 --- /dev/null +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h @@ -0,0 +1,63 @@ +#include +#include +#include +#include "ZDCBase/Constants.h" +#include "ZDCSimulation/ZDCSimParam.h" +#include "ZDCReconstruction/RecoParamZDC.h" +#include "ZDCReconstruction/ZDCTDCParam.h" +#include "ZDCReconstruction/ZDCIntegrationParam.h" +#include "ZDCBase/ModuleConfig.h" +#include "DataFormatsZDC/BCData.h" +#include "DataFormatsZDC/ChannelData.h" +#include "DataFormatsZDC/OrbitData.h" +#include "DataFormatsZDC/RecEvent.h" + +#ifndef ALICEO2_ZDC_DIGI_RECO_H +#define ALICEO2_ZDC_DIGI_RECO_H +namespace o2 +{ +namespace zdc +{ +class DigiReco +{ + public: + DigiReco() = default; + void init(); + int process(const std::vector *orbitdata, const std::vector *bcdata, std::vector *chdata); + int write(); + void setVerbosity(int v) + { + mVerbosity = v; + } + int getVerbosity() const { return mVerbosity; } + + void setModuleConfig(const ModuleConfig* moduleConfig) { mModuleConfig = moduleConfig; }; + const ModuleConfig* getModuleConfig() { return mModuleConfig; }; + void setTDCParam(const ZDCTDCParam* param) { mTDCParam = param; }; + const ZDCTDCParam* getTDCParam() { return mTDCParam; }; + void setIntegrationParam(const ZDCIntegrationParam* param) { mIntParam = param; }; + const ZDCIntegrationParam* getIntegrationParam() { return mIntParam; }; + const ModuleConfig* mModuleConfig = nullptr; /// Trigger/readout configuration object + + private: + int reconstruct(int seq_beg, int seq_end); + bool mIsContinuous = true; /// continuous (self-triggered) or externally-triggered readout + int mNBCAHead = 0; /// when storing triggered BC, store also mNBCAHead BCs + const ZDCTDCParam* mTDCParam = nullptr; /// TDC calibration object + const ZDCIntegrationParam* mIntParam = nullptr; /// Configuration of integration + bool mVerbosity; + Double_t mTS[NTS]; /// Tapered sinc function + TFile* mDbg = nullptr; /// Debug output + TTree* mTDbg = nullptr; /// Debug tree + const std::vector *mOrbitData; /// Reconstructed data + const std::vector *mBCData; /// BC info + const std::vector *mChData; /// Payload + std::vector mReco; /// Reconstructed data + std::map mOrbit; /// Information about orbit + static constexpr int mNSB = TSN * NTimeBinsPerBC; /// Total number of interpolated points per bunch crossing + RecEvent mRec; /// Debug reconstruction event + int mNBC = 0; +}; +} // namespace zdc +} // namespace o2 +#endif diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h new file mode 100644 index 0000000000000..1bb44d1de0371 --- /dev/null +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h @@ -0,0 +1,50 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_ZDC_RECOPARAMZDC_H_ +#define O2_ZDC_RECOPARAMZDC_H_ + +#include +#include "CommonUtils/ConfigurableParam.h" +#include "CommonUtils/ConfigurableParamHelper.h" +#include "ZDCBase/Constants.h" + +/// \file RecoParamZDC.h +/// \brief ZDC reconstruction parameters +/// \author P. Cortese + +namespace o2 +{ +namespace zdc +{ +// parameters of ZDC reconstruction + +struct RecoParamZDC : public o2::conf::ConfigurableParamHelper { + Int_t tsh[NTDCChannels] = {4, 4, 4, 4, 4, 4, 4, 4, 4, 4}; // Trigger shift + Int_t tth[NTDCChannels] = {8, 8, 8, 8, 8, 8, 8, 8, 8, 8}; // Trigger threshold + Int_t tmod[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of TDC channel in raw data + Int_t tch[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of TDC channel in raw data + Int_t amod[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of ADC channel in raw data + Int_t ach[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of ADC channel in raw data + float tdc_shift[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Correction of TDC position (0-25 ns, units of ~10 ps) + float tdc_search[NTDCChannels] = {250, 250, 250, 250, 250, 250, 250, 250, 250, 250}; // Search zone for a TDC signal ideally 2.5 ns (units of ~10 ps) + Int_t beg_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Start integration - signal + Int_t end_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // End integration - signal + Int_t beg_ped_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Start integration - pedestal + Int_t end_ped_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // End integration - pedestal + std::array bitset = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Set bits in coincidence + public: + void setBit(uint32_t ibit, bool val = true); + O2ParamDef(RecoParamZDC, "RecoParamZDC"); +}; +} // namespace zdc +} // namespace o2 + +#endif diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCIntegrationParam.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCIntegrationParam.h new file mode 100644 index 0000000000000..5e62533d37a63 --- /dev/null +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCIntegrationParam.h @@ -0,0 +1,42 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_ZDC_INTEGRATIONPARAM_H_ +#define O2_ZDC_INTEGRATIONPARAM_H_ + +#include "ZDCBase/Constants.h" +#include +#include + +/// \file ZDCIntegrationParam.h +/// \brief Parameters to configure integration +/// \author P. Cortese + +namespace o2 +{ +namespace zdc +{ +// parameters of ZDC reconstruction + +struct ZDCIntegrationParam { + public: + Int_t beg_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Start integration - signal + Int_t end_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // End integration - signal + Int_t beg_ped_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Start integration - pedestal + Int_t end_ped_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // End integration - pedestal + void setIntegration(uint32_t ich, int beg, int end, int beg_ped, int end_ped); + void print(); + + ClassDefNV(ZDCIntegrationParam, 1); +}; +} // namespace zdc +} // namespace o2 + +#endif diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h new file mode 100644 index 0000000000000..312c949e252e9 --- /dev/null +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h @@ -0,0 +1,40 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_ZDC_TDCPARAM_H_ +#define O2_ZDC_TDCPARAM_H_ + +#include "ZDCBase/Constants.h" +#include +#include + +/// \file ZDCTDCParam.h +/// \brief Parameters to correct TDCs +/// \author P. Cortese + +namespace o2 +{ +namespace zdc +{ +// parameters of ZDC reconstruction + +struct ZDCTDCParam { + float tdc_shift[NTDCChannels] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Correction of TDC position (ns) + public: + void setShift(uint32_t ich, float val); + float getShift(uint32_t ich) const; + void print(); + + ClassDefNV(ZDCTDCParam, 1); +}; +} // namespace zdc +} // namespace o2 + +#endif diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx new file mode 100644 index 0000000000000..2ae7bfb4a4ff5 --- /dev/null +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -0,0 +1,429 @@ +#include +#include "FairLogger.h" +#include "ZDCReconstruction/DigiReco.h" +namespace o2 +{ +namespace zdc +{ + +void DigiReco::init(){ + // Load configuration parameters + auto& sopt = ZDCSimParam::Instance(); + mIsContinuous = sopt.continuous; + mNBCAHead = mIsContinuous ? sopt.nBCAheadCont : sopt.nBCAheadTrig; + + if (!mModuleConfig) { + LOG(FATAL) << "Missing ModuleConfig configuration object"; + return; + } + + // Prepare tapered sinc function + // tsc/TSN =3.75 (~ 4) and TSL*TSN*sqrt(2)/tsc >> 1 (n. of sigma) + const Double_t tsc = 750; + Int_t n = TSL * TSN; + for (Int_t tsi = 0; tsi <= n; tsi++) { + Double_t arg1 = TMath::Pi() * Double_t(tsi) / Double_t(TSN); + Double_t fs = 1; + if (arg1 != 0) + fs = TMath::Sin(arg1) / arg1; + Double_t arg2 = Double_t(tsi) / tsc; + Double_t fg = TMath::Exp(-arg2 * arg2); + mTS[n + tsi] = fs * fg; + mTS[n - tsi] = mTS[n + tsi]; // Function is even + } + + // Open debug file + mDbg = new TFile("ZDCReco.root", "recreate"); + mTDbg = new TTree("zdcr", "ZDCReco"); + mTDbg->Branch("zdcr", "RecEvent", &mRec); + // Update reconstruction parameters + //auto& ropt=RecoParamZDC::Instance(); + o2::zdc::RecoParamZDC& ropt = const_cast(RecoParamZDC::Instance()); + + // Fill maps + for (Int_t itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { + // If the reconstruction parameters were not manually set + if (ropt.tmod[itdc] < 0 || ropt.tch[itdc] < 0) { + Int_t isig = TDCSignal[itdc]; + for (Int_t im = 0; im < NModules; im++) { + for (UInt_t ic = 0; ic < NChPerModule; ic++) { + if (mModuleConfig->modules[im].channelID[ic] == isig && mModuleConfig->modules[im].readChannel[ic]) { + //ropt.updateFromString(TString::Format("RecoParamZDC.tmod[%d]=%d;",itdc,im)); + //ropt.updateFromString(TString::Format("RecoParamZDC.tch[%d]=%d;",itdc,ic)); + ropt.tmod[itdc] = im; + ropt.tch[itdc] = ic; + goto next_itdc; + } + } + } + } + next_itdc:; + LOG(INFO) << "TDC " << itdc << "(" << ChannelNames[TDCSignal[itdc]] << ")" << " mod " << ropt.tmod[itdc] << " ch " << ropt.tch[itdc]; + } + + // Fill maps channel maps for integration + for (Int_t ich = 0; ich < NChannels; ich++) { + // If the reconstruction parameters were not manually set + if (ropt.amod[ich] < 0 || ropt.ach[ich] < 0) { + for (Int_t im = 0; im < NModules; im++) { + for (UInt_t ic = 0; ic < NChPerModule; ic++) { + if (mModuleConfig->modules[im].channelID[ic] == ich && mModuleConfig->modules[im].readChannel[ic]) { + ropt.amod[ich] = im; + ropt.ach[ich] = ic; + goto next_ich; + } + } + } + } + next_ich:; + LOG(INFO) << "ADC " << ich << "(" << ChannelNames[ich] << ") mod " << ropt.amod[ich] << " ch " << ropt.ach[ich]; + } + + // Integration ranges + for (Int_t ich = 0; ich < NChannels; ich++) { + // If the reconstruction parameters were not manually set + if (ropt.beg_int[ich] < 0 || ropt.end_int[ich] < 0) { + if (!mIntParam) { + LOG(ERROR) << "Integration for signal " << ich << " missing configuration object and no manual override"; + } else { + ropt.beg_int[ich] = mIntParam->beg_int[ich]; + ropt.end_int[ich] = mIntParam->end_int[ich]; + } + } + if (ropt.beg_ped_int[ich] < 0 || ropt.end_ped_int[ich] < 0) { + if (!mIntParam) { + LOG(ERROR) << "Integration for pedestal " << ich << " missing configuration object and no manual override"; + } else { + ropt.beg_ped_int[ich] = mIntParam->beg_ped_int[ich]; + ropt.end_ped_int[ich] = mIntParam->end_ped_int[ich]; + } + } + LOG(INFO) << ChannelNames[ich] << " integration: signal=[" << ropt.beg_int[ich] << "-" << ropt.end_int[ich] << "] pedestal=[" << ropt.beg_ped_int[ich] << "-" << ropt.end_ped_int[ich] <<"]"; + } +} + +int DigiReco::process(const std::vector *orbitdata, const std::vector *bcdata, std::vector *chdata){ + // We assume that vectors contain data from a full time frame + mOrbitData=orbitdata; + mBCData=bcdata; + mChData=chdata; + + const std::vector &OrbitData=*orbitdata; + const std::vector &BCData=*bcdata; + const std::vector &ChData=*chdata; + + // Initialization of lookup structure for pedestals + mOrbit.clear(); + int norb=OrbitData.size(); + for(Int_t iorb=0; iorb1){ + // Detected a gap + reconstruct(seq_beg, seq_end); + seq_beg=ibc; + seq_end=ibc; + }else if(ibc==(mNBC-1)){ + // Last bunch + seq_end=ibc; + reconstruct(seq_beg, seq_end); + seq_beg=mNBC; + seq_end=mNBC; + }else{ + // Look for another bunch + seq_end=ibc; + } + } + +/* + +std::map::iterator it; + + mymap['a']=50; + mymap['b']=100; + mymap['c']=150; + mymap['d']=200; + + it = mymap.find('b'); + if (it != mymap.end()) + mymap.erase (it); + */ + return 0; +} + +int DigiReco::reconstruct(int seq_beg, int seq_end){ + // Process consecutive BCs + if (seq_beg == seq_end) { + LOG(INFO) << "Lonely bunch " << mReco[seq_beg].ir.orbit << "." << mReco[seq_beg].ir.bc; + return 0; + } + LOG(INFO) << "Processing " << mReco[seq_beg].ir.orbit << "." << mReco[seq_beg].ir.bc << " - " << mReco[seq_end].ir.orbit << "." << mReco[seq_end].ir.bc; + auto& ropt = ZDCRecoParam::Instance(); + /* + // Apply differential discrimination with triple condition + for (Int_t itdc = 0; itdc < NTDCChannels; itdc++) { + Int_t im = ropt.tmod[itdc]; + Int_t ic = ropt.tch[itdc]; + // Check if the TDC channel is connected + if (im >= 0 && ic >= 0) { + // Check if channel has valid data for consecutive bunches in current bunch range + // N.B. there are events recorded from ibeg-iend but we are not sure if it is the + // case for every TDC channel + int istart = -1, istop = -1; + // Loop allows for gaps in the data sequence for each TDC channel + for (int ibun = ibeg; ibun <= iend; ibun++) { + auto& ch = mData[ibun].data[im][ic]; + if (ch.f.fixed_0 == Id_w0 && ch.f.fixed_1 == Id_w1 && ch.f.fixed_2 == Id_w2) { + if (istart < 0) { + istart = ibun; + } + istop = ibun; + } else { + // A gap is detected gap + if (istart >= 0 && (istop - istart) > 0) { + // Need data for at least two consecutive bunch crossings + processTrigger(itdc, istart, istop); + } + istart = -1; + istop = -1; + } + } + // Check if there are consecutive bunch crossings at the end of group + if (istart >= 0 && (istop - istart) > 0) { + processTrigger(itdc, istart, istop); + } + } + } + // Reconstruct integrated charges and fill output tree + // TODO: compare average pedestal with estimation from current event + // TODO: failover in case of discrepancy + for (Int_t ibun = ibeg; ibun <= iend; ibun++) { + mRec = mReco[ibun]; + for (Int_t itdc = 0; itdc < NTDCChannels; itdc++) { + printf("%d %u.%u %d ", ibun, mReco[ibun].ir.orbit, mReco[ibun].ir.bc, itdc); + for (Int_t isam = 0; isam < NTimeBinsPerBC; isam++) { + printf("%d", mRec.fired[itdc][isam]); + } + printf("\n"); + for (Int_t i = 0; i < MaxTDCValues; i++) { + mRec.TdcChannels[itdc][i] = kMinShort; + mRec.TdcAmplitudes[itdc][i] = -999; + } + Int_t i = 0; + mRec.pattern[itdc] = 0; + for (int16_t val : mReco[ibun].tdcChannels[itdc]) { + LOG(INFO) << "TdcChannels[" << itdc << "][" << i << "]=" << val; + mRec.TdcChannels[itdc][i] = val; + // There is a TDC value in the search zone around main-main position + if (std::abs(mRec.TdcChannels[itdc][i]) < ropt.tdc_search[itdc]) { + mRec.pattern[itdc] = 1; + } + i++; + } + i = 0; + for (float val : mReco[ibun].tdcAmplitudes[itdc]) { + //mRec.tdcAmplitudes[itdc].push_back(val); + //LOG(INFO) << itdc << " valt=" << val; + LOG(INFO) << "TdcAmplitudes[" << itdc << "][" << i << "]=" << val; + mRec.TdcAmplitudes[itdc][i] = val; + i++; + } + } + printf("%d PATTERN: ", ibun); + for (Int_t itdc = 0; itdc < NTDCChannels; itdc++) { + printf("%d", mRec.pattern[itdc]); + } + printf("\n"); + + // Check if coincidence of common PM and sum of towers is satisfied + bool fired[NChannels] = {0}; + // Side A + if ((mRec.pattern[TDCZNAC] || ropt.bitset[TDCZNAC]) && (mRec.pattern[TDCZNAS] || ropt.bitset[TDCZNAS])) { + for (Int_t ich = IdZNAC; ich <= IdZNASum; ich++) { + fired[ich] = true; + } + } + if ((mRec.pattern[TDCZPAC] || ropt.bitset[TDCZPAC]) && (mRec.pattern[TDCZPAS] || ropt.bitset[TDCZPAS])) { + for (Int_t ich = IdZPAC; ich <= IdZPASum; ich++) { + fired[ich] = true; + } + } + // ZEM1 and ZEM2 are not in coincidence + fired[IdZEM1] = mRec.pattern[TDCZEM1]; + fired[IdZEM2] = mRec.pattern[TDCZEM2]; + // Side C + if ((mRec.pattern[TDCZNCC] || ropt.bitset[TDCZNCC]) && (mRec.pattern[TDCZNCS] || ropt.bitset[TDCZNCS])) { + for (Int_t ich = IdZNCC; ich <= IdZNCSum; ich++) { + fired[ich] = true; + } + } + if ((mRec.pattern[TDCZPCC] || ropt.bitset[TDCZPCC]) && (mRec.pattern[TDCZPCS] || ropt.bitset[TDCZPCS])) { + for (Int_t ich = IdZPCC; ich <= IdZPCSum; ich++) { + fired[ich] = true; + } + } + + // Access samples from raw data + for (Int_t i = 0; i < NChannelsZEM; i++) { + mRec.energyZEM[i] = -999; + } + for (Int_t i = 0; i < NChannelsZN; i++) { + mRec.energyZNA[i] = -999; + } + for (Int_t i = 0; i < NChannelsZN; i++) { + mRec.energyZNC[i] = -999; + } + for (Int_t i = 0; i < NChannelsZP; i++) { + mRec.energyZPA[i] = -999; + } + for (Int_t i = 0; i < NChannelsZP; i++) { + mRec.energyZPC[i] = -999; + } + auto& data = mData[ibun]; + printf("%d FIRED: ", ibun); + for (Int_t ich = 0; ich < NChannels; ich++) { + printf("%d", fired[ich]); + } + printf("\n"); + for (Int_t ich = 0; ich < NChannels; ich++) { + // Check if the corresponding TDC is fired + if (fired[ich]) { + // Check if channels are present in payload + Int_t im = ropt.amod[ich]; + Int_t ic = ropt.ach[ich]; + // Check if the ADC channel is connected + if (im >= 0 && ic >= 0) { + // Check if the ADC has payload + auto& ch = data.data[im][ic]; + if (ch.f.fixed_0 == Id_w0 && ch.f.fixed_1 == Id_w1 && ch.f.fixed_2 == Id_w2) { + float sum = 0; + for (Int_t is = ropt.beg_int[ich]; is <= ropt.end_int[ich]; is++) { + // TODO: fallback if offset is missing + // TODO: fallback if channel has pile-up + sum += (mOffset[im][ic] - float(data.s[im][ic][is])); + } + printf("CH %d %s: %f\n", ich, ChannelNames[ich].data(), sum); + if (ich == IdZNAC) { + mRec.energyZNA[0] = sum; + } + if (ich == IdZNA1) { + mRec.energyZNA[1] = sum; + } + if (ich == IdZNA2) { + mRec.energyZNA[2] = sum; + } + if (ich == IdZNA3) { + mRec.energyZNA[3] = sum; + } + if (ich == IdZNA4) { + mRec.energyZNA[4] = sum; + } + if (ich == IdZNASum) { + mRec.energyZNA[5] = sum; + } + if (ich == IdZPAC) { + mRec.energyZPA[0] = sum; + } + if (ich == IdZPA1) { + mRec.energyZPA[1] = sum; + } + if (ich == IdZPA2) { + mRec.energyZPA[2] = sum; + } + if (ich == IdZPA3) { + mRec.energyZPA[3] = sum; + } + if (ich == IdZPA4) { + mRec.energyZPA[4] = sum; + } + if (ich == IdZPASum) { + mRec.energyZPA[5] = sum; + } + if (ich == IdZEM1) { + mRec.energyZEM[0] = sum; + } + if (ich == IdZEM2) { + mRec.energyZEM[1] = sum; + } + if (ich == IdZNCC) { + mRec.energyZNC[0] = sum; + } + if (ich == IdZNC1) { + mRec.energyZNC[1] = sum; + } + if (ich == IdZNC2) { + mRec.energyZNC[2] = sum; + } + if (ich == IdZNC3) { + mRec.energyZNC[3] = sum; + } + if (ich == IdZNC4) { + mRec.energyZNC[4] = sum; + } + if (ich == IdZNCSum) { + mRec.energyZNC[5] = sum; + } + if (ich == IdZPCC) { + mRec.energyZPC[0] = sum; + } + if (ich == IdZPC1) { + mRec.energyZPC[1] = sum; + } + if (ich == IdZPC2) { + mRec.energyZPC[2] = sum; + } + if (ich == IdZPC3) { + mRec.energyZPC[3] = sum; + } + if (ich == IdZPC4) { + mRec.energyZPC[4] = sum; + } + if (ich == IdZPCSum) { + mRec.energyZPC[5] = sum; + } + } + } + } + } + // TODO: energy calibration + mTDbg->Fill(); + } + */ +} + +} // namespace zdc +} // namespace o2 diff --git a/Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx b/Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx new file mode 100644 index 0000000000000..9c1c61ee98163 --- /dev/null +++ b/Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx @@ -0,0 +1,24 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "FairLogger.h" +#include "ZDCReconstruction/RecoParamZDC.h" + +using namespace o2::zdc; + +O2ParamImpl(RecoParamZDC); + +void RecoParamZDC::setBit(uint32_t ibit, bool val){ + if(ibit>=0 && ibit= 0 && ich < NChannels) { + if (beg < 0 || beg >= NTimeBinsPerBC) { + LOG(FATAL) << "Integration start = " << beg << " for signal " << ich << " (" << ChannelNames[ich] << ") not in allowed range [0-" << NTimeBinsPerBC - 1; + return; + } + if (end < 0 || end >= NTimeBinsPerBC) { + LOG(FATAL) << "Integration end = " << end << " for signal " << ich << " (" << ChannelNames[ich] << ") not in allowed range [0-" << NTimeBinsPerBC - 1; + return; + } + if (beg_ped < 0 || beg_ped >= NTimeBinsPerBC) { + LOG(FATAL) << "Pedestal integration start = " << beg_ped << " for signal " << ich << " (" << ChannelNames[ich] << ") not in allowed range [0-" << NTimeBinsPerBC - 1; + return; + } + if (beg < 0 || beg >= NTimeBinsPerBC) { + LOG(FATAL) << "Pedestal integration end = " << end_ped << " for signal " << ich << " (" << ChannelNames[ich] << ") not in allowed range [0-" << NTimeBinsPerBC - 1; + return; + } + beg_int[ich] = beg; + end_int[ich] = end; + beg_ped_int[ich] = beg_ped; + end_ped_int[ich] = end_ped; + } else { + LOG(FATAL) << __func__ << " channel " << ich << " not in allowed range"; + } +} + +void ZDCIntegrationParam::print() +{ + for (Int_t ich = 0; ich < NChannels; ich++) { + LOG(INFO) << ChannelNames[ich] << " integration: signal=[" << beg_int[ich] << "-" << end_int[ich] << "] pedestal=[" << beg_ped_int[ich] << "-" << end_ped_int[ich] <<"]"; + } +} diff --git a/Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx b/Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx new file mode 100644 index 0000000000000..7cbccde9863fa --- /dev/null +++ b/Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx @@ -0,0 +1,47 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "FairLogger.h" +#include "ZDCReconstruction/ZDCTDCParam.h" + +using namespace o2::zdc; + +void ZDCTDCParam::setShift(uint32_t ich, float val) +{ + if (ich >= 0 && ich < NTDCChannels) { + tdc_shift[ich] = val; + } else { + LOG(FATAL) << __func__ << " channel " << ich << " not in allowed range"; + } +} + +void ZDCTDCParam::print() +{ + LOG(INFO) << "TDCZNAC shift " << tdc_shift[TDCZNAC] << " ns"; + LOG(INFO) << "TDCZNAS shift " << tdc_shift[TDCZNAS] << " ns"; + LOG(INFO) << "TDCZPAC shift " << tdc_shift[TDCZPAC] << " ns"; + LOG(INFO) << "TDCZPAS shift " << tdc_shift[TDCZPAS] << " ns"; + LOG(INFO) << "TDCZEM1 shift " << tdc_shift[TDCZEM1] << " ns"; + LOG(INFO) << "TDCZEM2 shift " << tdc_shift[TDCZEM2] << " ns"; + LOG(INFO) << "TDCZNCC shift " << tdc_shift[TDCZNCC] << " ns"; + LOG(INFO) << "TDCZNCS shift " << tdc_shift[TDCZNCS] << " ns"; + LOG(INFO) << "TDCZPCC shift " << tdc_shift[TDCZPCC] << " ns"; + LOG(INFO) << "TDCZPCS shift " << tdc_shift[TDCZPCS] << " ns"; +} + +float ZDCTDCParam::getShift(uint32_t ich) const +{ + if (ich >= 0 && ich < NTDCChannels) { + return tdc_shift[ich]; + } else { + LOG(FATAL) << __func__ << " channel " << ich << " not in allowed range"; + return 0; + } +} From c00dc36822c6eefb100f67c7db6673eec77b6653 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 30 Apr 2021 11:25:11 +0200 Subject: [PATCH 002/770] First reconstruction on digits --- .../ZDC/include/DataFormatsZDC/RecEvent.h | 4 +- .../ZDC/base/include/ZDCBase/Constants.h | 10 + .../include/ZDCReconstruction/DigiReco.h | 16 +- Detectors/ZDC/reconstruction/src/DigiReco.cxx | 778 ++++++++++++++---- 4 files changed, 633 insertions(+), 175 deletions(-) diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h index a9350727c74d0..6e13d1489a15c 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h @@ -49,9 +49,11 @@ struct RecEvent { //std::array tdcAmplitudes; /// At most MaxTDCValues Values in ns per TDC channel int16_t tdcChannels[NTDCChannels][MaxTDCValues]; /// TdcChannels float tdcAmplitudes[NTDCChannels][MaxTDCValues]; /// TdcAmplitudes + int ntdc[NTDCChannels]={0}; std::array pattern; /// Pattern of TDC - Short_t fired[NTDCChannels][NTimeBinsPerBC] = {0}; /// Position at which the trigger algorithm is fired + uint16_t fired[NTDCChannels] = {0}; /// Position at which the trigger algorithm is fired float inter[NTDCChannels][NTimeBinsPerBC * TSN] = {0}; /// Interpolated samples + uint32_t ref[NChannels]={O2_ZDC_REF_INIT}; /// Cache of references void print() const; diff --git a/Detectors/ZDC/base/include/ZDCBase/Constants.h b/Detectors/ZDC/base/include/ZDCBase/Constants.h index b773bfda76383..583542fdf4b30 100644 --- a/Detectors/ZDC/base/include/ZDCBase/Constants.h +++ b/Detectors/ZDC/base/include/ZDCBase/Constants.h @@ -51,6 +51,11 @@ constexpr float ChannelTimeBinNS = 2.; //< bin length in NS constexpr float SampleLenghtNS = NTimeBinsPerBC * ChannelTimeBinNS; constexpr int NChannels = 2 * (NChannelsZN + NChannelsZP) + NChannelsZEM; +#define O2_ZDC_REF_INIT_VAL 0xffffffff +#define O2_ZDC_REF_INIT_ZEM O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL +#define O2_ZDC_REF_INIT_ZDC O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL +#define O2_ZDC_REF_INIT O2_ZDC_REF_INIT_ZDC, O2_ZDC_REF_INIT_ZDC, O2_ZDC_REF_INIT_ZEM, O2_ZDC_REF_INIT_ZDC, O2_ZDC_REF_INIT_ZDC + constexpr uint8_t ALICETriggerMask = 0x1; constexpr int NModules = 8; @@ -173,6 +178,11 @@ const int TDCSignal[NTDCChannels] = { IdZPCSum // TDCZPCS }; +constexpr int DbgZero = 0; +constexpr int DbgMinimal = 1; +constexpr int DbgMedium = 2; +constexpr int DbgFull = 3; + // paths to CCDB objects // TODO: eventually these paths should be retrieved from NameConfigurator class // TODO: we would better use "constexpr string_view" here, but it makes sense only if diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h index 14c342387a8f2..7ebdf7357a0ab 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h @@ -22,8 +22,12 @@ class DigiReco { public: DigiReco() = default; + ~DigiReco() { + mTDbg->Write(); + mDbg->Close(); + } void init(); - int process(const std::vector *orbitdata, const std::vector *bcdata, std::vector *chdata); + int process(const std::vector *orbitdata, const std::vector *bcdata, const std::vector *chdata); int write(); void setVerbosity(int v) { @@ -40,12 +44,16 @@ class DigiReco const ModuleConfig* mModuleConfig = nullptr; /// Trigger/readout configuration object private: - int reconstruct(int seq_beg, int seq_end); + int reconstruct(int seq_beg, int seq_end); /// Main method for data reconstruction + void processTrigger(int itdc, int ibeg, int iend); /// Replay of trigger algorithm on acquired data + void interpolate(int itdc, int ibeg, int iend); /// Interpolation of samples to evaluate signal amplitude and arrival time + void assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float amp); // Set reconstructed TDC values bool mIsContinuous = true; /// continuous (self-triggered) or externally-triggered readout int mNBCAHead = 0; /// when storing triggered BC, store also mNBCAHead BCs const ZDCTDCParam* mTDCParam = nullptr; /// TDC calibration object + uint32_t mTDCMask[NTDCChannels]={0}; /// Identify TDC channels in trigger mask const ZDCIntegrationParam* mIntParam = nullptr; /// Configuration of integration - bool mVerbosity; + bool mVerbosity=DbgFull; Double_t mTS[NTS]; /// Tapered sinc function TFile* mDbg = nullptr; /// Debug output TTree* mTDbg = nullptr; /// Debug tree @@ -57,6 +65,8 @@ class DigiReco static constexpr int mNSB = TSN * NTimeBinsPerBC; /// Total number of interpolated points per bunch crossing RecEvent mRec; /// Debug reconstruction event int mNBC = 0; + int16_t tdc_shift[NTDCChannels] = {0}; /// TDC correction (units of 1/96 ns) + constexpr static uint16_t mMask[NTimeBinsPerBC]={0x0001,0x002,0x004,0x008, 0x0010,0x0020,0x0040,0x0080, 0x0100,0x0200,0x0400,0x0800}; }; } // namespace zdc } // namespace o2 diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index 2ae7bfb4a4ff5..f8a420dc441f5 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -1,6 +1,8 @@ #include #include "FairLogger.h" #include "ZDCReconstruction/DigiReco.h" +#include "ZDCReconstruction/RecoParamZDC.h" + namespace o2 { namespace zdc @@ -52,6 +54,8 @@ void DigiReco::init(){ //ropt.updateFromString(TString::Format("RecoParamZDC.tch[%d]=%d;",itdc,ic)); ropt.tmod[itdc] = im; ropt.tch[itdc] = ic; + // Fill mask to identify TDC channels + mTDCMask[itdc]=(0x1<<(4*im+ic)); goto next_itdc; } } @@ -61,6 +65,34 @@ void DigiReco::init(){ LOG(INFO) << "TDC " << itdc << "(" << ChannelNames[TDCSignal[itdc]] << ")" << " mod " << ropt.tmod[itdc] << " ch " << ropt.tch[itdc]; } + // TDC calibration + for (Int_t itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { + float fval = ropt.tdc_shift[itdc]; + // If the reconstruction parameters were not manually set + if (fval < 0) { + // Check if calibration object is present + if (!mTDCParam) { + LOG(FATAL) << "TDC " << itdc << " missing configuration object and no manual override"; + } else { + fval = mTDCParam->getShift(itdc) * 96.; + } + } + auto val = std::nearbyint(fval); + if (val < kMinShort) { + LOG(FATAL) << "Shift for TDC " << itdc << " " << val << " is out of range"; + } + if (val > kMaxShort) { + LOG(FATAL) << "Shift for TDC " << itdc << " " << val << " is out of range"; + } + tdc_shift[itdc] = val; + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " shift= " << tdc_shift[itdc] << " i.s. = " << val / 96. << " ns"; + } + // TDC search zone + // TODO: override with configuration object + for (Int_t itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << ropt.tdc_search[itdc] << " i.s. = " << ropt.tdc_search[itdc] / 96. << " ns"; + } + // Fill maps channel maps for integration for (Int_t ich = 0; ich < NChannels; ich++) { // If the reconstruction parameters were not manually set @@ -102,7 +134,7 @@ void DigiReco::init(){ } } -int DigiReco::process(const std::vector *orbitdata, const std::vector *bcdata, std::vector *chdata){ +int DigiReco::process(const std::vector *orbitdata, const std::vector *bcdata, const std::vector *chdata){ // We assume that vectors contain data from a full time frame mOrbitData=orbitdata; mBCData=bcdata; @@ -117,14 +149,25 @@ int DigiReco::process(const std::vector *orbitdata, const st int norb=OrbitData.size(); for(Int_t iorb=0; iorb=DbgFull){ + LOG(INFO) << "OrbitData[" << OrbitData[iorb].ir.orbit << "] = " << iorb; + } } mNBC=BCData.size(); mReco.clear(); mReco.reserve(mNBC); // Initialization of reco structure for(Int_t ibc=0; ibcIdDummy && chd.id ::iterator it; return 0; } -int DigiReco::reconstruct(int seq_beg, int seq_end){ +int DigiReco::reconstruct(int ibeg, int iend){ // Process consecutive BCs - if (seq_beg == seq_end) { - LOG(INFO) << "Lonely bunch " << mReco[seq_beg].ir.orbit << "." << mReco[seq_beg].ir.bc; + if (ibeg == iend) { + LOG(INFO) << "Lonely bunch " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc; return 0; } - LOG(INFO) << "Processing " << mReco[seq_beg].ir.orbit << "." << mReco[seq_beg].ir.bc << " - " << mReco[seq_end].ir.orbit << "." << mReco[seq_end].ir.bc; - auto& ropt = ZDCRecoParam::Instance(); - /* + LOG(INFO) << __func__ << "(" << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; + // Get references to arrays + const std::vector &OrbitData=*mOrbitData; + const std::vector &BCData=*mBCData; + const std::vector &ChData=*mChData; + + // Get reconstruction parameters + auto& ropt = RecoParamZDC::Instance(); + +// int chEnt = bcd.ref.getFirstEntry(); +// for (int ic = 0; ic < bcd.ref.getEntries(); ic++) { +// const auto& chd = zdcChData[chEnt++]; +// chd.print(); +// UShort_t bc=bcd.ir.bc; +// UInt_t orbit=bcd.ir.orbit; +// for(Int_t is=0; isGetN(); +// gr[chd.id]->SetPoint(ip,3564.*orbit+bc+is/12.,myval); +// } +// } + // Apply differential discrimination with triple condition for (Int_t itdc = 0; itdc < NTDCChannels; itdc++) { - Int_t im = ropt.tmod[itdc]; - Int_t ic = ropt.tch[itdc]; - // Check if the TDC channel is connected - if (im >= 0 && ic >= 0) { - // Check if channel has valid data for consecutive bunches in current bunch range - // N.B. there are events recorded from ibeg-iend but we are not sure if it is the - // case for every TDC channel - int istart = -1, istop = -1; - // Loop allows for gaps in the data sequence for each TDC channel - for (int ibun = ibeg; ibun <= iend; ibun++) { - auto& ch = mData[ibun].data[im][ic]; - if (ch.f.fixed_0 == Id_w0 && ch.f.fixed_1 == Id_w1 && ch.f.fixed_2 == Id_w2) { - if (istart < 0) { - istart = ibun; - } - istop = ibun; - } else { - // A gap is detected gap - if (istart >= 0 && (istop - istart) > 0) { - // Need data for at least two consecutive bunch crossings - processTrigger(itdc, istart, istop); - } - istart = -1; - istop = -1; + // Check if channel has valid data for consecutive bunches in current bunch range + // N.B. there are events recorded from ibeg-iend but we are not sure if it is the + // case for every TDC channel + int istart = -1, istop = -1; + // Loop allows for gaps in the data sequence for each TDC channel + for (int ibun = ibeg; ibun <= iend; ibun++) { + if (BCData[ibun].channels&mTDCMask[itdc]) { // TDC channel has data for this event + if (istart < 0) { + istart = ibun; } + istop = ibun; + } else { // No data from channel + // A gap is detected + if (istart >= 0 && (istop - istart) > 0) { + // Need data for at least two consecutive bunch crossings + processTrigger(itdc, istart, istop); + } + istart = -1; + istop = -1; } - // Check if there are consecutive bunch crossings at the end of group - if (istart >= 0 && (istop - istart) > 0) { - processTrigger(itdc, istart, istop); - } + } + // Check if there are consecutive bunch crossings at the end of group + if (istart >= 0 && (istop - istart) > 0) { + processTrigger(itdc, istart, istop); } } + + // Loop on bunches after trigger evaluation // Reconstruct integrated charges and fill output tree // TODO: compare average pedestal with estimation from current event // TODO: failover in case of discrepancy for (Int_t ibun = ibeg; ibun <= iend; ibun++) { - mRec = mReco[ibun]; - for (Int_t itdc = 0; itdc < NTDCChannels; itdc++) { - printf("%d %u.%u %d ", ibun, mReco[ibun].ir.orbit, mReco[ibun].ir.bc, itdc); - for (Int_t isam = 0; isam < NTimeBinsPerBC; isam++) { - printf("%d", mRec.fired[itdc][isam]); + // Look for offset + float pbun[NChannels]; + auto orbit=BCData[ibun].ir.orbit; + std::map::iterator it = mOrbit.find(orbit); + if (it != mOrbit.end()){ + // Subtract pedestal + auto &orbitdata=OrbitData[it->second]; + for(int ich=0; ich::infinity(); } - Int_t i = 0; - mRec.pattern[itdc] = 0; - for (int16_t val : mReco[ibun].tdcChannels[itdc]) { - LOG(INFO) << "TdcChannels[" << itdc << "][" << i << "]=" << val; - mRec.TdcChannels[itdc][i] = val; - // There is a TDC value in the search zone around main-main position - if (std::abs(mRec.TdcChannels[itdc][i]) < ropt.tdc_search[itdc]) { - mRec.pattern[itdc] = 1; - } - i++; + } + // Debug dump of pedestal + if(mVerbosity>=DbgFull){ + for(int ich=0; ich= 0 && ic >= 0) { - // Check if the ADC has payload - auto& ch = data.data[im][ic]; - if (ch.f.fixed_0 == Id_w0 && ch.f.fixed_1 == Id_w1 && ch.f.fixed_2 == Id_w2) { - float sum = 0; - for (Int_t is = ropt.beg_int[ich]; is <= ropt.end_int[ich]; is++) { - // TODO: fallback if offset is missing - // TODO: fallback if channel has pile-up - sum += (mOffset[im][ic] - float(data.s[im][ic][is])); - } - printf("CH %d %s: %f\n", ich, ChannelNames[ich].data(), sum); - if (ich == IdZNAC) { - mRec.energyZNA[0] = sum; - } - if (ich == IdZNA1) { - mRec.energyZNA[1] = sum; - } - if (ich == IdZNA2) { - mRec.energyZNA[2] = sum; - } - if (ich == IdZNA3) { - mRec.energyZNA[3] = sum; - } - if (ich == IdZNA4) { - mRec.energyZNA[4] = sum; - } - if (ich == IdZNASum) { - mRec.energyZNA[5] = sum; - } - if (ich == IdZPAC) { - mRec.energyZPA[0] = sum; - } - if (ich == IdZPA1) { - mRec.energyZPA[1] = sum; - } - if (ich == IdZPA2) { - mRec.energyZPA[2] = sum; - } - if (ich == IdZPA3) { - mRec.energyZPA[3] = sum; - } - if (ich == IdZPA4) { - mRec.energyZPA[4] = sum; - } - if (ich == IdZPASum) { - mRec.energyZPA[5] = sum; - } - if (ich == IdZEM1) { - mRec.energyZEM[0] = sum; - } - if (ich == IdZEM2) { - mRec.energyZEM[1] = sum; - } - if (ich == IdZNCC) { - mRec.energyZNC[0] = sum; - } - if (ich == IdZNC1) { - mRec.energyZNC[1] = sum; - } - if (ich == IdZNC2) { - mRec.energyZNC[2] = sum; - } - if (ich == IdZNC3) { - mRec.energyZNC[3] = sum; - } - if (ich == IdZNC4) { - mRec.energyZNC[4] = sum; - } - if (ich == IdZNCSum) { - mRec.energyZNC[5] = sum; - } - if (ich == IdZPCC) { - mRec.energyZPC[0] = sum; - } - if (ich == IdZPC1) { - mRec.energyZPC[1] = sum; - } - if (ich == IdZPC2) { - mRec.energyZPC[2] = sum; - } - if (ich == IdZPC3) { - mRec.energyZPC[3] = sum; - } - if (ich == IdZPC4) { - mRec.energyZPC[4] = sum; - } - if (ich == IdZPCSum) { - mRec.energyZPC[5] = sum; - } + // Check if channel data are present in payload + auto ref = mReco[ibun].ref[ich]; + if(ref < O2_ZDC_REF_INIT_VAL){ + float sum = 0; + for (Int_t is = ropt.beg_int[ich]; is <= ropt.end_int[ich]; is++) { + // TODO: fallback if offset is missing + // TODO: fallback if channel has pile-up + // TODO: manage signal positioned across boundary + sum += (pbun[ich] - float(ChData[ref].data[is])); + } + printf("CH %d %s: %f\n", ich, ChannelNames[ich].data(), sum); + if (ich == IdZNAC) { + rec.energyZNA[0] = sum; + } + if (ich == IdZNA1) { + rec.energyZNA[1] = sum; + } + if (ich == IdZNA2) { + rec.energyZNA[2] = sum; + } + if (ich == IdZNA3) { + rec.energyZNA[3] = sum; + } + if (ich == IdZNA4) { + rec.energyZNA[4] = sum; + } + if (ich == IdZNASum) { + rec.energyZNA[5] = sum; + } + if (ich == IdZPAC) { + rec.energyZPA[0] = sum; + } + if (ich == IdZPA1) { + rec.energyZPA[1] = sum; + } + if (ich == IdZPA2) { + rec.energyZPA[2] = sum; + } + if (ich == IdZPA3) { + rec.energyZPA[3] = sum; + } + if (ich == IdZPA4) { + rec.energyZPA[4] = sum; + } + if (ich == IdZPASum) { + rec.energyZPA[5] = sum; + } + if (ich == IdZEM1) { + rec.energyZEM[0] = sum; + } + if (ich == IdZEM2) { + rec.energyZEM[1] = sum; + } + if (ich == IdZNCC) { + rec.energyZNC[0] = sum; + } + if (ich == IdZNC1) { + rec.energyZNC[1] = sum; + } + if (ich == IdZNC2) { + rec.energyZNC[2] = sum; + } + if (ich == IdZNC3) { + rec.energyZNC[3] = sum; + } + if (ich == IdZNC4) { + rec.energyZNC[4] = sum; + } + if (ich == IdZNCSum) { + rec.energyZNC[5] = sum; + } + if (ich == IdZPCC) { + rec.energyZPC[0] = sum; + } + if (ich == IdZPC1) { + rec.energyZPC[1] = sum; + } + if (ich == IdZPC2) { + rec.energyZPC[2] = sum; + } + if (ich == IdZPC3) { + rec.energyZPC[3] = sum; + } + if (ich == IdZPC4) { + rec.energyZPC[4] = sum; + } + if (ich == IdZPCSum) { + rec.energyZPC[5] = sum; } } } } // TODO: energy calibration + mRec=rec; mTDbg->Fill(); + } // Loop on bunches +} + +void DigiReco::processTrigger(int itdc, int ibeg, int iend) +{ + LOG(INFO) << __func__ << "(itdc=" << itdc << "[" << ChannelNames[TDCSignal[itdc]] << "] ," << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; + + const std::vector &OrbitData=*mOrbitData; + const std::vector &BCData=*mBCData; + const std::vector &ChData=*mChData; + + // Get reconstruction parameters + auto& ropt = RecoParamZDC::Instance(); + +// int chEnt = bcd.ref.getFirstEntry(); +// for (int ic = 0; ic < bcd.ref.getEntries(); ic++) { +// const auto& chd = zdcChData[chEnt++]; +// chd.print(); +// UShort_t bc=bcd.ir.bc; +// UInt_t orbit=bcd.ir.orbit; +// for(Int_t is=0; isGetN(); +// gr[chd.id]->SetPoint(ip,3564.*orbit+bc+is/12.,myval); +// } +// } + + Int_t nbun = iend - ibeg + 1; + Int_t maxs2 = NTimeBinsPerBC * nbun - 1; + Int_t shift = ropt.tsh[itdc]; + Int_t thr = ropt.tth[itdc]; + + Int_t is1 = 0, is2 = 1; + Int_t isfired[3] = {0}; + Int_t it1=0,it2=0,ib1=-1,ib2=-1; + for (;;) { + // Shift data + for (Int_t i = 1; i < 3; i++) { + isfired[i] = isfired[i - 1]; + } + // Bunches and samples that are used in the difference + Int_t b1 = ibeg + is1 / NTimeBinsPerBC; + Int_t b2 = ibeg + is2 / NTimeBinsPerBC; + Int_t s1 = is1 % NTimeBinsPerBC; + Int_t s2 = is2 % NTimeBinsPerBC; + auto ref_m = mReco[b1].ref[TDCSignal[itdc]]; + auto ref_s = mReco[b2].ref[TDCSignal[itdc]]; + // Check data consistency before computing difference + if(ref_m == O2_ZDC_REF_INIT_VAL || ref_s == O2_ZDC_REF_INIT_VAL){ + LOG(FATAL) << "Missing information for bunch crossing"; + return; + } + // TODO: More checks that bunch crossings are indeed consecutive + int diff = ChData[ref_m].data[s1] - ChData[ref_s].data[s2]; + // Triple trigger condition + if (diff > thr) { + isfired[0] = 1; + if (isfired[1] == 1 && isfired[2] == 1) { + // Fired bit is assigned to the second sample, i.e. to the one that can identify the + // signal peak position + mReco[b2].fired[itdc]|=mMask[s2]; + //LOG(INFO) << itdc << " Fired @ " << mReco[b2].ir.orbit << "." << mReco[b2].ir.bc << " " << b2 - ibeg << "." << s2 << "=" << NTimeBinsPerBC * (b2 - ibeg) + s2; + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " Fired @ " << mReco[b2].ir.orbit << "." << mReco[b2].ir.bc << ".s" << s2; + } + } + if (is2 >= shift) { + is1++; + } + if (is2 < maxs2) { + is2++; + } + if (is1 == maxs2) { + break; + } + } + interpolate(itdc, ibeg, iend); +} + +void DigiReco::interpolate(int itdc, int ibeg, int iend) +{ + LOG(INFO) << __func__ << "(itdc=" << itdc << "[" << ChannelNames[TDCSignal[itdc]] << "] ," << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; + // TODO: get data from preceding time frame + constexpr int MaxTimeBin = NTimeBinsPerBC - 1; //< number of samples per BC + constexpr int tsnh = TSN / 2; // Half number of points in interpolation + constexpr int nsbun = TSN * NTimeBinsPerBC; // Total number of interpolated points per bunch crossing + Int_t nbun = iend - ibeg + 1; // Number of adjacent bunches + Int_t nsam = nbun * NTimeBinsPerBC; // Number of acquired samples + Int_t ntot = nsam * TSN; // Total number of points in the interpolated arrays + Int_t nint = (nbun * NTimeBinsPerBC - 1) * TSN; // Total points in the interpolation region (-1) + constexpr int nsp = 5; // Number of points to be searched + + const std::vector &OrbitData=*mOrbitData; + const std::vector &BCData=*mBCData; + const std::vector &ChData=*mChData; + + // At this level there should be no need to check if the TDC channel is connected + // since a fatal should have been raised already + for(int ibun=ibeg; ibun<=iend; ibun++){ + auto ref = mReco[ibun].ref[TDCSignal[itdc]]; + if(ref == O2_ZDC_REF_INIT_VAL){ + LOG(FATAL) << "Missing information for bunch crossing"; + } + } + + // Get reconstruction parameters + auto& ropt = RecoParamZDC::Instance(); + + Int_t imod = ropt.tmod[itdc]; // Module corresponding to TDC channel + Int_t ich = ropt.tch[itdc]; // Hardware channel corresponding to TDC channel + + auto ref_beg = mReco[ibeg].ref[TDCSignal[itdc]]; + auto ref_end = mReco[iend].ref[TDCSignal[itdc]]; + + Double_t first_sample = ChData[ref_beg].data[0]; + Double_t last_sample = ChData[ref_end].data[NTimeBinsPerBC - 1]; + + // Constant extrapolation at the beginning and at the end of the array + // Assign value of first sample + for (Int_t i = 0; i < tsnh; i++) { + mReco[ibeg].inter[itdc][i] = first_sample; + } + // Assign value of last sample + for (Int_t i = ntot - tsnh; i < ntot; i++) { + Int_t isam = i % nsbun; + mReco[iend].inter[itdc][isam] = last_sample; + } + // Interpolation between acquired points (n.b. loop from 0 to nint) + for (Int_t i = 0; i < nint; i++) { + // Identification of the point to be assigned (need to add tsnh to identify the point) + Int_t ibun = ibeg + (i + tsnh) / nsbun; + Int_t isam = (i + tsnh) % nsbun; + Int_t im = i % TSN; + if (im == 0) { + // This is an acquired point + Int_t ip = (i / TSN) % NTimeBinsPerBC; + Int_t ib = ibeg + (i / TSN) / NTimeBinsPerBC; + if (ib != ibun) { + LOG(FATAL) << "ib=" << ib << " ibun=" << ibun; + return; + } + mReco[ibun].inter[itdc][isam] = ChData[mReco[ibun].ref[TDCSignal[itdc]]].data[ip]; + } else { + // Do the actual interpolation + Double_t y = 0; + Int_t ip = i / TSN; + Double_t sum = 0; + for (Int_t is = TSN - im, ii = ip - TSL + 1; is < NTS; is += TSN, ii++) { + // Default is first point in the array + Double_t yy = first_sample; + if (ii > 0) { + if (ii < nsam) { + Int_t ip = ii % NTimeBinsPerBC; + Int_t ib = ibeg + ii / NTimeBinsPerBC; + yy = ChData[mReco[ib].ref[TDCSignal[itdc]]].data[ip]; + } else { + // Last acquired point + yy = last_sample; + } + } + sum += mTS[is]; + y += yy * mTS[is]; + } + y = y / sum; + mReco[ibun].inter[itdc][isam] = y; + } + } + // Looking for a local maximum in a searching zone + float amp = std::numeric_limits::infinity(); // Amplitude to be stored + Int_t isam_amp = 0; // Sample at maximum amplitude (relative to beginning of group) + Int_t ip_old = -1, ip_cur = -1, ib_cur = -1; // Current and old points + bool is_searchable = false; // Flag for point in the search zone for maximum amplitude + bool was_searchable = false; // Flag for point in the search zone for maximum amplitude + Int_t ib[nsp] = {-1, -1, -1, -1, -1}; + Int_t ip[nsp] = {-1, -1, -1, -1, -1}; + // N.B. Points at the extremes are constant therefore no local maximum + // can occur in these two regions + for (Int_t i = 0; i < nint; i++) { + Int_t isam = i + tsnh; + // Check if trigger is fired for this point + // For the moment we don't take into account possible extensions of the search zone + // ip_cur can span several bunches and is used just to identify transitions + ip_cur = isam / TSN; + // Speed up computation + if (ip_cur != ip_old) { + ip_old = ip_cur; + for (Int_t j = 0; j < 5; j++) { + ib[j] = -1; + ip[j] = -1; + } + // There are three possible triple conditions that involve current point (middle is current point) + ip[2] = ip_cur % NTimeBinsPerBC; + ib[2] = ibeg + ip_cur / NTimeBinsPerBC; + ib_cur = ib[2]; + if (ip[2] > 0) { + ip[1] = ip[2] - 1; + ib[1] = ib[2]; + } else if (ip[2] == 0) { + if (ib[2] > ibeg) { + ib[1] = ib[2] - 1; + ip[1] = MaxTimeBin; + } + } + if (ip[1] > 0) { + ip[0] = ip[1] - 1; + ib[0] = ib[1]; + } else if (ip[1] == 0) { + if (ib[1] > ibeg) { + ib[0] = ib[1] - 1; + ip[0] = MaxTimeBin; + } + } + if (ip[2] < MaxTimeBin) { + ip[3] = ip[2] + 1; + ib[3] = ib[2]; + } else if (ip[2] == MaxTimeBin) { + if (ib[2] < iend) { + ib[3] = ib[2] + 1; + ip[3] = 0; + } + } + if (ip[3] < MaxTimeBin) { + ip[4] = ip[3] + 1; + ib[4] = ib[3]; + } else if (ip[3] == MaxTimeBin) { + if (ib[3] < iend) { + ib[4] = ib[3] + 1; + ip[4] = 0; + } + } + // meet the threshold condition + was_searchable = is_searchable; + // Search conditions with list of allowed patterns + // No need to double check ib[?] and ip[?] because either we assign both or none + uint16_t triggered=0x0000; + for (Int_t j = 0; j < 5; j++) { + if (ib[j] >= 0 && (mReco[ib[j]].fired[itdc]&mMask[ip[j]]) > 0) { + triggered |= (0x1<reject) + is_searchable = 0; + if(triggered!=0){ + for(Int_t j=0; j<14; j++){ + if(triggered==accept[j]){ + is_searchable = 1; + break; + } + } + } + } + // We do not restrict search zone around expected main-main collision + // because we would like to be able to identify pile-up from collisions + // with satellites (buggy) + + // If we exit from searching zone + if (was_searchable && !is_searchable) { + if (amp <= ADCMax) { + // Store identified peak + Int_t ibun = ibeg + isam_amp / nsbun; + Int_t tdc = isam_amp % nsbun; + // Look for offset + auto orbit=BCData[ibun].ir.orbit; + std::map::iterator it = mOrbit.find(orbit); + if (it != mOrbit.end()){ + // Subtract pedestal + auto &orbitdata=OrbitData[it->second]; + amp = orbitdata.asFloat(ich) - amp; + }else{ + LOG(ERROR) << "Missing pedestal"; + amp = std::numeric_limits::infinity(); + } + assignTDC(ibun, ibeg, iend, itdc, tdc, amp); + } + amp = std::numeric_limits::infinity(); + isam_amp = 0; + was_searchable = 0; + } + if (is_searchable) { + Int_t mysam = isam % nsbun; + if (mReco[ib_cur].inter[itdc][mysam] < amp) { + amp = mReco[ib_cur].inter[itdc][mysam]; + isam_amp = isam; + } + } + } + // Trigger flag still present at the of the scan + if (is_searchable) { + // Add last identified peak + if (amp <= ADCMax) { + // Store identified peak + Int_t ibun = ibeg + isam_amp / nsbun; + Int_t tdc = isam_amp % nsbun; + // Look for offset + auto orbit=BCData[ibun].ir.orbit; + std::map::iterator it = mOrbit.find(orbit); + if (it != mOrbit.end()){ + // Subtract pedestal + auto &orbitdata=OrbitData[it->second]; + amp = orbitdata.asFloat(ich) - amp; + }else{ + LOG(ERROR) << "Missing pedestal"; + amp = std::numeric_limits::infinity(); + } + assignTDC(ibun, ibeg, iend, itdc, tdc, amp); + } + } +} + +void DigiReco::assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float amp) +{ + constexpr int nsbun = TSN * NTimeBinsPerBC; // Total number of interpolated points per bunch crossing + constexpr int tdc_max = nsbun / 2; + constexpr int tdc_min = -tdc_max; + + // Apply tdc shift correction + Int_t tdc_cor = tdc - tdc_shift[itdc]; + // Correct bunch assignment + if (tdc_cor < tdc_min && ibun >= ibeg) { + // Assign to preceding bunch + ibun = ibun - 1; + tdc_cor = tdc_cor + nsbun; + } else if (tdc_cor >= tdc_max && ibun < iend) { + // Assign to following bunch + ibun = ibun + 1; + tdc_cor = tdc_cor - nsbun; + } + if (tdc_cor < kMinShort) { + LOG(ERROR) << "TDC " << itdc << " " << tdc_cor << " is out of range"; + tdc_cor = kMinShort; + } + if (tdc_cor > kMaxShort) { + LOG(ERROR) << "TDC " << itdc << " " << tdc_cor << " is out of range"; + tdc_cor = kMaxShort; + } + // Assign to correct bunch + int &ihit=mReco[ibun].ntdc[itdc]; + if(ihit Date: Thu, 6 May 2021 17:55:17 +0200 Subject: [PATCH 003/770] Code cleanup --- .../ZDC/include/DataFormatsZDC/RecEvent.h | 75 ++- .../Detectors/ZDC/src/DataFormatsZDCLinkDef.h | 1 + .../ZDC/base/include/ZDCBase/Constants.h | 12 + Detectors/ZDC/macro/CMakeLists.txt | 5 + Detectors/ZDC/macro/CreateIntegrationParam.C | 75 +++ Detectors/ZDC/reconstruction/CMakeLists.txt | 15 +- .../include/ZDCReconstruction/DigiReco.h | 72 +- .../include/ZDCReconstruction/RecoParamZDC.h | 32 +- .../ZDCReconstruction/ZDCIntegrationParam.h | 14 +- Detectors/ZDC/reconstruction/src/DigiReco.cxx | 626 ++++++++---------- .../src/ZDCIntegrationParam.cxx | 4 +- 11 files changed, 496 insertions(+), 435 deletions(-) create mode 100644 Detectors/ZDC/macro/CreateIntegrationParam.C diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h index 6e13d1489a15c..6e7ae27776f27 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h @@ -16,6 +16,7 @@ #include "ZDCBase/Constants.h" #include #include +#include /// \file RecEvent.h /// \brief Class to describe reconstructed ZDC event (single BC with signal in one of detectors) @@ -25,38 +26,66 @@ namespace o2 { namespace zdc { - struct RecEvent { //using TDCChannel = std::array; //using TDCAmplitude = std::array; //using TDCChannel = std::vector; //using TDCAmplitude = std::vector; o2::InteractionRecord ir; - uint32_t flags; /// reconstruction flags -// std::array energyZEM; /// signal in the electromagnetic ZDCs -// std::array energyZNA; /// reco E in 5 ZNA sectors + sum -// std::array energyZNC; /// reco E in 5 ZNC sectors + sum -// std::array energyZPA; /// reco E in 5 ZPA sectors + sum -// std::array energyZPC; /// reco E in 5 ZPC sectors + sum - float energyZEM[NChannelsZEM]; /// signal in the electromagnetic ZDCs - float energyZNA[NChannelsZN]; /// reco E in 5 ZNA sectors + sum - float energyZNC[NChannelsZN]; /// reco E in 5 ZNC sectors + sum - float energyZPA[NChannelsZP]; /// reco E in 5 ZPA sectors + sum - float energyZPC[NChannelsZP]; /// reco E in 5 ZPC sectors + sum - math_utils::Point2D centroidZNA; /// centroid coordinates for ZNA - math_utils::Point2D centroidZNC; /// centroid coordinates for ZNC - //std::array tdcChannels; /// At most MaxTDCValues Values in ns per TDC channel - //std::array tdcAmplitudes; /// At most MaxTDCValues Values in ns per TDC channel - int16_t tdcChannels[NTDCChannels][MaxTDCValues]; /// TdcChannels - float tdcAmplitudes[NTDCChannels][MaxTDCValues]; /// TdcAmplitudes - int ntdc[NTDCChannels]={0}; - std::array pattern; /// Pattern of TDC - uint16_t fired[NTDCChannels] = {0}; /// Position at which the trigger algorithm is fired - float inter[NTDCChannels][NTimeBinsPerBC * TSN] = {0}; /// Interpolated samples - uint32_t ref[NChannels]={O2_ZDC_REF_INIT}; /// Cache of references + uint32_t flags; /// reconstruction flags + std::map ezdc; /// signal in ZDCs + float energy[NChannels] = {O2_ZDC_FLT_INIT}; /// ZDC signal + math_utils::Point2D centroidZNA; /// centroid coordinates for ZNA + math_utils::Point2D centroidZNC; /// centroid coordinates for ZNC + int16_t tdcVal[NTDCChannels][MaxTDCValues]; /// TdcChannels + float tdcAmp[NTDCChannels][MaxTDCValues]; /// TdcAmplitudes + int ntdc[NTDCChannels] = {0}; + std::array pattern; /// Pattern of TDC + uint16_t fired[NTDCChannels] = {0}; /// Position at which the trigger algorithm is fired + float inter[NTDCChannels][NTimeBinsPerBC * TSN] = {0}; /// Interpolated samples + uint32_t ref[NChannels] = {O2_ZDC_REF_INIT}; /// Cache of references void print() const; + float EZDC(uint8_t ich) + { + std::map::iterator it = ezdc.find(ich); + if (it != ezdc.end()) { + return it->second; + } else { + return -std::numeric_limits::infinity(); + } + } + + float EZNAC() { return EZDC(IdZNAC); } + float EZNA1() { return EZDC(IdZNA1); } + float EZNA2() { return EZDC(IdZNA2); } + float EZNA3() { return EZDC(IdZNA3); } + float EZNA4() { return EZDC(IdZNA4); } + float EZNASum() { return EZDC(IdZNASum); } + + float EZPAC() { return EZDC(IdZPAC); } + float EZPA1() { return EZDC(IdZPA1); } + float EZPA2() { return EZDC(IdZPA2); } + float EZPA3() { return EZDC(IdZPA3); } + float EZPA4() { return EZDC(IdZPA4); } + float EZPASum() { return EZDC(IdZPASum); } + + float EZEM1() { return EZDC(IdZEM1); } + float EZEM2() { return EZDC(IdZEM2); } + + float EZNCC() { return EZDC(IdZNCC); } + float EZNC1() { return EZDC(IdZNC1); } + float EZNC2() { return EZDC(IdZNC2); } + float EZNC3() { return EZDC(IdZNC3); } + float EZNC4() { return EZDC(IdZNC4); } + float EZNCSum() { return EZDC(IdZNCSum); } + float EZPCC() { return EZDC(IdZPCC); } + float EZPC1() { return EZDC(IdZPC1); } + float EZPC2() { return EZDC(IdZPC2); } + float EZPC3() { return EZDC(IdZPC3); } + float EZPC4() { return EZDC(IdZPC4); } + float EZPCSum() { return EZDC(IdZPCSum); } ClassDefNV(RecEvent, 1); }; diff --git a/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h b/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h index 386e6426b00ca..bcac26d11c23a 100644 --- a/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h +++ b/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h @@ -24,6 +24,7 @@ #pragma link C++ class o2::zdc::ChannelData + ; #pragma link C++ class o2::zdc::BCData + ; #pragma link C++ class o2::zdc::OrbitData + ; +#pragma link C++ class o2::zdc::RecEvent + ; #pragma link C++ class std::vector < o2::zdc::ChannelData> + ; #pragma link C++ class std::vector < o2::zdc::BCData> + ; #pragma link C++ class std::vector < o2::zdc::OrbitData> + ; diff --git a/Detectors/ZDC/base/include/ZDCBase/Constants.h b/Detectors/ZDC/base/include/ZDCBase/Constants.h index 583542fdf4b30..eebbec2e3bf6a 100644 --- a/Detectors/ZDC/base/include/ZDCBase/Constants.h +++ b/Detectors/ZDC/base/include/ZDCBase/Constants.h @@ -13,6 +13,7 @@ #include "CommonConstants/PhysicsConstants.h" #include +#include #include #include #include @@ -56,6 +57,11 @@ constexpr int NChannels = 2 * (NChannelsZN + NChannelsZP) + NChannelsZEM; #define O2_ZDC_REF_INIT_ZDC O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL #define O2_ZDC_REF_INIT O2_ZDC_REF_INIT_ZDC, O2_ZDC_REF_INIT_ZDC, O2_ZDC_REF_INIT_ZEM, O2_ZDC_REF_INIT_ZDC, O2_ZDC_REF_INIT_ZDC +#define O2_ZDC_FLT_INIT_VAL -INFINITY +#define O2_ZDC_FLT_INIT_ZEM O2_ZDC_FLT_INIT_VAL, O2_ZDC_FLT_INIT_VAL +#define O2_ZDC_FLT_INIT_ZDC O2_ZDC_FLT_INIT_VAL, O2_ZDC_FLT_INIT_VAL, O2_ZDC_FLT_INIT_VAL, O2_ZDC_FLT_INIT_VAL, O2_ZDC_FLT_INIT_VAL, O2_ZDC_FLT_INIT_VAL +#define O2_ZDC_FLT_INIT O2_ZDC_FLT_INIT_ZDC, O2_ZDC_FLT_INIT_ZDC, O2_ZDC_FLT_INIT_ZEM, O2_ZDC_FLT_INIT_ZDC, O2_ZDC_FLT_INIT_ZDC + constexpr uint8_t ALICETriggerMask = 0x1; constexpr int NModules = 8; @@ -190,6 +196,12 @@ constexpr int DbgFull = 3; const std::string CCDBPathConfigSim = "ZDC/Config/Sim"; const std::string CCDBPathConfigModule = "ZDC/Config/Module"; +const std::string CCDBPathConfigReco= "ZDC/Calib/RecoParam"; +const std::string CCDBPathConfigIntegration= "ZDC/Calib/IntegrationParam"; +const std::string CCDBPathTDCCalib= "ZDC/Calib/TDCCalib"; + +// Placeholders +constexpr int DummyIntRange = -NTimeBinsPerBC -1; constexpr std::string_view DummyName = "Dumm"; constexpr std::string_view VoidName = " NA "; diff --git a/Detectors/ZDC/macro/CMakeLists.txt b/Detectors/ZDC/macro/CMakeLists.txt index 46f4575ceaf36..23143ec9aad44 100644 --- a/Detectors/ZDC/macro/CMakeLists.txt +++ b/Detectors/ZDC/macro/CMakeLists.txt @@ -20,3 +20,8 @@ o2_add_test_root_macro(CreateModuleConfig.C o2_add_test_root_macro(readZDCDigits.C PUBLIC_LINK_LIBRARIES O2::ZDCSimulation O2::CCDB LABELS zdc) + +o2_add_test_root_macro(CreateIntegrationParam.C + PUBLIC_LINK_LIBRARIES O2::ZDCBase O2::ZDCReconstruction + O2::SimulationDataFormat O2::CCDB + LABELS zdc) diff --git a/Detectors/ZDC/macro/CreateIntegrationParam.C b/Detectors/ZDC/macro/CreateIntegrationParam.C new file mode 100644 index 0000000000000..df8ba52bfc70d --- /dev/null +++ b/Detectors/ZDC/macro/CreateIntegrationParam.C @@ -0,0 +1,75 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#if !defined(__CLING__) || defined(__ROOTCLING__) + +#include "FairLogger.h" +#include "CCDB/CcdbApi.h" +#include "ZDCReconstruction/ZDCIntegrationParam.h" +#include "ZDCBase/Constants.h" +#include +#include +#include + +#endif + +using namespace o2::zdc; +using namespace std; + +void CreateIntegrationParam(long tmin = 0, long tmax = -1, + std::string ccdbHost = "http://ccdb-test.cern.ch:8080") +{ + + ZDCIntegrationParam conf; + + // Integration limits for all signals + // Values should be in range -12..11 + // Channel ID, signal begin, end, pedestal begin, end + conf.setIntegration(IdZNAC, 5, 9, -12, -8); + conf.setIntegration(IdZNA1, 5, 9, -12, -8); + conf.setIntegration(IdZNA2, 5, 9, -12, -8); + conf.setIntegration(IdZNA3, 5, 9, -12, -8); + conf.setIntegration(IdZNA4, 5, 9, -12, -8); + conf.setIntegration(IdZNASum, 5, 9, -12, -8); + // + conf.setIntegration(IdZPAC, 5, 9, -12, -8); + conf.setIntegration(IdZPA1, 5, 9, -12, -8); + conf.setIntegration(IdZPA2, 5, 9, -12, -8); + conf.setIntegration(IdZPA3, 5, 9, -12, -8); + conf.setIntegration(IdZPA4, 5, 9, -12, -8); + conf.setIntegration(IdZPASum, 5, 9, -12, -8); + // + conf.setIntegration(IdZEM1, 5, 9, -12, -8); + conf.setIntegration(IdZEM2, 5, 9, -12, -8); + // + conf.setIntegration(IdZNCC, 5, 9, -12, -8); + conf.setIntegration(IdZNC1, 5, 9, -12, -8); + conf.setIntegration(IdZNC2, 5, 9, -12, -8); + conf.setIntegration(IdZNC3, 5, 9, -12, -8); + conf.setIntegration(IdZNC4, 5, 9, -12, -8); + conf.setIntegration(IdZNCSum, 5, 9, -12, -8); + // + conf.setIntegration(IdZPCC, 5, 9, -12, -8); + conf.setIntegration(IdZPC1, 5, 9, -12, -8); + conf.setIntegration(IdZPC2, 5, 9, -12, -8); + conf.setIntegration(IdZPC3, 5, 9, -12, -8); + conf.setIntegration(IdZPC4, 5, 9, -12, -8); + conf.setIntegration(IdZPCSum, 5, 9, -12, -8); + + conf.print(); + + o2::ccdb::CcdbApi api; + map metadata; // can be empty + api.init(ccdbHost.c_str()); // or http://localhost:8080 for a local installation + // store abitrary user object in strongly typed manner + api.storeAsTFileAny(&conf, CCDBPathConfigIntegration, metadata, tmin, tmax); + + // return conf; +} diff --git a/Detectors/ZDC/reconstruction/CMakeLists.txt b/Detectors/ZDC/reconstruction/CMakeLists.txt index cde859dd602ce..fa310cfd0e2bb 100644 --- a/Detectors/ZDC/reconstruction/CMakeLists.txt +++ b/Detectors/ZDC/reconstruction/CMakeLists.txt @@ -1,12 +1,12 @@ -#Copyright CERN and copyright holders of ALICE O2.This software is distributed -#under the terms of the GNU General Public License v3(GPL Version 3), copied -#verbatim in the file "COPYING". +# Copyright CERN and copyright holders of ALICE O2.This software is distributed +# under the terms of the GNU General Public License v3(GPL Version 3), copied +# verbatim in the file "COPYING". # -#See http: //alice-o2.web.cern.ch/license for full licensing information. +# See http: //alice-o2.web.cern.ch/license for full licensing information. # -#In applying this license CERN does not waive the privileges and immunities -#granted to it by virtue of its status as an Intergovernmental Organization or -#submit itself to any jurisdiction. +# In applying this license CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization or +# submit itself to any jurisdiction. o2_add_library(ZDCReconstruction SOURCES src/CTFCoder.cxx @@ -14,6 +14,7 @@ o2_add_library(ZDCReconstruction src/DigiReco.cxx src/RecoParamZDC.cxx src/ZDCTDCParam.cxx + src/ZDCIntegrationParam.cxx PUBLIC_LINK_LIBRARIES O2::ZDCBase O2::DataFormatsZDC O2::ZDCSimulation diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h index 7ebdf7357a0ab..79d638e948b86 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h @@ -1,4 +1,14 @@ -#include +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include #include #include #include "ZDCBase/Constants.h" @@ -22,18 +32,25 @@ class DigiReco { public: DigiReco() = default; - ~DigiReco() { - mTDbg->Write(); - mDbg->Close(); + ~DigiReco() + { + if (mTreeDbg) { + mTDbg->Write(); + mDbg->Close(); + } } void init(); - int process(const std::vector *orbitdata, const std::vector *bcdata, const std::vector *chdata); + int process(const std::vector* orbitdata, const std::vector* bcdata, const std::vector* chdata); int write(); void setVerbosity(int v) { mVerbosity = v; } int getVerbosity() const { return mVerbosity; } + void setDebugOutput(bool state = true) + { + mTreeDbg = state; + } void setModuleConfig(const ModuleConfig* moduleConfig) { mModuleConfig = moduleConfig; }; const ModuleConfig* getModuleConfig() { return mModuleConfig; }; @@ -41,32 +58,33 @@ class DigiReco const ZDCTDCParam* getTDCParam() { return mTDCParam; }; void setIntegrationParam(const ZDCIntegrationParam* param) { mIntParam = param; }; const ZDCIntegrationParam* getIntegrationParam() { return mIntParam; }; - const ModuleConfig* mModuleConfig = nullptr; /// Trigger/readout configuration object private: - int reconstruct(int seq_beg, int seq_end); /// Main method for data reconstruction - void processTrigger(int itdc, int ibeg, int iend); /// Replay of trigger algorithm on acquired data - void interpolate(int itdc, int ibeg, int iend); /// Interpolation of samples to evaluate signal amplitude and arrival time + const ModuleConfig* mModuleConfig = nullptr; /// Trigger/readout configuration object + int reconstruct(int seq_beg, int seq_end); /// Main method for data reconstruction + void processTrigger(int itdc, int ibeg, int iend); /// Replay of trigger algorithm on acquired data + void interpolate(int itdc, int ibeg, int iend); /// Interpolation of samples to evaluate signal amplitude and arrival time void assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float amp); // Set reconstructed TDC values - bool mIsContinuous = true; /// continuous (self-triggered) or externally-triggered readout - int mNBCAHead = 0; /// when storing triggered BC, store also mNBCAHead BCs - const ZDCTDCParam* mTDCParam = nullptr; /// TDC calibration object - uint32_t mTDCMask[NTDCChannels]={0}; /// Identify TDC channels in trigger mask - const ZDCIntegrationParam* mIntParam = nullptr; /// Configuration of integration - bool mVerbosity=DbgFull; - Double_t mTS[NTS]; /// Tapered sinc function - TFile* mDbg = nullptr; /// Debug output - TTree* mTDbg = nullptr; /// Debug tree - const std::vector *mOrbitData; /// Reconstructed data - const std::vector *mBCData; /// BC info - const std::vector *mChData; /// Payload - std::vector mReco; /// Reconstructed data - std::map mOrbit; /// Information about orbit - static constexpr int mNSB = TSN * NTimeBinsPerBC; /// Total number of interpolated points per bunch crossing - RecEvent mRec; /// Debug reconstruction event + bool mIsContinuous = true; /// continuous (self-triggered) or externally-triggered readout + int mNBCAHead = 0; /// when storing triggered BC, store also mNBCAHead BCs + const ZDCTDCParam* mTDCParam = nullptr; /// TDC calibration object + uint32_t mTDCMask[NTDCChannels] = {0}; /// Identify TDC channels in trigger mask + const ZDCIntegrationParam* mIntParam = nullptr; /// Configuration of integration + bool mVerbosity = DbgFull; + Double_t mTS[NTS]; /// Tapered sinc function + bool mTreeDbg = false; /// Write reconstructed data in debug output file + TFile* mDbg = nullptr; /// Debug output file + TTree* mTDbg = nullptr; /// Debug tree + const std::vector* mOrbitData; /// Reconstructed data + const std::vector* mBCData; /// BC info + const std::vector* mChData; /// Payload + std::vector mReco; /// Reconstructed data + std::map mOrbit; /// Information about orbit + static constexpr int mNSB = TSN * NTimeBinsPerBC; /// Total number of interpolated points per bunch crossing + RecEvent mRec; /// Debug reconstruction event int mNBC = 0; - int16_t tdc_shift[NTDCChannels] = {0}; /// TDC correction (units of 1/96 ns) - constexpr static uint16_t mMask[NTimeBinsPerBC]={0x0001,0x002,0x004,0x008, 0x0010,0x0020,0x0040,0x0080, 0x0100,0x0200,0x0400,0x0800}; + int16_t tdc_shift[NTDCChannels] = {0}; /// TDC correction (units of 1/96 ns) + constexpr static uint16_t mMask[NTimeBinsPerBC] = {0x0001, 0x002, 0x004, 0x008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200, 0x0400, 0x0800}; }; } // namespace zdc } // namespace o2 diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h index 1bb44d1de0371..b7932ce353b7b 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h @@ -8,8 +8,8 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef O2_ZDC_RECOPARAMZDC_H_ -#define O2_ZDC_RECOPARAMZDC_H_ +#ifndef O2_ZDC_RECOPARAMZDC_H +#define O2_ZDC_RECOPARAMZDC_H #include #include "CommonUtils/ConfigurableParam.h" @@ -27,19 +27,21 @@ namespace zdc // parameters of ZDC reconstruction struct RecoParamZDC : public o2::conf::ConfigurableParamHelper { - Int_t tsh[NTDCChannels] = {4, 4, 4, 4, 4, 4, 4, 4, 4, 4}; // Trigger shift - Int_t tth[NTDCChannels] = {8, 8, 8, 8, 8, 8, 8, 8, 8, 8}; // Trigger threshold - Int_t tmod[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of TDC channel in raw data - Int_t tch[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of TDC channel in raw data - Int_t amod[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of ADC channel in raw data - Int_t ach[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of ADC channel in raw data - float tdc_shift[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Correction of TDC position (0-25 ns, units of ~10 ps) - float tdc_search[NTDCChannels] = {250, 250, 250, 250, 250, 250, 250, 250, 250, 250}; // Search zone for a TDC signal ideally 2.5 ns (units of ~10 ps) - Int_t beg_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Start integration - signal - Int_t end_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // End integration - signal - Int_t beg_ped_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Start integration - pedestal - Int_t end_ped_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // End integration - pedestal - std::array bitset = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Set bits in coincidence + Int_t tsh[NTDCChannels] = {4, 4, 4, 4, 4, 4, 4, 4, 4, 4}; // Trigger shift + Int_t tth[NTDCChannels] = {8, 8, 8, 8, 8, 8, 8, 8, 8, 8}; // Trigger threshold + Int_t tmod[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of TDC channel in raw data + Int_t tch[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of TDC channel in raw data + Int_t amod[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of ADC channel in raw data + Int_t ach[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of ADC channel in raw data + float tdc_shift[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Correction of TDC position (0-25 ns, units of ~10 ps) + float tdc_search[NTDCChannels] = {250, 250, 250, 250, 250, 250, 250, 250, 250, 250}; // Search zone for a TDC signal ideally 2.5 ns (units of ~10 ps) + // Beginning and end of integration range: signal + Int_t beg_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; + Int_t end_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; + // Beginning and end of integration range: pedestal + Int_t beg_ped_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; + Int_t end_ped_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; + std::array bitset = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Set bits in coincidence public: void setBit(uint32_t ibit, bool val = true); O2ParamDef(RecoParamZDC, "RecoParamZDC"); diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCIntegrationParam.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCIntegrationParam.h index 5e62533d37a63..9dfd55dfaa218 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCIntegrationParam.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCIntegrationParam.h @@ -8,8 +8,8 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef O2_ZDC_INTEGRATIONPARAM_H_ -#define O2_ZDC_INTEGRATIONPARAM_H_ +#ifndef O2_ZDC_INTEGRATIONPARAM_H +#define O2_ZDC_INTEGRATIONPARAM_H #include "ZDCBase/Constants.h" #include @@ -27,10 +27,12 @@ namespace zdc struct ZDCIntegrationParam { public: - Int_t beg_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Start integration - signal - Int_t end_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // End integration - signal - Int_t beg_ped_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Start integration - pedestal - Int_t end_ped_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // End integration - pedestal + // Beginning and end of integration range: signal + Int_t beg_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; + Int_t end_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; + // Beginning and end of integration range: pedestal + Int_t beg_ped_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; + Int_t end_ped_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; void setIntegration(uint32_t ich, int beg, int end, int beg_ped, int end_ped); void print(); diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index f8a420dc441f5..72f0394cd05c1 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -1,14 +1,27 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + #include #include "FairLogger.h" #include "ZDCReconstruction/DigiReco.h" #include "ZDCReconstruction/RecoParamZDC.h" +#define O2_ZDC_DIGIRECO_FLT float + namespace o2 { namespace zdc { - -void DigiReco::init(){ + +void DigiReco::init() +{ // Load configuration parameters auto& sopt = ZDCSimParam::Instance(); mIsContinuous = sopt.continuous; @@ -21,52 +34,55 @@ void DigiReco::init(){ // Prepare tapered sinc function // tsc/TSN =3.75 (~ 4) and TSL*TSN*sqrt(2)/tsc >> 1 (n. of sigma) - const Double_t tsc = 750; - Int_t n = TSL * TSN; - for (Int_t tsi = 0; tsi <= n; tsi++) { - Double_t arg1 = TMath::Pi() * Double_t(tsi) / Double_t(TSN); - Double_t fs = 1; + const O2_ZDC_DIGIRECO_FLT tsc = 750; + int n = TSL * TSN; + for (int tsi = 0; tsi <= n; tsi++) { + O2_ZDC_DIGIRECO_FLT arg1 = TMath::Pi() * O2_ZDC_DIGIRECO_FLT(tsi) / O2_ZDC_DIGIRECO_FLT(TSN); + O2_ZDC_DIGIRECO_FLT fs = 1; if (arg1 != 0) fs = TMath::Sin(arg1) / arg1; - Double_t arg2 = Double_t(tsi) / tsc; - Double_t fg = TMath::Exp(-arg2 * arg2); + O2_ZDC_DIGIRECO_FLT arg2 = O2_ZDC_DIGIRECO_FLT(tsi) / tsc; + O2_ZDC_DIGIRECO_FLT fg = TMath::Exp(-arg2 * arg2); mTS[n + tsi] = fs * fg; mTS[n - tsi] = mTS[n + tsi]; // Function is even } - // Open debug file - mDbg = new TFile("ZDCReco.root", "recreate"); - mTDbg = new TTree("zdcr", "ZDCReco"); - mTDbg->Branch("zdcr", "RecEvent", &mRec); + if (mTreeDbg) { + // Open debug file + mDbg = new TFile("ZDCReco.root", "recreate"); + mTDbg = new TTree("zdcr", "ZDCReco"); + mTDbg->Branch("zdcr", "RecEvent", &mRec); + } // Update reconstruction parameters //auto& ropt=RecoParamZDC::Instance(); o2::zdc::RecoParamZDC& ropt = const_cast(RecoParamZDC::Instance()); - // Fill maps - for (Int_t itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { + // Fill maps to decode the pattern of channels with hit + for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { // If the reconstruction parameters were not manually set if (ropt.tmod[itdc] < 0 || ropt.tch[itdc] < 0) { - Int_t isig = TDCSignal[itdc]; - for (Int_t im = 0; im < NModules; im++) { - for (UInt_t ic = 0; ic < NChPerModule; ic++) { + int isig = TDCSignal[itdc]; + for (int im = 0; im < NModules; im++) { + for (uint32_t ic = 0; ic < NChPerModule; ic++) { if (mModuleConfig->modules[im].channelID[ic] == isig && mModuleConfig->modules[im].readChannel[ic]) { //ropt.updateFromString(TString::Format("RecoParamZDC.tmod[%d]=%d;",itdc,im)); //ropt.updateFromString(TString::Format("RecoParamZDC.tch[%d]=%d;",itdc,ic)); ropt.tmod[itdc] = im; ropt.tch[itdc] = ic; - // Fill mask to identify TDC channels - mTDCMask[itdc]=(0x1<<(4*im+ic)); + // Fill mask to identify TDC channels + mTDCMask[itdc] = (0x1 << (4 * im + ic)); goto next_itdc; } } } } next_itdc:; - LOG(INFO) << "TDC " << itdc << "(" << ChannelNames[TDCSignal[itdc]] << ")" << " mod " << ropt.tmod[itdc] << " ch " << ropt.tch[itdc]; + LOG(INFO) << "TDC " << itdc << "(" << ChannelNames[TDCSignal[itdc]] << ")" + << " mod " << ropt.tmod[itdc] << " ch " << ropt.tch[itdc]; } // TDC calibration - for (Int_t itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { + for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { float fval = ropt.tdc_shift[itdc]; // If the reconstruction parameters were not manually set if (fval < 0) { @@ -89,16 +105,16 @@ void DigiReco::init(){ } // TDC search zone // TODO: override with configuration object - for (Int_t itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { + for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << ropt.tdc_search[itdc] << " i.s. = " << ropt.tdc_search[itdc] / 96. << " ns"; } // Fill maps channel maps for integration - for (Int_t ich = 0; ich < NChannels; ich++) { + for (int ich = 0; ich < NChannels; ich++) { // If the reconstruction parameters were not manually set if (ropt.amod[ich] < 0 || ropt.ach[ich] < 0) { - for (Int_t im = 0; im < NModules; im++) { - for (UInt_t ic = 0; ic < NChPerModule; ic++) { + for (int im = 0; im < NModules; im++) { + for (uint32_t ic = 0; ic < NChPerModule; ic++) { if (mModuleConfig->modules[im].channelID[ic] == ich && mModuleConfig->modules[im].readChannel[ic]) { ropt.amod[ich] = im; ropt.ach[ich] = ic; @@ -112,9 +128,9 @@ void DigiReco::init(){ } // Integration ranges - for (Int_t ich = 0; ich < NChannels; ich++) { + for (int ich = 0; ich < NChannels; ich++) { // If the reconstruction parameters were not manually set - if (ropt.beg_int[ich] < 0 || ropt.end_int[ich] < 0) { + if (ropt.beg_int[ich] <= DummyIntRange || ropt.end_int[ich] <= DummyIntRange) { if (!mIntParam) { LOG(ERROR) << "Integration for signal " << ich << " missing configuration object and no manual override"; } else { @@ -122,7 +138,7 @@ void DigiReco::init(){ ropt.end_int[ich] = mIntParam->end_int[ich]; } } - if (ropt.beg_ped_int[ich] < 0 || ropt.end_ped_int[ich] < 0) { + if (ropt.beg_ped_int[ich] <= DummyIntRange || ropt.end_ped_int[ich] <= DummyIntRange) { if (!mIntParam) { LOG(ERROR) << "Integration for pedestal " << ich << " missing configuration object and no manual override"; } else { @@ -130,89 +146,92 @@ void DigiReco::init(){ ropt.end_ped_int[ich] = mIntParam->end_ped_int[ich]; } } - LOG(INFO) << ChannelNames[ich] << " integration: signal=[" << ropt.beg_int[ich] << "-" << ropt.end_int[ich] << "] pedestal=[" << ropt.beg_ped_int[ich] << "-" << ropt.end_ped_int[ich] <<"]"; + LOG(INFO) << ChannelNames[ich] << " integration: signal=[" << ropt.beg_int[ich] << "-" << ropt.end_int[ich] << "] pedestal=[" << ropt.beg_ped_int[ich] << "-" << ropt.end_ped_int[ich] << "]"; } } -int DigiReco::process(const std::vector *orbitdata, const std::vector *bcdata, const std::vector *chdata){ +int DigiReco::process(const std::vector* orbitdata, const std::vector* bcdata, const std::vector* chdata) +{ // We assume that vectors contain data from a full time frame - mOrbitData=orbitdata; - mBCData=bcdata; - mChData=chdata; - - const std::vector &OrbitData=*orbitdata; - const std::vector &BCData=*bcdata; - const std::vector &ChData=*chdata; - + mOrbitData = orbitdata; + mBCData = bcdata; + mChData = chdata; + + const std::vector& OrbitData = *orbitdata; + const std::vector& BCData = *bcdata; + const std::vector& ChData = *chdata; + // Initialization of lookup structure for pedestals mOrbit.clear(); - int norb=OrbitData.size(); - for(Int_t iorb=0; iorb=DbgFull){ + int norb = OrbitData.size(); + for (int iorb = 0; iorb < norb; iorb++) { + mOrbit[OrbitData[iorb].ir.orbit] = iorb; + if (mVerbosity >= DbgFull) { LOG(INFO) << "OrbitData[" << OrbitData[iorb].ir.orbit << "] = " << iorb; } } - mNBC=BCData.size(); + mNBC = BCData.size(); mReco.clear(); - mReco.reserve(mNBC); + mReco.resize(mNBC); // Initialization of reco structure - for(Int_t ibc=0; ibcIdDummy && chd.id IdDummy && chd.id < NChannels) { + bcr.ref[chd.id] = chEnt; } chEnt++; } } - + // Probably this is not necessary -// for(Int_t itdc=0; itdc1){ + } else if (bcd > 1) { // Detected a gap reconstruct(seq_beg, seq_end); - seq_beg=ibc; - seq_end=ibc; - }else if(ibc==(mNBC-1)){ + seq_beg = ibc; + seq_end = ibc; + } else if (ibc == (mNBC - 1)) { // Last bunch - seq_end=ibc; + seq_end = ibc; reconstruct(seq_beg, seq_end); - seq_beg=mNBC; - seq_end=mNBC; - }else{ + seq_beg = mNBC; + seq_end = mNBC; + } else { // Look for another bunch - seq_end=ibc; + seq_end = ibc; } } -/* + /* std::map::iterator it; @@ -228,7 +247,8 @@ std::map::iterator it; return 0; } -int DigiReco::reconstruct(int ibeg, int iend){ +int DigiReco::reconstruct(int ibeg, int iend) +{ // Process consecutive BCs if (ibeg == iend) { LOG(INFO) << "Lonely bunch " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc; @@ -236,35 +256,22 @@ int DigiReco::reconstruct(int ibeg, int iend){ } LOG(INFO) << __func__ << "(" << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; // Get references to arrays - const std::vector &OrbitData=*mOrbitData; - const std::vector &BCData=*mBCData; - const std::vector &ChData=*mChData; + const std::vector& OrbitData = *mOrbitData; + const std::vector& BCData = *mBCData; + const std::vector& ChData = *mChData; // Get reconstruction parameters auto& ropt = RecoParamZDC::Instance(); -// int chEnt = bcd.ref.getFirstEntry(); -// for (int ic = 0; ic < bcd.ref.getEntries(); ic++) { -// const auto& chd = zdcChData[chEnt++]; -// chd.print(); -// UShort_t bc=bcd.ir.bc; -// UInt_t orbit=bcd.ir.orbit; -// for(Int_t is=0; isGetN(); -// gr[chd.id]->SetPoint(ip,3564.*orbit+bc+is/12.,myval); -// } -// } - // Apply differential discrimination with triple condition - for (Int_t itdc = 0; itdc < NTDCChannels; itdc++) { + for (int itdc = 0; itdc < NTDCChannels; itdc++) { // Check if channel has valid data for consecutive bunches in current bunch range // N.B. there are events recorded from ibeg-iend but we are not sure if it is the // case for every TDC channel int istart = -1, istop = -1; // Loop allows for gaps in the data sequence for each TDC channel for (int ibun = ibeg; ibun <= iend; ibun++) { - if (BCData[ibun].channels&mTDCMask[itdc]) { // TDC channel has data for this event + if (BCData[ibun].channels & mTDCMask[itdc]) { // TDC channel has data for this event if (istart < 0) { istart = ibun; } @@ -289,56 +296,56 @@ int DigiReco::reconstruct(int ibeg, int iend){ // Reconstruct integrated charges and fill output tree // TODO: compare average pedestal with estimation from current event // TODO: failover in case of discrepancy - for (Int_t ibun = ibeg; ibun <= iend; ibun++) { + for (int ibun = ibeg; ibun <= iend; ibun++) { // Look for offset float pbun[NChannels]; - auto orbit=BCData[ibun].ir.orbit; - std::map::iterator it = mOrbit.find(orbit); - if (it != mOrbit.end()){ + auto orbit = BCData[ibun].ir.orbit; + std::map::iterator it = mOrbit.find(orbit); + if (it != mOrbit.end()) { // Subtract pedestal - auto &orbitdata=OrbitData[it->second]; - for(int ich=0; ichsecond]; + for (int ich = 0; ich < NChannels; ich++) { + pbun[ich] = orbitdata.asFloat(ich); } - }else{ + } else { LOG(ERROR) << "Missing pedestal for bunch " << ibun; - for(int ich=0; ich::infinity(); + for (int ich = 0; ich < NChannels; ich++) { + pbun[ich] = std::numeric_limits::infinity(); } } // Debug dump of pedestal - if(mVerbosity>=DbgFull){ - for(int ich=0; ich= DbgFull) { + for (int ich = 0; ich < NChannels; ich++) { + LOG(INFO) << "bunch: " << ibun << " ch: " << ich << " " << ChannelNames[ich] << " offset: " << pbun[ich]; } } - RecEvent &rec = mReco[ibun]; - for (Int_t itdc = 0; itdc < NTDCChannels; itdc++) { - if(rec.fired[itdc]!=0x0){ - printf("%d %u.%u TDC %d %x", ibun, rec.ir.orbit, rec.ir.bc, itdc,rec.fired[itdc]); - for (Int_t isam = 0; isam < NTimeBinsPerBC; isam++) { - printf("%d", rec.fired[itdc]&mMask[isam]?1:0); - } - printf("\n"); + RecEvent& rec = mReco[ibun]; + for (int itdc = 0; itdc < NTDCChannels; itdc++) { + if (rec.fired[itdc] != 0x0) { + printf("%d %u.%u TDC %d %x", ibun, rec.ir.orbit, rec.ir.bc, itdc, rec.fired[itdc]); + for (int isam = 0; isam < NTimeBinsPerBC; isam++) { + printf("%d", rec.fired[itdc] & mMask[isam] ? 1 : 0); + } + printf("\n"); } -// for (Int_t i = 0; i < MaxTDCValues; i++) { -// rec.tdcChannels[itdc][i] = kMinShort; -// rec.tdcAmplitudes[itdc][i] = -999; -// } + // for (int i = 0; i < MaxTDCValues; i++) { + // rec.tdcVal[itdc][i] = kMinShort; + // rec.tdcAmp[itdc][i] = -999; + // } rec.pattern[itdc] = 0; - for(int32_t i=0; iFill(); + } } // Loop on bunches } @@ -498,48 +414,48 @@ void DigiReco::processTrigger(int itdc, int ibeg, int iend) { LOG(INFO) << __func__ << "(itdc=" << itdc << "[" << ChannelNames[TDCSignal[itdc]] << "] ," << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; - const std::vector &OrbitData=*mOrbitData; - const std::vector &BCData=*mBCData; - const std::vector &ChData=*mChData; + const std::vector& OrbitData = *mOrbitData; + const std::vector& BCData = *mBCData; + const std::vector& ChData = *mChData; // Get reconstruction parameters auto& ropt = RecoParamZDC::Instance(); -// int chEnt = bcd.ref.getFirstEntry(); -// for (int ic = 0; ic < bcd.ref.getEntries(); ic++) { -// const auto& chd = zdcChData[chEnt++]; -// chd.print(); -// UShort_t bc=bcd.ir.bc; -// UInt_t orbit=bcd.ir.orbit; -// for(Int_t is=0; isGetN(); -// gr[chd.id]->SetPoint(ip,3564.*orbit+bc+is/12.,myval); -// } -// } - - Int_t nbun = iend - ibeg + 1; - Int_t maxs2 = NTimeBinsPerBC * nbun - 1; - Int_t shift = ropt.tsh[itdc]; - Int_t thr = ropt.tth[itdc]; - - Int_t is1 = 0, is2 = 1; - Int_t isfired[3] = {0}; - Int_t it1=0,it2=0,ib1=-1,ib2=-1; + // int chEnt = bcd.ref.getFirstEntry(); + // for (int ic = 0; ic < bcd.ref.getEntries(); ic++) { + // const auto& chd = zdcChData[chEnt++]; + // chd.print(); + // auto bc=bcd.ir.bc; + // auto orbit=bcd.ir.orbit; + // for(int is=0; isGetN(); + // gr[chd.id]->SetPoint(ip,3564.*orbit+bc+is/12.,myval); + // } + // } + + int nbun = iend - ibeg + 1; + int maxs2 = NTimeBinsPerBC * nbun - 1; + int shift = ropt.tsh[itdc]; + int thr = ropt.tth[itdc]; + + int is1 = 0, is2 = 1; + int isfired[3] = {0}; + int it1 = 0, it2 = 0, ib1 = -1, ib2 = -1; for (;;) { // Shift data - for (Int_t i = 1; i < 3; i++) { + for (int i = 1; i < 3; i++) { isfired[i] = isfired[i - 1]; } // Bunches and samples that are used in the difference - Int_t b1 = ibeg + is1 / NTimeBinsPerBC; - Int_t b2 = ibeg + is2 / NTimeBinsPerBC; - Int_t s1 = is1 % NTimeBinsPerBC; - Int_t s2 = is2 % NTimeBinsPerBC; + int b1 = ibeg + is1 / NTimeBinsPerBC; + int b2 = ibeg + is2 / NTimeBinsPerBC; + int s1 = is1 % NTimeBinsPerBC; + int s2 = is2 % NTimeBinsPerBC; auto ref_m = mReco[b1].ref[TDCSignal[itdc]]; auto ref_s = mReco[b2].ref[TDCSignal[itdc]]; // Check data consistency before computing difference - if(ref_m == O2_ZDC_REF_INIT_VAL || ref_s == O2_ZDC_REF_INIT_VAL){ + if (ref_m == O2_ZDC_REF_INIT_VAL || ref_s == O2_ZDC_REF_INIT_VAL) { LOG(FATAL) << "Missing information for bunch crossing"; return; } @@ -551,7 +467,7 @@ void DigiReco::processTrigger(int itdc, int ibeg, int iend) if (isfired[1] == 1 && isfired[2] == 1) { // Fired bit is assigned to the second sample, i.e. to the one that can identify the // signal peak position - mReco[b2].fired[itdc]|=mMask[s2]; + mReco[b2].fired[itdc] |= mMask[s2]; //LOG(INFO) << itdc << " Fired @ " << mReco[b2].ir.orbit << "." << mReco[b2].ir.bc << " " << b2 - ibeg << "." << s2 << "=" << NTimeBinsPerBC * (b2 - ibeg) + s2; LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " Fired @ " << mReco[b2].ir.orbit << "." << mReco[b2].ir.bc << ".s" << s2; } @@ -573,60 +489,60 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) { LOG(INFO) << __func__ << "(itdc=" << itdc << "[" << ChannelNames[TDCSignal[itdc]] << "] ," << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; // TODO: get data from preceding time frame - constexpr int MaxTimeBin = NTimeBinsPerBC - 1; //< number of samples per BC - constexpr int tsnh = TSN / 2; // Half number of points in interpolation - constexpr int nsbun = TSN * NTimeBinsPerBC; // Total number of interpolated points per bunch crossing - Int_t nbun = iend - ibeg + 1; // Number of adjacent bunches - Int_t nsam = nbun * NTimeBinsPerBC; // Number of acquired samples - Int_t ntot = nsam * TSN; // Total number of points in the interpolated arrays - Int_t nint = (nbun * NTimeBinsPerBC - 1) * TSN; // Total points in the interpolation region (-1) - constexpr int nsp = 5; // Number of points to be searched - - const std::vector &OrbitData=*mOrbitData; - const std::vector &BCData=*mBCData; - const std::vector &ChData=*mChData; + constexpr int MaxTimeBin = NTimeBinsPerBC - 1; //< number of samples per BC + constexpr int tsnh = TSN / 2; // Half number of points in interpolation + constexpr int nsbun = TSN * NTimeBinsPerBC; // Total number of interpolated points per bunch crossing + int nbun = iend - ibeg + 1; // Number of adjacent bunches + int nsam = nbun * NTimeBinsPerBC; // Number of acquired samples + int ntot = nsam * TSN; // Total number of points in the interpolated arrays + int nint = (nbun * NTimeBinsPerBC - 1) * TSN; // Total points in the interpolation region (-1) + constexpr int nsp = 5; // Number of points to be searched + + const std::vector& OrbitData = *mOrbitData; + const std::vector& BCData = *mBCData; + const std::vector& ChData = *mChData; // At this level there should be no need to check if the TDC channel is connected // since a fatal should have been raised already - for(int ibun=ibeg; ibun<=iend; ibun++){ + for (int ibun = ibeg; ibun <= iend; ibun++) { auto ref = mReco[ibun].ref[TDCSignal[itdc]]; - if(ref == O2_ZDC_REF_INIT_VAL){ + if (ref == O2_ZDC_REF_INIT_VAL) { LOG(FATAL) << "Missing information for bunch crossing"; } } - + // Get reconstruction parameters auto& ropt = RecoParamZDC::Instance(); - Int_t imod = ropt.tmod[itdc]; // Module corresponding to TDC channel - Int_t ich = ropt.tch[itdc]; // Hardware channel corresponding to TDC channel + int imod = ropt.tmod[itdc]; // Module corresponding to TDC channel + int ich = ropt.tch[itdc]; // Hardware channel corresponding to TDC channel auto ref_beg = mReco[ibeg].ref[TDCSignal[itdc]]; auto ref_end = mReco[iend].ref[TDCSignal[itdc]]; - Double_t first_sample = ChData[ref_beg].data[0]; - Double_t last_sample = ChData[ref_end].data[NTimeBinsPerBC - 1]; + O2_ZDC_DIGIRECO_FLT first_sample = ChData[ref_beg].data[0]; + O2_ZDC_DIGIRECO_FLT last_sample = ChData[ref_end].data[NTimeBinsPerBC - 1]; // Constant extrapolation at the beginning and at the end of the array // Assign value of first sample - for (Int_t i = 0; i < tsnh; i++) { + for (int i = 0; i < tsnh; i++) { mReco[ibeg].inter[itdc][i] = first_sample; } // Assign value of last sample - for (Int_t i = ntot - tsnh; i < ntot; i++) { - Int_t isam = i % nsbun; + for (int i = ntot - tsnh; i < ntot; i++) { + int isam = i % nsbun; mReco[iend].inter[itdc][isam] = last_sample; } // Interpolation between acquired points (n.b. loop from 0 to nint) - for (Int_t i = 0; i < nint; i++) { + for (int i = 0; i < nint; i++) { // Identification of the point to be assigned (need to add tsnh to identify the point) - Int_t ibun = ibeg + (i + tsnh) / nsbun; - Int_t isam = (i + tsnh) % nsbun; - Int_t im = i % TSN; + int ibun = ibeg + (i + tsnh) / nsbun; + int isam = (i + tsnh) % nsbun; + int im = i % TSN; if (im == 0) { // This is an acquired point - Int_t ip = (i / TSN) % NTimeBinsPerBC; - Int_t ib = ibeg + (i / TSN) / NTimeBinsPerBC; + int ip = (i / TSN) % NTimeBinsPerBC; + int ib = ibeg + (i / TSN) / NTimeBinsPerBC; if (ib != ibun) { LOG(FATAL) << "ib=" << ib << " ibun=" << ibun; return; @@ -634,17 +550,17 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) mReco[ibun].inter[itdc][isam] = ChData[mReco[ibun].ref[TDCSignal[itdc]]].data[ip]; } else { // Do the actual interpolation - Double_t y = 0; - Int_t ip = i / TSN; - Double_t sum = 0; - for (Int_t is = TSN - im, ii = ip - TSL + 1; is < NTS; is += TSN, ii++) { + O2_ZDC_DIGIRECO_FLT y = 0; + int ip = i / TSN; + O2_ZDC_DIGIRECO_FLT sum = 0; + for (int is = TSN - im, ii = ip - TSL + 1; is < NTS; is += TSN, ii++) { // Default is first point in the array - Double_t yy = first_sample; + O2_ZDC_DIGIRECO_FLT yy = first_sample; if (ii > 0) { if (ii < nsam) { - Int_t ip = ii % NTimeBinsPerBC; - Int_t ib = ibeg + ii / NTimeBinsPerBC; - yy = ChData[mReco[ib].ref[TDCSignal[itdc]]].data[ip]; + int ip = ii % NTimeBinsPerBC; + int ib = ibeg + ii / NTimeBinsPerBC; + yy = ChData[mReco[ib].ref[TDCSignal[itdc]]].data[ip]; } else { // Last acquired point yy = last_sample; @@ -659,16 +575,16 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) } // Looking for a local maximum in a searching zone float amp = std::numeric_limits::infinity(); // Amplitude to be stored - Int_t isam_amp = 0; // Sample at maximum amplitude (relative to beginning of group) - Int_t ip_old = -1, ip_cur = -1, ib_cur = -1; // Current and old points + int isam_amp = 0; // Sample at maximum amplitude (relative to beginning of group) + int ip_old = -1, ip_cur = -1, ib_cur = -1; // Current and old points bool is_searchable = false; // Flag for point in the search zone for maximum amplitude bool was_searchable = false; // Flag for point in the search zone for maximum amplitude - Int_t ib[nsp] = {-1, -1, -1, -1, -1}; - Int_t ip[nsp] = {-1, -1, -1, -1, -1}; + int ib[nsp] = {-1, -1, -1, -1, -1}; + int ip[nsp] = {-1, -1, -1, -1, -1}; // N.B. Points at the extremes are constant therefore no local maximum // can occur in these two regions - for (Int_t i = 0; i < nint; i++) { - Int_t isam = i + tsnh; + for (int i = 0; i < nint; i++) { + int isam = i + tsnh; // Check if trigger is fired for this point // For the moment we don't take into account possible extensions of the search zone // ip_cur can span several bunches and is used just to identify transitions @@ -676,7 +592,7 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) // Speed up computation if (ip_cur != ip_old) { ip_old = ip_cur; - for (Int_t j = 0; j < 5; j++) { + for (int j = 0; j < 5; j++) { ib[j] = -1; ip[j] = -1; } @@ -724,10 +640,10 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) was_searchable = is_searchable; // Search conditions with list of allowed patterns // No need to double check ib[?] and ip[?] because either we assign both or none - uint16_t triggered=0x0000; - for (Int_t j = 0; j < 5; j++) { - if (ib[j] >= 0 && (mReco[ib[j]].fired[itdc]&mMask[ip[j]]) > 0) { - triggered |= (0x1<= 0 && (mReco[ib[j]].fired[itdc] & mMask[ip[j]]) > 0) { + triggered |= (0x1 << j); } } // Reject conditions: @@ -736,7 +652,7 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) // One among 10000 and 00001 // Accept conditions: constexpr uint16_t accept[14] = { -// 0x01, // 00001 extend search zone before maximum + // 0x01, // 00001 extend search zone before maximum 0x02, // 00010 0x04, // 00100 0x08, // 01000 @@ -751,16 +667,16 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) 0x0f, // 01111 0x1e, // 11110 0x1f // 11111 - }; + }; // All other are not correct (->reject) is_searchable = 0; - if(triggered!=0){ - for(Int_t j=0; j<14; j++){ - if(triggered==accept[j]){ + if (triggered != 0) { + for (int j = 0; j < 14; j++) { + if (triggered == accept[j]) { is_searchable = 1; - break; - } - } + break; + } + } } } // We do not restrict search zone around expected main-main collision @@ -771,19 +687,19 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) if (was_searchable && !is_searchable) { if (amp <= ADCMax) { // Store identified peak - Int_t ibun = ibeg + isam_amp / nsbun; - Int_t tdc = isam_amp % nsbun; - // Look for offset - auto orbit=BCData[ibun].ir.orbit; - std::map::iterator it = mOrbit.find(orbit); - if (it != mOrbit.end()){ - // Subtract pedestal - auto &orbitdata=OrbitData[it->second]; + int ibun = ibeg + isam_amp / nsbun; + int tdc = isam_amp % nsbun; + // Look for offset + auto orbit = BCData[ibun].ir.orbit; + std::map::iterator it = mOrbit.find(orbit); + if (it != mOrbit.end()) { + // Subtract pedestal + auto& orbitdata = OrbitData[it->second]; amp = orbitdata.asFloat(ich) - amp; - }else{ - LOG(ERROR) << "Missing pedestal"; - amp = std::numeric_limits::infinity(); - } + } else { + LOG(ERROR) << "Missing pedestal"; + amp = std::numeric_limits::infinity(); + } assignTDC(ibun, ibeg, iend, itdc, tdc, amp); } amp = std::numeric_limits::infinity(); @@ -791,7 +707,7 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) was_searchable = 0; } if (is_searchable) { - Int_t mysam = isam % nsbun; + int mysam = isam % nsbun; if (mReco[ib_cur].inter[itdc][mysam] < amp) { amp = mReco[ib_cur].inter[itdc][mysam]; isam_amp = isam; @@ -803,18 +719,18 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) // Add last identified peak if (amp <= ADCMax) { // Store identified peak - Int_t ibun = ibeg + isam_amp / nsbun; - Int_t tdc = isam_amp % nsbun; + int ibun = ibeg + isam_amp / nsbun; + int tdc = isam_amp % nsbun; // Look for offset - auto orbit=BCData[ibun].ir.orbit; - std::map::iterator it = mOrbit.find(orbit); - if (it != mOrbit.end()){ - // Subtract pedestal - auto &orbitdata=OrbitData[it->second]; + auto orbit = BCData[ibun].ir.orbit; + std::map::iterator it = mOrbit.find(orbit); + if (it != mOrbit.end()) { + // Subtract pedestal + auto& orbitdata = OrbitData[it->second]; amp = orbitdata.asFloat(ich) - amp; - }else{ - LOG(ERROR) << "Missing pedestal"; - amp = std::numeric_limits::infinity(); + } else { + LOG(ERROR) << "Missing pedestal"; + amp = std::numeric_limits::infinity(); } assignTDC(ibun, ibeg, iend, itdc, tdc, amp); } @@ -828,7 +744,7 @@ void DigiReco::assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float constexpr int tdc_min = -tdc_max; // Apply tdc shift correction - Int_t tdc_cor = tdc - tdc_shift[itdc]; + int tdc_cor = tdc - tdc_shift[itdc]; // Correct bunch assignment if (tdc_cor < tdc_min && ibun >= ibeg) { // Assign to preceding bunch @@ -848,16 +764,16 @@ void DigiReco::assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float tdc_cor = kMaxShort; } // Assign to correct bunch - int &ihit=mReco[ibun].ntdc[itdc]; - if(ihit Date: Fri, 7 May 2021 13:46:15 +0200 Subject: [PATCH 004/770] avoid to store some floats --- .../ZDC/include/DataFormatsZDC/RecEvent.h | 17 +++++++------- Detectors/ZDC/reconstruction/src/DigiReco.cxx | 22 ++++++++++--------- 2 files changed, 20 insertions(+), 19 deletions(-) diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h index 6e7ae27776f27..887e95b479c68 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h @@ -27,24 +27,23 @@ namespace o2 namespace zdc { struct RecEvent { - //using TDCChannel = std::array; - //using TDCAmplitude = std::array; - //using TDCChannel = std::vector; - //using TDCAmplitude = std::vector; o2::InteractionRecord ir; uint32_t flags; /// reconstruction flags std::map ezdc; /// signal in ZDCs float energy[NChannels] = {O2_ZDC_FLT_INIT}; /// ZDC signal - math_utils::Point2D centroidZNA; /// centroid coordinates for ZNA - math_utils::Point2D centroidZNC; /// centroid coordinates for ZNC - - int16_t tdcVal[NTDCChannels][MaxTDCValues]; /// TdcChannels - float tdcAmp[NTDCChannels][MaxTDCValues]; /// TdcAmplitudes + constexpr static float fAmp = 1. / 8.; /// Multiplication factor in conversion from integer + constexpr static float fVal = 1. / TSNS; /// Multiplication factor in conversion from integer + int16_t tdcVal[NTDCChannels][MaxTDCValues]; /// TdcChannels + int16_t tdcAmp[NTDCChannels][MaxTDCValues]; /// TdcAmplitudes int ntdc[NTDCChannels] = {0}; + + // Internal variables std::array pattern; /// Pattern of TDC uint16_t fired[NTDCChannels] = {0}; /// Position at which the trigger algorithm is fired float inter[NTDCChannels][NTimeBinsPerBC * TSN] = {0}; /// Interpolated samples uint32_t ref[NChannels] = {O2_ZDC_REF_INIT}; /// Cache of references + + // Functions void print() const; float EZDC(uint8_t ich) { diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index 72f0394cd05c1..567d63ca110e6 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -90,7 +90,7 @@ void DigiReco::init() if (!mTDCParam) { LOG(FATAL) << "TDC " << itdc << " missing configuration object and no manual override"; } else { - fval = mTDCParam->getShift(itdc) * 96.; + fval = mTDCParam->getShift(itdc) / RecEvent::fVal; } } auto val = std::nearbyint(fval); @@ -101,12 +101,12 @@ void DigiReco::init() LOG(FATAL) << "Shift for TDC " << itdc << " " << val << " is out of range"; } tdc_shift[itdc] = val; - LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " shift= " << tdc_shift[itdc] << " i.s. = " << val / 96. << " ns"; + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " shift= " << tdc_shift[itdc] << " i.s. = " << val*RecEvent::fVal << " ns"; } // TDC search zone // TODO: override with configuration object for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { - LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << ropt.tdc_search[itdc] << " i.s. = " << ropt.tdc_search[itdc] / 96. << " ns"; + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << ropt.tdc_search[itdc] << " i.s. = " << ropt.tdc_search[itdc]*RecEvent::fVal << " ns"; } // Fill maps channel maps for integration @@ -176,6 +176,12 @@ int DigiReco::process(const std::vector* orbitdata, const st // Initialization of reco structure for (int ibc = 0; ibc < mNBC; ibc++) { auto& bcr = mReco[ibc]; + for (int itdc = 0; itdc < NTDCChannels; itdc++) { + for (int i = 0; i < MaxTDCValues; i++) { + bcr.tdcVal[itdc][i] = kMinShort; + bcr.tdcAmp[itdc][i] = kMinShort; + } + } auto& bcd = BCData[ibc]; bcr.ir = bcd.ir; int chEnt = bcd.ref.getFirstEntry(); @@ -329,10 +335,6 @@ int DigiReco::reconstruct(int ibeg, int iend) } printf("\n"); } - // for (int i = 0; i < MaxTDCValues; i++) { - // rec.tdcVal[itdc][i] = kMinShort; - // rec.tdcAmp[itdc][i] = -999; - // } rec.pattern[itdc] = 0; for (int32_t i = 0; i < rec.ntdc[itdc]; i++) { LOG(INFO) << "tdc " << i << " [" << ChannelNames[TDCSignal[itdc]] << "] " << rec.tdcAmp[itdc][i] << " @ " << rec.tdcVal[itdc][i]; @@ -767,13 +769,13 @@ void DigiReco::assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float int& ihit = mReco[ibun].ntdc[itdc]; if (ihit < MaxTDCValues) { mReco[ibun].tdcVal[itdc][ihit] = tdc_cor; - mReco[ibun].tdcAmp[itdc][ihit] = amp; + mReco[ibun].tdcAmp[itdc][ihit] = std::nearbyint(amp/RecEvent::fAmp); ihit++; LOG(INFO) << mReco[ibun].ir.orbit << "." << mReco[ibun].ir.bc << " " - << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor << " amp=" << amp; + << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor*RecEvent::fVal << " amp=" << amp*RecEvent::fAmp; } else { LOG(ERROR) << mReco[ibun].ir.orbit << "." << mReco[ibun].ir.bc << " " - << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor << " amp=" << amp << " OVERFLOW"; + << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor*RecEvent::fVal << " amp=" << amp*RecEvent::fAmp << " OVERFLOW"; } } From f2ce8f63fe98695c00793d57004c3daa4e810c09 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 7 May 2021 17:09:44 +0200 Subject: [PATCH 005/770] Start reworking rec event structure --- DataFormats/Detectors/ZDC/CMakeLists.txt | 7 +- .../ZDC/include/DataFormatsZDC/BCRecData.h | 57 ++++++++++ .../ZDC/include/DataFormatsZDC/RecEvent.h | 6 +- .../ZDC/include/DataFormatsZDC/RecEventAux.h | 106 ++++++++++++++++++ .../ZDC/include/DataFormatsZDC/TDCData.h | 48 ++++++++ DataFormats/Detectors/ZDC/src/BCRecData.cxx | 27 +++++ .../Detectors/ZDC/src/DataFormatsZDCLinkDef.h | 1 + DataFormats/Detectors/ZDC/src/RecEventAux.cxx | 18 +++ DataFormats/Detectors/ZDC/src/TDCData.cxx | 18 +++ .../include/ZDCReconstruction/DigiReco.h | 7 +- .../include/ZDCReconstruction/ZDCTDCParam.h | 2 +- Detectors/ZDC/reconstruction/src/DigiReco.cxx | 5 +- 12 files changed, 289 insertions(+), 13 deletions(-) create mode 100644 DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h create mode 100644 DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h create mode 100644 DataFormats/Detectors/ZDC/include/DataFormatsZDC/TDCData.h create mode 100644 DataFormats/Detectors/ZDC/src/BCRecData.cxx create mode 100644 DataFormats/Detectors/ZDC/src/RecEventAux.cxx create mode 100644 DataFormats/Detectors/ZDC/src/TDCData.cxx diff --git a/DataFormats/Detectors/ZDC/CMakeLists.txt b/DataFormats/Detectors/ZDC/CMakeLists.txt index 4db60534f04f4..936a9edcd2592 100644 --- a/DataFormats/Detectors/ZDC/CMakeLists.txt +++ b/DataFormats/Detectors/ZDC/CMakeLists.txt @@ -9,8 +9,8 @@ # submit itself to any jurisdiction. o2_add_library(DataFormatsZDC - SOURCES src/ChannelData.cxx src/BCData.cxx src/RecEvent.cxx src/RawEventData.cxx - src/OrbitRawData.cxx src/OrbitRecData.cxx src/OrbitData.cxx + SOURCES src/ChannelData.cxx src/BCData.cxx src/RecEvent.cxx src/RecEventAux.cxx src/RawEventData.cxx + src/OrbitRawData.cxx src/OrbitRecData.cxx src/OrbitData.cxx src/TDCData.cxx src/CTF.cxx PUBLIC_LINK_LIBRARIES O2::CommonConstants O2::CommonDataFormat O2::ZDCBase ROOT::MathCore FairRoot::Base @@ -21,5 +21,6 @@ o2_target_root_dictionary(DataFormatsZDC HEADERS include/DataFormatsZDC/Hit.h include/DataFormatsZDC/MCLabel.h include/DataFormatsZDC/BCData.h include/DataFormatsZDC/ChannelData.h include/DataFormatsZDC/OrbitData.h include/DataFormatsZDC/CTF.h - include/DataFormatsZDC/RecEvent.h include/DataFormatsZDC/OrbitRawData.h + include/DataFormatsZDC/RecEvent.h include/DataFormatsZDC/RecEventAux.h + include/DataFormatsZDC/OrbitRawData.h include/DataFormatsZDC/TDCData.h include/DataFormatsZDC/OrbitRecData.h include/DataFormatsZDC/RawEventData.h) diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h new file mode 100644 index 0000000000000..e67f54d7b5444 --- /dev/null +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h @@ -0,0 +1,57 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef _ZDC_BC_REC_DATA_H +#define _ZDC_BC_REC_DATA_H + +#include "CommonDataFormat/InteractionRecord.h" +#include "CommonDataFormat/RangeReference.h" +#include "ZDCBase/Constants.h" +#include +#include + +/// \file BCData.h +/// \brief Class to describe reconstructed data and refer to channel data +/// \author ruben.shahoyan@cern.ch, pietro.cortese@cern.ch + +namespace o2 +{ +namespace zdc +{ +class ChannelData; + + +struct BCRecData { + /// we are going to refer to at most 26 channels, so 5 bits for the NChannels and 27 for the reference + o2::dataformats::RangeRefComp<5> refe; + o2::dataformats::RangeRefComp<5> reft; + o2::InteractionRecord ir; + uint32_t flags; + + BCRecData() = default; + BCRecData(int firste, int ne, int firstt, int nt, o2::InteractionRecord iRec, uint32_t fl) + { + refe.setFirstEntry(firste); + refe.setEntries(ne); + reft.setFirstEntry(firstt); + reft.setEntries(nt); + ir = iRec; + flags = fl; + } + + gsl::span getBunchChannelData(const gsl::span tfdata) const; + void print() const; + + ClassDefNV(BCRecData, 1 b); +}; +} // namespace zdc +} // namespace o2 + +#endif diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h index 887e95b479c68..6d3240bd775e1 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h @@ -8,8 +8,8 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef _ZDC_RECEVENT_H_ -#define _ZDC_RECEVENT_H_ +#ifndef _ZDC_RECEVENT_H +#define _ZDC_RECEVENT_H #include "CommonDataFormat/InteractionRecord.h" #include "MathUtils/Cartesian.h" @@ -29,7 +29,6 @@ namespace zdc struct RecEvent { o2::InteractionRecord ir; uint32_t flags; /// reconstruction flags - std::map ezdc; /// signal in ZDCs float energy[NChannels] = {O2_ZDC_FLT_INIT}; /// ZDC signal constexpr static float fAmp = 1. / 8.; /// Multiplication factor in conversion from integer constexpr static float fVal = 1. / TSNS; /// Multiplication factor in conversion from integer @@ -38,6 +37,7 @@ struct RecEvent { int ntdc[NTDCChannels] = {0}; // Internal variables + std::map ezdc; /// signal in ZDCs std::array pattern; /// Pattern of TDC uint16_t fired[NTDCChannels] = {0}; /// Position at which the trigger algorithm is fired float inter[NTDCChannels][NTimeBinsPerBC * TSN] = {0}; /// Interpolated samples diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h new file mode 100644 index 0000000000000..908ce5ae490e1 --- /dev/null +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h @@ -0,0 +1,106 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef _ZDC_RECEVENT_AUX_H +#define _ZDC_RECEVENT_AUX_H + +#include "CommonDataFormat/InteractionRecord.h" +#include "MathUtils/Cartesian.h" +#include "ZDCBase/Constants.h" +#include +#include +#include + +/// \file RecEvent.h +/// \brief Class to describe reconstructed ZDC event (single BC with signal in one of detectors) during the reconstruction stage +/// \author cortese@to.infn.it, ruben.shahoyan@cern.ch + +namespace o2 +{ +namespace zdc +{ + +struct RecEventAux { + o2::InteractionRecord ir; + uint32_t flags; /// reconstruction flags + constexpr static float fAmp = 1. / 8.; /// Multiplication factor in conversion from integer + constexpr static float fVal = 1. / TSNS; /// Multiplication factor in conversion from integer + std::map ezdc; /// signal in ZDCs + int16_t tdcVal[NTDCChannels][MaxTDCValues]; /// TdcChannels + int16_t tdcAmp[NTDCChannels][MaxTDCValues]; /// TdcAmplitudes + int ntdc[NTDCChannels] = {0}; /// Number of hits in TDC + std::array pattern; /// Pattern of TDC + uint16_t fired[NTDCChannels] = {0}; /// Position at which the trigger algorithm is fired + float inter[NTDCChannels][NTimeBinsPerBC * TSN] = {0}; /// Interpolated samples + uint32_t ref[NChannels] = {O2_ZDC_REF_INIT}; /// Cache of references + + // Functions + void print() const; + float EZDC(uint8_t ich) + { + std::map::iterator it = ezdc.find(ich); + if (it != ezdc.end()) { + return it->second; + } else { + return -std::numeric_limits::infinity(); + } + } + + float EZNAC() { return EZDC(IdZNAC); } + float EZNA1() { return EZDC(IdZNA1); } + float EZNA2() { return EZDC(IdZNA2); } + float EZNA3() { return EZDC(IdZNA3); } + float EZNA4() { return EZDC(IdZNA4); } + float EZNASum() { return EZDC(IdZNASum); } + + float EZPAC() { return EZDC(IdZPAC); } + float EZPA1() { return EZDC(IdZPA1); } + float EZPA2() { return EZDC(IdZPA2); } + float EZPA3() { return EZDC(IdZPA3); } + float EZPA4() { return EZDC(IdZPA4); } + float EZPASum() { return EZDC(IdZPASum); } + + float EZEM1() { return EZDC(IdZEM1); } + float EZEM2() { return EZDC(IdZEM2); } + + float EZNCC() { return EZDC(IdZNCC); } + float EZNC1() { return EZDC(IdZNC1); } + float EZNC2() { return EZDC(IdZNC2); } + float EZNC3() { return EZDC(IdZNC3); } + float EZNC4() { return EZDC(IdZNC4); } + float EZNCSum() { return EZDC(IdZNCSum); } + + float EZPCC() { return EZDC(IdZPCC); } + float EZPC1() { return EZDC(IdZPC1); } + float EZPC2() { return EZDC(IdZPC2); } + float EZPC3() { return EZDC(IdZPC3); } + float EZPC4() { return EZDC(IdZPC4); } + float EZPCSum() { return EZDC(IdZPCSum); } + ClassDefNV(RecEventAux, 1); +}; + +} // namespace zdc + +/// Defining RecEventAux explicitly as messageable +/// +/// It does not fulfill is_messageable because the underlying ROOT +/// classes of Point2D are note trivially copyable. +namespace framework +{ +template +struct is_messageable; +template <> +struct is_messageable : std::true_type { +}; +} // namespace framework + +} // namespace o2 + +#endif diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/TDCData.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/TDCData.h new file mode 100644 index 0000000000000..bfb617cf09ab2 --- /dev/null +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/TDCData.h @@ -0,0 +1,48 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef _ZDC_TDC_DATA_H +#define _ZDC_TDC_DATA_H + +#include "ZDCBase/Constants.h" +#include +#include + +/// \file TDCData.h +/// \brief Container class to store a TDC hit in a ZDC channel +/// \author pietro.cortese@cern.ch + +namespace o2 +{ +namespace zdc +{ + +struct TDCData { + + int8_t id = IdDummy; // channel ID + int16_t val; // tdc value + int16_t amp; // tdc amplitude + + TDCData() = default; + TDCData(int8_t ida, int16_t vala, int16_t ampa) + { + id = ida; + val = vala; + amp = ampa; + } + + void print() const; + + ClassDefNV(TDCData, 1); +}; +} // namespace zdc +} // namespace o2 + +#endif diff --git a/DataFormats/Detectors/ZDC/src/BCRecData.cxx b/DataFormats/Detectors/ZDC/src/BCRecData.cxx new file mode 100644 index 0000000000000..e47be2b42e573 --- /dev/null +++ b/DataFormats/Detectors/ZDC/src/BCRecData.cxx @@ -0,0 +1,27 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "DataFormatsZDC/BCData.h" +#include "DataFormatsZDC/ChannelData.h" +#include + +using namespace o2::zdc; + +void BCData::print() const +{ + printf("Orbit %9u bc %4u nch %2d pos %d ntdc %2d pos %d\n", ir.orbit, ir.bc, + refe.getEntries(), refe.getFirstEntry(),reft.getEntries(), reft.getFirstEntry()); +} + +gsl::span BCData::getBunchChannelData(const gsl::span tfdata) const +{ + // extract the span of channel data for this bunch from the whole TF data + return ref.getEntries() ? gsl::span(&tfdata[ref.getFirstEntry()], ref.getEntries()) : gsl::span(); +} diff --git a/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h b/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h index bcac26d11c23a..7408376032e37 100644 --- a/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h +++ b/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h @@ -30,6 +30,7 @@ #pragma link C++ class std::vector < o2::zdc::OrbitData> + ; #pragma link C++ class std::vector < o2::zdc::RecEvent> + ; +#pragma link C++ class std::vector < o2::zdc::RecEventAux> + ; #pragma link C++ class std::vector < o2::zdc::OrbitRawData> + ; #pragma link C++ class std::vector < o2::zdc::OrbitRecData> + ; diff --git a/DataFormats/Detectors/ZDC/src/RecEventAux.cxx b/DataFormats/Detectors/ZDC/src/RecEventAux.cxx new file mode 100644 index 0000000000000..7e774ff4ec6fe --- /dev/null +++ b/DataFormats/Detectors/ZDC/src/RecEventAux.cxx @@ -0,0 +1,18 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "DataFormatsZDC/RecEventAux.h" + +using namespace o2::zdc; + +void RecEventAux::print() const +{ + ir.print(); +} diff --git a/DataFormats/Detectors/ZDC/src/TDCData.cxx b/DataFormats/Detectors/ZDC/src/TDCData.cxx new file mode 100644 index 0000000000000..9a51c5eb32efd --- /dev/null +++ b/DataFormats/Detectors/ZDC/src/TDCData.cxx @@ -0,0 +1,18 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "DataFormatsZDC/TDCData.h" + +using namespace o2::zdc; + +void TDCData::print() const +{ + printf("%2d (%s) %d @ %d\n", id, channelName(id), amp, val); +} diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h index 79d638e948b86..b38c031ffcbdd 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h @@ -21,6 +21,7 @@ #include "DataFormatsZDC/ChannelData.h" #include "DataFormatsZDC/OrbitData.h" #include "DataFormatsZDC/RecEvent.h" +#include "DataFormatsZDC/RecEventAux.h" #ifndef ALICEO2_ZDC_DIGI_RECO_H #define ALICEO2_ZDC_DIGI_RECO_H @@ -60,7 +61,7 @@ class DigiReco const ZDCIntegrationParam* getIntegrationParam() { return mIntParam; }; private: - const ModuleConfig* mModuleConfig = nullptr; /// Trigger/readout configuration object + const ModuleConfig* mModuleConfig = nullptr; /// Trigger/readout configuration object int reconstruct(int seq_beg, int seq_end); /// Main method for data reconstruction void processTrigger(int itdc, int ibeg, int iend); /// Replay of trigger algorithm on acquired data void interpolate(int itdc, int ibeg, int iend); /// Interpolation of samples to evaluate signal amplitude and arrival time @@ -78,10 +79,10 @@ class DigiReco const std::vector* mOrbitData; /// Reconstructed data const std::vector* mBCData; /// BC info const std::vector* mChData; /// Payload - std::vector mReco; /// Reconstructed data + std::vector mReco; /// Reconstructed data std::map mOrbit; /// Information about orbit static constexpr int mNSB = TSN * NTimeBinsPerBC; /// Total number of interpolated points per bunch crossing - RecEvent mRec; /// Debug reconstruction event + RecEventAux mRec; /// Debug reconstruction event int mNBC = 0; int16_t tdc_shift[NTDCChannels] = {0}; /// TDC correction (units of 1/96 ns) constexpr static uint16_t mMask[NTimeBinsPerBC] = {0x0001, 0x002, 0x004, 0x008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200, 0x0400, 0x0800}; diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h index 312c949e252e9..e6dc0c6472c89 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h @@ -26,8 +26,8 @@ namespace zdc // parameters of ZDC reconstruction struct ZDCTDCParam { + //std::array tdcShift{} float tdc_shift[NTDCChannels] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Correction of TDC position (ns) - public: void setShift(uint32_t ich, float val); float getShift(uint32_t ich) const; void print(); diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index 567d63ca110e6..c94bbcfc5c1d9 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -13,12 +13,12 @@ #include "ZDCReconstruction/DigiReco.h" #include "ZDCReconstruction/RecoParamZDC.h" -#define O2_ZDC_DIGIRECO_FLT float namespace o2 { namespace zdc { +using O2_ZDC_DIGIRECO_FLT=float; void DigiReco::init() { @@ -326,7 +326,7 @@ int DigiReco::reconstruct(int ibeg, int iend) } } - RecEvent& rec = mReco[ibun]; + auto &rec = mReco[ibun]; for (int itdc = 0; itdc < NTDCChannels; itdc++) { if (rec.fired[itdc] != 0x0) { printf("%d %u.%u TDC %d %x", ibun, rec.ir.orbit, rec.ir.bc, itdc, rec.fired[itdc]); @@ -399,7 +399,6 @@ int DigiReco::reconstruct(int ibeg, int iend) sum += (pbun[ich] - float(ChData[ref].data[is])); } printf("CH %d %s: %f\n", ich, ChannelNames[ich].data(), sum); - rec.energy[ich] = sum; rec.ezdc[ich] = sum; } } From 1acea594c5fce17b09597ef1b7a31e9b9f61a8b3 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Thu, 20 May 2021 17:58:33 +0200 Subject: [PATCH 006/770] Reworking event structure --- DataFormats/Detectors/ZDC/CMakeLists.txt | 7 +- .../ZDC/include/DataFormatsZDC/BCRecData.h | 23 +++--- .../ZDC/include/DataFormatsZDC/RecEvent.h | 79 +++++-------------- .../ZDC/include/DataFormatsZDC/ZDCEnergy.h | 63 +++++++++++++++ .../{TDCData.h => ZDCTDCData.h} | 10 +-- DataFormats/Detectors/ZDC/src/BCRecData.cxx | 16 ++-- .../Detectors/ZDC/src/DataFormatsZDCLinkDef.h | 5 ++ DataFormats/Detectors/ZDC/src/RecEvent.cxx | 4 +- DataFormats/Detectors/ZDC/src/ZDCEnergy.cxx | 18 +++++ .../ZDC/src/{TDCData.cxx => ZDCTDCData.cxx} | 4 +- .../ZDC/base/include/ZDCBase/Constants.h | 22 ++++-- .../include/ZDCReconstruction/DigiReco.h | 4 +- .../ZDCReconstruction/ZDCEnergyParam.h | 40 ++++++++++ Detectors/ZDC/reconstruction/src/DigiReco.cxx | 12 +-- Detectors/ZDC/workflow/CMakeLists.txt | 1 + .../ZDCWorkflow/ZDCRecoWriterDPLSpec.h | 33 ++++++++ .../ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx | 42 ++++++++++ 17 files changed, 279 insertions(+), 104 deletions(-) create mode 100644 DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h rename DataFormats/Detectors/ZDC/include/DataFormatsZDC/{TDCData.h => ZDCTDCData.h} (86%) create mode 100644 DataFormats/Detectors/ZDC/src/ZDCEnergy.cxx rename DataFormats/Detectors/ZDC/src/{TDCData.cxx => ZDCTDCData.cxx} (87%) create mode 100644 Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCEnergyParam.h create mode 100644 Detectors/ZDC/workflow/include/ZDCWorkflow/ZDCRecoWriterDPLSpec.h create mode 100644 Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx diff --git a/DataFormats/Detectors/ZDC/CMakeLists.txt b/DataFormats/Detectors/ZDC/CMakeLists.txt index 936a9edcd2592..396c33f32ce57 100644 --- a/DataFormats/Detectors/ZDC/CMakeLists.txt +++ b/DataFormats/Detectors/ZDC/CMakeLists.txt @@ -9,8 +9,8 @@ # submit itself to any jurisdiction. o2_add_library(DataFormatsZDC - SOURCES src/ChannelData.cxx src/BCData.cxx src/RecEvent.cxx src/RecEventAux.cxx src/RawEventData.cxx - src/OrbitRawData.cxx src/OrbitRecData.cxx src/OrbitData.cxx src/TDCData.cxx + SOURCES src/ChannelData.cxx src/BCData.cxx src/BCRecData.cxx src/RecEvent.cxx src/RecEventAux.cxx src/RawEventData.cxx + src/OrbitRawData.cxx src/OrbitRecData.cxx src/OrbitData.cxx src/ZDCTDCData.cxx src/ZDCEnergy.cxx src/CTF.cxx PUBLIC_LINK_LIBRARIES O2::CommonConstants O2::CommonDataFormat O2::ZDCBase ROOT::MathCore FairRoot::Base @@ -22,5 +22,6 @@ o2_target_root_dictionary(DataFormatsZDC include/DataFormatsZDC/BCData.h include/DataFormatsZDC/ChannelData.h include/DataFormatsZDC/OrbitData.h include/DataFormatsZDC/CTF.h include/DataFormatsZDC/RecEvent.h include/DataFormatsZDC/RecEventAux.h - include/DataFormatsZDC/OrbitRawData.h include/DataFormatsZDC/TDCData.h + include/DataFormatsZDC/OrbitRawData.h include/DataFormatsZDC/ZDCTDCData.h + include/DataFormatsZDC/BCRecData.h include/DataFormatsZDC/ZDCEnergy.h include/DataFormatsZDC/OrbitRecData.h include/DataFormatsZDC/RawEventData.h) diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h index e67f54d7b5444..c964a4fcc4948 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h @@ -29,27 +29,30 @@ class ChannelData; struct BCRecData { - /// we are going to refer to at most 26 channels, so 5 bits for the NChannels and 27 for the reference - o2::dataformats::RangeRefComp<5> refe; - o2::dataformats::RangeRefComp<5> reft; + /// we are going to refer to at most 26 channels, so 5 bits are reserved + o2::dataformats::RangeRefComp<5> refe; // Reference to reconstructed energy + o2::dataformats::RangeRefComp<5> reft; // Reference to reconstructed TDC + o2::dataformats::RangeRefComp<5> refm; // Reference to reconstruction error/information flags o2::InteractionRecord ir; - uint32_t flags; BCRecData() = default; - BCRecData(int firste, int ne, int firstt, int nt, o2::InteractionRecord iRec, uint32_t fl) + BCRecData(int firste, int firstt, int firstm, o2::InteractionRecord iRec) { refe.setFirstEntry(firste); - refe.setEntries(ne); + refe.setEntries(0); reft.setFirstEntry(firstt); - reft.setEntries(nt); + reft.setEntries(0); + refm.setFirstEntry(firstm); + refm.setEntries(0); ir = iRec; - flags = fl; } - gsl::span getBunchChannelData(const gsl::span tfdata) const; + inline void addEnergy(){ + refe.setEntries(refe.getEntries()+1); + } void print() const; - ClassDefNV(BCRecData, 1 b); + ClassDefNV(BCRecData, 1); }; } // namespace zdc } // namespace o2 diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h index 6d3240bd775e1..e3e8d736fed2b 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h @@ -8,14 +8,18 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef _ZDC_RECEVENT_H -#define _ZDC_RECEVENT_H +#ifndef _ZDC_RECEVENT_H_ +#define _ZDC_RECEVENT_H_ #include "CommonDataFormat/InteractionRecord.h" +#include "DataFormatsZDC/BCRecData.h" +#include "DataFormatsZDC/ZDCEnergy.h" +#include "DataFormatsZDC/ZDCTDCData.h" #include "MathUtils/Cartesian.h" #include "ZDCBase/Constants.h" #include #include +#include #include /// \file RecEvent.h @@ -27,64 +31,22 @@ namespace o2 namespace zdc { struct RecEvent { - o2::InteractionRecord ir; - uint32_t flags; /// reconstruction flags - float energy[NChannels] = {O2_ZDC_FLT_INIT}; /// ZDC signal - constexpr static float fAmp = 1. / 8.; /// Multiplication factor in conversion from integer - constexpr static float fVal = 1. / TSNS; /// Multiplication factor in conversion from integer - int16_t tdcVal[NTDCChannels][MaxTDCValues]; /// TdcChannels - int16_t tdcAmp[NTDCChannels][MaxTDCValues]; /// TdcAmplitudes - int ntdc[NTDCChannels] = {0}; - - // Internal variables - std::map ezdc; /// signal in ZDCs - std::array pattern; /// Pattern of TDC - uint16_t fired[NTDCChannels] = {0}; /// Position at which the trigger algorithm is fired - float inter[NTDCChannels][NTimeBinsPerBC * TSN] = {0}; /// Interpolated samples - uint32_t ref[NChannels] = {O2_ZDC_REF_INIT}; /// Cache of references - - // Functions - void print() const; - float EZDC(uint8_t ich) + std::vector mRecBC; + std::vector mEnergy; + std::vector mTDCData; + std::vector mInfo; + // Add new bunch crossing without data + void addBC(o2::InteractionRecord ir) { - std::map::iterator it = ezdc.find(ich); - if (it != ezdc.end()) { - return it->second; - } else { - return -std::numeric_limits::infinity(); - } + //mRecBC.emplace_back(mEnergy.size(), mTDCData.size(), mInfo.size(), ir); + mRecBC.emplace_back(mEnergy.size(), 0, mInfo.size(), ir); } - - float EZNAC() { return EZDC(IdZNAC); } - float EZNA1() { return EZDC(IdZNA1); } - float EZNA2() { return EZDC(IdZNA2); } - float EZNA3() { return EZDC(IdZNA3); } - float EZNA4() { return EZDC(IdZNA4); } - float EZNASum() { return EZDC(IdZNASum); } - - float EZPAC() { return EZDC(IdZPAC); } - float EZPA1() { return EZDC(IdZPA1); } - float EZPA2() { return EZDC(IdZPA2); } - float EZPA3() { return EZDC(IdZPA3); } - float EZPA4() { return EZDC(IdZPA4); } - float EZPASum() { return EZDC(IdZPASum); } - - float EZEM1() { return EZDC(IdZEM1); } - float EZEM2() { return EZDC(IdZEM2); } - - float EZNCC() { return EZDC(IdZNCC); } - float EZNC1() { return EZDC(IdZNC1); } - float EZNC2() { return EZDC(IdZNC2); } - float EZNC3() { return EZDC(IdZNC3); } - float EZNC4() { return EZDC(IdZNC4); } - float EZNCSum() { return EZDC(IdZNCSum); } - - float EZPCC() { return EZDC(IdZPCC); } - float EZPC1() { return EZDC(IdZPC1); } - float EZPC2() { return EZDC(IdZPC2); } - float EZPC3() { return EZDC(IdZPC3); } - float EZPC4() { return EZDC(IdZPC4); } - float EZPCSum() { return EZDC(IdZPCSum); } + void addEnergy(uint8_t ch, float energy) + { + mEnergy.emplace_back(ch, energy); + mRecBC.back().addEnergy(); + } + void print() const; ClassDefNV(RecEvent, 1); }; @@ -102,7 +64,6 @@ template <> struct is_messageable : std::true_type { }; } // namespace framework - } // namespace o2 #endif diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h new file mode 100644 index 0000000000000..3e4d29546450d --- /dev/null +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h @@ -0,0 +1,63 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef _ZDC_TDC_DATA_H +#define _ZDC_TDC_DATA_H + +#include "ZDCBase/Constants.h" +#include +#include +#include + +/// \file ZDCEnergy.h +/// \brief Container class to store energy released in a ZDC +/// \author pietro.cortese@cern.ch + +namespace o2 +{ +namespace zdc +{ + +struct ZDCEnergy { + + uint32_t value = 0; // Signal id and energy released in calorimeter + + ZDCEnergy() = default; + ZDCEnergy(uint8_t ch, float energy) + { + float escaled=(energy+EnergyOffset)/EnergyUnit; + value=0; + if(escaled>0){ + if(escaled>EnergyMask){ + value=EnergyMask; + }else{ + value=std::nearbyint(escaled); + } + } + if(ch>=NChannels){ + ch=0x1f; + } + value=(value&EnergyMask)|(ch<<27); + } + float energy(){ + return (float(value&EnergyMask)-EnergyOffset)*EnergyUnit; + } + uint8_t ch(){ + return (value&EnergyChMask)>>27; + } + + void print() const; + + ClassDefNV(ZDCEnergy, 1); +}; +} // namespace zdc +} // namespace o2 + +#endif diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/TDCData.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCTDCData.h similarity index 86% rename from DataFormats/Detectors/ZDC/include/DataFormatsZDC/TDCData.h rename to DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCTDCData.h index bfb617cf09ab2..ca5c08e576f60 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/TDCData.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCTDCData.h @@ -15,7 +15,7 @@ #include #include -/// \file TDCData.h +/// \file ZDCTDCData.h /// \brief Container class to store a TDC hit in a ZDC channel /// \author pietro.cortese@cern.ch @@ -24,14 +24,14 @@ namespace o2 namespace zdc { -struct TDCData { +struct ZDCTDCData { int8_t id = IdDummy; // channel ID int16_t val; // tdc value int16_t amp; // tdc amplitude - TDCData() = default; - TDCData(int8_t ida, int16_t vala, int16_t ampa) + ZDCTDCData() = default; + ZDCTDCData(int8_t ida, int16_t vala, int16_t ampa) { id = ida; val = vala; @@ -40,7 +40,7 @@ struct TDCData { void print() const; - ClassDefNV(TDCData, 1); + ClassDefNV(ZDCTDCData, 1); }; } // namespace zdc } // namespace o2 diff --git a/DataFormats/Detectors/ZDC/src/BCRecData.cxx b/DataFormats/Detectors/ZDC/src/BCRecData.cxx index e47be2b42e573..88fdfb6989119 100644 --- a/DataFormats/Detectors/ZDC/src/BCRecData.cxx +++ b/DataFormats/Detectors/ZDC/src/BCRecData.cxx @@ -8,20 +8,16 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#include "DataFormatsZDC/BCData.h" +#include "DataFormatsZDC/BCRecData.h" #include "DataFormatsZDC/ChannelData.h" #include using namespace o2::zdc; -void BCData::print() const +void BCRecData::print() const { - printf("Orbit %9u bc %4u nch %2d pos %d ntdc %2d pos %d\n", ir.orbit, ir.bc, - refe.getEntries(), refe.getFirstEntry(),reft.getEntries(), reft.getFirstEntry()); -} - -gsl::span BCData::getBunchChannelData(const gsl::span tfdata) const -{ - // extract the span of channel data for this bunch from the whole TF data - return ref.getEntries() ? gsl::span(&tfdata[ref.getFirstEntry()], ref.getEntries()) : gsl::span(); + printf("Orbit %9u bc %4u nch %2d pos %d ntdc %2d pos %d nmsg %2d pos %\n", ir.orbit, ir.bc, + refe.getEntries(), refe.getFirstEntry(), + reft.getEntries(), reft.getFirstEntry(), + refm.getEntries(), refm.getFirstEntry()); } diff --git a/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h b/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h index 7408376032e37..ccf2458f1ec5a 100644 --- a/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h +++ b/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h @@ -25,9 +25,14 @@ #pragma link C++ class o2::zdc::BCData + ; #pragma link C++ class o2::zdc::OrbitData + ; #pragma link C++ class o2::zdc::RecEvent + ; +#pragma link C++ class o2::zdc::ZDCEnergy + ; +#pragma link C++ class o2::zdc::ZDCTDCData + ; #pragma link C++ class std::vector < o2::zdc::ChannelData> + ; #pragma link C++ class std::vector < o2::zdc::BCData> + ; #pragma link C++ class std::vector < o2::zdc::OrbitData> + ; +#pragma link C++ class std::vector < o2::zdc::BCRecData> + ; +#pragma link C++ class std::vector < o2::zdc::ZDCEnergy> + ; +#pragma link C++ class std::vector < o2::zdc::ZDCTDCData> + ; #pragma link C++ class std::vector < o2::zdc::RecEvent> + ; #pragma link C++ class std::vector < o2::zdc::RecEventAux> + ; diff --git a/DataFormats/Detectors/ZDC/src/RecEvent.cxx b/DataFormats/Detectors/ZDC/src/RecEvent.cxx index 513b117773694..8b24d0033279a 100644 --- a/DataFormats/Detectors/ZDC/src/RecEvent.cxx +++ b/DataFormats/Detectors/ZDC/src/RecEvent.cxx @@ -14,5 +14,7 @@ using namespace o2::zdc; void RecEvent::print() const { - ir.print(); + for (auto it : mRecBC){ + it.ir.print(); + } } diff --git a/DataFormats/Detectors/ZDC/src/ZDCEnergy.cxx b/DataFormats/Detectors/ZDC/src/ZDCEnergy.cxx new file mode 100644 index 0000000000000..d8a3914749516 --- /dev/null +++ b/DataFormats/Detectors/ZDC/src/ZDCEnergy.cxx @@ -0,0 +1,18 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "DataFormatsZDC/ZDCEnergy.h" + +using namespace o2::zdc; + +void ZDCEnergy::print() const +{ + //printf("%2d (%s) %d @ %d\n", id, channelName(id), amp, val); +} diff --git a/DataFormats/Detectors/ZDC/src/TDCData.cxx b/DataFormats/Detectors/ZDC/src/ZDCTDCData.cxx similarity index 87% rename from DataFormats/Detectors/ZDC/src/TDCData.cxx rename to DataFormats/Detectors/ZDC/src/ZDCTDCData.cxx index 9a51c5eb32efd..b0d845d19aa51 100644 --- a/DataFormats/Detectors/ZDC/src/TDCData.cxx +++ b/DataFormats/Detectors/ZDC/src/ZDCTDCData.cxx @@ -8,11 +8,11 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#include "DataFormatsZDC/TDCData.h" +#include "DataFormatsZDC/ZDCTDCData.h" using namespace o2::zdc; -void TDCData::print() const +void o2::zdc::ZDCTDCData::print() const { printf("%2d (%s) %d @ %d\n", id, channelName(id), amp, val); } diff --git a/Detectors/ZDC/base/include/ZDCBase/Constants.h b/Detectors/ZDC/base/include/ZDCBase/Constants.h index eebbec2e3bf6a..2ae89763753eb 100644 --- a/Detectors/ZDC/base/include/ZDCBase/Constants.h +++ b/Detectors/ZDC/base/include/ZDCBase/Constants.h @@ -72,12 +72,20 @@ constexpr int NWPerBc = 3; constexpr int MaxTriggerChannels = NChannels; constexpr int ADCMin = -2048, ADCMax = 2047, ADCRange = 4096; // 12 bit ADC +// Encoding of ZDC energy into an uint32_t value +// Most significant 5 bits are for channel id, least significant 27 bits are for energy +// with offset and unit as specified below +constexpr float EnergyOffset = 10000; // Energy offset (GeV) +constexpr float EnergyUnit = 0.01; // Energy unit (GeV) +constexpr uint32_t EnergyMask = 0x07ffffff; +constexpr uint32_t EnergyChMask = 0xf8000000; + constexpr int MaxTDCValues = 5; // max number of TDC values to store in reconstructed event constexpr int NTDCChannels = 10; // max number of TDC values to store in reconstructed event // Parameters of interpolating function -constexpr int TSL = 6; // number of zeros on the right (and on the left) of central peak -constexpr int TSN = 200; // Number of interpolated points between each pair = TSN-1 -constexpr int TSNS = 96; // Number of interpolated points per ns +constexpr int TSL = 6; // number of zeros on the right (and on the left) of central peak +constexpr int TSN = 200; // Number of interpolated points between each pair = TSN-1 +constexpr int TSNS = 96; // Number of interpolated points per ns constexpr int NTS = 2 * TSL * TSN + 1; //Tapered sinc function array size enum TDCChannelID { TDCZNAC, @@ -196,12 +204,12 @@ constexpr int DbgFull = 3; const std::string CCDBPathConfigSim = "ZDC/Config/Sim"; const std::string CCDBPathConfigModule = "ZDC/Config/Module"; -const std::string CCDBPathConfigReco= "ZDC/Calib/RecoParam"; -const std::string CCDBPathConfigIntegration= "ZDC/Calib/IntegrationParam"; -const std::string CCDBPathTDCCalib= "ZDC/Calib/TDCCalib"; +const std::string CCDBPathConfigReco = "ZDC/Calib/RecoParam"; +const std::string CCDBPathConfigIntegration = "ZDC/Calib/IntegrationParam"; +const std::string CCDBPathTDCCalib = "ZDC/Calib/TDCCalib"; // Placeholders -constexpr int DummyIntRange = -NTimeBinsPerBC -1; +constexpr int DummyIntRange = -NTimeBinsPerBC - 1; constexpr std::string_view DummyName = "Dumm"; constexpr std::string_view VoidName = " NA "; diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h index b38c031ffcbdd..9efdaac0880ba 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h @@ -60,12 +60,14 @@ class DigiReco void setIntegrationParam(const ZDCIntegrationParam* param) { mIntParam = param; }; const ZDCIntegrationParam* getIntegrationParam() { return mIntParam; }; + const std::vector& getReco() { return mReco; } + private: const ModuleConfig* mModuleConfig = nullptr; /// Trigger/readout configuration object int reconstruct(int seq_beg, int seq_end); /// Main method for data reconstruction void processTrigger(int itdc, int ibeg, int iend); /// Replay of trigger algorithm on acquired data void interpolate(int itdc, int ibeg, int iend); /// Interpolation of samples to evaluate signal amplitude and arrival time - void assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float amp); // Set reconstructed TDC values + void assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float amp); /// Set reconstructed TDC values bool mIsContinuous = true; /// continuous (self-triggered) or externally-triggered readout int mNBCAHead = 0; /// when storing triggered BC, store also mNBCAHead BCs const ZDCTDCParam* mTDCParam = nullptr; /// TDC calibration object diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCEnergyParam.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCEnergyParam.h new file mode 100644 index 0000000000000..1160a75c46ff3 --- /dev/null +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCEnergyParam.h @@ -0,0 +1,40 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_ZDC_ENERGYPARAM_H +#define O2_ZDC_ENERGYPARAM_H + +#include "ZDCBase/Constants.h" +#include +#include + +/// \file ZDCEnergyParam.h +/// \brief Parameters to correct TDCs +/// \author P. Cortese + +namespace o2 +{ +namespace zdc +{ +// parameters of ZDC reconstruction + +struct ZDCEnergyParam { + //std::array tdcShift{} + float tdc_shift[NTDCChannels] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Correction of TDC position (ns) + void setShift(uint32_t ich, float val); + float getShift(uint32_t ich) const; + void print(); + + ClassDefNV(ZDCEnergyParam, 1); +}; +} // namespace zdc +} // namespace o2 + +#endif diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index c94bbcfc5c1d9..25c7672453f69 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -90,7 +90,7 @@ void DigiReco::init() if (!mTDCParam) { LOG(FATAL) << "TDC " << itdc << " missing configuration object and no manual override"; } else { - fval = mTDCParam->getShift(itdc) / RecEvent::fVal; + fval = mTDCParam->getShift(itdc) / RecEventAux::fVal; } } auto val = std::nearbyint(fval); @@ -101,12 +101,12 @@ void DigiReco::init() LOG(FATAL) << "Shift for TDC " << itdc << " " << val << " is out of range"; } tdc_shift[itdc] = val; - LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " shift= " << tdc_shift[itdc] << " i.s. = " << val*RecEvent::fVal << " ns"; + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " shift= " << tdc_shift[itdc] << " i.s. = " << val*RecEventAux::fVal << " ns"; } // TDC search zone // TODO: override with configuration object for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { - LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << ropt.tdc_search[itdc] << " i.s. = " << ropt.tdc_search[itdc]*RecEvent::fVal << " ns"; + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << ropt.tdc_search[itdc] << " i.s. = " << ropt.tdc_search[itdc]*RecEventAux::fVal << " ns"; } // Fill maps channel maps for integration @@ -768,13 +768,13 @@ void DigiReco::assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float int& ihit = mReco[ibun].ntdc[itdc]; if (ihit < MaxTDCValues) { mReco[ibun].tdcVal[itdc][ihit] = tdc_cor; - mReco[ibun].tdcAmp[itdc][ihit] = std::nearbyint(amp/RecEvent::fAmp); + mReco[ibun].tdcAmp[itdc][ihit] = std::nearbyint(amp/RecEventAux::fAmp); ihit++; LOG(INFO) << mReco[ibun].ir.orbit << "." << mReco[ibun].ir.bc << " " - << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor*RecEvent::fVal << " amp=" << amp*RecEvent::fAmp; + << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor*RecEventAux::fVal << " amp=" << amp*RecEventAux::fAmp; } else { LOG(ERROR) << mReco[ibun].ir.orbit << "." << mReco[ibun].ir.bc << " " - << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor*RecEvent::fVal << " amp=" << amp*RecEvent::fAmp << " OVERFLOW"; + << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor*RecEventAux::fVal << " amp=" << amp*RecEventAux::fAmp << " OVERFLOW"; } } diff --git a/Detectors/ZDC/workflow/CMakeLists.txt b/Detectors/ZDC/workflow/CMakeLists.txt index 63a8972c5d79d..3f929f6df61c7 100644 --- a/Detectors/ZDC/workflow/CMakeLists.txt +++ b/Detectors/ZDC/workflow/CMakeLists.txt @@ -14,6 +14,7 @@ o2_add_library(ZDCWorkflow src/EntropyDecoderSpec.cxx src/ZDCDataReaderDPLSpec.cxx src/ZDCDigitWriterDPLSpec.cxx + src/ZDCRecoWriterDPLSpec.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DataFormatsZDC O2::ZDCRaw diff --git a/Detectors/ZDC/workflow/include/ZDCWorkflow/ZDCRecoWriterDPLSpec.h b/Detectors/ZDC/workflow/include/ZDCWorkflow/ZDCRecoWriterDPLSpec.h new file mode 100644 index 0000000000000..19f489653230d --- /dev/null +++ b/Detectors/ZDC/workflow/include/ZDCWorkflow/ZDCRecoWriterDPLSpec.h @@ -0,0 +1,33 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file ZDCRecoWriterDPLSpec.h + +#ifndef O2_ZDCRECOTWRITERDPLSPEC_H +#define O2_ZDCRECOTWRITERDPLSPEC_H + +#include "Framework/DataProcessorSpec.h" +#include "SimulationDataFormat/MCTruthContainer.h" +#include "DataFormatsZDC/MCLabel.h" + +using namespace o2::framework; + +namespace o2 +{ +namespace zdc +{ + +/// create a processor spec +framework::DataProcessorSpec getZDCRecoWriterDPLSpec(); + +} // namespace zdc +} // namespace o2 + +#endif /* O2_ZDCRECOTWRITERDPLSPEC_H */ diff --git a/Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx b/Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx new file mode 100644 index 0000000000000..8607fd46867bc --- /dev/null +++ b/Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx @@ -0,0 +1,42 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file FT0DigitWriterSpec.cxx + +#include + +#include "DPLUtils/MakeRootTreeWriterSpec.h" +#include "DataFormatsZDC/BCRecData.h" + +#include "ZDCWorkflow/ZDCRecoWriterDPLSpec.h" +using namespace o2::framework; + +namespace o2 +{ +namespace zdc +{ + +template +using BranchDefinition = MakeRootTreeWriterSpec::BranchDefinition; +DataProcessorSpec getZDCRecoWriterDPLSpec(bool mctruth, bool simVersion) +{ + std::string writerName = "ZDCRecoWriter"; + std::string fnameDef = "zdcreco.root"; + + using InputSpec = framework::InputSpec; + using MakeRootTreeWriterSpec = framework::MakeRootTreeWriterSpec; + return MakeRootTreeWriterSpec(writerName.data(), + fnameDef.data(), + "o2rec", + BranchDefinition>{InputSpec{"RecBCinput", "ZDC", "RECBC"}, "ZDCRecBC"})(); +} + +} // namespace zdc +} // namespace o2 From db529f8197e40818d350f151a87c93a72e761cad Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 21 May 2021 07:44:44 +0200 Subject: [PATCH 007/770] Corrected compilation bug --- DataFormats/Detectors/ZDC/CMakeLists.txt | 6 +++--- .../Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h | 4 ++-- .../Detectors/ZDC/include/DataFormatsZDC/ZDCTDCData.h | 8 ++++---- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/DataFormats/Detectors/ZDC/CMakeLists.txt b/DataFormats/Detectors/ZDC/CMakeLists.txt index 396c33f32ce57..00528c3a43556 100644 --- a/DataFormats/Detectors/ZDC/CMakeLists.txt +++ b/DataFormats/Detectors/ZDC/CMakeLists.txt @@ -10,7 +10,7 @@ o2_add_library(DataFormatsZDC SOURCES src/ChannelData.cxx src/BCData.cxx src/BCRecData.cxx src/RecEvent.cxx src/RecEventAux.cxx src/RawEventData.cxx - src/OrbitRawData.cxx src/OrbitRecData.cxx src/OrbitData.cxx src/ZDCTDCData.cxx src/ZDCEnergy.cxx + src/OrbitRawData.cxx src/OrbitRecData.cxx src/OrbitData.cxx src/ZDCEnergy.cxx src/ZDCTDCData.cxx src/CTF.cxx PUBLIC_LINK_LIBRARIES O2::CommonConstants O2::CommonDataFormat O2::ZDCBase ROOT::MathCore FairRoot::Base @@ -22,6 +22,6 @@ o2_target_root_dictionary(DataFormatsZDC include/DataFormatsZDC/BCData.h include/DataFormatsZDC/ChannelData.h include/DataFormatsZDC/OrbitData.h include/DataFormatsZDC/CTF.h include/DataFormatsZDC/RecEvent.h include/DataFormatsZDC/RecEventAux.h - include/DataFormatsZDC/OrbitRawData.h include/DataFormatsZDC/ZDCTDCData.h - include/DataFormatsZDC/BCRecData.h include/DataFormatsZDC/ZDCEnergy.h + include/DataFormatsZDC/OrbitRawData.h include/DataFormatsZDC/BCRecData.h + include/DataFormatsZDC/ZDCEnergy.h include/DataFormatsZDC/ZDCTDCData.h include/DataFormatsZDC/OrbitRecData.h include/DataFormatsZDC/RawEventData.h) diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h index 3e4d29546450d..8501c964c00d5 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h @@ -8,8 +8,8 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef _ZDC_TDC_DATA_H -#define _ZDC_TDC_DATA_H +#ifndef ZDC_ENERGY_H +#define ZDC_ENERGY_H #include "ZDCBase/Constants.h" #include diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCTDCData.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCTDCData.h index ca5c08e576f60..d5e53f3349599 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCTDCData.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCTDCData.h @@ -8,8 +8,8 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef _ZDC_TDC_DATA_H -#define _ZDC_TDC_DATA_H +#ifndef ZDC_TDC_DATA_H +#define ZDC_TDC_DATA_H #include "ZDCBase/Constants.h" #include @@ -27,8 +27,8 @@ namespace zdc struct ZDCTDCData { int8_t id = IdDummy; // channel ID - int16_t val; // tdc value - int16_t amp; // tdc amplitude + int16_t val = 0; // tdc value + int16_t amp = 0; // tdc amplitude ZDCTDCData() = default; ZDCTDCData(int8_t ida, int16_t vala, int16_t ampa) From 9d1dd5293bad73b521c6d5db24e8f7273cc47776 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 21 May 2021 09:48:28 +0200 Subject: [PATCH 008/770] New ZDC rec event format --- .../ZDC/include/DataFormatsZDC/BCRecData.h | 38 +++++++++++++----- .../ZDC/include/DataFormatsZDC/RecEvent.h | 40 ++++++++++++++----- .../ZDC/include/DataFormatsZDC/RecEventAux.h | 2 + .../ZDC/include/DataFormatsZDC/ZDCEnergy.h | 30 +++++++------- DataFormats/Detectors/ZDC/src/BCRecData.cxx | 8 ++-- .../Detectors/ZDC/src/DataFormatsZDCLinkDef.h | 1 + DataFormats/Detectors/ZDC/src/RecEvent.cxx | 4 +- Detectors/ZDC/reconstruction/src/DigiReco.cxx | 31 +++++++------- 8 files changed, 99 insertions(+), 55 deletions(-) diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h index c964a4fcc4948..2759220849391 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h @@ -17,8 +17,8 @@ #include #include -/// \file BCData.h -/// \brief Class to describe reconstructed data and refer to channel data +/// \file BCRecData.h +/// \brief Class to refer to the reconstructed information /// \author ruben.shahoyan@cern.ch, pietro.cortese@cern.ch namespace o2 @@ -27,28 +27,44 @@ namespace zdc { class ChannelData; - struct BCRecData { - /// we are going to refer to at most 26 channels, so 5 bits are reserved + o2::InteractionRecord ir; + uint32_t channels = 0; // Pattern of channels acquired + uint32_t triggers = 0; // Pattern of channels with autotrigger bit o2::dataformats::RangeRefComp<5> refe; // Reference to reconstructed energy o2::dataformats::RangeRefComp<5> reft; // Reference to reconstructed TDC - o2::dataformats::RangeRefComp<5> refm; // Reference to reconstruction error/information flags - o2::InteractionRecord ir; + o2::dataformats::RangeRefComp<5> refi; // Reference to reconstruction error/information flags BCRecData() = default; - BCRecData(int firste, int firstt, int firstm, o2::InteractionRecord iRec) + + // Insert interaction record for new event (will set later the number of entries) + BCRecData(int firste, int firstt, int firsti, o2::InteractionRecord iRec) { refe.setFirstEntry(firste); refe.setEntries(0); reft.setFirstEntry(firstt); reft.setEntries(0); - refm.setFirstEntry(firstm); - refm.setEntries(0); + refi.setFirstEntry(firsti); + refi.setEntries(0); ir = iRec; } - inline void addEnergy(){ - refe.setEntries(refe.getEntries()+1); + // Update counter of energy entries + inline void addEnergy() + { + refe.setEntries(refe.getEntries() + 1); + } + + // Update counter of TDC entries + inline void addTDC() + { + reft.setEntries(reft.getEntries() + 1); + } + + // Update counter of Info entries + inline void addInfo() + { + refi.setEntries(refi.getEntries() + 1); } void print() const; diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h index e3e8d736fed2b..a7f474a2c2b04 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h @@ -24,28 +24,50 @@ /// \file RecEvent.h /// \brief Class to describe reconstructed ZDC event (single BC with signal in one of detectors) -/// \author cortese@to.infn.it, ruben.shahoyan@cern.ch +/// \author pietro.cortese@cern.ch, ruben.shahoyan@cern.ch namespace o2 { namespace zdc { struct RecEvent { - std::vector mRecBC; - std::vector mEnergy; - std::vector mTDCData; - std::vector mInfo; + std::vector mRecBC; /// Interaction record and references to data + std::vector mEnergy; /// ZDC energy + std::vector mTDCData; /// ZDC TDC + std::vector mInfo; /// Event quality information // Add new bunch crossing without data - void addBC(o2::InteractionRecord ir) + inline void addBC(o2::InteractionRecord ir) { - //mRecBC.emplace_back(mEnergy.size(), mTDCData.size(), mInfo.size(), ir); - mRecBC.emplace_back(mEnergy.size(), 0, mInfo.size(), ir); + mRecBC.emplace_back(mEnergy.size(), mTDCData.size(), mInfo.size(), ir); } - void addEnergy(uint8_t ch, float energy) + inline void addBC(o2::InteractionRecord ir, uint32_t channels, uint32_t triggers) + { + mRecBC.emplace_back(mEnergy.size(), mTDCData.size(), mInfo.size(), ir); + mRecBC.back().channels = channels; + mRecBC.back().triggers = triggers; + } + // Add energy + inline void addEnergy(uint8_t ch, float energy) { mEnergy.emplace_back(ch, energy); mRecBC.back().addEnergy(); } + // Add TDC + inline void addTDC(uint8_t ch, int16_t val, int16_t amp) + { + mTDCData.emplace_back(ch, val, amp); + mRecBC.back().addTDC(); + } + // Add event information + inline void addInfo(uint8_t ch, uint16_t info) + { + if (ch >= NChannels) { + ch = 0x1f; + } + info = (info & 0x07ff) || ch << 11; + mInfo.emplace_back(info); + mRecBC.back().addInfo(); + } void print() const; ClassDefNV(RecEvent, 1); }; diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h index 908ce5ae490e1..53f9186b029b7 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h @@ -29,6 +29,8 @@ namespace zdc struct RecEventAux { o2::InteractionRecord ir; + uint32_t channels = 0; /// pattern of channels acquired + uint32_t triggers = 0; /// pattern of channels with autotrigger bit uint32_t flags; /// reconstruction flags constexpr static float fAmp = 1. / 8.; /// Multiplication factor in conversion from integer constexpr static float fVal = 1. / TSNS; /// Multiplication factor in conversion from integer diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h index 8501c964c00d5..67876d4d48806 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h @@ -32,25 +32,27 @@ struct ZDCEnergy { ZDCEnergy() = default; ZDCEnergy(uint8_t ch, float energy) { - float escaled=(energy+EnergyOffset)/EnergyUnit; - value=0; - if(escaled>0){ - if(escaled>EnergyMask){ - value=EnergyMask; - }else{ - value=std::nearbyint(escaled); + float escaled = (energy + EnergyOffset) / EnergyUnit; + value = 0; + if (escaled > 0) { + if (escaled > EnergyMask) { + value = EnergyMask; + } else { + value = std::nearbyint(escaled); } } - if(ch>=NChannels){ - ch=0x1f; + if (ch >= NChannels) { + ch = 0x1f; } - value=(value&EnergyMask)|(ch<<27); + value = (value & EnergyMask) | (ch << 27); } - float energy(){ - return (float(value&EnergyMask)-EnergyOffset)*EnergyUnit; + float energy() + { + return (float(value & EnergyMask) - EnergyOffset) * EnergyUnit; } - uint8_t ch(){ - return (value&EnergyChMask)>>27; + uint8_t ch() + { + return (value & EnergyChMask) >> 27; } void print() const; diff --git a/DataFormats/Detectors/ZDC/src/BCRecData.cxx b/DataFormats/Detectors/ZDC/src/BCRecData.cxx index 88fdfb6989119..577b01ccb619c 100644 --- a/DataFormats/Detectors/ZDC/src/BCRecData.cxx +++ b/DataFormats/Detectors/ZDC/src/BCRecData.cxx @@ -16,8 +16,8 @@ using namespace o2::zdc; void BCRecData::print() const { - printf("Orbit %9u bc %4u nch %2d pos %d ntdc %2d pos %d nmsg %2d pos %\n", ir.orbit, ir.bc, - refe.getEntries(), refe.getFirstEntry(), - reft.getEntries(), reft.getFirstEntry(), - refm.getEntries(), refm.getFirstEntry()); + printf("Orbit %9u bc %4u nch %2d pos %d ntdc %2d pos %d nmsg %2d pos %d\n", ir.orbit, ir.bc, + refe.getEntries(), refe.getFirstEntry(), + reft.getEntries(), reft.getFirstEntry(), + refi.getEntries(), refi.getFirstEntry()); } diff --git a/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h b/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h index ccf2458f1ec5a..4aca764157aec 100644 --- a/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h +++ b/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h @@ -25,6 +25,7 @@ #pragma link C++ class o2::zdc::BCData + ; #pragma link C++ class o2::zdc::OrbitData + ; #pragma link C++ class o2::zdc::RecEvent + ; +#pragma link C++ class o2::zdc::RecEventAux + ; #pragma link C++ class o2::zdc::ZDCEnergy + ; #pragma link C++ class o2::zdc::ZDCTDCData + ; #pragma link C++ class std::vector < o2::zdc::ChannelData> + ; diff --git a/DataFormats/Detectors/ZDC/src/RecEvent.cxx b/DataFormats/Detectors/ZDC/src/RecEvent.cxx index 8b24d0033279a..762f0a83f9dca 100644 --- a/DataFormats/Detectors/ZDC/src/RecEvent.cxx +++ b/DataFormats/Detectors/ZDC/src/RecEvent.cxx @@ -14,7 +14,7 @@ using namespace o2::zdc; void RecEvent::print() const { - for (auto it : mRecBC){ - it.ir.print(); + for (auto bcdata : mRecBC) { + bcdata.ir.print(); } } diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index 25c7672453f69..2ad069bd4daae 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -13,12 +13,11 @@ #include "ZDCReconstruction/DigiReco.h" #include "ZDCReconstruction/RecoParamZDC.h" - namespace o2 { namespace zdc { -using O2_ZDC_DIGIRECO_FLT=float; +using O2_ZDC_DIGIRECO_FLT = float; void DigiReco::init() { @@ -101,12 +100,12 @@ void DigiReco::init() LOG(FATAL) << "Shift for TDC " << itdc << " " << val << " is out of range"; } tdc_shift[itdc] = val; - LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " shift= " << tdc_shift[itdc] << " i.s. = " << val*RecEventAux::fVal << " ns"; + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " shift= " << tdc_shift[itdc] << " i.s. = " << val * RecEventAux::fVal << " ns"; } // TDC search zone // TODO: override with configuration object for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { - LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << ropt.tdc_search[itdc] << " i.s. = " << ropt.tdc_search[itdc]*RecEventAux::fVal << " ns"; + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << ropt.tdc_search[itdc] << " i.s. = " << ropt.tdc_search[itdc] * RecEventAux::fVal << " ns"; } // Fill maps channel maps for integration @@ -178,8 +177,8 @@ int DigiReco::process(const std::vector* orbitdata, const st auto& bcr = mReco[ibc]; for (int itdc = 0; itdc < NTDCChannels; itdc++) { for (int i = 0; i < MaxTDCValues; i++) { - bcr.tdcVal[itdc][i] = kMinShort; - bcr.tdcAmp[itdc][i] = kMinShort; + bcr.tdcVal[itdc][i] = kMinShort; + bcr.tdcAmp[itdc][i] = kMinShort; } } auto& bcd = BCData[ibc]; @@ -205,9 +204,11 @@ int DigiReco::process(const std::vector* orbitdata, const st // } // } - // Assign interaction record + // Assign interaction record and event information for (int ibc = 0; ibc < mNBC; ibc++) { mReco[ibc].ir = BCData[ibc].ir; + mReco[ibc].channels = BCData[ibc].channels; + mReco[ibc].triggers = BCData[ibc].triggers; } // Find consecutive bunch crossings and perform interpolation @@ -326,7 +327,7 @@ int DigiReco::reconstruct(int ibeg, int iend) } } - auto &rec = mReco[ibun]; + auto& rec = mReco[ibun]; for (int itdc = 0; itdc < NTDCChannels; itdc++) { if (rec.fired[itdc] != 0x0) { printf("%d %u.%u TDC %d %x", ibun, rec.ir.orbit, rec.ir.bc, itdc, rec.fired[itdc]); @@ -404,10 +405,10 @@ int DigiReco::reconstruct(int ibeg, int iend) } } // TODO: energy calibration - if(mTreeDbg){ - mRec = rec; - mTDbg->Fill(); - } + if (mTreeDbg) { + mRec = rec; + mTDbg->Fill(); + } } // Loop on bunches } @@ -768,13 +769,13 @@ void DigiReco::assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float int& ihit = mReco[ibun].ntdc[itdc]; if (ihit < MaxTDCValues) { mReco[ibun].tdcVal[itdc][ihit] = tdc_cor; - mReco[ibun].tdcAmp[itdc][ihit] = std::nearbyint(amp/RecEventAux::fAmp); + mReco[ibun].tdcAmp[itdc][ihit] = std::nearbyint(amp / RecEventAux::fAmp); ihit++; LOG(INFO) << mReco[ibun].ir.orbit << "." << mReco[ibun].ir.bc << " " - << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor*RecEventAux::fVal << " amp=" << amp*RecEventAux::fAmp; + << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor * RecEventAux::fVal << " amp=" << amp * RecEventAux::fAmp; } else { LOG(ERROR) << mReco[ibun].ir.orbit << "." << mReco[ibun].ir.bc << " " - << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor*RecEventAux::fVal << " amp=" << amp*RecEventAux::fAmp << " OVERFLOW"; + << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor * RecEventAux::fVal << " amp=" << amp * RecEventAux::fAmp << " OVERFLOW"; } } From da6447bc45d1e571c4b93476679cd3b84f341cc2 Mon Sep 17 00:00:00 2001 From: ALICE Action Bot Date: Fri, 21 May 2021 07:51:06 +0000 Subject: [PATCH 009/770] Please consider the following formatting changes --- Detectors/ZDC/macro/CreateIntegrationParam.C | 2 +- .../include/ZDCReconstruction/ZDCEnergyParam.h | 2 +- .../include/ZDCReconstruction/ZDCTDCParam.h | 2 +- Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx | 9 +++++---- Detectors/ZDC/reconstruction/src/ZDCIntegrationParam.cxx | 2 +- 5 files changed, 9 insertions(+), 8 deletions(-) diff --git a/Detectors/ZDC/macro/CreateIntegrationParam.C b/Detectors/ZDC/macro/CreateIntegrationParam.C index df8ba52bfc70d..91bc4cfedef03 100644 --- a/Detectors/ZDC/macro/CreateIntegrationParam.C +++ b/Detectors/ZDC/macro/CreateIntegrationParam.C @@ -24,7 +24,7 @@ using namespace o2::zdc; using namespace std; void CreateIntegrationParam(long tmin = 0, long tmax = -1, - std::string ccdbHost = "http://ccdb-test.cern.ch:8080") + std::string ccdbHost = "http://ccdb-test.cern.ch:8080") { ZDCIntegrationParam conf; diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCEnergyParam.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCEnergyParam.h index 1160a75c46ff3..a15b882bfde2e 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCEnergyParam.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCEnergyParam.h @@ -26,7 +26,7 @@ namespace zdc // parameters of ZDC reconstruction struct ZDCEnergyParam { - //std::array tdcShift{} + //std::array tdcShift{} float tdc_shift[NTDCChannels] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Correction of TDC position (ns) void setShift(uint32_t ich, float val); float getShift(uint32_t ich) const; diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h index e6dc0c6472c89..da4fefde6418d 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h @@ -26,7 +26,7 @@ namespace zdc // parameters of ZDC reconstruction struct ZDCTDCParam { - //std::array tdcShift{} + //std::array tdcShift{} float tdc_shift[NTDCChannels] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Correction of TDC position (ns) void setShift(uint32_t ich, float val); float getShift(uint32_t ich) const; diff --git a/Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx b/Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx index 9c1c61ee98163..013b8ead244f8 100644 --- a/Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx +++ b/Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx @@ -15,10 +15,11 @@ using namespace o2::zdc; O2ParamImpl(RecoParamZDC); -void RecoParamZDC::setBit(uint32_t ibit, bool val){ - if(ibit>=0 && ibit= 0 && ibit < NTDCChannels) { + bitset[ibit] = val; + } else { LOG(FATAL) << __func__ << " bit " << ibit << " not in allowed range"; } } diff --git a/Detectors/ZDC/reconstruction/src/ZDCIntegrationParam.cxx b/Detectors/ZDC/reconstruction/src/ZDCIntegrationParam.cxx index c0c07382649c1..5c8ebb05ffb4e 100644 --- a/Detectors/ZDC/reconstruction/src/ZDCIntegrationParam.cxx +++ b/Detectors/ZDC/reconstruction/src/ZDCIntegrationParam.cxx @@ -44,6 +44,6 @@ void ZDCIntegrationParam::setIntegration(uint32_t ich, int beg, int end, int beg void ZDCIntegrationParam::print() { for (Int_t ich = 0; ich < NChannels; ich++) { - LOG(INFO) << ChannelNames[ich] << " integration: signal=[" << beg_int[ich] << ":" << end_int[ich] << "] pedestal=[" << beg_ped_int[ich] << ":" << end_ped_int[ich] <<"]"; + LOG(INFO) << ChannelNames[ich] << " integration: signal=[" << beg_int[ich] << ":" << end_int[ich] << "] pedestal=[" << beg_ped_int[ich] << ":" << end_ped_int[ich] << "]"; } } From 69c66cdccfeb173907d7d949ee212ae14102a2b8 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 28 May 2021 10:27:49 +0200 Subject: [PATCH 010/770] Small updates --- .../ZDC/include/DataFormatsZDC/BCRecData.h | 12 +++ .../ZDC/include/DataFormatsZDC/RecEventAux.h | 2 - .../ZDC/include/DataFormatsZDC/ZDCEnergy.h | 6 +- .../ZDC/include/DataFormatsZDC/ZDCTDCData.h | 13 +++ DataFormats/Detectors/ZDC/src/RecEvent.cxx | 9 ++ DataFormats/Detectors/ZDC/src/ZDCEnergy.cxx | 3 +- DataFormats/Detectors/ZDC/src/ZDCTDCData.cxx | 2 +- .../ZDC/base/include/ZDCBase/Constants.h | 11 ++- Detectors/ZDC/reconstruction/src/DigiReco.cxx | 20 ++-- Detectors/ZDC/workflow/CMakeLists.txt | 1 + .../include/ZDCWorkflow/DigitRecoSpec.h | 47 ++++++++++ Detectors/ZDC/workflow/src/DigitRecoSpec.cxx | 93 +++++++++++++++++++ 12 files changed, 199 insertions(+), 20 deletions(-) create mode 100644 Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h create mode 100644 Detectors/ZDC/workflow/src/DigitRecoSpec.cxx diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h index 2759220849391..3959b5fb9d1ba 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h @@ -66,6 +66,18 @@ struct BCRecData { { refi.setEntries(refi.getEntries() + 1); } + + // Get information about event + inline void getRef(int& firste, int& ne, int& firstt, int& nt, int& firsti, int& ni) + { + firste = refe.getFirstEntry(); + firstt = reft.getFirstEntry(); + firsti = refi.getFirstEntry(); + ne = refe.getEntries(); + nt = reft.getEntries(); + ni = refi.getEntries(); + } + void print() const; ClassDefNV(BCRecData, 1); diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h index 53f9186b029b7..57dfb74584c3d 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h @@ -32,8 +32,6 @@ struct RecEventAux { uint32_t channels = 0; /// pattern of channels acquired uint32_t triggers = 0; /// pattern of channels with autotrigger bit uint32_t flags; /// reconstruction flags - constexpr static float fAmp = 1. / 8.; /// Multiplication factor in conversion from integer - constexpr static float fVal = 1. / TSNS; /// Multiplication factor in conversion from integer std::map ezdc; /// signal in ZDCs int16_t tdcVal[NTDCChannels][MaxTDCValues]; /// TdcChannels int16_t tdcAmp[NTDCChannels][MaxTDCValues]; /// TdcAmplitudes diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h index 67876d4d48806..975dfc4327e8d 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h @@ -17,7 +17,7 @@ #include /// \file ZDCEnergy.h -/// \brief Container class to store energy released in a ZDC +/// \brief Container class to store energy released in the ZDC /// \author pietro.cortese@cern.ch namespace o2 @@ -46,11 +46,11 @@ struct ZDCEnergy { } value = (value & EnergyMask) | (ch << 27); } - float energy() + float energy() const { return (float(value & EnergyMask) - EnergyOffset) * EnergyUnit; } - uint8_t ch() + uint8_t ch() const { return (value & EnergyChMask) >> 27; } diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCTDCData.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCTDCData.h index d5e53f3349599..83d8073a4a000 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCTDCData.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCTDCData.h @@ -38,6 +38,19 @@ struct ZDCTDCData { amp = ampa; } + inline float amplitude() const + { + return FTDCAmp*amp; + } + inline float value() const + { + return FTDCVal*val; + } + inline uint8_t ch() const + { + return id; + } + void print() const; ClassDefNV(ZDCTDCData, 1); diff --git a/DataFormats/Detectors/ZDC/src/RecEvent.cxx b/DataFormats/Detectors/ZDC/src/RecEvent.cxx index 762f0a83f9dca..4c94cea2c63b0 100644 --- a/DataFormats/Detectors/ZDC/src/RecEvent.cxx +++ b/DataFormats/Detectors/ZDC/src/RecEvent.cxx @@ -16,5 +16,14 @@ void RecEvent::print() const { for (auto bcdata : mRecBC) { bcdata.ir.print(); + int fe,ne,ft,nt,fi,ni; + bcdata.getRef(fe,ne,ft,nt,fi,ni); + for(int ie=0; iech(); + printf("%2d (%s): %9u = %9.2f\n", id, channelName(id), value & EnergyChMask, energy()); } diff --git a/DataFormats/Detectors/ZDC/src/ZDCTDCData.cxx b/DataFormats/Detectors/ZDC/src/ZDCTDCData.cxx index b0d845d19aa51..adc9b86dd2d98 100644 --- a/DataFormats/Detectors/ZDC/src/ZDCTDCData.cxx +++ b/DataFormats/Detectors/ZDC/src/ZDCTDCData.cxx @@ -14,5 +14,5 @@ using namespace o2::zdc; void o2::zdc::ZDCTDCData::print() const { - printf("%2d (%s) %d @ %d\n", id, channelName(id), amp, val); + printf("%2d (%s) %d = %8.3f @ %d = %6.3f\n", id, channelName(id), amp, amplitude(), val, value()); } diff --git a/Detectors/ZDC/base/include/ZDCBase/Constants.h b/Detectors/ZDC/base/include/ZDCBase/Constants.h index 2ae89763753eb..bda1b0a91bbad 100644 --- a/Detectors/ZDC/base/include/ZDCBase/Constants.h +++ b/Detectors/ZDC/base/include/ZDCBase/Constants.h @@ -83,10 +83,13 @@ constexpr uint32_t EnergyChMask = 0xf8000000; constexpr int MaxTDCValues = 5; // max number of TDC values to store in reconstructed event constexpr int NTDCChannels = 10; // max number of TDC values to store in reconstructed event // Parameters of interpolating function -constexpr int TSL = 6; // number of zeros on the right (and on the left) of central peak -constexpr int TSN = 200; // Number of interpolated points between each pair = TSN-1 -constexpr int TSNS = 96; // Number of interpolated points per ns -constexpr int NTS = 2 * TSL * TSN + 1; //Tapered sinc function array size +constexpr int TSL = 6; // number of zeros on the right (and on the left) of central peak +constexpr int TSN = 200; // Number of interpolated points between each pair = TSN-1 +constexpr int TSNS = 96; // Number of interpolated points per ns +constexpr int NTS = 2 * TSL * TSN + 1; //Tapered sinc function array size +constexpr static float FTDCAmp = 1. / 8.; /// Multiplication factor in conversion from integer +constexpr static float FTDCVal = 1. / TSNS; /// Multiplication factor in conversion from integer + enum TDCChannelID { TDCZNAC, TDCZNAS, diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index 2ad069bd4daae..5e9b03bd4c0ae 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -89,7 +89,7 @@ void DigiReco::init() if (!mTDCParam) { LOG(FATAL) << "TDC " << itdc << " missing configuration object and no manual override"; } else { - fval = mTDCParam->getShift(itdc) / RecEventAux::fVal; + fval = mTDCParam->getShift(itdc) / FTDCVal; } } auto val = std::nearbyint(fval); @@ -100,12 +100,12 @@ void DigiReco::init() LOG(FATAL) << "Shift for TDC " << itdc << " " << val << " is out of range"; } tdc_shift[itdc] = val; - LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " shift= " << tdc_shift[itdc] << " i.s. = " << val * RecEventAux::fVal << " ns"; + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " shift= " << tdc_shift[itdc] << " i.s. = " << val * FTDCVal << " ns"; } // TDC search zone // TODO: override with configuration object for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { - LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << ropt.tdc_search[itdc] << " i.s. = " << ropt.tdc_search[itdc] * RecEventAux::fVal << " ns"; + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << ropt.tdc_search[itdc] << " i.s. = " << ropt.tdc_search[itdc] * FTDCVal << " ns"; } // Fill maps channel maps for integration @@ -145,7 +145,7 @@ void DigiReco::init() ropt.end_ped_int[ich] = mIntParam->end_ped_int[ich]; } } - LOG(INFO) << ChannelNames[ich] << " integration: signal=[" << ropt.beg_int[ich] << "-" << ropt.end_int[ich] << "] pedestal=[" << ropt.beg_ped_int[ich] << "-" << ropt.end_ped_int[ich] << "]"; + LOG(INFO) << ChannelNames[ich] << " integration: signal=[" << ropt.beg_int[ich] << ":" << ropt.end_int[ich] << "] pedestal=[" << ropt.beg_ped_int[ich] << ":" << ropt.end_ped_int[ich] << "]"; } } @@ -211,10 +211,12 @@ int DigiReco::process(const std::vector* orbitdata, const st mReco[ibc].triggers = BCData[ibc].triggers; } - // Find consecutive bunch crossings and perform interpolation + // Find consecutive bunch crossings and perform signal interpolation + // in the identified ranges (in the reconstruction method we take into + // account for signals that do not span the entire reange) int seq_beg = 0; int seq_end = 0; - LOG(INFO) << "Reconstruction for " << mNBC << " bunch crossings"; + LOG(INFO) << "ZDC reconstruction for " << mNBC << " bunch crossings"; for (int ibc = 0; ibc < mNBC; ibc++) { auto& ir = BCData[seq_end].ir; auto bcd = BCData[ibc].ir.differenceInBC(ir); @@ -769,13 +771,13 @@ void DigiReco::assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float int& ihit = mReco[ibun].ntdc[itdc]; if (ihit < MaxTDCValues) { mReco[ibun].tdcVal[itdc][ihit] = tdc_cor; - mReco[ibun].tdcAmp[itdc][ihit] = std::nearbyint(amp / RecEventAux::fAmp); + mReco[ibun].tdcAmp[itdc][ihit] = std::nearbyint(amp / FTDCAmp); ihit++; LOG(INFO) << mReco[ibun].ir.orbit << "." << mReco[ibun].ir.bc << " " - << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor * RecEventAux::fVal << " amp=" << amp * RecEventAux::fAmp; + << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor * FTDCVal << " amp=" << amp * FTDCAmp; } else { LOG(ERROR) << mReco[ibun].ir.orbit << "." << mReco[ibun].ir.bc << " " - << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor * RecEventAux::fVal << " amp=" << amp * RecEventAux::fAmp << " OVERFLOW"; + << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor * FTDCVal << " amp=" << amp * FTDCAmp << " OVERFLOW"; } } diff --git a/Detectors/ZDC/workflow/CMakeLists.txt b/Detectors/ZDC/workflow/CMakeLists.txt index 3f929f6df61c7..a8378c04d290b 100644 --- a/Detectors/ZDC/workflow/CMakeLists.txt +++ b/Detectors/ZDC/workflow/CMakeLists.txt @@ -15,6 +15,7 @@ o2_add_library(ZDCWorkflow src/ZDCDataReaderDPLSpec.cxx src/ZDCDigitWriterDPLSpec.cxx src/ZDCRecoWriterDPLSpec.cxx + src/DigitRecoSpec.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DataFormatsZDC O2::ZDCRaw diff --git a/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h b/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h new file mode 100644 index 0000000000000..de172947415fd --- /dev/null +++ b/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h @@ -0,0 +1,47 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file DigitRecoSpec.h +/// @brief Convert ZDC data to CTF (EncodedBlocks) +/// @author pietro.cortese@cern.ch + +#ifndef O2_ZDC_DIGITRECO_SPEC +#define O2_ZDC_DIGITRECO_SPEC + +#include "Framework/DataProcessorSpec.h" +#include "Framework/Task.h" +#include + +namespace o2 +{ +namespace zdc +{ + +class DigitRecoSpec : public o2::framework::Task +{ + public: + DigitRecoSpec(); + ~DigitRecoSpec() override = default; + void run(o2::framework::ProcessingContext& pc) final; + void init(o2::framework::InitContext& ic) final; + void endOfStream(o2::framework::EndOfStreamContext& ec) final; + + private: + TStopwatch mTimer; + bool mInitialized = false; +}; + +/// create a processor spec +//framework::DataProcessorSpec getDigitRecoSpec(); + +} // namespace zdc +} // namespace o2 + +#endif diff --git a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx new file mode 100644 index 0000000000000..a60124619d4c3 --- /dev/null +++ b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx @@ -0,0 +1,93 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file DigitRecoSpec.cxx +/// @brief ZDC reconstruction +/// @author pietro.cortese@cern.ch + +#include +#include "CCDB/BasicCCDBManager.h" +#include "CCDB/CCDBTimeStampUtils.h" +#include "Framework/ControlService.h" +#include "Framework/ConfigParamRegistry.h" +#include "ZDCWorkflow/DigitRecoSpec.h" +#include "DetectorsCommonDataFormats/DetID.h" +#include "DataFormatsZDC/BCData.h" +#include "DataFormatsZDC/ChannelData.h" +#include "DataFormatsZDC/OrbitData.h" +#include "FairLogger.h" + +using namespace o2::framework; + +namespace o2 +{ +namespace zdc +{ + +DigitRecoSpec::DigitRecoSpec() +{ + mTimer.Stop(); + mTimer.Reset(); +} + +void DigitRecoSpec::init(o2::framework::InitContext& ic) +{ + // At this stage we cannot access the CCDB yet +// std::string dictPath = ic.options().get("zdc-ctf-dictionary"); +// if (!dictPath.empty() && dictPath != "none") { +// mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Encoder); +// } +} + +void DigitRecoSpec::run(ProcessingContext& pc) +{ + if(!mInitialized){ + mInitialized = true; + // Initialization from CCDB + } + auto cput = mTimer.CpuTime(); + mTimer.Start(false); + auto bcdata = pc.inputs().get>("trig"); + auto chans = pc.inputs().get>("chan"); + auto peds = pc.inputs().get>("peds"); + +// auto& buffer = pc.outputs().make>(Output{"ZDC", "CTFDATA", 0, Lifetime::Timeframe}); +// mCTFCoder.encode(buffer, bcdata, chans, peds); +// auto eeb = CTF::get(buffer.data()); // cast to container pointer +// eeb->compactify(); // eliminate unnecessary padding +// buffer.resize(eeb->size()); // shrink buffer to strictly necessary size + // eeb->print(); + mTimer.Stop(); +// LOG(INFO) << "Created encoded data of size " << eeb->size() << " for ZDC in " << mTimer.CpuTime() - cput << " s"; +} + +void DigitRecoSpec::endOfStream(EndOfStreamContext& ec) +{ + LOGF(INFO, "ZDC Reconstruction total timing: Cpu: %.3e Real: %.3e s in %d slots", + mTimer.CpuTime(), mTimer.RealTime(), mTimer.Counter() - 1); +} + + +DataProcessorSpec getDigitRecoSpec() +{ + std::vector inputs; + inputs.emplace_back("trig", "ZDC", "DIGITSBC", 0, Lifetime::Timeframe); + inputs.emplace_back("chan", "ZDC", "DIGITSCH", 0, Lifetime::Timeframe); + inputs.emplace_back("peds", "ZDC", "DIGITSPD", 0, Lifetime::Timeframe); + + return DataProcessorSpec{ + "zdc-digi-reco", + inputs, + Outputs{{"ZDC", "RECODATA", 0, Lifetime::Timeframe}}, + AlgorithmSpec{adaptFromTask()}}; +} + +} // namespace zdc +} // namespace o2 From 8c5c32e079daaab7537e73a313f3995b6617461d Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 28 May 2021 10:30:49 +0200 Subject: [PATCH 011/770] clang format --- DataFormats/Detectors/ZDC/src/RecEvent.cxx | 12 +++++----- Detectors/ZDC/workflow/src/DigitRecoSpec.cxx | 23 ++++++++++---------- 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/DataFormats/Detectors/ZDC/src/RecEvent.cxx b/DataFormats/Detectors/ZDC/src/RecEvent.cxx index 4c94cea2c63b0..2cbd771dae325 100644 --- a/DataFormats/Detectors/ZDC/src/RecEvent.cxx +++ b/DataFormats/Detectors/ZDC/src/RecEvent.cxx @@ -16,13 +16,13 @@ void RecEvent::print() const { for (auto bcdata : mRecBC) { bcdata.ir.print(); - int fe,ne,ft,nt,fi,ni; - bcdata.getRef(fe,ne,ft,nt,fi,ni); - for(int ie=0; ie("zdc-ctf-dictionary"); -// if (!dictPath.empty() && dictPath != "none") { -// mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Encoder); -// } + // std::string dictPath = ic.options().get("zdc-ctf-dictionary"); + // if (!dictPath.empty() && dictPath != "none") { + // mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Encoder); + // } } void DigitRecoSpec::run(ProcessingContext& pc) { - if(!mInitialized){ + if (!mInitialized) { mInitialized = true; // Initialization from CCDB } @@ -58,14 +58,14 @@ void DigitRecoSpec::run(ProcessingContext& pc) auto chans = pc.inputs().get>("chan"); auto peds = pc.inputs().get>("peds"); -// auto& buffer = pc.outputs().make>(Output{"ZDC", "CTFDATA", 0, Lifetime::Timeframe}); -// mCTFCoder.encode(buffer, bcdata, chans, peds); -// auto eeb = CTF::get(buffer.data()); // cast to container pointer -// eeb->compactify(); // eliminate unnecessary padding -// buffer.resize(eeb->size()); // shrink buffer to strictly necessary size + // auto& buffer = pc.outputs().make>(Output{"ZDC", "CTFDATA", 0, Lifetime::Timeframe}); + // mCTFCoder.encode(buffer, bcdata, chans, peds); + // auto eeb = CTF::get(buffer.data()); // cast to container pointer + // eeb->compactify(); // eliminate unnecessary padding + // buffer.resize(eeb->size()); // shrink buffer to strictly necessary size // eeb->print(); mTimer.Stop(); -// LOG(INFO) << "Created encoded data of size " << eeb->size() << " for ZDC in " << mTimer.CpuTime() - cput << " s"; + // LOG(INFO) << "Created encoded data of size " << eeb->size() << " for ZDC in " << mTimer.CpuTime() - cput << " s"; } void DigitRecoSpec::endOfStream(EndOfStreamContext& ec) @@ -74,7 +74,6 @@ void DigitRecoSpec::endOfStream(EndOfStreamContext& ec) mTimer.CpuTime(), mTimer.RealTime(), mTimer.Counter() - 1); } - DataProcessorSpec getDigitRecoSpec() { std::vector inputs; From 700e574a93afaafa4b40d46573a5c0bdd60f95db Mon Sep 17 00:00:00 2001 From: ALICE Action Bot Date: Fri, 28 May 2021 08:31:41 +0000 Subject: [PATCH 012/770] Please consider the following formatting changes --- DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCTDCData.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCTDCData.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCTDCData.h index 83d8073a4a000..421cbe51aaa2d 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCTDCData.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCTDCData.h @@ -40,11 +40,11 @@ struct ZDCTDCData { inline float amplitude() const { - return FTDCAmp*amp; + return FTDCAmp * amp; } inline float value() const { - return FTDCVal*val; + return FTDCVal * val; } inline uint8_t ch() const { From f1921856b4f06eafc643309dff89c8d54f0f3157 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Tue, 1 Jun 2021 18:09:16 +0200 Subject: [PATCH 013/770] Some corrections from Ruben --- .../ZDC/include/DataFormatsZDC/BCData.h | 1 + .../ZDC/include/DataFormatsZDC/ChannelData.h | 1 + .../ZDC/include/DataFormatsZDC/FEEConfig.h | 51 +++++++++++ .../ZDC/include/DataFormatsZDC/RecEvent.h | 16 +--- .../ZDC/include/DataFormatsZDC/RecEventAux.h | 14 --- .../include/ZDCReconstruction/DigiReco.h | 29 ++++--- .../include/ZDCReconstruction/RecoParamZDC.h | 2 +- Detectors/ZDC/reconstruction/src/DigiReco.cxx | 72 ++++++---------- Detectors/ZDC/workflow/CMakeLists.txt | 10 +++ .../include/ZDCWorkflow/DigitRecoSpec.h | 2 + Detectors/ZDC/workflow/src/DigitRecoSpec.cxx | 86 ++++++++++++++++--- .../ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx | 4 +- 12 files changed, 190 insertions(+), 98 deletions(-) create mode 100644 DataFormats/Detectors/ZDC/include/DataFormatsZDC/FEEConfig.h diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCData.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCData.h index 48117805f3220..22917556048a9 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCData.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCData.h @@ -65,6 +65,7 @@ struct BCData { triggers = chTrig; ext_triggers = extTrig; } + BCData(const BCData&) = default; gsl::span getBunchChannelData(const gsl::span tfdata) const; void print(uint32_t triggerMask = 0, int diff = 0) const; diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ChannelData.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ChannelData.h index 5ae041e690633..be5427382d925 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ChannelData.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ChannelData.h @@ -37,6 +37,7 @@ struct ChannelData { data[i] = int16_t(src[i]); } } + ChannelData(const ChannelData&) = default; void print() const; diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/FEEConfig.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/FEEConfig.h new file mode 100644 index 0000000000000..4bec3a9fd10ff --- /dev/null +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/FEEConfig.h @@ -0,0 +1,51 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. +// +// DataFormats/Detectors/ZDC/include/DataFormatsZDC/RawEventData.h + +#include "ZDCBase/Constants.h" + +#ifndef ALICEO2_ZDC_FEECONFIG_H +#define ALICEO2_ZDC_FEECONFIG_H + +/// \file FEEConfig.h +/// \brief ZDC FEE configuration +/// \author pietro.cortese@cern.ch + +namespace o2 +{ +namespace zdc +{ + +struct FEEFillingMap { + uint64_t filling[56]; +}; + +struct FEEConfigMap { + uint32_t address[5 * NChPerModule + 3] = {0, 1, 2, 3, + 4, 5, 6, 7, + 8, 9, 10, 11, + 12, 13, 14, 15, + 16, 17, 18, 19, + 76, 77, 78}; + uint64_t delay_sample[NChPerModule] = {6, 6, 6, 6}; // 4 bits + uint64_t delay_coarse[NChPerModule] = {200, 200, 200, 200}; // 8 bits + uint64_t threshold_level[NChPerModule] = {10, 10, 10, 10}; // 12 bits + uint64_t difference_delta[NChPerModule] = {4, 4, 4, 4}; // 3 bits + uint64_t masking_difference[NChPerModule] = {0x00ff00, 0x00ff00, 0x00ff00, 0x00ff00}; // 24 bits + uint64_t masking_alicet = 0x00000010; // 32 bits + uint64_t masking_autot = 0xf; // 4 bits + uint64_t masking_readout = 0xf; // 4 bits +}; + +} // namespace zdc +} // namespace o2 + +#endif diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h index a7f474a2c2b04..c40cff9a21a18 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h @@ -15,8 +15,8 @@ #include "DataFormatsZDC/BCRecData.h" #include "DataFormatsZDC/ZDCEnergy.h" #include "DataFormatsZDC/ZDCTDCData.h" -#include "MathUtils/Cartesian.h" #include "ZDCBase/Constants.h" +#include "MathUtils/Cartesian.h" #include #include #include @@ -69,23 +69,11 @@ struct RecEvent { mRecBC.back().addInfo(); } void print() const; + // TODO: remove persitency of this object (here for debugging) ClassDefNV(RecEvent, 1); }; } // namespace zdc - -/// Defining RecEvent explicitly as messageable -/// -/// It does not fulfill is_messageable because the underlying ROOT -/// classes of Point2D are note trivially copyable. -namespace framework -{ -template -struct is_messageable; -template <> -struct is_messageable : std::true_type { -}; -} // namespace framework } // namespace o2 #endif diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h index 57dfb74584c3d..fbdbe68a8c404 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h @@ -87,20 +87,6 @@ struct RecEventAux { }; } // namespace zdc - -/// Defining RecEventAux explicitly as messageable -/// -/// It does not fulfill is_messageable because the underlying ROOT -/// classes of Point2D are note trivially copyable. -namespace framework -{ -template -struct is_messageable; -template <> -struct is_messageable : std::true_type { -}; -} // namespace framework - } // namespace o2 #endif diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h index 9efdaac0880ba..3bd298d9fb025 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h @@ -9,6 +9,7 @@ // or submit itself to any jurisdiction. #include +#include #include #include #include "ZDCBase/Constants.h" @@ -37,11 +38,15 @@ class DigiReco { if (mTreeDbg) { mTDbg->Write(); + mTDbg.reset(); mDbg->Close(); + mDbg.reset(); } } void init(); - int process(const std::vector* orbitdata, const std::vector* bcdata, const std::vector* chdata); + int process(const gsl::span& orbitdata, + const gsl::span& bcdata, + const gsl::span& chdata); int write(); void setVerbosity(int v) { @@ -74,17 +79,17 @@ class DigiReco uint32_t mTDCMask[NTDCChannels] = {0}; /// Identify TDC channels in trigger mask const ZDCIntegrationParam* mIntParam = nullptr; /// Configuration of integration bool mVerbosity = DbgFull; - Double_t mTS[NTS]; /// Tapered sinc function - bool mTreeDbg = false; /// Write reconstructed data in debug output file - TFile* mDbg = nullptr; /// Debug output file - TTree* mTDbg = nullptr; /// Debug tree - const std::vector* mOrbitData; /// Reconstructed data - const std::vector* mBCData; /// BC info - const std::vector* mChData; /// Payload - std::vector mReco; /// Reconstructed data - std::map mOrbit; /// Information about orbit - static constexpr int mNSB = TSN * NTimeBinsPerBC; /// Total number of interpolated points per bunch crossing - RecEventAux mRec; /// Debug reconstruction event + Double_t mTS[NTS]; /// Tapered sinc function + bool mTreeDbg = false; /// Write reconstructed data in debug output file + std::unique_ptr mDbg = nullptr; /// Debug output file + std::unique_ptr mTDbg = nullptr; /// Debug tree + gsl::span mOrbitData; /// Reconstructed data + gsl::span mBCData; /// BC info + gsl::span mChData; /// Payload + std::vector mReco; /// Reconstructed data + std::map mOrbit; /// Information about orbit + static constexpr int mNSB = TSN * NTimeBinsPerBC; /// Total number of interpolated points per bunch crossing + RecEventAux mRec; /// Debug reconstruction event int mNBC = 0; int16_t tdc_shift[NTDCChannels] = {0}; /// TDC correction (units of 1/96 ns) constexpr static uint16_t mMask[NTimeBinsPerBC] = {0x0001, 0x002, 0x004, 0x008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200, 0x0400, 0x0800}; diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h index b7932ce353b7b..484ea82e3cf49 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h @@ -42,7 +42,7 @@ struct RecoParamZDC : public o2::conf::ConfigurableParamHelper { Int_t beg_ped_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; Int_t end_ped_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; std::array bitset = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Set bits in coincidence - public: + void setBit(uint32_t ibit, bool val = true); O2ParamDef(RecoParamZDC, "RecoParamZDC"); }; diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index 5e9b03bd4c0ae..0fa58d5a77e26 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -48,8 +48,8 @@ void DigiReco::init() if (mTreeDbg) { // Open debug file - mDbg = new TFile("ZDCReco.root", "recreate"); - mTDbg = new TTree("zdcr", "ZDCReco"); + mDbg = std::make_unique("ZDCReco.root", "recreate"); + mTDbg = std::make_unique("zdcr", "ZDCReco"); mTDbg->Branch("zdcr", "RecEvent", &mRec); } // Update reconstruction parameters @@ -149,27 +149,23 @@ void DigiReco::init() } } -int DigiReco::process(const std::vector* orbitdata, const std::vector* bcdata, const std::vector* chdata) +int DigiReco::process(const gsl::span& orbitdata, const gsl::span& bcdata, const gsl::span& chdata) { // We assume that vectors contain data from a full time frame mOrbitData = orbitdata; mBCData = bcdata; mChData = chdata; - const std::vector& OrbitData = *orbitdata; - const std::vector& BCData = *bcdata; - const std::vector& ChData = *chdata; - // Initialization of lookup structure for pedestals mOrbit.clear(); - int norb = OrbitData.size(); + int norb = mOrbitData.size(); for (int iorb = 0; iorb < norb; iorb++) { - mOrbit[OrbitData[iorb].ir.orbit] = iorb; + mOrbit[mOrbitData[iorb].ir.orbit] = iorb; if (mVerbosity >= DbgFull) { - LOG(INFO) << "OrbitData[" << OrbitData[iorb].ir.orbit << "] = " << iorb; + LOG(INFO) << "mOrbitData[" << mOrbitData[iorb].ir.orbit << "] = " << iorb; } } - mNBC = BCData.size(); + mNBC = mBCData.size(); mReco.clear(); mReco.resize(mNBC); // Initialization of reco structure @@ -181,11 +177,11 @@ int DigiReco::process(const std::vector* orbitdata, const st bcr.tdcAmp[itdc][i] = kMinShort; } } - auto& bcd = BCData[ibc]; + auto& bcd = mBCData[ibc]; bcr.ir = bcd.ir; int chEnt = bcd.ref.getFirstEntry(); for (int ic = 0; ic < bcd.ref.getEntries(); ic++) { - auto& chd = ChData[chEnt]; + auto& chd = mChData[chEnt]; if (chd.id > IdDummy && chd.id < NChannels) { bcr.ref[chd.id] = chEnt; } @@ -206,9 +202,9 @@ int DigiReco::process(const std::vector* orbitdata, const st // Assign interaction record and event information for (int ibc = 0; ibc < mNBC; ibc++) { - mReco[ibc].ir = BCData[ibc].ir; - mReco[ibc].channels = BCData[ibc].channels; - mReco[ibc].triggers = BCData[ibc].triggers; + mReco[ibc].ir = mBCData[ibc].ir; + mReco[ibc].channels = mBCData[ibc].channels; + mReco[ibc].triggers = mBCData[ibc].triggers; } // Find consecutive bunch crossings and perform signal interpolation @@ -218,10 +214,10 @@ int DigiReco::process(const std::vector* orbitdata, const st int seq_end = 0; LOG(INFO) << "ZDC reconstruction for " << mNBC << " bunch crossings"; for (int ibc = 0; ibc < mNBC; ibc++) { - auto& ir = BCData[seq_end].ir; - auto bcd = BCData[ibc].ir.differenceInBC(ir); + auto& ir = mBCData[seq_end].ir; + auto bcd = mBCData[ibc].ir.differenceInBC(ir); if (bcd < 0) { - LOG(FATAL) << "Orbit number is not increasing " << BCData[seq_end].ir.orbit << "." << BCData[seq_end].ir.bc << " followed by " << BCData[ibc].ir.orbit << "." << BCData[ibc].ir.bc; + LOG(FATAL) << "Orbit number is not increasing " << mBCData[seq_end].ir.orbit << "." << mBCData[seq_end].ir.bc << " followed by " << mBCData[ibc].ir.orbit << "." << mBCData[ibc].ir.bc; return __LINE__; } else if (bcd > 1) { // Detected a gap @@ -264,10 +260,6 @@ int DigiReco::reconstruct(int ibeg, int iend) return 0; } LOG(INFO) << __func__ << "(" << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; - // Get references to arrays - const std::vector& OrbitData = *mOrbitData; - const std::vector& BCData = *mBCData; - const std::vector& ChData = *mChData; // Get reconstruction parameters auto& ropt = RecoParamZDC::Instance(); @@ -280,7 +272,7 @@ int DigiReco::reconstruct(int ibeg, int iend) int istart = -1, istop = -1; // Loop allows for gaps in the data sequence for each TDC channel for (int ibun = ibeg; ibun <= iend; ibun++) { - if (BCData[ibun].channels & mTDCMask[itdc]) { // TDC channel has data for this event + if (mBCData[ibun].channels & mTDCMask[itdc]) { // TDC channel has data for this event if (istart < 0) { istart = ibun; } @@ -308,11 +300,11 @@ int DigiReco::reconstruct(int ibeg, int iend) for (int ibun = ibeg; ibun <= iend; ibun++) { // Look for offset float pbun[NChannels]; - auto orbit = BCData[ibun].ir.orbit; + auto orbit = mBCData[ibun].ir.orbit; std::map::iterator it = mOrbit.find(orbit); if (it != mOrbit.end()) { // Subtract pedestal - auto& orbitdata = OrbitData[it->second]; + auto& orbitdata = mOrbitData[it->second]; for (int ich = 0; ich < NChannels; ich++) { pbun[ich] = orbitdata.asFloat(ich); } @@ -399,7 +391,7 @@ int DigiReco::reconstruct(int ibeg, int iend) // TODO: fallback if offset is missing // TODO: fallback if channel has pile-up // TODO: manage signal positioned across boundary - sum += (pbun[ich] - float(ChData[ref].data[is])); + sum += (pbun[ich] - float(mChData[ref].data[is])); } printf("CH %d %s: %f\n", ich, ChannelNames[ich].data(), sum); rec.ezdc[ich] = sum; @@ -418,10 +410,6 @@ void DigiReco::processTrigger(int itdc, int ibeg, int iend) { LOG(INFO) << __func__ << "(itdc=" << itdc << "[" << ChannelNames[TDCSignal[itdc]] << "] ," << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; - const std::vector& OrbitData = *mOrbitData; - const std::vector& BCData = *mBCData; - const std::vector& ChData = *mChData; - // Get reconstruction parameters auto& ropt = RecoParamZDC::Instance(); @@ -464,7 +452,7 @@ void DigiReco::processTrigger(int itdc, int ibeg, int iend) return; } // TODO: More checks that bunch crossings are indeed consecutive - int diff = ChData[ref_m].data[s1] - ChData[ref_s].data[s2]; + int diff = mChData[ref_m].data[s1] - mChData[ref_s].data[s2]; // Triple trigger condition if (diff > thr) { isfired[0] = 1; @@ -502,10 +490,6 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) int nint = (nbun * NTimeBinsPerBC - 1) * TSN; // Total points in the interpolation region (-1) constexpr int nsp = 5; // Number of points to be searched - const std::vector& OrbitData = *mOrbitData; - const std::vector& BCData = *mBCData; - const std::vector& ChData = *mChData; - // At this level there should be no need to check if the TDC channel is connected // since a fatal should have been raised already for (int ibun = ibeg; ibun <= iend; ibun++) { @@ -524,8 +508,8 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) auto ref_beg = mReco[ibeg].ref[TDCSignal[itdc]]; auto ref_end = mReco[iend].ref[TDCSignal[itdc]]; - O2_ZDC_DIGIRECO_FLT first_sample = ChData[ref_beg].data[0]; - O2_ZDC_DIGIRECO_FLT last_sample = ChData[ref_end].data[NTimeBinsPerBC - 1]; + O2_ZDC_DIGIRECO_FLT first_sample = mChData[ref_beg].data[0]; + O2_ZDC_DIGIRECO_FLT last_sample = mChData[ref_end].data[NTimeBinsPerBC - 1]; // Constant extrapolation at the beginning and at the end of the array // Assign value of first sample @@ -551,7 +535,7 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) LOG(FATAL) << "ib=" << ib << " ibun=" << ibun; return; } - mReco[ibun].inter[itdc][isam] = ChData[mReco[ibun].ref[TDCSignal[itdc]]].data[ip]; + mReco[ibun].inter[itdc][isam] = mChData[mReco[ibun].ref[TDCSignal[itdc]]].data[ip]; } else { // Do the actual interpolation O2_ZDC_DIGIRECO_FLT y = 0; @@ -564,7 +548,7 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) if (ii < nsam) { int ip = ii % NTimeBinsPerBC; int ib = ibeg + ii / NTimeBinsPerBC; - yy = ChData[mReco[ib].ref[TDCSignal[itdc]]].data[ip]; + yy = mChData[mReco[ib].ref[TDCSignal[itdc]]].data[ip]; } else { // Last acquired point yy = last_sample; @@ -694,11 +678,11 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) int ibun = ibeg + isam_amp / nsbun; int tdc = isam_amp % nsbun; // Look for offset - auto orbit = BCData[ibun].ir.orbit; + auto orbit = mBCData[ibun].ir.orbit; std::map::iterator it = mOrbit.find(orbit); if (it != mOrbit.end()) { // Subtract pedestal - auto& orbitdata = OrbitData[it->second]; + auto& orbitdata = mOrbitData[it->second]; amp = orbitdata.asFloat(ich) - amp; } else { LOG(ERROR) << "Missing pedestal"; @@ -726,11 +710,11 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) int ibun = ibeg + isam_amp / nsbun; int tdc = isam_amp % nsbun; // Look for offset - auto orbit = BCData[ibun].ir.orbit; + auto orbit = mBCData[ibun].ir.orbit; std::map::iterator it = mOrbit.find(orbit); if (it != mOrbit.end()) { // Subtract pedestal - auto& orbitdata = OrbitData[it->second]; + auto& orbitdata = mOrbitData[it->second]; amp = orbitdata.asFloat(ich) - amp; } else { LOG(ERROR) << "Missing pedestal"; diff --git a/Detectors/ZDC/workflow/CMakeLists.txt b/Detectors/ZDC/workflow/CMakeLists.txt index a8378c04d290b..ed38925db1332 100644 --- a/Detectors/ZDC/workflow/CMakeLists.txt +++ b/Detectors/ZDC/workflow/CMakeLists.txt @@ -33,3 +33,13 @@ o2_add_executable(entropy-encoder-workflow COMPONENT_NAME zdc SOURCES src/entropy-encoder-workflow.cxx PUBLIC_LINK_LIBRARIES O2::ZDCWorkflow) + +o2_add_executable(digits-reco + COMPONENT_NAME zdc + SOURCES src/DigitRecoSpec.cxx + PUBLIC_LINK_LIBRARIES O2::ZDCWorkflow) + +o2_add_executable(write-reco + COMPONENT_NAME zdc + SOURCES src/ZDCRecoWriterDPLSpec.cxx + PUBLIC_LINK_LIBRARIES O2::ZDCWorkflow) diff --git a/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h b/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h index de172947415fd..b2e9ebbcab6e4 100644 --- a/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h +++ b/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h @@ -17,6 +17,7 @@ #include "Framework/DataProcessorSpec.h" #include "Framework/Task.h" +#include "ZDCReconstruction/DigiReco.h" #include namespace o2 @@ -34,6 +35,7 @@ class DigitRecoSpec : public o2::framework::Task void endOfStream(o2::framework::EndOfStreamContext& ec) final; private: + DigiReco mDR; TStopwatch mTimer; bool mInitialized = false; }; diff --git a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx index 83b135598fa54..50380464f59c9 100644 --- a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx +++ b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx @@ -22,7 +22,12 @@ #include "DataFormatsZDC/BCData.h" #include "DataFormatsZDC/ChannelData.h" #include "DataFormatsZDC/OrbitData.h" +#include "DataFormatsZDC/RecEvent.h" #include "FairLogger.h" +#include "CCDB/BasicCCDBManager.h" +#include "CCDB/CCDBTimeStampUtils.h" +#include "ZDCReconstruction/ZDCIntegrationParam.h" +#include "ZDCReconstruction/ZDCTDCParam.h" using namespace o2::framework; @@ -40,10 +45,6 @@ DigitRecoSpec::DigitRecoSpec() void DigitRecoSpec::init(o2::framework::InitContext& ic) { // At this stage we cannot access the CCDB yet - // std::string dictPath = ic.options().get("zdc-ctf-dictionary"); - // if (!dictPath.empty() && dictPath != "none") { - // mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Encoder); - // } } void DigitRecoSpec::run(ProcessingContext& pc) @@ -51,6 +52,33 @@ void DigitRecoSpec::run(ProcessingContext& pc) if (!mInitialized) { mInitialized = true; // Initialization from CCDB + std::string ccdbHost = "http://ccdb-test.cern.ch:8080"; + + auto& mgr = o2::ccdb::BasicCCDBManager::instance(); + mgr.setURL(ccdbHost); + long timeStamp = 0; + if (timeStamp == mgr.getTimestamp()) { + return; + } + mgr.setTimestamp(timeStamp); + auto* moduleConfig = + mgr.get(o2::zdc::CCDBPathConfigModule); + if (!moduleConfig) { + LOG(FATAL) << "Missing configuration object"; + return; + } + LOG(INFO) << "Loaded module configuration for timestamp " << timeStamp; + + // Get Reconstruction parameters + auto* integrationParam = + mgr.get(o2::zdc::CCDBPathConfigIntegration); + if (!integrationParam) { + LOG(FATAL) << "Missing ZDCIntegrationParam object"; + return; + } + mDR.setModuleConfig(moduleConfig); + mDR.setIntegrationParam(integrationParam); + mDR.setDebugOutput(); } auto cput = mTimer.CpuTime(); mTimer.Start(false); @@ -58,14 +86,43 @@ void DigitRecoSpec::run(ProcessingContext& pc) auto chans = pc.inputs().get>("chan"); auto peds = pc.inputs().get>("peds"); - // auto& buffer = pc.outputs().make>(Output{"ZDC", "CTFDATA", 0, Lifetime::Timeframe}); - // mCTFCoder.encode(buffer, bcdata, chans, peds); - // auto eeb = CTF::get(buffer.data()); // cast to container pointer - // eeb->compactify(); // eliminate unnecessary padding - // buffer.resize(eeb->size()); // shrink buffer to strictly necessary size - // eeb->print(); + mDR.process(peds, bcdata, chans); + const std::vector& recAux = mDR.getReco(); + + RecEvent recEvent; + + LOG(INFO) << "BC in recAux " << recAux.size(); + for (auto reca : recAux) { + int32_t ne = reca.ezdc.size(); + int32_t nt = 0; + for (int32_t it = 0; it < o2::zdc::NTDCChannels; it++) { + for (int32_t ih = 0; ih < reca.ntdc[it]; ih++) { + if (nt == 0) { + recEvent.addBC(reca.ir, reca.channels, reca.triggers); + } + nt++; + recEvent.addTDC(it, reca.tdcVal[it][ih], reca.tdcAmp[it][ih]); + } + } + if (ne > 0 && nt == 0) { + recEvent.addBC(reca.ir); + } + if (ne > 0) { + std::map::iterator it; + for (it = reca.ezdc.begin(); it != reca.ezdc.end(); it++) { + recEvent.addEnergy(it->first, it->second); + } + } + if (nt > 0 || ne > 0) { + printf("Orbit %9u bc %4u ntdc %2d ne %2d\n", reca.ir.orbit, reca.ir.bc, nt, ne); + } + } + + pc.outputs().snapshot(Output{"ZDC", "BCREC", 0, Lifetime::Timeframe}, recEvent.mRecBC); + pc.outputs().snapshot(Output{"ZDC", "ENERGY", 0, Lifetime::Timeframe}, recEvent.mEnergy); + pc.outputs().snapshot(Output{"ZDC", "TDCDATA", 0, Lifetime::Timeframe}, recEvent.mTDCData); mTimer.Stop(); - // LOG(INFO) << "Created encoded data of size " << eeb->size() << " for ZDC in " << mTimer.CpuTime() - cput << " s"; + LOG(INFO) << "Reconstructed ZDC data for " << recEvent.mRecBC.size() << " b.c. in " << mTimer.CpuTime() - cput << " s"; } void DigitRecoSpec::endOfStream(EndOfStreamContext& ec) @@ -81,10 +138,15 @@ DataProcessorSpec getDigitRecoSpec() inputs.emplace_back("chan", "ZDC", "DIGITSCH", 0, Lifetime::Timeframe); inputs.emplace_back("peds", "ZDC", "DIGITSPD", 0, Lifetime::Timeframe); + std::vector outputs; + outputs.emplace_back("ZDC", "BCREC", 0, Lifetime::Timeframe); + outputs.emplace_back("ZDC", "ENERGY", 0, Lifetime::Timeframe); + outputs.emplace_back("ZDC", "TDCDATA", 0, Lifetime::Timeframe); + return DataProcessorSpec{ "zdc-digi-reco", inputs, - Outputs{{"ZDC", "RECODATA", 0, Lifetime::Timeframe}}, + outputs, AlgorithmSpec{adaptFromTask()}}; } diff --git a/Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx b/Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx index 8607fd46867bc..684e15273a14c 100644 --- a/Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx +++ b/Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx @@ -35,7 +35,9 @@ DataProcessorSpec getZDCRecoWriterDPLSpec(bool mctruth, bool simVersion) return MakeRootTreeWriterSpec(writerName.data(), fnameDef.data(), "o2rec", - BranchDefinition>{InputSpec{"RecBCinput", "ZDC", "RECBC"}, "ZDCRecBC"})(); + BranchDefinition>{InputSpec{"bcrec", "ZDC", "BCREC"}, "ZDCRecBC"}, + BranchDefinition>{InputSpec{"energy", "ZDC", "ENERGY"}, "ZDCRecE"}, + BranchDefinition>{InputSpec{"tdcdata", "ZDC", "TDCDATA"}, "ZDCRecTDC"})(); } } // namespace zdc From d0594616e42d182c65de928130f3f1f989103381 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 4 Jun 2021 09:37:10 +0200 Subject: [PATCH 014/770] Digits reader --- Detectors/ZDC/workflow/CMakeLists.txt | 6 +++ .../include/ZDCWorkflow/RecoWorkflow.h | 25 ++++++++++ .../ZDC/workflow/src/DigitReaderSpec.cxx | 40 ++++++++-------- Detectors/ZDC/workflow/src/RecoWorkflow.cxx | 38 +++++++++++++++ .../ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx | 2 +- .../workflow/src/digits-reader-workflow.cxx | 47 +++++++++++++++++++ 6 files changed, 138 insertions(+), 20 deletions(-) create mode 100644 Detectors/ZDC/workflow/include/ZDCWorkflow/RecoWorkflow.h create mode 100644 Detectors/ZDC/workflow/src/RecoWorkflow.cxx create mode 100644 Detectors/ZDC/workflow/src/digits-reader-workflow.cxx diff --git a/Detectors/ZDC/workflow/CMakeLists.txt b/Detectors/ZDC/workflow/CMakeLists.txt index ed38925db1332..89f271093008b 100644 --- a/Detectors/ZDC/workflow/CMakeLists.txt +++ b/Detectors/ZDC/workflow/CMakeLists.txt @@ -16,6 +16,7 @@ o2_add_library(ZDCWorkflow src/ZDCDigitWriterDPLSpec.cxx src/ZDCRecoWriterDPLSpec.cxx src/DigitRecoSpec.cxx + src/DigitReaderSpec.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DataFormatsZDC O2::ZDCRaw @@ -34,6 +35,11 @@ o2_add_executable(entropy-encoder-workflow SOURCES src/entropy-encoder-workflow.cxx PUBLIC_LINK_LIBRARIES O2::ZDCWorkflow) +o2_add_executable(digits-read + COMPONENT_NAME zdc + SOURCES src/digits-reader-workflow.cxx + PUBLIC_LINK_LIBRARIES O2::ZDCWorkflow) + o2_add_executable(digits-reco COMPONENT_NAME zdc SOURCES src/DigitRecoSpec.cxx diff --git a/Detectors/ZDC/workflow/include/ZDCWorkflow/RecoWorkflow.h b/Detectors/ZDC/workflow/include/ZDCWorkflow/RecoWorkflow.h new file mode 100644 index 0000000000000..919c6b4e492b1 --- /dev/null +++ b/Detectors/ZDC/workflow/include/ZDCWorkflow/RecoWorkflow.h @@ -0,0 +1,25 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_ZDC_RECOWORKFLOW_H +#define O2_ZDC_RECOWORKFLOW_H + +/// @file RecoWorkflow.h + +#include "Framework/WorkflowSpec.h" + +namespace o2 +{ +namespace zdc +{ +framework::WorkflowSpec getRecoWorkflow(bool useMC, bool disableRootInp, bool disableRootOut); +} // namespace zdc +} // namespace o2 +#endif diff --git a/Detectors/ZDC/workflow/src/DigitReaderSpec.cxx b/Detectors/ZDC/workflow/src/DigitReaderSpec.cxx index 98e94b2b099e9..14a5b2fd42d53 100644 --- a/Detectors/ZDC/workflow/src/DigitReaderSpec.cxx +++ b/Detectors/ZDC/workflow/src/DigitReaderSpec.cxx @@ -18,9 +18,9 @@ #include "Framework/ControlService.h" #include "Framework/Logger.h" #include "ZDCWorkflow/DigitReaderSpec.h" -#include "DataFormatsZDC/ChannelData.h" -#include "DataFormatsZDC/BCData.h" #include "DataFormatsZDC/OrbitData.h" +#include "DataFormatsZDC/BCData.h" +#include "DataFormatsZDC/ChannelData.h" #include "DataFormatsZDC/MCLabel.h" #include "SimulationDataFormat/MCTruthContainer.h" @@ -34,7 +34,7 @@ namespace zdc void DigitReader::init(InitContext& ic) { auto filename = ic.options().get("zdc-digit-infile"); - mFile = std::make_unique(filename.c_str()); + mFile = std::make_unique(filename.c_str(), "OLD"); if (!mFile->IsOpen()) { LOG(ERROR) << "Cannot open the " << filename.c_str() << " file !"; throw std::runtime_error("cannot open input digits file"); @@ -48,29 +48,32 @@ void DigitReader::init(InitContext& ic) void DigitReader::run(ProcessingContext& pc) { - std::vector digitsCh, *digitsChPtr = &digitsCh; - std::vector digitsBC, *digitsBCPtr = &digitsBC; - std::vector orbitData, *orbitDataPtr = &orbitData; - mTree->SetBranchAddress("ZDCDigitBC", &digitsBCPtr); - mTree->SetBranchAddress("ZDCDigitCh", &digitsChPtr); - mTree->SetBranchAddress("ZDCDigitOrbit", &orbitDataPtr); + std::vector zdcOrbitData, *zdcOrbitDataPtr = &zdcOrbitData; + std::vector zdcBCData, *zdcBCDataPtr = &zdcBCData; + std::vector zdcChData, *zdcChDataPtr = &zdcChData; + + mTree->SetBranchAddress("ZDCDigitOrbit", &zdcOrbitDataPtr); + mTree->SetBranchAddress("ZDCDigitBC", &zdcBCDataPtr); + mTree->SetBranchAddress("ZDCDigitCh", &zdcChDataPtr); o2::dataformats::MCTruthContainer labels, *plabels = &labels; if (mUseMC) { mTree->SetBranchAddress("ZDCDigitLabels", &plabels); } - mTree->GetEntry(0); - - LOG(INFO) << "ZDCDigitReader pushed " << digitsCh.size() << " channels in " << digitsBC.size() << " digits"; - - pc.outputs().snapshot(Output{"ZDC", "DIGITSBC", 0, Lifetime::Timeframe}, digitsBC); - pc.outputs().snapshot(Output{"ZDC", "DIGITSCH", 0, Lifetime::Timeframe}, digitsCh); - pc.outputs().snapshot(Output{"ZDC", "DIGITSPD", 0, Lifetime::Timeframe}, orbitData); + auto ent = mTree->GetReadEntry() + 1; + assert(ent < mTree->GetEntries()); // this should not happen + mTree->GetEntry(ent); + LOG(INFO) << "ZDCDigitReader pushed " << zdcOrbitData.size() << " orbits with " << zdcBCData.size() << " bcs and " << zdcChData.size() << " digits"; + pc.outputs().snapshot(Output{"ZDC", "DIGITSPD", 0, Lifetime::Timeframe}, zdcOrbitData); + pc.outputs().snapshot(Output{"ZDC", "DIGITSBC", 0, Lifetime::Timeframe}, zdcBCData); + pc.outputs().snapshot(Output{"ZDC", "DIGITSCH", 0, Lifetime::Timeframe}, zdcChData); if (mUseMC) { pc.outputs().snapshot(Output{"ZDC", "DIGITSLBL", 0, Lifetime::Timeframe}, labels); } - pc.services().get().endOfStream(); - pc.services().get().readyToQuit(QuitRequest::Me); + if (mTree->GetReadEntry() + 1 >= mTree->GetEntries()) { + pc.services().get().endOfStream(); + pc.services().get().readyToQuit(QuitRequest::Me); + } } DataProcessorSpec getDigitReaderSpec(bool useMC) @@ -82,7 +85,6 @@ DataProcessorSpec getDigitReaderSpec(bool useMC) if (useMC) { outputs.emplace_back("ZDC", "DIGITSLBL", 0, Lifetime::Timeframe); } - return DataProcessorSpec{ "zdc-digit-reader", Inputs{}, diff --git a/Detectors/ZDC/workflow/src/RecoWorkflow.cxx b/Detectors/ZDC/workflow/src/RecoWorkflow.cxx new file mode 100644 index 0000000000000..86e94d2430fdc --- /dev/null +++ b/Detectors/ZDC/workflow/src/RecoWorkflow.cxx @@ -0,0 +1,38 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file RecoWorkflow.cxx + +#include "FT0Workflow/RecoWorkflow.h" +#include "FT0Workflow/DigitReaderSpec.h" +#include "FT0Workflow/RecPointWriterSpec.h" +#include "FT0Workflow/ReconstructionSpec.h" +#include "FT0Workflow/FT0DataReaderDPLSpec.h" + +namespace o2 +{ +namespace zdc +{ + +framework::WorkflowSpec getRecoWorkflow(bool useMC, bool disableRootInp, bool disableRootOut) +{ + framework::WorkflowSpec specs; + if (!disableRootInp) { + specs.emplace_back(o2::zdc::getDigitReaderSpec(useMC)); + } + specs.emplace_back(o2::zdc::getReconstructionSpec(useMC)); + if (!disableRootOut) { + specs.emplace_back(o2::zdc::getRecPointWriterSpec(useMC)); + } + return specs; +} + +} // namespace zdc +} // namespace o2 diff --git a/Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx b/Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx index 684e15273a14c..8b0298b5759ca 100644 --- a/Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx +++ b/Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file FT0DigitWriterSpec.cxx +/// @file ZDCRecoWriterDPLSpec.cxx #include diff --git a/Detectors/ZDC/workflow/src/digits-reader-workflow.cxx b/Detectors/ZDC/workflow/src/digits-reader-workflow.cxx new file mode 100644 index 0000000000000..72014cfda9a5c --- /dev/null +++ b/Detectors/ZDC/workflow/src/digits-reader-workflow.cxx @@ -0,0 +1,47 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file digits-reader-workflow.cxx +/// \brief Implementation of ZDC digits reader +/// +/// \author ruben.shahoyan@cern.ch + +#include "Framework/CallbackService.h" +#include "Framework/ControlService.h" +#include "Framework/ConfigParamRegistry.h" +#include "Framework/Task.h" +#include "ZDCWorkflow/DigitReaderSpec.h" +#include "CommonUtils/ConfigurableParam.h" + +using namespace o2::framework; + +// we need to add workflow options before including Framework/runDataProcessing +void customize(std::vector& workflowOptions) +{ + // option allowing to set parameters + + std::vector options{ + {"disable-mc", o2::framework::VariantType::Bool, false, {"disable MC propagation even if available"}}}; + + std::string keyvaluehelp("Semicolon separated key=value strings"); + options.push_back(ConfigParamSpec{"configKeyValues", VariantType::String, "", {keyvaluehelp}}); + std::swap(workflowOptions, options); +} + +#include "Framework/runDataProcessing.h" + +WorkflowSpec defineDataProcessing(const ConfigContext& ctx) +{ + WorkflowSpec specs; + + DataProcessorSpec producer = o2::zdc::getDigitReaderSpec(ctx.options().get("disable-mc")); + specs.push_back(producer); + return specs; +} From 3e04a8c533ce1c6dc47c22c7ae57bafc57720f25 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 4 Jun 2021 10:33:38 +0200 Subject: [PATCH 015/770] First reco workflow --- .../ZDC/include/DataFormatsZDC/BCData.h | 4 +- .../ZDC/include/DataFormatsZDC/BCRecData.h | 4 +- .../Detectors/ZDC/src/DataFormatsZDCLinkDef.h | 1 + Detectors/ZDC/reconstruction/src/DigiReco.cxx | 5 +- Detectors/ZDC/workflow/CMakeLists.txt | 3 +- .../include/ZDCWorkflow/DigitRecoSpec.h | 2 +- .../ZDCWorkflow/ZDCRecoWriterDPLSpec.h | 2 +- Detectors/ZDC/workflow/src/DigitRecoSpec.cxx | 23 +++++++++ Detectors/ZDC/workflow/src/RecoWorkflow.cxx | 17 ++++--- .../ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx | 3 +- .../ZDC/workflow/src/zdc-reco-workflow.cxx | 50 +++++++++++++++++++ 11 files changed, 97 insertions(+), 17 deletions(-) create mode 100644 Detectors/ZDC/workflow/src/zdc-reco-workflow.cxx diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCData.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCData.h index 22917556048a9..f9182e3e7559a 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCData.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCData.h @@ -8,8 +8,8 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef _ZDC_BC_DATA_H_ -#define _ZDC_BC_DATA_H_ +#ifndef O2_ZDC_BC_DATA_H_ +#define O2_ZDC_BC_DATA_H_ #include "CommonDataFormat/InteractionRecord.h" #include "CommonDataFormat/RangeReference.h" diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h index 3959b5fb9d1ba..6803b11625792 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h @@ -8,8 +8,8 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef _ZDC_BC_REC_DATA_H -#define _ZDC_BC_REC_DATA_H +#ifndef O2_ZDC_BC_REC_DATA_H +#define O2_ZDC_BC_REC_DATA_H #include "CommonDataFormat/InteractionRecord.h" #include "CommonDataFormat/RangeReference.h" diff --git a/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h b/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h index 4aca764157aec..d8d92119a67f7 100644 --- a/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h +++ b/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h @@ -23,6 +23,7 @@ #pragma link C++ class o2::zdc::ChannelData + ; #pragma link C++ class o2::zdc::BCData + ; +#pragma link C++ class o2::zdc::BCRecData + ; #pragma link C++ class o2::zdc::OrbitData + ; #pragma link C++ class o2::zdc::RecEvent + ; #pragma link C++ class o2::zdc::RecEventAux + ; diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index 0fa58d5a77e26..ae2cb3059a9f9 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -21,6 +21,7 @@ using O2_ZDC_DIGIRECO_FLT = float; void DigiReco::init() { + LOG(INFO) << "Initialization of ZDC reconstruction"; // Load configuration parameters auto& sopt = ZDCSimParam::Instance(); mIsContinuous = sopt.continuous; @@ -48,9 +49,9 @@ void DigiReco::init() if (mTreeDbg) { // Open debug file - mDbg = std::make_unique("ZDCReco.root", "recreate"); + mDbg = std::make_unique("ZDCRecoDbg.root", "recreate"); mTDbg = std::make_unique("zdcr", "ZDCReco"); - mTDbg->Branch("zdcr", "RecEvent", &mRec); + mTDbg->Branch("zdcr", "RecEventAux", &mRec); } // Update reconstruction parameters //auto& ropt=RecoParamZDC::Instance(); diff --git a/Detectors/ZDC/workflow/CMakeLists.txt b/Detectors/ZDC/workflow/CMakeLists.txt index 89f271093008b..a4d9aff4f6485 100644 --- a/Detectors/ZDC/workflow/CMakeLists.txt +++ b/Detectors/ZDC/workflow/CMakeLists.txt @@ -15,6 +15,7 @@ o2_add_library(ZDCWorkflow src/ZDCDataReaderDPLSpec.cxx src/ZDCDigitWriterDPLSpec.cxx src/ZDCRecoWriterDPLSpec.cxx + src/RecoWorkflow.cxx src/DigitRecoSpec.cxx src/DigitReaderSpec.cxx PUBLIC_LINK_LIBRARIES O2::Framework @@ -42,7 +43,7 @@ o2_add_executable(digits-read o2_add_executable(digits-reco COMPONENT_NAME zdc - SOURCES src/DigitRecoSpec.cxx + SOURCES src/zdc-reco-workflow.cxx PUBLIC_LINK_LIBRARIES O2::ZDCWorkflow) o2_add_executable(write-reco diff --git a/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h b/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h index b2e9ebbcab6e4..5cdf0c71e2cf6 100644 --- a/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h +++ b/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h @@ -41,7 +41,7 @@ class DigitRecoSpec : public o2::framework::Task }; /// create a processor spec -//framework::DataProcessorSpec getDigitRecoSpec(); +framework::DataProcessorSpec getDigitRecoSpec(); } // namespace zdc } // namespace o2 diff --git a/Detectors/ZDC/workflow/include/ZDCWorkflow/ZDCRecoWriterDPLSpec.h b/Detectors/ZDC/workflow/include/ZDCWorkflow/ZDCRecoWriterDPLSpec.h index 19f489653230d..89f5748b40b21 100644 --- a/Detectors/ZDC/workflow/include/ZDCWorkflow/ZDCRecoWriterDPLSpec.h +++ b/Detectors/ZDC/workflow/include/ZDCWorkflow/ZDCRecoWriterDPLSpec.h @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file ZDCRecoWriterDPLSpec.h +/// @file ZDCRecoWriterSpec.h #ifndef O2_ZDCRECOTWRITERDPLSPEC_H #define O2_ZDCRECOTWRITERDPLSPEC_H diff --git a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx index 50380464f59c9..99915cce9f08e 100644 --- a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx +++ b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx @@ -79,6 +79,29 @@ void DigitRecoSpec::run(ProcessingContext& pc) mDR.setModuleConfig(moduleConfig); mDR.setIntegrationParam(integrationParam); mDR.setDebugOutput(); + // TDC + auto *zdc_tdcp = new o2::zdc::ZDCTDCParam(); + for (Int_t itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { + zdc_tdcp->setShift(itdc, 14.5); + } + mDR.setTDCParam(zdc_tdcp); + + auto *zdc_ip = new o2::zdc::ZDCIntegrationParam(); + int beg = 6; + int end = 8; + int beg_ped = -1; + int end_ped = -1; + for (Int_t ich = 0; ich < o2::zdc::NChannels; ich++) { + // zdc_ip->setIntegration(ich, beg, end, beg_ped, end_ped); + zdc_ip->beg_int[ich] = beg; + zdc_ip->end_int[ich] = end; + } + mDR.setIntegrationParam(zdc_ip); + + + + + mDR.init(); } auto cput = mTimer.CpuTime(); mTimer.Start(false); diff --git a/Detectors/ZDC/workflow/src/RecoWorkflow.cxx b/Detectors/ZDC/workflow/src/RecoWorkflow.cxx index 86e94d2430fdc..18bec0781e0dd 100644 --- a/Detectors/ZDC/workflow/src/RecoWorkflow.cxx +++ b/Detectors/ZDC/workflow/src/RecoWorkflow.cxx @@ -10,11 +10,10 @@ /// @file RecoWorkflow.cxx -#include "FT0Workflow/RecoWorkflow.h" -#include "FT0Workflow/DigitReaderSpec.h" -#include "FT0Workflow/RecPointWriterSpec.h" -#include "FT0Workflow/ReconstructionSpec.h" -#include "FT0Workflow/FT0DataReaderDPLSpec.h" +#include "ZDCWorkflow/RecoWorkflow.h" +#include "ZDCWorkflow/DigitReaderSpec.h" +#include "ZDCWorkflow/ZDCRecoWriterDPLSpec.h" +#include "ZDCWorkflow/DigitRecoSpec.h" namespace o2 { @@ -27,10 +26,14 @@ framework::WorkflowSpec getRecoWorkflow(bool useMC, bool disableRootInp, bool di if (!disableRootInp) { specs.emplace_back(o2::zdc::getDigitReaderSpec(useMC)); } - specs.emplace_back(o2::zdc::getReconstructionSpec(useMC)); + specs.emplace_back(o2::zdc::getDigitRecoSpec()); if (!disableRootOut) { - specs.emplace_back(o2::zdc::getRecPointWriterSpec(useMC)); + specs.emplace_back(o2::zdc::getZDCRecoWriterDPLSpec()); } +// specs.emplace_back(o2::zdc::getReconstructionSpec(useMC)); +// if (!disableRootOut) { +// specs.emplace_back(o2::zdc::getRecPointWriterSpec(useMC)); +// } return specs; } diff --git a/Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx b/Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx index 8b0298b5759ca..0791b351f54c3 100644 --- a/Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx +++ b/Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx @@ -25,7 +25,8 @@ namespace zdc template using BranchDefinition = MakeRootTreeWriterSpec::BranchDefinition; -DataProcessorSpec getZDCRecoWriterDPLSpec(bool mctruth, bool simVersion) +// Unused arguments: bool mctruth, bool simVersion +DataProcessorSpec getZDCRecoWriterDPLSpec() { std::string writerName = "ZDCRecoWriter"; std::string fnameDef = "zdcreco.root"; diff --git a/Detectors/ZDC/workflow/src/zdc-reco-workflow.cxx b/Detectors/ZDC/workflow/src/zdc-reco-workflow.cxx new file mode 100644 index 0000000000000..80f589635e159 --- /dev/null +++ b/Detectors/ZDC/workflow/src/zdc-reco-workflow.cxx @@ -0,0 +1,50 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "ZDCWorkflow/RecoWorkflow.h" +#include "CommonUtils/ConfigurableParam.h" + +using namespace o2::framework; + +// ------------------------------------------------------------------ + +// we need to add workflow options before including Framework/runDataProcessing +void customize(std::vector& workflowOptions) +{ + // option allowing to set parameters + workflowOptions.push_back(ConfigParamSpec{ + "disable-mc", o2::framework::VariantType::Bool, false, {"disable MC propagation even if available"}}); + workflowOptions.push_back(ConfigParamSpec{ + "disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}); + workflowOptions.push_back(ConfigParamSpec{ + "disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}); + std::string keyvaluehelp("Semicolon separated key=value strings ..."); + workflowOptions.push_back(ConfigParamSpec{"configKeyValues", VariantType::String, "", {keyvaluehelp}}); +} + +// ------------------------------------------------------------------ + +#include "Framework/runDataProcessing.h" + +WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) +{ + LOG(INFO) << "WorkflowSpec defineDataProcessing"; + // Update the (declared) parameters if changed from the command line + o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); + // write the configuration used for the digitizer workflow + //o2::conf::ConfigurableParam::writeINI("o2tpcits-match-recoflow_configuration.ini"); + + auto useMC = !configcontext.options().get("disable-mc"); + auto disableRootInp = configcontext.options().get("disable-root-input"); + auto disableRootOut = configcontext.options().get("disable-root-output"); + + LOG(INFO) << "WorkflowSpec getRecoWorkflow useMC " << useMC; + return std::move(o2::zdc::getRecoWorkflow(useMC, disableRootInp, disableRootOut)); +} From f6006aa649b60c398efcc1f9a0c4ed9f702d191d Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 4 Jun 2021 17:28:55 +0200 Subject: [PATCH 016/770] Bugs in reco tree --- .../include/ZDCReconstruction/DigiReco.h | 20 ++++++----- Detectors/ZDC/reconstruction/src/DigiReco.cxx | 33 +++++++------------ .../include/ZDCWorkflow/DigitRecoSpec.h | 1 + Detectors/ZDC/workflow/src/DigitRecoSpec.cxx | 10 ++---- .../ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx | 6 ++-- 5 files changed, 29 insertions(+), 41 deletions(-) diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h index 3bd298d9fb025..1a0509daefee3 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h @@ -12,6 +12,7 @@ #include #include #include +#include "FairLogger.h" #include "ZDCBase/Constants.h" #include "ZDCSimulation/ZDCSimParam.h" #include "ZDCReconstruction/RecoParamZDC.h" @@ -34,15 +35,7 @@ class DigiReco { public: DigiReco() = default; - ~DigiReco() - { - if (mTreeDbg) { - mTDbg->Write(); - mTDbg.reset(); - mDbg->Close(); - mDbg.reset(); - } - } + ~DigiReco() = default; void init(); int process(const gsl::span& orbitdata, const gsl::span& bcdata, @@ -57,6 +50,15 @@ class DigiReco { mTreeDbg = state; } + void eor(){ + if (mTreeDbg) { + LOG(INFO) << "ZDC DigiReco: closing debug output"; + mTDbg->Write(); + mTDbg.reset(); + mDbg->Close(); + mDbg.reset(); + } + } void setModuleConfig(const ModuleConfig* moduleConfig) { mModuleConfig = moduleConfig; }; const ModuleConfig* getModuleConfig() { return mModuleConfig; }; diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index ae2cb3059a9f9..bdd025441177c 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -49,6 +49,7 @@ void DigiReco::init() if (mTreeDbg) { // Open debug file + LOG(INFO) << "ZDC DigiReco: opening debug output"; mDbg = std::make_unique("ZDCRecoDbg.root", "recreate"); mTDbg = std::make_unique("zdcr", "ZDCReco"); mTDbg->Branch("zdcr", "RecEventAux", &mRec); @@ -376,11 +377,13 @@ int DigiReco::reconstruct(int ibeg, int iend) } } - printf("%d FIRED: ", ibun); - for (int ich = 0; ich < NChannels; ich++) { - printf("%d", fired[ich]); - } - printf("\n"); + printf("%d FIRED ", ibun); + printf("ZNA:%d%d%d%d%d%d ZPA:%d%d%d%d%d%d ZEM:%d%d ZNC:%d%d%d%d%d%d ZPC:%d%d%d%d%d%d\n", + fired[IdZNAC], fired[IdZNA1], fired[IdZNA2], fired[IdZNA3], fired[IdZNA4], fired[IdZNASum], + fired[IdZPAC], fired[IdZPA1], fired[IdZPA2], fired[IdZPA3], fired[IdZPA4], fired[IdZPASum], + fired[IdZEM1], fired[IdZEM2], + fired[IdZNCC], fired[IdZNC1], fired[IdZNC2], fired[IdZNC3], fired[IdZNC4], fired[IdZNCSum], + fired[IdZPCC], fired[IdZPC1], fired[IdZPC2], fired[IdZPC3], fired[IdZPC4], fired[IdZPCSum]); for (int ich = 0; ich < NChannels; ich++) { // Check if the corresponding TDC is fired if (fired[ich]) { @@ -394,7 +397,7 @@ int DigiReco::reconstruct(int ibeg, int iend) // TODO: manage signal positioned across boundary sum += (pbun[ich] - float(mChData[ref].data[is])); } - printf("CH %d %s: %f\n", ich, ChannelNames[ich].data(), sum); + printf("CH %2d %s: %f\n", ich, ChannelNames[ich].data(), sum); rec.ezdc[ich] = sum; } } @@ -409,24 +412,11 @@ int DigiReco::reconstruct(int ibeg, int iend) void DigiReco::processTrigger(int itdc, int ibeg, int iend) { - LOG(INFO) << __func__ << "(itdc=" << itdc << "[" << ChannelNames[TDCSignal[itdc]] << "] ," << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; + LOG(DEBUG) << __func__ << "(itdc=" << itdc << "[" << ChannelNames[TDCSignal[itdc]] << "] ," << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; // Get reconstruction parameters auto& ropt = RecoParamZDC::Instance(); - // int chEnt = bcd.ref.getFirstEntry(); - // for (int ic = 0; ic < bcd.ref.getEntries(); ic++) { - // const auto& chd = zdcChData[chEnt++]; - // chd.print(); - // auto bc=bcd.ir.bc; - // auto orbit=bcd.ir.orbit; - // for(int is=0; isGetN(); - // gr[chd.id]->SetPoint(ip,3564.*orbit+bc+is/12.,myval); - // } - // } - int nbun = iend - ibeg + 1; int maxs2 = NTimeBinsPerBC * nbun - 1; int shift = ropt.tsh[itdc]; @@ -461,8 +451,7 @@ void DigiReco::processTrigger(int itdc, int ibeg, int iend) // Fired bit is assigned to the second sample, i.e. to the one that can identify the // signal peak position mReco[b2].fired[itdc] |= mMask[s2]; - //LOG(INFO) << itdc << " Fired @ " << mReco[b2].ir.orbit << "." << mReco[b2].ir.bc << " " << b2 - ibeg << "." << s2 << "=" << NTimeBinsPerBC * (b2 - ibeg) + s2; - LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " Fired @ " << mReco[b2].ir.orbit << "." << mReco[b2].ir.bc << ".s" << s2; + LOG(DEBUG) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " Fired @ " << mReco[b2].ir.orbit << "." << mReco[b2].ir.bc << ".s" << s2; } } if (is2 >= shift) { diff --git a/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h b/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h index 5cdf0c71e2cf6..a018f048cbf4d 100644 --- a/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h +++ b/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h @@ -15,6 +15,7 @@ #ifndef O2_ZDC_DIGITRECO_SPEC #define O2_ZDC_DIGITRECO_SPEC +#include "FairLogger.h" #include "Framework/DataProcessorSpec.h" #include "Framework/Task.h" #include "ZDCReconstruction/DigiReco.h" diff --git a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx index 99915cce9f08e..a931194a50d26 100644 --- a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx +++ b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx @@ -53,7 +53,6 @@ void DigitRecoSpec::run(ProcessingContext& pc) mInitialized = true; // Initialization from CCDB std::string ccdbHost = "http://ccdb-test.cern.ch:8080"; - auto& mgr = o2::ccdb::BasicCCDBManager::instance(); mgr.setURL(ccdbHost); long timeStamp = 0; @@ -97,10 +96,6 @@ void DigitRecoSpec::run(ProcessingContext& pc) zdc_ip->end_int[ich] = end; } mDR.setIntegrationParam(zdc_ip); - - - - mDR.init(); } auto cput = mTimer.CpuTime(); @@ -113,8 +108,7 @@ void DigitRecoSpec::run(ProcessingContext& pc) const std::vector& recAux = mDR.getReco(); RecEvent recEvent; - - LOG(INFO) << "BC in recAux " << recAux.size(); + LOG(INFO) << "BC processed during reconstruction " << recAux.size(); for (auto reca : recAux) { int32_t ne = reca.ezdc.size(); int32_t nt = 0; @@ -140,7 +134,6 @@ void DigitRecoSpec::run(ProcessingContext& pc) printf("Orbit %9u bc %4u ntdc %2d ne %2d\n", reca.ir.orbit, reca.ir.bc, nt, ne); } } - pc.outputs().snapshot(Output{"ZDC", "BCREC", 0, Lifetime::Timeframe}, recEvent.mRecBC); pc.outputs().snapshot(Output{"ZDC", "ENERGY", 0, Lifetime::Timeframe}, recEvent.mEnergy); pc.outputs().snapshot(Output{"ZDC", "TDCDATA", 0, Lifetime::Timeframe}, recEvent.mTDCData); @@ -150,6 +143,7 @@ void DigitRecoSpec::run(ProcessingContext& pc) void DigitRecoSpec::endOfStream(EndOfStreamContext& ec) { + mDR.eor(); LOGF(INFO, "ZDC Reconstruction total timing: Cpu: %.3e Real: %.3e s in %d slots", mTimer.CpuTime(), mTimer.RealTime(), mTimer.Counter() - 1); } diff --git a/Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx b/Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx index 0791b351f54c3..5a572050e3498 100644 --- a/Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx +++ b/Detectors/ZDC/workflow/src/ZDCRecoWriterDPLSpec.cxx @@ -14,6 +14,8 @@ #include "DPLUtils/MakeRootTreeWriterSpec.h" #include "DataFormatsZDC/BCRecData.h" +#include "DataFormatsZDC/ZDCEnergy.h" +#include "DataFormatsZDC/ZDCTDCData.h" #include "ZDCWorkflow/ZDCRecoWriterDPLSpec.h" using namespace o2::framework; @@ -37,8 +39,8 @@ DataProcessorSpec getZDCRecoWriterDPLSpec() fnameDef.data(), "o2rec", BranchDefinition>{InputSpec{"bcrec", "ZDC", "BCREC"}, "ZDCRecBC"}, - BranchDefinition>{InputSpec{"energy", "ZDC", "ENERGY"}, "ZDCRecE"}, - BranchDefinition>{InputSpec{"tdcdata", "ZDC", "TDCDATA"}, "ZDCRecTDC"})(); + BranchDefinition>{InputSpec{"energy", "ZDC", "ENERGY"}, "ZDCRecE"}, + BranchDefinition>{InputSpec{"tdcdata", "ZDC", "TDCDATA"}, "ZDCRecTDC"})(); } } // namespace zdc From efd3a0c364853d4fd80c29b0ba459a97eb75758a Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 4 Jun 2021 20:43:11 +0200 Subject: [PATCH 017/770] Corrected bug in Energy decoding --- .../Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h index 975dfc4327e8d..ca402edc26aef 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/ZDCEnergy.h @@ -31,6 +31,10 @@ struct ZDCEnergy { ZDCEnergy() = default; ZDCEnergy(uint8_t ch, float energy) + { + set(ch, energy); + } + inline void set(uint8_t ch, float energy) { float escaled = (energy + EnergyOffset) / EnergyUnit; value = 0; @@ -48,7 +52,7 @@ struct ZDCEnergy { } float energy() const { - return (float(value & EnergyMask) - EnergyOffset) * EnergyUnit; + return float(value & EnergyMask) * EnergyUnit - EnergyOffset; } uint8_t ch() const { From e763646b05b4a0bc551ef9a0a14031dfac21a007 Mon Sep 17 00:00:00 2001 From: ALICE Action Bot Date: Fri, 4 Jun 2021 18:44:19 +0000 Subject: [PATCH 018/770] Please consider the following formatting changes --- .../reconstruction/include/ZDCReconstruction/DigiReco.h | 3 ++- Detectors/ZDC/workflow/src/DigitRecoSpec.cxx | 4 ++-- Detectors/ZDC/workflow/src/RecoWorkflow.cxx | 8 ++++---- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h index 1a0509daefee3..7d4b8ac57b2b1 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h @@ -50,7 +50,8 @@ class DigiReco { mTreeDbg = state; } - void eor(){ + void eor() + { if (mTreeDbg) { LOG(INFO) << "ZDC DigiReco: closing debug output"; mTDbg->Write(); diff --git a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx index a931194a50d26..e17c8d1fca8cc 100644 --- a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx +++ b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx @@ -79,13 +79,13 @@ void DigitRecoSpec::run(ProcessingContext& pc) mDR.setIntegrationParam(integrationParam); mDR.setDebugOutput(); // TDC - auto *zdc_tdcp = new o2::zdc::ZDCTDCParam(); + auto* zdc_tdcp = new o2::zdc::ZDCTDCParam(); for (Int_t itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { zdc_tdcp->setShift(itdc, 14.5); } mDR.setTDCParam(zdc_tdcp); - auto *zdc_ip = new o2::zdc::ZDCIntegrationParam(); + auto* zdc_ip = new o2::zdc::ZDCIntegrationParam(); int beg = 6; int end = 8; int beg_ped = -1; diff --git a/Detectors/ZDC/workflow/src/RecoWorkflow.cxx b/Detectors/ZDC/workflow/src/RecoWorkflow.cxx index 18bec0781e0dd..81a47a97d7193 100644 --- a/Detectors/ZDC/workflow/src/RecoWorkflow.cxx +++ b/Detectors/ZDC/workflow/src/RecoWorkflow.cxx @@ -30,10 +30,10 @@ framework::WorkflowSpec getRecoWorkflow(bool useMC, bool disableRootInp, bool di if (!disableRootOut) { specs.emplace_back(o2::zdc::getZDCRecoWriterDPLSpec()); } -// specs.emplace_back(o2::zdc::getReconstructionSpec(useMC)); -// if (!disableRootOut) { -// specs.emplace_back(o2::zdc::getRecPointWriterSpec(useMC)); -// } + // specs.emplace_back(o2::zdc::getReconstructionSpec(useMC)); + // if (!disableRootOut) { + // specs.emplace_back(o2::zdc::getRecPointWriterSpec(useMC)); + // } return specs; } From 5ae1cd3ada4cee0993811fbc9daf5ee35fc47fc0 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Mon, 7 Jun 2021 16:09:23 +0200 Subject: [PATCH 019/770] TDC calibration object --- Detectors/ZDC/macro/CMakeLists.txt | 5 ++ Detectors/ZDC/macro/CreateIntegrationParam.C | 58 ++++++++++--------- Detectors/ZDC/macro/CreateZDCTDCParam.C | 50 ++++++++++++++++ Detectors/ZDC/reconstruction/src/DigiReco.cxx | 3 + .../src/ZDCReconstructionLinkDef.h | 2 + Detectors/ZDC/workflow/src/DigitRecoSpec.cxx | 38 +++++------- 6 files changed, 107 insertions(+), 49 deletions(-) create mode 100644 Detectors/ZDC/macro/CreateZDCTDCParam.C diff --git a/Detectors/ZDC/macro/CMakeLists.txt b/Detectors/ZDC/macro/CMakeLists.txt index 23143ec9aad44..8da744c40e588 100644 --- a/Detectors/ZDC/macro/CMakeLists.txt +++ b/Detectors/ZDC/macro/CMakeLists.txt @@ -25,3 +25,8 @@ o2_add_test_root_macro(CreateIntegrationParam.C PUBLIC_LINK_LIBRARIES O2::ZDCBase O2::ZDCReconstruction O2::SimulationDataFormat O2::CCDB LABELS zdc) + +o2_add_test_root_macro(CreateZDCTDCParam.C + PUBLIC_LINK_LIBRARIES O2::ZDCBase O2::ZDCReconstruction + O2::SimulationDataFormat O2::CCDB + LABELS zdc) diff --git a/Detectors/ZDC/macro/CreateIntegrationParam.C b/Detectors/ZDC/macro/CreateIntegrationParam.C index 91bc4cfedef03..c3408f5f9798d 100644 --- a/Detectors/ZDC/macro/CreateIntegrationParam.C +++ b/Detectors/ZDC/macro/CreateIntegrationParam.C @@ -29,39 +29,45 @@ void CreateIntegrationParam(long tmin = 0, long tmax = -1, ZDCIntegrationParam conf; + int beg_sig = 6; + int end_sig = 8; + int beg_ped = -12; + int end_ped = -8; + // Integration limits for all signals // Values should be in range -12..11 // Channel ID, signal begin, end, pedestal begin, end - conf.setIntegration(IdZNAC, 5, 9, -12, -8); - conf.setIntegration(IdZNA1, 5, 9, -12, -8); - conf.setIntegration(IdZNA2, 5, 9, -12, -8); - conf.setIntegration(IdZNA3, 5, 9, -12, -8); - conf.setIntegration(IdZNA4, 5, 9, -12, -8); - conf.setIntegration(IdZNASum, 5, 9, -12, -8); + + conf.setIntegration(IdZNAC, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZNA1, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZNA2, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZNA3, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZNA4, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZNASum, beg_sig, end_sig, beg_ped, end_ped); // - conf.setIntegration(IdZPAC, 5, 9, -12, -8); - conf.setIntegration(IdZPA1, 5, 9, -12, -8); - conf.setIntegration(IdZPA2, 5, 9, -12, -8); - conf.setIntegration(IdZPA3, 5, 9, -12, -8); - conf.setIntegration(IdZPA4, 5, 9, -12, -8); - conf.setIntegration(IdZPASum, 5, 9, -12, -8); + conf.setIntegration(IdZPAC, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZPA1, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZPA2, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZPA3, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZPA4, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZPASum, beg_sig, end_sig, beg_ped, end_ped); // - conf.setIntegration(IdZEM1, 5, 9, -12, -8); - conf.setIntegration(IdZEM2, 5, 9, -12, -8); + conf.setIntegration(IdZEM1, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZEM2, beg_sig, end_sig, beg_ped, end_ped); // - conf.setIntegration(IdZNCC, 5, 9, -12, -8); - conf.setIntegration(IdZNC1, 5, 9, -12, -8); - conf.setIntegration(IdZNC2, 5, 9, -12, -8); - conf.setIntegration(IdZNC3, 5, 9, -12, -8); - conf.setIntegration(IdZNC4, 5, 9, -12, -8); - conf.setIntegration(IdZNCSum, 5, 9, -12, -8); + conf.setIntegration(IdZNCC, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZNC1, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZNC2, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZNC3, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZNC4, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZNCSum, beg_sig, end_sig, beg_ped, end_ped); // - conf.setIntegration(IdZPCC, 5, 9, -12, -8); - conf.setIntegration(IdZPC1, 5, 9, -12, -8); - conf.setIntegration(IdZPC2, 5, 9, -12, -8); - conf.setIntegration(IdZPC3, 5, 9, -12, -8); - conf.setIntegration(IdZPC4, 5, 9, -12, -8); - conf.setIntegration(IdZPCSum, 5, 9, -12, -8); + conf.setIntegration(IdZPCC, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZPC1, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZPC2, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZPC3, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZPC4, beg_sig, end_sig, beg_ped, end_ped); + conf.setIntegration(IdZPCSum, beg_sig, end_sig, beg_ped, end_ped); conf.print(); diff --git a/Detectors/ZDC/macro/CreateZDCTDCParam.C b/Detectors/ZDC/macro/CreateZDCTDCParam.C new file mode 100644 index 0000000000000..4c919f6f729a2 --- /dev/null +++ b/Detectors/ZDC/macro/CreateZDCTDCParam.C @@ -0,0 +1,50 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#if !defined(__CLING__) || defined(__ROOTCLING__) +#include "FairLogger.h" +#include "CCDB/CcdbApi.h" +#include +#include +#include +#include +#endif + +#include "ZDCBase/Constants.h" +#include "ZDCReconstruction/ZDCTDCParam.h" + +using namespace std; + +void CreateZDCTDCParam(long tmin = 0, long tmax = -1, std::string ccdbHost = "http://ccdb-test.cern.ch:8080") +{ + o2::zdc::ZDCTDCParam conf; + float def_shift = 14.5; + // TODO: extract shift from TDC spectra + conf.setShift(o2::zdc::TDCZNAC, def_shift); + conf.setShift(o2::zdc::TDCZNAS, def_shift); + conf.setShift(o2::zdc::TDCZPAC, def_shift); + conf.setShift(o2::zdc::TDCZPAS, def_shift); + conf.setShift(o2::zdc::TDCZEM1, def_shift); + conf.setShift(o2::zdc::TDCZEM2, def_shift); + conf.setShift(o2::zdc::TDCZNCC, def_shift); + conf.setShift(o2::zdc::TDCZNCS, def_shift); + conf.setShift(o2::zdc::TDCZPCC, def_shift); + conf.setShift(o2::zdc::TDCZPCS, def_shift); + + conf.print(); + + o2::ccdb::CcdbApi api; + map metadata; // can be empty + api.init(ccdbHost.c_str()); // or http://localhost:8080 for a local installation + // store abitrary user object in strongly typed manner + api.storeAsTFileAny(&conf, o2::zdc::CCDBPathTDCCalib, metadata, tmin, tmax); + + // return conf; +} diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index bdd025441177c..ea4e6de6cb51c 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -104,6 +104,7 @@ void DigiReco::init() tdc_shift[itdc] = val; LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " shift= " << tdc_shift[itdc] << " i.s. = " << val * FTDCVal << " ns"; } + // TDC search zone // TODO: override with configuration object for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { @@ -149,6 +150,8 @@ void DigiReco::init() } LOG(INFO) << ChannelNames[ich] << " integration: signal=[" << ropt.beg_int[ich] << ":" << ropt.end_int[ich] << "] pedestal=[" << ropt.beg_ped_int[ich] << ":" << ropt.end_ped_int[ich] << "]"; } + + // TODO: Energy calibration } int DigiReco::process(const gsl::span& orbitdata, const gsl::span& bcdata, const gsl::span& chdata) diff --git a/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h b/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h index 71519a02a652e..6f6c418b69ed8 100644 --- a/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h +++ b/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h @@ -14,4 +14,6 @@ #pragma link off all classes; #pragma link off all functions; +#pragma link C++ class o2::zdc::ZDCIntegrationParam + ; + #endif diff --git a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx index e17c8d1fca8cc..31ba300a230d8 100644 --- a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx +++ b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx @@ -60,42 +60,34 @@ void DigitRecoSpec::run(ProcessingContext& pc) return; } mgr.setTimestamp(timeStamp); - auto* moduleConfig = - mgr.get(o2::zdc::CCDBPathConfigModule); + auto* moduleConfig = mgr.get(o2::zdc::CCDBPathConfigModule); if (!moduleConfig) { LOG(FATAL) << "Missing configuration object"; return; } LOG(INFO) << "Loaded module configuration for timestamp " << timeStamp; - // Get Reconstruction parameters - auto* integrationParam = - mgr.get(o2::zdc::CCDBPathConfigIntegration); + // Integration parameters + auto* integrationParam = mgr.get(o2::zdc::CCDBPathConfigIntegration); if (!integrationParam) { LOG(FATAL) << "Missing ZDCIntegrationParam object"; return; } + + // TDC centering + auto* tdcParam = mgr.get(o2::zdc::CCDBPathTDCCalib); + if (!tdcParam) { + LOG(FATAL) << "Missing ZDCTDCParam calibration object"; + return; + } + mDR.setModuleConfig(moduleConfig); mDR.setIntegrationParam(integrationParam); + mDR.setTDCParam(tdcParam); + + // TODO: conditional debug output mDR.setDebugOutput(); - // TDC - auto* zdc_tdcp = new o2::zdc::ZDCTDCParam(); - for (Int_t itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { - zdc_tdcp->setShift(itdc, 14.5); - } - mDR.setTDCParam(zdc_tdcp); - - auto* zdc_ip = new o2::zdc::ZDCIntegrationParam(); - int beg = 6; - int end = 8; - int beg_ped = -1; - int end_ped = -1; - for (Int_t ich = 0; ich < o2::zdc::NChannels; ich++) { - // zdc_ip->setIntegration(ich, beg, end, beg_ped, end_ped); - zdc_ip->beg_int[ich] = beg; - zdc_ip->end_int[ich] = end; - } - mDR.setIntegrationParam(zdc_ip); + mDR.init(); } auto cput = mTimer.CpuTime(); From 479a6c459d2cb250d9b2f803ab6fa8b21d717500 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Tue, 8 Jun 2021 10:27:15 +0200 Subject: [PATCH 020/770] ccdbHost for reconstruction + bux fixes --- .../Detectors/ZDC/src/DataFormatsZDCLinkDef.h | 2 ++ .../src/ZDCIntegrationParam.cxx | 29 ++++++++++++++----- .../src/ZDCReconstructionLinkDef.h | 1 + .../include/ZDCWorkflow/DigitRecoSpec.h | 7 +++-- .../include/ZDCWorkflow/RecoWorkflow.h | 2 +- Detectors/ZDC/workflow/src/DigitRecoSpec.cxx | 23 +++++++++++---- Detectors/ZDC/workflow/src/RecoWorkflow.cxx | 4 +-- .../ZDC/workflow/src/zdc-reco-workflow.cxx | 16 +++++----- 8 files changed, 58 insertions(+), 26 deletions(-) diff --git a/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h b/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h index d8d92119a67f7..e19ae7019d8ef 100644 --- a/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h +++ b/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h @@ -41,6 +41,8 @@ #pragma link C++ class std::vector < o2::zdc::OrbitRawData> + ; #pragma link C++ class std::vector < o2::zdc::OrbitRecData> + ; +#pragma link C++ class std::vector < uint16_t > + ; + #pragma link C++ struct o2::zdc::CTFHeader + ; #pragma link C++ struct o2::zdc::CTF + ; #pragma link C++ class o2::ctf::EncodedBlocks < o2::zdc::CTFHeader, 12, uint32_t> + ; diff --git a/Detectors/ZDC/reconstruction/src/ZDCIntegrationParam.cxx b/Detectors/ZDC/reconstruction/src/ZDCIntegrationParam.cxx index 5c8ebb05ffb4e..f94f3504a957a 100644 --- a/Detectors/ZDC/reconstruction/src/ZDCIntegrationParam.cxx +++ b/Detectors/ZDC/reconstruction/src/ZDCIntegrationParam.cxx @@ -15,21 +15,34 @@ using namespace o2::zdc; void ZDCIntegrationParam::setIntegration(uint32_t ich, int beg, int end, int beg_ped, int end_ped) { + int sig_l = 0; + int sig_h = NTimeBinsPerBC - 1; + int ped_l = -NTimeBinsPerBC; + int ped_h = NTimeBinsPerBC - 1; + if (ich >= 0 && ich < NChannels) { - if (beg < 0 || beg >= NTimeBinsPerBC) { - LOG(FATAL) << "Integration start = " << beg << " for signal " << ich << " (" << ChannelNames[ich] << ") not in allowed range [0-" << NTimeBinsPerBC - 1; + if (beg < sig_l || beg > sig_h) { + LOG(FATAL) << "Integration start = " << beg << " for signal " << ich << " (" << ChannelNames[ich] << ") not in allowed range [" << sig_l << "-" << sig_h << "]"; + return; + } + if (end < sig_l || end > sig_h) { + LOG(FATAL) << "Integration end = " << beg << " for signal " << ich << " (" << ChannelNames[ich] << ") not in allowed range [" << sig_l << "-" << sig_h << "]"; + return; + } + if (end < beg) { + LOG(FATAL) << "Inconsistent integration range for signal " << ich << " (" << ChannelNames[ich] << "): [" << beg << "-" << end << "]"; return; } - if (end < 0 || end >= NTimeBinsPerBC) { - LOG(FATAL) << "Integration end = " << end << " for signal " << ich << " (" << ChannelNames[ich] << ") not in allowed range [0-" << NTimeBinsPerBC - 1; + if (beg_ped < ped_l || beg_ped > ped_h) { + LOG(FATAL) << "Pedestal integration start = " << beg_ped << " for signal " << ich << " (" << ChannelNames[ich] << ") not in allowed range [" << ped_l << "-" << ped_h << "]"; return; } - if (beg_ped < 0 || beg_ped >= NTimeBinsPerBC) { - LOG(FATAL) << "Pedestal integration start = " << beg_ped << " for signal " << ich << " (" << ChannelNames[ich] << ") not in allowed range [0-" << NTimeBinsPerBC - 1; + if (end_ped < ped_l || end_ped > ped_h) { + LOG(FATAL) << "Pedestal integration end = " << end_ped << " for signal " << ich << " (" << ChannelNames[ich] << ") not in allowed range [" << ped_l << "-" << ped_h << "]"; return; } - if (beg < 0 || beg >= NTimeBinsPerBC) { - LOG(FATAL) << "Pedestal integration end = " << end_ped << " for signal " << ich << " (" << ChannelNames[ich] << ") not in allowed range [0-" << NTimeBinsPerBC - 1; + if (end_ped < beg_ped) { + LOG(FATAL) << "Inconsistent integration range for pedestal " << ich << " (" << ChannelNames[ich] << "): [" << beg_ped << "-" << end_ped << "]"; return; } beg_int[ich] = beg; diff --git a/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h b/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h index 6f6c418b69ed8..25a6e79ce1a5e 100644 --- a/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h +++ b/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h @@ -15,5 +15,6 @@ #pragma link off all functions; #pragma link C++ class o2::zdc::ZDCIntegrationParam + ; +#pragma link C++ class o2::zdc::ZDCTDCParam + ; #endif diff --git a/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h b/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h index a018f048cbf4d..cb1cfef9b5f7e 100644 --- a/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h +++ b/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h @@ -30,6 +30,7 @@ class DigitRecoSpec : public o2::framework::Task { public: DigitRecoSpec(); + DigitRecoSpec(const bool debugOut, const std::string& ccdbURL); ~DigitRecoSpec() override = default; void run(o2::framework::ProcessingContext& pc) final; void init(o2::framework::InitContext& ic) final; @@ -37,12 +38,14 @@ class DigitRecoSpec : public o2::framework::Task private: DigiReco mDR; - TStopwatch mTimer; + std::string mccdbHost; + bool mDebugOut = false; bool mInitialized = false; + TStopwatch mTimer; }; /// create a processor spec -framework::DataProcessorSpec getDigitRecoSpec(); +framework::DataProcessorSpec getDigitRecoSpec(const bool enableDebugOut, const std::string ccdbURL); } // namespace zdc } // namespace o2 diff --git a/Detectors/ZDC/workflow/include/ZDCWorkflow/RecoWorkflow.h b/Detectors/ZDC/workflow/include/ZDCWorkflow/RecoWorkflow.h index 919c6b4e492b1..9158f067ef52d 100644 --- a/Detectors/ZDC/workflow/include/ZDCWorkflow/RecoWorkflow.h +++ b/Detectors/ZDC/workflow/include/ZDCWorkflow/RecoWorkflow.h @@ -19,7 +19,7 @@ namespace o2 { namespace zdc { -framework::WorkflowSpec getRecoWorkflow(bool useMC, bool disableRootInp, bool disableRootOut); +framework::WorkflowSpec getRecoWorkflow(bool useMC, bool disableRootInp, bool disableRootOut, bool enableDebugOut, std::string ccdbURL); } // namespace zdc } // namespace o2 #endif diff --git a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx index 31ba300a230d8..43652ea59e9c6 100644 --- a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx +++ b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx @@ -40,6 +40,19 @@ DigitRecoSpec::DigitRecoSpec() { mTimer.Stop(); mTimer.Reset(); + if(mccdbHost.empty()){ + mccdbHost = "http://ccdb-test.cern.ch:8080"; + } +} + +DigitRecoSpec::DigitRecoSpec(const bool debugOut, const std::string& ccdbURL) + : mDebugOut(debugOut), mccdbHost(ccdbURL) +{ + if(mccdbHost.empty()){ + mccdbHost = "http://ccdb-test.cern.ch:8080"; + } + mTimer.Stop(); + mTimer.Reset(); } void DigitRecoSpec::init(o2::framework::InitContext& ic) @@ -52,9 +65,8 @@ void DigitRecoSpec::run(ProcessingContext& pc) if (!mInitialized) { mInitialized = true; // Initialization from CCDB - std::string ccdbHost = "http://ccdb-test.cern.ch:8080"; auto& mgr = o2::ccdb::BasicCCDBManager::instance(); - mgr.setURL(ccdbHost); + mgr.setURL(mccdbHost); long timeStamp = 0; if (timeStamp == mgr.getTimestamp()) { return; @@ -85,8 +97,7 @@ void DigitRecoSpec::run(ProcessingContext& pc) mDR.setIntegrationParam(integrationParam); mDR.setTDCParam(tdcParam); - // TODO: conditional debug output - mDR.setDebugOutput(); + if(mDebugOut)mDR.setDebugOutput(); mDR.init(); } @@ -140,7 +151,7 @@ void DigitRecoSpec::endOfStream(EndOfStreamContext& ec) mTimer.CpuTime(), mTimer.RealTime(), mTimer.Counter() - 1); } -DataProcessorSpec getDigitRecoSpec() +DataProcessorSpec getDigitRecoSpec(const bool enableDebugOut=false, const std::string ccdbURL="") { std::vector inputs; inputs.emplace_back("trig", "ZDC", "DIGITSBC", 0, Lifetime::Timeframe); @@ -156,7 +167,7 @@ DataProcessorSpec getDigitRecoSpec() "zdc-digi-reco", inputs, outputs, - AlgorithmSpec{adaptFromTask()}}; + AlgorithmSpec{adaptFromTask(enableDebugOut, ccdbURL)}}; } } // namespace zdc diff --git a/Detectors/ZDC/workflow/src/RecoWorkflow.cxx b/Detectors/ZDC/workflow/src/RecoWorkflow.cxx index 81a47a97d7193..de2ae41317f47 100644 --- a/Detectors/ZDC/workflow/src/RecoWorkflow.cxx +++ b/Detectors/ZDC/workflow/src/RecoWorkflow.cxx @@ -20,13 +20,13 @@ namespace o2 namespace zdc { -framework::WorkflowSpec getRecoWorkflow(bool useMC, bool disableRootInp, bool disableRootOut) +framework::WorkflowSpec getRecoWorkflow(const bool useMC, const bool disableRootInp, const bool disableRootOut, const bool enableDebugOut, const std::string ccdbURL) { framework::WorkflowSpec specs; if (!disableRootInp) { specs.emplace_back(o2::zdc::getDigitReaderSpec(useMC)); } - specs.emplace_back(o2::zdc::getDigitRecoSpec()); + specs.emplace_back(o2::zdc::getDigitRecoSpec(enableDebugOut, ccdbURL)); if (!disableRootOut) { specs.emplace_back(o2::zdc::getZDCRecoWriterDPLSpec()); } diff --git a/Detectors/ZDC/workflow/src/zdc-reco-workflow.cxx b/Detectors/ZDC/workflow/src/zdc-reco-workflow.cxx index 80f589635e159..54635dfb662e4 100644 --- a/Detectors/ZDC/workflow/src/zdc-reco-workflow.cxx +++ b/Detectors/ZDC/workflow/src/zdc-reco-workflow.cxx @@ -19,12 +19,12 @@ using namespace o2::framework; void customize(std::vector& workflowOptions) { // option allowing to set parameters - workflowOptions.push_back(ConfigParamSpec{ - "disable-mc", o2::framework::VariantType::Bool, false, {"disable MC propagation even if available"}}); - workflowOptions.push_back(ConfigParamSpec{ - "disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}); - workflowOptions.push_back(ConfigParamSpec{ - "disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}); + workflowOptions.push_back(ConfigParamSpec{"disable-mc", o2::framework::VariantType::Bool, false, {"disable MC propagation even if available"}}); + workflowOptions.push_back(ConfigParamSpec{"disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}); + workflowOptions.push_back(ConfigParamSpec{"disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}); + workflowOptions.push_back(ConfigParamSpec{"enable-debug-output", VariantType::Bool, false, {"enable debug tree output"}}); + workflowOptions.push_back(ConfigParamSpec{"ccdb-url", VariantType::String, "http://ccdb-test.cern.ch:8080", {"url of CCDB"}}); + std::string keyvaluehelp("Semicolon separated key=value strings ..."); workflowOptions.push_back(ConfigParamSpec{"configKeyValues", VariantType::String, "", {keyvaluehelp}}); } @@ -44,7 +44,9 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) auto useMC = !configcontext.options().get("disable-mc"); auto disableRootInp = configcontext.options().get("disable-root-input"); auto disableRootOut = configcontext.options().get("disable-root-output"); + auto enableDebugOut = configcontext.options().get("enable-debug-output"); + auto ccdbURL = configcontext.options().get("ccdb-url"); LOG(INFO) << "WorkflowSpec getRecoWorkflow useMC " << useMC; - return std::move(o2::zdc::getRecoWorkflow(useMC, disableRootInp, disableRootOut)); + return std::move(o2::zdc::getRecoWorkflow(useMC, disableRootInp, disableRootOut, enableDebugOut, ccdbURL)); } From ad16d33a4bc0f60f4279e737a35ddd7c632018e1 Mon Sep 17 00:00:00 2001 From: ALICE Action Bot Date: Tue, 8 Jun 2021 08:28:23 +0000 Subject: [PATCH 021/770] Please consider the following formatting changes --- Detectors/ZDC/workflow/src/DigitRecoSpec.cxx | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx index 43652ea59e9c6..7698528128ba9 100644 --- a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx +++ b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx @@ -40,7 +40,7 @@ DigitRecoSpec::DigitRecoSpec() { mTimer.Stop(); mTimer.Reset(); - if(mccdbHost.empty()){ + if (mccdbHost.empty()) { mccdbHost = "http://ccdb-test.cern.ch:8080"; } } @@ -48,7 +48,7 @@ DigitRecoSpec::DigitRecoSpec() DigitRecoSpec::DigitRecoSpec(const bool debugOut, const std::string& ccdbURL) : mDebugOut(debugOut), mccdbHost(ccdbURL) { - if(mccdbHost.empty()){ + if (mccdbHost.empty()) { mccdbHost = "http://ccdb-test.cern.ch:8080"; } mTimer.Stop(); @@ -97,7 +97,8 @@ void DigitRecoSpec::run(ProcessingContext& pc) mDR.setIntegrationParam(integrationParam); mDR.setTDCParam(tdcParam); - if(mDebugOut)mDR.setDebugOutput(); + if (mDebugOut) + mDR.setDebugOutput(); mDR.init(); } @@ -151,7 +152,7 @@ void DigitRecoSpec::endOfStream(EndOfStreamContext& ec) mTimer.CpuTime(), mTimer.RealTime(), mTimer.Counter() - 1); } -DataProcessorSpec getDigitRecoSpec(const bool enableDebugOut=false, const std::string ccdbURL="") +DataProcessorSpec getDigitRecoSpec(const bool enableDebugOut = false, const std::string ccdbURL = "") { std::vector inputs; inputs.emplace_back("trig", "ZDC", "DIGITSBC", 0, Lifetime::Timeframe); From 04b41bf8a683871829071b4e02e213ea3c3aa4bb Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Tue, 8 Jun 2021 11:45:32 +0200 Subject: [PATCH 022/770] Correcting whitespaces --- Detectors/ZDC/reconstruction/CMakeLists.txt | 12 +++++------ Detectors/ZDC/workflow/CMakeLists.txt | 24 ++++++++++----------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/Detectors/ZDC/reconstruction/CMakeLists.txt b/Detectors/ZDC/reconstruction/CMakeLists.txt index 4561545efb4c6..14e14009817a6 100644 --- a/Detectors/ZDC/reconstruction/CMakeLists.txt +++ b/Detectors/ZDC/reconstruction/CMakeLists.txt @@ -10,14 +10,14 @@ o2_add_library(ZDCReconstruction SOURCES src/CTFCoder.cxx - src/CTFHelper.cxx - src/DigiReco.cxx - src/RecoParamZDC.cxx - src/ZDCTDCParam.cxx - src/ZDCIntegrationParam.cxx + src/CTFHelper.cxx + src/DigiReco.cxx + src/RecoParamZDC.cxx + src/ZDCTDCParam.cxx + src/ZDCIntegrationParam.cxx PUBLIC_LINK_LIBRARIES O2::ZDCBase O2::DataFormatsZDC - O2::ZDCSimulation + O2::ZDCSimulation O2::DetectorsRaw AliceO2::InfoLogger O2::rANS diff --git a/Detectors/ZDC/workflow/CMakeLists.txt b/Detectors/ZDC/workflow/CMakeLists.txt index a4d9aff4f6485..f96e0155bf277 100644 --- a/Detectors/ZDC/workflow/CMakeLists.txt +++ b/Detectors/ZDC/workflow/CMakeLists.txt @@ -10,27 +10,27 @@ o2_add_library(ZDCWorkflow SOURCES src/DigitReaderSpec.cxx - src/EntropyEncoderSpec.cxx - src/EntropyDecoderSpec.cxx + src/EntropyEncoderSpec.cxx + src/EntropyDecoderSpec.cxx src/ZDCDataReaderDPLSpec.cxx - src/ZDCDigitWriterDPLSpec.cxx - src/ZDCRecoWriterDPLSpec.cxx - src/RecoWorkflow.cxx - src/DigitRecoSpec.cxx - src/DigitReaderSpec.cxx - PUBLIC_LINK_LIBRARIES O2::Framework + src/ZDCDigitWriterDPLSpec.cxx + src/ZDCRecoWriterDPLSpec.cxx + src/RecoWorkflow.cxx + src/DigitRecoSpec.cxx + src/DigitReaderSpec.cxx + PUBLIC_LINK_LIBRARIES O2::Framework O2::DataFormatsZDC O2::ZDCRaw - O2::SimulationDataFormat + O2::SimulationDataFormat O2::DPLUtils - O2::ZDCReconstruction - O2::DataFormatsZDC) + O2::ZDCReconstruction + O2::DataFormatsZDC) o2_add_executable(raw2digits COMPONENT_NAME zdc SOURCES src/o2-zdc-raw2digits.cxx PUBLIC_LINK_LIBRARIES O2::ZDCWorkflow) - + o2_add_executable(entropy-encoder-workflow COMPONENT_NAME zdc SOURCES src/entropy-encoder-workflow.cxx From bd7e8bd840800411d61fc147fd88e850bfd58401 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Tue, 8 Jun 2021 11:55:54 +0200 Subject: [PATCH 023/770] Correcting whitespaces --- DataFormats/Detectors/ZDC/CMakeLists.txt | 14 +++++++------- Detectors/ZDC/workflow/CMakeLists.txt | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/DataFormats/Detectors/ZDC/CMakeLists.txt b/DataFormats/Detectors/ZDC/CMakeLists.txt index b0b19cba80cdb..e739ee16461e8 100644 --- a/DataFormats/Detectors/ZDC/CMakeLists.txt +++ b/DataFormats/Detectors/ZDC/CMakeLists.txt @@ -10,8 +10,8 @@ o2_add_library(DataFormatsZDC SOURCES src/ChannelData.cxx src/BCData.cxx src/BCRecData.cxx src/RecEvent.cxx src/RecEventAux.cxx src/RawEventData.cxx - src/OrbitRawData.cxx src/OrbitRecData.cxx src/OrbitData.cxx src/ZDCEnergy.cxx src/ZDCTDCData.cxx - src/CTF.cxx + src/OrbitRawData.cxx src/OrbitRecData.cxx src/OrbitData.cxx src/ZDCEnergy.cxx src/ZDCTDCData.cxx + src/CTF.cxx PUBLIC_LINK_LIBRARIES O2::CommonConstants O2::CommonDataFormat O2::ZDCBase ROOT::MathCore FairRoot::Base O2::SimulationDataFormat @@ -20,8 +20,8 @@ o2_add_library(DataFormatsZDC o2_target_root_dictionary(DataFormatsZDC HEADERS include/DataFormatsZDC/Hit.h include/DataFormatsZDC/MCLabel.h include/DataFormatsZDC/BCData.h include/DataFormatsZDC/ChannelData.h - include/DataFormatsZDC/OrbitData.h include/DataFormatsZDC/CTF.h - include/DataFormatsZDC/RecEvent.h include/DataFormatsZDC/RecEventAux.h - include/DataFormatsZDC/OrbitRawData.h include/DataFormatsZDC/BCRecData.h - include/DataFormatsZDC/ZDCEnergy.h include/DataFormatsZDC/ZDCTDCData.h - include/DataFormatsZDC/OrbitRecData.h include/DataFormatsZDC/RawEventData.h) + include/DataFormatsZDC/OrbitData.h include/DataFormatsZDC/CTF.h + include/DataFormatsZDC/RecEvent.h include/DataFormatsZDC/RecEventAux.h + include/DataFormatsZDC/OrbitRawData.h include/DataFormatsZDC/BCRecData.h + include/DataFormatsZDC/ZDCEnergy.h include/DataFormatsZDC/ZDCTDCData.h + include/DataFormatsZDC/OrbitRecData.h include/DataFormatsZDC/RawEventData.h) diff --git a/Detectors/ZDC/workflow/CMakeLists.txt b/Detectors/ZDC/workflow/CMakeLists.txt index f96e0155bf277..620279c47d225 100644 --- a/Detectors/ZDC/workflow/CMakeLists.txt +++ b/Detectors/ZDC/workflow/CMakeLists.txt @@ -30,7 +30,7 @@ o2_add_executable(raw2digits COMPONENT_NAME zdc SOURCES src/o2-zdc-raw2digits.cxx PUBLIC_LINK_LIBRARIES O2::ZDCWorkflow) - + o2_add_executable(entropy-encoder-workflow COMPONENT_NAME zdc SOURCES src/entropy-encoder-workflow.cxx From 2032bdf9d1b0e4d2d2e2bbaaf34355d054d1a5fc Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Tue, 8 Jun 2021 12:03:32 +0200 Subject: [PATCH 024/770] Correcting whitespaces --- DataFormats/Detectors/ZDC/CMakeLists.txt | 2 +- .../ZDC/reconstruction/include/ZDCReconstruction/CTFCoder.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/DataFormats/Detectors/ZDC/CMakeLists.txt b/DataFormats/Detectors/ZDC/CMakeLists.txt index e739ee16461e8..ec7cc28a9e4b6 100644 --- a/DataFormats/Detectors/ZDC/CMakeLists.txt +++ b/DataFormats/Detectors/ZDC/CMakeLists.txt @@ -21,7 +21,7 @@ o2_target_root_dictionary(DataFormatsZDC HEADERS include/DataFormatsZDC/Hit.h include/DataFormatsZDC/MCLabel.h include/DataFormatsZDC/BCData.h include/DataFormatsZDC/ChannelData.h include/DataFormatsZDC/OrbitData.h include/DataFormatsZDC/CTF.h - include/DataFormatsZDC/RecEvent.h include/DataFormatsZDC/RecEventAux.h + include/DataFormatsZDC/RecEvent.h include/DataFormatsZDC/RecEventAux.h include/DataFormatsZDC/OrbitRawData.h include/DataFormatsZDC/BCRecData.h include/DataFormatsZDC/ZDCEnergy.h include/DataFormatsZDC/ZDCTDCData.h include/DataFormatsZDC/OrbitRecData.h include/DataFormatsZDC/RawEventData.h) diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/CTFCoder.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/CTFCoder.h index 0ce4305f1675b..1a17aaf2fbd2a 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/CTFCoder.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/CTFCoder.h @@ -100,7 +100,7 @@ void CTFCoder::encode(VEC& buff, const gsl::span& trigData, const ENCODEZDC(helper.begin_nchanTrig(), helper.end_nchanTrig(), CTF::BLC_nchanTrig, 0); // ENCODEZDC(helper.begin_chanID(), helper.end_chanID(), CTF::BLC_chanID, 0); - ENCODEZDC(helper.begin_chanData(), helper.end_chanData(), CTF::BLC_chanData, 0); + ENCODEZDC(helper.begin_chanData(), helper.end_chanData(), CTF::BLC_chanData, 0); // ENCODEZDC(helper.begin_orbitIncEOD(), helper.end_orbitIncEOD(), CTF::BLC_orbitIncEOD, 0); ENCODEZDC(helper.begin_pedData(), helper.end_pedData(), CTF::BLC_pedData, 0); From 58db003f929c632aeb271d4dece489cb5abbefe7 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Tue, 8 Jun 2021 14:05:45 +0200 Subject: [PATCH 025/770] Enable debug output/printout from command line --- Detectors/ZDC/reconstruction/src/DigiReco.cxx | 43 +++++++++++-------- .../include/ZDCWorkflow/DigitRecoSpec.h | 11 ++--- Detectors/ZDC/workflow/src/DigitRecoSpec.cxx | 13 +++--- Detectors/ZDC/workflow/src/RecoWorkflow.cxx | 4 +- .../ZDC/workflow/src/zdc-reco-workflow.cxx | 5 ++- 5 files changed, 45 insertions(+), 31 deletions(-) diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index ea4e6de6cb51c..502cca690ad15 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -264,7 +264,10 @@ int DigiReco::reconstruct(int ibeg, int iend) LOG(INFO) << "Lonely bunch " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc; return 0; } - LOG(INFO) << __func__ << "(" << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; + + if (mVerbosity >= DbgFull) { + LOG(INFO) << __func__ << "(" << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; + } // Get reconstruction parameters auto& ropt = RecoParamZDC::Instance(); @@ -328,7 +331,7 @@ int DigiReco::reconstruct(int ibeg, int iend) auto& rec = mReco[ibun]; for (int itdc = 0; itdc < NTDCChannels; itdc++) { - if (rec.fired[itdc] != 0x0) { + if (mVerbosity >= DbgFull && rec.fired[itdc] != 0x0) { printf("%d %u.%u TDC %d %x", ibun, rec.ir.orbit, rec.ir.bc, itdc, rec.fired[itdc]); for (int isam = 0; isam < NTimeBinsPerBC; isam++) { printf("%d", rec.fired[itdc] & mMask[isam] ? 1 : 0); @@ -337,20 +340,22 @@ int DigiReco::reconstruct(int ibeg, int iend) } rec.pattern[itdc] = 0; for (int32_t i = 0; i < rec.ntdc[itdc]; i++) { - LOG(INFO) << "tdc " << i << " [" << ChannelNames[TDCSignal[itdc]] << "] " << rec.tdcAmp[itdc][i] << " @ " << rec.tdcVal[itdc][i]; + LOG(DEBUG) << "tdc " << i << " [" << ChannelNames[TDCSignal[itdc]] << "] " << rec.tdcAmp[itdc][i] << " @ " << rec.tdcVal[itdc][i]; // There is a TDC value in the search zone around main-main position if (std::abs(rec.tdcVal[itdc][i]) < ropt.tdc_search[itdc]) { rec.pattern[itdc] = 1; } else { - LOG(INFO) << rec.tdcVal[itdc][i] << " " << ropt.tdc_search[itdc]; + LOG(DEBUG) << rec.tdcVal[itdc][i] << " " << ropt.tdc_search[itdc]; } } } - printf("%d %u.%-4u TDC PATTERN: ", ibun, mReco[ibun].ir.orbit, mReco[ibun].ir.bc); - for (int itdc = 0; itdc < NTDCChannels; itdc++) { - printf("%d", rec.pattern[itdc]); + if (mVerbosity >= DbgFull) { + printf("%d %u.%-4u TDC PATTERN: ", ibun, mReco[ibun].ir.orbit, mReco[ibun].ir.bc); + for (int itdc = 0; itdc < NTDCChannels; itdc++) { + printf("%d", rec.pattern[itdc]); + } + printf("\n"); } - printf("\n"); // Check if coincidence of common PM and sum of towers is satisfied bool fired[NChannels] = {0}; @@ -380,13 +385,15 @@ int DigiReco::reconstruct(int ibeg, int iend) } } - printf("%d FIRED ", ibun); - printf("ZNA:%d%d%d%d%d%d ZPA:%d%d%d%d%d%d ZEM:%d%d ZNC:%d%d%d%d%d%d ZPC:%d%d%d%d%d%d\n", - fired[IdZNAC], fired[IdZNA1], fired[IdZNA2], fired[IdZNA3], fired[IdZNA4], fired[IdZNASum], - fired[IdZPAC], fired[IdZPA1], fired[IdZPA2], fired[IdZPA3], fired[IdZPA4], fired[IdZPASum], - fired[IdZEM1], fired[IdZEM2], - fired[IdZNCC], fired[IdZNC1], fired[IdZNC2], fired[IdZNC3], fired[IdZNC4], fired[IdZNCSum], - fired[IdZPCC], fired[IdZPC1], fired[IdZPC2], fired[IdZPC3], fired[IdZPC4], fired[IdZPCSum]); + if (mVerbosity >= DbgFull) { + printf("%d FIRED ", ibun); + printf("ZNA:%d%d%d%d%d%d ZPA:%d%d%d%d%d%d ZEM:%d%d ZNC:%d%d%d%d%d%d ZPC:%d%d%d%d%d%d\n", + fired[IdZNAC], fired[IdZNA1], fired[IdZNA2], fired[IdZNA3], fired[IdZNA4], fired[IdZNASum], + fired[IdZPAC], fired[IdZPA1], fired[IdZPA2], fired[IdZPA3], fired[IdZPA4], fired[IdZPASum], + fired[IdZEM1], fired[IdZEM2], + fired[IdZNCC], fired[IdZNC1], fired[IdZNC2], fired[IdZNC3], fired[IdZNC4], fired[IdZNCSum], + fired[IdZPCC], fired[IdZPC1], fired[IdZPC2], fired[IdZPC3], fired[IdZPC4], fired[IdZPCSum]); + } for (int ich = 0; ich < NChannels; ich++) { // Check if the corresponding TDC is fired if (fired[ich]) { @@ -400,7 +407,9 @@ int DigiReco::reconstruct(int ibeg, int iend) // TODO: manage signal positioned across boundary sum += (pbun[ich] - float(mChData[ref].data[is])); } - printf("CH %2d %s: %f\n", ich, ChannelNames[ich].data(), sum); + if (mVerbosity >= DbgFull) { + printf("CH %2d %s: %f\n", ich, ChannelNames[ich].data(), sum); + } rec.ezdc[ich] = sum; } } @@ -750,7 +759,7 @@ void DigiReco::assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float mReco[ibun].tdcVal[itdc][ihit] = tdc_cor; mReco[ibun].tdcAmp[itdc][ihit] = std::nearbyint(amp / FTDCAmp); ihit++; - LOG(INFO) << mReco[ibun].ir.orbit << "." << mReco[ibun].ir.bc << " " + LOG(DEBUG) << mReco[ibun].ir.orbit << "." << mReco[ibun].ir.bc << " " << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor * FTDCVal << " amp=" << amp * FTDCAmp; } else { LOG(ERROR) << mReco[ibun].ir.orbit << "." << mReco[ibun].ir.bc << " " diff --git a/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h b/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h index cb1cfef9b5f7e..11a93576c6e1a 100644 --- a/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h +++ b/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h @@ -30,17 +30,18 @@ class DigitRecoSpec : public o2::framework::Task { public: DigitRecoSpec(); - DigitRecoSpec(const bool debugOut, const std::string& ccdbURL); + DigitRecoSpec(const int verbosity, const bool debugOut, const std::string& ccdbURL); ~DigitRecoSpec() override = default; void run(o2::framework::ProcessingContext& pc) final; void init(o2::framework::InitContext& ic) final; void endOfStream(o2::framework::EndOfStreamContext& ec) final; private: - DigiReco mDR; - std::string mccdbHost; - bool mDebugOut = false; - bool mInitialized = false; + DigiReco mDR; // Reconstruction object + std::string mccdbHost; // Alternative ccdb server + int mVerbosity = 0; // Verbosity level during recostruction + bool mDebugOut = false; // Save temporary reconstruction structures on root file + bool mInitialized = false; // Connect once to CCDB during initialization TStopwatch mTimer; }; diff --git a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx index 7698528128ba9..69b89b4fa061b 100644 --- a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx +++ b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx @@ -45,8 +45,8 @@ DigitRecoSpec::DigitRecoSpec() } } -DigitRecoSpec::DigitRecoSpec(const bool debugOut, const std::string& ccdbURL) - : mDebugOut(debugOut), mccdbHost(ccdbURL) +DigitRecoSpec::DigitRecoSpec(const int verbosity, const bool debugOut, const std::string& ccdbURL) + : mVerbosity(verbosity), mDebugOut(debugOut), mccdbHost(ccdbURL) { if (mccdbHost.empty()) { mccdbHost = "http://ccdb-test.cern.ch:8080"; @@ -97,8 +97,11 @@ void DigitRecoSpec::run(ProcessingContext& pc) mDR.setIntegrationParam(integrationParam); mDR.setTDCParam(tdcParam); - if (mDebugOut) + if (mDebugOut) { mDR.setDebugOutput(); + } + + mDR.setVerbosity(nVerbosity); mDR.init(); } @@ -152,7 +155,7 @@ void DigitRecoSpec::endOfStream(EndOfStreamContext& ec) mTimer.CpuTime(), mTimer.RealTime(), mTimer.Counter() - 1); } -DataProcessorSpec getDigitRecoSpec(const bool enableDebugOut = false, const std::string ccdbURL = "") +DataProcessorSpec getDigitRecoSpec(const int verbosity, const bool enableDebugOut = false, const std::string ccdbURL = "") { std::vector inputs; inputs.emplace_back("trig", "ZDC", "DIGITSBC", 0, Lifetime::Timeframe); @@ -168,7 +171,7 @@ DataProcessorSpec getDigitRecoSpec(const bool enableDebugOut = false, const std: "zdc-digi-reco", inputs, outputs, - AlgorithmSpec{adaptFromTask(enableDebugOut, ccdbURL)}}; + AlgorithmSpec{adaptFromTask(verbosity, enableDebugOut, ccdbURL)}}; } } // namespace zdc diff --git a/Detectors/ZDC/workflow/src/RecoWorkflow.cxx b/Detectors/ZDC/workflow/src/RecoWorkflow.cxx index de2ae41317f47..cc16438b609ad 100644 --- a/Detectors/ZDC/workflow/src/RecoWorkflow.cxx +++ b/Detectors/ZDC/workflow/src/RecoWorkflow.cxx @@ -20,13 +20,13 @@ namespace o2 namespace zdc { -framework::WorkflowSpec getRecoWorkflow(const bool useMC, const bool disableRootInp, const bool disableRootOut, const bool enableDebugOut, const std::string ccdbURL) +framework::WorkflowSpec getRecoWorkflow(const bool useMC, const bool disableRootInp, const bool disableRootOut, const int verbosity, const bool enableDebugOut, const std::string ccdbURL) { framework::WorkflowSpec specs; if (!disableRootInp) { specs.emplace_back(o2::zdc::getDigitReaderSpec(useMC)); } - specs.emplace_back(o2::zdc::getDigitRecoSpec(enableDebugOut, ccdbURL)); + specs.emplace_back(o2::zdc::getDigitRecoSpec(verbosity, enableDebugOut, ccdbURL)); if (!disableRootOut) { specs.emplace_back(o2::zdc::getZDCRecoWriterDPLSpec()); } diff --git a/Detectors/ZDC/workflow/src/zdc-reco-workflow.cxx b/Detectors/ZDC/workflow/src/zdc-reco-workflow.cxx index 54635dfb662e4..b3b9e5b3ba3c5 100644 --- a/Detectors/ZDC/workflow/src/zdc-reco-workflow.cxx +++ b/Detectors/ZDC/workflow/src/zdc-reco-workflow.cxx @@ -22,9 +22,9 @@ void customize(std::vector& workflowOptions) workflowOptions.push_back(ConfigParamSpec{"disable-mc", o2::framework::VariantType::Bool, false, {"disable MC propagation even if available"}}); workflowOptions.push_back(ConfigParamSpec{"disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}); workflowOptions.push_back(ConfigParamSpec{"disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}); + workflowOptions.push_back(ConfigParamSpec{"verbosity", VariantType::Int, 0, {"verbosity level"}}); workflowOptions.push_back(ConfigParamSpec{"enable-debug-output", VariantType::Bool, false, {"enable debug tree output"}}); workflowOptions.push_back(ConfigParamSpec{"ccdb-url", VariantType::String, "http://ccdb-test.cern.ch:8080", {"url of CCDB"}}); - std::string keyvaluehelp("Semicolon separated key=value strings ..."); workflowOptions.push_back(ConfigParamSpec{"configKeyValues", VariantType::String, "", {keyvaluehelp}}); } @@ -44,9 +44,10 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) auto useMC = !configcontext.options().get("disable-mc"); auto disableRootInp = configcontext.options().get("disable-root-input"); auto disableRootOut = configcontext.options().get("disable-root-output"); + auto verbosity = configcontext.options().get("verbosity"); auto enableDebugOut = configcontext.options().get("enable-debug-output"); auto ccdbURL = configcontext.options().get("ccdb-url"); LOG(INFO) << "WorkflowSpec getRecoWorkflow useMC " << useMC; - return std::move(o2::zdc::getRecoWorkflow(useMC, disableRootInp, disableRootOut, enableDebugOut, ccdbURL)); + return std::move(o2::zdc::getRecoWorkflow(useMC, disableRootInp, disableRootOut, verbosity, enableDebugOut, ccdbURL)); } From 330458c3e343831090599e409c3499437f4ce8e0 Mon Sep 17 00:00:00 2001 From: ALICE Action Bot Date: Tue, 8 Jun 2021 12:06:58 +0000 Subject: [PATCH 026/770] Please consider the following formatting changes --- Detectors/ZDC/reconstruction/src/DigiReco.cxx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index 502cca690ad15..0246e0f6fa537 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -352,7 +352,7 @@ int DigiReco::reconstruct(int ibeg, int iend) if (mVerbosity >= DbgFull) { printf("%d %u.%-4u TDC PATTERN: ", ibun, mReco[ibun].ir.orbit, mReco[ibun].ir.bc); for (int itdc = 0; itdc < NTDCChannels; itdc++) { - printf("%d", rec.pattern[itdc]); + printf("%d", rec.pattern[itdc]); } printf("\n"); } @@ -407,9 +407,9 @@ int DigiReco::reconstruct(int ibeg, int iend) // TODO: manage signal positioned across boundary sum += (pbun[ich] - float(mChData[ref].data[is])); } - if (mVerbosity >= DbgFull) { + if (mVerbosity >= DbgFull) { printf("CH %2d %s: %f\n", ich, ChannelNames[ich].data(), sum); - } + } rec.ezdc[ich] = sum; } } @@ -760,7 +760,7 @@ void DigiReco::assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float mReco[ibun].tdcAmp[itdc][ihit] = std::nearbyint(amp / FTDCAmp); ihit++; LOG(DEBUG) << mReco[ibun].ir.orbit << "." << mReco[ibun].ir.bc << " " - << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor * FTDCVal << " amp=" << amp * FTDCAmp; + << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor * FTDCVal << " amp=" << amp * FTDCAmp; } else { LOG(ERROR) << mReco[ibun].ir.orbit << "." << mReco[ibun].ir.bc << " " << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor * FTDCVal << " amp=" << amp * FTDCAmp << " OVERFLOW"; From 8219070bb0f6a64a8b5d0847369a0e66b0cddc58 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Tue, 8 Jun 2021 18:42:34 +0200 Subject: [PATCH 027/770] Corrections --- .../ZDC/base/include/ZDCBase/Constants.h | 3 ++ Detectors/ZDC/reconstruction/src/DigiReco.cxx | 48 ++++++++----------- Detectors/ZDC/workflow/CMakeLists.txt | 2 +- .../include/ZDCWorkflow/DigitRecoSpec.h | 2 +- .../include/ZDCWorkflow/RecoWorkflow.h | 2 +- Detectors/ZDC/workflow/src/DigitRecoSpec.cxx | 4 +- 6 files changed, 27 insertions(+), 34 deletions(-) diff --git a/Detectors/ZDC/base/include/ZDCBase/Constants.h b/Detectors/ZDC/base/include/ZDCBase/Constants.h index bda1b0a91bbad..885d9a99402f4 100644 --- a/Detectors/ZDC/base/include/ZDCBase/Constants.h +++ b/Detectors/ZDC/base/include/ZDCBase/Constants.h @@ -18,6 +18,9 @@ #include #include +// Enable debug output in reconstruction +//#define O2_ZDC_DEBUG + namespace o2 { namespace zdc diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index 0246e0f6fa537..6b25962296dcd 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -54,6 +54,7 @@ void DigiReco::init() mTDbg = std::make_unique("zdcr", "ZDCReco"); mTDbg->Branch("zdcr", "RecEventAux", &mRec); } + // Update reconstruction parameters //auto& ropt=RecoParamZDC::Instance(); o2::zdc::RecoParamZDC& ropt = const_cast(RecoParamZDC::Instance()); @@ -241,19 +242,6 @@ int DigiReco::process(const gsl::span& orbitdata, cons } } - /* - -std::map::iterator it; - - mymap['a']=50; - mymap['b']=100; - mymap['c']=150; - mymap['d']=200; - - it = mymap.find('b'); - if (it != mymap.end()) - mymap.erase (it); - */ return 0; } @@ -322,22 +310,25 @@ int DigiReco::reconstruct(int ibeg, int iend) pbun[ich] = std::numeric_limits::infinity(); } } + +#ifdef O2_ZDC_DEBUG // Debug dump of pedestal - if (mVerbosity >= DbgFull) { - for (int ich = 0; ich < NChannels; ich++) { - LOG(INFO) << "bunch: " << ibun << " ch: " << ich << " " << ChannelNames[ich] << " offset: " << pbun[ich]; - } + for (int ich = 0; ich < NChannels; ich++) { + LOG(INFO) << "bunch: " << ibun << " ch: " << ich << " " << ChannelNames[ich] << " offset: " << pbun[ich]; } +#endif auto& rec = mReco[ibun]; for (int itdc = 0; itdc < NTDCChannels; itdc++) { - if (mVerbosity >= DbgFull && rec.fired[itdc] != 0x0) { +#ifdef O2_ZDC_DEBUG + if (rec.fired[itdc] != 0x0) { printf("%d %u.%u TDC %d %x", ibun, rec.ir.orbit, rec.ir.bc, itdc, rec.fired[itdc]); for (int isam = 0; isam < NTimeBinsPerBC; isam++) { printf("%d", rec.fired[itdc] & mMask[isam] ? 1 : 0); } printf("\n"); } +#endif rec.pattern[itdc] = 0; for (int32_t i = 0; i < rec.ntdc[itdc]; i++) { LOG(DEBUG) << "tdc " << i << " [" << ChannelNames[TDCSignal[itdc]] << "] " << rec.tdcAmp[itdc][i] << " @ " << rec.tdcVal[itdc][i]; @@ -349,14 +340,13 @@ int DigiReco::reconstruct(int ibeg, int iend) } } } - if (mVerbosity >= DbgFull) { - printf("%d %u.%-4u TDC PATTERN: ", ibun, mReco[ibun].ir.orbit, mReco[ibun].ir.bc); - for (int itdc = 0; itdc < NTDCChannels; itdc++) { - printf("%d", rec.pattern[itdc]); - } - printf("\n"); +#ifdef O2_ZDC_DEBUG + printf("%d %u.%-4u TDC PATTERN: ", ibun, mReco[ibun].ir.orbit, mReco[ibun].ir.bc); + for (int itdc = 0; itdc < NTDCChannels; itdc++) { + printf("%d", rec.pattern[itdc]); } - + printf("\n"); +#endif // Check if coincidence of common PM and sum of towers is satisfied bool fired[NChannels] = {0}; // Side A @@ -407,9 +397,9 @@ int DigiReco::reconstruct(int ibeg, int iend) // TODO: manage signal positioned across boundary sum += (pbun[ich] - float(mChData[ref].data[is])); } - if (mVerbosity >= DbgFull) { - printf("CH %2d %s: %f\n", ich, ChannelNames[ich].data(), sum); - } +#ifdef O2_ZDC_DEBUG + printf("CH %2d %s: %f\n", ich, ChannelNames[ich].data(), sum); +#endif rec.ezdc[ich] = sum; } } @@ -481,7 +471,7 @@ void DigiReco::processTrigger(int itdc, int ibeg, int iend) void DigiReco::interpolate(int itdc, int ibeg, int iend) { - LOG(INFO) << __func__ << "(itdc=" << itdc << "[" << ChannelNames[TDCSignal[itdc]] << "] ," << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; + LOG(DEBUG) << __func__ << "(itdc=" << itdc << "[" << ChannelNames[TDCSignal[itdc]] << "] ," << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; // TODO: get data from preceding time frame constexpr int MaxTimeBin = NTimeBinsPerBC - 1; //< number of samples per BC constexpr int tsnh = TSN / 2; // Half number of points in interpolation diff --git a/Detectors/ZDC/workflow/CMakeLists.txt b/Detectors/ZDC/workflow/CMakeLists.txt index 620279c47d225..d8d0fec2d3f98 100644 --- a/Detectors/ZDC/workflow/CMakeLists.txt +++ b/Detectors/ZDC/workflow/CMakeLists.txt @@ -44,7 +44,7 @@ o2_add_executable(digits-read o2_add_executable(digits-reco COMPONENT_NAME zdc SOURCES src/zdc-reco-workflow.cxx - PUBLIC_LINK_LIBRARIES O2::ZDCWorkflow) + PUBLIC_LINK_LIBRARIES O2::ZDCWorkflow O2::ZDCReconstruction) o2_add_executable(write-reco COMPONENT_NAME zdc diff --git a/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h b/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h index 11a93576c6e1a..a93c6837c4ff3 100644 --- a/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h +++ b/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h @@ -46,7 +46,7 @@ class DigitRecoSpec : public o2::framework::Task }; /// create a processor spec -framework::DataProcessorSpec getDigitRecoSpec(const bool enableDebugOut, const std::string ccdbURL); +framework::DataProcessorSpec getDigitRecoSpec(const int verbosity, const bool enableDebugOut, const std::string ccdbURL); } // namespace zdc } // namespace o2 diff --git a/Detectors/ZDC/workflow/include/ZDCWorkflow/RecoWorkflow.h b/Detectors/ZDC/workflow/include/ZDCWorkflow/RecoWorkflow.h index 9158f067ef52d..18b02aa4f9bb2 100644 --- a/Detectors/ZDC/workflow/include/ZDCWorkflow/RecoWorkflow.h +++ b/Detectors/ZDC/workflow/include/ZDCWorkflow/RecoWorkflow.h @@ -19,7 +19,7 @@ namespace o2 { namespace zdc { -framework::WorkflowSpec getRecoWorkflow(bool useMC, bool disableRootInp, bool disableRootOut, bool enableDebugOut, std::string ccdbURL); +framework::WorkflowSpec getRecoWorkflow(const bool useMC, const bool disableRootInp, const bool disableRootOut, const int verbosity, const bool enableDebugOut, const std::string ccdbURL); } // namespace zdc } // namespace o2 #endif diff --git a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx index 69b89b4fa061b..839e481822d58 100644 --- a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx +++ b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx @@ -101,7 +101,7 @@ void DigitRecoSpec::run(ProcessingContext& pc) mDR.setDebugOutput(); } - mDR.setVerbosity(nVerbosity); + mDR.setVerbosity(mVerbosity); mDR.init(); } @@ -155,7 +155,7 @@ void DigitRecoSpec::endOfStream(EndOfStreamContext& ec) mTimer.CpuTime(), mTimer.RealTime(), mTimer.Counter() - 1); } -DataProcessorSpec getDigitRecoSpec(const int verbosity, const bool enableDebugOut = false, const std::string ccdbURL = "") +framework::DataProcessorSpec getDigitRecoSpec(const bool enableDebugOut = false, const int verbosity=0, const std::string ccdbURL = "") { std::vector inputs; inputs.emplace_back("trig", "ZDC", "DIGITSBC", 0, Lifetime::Timeframe); From 928ed1f0e329af2bc3c1b1da00463cb4d3abbc85 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Tue, 8 Jun 2021 18:45:42 +0200 Subject: [PATCH 028/770] Corrections --- Detectors/ZDC/workflow/src/DigitRecoSpec.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx index 839e481822d58..027eed707893c 100644 --- a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx +++ b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx @@ -155,7 +155,7 @@ void DigitRecoSpec::endOfStream(EndOfStreamContext& ec) mTimer.CpuTime(), mTimer.RealTime(), mTimer.Counter() - 1); } -framework::DataProcessorSpec getDigitRecoSpec(const bool enableDebugOut = false, const int verbosity=0, const std::string ccdbURL = "") +framework::DataProcessorSpec getDigitRecoSpec(const int verbosity=0, const bool enableDebugOut = false, const std::string ccdbURL = "") { std::vector inputs; inputs.emplace_back("trig", "ZDC", "DIGITSBC", 0, Lifetime::Timeframe); From b497223b5fa2ffd79f1ec08eae6518c986641154 Mon Sep 17 00:00:00 2001 From: ALICE Action Bot Date: Tue, 8 Jun 2021 16:46:34 +0000 Subject: [PATCH 029/770] Please consider the following formatting changes --- Detectors/ZDC/workflow/src/DigitRecoSpec.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx index 027eed707893c..50e00e298eeb3 100644 --- a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx +++ b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx @@ -155,7 +155,7 @@ void DigitRecoSpec::endOfStream(EndOfStreamContext& ec) mTimer.CpuTime(), mTimer.RealTime(), mTimer.Counter() - 1); } -framework::DataProcessorSpec getDigitRecoSpec(const int verbosity=0, const bool enableDebugOut = false, const std::string ccdbURL = "") +framework::DataProcessorSpec getDigitRecoSpec(const int verbosity = 0, const bool enableDebugOut = false, const std::string ccdbURL = "") { std::vector inputs; inputs.emplace_back("trig", "ZDC", "DIGITSBC", 0, Lifetime::Timeframe); From 2357ebab91a5e1b99716c46e89115069e315f0b4 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Wed, 9 Jun 2021 17:58:33 +0200 Subject: [PATCH 030/770] Configuration parameters for reconstruction --- Detectors/ZDC/macro/CMakeLists.txt | 2 +- ...tegrationParam.C => CreateRecoConfigZDC.C} | 9 ++- Detectors/ZDC/reconstruction/CMakeLists.txt | 2 +- .../include/ZDCReconstruction/DigiReco.h | 4 +- ...{ZDCIntegrationParam.h => RecoConfigZDC.h} | 30 ++++++---- .../include/ZDCReconstruction/RecoParamZDC.h | 2 +- .../include/ZDCReconstruction/ZDCTDCParam.h | 5 +- Detectors/ZDC/reconstruction/src/DigiReco.cxx | 58 +++++++++++++------ ...IntegrationParam.cxx => RecoConfigZDC.cxx} | 32 +++++++++- .../src/ZDCReconstructionLinkDef.h | 2 +- .../ZDC/reconstruction/src/ZDCTDCParam.cxx | 21 +++---- Detectors/ZDC/workflow/src/DigitRecoSpec.cxx | 20 ++++--- 12 files changed, 121 insertions(+), 66 deletions(-) rename Detectors/ZDC/macro/{CreateIntegrationParam.C => CreateRecoConfigZDC.C} (93%) rename Detectors/ZDC/reconstruction/include/ZDCReconstruction/{ZDCIntegrationParam.h => RecoConfigZDC.h} (76%) rename Detectors/ZDC/reconstruction/src/{ZDCIntegrationParam.cxx => RecoConfigZDC.cxx} (74%) diff --git a/Detectors/ZDC/macro/CMakeLists.txt b/Detectors/ZDC/macro/CMakeLists.txt index 8da744c40e588..c8ff2d64fb6fa 100644 --- a/Detectors/ZDC/macro/CMakeLists.txt +++ b/Detectors/ZDC/macro/CMakeLists.txt @@ -21,7 +21,7 @@ o2_add_test_root_macro(readZDCDigits.C PUBLIC_LINK_LIBRARIES O2::ZDCSimulation O2::CCDB LABELS zdc) -o2_add_test_root_macro(CreateIntegrationParam.C +o2_add_test_root_macro(CreateRecoConfigZDC.C PUBLIC_LINK_LIBRARIES O2::ZDCBase O2::ZDCReconstruction O2::SimulationDataFormat O2::CCDB LABELS zdc) diff --git a/Detectors/ZDC/macro/CreateIntegrationParam.C b/Detectors/ZDC/macro/CreateRecoConfigZDC.C similarity index 93% rename from Detectors/ZDC/macro/CreateIntegrationParam.C rename to Detectors/ZDC/macro/CreateRecoConfigZDC.C index c3408f5f9798d..c995c8a428a2b 100644 --- a/Detectors/ZDC/macro/CreateIntegrationParam.C +++ b/Detectors/ZDC/macro/CreateRecoConfigZDC.C @@ -12,7 +12,7 @@ #include "FairLogger.h" #include "CCDB/CcdbApi.h" -#include "ZDCReconstruction/ZDCIntegrationParam.h" +#include "ZDCReconstruction/RecoConfigZDC.h" #include "ZDCBase/Constants.h" #include #include @@ -23,10 +23,13 @@ using namespace o2::zdc; using namespace std; -void CreateIntegrationParam(long tmin = 0, long tmax = -1, +void CreateRecoConfigZDC(long tmin = 0, long tmax = -1, std::string ccdbHost = "http://ccdb-test.cern.ch:8080") { + // Offline trigger + // TDC + // Charge integration ZDCIntegrationParam conf; int beg_sig = 6; @@ -75,7 +78,7 @@ void CreateIntegrationParam(long tmin = 0, long tmax = -1, map metadata; // can be empty api.init(ccdbHost.c_str()); // or http://localhost:8080 for a local installation // store abitrary user object in strongly typed manner - api.storeAsTFileAny(&conf, CCDBPathConfigIntegration, metadata, tmin, tmax); + api.storeAsTFileAny(&conf, CCDBPathRecoConfigZDC, metadata, tmin, tmax); // return conf; } diff --git a/Detectors/ZDC/reconstruction/CMakeLists.txt b/Detectors/ZDC/reconstruction/CMakeLists.txt index 14e14009817a6..9b4ed62286fa7 100644 --- a/Detectors/ZDC/reconstruction/CMakeLists.txt +++ b/Detectors/ZDC/reconstruction/CMakeLists.txt @@ -14,7 +14,7 @@ o2_add_library(ZDCReconstruction src/DigiReco.cxx src/RecoParamZDC.cxx src/ZDCTDCParam.cxx - src/ZDCIntegrationParam.cxx + src/RecoConfigZDC.cxx PUBLIC_LINK_LIBRARIES O2::ZDCBase O2::DataFormatsZDC O2::ZDCSimulation diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h index 7d4b8ac57b2b1..16e40bb5ff89a 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h @@ -17,7 +17,7 @@ #include "ZDCSimulation/ZDCSimParam.h" #include "ZDCReconstruction/RecoParamZDC.h" #include "ZDCReconstruction/ZDCTDCParam.h" -#include "ZDCReconstruction/ZDCIntegrationParam.h" +#include "ZDCReconstruction/RecoConfigZDC.h" #include "ZDCBase/ModuleConfig.h" #include "DataFormatsZDC/BCData.h" #include "DataFormatsZDC/ChannelData.h" @@ -80,7 +80,7 @@ class DigiReco int mNBCAHead = 0; /// when storing triggered BC, store also mNBCAHead BCs const ZDCTDCParam* mTDCParam = nullptr; /// TDC calibration object uint32_t mTDCMask[NTDCChannels] = {0}; /// Identify TDC channels in trigger mask - const ZDCIntegrationParam* mIntParam = nullptr; /// Configuration of integration + const RecoConfigZDC* mRecoConfigZDC = nullptr; /// CCDB configuration parameters bool mVerbosity = DbgFull; Double_t mTS[NTS]; /// Tapered sinc function bool mTreeDbg = false; /// Write reconstructed data in debug output file diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCIntegrationParam.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoConfigZDC.h similarity index 76% rename from Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCIntegrationParam.h rename to Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoConfigZDC.h index 9dfd55dfaa218..0f5136ec4fe48 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCIntegrationParam.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoConfigZDC.h @@ -8,25 +8,34 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef O2_ZDC_INTEGRATIONPARAM_H -#define O2_ZDC_INTEGRATIONPARAM_H +#ifndef O2_ZDC_RECOCONFIGZDC_H +#define O2_ZDC_RECOCONFIGZDC_H -#include "ZDCBase/Constants.h" -#include #include +#include +#include "ZDCBase/Constants.h" -/// \file ZDCIntegrationParam.h -/// \brief Parameters to configure integration +/// \file RecoConfigZDC.h +/// \brief ZDC reconstruction parameters /// \author P. Cortese namespace o2 { namespace zdc { -// parameters of ZDC reconstruction +struct RecoConfigZDC { + // Trigger + Int_t tsh[NTDCChannels] = {4, 4, 4, 4, 4, 4, 4, 4, 4, 4}; // Trigger shift + Int_t tth[NTDCChannels] = {8, 8, 8, 8, 8, 8, 8, 8, 8, 8}; // Trigger threshold + std::array bitset = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Set bits in coincidence + void setBit(uint32_t ibit, bool val = true); + + // TDC + int tdc_search[NTDCChannels] = {250, 250, 250, 250, 250, 250, 250, 250, 250, 250}; // Search zone for a TDC signal ideally 2.5 ns (units of ~10 ps) + void setSearch(uint32_t ich, int val); + int getSearch(uint32_t ich) const; -struct ZDCIntegrationParam { - public: + // Charge integration // Beginning and end of integration range: signal Int_t beg_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; Int_t end_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; @@ -34,9 +43,10 @@ struct ZDCIntegrationParam { Int_t beg_ped_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; Int_t end_ped_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; void setIntegration(uint32_t ich, int beg, int end, int beg_ped, int end_ped); + void print(); - ClassDefNV(ZDCIntegrationParam, 1); + ClassDefNV(RecoConfigZDC, 1); }; } // namespace zdc } // namespace o2 diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h index 484ea82e3cf49..4ec25c93a721e 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h @@ -34,7 +34,7 @@ struct RecoParamZDC : public o2::conf::ConfigurableParamHelper { Int_t amod[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of ADC channel in raw data Int_t ach[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of ADC channel in raw data float tdc_shift[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Correction of TDC position (0-25 ns, units of ~10 ps) - float tdc_search[NTDCChannels] = {250, 250, 250, 250, 250, 250, 250, 250, 250, 250}; // Search zone for a TDC signal ideally 2.5 ns (units of ~10 ps) + float tdc_search[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Search zone for a TDC signal ideally 2.5 ns (units of ~10 ps) // Beginning and end of integration range: signal Int_t beg_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; Int_t end_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h index da4fefde6418d..3890cf79b40f6 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h @@ -16,22 +16,19 @@ #include /// \file ZDCTDCParam.h -/// \brief Parameters to correct TDCs +/// \brief Parameters to correct TDCs (produced by QA) /// \author P. Cortese namespace o2 { namespace zdc { -// parameters of ZDC reconstruction - struct ZDCTDCParam { //std::array tdcShift{} float tdc_shift[NTDCChannels] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Correction of TDC position (ns) void setShift(uint32_t ich, float val); float getShift(uint32_t ich) const; void print(); - ClassDefNV(ZDCTDCParam, 1); }; } // namespace zdc diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index 6b25962296dcd..0c737afcd9602 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -107,8 +107,15 @@ void DigiReco::init() } // TDC search zone - // TODO: override with configuration object for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { + // If the reconstruction parameters were not manually set + if (ropt.tdc_search[ich] <= 0) { + if (!mRecoConfigZDC) { + LOG(FATAL) << "Search zone for TDC " << itdc << " missing configuration object and no manual override"; + } else { + ropt.tdc_search[itdc] = mRecoConfigZDC->tdc_search[itdc]; + } + } LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << ropt.tdc_search[itdc] << " i.s. = " << ropt.tdc_search[itdc] * FTDCVal << " ns"; } @@ -133,20 +140,20 @@ void DigiReco::init() // Integration ranges for (int ich = 0; ich < NChannels; ich++) { // If the reconstruction parameters were not manually set - if (ropt.beg_int[ich] <= DummyIntRange || ropt.end_int[ich] <= DummyIntRange) { - if (!mIntParam) { - LOG(ERROR) << "Integration for signal " << ich << " missing configuration object and no manual override"; + if (ropt.beg_int[ich] == DummyIntRange || ropt.end_int[ich] == DummyIntRange) { + if (!mRecoConfigZDC) { + LOG(FATAL) << "Integration for signal " << ich << " missing configuration object and no manual override"; } else { - ropt.beg_int[ich] = mIntParam->beg_int[ich]; - ropt.end_int[ich] = mIntParam->end_int[ich]; + ropt.beg_int[ich] = mRecoConfigZDC->beg_int[ich]; + ropt.end_int[ich] = mRecoConfigZDC->end_int[ich]; } } - if (ropt.beg_ped_int[ich] <= DummyIntRange || ropt.end_ped_int[ich] <= DummyIntRange) { - if (!mIntParam) { + if (ropt.beg_ped_int[ich] == DummyIntRange || ropt.end_ped_int[ich] == DummyIntRange) { + if (!mRecoConfigZDC) { LOG(ERROR) << "Integration for pedestal " << ich << " missing configuration object and no manual override"; } else { - ropt.beg_ped_int[ich] = mIntParam->beg_ped_int[ich]; - ropt.end_ped_int[ich] = mIntParam->end_ped_int[ich]; + ropt.beg_ped_int[ich] = mRecoConfigZDC->beg_ped_int[ich]; + ropt.end_ped_int[ich] = mRecoConfigZDC->end_ped_int[ich]; } } LOG(INFO) << ChannelNames[ich] << " integration: signal=[" << ropt.beg_int[ich] << ":" << ropt.end_int[ich] << "] pedestal=[" << ropt.beg_ped_int[ich] << ":" << ropt.end_ped_int[ich] << "]"; @@ -331,13 +338,18 @@ int DigiReco::reconstruct(int ibeg, int iend) #endif rec.pattern[itdc] = 0; for (int32_t i = 0; i < rec.ntdc[itdc]; i++) { - LOG(DEBUG) << "tdc " << i << " [" << ChannelNames[TDCSignal[itdc]] << "] " << rec.tdcAmp[itdc][i] << " @ " << rec.tdcVal[itdc][i]; +#ifdef O2_ZDC_DEBUG + LOG(INFO) << "tdc " << i << " [" << ChannelNames[TDCSignal[itdc]] << "] " << rec.tdcAmp[itdc][i] << " @ " << rec.tdcVal[itdc][i]; +#endif // There is a TDC value in the search zone around main-main position if (std::abs(rec.tdcVal[itdc][i]) < ropt.tdc_search[itdc]) { rec.pattern[itdc] = 1; - } else { - LOG(DEBUG) << rec.tdcVal[itdc][i] << " " << ropt.tdc_search[itdc]; } +#ifdef O2_ZDC_DEBUG + else { + LOG(INFO) << rec.tdcVal[itdc][i] << " " << ropt.tdc_search[itdc]; + } +#endif } } #ifdef O2_ZDC_DEBUG @@ -410,12 +422,14 @@ int DigiReco::reconstruct(int ibeg, int iend) mTDbg->Fill(); } } // Loop on bunches + return 0; } void DigiReco::processTrigger(int itdc, int ibeg, int iend) { - LOG(DEBUG) << __func__ << "(itdc=" << itdc << "[" << ChannelNames[TDCSignal[itdc]] << "] ," << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; - +#ifdef O2_ZDC_DEBUG + LOG(INFO) << __func__ << "(itdc=" << itdc << "[" << ChannelNames[TDCSignal[itdc]] << "] ," << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; +#endif // Get reconstruction parameters auto& ropt = RecoParamZDC::Instance(); @@ -453,7 +467,9 @@ void DigiReco::processTrigger(int itdc, int ibeg, int iend) // Fired bit is assigned to the second sample, i.e. to the one that can identify the // signal peak position mReco[b2].fired[itdc] |= mMask[s2]; - LOG(DEBUG) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " Fired @ " << mReco[b2].ir.orbit << "." << mReco[b2].ir.bc << ".s" << s2; +#ifdef O2_ZDC_DEBUG + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " Fired @ " << mReco[b2].ir.orbit << "." << mReco[b2].ir.bc << ".s" << s2; +#endif } } if (is2 >= shift) { @@ -471,7 +487,9 @@ void DigiReco::processTrigger(int itdc, int ibeg, int iend) void DigiReco::interpolate(int itdc, int ibeg, int iend) { - LOG(DEBUG) << __func__ << "(itdc=" << itdc << "[" << ChannelNames[TDCSignal[itdc]] << "] ," << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; +#ifdef O2_ZDC_DEBUG + LOG(INFO) << __func__ << "(itdc=" << itdc << "[" << ChannelNames[TDCSignal[itdc]] << "] ," << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; +#endif // TODO: get data from preceding time frame constexpr int MaxTimeBin = NTimeBinsPerBC - 1; //< number of samples per BC constexpr int tsnh = TSN / 2; // Half number of points in interpolation @@ -749,8 +767,10 @@ void DigiReco::assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float mReco[ibun].tdcVal[itdc][ihit] = tdc_cor; mReco[ibun].tdcAmp[itdc][ihit] = std::nearbyint(amp / FTDCAmp); ihit++; - LOG(DEBUG) << mReco[ibun].ir.orbit << "." << mReco[ibun].ir.bc << " " - << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor * FTDCVal << " amp=" << amp * FTDCAmp; +#ifdef O2_ZDC_DEBUG + LOG(INFO) << mReco[ibun].ir.orbit << "." << mReco[ibun].ir.bc << " " + << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor * FTDCVal << " amp=" << amp * FTDCAmp; +#endif } else { LOG(ERROR) << mReco[ibun].ir.orbit << "." << mReco[ibun].ir.bc << " " << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor * FTDCVal << " amp=" << amp * FTDCAmp << " OVERFLOW"; diff --git a/Detectors/ZDC/reconstruction/src/ZDCIntegrationParam.cxx b/Detectors/ZDC/reconstruction/src/RecoConfigZDC.cxx similarity index 74% rename from Detectors/ZDC/reconstruction/src/ZDCIntegrationParam.cxx rename to Detectors/ZDC/reconstruction/src/RecoConfigZDC.cxx index f94f3504a957a..481699e635ff0 100644 --- a/Detectors/ZDC/reconstruction/src/ZDCIntegrationParam.cxx +++ b/Detectors/ZDC/reconstruction/src/RecoConfigZDC.cxx @@ -9,11 +9,37 @@ // or submit itself to any jurisdiction. #include "FairLogger.h" -#include "ZDCReconstruction/ZDCIntegrationParam.h" +#include "ZDCReconstruction/RecoConfigZDC.h" using namespace o2::zdc; -void ZDCIntegrationParam::setIntegration(uint32_t ich, int beg, int end, int beg_ped, int end_ped) +void RecoConfigZDC::setSearch(uint32_t ich, int val) +{ + if (ich >= 0 && ich < NTDCChannels) { + tdc_search[ich] = val; + } else { + LOG(FATAL) << __func__ << " channel " << ich << " not in allowed range"; + } +} + +void RecoConfigZDC::print() +{ + for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << tdc_search[itdc] << " = " tdc_search[itdc] * FTDCVal << " ns"; + } +} + +int RecoConfigZDC::getSearch(uint32_t ich) const +{ + if (ich >= 0 && ich < NTDCChannels) { + return tdc_search[ich]; + } else { + LOG(FATAL) << __func__ << " channel " << ich << " not in allowed range"; + return -1; + } +} + +void RecoConfigZDC::setIntegration(uint32_t ich, int beg, int end, int beg_ped, int end_ped) { int sig_l = 0; int sig_h = NTimeBinsPerBC - 1; @@ -54,7 +80,7 @@ void ZDCIntegrationParam::setIntegration(uint32_t ich, int beg, int end, int beg } } -void ZDCIntegrationParam::print() +void RecoConfigZDC::print() { for (Int_t ich = 0; ich < NChannels; ich++) { LOG(INFO) << ChannelNames[ich] << " integration: signal=[" << beg_int[ich] << ":" << end_int[ich] << "] pedestal=[" << beg_ped_int[ich] << ":" << end_ped_int[ich] << "]"; diff --git a/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h b/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h index 25a6e79ce1a5e..cb520d805b368 100644 --- a/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h +++ b/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h @@ -14,7 +14,7 @@ #pragma link off all classes; #pragma link off all functions; -#pragma link C++ class o2::zdc::ZDCIntegrationParam + ; +#pragma link C++ class o2::zdc::RecoConfigZDC + ; #pragma link C++ class o2::zdc::ZDCTDCParam + ; #endif diff --git a/Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx b/Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx index 7cbccde9863fa..e38ec89814fa4 100644 --- a/Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx +++ b/Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx @@ -22,20 +22,6 @@ void ZDCTDCParam::setShift(uint32_t ich, float val) } } -void ZDCTDCParam::print() -{ - LOG(INFO) << "TDCZNAC shift " << tdc_shift[TDCZNAC] << " ns"; - LOG(INFO) << "TDCZNAS shift " << tdc_shift[TDCZNAS] << " ns"; - LOG(INFO) << "TDCZPAC shift " << tdc_shift[TDCZPAC] << " ns"; - LOG(INFO) << "TDCZPAS shift " << tdc_shift[TDCZPAS] << " ns"; - LOG(INFO) << "TDCZEM1 shift " << tdc_shift[TDCZEM1] << " ns"; - LOG(INFO) << "TDCZEM2 shift " << tdc_shift[TDCZEM2] << " ns"; - LOG(INFO) << "TDCZNCC shift " << tdc_shift[TDCZNCC] << " ns"; - LOG(INFO) << "TDCZNCS shift " << tdc_shift[TDCZNCS] << " ns"; - LOG(INFO) << "TDCZPCC shift " << tdc_shift[TDCZPCC] << " ns"; - LOG(INFO) << "TDCZPCS shift " << tdc_shift[TDCZPCS] << " ns"; -} - float ZDCTDCParam::getShift(uint32_t ich) const { if (ich >= 0 && ich < NTDCChannels) { @@ -45,3 +31,10 @@ float ZDCTDCParam::getShift(uint32_t ich) const return 0; } } + +void ZDCTDCParam::print() +{ + for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " shift = " << tdc_shift[itdc] << " ns"; + } +} diff --git a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx index 50e00e298eeb3..8804e88cfc943 100644 --- a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx +++ b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx @@ -26,7 +26,7 @@ #include "FairLogger.h" #include "CCDB/BasicCCDBManager.h" #include "CCDB/CCDBTimeStampUtils.h" -#include "ZDCReconstruction/ZDCIntegrationParam.h" +#include "ZDCReconstruction/RecoConfigZDC.h" #include "ZDCReconstruction/ZDCTDCParam.h" using namespace o2::framework; @@ -79,10 +79,10 @@ void DigitRecoSpec::run(ProcessingContext& pc) } LOG(INFO) << "Loaded module configuration for timestamp " << timeStamp; - // Integration parameters - auto* integrationParam = mgr.get(o2::zdc::CCDBPathConfigIntegration); - if (!integrationParam) { - LOG(FATAL) << "Missing ZDCIntegrationParam object"; + // Configuration parameters for ZDC reconstruction + auto* recoConfigZDC = mgr.get(o2::zdc::CCDBPathRecoConfigZDC); + if (!recoConfigZDC) { + LOG(FATAL) << "Missing RecoConfigZDC object"; return; } @@ -94,7 +94,7 @@ void DigitRecoSpec::run(ProcessingContext& pc) } mDR.setModuleConfig(moduleConfig); - mDR.setIntegrationParam(integrationParam); + mDR.setRecoConfigZDC(recoConfigZDC); mDR.setTDCParam(tdcParam); if (mDebugOut) { @@ -116,6 +116,7 @@ void DigitRecoSpec::run(ProcessingContext& pc) RecEvent recEvent; LOG(INFO) << "BC processed during reconstruction " << recAux.size(); + int32_t nte=0, ntt=0; for (auto reca : recAux) { int32_t ne = reca.ezdc.size(); int32_t nt = 0; @@ -137,10 +138,15 @@ void DigitRecoSpec::run(ProcessingContext& pc) recEvent.addEnergy(it->first, it->second); } } - if (nt > 0 || ne > 0) { + nte+=ne; + ntt+=nt; + if (mVerbosity > 0 && (nt > 0 || ne > 0)) { printf("Orbit %9u bc %4u ntdc %2d ne %2d\n", reca.ir.orbit, reca.ir.bc, nt, ne); } } + LOG(INFO) << "Reconstructed " << ntt << " signal TDCs and " << nte << " energies"; + // TODO: rate information for all channels + // TODO: summary of reconstruction to be collected by DQM? pc.outputs().snapshot(Output{"ZDC", "BCREC", 0, Lifetime::Timeframe}, recEvent.mRecBC); pc.outputs().snapshot(Output{"ZDC", "ENERGY", 0, Lifetime::Timeframe}, recEvent.mEnergy); pc.outputs().snapshot(Output{"ZDC", "TDCDATA", 0, Lifetime::Timeframe}, recEvent.mTDCData); From 6cc3098a0fcdef5c958ed07bfc31560a67277427 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Thu, 10 Jun 2021 09:46:46 +0200 Subject: [PATCH 031/770] Configuration parameters for reconstruction - bug fixes --- .../ZDC/base/include/ZDCBase/Constants.h | 2 +- Detectors/ZDC/macro/CreateRecoConfigZDC.C | 30 +++++++++++++++++-- .../include/ZDCReconstruction/DigiReco.h | 4 +-- Detectors/ZDC/reconstruction/src/DigiReco.cxx | 2 +- .../ZDC/reconstruction/src/RecoConfigZDC.cxx | 10 ++----- Detectors/ZDC/workflow/src/DigitRecoSpec.cxx | 6 ++++ 6 files changed, 40 insertions(+), 14 deletions(-) diff --git a/Detectors/ZDC/base/include/ZDCBase/Constants.h b/Detectors/ZDC/base/include/ZDCBase/Constants.h index 885d9a99402f4..f42fc8c0c72ae 100644 --- a/Detectors/ZDC/base/include/ZDCBase/Constants.h +++ b/Detectors/ZDC/base/include/ZDCBase/Constants.h @@ -211,7 +211,7 @@ constexpr int DbgFull = 3; const std::string CCDBPathConfigSim = "ZDC/Config/Sim"; const std::string CCDBPathConfigModule = "ZDC/Config/Module"; const std::string CCDBPathConfigReco = "ZDC/Calib/RecoParam"; -const std::string CCDBPathConfigIntegration = "ZDC/Calib/IntegrationParam"; +const std::string CCDBPathRecoConfigZDC = "ZDC/Calib/RecoConfigZDC"; const std::string CCDBPathTDCCalib = "ZDC/Calib/TDCCalib"; // Placeholders diff --git a/Detectors/ZDC/macro/CreateRecoConfigZDC.C b/Detectors/ZDC/macro/CreateRecoConfigZDC.C index c995c8a428a2b..9c86552ed8a48 100644 --- a/Detectors/ZDC/macro/CreateRecoConfigZDC.C +++ b/Detectors/ZDC/macro/CreateRecoConfigZDC.C @@ -24,14 +24,38 @@ using namespace o2::zdc; using namespace std; void CreateRecoConfigZDC(long tmin = 0, long tmax = -1, - std::string ccdbHost = "http://ccdb-test.cern.ch:8080") + std::string ccdbHost = "http://ccdb-test.cern.ch:8080") { + RecoConfigZDC conf; + // Offline trigger + // Set trigger bitsincoincidence to ignore dead channels + // conf.setBit(IdZNAC); + // conf.setBit(IdZNASum); + // conf.setBit(IdZPAC); + // conf.setBit(IdZPASum); + // conf.setBit(IdZEM1); + // conf.setBit(IdZEM2); + // conf.setBit(IdZNCC); + // conf.setBit(IdZNCSum); + // conf.setBit(IdZPCC); + // conf.setBit(IdZPCSum); + // TDC - // Charge integration - ZDCIntegrationParam conf; + int def_search = 250; // Unit of ~10 ps + conf.setSearch(TDCZNAC, def_search); + conf.setSearch(TDCZNAS, def_search); + conf.setSearch(TDCZPAC, def_search); + conf.setSearch(TDCZPAS, def_search); + conf.setSearch(TDCZEM1, def_search); + conf.setSearch(TDCZEM2, def_search); + conf.setSearch(TDCZNCC, def_search); + conf.setSearch(TDCZNCS, def_search); + conf.setSearch(TDCZPCC, def_search); + conf.setSearch(TDCZPCS, def_search); + // Charge integration int beg_sig = 6; int end_sig = 8; int beg_ped = -12; diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h index 16e40bb5ff89a..fb0943cd92ad3 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h @@ -65,8 +65,8 @@ class DigiReco const ModuleConfig* getModuleConfig() { return mModuleConfig; }; void setTDCParam(const ZDCTDCParam* param) { mTDCParam = param; }; const ZDCTDCParam* getTDCParam() { return mTDCParam; }; - void setIntegrationParam(const ZDCIntegrationParam* param) { mIntParam = param; }; - const ZDCIntegrationParam* getIntegrationParam() { return mIntParam; }; + void setRecoConfigZDC(const RecoConfigZDC* cfg) { mRecoConfigZDC = cfg; }; + const RecoConfigZDC* getRecoConfigZDC() { return mRecoConfigZDC; }; const std::vector& getReco() { return mReco; } diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index 0c737afcd9602..bc38a585d7d8e 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -109,7 +109,7 @@ void DigiReco::init() // TDC search zone for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { // If the reconstruction parameters were not manually set - if (ropt.tdc_search[ich] <= 0) { + if (ropt.tdc_search[itdc] <= 0) { if (!mRecoConfigZDC) { LOG(FATAL) << "Search zone for TDC " << itdc << " missing configuration object and no manual override"; } else { diff --git a/Detectors/ZDC/reconstruction/src/RecoConfigZDC.cxx b/Detectors/ZDC/reconstruction/src/RecoConfigZDC.cxx index 481699e635ff0..a1ec9a852fe4e 100644 --- a/Detectors/ZDC/reconstruction/src/RecoConfigZDC.cxx +++ b/Detectors/ZDC/reconstruction/src/RecoConfigZDC.cxx @@ -22,13 +22,6 @@ void RecoConfigZDC::setSearch(uint32_t ich, int val) } } -void RecoConfigZDC::print() -{ - for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { - LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << tdc_search[itdc] << " = " tdc_search[itdc] * FTDCVal << " ns"; - } -} - int RecoConfigZDC::getSearch(uint32_t ich) const { if (ich >= 0 && ich < NTDCChannels) { @@ -82,6 +75,9 @@ void RecoConfigZDC::setIntegration(uint32_t ich, int beg, int end, int beg_ped, void RecoConfigZDC::print() { + for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << tdc_search[itdc] << " = " << tdc_search[itdc] * FTDCVal << " ns"; + } for (Int_t ich = 0; ich < NChannels; ich++) { LOG(INFO) << ChannelNames[ich] << " integration: signal=[" << beg_int[ich] << ":" << end_int[ich] << "] pedestal=[" << beg_ped_int[ich] << ":" << end_ped_int[ich] << "]"; } diff --git a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx index 8804e88cfc943..15b6838817508 100644 --- a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx +++ b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx @@ -23,6 +23,7 @@ #include "DataFormatsZDC/ChannelData.h" #include "DataFormatsZDC/OrbitData.h" #include "DataFormatsZDC/RecEvent.h" +#include "ZDCBase/ModuleConfig.h" #include "FairLogger.h" #include "CCDB/BasicCCDBManager.h" #include "CCDB/CCDBTimeStampUtils.h" @@ -78,6 +79,7 @@ void DigitRecoSpec::run(ProcessingContext& pc) return; } LOG(INFO) << "Loaded module configuration for timestamp " << timeStamp; + moduleConfig->print(); // Configuration parameters for ZDC reconstruction auto* recoConfigZDC = mgr.get(o2::zdc::CCDBPathRecoConfigZDC); @@ -85,6 +87,8 @@ void DigitRecoSpec::run(ProcessingContext& pc) LOG(FATAL) << "Missing RecoConfigZDC object"; return; } + LOG(INFO) << "Loaded RecoConfigZDC for timestamp " << timeStamp; + recoConfigZDC->print(); // TDC centering auto* tdcParam = mgr.get(o2::zdc::CCDBPathTDCCalib); @@ -92,6 +96,8 @@ void DigitRecoSpec::run(ProcessingContext& pc) LOG(FATAL) << "Missing ZDCTDCParam calibration object"; return; } + LOG(INFO) << "Loaded TDC centering ZDCTDCParam for timestamp " << timeStamp; + tdcParam->print(); mDR.setModuleConfig(moduleConfig); mDR.setRecoConfigZDC(recoConfigZDC); From bee59265584aca7387996da2bf77e4d97c83a7d3 Mon Sep 17 00:00:00 2001 From: ALICE Action Bot Date: Thu, 10 Jun 2021 07:47:43 +0000 Subject: [PATCH 032/770] Please consider the following formatting changes --- Detectors/ZDC/workflow/src/DigitRecoSpec.cxx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx index 15b6838817508..3e95d6ba0cff1 100644 --- a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx +++ b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx @@ -122,7 +122,7 @@ void DigitRecoSpec::run(ProcessingContext& pc) RecEvent recEvent; LOG(INFO) << "BC processed during reconstruction " << recAux.size(); - int32_t nte=0, ntt=0; + int32_t nte = 0, ntt = 0; for (auto reca : recAux) { int32_t ne = reca.ezdc.size(); int32_t nt = 0; @@ -144,8 +144,8 @@ void DigitRecoSpec::run(ProcessingContext& pc) recEvent.addEnergy(it->first, it->second); } } - nte+=ne; - ntt+=nt; + nte += ne; + ntt += nt; if (mVerbosity > 0 && (nt > 0 || ne > 0)) { printf("Orbit %9u bc %4u ntdc %2d ne %2d\n", reca.ir.orbit, reca.ir.bc, nt, ne); } From 2e49f84348f1a9163f5fb5b3c43e8c2f53845967 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Thu, 10 Jun 2021 13:29:57 +0200 Subject: [PATCH 033/770] Configuration parameters for reconstruction - bug fixes --- Detectors/ZDC/macro/CreateRecoConfigZDC.C | 10 ++++++++++ .../include/ZDCReconstruction/RecoParamZDC.h | 4 +--- Detectors/ZDC/reconstruction/src/RecoConfigZDC.cxx | 2 +- Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx | 6 ++---- .../ZDC/reconstruction/src/ZDCReconstructionLinkDef.h | 2 ++ 5 files changed, 16 insertions(+), 8 deletions(-) diff --git a/Detectors/ZDC/macro/CreateRecoConfigZDC.C b/Detectors/ZDC/macro/CreateRecoConfigZDC.C index 9c86552ed8a48..50a902dbf9ac6 100644 --- a/Detectors/ZDC/macro/CreateRecoConfigZDC.C +++ b/Detectors/ZDC/macro/CreateRecoConfigZDC.C @@ -54,6 +54,16 @@ void CreateRecoConfigZDC(long tmin = 0, long tmax = -1, conf.setSearch(TDCZNCS, def_search); conf.setSearch(TDCZPCC, def_search); conf.setSearch(TDCZPCS, def_search); + conf.setSearch(TDCZNAC, 250); + conf.setSearch(TDCZNAS, 251); + conf.setSearch(TDCZPAC, 252); + conf.setSearch(TDCZPAS, 253); + conf.setSearch(TDCZEM1, 254); + conf.setSearch(TDCZEM2, 255); + conf.setSearch(TDCZNCC, 256); + conf.setSearch(TDCZNCS, 257); + conf.setSearch(TDCZPCC, 258); + conf.setSearch(TDCZPCS, 259); // Charge integration int beg_sig = 6; diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h index 4ec25c93a721e..f9670487d5192 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h @@ -24,8 +24,6 @@ namespace o2 { namespace zdc { -// parameters of ZDC reconstruction - struct RecoParamZDC : public o2::conf::ConfigurableParamHelper { Int_t tsh[NTDCChannels] = {4, 4, 4, 4, 4, 4, 4, 4, 4, 4}; // Trigger shift Int_t tth[NTDCChannels] = {8, 8, 8, 8, 8, 8, 8, 8, 8, 8}; // Trigger threshold @@ -44,7 +42,7 @@ struct RecoParamZDC : public o2::conf::ConfigurableParamHelper { std::array bitset = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Set bits in coincidence void setBit(uint32_t ibit, bool val = true); - O2ParamDef(RecoParamZDC, "RecoParamZDC"); + O2ParamDef(RecoParamZDC, "recoparamzdc"); }; } // namespace zdc } // namespace o2 diff --git a/Detectors/ZDC/reconstruction/src/RecoConfigZDC.cxx b/Detectors/ZDC/reconstruction/src/RecoConfigZDC.cxx index a1ec9a852fe4e..f1b42a23bcfae 100644 --- a/Detectors/ZDC/reconstruction/src/RecoConfigZDC.cxx +++ b/Detectors/ZDC/reconstruction/src/RecoConfigZDC.cxx @@ -75,7 +75,7 @@ void RecoConfigZDC::setIntegration(uint32_t ich, int beg, int end, int beg_ped, void RecoConfigZDC::print() { - for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { + for (int itdc = 0; itdc < NTDCChannels; itdc++) { LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << tdc_search[itdc] << " = " << tdc_search[itdc] * FTDCVal << " ns"; } for (Int_t ich = 0; ich < NChannels; ich++) { diff --git a/Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx b/Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx index 013b8ead244f8..4e3755a784790 100644 --- a/Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx +++ b/Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx @@ -11,11 +11,9 @@ #include "FairLogger.h" #include "ZDCReconstruction/RecoParamZDC.h" -using namespace o2::zdc; +O2ParamImpl(o2::zdc::RecoParamZDC); -O2ParamImpl(RecoParamZDC); - -void RecoParamZDC::setBit(uint32_t ibit, bool val) +void o2::zdc::RecoParamZDC::setBit(uint32_t ibit, bool val) { if (ibit >= 0 && ibit < NTDCChannels) { bitset[ibit] = val; diff --git a/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h b/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h index cb520d805b368..30455a4e7e2a3 100644 --- a/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h +++ b/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h @@ -15,6 +15,8 @@ #pragma link off all functions; #pragma link C++ class o2::zdc::RecoConfigZDC + ; +#pragma link C++ class o2::zdc::RecoParamZDC + ; #pragma link C++ class o2::zdc::ZDCTDCParam + ; +#pragma link C++ class o2::zdc::ZDCEnergyParam + ; #endif From 2793e153e0017f0d3a93970b672064f14fc714eb Mon Sep 17 00:00:00 2001 From: shahoian Date: Thu, 10 Jun 2021 15:55:34 +0200 Subject: [PATCH 034/770] fixes --- Detectors/ZDC/reconstruction/CMakeLists.txt | 13 +++++++++---- .../reconstruction/src/ZDCReconstructionLinkDef.h | 2 +- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/Detectors/ZDC/reconstruction/CMakeLists.txt b/Detectors/ZDC/reconstruction/CMakeLists.txt index 9b4ed62286fa7..17366fa81c424 100644 --- a/Detectors/ZDC/reconstruction/CMakeLists.txt +++ b/Detectors/ZDC/reconstruction/CMakeLists.txt @@ -14,14 +14,19 @@ o2_add_library(ZDCReconstruction src/DigiReco.cxx src/RecoParamZDC.cxx src/ZDCTDCParam.cxx +# src/ZDCEnergyParam.cxx src/RecoConfigZDC.cxx PUBLIC_LINK_LIBRARIES O2::ZDCBase O2::DataFormatsZDC O2::ZDCSimulation O2::DetectorsRaw AliceO2::InfoLogger - O2::rANS - Microsoft.GSL::GSL) + O2::rANS + Microsoft.GSL::GSL) -# o2_target_root_dictionary(ZDCReconstruction -# HEADERS ) +o2_target_root_dictionary(ZDCReconstruction + HEADERS include/ZDCReconstruction/RecoConfigZDC.h + include/ZDCReconstruction/RecoParamZDC.h + include/ZDCReconstruction/ZDCTDCParam.h +# include/ZDCReconstruction/ZDCEnergyParam.h + ) diff --git a/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h b/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h index 30455a4e7e2a3..5e83eec6e1323 100644 --- a/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h +++ b/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h @@ -17,6 +17,6 @@ #pragma link C++ class o2::zdc::RecoConfigZDC + ; #pragma link C++ class o2::zdc::RecoParamZDC + ; #pragma link C++ class o2::zdc::ZDCTDCParam + ; -#pragma link C++ class o2::zdc::ZDCEnergyParam + ; +//#pragma link C++ class o2::zdc::ZDCEnergyParam + ; #endif From 8091cd0de9d2606a84fd4231c2f45daf48a44cd2 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 11 Jun 2021 08:43:57 +0200 Subject: [PATCH 035/770] Energy and Tower calibration --- .../ZDC/base/include/ZDCBase/Constants.h | 2 + Detectors/ZDC/macro/CMakeLists.txt | 12 +++- Detectors/ZDC/macro/CreateEnergyCalib.C | 56 ++++++++++++++++ Detectors/ZDC/macro/CreateModuleConfig.C | 2 +- Detectors/ZDC/macro/CreateRecoConfigZDC.C | 12 +--- Detectors/ZDC/macro/CreateSimCondition.C | 2 +- .../{CreateZDCTDCParam.C => CreateTDCCalib.C} | 2 +- Detectors/ZDC/macro/CreateTowerCalib.C | 66 +++++++++++++++++++ Detectors/ZDC/macro/readZDCDigits.C | 3 +- Detectors/ZDC/raw/src/DumpRaw.cxx | 2 +- Detectors/ZDC/reconstruction/CMakeLists.txt | 6 +- .../include/ZDCReconstruction/DigiReco.h | 2 +- .../include/ZDCReconstruction/RecoParamZDC.h | 23 ++++--- .../ZDCReconstruction/ZDCEnergyParam.h | 12 ++-- .../include/ZDCReconstruction/ZDCTowerParam.h | 36 ++++++++++ Detectors/ZDC/reconstruction/src/DigiReco.cxx | 2 +- .../ZDC/reconstruction/src/RecoConfigZDC.cxx | 2 +- .../ZDC/reconstruction/src/RecoParamZDC.cxx | 2 +- .../ZDC/reconstruction/src/ZDCEnergyParam.cxx | 54 +++++++++++++++ .../src/ZDCReconstructionLinkDef.h | 3 +- .../ZDC/reconstruction/src/ZDCTDCParam.cxx | 2 +- .../ZDC/reconstruction/src/ZDCTowerParam.cxx | 55 ++++++++++++++++ Detectors/ZDC/simulation/src/Detector.cxx | 2 +- Detectors/ZDC/simulation/src/Digitizer.cxx | 2 +- Detectors/ZDC/simulation/src/Digits2Raw.cxx | 3 +- .../include/ZDCWorkflow/DigitRecoSpec.h | 2 +- Detectors/ZDC/workflow/src/DigitRecoSpec.cxx | 3 +- 27 files changed, 324 insertions(+), 46 deletions(-) create mode 100644 Detectors/ZDC/macro/CreateEnergyCalib.C rename Detectors/ZDC/macro/{CreateZDCTDCParam.C => CreateTDCCalib.C} (98%) create mode 100644 Detectors/ZDC/macro/CreateTowerCalib.C create mode 100644 Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTowerParam.h create mode 100644 Detectors/ZDC/reconstruction/src/ZDCEnergyParam.cxx create mode 100644 Detectors/ZDC/reconstruction/src/ZDCTowerParam.cxx diff --git a/Detectors/ZDC/base/include/ZDCBase/Constants.h b/Detectors/ZDC/base/include/ZDCBase/Constants.h index f42fc8c0c72ae..e566c4457768b 100644 --- a/Detectors/ZDC/base/include/ZDCBase/Constants.h +++ b/Detectors/ZDC/base/include/ZDCBase/Constants.h @@ -213,6 +213,8 @@ const std::string CCDBPathConfigModule = "ZDC/Config/Module"; const std::string CCDBPathConfigReco = "ZDC/Calib/RecoParam"; const std::string CCDBPathRecoConfigZDC = "ZDC/Calib/RecoConfigZDC"; const std::string CCDBPathTDCCalib = "ZDC/Calib/TDCCalib"; +const std::string CCDBPathEnergyCalib = "ZDC/Calib/EnergyCalib"; +const std::string CCDBPathTowerCalib = "ZDC/Calib/TowerCalib"; // Placeholders constexpr int DummyIntRange = -NTimeBinsPerBC - 1; diff --git a/Detectors/ZDC/macro/CMakeLists.txt b/Detectors/ZDC/macro/CMakeLists.txt index c8ff2d64fb6fa..09f5b61697d23 100644 --- a/Detectors/ZDC/macro/CMakeLists.txt +++ b/Detectors/ZDC/macro/CMakeLists.txt @@ -26,7 +26,17 @@ o2_add_test_root_macro(CreateRecoConfigZDC.C O2::SimulationDataFormat O2::CCDB LABELS zdc) -o2_add_test_root_macro(CreateZDCTDCParam.C +o2_add_test_root_macro(CreateTDCCalib.C + PUBLIC_LINK_LIBRARIES O2::ZDCBase O2::ZDCReconstruction + O2::SimulationDataFormat O2::CCDB + LABELS zdc) + +o2_add_test_root_macro(CreateEnergyCalib.C + PUBLIC_LINK_LIBRARIES O2::ZDCBase O2::ZDCReconstruction + O2::SimulationDataFormat O2::CCDB + LABELS zdc) + +o2_add_test_root_macro(CreateTowerCalib.C PUBLIC_LINK_LIBRARIES O2::ZDCBase O2::ZDCReconstruction O2::SimulationDataFormat O2::CCDB LABELS zdc) diff --git a/Detectors/ZDC/macro/CreateEnergyCalib.C b/Detectors/ZDC/macro/CreateEnergyCalib.C new file mode 100644 index 0000000000000..b206b1e6bb31b --- /dev/null +++ b/Detectors/ZDC/macro/CreateEnergyCalib.C @@ -0,0 +1,56 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#if !defined(__CLING__) || defined(__ROOTCLING__) + +#include "Framework/Logger.h" +#include "CCDB/CcdbApi.h" +#include "ZDCBase/Constants.h" +#include "ZDCReconstruction/ZDCEnergyParam.h" +#include +#include +#include + +#endif + +using namespace o2::zdc; +using namespace std; + +void CreateEnergyCalib(long tmin = 0, long tmax = -1, + std::string ccdbHost = "http://ccdb-test.cern.ch:8080") +{ + + ZDCEnergyParam conf; + + // This object allows for the calibration of 4 common photomultipliers and 2 ZEM + // Optionally also the analog sum can have a calibration coefficient otherwise + // the coefficient of the common PM will be used + conf.setEnergyCalib(IdZNAC, 1.); + conf.setEnergyCalib(IdZPAC, 1.); + conf.setEnergyCalib(IdZEM1, 1.); + conf.setEnergyCalib(IdZEM2, 1.); + conf.setEnergyCalib(IdZNCC, 1.); + conf.setEnergyCalib(IdZPCC, 1.); + +// conf.setEnergyCalib(IdZNASum, 1.); +// conf.setEnergyCalib(IdZPASum, 1.); +// conf.setEnergyCalib(IdZNCSum, 1.); +// conf.setEnergyCalib(IdZPCSum, 1.); + + conf.print(); + + o2::ccdb::CcdbApi api; + map metadata; // can be empty + api.init(ccdbHost.c_str()); // or http://localhost:8080 for a local installation + // store abitrary user object in strongly typed manner + api.storeAsTFileAny(&conf, CCDBPathEnergyCalib, metadata, tmin, tmax); + + // return conf; +} diff --git a/Detectors/ZDC/macro/CreateModuleConfig.C b/Detectors/ZDC/macro/CreateModuleConfig.C index 164a71bb83d1f..4899e461ebba2 100644 --- a/Detectors/ZDC/macro/CreateModuleConfig.C +++ b/Detectors/ZDC/macro/CreateModuleConfig.C @@ -10,7 +10,7 @@ #if !defined(__CLING__) || defined(__ROOTCLING__) -#include "FairLogger.h" +#include "Framework/Logger.h" #include "CCDB/CcdbApi.h" #include "ZDCBase/ModuleConfig.h" #include "ZDCBase/Constants.h" diff --git a/Detectors/ZDC/macro/CreateRecoConfigZDC.C b/Detectors/ZDC/macro/CreateRecoConfigZDC.C index 50a902dbf9ac6..20416b9480f47 100644 --- a/Detectors/ZDC/macro/CreateRecoConfigZDC.C +++ b/Detectors/ZDC/macro/CreateRecoConfigZDC.C @@ -10,7 +10,7 @@ #if !defined(__CLING__) || defined(__ROOTCLING__) -#include "FairLogger.h" +#include "Framework/Logger.h" #include "CCDB/CcdbApi.h" #include "ZDCReconstruction/RecoConfigZDC.h" #include "ZDCBase/Constants.h" @@ -54,16 +54,6 @@ void CreateRecoConfigZDC(long tmin = 0, long tmax = -1, conf.setSearch(TDCZNCS, def_search); conf.setSearch(TDCZPCC, def_search); conf.setSearch(TDCZPCS, def_search); - conf.setSearch(TDCZNAC, 250); - conf.setSearch(TDCZNAS, 251); - conf.setSearch(TDCZPAC, 252); - conf.setSearch(TDCZPAS, 253); - conf.setSearch(TDCZEM1, 254); - conf.setSearch(TDCZEM2, 255); - conf.setSearch(TDCZNCC, 256); - conf.setSearch(TDCZNCS, 257); - conf.setSearch(TDCZPCC, 258); - conf.setSearch(TDCZPCS, 259); // Charge integration int beg_sig = 6; diff --git a/Detectors/ZDC/macro/CreateSimCondition.C b/Detectors/ZDC/macro/CreateSimCondition.C index e93b14e883a28..fc283254b1ed7 100644 --- a/Detectors/ZDC/macro/CreateSimCondition.C +++ b/Detectors/ZDC/macro/CreateSimCondition.C @@ -9,7 +9,7 @@ // or submit itself to any jurisdiction. #if !defined(__CLING__) || defined(__ROOTCLING__) -#include "FairLogger.h" +#include "Framework/Logger.h" #include "CCDB/CcdbApi.h" #include #include diff --git a/Detectors/ZDC/macro/CreateZDCTDCParam.C b/Detectors/ZDC/macro/CreateTDCCalib.C similarity index 98% rename from Detectors/ZDC/macro/CreateZDCTDCParam.C rename to Detectors/ZDC/macro/CreateTDCCalib.C index 4c919f6f729a2..cc8db9e99b905 100644 --- a/Detectors/ZDC/macro/CreateZDCTDCParam.C +++ b/Detectors/ZDC/macro/CreateTDCCalib.C @@ -9,7 +9,7 @@ // or submit itself to any jurisdiction. #if !defined(__CLING__) || defined(__ROOTCLING__) -#include "FairLogger.h" +#include "Framework/Logger.h" #include "CCDB/CcdbApi.h" #include #include diff --git a/Detectors/ZDC/macro/CreateTowerCalib.C b/Detectors/ZDC/macro/CreateTowerCalib.C new file mode 100644 index 0000000000000..3538f8985648e --- /dev/null +++ b/Detectors/ZDC/macro/CreateTowerCalib.C @@ -0,0 +1,66 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#if !defined(__CLING__) || defined(__ROOTCLING__) + +#include "Framework/Logger.h" +#include "CCDB/CcdbApi.h" +#include "ZDCBase/Constants.h" +#include "ZDCReconstruction/ZDCTowerParam.h" +#include +#include +#include + +#endif + +using namespace o2::zdc; +using namespace std; + +void CreateTowerCalib(long tmin = 0, long tmax = -1, + std::string ccdbHost = "http://ccdb-test.cern.ch:8080") +{ + + ZDCTowerParam conf; + + // This object allows for the calibration of the 4 towers of each calorimeter + // The relative calibration coefficients of towers w.r.t. the common PM + // need to be provided + + conf.setTowerCalib(IdZNA1, 1.); + conf.setTowerCalib(IdZNA2, 1.); + conf.setTowerCalib(IdZNA3, 1.); + conf.setTowerCalib(IdZNA4, 1.); + + conf.setTowerCalib(IdZPA1, 1.); + conf.setTowerCalib(IdZPA2, 1.); + conf.setTowerCalib(IdZPA3, 1.); + conf.setTowerCalib(IdZPA4, 1.); + + conf.setTowerCalib(IdZNC1, 1.); + conf.setTowerCalib(IdZNC2, 1.); + conf.setTowerCalib(IdZNC3, 1.); + conf.setTowerCalib(IdZNC4, 1.); + + conf.setTowerCalib(IdZPC1, 1.); + conf.setTowerCalib(IdZPC2, 1.); + conf.setTowerCalib(IdZPC3, 1.); + conf.setTowerCalib(IdZPC4, 1.); + + conf.check(); + conf.print(); + + o2::ccdb::CcdbApi api; + map metadata; // can be empty + api.init(ccdbHost.c_str()); // or http://localhost:8080 for a local installation + // store abitrary user object in strongly typed manner + api.storeAsTFileAny(&conf, CCDBPathTowerCalib, metadata, tmin, tmax); + + // return conf; +} diff --git a/Detectors/ZDC/macro/readZDCDigits.C b/Detectors/ZDC/macro/readZDCDigits.C index 7e24de75a773b..58022a9699a21 100644 --- a/Detectors/ZDC/macro/readZDCDigits.C +++ b/Detectors/ZDC/macro/readZDCDigits.C @@ -13,7 +13,8 @@ #endif #include "DataFormatsZDC/MCLabel.h" -#include "FairLogger.h" +#include "Framework/Logger.h" + /// Example of accessing the ZDC digits diff --git a/Detectors/ZDC/raw/src/DumpRaw.cxx b/Detectors/ZDC/raw/src/DumpRaw.cxx index c4d1da110dc2a..c8af09e2ac0b7 100644 --- a/Detectors/ZDC/raw/src/DumpRaw.cxx +++ b/Detectors/ZDC/raw/src/DumpRaw.cxx @@ -16,7 +16,7 @@ #include "ZDCRaw/DumpRaw.h" #include "CommonConstants/LHCConstants.h" #include "ZDCSimulation/Digits2Raw.h" -#include "FairLogger.h" +#include "Framework/Logger.h" using namespace o2::zdc; diff --git a/Detectors/ZDC/reconstruction/CMakeLists.txt b/Detectors/ZDC/reconstruction/CMakeLists.txt index 17366fa81c424..f7f0627e5b864 100644 --- a/Detectors/ZDC/reconstruction/CMakeLists.txt +++ b/Detectors/ZDC/reconstruction/CMakeLists.txt @@ -14,7 +14,8 @@ o2_add_library(ZDCReconstruction src/DigiReco.cxx src/RecoParamZDC.cxx src/ZDCTDCParam.cxx -# src/ZDCEnergyParam.cxx + src/ZDCEnergyParam.cxx + src/ZDCTowerParam.cxx src/RecoConfigZDC.cxx PUBLIC_LINK_LIBRARIES O2::ZDCBase O2::DataFormatsZDC @@ -28,5 +29,6 @@ o2_target_root_dictionary(ZDCReconstruction HEADERS include/ZDCReconstruction/RecoConfigZDC.h include/ZDCReconstruction/RecoParamZDC.h include/ZDCReconstruction/ZDCTDCParam.h -# include/ZDCReconstruction/ZDCEnergyParam.h + include/ZDCReconstruction/ZDCEnergyParam.h + include/ZDCReconstruction/ZDCTowerParam.h ) diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h index fb0943cd92ad3..3c58eac13aea9 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h @@ -12,7 +12,7 @@ #include #include #include -#include "FairLogger.h" +#include "Framework/Logger.h" #include "ZDCBase/Constants.h" #include "ZDCSimulation/ZDCSimParam.h" #include "ZDCReconstruction/RecoParamZDC.h" diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h index f9670487d5192..b8c08ed1690d2 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h @@ -25,23 +25,30 @@ namespace o2 namespace zdc { struct RecoParamZDC : public o2::conf::ConfigurableParamHelper { - Int_t tsh[NTDCChannels] = {4, 4, 4, 4, 4, 4, 4, 4, 4, 4}; // Trigger shift - Int_t tth[NTDCChannels] = {8, 8, 8, 8, 8, 8, 8, 8, 8, 8}; // Trigger threshold - Int_t tmod[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of TDC channel in raw data - Int_t tch[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of TDC channel in raw data + // Trigger + Int_t tsh[NTDCChannels] = {4, 4, 4, 4, 4, 4, 4, 4, 4, 4}; // Trigger shift + Int_t tth[NTDCChannels] = {8, 8, 8, 8, 8, 8, 8, 8, 8, 8}; // Trigger threshold + std::array bitset = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Set bits in coincidence + void setBit(uint32_t ibit, bool val = true); + + // TDC + Int_t tmod[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of TDC channel in raw data + Int_t tch[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of TDC channel in raw data + float tdc_shift[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Correction of TDC position (0-25 ns, units of ~10 ps) + float tdc_search[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Search zone for a TDC signal ideally 2.5 ns (units of ~10 ps) + + // Charge integration Int_t amod[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of ADC channel in raw data Int_t ach[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of ADC channel in raw data - float tdc_shift[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Correction of TDC position (0-25 ns, units of ~10 ps) - float tdc_search[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Search zone for a TDC signal ideally 2.5 ns (units of ~10 ps) // Beginning and end of integration range: signal Int_t beg_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; Int_t end_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; // Beginning and end of integration range: pedestal Int_t beg_ped_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; Int_t end_ped_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; - std::array bitset = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Set bits in coincidence - void setBit(uint32_t ibit, bool val = true); + // Energy calibration + float energy_calib[NChannels] = {0}; // Energy calibration coefficients O2ParamDef(RecoParamZDC, "recoparamzdc"); }; } // namespace zdc diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCEnergyParam.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCEnergyParam.h index a15b882bfde2e..3fbbe3ebcd105 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCEnergyParam.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCEnergyParam.h @@ -16,22 +16,18 @@ #include /// \file ZDCEnergyParam.h -/// \brief Parameters to correct TDCs +/// \brief ZDC Energy calibration /// \author P. Cortese namespace o2 { namespace zdc { -// parameters of ZDC reconstruction - struct ZDCEnergyParam { - //std::array tdcShift{} - float tdc_shift[NTDCChannels] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Correction of TDC position (ns) - void setShift(uint32_t ich, float val); - float getShift(uint32_t ich) const; + float energy_calib[NChannels] = {0}; // Energy calibration coefficients + void setEnergyCalib(uint32_t ich, float val); + float getEnergyCalib(uint32_t ich) const; void print(); - ClassDefNV(ZDCEnergyParam, 1); }; } // namespace zdc diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTowerParam.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTowerParam.h new file mode 100644 index 0000000000000..31b6db95c8503 --- /dev/null +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTowerParam.h @@ -0,0 +1,36 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_ZDC_TOWERPARAM_H +#define O2_ZDC_TOWERPARAM_H + +#include "ZDCBase/Constants.h" +#include +#include + +/// \file ZDCTowerParam.h +/// \brief ZDC Tower calibration +/// \author P. Cortese + +namespace o2 +{ +namespace zdc +{ +struct ZDCTowerParam { + float tower_calib[NChannels] = {0}; // Tower calibration coefficients + void setTowerCalib(uint32_t ich, float val); + float getTowerCalib(uint32_t ich) const; + void print(); + ClassDefNV(ZDCTowerParam, 1); +}; +} // namespace zdc +} // namespace o2 + +#endif diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index bc38a585d7d8e..98c4c1f0b931e 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -9,7 +9,7 @@ // or submit itself to any jurisdiction. #include -#include "FairLogger.h" +#include "Framework/Logger.h" #include "ZDCReconstruction/DigiReco.h" #include "ZDCReconstruction/RecoParamZDC.h" diff --git a/Detectors/ZDC/reconstruction/src/RecoConfigZDC.cxx b/Detectors/ZDC/reconstruction/src/RecoConfigZDC.cxx index f1b42a23bcfae..21ffe398822dd 100644 --- a/Detectors/ZDC/reconstruction/src/RecoConfigZDC.cxx +++ b/Detectors/ZDC/reconstruction/src/RecoConfigZDC.cxx @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#include "FairLogger.h" +#include "Framework/Logger.h" #include "ZDCReconstruction/RecoConfigZDC.h" using namespace o2::zdc; diff --git a/Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx b/Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx index 4e3755a784790..8a5a2ca330697 100644 --- a/Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx +++ b/Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#include "FairLogger.h" +#include "Framework/Logger.h" #include "ZDCReconstruction/RecoParamZDC.h" O2ParamImpl(o2::zdc::RecoParamZDC); diff --git a/Detectors/ZDC/reconstruction/src/ZDCEnergyParam.cxx b/Detectors/ZDC/reconstruction/src/ZDCEnergyParam.cxx new file mode 100644 index 0000000000000..241bb738cde2a --- /dev/null +++ b/Detectors/ZDC/reconstruction/src/ZDCEnergyParam.cxx @@ -0,0 +1,54 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "Framework/Logger.h" +#include "ZDCReconstruction/ZDCEnergyParam.h" + +using namespace o2::zdc; + +void ZDCEnergyParam::setEnergyCalib(uint32_t ich, float val) +{ + constexpr std::array chlist{IdZNAC, IdZNASum, IdZPAC, IdZPASum, + IdZEM1, IdZEM2, + IdZNCC, IdZNCSum, IdZPCC, IdZPCSum}; + bool in_list = in_list; + for (int il = 0; il < chlist.size(); il++) { + if (ich == chlist[il]) { + in_list = true; + break; + } + } + if (in_list) { + energy_calib[ich] = val; + } else { + LOG(FATAL) << __func__ << " channel " << ich << " not in allowed range"; + for (int il = 0; il < chlist.size(); il++) { + LOG(info) << __func__ << " channel " << chlist[il] << " " << ChannelNames[chlist[il]]; + } + } +} + +float ZDCEnergyParam::getEnergyCalib(uint32_t ich) const +{ + if (ich >= 0 && ich < NChannels) { + return energy_calib[ich]; + } else { + LOG(FATAL) << __func__ << " channel " << ich << " not in allowed range"; + return 0; + } +} + +void ZDCEnergyParam::print() +{ + for (Int_t ich = 0; ich < NChannels; ich++) { + if (energy_calib[ich] > 0) + LOG(INFO) << ChannelNames[ich] << " calibration factor = " << energy_calib[ich]; + } +} diff --git a/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h b/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h index 5e83eec6e1323..0d600e2f064d6 100644 --- a/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h +++ b/Detectors/ZDC/reconstruction/src/ZDCReconstructionLinkDef.h @@ -17,6 +17,7 @@ #pragma link C++ class o2::zdc::RecoConfigZDC + ; #pragma link C++ class o2::zdc::RecoParamZDC + ; #pragma link C++ class o2::zdc::ZDCTDCParam + ; -//#pragma link C++ class o2::zdc::ZDCEnergyParam + ; +#pragma link C++ class o2::zdc::ZDCEnergyParam + ; +#pragma link C++ class o2::zdc::ZDCTowerParam + ; #endif diff --git a/Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx b/Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx index e38ec89814fa4..981b8f5cd70cb 100644 --- a/Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx +++ b/Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#include "FairLogger.h" +#include "Framework/Logger.h" #include "ZDCReconstruction/ZDCTDCParam.h" using namespace o2::zdc; diff --git a/Detectors/ZDC/reconstruction/src/ZDCTowerParam.cxx b/Detectors/ZDC/reconstruction/src/ZDCTowerParam.cxx new file mode 100644 index 0000000000000..325177e8da092 --- /dev/null +++ b/Detectors/ZDC/reconstruction/src/ZDCTowerParam.cxx @@ -0,0 +1,55 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "Framework/Logger.h" +#include "ZDCReconstruction/ZDCTowerParam.h" + +using namespace o2::zdc; + +void ZDCTowerParam::setTowerCalib(uint32_t ich, float val) +{ + constexpr std::array chlist{IdZNA1, IdZNA2, IdZNA3, IdZNA4, + IdZPA1, IdZPA2, IdZPA3, IdZPA4, + IdZNC1, IdZNC2, IdZNC3, IdZNC4, + IdZPC1, IdZPC2, IdZPC3, IdZPC4}; + bool in_list = in_list; + for (int il = 0; il < chlist.size(); il++) { + if (ich == chlist[il]) { + in_list = true; + break; + } + } + if (in_list) { + tower_calib[ich] = val; + } else { + LOG(FATAL) << __func__ << " channel " << ich << " not in allowed range"; + for (int il = 0; il < chlist.size(); il++) { + LOG(info) << __func__ << " channel " << chlist[il] << " " << ChannelNames[chlist[il]]; + } + } +} + +float ZDCTowerParam::getTowerCalib(uint32_t ich) const +{ + if (ich >= 0 && ich < NChannels) { + return tower_calib[ich]; + } else { + LOG(FATAL) << __func__ << " channel " << ich << " not in allowed range"; + return 0; + } +} + +void ZDCTowerParam::print() +{ + for (Int_t ich = 0; ich < NChannels; ich++) { + if (tower_calib[ich] > 0) + LOG(INFO) << ChannelNames[ich] << " calibration factor = " << tower_calib[ich]; + } +} diff --git a/Detectors/ZDC/simulation/src/Detector.cxx b/Detectors/ZDC/simulation/src/Detector.cxx index c7aa11af57f9b..b2e5008bd7eaa 100644 --- a/Detectors/ZDC/simulation/src/Detector.cxx +++ b/Detectors/ZDC/simulation/src/Detector.cxx @@ -9,7 +9,7 @@ // or submit itself to any jurisdiction. // FairRoot includes -#include "FairLogger.h" // for LOG, LOG_IF +#include "Framework/Logger.h" #include "FairRootManager.h" // for FairRootManager #include "FairVolume.h" // for FairVolume #include "DetectorsBase/MaterialManager.h" diff --git a/Detectors/ZDC/simulation/src/Digitizer.cxx b/Detectors/ZDC/simulation/src/Digitizer.cxx index 3c32fbd2d6422..345dd24e058f1 100644 --- a/Detectors/ZDC/simulation/src/Digitizer.cxx +++ b/Detectors/ZDC/simulation/src/Digitizer.cxx @@ -11,11 +11,11 @@ #include "CommonConstants/LHCConstants.h" #include "CCDB/BasicCCDBManager.h" #include "CCDB/CCDBTimeStampUtils.h" +#include "Framework/Logger.h" #include "ZDCSimulation/Digitizer.h" #include "ZDCSimulation/SimCondition.h" #include "ZDCSimulation/ZDCSimParam.h" #include -#include using namespace o2::zdc; diff --git a/Detectors/ZDC/simulation/src/Digits2Raw.cxx b/Detectors/ZDC/simulation/src/Digits2Raw.cxx index c4e04c6568d48..230848864d971 100644 --- a/Detectors/ZDC/simulation/src/Digits2Raw.cxx +++ b/Detectors/ZDC/simulation/src/Digits2Raw.cxx @@ -19,7 +19,8 @@ #include "ZDCSimulation/Digits2Raw.h" #include "ZDCSimulation/ZDCSimParam.h" #include "CommonUtils/StringUtils.h" -#include "FairLogger.h" +#include "Framework/Logger.h" + using namespace o2::zdc; diff --git a/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h b/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h index a93c6837c4ff3..c52ebe16df429 100644 --- a/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h +++ b/Detectors/ZDC/workflow/include/ZDCWorkflow/DigitRecoSpec.h @@ -15,7 +15,7 @@ #ifndef O2_ZDC_DIGITRECO_SPEC #define O2_ZDC_DIGITRECO_SPEC -#include "FairLogger.h" +#include "Framework/Logger.h" #include "Framework/DataProcessorSpec.h" #include "Framework/Task.h" #include "ZDCReconstruction/DigiReco.h" diff --git a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx index 3e95d6ba0cff1..e61725b9e8bc0 100644 --- a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx +++ b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx @@ -15,6 +15,7 @@ #include #include "CCDB/BasicCCDBManager.h" #include "CCDB/CCDBTimeStampUtils.h" +#include "Framework/Logger.h" #include "Framework/ControlService.h" #include "Framework/ConfigParamRegistry.h" #include "ZDCWorkflow/DigitRecoSpec.h" @@ -24,7 +25,7 @@ #include "DataFormatsZDC/OrbitData.h" #include "DataFormatsZDC/RecEvent.h" #include "ZDCBase/ModuleConfig.h" -#include "FairLogger.h" + #include "CCDB/BasicCCDBManager.h" #include "CCDB/CCDBTimeStampUtils.h" #include "ZDCReconstruction/RecoConfigZDC.h" From 4e75a4d5cab8d623db35ba9e2a038293f5666359 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 11 Jun 2021 08:57:29 +0200 Subject: [PATCH 036/770] Correcting spaces --- Detectors/ZDC/macro/CreateTowerCalib.C | 1 - Detectors/ZDC/reconstruction/src/ZDCEnergyParam.cxx | 11 ++++++----- Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx | 2 +- Detectors/ZDC/reconstruction/src/ZDCTowerParam.cxx | 13 +++++++------ Detectors/ZDC/simulation/src/Detector.cxx | 8 ++++---- 5 files changed, 18 insertions(+), 17 deletions(-) diff --git a/Detectors/ZDC/macro/CreateTowerCalib.C b/Detectors/ZDC/macro/CreateTowerCalib.C index 3538f8985648e..70992ae5c254a 100644 --- a/Detectors/ZDC/macro/CreateTowerCalib.C +++ b/Detectors/ZDC/macro/CreateTowerCalib.C @@ -53,7 +53,6 @@ void CreateTowerCalib(long tmin = 0, long tmax = -1, conf.setTowerCalib(IdZPC3, 1.); conf.setTowerCalib(IdZPC4, 1.); - conf.check(); conf.print(); o2::ccdb::CcdbApi api; diff --git a/Detectors/ZDC/reconstruction/src/ZDCEnergyParam.cxx b/Detectors/ZDC/reconstruction/src/ZDCEnergyParam.cxx index 241bb738cde2a..7d2949e926833 100644 --- a/Detectors/ZDC/reconstruction/src/ZDCEnergyParam.cxx +++ b/Detectors/ZDC/reconstruction/src/ZDCEnergyParam.cxx @@ -15,9 +15,9 @@ using namespace o2::zdc; void ZDCEnergyParam::setEnergyCalib(uint32_t ich, float val) { - constexpr std::array chlist{IdZNAC, IdZNASum, IdZPAC, IdZPASum, - IdZEM1, IdZEM2, - IdZNCC, IdZNCSum, IdZPCC, IdZPCSum}; + constexpr std::array chlist{IdZNAC, IdZNASum, IdZPAC, IdZPASum, + IdZEM1, IdZEM2, + IdZNCC, IdZNCSum, IdZPCC, IdZPCSum}; bool in_list = in_list; for (int il = 0; il < chlist.size(); il++) { if (ich == chlist[il]) { @@ -48,7 +48,8 @@ float ZDCEnergyParam::getEnergyCalib(uint32_t ich) const void ZDCEnergyParam::print() { for (Int_t ich = 0; ich < NChannels; ich++) { - if (energy_calib[ich] > 0) - LOG(INFO) << ChannelNames[ich] << " calibration factor = " << energy_calib[ich]; + if (energy_calib[ich] > 0) { + LOG(INFO) << ChannelNames[ich] << " calibration factor = " << energy_calib[ich]; + } } } diff --git a/Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx b/Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx index 981b8f5cd70cb..5a06eea79b1db 100644 --- a/Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx +++ b/Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx @@ -35,6 +35,6 @@ float ZDCTDCParam::getShift(uint32_t ich) const void ZDCTDCParam::print() { for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { - LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " shift = " << tdc_shift[itdc] << " ns"; + LOG(INFO) << ChannelNames[TDCSignal[itdc]] << " shift = " << tdc_shift[itdc] << " ns"; } } diff --git a/Detectors/ZDC/reconstruction/src/ZDCTowerParam.cxx b/Detectors/ZDC/reconstruction/src/ZDCTowerParam.cxx index 325177e8da092..15c8d9af9335b 100644 --- a/Detectors/ZDC/reconstruction/src/ZDCTowerParam.cxx +++ b/Detectors/ZDC/reconstruction/src/ZDCTowerParam.cxx @@ -15,10 +15,10 @@ using namespace o2::zdc; void ZDCTowerParam::setTowerCalib(uint32_t ich, float val) { - constexpr std::array chlist{IdZNA1, IdZNA2, IdZNA3, IdZNA4, - IdZPA1, IdZPA2, IdZPA3, IdZPA4, - IdZNC1, IdZNC2, IdZNC3, IdZNC4, - IdZPC1, IdZPC2, IdZPC3, IdZPC4}; + constexpr std::array chlist{IdZNA1, IdZNA2, IdZNA3, IdZNA4, + IdZPA1, IdZPA2, IdZPA3, IdZPA4, + IdZNC1, IdZNC2, IdZNC3, IdZNC4, + IdZPC1, IdZPC2, IdZPC3, IdZPC4}; bool in_list = in_list; for (int il = 0; il < chlist.size(); il++) { if (ich == chlist[il]) { @@ -49,7 +49,8 @@ float ZDCTowerParam::getTowerCalib(uint32_t ich) const void ZDCTowerParam::print() { for (Int_t ich = 0; ich < NChannels; ich++) { - if (tower_calib[ich] > 0) - LOG(INFO) << ChannelNames[ich] << " calibration factor = " << tower_calib[ich]; + if (tower_calib[ich] > 0) { + LOG(INFO) << ChannelNames[ich] << " calibration factor = " << tower_calib[ich]; + } } } diff --git a/Detectors/ZDC/simulation/src/Detector.cxx b/Detectors/ZDC/simulation/src/Detector.cxx index b2e5008bd7eaa..d8431218823fd 100644 --- a/Detectors/ZDC/simulation/src/Detector.cxx +++ b/Detectors/ZDC/simulation/src/Detector.cxx @@ -124,8 +124,8 @@ void Detector::InitializeO2Detector() // check a few values to test correctness of reading from file light22620362207s /*assert(std::abs(mLightTableZN[0][ZNRADIUSBINS - 1][0] - 1.39742) < 1.E-4); // beta=0; radius = ZNRADIUSBINS - 1; anglebin = 2; assert(std::abs(mLightTableZN[0][ZNRADIUSBINS - 1][1] - .45017) < 1.E-4); // beta=1; radius = ZNRADIUSBINS - 1; anglebin = 2; - assert(std::abs(mLightTableZN[0][0][2] - .47985) < 1.E-4); // beta=0; radius = 0; anglebin = 2; - assert(std::abs(mLightTableZN[0][0][11] - .01358) < 1.E-4); // beta=0; radius = 0; anglebin = 11; + assert(std::abs(mLightTableZN[0][0][2] - .47985) < 1.E-4); // beta=0; radius = 0; anglebin = 2; + assert(std::abs(mLightTableZN[0][0][11] - .01358) < 1.E-4); // beta=0; radius = 0; anglebin = 11; */ //ZP case @@ -994,7 +994,7 @@ void Detector::createAsideBeamLine() // The following tube ID 212.7 mm // represents VMBGA (400 mm) + VCDWE (300 mm) + VMBGA (400 mm) + - // BTVTS (600 mm) + VMLGB (400 mm) + // BTVTS (600 mm) + VMLGB (400 mm) tubpar[0] = 21.27 / 2.; tubpar[1] = 21.87 / 2.; tubpar[2] = 210.0 / 2.; @@ -1016,7 +1016,7 @@ void Detector::createAsideBeamLine() zA += 2. * conpar[0] + 0.37 + 1.35; // The following tube ID 797 mm represents the second part of VCTCC (4272 mm) + - // 4 x VCDGA (4 x 4272 mm) + the first part of VCTCR (850 mm) + // 4 x VCDGA (4 x 4272 mm) + the first part of VCTCR (850 mm) tubpar[0] = 79.7 / 2.; tubpar[1] = 81.3 / 2.; tubpar[2] = (2221. - 136.) / 2.; From 742685e8a07efe82dd9b9ee9083407ed327b1656 Mon Sep 17 00:00:00 2001 From: ALICE Action Bot Date: Fri, 11 Jun 2021 06:58:24 +0000 Subject: [PATCH 037/770] Please consider the following formatting changes --- Detectors/ZDC/macro/CreateEnergyCalib.C | 10 +++++----- Detectors/ZDC/macro/CreateTowerCalib.C | 2 +- Detectors/ZDC/macro/readZDCDigits.C | 1 - Detectors/ZDC/simulation/src/Digits2Raw.cxx | 1 - 4 files changed, 6 insertions(+), 8 deletions(-) diff --git a/Detectors/ZDC/macro/CreateEnergyCalib.C b/Detectors/ZDC/macro/CreateEnergyCalib.C index b206b1e6bb31b..c363e00fb0658 100644 --- a/Detectors/ZDC/macro/CreateEnergyCalib.C +++ b/Detectors/ZDC/macro/CreateEnergyCalib.C @@ -24,7 +24,7 @@ using namespace o2::zdc; using namespace std; void CreateEnergyCalib(long tmin = 0, long tmax = -1, - std::string ccdbHost = "http://ccdb-test.cern.ch:8080") + std::string ccdbHost = "http://ccdb-test.cern.ch:8080") { ZDCEnergyParam conf; @@ -39,10 +39,10 @@ void CreateEnergyCalib(long tmin = 0, long tmax = -1, conf.setEnergyCalib(IdZNCC, 1.); conf.setEnergyCalib(IdZPCC, 1.); -// conf.setEnergyCalib(IdZNASum, 1.); -// conf.setEnergyCalib(IdZPASum, 1.); -// conf.setEnergyCalib(IdZNCSum, 1.); -// conf.setEnergyCalib(IdZPCSum, 1.); + // conf.setEnergyCalib(IdZNASum, 1.); + // conf.setEnergyCalib(IdZPASum, 1.); + // conf.setEnergyCalib(IdZNCSum, 1.); + // conf.setEnergyCalib(IdZPCSum, 1.); conf.print(); diff --git a/Detectors/ZDC/macro/CreateTowerCalib.C b/Detectors/ZDC/macro/CreateTowerCalib.C index 70992ae5c254a..08dc410a58246 100644 --- a/Detectors/ZDC/macro/CreateTowerCalib.C +++ b/Detectors/ZDC/macro/CreateTowerCalib.C @@ -24,7 +24,7 @@ using namespace o2::zdc; using namespace std; void CreateTowerCalib(long tmin = 0, long tmax = -1, - std::string ccdbHost = "http://ccdb-test.cern.ch:8080") + std::string ccdbHost = "http://ccdb-test.cern.ch:8080") { ZDCTowerParam conf; diff --git a/Detectors/ZDC/macro/readZDCDigits.C b/Detectors/ZDC/macro/readZDCDigits.C index 58022a9699a21..5f148b87443f9 100644 --- a/Detectors/ZDC/macro/readZDCDigits.C +++ b/Detectors/ZDC/macro/readZDCDigits.C @@ -15,7 +15,6 @@ #include "DataFormatsZDC/MCLabel.h" #include "Framework/Logger.h" - /// Example of accessing the ZDC digits void readZDCDigits(std::string digiFName = "zdcdigits.root") diff --git a/Detectors/ZDC/simulation/src/Digits2Raw.cxx b/Detectors/ZDC/simulation/src/Digits2Raw.cxx index 230848864d971..fdcf1f4b3c047 100644 --- a/Detectors/ZDC/simulation/src/Digits2Raw.cxx +++ b/Detectors/ZDC/simulation/src/Digits2Raw.cxx @@ -21,7 +21,6 @@ #include "CommonUtils/StringUtils.h" #include "Framework/Logger.h" - using namespace o2::zdc; //ClassImp(Digits2Raw); From 65c4833703abd788ccf5c1d8419b4256a88de3cf Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 11 Jun 2021 09:11:33 +0200 Subject: [PATCH 038/770] Correcting tabs --- Detectors/ZDC/simulation/src/Detector.cxx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Detectors/ZDC/simulation/src/Detector.cxx b/Detectors/ZDC/simulation/src/Detector.cxx index d8431218823fd..acf8efd6f9267 100644 --- a/Detectors/ZDC/simulation/src/Detector.cxx +++ b/Detectors/ZDC/simulation/src/Detector.cxx @@ -810,9 +810,9 @@ void Detector::createAsideBeamLine() zA += 2. * conpar[0]; // Upper section : one single phi segment of a tube - // 5 parameters for tubs: inner radius = 0., - // outer radius = 7. cm, half length = 50 cm - // phi1 = 0., phi2 = 180. + // 5 parameters for tubs: inner radius = 0., + // outer radius = 7. cm, half length = 50 cm + // phi1 = 0., phi2 = 180. tubspar[0] = 0.0 / 2.; tubspar[1] = 14.0 / 2.; tubspar[2] = 100.0 / 2.; From 03e63c1cff9863a2cb2226977f4712b66969e6fe Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 11 Jun 2021 09:48:47 +0200 Subject: [PATCH 039/770] Inclusion of Energy and Tower calibration objects --- .../ZDC/base/include/ZDCBase/Constants.h | 11 ++++++++ .../include/ZDCReconstruction/DigiReco.h | 8 ++++++ .../include/ZDCReconstruction/RecoParamZDC.h | 1 + Detectors/ZDC/reconstruction/src/DigiReco.cxx | 26 +++++++++++++++++++ .../ZDC/reconstruction/src/ZDCEnergyParam.cxx | 11 +++----- .../ZDC/reconstruction/src/ZDCTowerParam.cxx | 12 +++------ Detectors/ZDC/workflow/src/DigitRecoSpec.cxx | 20 ++++++++++++++ 7 files changed, 74 insertions(+), 15 deletions(-) diff --git a/Detectors/ZDC/base/include/ZDCBase/Constants.h b/Detectors/ZDC/base/include/ZDCBase/Constants.h index e566c4457768b..dad4b224050bb 100644 --- a/Detectors/ZDC/base/include/ZDCBase/Constants.h +++ b/Detectors/ZDC/base/include/ZDCBase/Constants.h @@ -14,6 +14,7 @@ #include "CommonConstants/PhysicsConstants.h" #include #include +#include #include #include #include @@ -216,6 +217,16 @@ const std::string CCDBPathTDCCalib = "ZDC/Calib/TDCCalib"; const std::string CCDBPathEnergyCalib = "ZDC/Calib/EnergyCalib"; const std::string CCDBPathTowerCalib = "ZDC/Calib/TowerCalib"; +// List of channels that can be calibrated +constexpr std::array ChEnergyCalib{IdZNAC, IdZNASum, IdZPAC, IdZPASum, + IdZEM1, IdZEM2, + IdZNCC, IdZNCSum, IdZPCC, IdZPCSum}; + +constexpr std::array ChTowerCalib{IdZNA1, IdZNA2, IdZNA3, IdZNA4, + IdZPA1, IdZPA2, IdZPA3, IdZPA4, + IdZNC1, IdZNC2, IdZNC3, IdZNC4, + IdZPC1, IdZPC2, IdZPC3, IdZPC4}; + // Placeholders constexpr int DummyIntRange = -NTimeBinsPerBC - 1; diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h index 3c58eac13aea9..a6a0015368a2b 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h @@ -17,6 +17,8 @@ #include "ZDCSimulation/ZDCSimParam.h" #include "ZDCReconstruction/RecoParamZDC.h" #include "ZDCReconstruction/ZDCTDCParam.h" +#include "ZDCReconstruction/ZDCEnergyParam.h" +#include "ZDCReconstruction/ZDCTowerParam.h" #include "ZDCReconstruction/RecoConfigZDC.h" #include "ZDCBase/ModuleConfig.h" #include "DataFormatsZDC/BCData.h" @@ -65,6 +67,10 @@ class DigiReco const ModuleConfig* getModuleConfig() { return mModuleConfig; }; void setTDCParam(const ZDCTDCParam* param) { mTDCParam = param; }; const ZDCTDCParam* getTDCParam() { return mTDCParam; }; + void setEnergyParam(const ZDCEnergyParam* param) { mEnergyParam = param; }; + const ZDCEnergyParam* getEnergyParam() { return mEnergyParam; }; + void setTowerParam(const ZDCTowerParam* param) { mTowerParam = param; }; + const ZDCTowerParam* getTowerParam() { return mTowerParam; }; void setRecoConfigZDC(const RecoConfigZDC* cfg) { mRecoConfigZDC = cfg; }; const RecoConfigZDC* getRecoConfigZDC() { return mRecoConfigZDC; }; @@ -79,6 +85,8 @@ class DigiReco bool mIsContinuous = true; /// continuous (self-triggered) or externally-triggered readout int mNBCAHead = 0; /// when storing triggered BC, store also mNBCAHead BCs const ZDCTDCParam* mTDCParam = nullptr; /// TDC calibration object + const ZDCEnergyParam* mEnergyParam = nullptr; /// Energy calibration object + const ZDCTowerParam* mTowerParam = nullptr; /// Tower calibration object uint32_t mTDCMask[NTDCChannels] = {0}; /// Identify TDC channels in trigger mask const RecoConfigZDC* mRecoConfigZDC = nullptr; /// CCDB configuration parameters bool mVerbosity = DbgFull; diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h index b8c08ed1690d2..008c5dbb34756 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h @@ -49,6 +49,7 @@ struct RecoParamZDC : public o2::conf::ConfigurableParamHelper { // Energy calibration float energy_calib[NChannels] = {0}; // Energy calibration coefficients + float tower_calib[NChannels] = {0}; // Tower calibration coefficients O2ParamDef(RecoParamZDC, "recoparamzdc"); }; } // namespace zdc diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index 98c4c1f0b931e..554a7c686243f 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -119,6 +119,32 @@ void DigiReco::init() LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << ropt.tdc_search[itdc] << " i.s. = " << ropt.tdc_search[itdc] * FTDCVal << " ns"; } + // Energy calibration + for (int il = 0; il < ChEnergyCalib.size(); il++) { + if (ropt.energy_calib[ChEnergyCalib[il]] > 0) { + LOG(INFO) << "Energy Calibration from command line " << ChannelNames[ChEnergyCalib[il]] << " = " << ropt.energy_calib[ChEnergyCalib[il]]; + } else if (mEnergyParam && mEnergyParam->energy_calib[ChEnergyCalib[il]] > 0) { + ropt.energy_calib[ChEnergyCalib[il]] = mEnergyParam->energy_calib[ChEnergyCalib[il]]; + LOG(INFO) << "Energy Calibration from CCDB " << ChannelNames[ChEnergyCalib[il]] << " = " << ropt.energy_calib[ChEnergyCalib[il]]; + } else { + ropt.energy_calib[ChEnergyCalib[il]] = 1; + LOG(WARNING) << "Default Energy Calibration " << ChannelNames[ChEnergyCalib[il]] << " = " << ropt.energy_calib[ChEnergyCalib[il]]; + } + } + + // Tower calibration + for (int il = 0; il < ChTowerCalib.size(); il++) { + if (ropt.tower_calib[ChTowerCalib[il]] > 0) { + LOG(INFO) << "Tower Calibration from command line " << ChannelNames[ChTowerCalib[il]] << " = " << ropt.tower_calib[ChTowerCalib[il]]; + } else if (mTowerParam && mTowerParam->tower_calib[ChTowerCalib[il]] > 0) { + ropt.tower_calib[ChTowerCalib[il]] = mTowerParam->tower_calib[ChTowerCalib[il]]; + LOG(INFO) << "Tower Calibration from CCDB " << ChannelNames[ChTowerCalib[il]] << " = " << ropt.tower_calib[ChTowerCalib[il]]; + } else { + ropt.tower_calib[ChTowerCalib[il]] = 1; + LOG(WARNING) << "Default Tower Calibration " << ChannelNames[ChTowerCalib[il]] << " = " << ropt.tower_calib[ChTowerCalib[il]]; + } + } + // Fill maps channel maps for integration for (int ich = 0; ich < NChannels; ich++) { // If the reconstruction parameters were not manually set diff --git a/Detectors/ZDC/reconstruction/src/ZDCEnergyParam.cxx b/Detectors/ZDC/reconstruction/src/ZDCEnergyParam.cxx index 7d2949e926833..c36f6ab0738c8 100644 --- a/Detectors/ZDC/reconstruction/src/ZDCEnergyParam.cxx +++ b/Detectors/ZDC/reconstruction/src/ZDCEnergyParam.cxx @@ -15,12 +15,9 @@ using namespace o2::zdc; void ZDCEnergyParam::setEnergyCalib(uint32_t ich, float val) { - constexpr std::array chlist{IdZNAC, IdZNASum, IdZPAC, IdZPASum, - IdZEM1, IdZEM2, - IdZNCC, IdZNCSum, IdZPCC, IdZPCSum}; bool in_list = in_list; - for (int il = 0; il < chlist.size(); il++) { - if (ich == chlist[il]) { + for (int il = 0; il < ChEnergyCalib.size(); il++) { + if (ich == ChEnergyCalib[il]) { in_list = true; break; } @@ -29,8 +26,8 @@ void ZDCEnergyParam::setEnergyCalib(uint32_t ich, float val) energy_calib[ich] = val; } else { LOG(FATAL) << __func__ << " channel " << ich << " not in allowed range"; - for (int il = 0; il < chlist.size(); il++) { - LOG(info) << __func__ << " channel " << chlist[il] << " " << ChannelNames[chlist[il]]; + for (int il = 0; il < ChEnergyCalib.size(); il++) { + LOG(info) << __func__ << " channel " << ChEnergyCalib[il] << " " << ChannelNames[ChEnergyCalib[il]]; } } } diff --git a/Detectors/ZDC/reconstruction/src/ZDCTowerParam.cxx b/Detectors/ZDC/reconstruction/src/ZDCTowerParam.cxx index 15c8d9af9335b..daa4e6ac2c54d 100644 --- a/Detectors/ZDC/reconstruction/src/ZDCTowerParam.cxx +++ b/Detectors/ZDC/reconstruction/src/ZDCTowerParam.cxx @@ -15,13 +15,9 @@ using namespace o2::zdc; void ZDCTowerParam::setTowerCalib(uint32_t ich, float val) { - constexpr std::array chlist{IdZNA1, IdZNA2, IdZNA3, IdZNA4, - IdZPA1, IdZPA2, IdZPA3, IdZPA4, - IdZNC1, IdZNC2, IdZNC3, IdZNC4, - IdZPC1, IdZPC2, IdZPC3, IdZPC4}; bool in_list = in_list; - for (int il = 0; il < chlist.size(); il++) { - if (ich == chlist[il]) { + for (int il = 0; il < ChTowerCalib.size(); il++) { + if (ich == ChTowerCalib[il]) { in_list = true; break; } @@ -30,8 +26,8 @@ void ZDCTowerParam::setTowerCalib(uint32_t ich, float val) tower_calib[ich] = val; } else { LOG(FATAL) << __func__ << " channel " << ich << " not in allowed range"; - for (int il = 0; il < chlist.size(); il++) { - LOG(info) << __func__ << " channel " << chlist[il] << " " << ChannelNames[chlist[il]]; + for (int il = 0; il < ChTowerCalib.size(); il++) { + LOG(info) << __func__ << " channel " << ChTowerCalib[il] << " " << ChannelNames[ChTowerCalib[il]]; } } } diff --git a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx index e61725b9e8bc0..db7c5a428f16b 100644 --- a/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx +++ b/Detectors/ZDC/workflow/src/DigitRecoSpec.cxx @@ -100,9 +100,29 @@ void DigitRecoSpec::run(ProcessingContext& pc) LOG(INFO) << "Loaded TDC centering ZDCTDCParam for timestamp " << timeStamp; tdcParam->print(); + // Energy calibration + auto* energyParam = mgr.get(o2::zdc::CCDBPathEnergyCalib); + if (!energyParam) { + LOG(WARNING) << "Missing ZDCEnergyParam calibration object - using default"; + } else { + LOG(INFO) << "Loaded Energy calibration ZDCEnergyParam for timestamp " << timeStamp; + energyParam->print(); + } + + // Tower calibration + auto* towerParam = mgr.get(o2::zdc::CCDBPathTowerCalib); + if (!towerParam) { + LOG(WARNING) << "Missing ZDCTowerParam calibration object - using default"; + } else { + LOG(INFO) << "Loaded Tower calibration ZDCTowerParam for timestamp " << timeStamp; + towerParam->print(); + } + mDR.setModuleConfig(moduleConfig); mDR.setRecoConfigZDC(recoConfigZDC); mDR.setTDCParam(tdcParam); + mDR.setEnergyParam(energyParam); + mDR.setTowerParam(towerParam); if (mDebugOut) { mDR.setDebugOutput(); From ca481c0de9293d9a2e00173b0f7f85b1cecb4d97 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 11 Jun 2021 10:32:13 +0200 Subject: [PATCH 040/770] Energy calibration and tower intercalibration in reconstruction --- .../ZDC/base/include/ZDCBase/Constants.h | 6 +++++ Detectors/ZDC/reconstruction/src/DigiReco.cxx | 27 ++++++++++++++----- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/Detectors/ZDC/base/include/ZDCBase/Constants.h b/Detectors/ZDC/base/include/ZDCBase/Constants.h index dad4b224050bb..f569688947066 100644 --- a/Detectors/ZDC/base/include/ZDCBase/Constants.h +++ b/Detectors/ZDC/base/include/ZDCBase/Constants.h @@ -227,6 +227,12 @@ constexpr std::array ChTowerCalib{IdZNA1, IdZNA2, IdZNA3, IdZNA4, IdZNC1, IdZNC2, IdZNC3, IdZNC4, IdZPC1, IdZPC2, IdZPC3, IdZPC4}; +constexpr std::array CaloCommonPM{IdZNAC, IdZNAC, IdZNAC, IdZNAC, IdZNAC, IdZNAC, + IdZPAC, IdZPAC, IdZPAC, IdZPAC, IdZPAC, IdZPAC, + IdZEM1, IdZEM2, + IdZNCC, IdZNCC, IdZNCC, IdZNCC, IdZNCC, IdZNCC, + IdZPCC, IdZPCC, IdZPCC, IdZPCC, IdZPCC, IdZPCC}; + // Placeholders constexpr int DummyIntRange = -NTimeBinsPerBC - 1; diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index 554a7c686243f..b69a900734c54 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -127,8 +127,16 @@ void DigiReco::init() ropt.energy_calib[ChEnergyCalib[il]] = mEnergyParam->energy_calib[ChEnergyCalib[il]]; LOG(INFO) << "Energy Calibration from CCDB " << ChannelNames[ChEnergyCalib[il]] << " = " << ropt.energy_calib[ChEnergyCalib[il]]; } else { - ropt.energy_calib[ChEnergyCalib[il]] = 1; - LOG(WARNING) << "Default Energy Calibration " << ChannelNames[ChEnergyCalib[il]] << " = " << ropt.energy_calib[ChEnergyCalib[il]]; + if (ChEnergyCalib[il] == CaloCommonPM[ChEnergyCalib[il]]) { + // Is a common PM or a ZEM + ropt.energy_calib[ChEnergyCalib[il]] = 1; + LOG(WARNING) << "Default Energy Calibration " << ChannelNames[ChEnergyCalib[il]] << " = " << ropt.energy_calib[ChEnergyCalib[il]]; + } else { + // Is one of the analog sums -> same calibration as common PM + // N.B. the calibration for common has already been set in the loop + ropt.energy_calib[ChEnergyCalib[il]] = ropt.energy_calib[CaloCommonPM[il]]; + LOG(INFO) << "SUM Energy Calibration " << ChannelNames[ChEnergyCalib[il]] << " = " << ropt.energy_calib[ChEnergyCalib[il]]; + } } } @@ -145,6 +153,16 @@ void DigiReco::init() } } + // Tower energy calibration + for (int il = 0; il < ChTowerCalib.size(); il++) { + if (ropt.energy_calib[ChTowerCalib[il]] > 0) { + LOG(INFO) << "Tower Energy Calibration from command line " << ChannelNames[ChTowerCalib[il]] << " = " << ropt.energy_calib[ChTowerCalib[il]]; + } else { + ropt.energy_calib[ChTowerCalib[il]] = ropt.tower_calib[ChTowerCalib[il]] * ropt.energy_calib[CaloCommonPM[ChTowerCalib[il]]]; + LOG(INFO) << "Tower Energy Calibration " << ChannelNames[ChTowerCalib[il]] << " = " << ropt.energy_calib[ChTowerCalib[il]]; + } + } + // Fill maps channel maps for integration for (int ich = 0; ich < NChannels; ich++) { // If the reconstruction parameters were not manually set @@ -184,8 +202,6 @@ void DigiReco::init() } LOG(INFO) << ChannelNames[ich] << " integration: signal=[" << ropt.beg_int[ich] << ":" << ropt.end_int[ich] << "] pedestal=[" << ropt.beg_ped_int[ich] << ":" << ropt.end_ped_int[ich] << "]"; } - - // TODO: Energy calibration } int DigiReco::process(const gsl::span& orbitdata, const gsl::span& bcdata, const gsl::span& chdata) @@ -438,11 +454,10 @@ int DigiReco::reconstruct(int ibeg, int iend) #ifdef O2_ZDC_DEBUG printf("CH %2d %s: %f\n", ich, ChannelNames[ich].data(), sum); #endif - rec.ezdc[ich] = sum; + rec.ezdc[ich] = sum * ropt.energy_calib[ich]; } } } - // TODO: energy calibration if (mTreeDbg) { mRec = rec; mTDbg->Fill(); From e29ad7c4a2a6a8b3dd76cb69f4b1904f14be40fe Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 11 Jun 2021 10:36:58 +0200 Subject: [PATCH 041/770] Correcting tabs --- Detectors/ZDC/simulation/src/Detector.cxx | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Detectors/ZDC/simulation/src/Detector.cxx b/Detectors/ZDC/simulation/src/Detector.cxx index acf8efd6f9267..a31ed5a464c76 100644 --- a/Detectors/ZDC/simulation/src/Detector.cxx +++ b/Detectors/ZDC/simulation/src/Detector.cxx @@ -1269,7 +1269,7 @@ void Detector::createAsideBeamLine() TVirtualMC::GetMC()->Gsvolu("QA29", "TUBE", getMediumID(kFe), tubpar, 3); TVirtualMC::GetMC()->Gspos("QA29", 1, "ZDCA", -16.5 / 2., 0., tubpar[2] + zA, 0, "ONLY"); TVirtualMC::GetMC()->Gspos("QA29", 2, "ZDCA", 16.5 / 2., 0., tubpar[2] + zA, 0, "ONLY"); - //printf(" QA29 TUBE from z = %1.2f to z= %1.2f (separate pipes)\n",zA,2*tubpar[2]+zA); + //printf("QA29 TUBE from z = %1.2f to z= %1.2f (separate pipes)\n",zA,2*tubpar[2]+zA); zA += 2. * tubpar[2]; @@ -1280,7 +1280,7 @@ void Detector::createAsideBeamLine() boxpar[2] = mLumiLength / 2.; TVirtualMC::GetMC()->Gsvolu("QLUA", "BOX ", getMediumID(kCuLumi), boxpar, 3); TVirtualMC::GetMC()->Gspos("QLUA", 1, "ZDCA", 0., 0., Geometry::ZNAPOSITION[1] /*fPosZNA[2]*/ - 66. - boxpar[2], 0, "ONLY"); - LOG(DEBUG) << " A-side luminometer positioned in front of ZNA\n"; + LOG(DEBUG) << "A-side luminometer positioned in front of ZNA\n"; } } @@ -1327,7 +1327,7 @@ void Detector::createCsideBeamLine() //-- BEAM PIPE from the end of D1 to the beginning of D2 //-- FROM MAGNETIC BEGINNING OF D1 TO MAGNETIC END OF D1 - //-- Cylindrical pipe (r = 3.47) + conical flare + //-- Cylindrical pipe (r = 3.47) + conical flare tubpar[0] = 6.94 / 2.; tubpar[1] = 7.34 / 2.; tubpar[2] = (6909.8 - zC) / 2.; @@ -1693,7 +1693,7 @@ void Detector::createCsideBeamLine() boxpar[2] = mLumiLength / 2.; // FIX IT!!!!!!!!!!!!!!!!!!!!!!!! TVirtualMC::GetMC()->Gsvolu("QLUC", "BOX ", getMediumID(kCuLumi), boxpar, 3); TVirtualMC::GetMC()->Gspos("QLUC", 1, "ZDCC", 0., 0., Geometry::ZNCPOSITION[1] + 66. + boxpar[2], 0, "ONLY"); - LOG(DEBUG) << " C-side luminometer positioned in front of ZNC\n"; + LOG(DEBUG) << "C-side luminometer positioned in front of ZNC\n"; } } @@ -1709,7 +1709,7 @@ void Detector::createMagnets() double zD2Field = 12167.8; // *************************************************************** - // SIDE C + //SIDE C // *************************************************************** // -- COMPENSATOR DIPOLE (MBXW) // -- GAP (VACUUM WITH MAGNETIC FIELD) @@ -1811,7 +1811,7 @@ void Detector::createMagnets() TVirtualMC::GetMC()->Gspos("MD2 ", 2, "YD2 ", 9.4, 0., 0., 0, "ONLY"); // *************************************************************** - // SIDE A + //SIDE A // *************************************************************** // COMPENSATOR DIPOLE (MCBWA) (2nd compensator) From e4f9435a8add7009b022b75906fe6e7c3e4d9c2c Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 6 Apr 2021 11:19:46 +0200 Subject: [PATCH 042/770] Full system test: Use severity debug for StfBuilder to get buffer fill status printout --- prodtests/full-system-test/start_tmux.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/prodtests/full-system-test/start_tmux.sh b/prodtests/full-system-test/start_tmux.sh index a050ace5ab25b..70803e78ce353 100755 --- a/prodtests/full-system-test/start_tmux.sh +++ b/prodtests/full-system-test/start_tmux.sh @@ -38,5 +38,5 @@ rm -f /dev/shm/*fmq* tmux \ new-session "NUMAID=0 numactl --membind 0 --cpunodebind 0 $MYDIR/dpl-workflow.sh; echo END; sleep 1000" \; \ split-window "sleep 30; NUMAID=1 numactl --membind 1 --cpunodebind 1 $MYDIR/dpl-workflow.sh; echo END; sleep 1000" \; \ - split-window "sleep 60; SEVERITY=info numactl --interleave=all $MYDIR/$CMD; echo END; sleep 1000" \; \ + split-window "sleep 60; SEVERITY=debug numactl --interleave=all $MYDIR/$CMD; echo END; sleep 1000" \; \ select-layout even-vertical From a58cdc0f3b350f551316b90fd6a1383b7ab73580 Mon Sep 17 00:00:00 2001 From: Francesco Noferini Date: Tue, 6 Apr 2021 10:21:12 +0200 Subject: [PATCH 043/770] recover TPC-TOF matching perf in Pb-Pb sim --- Detectors/GlobalTracking/src/MatchTOF.cxx | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/Detectors/GlobalTracking/src/MatchTOF.cxx b/Detectors/GlobalTracking/src/MatchTOF.cxx index 4fb4c2415867e..dd6928a9ebd22 100644 --- a/Detectors/GlobalTracking/src/MatchTOF.cxx +++ b/Detectors/GlobalTracking/src/MatchTOF.cxx @@ -1152,6 +1152,7 @@ void MatchTOF::doMatchingForTPC(int sec) std::vector> nStepsInsideSameStrip; LOG(DEBUG) << "Trying to match %d tracks" << cacheTrk.size(); + for (int itrk = 0; itrk < cacheTrk.size(); itrk++) { auto& trackWork = mTracksWork[cacheTrk[itrk]]; auto& trefTrk = trackWork.first; @@ -1170,13 +1171,14 @@ void MatchTOF::doMatchingForTPC(int sec) // printf("trk time %f - %f (max shift +/- %f cm)\n",minTrkTime,maxTrkTime,trackWork.second.getTimeStampError()*vdrift ); - for (double tBC = minTrkTime; tBC < maxTrkTime; tBC += BCgranularity) { - unsigned long ibc = (unsigned long)(tBC * Geo::BC_TIME_INPS_INV); - BCcand.emplace_back(ibc); - nStripsCrossedInPropagation.emplace_back(0); + if (mIsCosmics) { + for (double tBC = minTrkTime; tBC < maxTrkTime; tBC += BCgranularity) { + unsigned long ibc = (unsigned long)(tBC * Geo::BC_TIME_INPS_INV); + BCcand.emplace_back(ibc); + nStripsCrossedInPropagation.emplace_back(0); + } } - /* for (auto itof = itof0; itof < nTOFCls; itof++) { auto& trefTOF = mTOFClusWork[cacheTOF[itof]]; @@ -1212,7 +1214,7 @@ void MatchTOF::doMatchingForTPC(int sec) nStripsCrossedInPropagation.emplace_back(0); } } -*/ + // printf("BC = %ld\n",BCcand.size()); detId.clear(); From ee1d17f3b30bdc7548417e7c99d25857be16cd9a Mon Sep 17 00:00:00 2001 From: Francesco Noferini Date: Tue, 6 Apr 2021 10:59:09 +0200 Subject: [PATCH 044/770] TOF fix for codechecker --- Detectors/TOF/reconstruction/src/CosmicProcessor.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Detectors/TOF/reconstruction/src/CosmicProcessor.cxx b/Detectors/TOF/reconstruction/src/CosmicProcessor.cxx index f685e19afddb2..5ad32d7ceddd9 100644 --- a/Detectors/TOF/reconstruction/src/CosmicProcessor.cxx +++ b/Detectors/TOF/reconstruction/src/CosmicProcessor.cxx @@ -65,7 +65,7 @@ void CosmicProcessor::process(DigitDataReader& reader, bool fill) for (int j = i + 1; j < ndig2; j++) { auto& dig2 = (*array)[j]; int64_t bc2 = int64_t(dig2.getBC()) - bc1; - if (abs(bc2) > bcdist) { + if (labs(bc2) > bcdist) { continue; } @@ -96,7 +96,7 @@ void CosmicProcessor::process(DigitDataReader& reader, bool fill) dtime -= l * 33.356409; // corrected for pad distance assuiming muonn downward - if (abs(dtime) > thr) { + if (fabs(dtime) > thr) { continue; } From 7f528df910c355c065d6bd5ff3828f22465e79ee Mon Sep 17 00:00:00 2001 From: wiechula Date: Tue, 6 Apr 2021 16:55:04 +0200 Subject: [PATCH 045/770] define one event as a TF --- Detectors/TPC/reconstruction/src/RawReaderCRU.cxx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Detectors/TPC/reconstruction/src/RawReaderCRU.cxx b/Detectors/TPC/reconstruction/src/RawReaderCRU.cxx index 4fc05a50647b7..03e10609b566c 100644 --- a/Detectors/TPC/reconstruction/src/RawReaderCRU.cxx +++ b/Detectors/TPC/reconstruction/src/RawReaderCRU.cxx @@ -52,11 +52,13 @@ RawReaderCRUEventSync::EventInfo& RawReaderCRUEventSync::createEvent(const RDH& for (auto& ev : mEventInformation) { const auto hbMatch = ev.hasHearbeatOrbit(heartbeatOrbit); + const long hbDiff = long(heartbeatOrbit) - long(ev.HeartbeatOrbits.front()); if (hbMatch) { mLastEvent = &ev; return ev; - } else if (std::abs(long(ev.HeartbeatOrbits.back()) - long(heartbeatOrbit)) < 54) { + } else if ((hbDiff >= 0) && (hbDiff < 256)) { ev.HeartbeatOrbits.emplace_back(heartbeatOrbit); + std::sort(ev.HeartbeatOrbits.begin(), ev.HeartbeatOrbits.end()); mLastEvent = &ev; return ev; } From bd51f20dcca9ae1e8c86726b5317da39404e942d Mon Sep 17 00:00:00 2001 From: wiechula Date: Tue, 6 Apr 2021 16:59:13 +0200 Subject: [PATCH 046/770] better naming of device --- Detectors/TPC/workflow/src/RawToDigitsSpec.cxx | 2 +- Detectors/TPC/workflow/src/tpc-raw-to-digits-workflow.cxx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Detectors/TPC/workflow/src/RawToDigitsSpec.cxx b/Detectors/TPC/workflow/src/RawToDigitsSpec.cxx index ea43625b3f320..59c24c42d4eb4 100644 --- a/Detectors/TPC/workflow/src/RawToDigitsSpec.cxx +++ b/Detectors/TPC/workflow/src/RawToDigitsSpec.cxx @@ -170,7 +170,7 @@ DataProcessorSpec getRawToDigitsSpec(int channel, const std::string inputSpec, s } return DataProcessorSpec{ - fmt::format("TPCDigitizer{}", channel), + fmt::format("tpc-raw-to-digits-{}", channel), select(inputSpec.data()), outputs, AlgorithmSpec{adaptFromTask(tpcSectors)}, diff --git a/Detectors/TPC/workflow/src/tpc-raw-to-digits-workflow.cxx b/Detectors/TPC/workflow/src/tpc-raw-to-digits-workflow.cxx index 92dff6423cde8..2b0431286798f 100644 --- a/Detectors/TPC/workflow/src/tpc-raw-to-digits-workflow.cxx +++ b/Detectors/TPC/workflow/src/tpc-raw-to-digits-workflow.cxx @@ -32,7 +32,7 @@ using namespace o2::framework; void customize(std::vector& policies) { using o2::framework::CompletionPolicy; - policies.push_back(CompletionPolicyHelpers::defineByName("TPCDigitizer.*", CompletionPolicy::CompletionOp::Consume)); + policies.push_back(CompletionPolicyHelpers::defineByName("tpc-raw-to-digits-.*", CompletionPolicy::CompletionOp::Consume)); } // we need to add workflow options before including Framework/runDataProcessing From e91d40c0f961045bc82dc036bac0f5a5c6521a41 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 6 Apr 2021 22:42:36 +0200 Subject: [PATCH 047/770] TPC Workflow: Give a proper error when some TPC digit MC labels are missing --- .../TPC/include/DataFormatsTPC/WorkflowHelper.h | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/DataFormats/Detectors/TPC/include/DataFormatsTPC/WorkflowHelper.h b/DataFormats/Detectors/TPC/include/DataFormatsTPC/WorkflowHelper.h index aa883a3d3b844..9db5fb507c0cf 100644 --- a/DataFormats/Detectors/TPC/include/DataFormatsTPC/WorkflowHelper.h +++ b/DataFormats/Detectors/TPC/include/DataFormatsTPC/WorkflowHelper.h @@ -49,7 +49,6 @@ struct getWorkflowTPCInput_ret_internal { std::map inputrefs; std::vector mcInputs; std::vector> inputs; - std::array inputDigitsMCIndex; std::vector inputDigitsMC; std::unique_ptr clusterBuffer; ClusterNativeHelper::ConstMCLabelContainerViewWithBuffer clustersMCBuffer; @@ -69,6 +68,7 @@ static auto getWorkflowTPCInput(o2::framework::ProcessingContext& pc, int verbos if (do_clusters && do_digits) { throw std::invalid_argument("Currently cannot process both clusters and digits"); } + std::array inputDigitsMCIndex; if (do_mcLabels) { std::vector filter = { @@ -76,6 +76,9 @@ static auto getWorkflowTPCInput(o2::framework::ProcessingContext& pc, int verbos {"check", o2::framework::ConcreteDataTypeMatcher{o2::header::gDataOriginTPC, "CLNATIVEMCLBL"}, o2::framework::Lifetime::Timeframe}, }; unsigned long recvMask = 0; + if (do_digits) { + std::fill(inputDigitsMCIndex.begin(), inputDigitsMCIndex.end(), -1); + } for (auto const& ref : o2::framework::InputRecordWalker(pc.inputs(), filter)) { auto const* sectorHeader = o2::framework::DataRefUtils::getHeader(ref); if (sectorHeader == nullptr) { @@ -93,7 +96,7 @@ static auto getWorkflowTPCInput(o2::framework::ProcessingContext& pc, int verbos recvMask |= (sectorHeader->sectorBits & tpcSectorMask); retVal->internal.inputrefs[sector].labels = ref; if (do_digits) { - retVal->internal.inputDigitsMCIndex[sector] = retVal->internal.inputDigitsMC.size(); + inputDigitsMCIndex[sector] = retVal->internal.inputDigitsMC.size(); retVal->internal.inputDigitsMC.emplace_back(o2::dataformats::ConstMCLabelContainerView(pc.inputs().get>(ref))); } } @@ -104,9 +107,12 @@ static auto getWorkflowTPCInput(o2::framework::ProcessingContext& pc, int verbos for (unsigned int i = 0; i < constants::MAXSECTOR; i++) { if (tpcSectorMask & (1ul << i)) { if (verbosity >= 1) { - LOG(INFO) << "GOT MC LABELS FOR SECTOR " << i << " -> " << retVal->internal.inputDigitsMC[retVal->internal.inputDigitsMCIndex[i]].getNElements(); + LOG(INFO) << "GOT MC LABELS FOR SECTOR " << i << " -> " << retVal->internal.inputDigitsMC[inputDigitsMCIndex[i]].getNElements(); + } + if (inputDigitsMCIndex[i] == -1) { + throw std::runtime_error("digit mc labels missing"); } - retVal->inputDigitsMCPtrs[i] = &retVal->internal.inputDigitsMC[retVal->internal.inputDigitsMCIndex[i]]; + retVal->inputDigitsMCPtrs[i] = &retVal->internal.inputDigitsMC[inputDigitsMCIndex[i]]; } else { retVal->inputDigitsMCPtrs[i] = nullptr; } From abe20606f14f7b5546b577b3ca4abea2fde66ca1 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 6 Apr 2021 22:43:00 +0200 Subject: [PATCH 048/770] TPC Workflow: Fix missing default initialization of TPC digit label map --- GPU/GPUTracking/DataTypes/GPUDataTypes.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/GPUTracking/DataTypes/GPUDataTypes.h b/GPU/GPUTracking/DataTypes/GPUDataTypes.h index a6bf3b65ae50f..48e32b259eea1 100644 --- a/GPU/GPUTracking/DataTypes/GPUDataTypes.h +++ b/GPU/GPUTracking/DataTypes/GPUDataTypes.h @@ -207,7 +207,7 @@ struct GPUTrackingInOutDigits { static constexpr unsigned int NSLICES = GPUDataTypes::NSLICES; const o2::tpc::Digit* tpcDigits[NSLICES] = {nullptr}; size_t nTPCDigits[NSLICES] = {0}; - GPUTPCDigitsMCInput* tpcDigitsMC; + GPUTPCDigitsMCInput* tpcDigitsMC = nullptr; }; struct GPUTrackingInOutPointers { From e0b354c8e438e4ad210ff00b7b44a307908a589b Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 6 Apr 2021 22:48:19 +0200 Subject: [PATCH 049/770] GPU: Fix compiler warning --- Common/MathUtils/include/MathUtils/SMatrixGPU.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Common/MathUtils/include/MathUtils/SMatrixGPU.h b/Common/MathUtils/include/MathUtils/SMatrixGPU.h index 5da7f2603ad54..703dee12fc579 100644 --- a/Common/MathUtils/include/MathUtils/SMatrixGPU.h +++ b/Common/MathUtils/include/MathUtils/SMatrixGPU.h @@ -438,7 +438,7 @@ class Expr public: typedef T value_type; GPUd() Expr(const ExprType& rhs) : mRhs(rhs) {} // NOLINT: False positive - GPUd() ~Expr() = default; + GPUdDefault() ~Expr() = default; GPUdi() T apply(unsigned int i) const { return mRhs.apply(i); From 446fc1bef96cef9dfaf66167a4349ec0524d8d16 Mon Sep 17 00:00:00 2001 From: jgrosseo Date: Wed, 7 Apr 2021 09:11:15 +0200 Subject: [PATCH 050/770] Connecting to AliEn (#5866) --- Analysis/Core/CMakeLists.txt | 2 +- Analysis/Core/src/AODMerger.cxx | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Analysis/Core/CMakeLists.txt b/Analysis/Core/CMakeLists.txt index 36aab1706866c..64830f46c09a3 100644 --- a/Analysis/Core/CMakeLists.txt +++ b/Analysis/Core/CMakeLists.txt @@ -27,7 +27,7 @@ o2_target_root_dictionary(AnalysisCore o2_add_executable(merger COMPONENT_NAME aod SOURCES src/AODMerger.cxx - PUBLIC_LINK_LIBRARIES ROOT::Hist ROOT::Core) + PUBLIC_LINK_LIBRARIES ROOT::Hist ROOT::Core ROOT::Net) if(FastJet_FOUND) o2_add_library(AnalysisJets diff --git a/Analysis/Core/src/AODMerger.cxx b/Analysis/Core/src/AODMerger.cxx index f201040a17f26..9505d0ca29dc9 100644 --- a/Analysis/Core/src/AODMerger.cxx +++ b/Analysis/Core/src/AODMerger.cxx @@ -17,6 +17,7 @@ #include "TList.h" #include "TDirectory.h" #include "TObjString.h" +#include // AOD merger with correct index rewriting // No need to know the datamodel because the branch names follow a canonical standard (identified by fIndex) @@ -71,6 +72,7 @@ int main(int argc, char* argv[]) std::ifstream in; in.open(inputCollection); TString line; + bool connectedToAliEn = false; while (in.good()) { in >> line; @@ -78,6 +80,12 @@ int main(int argc, char* argv[]) continue; } + if (line.BeginsWith("alien:") && !connectedToAliEn) { + printf("Connecting to AliEn..."); + TGrid::Connect("alien:"); + connectedToAliEn = true; // Only try once + } + printf("Processing input file: %s\n", line.Data()); auto inputFile = TFile::Open(line); From 5e23331f40734a4f0ebdd76fa339a38ef7610dbc Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Wed, 7 Apr 2021 09:32:29 +0200 Subject: [PATCH 051/770] DPL Analysis: Make filter/table matching rely on a type hash rather than a string name (#5868) --- Framework/Core/include/Framework/ASoA.h | 190 +++++++++--------- .../Core/include/Framework/AnalysisTask.h | 4 +- .../Core/include/Framework/Expressions.h | 6 +- Framework/Core/src/ExpressionHelpers.h | 4 +- Framework/Core/src/Expressions.cxx | 20 +- Framework/Core/test/test_Expressions.cxx | 38 ++-- 6 files changed, 145 insertions(+), 117 deletions(-) diff --git a/Framework/Core/include/Framework/ASoA.h b/Framework/Core/include/Framework/ASoA.h index 714d848efbcbd..e0ed4e5c059b7 100644 --- a/Framework/Core/include/Framework/ASoA.h +++ b/Framework/Core/include/Framework/ASoA.h @@ -27,6 +27,7 @@ #include #include #include +#include namespace o2::soa { @@ -894,6 +895,11 @@ class Table using persistent_columns_t = framework::selected_pack; using external_index_columns_t = framework::selected_pack; + static constexpr auto hashes() + { + return std::set{typeid(C).hash_code()...}; + } + template struct RowViewBase : public RowViewCore { @@ -1266,7 +1272,7 @@ constexpr auto is_binding_compatible_v() return *mColumnIterator; \ } \ }; \ - static const o2::framework::expressions::BindingNode _Getter_ { _Label_, \ + static const o2::framework::expressions::BindingNode _Getter_ { _Label_, typeid(_Name_).hash_code(), \ o2::framework::expressions::selectArrowType<_Type_>() } #define DECLARE_SOA_COLUMN(_Name_, _Getter_, _Type_) \ @@ -1274,32 +1280,32 @@ constexpr auto is_binding_compatible_v() /// An 'expression' column. i.e. a column that can be calculated from other /// columns with gandiva based on supplied C++ expression. -#define DECLARE_SOA_EXPRESSION_COLUMN_FULL(_Name_, _Getter_, _Type_, _Label_, _Expression_) \ - struct _Name_ : o2::soa::Column<_Type_, _Name_> { \ - static constexpr const char* mLabel = _Label_; \ - using base = o2::soa::Column<_Type_, _Name_>; \ - using type = _Type_; \ - using column_t = _Name_; \ - using spawnable_t = std::true_type; \ - _Name_(arrow::ChunkedArray const* column) \ - : o2::soa::Column<_Type_, _Name_>(o2::soa::ColumnIterator(column)) \ - { \ - } \ - \ - _Name_() = default; \ - _Name_(_Name_ const& other) = default; \ - _Name_& operator=(_Name_ const& other) = default; \ - \ - decltype(auto) _Getter_() const \ - { \ - return *mColumnIterator; \ - } \ - static o2::framework::expressions::Projector Projector() \ - { \ - return _Expression_; \ - } \ - }; \ - static const o2::framework::expressions::BindingNode _Getter_ { _Label_, \ +#define DECLARE_SOA_EXPRESSION_COLUMN_FULL(_Name_, _Getter_, _Type_, _Label_, _Expression_) \ + struct _Name_ : o2::soa::Column<_Type_, _Name_> { \ + static constexpr const char* mLabel = _Label_; \ + using base = o2::soa::Column<_Type_, _Name_>; \ + using type = _Type_; \ + using column_t = _Name_; \ + using spawnable_t = std::true_type; \ + _Name_(arrow::ChunkedArray const* column) \ + : o2::soa::Column<_Type_, _Name_>(o2::soa::ColumnIterator(column)) \ + { \ + } \ + \ + _Name_() = default; \ + _Name_(_Name_ const& other) = default; \ + _Name_& operator=(_Name_ const& other) = default; \ + \ + decltype(auto) _Getter_() const \ + { \ + return *mColumnIterator; \ + } \ + static o2::framework::expressions::Projector Projector() \ + { \ + return _Expression_; \ + } \ + }; \ + static const o2::framework::expressions::BindingNode _Getter_ { _Label_, typeid(_Name_).hash_code(), \ o2::framework::expressions::selectArrowType<_Type_>() } #define DECLARE_SOA_EXPRESSION_COLUMN(_Name_, _Getter_, _Type_, _Expression_) \ @@ -1319,71 +1325,71 @@ constexpr auto is_binding_compatible_v() /// needs to go from parent to child, the only way is to either have /// a separate "association" with the two indices, or to use the standard /// grouping mechanism of AnalysisTask. -#define DECLARE_SOA_INDEX_COLUMN_FULL(_Name_, _Getter_, _Type_, _Table_, _Suffix_) \ - struct _Name_##Id : o2::soa::Column<_Type_, _Name_##Id> { \ - static_assert(std::is_integral_v<_Type_>, "Index type must be integral"); \ - static_assert((*_Suffix_ == '\0') || (*_Suffix_ == '_'), "Suffix has to begin with _"); \ - static constexpr const char* mLabel = "fIndex" #_Table_ _Suffix_; \ - using base = o2::soa::Column<_Type_, _Name_##Id>; \ - using type = _Type_; \ - using column_t = _Name_##Id; \ - using binding_t = _Table_; \ - _Name_##Id(arrow::ChunkedArray const* column) \ - : o2::soa::Column<_Type_, _Name_##Id>(o2::soa::ColumnIterator(column)) \ - { \ - } \ - \ - _Name_##Id() = default; \ - _Name_##Id(_Name_##Id const& other) = default; \ - _Name_##Id& operator=(_Name_##Id const& other) = default; \ - type inline getId() const \ - { \ - return _Getter_##Id(); \ - } \ - \ - type _Getter_##Id() const \ - { \ - return *mColumnIterator; \ - } \ - \ - bool has_##_Getter_() const \ - { \ - return *mColumnIterator >= 0; \ - } \ - \ - template \ - auto _Getter_##_as() const \ - { \ - assert(mBinding != nullptr); \ - return static_cast(mBinding)->begin() + *mColumnIterator; \ - } \ - \ - auto _Getter_() const \ - { \ - return _Getter_##_as(); \ - } \ - \ - template \ - bool setCurrent(T* current) \ - { \ - if constexpr (o2::soa::is_binding_compatible_v()) { \ - assert(current != nullptr); \ - this->mBinding = current; \ - return true; \ - } \ - return false; \ - } \ - \ - bool setCurrentRaw(void* current) \ - { \ - this->mBinding = current; \ - return true; \ - } \ - binding_t* getCurrent() const { return static_cast(mBinding); } \ - void* getCurrentRaw() const { return mBinding; } \ - void* mBinding = nullptr; \ - }; \ - static const o2::framework::expressions::BindingNode _Getter_##Id { "fIndex" #_Table_ _Suffix_, \ +#define DECLARE_SOA_INDEX_COLUMN_FULL(_Name_, _Getter_, _Type_, _Table_, _Suffix_) \ + struct _Name_##Id : o2::soa::Column<_Type_, _Name_##Id> { \ + static_assert(std::is_integral_v<_Type_>, "Index type must be integral"); \ + static_assert((*_Suffix_ == '\0') || (*_Suffix_ == '_'), "Suffix has to begin with _"); \ + static constexpr const char* mLabel = "fIndex" #_Table_ _Suffix_; \ + using base = o2::soa::Column<_Type_, _Name_##Id>; \ + using type = _Type_; \ + using column_t = _Name_##Id; \ + using binding_t = _Table_; \ + _Name_##Id(arrow::ChunkedArray const* column) \ + : o2::soa::Column<_Type_, _Name_##Id>(o2::soa::ColumnIterator(column)) \ + { \ + } \ + \ + _Name_##Id() = default; \ + _Name_##Id(_Name_##Id const& other) = default; \ + _Name_##Id& operator=(_Name_##Id const& other) = default; \ + type inline getId() const \ + { \ + return _Getter_##Id(); \ + } \ + \ + type _Getter_##Id() const \ + { \ + return *mColumnIterator; \ + } \ + \ + bool has_##_Getter_() const \ + { \ + return *mColumnIterator >= 0; \ + } \ + \ + template \ + auto _Getter_##_as() const \ + { \ + assert(mBinding != nullptr); \ + return static_cast(mBinding)->begin() + *mColumnIterator; \ + } \ + \ + auto _Getter_() const \ + { \ + return _Getter_##_as(); \ + } \ + \ + template \ + bool setCurrent(T* current) \ + { \ + if constexpr (o2::soa::is_binding_compatible_v()) { \ + assert(current != nullptr); \ + this->mBinding = current; \ + return true; \ + } \ + return false; \ + } \ + \ + bool setCurrentRaw(void* current) \ + { \ + this->mBinding = current; \ + return true; \ + } \ + binding_t* getCurrent() const { return static_cast(mBinding); } \ + void* getCurrentRaw() const { return mBinding; } \ + void* mBinding = nullptr; \ + }; \ + static const o2::framework::expressions::BindingNode _Getter_##Id { "fIndex" #_Table_ _Suffix_, typeid(_Name_##Id).hash_code(), \ o2::framework::expressions::selectArrowType<_Type_>() } #define DECLARE_SOA_INDEX_COLUMN(_Name_, _Getter_) DECLARE_SOA_INDEX_COLUMN_FULL(_Name_, _Getter_, int32_t, _Name_##s, "") diff --git a/Framework/Core/include/Framework/AnalysisTask.h b/Framework/Core/include/Framework/AnalysisTask.h index 3e653ed43b615..cc688b4221a31 100644 --- a/Framework/Core/include/Framework/AnalysisTask.h +++ b/Framework/Core/include/Framework/AnalysisTask.h @@ -107,10 +107,10 @@ struct AnalysisDataProcessorBuilder { { using dT = std::decay_t; if constexpr (framework::is_specialization::value) { - eInfos.push_back({at, o2::soa::createSchemaFromColumns(typename dT::table_t::persistent_columns_t{}), nullptr}); + eInfos.push_back({at, dT::hashes(), o2::soa::createSchemaFromColumns(typename dT::table_t::persistent_columns_t{}), nullptr}); } else if constexpr (soa::is_soa_iterator_t
::value) { if constexpr (std::is_same_v) { - eInfos.push_back({at, o2::soa::createSchemaFromColumns(typename dT::table_t::persistent_columns_t{}), nullptr}); + eInfos.push_back({at, dT::parent_t::hashes(), o2::soa::createSchemaFromColumns(typename dT::table_t::persistent_columns_t{}), nullptr}); } } doAppendInputWithMetadata(soa::make_originals_from_type
(), inputs); diff --git a/Framework/Core/include/Framework/Expressions.h b/Framework/Core/include/Framework/Expressions.h index 2484e4dd43a43..e255029136ff8 100644 --- a/Framework/Core/include/Framework/Expressions.h +++ b/Framework/Core/include/Framework/Expressions.h @@ -40,10 +40,13 @@ class Filter; #include #include #include +#include +#include using atype = arrow::Type; struct ExpressionInfo { size_t index; + std::set hashes; gandiva::SchemaPtr schema; gandiva::NodePtr tree; }; @@ -104,8 +107,9 @@ struct LiteralNode { struct BindingNode { BindingNode(BindingNode const&) = default; BindingNode(BindingNode&&) = delete; - BindingNode(std::string const& name_, atype::type type_) : name{name_}, type{type_} {} + BindingNode(std::string const& name_, std::size_t hash_, atype::type type_) : name{name_}, hash{hash_}, type{type_} {} std::string name; + std::size_t hash; atype::type type; }; diff --git a/Framework/Core/src/ExpressionHelpers.h b/Framework/Core/src/ExpressionHelpers.h index 2d3f9cb704029..730117a2cc756 100644 --- a/Framework/Core/src/ExpressionHelpers.h +++ b/Framework/Core/src/ExpressionHelpers.h @@ -49,10 +49,12 @@ struct DatumSpec { /// datum spec either contains an index, a value of a literal or a binding label using datum_t = std::variant; datum_t datum = std::monostate{}; + size_t hash = 0; atype::type type = atype::NA; + explicit DatumSpec(size_t index, atype::type type_) : datum{index}, type{type_} {} explicit DatumSpec(LiteralNode::var_t literal, atype::type type_) : datum{literal}, type{type_} {} - explicit DatumSpec(std::string binding, atype::type type_) : datum{binding}, type{type_} {} + explicit DatumSpec(std::string binding, size_t hash_, atype::type type_) : datum{binding}, hash{hash_}, type{type_} {} DatumSpec() = default; DatumSpec(DatumSpec const&) = default; DatumSpec(DatumSpec&&) = default; diff --git a/Framework/Core/src/Expressions.cxx b/Framework/Core/src/Expressions.cxx index 2d532f58e40ef..0596f7aba606b 100644 --- a/Framework/Core/src/Expressions.cxx +++ b/Framework/Core/src/Expressions.cxx @@ -37,7 +37,7 @@ struct LiteralNodeHelper { struct BindingNodeHelper { DatumSpec operator()(BindingNode node) const { - return DatumSpec{node.name, node.type}; + return DatumSpec{node.name, node.hash, node.type}; } }; @@ -527,6 +527,22 @@ gandiva::NodePtr createExpressionTree(Operations const& opSpecs, return tree; } +bool isTableCompatible(std::set const& hashes, Operations const& specs) +{ + std::set opHashes; + for (auto& spec : specs) { + if (spec.left.datum.index() == 3) { + opHashes.insert(spec.left.hash); + } + if (spec.right.datum.index() == 3) { + opHashes.insert(spec.right.hash); + } + } + + return std::includes(hashes.begin(), hashes.end(), + opHashes.begin(), opHashes.end()); +} + bool isSchemaCompatible(gandiva::SchemaPtr const& Schema, Operations const& opSpecs) { std::set opFieldNames; @@ -555,7 +571,7 @@ void updateExpressionInfos(expressions::Filter const& filter, std::vectorleft->self.index(), 1); BOOST_REQUIRE_EQUAL(ptfilter.node->right->self.index(), 3); auto ptfilterspecs = createOperations(ptfilter); - BOOST_REQUIRE_EQUAL(ptfilterspecs[0].left, (DatumSpec{std::string{"fPt"}, atype::FLOAT})); + BOOST_REQUIRE_EQUAL(ptfilterspecs[0].left, (DatumSpec{std::string{"fPt"}, typeid(o2::aod::track::Pt).hash_code(), atype::FLOAT})); BOOST_REQUIRE_EQUAL(ptfilterspecs[0].right, (DatumSpec{LiteralNode::var_t{0.5f}, atype::FLOAT})); BOOST_REQUIRE_EQUAL(ptfilterspecs[0].result, (DatumSpec{0u, atype::BOOL})); } @@ -139,12 +139,12 @@ BOOST_AUTO_TEST_CASE(TestGandivaTreeCreation) { Projector pze = o2::aod::track::Pze::Projector(); auto pzspecs = createOperations(std::move(pze)); - BOOST_REQUIRE_EQUAL(pzspecs[0].left, (DatumSpec{std::string{"fTgl"}, atype::FLOAT})); + BOOST_REQUIRE_EQUAL(pzspecs[0].left, (DatumSpec{std::string{"fTgl"}, typeid(o2::aod::track::Tgl).hash_code(), atype::FLOAT})); BOOST_REQUIRE_EQUAL(pzspecs[0].right, (DatumSpec{1u, atype::FLOAT})); BOOST_REQUIRE_EQUAL(pzspecs[0].result, (DatumSpec{0u, atype::FLOAT})); BOOST_REQUIRE_EQUAL(pzspecs[1].left, (DatumSpec{LiteralNode::var_t{1.f}, atype::FLOAT})); - BOOST_REQUIRE_EQUAL(pzspecs[1].right, (DatumSpec{std::string{"fSigned1Pt"}, atype::FLOAT})); + BOOST_REQUIRE_EQUAL(pzspecs[1].right, (DatumSpec{std::string{"fSigned1Pt"}, typeid(o2::aod::track::Signed1Pt).hash_code(), atype::FLOAT})); BOOST_REQUIRE_EQUAL(pzspecs[1].result, (DatumSpec{1u, atype::FLOAT})); auto infield1 = o2::aod::track::Signed1Pt::asArrowField(); auto infield2 = o2::aod::track::Tgl::asArrowField(); @@ -163,7 +163,7 @@ BOOST_AUTO_TEST_CASE(TestGandivaTreeCreation) BOOST_REQUIRE_EQUAL(ptespecs[0].result, (DatumSpec{0u, atype::FLOAT})); BOOST_REQUIRE_EQUAL(ptespecs[1].left, (DatumSpec{LiteralNode::var_t{1.f}, atype::FLOAT})); - BOOST_REQUIRE_EQUAL(ptespecs[1].right, (DatumSpec{std::string{"fSigned1Pt"}, atype::FLOAT})); + BOOST_REQUIRE_EQUAL(ptespecs[1].right, (DatumSpec{std::string{"fSigned1Pt"}, typeid(o2::aod::track::Signed1Pt).hash_code(), atype::FLOAT})); BOOST_REQUIRE_EQUAL(ptespecs[1].result, (DatumSpec{1u, atype::FLOAT})); auto infield3 = o2::aod::track::Signed1Pt::asArrowField(); From d49f9c3ad166c051612235e398059fb4329a6a06 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Wed, 7 Apr 2021 10:26:56 +0200 Subject: [PATCH 052/770] Add CODEOWNERS to /Detectors/Calibration (#5875) --- CODEOWNERS | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CODEOWNERS b/CODEOWNERS index cbd1cc3d2e26a..aa0fb29d2fb26 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -57,10 +57,11 @@ /DataFormats/simulation @sawenzel /Detectors/Base @sawenzel @shahor02 -/Detectors/Geometry @sawenzel @shahor02 +/Detectors/Calibration @chiarazampolli @shahor02 /Detectors/CPV @peressounko @kharlov /Detectors/EMCAL @mfasDa /Detectors/FIT @AllaMaevskaya @jotwinow @mslupeck +/Detectors/Geometry @sawenzel @shahor02 /Detectors/GlobalTracking @shahor02 /Detectors/GlobalTrackingWorkflow @shahor02 /Detectors/HMPID @gvolpe79 From 315746237a0c5b3e52571936535967ff98f29fcc Mon Sep 17 00:00:00 2001 From: Antonio FRANCO Date: Wed, 7 Apr 2021 10:49:28 +0200 Subject: [PATCH 053/770] HMPID_NewDigitStructure (#5795) * Version * Fix C-Lang * Fix Coding conventions * Fix C-Lang 2 * @shahor02 requested changes 26/03/21 * fix clang * Fix bugs in Cluster place holders --- DataFormats/Detectors/CMakeLists.txt | 1 + DataFormats/Detectors/HMPID/CMakeLists.txt | 18 +- .../HMPID/include/DataFormatsHMP/Cluster.h | 61 + .../HMPID/include/DataFormatsHMP/Digit.h | 154 ++ .../HMPID/include/DataFormatsHMP}/Hit.h | 21 +- .../HMPID/include/DataFormatsHMP/Trigger.h | 95 ++ .../Detectors/HMPID}/src/Cluster.cxx | 22 +- .../HMPID/src/DataFormatsHMPLinkDef.h | 10 +- .../Detectors/HMPID}/src/Digit.cxx | 158 +- DataFormats/Detectors/HMPID/src/Trigger.cxx | 40 + Detectors/HMPID/README.md | 11 - Detectors/HMPID/base/CMakeLists.txt | 8 +- .../HMPID/base/include/HMPIDBase/Cluster.h | 67 - .../HMPID/base/include/HMPIDBase/Digit.h | 175 --- .../HMPID/base/include/HMPIDBase/Param.h | 212 ++- .../HMPID/base/include/HMPIDBase/Trigger.h | 102 -- Detectors/HMPID/base/src/HMPIDBaseLinkDef.h | 8 - Detectors/HMPID/base/src/Param.cxx | 104 +- Detectors/HMPID/reconstruction/CMakeLists.txt | 13 +- .../include/HMPIDReconstruction/Clusterer.h | 4 +- .../include/HMPIDReconstruction/DataReader.h | 12 - .../HMPIDReconstruction/HmpidDecodeRawFile.h | 2 +- .../HMPIDReconstruction/HmpidDecodeRawMem.h | 6 +- .../HMPIDReconstruction/HmpidDecoder.h | 7 +- .../HMPIDReconstruction/HmpidDecoder2.h | 181 +++ .../HMPIDReconstruction/HmpidEquipment.h | 2 +- .../HMPID/reconstruction/src/Clusterer.cxx | 2 +- .../HMPID/reconstruction/src/DataReader.cxx | 12 - .../src/HMPIDReconstructionLinkDef.h | 3 +- .../reconstruction/src/HmpidDecodeRawFile.cxx | 9 +- .../reconstruction/src/HmpidDecodeRawMem.cxx | 6 +- .../HMPID/reconstruction/src/HmpidDecoder.cxx | 10 +- .../reconstruction/src/HmpidDecoder2.cxx | 1294 +++++++++++++++++ Detectors/HMPID/simulation/CMakeLists.txt | 13 +- .../include/HMPIDSimulation/Detector.h | 8 +- .../include/HMPIDSimulation/HMPIDDigitizer.h | 8 +- .../include/HMPIDSimulation/HmpidCoder.h | 164 --- .../include/HMPIDSimulation/HmpidCoder2.h | 6 +- Detectors/HMPID/simulation/src/Detector.cxx | 13 +- .../HMPID/simulation/src/HMPIDDigitizer.cxx | 16 +- .../simulation/src/HMPIDSimulationLinkDef.h | 1 - Detectors/HMPID/simulation/src/HmpidCoder.cxx | 442 ------ .../HMPID/simulation/src/HmpidCoder2.cxx | 41 +- Detectors/HMPID/workflow/CMakeLists.txt | 44 +- Detectors/HMPID/workflow/README.md | 86 +- ...izerSpec.h => ClusterizerSpec.h_notused.h} | 0 .../include/HMPIDWorkflow/DataDecoderSpec.h | 7 +- ...aderSpec.h => DigitReaderSpec.h_notused.h} | 2 +- .../include/HMPIDWorkflow/DigitsToRawSpec.h | 5 +- .../HMPIDWorkflow/PedestalsCalculationSpec.h | 9 +- .../include/HMPIDWorkflow/RawToDigitsSpec.h | 70 + .../include/HMPIDWorkflow/ReadRawFileSpec.h | 2 +- ...RawFromDigitsSpec.h => WriteRawFileSpec.h} | 18 +- .../HMPIDWorkflow/WriteRootFromDigitsSpec.h | 45 - .../HMPID/workflow/src/ClusterizerSpec.cxx | 112 -- .../HMPID/workflow/src/DataDecoderSpec.cxx | 59 +- .../HMPID/workflow/src/DigitReaderSpec.cxx | 93 -- .../HMPID/workflow/src/DigitsToRawSpec.cxx | 60 +- .../HMPID/workflow/src/DumpDigitsSpec.cxx | 44 +- .../HMPID/workflow/src/HMPIDRecoWorkflow.cxx | 58 - .../workflow/src/PedestalsCalculationSpec.cxx | 43 +- .../HMPID/workflow/src/RawToDigitsSpec.cxx | 396 +++++ .../HMPID/workflow/src/ReadRawFileSpec.cxx | 2 +- .../HMPID/workflow/src/WriteRawFileSpec.cxx | 169 +++ .../workflow/src/WriteRawFromDigitsSpec.cxx | 146 -- ....cxx => digits-to-raw-stream-workflow.cxx} | 20 +- .../workflow/src/digits-to-raw-workflow.cxx | 3 +- ...ow.cxx => dump-digits-stream-workflow.cxx} | 18 +- .../src/raw-to-digits-stream-workflow.cxx | 67 + .../workflow/src/raw-to-digits-workflow.cxx | 45 +- .../src/raw-to-pedestals-workflow.cxx | 17 +- ....cxx => read-raw-file-stream-workflow.cxx} | 24 +- .../src/write-raw-from-digits-workflow.cxx | 51 - .../src/HMPIDDigitWriterSpec.h | 6 +- .../src/HMPIDDigitizerSpec.cxx | 15 +- 75 files changed, 3215 insertions(+), 2063 deletions(-) create mode 100644 DataFormats/Detectors/HMPID/include/DataFormatsHMP/Cluster.h create mode 100644 DataFormats/Detectors/HMPID/include/DataFormatsHMP/Digit.h rename {Detectors/HMPID/base/include/HMPIDBase => DataFormats/Detectors/HMPID/include/DataFormatsHMP}/Hit.h (65%) create mode 100644 DataFormats/Detectors/HMPID/include/DataFormatsHMP/Trigger.h rename {Detectors/HMPID/base => DataFormats/Detectors/HMPID}/src/Cluster.cxx (65%) rename {Detectors/HMPID/base => DataFormats/Detectors/HMPID}/src/Digit.cxx (80%) create mode 100644 DataFormats/Detectors/HMPID/src/Trigger.cxx delete mode 100644 Detectors/HMPID/README.md delete mode 100644 Detectors/HMPID/base/include/HMPIDBase/Cluster.h delete mode 100644 Detectors/HMPID/base/include/HMPIDBase/Digit.h delete mode 100644 Detectors/HMPID/base/include/HMPIDBase/Trigger.h delete mode 100644 Detectors/HMPID/reconstruction/include/HMPIDReconstruction/DataReader.h create mode 100644 Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidDecoder2.h delete mode 100644 Detectors/HMPID/reconstruction/src/DataReader.cxx create mode 100644 Detectors/HMPID/reconstruction/src/HmpidDecoder2.cxx delete mode 100644 Detectors/HMPID/simulation/include/HMPIDSimulation/HmpidCoder.h delete mode 100644 Detectors/HMPID/simulation/src/HmpidCoder.cxx rename Detectors/HMPID/workflow/include/HMPIDWorkflow/{ClusterizerSpec.h => ClusterizerSpec.h_notused.h} (100%) rename Detectors/HMPID/workflow/include/HMPIDWorkflow/{DigitReaderSpec.h => DigitReaderSpec.h_notused.h} (97%) create mode 100644 Detectors/HMPID/workflow/include/HMPIDWorkflow/RawToDigitsSpec.h rename Detectors/HMPID/workflow/include/HMPIDWorkflow/{WriteRawFromDigitsSpec.h => WriteRawFileSpec.h} (76%) delete mode 100644 Detectors/HMPID/workflow/include/HMPIDWorkflow/WriteRootFromDigitsSpec.h delete mode 100644 Detectors/HMPID/workflow/src/ClusterizerSpec.cxx delete mode 100644 Detectors/HMPID/workflow/src/DigitReaderSpec.cxx delete mode 100644 Detectors/HMPID/workflow/src/HMPIDRecoWorkflow.cxx create mode 100644 Detectors/HMPID/workflow/src/RawToDigitsSpec.cxx create mode 100644 Detectors/HMPID/workflow/src/WriteRawFileSpec.cxx delete mode 100644 Detectors/HMPID/workflow/src/WriteRawFromDigitsSpec.cxx rename Detectors/HMPID/workflow/src/{write-root-from-digits-workflow.cxx => digits-to-raw-stream-workflow.cxx} (72%) rename Detectors/HMPID/workflow/src/{dump-digits-workflow.cxx => dump-digits-stream-workflow.cxx} (69%) create mode 100644 Detectors/HMPID/workflow/src/raw-to-digits-stream-workflow.cxx rename Detectors/HMPID/workflow/src/{read-raw-file-workflow.cxx => read-raw-file-stream-workflow.cxx} (74%) delete mode 100644 Detectors/HMPID/workflow/src/write-raw-from-digits-workflow.cxx diff --git a/DataFormats/Detectors/CMakeLists.txt b/DataFormats/Detectors/CMakeLists.txt index a4ad99788afb7..37f11d409722f 100644 --- a/DataFormats/Detectors/CMakeLists.txt +++ b/DataFormats/Detectors/CMakeLists.txt @@ -16,6 +16,7 @@ add_subdirectory(ITSMFT) add_subdirectory(MUON) add_subdirectory(TOF) add_subdirectory(FIT) +add_subdirectory(HMPID) add_subdirectory(EMCAL) add_subdirectory(ZDC) add_subdirectory(TRD) diff --git a/DataFormats/Detectors/HMPID/CMakeLists.txt b/DataFormats/Detectors/HMPID/CMakeLists.txt index 7c5851c1560cb..4ff82f9474eb8 100644 --- a/DataFormats/Detectors/HMPID/CMakeLists.txt +++ b/DataFormats/Detectors/HMPID/CMakeLists.txt @@ -8,10 +8,16 @@ # granted to it by virtue of its status as an Intergovernmental Organization or # submit itself to any jurisdiction. -# o2_add_library(DataFormatsHMP -# SOURCES src/Cluster.cxx -# PUBLIC_LINK_LIBRARIES O2::ReconstructionDataFormats -# Boost::serialization) +o2_add_library(DataFormatsHMP + SOURCES src/Digit.cxx src/Cluster.cxx src/Trigger.cxx + PUBLIC_LINK_LIBRARIES O2::ReconstructionDataFormats + O2::HMPIDBase + O2::CommonDataFormat + O2::SimulationDataFormat) -# o2_target_root_dictionary(DataFormatsHMP -# HEADERS include/DataFormatsHMP/DataFormat.h +o2_target_root_dictionary(DataFormatsHMP + HEADERS include/DataFormatsHMP/DataFormat.h + include/DataFormatsHMP/Digit.h + include/DataFormatsHMP/Trigger.h + include/DataFormatsHMP/Cluster.h + include/DataFormatsHMP/Hit.h) diff --git a/DataFormats/Detectors/HMPID/include/DataFormatsHMP/Cluster.h b/DataFormats/Detectors/HMPID/include/DataFormatsHMP/Cluster.h new file mode 100644 index 0000000000000..b33cb3b2e01f4 --- /dev/null +++ b/DataFormats/Detectors/HMPID/include/DataFormatsHMP/Cluster.h @@ -0,0 +1,61 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef DETECTORS_HMPID_BASE_INCLUDE_HMPIDDATAFORMAT_CLUSTER_H_ +#define DETECTORS_HMPID_BASE_INCLUDE_HMPIDDATAFORMAT_CLUSTER_H_ + +namespace o2 +{ +namespace hmpid +{ +/// \class Cluster +/// \brief HMPID cluster implementation +class Cluster +{ + public: + Cluster() = default; + + Cluster(int chamber, int size, int NlocMax, float QRaw, float Q, float X, float Y); + ~Cluster() = default; + + int getCh() const { return mChamber; } + void setCh(int chamber) { mChamber = chamber; } + + int getSize() const { return mSize; } + void setSize(int size) { mSize = size; } + + int getQRaw() const { return mQRaw; } + void setQRaw(int QRaw) { mQRaw = QRaw; } + + int getQ() const { return mQ; } + void setQ(int Q) { mQ = Q; } + + int getX() const { return mX; } + void setX(int X) { mX = X; } + + int getY() const { return mY; } + void setY(int Y) { mY = Y; } + + protected: + int mChamber; /// chamber number + int mSize; /// size of the formed cluster from which this cluster deduced + int mNlocMax; /// number of local maxima in formed cluster + float mQRaw; /// QDC value of the raw cluster + float mQ; /// QDC value of the actual cluster + float mX; /// local x postion, [cm] + float mY; /// local y postion, [cm] + + ClassDefNV(Cluster, 1); +}; + +} // namespace hmpid +} // namespace o2 + +#endif /* DETECTORS_HMPID_BASE_INCLUDE_HMPIDDATAFORMAT_CLUSTER_H_ */ diff --git a/DataFormats/Detectors/HMPID/include/DataFormatsHMP/Digit.h b/DataFormats/Detectors/HMPID/include/DataFormatsHMP/Digit.h new file mode 100644 index 0000000000000..fc7708bf23f5a --- /dev/null +++ b/DataFormats/Detectors/HMPID/include/DataFormatsHMP/Digit.h @@ -0,0 +1,154 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// +/// \file Digit.h +/// \author Antonio Franco - INFN Bari +/// \version 1.0 +/// \date 15/02/2021 + +// History +// 10/03/2021 Complete review + +#ifndef DETECTORS_HMPID_BASE_INCLUDE_HMPIDDATAFORMAT_DIGIT_H_ +#define DETECTORS_HMPID_BASE_INCLUDE_HMPIDDATAFORMAT_DIGIT_H_ + +#include +#include +#include "DataFormatsHMP/Hit.h" // for hit +#include "HMPIDBase/Param.h" // for param + +namespace o2 +{ +namespace hmpid +{ +/// \class Digit +/// \brief HMPID Digit declaration +class Digit +{ + public: + // Coordinates Conversion Functions + static inline uint32_t abs(int ch, int pc, int x, int y) { return ch << 24 | pc << 16 | x << 8 | y; } + static inline int ddl2C(int ddl) { return ddl >> 1; } //ddl -> chamber + static inline int a2C(uint32_t pad) { return (pad & 0xFF000000) >> 24; } //abs pad -> chamber + static inline int a2P(uint32_t pad) { return (pad & 0x00FF0000) >> 16; } //abs pad -> pc + static inline int a2X(uint32_t pad) { return (pad & 0x0000FF00) >> 8; } //abs pad -> pad X + static inline int a2Y(uint32_t pad) { return (pad & 0x000000FF); } //abs pad -> pad Y + static inline uint32_t photo2Pad(int ch, int pc, int x, int y) { return abs(ch, pc, x, y); } + static uint32_t equipment2Pad(int Equi, int Colu, int Dilo, int Chan); + static uint32_t absolute2Pad(int Module, int x, int y); + static void pad2Equipment(uint32_t pad, int* Equi, int* Colu, int* Dilo, int* Chan); + static void pad2Absolute(uint32_t pad, int* Module, int* x, int* y); + static void pad2Photo(uint32_t pad, uint8_t* chamber, uint8_t* photo, uint8_t* x, uint8_t* y); + static void absolute2Equipment(int Module, int x, int y, int* Equi, int* Colu, int* Dilo, int* Chan); + static void equipment2Absolute(int Equi, int Colu, int Dilo, int Chan, int* Module, int* x, int* y); + + // Trigger time Conversion Functions + // static inline uint64_t orbitBcToEventId(uint32_t Orbit, uint16_t BC) { return ((Orbit << 12) | (0x0FFF & BC)); }; + // static inline uint32_t eventIdToOrbit(uint64_t EventId) { return (EventId >> 12); }; + // static inline uint16_t EventIdToBc(uint64_t EventId) { return (EventId & 0x0FFF); }; + // static double OrbitBcToTimeNs(uint32_t Orbit, uint16_t BC); + // static uint32_t TimeNsToOrbit(double TimeNs); + // static uint16_t TimeNsToBc(double TimeNs); + // static void TimeNsToOrbitBc(double TimeNs, uint32_t& Orbit, uint16_t& Bc); + + // Operators definition ! + friend inline bool operator<(const Digit& l, const Digit& r) { return l.getPadID() < r.getPadID(); }; + friend inline bool operator==(const Digit& l, const Digit& r) { return l.getPadID() == r.getPadID(); }; + friend inline bool operator>(const Digit& l, const Digit& r) { return r < l; }; + friend inline bool operator<=(const Digit& l, const Digit& r) { return !(l > r); }; + friend inline bool operator>=(const Digit& l, const Digit& r) { return !(l < r); }; + friend inline bool operator!=(const Digit& l, const Digit& r) { return !(l == r); }; + + friend std::ostream& operator<<(std::ostream& os, const Digit& d); + + public: + Digit() = default; + Digit(int pad, uint16_t charge); + Digit(int chamber, int photo, int x, int y, uint16_t charge); + Digit(uint16_t charge, int equipment, int column, int dilogic, int channel); + Digit(uint16_t charge, int module, int x, int y); + + // Getter & Setters + uint16_t getCharge() const { return mQ; } + void setCharge(uint16_t Q) + { + mQ = Q; + return; + }; + int getPadID() const { return mCh << 24 | mPh << 16 | mX << 8 | mY; } + void setPadID(uint32_t pad) + { + mCh = pad >> 24; + mPh = (pad & 0x00FF0000) >> 16; + mX = (pad & 0x0000FF00) >> 8; + mY = (pad & 0x000000FF); + return; + }; + + bool isValid() { return (mCh == 0xFF ? true : false); }; + void setInvalid() + { + mCh = 0xFF; + return; + }; + + // // convenience wrapper function for conversion to x-y pad coordinates + // int getPx() const { return A2X(mPad); } + // int getPy() const { return A2Y(mPad); } + // int getPhC() const { return A2P(mPad); } + // int getCh() const { return A2C(mPad); } + + // Charge management functions + static void getPadAndTotalCharge(o2::hmpid::HitType const& hit, int& chamber, int& pc, int& px, int& py, float& totalcharge); + static float getFractionalContributionForPad(o2::hmpid::HitType const& hit, int somepad); + void addCharge(float q) + { + mQ += q; + if (mQ > 0x0FFF) { + mQ = 0x0FFF; + } + } + void subCharge(float q) { mQ -= q; } + + public: + // Members + uint16_t mQ = 0; + uint8_t mCh = 0; // 0xFF indicates invalid digit + uint8_t mPh = 0; + uint8_t mX = 0; + uint8_t mY = 0; + + // The Pad Unique Id, code a pad inside one HMPID chamber. + // Bit Map : 0000.0000.cccc.pppp.xxxx.xxxx.yyyy.yyyy + // cccc := chamber [0..6] + // pppp := photo cathode [0..5] + // xxxx.xxxx := horizontal displacement [0..79] + // yyyy.yyyy := vertical displacement [0..47] + //uint32_t mPad = 0; // 0xFFFFFFFF indicates invalid digit + + // Get the Geometric center of the pad + static float lorsX(int pad) { return Param::lorsX(a2P(pad), a2X(pad)); } //center of the pad x, [cm] + static float lorsY(int pad) { return Param::lorsY(a2P(pad), a2Y(pad)); } //center of the pad y, [cm] + + // determines the total charge created by a hit + // might modify the localX, localY coordiates associated to the hit + static Double_t qdcTot(Double_t e, Double_t time, Int_t pc, Int_t px, Int_t py, Double_t& localX, Double_t& localY); + static Double_t intPartMathiX(Double_t x, Int_t pad); + static Double_t intPartMathiY(Double_t y, Int_t pad); + static Double_t inMathieson(Double_t localX, Double_t localY, int pad); + + ClassDefNV(Digit, 2); +}; + +} // namespace hmpid +} // namespace o2 + +#endif /* DETECTORS_HMPID_BASE_INCLUDE_HMPIDDATAFORMAT_DIGIT_H_ */ diff --git a/Detectors/HMPID/base/include/HMPIDBase/Hit.h b/DataFormats/Detectors/HMPID/include/DataFormatsHMP/Hit.h similarity index 65% rename from Detectors/HMPID/base/include/HMPIDBase/Hit.h rename to DataFormats/Detectors/HMPID/include/DataFormatsHMP/Hit.h index 16e944da8a051..f049c98d30af8 100644 --- a/Detectors/HMPID/base/include/HMPIDBase/Hit.h +++ b/DataFormats/Detectors/HMPID/include/DataFormatsHMP/Hit.h @@ -8,10 +8,18 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef DETECTORS_HMPID_BASE_INCLUDE_HMPIDBASE_HIT_H_ -#define DETECTORS_HMPID_BASE_INCLUDE_HMPIDBASE_HIT_H_ +/// +/// \file Digit.h +/// \author Antonio Franco - INFN Bari +/// \version 1.0 +/// \date 15/02/2021 -#include "SimulationDataFormat/BaseHits.h" +// History +// +#ifndef DETECTORS_HMPID_BASE_INCLUDE_HMPIDDATAFORMAT_HIT_H_ +#define DETECTORS_HMPID_BASE_INCLUDE_HMPIDDATAFORMAT_HIT_H_ + +#include "SimulationDataFormat/BaseHits.h" // for BasicXYZEHit #include "CommonUtils/ShmAllocator.h" namespace o2 @@ -20,11 +28,12 @@ namespace hmpid { // define HMPID hit type +// class Hit : public o2::BasicXYZQHit class HitType : public o2::BasicXYZEHit { public: - using Base = o2::BasicXYZEHit; - using Base::Base; + using BasicXYZEHit::BasicXYZEHit; + ClassDef(HitType, 1); }; @@ -41,4 +50,4 @@ class allocator : public o2::utils::ShmAllocator +#include "CommonDataFormat/InteractionRecord.h" + +namespace o2 +{ +namespace hmpid +{ +/// \class Trigger +/// \brief HMPID Trigger declaration +class Event +{ + public: + static inline uint64_t getTriggerID(uint32_t Orbit, uint16_t BC) { return ((Orbit << 12) | (0x0FFF & BC)); }; + + public: + Event() = default; + Event(InteractionRecord ir, int32_t first, int32_t last) + { + mIr.bc = ir.bc; + mIr.orbit = ir.orbit; + mFirstDigit = first; + mLastDigit = last; + }; + const InteractionRecord& getIr() const { return mIr; }; + uint32_t getOrbit() const { return mIr.orbit; }; + uint16_t getBc() const { return mIr.bc; }; + uint64_t getTriggerID() const { return ((mIr.orbit << 12) | (0x0FFF & mIr.bc)); }; + void setOrbit(uint32_t orbit) + { + mIr.orbit = orbit; + return; + } + void setBC(uint16_t bc) + { + mIr.bc = bc; + return; + } + void setTriggerID(uint64_t trigger) + { + mIr.orbit = (trigger >> 12); + mIr.bc = (trigger & 0x0FFF); + return; + } + void setDigitsPointer(int32_t first, int32_t last) + { + mFirstDigit = first; + mLastDigit = last; + return; + } + + // Operators definition ! + friend inline bool operator<(const Event& l, const Event& r) { return l.getTriggerID() < r.getTriggerID(); }; + friend inline bool operator==(const Event& l, const Event& r) { return l.getTriggerID() == r.getTriggerID(); }; + friend inline bool operator>(const Event& l, const Event& r) { return r < l; }; + friend inline bool operator<=(const Event& l, const Event& r) { return !(l > r); }; + friend inline bool operator>=(const Event& l, const Event& r) { return !(l < r); }; + friend inline bool operator!=(const Event& l, const Event& r) { return !(l == r); }; + + // Digit ASCII format (Orbit,BunchCrossing)[LHC Time nSec] + friend std::ostream& operator<<(std::ostream& os, const Event& d); + + public: + int32_t mFirstDigit = 0; + int32_t mLastDigit = -1; + + private: + // Members + InteractionRecord mIr; + + ClassDefNV(Event, 2); +}; + +} // namespace hmpid +} // namespace o2 + +#endif /* DETECTORS_HMPID_BASE_INCLUDE_HMPIDBASE_TRIGGER_H_ */ diff --git a/Detectors/HMPID/base/src/Cluster.cxx b/DataFormats/Detectors/HMPID/src/Cluster.cxx similarity index 65% rename from Detectors/HMPID/base/src/Cluster.cxx rename to DataFormats/Detectors/HMPID/src/Cluster.cxx index 1b5197b33d0c0..96862940d0e34 100644 --- a/Detectors/HMPID/base/src/Cluster.cxx +++ b/DataFormats/Detectors/HMPID/src/Cluster.cxx @@ -8,16 +8,20 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#include "HMPIDBase/Cluster.h" -#include "HMPIDBase/Param.h" -#include "TRandom.h" -#include "TMath.h" - -using namespace o2::hmpid; +#include +#include "DataFormatsHMP/Cluster.h" ClassImp(o2::hmpid::Cluster); -Cluster::Cluster(Int_t chamber, Int_t size, Int_t NlocMax, Double_t QRaw, Double_t Q, Double_t X, Double_t Y) - : mChamber(chamber), mSize(size), mNlocMax(NlocMax), mQRaw(QRaw), mQ(Q), mX(X), mY(Y) +namespace o2 { -} +namespace hmpid +{ + +Cluster::Cluster(int chamber, int size, int NlocMax, float QRaw, float Q, float X, float Y) + : mChamber(chamber), mSize(size), mNlocMax(NlocMax), mQRaw(QRaw), mQ(Q), mX(X), mY(Y) + + {}; + +} // namespace hmpid +} // namespace o2 diff --git a/DataFormats/Detectors/HMPID/src/DataFormatsHMPLinkDef.h b/DataFormats/Detectors/HMPID/src/DataFormatsHMPLinkDef.h index 027b310bd7b29..cd0af6426635a 100644 --- a/DataFormats/Detectors/HMPID/src/DataFormatsHMPLinkDef.h +++ b/DataFormats/Detectors/HMPID/src/DataFormatsHMPLinkDef.h @@ -13,6 +13,14 @@ #pragma link off all globals; #pragma link off all classes; #pragma link off all functions; -//#pragma link C++ class o2::hmpid::Cluster + ; + +#pragma link C++ class o2::hmpid::Digit + ; +#pragma link C++ class vector < o2::hmpid::Digit> + ; +#pragma link C++ class o2::hmpid::HitType + ; +#pragma link C++ class vector < o2::hmpid::HitType> + ; +#pragma link C++ class o2::hmpid::Cluster + ; +#pragma link C++ class vector < o2::hmpid::Cluster> + ; +#pragma link C++ class o2::hmpid::Event + ; +#pragma link C++ class vector < o2::hmpid::Event> + ; #endif diff --git a/Detectors/HMPID/base/src/Digit.cxx b/DataFormats/Detectors/HMPID/src/Digit.cxx similarity index 80% rename from Detectors/HMPID/base/src/Digit.cxx rename to DataFormats/Detectors/HMPID/src/Digit.cxx index 2711a642a2971..96a95ca56458e 100644 --- a/Detectors/HMPID/base/src/Digit.cxx +++ b/DataFormats/Detectors/HMPID/src/Digit.cxx @@ -16,88 +16,90 @@ /// \date 15/02/2021 /* ------ HISTORY --------- + 10/03/2021 / complete review + */ -#include "HMPIDBase/Digit.h" +#include +#include +#include "CommonConstants/LHCConstants.h" #include "HMPIDBase/Geo.h" #include "HMPIDBase/Param.h" -#include "TRandom.h" -#include "TMath.h" -#include "CommonConstants/LHCConstants.h" - -using namespace o2::hmpid; +#include "DataFormatsHMP/Digit.h" ClassImp(o2::hmpid::Digit); +namespace o2 +{ +namespace hmpid +{ + // ============= Digit Class implementation ======= /// Constructor : Create the Digit structure. Accepts the trigger time (Orbit,BC) /// The mapping of the digit is in the Photo Cathod coords /// (Chamber, PhotoCathod, X, Y) -/// @param[in] bc : the bunch crossing [0 .. 2^12-1] -/// @param[in] orbit : the orbit number [0 .. 2^32-1] /// @param[in] pad : the Digit Unique Id [0x00CPXXYY] /// @param[in] charge : the value of the charge [0 .. 2^12-1] -Digit::Digit(uint16_t bc, uint32_t orbit, int pad, uint16_t charge) +Digit::Digit(int pad, uint16_t charge) { - mBc = bc; - mOrbit = orbit; mQ = charge > 0x0FFF ? 0x0FFF : charge; - mPad = pad; + mCh = a2C(pad); + mPh = a2P(pad); + mX = a2X(pad); + mY = a2Y(pad); } /// Constructor : Create the Digit structure. Accepts the trigger time (Orbit,BC) /// The mapping of the digit is in the Photo Cathod coords /// (Chamber, PhotoCathod, X, Y) -/// @param[in] bc : the bunch crossing [0 .. 2^12-1] -/// @param[in] orbit : the orbit number [0 .. 2^32-1] /// @param[in] chamber : the HMPID module [0 .. 6] /// @param[in] photo : the photo cathode number [0 .. 5] (left-down to right-up) /// @param[in] x : the horizontal in cathode displacement [0 .. 79] /// @param[in] y : the vertical in cathode displacement [0 .. 47] /// @param[in] charge : the value of the charge [0 .. 2^12-1] -Digit::Digit(uint16_t bc, uint32_t orbit, int chamber, int photo, int x, int y, uint16_t charge) +Digit::Digit(int chamber, int photo, int x, int y, uint16_t charge) { - mBc = bc; - mOrbit = orbit; mQ = charge > 0x0FFF ? 0x0FFF : charge; - mPad = Abs(chamber, photo, x, y); + mCh = chamber; + mPh = photo; + mX = x; + mY = y; } /// Constructor : Create the Digit structure. Accepts the trigger time (Orbit,BC) /// The mapping of the digit is in the Hardware coords /// (Equipment, Column, Dilogic, Channel) -/// @param[in] bc : the bunch crossing [0 .. 2^12-1] -/// @param[in] orbit : the orbit number [0 .. 2^32-1] /// @param[in] charge : the value of the charge [0 .. 2^12-1] /// @param[in] equipment : the HMPID DDL link [0 .. 13] /// @param[in] column : the readout column number [0 .. 23] /// @param[in] dilogic : the displacement in the Dilogics chain [0 .. 9] /// @param[in] channel : the number of gassiplexes channels [0 .. 47] -Digit::Digit(uint16_t bc, uint32_t orbit, uint16_t charge, int equipment, int column, int dilogic, int channel) +Digit::Digit(uint16_t charge, int equipment, int column, int dilogic, int channel) { - mBc = bc; - mOrbit = orbit; mQ = charge > 0x0FFF ? 0x0FFF : charge; - mPad = Equipment2Pad(equipment, column, dilogic, channel); + pad2Photo(equipment2Pad(equipment, column, dilogic, channel), &mCh, &mPh, &mX, &mY); } /// Constructor : Create the Digit structure. Accepts the trigger time (Orbit,BC) /// The mapping of the digit is in the Logical coords /// (Module, X, Y) -/// @param[in] bc : the bunch crossing [0 .. 2^12-1] -/// @param[in] orbit : the orbit number [0 .. 2^32-1] /// @param[in] charge : the value of the charge [0 .. 2^12-1] /// @param[in] module : the HMPID Module [0 .. 6] /// @param[in] x : the horizontal in Module displacement [0 .. 159] /// @param[in] y : the vertical in Module displacement [0 .. 143] -Digit::Digit(uint16_t bc, uint32_t orbit, uint16_t charge, int module, int x, int y) +Digit::Digit(uint16_t charge, int module, int x, int y) { - mBc = bc; - mOrbit = orbit; mQ = charge > 0x0FFF ? 0x0FFF : charge; - mPad = Absolute2Pad(module, x, y); + pad2Photo(absolute2Pad(module, x, y), &mCh, &mPh, &mX, &mY); } +// Digit ASCCI format Dump := [Chamber,PhotoCathod,X,Y]@(Orbit,BunchCrossing)=Charge +std::ostream& operator<<(std::ostream& os, const o2::hmpid::Digit& d) +{ + os << "[" << (int)d.mCh << "," << (int)d.mPh << "," << (int)d.mX << "," << (int)d.mY << "]=" << d.mQ; + return os; +}; + // ----- Coordinate Conversion ----- /// Equipment2Pad : Converts the coords from Hardware to Digit Unique Id @@ -106,7 +108,7 @@ Digit::Digit(uint16_t bc, uint32_t orbit, uint16_t charge, int module, int x, in /// @param[in] Dilo : the displacement in the Dilogics chain [0 .. 9] /// @param[in] Chan : the number of gassiplexes channels [0 .. 47] /// @return uint32_t : the Digit Unique Id [0x00CPXXYY] -uint32_t Digit::Equipment2Pad(int Equi, int Colu, int Dilo, int Chan) +uint32_t Digit::equipment2Pad(int Equi, int Colu, int Dilo, int Chan) { // Check the input data if (Equi < 0 || Equi >= Geo::MAXEQUIPMENTS || Colu < 0 || Colu >= Geo::N_COLUMNS || @@ -127,7 +129,7 @@ uint32_t Digit::Equipment2Pad(int Equi, int Colu, int Dilo, int Chan) pc = 5 - pc; py = Geo::MAXYPHOTO - py; } - return Abs(ch, pc, px, py); // Pack the coords into the PadID word + return abs(ch, pc, px, py); // Pack the coords into the PadID word } /// Pad2Equipment : Converts the Digit Unique Id to Hardware coords @@ -136,12 +138,12 @@ uint32_t Digit::Equipment2Pad(int Equi, int Colu, int Dilo, int Chan) /// @param[out] Colu : the readout column number [0 .. 23] /// @param[out] Dilo : the displacement in the Dilogics chain [0 .. 9] /// @param[out] Chan : the number of gassiplexes channels [0 .. 47] -void Digit::Pad2Equipment(uint32_t pad, int* Equi, int* Colu, int* Dilo, int* Chan) +void Digit::pad2Equipment(uint32_t pad, int* Equi, int* Colu, int* Dilo, int* Chan) { - int ch, ph, px, py; + uint8_t ch, ph, px, py; int y2chan[6] = {5, 3, 1, 0, 2, 4}; - Pad2Photo(pad, &ch, &ph, &px, &py); // Unpak the pad ID in the photo cathode coords + pad2Photo(pad, &ch, &ph, &px, &py); // Unpak the pad ID in the photo cathode coords bool isEven = (ph % 2) == 0 ? true : false; int eq = ch * Geo::EQUIPMENTSPERMODULE + 1; @@ -166,10 +168,10 @@ void Digit::Pad2Equipment(uint32_t pad, int* Equi, int* Colu, int* Dilo, int* Ch /// @param[out] Colu : the readout column number [0 .. 23] /// @param[out] Dilo : the displacement in the Dilogics chain [0 .. 9] /// @param[out] Chan : the number of gassiplexes channels [0 .. 47] -void Digit::Absolute2Equipment(int Module, int x, int y, int* Equi, int* Colu, int* Dilo, int* Chan) +void Digit::absolute2Equipment(int Module, int x, int y, int* Equi, int* Colu, int* Dilo, int* Chan) { - uint32_t pad = Absolute2Pad(Module, x, y); - Pad2Equipment(pad, Equi, Colu, Dilo, Chan); + uint32_t pad = absolute2Pad(Module, x, y); + pad2Equipment(pad, Equi, Colu, Dilo, Chan); return; } @@ -181,10 +183,10 @@ void Digit::Absolute2Equipment(int Module, int x, int y, int* Equi, int* Colu, i /// @param[out] Module : the HMPID Module number [0..6] /// @param[out] x : the horizontal displacement [0..159] /// @param[out] y : the vertical displacement [0..143] -void Digit::Equipment2Absolute(int Equi, int Colu, int Dilo, int Chan, int* Module, int* x, int* y) +void Digit::equipment2Absolute(int Equi, int Colu, int Dilo, int Chan, int* Module, int* x, int* y) { - uint32_t pad = Equipment2Pad(Equi, Colu, Dilo, Chan); - Pad2Absolute(pad, Module, x, y); + uint32_t pad = equipment2Pad(Equi, Colu, Dilo, Chan); + pad2Absolute(pad, Module, x, y); return; } @@ -193,12 +195,12 @@ void Digit::Equipment2Absolute(int Equi, int Colu, int Dilo, int Chan, int* Modu /// @param[in] x : the horizontal displacement [0..159] /// @param[in] y : the vertical displacement [0..143] /// @return uint32_t : the Digit Unique Id [0x00CPXXYY] -uint32_t Digit::Absolute2Pad(int Module, int x, int y) +uint32_t Digit::absolute2Pad(int Module, int x, int y) { int ph = (y / Geo::N_PHOTOCATODSY) * 2 + ((x >= Geo::HALFXROWS) ? 1 : 0); int px = x % Geo::HALFXROWS; int py = y % Geo::N_PHOTOCATODSY; - return Abs(Module, ph, px, py); + return abs(Module, ph, px, py); } /// Pad2Absolute : Converts the the Digit Unique Id to Module coords @@ -206,12 +208,12 @@ uint32_t Digit::Absolute2Pad(int Module, int x, int y) /// @param[out] Module : the HMPID Module number [0..6] /// @param[out] x : the horizontal displacement [0..159] /// @param[out] y : the vertical displacement [0..143] -void Digit::Pad2Absolute(uint32_t pad, int* Module, int* x, int* y) +void Digit::pad2Absolute(uint32_t pad, int* Module, int* x, int* y) { - *Module = A2C(pad); - int ph = A2P(pad); - int px = A2X(pad); - int py = A2Y(pad); + *Module = a2C(pad); + int ph = a2P(pad); + int px = a2X(pad); + int py = a2Y(pad); *x = px + ((ph % 2 == 1) ? Geo::HALFXROWS : 0); *y = ((ph >> 1) * Geo::N_PHOTOCATODSY) + py; return; @@ -223,12 +225,12 @@ void Digit::Pad2Absolute(uint32_t pad, int* Module, int* x, int* y) /// @param[out] photo : the photo cathode number [0..5] /// @param[out] x : the horizontal displacement [0..79] /// @param[out] y : the vertical displacement [0..47] -void Digit::Pad2Photo(uint32_t pad, int* chamber, int* photo, int* x, int* y) +void Digit::pad2Photo(uint32_t pad, uint8_t* chamber, uint8_t* photo, uint8_t* x, uint8_t* y) { - *chamber = A2C(pad); - *photo = A2P(pad); - *x = A2X(pad); - *y = A2Y(pad); + *chamber = a2C(pad); + *photo = a2P(pad); + *x = a2X(pad); + *y = a2Y(pad); return; } @@ -246,10 +248,10 @@ void Digit::getPadAndTotalCharge(HitType const& hit, int& chamber, int& pc, int& double localY; chamber = hit.GetDetectorID(); double tmp[3] = {hit.GetX(), hit.GetY(), hit.GetZ()}; - Param::Instance()->Mars2Lors(chamber, tmp, localX, localY); - Param::Lors2Pad(localX, localY, pc, px, py); + Param::instance()->mars2Lors(chamber, tmp, localX, localY); + Param::lors2Pad(localX, localY, pc, px, py); - totalcharge = Digit::QdcTot(hit.GetEnergyLoss(), hit.GetTime(), pc, px, py, localX, localY); + totalcharge = Digit::qdcTot(hit.GetEnergyLoss(), hit.GetTime(), pc, px, py, localX, localY); return; } @@ -266,9 +268,9 @@ float Digit::getFractionalContributionForPad(HitType const& hit, int somepad) const auto chamber = hit.GetDetectorID(); // chamber number is in detID double tmp[3] = {hit.GetX(), hit.GetY(), hit.GetZ()}; // converting chamber id and hit coordiates to local coordinates - Param::Instance()->Mars2Lors(chamber, tmp, localX, localY); + Param::instance()->mars2Lors(chamber, tmp, localX, localY); // calculate charge fraction in given pad - return Digit::InMathieson(localX, localY, somepad); + return Digit::inMathieson(localX, localY, somepad); } /// QdcTot : Samples total charge associated to a hit @@ -281,7 +283,7 @@ float Digit::getFractionalContributionForPad(HitType const& hit, int somepad) /// @param[out] localX : the horizontal displacement related to Anode Wires /// @param[out] localY : the vertical displacement related to Anode Wires /// @return : total QDC -Double_t Digit::QdcTot(Double_t e, Double_t time, Int_t pc, Int_t px, Int_t py, Double_t& localX, Double_t& localY) +Double_t Digit::qdcTot(Double_t e, Double_t time, Int_t pc, Int_t px, Int_t py, Double_t& localX, Double_t& localY) { // // Arguments: e- @@ -293,7 +295,7 @@ Double_t Digit::QdcTot(Double_t e, Double_t time, Int_t pc, Int_t px, Int_t py, if (py < 0) { return 0; } else { - double y = Param::LorsY(pc, py); + double y = Param::lorsY(pc, py); localY = ((y - localY) > 0) ? y - 0.2 : y + 0.2; //shift to the nearest anod wire double x = (localX > 66.6) ? localX - 66.6 : localX; //sagita is for PC (0-64) and not for chamber @@ -321,15 +323,15 @@ Double_t Digit::QdcTot(Double_t e, Double_t time, Int_t pc, Int_t px, Int_t py, /// @param[in] x : position of the center of Mathieson distribution /// @param[in] pad : the Digit Unique Id [0x00CPXXYY] /// @return : a charge fraction [0-1] imposed into the pad -Double_t Digit::IntPartMathiX(Double_t x, int pad) +Double_t Digit::intPartMathiX(Double_t x, int pad) { - Double_t shift1 = -LorsX(pad) + 0.5 * o2::hmpid::Param::SizePadX(); - Double_t shift2 = -LorsX(pad) - 0.5 * o2::hmpid::Param::SizePadX(); + Double_t shift1 = -lorsX(pad) + 0.5 * o2::hmpid::Param::sizePadX(); + Double_t shift2 = -lorsX(pad) - 0.5 * o2::hmpid::Param::sizePadX(); - Double_t ux1 = o2::hmpid::Param::SqrtK3x() * TMath::TanH(o2::hmpid::Param::K2x() * (x + shift1) / o2::hmpid::Param::PitchAnodeCathode()); - Double_t ux2 = o2::hmpid::Param::SqrtK3x() * TMath::TanH(o2::hmpid::Param::K2x() * (x + shift2) / o2::hmpid::Param::PitchAnodeCathode()); + Double_t ux1 = o2::hmpid::Param::sqrtK3x() * TMath::TanH(o2::hmpid::Param::k2x() * (x + shift1) / o2::hmpid::Param::pitchAnodeCathode()); + Double_t ux2 = o2::hmpid::Param::sqrtK3x() * TMath::TanH(o2::hmpid::Param::k2x() * (x + shift2) / o2::hmpid::Param::pitchAnodeCathode()); - return o2::hmpid::Param::K4x() * (TMath::ATan(ux2) - TMath::ATan(ux1)); + return o2::hmpid::Param::k4x() * (TMath::ATan(ux2) - TMath::ATan(ux1)); } /// IntPartMathiY : Integration of Mathieson. @@ -339,15 +341,15 @@ Double_t Digit::IntPartMathiX(Double_t x, int pad) /// @param[in] y : position of the center of Mathieson distribution /// @param[in] pad : the Digit Unique Id [0x00CPXXYY] /// @return : a charge fraction [0-1] imposed into the pad -Double_t Digit::IntPartMathiY(Double_t y, int pad) +Double_t Digit::intPartMathiY(Double_t y, int pad) { - Double_t shift1 = -LorsY(pad) + 0.5 * o2::hmpid::Param::SizePadY(); - Double_t shift2 = -LorsY(pad) - 0.5 * o2::hmpid::Param::SizePadY(); + Double_t shift1 = -lorsY(pad) + 0.5 * o2::hmpid::Param::sizePadY(); + Double_t shift2 = -lorsY(pad) - 0.5 * o2::hmpid::Param::sizePadY(); - Double_t uy1 = o2::hmpid::Param::SqrtK3y() * TMath::TanH(o2::hmpid::Param::K2y() * (y + shift1) / o2::hmpid::Param::PitchAnodeCathode()); - Double_t uy2 = o2::hmpid::Param::SqrtK3y() * TMath::TanH(o2::hmpid::Param::K2y() * (y + shift2) / o2::hmpid::Param::PitchAnodeCathode()); + Double_t uy1 = o2::hmpid::Param::sqrtK3y() * TMath::TanH(o2::hmpid::Param::k2y() * (y + shift1) / o2::hmpid::Param::pitchAnodeCathode()); + Double_t uy2 = o2::hmpid::Param::sqrtK3y() * TMath::TanH(o2::hmpid::Param::k2y() * (y + shift2) / o2::hmpid::Param::pitchAnodeCathode()); - return o2::hmpid::Param::K4y() * (TMath::ATan(uy2) - TMath::ATan(uy1)); + return o2::hmpid::Param::k4y() * (TMath::ATan(uy2) - TMath::ATan(uy1)); } /// InMathieson : Integration of Mathieson. @@ -358,11 +360,11 @@ Double_t Digit::IntPartMathiY(Double_t y, int pad) /// @param[in] localY : Y position of the center of Mathieson distribution /// @param[in] pad : the Digit Unique Id [0x00CPXXYY] /// @return : a charge fraction [0-1] imposed into the pad -Double_t Digit::InMathieson(Double_t localX, Double_t localY, Int_t pad) +Double_t Digit::inMathieson(Double_t localX, Double_t localY, Int_t pad) { - return 4. * IntPartMathiX(localX, pad) * IntPartMathiY(localY, pad); + return 4. * intPartMathiX(localX, pad) * intPartMathiY(localY, pad); } - +/* // ---- Time conversion functions ---- /// OrbitBcToTimeNs : Converts the Orbit,BC pair in absolute @@ -409,6 +411,7 @@ void Digit::TimeNsToOrbitBc(double TimeNs, uint32_t& Orbit, uint16_t& Bc) return; } + // ---- Functions to manage Digit vectors ---- /// eventEquipPadsComp : Function for order digits (Event,Chamber,Photo,x,y) @@ -434,6 +437,7 @@ bool Digit::eventEquipPadsComp(Digit& d1, Digit& d2) return false; }; + /// extractDigitsPerEvent : Function for select a sub vector of Digits of the /// same event /// @param[in] Digits : one vector of Digits @@ -464,5 +468,7 @@ std::vector* Digit::extractEvents(std::vector& Digit } return (eventIds); }; +*/ -// -------- eof ----------- +} // namespace hmpid +} // namespace o2 diff --git a/DataFormats/Detectors/HMPID/src/Trigger.cxx b/DataFormats/Detectors/HMPID/src/Trigger.cxx new file mode 100644 index 0000000000000..fb4edbafe044c --- /dev/null +++ b/DataFormats/Detectors/HMPID/src/Trigger.cxx @@ -0,0 +1,40 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// +/// \file Trigger.cxx +/// \author Antonio Franco - INFN Bari +/// \brief Base Class to manage HMPID Trigger data +/// \version 1.0 +/// \date 6/04/2021 + +/* ------ HISTORY --------- + +*/ + +#include +#include "DataFormatsHMP/Trigger.h" + +ClassImp(o2::hmpid::Event); + +namespace o2 +{ +namespace hmpid +{ + +// Digit ASCCI format Dump := (Orbit,BC @ LHCtime ns) [first_digit_idx .. last_digit_idx] +std::ostream& operator<<(std::ostream& os, const o2::hmpid::Event& d) +{ + os << "(" << d.mIr.orbit << "," << d.mIr.bc << " @ " << d.mIr.bc2ns() << " ns) [" << d.mFirstDigit << " .. " << d.mLastDigit << "]"; + return os; +}; + +} // namespace hmpid +} // namespace o2 diff --git a/Detectors/HMPID/README.md b/Detectors/HMPID/README.md deleted file mode 100644 index 8a737eeb5688f..0000000000000 --- a/Detectors/HMPID/README.md +++ /dev/null @@ -1,11 +0,0 @@ - - -# HMPID - -This is a top page for the HMPID detector documentation. - - \ No newline at end of file diff --git a/Detectors/HMPID/base/CMakeLists.txt b/Detectors/HMPID/base/CMakeLists.txt index 2bab4f0230f37..f8cc5111478e2 100644 --- a/Detectors/HMPID/base/CMakeLists.txt +++ b/Detectors/HMPID/base/CMakeLists.txt @@ -9,13 +9,11 @@ # submit itself to any jurisdiction. o2_add_library(HMPIDBase - SOURCES src/Param.cxx src/Digit.cxx src/Cluster.cxx src/Geo.cxx + SOURCES src/Param.cxx src/Geo.cxx PUBLIC_LINK_LIBRARIES O2::CommonDataFormat - O2::SimulationDataFormat ROOT::Physics) + O2::SimulationDataFormat + ROOT::Physics) o2_target_root_dictionary(HMPIDBase HEADERS include/HMPIDBase/Param.h - include/HMPIDBase/Digit.h - include/HMPIDBase/Trigger.h - include/HMPIDBase/Cluster.h include/HMPIDBase/Geo.h) diff --git a/Detectors/HMPID/base/include/HMPIDBase/Cluster.h b/Detectors/HMPID/base/include/HMPIDBase/Cluster.h deleted file mode 100644 index 4ceb801e1aee5..0000000000000 --- a/Detectors/HMPID/base/include/HMPIDBase/Cluster.h +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -#ifndef DETECTORS_HMPID_BASE_INCLUDE_HMPIDBASE_CLUSTER_H_ -#define DETECTORS_HMPID_BASE_INCLUDE_HMPIDBASE_CLUSTER_H_ - -#include "CommonDataFormat/TimeStamp.h" -//#include "HMPIDBase/Hit.h" // for hit -#include "HMPIDBase/Param.h" // for param -#include "TMath.h" - -namespace o2 -{ -namespace hmpid -{ - -/// \class Claster -/// \brief HMPID cluster implementation -class Cluster -{ - public: - Cluster() = default; - - Cluster(Int_t chamber, Int_t size, Int_t NlocMax, Double_t QRaw, Double_t Q, Double_t X, Double_t Y); - ~Cluster() = default; - - Int_t getCh() const { return mChamber; } - void setCh(Int_t chamber) { mChamber = chamber; } - - Int_t getSize() const { return mSize; } - void setSize(Int_t size) { mSize = size; } - - Int_t getQRaw() const { return mQRaw; } - void setQRaw(Int_t QRaw) { mQRaw = QRaw; } - - Int_t getQ() const { return mQ; } - void setQ(Int_t Q) { mQ = Q; } - - Int_t getX() const { return mX; } - void setX(Int_t X) { mX = X; } - - Int_t getY() const { return mY; } - void setY(Int_t Y) { mY = Y; } - - protected: - Int_t mChamber; /// chamber number - Int_t mSize; /// size of the formed cluster from which this cluster deduced - Int_t mNlocMax; /// number of local maxima in formed cluster - Double_t mQRaw; /// QDC value of the raw cluster - Double_t mQ; /// QDC value of the actual cluster - Double_t mX; /// local x postion, [cm] - Double_t mY; /// local y postion, [cm] - - ClassDefNV(Cluster, 1); -}; - -} // namespace hmpid -} // namespace o2 - -#endif /* DETECTORS_HMPID_BASE_INCLUDE_HMPIDBASE_CLUSTER_H_ */ diff --git a/Detectors/HMPID/base/include/HMPIDBase/Digit.h b/Detectors/HMPID/base/include/HMPIDBase/Digit.h deleted file mode 100644 index 7fcf96a8e4527..0000000000000 --- a/Detectors/HMPID/base/include/HMPIDBase/Digit.h +++ /dev/null @@ -1,175 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// -/// \file Digit.h -/// \author Antonio Franco - INFN Bari -/// \version 1.0 -/// \date 15/02/2021 - -#ifndef DETECTORS_HMPID_BASE_INCLUDE_HMPIDBASE_DIGIT_H_ -#define DETECTORS_HMPID_BASE_INCLUDE_HMPIDBASE_DIGIT_H_ - -#include -#include "CommonDataFormat/TimeStamp.h" -#include "HMPIDBase/Hit.h" // for hit -#include "HMPIDBase/Param.h" // for param -#include "TMath.h" - -namespace o2 -{ -namespace hmpid -{ - -/// \class Digit -/// \brief HMPID Digit declaration -class Digit -{ - public: - // Coordinates Conversion Functions - static inline uint32_t Abs(int ch, int pc, int x, int y) { return ch << 20 | pc << 16 | x << 8 | y; } - static inline int DDL2C(int ddl) { return ddl >> 1; } //ddl -> chamber - static inline int A2C(uint32_t pad) { return (pad & 0x00F00000) >> 20; } //abs pad -> chamber - static inline int A2P(uint32_t pad) { return (pad & 0x000F0000) >> 16; } //abs pad -> pc - static inline int A2X(uint32_t pad) { return (pad & 0x0000FF00) >> 8; } //abs pad -> pad X - static inline int A2Y(uint32_t pad) { return (pad & 0x000000FF); } //abs pad -> pad Y - static inline uint32_t Photo2Pad(int ch, int pc, int x, int y) { return Abs(ch, pc, x, y); } - static uint32_t Equipment2Pad(int Equi, int Colu, int Dilo, int Chan); - static void Pad2Equipment(uint32_t pad, int* Equi, int* Colu, int* Dilo, int* Chan); - static void Pad2Absolute(uint32_t pad, int* Module, int* x, int* y); - static uint32_t Absolute2Pad(int Module, int x, int y); - static void Pad2Photo(uint32_t pad, int* chamber, int* photo, int* x, int* y); - static void Absolute2Equipment(int Module, int x, int y, int* Equi, int* Colu, int* Dilo, int* Chan); - static void Equipment2Absolute(int Equi, int Colu, int Dilo, int Chan, int* Module, int* x, int* y); - - // Trigger time Conversion Functions - static inline uint64_t OrbitBcToEventId(uint32_t Orbit, uint16_t BC) { return ((Orbit << 12) | (0x0FFF & BC)); }; - static inline uint32_t EventIdToOrbit(uint64_t EventId) { return (EventId >> 12); }; - static inline uint16_t EventIdToBc(uint64_t EventId) { return (EventId & 0x0FFF); }; - static double OrbitBcToTimeNs(uint32_t Orbit, uint16_t BC); - static uint32_t TimeNsToOrbit(double TimeNs); - static uint16_t TimeNsToBc(double TimeNs); - static void TimeNsToOrbitBc(double TimeNs, uint32_t& Orbit, uint16_t& Bc); - - // Operators definition ! - friend inline bool operator<(const Digit& l, const Digit& r) { return l.mPad < r.mPad; }; - friend inline bool operator==(const Digit& l, const Digit& r) { return l.mPad == r.mPad; }; - friend inline bool operator>(const Digit& l, const Digit& r) { return r < l; }; - friend inline bool operator<=(const Digit& l, const Digit& r) { return !(l > r); }; - friend inline bool operator>=(const Digit& l, const Digit& r) { return !(l < r); }; - friend inline bool operator!=(const Digit& l, const Digit& r) { return !(l == r); }; - - // Digit ASCCI format Dump := [Chamber,PhotoCathod,X,Y]@(Orbit,BunchCrossing)=Charge - friend std::ostream& operator<<(std::ostream& os, const Digit& d) - { - os << "[" << A2C(d.mPad) << "," << A2P(d.mPad) << "," << A2X(d.mPad) << "," << A2Y(d.mPad) << "]@(" << d.mOrbit << "," << d.mBc << ")=" << d.mQ; - return os; - }; - - // Functions to manage Digit Vectors - static bool eventEquipPadsComp(Digit& d1, Digit& d2); - static std::vector* extractDigitsPerEvent(std::vector& Digits, uint64_t EventID); - static std::vector* extractEvents(std::vector& Digits); - - public: - Digit() = default; - Digit(uint16_t bc, uint32_t orbit, int pad, uint16_t charge); - Digit(uint16_t bc, uint32_t orbit, int chamber, int photo, int x, int y, uint16_t charge); - Digit(uint16_t bc, uint32_t orbit, uint16_t charge, int equipment, int column, int dilogic, int channel); - Digit(uint16_t bc, uint32_t orbit, uint16_t charge, int module, int x, int y); - - // Getter & Setters - uint16_t getCharge() const { return mQ; } - void setCharge(uint16_t Q) - { - mQ = Q; - return; - }; - int getPadID() const { return mPad; } - void setPadID(uint32_t pad) - { - mPad = pad; - return; - }; - uint32_t getOrbit() const { return mOrbit; } - uint16_t getBC() const { return mBc; } - uint64_t getTriggerID() const { return OrbitBcToEventId(mOrbit, mBc); } - void setOrbit(uint32_t orbit) - { - mOrbit = orbit; - return; - } - void setBC(uint16_t bc) - { - mBc = bc; - return; - } - void setTriggerID(uint64_t trigger) - { - mOrbit = (trigger >> 12); - mBc = (trigger & 0x0FFF); - return; - } - bool isValid() { return (mPad == 0xFFFFFFFF ? true : false); }; - void setInvalid() - { - mPad = 0xFFFFFFFF; - return; - }; - - // convenience wrapper function for conversion to x-y pad coordinates - int getPx() const { return A2X(mPad); } - int getPy() const { return A2Y(mPad); } - int getPhC() const { return A2P(mPad); } - int getCh() const { return A2C(mPad); } - - // Charge management functions - static void getPadAndTotalCharge(HitType const& hit, int& chamber, int& pc, int& px, int& py, float& totalcharge); - static float getFractionalContributionForPad(HitType const& hit, int somepad); - void addCharge(float q) - { - mQ += q; - if (mQ > 0x0FFF) { - mQ = 0x0FFF; - } - } - void subCharge(float q) { mQ -= q; } - - private: - // Members - uint16_t mQ = 0; - uint16_t mBc = 0.; - uint32_t mOrbit = 0; - // The Pad Unique Id, code a pad inside one HMPID chamber. - // Bit Map : 0000.0000.cccc.pppp.xxxx.xxxx.yyyy.yyyy - // cccc := chamber [0..6] - // pppp := photo cathode [0..5] - // xxxx.xxxx := horizontal displacement [0..79] - // yyyy.yyyy := vertical displacement [0..47] - uint32_t mPad = 0; // 0xFFFFFFFF indicates invalid digit - - // Get the Geometric center of the pad - static float LorsX(int pad) { return Param::LorsX(A2P(pad), A2X(pad)); } //center of the pad x, [cm] - static float LorsY(int pad) { return Param::LorsY(A2P(pad), A2Y(pad)); } //center of the pad y, [cm] - - // determines the total charge created by a hit - // might modify the localX, localY coordiates associated to the hit - static Double_t QdcTot(Double_t e, Double_t time, Int_t pc, Int_t px, Int_t py, Double_t& localX, Double_t& localY); - static Double_t IntPartMathiX(Double_t x, Int_t pad); - static Double_t IntPartMathiY(Double_t y, Int_t pad); - static Double_t InMathieson(Double_t localX, Double_t localY, int pad); - - ClassDefNV(Digit, 2); -}; - -} // namespace hmpid -} // namespace o2 - -#endif /* DETECTORS_HMPID_BASE_INCLUDE_HMPIDBASE_DIGIT_H_ */ diff --git a/Detectors/HMPID/base/include/HMPIDBase/Param.h b/Detectors/HMPID/base/include/HMPIDBase/Param.h index b49e753b778e7..2321aa58641f3 100644 --- a/Detectors/HMPID/base/include/HMPIDBase/Param.h +++ b/Detectors/HMPID/base/include/HMPIDBase/Param.h @@ -41,10 +41,10 @@ class Param } } - void Print(Option_t* opt = "") const; //print current parametrization + void print(Option_t* opt = "") const; //print current parametrization - static Param* Instance(); //pointer to Param singleton - static inline Param* InstanceNoGeo(); //pointer to Param singleton without geometry.root for MOOD, displays, ... + static Param* instance(); //pointer to Param singleton + static inline Param* instanceNoGeo(); //pointer to Param singleton without geometry.root for MOOD, displays, ... //geo info enum EChamberData { kMinCh = 0, kMaxCh = 6, @@ -66,127 +66,111 @@ class Param kPadSigmaMasked = 20 }; //One can go up to 5 sigma cut, overflow is protected in AliHMPIDCalib static float r2d() { return 57.2957795; } - static float SizePadX() { return fgCellX; } //pad size x, [cm] - static float SizePadY() { return fgCellY; } //pad size y, [cm] - - static float SizePcX() { return fgPcX; } // PC size x - static float SizePcY() { return fgPcY; } // PC size y - static float MaxPcX(Int_t iPc) { return fgkMaxPcX[iPc]; } // PC limits - static float MaxPcY(Int_t iPc) { return fgkMaxPcY[iPc]; } // PC limits - static float MinPcX(Int_t iPc) { return fgkMinPcX[iPc]; } // PC limits - static float MinPcY(Int_t iPc) { return fgkMinPcY[iPc]; } // PC limits - static Int_t Nsig() { return fgNSigmas; } //Getter n. sigmas for noise - static float SizeAllX() { return fgAllX; } //all PCs size x, [cm] - static float SizeAllY() { return fgAllY; } //all PCs size y, [cm] + static float sizePadX() { return fgCellX; } //pad size x, [cm] + static float sizePadY() { return fgCellY; } //pad size y, [cm] + + static float sizePcX() { return fgPcX; } // PC size x + static float sizePcY() { return fgPcY; } // PC size y + static float maxPcX(Int_t iPc) { return fgkMaxPcX[iPc]; } // PC limits + static float maxPcY(Int_t iPc) { return fgkMaxPcY[iPc]; } // PC limits + static float minPcX(Int_t iPc) { return fgkMinPcX[iPc]; } // PC limits + static float minPcY(Int_t iPc) { return fgkMinPcY[iPc]; } // PC limits + static Int_t nsig() { return fgNSigmas; } //Getter n. sigmas for noise + static float sizeAllX() { return fgAllX; } //all PCs size x, [cm] + static float sizeAllY() { return fgAllY; } //all PCs size y, [cm] //center of the pad x, [cm] - static float LorsX(Int_t pc, int padx) { return (padx + 0.5) * SizePadX() + fgkMinPcX[pc]; } + static float lorsX(Int_t pc, Int_t padx) { return (padx + 0.5) * sizePadX() + fgkMinPcX[pc]; } //center of the pad y, [cm] - static float LorsY(Int_t pc, int pady) { return (pady + 0.5) * SizePadY() + fgkMinPcY[pc]; } + static float lorsY(Int_t pc, Int_t pady) { return (pady + 0.5) * sizePadY() + fgkMinPcY[pc]; } //PhiMin (degree) of the camber ch - float ChPhiMin(Int_t ch) { return Lors2Mars(ch, LorsX(ch, kMinPx) - mX, LorsY(ch, kMinPy) - mY).Phi() * r2d(); } + float chPhiMin(Int_t ch) { return lors2Mars(ch, lorsX(ch, kMinPx) - mX, lorsY(ch, kMinPy) - mY).Phi() * r2d(); } //ThMin (degree) of the camber ch - float ChThMin(Int_t ch) { return Lors2Mars(ch, LorsX(ch, kMinPx) - mX, LorsY(ch, kMinPy) - mY).Theta() * r2d(); } + float chThMin(Int_t ch) { return lors2Mars(ch, lorsX(ch, kMinPx) - mX, lorsY(ch, kMinPy) - mY).Theta() * r2d(); } //PhiMax (degree) of the camber ch - float ChPhiMax(Int_t ch) { return Lors2Mars(ch, LorsX(ch, kMaxPcx) - mX, LorsY(ch, kMaxPcy) - mY).Phi() * r2d(); } + float chPhiMax(Int_t ch) { return lors2Mars(ch, lorsX(ch, kMaxPcx) - mX, lorsY(ch, kMaxPcy) - mY).Phi() * r2d(); } //ThMax (degree) of the camber ch - float ChThMax(Int_t ch) { return Lors2Mars(ch, LorsX(ch, kMaxPcx) - mX, LorsY(ch, kMaxPcy) - mY).Theta() * r2d(); } + float chThMax(Int_t ch) { return lors2Mars(ch, lorsX(ch, kMaxPcx) - mX, lorsY(ch, kMaxPcy) - mY).Theta() * r2d(); } - static void Lors2Pad(float x, float y, Int_t& pc, Int_t& px, Int_t& py); //(x,y)->(pc,px,py) + static void lors2Pad(float x, float y, Int_t& pc, Int_t& px, Int_t& py); //(x,y)->(pc,px,py) - //(ch,pc,padx,pady)-> abs pad - // static Int_t Abs(Int_t ch, Int_t pc, Int_t x, Int_t y) { return ch * 100000000 + pc * 1000000 + x * 1000 + y; } - // static Int_t DDL2C(Int_t ddl) { return ddl / 2; } //ddl -> chamber - // static Int_t A2C(Int_t pad) { return pad / 100000000; } //abs pad -> chamber - // static Int_t A2P(Int_t pad) { return pad % 100000000 / 1000000; } //abs pad -> pc - // static Int_t A2X(Int_t pad) { return pad % 1000000 / 1000; } //abs pad -> pad X - // static Int_t A2Y(Int_t pad) { return pad % 1000; } //abs pad -> pad Y + static bool isOverTh(float q) { return q >= fgThreshold; } //is digit over threshold? - // Moved in Digit.h - static Int_t Abs(Int_t ch, Int_t pc, Int_t x, Int_t y) { return ch << 20 | pc << 16 | x << 8 | y; } - static Int_t DDL2C(Int_t ddl) { return ddl >> 1; } //ddl -> chamber - static Int_t A2C(Int_t pad) { return (pad & 0x00F00000) >> 20; } //abs pad -> chamber - static Int_t A2P(Int_t pad) { return (pad & 0x000F0000) >> 16; } //abs pad -> pc - static Int_t A2X(Int_t pad) { return (pad & 0x0000FF00) >> 8; } //abs pad -> pad X - static Int_t A2Y(Int_t pad) { return (pad & 0x000000FF); } //abs pad -> pad Y + bool getInstType() const { return fgInstanceType; } //return if the instance is from geom or ideal - static bool IsOverTh(float q) { return q >= fgThreshold; } //is digit over threshold? + inline static bool isInDead(float x, float y); //is the point in dead area? + inline static bool isDeadPad(Int_t padx, Int_t pady, Int_t ch); //is a dead pad? - bool GetInstType() const { return fgInstanceType; } //return if the instance is from geom or ideal + inline void setChStatus(Int_t ch, bool status = kTRUE); + inline void setSectStatus(Int_t ch, Int_t sect, bool status); + inline void setPcStatus(Int_t ch, Int_t pc, bool status); + inline void printChStatus(Int_t ch); + inline void setGeomAccept(); - inline static bool IsInDead(float x, float y); //is the point in dead area? - inline static bool IsDeadPad(Int_t padx, Int_t pady, Int_t ch); //is a dead pad? - - inline void SetChStatus(Int_t ch, bool status = kTRUE); - inline void SetSectStatus(Int_t ch, Int_t sect, bool status); - inline void SetPcStatus(Int_t ch, Int_t pc, bool status); - inline void PrintChStatus(Int_t ch); - inline void SetGeomAccept(); - - static Int_t InHVSector(float y); //find HV sector - static Int_t Radiator(float y) + static Int_t inHVSector(float y); //find HV sector + static Int_t radiator(float y) { - if (InHVSector(y) < 0) { + if (inHVSector(y) < 0) { return -1; } - return InHVSector(y) / 2; + return inHVSector(y) / 2; } // height in the radiator to estimate temperature from gradient - static double HinRad(float y) + static double hinRad(float y) { - if (Radiator(y) < 0) { + if (radiator(y) < 0) { return -1; } - return y - Radiator(y) * fgkMinPcY[Radiator(y)]; + return y - radiator(y) * fgkMinPcY[radiator(y)]; } //is point inside chamber boundaries? - static bool IsInside(float x, float y, float d = 0) + static bool isInside(float x, float y, float d = 0) { return x > -d && y > -d && x < fgkMaxPcX[kMaxPc] + d && y < fgkMaxPcY[kMaxPc] + d; } //For optical properties - static double EPhotMin() { return 5.5; } // - static double EPhotMax() { return 8.5; } //Photon energy range,[eV] - static double NIdxRad(double eV, double temp) + static double ePhotMin() { return 5.5; } // + static double ePhotMax() { return 8.5; } //Photon energy range,[eV] + static double nIdxRad(double eV, double temp) { return TMath::Sqrt(1 + 0.554 * (1239.84 / eV) * (1239.84 / eV) / ((1239.84 / eV) * (1239.84 / eV) - 5769)) - 0.0005 * (temp - 20); } - static double NIdxWin(double eV) { return TMath::Sqrt(1 + 46.411 / (10.666 * 10.666 - eV * eV) + 228.71 / (18.125 * 18.125 - eV * eV)); } - static double NMgF2Idx(double eV) { return 1.7744 - 2.866e-3 * (1239.842609 / eV) + 5.5564e-6 * (1239.842609 / eV) * (1239.842609 / eV); } // MgF2 idx of trasparency system - static double NIdxGap(double eV) { return 1 + 0.12489e-6 / (2.62e-4 - eV * eV / 1239.84 / 1239.84); } - static double LAbsRad(double eV) { return (eV < 7.8) * (GausPar(eV, 3.20491e16, -0.00917890, 0.742402) + GausPar(eV, 3035.37, 4.81171, 0.626309)) + (eV >= 7.8) * 0.0001; } - static double LAbsWin(double eV) { return (eV < 8.2) * (818.8638 - 301.0436 * eV + 36.89642 * eV * eV - 1.507555 * eV * eV * eV) + (eV >= 8.2) * 0.0001; } //fit from DiMauro data 28.10.03 - static double LAbsGap(double eV) { return (eV < 7.75) * 6512.399 + (eV >= 7.75) * 3.90743e-2 / (-1.655279e-1 + 6.307392e-2 * eV - 8.011441e-3 * eV * eV + 3.392126e-4 * eV * eV * eV); } - static double QEffCSI(double eV) { return (eV > 6.07267) * 0.344811 * (1 - exp(-1.29730 * (eV - 6.07267))); } //fit from DiMauro data 28.10.03 - static double GausPar(double x, double a1, double a2, double a3) { return a1 * TMath::Exp(-0.5 * ((x - a2) / a3) * ((x - a2) / a3)); } + static double nIdxWin(double eV) { return TMath::Sqrt(1 + 46.411 / (10.666 * 10.666 - eV * eV) + 228.71 / (18.125 * 18.125 - eV * eV)); } + static double nMgF2Idx(double eV) { return 1.7744 - 2.866e-3 * (1239.842609 / eV) + 5.5564e-6 * (1239.842609 / eV) * (1239.842609 / eV); } // MgF2 idx of trasparency system + static double nIdxGap(double eV) { return 1 + 0.12489e-6 / (2.62e-4 - eV * eV / 1239.84 / 1239.84); } + static double lAbsRad(double eV) { return (eV < 7.8) * (gausPar(eV, 3.20491e16, -0.00917890, 0.742402) + gausPar(eV, 3035.37, 4.81171, 0.626309)) + (eV >= 7.8) * 0.0001; } + static double lAbsWin(double eV) { return (eV < 8.2) * (818.8638 - 301.0436 * eV + 36.89642 * eV * eV - 1.507555 * eV * eV * eV) + (eV >= 8.2) * 0.0001; } //fit from DiMauro data 28.10.03 + static double lAbsGap(double eV) { return (eV < 7.75) * 6512.399 + (eV >= 7.75) * 3.90743e-2 / (-1.655279e-1 + 6.307392e-2 * eV - 8.011441e-3 * eV * eV + 3.392126e-4 * eV * eV * eV); } + static double qEffCSI(double eV) { return (eV > 6.07267) * 0.344811 * (1 - exp(-1.29730 * (eV - 6.07267))); } //fit from DiMauro data 28.10.03 + static double gausPar(double x, double a1, double a2, double a3) { return a1 * TMath::Exp(-0.5 * ((x - a2) / a3) * ((x - a2) / a3)); } //find the temperature of the C6F14 in a given point with coord. y (in x is uniform) - inline static double FindTemp(double tLow, double tUp, double y); + inline static double findTemp(double tLow, double tUp, double y); - double GetEPhotMean() const { return mPhotEMean; } - double GetRefIdx() const { return mRefIdx; } //running refractive index + double getEPhotMean() const { return mPhotEMean; } + double getRefIdx() const { return mRefIdx; } //running refractive index - double MeanIdxRad() const { return NIdxRad(mPhotEMean, mTemp); } - double MeanIdxWin() const { return NIdxWin(mPhotEMean); } + double meanIdxRad() const { return nIdxRad(mPhotEMean, mTemp); } + double meanIdxWin() const { return nIdxWin(mPhotEMean); } // - float DistCut() const { return 1.0; } //<--TEMPORAR--> to be removed in future. Cut for MIP-TRACK residual - float QCut() const { return 100; } //<--TEMPORAR--> to be removed in future. Separation PHOTON-MIP charge - float MultCut() const { return 30; } //<--TEMPORAR--> to be removed in future. Multiplicity cut to activate WEIGHT procedure - - double RadThick() const { return 1.5; } //<--TEMPORAR--> to be removed in future. Radiator thickness - double WinThick() const { return 0.5; } //<--TEMPORAR--> to be removed in future. Window thickness - double GapThick() const { return 8.0; } //<--TEMPORAR--> to be removed in future. Proximity gap thickness - double WinIdx() const { return 1.5787; } //<--TEMPORAR--> to be removed in future. Mean refractive index of WIN material (SiO2) - double GapIdx() const { return 1.0005; } //<--TEMPORAR--> to be removed in future. Mean refractive index of GAP material (CH4) - - static Int_t Stack(Int_t evt = -1, Int_t tid = -1); //Print stack info for event and tid - static Int_t StackCount(Int_t pid, Int_t evt); //Counts stack particles of given sort in given event - static void IdealPosition(Int_t iCh, TGeoHMatrix* m); //ideal position of given chamber + float distCut() const { return 1.0; } //<--TEMPORAR--> to be removed in future. Cut for MIP-TRACK residual + float qCut() const { return 100; } //<--TEMPORAR--> to be removed in future. Separation PHOTON-MIP charge + float multCut() const { return 30; } //<--TEMPORAR--> to be removed in future. Multiplicity cut to activate WEIGHT procedure + + double radThick() const { return 1.5; } //<--TEMPORAR--> to be removed in future. Radiator thickness + double winThick() const { return 0.5; } //<--TEMPORAR--> to be removed in future. Window thickness + double gapThick() const { return 8.0; } //<--TEMPORAR--> to be removed in future. Proximity gap thickness + double winIdx() const { return 1.5787; } //<--TEMPORAR--> to be removed in future. Mean refractive index of WIN material (SiO2) + double gapIdx() const { return 1.0005; } //<--TEMPORAR--> to be removed in future. Mean refractive index of GAP material (CH4) + + static Int_t stack(Int_t evt = -1, Int_t tid = -1); //Print stack info for event and tid + static Int_t stackCount(Int_t pid, Int_t evt); //Counts stack particles of given sort in given event + static void idealPosition(Int_t iCh, TGeoHMatrix* m); //ideal position of given chamber //trasformation methodes - void Lors2Mars(Int_t c, double x, double y, double* m, Int_t pl = kPc) const + void lors2Mars(Int_t c, double x, double y, double* m, Int_t pl = kPc) const { double z = 0; switch (pl) { @@ -203,20 +187,20 @@ class Param double l[3] = {x - mX, y - mY, z}; mM[c]->LocalToMaster(l, m); } - TVector3 Lors2Mars(Int_t c, double x, double y, Int_t pl = kPc) const + TVector3 lors2Mars(Int_t c, double x, double y, Int_t pl = kPc) const { double m[3]; - Lors2Mars(c, x, y, m, pl); + lors2Mars(c, x, y, m, pl); return TVector3(m); } //MRS->LRS - void Mars2Lors(Int_t c, double* m, double& x, double& y) const + void mars2Lors(Int_t c, double* m, double& x, double& y) const { double l[3]; mM[c]->MasterToLocal(m, l); x = l[0] + mX; y = l[1] + mY; } //MRS->LRS - void Mars2LorsVec(Int_t c, double* m, double& th, double& ph) const + void mars2LorsVec(Int_t c, double* m, double& th, double& ph) const { double l[3]; mM[c]->MasterToLocalVect(m, l); @@ -224,47 +208,47 @@ class Param th = TMath::ATan(pt / l[2]); ph = TMath::ATan2(l[1], l[0]); } - void Lors2MarsVec(Int_t c, double* m, double* l) const { mM[c]->LocalToMasterVect(m, l); } //LRS->MRS - TVector3 Norm(Int_t c) const + void lors2MarsVec(Int_t c, double* m, double* l) const { mM[c]->LocalToMasterVect(m, l); } //LRS->MRS + TVector3 norm(Int_t c) const { double n[3]; - Norm(c, n); + norm(c, n); return TVector3(n); } //norm - void Norm(Int_t c, double* n) const + void norm(Int_t c, double* n) const { double l[3] = {0, 0, 1}; mM[c]->LocalToMasterVect(l, n); } //norm - void Point(Int_t c, double* p, Int_t plane) const { Lors2Mars(c, 0, 0, p, plane); } //point of given chamber plane + void point(Int_t c, double* p, Int_t plane) const { lors2Mars(c, 0, 0, p, plane); } //point of given chamber plane - void SetTemp(double temp) { mTemp = temp; } //set actual temperature of the C6F14 - void SetEPhotMean(double ePhotMean) { mPhotEMean = ePhotMean; } //set mean photon energy + void setTemp(double temp) { mTemp = temp; } //set actual temperature of the C6F14 + void setEPhotMean(double ePhotMean) { mPhotEMean = ePhotMean; } //set mean photon energy - void SetRefIdx(double refRadIdx) { mRefIdx = refRadIdx; } //set running refractive index + void setRefIdx(double refRadIdx) { mRefIdx = refRadIdx; } //set running refractive index - void SetNSigmas(Int_t sigmas) { fgNSigmas = sigmas; } //set sigma cut - void SetThreshold(Int_t thres) { fgThreshold = thres; } //set sigma cut - void SetInstanceType(bool inst) { fgInstanceType = inst; } //kTRUE if from geomatry kFALSE if from ideal geometry + void setNSigmas(Int_t sigmas) { fgNSigmas = sigmas; } //set sigma cut + void setThreshold(Int_t thres) { fgThreshold = thres; } //set sigma cut + void setInstanceType(bool inst) { fgInstanceType = inst; } //kTRUE if from geomatry kFALSE if from ideal geometry //For PID - double SigLoc(double trkTheta, double trkPhi, double ckovTh, double ckovPh, double beta); //error due to cathode segmetation - double SigGeom(double trkTheta, double trkPhi, double ckovTh, double ckovPh, double beta); //error due to unknown photon origin - double SigCrom(double trkTheta, double trkPhi, double ckovTh, double ckovPh, double beta); //error due to unknonw photon energy - double Sigma2(double trkTheta, double trkPhi, double ckovTh, double ckovPh); //photon candidate sigma^2 + double sigLoc(double trkTheta, double trkPhi, double ckovTh, double ckovPh, double beta); //error due to cathode segmetation + double sigGeom(double trkTheta, double trkPhi, double ckovTh, double ckovPh, double beta); //error due to unknown photon origin + double sigCrom(double trkTheta, double trkPhi, double ckovTh, double ckovPh, double beta); //error due to unknonw photon energy + double sigma2(double trkTheta, double trkPhi, double ckovTh, double ckovPh); //photon candidate sigma^2 - static double SigmaCorrFact(Int_t iPart, double occupancy); //correction factor for theoretical resolution + static double sigmaCorrFact(Int_t iPart, double occupancy); //correction factor for theoretical resolution //Mathieson Getters - static double PitchAnodeCathode() { return fgkD; } - static double SqrtK3x() { return fgkSqrtK3x; } - static double K2x() { return fgkK2x; } - static double K1x() { return fgkK1x; } - static double K4x() { return fgkK4x; } - static double SqrtK3y() { return fgkSqrtK3y; } - static double K2y() { return fgkK2y; } - static double K1y() { return fgkK1y; } - static double K4y() { return fgkK4y; } + static double pitchAnodeCathode() { return fgkD; } + static double sqrtK3x() { return fgkSqrtK3x; } + static double k2x() { return fgkK2x; } + static double k1x() { return fgkK1x; } + static double k4x() { return fgkK4x; } + static double sqrtK3y() { return fgkSqrtK3y; } + static double k2y() { return fgkK2y; } + static double k1y() { return fgkK1y; } + static double k4y() { return fgkK4y; } // enum EPlaneId { kPc, kRad, diff --git a/Detectors/HMPID/base/include/HMPIDBase/Trigger.h b/Detectors/HMPID/base/include/HMPIDBase/Trigger.h deleted file mode 100644 index 1515b3b3be161..0000000000000 --- a/Detectors/HMPID/base/include/HMPIDBase/Trigger.h +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// -/// \file Trigger.h -/// \author Antonio Franco - INFN Bari -/// \version 1.0 -/// \date 2/03/2021 - -#ifndef DETECTORS_HMPID_BASE_INCLUDE_HMPIDBASE_TRIGGER_H_ -#define DETECTORS_HMPID_BASE_INCLUDE_HMPIDBASE_TRIGGER_H_ - -#include -#include "TMath.h" -#include "CommonDataFormat/TimeStamp.h" -#include "CommonConstants/LHCConstants.h" - -namespace o2 -{ -namespace hmpid -{ - -/// \class Trigger -/// \brief HMPID Trigger declaration -class Trigger -{ - public: - // Trigger time Conversion Functions - static inline uint64_t OrbitBcToEventId(uint32_t Orbit, uint16_t BC) { return ((Orbit << 12) | (0x0FFF & BC)); }; - static inline uint32_t EventIdToOrbit(uint64_t EventId) { return (EventId >> 12); }; - static inline uint16_t EventIdToBc(uint64_t EventId) { return (EventId & 0x0FFF); }; - static double OrbitBcToTimeNs(uint32_t Orbit, uint16_t BC) { return (BC * o2::constants::lhc::LHCBunchSpacingNS + Orbit * o2::constants::lhc::LHCOrbitNS); }; - static uint32_t TimeNsToOrbit(double TimeNs) { return (uint32_t)(TimeNs / o2::constants::lhc::LHCOrbitNS); }; - static uint16_t TimeNsToBc(double TimeNs) { return (uint16_t)(std::fmod(TimeNs, o2::constants::lhc::LHCOrbitNS) / o2::constants::lhc::LHCBunchSpacingNS); }; - static void TimeNsToOrbitBc(double TimeNs, uint32_t& Orbit, uint16_t& Bc) - { - Orbit = TimeNsToOrbit(TimeNs); - Bc = TimeNsToBc(TimeNs); - return; - }; - - // Operators definition ! - friend inline bool operator<(const Trigger& l, const Trigger& r) { return OrbitBcToEventId(l.mOrbit, l.mBc) < OrbitBcToEventId(r.mOrbit, r.mBc); }; - friend inline bool operator==(const Trigger& l, const Trigger& r) { return OrbitBcToEventId(l.mOrbit, l.mBc) == OrbitBcToEventId(r.mOrbit, r.mBc); }; - friend inline bool operator>(const Trigger& l, const Trigger& r) { return r < l; }; - friend inline bool operator<=(const Trigger& l, const Trigger& r) { return !(l > r); }; - friend inline bool operator>=(const Trigger& l, const Trigger& r) { return !(l < r); }; - friend inline bool operator!=(const Trigger& l, const Trigger& r) { return !(l == r); }; - - // Digit ASCII format (Orbit,BunchCrossing)[LHC Time nSec] - friend std::ostream& operator<<(std::ostream& os, const Trigger& d) - { - os << "(" << d.mOrbit << "," << d.mBc << ")[" << OrbitBcToTimeNs(d.mOrbit, d.mBc) << " ns]"; - return os; - }; - - public: - Trigger() = default; - Trigger(uint16_t bc, uint32_t orbit) - { - mBc = bc; - mOrbit = orbit; - }; - uint32_t getOrbit() const { return mOrbit; } - uint16_t getBc() const { return mBc; } - uint64_t getTriggerID() const { return OrbitBcToEventId(mOrbit, mBc); } - void setOrbit(uint32_t orbit) - { - mOrbit = orbit; - return; - } - void setBC(uint16_t bc) - { - mBc = bc; - return; - } - void setTriggerID(uint64_t trigger) - { - mOrbit = (trigger >> 12); - mBc = (trigger & 0x0FFF); - return; - } - - private: - // Members - uint16_t mBc = 0.; - uint32_t mOrbit = 0; - - ClassDefNV(Trigger, 2); -}; - -} // namespace hmpid -} // namespace o2 - -#endif /* DETECTORS_HMPID_BASE_INCLUDE_HMPIDBASE_TRIGGER_H_ */ diff --git a/Detectors/HMPID/base/src/HMPIDBaseLinkDef.h b/Detectors/HMPID/base/src/HMPIDBaseLinkDef.h index 462c67964ceed..35839105de08e 100644 --- a/Detectors/HMPID/base/src/HMPIDBaseLinkDef.h +++ b/Detectors/HMPID/base/src/HMPIDBaseLinkDef.h @@ -14,15 +14,7 @@ #pragma link off all classes; #pragma link off all functions; -#pragma link C++ class o2::hmpid::Cluster + ; -#pragma link C++ class vector < o2::hmpid::Cluster> + ; #pragma link C++ class o2::hmpid::Param + ; -#pragma link C++ class o2::hmpid::Digit + ; -#pragma link C++ class vector < o2::hmpid::Digit> + ; -#pragma link C++ class o2::hmpid::HitType + ; -#pragma link C++ class vector < o2::hmpid::HitType> + ; #pragma link C++ class o2::hmpid::Geo + ; -#pragma link C++ class o2::hmpid::Trigger + ; -#pragma link C++ class vector < o2::hmpid::Trigger> + ; #endif diff --git a/Detectors/HMPID/base/src/Param.cxx b/Detectors/HMPID/base/src/Param.cxx index 9358bc480e691..01b04e640f27b 100644 --- a/Detectors/HMPID/base/src/Param.cxx +++ b/Detectors/HMPID/base/src/Param.cxx @@ -89,7 +89,7 @@ Param::Param(bool noGeo) : mX(0), mY(0), mRefIdx(1.28947), mPhotEMean(6.675), mT } } */ - mRefIdx = MeanIdxRad(); //initialization of the running ref. index of freon + mRefIdx = meanIdxRad(); //initialization of the running ref. index of freon float dead = 2.6; // cm of the dead zones between PCs-> See 2CRC2099P1 @@ -141,8 +141,8 @@ Param::Param(bool noGeo) : mX(0), mY(0), mRefIdx(1.28947), mPhotEMean(6.675), mT fgkMaxPcY[4] = fgAllY; fgkMaxPcY[5] = fgkMaxPcY[4]; - mX = 0.5 * SizeAllX(); - mY = 0.5 * SizeAllY(); + mX = 0.5 * sizeAllX(); + mY = 0.5 * sizeAllY(); for (Int_t ich = kMinCh; ich <= kMaxCh; ich++) { for (Int_t padx = 0; padx < 160; padx++) { @@ -158,25 +158,25 @@ Param::Param(bool noGeo) : mX(0), mY(0), mRefIdx(1.28947), mPhotEMean(6.675), mT if (!pne) { //AliErrorClass(Form("The symbolic volume %s does not correspond to any physical entry!",Form("HMPID_%i",i))); mM[i] = new TGeoHMatrix; - IdealPosition(i, mM[i]); + idealPosition(i, mM[i]); } else { TGeoPhysicalNode* pnode = pne->GetPhysicalNode(); if (pnode) { mM[i] = new TGeoHMatrix(*(pnode->GetMatrix())); } else { mM[i] = new TGeoHMatrix; - IdealPosition(i, mM[i]); + idealPosition(i, mM[i]); } } } else { mM[i] = new TGeoHMatrix; - IdealPosition(i, mM[i]); + idealPosition(i, mM[i]); } } fgInstance = this; } //ctor //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void Param::Print(Option_t* opt) const +void Param::print(Option_t* opt) const { // print some usefull (hopefully) info on some internal guts of HMPID parametrisation @@ -185,7 +185,7 @@ void Param::Print(Option_t* opt) const } } //Print() //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void Param::IdealPosition(Int_t iCh, TGeoHMatrix* pMatrix) +void Param::idealPosition(Int_t iCh, TGeoHMatrix* pMatrix) { // Construct ideal position matrix for a given chamber // Arguments: iCh- chamber ID; pMatrix- pointer to precreated unity matrix where to store the results @@ -275,7 +275,7 @@ void Param::IdealPosition(Int_t iCh, TGeoHMatrix* pMatrix) return iCnt; }*/ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -double Param::Sigma2(double trkTheta, double trkPhi, double ckovTh, double ckovPh) +double Param::sigma2(double trkTheta, double trkPhi, double ckovTh, double ckovPh) { // Analithical calculation of total error (as a sum of localization, geometrical and chromatic errors) // on Cerenkov angle for a given Cerenkov photon @@ -286,7 +286,7 @@ double Param::Sigma2(double trkTheta, double trkPhi, double ckovTh, double ckovP // Returns: absolute error on Cerenkov angle, [radians] TVector3 v(-999, -999, -999); - double trkBeta = 1. / (TMath::Cos(ckovTh) * GetRefIdx()); + double trkBeta = 1. / (TMath::Cos(ckovTh) * getRefIdx()); if (trkBeta > 1) { trkBeta = 1; //protection against bad measured thetaCer @@ -295,14 +295,14 @@ double Param::Sigma2(double trkTheta, double trkPhi, double ckovTh, double ckovP trkBeta = 0.0001; // } - v.SetX(SigLoc(trkTheta, trkPhi, ckovTh, ckovPh, trkBeta)); - v.SetY(SigGeom(trkTheta, trkPhi, ckovTh, ckovPh, trkBeta)); - v.SetZ(SigCrom(trkTheta, trkPhi, ckovTh, ckovPh, trkBeta)); + v.SetX(sigLoc(trkTheta, trkPhi, ckovTh, ckovPh, trkBeta)); + v.SetY(sigGeom(trkTheta, trkPhi, ckovTh, ckovPh, trkBeta)); + v.SetZ(sigCrom(trkTheta, trkPhi, ckovTh, ckovPh, trkBeta)); return v.Mag2(); } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -double Param::SigLoc(double trkTheta, double trkPhi, double thetaC, double phiC, double betaM) +double Param::sigLoc(double trkTheta, double trkPhi, double thetaC, double phiC, double betaM) { // Analitical calculation of localization error (due to finite segmentation of PC) on Cerenkov angle for a given // Cerenkov photon @@ -323,14 +323,14 @@ double Param::SigLoc(double trkTheta, double trkPhi, double thetaC, double phiC, double tantheta = TMath::Tan(thetaC); double alpha = cost - tantheta * cosfd * sint; // formula (11) - double k = 1. - GetRefIdx() * GetRefIdx() + alpha * alpha / (betaM * betaM); // formula (after 8 in the text) + double k = 1. - getRefIdx() * getRefIdx() + alpha * alpha / (betaM * betaM); // formula (after 8 in the text) if (k < 0) { return 1e10; } double mu = sint * sinf + tantheta * (cost * cosfd * sinf + sinfd * cosf); // formula (10) double e = sint * cosf + tantheta * (cost * cosfd * cosf - sinfd * sinf); // formula (9) - double kk = betaM * TMath::Sqrt(k) / (GapThick() * alpha); // formula (6) and (7) + double kk = betaM * TMath::Sqrt(k) / (gapThick() * alpha); // formula (6) and (7) // formula (6) double dtdxc = kk * (k * (cosfd * cosf - cost * sinfd * sinf) - (alpha * mu / (betaM * betaM)) * sint * sinfd); // formula (7) pag.4 @@ -340,7 +340,7 @@ double Param::SigLoc(double trkTheta, double trkPhi, double thetaC, double phiC, return TMath::Sqrt(errX * errX * dtdxc * dtdxc + errY * errY * dtdyc * dtdyc); } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -double Param::SigCrom(double trkTheta, double trkPhi, double thetaC, double phiC, double betaM) +double Param::sigCrom(double trkTheta, double trkPhi, double thetaC, double phiC, double betaM) { // Analitical calculation of chromatic error (due to lack of knowledge of Cerenkov photon energy) // on Cerenkov angle for a given Cerenkov photon @@ -358,7 +358,7 @@ double Param::SigCrom(double trkTheta, double trkPhi, double thetaC, double phiC double tantheta = TMath::Tan(thetaC); double alpha = cost - tantheta * cosfd * sint; // formula (11) - double dtdn = cost * GetRefIdx() * betaM * betaM / (alpha * tantheta); // formula (12) + double dtdn = cost * getRefIdx() * betaM * betaM / (alpha * tantheta); // formula (12) // double f = 0.00928*(7.75-5.635)/TMath::Sqrt(12.); double f = 0.0172 * (7.75 - 5.635) / TMath::Sqrt(24.); @@ -366,7 +366,7 @@ double Param::SigCrom(double trkTheta, double trkPhi, double thetaC, double phiC return f * dtdn; } //SigCrom() //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -double Param::SigGeom(double trkTheta, double trkPhi, double thetaC, double phiC, double betaM) +double Param::sigGeom(double trkTheta, double trkPhi, double thetaC, double phiC, double betaM) { // Analitical calculation of geometric error (due to lack of knowledge of creation point in radiator) // on Cerenkov angle for a given Cerenkov photon @@ -387,25 +387,25 @@ double Param::SigGeom(double trkTheta, double trkPhi, double thetaC, double phiC double alpha = cost - tantheta * cosfd * sint; // formula (11) - double k = 1. - GetRefIdx() * GetRefIdx() + alpha * alpha / (betaM * betaM); // formula (after 8 in the text) + double k = 1. - getRefIdx() * getRefIdx() + alpha * alpha / (betaM * betaM); // formula (after 8 in the text) if (k < 0) { return 1e10; } - double eTr = 0.5 * RadThick() * betaM * TMath::Sqrt(k) / (GapThick() * alpha); // formula (14) + double eTr = 0.5 * radThick() * betaM * TMath::Sqrt(k) / (gapThick() * alpha); // formula (14) double lambda = (1. - sint * sinf) * (1. + sint * sinf); // formula (15) double c1 = 1. / (1. + eTr * k / (alpha * alpha * costheta * costheta)); // formula (13.a) - double c2 = betaM * TMath::Power(k, 1.5) * tantheta * lambda / (GapThick() * alpha * alpha); // formula (13.b) + double c2 = betaM * TMath::Power(k, 1.5) * tantheta * lambda / (gapThick() * alpha * alpha); // formula (13.b) double c3 = (1. + eTr * k * betaM * betaM) / ((1 + eTr) * alpha * alpha); // formula (13.c) - double c4 = TMath::Sqrt(k) * tantheta * (1 - lambda) / (GapThick() * betaM); // formula (13.d) + double c4 = TMath::Sqrt(k) * tantheta * (1 - lambda) / (gapThick() * betaM); // formula (13.d) double dtdT = c1 * (c2 + c3 * c4); - double trErr = RadThick() / (TMath::Sqrt(12.) * cost); + double trErr = radThick() / (TMath::Sqrt(12.) * cost); return trErr * dtdT; } //SigGeom() //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -double Param::SigmaCorrFact(Int_t iPart, double occupancy) +double Param::sigmaCorrFact(Int_t iPart, double occupancy) { double corr = 1.0; @@ -430,7 +430,7 @@ double Param::SigmaCorrFact(Int_t iPart, double occupancy) return corr; } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -Param* Param::Instance() +Param* Param::instance() { // Return pointer to the AliHMPIDParam singleton. // Arguments: none @@ -442,7 +442,7 @@ Param* Param::Instance() } //Instance() //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -Param* Param::InstanceNoGeo() +Param* Param::instanceNoGeo() { // Return pointer to the AliHMPIDParam singleton without the geometry.root. // Arguments: none @@ -453,7 +453,7 @@ Param* Param::InstanceNoGeo() return fgInstance; } //Instance() //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -bool Param::IsInDead(float x, float y) +bool Param::isInDead(float x, float y) { // Check is the current point is outside of sensitive area or in dead zones // Arguments: x,y -position @@ -467,7 +467,7 @@ bool Param::IsInDead(float x, float y) return kTRUE; } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -bool Param::IsDeadPad(Int_t padx, Int_t pady, Int_t ch) +bool Param::isDeadPad(Int_t padx, Int_t pady, Int_t ch) { // Check is the current pad is active or not // Arguments: padx,pady pad integer coord @@ -480,7 +480,7 @@ bool Param::IsDeadPad(Int_t padx, Int_t pady, Int_t ch) return kTRUE; } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void Param::Lors2Pad(float x, float y, Int_t& pc, Int_t& px, Int_t& py) +void Param::lors2Pad(float x, float y, Int_t& pc, Int_t& px, Int_t& py) { // Check the pad of given position // Arguments: x,y- position [cm] in LORS; pc,px,py- pad where to store the result @@ -488,32 +488,32 @@ void Param::Lors2Pad(float x, float y, Int_t& pc, Int_t& px, Int_t& py) pc = px = py = -1; if (x > fgkMinPcX[0] && x < fgkMaxPcX[0]) { pc = 0; - px = Int_t(x / SizePadX()); + px = Int_t(x / sizePadX()); } //PC 0 or 2 or 4 else if (x > fgkMinPcX[1] && x < fgkMaxPcX[1]) { pc = 1; - px = Int_t((x - fgkMinPcX[1]) / SizePadX()); + px = Int_t((x - fgkMinPcX[1]) / sizePadX()); } //PC 1 or 3 or 5 else { return; } if (y > fgkMinPcY[0] && y < fgkMaxPcY[0]) { - py = Int_t(y / SizePadY()); + py = Int_t(y / sizePadY()); } //PC 0 or 1 else if (y > fgkMinPcY[2] && y < fgkMaxPcY[2]) { pc += 2; - py = Int_t((y - fgkMinPcY[2]) / SizePadY()); + py = Int_t((y - fgkMinPcY[2]) / sizePadY()); } //PC 2 or 3 else if (y > fgkMinPcY[4] && y < fgkMaxPcY[4]) { pc += 4; - py = Int_t((y - fgkMinPcY[4]) / SizePadY()); + py = Int_t((y - fgkMinPcY[4]) / sizePadY()); } //PC 4 or 5 else { return; } } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -Int_t Param::InHVSector(float y) +Int_t Param::inHVSector(float y) { //Calculate the HV sector corresponding to the cluster position //Arguments: y @@ -521,7 +521,7 @@ Int_t Param::InHVSector(float y) Int_t hvsec = -1; Int_t pc, px, py; - Lors2Pad(1., y, pc, px, py); + lors2Pad(1., y, pc, px, py); if (py == -1) { return hvsec; } @@ -531,25 +531,25 @@ Int_t Param::InHVSector(float y) return hvsec; } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -double Param::FindTemp(double tLow, double tHigh, double y) +double Param::findTemp(double tLow, double tHigh, double y) { // Model for gradient in temperature - double yRad = HinRad(y); //height in a given radiator + double yRad = hinRad(y); //height in a given radiator if (tHigh < tLow) { tHigh = tLow; //if Tout < Tin consider just Tin as reference... } if (yRad < 0) { yRad = 0; //protection against fake y values } - if (yRad > SizePcY()) { - yRad = SizePcY(); //protection against fake y values + if (yRad > sizePcY()) { + yRad = sizePcY(); //protection against fake y values } - double gradT = (tHigh - tLow) / SizePcY(); // linear gradient + double gradT = (tHigh - tLow) / sizePcY(); // linear gradient return gradT * yRad + tLow; } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void Param::SetChStatus(Int_t ch, bool status) +void Param::setChStatus(Int_t ch, bool status) { //Set a chamber on or off depending on the status //Arguments: ch=chamber,status=kTRUE = active, kFALSE=off @@ -561,7 +561,7 @@ void Param::SetChStatus(Int_t ch, bool status) } } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void Param::SetSectStatus(Int_t ch, Int_t sect, bool status) +void Param::setSectStatus(Int_t ch, Int_t sect, bool status) { //Set a given sector sect for a chamber ch on or off depending on the status //Sector=0,5 (6 sectors) @@ -579,7 +579,7 @@ void Param::SetSectStatus(Int_t ch, Int_t sect, bool status) } } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void Param::SetPcStatus(Int_t ch, Int_t pc, bool status) +void Param::setPcStatus(Int_t ch, Int_t pc, bool status) { //Set a given PC pc for a chamber ch on or off depending on the status //Arguments: ch=chamber,pc=PC,status: kTRUE = active, kFALSE=off @@ -599,7 +599,7 @@ void Param::SetPcStatus(Int_t ch, Int_t pc, bool status) } } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void Param::PrintChStatus(Int_t ch) +void Param::printChStatus(Int_t ch) { //Print the map status of a chamber on or off depending on the status //Arguments: ch=chamber @@ -621,14 +621,14 @@ void Param::PrintChStatus(Int_t ch) printf("\n"); } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void Param::SetGeomAccept() +void Param::setGeomAccept() { //Set the real acceptance of the modules, due to ineficciency or hardware problems (up tp 1/6/2010) //Arguments: none //Returns: none - SetSectStatus(0, 3, kFALSE); - SetSectStatus(4, 0, kFALSE); - SetSectStatus(5, 1, kFALSE); - SetSectStatus(6, 2, kFALSE); - SetSectStatus(6, 3, kFALSE); + setSectStatus(0, 3, kFALSE); + setSectStatus(4, 0, kFALSE); + setSectStatus(5, 1, kFALSE); + setSectStatus(6, 2, kFALSE); + setSectStatus(6, 3, kFALSE); } diff --git a/Detectors/HMPID/reconstruction/CMakeLists.txt b/Detectors/HMPID/reconstruction/CMakeLists.txt index b4ed8db47cec7..c695ce348e459 100644 --- a/Detectors/HMPID/reconstruction/CMakeLists.txt +++ b/Detectors/HMPID/reconstruction/CMakeLists.txt @@ -9,13 +9,14 @@ # submit itself to any jurisdiction. o2_add_library(HMPIDReconstruction - SOURCES src/Clusterer.cxx SOURCES src/HmpidDecoder.cxx src/HmpidDecodeRawMem.cxx src/HmpidEquipment.cxx + SOURCES src/Clusterer.cxx + src/HmpidDecoder2.cxx + src/HmpidEquipment.cxx PUBLIC_LINK_LIBRARIES O2::HMPIDBase + O2::DataFormatsHMP O2::HMPIDSimulation) o2_target_root_dictionary(HMPIDReconstruction - HEADERS include/HMPIDReconstruction/Clusterer.h) - #include/HMPIDReconstruction/HmpidDecodeRawMem.h - #include/HMPIDReconstruction/HmpidDecoder.h - #include/HMPIDReconstruction/HmpidEquipment.h) - #include/HMPIDReconstruction/DataReader.h) + HEADERS include/HMPIDReconstruction/Clusterer.h + include/HMPIDReconstruction/HmpidDecoder2.h + include/HMPIDReconstruction/HmpidEquipment.h) diff --git a/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/Clusterer.h b/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/Clusterer.h index 461729f2704e5..d551af51bd91d 100644 --- a/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/Clusterer.h +++ b/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/Clusterer.h @@ -15,8 +15,8 @@ #include #include -#include "HMPIDBase/Cluster.h" -#include "HMPIDBase/Digit.h" +#include "DataFormatsHMP/Cluster.h" +#include "DataFormatsHMP/Digit.h" #include "SimulationDataFormat/MCTruthContainer.h" #include "SimulationDataFormat/MCCompLabel.h" diff --git a/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/DataReader.h b/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/DataReader.h deleted file mode 100644 index e0cfd8791af4a..0000000000000 --- a/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/DataReader.h +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// \file DataReader.h -/// \brief Definition of the TOF hit reader diff --git a/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidDecodeRawFile.h b/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidDecodeRawFile.h index fed7466e1fd35..3b49837d98806 100644 --- a/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidDecodeRawFile.h +++ b/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidDecodeRawFile.h @@ -25,7 +25,7 @@ #include #include -#include "HmpidDecoder.h" +#include "HMPIDReconstruction/HmpidDecoder.h" #define MAXFILENAMEBUFFER 512 #define MAXRAWFILEBUFFER RAWBLOCKDIMENSION_W * 4 + 8 diff --git a/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidDecodeRawMem.h b/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidDecodeRawMem.h index edec37ba01e89..bce2d97a6eb6d 100644 --- a/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidDecodeRawMem.h +++ b/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidDecodeRawMem.h @@ -25,9 +25,11 @@ #include #include -#include "HMPIDBase/Digit.h" +#include "DataFormatsHMP/Digit.h" #include "HMPIDBase/Geo.h" -#include "HmpidDecoder.h" +#include "HMPIDReconstruction/HmpidDecoder.h" + +using namespace o2; namespace o2 { diff --git a/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidDecoder.h b/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidDecoder.h index abdf757b7c990..00d455c0a8d56 100644 --- a/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidDecoder.h +++ b/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidDecoder.h @@ -23,8 +23,9 @@ #include #include "FairLogger.h" +#include "CommonDataFormat/InteractionRecord.h" -#include "HmpidEquipment.h" +#include "HMPIDReconstruction/HmpidEquipment.h" #define MAXDESCRIPTIONLENGHT 50 @@ -40,6 +41,8 @@ #define WTYPE_EOE 4 #define WTYPE_NONE 0 +using namespace o2; + // Hmpid Equipment class namespace o2 { @@ -140,6 +143,8 @@ class HmpidDecoder float getAverageEventSize(int Equipment); float getAverageBusyTime(int Equipment); + o2::InteractionRecord mIntReco; + protected: int checkType(uint32_t wp, int* p1, int* p2, int* p3, int* p4); bool isRowMarker(uint32_t wp, int* Err, int* rowSize, int* mark); diff --git a/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidDecoder2.h b/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidDecoder2.h new file mode 100644 index 0000000000000..5ff034e074039 --- /dev/null +++ b/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidDecoder2.h @@ -0,0 +1,181 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// +/// \file HmpidDecoder.h +/// \author Antonio Franco - INFN Bari +/// \brief Base Class to decode HMPID Raw Data stream +/// + +#ifndef COMMON_HMPIDDECODER2_H_ +#define COMMON_HMPIDDECODER2_H_ + +#include +#include +#include +#include + +#include "Headers/RAWDataHeader.h" +#include "CommonDataFormat/InteractionRecord.h" +#include "DetectorsRaw/HBFUtils.h" +#include "DetectorsRaw/RawFileReader.h" + +#include "DataFormatsHMP/Digit.h" + +#include "FairLogger.h" + +#include "HMPIDReconstruction/HmpidEquipment.h" + +#define MAXDESCRIPTIONLENGHT 50 + +// ---- RDH 6 standard dimension ------- +#define RAWBLOCKDIMENSION_W 2048 +#define HEADERDIMENSION_W 16 +#define PAYLOADDIMENSION_W 2032 + +// ---- Defines for the decoding +#define WTYPE_ROW 1 +#define WTYPE_EOS 2 +#define WTYPE_PAD 3 +#define WTYPE_EOE 4 +#define WTYPE_NONE 0 + +using namespace o2::raw; + +// Hmpid Equipment class +namespace o2 +{ + +namespace hmpid +{ + +class HmpidDecoder2 +{ + + // Members + public: + int mVerbose; + HmpidEquipment* mTheEquipments[Geo::MAXEQUIPMENTS]; + int mNumberOfEquipments; + + static char sErrorDescription[MAXERRORS][MAXDESCRIPTIONLENGHT]; + static char sHmpidErrorDescription[MAXHMPIDERRORS][MAXDESCRIPTIONLENGHT]; + + public: + uint64_t mHeEvent; + int mHeBusy; + int mNumberWordToRead; + int mPayloadTail; + + int mHeFEEID; + int mHeSize; + int mHeVer; + int mHePrior; + int mHeStop; + int mHePages; + int mEquipment; + + int mHeOffsetNewPack; + int mHeMemorySize; + + int mHeDetectorID; + int mHeDW; + int mHeCruID; + int mHePackNum; + int mHePAR; + + int mHePageNum; + int mHeLinkNum; + int mHeFirmwareVersion; + int mHeHmpidError; + int mHeBCDI; + int mHeORBIT; + int mHeTType; + + uint32_t* mActualStreamPtr; + uint32_t* mEndStreamPtr; + uint32_t* mStartStreamPtr; + int mRDHSize; + int mRDHAcceptedVersion; + + o2::InteractionRecord mIntReco; + std::vector mDigits; + + // Methods + public: + HmpidDecoder2(int* EqIds, int* CruIds, int* LinkIds, int numOfEquipments); + HmpidDecoder2(int numOfEquipments); + ~HmpidDecoder2(); + + void init(); + bool setUpStream(void* Buffer, long BufferLen); + void setVerbosity(int Level) + { + mVerbose = Level; + }; + int getVerbosity() + { + return (mVerbose); + }; + + int getNumberOfEquipments() + { + return (mNumberOfEquipments); + }; + int getEquipmentIndex(int EquipmentId); + int getEquipmentIndex(int CruID, int LinkId); + int getEquipmentID(int CruId, int LinkId); + + void decodePage(uint32_t** streamBuffer); + void decodePageFast(uint32_t** streamBuf); + bool decodeBuffer(); + bool decodeBufferFast(); + + uint16_t getChannelSamples(int Equipment, int Column, int Dilogic, int Channel); + double getChannelSum(int Equipment, int Column, int Dilogic, int Channel); + double getChannelSquare(int Equipment, int Column, int Dilogic, int Channel); + uint16_t getPadSamples(int Module, int Row, int Column); + double getPadSum(int Module, int Row, int Column); + double getPadSquares(int Module, int Row, int Column); + + void dumpErrors(int Equipment); + void dumpPads(int Equipment, int type = 0); + void writeSummaryFile(char* summaryFileName); + + float getAverageEventSize(int Equipment); + float getAverageBusyTime(int Equipment); + + protected: + int checkType(uint32_t wp, int* p1, int* p2, int* p3, int* p4); + bool isRowMarker(uint32_t wp, int* Err, int* rowSize, int* mark); + bool isSegmentMarker(uint32_t wp, int* Err, int* segSize, int* Seg, int* mark); + bool isEoEmarker(uint32_t wp, int* Err, int* Col, int* Dilogic, int* Eoesize); + void setPad(HmpidEquipment* eq, int col, int dil, int ch, uint16_t charge); + + public: + bool decodeHmpidError(int ErrorField, char* outbuf); + void dumpHmpidError(int ErrorField); + bool isPadWord(uint32_t wp, int* Err, int* Col, int* Dilogic, int* Channel, int* Charge); + int decodeHeader(uint32_t* streamPtrAdr, int* EquipIndex); + HmpidEquipment* evaluateHeaderContents(int EquipmentIndex); + void updateStatistics(HmpidEquipment* eq); + + protected: + bool getBlockFromStream(uint32_t** streamPtr, uint32_t Size); + bool getHeaderFromStream(uint32_t** streamPtr); + bool getWordFromStream(uint32_t* word); + uint32_t* getActualStreamPtr() + { + return (mActualStreamPtr); + }; +}; +} // namespace hmpid +} // namespace o2 +#endif /* COMMON_HMPIDDECODER2ß_H_ */ diff --git a/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidEquipment.h b/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidEquipment.h index bf0bf74c1ec1a..0cc1f51d8cd9a 100644 --- a/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidEquipment.h +++ b/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/HmpidEquipment.h @@ -30,7 +30,7 @@ namespace hmpid { const int MAXERRORS = 13; -const int MAXHMPIDERRORS = 5; +const int MAXHMPIDERRORS = 6; const int ERR_NOTKNOWN = 0; const int ERR_ROWMARKEMPTY = 1; diff --git a/Detectors/HMPID/reconstruction/src/Clusterer.cxx b/Detectors/HMPID/reconstruction/src/Clusterer.cxx index 4f55089365932..87a48176dae28 100644 --- a/Detectors/HMPID/reconstruction/src/Clusterer.cxx +++ b/Detectors/HMPID/reconstruction/src/Clusterer.cxx @@ -13,7 +13,7 @@ #include #include "FairLogger.h" // for LOG #include "Framework/Logger.h" -#include "HMPIDBase/Cluster.h" +#include "DataFormatsHMP/Cluster.h" #include "HMPIDReconstruction/Clusterer.h" #include "SimulationDataFormat/MCCompLabel.h" #include "SimulationDataFormat/MCTruthContainer.h" diff --git a/Detectors/HMPID/reconstruction/src/DataReader.cxx b/Detectors/HMPID/reconstruction/src/DataReader.cxx deleted file mode 100644 index b2306eab0eb09..0000000000000 --- a/Detectors/HMPID/reconstruction/src/DataReader.cxx +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// \file Clusterer.cxx -/// \brief Implementation of the HMPID data reader class diff --git a/Detectors/HMPID/reconstruction/src/HMPIDReconstructionLinkDef.h b/Detectors/HMPID/reconstruction/src/HMPIDReconstructionLinkDef.h index 26b789b661b47..753dd9d0669bd 100644 --- a/Detectors/HMPID/reconstruction/src/HMPIDReconstructionLinkDef.h +++ b/Detectors/HMPID/reconstruction/src/HMPIDReconstructionLinkDef.h @@ -18,6 +18,7 @@ #pragma link C++ class o2::hmpid::Clusterer + ; //#pragma link C++ class o2::hmpid::HmpidDecodeRawMem + ; //#pragma link C++ class o2::hmpid::HmpidDecoder + ; -//#pragma link C++ class o2::hmpid::HmpidEquipment + ; +#pragma link C++ class o2::hmpid::HmpidDecoder2 + ; +#pragma link C++ class o2::hmpid::HmpidEquipment + ; #endif diff --git a/Detectors/HMPID/reconstruction/src/HmpidDecodeRawFile.cxx b/Detectors/HMPID/reconstruction/src/HmpidDecodeRawFile.cxx index 0be71d2457a66..a575ca8df84cf 100644 --- a/Detectors/HMPID/reconstruction/src/HmpidDecodeRawFile.cxx +++ b/Detectors/HMPID/reconstruction/src/HmpidDecodeRawFile.cxx @@ -17,6 +17,8 @@ /* ------ HISTORY --------- */ +#include "FairLogger.h" // for LOG +#include "Framework/Logger.h" #include "HMPIDReconstruction/HmpidDecodeRawFile.h" @@ -58,13 +60,13 @@ bool HmpidDecodeRawFile::setUpStream(void* FileName, long Size) strcpy(mInputFile, (const char*)FileName); // files section ---- if (!fileExists(mInputFile)) { - LOG(ERROR) << "The input file " << mInputFile << " does not exist at this time." << FairLogger::endl; + LOG(ERROR) << "The input file " << mInputFile << " does not exist at this time."; throw TH_FILENOTEXISTS; } // open the file fh = fopen(mInputFile, "rb"); if (fh == 0) { - LOG(ERROR) << "ERROR to open Input file ! [" << mInputFile << "]" << FairLogger::endl; + LOG(ERROR) << "ERROR to open Input file ! [" << mInputFile << "]"; throw TH_OPENFILE; } @@ -95,7 +97,7 @@ bool HmpidDecodeRawFile::getBlockFromStream(uint32_t** streamPtr, uint32_t Size) } Size = ((mFileBuffer[2] & 0x0000FFFF) / sizeof(int32_t)) - HEADERDIMENSION_W; nr = fread(mFileBuffer + HEADERDIMENSION_W, sizeof(int32_t), Size, fh); - LOG(DEBUG) << " getBlockFromStream read " << nr << " of " << Size + HEADERDIMENSION_W << " words !" << FairLogger::endl; + LOG(DEBUG) << " getBlockFromStream read " << nr << " of " << Size + HEADERDIMENSION_W << " words !"; if (nr != Size) { throw TH_WRONGFILELEN; } @@ -152,3 +154,4 @@ int HmpidDecodeRawFile::fileExists(char* filewithpath) return (false); } } +o2::hmpid::Digit diff --git a/Detectors/HMPID/reconstruction/src/HmpidDecodeRawMem.cxx b/Detectors/HMPID/reconstruction/src/HmpidDecodeRawMem.cxx index 760a18b6877c4..b633838515987 100644 --- a/Detectors/HMPID/reconstruction/src/HmpidDecodeRawMem.cxx +++ b/Detectors/HMPID/reconstruction/src/HmpidDecodeRawMem.cxx @@ -17,8 +17,10 @@ /* ------ HISTORY --------- */ +#include "FairLogger.h" // for LOG +#include "Framework/Logger.h" -#include "HMPIDBase/Digit.h" +#include "DataFormatsHMP/Digit.h" #include "HMPIDBase/Geo.h" #include "HMPIDReconstruction/HmpidDecodeRawMem.h" @@ -175,7 +177,7 @@ HmpidDecodeRawDigit::~HmpidDecodeRawDigit() = default; void HmpidDecodeRawDigit::setPad(HmpidEquipment* eq, int col, int dil, int ch, uint16_t charge) { eq->setPad(col, dil, ch, charge); - mDigits.push_back(Digit(mHeBCDI, mHeORBIT, charge, eq->getEquipmentId(), col, dil, ch)); + mDigits.push_back(o2::hmpid::Digit(charge, eq->getEquipmentId(), col, dil, ch)); //std::cout << "DI " << mDigits.back() << " "<mEventSize = 0; // reset the event eq->mSampleNumber = 0; eq->mErrorsCounter = 0; + mIntReco = {(uint16_t)mHeBCDI, (uint32_t)mHeORBIT}; } eq->mEventSize += mNumberWordToRead * sizeof(uint32_t); // Calculate the size in bytes if (mHeHmpidError != 0) { @@ -871,7 +873,7 @@ bool HmpidDecoder::decodeBufferFast() uint16_t HmpidDecoder::getPadSamples(int Module, int Row, int Column) { int e, c, d, h; - Digit::Absolute2Equipment(Module, Row, Column, &e, &c, &d, &h); + o2::hmpid::Digit::absolute2Equipment(Module, Row, Column, &e, &c, &d, &h); int EqInd = getEquipmentIndex(e); if (EqInd < 0) { return (0); @@ -887,7 +889,7 @@ uint16_t HmpidDecoder::getPadSamples(int Module, int Row, int Column) double HmpidDecoder::getPadSum(int Module, int Row, int Column) { int e, c, d, h; - Digit::Absolute2Equipment(Module, Row, Column, &e, &c, &d, &h); + o2::hmpid::Digit::absolute2Equipment(Module, Row, Column, &e, &c, &d, &h); int EqInd = getEquipmentIndex(e); if (EqInd < 0) { return (0); @@ -903,7 +905,7 @@ double HmpidDecoder::getPadSum(int Module, int Row, int Column) double HmpidDecoder::getPadSquares(int Module, int Row, int Column) { int e, c, d, h; - Digit::Absolute2Equipment(Module, Row, Column, &e, &c, &d, &h); + o2::hmpid::Digit::absolute2Equipment(Module, Row, Column, &e, &c, &d, &h); int EqInd = getEquipmentIndex(e); if (EqInd < 0) { return (0); diff --git a/Detectors/HMPID/reconstruction/src/HmpidDecoder2.cxx b/Detectors/HMPID/reconstruction/src/HmpidDecoder2.cxx new file mode 100644 index 0000000000000..e953904b374be --- /dev/null +++ b/Detectors/HMPID/reconstruction/src/HmpidDecoder2.cxx @@ -0,0 +1,1294 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// +/// \file HmpidDecoder.cxx +/// \author Antonio Franco - INFN Bari +/// \brief Base Class to decode HMPID Raw Data stream +/// \version 1.1 +/// \date 17/11/2020 + +/* ------ HISTORY --------- +*/ + +#include "FairLogger.h" // for LOG +#include "Framework/Logger.h" +#include "Headers/RAWDataHeader.h" +#include "HMPIDReconstruction/HmpidEquipment.h" +#include "HMPIDReconstruction/HmpidDecoder2.h" +#include "DataFormatsHMP/Digit.h" + +using namespace o2::hmpid; + +// ============= HmpidDecoder Class implementation ======= + +/// Decoding Error Messages Definitions +char HmpidDecoder2::sErrorDescription[MAXERRORS][MAXDESCRIPTIONLENGHT] = {"Word that I don't known !", + "Row Marker Word with 0 words", + "Duplicated Pad Word !", + "Row Marker Wrong/Lost -> to EoE", + "Row Marker Wrong/Lost -> to EoE", + "Row Marker reports an ERROR !", + "Lost EoE Marker !", + "Double EoE marker", + "Wrong size definition in EoE Marker", + "Double Mark Word", "Wrong Size in Segment Marker", + "Lost EoS Marker !", + "HMPID Header Errors"}; + +/// HMPID Firmware Error Messages Definitions +char HmpidDecoder2::sHmpidErrorDescription[MAXHMPIDERRORS][MAXDESCRIPTIONLENGHT] = { + "L0 Missing", + "L1 is received without L0", + "L1A signal arrived before the L1 Latency", + "L1A signal arrived after the L1 Latency", + "L1A is missing or L1 timeout", + "L1A Message is missing or L1 Message"}; + +/// Constructor : accepts the number of equipments to define +/// The mapping is the default at P2 +/// Allocates instances for all defined equipments +/// normally it is equal to 14 +/// @param[in] numOfEquipments : the number of equipments to define [1..14] +HmpidDecoder2::HmpidDecoder2(int numOfEquipments) +{ + mNumberOfEquipments = numOfEquipments; + for (int i = 0; i < mNumberOfEquipments; i++) { + mTheEquipments[i] = new HmpidEquipment(ReadOut::FeeId(i), ReadOut::CruId(i), ReadOut::LnkId(i)); + } +} + +/// Constructor : accepts the number of equipments to define +/// and their complete address map +/// Allocates instances for all defined equipments +/// +/// The Address map is build from three array +/// @param[in] numOfEquipments : the number of equipments to define [1..14] +/// @param[in] *EqIds : the pointer to the Equipments ID array +/// @param[in] *CruIds : the pointer to the CRU ID array +/// @param[in] *LinkIds : the pointer to the Link ID array +HmpidDecoder2::HmpidDecoder2(int* EqIds, int* CruIds, int* LinkIds, int numOfEquipments) +{ + mNumberOfEquipments = numOfEquipments; + for (int i = 0; i < mNumberOfEquipments; i++) { + mTheEquipments[i] = new HmpidEquipment(EqIds[i], CruIds[i], LinkIds[i]); + } +} + +/// Destructor : remove the Equipments instances +HmpidDecoder2::~HmpidDecoder2() +{ + for (int i = 0; i < mNumberOfEquipments; i++) { + delete mTheEquipments[i]; + } +} + +/// Init all the members variables. +void HmpidDecoder2::init() +{ + mVerbose = 0; + + mRDHAcceptedVersion = 6; + mRDHSize = sizeof(o2::header::RAWDataHeaderV6) / sizeof(uint32_t); + + mHeEvent = 0; + mHeBusy = 0; + mNumberWordToRead = 0; + mPayloadTail = 0; + + mHeFEEID = 0; + mHeSize = 0; + mHeVer = 0; + mHePrior = 0; + mHeStop = 0; + mHePages = 0; + mEquipment = 0; + + mHeOffsetNewPack = 0; + mHeMemorySize = 0; + + mHeDetectorID = 0; + mHeDW = 0; + mHeCruID = 0; + mHePackNum = 0; + mHePAR = 0; + mHePageNum = 0; + mHeLinkNum = 0; + mHeFirmwareVersion = 0; + mHeHmpidError = 0; + mHeBCDI = 0; + mHeORBIT = 0; + mHeTType = 0; + + mActualStreamPtr = nullptr; + mEndStreamPtr = nullptr; + mStartStreamPtr = nullptr; + + for (int i = 0; i < mNumberOfEquipments; i++) { + mTheEquipments[i]->init(); + mTheEquipments[i]->resetPadMap(); + } + + mDigits.clear(); +} + +/// Returns the Equipment Index (Pointer of the array) converting +/// the FLP hardware coords (CRU_Id and Link_Id) +/// @param[in] CruId : the CRU ID [0..3] -> FLP 160 = [0,1] FLP 161 = [2,3] +/// @param[in] LinkId : the Link ID [0..3] +/// @returns EquipmentIndex : the index in the Equipment array [0..13] (-1 := error) +int HmpidDecoder2::getEquipmentIndex(int CruId, int LinkId) +{ + for (int i = 0; i < mNumberOfEquipments; i++) { + if (mTheEquipments[i]->getEquipmentId(CruId, LinkId) != -1) { + return (i); + } + } + return (-1); +} + +/// Returns the Equipment Index (Pointer of the array) converting +/// the Equipment_ID (Firmaware defined Id AKA FFEID) +/// @param[in] EquipmentId : the Equipment ID [0..13] +/// @returns EquipmentIndex : the index in the Equipment array [0..13] (-1 := error) +int HmpidDecoder2::getEquipmentIndex(int EquipmentId) +{ + for (int i = 0; i < mNumberOfEquipments; i++) { + if (mTheEquipments[i]->getEquipmentId() == EquipmentId) { + return (i); + } + } + return (-1); +} + +/// Returns the Equipment_ID converting the FLP hardware coords +/// @param[in] CruId : the CRU ID [0..3] -> FLP 160 = [0,1] FLP 161 = [2,3] +/// @param[in] LinkId : the Link ID [0..3] +/// @returns EquipmentID : the ID of the Equipment [0..13] (-1 := error) +int HmpidDecoder2::getEquipmentID(int CruId, int LinkId) +{ + for (int i = 0; i < mNumberOfEquipments; i++) { + if (mTheEquipments[i]->getEquipmentId(CruId, LinkId) != -1) { + return (mTheEquipments[i]->getEquipmentId()); + } + } + return (-1); +} + +/// Scans the BitMap of Raw Data File word and detect the type +/// and the parameters +/// @param[in] wp : the word to analyze +/// @param[out] *p1 : first parameter extract (if it exists) +/// @param[out] *p2 : second parameter extract (if it exists) +/// @param[out] *p3 : third parameter extract (if it exists) +/// @param[out] *p4 : fourth parameter extract (if it exists) +/// @returns Type of Word : the type of word [0..4] (0 := undetect) +int HmpidDecoder2::checkType(uint32_t wp, int* p1, int* p2, int* p3, int* p4) +{ + if ((wp & 0x0000ffff) == 0x000036A8 || (wp & 0x0000ffff) == 0x000032A8 || (wp & 0x0000ffff) == 0x000030A0 || (wp & 0x0800ffff) == 0x080010A0) { + *p2 = (wp & 0x03ff0000) >> 16; // Number of words of row + *p1 = wp & 0x0000ffff; + return (WTYPE_ROW); + } + if ((wp & 0xfff00000) >> 20 == 0xAB0) { + *p2 = (wp & 0x000fff00) >> 8; // Number of words of Segment + *p1 = (wp & 0xfff00000) >> 20; + *p3 = wp & 0x0000000F; + if (*p3 < 4 && *p3 > 0) { + return (WTYPE_EOS); + } + } + // #EX MASK Raul 0x3803FF80 # ex mask 0xF803FF80 - this is EoE marker 0586800B0 + if ((wp & 0x0803FF80) == 0x08000080) { + *p1 = (wp & 0x07c00000) >> 22; + *p2 = (wp & 0x003C0000) >> 18; + *p3 = (wp & 0x0000007F); + if (*p1 < 25 && *p2 < 11) { + return (WTYPE_EOE); + } + } + if ((wp & 0x08000000) == 0) { // # this is a pad + // PAD:0000.0ccc.ccdd.ddnn.nnnn.vvvv.vvvv.vvvv :: c=col,d=dilo,n=chan,v=value + *p1 = (wp & 0x07c00000) >> 22; + *p2 = (wp & 0x003C0000) >> 18; + *p3 = (wp & 0x0003F000) >> 12; + *p4 = (wp & 0x00000FFF); + if (*p1 > 0 && *p1 < 25 && *p2 > 0 && *p2 < 11 && *p3 < 48) { + return (WTYPE_PAD); + } + } else { + return (WTYPE_NONE); + } + return (WTYPE_NONE); +} + +/// Checks if is a Raw Marker and extract the Row Size +/// @param[in] wp : the word to check +/// @param[out] *Err : true if an error is detected +/// @param[out] *rowSize : the number of words of the row +/// @param[out] *mark : the row marker +/// @returns True if Row Marker is detected +bool HmpidDecoder2::isRowMarker(uint32_t wp, int* Err, int* rowSize, int* mark) +{ + if ((wp & 0x0000ffff) == 0x36A8 || (wp & 0x0000ffff) == 0x32A8 || (wp & 0x0000ffff) == 0x30A0 || (wp & 0x0800ffff) == 0x080010A0) { + *rowSize = (wp & 0x03ff0000) >> 16; // # Number of words of row + *mark = wp & 0x0000ffff; + *Err = false; + return (true); + } else { + *Err = true; + return (false); + } +} + +/// Checks if is a Segment Marker and extracts the Segment number and the size +/// @param[in] wp : the word to check +/// @param[out] *Err : true if an error is detected +/// @param[out] *segSize : the number of words of the segment +/// @param[out] *Seg : the Segment number [1..3] +/// @param[out] *mark : the Segment Marker +/// @returns True if Segment Marker is detected +bool HmpidDecoder2::isSegmentMarker(uint32_t wp, int* Err, int* segSize, int* Seg, int* mark) +{ + *Err = false; + if ((wp & 0xfff00000) >> 20 == 0xAB0) { + *segSize = (wp & 0x000fff00) >> 8; // # Number of words of Segment + *mark = (wp & 0xfff00000) >> 20; + *Seg = wp & 0x0000000F; + if (*Seg > 3 || *Seg < 1) { + if (mVerbose > 6) { + std::cout << "HMPID Decoder2 : [INFO] " + << " Wrong segment Marker Word, bad Number of segment" << *Seg << "!" << std::endl; + } + *Err = true; + } + return (true); + } else { + return (false); + } +} + +/// Checks if is a PAD Word and extracts all the parameters +/// PAD map : 0000.0ccc.ccdd.ddnn.nnnn.vvvv.vvvv.vvvv :: c=col,d=dilo,n=chan,v=value +/// @param[in] wp : the word to check +/// @param[out] *Err : true if an error is detected +/// @param[out] *Col : the column number [1..24] +/// @param[out] *Dilogic : the dilogic number [1..10] +/// @param[out] *Channel : the channel number [0..47] +/// @param[out] *Charge : the value of Charge [0..4095] +/// @returns True if PAD Word is detected +bool HmpidDecoder2::isPadWord(uint32_t wp, int* Err, int* Col, int* Dilogic, int* Channel, int* Charge) +{ + *Err = false; + // if ((wp & 0x08000000) != 0) { + if ((wp & 0x08000000) != 0) { + return (false); + } + *Col = (wp & 0x07c00000) >> 22; + *Dilogic = (wp & 0x003C0000) >> 18; + *Channel = (wp & 0x0003F000) >> 12; + *Charge = (wp & 0x00000FFF); + uint16_t mark, row; + mark = wp & 0x0ffff; + row = (wp & 0x03ff0000) >> 16; + + if (mark == 0x036A8 || mark == 0x032A8 || mark == 0x030A0 || mark == 0x010A0) { // # ! this is a pad + if (*Dilogic > 10 || *Channel > 47 || *Dilogic < 1 || *Col > 24 || *Col < 1 || row <= 490 || row > 10) { + return (false); + } + } else { + if (*Dilogic > 10 || *Channel > 47 || *Dilogic < 1 || *Col > 24 || *Col < 1) { + // LOG_WARNING << " Wrong Pad values Col=" << *Col << " Dilogic=" << *Dilogic << " Channel=" << *Channel << " Charge=" << *Charge << " wp:0x" << std::hex << wp << std::dec; + *Err = true; + return (false); + } + } + return (true); +} + +/// Checks if is a EoE Marker and extracts the Column, Dilogic and the size +/// @param[in] wp : the word to check +/// @param[out] *Err : true if an error is detected +/// @param[out] *Col : the column number [1..24] +/// @param[out] *Dilogic : the dilogic number [1..10] +/// @param[out] *Eoesize : the number of words for dilogic +/// @returns True if EoE marker is detected +bool HmpidDecoder2::isEoEmarker(uint32_t wp, int* Err, int* Col, int* Dilogic, int* Eoesize) +{ + *Err = false; + // #EX MASK Raul 0x3803FF80 # ex mask 0xF803FF80 - this is EoE marker 0586800B0 + if ((wp & 0x0803FF80) == 0x08000080) { + *Col = (wp & 0x07c00000) >> 22; + *Dilogic = (wp & 0x003C0000) >> 18; + *Eoesize = (wp & 0x0000007F); + if (*Col > 24 || *Dilogic > 10) { + if (mVerbose > 8) { + std::cout << "HMPID Decoder2 : [DEBUG] " + << " EoE size wrong definition. Col=" << *Col << " Dilogic=" << *Dilogic << std::endl; + } + *Err = true; + } + return (true); + } else { + return (false); + } +} + +/// Decode the HMPID error BitMap field (5 bits) and returns true if there are +/// errors and in addition the concat string that contains the error messages +/// ATTENTION : the char * outbuf MUST point to a 250 bytes buffer +/// @param[in] ErrorField : the HMPID Error field +/// @param[out] *outbuf : the output buffer that contains the error description +/// @returns True if EoE marker is detected +bool HmpidDecoder2::decodeHmpidError(int ErrorField, char* outbuf) +{ + int res = false; + outbuf[0] = '\0'; + for (int i = 0; i < MAXHMPIDERRORS; i++) { + if ((ErrorField & (0x01 << i)) != 0) { + res = true; + strcat(outbuf, sHmpidErrorDescription[i]); + } + } + return (res); +} + +/// This Decode the Raw Data Header, returns the EquipmentIndex +/// that is obtained with the FLP hardware coords +/// +/// ATTENTION : the 'EquipIndex' parameter and the mEquipment member +/// are different data: the first is the pointer in the Equipments instances +/// array, the second is the FEE_ID number +/// +/// The EVENT_NUMBER : actually is calculated from the ORBIT number +/// +/// @param[in] *streamPtrAdr : the pointer to the Header buffer +/// @param[out] *EquipIndex : the Index to the Equipment Object Array [0..13] +/// @returns True every time +/// @throws TH_WRONGEQUIPINDEX Thrown if the Equipment Index is out of boundary (Equipment not recognized) +int HmpidDecoder2::decodeHeader(uint32_t* streamPtrAdr, int* EquipIndex) +{ + uint32_t* buffer = streamPtrAdr; // Sets the pointer to buffer + o2::header::RAWDataHeaderV6* hpt = (o2::header::RAWDataHeaderV6*)buffer; + + /* + mHeFEEID = (buffer[0] & 0x000f0000) >> 16; + mHeSize = (buffer[0] & 0x0000ff00) >> 8; + mHeVer = (buffer[0] & 0x000000ff); + mHePrior = (buffer[1] & 0x000000FF); + mHeDetectorID = (buffer[1] & 0x0000FF00) >> 8; + mHeOffsetNewPack = (buffer[2] & 0x0000FFFF); + mHeMemorySize = (buffer[2] & 0xffff0000) >> 16; + mHeDW = (buffer[3] & 0xF0000000) >> 24; + mHeCruID = (buffer[3] & 0x0FF0000) >> 16; + mHePackNum = (buffer[3] & 0x0000FF00) >> 8; + mHeLinkNum = (buffer[3] & 0x000000FF); + mHeBCDI = (buffer[4] & 0x00000FFF); + mHeORBIT = buffer[5]; + mHeTType = buffer[8]; + mHePageNum = (buffer[9] & 0x0000FFFF); + mHeStop = (buffer[9] & 0x00ff0000) >> 16; + mHeBusy = (buffer[12] & 0xfffffe00) >> 9; + mHeFirmwareVersion = buffer[12] & 0x0000000f; + mHeHmpidError = (buffer[12] & 0x000001F0) >> 4; + mHePAR = buffer[13] & 0x0000FFFF; + */ + mHeFEEID = hpt->feeId; + mHeSize = hpt->headerSize; + mHeVer = hpt->version; + mHePrior = hpt->priority; + mHeDetectorID = hpt->sourceID; + mHeOffsetNewPack = hpt->offsetToNext; + mHeMemorySize = hpt->memorySize; + mHeDW = hpt->endPointID; + mHeCruID = hpt->cruID; + mHePackNum = hpt->packetCounter; + mHeLinkNum = hpt->linkID; + mHeBCDI = hpt->bunchCrossing; + mHeORBIT = hpt->orbit; + mHeTType = hpt->triggerType; + mHePageNum = hpt->pageCnt; + mHeStop = hpt->stop; + mHeBusy = (hpt->detectorField & 0xfffffe00) >> 9; + mHeFirmwareVersion = hpt->detectorField & 0x0000000f; + mHeHmpidError = (hpt->detectorField & 0x000001F0) >> 4; + mHePAR = hpt->detectorPAR; + + *EquipIndex = getEquipmentIndex(mHeCruID, mHeLinkNum); + // mEquipment = (*EquipIndex != -1) ? mTheEquipments[*EquipIndex]->getEquipmentId() : -1; + mEquipment = mHeFEEID & 0x000F; + mNumberWordToRead = ((mHeMemorySize - mHeSize) / sizeof(uint32_t)); + mPayloadTail = ((mHeOffsetNewPack - mHeMemorySize) / sizeof(uint32_t)); + + // ---- Event ID : Actualy based on ORBIT NUMBER and BC + mHeEvent = (mHeORBIT << 12) | mHeBCDI; + + if (mVerbose > 6) { + std::cout << "HMPID Decoder2 : [INFO] " + << "FEE-ID=" << mHeFEEID << " HeSize=" << mHeSize << " HePrior=" << mHePrior << " Det.Id=" << mHeDetectorID << " HeMemorySize=" << mHeMemorySize << " HeOffsetNewPack=" << mHeOffsetNewPack << std::endl; + std::cout << " Equipment=" << mEquipment << " PakCounter=" << mHePackNum << " Link=" << mHeLinkNum << " CruID=" << mHeCruID << " DW=" << mHeDW << " BC=" << mHeBCDI << " ORBIT=" << mHeORBIT << std::endl; + std::cout << " TType=" << mHeTType << " HeStop=" << mHeStop << " PagesCounter=" << mHePageNum << " FirmVersion=" << mHeFirmwareVersion << " BusyTime=" << mHeBusy << " Error=" << mHeHmpidError << " PAR=" << mHePAR << std::endl; + std::cout << " EquIdx = " << *EquipIndex << " Event = " << mHeEvent << " Payload : Words to read=" << mNumberWordToRead << " PailoadTail=" << mPayloadTail << std::endl; + } + if (*EquipIndex == -1) { + if (mVerbose > 1) { + std::cout << "HMPID Decoder2 : [ERROR] " + << "ERROR ! Bad equipment Number: " << mEquipment << std::endl; + } + throw TH_WRONGEQUIPINDEX; + } + // std::cout << "HMPID ! Exit decode header" << std::endl; + return (true); +} + +/// Updates some information related to the Event +/// this function is called at the end of the event +/// @param[in] *eq : the pointer to the Equipment Object +void HmpidDecoder2::updateStatistics(HmpidEquipment* eq) +{ + eq->mPadsPerEventAverage = ((eq->mPadsPerEventAverage * (eq->mNumberOfEvents - 1)) + eq->mSampleNumber) / (eq->mNumberOfEvents); + eq->mEventSizeAverage = ((eq->mEventSizeAverage * (eq->mNumberOfEvents - 1)) + eq->mEventSize) / (eq->mNumberOfEvents); + eq->mBusyTimeAverage = ((eq->mBusyTimeAverage * eq->mBusyTimeSamples) + eq->mBusyTimeValue) / (++(eq->mBusyTimeSamples)); + if (eq->mSampleNumber == 0) { + eq->mNumberOfEmptyEvents += 1; + } + if (eq->mErrorsCounter > 0) { + eq->mNumberOfWrongEvents += 1; + } + eq->mTotalPads += eq->mSampleNumber; + eq->mTotalErrors += eq->mErrorsCounter; + + //std::cout << ">>>updateStatistics() >>> "<< eq->getEquipmentId() << "="<< eq->mNumberOfEvents<<" :" << eq->mEventSize <<","<< eq->mTotalPads << ", " << eq->mSampleNumber << std::endl; + + return; +} + +/// Evaluates the content of the header and detect the change of the event +/// with the relevant updates... +/// @param[in] EquipmentIndex : the pointer to the Array of Equipments Array +/// @returns the Pointer to the modified Equipment object +HmpidEquipment* HmpidDecoder2::evaluateHeaderContents(int EquipmentIndex) +{ + if (EquipmentIndex < 0 || EquipmentIndex > 13) { + if (mVerbose > 1) { + std::cout << "HMPID Decoder2 : [ERROR] " + << "Bad Equipment number !" << EquipmentIndex << std::endl; + } + throw TH_WRONGEQUIPINDEX; + } + HmpidEquipment* eq = mTheEquipments[EquipmentIndex]; + if (mHeEvent != eq->mEventNumber) { // Is a new event + if (eq->mEventNumber != OUTRANGEEVENTNUMBER) { // skip the first + updateStatistics(eq); // update previous statistics + } + eq->mNumberOfEvents++; + eq->mEventNumber = mHeEvent; + eq->mBusyTimeValue = mHeBusy * 0.00000005; + eq->mEventSize = 0; // reset the event + eq->mSampleNumber = 0; + eq->mErrorsCounter = 0; + mIntReco = {(uint16_t)mHeBCDI, (uint32_t)mHeORBIT}; + } + eq->mEventSize += mNumberWordToRead * sizeof(uint32_t); // Calculate the size in bytes + if (mHeHmpidError != 0) { + std::cout << "HMPID Header reports an error : " << mHeHmpidError << std::endl; + dumpHmpidError(mHeHmpidError); + eq->setError(ERR_HMPID); + } + // std::cout << ".. end evaluateHeaderContents = " << eq->mEventNumber << std::endl; + return (eq); +} + +/// --------------- Decode One Page from Data Buffer --------------- +/// Read the stream, decode the contents and store resuls. +/// ATTENTION : Assumes that the input stream was set +/// @throws TH_WRONGHEADER Thrown if the Fails to decode the Header +/// @param[in] streamBuf : the pointer to the Pointer of the Stream Buffer +void HmpidDecoder2::decodePage(uint32_t** streamBuf) +{ + mActualStreamPtr = *streamBuf; + int equipmentIndex; + try { + getHeaderFromStream(streamBuf); + } catch (int e) { + // The stream end ! + if (mVerbose > 8) { + std::cout << "HMPID Decoder2 : [DEBUG] " + << "End main decoding loop !" << std::endl; + } + throw TH_BUFFEREMPTY; + } + try { + decodeHeader(*streamBuf, &equipmentIndex); + } catch (int e) { + if (mVerbose > 1) { + std::cout << "HMPID Decoder2 : [ERROR] " + << "Failed to decode the Header !" << std::endl; + } + throw TH_WRONGHEADER; + } + HmpidEquipment* eq; + try { + eq = evaluateHeaderContents(equipmentIndex); + } catch (int e) { + throw TH_WRONGHEADER; + } + + uint32_t wpprev = 0; + uint32_t wp = 0; + int newOne = true; + int p1, p2, p3, p4; + int error; + int type; + bool isIt; + + int payIndex = 0; + while (payIndex < mNumberWordToRead) { //start the payload loop word by word + if (newOne == true) { + wpprev = wp; + if (!getWordFromStream(&wp)) { // end the stream + break; + } + type = checkType(wp, &p1, &p2, &p3, &p4); + if (type == WTYPE_NONE) { + if (eq->mWillBePad == true) { // try to recover the first pad ! + type = checkType((wp & 0xF7FFFFFF), &p1, &p2, &p3, &p4); + if (type == WTYPE_PAD && p3 == 0 && eq->mWordsPerDilogicCounter == 0) { + newOne = false; // # reprocess as pad + continue; + } + } + eq->setError(ERR_NOTKNOWN); + eq->mWordsPerRowCounter++; + eq->mWordsPerSegCounter++; + payIndex++; + continue; + } + } + if (mEquipment == 8) { + if (mVerbose > 6) { + std::cout << "HMPID Decoder2 : [INFO] " + "Event" + << eq->mEventNumber << " >" << std::hex << wp << std::dec << "<" << type << std::endl; + } + } + if (eq->mWillBeRowMarker == true) { // #shoud be a Row Marker + if (type == WTYPE_ROW) { + eq->mColumnCounter++; + eq->mWordsPerSegCounter++; + eq->mRowSize = p2; + switch (p2) { + case 0: // Empty column + eq->setError(ERR_ROWMARKEMPTY); + eq->mWillBeRowMarker = true; + break; + case 0x3FF: // Error in column + eq->setError(ERR_ROWMARKERROR); + eq->mWillBeRowMarker = true; + break; + case 0x3FE: // Masked column + if (mVerbose > 6) { + std::cout << "HMPID Decoder2 : [INFO] " + << "Equip=" << mEquipment << "The column=" << (eq->mSegment) * 8 + eq->mColumnCounter << " is Masked !" << std::endl; + } + eq->mWillBeRowMarker = true; + break; + default: + eq->mWillBeRowMarker = false; + eq->mWillBePad = true; + break; + } + newOne = true; + } else { + if (wp == wpprev) { + eq->setError(ERR_DUPLICATEPAD); + newOne = true; + } else if (type == WTYPE_EOE) { // # Could be a EoE + eq->mColumnCounter++; + eq->setError(ERR_ROWMARKWRONG); + eq->mWillBeRowMarker = false; + eq->mWillBePad = true; + newOne = true; + } else if (type == WTYPE_PAD) { //# Could be a PAD + eq->mColumnCounter++; + eq->setError(ERR_ROWMARKLOST); + eq->mWillBeRowMarker = false; + eq->mWillBePad = true; + newOne = true; + } else if (type == WTYPE_EOS) { // # Could be a EoS + eq->mWillBeRowMarker = false; + eq->mWillBeSegmentMarker = true; + newOne = false; + } else { + eq->mColumnCounter++; + eq->setError(ERR_ROWMARKLOST); + eq->mWillBeRowMarker = false; + eq->mWillBePad = true; + newOne = true; + } + } + } else if (eq->mWillBePad == true) { // # We expect a pad + //# PAD:0000.0ccc.ccdd.ddnn.nnnn.vvvv.vvvv.vvvv :: c=col,d=dilo,n=chan,v=value + // c = 1..24 d = 1..10 n = 0..47 + if (type == WTYPE_PAD) { + newOne = true; + if (wp == wpprev) { + eq->setError(ERR_DUPLICATEPAD); + } else if (p1 != (eq->mSegment * 8 + eq->mColumnCounter)) { // # Manage + // We try to recover the RowMarker misunderstanding + isIt = isRowMarker(wp, &error, &p2, &p1); + if (isIt == true && error == false) { + type = WTYPE_ROW; + newOne = false; + eq->mWillBeEoE = true; + eq->mWillBePad = false; + } else { + eq->mColumnCounter = p1 % 8; + } + } else { + setPad(eq, p1 - 1, p2 - 1, p3, p4); + if (mEquipment == 8) { + if (mVerbose > 6) { + std::cout << "HMPID Decoder2 : [INFO] " + << "Event" << eq->mEventNumber << " >" << p1 - 1 << "," << p2 - 1 << "," << p3 << "," << p4 << std::endl; + } + } + eq->mWordsPerDilogicCounter++; + eq->mSampleNumber++; + if (p3 == 47) { + eq->mWillBeEoE = true; + eq->mWillBePad = false; + } + } + eq->mWordsPerRowCounter++; + eq->mWordsPerSegCounter++; + } else if (type == WTYPE_EOE) { //# the pads are end ok + eq->mWillBeEoE = true; + eq->mWillBePad = false; + newOne = false; + } else if (type == WTYPE_ROW) { // # We Lost the EoE ! + // We try to recover the PAD misunderstanding + isIt = isPadWord(wp, &error, &p1, &p2, &p3, &p4); + if (isIt == true && error == false) { + type = WTYPE_PAD; + newOne = false; // # reprocess as pad + } else { + eq->setError(ERR_LOSTEOEMARK); + eq->mWillBeRowMarker = true; + eq->mWillBePad = false; + newOne = false; + } + } else if (type == WTYPE_EOS) { // # We Lost the EoE ! + eq->setError(ERR_LOSTEOEMARK); + eq->mWillBeSegmentMarker = true; + eq->mWillBePad = false; + newOne = false; + } + } else if (eq->mWillBeEoE == true) { // # We expect a EoE + if (type == WTYPE_EOE) { + eq->mWordsPerRowCounter++; + eq->mWordsPerSegCounter++; + if (wpprev == wp) { + eq->setError(ERR_DOUBLEEOEMARK); + } else if (p3 != eq->mWordsPerDilogicCounter) { + eq->setError(ERR_WRONGSIZEINEOE); + } + eq->mWordsPerDilogicCounter = 0; + if (p2 == 10) { + if (p1 % 8 != 0) { // # we expect the Row Marker + eq->mWillBeRowMarker = true; + } else { + eq->mWillBeSegmentMarker = true; + } + } else { + eq->mWillBePad = true; + } + eq->mWillBeEoE = false; + newOne = true; + } else if (type == WTYPE_EOS) { // We Lost the EoE ! + eq->setError(ERR_LOSTEOEMARK); + eq->mWillBeSegmentMarker = true; + eq->mWillBeEoE = false; + newOne = false; + } else if (type == WTYPE_ROW) { //# We Lost the EoE ! + eq->setError(ERR_LOSTEOEMARK); + eq->mWillBeRowMarker = true; + eq->mWillBeEoE = false; + newOne = false; + } else if (type == WTYPE_PAD) { // # We Lost the EoE ! + int typb, p1b, p2b, p3b, p4b; + typb = checkType((wp | 0x08000000), &p1b, &p2b, &p3b, &p4b); + if (typb == WTYPE_EOE && p3b == 48) { + type = typb; + p1 = p1b; + p2 = p2b; + p3 = p3b; + p4 = p4b; + newOne = false; // # reprocess as EoE + } else { + eq->setError(ERR_LOSTEOEMARK); + eq->mWillBePad = true; + eq->mWillBeEoE = false; + newOne = false; + } + } + } else if (eq->mWillBeSegmentMarker == true) { // # We expect a EoSegment + if (wpprev == wp) { + eq->setError(ERR_DOUBLEMARKWORD); + newOne = true; + } else if (type == 2) { + if (abs(eq->mWordsPerSegCounter - p2) > 5) { + eq->setError(ERR_WRONGSIZESEGMENTMARK); + } + eq->mWordsPerSegCounter = 0; + eq->mWordsPerRowCounter = 0; + eq->mColumnCounter = 0; + eq->mSegment = p3 % 3; + eq->mWillBeRowMarker = true; + eq->mWillBeSegmentMarker = false; + newOne = true; + } else { + eq->setError(ERR_LOSTEOSMARK); + eq->mWillBeSegmentMarker = false; + eq->mWillBeRowMarker = true; + newOne = false; + } + } + if (newOne) { + payIndex += 1; + } + } + for (int i = 0; i < mPayloadTail; i++) { // move the pointer to skip the Payload Tail + getWordFromStream(&wp); + } + *streamBuf = mActualStreamPtr; +} + +/// --------------- Read Raw Data Buffer --------------- +/// Read the stream, decode the contents and store resuls. +/// ATTENTION : Assumes that the input stream was set +/// @throws TH_WRONGHEADER Thrown if the Fails to decode the Header +bool HmpidDecoder2::decodeBuffer() +{ + // ---------resets the PAdMap----------- + for (int i = 0; i < mNumberOfEquipments; i++) { + mTheEquipments[i]->init(); + mTheEquipments[i]->resetPadMap(); + mTheEquipments[i]->resetErrors(); + } + + uint32_t* streamBuf = mStartStreamPtr; + if (mVerbose > 8) { + std::cout << "HMPID Decoder2 : [DEBUG] " + << "Enter decoding !" << std::endl; + } + + // Input Stream Main Loop + while (true) { + try { + decodePage(&streamBuf); + } catch (int e) { + if (mVerbose > 8) { + std::cout << "HMPID Decoder2 : [DEBUG] " + << "End main buffer decoding loop !" << std::endl; + } + break; + } + } // this is the end of stream + + // cycle in order to update info for the last event + for (int i = 0; i < mNumberOfEquipments; i++) { + if (mTheEquipments[i]->mNumberOfEvents > 0) { + updateStatistics(mTheEquipments[i]); + } + } + return (true); +} + +/// ----- Sets the Pad ! ------ +/// this is an overloaded method. In this version the value of the charge +/// is used to update the statistical matrix of the base class +/// +/// @param[in] *eq : the pointer to the Equipment object +/// @param[in] col : the column [0..23] +/// @param[in] dil : the dilogic [0..9] +/// @param[in] ch : the channel [0..47] +/// @param[in] charge : the value of the charge +void HmpidDecoder2::setPad(HmpidEquipment* eq, int col, int dil, int ch, uint16_t charge) +{ + eq->setPad(col, dil, ch, charge); + mDigits.push_back(o2::hmpid::Digit(charge, eq->getEquipmentId(), col, dil, ch)); + //std::cout << "DI " << mDigits.back() << " "< 6) { + std::cout << "HMPID Decoder2 : [INFO] " + << "Failed to decode the Header !" << std::endl; + } + throw TH_WRONGHEADER; + } + + HmpidEquipment* eq; + try { + eq = evaluateHeaderContents(equipmentIndex); + } catch (int e) { + throw TH_WRONGHEADER; + } + + uint32_t wpprev = 0; + uint32_t wp = 0; + int newOne = true; + int Column, Dilogic, Channel, Charge; + int pwer; + int payIndex = 0; + while (payIndex < mNumberWordToRead) { //start the payload loop word by word + wpprev = wp; + if (!getWordFromStream(&wp)) { // end the stream + //mPayloadTail = 0; + throw TH_BUFFEREMPTY; + } + if (wp == wpprev) { + if (mVerbose > 8) { + std::cout << "HMPID Decoder2 : [DEBUG] " + << "Equip=" << mEquipment << sErrorDescription[ERR_DUPLICATEPAD] << " col=" << (eq->mSegment) * 8 + eq->mColumnCounter << "[" << Column << "]" << std::endl; + } + } else { + if (isPadWord(wp, &pwer, &Column, &Dilogic, &Channel, &Charge) == true) { + if (pwer != true) { + setPad(eq, Column - 1, Dilogic - 1, Channel, Charge); + eq->mSampleNumber++; + } + } + } + payIndex += 1; + } + for (int i = 0; i < mPayloadTail; i++) { // move the pointer to skip the Payload Tail + if (!getWordFromStream(&wp)) { + throw TH_BUFFEREMPTY; + } + } + *streamBuf = mActualStreamPtr; + return; +} + +/// ---------- Read Raw Data Buffer with Fast Decoding ---------- +/// Read the stream, decode the contents and store resuls. +/// Fast alghoritm : no parsing of control words ! +/// ATTENTION : Assumes that the input stream was set +/// @throws TH_WRONGHEADER Thrown if the Fails to decode the Header +bool HmpidDecoder2::decodeBufferFast() +{ + // ---------resets the PAdMap----------- + for (int i = 0; i < mNumberOfEquipments; i++) { + mTheEquipments[i]->init(); + mTheEquipments[i]->resetPadMap(); + } + uint32_t* streamBuf = mStartStreamPtr; + if (mVerbose > 6) { + std::cout << "HMPID Decoder2 : [INFO] " + << "Enter FAST decoding !" << std::endl; + } + // Input Stream Main Loop + while (true) { + try { + decodePageFast(&streamBuf); + } catch (int e) { + if (mVerbose > 6) { + std::cout << "HMPID Decoder2 : [INFO] " + << " End Buffer Fast Decoding !" << std::endl; + } + break; + } + } // this is the end of stream + + // cycle in order to update info for the last event + for (int i = 0; i < mNumberOfEquipments; i++) { + if (mTheEquipments[i]->mNumberOfEvents > 0) { + updateStatistics(mTheEquipments[i]); + } + } + return (true); +} + +// ========================================================= + +/// Getter method to extract Statistic Data in Digit Coords +/// @param[in] Module : the HMPID Module number [0..6] +/// @param[in] Column : the HMPID Module Column number [0..143] +/// @param[in] Row : the HMPID Module Row number [0..159] +/// @returns The Number of entries for specified pad +uint16_t HmpidDecoder2::getPadSamples(int Module, int Row, int Column) +{ + int e, c, d, h; + o2::hmpid::Digit::absolute2Equipment(Module, Row, Column, &e, &c, &d, &h); + int EqInd = getEquipmentIndex(e); + if (EqInd < 0) { + return (0); + } + return (mTheEquipments[EqInd]->mPadSamples[c][d][h]); +} + +/// Getter method to extract Statistic Data in Digit Coords +/// @param[in] Module : the HMPID Module number [0..6] +/// @param[in] Column : the HMPID Module Column number [0..143] +/// @param[in] Row : the HMPID Module Row number [0..159] +/// @returns The Sum of Charges for specified pad +double HmpidDecoder2::getPadSum(int Module, int Row, int Column) +{ + int e, c, d, h; + o2::hmpid::Digit::absolute2Equipment(Module, Row, Column, &e, &c, &d, &h); + int EqInd = getEquipmentIndex(e); + if (EqInd < 0) { + return (0); + } + return (mTheEquipments[EqInd]->mPadSum[c][d][h]); +} + +/// Getter method to extract Statistic Data in Digit Coords +/// @param[in] Module : the HMPID Module number [0..6] +/// @param[in] Column : the HMPID Module Column number [0..143] +/// @param[in] Row : the HMPID Module Row number [0..159] +/// @returns The Sum of Square Charges for specified pad +double HmpidDecoder2::getPadSquares(int Module, int Row, int Column) +{ + int e, c, d, h; + o2::hmpid::Digit::absolute2Equipment(Module, Row, Column, &e, &c, &d, &h); + int EqInd = getEquipmentIndex(e); + if (EqInd < 0) { + return (0); + } + return (mTheEquipments[EqInd]->mPadSquares[c][d][h]); +} + +/// Getter method to extract Statistic Data in Hardware Coords +/// @param[in] EquipmId : the HMPID EquipmentId [0..13] +/// @param[in] Column : the HMPID Module Column number [0..23] +/// @param[in] Dilogic : the HMPID Module Row number [0..9] +/// @param[in] Channel : the HMPID Module Row number [0..47] +/// @returns The Number of Entries for specified pad +uint16_t HmpidDecoder2::getChannelSamples(int EquipmId, int Column, int Dilogic, int Channel) +{ + int EqInd = getEquipmentIndex(EquipmId); + if (EqInd < 0) { + return (0); + } + return (mTheEquipments[EqInd]->mPadSamples[Column][Dilogic][Channel]); +} + +/// Getter method to extract Statistic Data in Hardware Coords +/// @param[in] EquipmId : the HMPID EquipmentId [0..13] +/// @param[in] Column : the HMPID Module Column number [0..23] +/// @param[in] Dilogic : the HMPID Module Row number [0..9] +/// @param[in] Channel : the HMPID Module Row number [0..47] +/// @returns The Sum of Charges for specified pad +double HmpidDecoder2::getChannelSum(int EquipmId, int Column, int Dilogic, int Channel) +{ + int EqInd = getEquipmentIndex(EquipmId); + if (EqInd < 0) { + return (0); + } + return (mTheEquipments[EqInd]->mPadSum[Column][Dilogic][Channel]); +} + +/// Getter method to extract Statistic Data in Hardware Coords +/// @param[in] EquipmId : the HMPID EquipmentId [0..13] +/// @param[in] Column : the HMPID Module Column number [0..23] +/// @param[in] Dilogic : the HMPID Module Row number [0..9] +/// @param[in] Channel : the HMPID Module Row number [0..47] +/// @returns The Sum of Square Charges for specified pad +double HmpidDecoder2::getChannelSquare(int EquipmId, int Column, int Dilogic, int Channel) +{ + int EqInd = getEquipmentIndex(EquipmId); + if (EqInd < 0) { + return (0); + } + return (mTheEquipments[EqInd]->mPadSquares[Column][Dilogic][Channel]); +} + +/// Gets the Average Event Size value +/// @param[in] EquipmId : the HMPID EquipmentId [0..13] +/// @returns The Average Event Size value ( 0 for wrong Equipment Id) +float HmpidDecoder2::getAverageEventSize(int EquipmId) +{ + int EqInd = getEquipmentIndex(EquipmId); + if (EqInd < 0) { + return (0.0); + } + return (mTheEquipments[EqInd]->mEventSizeAverage); +} + +/// Gets the Average Busy Time value +/// @param[in] EquipmId : the HMPID EquipmentId [0..13] +/// @returns The Average Busy Time value ( 0 for wrong Equipment Id) +float HmpidDecoder2::getAverageBusyTime(int EquipmId) +{ + int EqInd = getEquipmentIndex(EquipmId); + if (EqInd < 0) { + return (0.0); + } + return (mTheEquipments[EqInd]->mBusyTimeAverage); +} + +// =================================================== +// Methods to dump info + +/// Prints on the standard output the table of decoding +/// errors for one equipment +/// @param[in] EquipmId : the HMPID EquipmentId [0..13] +void HmpidDecoder2::dumpErrors(int EquipmId) +{ + int EqInd = getEquipmentIndex(EquipmId); + if (EqInd < 0) { + return; + } + std::cout << "Dump Errors for the Equipment = " << EquipmId << std::endl; + for (int i = 0; i < MAXERRORS; i++) { + std::cout << sErrorDescription[i] << " = " << mTheEquipments[EqInd]->mErrors[i] << std::endl; + } + std::cout << " -------- " << std::endl; + return; +} + +/// Prints on the standard output a Table of statistical +/// decoding information for one equipment +/// @param[in] EquipmId : the HMPID EquipmentId [0..13] +/// @type[in] The type of info. 0 = Entries, 1 = Sum, 2 = Sum of squares +void HmpidDecoder2::dumpPads(int EquipmId, int type) +{ + int EqInd = getEquipmentIndex(EquipmId); + if (EqInd < 0) { + return; + } + int Module = EquipmId / 2; + int StartRow = (EquipmId % 2 == 1) ? 80 : 0; + int EndRow = (EquipmId % 2 == 1) ? 160 : 80; + std::cout << "Dump Pads for the Equipment = " << EquipmId << std::endl; + for (int c = 0; c < 144; c++) { + for (int r = StartRow; r < EndRow; r++) { + switch (type) { + case 0: + std::cout << getPadSamples(Module, r, c) << ","; + break; + case 1: + std::cout << getPadSum(Module, r, c) << ","; + break; + case 2: + std::cout << getPadSquares(Module, r, c) << ","; + break; + } + } + std::cout << std::endl; + } + std::cout << " -------- " << std::endl; + return; +} + +/// Prints on the standard output the decoded HMPID error field +/// @param[in] ErrorField : the HMPID readout error field +void HmpidDecoder2::dumpHmpidError(int ErrorField) +{ + char printbuf[MAXHMPIDERRORS * MAXDESCRIPTIONLENGHT + 255]; + if (decodeHmpidError(ErrorField, printbuf) == true) { + if (mVerbose > 1) { + std::cout << "HMPID Decoder2 : [ERROR] " + << "HMPID Error field = " << ErrorField << " : " << printbuf << std::endl; + } + } + return; +} + +/// Writes in a ASCCI File the complete report of the decoding +/// procedure +/// @param[in] *summaryFileName : the name of the output file +/// @throws TH_CREATEFILE Thrown if was not able to create the file +void HmpidDecoder2::writeSummaryFile(char* summaryFileName) +{ + FILE* fs = fopen(summaryFileName, "w"); + if (fs == nullptr) { + printf("Error opening the file %s !\n", summaryFileName); + throw TH_CREATEFILE; + } + + fprintf(fs, "HMPID Readout Raw Data Decoding Summary File\n"); + fprintf(fs, "Equipment Id\t"); + for (int i = 0; i < Geo::MAXEQUIPMENTS; i++) { + fprintf(fs, "%d\t", mTheEquipments[i]->getEquipmentId()); + } + fprintf(fs, "\n"); + + fprintf(fs, "Number of events\t"); + for (int i = 0; i < Geo::MAXEQUIPMENTS; i++) { + fprintf(fs, "%d\t", mTheEquipments[i]->mNumberOfEvents); + } + fprintf(fs, "\n"); + + fprintf(fs, "Average Event Size\t"); + for (int i = 0; i < Geo::MAXEQUIPMENTS; i++) { + fprintf(fs, "%f\t", mTheEquipments[i]->mEventSizeAverage); + } + fprintf(fs, "\n"); + + fprintf(fs, "Total pads\t"); + for (int i = 0; i < Geo::MAXEQUIPMENTS; i++) { + fprintf(fs, "%d\t", mTheEquipments[i]->mTotalPads); + } + fprintf(fs, "\n"); + + fprintf(fs, "Average pads per event\t"); + for (int i = 0; i < Geo::MAXEQUIPMENTS; i++) { + fprintf(fs, "%f\t", mTheEquipments[i]->mPadsPerEventAverage); + } + fprintf(fs, "\n"); + + fprintf(fs, "Busy Time average\t"); + for (int i = 0; i < Geo::MAXEQUIPMENTS; i++) { + fprintf(fs, "%e\t", mTheEquipments[i]->mBusyTimeAverage); + } + fprintf(fs, "\n"); + + fprintf(fs, "Event rate\t"); + for (int i = 0; i < Geo::MAXEQUIPMENTS; i++) { + fprintf(fs, "%e\t", 1 / mTheEquipments[i]->mBusyTimeAverage); + } + fprintf(fs, "\n"); + + fprintf(fs, "Number of Empty Events\t"); + for (int i = 0; i < Geo::MAXEQUIPMENTS; i++) { + fprintf(fs, "%d\t", mTheEquipments[i]->mNumberOfEmptyEvents); + } + fprintf(fs, "\n"); + + fprintf(fs, "-------------Errors--------------------\n"); + fprintf(fs, "Wrong events\t"); + for (int i = 0; i < Geo::MAXEQUIPMENTS; i++) { + fprintf(fs, "%d\t", mTheEquipments[i]->mNumberOfWrongEvents); + } + fprintf(fs, "\n"); + + for (int j = 0; j < MAXERRORS; j++) { + fprintf(fs, "%s\t", sErrorDescription[j]); + for (int i = 0; i < Geo::MAXEQUIPMENTS; i++) { + fprintf(fs, "%d\t", mTheEquipments[i]->mErrors[j]); + } + fprintf(fs, "\n"); + } + + fprintf(fs, "Total errors\t"); + for (int i = 0; i < Geo::MAXEQUIPMENTS; i++) { + fprintf(fs, "%d\t", mTheEquipments[i]->mTotalErrors); + } + fprintf(fs, "\n"); + + fclose(fs); + return; +} + +/// Gets a sized chunk from the stream. The stream pointers members are updated +/// @param[in] **streamPtr : the pointer to the memory buffer +/// @param[in] Size : the dimension of the chunk (words) +/// @returns True every time +/// @throw TH_WRONGBUFFERDIM Buffer length shorter then the requested +bool HmpidDecoder2::getBlockFromStream(uint32_t** streamPtr, uint32_t Size) +{ + *streamPtr = mActualStreamPtr; + mActualStreamPtr += Size; + if (mActualStreamPtr > mEndStreamPtr) { + // std::cout << " getBlockFromStream : StPtr=" << mActualStreamPtr << " EndPtr=" << mEndStreamPtr << " Len=" << Size << std::endl; + // std::cout << "Beccato " << std::endl; + throw TH_WRONGBUFFERDIM; + return (false); + } + return (true); +} + +/// Gets the Header Block from the stream. +/// @param[in] **streamPtr : the pointer to the memory buffer +/// @returns True if the header is read +bool HmpidDecoder2::getHeaderFromStream(uint32_t** streamPtr) +{ + return (getBlockFromStream(streamPtr, mRDHSize)); +} + +/// Gets a Word from the stream. +/// @param[in] *word : the buffer for the read word +/// @returns True if the operation end well +bool HmpidDecoder2::getWordFromStream(uint32_t* word) +{ + uint32_t* appo; + if (getBlockFromStream(&appo, 1)) { + *word = *mActualStreamPtr; + return (true); + } + return (false); +} + +/// Setup the Input Stream with a Memory Pointer +/// the buffer length is in byte, some controls are done +/// +/// @param[in] *Buffer : the pointer to Memory buffer +/// @param[in] BufferLen : the length of the buffer (bytes) +/// @returns True if the stream is set +/// @throws TH_NULLBUFFERPOINTER Thrown if the pointer to the buffer is NULL +/// @throws TH_BUFFEREMPTY Thrown if the buffer is empty +/// @throws TH_WRONGBUFFERDIM Thrown if the buffer len is less then one header +bool HmpidDecoder2::setUpStream(void* Buffer, long BufferLen) +{ + long wordsBufferLen = BufferLen / (sizeof(int32_t) / sizeof(char)); // Converts the len in words + if (Buffer == nullptr) { + if (mVerbose > 1) { + std::cout << "HMPID Decoder2 : [ERROR] " + << "Raw data buffer null Pointer ! " << std::endl; + } + throw TH_NULLBUFFERPOINTER; + } + if (wordsBufferLen == 0) { + if (mVerbose > 1) { + std::cout << "HMPID Decoder2 : [ERROR] " + << "Raw data buffer Empty ! " << std::endl; + } + throw TH_BUFFEREMPTY; + } + if (wordsBufferLen < 16) { + if (mVerbose > 1) { + std::cout << "HMPID Decoder2 : [ERROR] " + << "Raw data buffer less then the Header Dimension = " << wordsBufferLen << std::endl; + } + throw TH_WRONGBUFFERDIM; + } + + mActualStreamPtr = (uint32_t*)Buffer; // sets the pointer to the Buffer + mEndStreamPtr = ((uint32_t*)Buffer) + wordsBufferLen; //sets the End of buffer + mStartStreamPtr = ((uint32_t*)Buffer); + // std::cout << " setUpStrem : StPtr=" << mStartStreamPtr << " EndPtr=" << mEndStreamPtr << " Len=" << wordsBufferLen << std::endl; + return (true); +} diff --git a/Detectors/HMPID/simulation/CMakeLists.txt b/Detectors/HMPID/simulation/CMakeLists.txt index 181cb2ad1d2ed..2488f68c6accb 100644 --- a/Detectors/HMPID/simulation/CMakeLists.txt +++ b/Detectors/HMPID/simulation/CMakeLists.txt @@ -9,16 +9,19 @@ # submit itself to any jurisdiction. o2_add_library(HMPIDSimulation - SOURCES src/Detector.cxx src/HMPIDDigitizer.cxx src/HmpidCoder.cxx - SOURCES src/HmpidCoder2.cxx + SOURCES src/HMPIDDigitizer.cxx + src/Detector.cxx + src/HmpidCoder2.cxx PUBLIC_LINK_LIBRARIES O2::HMPIDBase + O2::SimulationDataFormat + O2::DataFormatsHMP + O2::DetectorsBase O2::DetectorsRaw ROOT::Physics) o2_target_root_dictionary(HMPIDSimulation - HEADERS include/HMPIDSimulation/Detector.h - include/HMPIDSimulation/HmpidCoder.h - include/HMPIDSimulation/HmpidCoder2.h + HEADERS include/HMPIDSimulation/HmpidCoder2.h + include/HMPIDSimulation/Detector.h include/HMPIDSimulation/HMPIDDigitizer.h) diff --git a/Detectors/HMPID/simulation/include/HMPIDSimulation/Detector.h b/Detectors/HMPID/simulation/include/HMPIDSimulation/Detector.h index 328478c6a5307..288db7bfc93fc 100644 --- a/Detectors/HMPID/simulation/include/HMPIDSimulation/Detector.h +++ b/Detectors/HMPID/simulation/include/HMPIDSimulation/Detector.h @@ -13,7 +13,7 @@ #include #include "DetectorsBase/Detector.h" -#include "HMPIDBase/Hit.h" +#include "DataFormatsHMP/Hit.h" class TGeoVolume; class TGeoHMatrix; @@ -28,7 +28,7 @@ class Detector : public o2::base::DetImpl Detector(Bool_t active = true); ~Detector() override = default; - std::vector* getHits(int iColl) const + std::vector* getHits(int iColl) const { if (iColl == 0) { return mHits; @@ -38,7 +38,7 @@ class Detector : public o2::base::DetImpl void InitializeO2Detector() override; bool ProcessHits(FairVolume* v) override; - HitType* AddHit(float x, float y, float z, float time, float energy, Int_t trackId, Int_t detId); + o2::hmpid::HitType* AddHit(float x, float y, float z, float time, float energy, Int_t trackId, Int_t detId); void GenFee(float qtot); Bool_t IsLostByFresnel(); float Fresnel(float ene, float pdoti, Bool_t pola); @@ -61,7 +61,7 @@ class Detector : public o2::base::DetImpl // copy constructor for CloneModule Detector(const Detector&); - std::vector* mHits = nullptr; ///!< Collection of HMPID hits + std::vector* mHits = nullptr; ///!< Collection of HMPID hits enum EMedia { kAir = 1, kRoha = 2, diff --git a/Detectors/HMPID/simulation/include/HMPIDSimulation/HMPIDDigitizer.h b/Detectors/HMPID/simulation/include/HMPIDSimulation/HMPIDDigitizer.h index 92643e54a56a4..9d32e3eef54f2 100644 --- a/Detectors/HMPID/simulation/include/HMPIDSimulation/HMPIDDigitizer.h +++ b/Detectors/HMPID/simulation/include/HMPIDSimulation/HMPIDDigitizer.h @@ -11,8 +11,8 @@ #ifndef DETECTORS_HMPID_SIMULATION_INCLUDE_HMPIDSIMULATION_HMPIDDIGITIZER_H_ #define DETECTORS_HMPID_SIMULATION_INCLUDE_HMPIDSIMULATION_HMPIDDIGITIZER_H_ -#include "HMPIDBase/Digit.h" -#include "HMPIDBase/Trigger.h" +#include "DataFormatsHMP/Digit.h" +#include "DataFormatsHMP/Trigger.h" #include "HMPIDSimulation/Detector.h" // for the hit #include "SimulationDataFormat/MCTruthContainer.h" #include "SimulationDataFormat/MCCompLabel.h" @@ -45,12 +45,12 @@ class HMPIDDigitizer // for the first trigger no busy check necessary mCurrentTriggerTime = timeNS; mReadoutCounter++; - Trigger::TimeNsToOrbitBc(mCurrentTriggerTime, mOrbit, mBc); + mBc = o2::InteractionRecord::ns2bc(mCurrentTriggerTime, mOrbit); return true; } else { if ((timeNS - mCurrentTriggerTime) > BUSYTIME) { mCurrentTriggerTime = timeNS; - Trigger::TimeNsToOrbitBc(mCurrentTriggerTime, mOrbit, mBc); + mBc = o2::InteractionRecord::ns2bc(mCurrentTriggerTime, mOrbit); mReadoutCounter++; return true; } else { diff --git a/Detectors/HMPID/simulation/include/HMPIDSimulation/HmpidCoder.h b/Detectors/HMPID/simulation/include/HMPIDSimulation/HmpidCoder.h deleted file mode 100644 index 3f872eeca1d35..0000000000000 --- a/Detectors/HMPID/simulation/include/HMPIDSimulation/HmpidCoder.h +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// -/// \file HmpidCoder.h -/// \author Antonio Franco - INFN Bari -/// \brief Base Class to code HMPID Raw Data file -/// - -#ifndef COMMON_HMPIDCODER_H_ -#define COMMON_HMPIDCODER_H_ - -#include -#include -#include -#include -#include -#include -#include - -#include "FairLogger.h" -#include "HMPIDBase/Geo.h" -#include "HMPIDBase/Digit.h" - -// ---- RDH 6 standard dimension ------- -#define RAWBLOCKDIMENSION_W 2048 -#define HEADERDIMENSION_W 16 -#define PAYLOADDIMENSION_W 2032 -#define PAYLOADMAXSPACE_W 2028 - -// ---- CHARGE CONSTANTS ----- -#define CHARGE_CONST 150 -#define CHARGE_RAND_MAX 400 - -namespace o2 -{ - -namespace hmpid -{ - -class HmpidCoder -{ - public: - int mVerbose; - int mNumberOfEquipments; - - private: - // The standard definition of HMPID equipments at P2 - const int mEqIds[Geo::MAXEQUIPMENTS] = {0, 1, 2, 3, 4, 5, 8, 9, 6, 7, 10, 11, 12, 13}; - const int mCruIds[Geo::MAXEQUIPMENTS] = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3}; - const int mLinkIds[Geo::MAXEQUIPMENTS] = {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 0, 1, 2}; - const int mFlpIds[Geo::MAXEQUIPMENTS] = {160, 160, 160, 160, 160, 160, 160, 160, 161, 161, 161, 161, 161, 161}; - - bool mRandomCharge; - bool mRandomOccupancy; - - int mOccupancyPercentage; - - int mPailoadBufferDimPerEquipment; - uint32_t* mPayloadBufferPtr; - uint32_t* mEventBufferPtr; - uint32_t* mEventBufferBasePtr; - int mEventSizePerEquipment[Geo::MAXEQUIPMENTS]; - uint32_t mPacketCounterPerEquipment[Geo::MAXEQUIPMENTS]; - bool mSkipEmptyEvents; - bool mFixedPacketLenght; - - std::string mFileName160; - std::string mFileName161; - FILE* mOutStream160; - FILE* mOutStream161; - - long mPadsCoded; - long mPacketsCoded; - - std::vector mDigits; - uint32_t mPreviousOrbit = 0; - uint16_t mPreviousBc = 0; - long mLastProcessedDigit = 0; - uint32_t* mPadMap; - - public: - HmpidCoder(int numOfEquipments, bool skipEmptyEvents = false, bool fixedPacketLenght = true); - virtual ~HmpidCoder(); - - void reset(); - void setVerbosity(int Level) - { - mVerbose = Level; - }; - int getVerbosity() - { - return (mVerbose); - }; - int getNumberOfEquipments() - { - return (mNumberOfEquipments); - }; - - void setChargeRandomize(bool isRandom) - { - mRandomCharge = isRandom; - }; - bool getChargeRandomize() - { - return (mRandomCharge); - }; - - void setOccupancyRandomize(bool isRandom) - { - mRandomOccupancy = isRandom; - }; - bool getOccupancyRandomize() - { - return (mRandomOccupancy); - }; - - void setOccupancy(int Occupancy) - { - mOccupancyPercentage = Occupancy; - }; - int getOccupancy() - { - return (mOccupancyPercentage); - }; - - int addDigitsChunk(std::vector& digits); - void codeDigitsChunk(bool flushBuffer = false); - void codeDigitsVector(std::vector& digits); - - void openOutputStream(const char* OutputFileName); - void closeOutputStream(); - - void codeRandomEvent(uint32_t orbit, uint16_t bc); - void codeTest(int Events, uint16_t charge); - - void dumpResults(); - - protected: - void createRandomPayloadPerEvent(); - void savePacket(int Flp, int packetSize); - int calculateNumberOfPads(); - void codeEventChunkDigits(std::vector& digits, bool flushVector = false); - - private: - void getEquipCoord(int Equi, uint32_t* CruId, uint32_t* LinkId); - int getEquipmentPadIndex(int eq, int col, int dil, int cha); - int writeHeader(uint32_t* Buffer, uint32_t WordsToRead, uint32_t PayloadWords, int Equip, uint32_t PackNum, uint32_t BCDI, uint32_t ORBIT, uint32_t PageNum); - void fillPadsMap(uint32_t* padMap); - void fillTheOutputBuffer(uint32_t* padMap); - void writePaginatedEvent(uint32_t orbit, uint16_t bc); -}; - -} // namespace hmpid -} // namespace o2 - -#endif /* COMMON_HMPIDCODER_H_ */ diff --git a/Detectors/HMPID/simulation/include/HMPIDSimulation/HmpidCoder2.h b/Detectors/HMPID/simulation/include/HMPIDSimulation/HmpidCoder2.h index 2f27cadb8d9d7..ed17afff72365 100644 --- a/Detectors/HMPID/simulation/include/HMPIDSimulation/HmpidCoder2.h +++ b/Detectors/HMPID/simulation/include/HMPIDSimulation/HmpidCoder2.h @@ -32,8 +32,7 @@ #include "FairLogger.h" #include "HMPIDBase/Geo.h" -#include "HMPIDBase/Digit.h" -#include "HMPIDBase/Trigger.h" +#include "DataFormatsHMP/Digit.h" // ---- RDH 6 standard dimension ------- #define RAWBLOCKDIMENSION_W 2048 @@ -114,8 +113,7 @@ class HmpidCoder2 void openOutputStream(const std::string& outputFileName, const std::string& fileFor); void closeOutputStream(); - void codeEventChunkDigits(std::vector& digits); - void codeEventChunkDigits(std::vector& digits, Trigger ir); + void codeEventChunkDigits(std::vector& digits, InteractionRecord ir); void dumpResults(const std::string& outputFileName); private: diff --git a/Detectors/HMPID/simulation/src/Detector.cxx b/Detectors/HMPID/simulation/src/Detector.cxx index 2e869c3cba6f7..19e1f182b693c 100644 --- a/Detectors/HMPID/simulation/src/Detector.cxx +++ b/Detectors/HMPID/simulation/src/Detector.cxx @@ -39,10 +39,10 @@ namespace o2 namespace hmpid { -Detector::Detector(Bool_t active) : o2::base::DetImpl("HMP", active), mHits(new std::vector) {} +Detector::Detector(Bool_t active) : o2::base::DetImpl("HMP", active), mHits(new std::vector) {} Detector::Detector(const Detector& other) : mSensitiveVolumes(other.mSensitiveVolumes), - mHits(new std::vector) {} + mHits(new std::vector) {} void Detector::InitializeO2Detector() { @@ -75,7 +75,7 @@ bool Detector::ProcessHits(FairVolume* v) tmpname.Remove(0, 4); Int_t idch = tmpname.Atoi(); //retrieve the chamber number Double_t xl, yl; - Param::Instance()->Mars2Lors(idch, x, xl, yl); //take LORS position + o2::hmpid::Param::instance()->mars2Lors(idch, x, xl, yl); //take LORS position AddHit(x[0], x[1], x[2], hitTime, etot, tid, idch); //HIT for photon, position at P, etot will be set to Q GenFee(etot); //generate feedback photons etot is modified in hit ctor to Q of hit stack->addHit(GetDetId()); @@ -113,7 +113,7 @@ bool Detector::ProcessHits(FairVolume* v) tmpname.Remove(0, 4); Int_t idch = tmpname.Atoi(); //retrieve the chamber number Double_t xl, yl; - Param::Instance()->Mars2Lors(idch, out, xl, yl); //take LORS position + o2::hmpid::Param::instance()->mars2Lors(idch, out, xl, yl); //take LORS position if (eloss > 0) { // HIT for MIP, position near anod plane, eloss will be set to Q AddHit(out[0], out[1], out[2], hitTime, eloss, tid, idch); @@ -132,7 +132,7 @@ bool Detector::ProcessHits(FairVolume* v) return false; } //********************************************************************************************************* -HitType* Detector::AddHit(float x, float y, float z, float time, float energy, Int_t trackId, Int_t detId) +o2::hmpid::HitType* Detector::AddHit(float x, float y, float z, float time, float energy, Int_t trackId, Int_t detId) { mHits->emplace_back(x, y, z, time, energy, trackId, detId); return &(mHits->back()); @@ -1133,16 +1133,13 @@ TGeoVolume* Detector::CradleBaseVolume(TGeoMedium* med, Double_t l[7], const cha { /* The trapezoid is build in the xy plane - 0 ________________ 1 / | \ / | \ / (0,0) \ / | \ 3 /___________|____________\ 2 - 01 is right shifted => shift is positive - //1: small base (0-1); 2: long base (3-2); //3: trapezoid height; 4: shift between the two bases; //5: height 6: height reduction; 7: z-reduction; diff --git a/Detectors/HMPID/simulation/src/HMPIDDigitizer.cxx b/Detectors/HMPID/simulation/src/HMPIDDigitizer.cxx index aff73f8c1ab37..b65273bc477e3 100644 --- a/Detectors/HMPID/simulation/src/HMPIDDigitizer.cxx +++ b/Detectors/HMPID/simulation/src/HMPIDDigitizer.cxx @@ -9,10 +9,8 @@ // or submit itself to any jurisdiction. #include "HMPIDSimulation/HMPIDDigitizer.h" -#include "HMPIDBase/Digit.h" -#include "HMPIDBase/Trigger.h" - -#include "Framework/Logger.h" +#include "DataFormatsHMP/Digit.h" +#include "DataFormatsHMP/Trigger.h" #include "Framework/Logger.h" @@ -68,14 +66,14 @@ void HMPIDDigitizer::process(std::vector const& hits, std::v int chamber, pc, px, py; float totalQ; // retrieves center pad and the total charge - Digit::getPadAndTotalCharge(hit, chamber, pc, px, py, totalQ); + o2::hmpid::Digit::getPadAndTotalCharge(hit, chamber, pc, px, py, totalQ); if (px < 0 || py < 0) { continue; } // determine which pads to loop over - std::array allpads; + std::array allpads; int counter = 0; for (int nx = -1; nx <= 1; ++nx) { for (int ny = -1; ny <= 1; ++ny) { @@ -83,7 +81,7 @@ void HMPIDDigitizer::process(std::vector const& hits, std::v LOG(INFO) << ">> Pad out the PhotoCathod boundary. Excluded :" << px << " " << py << " :" << nx << "," << ny; continue; } - allpads[counter] = Param::Abs(chamber, pc, px + nx, py + ny); + allpads[counter] = o2::hmpid::Digit::abs(chamber, pc, px + nx, py + ny); counter++; } } @@ -95,7 +93,7 @@ void HMPIDDigitizer::process(std::vector const& hits, std::v index = iter->second; } // auto index = mIndexForPad[pad]; - float fraction = Digit::getFractionalContributionForPad(hit, pad); + float fraction = o2::hmpid::Digit::getFractionalContributionForPad(hit, (int)pad); // LOG(INFO) << "FRACTION ON PAD " << pad << " IS " << fraction; if (index != -1) { // digit exists ... reuse @@ -119,7 +117,7 @@ void HMPIDDigitizer::process(std::vector const& hits, std::v } else { // create digit ... and register // mDigits.emplace_back(mCurrentTriggerTime, pad, totalQ * fraction); - mDigits.emplace_back(mBc, mOrbit, pad, totalQ * fraction); + mDigits.emplace_back(pad, totalQ * fraction); mIndexForPad[pad] = mDigits.size() - 1; mInvolvedPads.emplace_back(pad); diff --git a/Detectors/HMPID/simulation/src/HMPIDSimulationLinkDef.h b/Detectors/HMPID/simulation/src/HMPIDSimulationLinkDef.h index 866728f3baad5..6ebaf6c6eb617 100644 --- a/Detectors/HMPID/simulation/src/HMPIDSimulationLinkDef.h +++ b/Detectors/HMPID/simulation/src/HMPIDSimulationLinkDef.h @@ -17,7 +17,6 @@ #pragma link C++ class o2::hmpid::Detector + ; #pragma link C++ class o2::base::DetImpl < o2::hmpid::Detector> + ; #pragma link C++ class o2::hmpid::HMPIDDigitizer + ; -#pragma link C++ class o2::hmpid::HmpidCoder + ; #pragma link C++ class o2::hmpid::HmpidCoder2 + ; #endif diff --git a/Detectors/HMPID/simulation/src/HmpidCoder.cxx b/Detectors/HMPID/simulation/src/HmpidCoder.cxx deleted file mode 100644 index 676fea54b93d9..0000000000000 --- a/Detectors/HMPID/simulation/src/HmpidCoder.cxx +++ /dev/null @@ -1,442 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// -/// \file HmpidCoder.cxx -/// \author Antonio Franco - INFN Bari -/// \brief Base Class for coding HMPID Raw Data File -/// \version 1.0 -/// \date 24 set 2020 - -#include "HMPIDBase/Digit.h" -#include "HMPIDSimulation/HmpidCoder.h" - -using namespace o2::hmpid; - -HmpidCoder::HmpidCoder(int numOfEquipments, bool skipEmptyEvents, bool fixedPacketsLenght) -{ - - mNumberOfEquipments = numOfEquipments; - mSkipEmptyEvents = skipEmptyEvents; - mFixedPacketLenght = fixedPacketsLenght; - - mVerbose = 0; - mOccupancyPercentage = 0; - mRandomOccupancy = false; - mRandomCharge = false; - mOutStream160 = nullptr; - mOutStream161 = nullptr; - mFileName160 = ""; - mFileName161 = ""; - - mPailoadBufferDimPerEquipment = ((Geo::N_SEGMENTS * (Geo::N_COLXSEGMENT * (Geo::N_DILOGICS * (Geo::N_CHANNELS + 1) + 1) + 1)) + 10); - - for (int i = 0; i < Geo::MAXEQUIPMENTS; i++) { - mPacketCounterPerEquipment[i] = 0; - } - mPayloadBufferPtr = (uint32_t*)std::malloc(mNumberOfEquipments * sizeof(uint32_t) * mPailoadBufferDimPerEquipment); - mEventBufferBasePtr = (uint32_t*)std::malloc(sizeof(uint32_t) * RAWBLOCKDIMENSION_W); - mEventBufferPtr = mEventBufferBasePtr; - - mPadMap = (uint32_t*)std::malloc(sizeof(uint32_t) * Geo::N_HMPIDTOTALPADS); - // TODO: Add memory allocation error check - - reset(); -} - -HmpidCoder::~HmpidCoder() -{ - // TODO Auto-generated destructor stub - std::free(mPayloadBufferPtr); - std::free(mEventBufferBasePtr); - std::free(mPadMap); -} - -void HmpidCoder::reset() -{ - srand((unsigned)time(nullptr)); - mPadsCoded = 0; - mPacketsCoded = 0; - mDigits.clear(); - mPreviousOrbit = 0; - mPreviousBc = 0; - mLastProcessedDigit = 0; - - return; -} - -// ===================== Random production of Raw Files =================== -int HmpidCoder::calculateNumberOfPads() -{ - int occupancyPercentage = 0; - if (mRandomOccupancy) { - occupancyPercentage = rand() % 1000; - } else { - occupancyPercentage = mOccupancyPercentage; - } - return (occupancyPercentage * Geo::MAXEQUIPMENTS * Geo::N_EQUIPMENTTOTALPADS / 1000); -} - -void HmpidCoder::fillPadsMap(uint32_t* padMap) -{ - int numberOfpads = calculateNumberOfPads(); - int mo, yc, xr, eq, col, dil, cha; - for (int i = 0; i < numberOfpads; i++) { - mo = rand() % Geo::N_MODULES; - xr = rand() % Geo::N_XROWS; - yc = rand() % Geo::N_YCOLS; - Digit::Absolute2Equipment(mo, xr, yc, &eq, &col, &dil, &cha); - int index = getEquipmentPadIndex(eq, col, dil, cha); - if (padMap[index] == 0) { - if (mRandomCharge) { - padMap[index] = (rand() % CHARGE_RAND_MAX) + 50; - } else { - padMap[index] = CHARGE_CONST; - } - } else { - i--; - } - } - return; -} - -void HmpidCoder::createRandomPayloadPerEvent() -{ - memset(mPadMap, 0, sizeof(uint32_t) * Geo::N_HMPIDTOTALPADS); - - fillPadsMap(mPadMap); - fillTheOutputBuffer(mPadMap); - - return; -} - -void HmpidCoder::codeRandomEvent(uint32_t orbit, uint16_t bc) -{ - createRandomPayloadPerEvent(); - writePaginatedEvent(orbit, bc); - return; -} -// ===================== END of Random production of Raw Files =================== - -void HmpidCoder::getEquipCoord(int Equi, uint32_t* CruId, uint32_t* LinkId) -{ - for (int i = 0; i < Geo::MAXEQUIPMENTS; i++) { - if (mEqIds[i] == Equi) { - *CruId = mCruIds[i]; - *LinkId = mLinkIds[i]; - return; - } - } - *CruId = mCruIds[0]; - *LinkId = mLinkIds[0]; - return; -} - -constexpr int p1() { return (Geo::N_SEGMENTS * Geo::N_COLXSEGMENT * Geo::N_DILOGICS * Geo::N_CHANNELS); } -constexpr int p2() { return (Geo::N_DILOGICS * Geo::N_CHANNELS); } - -int HmpidCoder::getEquipmentPadIndex(int eq, int col, int dil, int cha) -{ - return (eq * p1() + col * p2() + dil * Geo::N_CHANNELS + cha); -} - -void HmpidCoder::fillTheOutputBuffer(uint32_t* padMap) -{ - uint32_t rowMarker, segMarker, eoeMarker, padWord; - uint32_t rowSize; - uint32_t ptr = 0; - int pads[Geo::MAXEQUIPMENTS]; - int padsCount; - int segSize; - - for (int i = 0; i < Geo::MAXEQUIPMENTS; i++) { - mEventSizePerEquipment[i] = 0; - } - - for (int eq = 0; eq < mNumberOfEquipments; eq++) { - int startPtr = ptr; - padsCount = 0; - for (int s = 1; s <= Geo::N_SEGMENTS; s++) { - segSize = 0; - for (int c = 1; c <= Geo::N_COLXSEGMENT; c++) { - - // ---- Pre calculate the size of each column - for (int j = 0; j < Geo::N_DILOGICS; j++) { - pads[j] = 0; - } - rowSize = 0; - for (int j = 0; j < Geo::N_DILOGICS; j++) { - for (int k = 0; k < Geo::N_CHANNELS; k++) { - int idx = getEquipmentPadIndex(eq, ((s - 1) * Geo::N_COLXSEGMENT + (c - 1)), j, k); - if (padMap[idx] > 0) { - pads[j]++; - rowSize++; - padsCount++; - } - } - } - rowSize += Geo::N_DILOGICS; - segSize += (rowSize + 1); - rowMarker = 0x000036A8 | ((rowSize << 16) & 0x03ff0000); - - // ---- fills the Payload Buffer - mPayloadBufferPtr[ptr++] = rowMarker; - int col = (s - 1) * Geo::N_COLXSEGMENT + c; - for (int d = 1; d <= Geo::N_DILOGICS; d++) { - for (int p = 0; p < Geo::N_CHANNELS; p++) { - int idx = getEquipmentPadIndex(eq, ((s - 1) * Geo::N_COLXSEGMENT + (c - 1)), (d - 1), p); - if (padMap[idx] > 0) { - padWord = ((col << 22) & 0x07c00000) | ((d << 18) & 0x003C0000) | ((p << 12) & 0x0003F000) | (padMap[idx] & 0x00000FFF); - mPayloadBufferPtr[ptr++] = padWord; - } - } - eoeMarker = 0x08000080 | ((col << 22) & 0x07c00000) | (d << 18 & 0x003C0000) | (pads[d - 1] & 0x0000007F); - mPayloadBufferPtr[ptr++] = eoeMarker; - } - } - segSize += 1; - segMarker = 0xAB000000 | ((segSize << 8) & 0x000fff00) | (s & 0x0000000F); - mPayloadBufferPtr[ptr++] = segMarker; - } - - if (mSkipEmptyEvents && padsCount == 0) { // Sets the lenght of Events - mEventSizePerEquipment[eq] = 0; - } else { - mEventSizePerEquipment[eq] = ptr - startPtr; - } - } - return; -} - -void HmpidCoder::writePaginatedEvent(uint32_t orbit, uint16_t bc) -{ - int nWordToRead; - int count; - int payloatPtr = 0; - if (orbit == 0 || bc == 0) { - std::cerr << "HmpidCoder [ERROR] : Bad Orbit/BCid number (ORBIT=" << orbit << " BCID=" << bc << ")" << std::endl; - return; - } - - for (int eq = 0; eq < mNumberOfEquipments; eq++) { - int EventSize = mEventSizePerEquipment[eq]; - if (EventSize == 0) { - continue; // Skips the Events sized with 0 - } - int EquipmentCounter = 0; - int numOfPages = EventSize / PAYLOADMAXSPACE_W + 1; - - for (uint32_t PageNum = 1; PageNum <= numOfPages; PageNum++) { - count = 0; - while (count < PAYLOADMAXSPACE_W && EquipmentCounter < EventSize) { - mEventBufferPtr[HEADERDIMENSION_W + count++] = mPayloadBufferPtr[payloatPtr++]; - EquipmentCounter++; - } - nWordToRead = count; - - int nWordsTail = (mFixedPacketLenght) ? PAYLOADDIMENSION_W : ((count / 8 + 1) * 8); - while (count < nWordsTail) { - mEventBufferPtr[HEADERDIMENSION_W + count++] = 0; - } - uint32_t PackNum = mPacketCounterPerEquipment[eq]++; - int PacketSize = writeHeader(mEventBufferPtr, nWordToRead, nWordsTail, mEqIds[eq], PackNum, bc, orbit, PageNum); - savePacket(mFlpIds[eq], PacketSize); - } - } - return; -} - -int HmpidCoder::writeHeader(uint32_t* Buffer, uint32_t WordsToRead, uint32_t PayloadWords, - int Equip, uint32_t PackNum, uint32_t BCDI, uint32_t ORBIT, uint32_t PageNum) -{ - uint32_t CruId, LinkId; - uint32_t TType = 0; - uint32_t HeStop = 0; - uint32_t FirmVers = 9; - uint32_t HeError = 0; - uint32_t Busy = 3000; - uint32_t PAR = 0; - - uint32_t MemSize = WordsToRead * sizeof(uint32_t) + HEADERDIMENSION_W * sizeof(uint32_t); - uint32_t OffsetNext = PayloadWords * sizeof(uint32_t) + HEADERDIMENSION_W * sizeof(uint32_t); - getEquipCoord(Equip, &CruId, &LinkId); - - // FEEID Header Size Header version - Buffer[0] = 0xFFF00000 | ((Equip & 0x0F) << 16) | 0x00004000 | 0x00000006; - // Priority System ID - Buffer[1] = 0x00000100 | 0x00000006; - // .....Memory Size HeOffsetNewPack; - Buffer[2] = (MemSize << 16) | (OffsetNext & 0x0000FFFF); - // DW CruId PacNum Link Num - Buffer[3] = 0x10000000 | ((CruId & 0x00FF) << 16) | ((PackNum & 0x0FF) << 8) | (LinkId & 0x0FF); - Buffer[4] = 0x00000FFF & BCDI; - Buffer[5] = ORBIT; - Buffer[6] = 0; - Buffer[7] = 0; - Buffer[8] = TType; - Buffer[9] = ((HeStop & 0x00ff0000) << 16) | (PageNum & 0x0000FFFF); - Buffer[10] = 0; - Buffer[11] = 0; - Buffer[12] = (Busy << 9) | ((HeError & 0x000001F0) << 4) | (FirmVers & 0x0000000f); - Buffer[13] = PAR; - Buffer[14] = 0xAAAA0001; - Buffer[15] = 0xAAAA0001; - return (OffsetNext); -} - -void HmpidCoder::codeDigitsChunk(bool flushBuffer) -{ - codeEventChunkDigits(mDigits, flushBuffer); - return; -} - -int HmpidCoder::addDigitsChunk(std::vector& digits) -{ - mDigits.insert(mDigits.end(), digits.begin(), digits.end()); - return (mDigits.size()); -} - -void HmpidCoder::codeDigitsVector(std::vector& digits) -{ - codeEventChunkDigits(digits, true); - return; -} - -void HmpidCoder::codeEventChunkDigits(std::vector& digits, bool flushVector) -{ - int eq, col, dil, cha, mo, x, y, idx; - uint32_t orbit = 0; - uint16_t bc = 0; - - int padsCount = 0; - int lastEventDigit = -1; - mLastProcessedDigit = -1; - - for (o2::hmpid::Digit d : digits) { - orbit = d.getOrbit(); - bc = d.getBC(); - lastEventDigit++; - - if (orbit != mPreviousOrbit || bc != mPreviousBc) { //the event is changed - if (mPreviousOrbit != 0 || mPreviousBc != 0) { // isn't the first ! - fillTheOutputBuffer(mPadMap); - writePaginatedEvent(mPreviousOrbit, mPreviousBc); - mLastProcessedDigit = lastEventDigit; - } - memset(mPadMap, 0, sizeof(uint32_t) * Geo::N_HMPIDTOTALPADS); // Update for the new event - mPreviousOrbit = orbit; - mPreviousBc = bc; - } - Digit::Pad2Equipment(d.getPadID(), &eq, &col, &dil, &cha); // From Digit to Hardware coords - eq = mEqIds[eq]; // converts the Equipment Id in Cru/Link position ref - idx = getEquipmentPadIndex(eq, col, dil, cha); // finally to the unique padmap index - - if (mPadMap[idx] != 0) { // We already have the pad set - std::cerr << "HmpidCoder [ERROR] : Duplicated DIGIT =" << d << " (" << eq << "," << col << "," << dil << "," << cha << ")" << std::endl; - } else { - mPadMap[idx] = d.getCharge(); - padsCount++; - } - } - mPreviousOrbit = 0; - mPreviousBc = 0; - mPadsCoded += padsCount; - - if (flushVector) { - fillTheOutputBuffer(mPadMap); // Finalize the last event - writePaginatedEvent(orbit, bc); - digits.clear(); - } else { - if (mLastProcessedDigit >= 0) { - digits.erase(digits.begin(), digits.begin() + mLastProcessedDigit); - } - } - memset(mPadMap, 0, sizeof(uint32_t) * Geo::N_HMPIDTOTALPADS); // Update for the new event - return; -} - -void HmpidCoder::codeTest(int Events, uint16_t charge) -{ - uint32_t orbit = 0; - uint16_t bc = 0; - - //uint32_t *mPadMap = (uint32_t *) std::malloc(sizeof(uint32_t) * Geo::N_HMPIDTOTALPADS); - int eq, col, dil, cha, mo, x, y, idx; - - for (int e = 0; e < Events; e++) { - orbit++; - bc++; - charge++; - for (eq = 0; eq < Geo::MAXEQUIPMENTS; eq++) { - for (col = 0; col < Geo::N_COLUMNS; col++) { - for (dil = 0; dil < Geo::N_DILOGICS; dil++) { - for (cha = 0; cha < Geo::N_CHANNELS; cha++) { - idx = getEquipmentPadIndex(eq, col, dil, cha); - mPadMap[idx] = charge; - } - } - } - } - fillTheOutputBuffer(mPadMap); - writePaginatedEvent(orbit, bc); - memset(mPadMap, 0, sizeof(uint32_t) * Geo::N_HMPIDTOTALPADS); - } - return; -} -// ====================== FILES management functions ====================== - -void HmpidCoder::savePacket(int Flp, int packetSize) -{ - mPacketsCoded++; - if (Flp == 160) { - fwrite(mEventBufferPtr, packetSize, sizeof(uint8_t), mOutStream160); - } else { - fwrite(mEventBufferPtr, packetSize, sizeof(uint8_t), mOutStream161); - } - return; -} - -/// @throws TH_CREATEFILE Thrown if Fails to create the file -void HmpidCoder::openOutputStream(const char* OutputFileName) -{ - char FileName[512]; - sprintf(FileName, "%s%d%s", OutputFileName, 160, ".dat"); - mOutStream160 = fopen(FileName, "wb"); - if (mOutStream160 == nullptr) { - LOG(ERROR) << "ERROR to open Output file " << FileName; - throw nullptr; - } - mFileName160 = FileName; - - sprintf(FileName, "%s%d%s", OutputFileName, 161, ".dat"); - mOutStream161 = fopen(FileName, "wb"); - if (mOutStream161 == nullptr) { - LOG(ERROR) << "ERROR to open Output file " << FileName; - throw nullptr; - } - mFileName161 = FileName; - return; -} - -void HmpidCoder::closeOutputStream() -{ - fclose(mOutStream160); - fclose(mOutStream161); - return; -} - -void HmpidCoder::dumpResults() -{ - std::cout << " **** HMPID RawFile Coder : results ****" << std::endl; - std::cout << " Created files : " << mFileName160 << " ," << mFileName161 << std::endl; - std::cout << " Number of Pads coded : " << mPadsCoded << std::endl; - std::cout << " Number of Packets written : " << mPacketsCoded << std::endl; - std::cout << " ----------------------------------------" << std::endl; -} diff --git a/Detectors/HMPID/simulation/src/HmpidCoder2.cxx b/Detectors/HMPID/simulation/src/HmpidCoder2.cxx index c1647e1db0423..ff8e88504eadb 100644 --- a/Detectors/HMPID/simulation/src/HmpidCoder2.cxx +++ b/Detectors/HMPID/simulation/src/HmpidCoder2.cxx @@ -25,7 +25,7 @@ #include "DetectorsRaw/RawFileWriter.h" #include "DataFormatsParameters/GRPObject.h" -#include "HMPIDBase/Digit.h" +#include "DataFormatsHMP/Digit.h" #include "HMPIDSimulation/HmpidCoder2.h" using namespace o2::raw; @@ -179,7 +179,15 @@ void HmpidCoder2::writePaginatedEvent(uint32_t orbit, uint16_t bc) int EventSize = mEventSizePerEquipment[eq]; LOG(DEBUG) << "writePaginatedEvent() Eq=" << eq << " Size:" << EventSize << " Pads:" << mEventPadsPerEquipment[eq] << " Orbit:" << orbit << " BC:" << bc; if (mEventPadsPerEquipment[eq] > 0 || !mSkipEmptyEvents) { // Skips the Events with 0 Pads - mWriter.addData(ReadOut::FeeId(eq), ReadOut::CruId(eq), ReadOut::LnkId(eq), 0, {bc, orbit}, gsl::span(reinterpret_cast(ptrStartEquipment), EventSize * sizeof(uint32_t))); + mWriter.addData(ReadOut::FeeId(eq), + ReadOut::CruId(eq), + ReadOut::LnkId(eq), + 0, + {bc, orbit}, + gsl::span(reinterpret_cast(ptrStartEquipment), + EventSize * sizeof(uint32_t)), + false, + (uint32_t)((mBusyTime << 9) | ((mHmpidErrorFlag & 0x01F) << 4) | (mHmpidFrwVersion & 0x0F))); // We fill the fields ! // TODO: we can fill the detector field with Simulated Data setDetectorSpecificFields(0.000001 * EventSize); @@ -190,23 +198,6 @@ void HmpidCoder2::writePaginatedEvent(uint32_t orbit, uint16_t bc) return; } -/// Analyze a Digits Vector and setup the PADs array -/// with the charge value, then fills the output buffer -/// and forward it to the RawWriter object -/// -/// NOTE: this version take the Trigger info from the first -/// digit in the vector. We ASSUME that the vector contains -/// one and only one event !!!! -/// @param[in] digits : the vector of Digit structures -void HmpidCoder2::codeEventChunkDigits(std::vector& digits) -{ - if (digits.size() == 0) { - return; // the vector is empty ! - } - codeEventChunkDigits(digits, Trigger{digits[0].getBC(), digits[0].getOrbit()}); - return; -} - /// Analyze a Digits Vector and setup the PADs array /// with the charge value, then fills the output buffer /// and forward it to the RawWriter object @@ -214,20 +205,20 @@ void HmpidCoder2::codeEventChunkDigits(std::vector& digits) /// NOTE: the vector could be empty! /// @param[in] digits : the vector of Digit structures /// @param[in] ir : the Interaction Record structure -void HmpidCoder2::codeEventChunkDigits(std::vector& digits, Trigger ir) +void HmpidCoder2::codeEventChunkDigits(std::vector& digits, InteractionRecord ir) { int eq, col, dil, cha, mo, x, y, idx; - uint32_t orbit = ir.getOrbit(); - uint16_t bc = ir.getBc(); + uint32_t orbit = ir.orbit; + uint16_t bc = ir.bc; int padsCount = 0; - LOG(INFO) << "Manage chunk Orbit :" << orbit << " BC:" << bc << " Digits size:" << digits.size(); + LOG(DEBUG) << "Manage chunk Orbit :" << orbit << " BC:" << bc << " Digits size:" << digits.size(); for (o2::hmpid::Digit d : digits) { - Digit::Pad2Equipment(d.getPadID(), &eq, &col, &dil, &cha); // From Digit to Hardware coords + Digit::pad2Equipment(d.getPadID(), &eq, &col, &dil, &cha); // From Digit to Hardware coords eq = ReadOut::FeeId(eq); // converts the Equipment Id in Cru/Link position ref idx = getEquipmentPadIndex(eq, col, dil, cha); // finally to the unique padmap index if (mPadMap[idx] != 0) { // We already have the pad set - LOG(WARNING) << "Duplicated DIGIT =" << d << " (" << eq << "," << col << "," << dil << "," << cha << ")"; + LOG(WARNING) << "Duplicated DIGIT =" << d << " (" << eq << "," << col << "," << dil << "," << cha << ")" << idx; } else { mPadMap[idx] = d.getCharge(); padsCount++; diff --git a/Detectors/HMPID/workflow/CMakeLists.txt b/Detectors/HMPID/workflow/CMakeLists.txt index db5b765a1ef98..c851f6ddbeb67 100644 --- a/Detectors/HMPID/workflow/CMakeLists.txt +++ b/Detectors/HMPID/workflow/CMakeLists.txt @@ -10,29 +10,34 @@ o2_add_library(HMPIDWorkflow SOURCES src/DataDecoderSpec.cxx - src/DigitReaderSpec.cxx - src/ClusterizerSpec.cxx - src/DumpDigitsSpec.cxx - src/ReadRawFileSpec.cxx - src/WriteRawFromDigitsSpec.cxx src/DigitsToRawSpec.cxx + src/DumpDigitsSpec.cxx src/PedestalsCalculationSpec.cxx + src/RawToDigitsSpec.cxx + src/ReadRawFileSpec.cxx + src/WriteRawFileSpec.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::CCDB O2::DPLUtils O2::DetectorsRaw O2::HMPIDBase + O2::DataFormatsHMP O2::HMPIDSimulation O2::HMPIDReconstruction) -o2_add_executable(recoworkflow +#o2_add_executable(recoworkflow +# COMPONENT_NAME hmpid +# SOURCES src/HMPIDRecoWorkflow.cxx +# PUBLIC_LINK_LIBRARIES O2::HMPIDWorkflow) + +o2_add_executable(read-raw-file-stream-workflow COMPONENT_NAME hmpid - SOURCES src/HMPIDRecoWorkflow.cxx + SOURCES src/read-raw-file-stream-workflow.cxx PUBLIC_LINK_LIBRARIES O2::HMPIDWorkflow) -o2_add_executable(read-raw-file-workflow +o2_add_executable(raw-to-pedestals-workflow COMPONENT_NAME hmpid - SOURCES src/read-raw-file-workflow.cxx + SOURCES src/raw-to-pedestals-workflow.cxx PUBLIC_LINK_LIBRARIES O2::HMPIDWorkflow) o2_add_executable(raw-to-digits-workflow @@ -40,28 +45,23 @@ o2_add_executable(raw-to-digits-workflow SOURCES src/raw-to-digits-workflow.cxx PUBLIC_LINK_LIBRARIES O2::HMPIDWorkflow) -o2_add_executable(write-raw-from-digits-workflow - COMPONENT_NAME hmpid - SOURCES src/write-raw-from-digits-workflow.cxx - PUBLIC_LINK_LIBRARIES O2::HMPIDWorkflow) - -o2_add_executable(dump-digits-workflow +o2_add_executable(raw-to-digits-stream-workflow COMPONENT_NAME hmpid - SOURCES src/dump-digits-workflow.cxx + SOURCES src/raw-to-digits-stream-workflow.cxx PUBLIC_LINK_LIBRARIES O2::HMPIDWorkflow) -o2_add_executable(write-root-from-digits-workflow +o2_add_executable(dump-digits-stream-workflow COMPONENT_NAME hmpid - SOURCES src/write-root-from-digits-workflow.cxx + SOURCES src/dump-digits-stream-workflow.cxx PUBLIC_LINK_LIBRARIES O2::HMPIDWorkflow) -o2_add_executable(raw-to-pedestals-workflow +o2_add_executable(digits-to-raw-workflow COMPONENT_NAME hmpid - SOURCES src/raw-to-pedestals-workflow.cxx + SOURCES src/digits-to-raw-workflow.cxx PUBLIC_LINK_LIBRARIES O2::HMPIDWorkflow) -o2_add_executable(digits-to-raw-workflow +o2_add_executable(digits-to-raw-stream-workflow COMPONENT_NAME hmpid - SOURCES src/digits-to-raw-workflow.cxx + SOURCES src/digits-to-raw-stream-workflow.cxx PUBLIC_LINK_LIBRARIES O2::HMPIDWorkflow) \ No newline at end of file diff --git a/Detectors/HMPID/workflow/README.md b/Detectors/HMPID/workflow/README.md index f45ca7138d8ce..d36c2b07b49bd 100644 --- a/Detectors/HMPID/workflow/README.md +++ b/Detectors/HMPID/workflow/README.md @@ -2,85 +2,90 @@ \page refHMPworkflow HMP workflow /doxy --> -# DPL workflows for the HMPID v.0.4 +# DPL workflows for the HMPID v.0.7 ## HMPID DPL processors -* `hmpid-read-raw-file` reads data from ReadOut Raw File and outputs a stream of RDH6 pages as HMP/RAWDATA stream -* `hmpid-raw-to-digits` decodes the input raw pages stream (HMP/RAWDATA) and produces a vector of o2::hmpid::Digits (HMP/DIGITS) -* `hmpid-write-raw-from-digits` codes input o2::hmpid::Digits vector (HMP/DIGITS) into the binary HMPID raw file -* `hmpid-dump-digits` dumps the input o2::hmpid::Digits vector (HMP/DIGITS) to the stdout or in a ASCII file +* `hmpid-raw-to-digits` reads data from ReadOut Raw File and outputs a ROOT formatted file (Reconstruction flow) +* `hmpid-digits-to-raw` reads digits data from a ROOT formatted file and produce a ReadOut Raw File (Simulation flow) +* `hmpid-read-raw-file-stream` reads data from ReadOut Raw File and outputs a stream of RDH6 pages as HMP/RAWDATA stream +* `hmpid-raw-to-digits-stream` decodes the input raw pages stream (HMP/RAWDATA) and produces two streams avector of o2::hmpid::Digits (HMP/DIGITS) and a o2::InteractionRecord (HMP/INTRECORD) +* `hmpid-digits-to-raw-stream` codes input o2::hmpid::Digits vector (HMP/DIGITS) and (HMP/INTRECORD) stream into the binary HMPID raw file +* `hmpid-dump-digits-stream` dumps the input o2::hmpid::Digits vector (HMP/DIGITS) and (HMP/INTRECORD) stream to the stdout or in an ASCII file +* `hmpid-raw-to-pedestals` reads data from ReadOut Raw File and outputs results of Pedestals calculation in ReadOut format and CCDB (Calibration flow) ### Workflow example -The input is a HMPID rawfile and after the decoding the result is a reconstructed rawfile. +Dumping the contents of a Raw file. ``` - o2-hmpid-read-raw-file-workflow --raw-file test_full_flp1.raw -b | o2-hmpid-raw-to-digits-workflow -b | o2-hmpid-write-raw-from-digits-workflow --out-file /tmp/pippo -b + o2-hmpid-read-raw-file-stream-workflow --raw-file test_full_flp1.raw -b | o2-hmpid-raw-to-digits-stream-workflow -b | o2-hmpid-dump-digits-stream-workflow --out-file /tmp/pippo.txt -b ``` -This reads the `test_full_flp1.raw` file and after the decodeing produce a couple of raw files in the /tmp/ folder that are prefixed with `pippo` +This reads the `test_full_flp1.raw` file and after the decoding, produce an ASCII file in the /tmp/ folder that contains the Events/Digits dump. -### o2-hmpid-read-raw-file-workflow +### o2-hmpid-read-raw-file-stream-workflow Reads data from ReadOut Raw File and outputs a stream of RDH6 pages as HMP/RAWDATA stream. Display all options ``` -o2-hmpid-read-raw-file-workflow --help full +o2-hmpid-read-raw-file-stream-workflow --help full ``` Data processor options: HMP-ReadRawFile: ``` ---raw-file arg Raw input file name + --raw-file arg Raw input file name + --print verbose output ``` -### o2-hmpid-raw-to-digits-workflow -Decodes the input raw pages stream (HMP/RAWDATA) and produces a vector of o2::hmpid::Digits (HMP/DIGITS). +### o2-hmpid-raw-to-digits-stream-workflow +Decodes the input raw pages stream (HMP/RAWDATA) and produces a vector of o2::hmpid::Digits (HMP/DIGITS) and a o2::InteractionRecord (HMP/INTRECORD). Display all options ``` -o2-hmpid-raw-to-digits-workflow --help full +o2-hmpid-raw-to-digits-stream-workflow --help full ``` Data processor options: HMP-DataDecoder: ``` --root-file arg (=/tmp/hmpRawDecodeResults) - Name of the Root file with the decoding - results. + Name of the Root file with the decoding + results. + --fast-decode Use the fast algorithm. (error 0.8% ``` -### o2-hmpid-write-raw-from-digits-workflow -Codes input o2::hmpid::Digits vector (HMP/DIGITS) into the binary HMPID raw file. +### o2-hmpid-digits-to-raw-stream-workflow +Codes input o2::hmpid::Digits vector (HMP/DIGITS) and (HMP/INTRECORD) stream into the binary HMPID raw file. Display all options ``` -o2-hmpid-write-raw-from-digits-workflow --help full +o2-hmpid-digits-to-raw-stream-workflow --help full ``` Data processor options: HMP-WriteRawFromDigits: ``` - --out-file arg (=hmpidRaw) name prefix of the two output files - --order-events order the events in ascending time + --out-file arg (=hmpidRaw) name of the output file + --order-events order the events time --skip-empty skip empty events --fixed-lenght fixed lenght packets = 8K bytes ``` -### o2-hmpid-dump-digits-workflow -Dumps the input o2::hmpid::Digits vector (HMP/DIGITS) to the stdout or in a ASCII file. +### o2-hmpid-dump-digits-stream-workflow +Dumps the input o2::hmpid::Digits vector (HMP/DIGITS) and (HMP/INTRECORD) stream to the stdout or in an ASCII file. Display all options ``` -o2-hmpid-dump-digits-workflow --help full +o2-hmpid-dump-digits-stream-workflow --help full ``` Data processor options: HMP-DigitsDump: @@ -91,27 +96,26 @@ Data processor options: HMP-DigitsDump: ``` -### o2-hmpid-write-root-from-digits-workflow -Write the digit stream into a root formatted file +### o2-hmpid-raw-to-digits-workflow +Write Raw File into a root formatted file ``` -o2-hmpid-write-root-from-digit-workflow --help full +o2-hmpid-raw-to-digits-workflow --help full ``` Data processor options: HMPDigitWriter: ``` - --outfile arg (=hmpiddigits.root) Name of the output file - --treename arg (=o2sim) Name of tree - --treetitle arg (=o2sim) Title of tree - --nevents arg (=-1) Number of events to execute - --terminate arg (=process) Terminate the 'process' or 'workflow' + --in-file arg (=hmpidRaw.raw) name of the input Raw file + --out-file arg (=hmpReco.root) name of the output file + --base-file arg (=hmpDecode) base name for statistical output file + --fast-decode Use the fast algorithm. (error 0.8%) ``` Example ``` -[O2Suite/latest-o2] ~/Downloads/provaRec $> o2-hmpid-read-raw-file-workflow --raw-file test_full_flp1.raw -b | o2-hmpid-raw-to-digits-workflow -b | o2-hmpid-write-root-from-digits-workflow -b +[O2Suite/latest-o2] ~/Downloads/provaRec $> o2-hmpid-raw-to-digits-workflow --in-file test_full_flp1.raw --out-file hmpidReco.root --base-file /tmp/pippo -b ``` ### o2-hmpid-digits-to-raw-workflow @@ -124,11 +128,12 @@ o2-hmpid-digits-to-raw-workflow Data processor options: HMP-WriteRawFromRootFile: ``` - --outdir arg (=./) base dir for output file - --outfile arg (=hmpReadOut) base name for output file - --file-for ingle file per: (all),flp,link + --outdir arg (=./) base dir for output file + --file-for arg (=all) single file per: all,flp,link + --outfile arg (=hmpid) base name for output file --in-file arg (=hmpiddigits.root) name of the input sim root file - --dump-digits out the digits file in /tmp/hmpDumpDigits.dat + --dump-digits out the digits file in + /tmp/hmpDumpDigits.dat --skip-empty skip empty events ``` @@ -137,13 +142,13 @@ Example ``` [O2Suite/latest-o2] ~/Downloads/provaRec $>o2-sim-serial -m HMP -n 20 -e TGeant4 -g pythia8hi [O2Suite/latest-o2] ~/Downloads/provaRec $>o2-sim-digitizer-workflow --onlyDet HMP -[O2Suite/latest-o2] ~/Downloads/provaRec $>o2-hmpid-digits-to-raw-workflow --in-file hmpiddigits.root --hmp-raw-outfile hmpRawFromRoot --dump-digits -b +[O2Suite/latest-o2] ~/Downloads/provaRec $>o2-hmpid-digits-to-raw-workflow --outdir ./ --in-file hmpiddigits.root --outfile hmpRawFromRoot --file-for all --dump-digits -b ``` in order to verify the write, the inverse decoding of raw file ``` -[O2Suite/latest-o2] ~/Downloads/provaRec $>o2-hmpid-read-raw-file-workflow --raw-file hmpRawFromRoot.raw -b | o2-hmpid-raw-to-digits-workflow -b | o2-hmpid-dump-digits-workflow --out-file /tmp/hmpDumpDigitsVerify.dat +[O2Suite/latest-o2] ~/Downloads/provaRec $>o2-hmpid-read-raw-file-stream-workflow --raw-file hmpRawFromRoot.raw -b | o2-hmpid-raw-to-digits-stream-workflow -b | o2-hmpid-dump-digits-stream-workflow --out-file /tmp/hmpDumpDigitsVerify.dat ``` @@ -168,12 +173,13 @@ Data processor options: HMP-DataDecoder: pedestals/threshold values --sigmacut arg (=4) Sigma values for the Thresholds calculation. + --fast-decode Use the fast algorithm. (error 0.8%) ``` Example ``` -o2-hmpid-read-raw-file-workflow --raw-file test_full_flp1.raw -b | o2-hmpid-raw-to-pedestals-workflow --sigmacut=2.5 --files-basepath /tmp/pippo -b --use-ccdb --pedestals-tag TEST3 +o2-hmpid-read-raw-file-stream-workflow --raw-file ../hmpidRaw160.raw -b | o2-hmpid-raw-to-pedestals-workflow --sigmacut=2.5 --files-basepath /tmp/pippo -b --use-ccdb --pedestals-tag TEST3 ``` this command produce in the ccdb a set of `TMatrixF` object one for each chamber diff --git a/Detectors/HMPID/workflow/include/HMPIDWorkflow/ClusterizerSpec.h b/Detectors/HMPID/workflow/include/HMPIDWorkflow/ClusterizerSpec.h_notused.h similarity index 100% rename from Detectors/HMPID/workflow/include/HMPIDWorkflow/ClusterizerSpec.h rename to Detectors/HMPID/workflow/include/HMPIDWorkflow/ClusterizerSpec.h_notused.h diff --git a/Detectors/HMPID/workflow/include/HMPIDWorkflow/DataDecoderSpec.h b/Detectors/HMPID/workflow/include/HMPIDWorkflow/DataDecoderSpec.h index ff9151ce28c46..db5b7c4525b74 100644 --- a/Detectors/HMPID/workflow/include/HMPIDWorkflow/DataDecoderSpec.h +++ b/Detectors/HMPID/workflow/include/HMPIDWorkflow/DataDecoderSpec.h @@ -15,7 +15,8 @@ #include "Framework/Task.h" #include "HMPIDBase/Common.h" -#include "HMPIDReconstruction/HmpidDecodeRawMem.h" +#include "HMPIDReconstruction/HmpidDecoder2.h" +//#include "HMPIDReconstruction/HmpidDecodeRawMem.h" namespace o2 { @@ -35,16 +36,16 @@ class DataDecoderTask : public framework::Task void endOfStream(framework::EndOfStreamContext& ec) override; private: - HmpidDecodeRawDigit* mDeco; + HmpidDecoder2* mDeco; long mTotalDigits; long mTotalFrames; std::string mRootStatFile; + bool mFastAlgorithm; ExecutionTimer mExTimer; }; o2::framework::DataProcessorSpec getDecodingSpec(std::string inputSpec = "TF:HMP/RAWDATA"); -//o2::framework::DataProcessorSpec getDecodingSpec(); } // end namespace hmpid } // end namespace o2 diff --git a/Detectors/HMPID/workflow/include/HMPIDWorkflow/DigitReaderSpec.h b/Detectors/HMPID/workflow/include/HMPIDWorkflow/DigitReaderSpec.h_notused.h similarity index 97% rename from Detectors/HMPID/workflow/include/HMPIDWorkflow/DigitReaderSpec.h rename to Detectors/HMPID/workflow/include/HMPIDWorkflow/DigitReaderSpec.h_notused.h index 147c7f22976c5..2133992a81e30 100644 --- a/Detectors/HMPID/workflow/include/HMPIDWorkflow/DigitReaderSpec.h +++ b/Detectors/HMPID/workflow/include/HMPIDWorkflow/DigitReaderSpec.h_notused.h @@ -16,7 +16,7 @@ #include "TFile.h" #include "Framework/DataProcessorSpec.h" #include "Framework/Task.h" -#include "HMPIDBase/Digit.h" +#include "DataFormatsHMP/Digit.h" #include "SimulationDataFormat/MCCompLabel.h" #include "SimulationDataFormat/MCTruthContainer.h" diff --git a/Detectors/HMPID/workflow/include/HMPIDWorkflow/DigitsToRawSpec.h b/Detectors/HMPID/workflow/include/HMPIDWorkflow/DigitsToRawSpec.h index 0a89cc1fa655e..59d3a48c8ed94 100644 --- a/Detectors/HMPID/workflow/include/HMPIDWorkflow/DigitsToRawSpec.h +++ b/Detectors/HMPID/workflow/include/HMPIDWorkflow/DigitsToRawSpec.h @@ -18,8 +18,8 @@ #include "DetectorsRaw/RawFileWriter.h" #include "HMPIDBase/Common.h" -#include "HMPIDBase/Digit.h" -#include "HMPIDBase/Trigger.h" +#include "DataFormatsHMP/Digit.h" +#include "DataFormatsHMP/Trigger.h" #include "HMPIDSimulation/HmpidCoder2.h" namespace o2 @@ -44,6 +44,7 @@ class DigitsToRawSpec : public framework::Task bool mSkipEmpty = false; bool mDumpDigits = false; std::string mFileFor = "all"; + bool mFastAlgorithm; std::vector mDigits; long mDigitsReceived; diff --git a/Detectors/HMPID/workflow/include/HMPIDWorkflow/PedestalsCalculationSpec.h b/Detectors/HMPID/workflow/include/HMPIDWorkflow/PedestalsCalculationSpec.h index d516068394d50..119624f0acd45 100644 --- a/Detectors/HMPID/workflow/include/HMPIDWorkflow/PedestalsCalculationSpec.h +++ b/Detectors/HMPID/workflow/include/HMPIDWorkflow/PedestalsCalculationSpec.h @@ -8,8 +8,8 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef DETECTORS_HMPID_WORKFLOW_INCLUDE_HMPIDWORKFLOW_DATADECODERSPEC_H_ -#define DETECTORS_HMPID_WORKFLOW_INCLUDE_HMPIDWORKFLOW_DATADECODERSPEC_H_ +#ifndef DETECTORS_HMPID_WORKFLOW_INCLUDE_HMPIDWORKFLOW_PEDESTALS_H_ +#define DETECTORS_HMPID_WORKFLOW_INCLUDE_HMPIDWORKFLOW_PEDESTALS_H_ #include "Framework/DataProcessorSpec.h" #include "Framework/Task.h" @@ -17,7 +17,7 @@ #include "CCDB/CcdbApi.h" #include "HMPIDBase/Common.h" -#include "HMPIDReconstruction/HmpidDecodeRawMem.h" +#include "HMPIDReconstruction/HmpidDecoder2.h" namespace o2 { @@ -40,7 +40,7 @@ class PedestalsCalculationTask : public framework::Task void recordPedInCcdb(); private: - HmpidDecodeRawMem* mDeco; + HmpidDecoder2* mDeco; long mTotalDigits; long mTotalFrames; std::string mPedestalsBasePath; @@ -50,6 +50,7 @@ class PedestalsCalculationTask : public framework::Task o2::ccdb::CcdbApi mDBapi; std::map mDbMetadata; // can be empty bool mWriteToDB; + bool mFastAlgorithm; ExecutionTimer mExTimer; }; diff --git a/Detectors/HMPID/workflow/include/HMPIDWorkflow/RawToDigitsSpec.h b/Detectors/HMPID/workflow/include/HMPIDWorkflow/RawToDigitsSpec.h new file mode 100644 index 0000000000000..c6e9ffb71809a --- /dev/null +++ b/Detectors/HMPID/workflow/include/HMPIDWorkflow/RawToDigitsSpec.h @@ -0,0 +1,70 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef STEER_DIGITIZERWORKFLOW_SRC_HMPDIGITWRITERSPEC_H_ +#define STEER_DIGITIZERWORKFLOW_SRC_HMPDIGITWRITERSPEC_H_ + +#include "Framework/DataProcessorSpec.h" +#include "DPLUtils/MakeRootTreeWriterSpec.h" +#include "Framework/Task.h" +#include "Framework/InputSpec.h" + +#include "DetectorsRaw/RawFileReader.h" +#include "CommonDataFormat/InteractionRecord.h" +#include "HMPIDBase/Common.h" +#include "DataFormatsHMP/Digit.h" +#include "DataFormatsHMP/Trigger.h" +#include "HMPIDReconstruction/HmpidDecoder2.h" +#include "SimulationDataFormat/MCTruthContainer.h" +#include "SimulationDataFormat/MCCompLabel.h" + +namespace o2 +{ +namespace hmpid +{ + +class RawToDigitsTask : public framework::Task +{ + public: + RawToDigitsTask() = default; + ~RawToDigitsTask() override = default; + void init(framework::InitContext& ic) final; + void run(framework::ProcessingContext& pc) final; + void endOfStream(framework::EndOfStreamContext& ec) override; + + private: + void writeResults(); + void parseNoTF(); + + // static bool eventEquipPadsComparision(o2::hmpid::Digit d1, o2::hmpid::Digit d2); + std::string mBaseFileName = ""; + std::string mInputRawFileName = ""; + std::string mOutRootFileName = ""; + + o2::raw::RawFileReader mReader; + o2::hmpid::HmpidDecoder2* mDecod; + std::vector mAccumulateDigits; + std::vector mEvents; + + long mDigitsReceived; + long mFramesReceived; + long mTotalDigits; + long mTotalFrames; + bool mFastAlgorithm; + + ExecutionTimer mExTimer; +}; + +o2::framework::DataProcessorSpec getRawToDigitsSpec(std::string inputSpec = "HMP/RAWDATA"); + +} // end namespace hmpid +} // end namespace o2 + +#endif /* STEER_DIGITIZERWORKFLOW_SRC_HMPIDDIGITWRITERSPEC_H_ */ diff --git a/Detectors/HMPID/workflow/include/HMPIDWorkflow/ReadRawFileSpec.h b/Detectors/HMPID/workflow/include/HMPIDWorkflow/ReadRawFileSpec.h index d6d69d1433562..2dfcb18c3f8a9 100644 --- a/Detectors/HMPID/workflow/include/HMPIDWorkflow/ReadRawFileSpec.h +++ b/Detectors/HMPID/workflow/include/HMPIDWorkflow/ReadRawFileSpec.h @@ -15,7 +15,7 @@ #include "Framework/Task.h" #include "HMPIDBase/Common.h" -#include "HMPIDBase/Digit.h" +#include "DataFormatsHMP/Digit.h" namespace o2 { diff --git a/Detectors/HMPID/workflow/include/HMPIDWorkflow/WriteRawFromDigitsSpec.h b/Detectors/HMPID/workflow/include/HMPIDWorkflow/WriteRawFileSpec.h similarity index 76% rename from Detectors/HMPID/workflow/include/HMPIDWorkflow/WriteRawFromDigitsSpec.h rename to Detectors/HMPID/workflow/include/HMPIDWorkflow/WriteRawFileSpec.h index b9fa00d63d4bc..d00b962008ed4 100644 --- a/Detectors/HMPID/workflow/include/HMPIDWorkflow/WriteRawFromDigitsSpec.h +++ b/Detectors/HMPID/workflow/include/HMPIDWorkflow/WriteRawFileSpec.h @@ -14,21 +14,22 @@ #include #include "Framework/DataProcessorSpec.h" #include "Framework/Task.h" - +#include "CommonDataFormat/InteractionRecord.h" #include "HMPIDBase/Common.h" -#include "HMPIDBase/Digit.h" -#include "HMPIDSimulation/HmpidCoder.h" +#include "DataFormatsHMP/Digit.h" +#include "DataFormatsHMP/Trigger.h" +#include "HMPIDSimulation/HmpidCoder2.h" namespace o2 { namespace hmpid { -class WriteRawFromDigitsTask : public framework::Task +class WriteRawFileTask : public framework::Task { public: - WriteRawFromDigitsTask() = default; - ~WriteRawFromDigitsTask() override = default; + WriteRawFileTask() = default; + ~WriteRawFileTask() override = default; void init(framework::InitContext& ic) final; void run(framework::ProcessingContext& pc) final; void endOfStream(framework::EndOfStreamContext& ec) override; @@ -37,18 +38,19 @@ class WriteRawFromDigitsTask : public framework::Task // static bool eventEquipPadsComparision(o2::hmpid::Digit d1, o2::hmpid::Digit d2); std::string mBaseFileName = ""; std::vector mDigits; + std::vector mEvents; bool mSkipEmpty = false; bool mFixedPacketLenght = false; bool mOrderTheEvents = true; long mDigitsReceived; long mFramesReceived; bool mIsTheStremClosed = false; - HmpidCoder* mCod; + HmpidCoder2* mCod; ExecutionTimer mExTimer; }; -o2::framework::DataProcessorSpec getWriteRawFromDigitsSpec(std::string inputSpec = "HMP/DIGITS"); +o2::framework::DataProcessorSpec getWriteRawFileSpec(std::string inputSpec = "HMP/DIGITS"); } // end namespace hmpid } // end namespace o2 diff --git a/Detectors/HMPID/workflow/include/HMPIDWorkflow/WriteRootFromDigitsSpec.h b/Detectors/HMPID/workflow/include/HMPIDWorkflow/WriteRootFromDigitsSpec.h deleted file mode 100644 index d10e07b1046f5..0000000000000 --- a/Detectors/HMPID/workflow/include/HMPIDWorkflow/WriteRootFromDigitsSpec.h +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -#ifndef STEER_DIGITIZERWORKFLOW_SRC_HMPDIGITWRITERSPEC_H_ -#define STEER_DIGITIZERWORKFLOW_SRC_HMPDIGITWRITERSPEC_H_ - -#include "Framework/DataProcessorSpec.h" -#include "DPLUtils/MakeRootTreeWriterSpec.h" -#include "Framework/InputSpec.h" -#include "HMPIDBase/Digit.h" -#include "HMPIDBase/Trigger.h" -#include "SimulationDataFormat/MCTruthContainer.h" -#include "SimulationDataFormat/MCCompLabel.h" - -namespace o2 -{ -namespace hmpid -{ - -template -using BranchDefinition = framework::MakeRootTreeWriterSpec::BranchDefinition; - -o2::framework::DataProcessorSpec getWriteRootFromDigitSpec(bool mctruth = false) -{ - using InputSpec = framework::InputSpec; - using MakeRootTreeWriterSpec = framework::MakeRootTreeWriterSpec; - return MakeRootTreeWriterSpec("HMPRootFileWriter", - "hmpiddigits.root", - "o2sim", - -1, - BranchDefinition>{InputSpec{"digitinput", "HMP", "DIGITS"}, "HMPDigit"}, - BranchDefinition>{InputSpec{"labelinput", "HMP", "DIGITLBL"}, "HMPDigitLabels", mctruth ? 1 : 0})(); -} - -} // end namespace hmpid -} // end namespace o2 - -#endif /* STEER_DIGITIZERWORKFLOW_SRC_HMPIDDIGITWRITERSPEC_H_ */ diff --git a/Detectors/HMPID/workflow/src/ClusterizerSpec.cxx b/Detectors/HMPID/workflow/src/ClusterizerSpec.cxx deleted file mode 100644 index 4ff75082477a8..0000000000000 --- a/Detectors/HMPID/workflow/src/ClusterizerSpec.cxx +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -#include "HMPIDWorkflow/ClusterizerSpec.h" -#include "Framework/ControlService.h" -#include "Framework/DataProcessorSpec.h" -#include "Framework/DataRefUtils.h" -#include "Framework/Lifetime.h" -#include "Framework/Task.h" -#include "Framework/Logger.h" -#include "Headers/DataHeader.h" -#include "HMPIDReconstruction/Clusterer.h" -#include "HMPIDBase/Cluster.h" -#include "SimulationDataFormat/MCTruthContainer.h" -#include "SimulationDataFormat/MCCompLabel.h" -#include // for make_shared, make_unique, unique_ptr -#include - -using namespace o2::framework; - -namespace o2 -{ -namespace hmpid -{ - -// use the tasking system of DPL -// just need to implement 2 special methods init + run (there is no need to inherit from anything) -class HMPIDDPLClustererTask -{ - using MCLabelContainer = o2::dataformats::MCTruthContainer; - bool mUseMC = true; - - public: - explicit HMPIDDPLClustererTask(bool useMC) : mUseMC(useMC) {} - void init(framework::InitContext& ic) - { - // nothing special to be set up - } - - void run(framework::ProcessingContext& pc) - { - static bool finished = false; - if (finished) { - return; - } - // get digit data - auto digits = pc.inputs().get*>("hmpiddigits"); - LOG(INFO) << "RECEIVED " << digits->size() << " DIGITS"; - auto labelvector = std::make_shared>(); - if (mUseMC) { - auto digitlabels = pc.inputs().get*>("hmpiddigitlabels"); - *labelvector.get() = std::move(*digitlabels); - mClusterer.setMCTruthContainer(&mClsLabels); - mClsLabels.clear(); - } - // call actual clustering routine - mClustersArray.clear(); - - if (mUseMC) { - mClusterer.process(*digits.get(), mClustersArray, labelvector.get()); - } else { - mClusterer.process(*digits.get(), mClustersArray, nullptr); - } - - LOG(INFO) << "HMPID CLUSTERER : TRANSFORMED " << digits->size() - << " DIGITS TO " << mClustersArray.size() << " CLUSTERS"; - - // send clusters - //pc.outputs().snapshot(Output{"HMP", "CLUSTERS", 0, Lifetime::Timeframe}, mClustersArray); - // send labels - if (mUseMC) { - //pc.outputs().snapshot(Output{"HMP", "CLUSTERSMCTR", 0, Lifetime::Timeframe}, mClsLabels); - } - - // declare done - finished = true; - pc.services().get().readyToQuit(false); - } - - private: - Clusterer mClusterer; ///< Cluster finder - - std::vector mClustersArray; ///< Array of clusters - MCLabelContainer mClsLabels; -}; - -o2::framework::DataProcessorSpec getHMPIDClusterizerSpec(bool useMC) -{ - std::vector inputs; - inputs.emplace_back("hmpiddigits", "HMP", "DIGITS", 0, Lifetime::Timeframe); - if (useMC) { - inputs.emplace_back("hmpiddigitlabels", "HMP", "DIGITSMCTR", 0, Lifetime::Timeframe); - } - return DataProcessorSpec{ - "HMPClusterer", - inputs, - // Outputs{OutputSpec{"HMP", "CLUSTERS", 0, Lifetime::Timeframe}, - // OutputSpec{"HMP", "CLUSTERSMCTR", 0, Lifetime::Timeframe}}, - Outputs{}, - AlgorithmSpec{adaptFromTask(useMC)}, - Options{/* for the moment no options */}}; -} - -} // end namespace hmpid -} // end namespace o2 diff --git a/Detectors/HMPID/workflow/src/DataDecoderSpec.cxx b/Detectors/HMPID/workflow/src/DataDecoderSpec.cxx index 106053f6a8d62..df09358548eeb 100644 --- a/Detectors/HMPID/workflow/src/DataDecoderSpec.cxx +++ b/Detectors/HMPID/workflow/src/DataDecoderSpec.cxx @@ -42,9 +42,10 @@ #include "DetectorsRaw/RDHUtils.h" #include "DPLUtils/DPLRawParser.h" -#include "HMPIDBase/Digit.h" +#include "DataFormatsHMP/Digit.h" +#include "DataFormatsHMP/Trigger.h" #include "HMPIDBase/Geo.h" -#include "HMPIDReconstruction/HmpidDecodeRawMem.h" +#include "HMPIDReconstruction/HmpidDecoder2.h" #include "HMPIDWorkflow/DataDecoderSpec.h" namespace o2 @@ -61,10 +62,11 @@ using RDH = o2::header::RDHAny; void DataDecoderTask::init(framework::InitContext& ic) { - LOG(INFO) << "[HMPID Data Decoder - Init] ( create Decoder for " << Geo::MAXEQUIPMENTS << " equipments !"; + LOG(INFO) << "[HMPID Data Decoder - Init] ( create Raw Stream Decoder for " << Geo::MAXEQUIPMENTS << " equipments !"; - mRootStatFile = ic.options().get("root-file"); - mDeco = new o2::hmpid::HmpidDecodeRawDigit(Geo::MAXEQUIPMENTS); + mRootStatFile = ic.options().get("result-file"); + mFastAlgorithm = ic.options().get("fast-decode"); + mDeco = new o2::hmpid::HmpidDecoder2(Geo::MAXEQUIPMENTS); mDeco->init(); mTotalDigits = 0; mTotalFrames = 0; @@ -81,7 +83,7 @@ void DataDecoderTask::run(framework::ProcessingContext& pc) // decodeReadout(pc); // decodeRawFile(pc); - mExTimer.elapseMes("... Decoding... Digits decoded = " + std::to_string(mTotalDigits) + " Frames received = " + std::to_string(mTotalFrames)); + mExTimer.elapseMes("Decoding... Digits decoded = " + std::to_string(mTotalDigits) + " Frames received = " + std::to_string(mTotalFrames)); return; } @@ -147,8 +149,6 @@ void DataDecoderTask::endOfStream(framework::EndOfStreamContext& ec) mExTimer.logMes("End the Decoding ! Digits decoded = " + std::to_string(mTotalDigits) + " Frames received = " + std::to_string(mTotalFrames)); mExTimer.stop(); - //ec.services().get().endOfStream(); - // ec.services().get().readyToQuit(framework::QuitRequest::Me); return; } //_________________________________________________________________________________________________ @@ -164,12 +164,23 @@ void DataDecoderTask::decodeTF(framework::ProcessingContext& pc) for (auto it = parser.begin(), end = parser.end(); it != end; ++it) { uint32_t* theBuffer = (uint32_t*)it.raw(); mDeco->setUpStream(theBuffer, it.size() + it.offset()); - mDeco->decodePageFast(&theBuffer); + try { + if (mFastAlgorithm) { + mDeco->decodePageFast(&theBuffer); + } else { + mDeco->decodePage(&theBuffer); + } + } catch (int e) { + // The stream end ! + LOG(DEBUG) << "End Page decoding !"; + } mTotalFrames++; } pc.outputs().snapshot(o2::framework::Output{"HMP", "DIGITS", 0, o2::framework::Lifetime::Timeframe}, mDeco->mDigits); + pc.outputs().snapshot(o2::framework::Output{"HMP", "INTRECORDS", 0, o2::framework::Lifetime::Timeframe}, mDeco->mIntReco); + mTotalDigits += mDeco->mDigits.size(); - LOG(INFO) << "Writing " << mDeco->mDigits.size() << "/" << mTotalDigits << " Digits ..."; + LOG(DEBUG) << "Writing Digitis=" << mDeco->mDigits.size() << "/" << mTotalDigits << " Frame=" << mTotalFrames << " IntRec " << mDeco->mIntReco; return; } @@ -188,7 +199,16 @@ void DataDecoderTask::decodeReadout(framework::ProcessingContext& pc) for (auto it = parser.begin(), end = parser.end(); it != end; ++it) { uint32_t* theBuffer = (uint32_t*)it.raw(); mDeco->setUpStream(theBuffer, it.size() + it.offset()); - mDeco->decodePageFast(&theBuffer); + try { + if (mFastAlgorithm) { + mDeco->decodePageFast(&theBuffer); + } else { + mDeco->decodePage(&theBuffer); + } + } catch (int e) { + // The stream end ! + LOG(DEBUG) << "End Page decoding !"; + } } return; } @@ -217,7 +237,16 @@ void DataDecoderTask::decodeRawFile(framework::ProcessingContext& pc) uint32_t* theBuffer = (uint32_t*)input.payload; int pagesize = header->payloadSize; mDeco->setUpStream(theBuffer, pagesize); - mDeco->decodePageFast(&theBuffer); + try { + if (mFastAlgorithm) { + mDeco->decodePageFast(&theBuffer); + } else { + mDeco->decodePage(&theBuffer); + } + } catch (int e) { + // The stream end ! + LOG(DEBUG) << "End Page decoding !"; + } } } return; @@ -235,13 +264,15 @@ o2::framework::DataProcessorSpec getDecodingSpec(std::string inputSpec) std::vector outputs; outputs.emplace_back("HMP", "DIGITS", 0, o2::framework::Lifetime::Timeframe); + outputs.emplace_back("HMP", "INTRECORDS", 0, o2::framework::Lifetime::Timeframe); return DataProcessorSpec{ - "HMP-DataDecoder", + "HMP-RawStreamDecoder", o2::framework::select(inputSpec.c_str()), outputs, AlgorithmSpec{adaptFromTask()}, - Options{{"root-file", VariantType::String, "/tmp/hmpRawDecodeResults", {"Name of the Root file with the decoding results."}}}}; + Options{{"result-file", VariantType::String, "/tmp/hmpRawDecodeResults", {"Base name of the decoding results files."}}, + {"fast-decode", VariantType::Bool, false, {"Use the fast algorithm. (error 0.8%)"}}}}; } } // namespace hmpid diff --git a/Detectors/HMPID/workflow/src/DigitReaderSpec.cxx b/Detectors/HMPID/workflow/src/DigitReaderSpec.cxx deleted file mode 100644 index 9d67bd722c1fe..0000000000000 --- a/Detectors/HMPID/workflow/src/DigitReaderSpec.cxx +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// @file DigitReader.cxx - -#include - -#include "HMPIDWorkflow/DigitReaderSpec.h" -#include "TTree.h" - -#include "Framework/ControlService.h" -#include "Framework/ConfigParamRegistry.h" -#include "DataFormatsParameters/GRPObject.h" -#include "Framework/Logger.h" - -using namespace o2::framework; -using namespace o2::hmpid; - -namespace o2 -{ -namespace hmpid -{ - -void DigitReader::init(InitContext& ic) -{ - LOG(INFO) << "Init Digit reader!"; - auto filename = ic.options().get("hmpid-digit-infile"); - mFile = std::make_unique(filename.c_str(), "OLD"); - if (!mFile->IsOpen()) { - LOG(ERROR) << "Cannot open the " << filename.c_str() << " file !"; - mState = 0; - return; - } - mState = 1; -} - -void DigitReader::run(ProcessingContext& pc) -{ - if (mState != 1) { - return; - } - - std::unique_ptr treeDig((TTree*)mFile->Get("o2sim")); - - if (treeDig) { - treeDig->SetBranchAddress("HMPDigit", &mPdigits); - - if (mUseMC) { - treeDig->SetBranchAddress("HMPDigitLabels", &mPlabels); - } - - treeDig->GetEntry(0); - - // add digits loaded in the output snapshot - pc.outputs().snapshot(Output{"HMP", "DIGITS", 0, Lifetime::Timeframe}, mDigits); - if (mUseMC) { - pc.outputs().snapshot(Output{"HMP", "DIGITSMCTR", 0, Lifetime::Timeframe}, mLabels); - } - } else { - LOG(ERROR) << "Cannot read the HMPID digits !"; - return; - } - - mState = 2; - pc.services().get().readyToQuit(false); -} - -DataProcessorSpec getDigitReaderSpec(bool useMC) -{ - std::vector outputs; - outputs.emplace_back("HMP", "DIGITS", 0, Lifetime::Timeframe); - if (useMC) { - outputs.emplace_back("HMP", "DIGITSMCTR", 0, Lifetime::Timeframe); - } - - return DataProcessorSpec{ - "hmpid-digit-reader", - Inputs{}, - outputs, - AlgorithmSpec{adaptFromTask(useMC)}, - Options{ - {"hmpid-digit-infile", VariantType::String, "hmpiddigits.root", {"Name of the input file"}}}}; -} - -} // namespace hmpid -} // namespace o2 diff --git a/Detectors/HMPID/workflow/src/DigitsToRawSpec.cxx b/Detectors/HMPID/workflow/src/DigitsToRawSpec.cxx index 59c2f3317dc47..991922fb45e25 100644 --- a/Detectors/HMPID/workflow/src/DigitsToRawSpec.cxx +++ b/Detectors/HMPID/workflow/src/DigitsToRawSpec.cxx @@ -12,7 +12,7 @@ /// \author Antonio Franco - INFN Bari /// \version 1.0 /// \date 01 feb 2021 -/// \brief Implementation of a data processor to produce raw files from a Digits stream +/// \brief Implementation of a data processor to produce raw files from a Digits/Event root file /// #include @@ -33,6 +33,8 @@ #include "Framework/Output.h" #include "Framework/Task.h" #include "Framework/WorkflowSpec.h" + +#include "FairLogger.h" // for LOG #include "Framework/Logger.h" #include "Framework/InputRecordWalker.h" #include "DataFormatsParameters/GRPObject.h" @@ -45,8 +47,8 @@ #include "DetectorsRaw/RDHUtils.h" #include "DPLUtils/DPLRawParser.h" -#include "HMPIDBase/Digit.h" -#include "HMPIDBase/Trigger.h" +#include "DataFormatsHMP/Digit.h" +#include "DataFormatsHMP/Trigger.h" #include "HMPIDBase/Geo.h" #include "HMPIDSimulation/HmpidCoder2.h" #include "HMPIDWorkflow/DigitsToRawSpec.h" @@ -106,23 +108,21 @@ void DigitsToRawSpec::readRootFile() { std::vector digitsPerEvent; std::vector digits, *hmpBCDataPtr = &digits; - std::vector interactions, *interactionsPtr = &interactions; + std::vector interactions, *interactionsPtr = &interactions; // Keeps the Interactions ! mDigTree->SetBranchAddress("InteractionRecords", &interactionsPtr); - LOG(DEBUG) << "Number of Interaction Records vectors in the simulation file :" << mDigTree->GetEntries(); + LOG(INFO) << "Number of Interaction Records vectors in the simulation file :" << mDigTree->GetEntries(); for (int ient = 0; ient < mDigTree->GetEntries(); ient++) { mDigTree->GetEntry(ient); LOG(INFO) << "Interactions records in simulation :" << interactions.size(); for (auto a : interactions) { - LOG(DEBUG) << a; + LOG(INFO) << a; } } - sort(interactions.begin(), interactions.end()); // Sort interactions in ascending order - int trigPointer = 0; mDigTree->SetBranchAddress("HMPDigit", &hmpBCDataPtr); - LOG(INFO) << "Number of entries in the simulation file :" << mDigTree->GetEntries(); + LOG(DEBUG) << "Number of entries in the simulation file :" << mDigTree->GetEntries(); // Loops in the Entry of ROOT Branch for (int ient = 0; ient < mDigTree->GetEntries(); ient++) { @@ -132,37 +132,35 @@ void DigitsToRawSpec::readRootFile() LOG(INFO) << "The Entry :" << ient << " doesn't have digits !"; continue; } - sort(digits.begin(), digits.end(), o2::hmpid::Digit::eventEquipPadsComp); - if (mDumpDigits) { // we wand the dump of digits ? + if (mDumpDigits) { // we want the dump of digits ? std::ofstream dumpfile; dumpfile.open("/tmp/hmpDumpDigits.dat"); - for (int i = 0; i < nbc; i++) { - dumpfile << digits[i] << std::endl; + for (o2::hmpid::Event e : interactions) { + dumpfile << "Event Orbit=" << e.getOrbit() << " BC=" << e.getBc() << std::endl; + for (int i = e.mFirstDigit; i <= e.mLastDigit; i++) { + dumpfile << digits.at(i) << std::endl; + } } dumpfile.close(); } // ready to operate LOG(INFO) << "For the entry = " << ient << " there are " << nbc << " DIGITS stored."; - for (int i = 0; i < nbc; i++) { - if (digits[i].getOrbit() != interactions[trigPointer].getOrbit() || digits[i].getBC() != interactions[trigPointer].getBc()) { - do { - mEventsReceived++; - LOG(DEBUG) << "Orbit =" << interactions[trigPointer].getOrbit() << " BC =" << interactions[trigPointer].getBc(); - mCod->codeEventChunkDigits(digitsPerEvent, interactions[trigPointer]); - digitsPerEvent.clear(); - trigPointer++; - } while ((digits[i].getOrbit() != interactions[trigPointer].getOrbit() || digits[i].getBC() != interactions[trigPointer].getBc()) && trigPointer < interactions.size()); - if (trigPointer == interactions.size()) { - LOG(WARNING) << "Digits without Interaction Record !!! ABORT"; - break; - } + for (o2::hmpid::Event e : interactions) { + mEventsReceived++; + digitsPerEvent.clear(); + for (int i = e.mFirstDigit; i <= e.mLastDigit; i++) { + digitsPerEvent.push_back(digits[i]); } - digitsPerEvent.push_back(digits[i]); + LOG(DEBUG) << "Orbit =" << e.getOrbit() << " BC =" << e.getBc() << " Digits =" << digitsPerEvent.size(); + if (digitsPerEvent.size() == 0) { + LOG(INFO) << "Empty event !" << e; + } + mCod->codeEventChunkDigits(digitsPerEvent, e.getIr()); + mDigitsReceived += digitsPerEvent.size(); + } + if (mDigitsReceived != digits.size()) { + LOG(WARNING) << "Digits outside the events defined !"; } - mEventsReceived++; - LOG(DEBUG) << "Orbit =" << interactions[trigPointer].getOrbit() << " BC =" << interactions[trigPointer].getBc(); - mCod->codeEventChunkDigits(digitsPerEvent, interactions[trigPointer]); - mDigitsReceived += nbc; } mExTimer.logMes("End of Write raw file Job !"); return; diff --git a/Detectors/HMPID/workflow/src/DumpDigitsSpec.cxx b/Detectors/HMPID/workflow/src/DumpDigitsSpec.cxx index 5de9d2a74b2c9..f2446b83b65e6 100644 --- a/Detectors/HMPID/workflow/src/DumpDigitsSpec.cxx +++ b/Detectors/HMPID/workflow/src/DumpDigitsSpec.cxx @@ -32,13 +32,14 @@ #include "Framework/Task.h" #include "Framework/WorkflowSpec.h" #include "Framework/Logger.h" +#include "Framework/DataRefUtils.h" #include "Framework/InputRecordWalker.h" #include "Headers/RAWDataHeader.h" #include "DetectorsRaw/RDHUtils.h" #include "DPLUtils/DPLRawParser.h" -#include "HMPIDBase/Digit.h" +#include "DataFormatsHMP/Digit.h" #include "HMPIDBase/Geo.h" #include "HMPIDWorkflow/DumpDigitsSpec.h" @@ -48,6 +49,7 @@ namespace hmpid { using namespace o2; +using namespace o2::header; using namespace o2::framework; using RDH = o2::header::RDHAny; @@ -67,10 +69,10 @@ void DumpDigitsTask::init(framework::InitContext& ic) } } if (mPrintDigits) { - std::cout << "--- HMP Digits : [Chamb,PhoCat,x,y]@(Orbit,BC)=Charge ---" << std::endl; + std::cout << "--- HMP Digits : [Chamb,PhoCat,x,y]=Charge ---" << std::endl; } if (mIsOutputOnFile) { - mOsFile << "--- HMP Digits : [Chamb,PhoCat,x,y]@(Orbit,BC)=Charge ---" << std::endl; + mOsFile << "--- HMP Digits : [Chamb,PhoCat,x,y]=Charge ---" << std::endl; } mOrbit = -1; mBc = -1; @@ -83,27 +85,34 @@ void DumpDigitsTask::init(framework::InitContext& ic) void DumpDigitsTask::run(framework::ProcessingContext& pc) { LOG(DEBUG) << "[HMPID Dump Digits - run() ] Enter Dump ..."; + for (auto const& ref : InputRecordWalker(pc.inputs())) { - std::vector digits = pc.inputs().get>(ref); - LOG(DEBUG) << "The size of the vector =" << digits.size(); - mDigitsReceived += digits.size(); - if (mPrintDigits) { - for (o2::hmpid::Digit Dig : digits) { - std::cout << Dig << std::endl; + if (DataRefUtils::match(ref, {"check", ConcreteDataTypeMatcher{gDataOriginHMP, "INTRECORDS"}})) { + o2::InteractionRecord intReco = pc.inputs().get(ref); + if (mPrintDigits) { + std::cout << "Trigger Event Orbit = " << intReco.orbit << " BC = " << intReco.bc << std::endl; + } + if (mIsOutputOnFile) { + mOsFile << "Trigger Event Orbit = " << intReco.orbit << " BC = " << intReco.bc << std::endl; } } - if (mIsOutputOnFile) { - for (o2::hmpid::Digit Dig : digits) { - mOsFile << Dig << std::endl; - if (Dig.getOrbit() != mOrbit || Dig.getBC() != mBc) { - mOrbit = Dig.getOrbit(); - mBc = Dig.getBC(); - // LOG(INFO) << "Event :" << mOrbit << " / " << mBc; + if (DataRefUtils::match(ref, {"check", ConcreteDataTypeMatcher{gDataOriginHMP, "DIGITS"}})) { + std::vector digits = pc.inputs().get>(ref); + LOG(DEBUG) << "The size of the vector =" << digits.size(); + mDigitsReceived += digits.size(); + if (mPrintDigits) { + for (o2::hmpid::Digit Dig : digits) { + std::cout << Dig << std::endl; + } + } + if (mIsOutputOnFile) { + for (o2::hmpid::Digit Dig : digits) { + mOsFile << Dig << std::endl; } } } } - mExTimer.elapseMes("... Dumping Digits received = " + std::to_string(mDigitsReceived)); + mExTimer.elapseMes("Dumping Digits received = " + std::to_string(mDigitsReceived)); return; } @@ -123,6 +132,7 @@ o2::framework::DataProcessorSpec getDumpDigitsSpec(std::string inputSpec) std::vector inputs; inputs.emplace_back("digits", o2::header::gDataOriginHMP, "DIGITS", 0, Lifetime::Timeframe); + inputs.emplace_back("intrecord", o2::header::gDataOriginHMP, "INTRECORDS", 0, Lifetime::Timeframe); std::vector outputs; diff --git a/Detectors/HMPID/workflow/src/HMPIDRecoWorkflow.cxx b/Detectors/HMPID/workflow/src/HMPIDRecoWorkflow.cxx deleted file mode 100644 index 58867296224ab..0000000000000 --- a/Detectors/HMPID/workflow/src/HMPIDRecoWorkflow.cxx +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -#include "HMPIDWorkflow/DigitReaderSpec.h" -#include "HMPIDWorkflow/ClusterizerSpec.h" -#include "CommonUtils/ConfigurableParam.h" -#include "Framework/WorkflowSpec.h" -#include "Framework/ConfigParamSpec.h" -// ------------------------------------------------------------------ - -using namespace o2::framework; - -// we need to add workflow options before including Framework/runDataProcessing -void customize(std::vector& workflowOptions) -{ - // option allowing to set parameters - workflowOptions.push_back(ConfigParamSpec{ - "disable-mc", VariantType::Bool, false, {"disable MC propagation even if available"}}); - workflowOptions.push_back(ConfigParamSpec{ - "disable-root-input", VariantType::Bool, false, {"disable root-files input readers"}}); - workflowOptions.push_back(ConfigParamSpec{ - "disable-root-output", VariantType::Bool, false, {"disable root-files output writers"}}); - std::string keyvaluehelp("Semicolon separated key=value strings ..."); - workflowOptions.push_back(ConfigParamSpec{"configKeyValues", VariantType::String, "", {keyvaluehelp}}); -} - -#include "Framework/runDataProcessing.h" // the main driver - -/// The standalone workflow executable for HMPID reconstruction workflow -/// - digit reader -/// - clusterer - -/// This function hooks up the the workflow specifications into the DPL driver. -WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) -{ - WorkflowSpec specs; - o2::conf::ConfigurableParam::updateFromString(cfgc.options().get("configKeyValues")); - auto useMC = !cfgc.options().get("disable-mc"); - auto disableRootInp = cfgc.options().get("disable-root-input"); - auto disableRootOut = cfgc.options().get("disable-root-output"); - - if (!disableRootInp) { - specs.emplace_back(o2::hmpid::getDigitReaderSpec(useMC)); - } - specs.emplace_back(o2::hmpid::getHMPIDClusterizerSpec(useMC)); - if (!disableRootOut) { - // RS Here cluster writer should go - } - - return std::move(specs); -} diff --git a/Detectors/HMPID/workflow/src/PedestalsCalculationSpec.cxx b/Detectors/HMPID/workflow/src/PedestalsCalculationSpec.cxx index 2a6baace87860..30d6a353e63cb 100644 --- a/Detectors/HMPID/workflow/src/PedestalsCalculationSpec.cxx +++ b/Detectors/HMPID/workflow/src/PedestalsCalculationSpec.cxx @@ -46,9 +46,10 @@ #include "DetectorsRaw/RDHUtils.h" #include "DPLUtils/DPLRawParser.h" -#include "HMPIDBase/Digit.h" +#include "DataFormatsHMP/Digit.h" +#include "DataFormatsHMP/Trigger.h" #include "HMPIDBase/Geo.h" -#include "HMPIDReconstruction/HmpidDecodeRawMem.h" +#include "HMPIDReconstruction/HmpidDecoder2.h" #include "HMPIDWorkflow/PedestalsCalculationSpec.h" namespace o2 @@ -67,7 +68,7 @@ void PedestalsCalculationTask::init(framework::InitContext& ic) LOG(INFO) << "[HMPID Pedestal Calculation - Init] ( create Decoder for " << Geo::MAXEQUIPMENTS << " equipments !"; - mDeco = new o2::hmpid::HmpidDecodeRawMem(Geo::MAXEQUIPMENTS); + mDeco = new o2::hmpid::HmpidDecoder2(Geo::MAXEQUIPMENTS); mDeco->init(); mTotalDigits = 0; mTotalFrames = 0; @@ -77,6 +78,7 @@ void PedestalsCalculationTask::init(framework::InitContext& ic) mPedestalTag = ic.options().get("pedestals-tag"); mDBapi.init(ic.options().get("ccdb-uri")); // or http://localhost:8080 for a local installation mWriteToDB = mDBapi.isHostReachable() ? true : false; + mFastAlgorithm = ic.options().get("fast-decode"); mExTimer.start(); return; @@ -228,8 +230,18 @@ void PedestalsCalculationTask::decodeTF(framework::ProcessingContext& pc) for (auto it = parser.begin(), end = parser.end(); it != end; ++it) { uint32_t* theBuffer = (uint32_t*)it.raw(); mDeco->setUpStream(theBuffer, it.size() + it.offset()); - mDeco->decodePageFast(&theBuffer); + try { + if (mFastAlgorithm) { + mDeco->decodePageFast(&theBuffer); + } else { + mDeco->decodePage(&theBuffer); + } + } catch (int e) { + // The stream end ! + LOG(DEBUG) << "End Fast Page decoding !"; + } mTotalFrames++; + mTotalDigits += mDeco->mDigits.size(); } return; } @@ -248,7 +260,16 @@ void PedestalsCalculationTask::decodeReadout(framework::ProcessingContext& pc) for (auto it = parser.begin(), end = parser.end(); it != end; ++it) { uint32_t* theBuffer = (uint32_t*)it.raw(); mDeco->setUpStream(theBuffer, it.size() + it.offset()); - mDeco->decodePageFast(&theBuffer); + try { + if (mFastAlgorithm) { + mDeco->decodePageFast(&theBuffer); + } else { + mDeco->decodePage(&theBuffer); + } + } catch (int e) { + // The stream end ! + LOG(DEBUG) << "End Fast Page decoding !"; + } } return; } @@ -276,7 +297,16 @@ void PedestalsCalculationTask::decodeRawFile(framework::ProcessingContext& pc) uint32_t* theBuffer = (uint32_t*)input.payload; int pagesize = header->payloadSize; mDeco->setUpStream(theBuffer, pagesize); - mDeco->decodePageFast(&theBuffer); + try { + if (mFastAlgorithm) { + mDeco->decodePageFast(&theBuffer); + } else { + mDeco->decodePage(&theBuffer); + } + } catch (int e) { + // The stream end ! + LOG(DEBUG) << "End Fast Page decoding !"; + } } } return; @@ -304,6 +334,7 @@ o2::framework::DataProcessorSpec getPedestalsCalculationSpec(std::string inputSp Options{{"files-basepath", VariantType::String, "/tmp/hmpPedThr", {"Name of the Base Path of Pedestals/Thresholds files."}}, {"use-ccdb", VariantType::Bool, false, {"Register the Pedestals/Threshold values into the CCDB"}}, {"ccdb-uri", VariantType::String, "http://ccdb-test.cern.ch:8080", {"URI for the CCDB access."}}, + {"fast-decode", VariantType::Bool, false, {"Use the fast algorithm. (error 0.8%)"}}, {"pedestals-tag", VariantType::String, "Latest", {"The tag applied to this set of pedestals/threshold values"}}, {"sigmacut", VariantType::Float, 4.0f, {"Sigma values for the Thresholds calculation."}}}}; } diff --git a/Detectors/HMPID/workflow/src/RawToDigitsSpec.cxx b/Detectors/HMPID/workflow/src/RawToDigitsSpec.cxx new file mode 100644 index 0000000000000..2e7e6d1bc4549 --- /dev/null +++ b/Detectors/HMPID/workflow/src/RawToDigitsSpec.cxx @@ -0,0 +1,396 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file RawToDigitsSpec.cxx +/// \author Antonio Franco - INFN Bari +/// \version 1.0 +/// \date 18 mar 2021 +/// \brief Implementation of a data processor to produce Digits from Raw files +/// + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "DPLUtils/DPLRawParser.h" +#include "DPLUtils/MakeRootTreeWriterSpec.h" + +#include "TTree.h" +#include "TFile.h" + +#include + +#include "Framework/InputSpec.h" +#include "Framework/CallbackService.h" +#include "Framework/ConfigParamRegistry.h" +#include "Framework/ControlService.h" +#include "Framework/DataProcessorSpec.h" +#include "Framework/Lifetime.h" +#include "Framework/Output.h" +#include "Framework/Task.h" +#include "Framework/WorkflowSpec.h" +#include "Framework/Logger.h" +#include "Framework/InputRecordWalker.h" + +#include "Headers/RAWDataHeader.h" +#include "DetectorsRaw/RawFileReader.h" +#include "DetectorsRaw/RDHUtils.h" + +#include "CommonDataFormat/InteractionRecord.h" + +#include "DataFormatsHMP/Digit.h" +#include "DataFormatsHMP/Trigger.h" +#include "HMPIDBase/Geo.h" +#include "HMPIDReconstruction/HmpidDecoder2.h" +#include "HMPIDWorkflow/RawToDigitsSpec.h" + +namespace o2 +{ +namespace hmpid +{ + +using namespace o2; +using namespace o2::framework; +using RDH = o2::header::RDHAny; +using namespace o2::hmpid::raw; + +//======================= +// Data decoder +void RawToDigitsTask::init(framework::InitContext& ic) +{ + LOG(INFO) << "[HMPID Write Root File From Raw Files - init()]"; + + // get line command options + mOutRootFileName = ic.options().get("out-file"); + mBaseFileName = ic.options().get("base-file"); + mInputRawFileName = ic.options().get("in-file"); + mFastAlgorithm = ic.options().get("fast-decode"); + mDigitsReceived = 0; + mFramesReceived = 0; + + mReader.setDefaultDataOrigin(o2::header::gDataOriginHMP); + mReader.setDefaultDataDescription(o2::header::gDataDescriptionRawData); + mReader.setDefaultReadoutCardType(o2::raw::RawFileReader::RORC); + mReader.addFile(mInputRawFileName); + mReader.init(); + + mDecod = new o2::hmpid::HmpidDecoder2(Geo::MAXEQUIPMENTS); + mDecod->init(); + + mExTimer.start(); + return; +} + +void RawToDigitsTask::run(framework::ProcessingContext& pc) +{ + bool isInLoop = true; + int tfID; + std::vector dataBuffer; // where to put extracted data + + if (mReader.getNTimeFrames() == 0) { + parseNoTF(); + isInLoop = false; + } + + while (isInLoop) { + tfID = mReader.getNextTFToRead(); + if (tfID >= mReader.getNTimeFrames()) { + LOG(INFO) << "nothing left to read after " << tfID << " TFs read"; + break; + } + for (int il = 0; il < mReader.getNLinks(); il++) { + auto& link = mReader.getLink(il); + LOG(INFO) << "Decoding link " << il; + auto sz = link.getNextTFSize(); // size in char needed for the next TF of this link + dataBuffer.resize(sz); + link.readNextTF(dataBuffer.data()); + link.rewindToTF(tfID); + int nhbf = link.getNHBFinTF(); + LOG(DEBUG) << " Number of HBF " << nhbf; + for (int ib = 0; ib < nhbf; ib++) { + auto zs = link.getNextHBFSize(); // size in char needed for the next TF of this link + dataBuffer.resize(zs); + link.readNextHBF(dataBuffer.data()); + // Parse + uint32_t* ptrBuffer = (uint32_t*)dataBuffer.data(); + uint32_t* ptrBufferEnd = ptrBuffer + zs / 4; + mDecod->setUpStream(ptrBuffer, zs); + while (ptrBuffer < ptrBufferEnd) { + try { + if (mFastAlgorithm) { + mDecod->decodePageFast(&ptrBuffer); + } else { + mDecod->decodePage(&ptrBuffer); + } + } catch (int e) { + // The stream end ! + LOG(DEBUG) << "End Page decoding !"; + } + int first = mAccumulateDigits.size(); + mAccumulateDigits.insert(mAccumulateDigits.end(), mDecod->mDigits.begin(), mDecod->mDigits.end()); + int last = mAccumulateDigits.size() - 1; + if (last >= first) { + mEvents.push_back(o2::hmpid::Event(mDecod->mIntReco, (uint32_t)first, (uint32_t)last)); + mDigitsReceived += mDecod->mDigits.size(); + } + mFramesReceived++; + LOG(DEBUG) << "run() Digits received =" << mDigitsReceived << " frames = " << mFramesReceived << " size=" << sz << " F-L " << first << "," << last << " " << mDecod->mIntReco; + mDecod->mDigits.clear(); + } + } + } + mReader.setNextTFToRead(++tfID); + } + mTotalDigits += mDigitsReceived; + mTotalFrames += mFramesReceived; + + mExTimer.logMes("End of Decoding ! Digits = " + std::to_string(mTotalDigits) + " Frames received = " + std::to_string(mTotalFrames)); + + writeResults(); + + // pc.services().get().endOfStream(); + pc.services().get().readyToQuit(framework::QuitRequest::Me); + mExTimer.stop(); + return; +} + +void RawToDigitsTask::endOfStream(framework::EndOfStreamContext& ec) +{ + mExTimer.logMes("Received an End Of Stream !"); + return; +} + +void RawToDigitsTask::parseNoTF() +{ + std::vector dataBuffer; // where to put extracted data + + for (int il = 0; il < mReader.getNLinks(); il++) { + auto& link = mReader.getLink(il); + LOG(INFO) << "Decoding link " << il; + auto sz = link.getNextTFSize(); // size in char needed for the next TF of this link + LOG(INFO) << " Size TF " << sz; + dataBuffer.resize(sz); + link.readNextTF(dataBuffer.data()); + + uint32_t* ptrBuffer = (uint32_t*)dataBuffer.data(); + uint32_t* ptrBufferEnd = ptrBuffer + sz / 4; + mDecod->setUpStream(ptrBuffer, sz); + while (ptrBuffer < ptrBufferEnd) { + try { + if (mFastAlgorithm) { + mDecod->decodePageFast(&ptrBuffer); + } else { + mDecod->decodePage(&ptrBuffer); + } + } catch (int e) { + // The stream end ! + LOG(DEBUG) << "End Fast Page decoding !"; + } + int first = mAccumulateDigits.size(); + mAccumulateDigits.insert(mAccumulateDigits.end(), mDecod->mDigits.begin(), mDecod->mDigits.end()); + int last = mAccumulateDigits.size() - 1; + if (last >= first) { + mEvents.push_back(o2::hmpid::Event(mDecod->mIntReco, (uint32_t)first, (uint32_t)last)); + mDigitsReceived += mDecod->mDigits.size(); + } + mFramesReceived++; + LOG(INFO) << "run() Digits received =" << mDigitsReceived << " frames = " << mFramesReceived << " size=" << sz << " F-L " << first << "," << last << " " << mDecod->mIntReco; + mDecod->mDigits.clear(); + } + } + return; +} + +void RawToDigitsTask::writeResults() +{ + int numEqui = mDecod->getNumberOfEquipments(); // Update the Stat for the Decoding + for (int i = 0; i < numEqui; i++) { + if (mDecod->mTheEquipments[i]->mNumberOfEvents > 0) { + mDecod->updateStatistics(mDecod->mTheEquipments[i]); + } + } + if (mEvents.size() == 0) { // check if no evwnts + LOG(INFO) << "There are not Event recorded ! Abort. "; + mExTimer.stop(); + return; + } + for (int i = mEvents.size() - 1; i >= 0; i--) { // remove events that are (0,0) trigger + if (mEvents[i].getTriggerID() == 0) { + mEvents.erase(mEvents.begin() + i); + } + } + sort(mEvents.begin(), mEvents.end()); // sort the events + mExTimer.logMes("Sorted Events = " + std::to_string(mEvents.size())); + + /* ------ ROOT file version 1 ---------- + o2::hmpid::Digit digit; + o2::hmpid::Event event; + TString filename; + TString tit; + + filename = TString::Format("%s", mOutRootFileName.c_str()); + LOG(INFO) << "Create the ROOT file " << filename.Data(); + TFile mfileOut(TString::Format("%s", filename.Data()), "RECREATE"); + TTree* theTree; + TBranch* theDigits; + TBranch* theEvents; + tit = TString::Format("HMPID Raw File Decoding"); + theTree = new TTree("o2hmp", tit); + + theDigits = theTree->Branch("HMPDigit", &digit, sizeof(o2::hmpid::Digit), 1); + theEvents = theTree->Branch("InteractionRecords", &event, sizeof(o2::hmpid::Event), 1); + + o2::hmpid::Event prevEvent = mEvents[0]; + uint32_t theFirstDigit = 0; + uint32_t theLastDigit = 0; + for (int e = 0; e < mEvents.size(); e++) { + LOG(INFO) << "Manage event " << mEvents[e]; + if (prevEvent != mEvents[e]) { // changes the event Flush It + event = prevEvent; + event.mFirstDigit = theFirstDigit; + event.mLastDigit = theLastDigit-1; + theEvents->Fill(); + theFirstDigit = theLastDigit; + prevEvent = mEvents[e]; + } + int first = mEvents[e].mFirstDigit; + int last = mEvents[e].mLastDigit; + for(int idx = first; idx <= last; idx++) { + digit = mAccumulateDigits[idx]; + theDigits->Fill(); + theLastDigit++; + } + } + event = prevEvent; + event.mFirstDigit = theFirstDigit; + event.mLastDigit = theLastDigit-1; + theEvents->Fill(); + theTree->Write(); + mfileOut.Close(); + -------------------------- */ + + // ---------- ROOT file version 2 --------------- + TString filename; + TString tit; + + std::vector digitVec; + std::vector eventVec; + + filename = TString::Format("%s", mOutRootFileName.c_str()); + LOG(INFO) << "Create the ROOT file " << filename.Data(); + TFile mfileOut(TString::Format("%s", filename.Data()), "RECREATE"); + tit = TString::Format("HMPID Raw File Decoding"); + TTree* theTree = new TTree("o2hmp", tit); + + theTree->Branch("InteractionRecords", &eventVec); + theTree->Branch("HMPIDDigits", &digitVec); + + // builds the two arranged vectors of objects + o2::hmpid::Event prevEvent = mEvents[0]; + uint32_t theFirstDigit = 0; + uint32_t theLastDigit = 0; + for (int e = 0; e < mEvents.size(); e++) { + LOG(DEBUG) << "Manage event " << mEvents[e]; + if (prevEvent != mEvents[e]) { // changes the event Flush It + eventVec.push_back(o2::hmpid::Event(o2::InteractionRecord(prevEvent.getBc(), prevEvent.getOrbit()), theFirstDigit, theLastDigit - 1)); + theFirstDigit = theLastDigit; + prevEvent = mEvents[e]; + } + int first = mEvents[e].mFirstDigit; + int last = mEvents[e].mLastDigit; + for (int idx = first; idx <= last; idx++) { + digitVec.push_back(mAccumulateDigits[idx]); + theLastDigit++; + } + } + eventVec.push_back(o2::hmpid::Event(o2::InteractionRecord(prevEvent.getBc(), prevEvent.getOrbit()), theFirstDigit, theLastDigit - 1)); + theTree->Fill(); + theTree->Write(); + mfileOut.Close(); + mExTimer.logMes("Register Tree ! "); + + // ---------- Records the statistics ----------------- + float avgEventSize; //[o2::hmpid::Geo::MAXEQUIPMENTS]; + float avgBusyTime; //[o2::hmpid::Geo::MAXEQUIPMENTS]; + float numOfSamples; //[o2::hmpid::Geo::N_MODULES][o2::hmpid::Geo::N_YCOLS][o2::hmpid::Geo::N_XROWS]; + float sumOfCharges; //[o2::hmpid::Geo::N_MODULES][o2::hmpid::Geo::N_YCOLS][o2::hmpid::Geo::N_XROWS]; + float squareOfCharges; //[o2::hmpid::Geo::N_MODULES][o2::hmpid::Geo::N_YCOLS][o2::hmpid::Geo::N_XROWS]; + float xb; + float yb; + + filename = TString::Format("%s_stat.root", mBaseFileName.c_str()); + LOG(INFO) << "Create the ROOT file " << filename.Data(); + TFile mfileOutStat(TString::Format("%s", filename.Data()), "RECREATE"); + TTree* theObj[Geo::N_MODULES + 1]; + for (int i = 0; i < Geo::N_MODULES; i++) { // Create the TTree array + tit = TString::Format("HMPID Data Decoding Statistic results Mod=%d", i); + theObj[i] = new TTree("o2hmp", tit); + theObj[i]->Branch("x", &xb, "s"); + theObj[i]->Branch("y", &yb, "s"); + theObj[i]->Branch("Samples", &numOfSamples, "i"); + theObj[i]->Branch("Sum_of_charges", &sumOfCharges, "l"); + theObj[i]->Branch("Sum_of_square", &squareOfCharges, "l"); + } + theObj[Geo::N_MODULES] = new TTree("o2hmp", "HMPID Data Decoding Statistic results"); + theObj[Geo::N_MODULES]->Branch("Average_Event_Size", &avgEventSize, "F"); + theObj[Geo::N_MODULES]->Branch("Average_Busy_Time", &avgBusyTime, "F"); + + char summaryFileName[254]; + sprintf(summaryFileName, "%s_stat.txt", mBaseFileName.c_str()); + mDecod->writeSummaryFile(summaryFileName); + for (int e = 0; e < numEqui; e++) { + avgEventSize = mDecod->getAverageEventSize(e); + avgBusyTime = mDecod->getAverageBusyTime(e); + theObj[Geo::N_MODULES]->Fill(); + } + for (int m = 0; m < o2::hmpid::Geo::N_MODULES; m++) { + for (int y = 0; y < o2::hmpid::Geo::N_YCOLS; y++) { + for (int x = 0; x < o2::hmpid::Geo::N_XROWS; x++) { + xb = x; + yb = y; + numOfSamples = mDecod->getPadSamples(m, x, y); + sumOfCharges = mDecod->getPadSum(m, x, y); + squareOfCharges = mDecod->getPadSquares(m, x, y); + theObj[m]->Fill(); + } + } + } + for (int i = 0; i <= Geo::N_MODULES; i++) { + theObj[i]->Write(); + } + + mExTimer.logMes("End storing results ! Digits = " + std::to_string(mTotalDigits) + " Frames received = " + std::to_string(mTotalFrames)); + return; +} + +//_________________________________________________________________________________________________ +o2::framework::DataProcessorSpec getRawToDigitsSpec(std::string inputSpec) +{ + std::vector inputs; + std::vector outputs; + + return DataProcessorSpec{ + "HMP-RawToDigits", + inputs, + outputs, + AlgorithmSpec{adaptFromTask()}, + Options{{"in-file", VariantType::String, "hmpidRaw.raw", {"name of the input Raw file"}}, + {"fast-decode", VariantType::Bool, false, {"Use the fast algorithm. (error 0.8%)"}}, + {"out-file", VariantType::String, "hmpReco.root", {"name of the output file"}}, + {"base-file", VariantType::String, "hmpDecode", {"base name for statistical output file"}}}}; +} + +} // namespace hmpid +} // end namespace o2 diff --git a/Detectors/HMPID/workflow/src/ReadRawFileSpec.cxx b/Detectors/HMPID/workflow/src/ReadRawFileSpec.cxx index 970cf419d3448..2cef42fe076f6 100644 --- a/Detectors/HMPID/workflow/src/ReadRawFileSpec.cxx +++ b/Detectors/HMPID/workflow/src/ReadRawFileSpec.cxx @@ -12,7 +12,7 @@ /// \author Antonio Franco - INFN Bari /// \version 1.0 /// \date 01 feb 2021 -/// \brief Implementation of a data processor to read a raw file and produce Digits stream +/// \brief Implementation of a data processor to read a raw file and produce Raw Pages stream /// #include diff --git a/Detectors/HMPID/workflow/src/WriteRawFileSpec.cxx b/Detectors/HMPID/workflow/src/WriteRawFileSpec.cxx new file mode 100644 index 0000000000000..ea3419ef33f58 --- /dev/null +++ b/Detectors/HMPID/workflow/src/WriteRawFileSpec.cxx @@ -0,0 +1,169 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file WriteRawFileSpec.cxx +/// \author Antonio Franco - INFN Bari +/// \version 1.0 +/// \date 01 feb 2021 +/// \brief Implementation of a data processor to produce raw files from a Digits stream +/// + +#include "../include/HMPIDWorkflow/WriteRawFileSpec.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Framework/CallbackService.h" +#include "Framework/ConfigParamRegistry.h" +#include "Framework/ControlService.h" +#include "Framework/DataProcessorSpec.h" +#include "Framework/Lifetime.h" +#include "Framework/Output.h" +#include "Framework/Task.h" +#include "Framework/WorkflowSpec.h" +#include "Framework/Logger.h" +#include "Framework/DataRefUtils.h" +#include "Framework/InputRecordWalker.h" + +#include "Headers/RAWDataHeader.h" +#include "DetectorsRaw/RDHUtils.h" +#include "DPLUtils/DPLRawParser.h" + +#include "CommonDataFormat/InteractionRecord.h" + +#include "DataFormatsHMP/Digit.h" +#include "DataFormatsHMP/Trigger.h" +#include "HMPIDBase/Geo.h" +#include "HMPIDSimulation/HmpidCoder2.h" + +namespace o2 +{ +namespace hmpid +{ + +using namespace o2; +using namespace o2::header; +using namespace o2::framework; +using RDH = o2::header::RDHAny; + +//======================= +// Data decoder +void WriteRawFileTask::init(framework::InitContext& ic) +{ + LOG(INFO) << "[HMPID Write Raw File From Digits vector - init()]"; + mBaseFileName = ic.options().get("out-file"); + mSkipEmpty = ic.options().get("skip-empty"); + mFixedPacketLenght = ic.options().get("fixed-lenght"); + mOrderTheEvents = ic.options().get("order-events"); + mDigitsReceived = 0; + mFramesReceived = 0; + + mCod = new HmpidCoder2(Geo::MAXEQUIPMENTS); + mCod->setSkipEmptyEvents(mSkipEmpty); + mCod->openOutputStream(mBaseFileName.c_str(), "all"); + + mExTimer.start(); + return; +} + +void WriteRawFileTask::run(framework::ProcessingContext& pc) +{ + o2::InteractionRecord intReco; + std::vector digits; + + for (auto const& ref : InputRecordWalker(pc.inputs())) { + if (DataRefUtils::match(ref, {"check", ConcreteDataTypeMatcher{gDataOriginHMP, "INTRECORDS"}})) { + intReco = pc.inputs().get(ref); + } + if (DataRefUtils::match(ref, {"check", ConcreteDataTypeMatcher{gDataOriginHMP, "DIGITS"}})) { + digits = pc.inputs().get>(ref); + LOG(DEBUG) << "The size of the vector =" << digits.size(); + } + } + + if (mOrderTheEvents) { + int first = mDigits.size(); + mDigits.insert(mDigits.end(), digits.begin(), digits.end()); + int last = mDigits.size() - 1; + mEvents.push_back({intReco, first, last}); + } else { + mCod->codeEventChunkDigits(digits, intReco); + } + mDigitsReceived += digits.size(); + mFramesReceived++; + LOG(DEBUG) << "run() Digits received =" << mDigitsReceived << " frames = " << mFramesReceived; + + mExTimer.elapseMes("Write raw file ... Digits received = " + std::to_string(mDigitsReceived) + " Frames received = " + std::to_string(mFramesReceived)); + return; +} + +void WriteRawFileTask::endOfStream(framework::EndOfStreamContext& ec) +{ + std::vector dig; + + mExTimer.logMes("Received an End Of Stream !"); + if (mOrderTheEvents && mEvents.size() > 0) { + sort(mEvents.begin(), mEvents.end()); + uint32_t orbit = mEvents[0].getOrbit(); + uint16_t bc = mEvents[0].getBc(); + for (int idx = 0; idx < mEvents.size(); idx++) { + if (mSkipEmpty && (mEvents[idx].mLastDigit < mEvents[idx].mFirstDigit || mEvents[idx].getOrbit() == 0)) { + continue; + } + if (mEvents[idx].getOrbit() != orbit || mEvents[idx].getBc() != bc) { + mCod->codeEventChunkDigits(dig, o2::InteractionRecord(bc, orbit)); + LOG(INFO) << " Event :" << idx << " orbit=" << orbit << " bc=" << bc << " Digits:" << dig.size(); + dig.clear(); + orbit = mEvents[idx].getOrbit(); + bc = mEvents[idx].getBc(); + } + for (int i = mEvents[idx].mFirstDigit; i <= mEvents[idx].mLastDigit; i++) { + dig.push_back(mDigits[i]); + } + } + mCod->codeEventChunkDigits(dig, o2::InteractionRecord(bc, orbit)); + LOG(INFO) << " Event :" << mEvents.size() - 1 << " orbit=" << orbit << " bc=" << bc << " Digits:" << dig.size(); + } + mCod->closeOutputStream(); + mCod->dumpResults("all"); + + mExTimer.logMes("Raw File created ! Digits received = " + std::to_string(mDigitsReceived) + " Frame received =" + std::to_string(mFramesReceived)); + mExTimer.stop(); + return; +} + +//_________________________________________________________________________________________________ +o2::framework::DataProcessorSpec getWriteRawFileSpec(std::string inputSpec) +{ + std::vector inputs; + inputs.emplace_back("digits", o2::header::gDataOriginHMP, "DIGITS", 0, Lifetime::Timeframe); + inputs.emplace_back("intrecord", o2::header::gDataOriginHMP, "INTRECORDS", 0, Lifetime::Timeframe); + + std::vector outputs; + + return DataProcessorSpec{ + "HMP-WriteRawFile", + inputs, + outputs, + AlgorithmSpec{adaptFromTask()}, + Options{{"out-file", VariantType::String, "hmpidRaw", {"name of the output file"}}, + {"order-events", VariantType::Bool, false, {"order the events time"}}, + {"skip-empty", VariantType::Bool, false, {"skip empty events"}}, + {"fixed-lenght", VariantType::Bool, false, {"fixed lenght packets = 8K bytes"}}}}; +} + +} // namespace hmpid +} // end namespace o2 diff --git a/Detectors/HMPID/workflow/src/WriteRawFromDigitsSpec.cxx b/Detectors/HMPID/workflow/src/WriteRawFromDigitsSpec.cxx deleted file mode 100644 index a66df17c87fe1..0000000000000 --- a/Detectors/HMPID/workflow/src/WriteRawFromDigitsSpec.cxx +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// \file WriteRawFromDigitsSpec.cxx -/// \author Antonio Franco - INFN Bari -/// \version 1.0 -/// \date 01 feb 2021 -/// \brief Implementation of a data processor to produce raw files from a Digits stream -/// - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Framework/CallbackService.h" -#include "Framework/ConfigParamRegistry.h" -#include "Framework/ControlService.h" -#include "Framework/DataProcessorSpec.h" -#include "Framework/Lifetime.h" -#include "Framework/Output.h" -#include "Framework/Task.h" -#include "Framework/WorkflowSpec.h" -#include "Framework/Logger.h" -#include "Framework/InputRecordWalker.h" - -#include "Headers/RAWDataHeader.h" -#include "DetectorsRaw/RDHUtils.h" -#include "DPLUtils/DPLRawParser.h" - -#include "HMPIDBase/Digit.h" -#include "HMPIDBase/Geo.h" -#include "HMPIDSimulation/HmpidCoder.h" -#include "HMPIDWorkflow/WriteRawFromDigitsSpec.h" - -namespace o2 -{ -namespace hmpid -{ - -using namespace o2; -using namespace o2::framework; -using RDH = o2::header::RDHAny; - -//======================= -// Data decoder -void WriteRawFromDigitsTask::init(framework::InitContext& ic) -{ - LOG(INFO) << "[HMPID Write Raw File From Digits vector - init()]"; - mBaseFileName = ic.options().get("out-file"); - mSkipEmpty = ic.options().get("skip-empty"); - mFixedPacketLenght = ic.options().get("fixed-lenght"); - mOrderTheEvents = ic.options().get("order-events"); - mDigitsReceived = 0; - mFramesReceived = 0; - - mCod = new HmpidCoder(Geo::MAXEQUIPMENTS, mSkipEmpty, mFixedPacketLenght); - mCod->reset(); - mCod->openOutputStream(mBaseFileName.c_str()); - - mExTimer.start(); - return; -} - -/* -bool WriteRawFromDigitsTask::eventEquipPadsComparision(o2::hmpid::Digit d1, o2::hmpid::Digit d2) -{ - uint64_t t1,t2; - t1 = d1.getTriggerID(); - t2 = d2.getTriggerID(); - if (t1 < t2) return true; - if (t2 < t1) return false; - if (d1.getPadID() < d2.getPadID()) return true; - return false; -} -*/ - -void WriteRawFromDigitsTask::run(framework::ProcessingContext& pc) -{ - for (auto const& ref : InputRecordWalker(pc.inputs())) { - std::vector digits = pc.inputs().get>(ref); - if (mOrderTheEvents) { - mDigits.insert(mDigits.end(), digits.begin(), digits.end()); - } else { - mCod->addDigitsChunk(digits); - mCod->codeDigitsChunk(); - } - mDigitsReceived += digits.size(); - mFramesReceived++; - LOG(DEBUG) << "run() Digits received =" << mDigitsReceived << " frames = " << mFramesReceived; - } - mExTimer.elapseMes("... Write raw file ... Digits received = " + std::to_string(mDigitsReceived) + " Frames received = " + std::to_string(mFramesReceived)); - return; -} - -void WriteRawFromDigitsTask::endOfStream(framework::EndOfStreamContext& ec) -{ - mExTimer.logMes("Received an End Of Stream !"); - if (mOrderTheEvents) { - // sort(mDigits.begin(), mDigits.end(), eventEquipPadsComparision); - sort(mDigits.begin(), mDigits.end(), o2::hmpid::Digit::eventEquipPadsComp); - mExTimer.logMes("We sort " + std::to_string(mDigits.size()) + " ! "); - mCod->codeDigitsVector(mDigits); - } else { - mCod->codeDigitsChunk(true); - } - mCod->closeOutputStream(); - mCod->dumpResults(); - - mExTimer.logMes("Raw File created ! Digits received = " + std::to_string(mDigitsReceived) + " Frame received =" + std::to_string(mFramesReceived)); - mExTimer.stop(); - return; -} - -//_________________________________________________________________________________________________ -o2::framework::DataProcessorSpec getWriteRawFromDigitsSpec(std::string inputSpec) -{ - std::vector inputs; - inputs.emplace_back("digits", o2::header::gDataOriginHMP, "DIGITS", 0, Lifetime::Timeframe); - - std::vector outputs; - - return DataProcessorSpec{ - "HMP-WriteRawFromDigits", - inputs, - outputs, - AlgorithmSpec{adaptFromTask()}, - Options{{"out-file", VariantType::String, "hmpidRaw", {"name of the output file"}}, - {"order-events", VariantType::Bool, false, {"order the events time"}}, - {"skip-empty", VariantType::Bool, false, {"skip empty events"}}, - {"fixed-lenght", VariantType::Bool, false, {"fixed lenght packets = 8K bytes"}}}}; -} - -} // namespace hmpid -} // end namespace o2 diff --git a/Detectors/HMPID/workflow/src/write-root-from-digits-workflow.cxx b/Detectors/HMPID/workflow/src/digits-to-raw-stream-workflow.cxx similarity index 72% rename from Detectors/HMPID/workflow/src/write-root-from-digits-workflow.cxx rename to Detectors/HMPID/workflow/src/digits-to-raw-stream-workflow.cxx index 498e3778260b9..bc9b662f28285 100644 --- a/Detectors/HMPID/workflow/src/write-root-from-digits-workflow.cxx +++ b/Detectors/HMPID/workflow/src/digits-to-raw-stream-workflow.cxx @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// \file write-root-from-digit-workflow.cxx +/// \file write-raw-from-digits-workflow.cxx /// \author Antonio Franco - INFN Bari /// \version 1.0 /// \date 01 feb 2021 @@ -22,38 +22,36 @@ #include "Framework/CompletionPolicy.h" #include "Framework/CompletionPolicyHelpers.h" #include "Framework/DispatchPolicy.h" -#include "CommonUtils/ConfigurableParam.h" #include "Framework/ConfigParamSpec.h" #include "Framework/Variant.h" +#include "CommonUtils/ConfigurableParam.h" // customize the completion policy void customize(std::vector& policies) { using o2::framework::CompletionPolicy; using o2::framework::CompletionPolicyHelpers; - policies.push_back(CompletionPolicyHelpers::defineByName("digit-root-write", CompletionPolicy::CompletionOp::Consume)); + policies.push_back(CompletionPolicyHelpers::defineByName("digit-hmpid-write", CompletionPolicy::CompletionOp::Consume)); } +// we need to add workflow options before including Framework/runDataProcessing void customize(std::vector& workflowOptions) { - using o2::framework::ConfigParamSpec; std::string keyvaluehelp("Semicolon separated key=value strings ..."); - workflowOptions.push_back(ConfigParamSpec{"configKeyValues", o2::framework::VariantType::String, "", {keyvaluehelp}}); + workflowOptions.push_back(o2::framework::ConfigParamSpec{"configKeyValues", o2::framework::VariantType::String, "", {keyvaluehelp}}); } #include "Framework/runDataProcessing.h" - -#include "HMPIDWorkflow/WriteRawFromDigitsSpec.h" +#include "../include/HMPIDWorkflow/WriteRawFileSpec.h" using namespace o2; using namespace o2::framework; -WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) +WorkflowSpec defineDataProcessing(const ConfigContext& cx) { WorkflowSpec specs; - o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); - - DataProcessorSpec consumer = o2::hmpid::getWriteRawFromDigitsSpec(); + o2::conf::ConfigurableParam::updateFromString(cx.options().get("configKeyValues")); + DataProcessorSpec consumer = o2::hmpid::getWriteRawFileSpec(); specs.push_back(consumer); return specs; } diff --git a/Detectors/HMPID/workflow/src/digits-to-raw-workflow.cxx b/Detectors/HMPID/workflow/src/digits-to-raw-workflow.cxx index 5f7e7425254ed..78fea36312109 100644 --- a/Detectors/HMPID/workflow/src/digits-to-raw-workflow.cxx +++ b/Detectors/HMPID/workflow/src/digits-to-raw-workflow.cxx @@ -22,6 +22,8 @@ #include "Framework/CompletionPolicy.h" #include "Framework/CompletionPolicyHelpers.h" #include "Framework/DispatchPolicy.h" +#include "Framework/ConfigParamSpec.h" +#include "Framework/Variant.h" #include "CommonUtils/ConfigurableParam.h" #include "DetectorsCommonDataFormats/NameConf.h" @@ -58,6 +60,5 @@ WorkflowSpec defineDataProcessing(const ConfigContext& configcontext) o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); DataProcessorSpec consumer = o2::hmpid::getDigitsToRawSpec(); specs.push_back(consumer); - return specs; } diff --git a/Detectors/HMPID/workflow/src/dump-digits-workflow.cxx b/Detectors/HMPID/workflow/src/dump-digits-stream-workflow.cxx similarity index 69% rename from Detectors/HMPID/workflow/src/dump-digits-workflow.cxx rename to Detectors/HMPID/workflow/src/dump-digits-stream-workflow.cxx index a876d4844a8c4..a3df07478c3c5 100644 --- a/Detectors/HMPID/workflow/src/dump-digits-workflow.cxx +++ b/Detectors/HMPID/workflow/src/dump-digits-stream-workflow.cxx @@ -22,6 +22,9 @@ #include "Framework/CompletionPolicy.h" #include "Framework/CompletionPolicyHelpers.h" #include "Framework/DispatchPolicy.h" +#include "Framework/ConfigParamSpec.h" +#include "Framework/Variant.h" +#include "CommonUtils/ConfigurableParam.h" // customize the completion policy void customize(std::vector& policies) @@ -31,21 +34,24 @@ void customize(std::vector& policies) policies.push_back(CompletionPolicyHelpers::defineByName("digit-hmpid-dump", CompletionPolicy::CompletionOp::Consume)); } -#include "Framework/runDataProcessing.h" +// we need to add workflow options before including Framework/runDataProcessing +void customize(std::vector& workflowOptions) +{ + std::string keyvaluehelp("Semicolon separated key=value strings ..."); + workflowOptions.push_back(o2::framework::ConfigParamSpec{"configKeyValues", o2::framework::VariantType::String, "", {keyvaluehelp}}); +} +#include "Framework/runDataProcessing.h" #include "HMPIDWorkflow/DumpDigitsSpec.h" using namespace o2; using namespace o2::framework; -WorkflowSpec defineDataProcessing(const ConfigContext&) +WorkflowSpec defineDataProcessing(const ConfigContext& cx) { WorkflowSpec specs; - + o2::conf::ConfigurableParam::updateFromString(cx.options().get("configKeyValues")); DataProcessorSpec consumer = o2::hmpid::getDumpDigitsSpec(); - // DataProcessorSpec consumer = o2::hmpid::getDecodingSpec(); specs.push_back(consumer); - // specs.push_back(consumer); - return specs; } diff --git a/Detectors/HMPID/workflow/src/raw-to-digits-stream-workflow.cxx b/Detectors/HMPID/workflow/src/raw-to-digits-stream-workflow.cxx new file mode 100644 index 0000000000000..1f5487550bd53 --- /dev/null +++ b/Detectors/HMPID/workflow/src/raw-to-digits-stream-workflow.cxx @@ -0,0 +1,67 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "Framework/WorkflowSpec.h" +#include "Framework/DataSpecUtils.h" +#include "Framework/CallbackService.h" +#include "Framework/ControlService.h" +#include "Framework/Task.h" +#include "Framework/CompletionPolicy.h" +#include "Framework/CompletionPolicyHelpers.h" +#include "Framework/DispatchPolicy.h" +#include "Framework/DataProcessorSpec.h" +#include "Framework/InputRecordWalker.h" +#include "Framework/Logger.h" +#include "Framework/ConfigParamSpec.h" +#include "CommonUtils/ConfigurableParam.h" +#include "Framework/Variant.h" + +// customize dispatch policy, dispatch immediately what is ready +void customize(std::vector& policies) +{ + using DispatchOp = o2::framework::DispatchPolicy::DispatchOp; + auto readerMatcher = [](auto const& spec) { + return true; + }; + auto triggerMatcher = [](auto const& query) { + return true; + }; + policies.push_back({"decoded-hmpid-digits", readerMatcher, DispatchOp::WhenReady, triggerMatcher}); +} + +// customize the completion policy +void customize(std::vector& policies) +{ + using o2::framework::CompletionPolicy; + using o2::framework::CompletionPolicyHelpers; + policies.push_back(CompletionPolicyHelpers::defineByName("raw-hmpid-decode", CompletionPolicy::CompletionOp::Consume)); +} + +// we need to add workflow options before including Framework/runDataProcessing +void customize(std::vector& workflowOptions) +{ + std::string keyvaluehelp("Semicolon separated key=value strings ..."); + workflowOptions.push_back(o2::framework::ConfigParamSpec{"configKeyValues", o2::framework::VariantType::String, "", {keyvaluehelp}}); +} + +#include "Framework/runDataProcessing.h" +#include "HMPIDWorkflow/DataDecoderSpec.h" + +using namespace o2; +using namespace o2::framework; + +WorkflowSpec defineDataProcessing(const ConfigContext& cx) +{ + WorkflowSpec specs; + o2::conf::ConfigurableParam::updateFromString(cx.options().get("configKeyValues")); + DataProcessorSpec producer = o2::hmpid::getDecodingSpec(); + specs.push_back(producer); + return specs; +} diff --git a/Detectors/HMPID/workflow/src/raw-to-digits-workflow.cxx b/Detectors/HMPID/workflow/src/raw-to-digits-workflow.cxx index 25514761e14d9..00939b16aef37 100644 --- a/Detectors/HMPID/workflow/src/raw-to-digits-workflow.cxx +++ b/Detectors/HMPID/workflow/src/raw-to-digits-workflow.cxx @@ -8,6 +8,12 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +/// \file raw-to-digits-workflow.cxx +/// \author Antonio Franco - INFN Bari +/// \version 1.0 +/// \date 01 feb 2021 +/// + #include "Framework/WorkflowSpec.h" #include "Framework/DataSpecUtils.h" #include "Framework/CallbackService.h" @@ -16,45 +22,36 @@ #include "Framework/CompletionPolicy.h" #include "Framework/CompletionPolicyHelpers.h" #include "Framework/DispatchPolicy.h" -#include "Framework/DataProcessorSpec.h" -#include "Framework/InputRecordWalker.h" -#include "Framework/Logger.h" #include "Framework/ConfigParamSpec.h" - -// customize dispatch policy, dispatch immediately what is ready -void customize(std::vector& policies) -{ - using DispatchOp = o2::framework::DispatchPolicy::DispatchOp; - auto readerMatcher = [](auto const& spec) { - return true; - }; - auto triggerMatcher = [](auto const& query) { - return true; - }; - policies.push_back({"decoded-hmpid-digits", readerMatcher, DispatchOp::WhenReady, triggerMatcher}); -} +#include "Framework/Variant.h" +#include "CommonUtils/ConfigurableParam.h" // customize the completion policy void customize(std::vector& policies) { using o2::framework::CompletionPolicy; using o2::framework::CompletionPolicyHelpers; - policies.push_back(CompletionPolicyHelpers::defineByName("raw-hmpid-decode", CompletionPolicy::CompletionOp::Consume)); + policies.push_back(CompletionPolicyHelpers::defineByName("raw-hmpid-read", CompletionPolicy::CompletionOp::Process)); } -#include "Framework/runDataProcessing.h" +// we need to add workflow options before including Framework/runDataProcessing +void customize(std::vector& workflowOptions) +{ + std::string keyvaluehelp("Semicolon separated key=value strings ..."); + workflowOptions.push_back(o2::framework::ConfigParamSpec{"configKeyValues", o2::framework::VariantType::String, "", {keyvaluehelp}}); +} -#include "HMPIDWorkflow/DataDecoderSpec.h" +#include "Framework/runDataProcessing.h" +#include "../include/HMPIDWorkflow/RawToDigitsSpec.h" using namespace o2; using namespace o2::framework; -WorkflowSpec defineDataProcessing(const ConfigContext&) +WorkflowSpec defineDataProcessing(ConfigContext const& cx) { WorkflowSpec specs; - - DataProcessorSpec producer = o2::hmpid::getDecodingSpec(); - specs.push_back(producer); - + o2::conf::ConfigurableParam::updateFromString(cx.options().get("configKeyValues")); + DataProcessorSpec consumer = o2::hmpid::getRawToDigitsSpec(); + specs.push_back(consumer); return specs; } diff --git a/Detectors/HMPID/workflow/src/raw-to-pedestals-workflow.cxx b/Detectors/HMPID/workflow/src/raw-to-pedestals-workflow.cxx index c326f85169ccc..ac18c487da079 100644 --- a/Detectors/HMPID/workflow/src/raw-to-pedestals-workflow.cxx +++ b/Detectors/HMPID/workflow/src/raw-to-pedestals-workflow.cxx @@ -14,6 +14,7 @@ /// \date 01 feb 2021 /// +#include "Framework/Variant.h" #include "Framework/WorkflowSpec.h" #include "Framework/DataSpecUtils.h" #include "Framework/CallbackService.h" @@ -26,6 +27,7 @@ #include "Framework/InputRecordWalker.h" #include "Framework/Logger.h" #include "Framework/ConfigParamSpec.h" +#include "CommonUtils/ConfigurableParam.h" // customize dispatch policy, dispatch immediately what is ready void customize(std::vector& policies) @@ -37,22 +39,27 @@ void customize(std::vector& policies) auto triggerMatcher = [](auto const& query) { return true; }; - policies.push_back({"decoded-hmpid-digits", readerMatcher, DispatchOp::WhenReady, triggerMatcher}); + policies.push_back({"raw-hmpid-pedestals", readerMatcher, DispatchOp::WhenReady, triggerMatcher}); } -#include "Framework/runDataProcessing.h" +// we need to add workflow options before including Framework/runDataProcessing +void customize(std::vector& workflowOptions) +{ + std::string keyvaluehelp("Semicolon separated key=value strings ..."); + workflowOptions.push_back(o2::framework::ConfigParamSpec{"configKeyValues", o2::framework::VariantType::String, "", {keyvaluehelp}}); +} +#include "Framework/runDataProcessing.h" #include "HMPIDWorkflow/PedestalsCalculationSpec.h" using namespace o2; using namespace o2::framework; -WorkflowSpec defineDataProcessing(const ConfigContext&) +WorkflowSpec defineDataProcessing(const ConfigContext& cx) { WorkflowSpec specs; - + o2::conf::ConfigurableParam::updateFromString(cx.options().get("configKeyValues")); DataProcessorSpec producer = o2::hmpid::getPedestalsCalculationSpec(); specs.push_back(producer); - return specs; } diff --git a/Detectors/HMPID/workflow/src/read-raw-file-workflow.cxx b/Detectors/HMPID/workflow/src/read-raw-file-stream-workflow.cxx similarity index 74% rename from Detectors/HMPID/workflow/src/read-raw-file-workflow.cxx rename to Detectors/HMPID/workflow/src/read-raw-file-stream-workflow.cxx index 47e3447acb6ce..0c635eb0bea20 100644 --- a/Detectors/HMPID/workflow/src/read-raw-file-workflow.cxx +++ b/Detectors/HMPID/workflow/src/read-raw-file-stream-workflow.cxx @@ -14,13 +14,20 @@ /// \date 01 feb 2021 /// -#include #include "Framework/WorkflowSpec.h" #include "Framework/DataSpecUtils.h" #include "Framework/CallbackService.h" #include "Framework/ControlService.h" -#include "Framework/DispatchPolicy.h" #include "Framework/Task.h" +#include "Framework/CompletionPolicy.h" +#include "Framework/CompletionPolicyHelpers.h" +#include "Framework/DispatchPolicy.h" +#include "Framework/DataProcessorSpec.h" +#include "Framework/InputRecordWalker.h" +#include "Framework/Logger.h" +#include "Framework/ConfigParamSpec.h" +#include "Framework/Variant.h" +#include "CommonUtils/ConfigurableParam.h" // customize dispatch policy, dispatch immediately what is ready void customize(std::vector& policies) @@ -47,20 +54,25 @@ void customize(std::vector& policies) policies.push_back({"pr-f-re", readerMatcher, DispatchOp::WhenReady, triggerMatcher}); } -#include "Framework/runDataProcessing.h" +// we need to add workflow options before including Framework/runDataProcessing +void customize(std::vector& workflowOptions) +{ + std::string keyvaluehelp("Semicolon separated key=value strings ..."); + workflowOptions.push_back(o2::framework::ConfigParamSpec{"configKeyValues", o2::framework::VariantType::String, "", {keyvaluehelp}}); +} +#include "Framework/runDataProcessing.h" #include "HMPIDWorkflow/ReadRawFileSpec.h" using namespace o2; using namespace o2::framework; -WorkflowSpec defineDataProcessing(const ConfigContext&) +WorkflowSpec defineDataProcessing(const ConfigContext& cx) { WorkflowSpec specs; - + o2::conf::ConfigurableParam::updateFromString(cx.options().get("configKeyValues")); // The producer to generate some data in the workflow DataProcessorSpec producer = o2::hmpid::getReadRawFileSpec(); specs.push_back(producer); - return specs; } diff --git a/Detectors/HMPID/workflow/src/write-raw-from-digits-workflow.cxx b/Detectors/HMPID/workflow/src/write-raw-from-digits-workflow.cxx deleted file mode 100644 index 92fe151bd6384..0000000000000 --- a/Detectors/HMPID/workflow/src/write-raw-from-digits-workflow.cxx +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// \file write-raw-from-digits-workflow.cxx -/// \author Antonio Franco - INFN Bari -/// \version 1.0 -/// \date 01 feb 2021 -/// - -#include "Framework/WorkflowSpec.h" -#include "Framework/DataSpecUtils.h" -#include "Framework/CallbackService.h" -#include "Framework/ControlService.h" -#include "Framework/Task.h" -#include "Framework/CompletionPolicy.h" -#include "Framework/CompletionPolicyHelpers.h" -#include "Framework/DispatchPolicy.h" - -// customize the completion policy -void customize(std::vector& policies) -{ - using o2::framework::CompletionPolicy; - using o2::framework::CompletionPolicyHelpers; - policies.push_back(CompletionPolicyHelpers::defineByName("digit-hmpid-write", CompletionPolicy::CompletionOp::Consume)); -} - -#include "Framework/runDataProcessing.h" - -#include "HMPIDWorkflow/WriteRawFromDigitsSpec.h" - -using namespace o2; -using namespace o2::framework; - -WorkflowSpec defineDataProcessing(const ConfigContext&) -{ - WorkflowSpec specs; - - DataProcessorSpec consumer = o2::hmpid::getWriteRawFromDigitsSpec(); - // DataProcessorSpec consumer = o2::hmpid::getDecodingSpec(); - specs.push_back(consumer); - // specs.push_back(consumer); - - return specs; -} diff --git a/Steer/DigitizerWorkflow/src/HMPIDDigitWriterSpec.h b/Steer/DigitizerWorkflow/src/HMPIDDigitWriterSpec.h index 66c2875f48d3e..35ae3d46d86f0 100644 --- a/Steer/DigitizerWorkflow/src/HMPIDDigitWriterSpec.h +++ b/Steer/DigitizerWorkflow/src/HMPIDDigitWriterSpec.h @@ -14,8 +14,8 @@ #include "Framework/DataProcessorSpec.h" #include "DPLUtils/MakeRootTreeWriterSpec.h" #include "Framework/InputSpec.h" -#include "HMPIDBase/Digit.h" -#include "HMPIDBase/Trigger.h" +#include "DataFormatsHMP/Digit.h" +#include "DataFormatsHMP/Trigger.h" #include "SimulationDataFormat/MCTruthContainer.h" #include "SimulationDataFormat/MCCompLabel.h" @@ -36,7 +36,7 @@ o2::framework::DataProcessorSpec getHMPIDDigitWriterSpec(bool mctruth = true) "o2sim", 1, BranchDefinition>{InputSpec{"digitinput", "HMP", "DIGITS"}, "HMPDigit"}, - BranchDefinition>{InputSpec{"interactionrecods", "HMP", "INTRECORDS"}, "InteractionRecords"}, + BranchDefinition>{InputSpec{"interactionrecods", "HMP", "INTRECORDS"}, "InteractionRecords"}, BranchDefinition>{InputSpec{"labelinput", "HMP", "DIGITLBL"}, "HMPDigitLabels", mctruth ? 1 : 0})(); } diff --git a/Steer/DigitizerWorkflow/src/HMPIDDigitizerSpec.cxx b/Steer/DigitizerWorkflow/src/HMPIDDigitizerSpec.cxx index 874650ea55e72..33a7bffa989ba 100644 --- a/Steer/DigitizerWorkflow/src/HMPIDDigitizerSpec.cxx +++ b/Steer/DigitizerWorkflow/src/HMPIDDigitizerSpec.cxx @@ -22,8 +22,8 @@ #include #include "Framework/Task.h" #include "DataFormatsParameters/GRPObject.h" -#include "HMPIDBase/Digit.h" -#include "HMPIDBase/Trigger.h" +#include "DataFormatsHMP/Digit.h" +#include "DataFormatsHMP/Trigger.h" #include "HMPIDSimulation/HMPIDDigitizer.h" #include "HMPIDSimulation/Detector.h" #include "DetectorsBase/BaseDPLDigitizer.h" @@ -78,8 +78,14 @@ class HMPIDDPLDigitizerTask : public o2::base::BaseDPLDigitizer mDigitizer.flush(mDigits); LOG(INFO) << "HMPID flushed " << mDigits.size() << " digits at this time "; LOG(INFO) << "NUMBER OF LABEL OBTAINED " << mLabels.getNElements(); + int32_t first = digitsAccum.size(); // this is the first std::copy(mDigits.begin(), mDigits.end(), std::back_inserter(digitsAccum)); + int32_t last = digitsAccum.size() - 1; // this is the last labelAccum.mergeAtBack(mLabels); + + // save info for the triggers accepted + LOG(INFO) << "Trigger Orbit :" << mDigitizer.getOrbit() << " BC:" << mDigitizer.getBc(); + mIntRecord.push_back(o2::hmpid::Event(o2::InteractionRecord(mDigitizer.getBc(), mDigitizer.getOrbit()), first, last)); }; // loop over all composite collisions given from context @@ -109,9 +115,6 @@ class HMPIDDPLDigitizerTask : public o2::base::BaseDPLDigitizer mDigitizer.process(hits, mDigits); } - // save info for the triggers accepted - LOG(INFO) << "Trigger Orbit :" << mDigitizer.getOrbit() << " BC:" << mDigitizer.getBc(); - mIntRecord.push_back(o2::hmpid::Trigger(mDigitizer.getBc(), mDigitizer.getOrbit())); } else { LOG(INFO) << "COLLISION " << collID << "FALLS WITHIN A DEAD TIME"; @@ -139,7 +142,7 @@ class HMPIDDPLDigitizerTask : public o2::base::BaseDPLDigitizer std::vector mSimChains; std::vector mDigits; o2::dataformats::MCTruthContainer mLabels; // labels which get filled - std::vector mIntRecord; + std::vector mIntRecord; // RS: at the moment using hardcoded flag for continuous readout o2::parameters::GRPObject::ROMode mROMode = o2::parameters::GRPObject::CONTINUOUS; // readout mode From 221719becf885958fb2e8cc8b12ac7032cf544a0 Mon Sep 17 00:00:00 2001 From: Ole Schmidt Date: Thu, 1 Apr 2021 17:59:33 +0200 Subject: [PATCH 054/770] TRD TRAP simulation uses OpenMP - output tracklets are sorted by HCId - parallelisation is done over collisions - TODO: check hit calculation in TRAP simulation --- .../TRD/include/DataFormatsTRD/Constants.h | 1 + Detectors/TRD/base/include/TRDBase/Digit.h | 1 + .../TRD/simulation/src/TrapSimulator.cxx | 4 +- .../TRDWorkflow/TRDTrapSimulatorSpec.h | 6 +- .../TRD/workflow/src/TRDTrapSimulatorSpec.cxx | 219 +++++++++--------- 5 files changed, 119 insertions(+), 112 deletions(-) diff --git a/DataFormats/Detectors/TRD/include/DataFormatsTRD/Constants.h b/DataFormats/Detectors/TRD/include/DataFormatsTRD/Constants.h index 011987d71636f..1a4cd01626406 100644 --- a/DataFormats/Detectors/TRD/include/DataFormatsTRD/Constants.h +++ b/DataFormats/Detectors/TRD/include/DataFormatsTRD/Constants.h @@ -39,6 +39,7 @@ constexpr int NROWC0 = 12; // the number of pad rows for chambers of type C0 ( constexpr int NROWC1 = 16; // the number of pad rows for chambers of type C1 (installed in stack 2) constexpr int NMCMROB = 16; // the number of MCMs per ROB +constexpr int NMCMHCMAX = 64; // the maximum number of MCMs for one half chamber (C1 type) constexpr int NMCMROBINROW = 4; // the number of MCMs per ROB in row direction constexpr int NMCMROBINCOL = 4; // the number of MCMs per ROB in column direction constexpr int NROBC0 = 6; // the number of ROBs per C0 chamber diff --git a/Detectors/TRD/base/include/TRDBase/Digit.h b/Detectors/TRD/base/include/TRDBase/Digit.h index 69df71de54bd0..1d51d6bc9d690 100644 --- a/Detectors/TRD/base/include/TRDBase/Digit.h +++ b/Detectors/TRD/base/include/TRDBase/Digit.h @@ -63,6 +63,7 @@ class Digit void setADC(const gsl::span& adc) { std::copy(adc.begin(), adc.end(), mADC.begin()); } // Get methods int getDetector() const { return mDetector; } + int getHCId() const { return mDetector * 2 + (mROB % 2); } int getRow() const { return FeeParam::getPadRowFromMCM(mROB, mMCM); } int getPad() const { return FeeParam::getPadColFromADC(mROB, mMCM, mChannel); } int getROB() const { return mROB; } diff --git a/Detectors/TRD/simulation/src/TrapSimulator.cxx b/Detectors/TRD/simulation/src/TrapSimulator.cxx index 36506dbb79821..cf1f2ae5b5ec2 100644 --- a/Detectors/TRD/simulation/src/TrapSimulator.cxx +++ b/Detectors/TRD/simulation/src/TrapSimulator.cxx @@ -107,6 +107,7 @@ void TrapSimulator::reset() //clear the adc data std::fill(mADCR.begin(), mADCR.end(), 0); std::fill(mADCF.begin(), mADCF.end(), 0); + std::fill(mADCDigitIndices.begin(), mADCDigitIndices.end(), -1); for (auto filterreg : mInternalFilterRegisters) { filterreg.ClearReg(); @@ -2069,7 +2070,8 @@ void TrapSimulator::fitTracklet() } bool printoutadcs = false; for (int i = 0; i < 21; i++) { - if (adchitbp & (1U << i)) { + // FIXME it can happen that there is a hit found in a channel where there is no digit provided as input. Is this expected? + if ((adchitbp & (1U << i)) && (mADCDigitIndices[i] >= 0)) { mTrackletDigitCount.back() += 1; mTrackletDigitIndices.push_back(mADCDigitIndices[i]); } diff --git a/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrapSimulatorSpec.h b/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrapSimulatorSpec.h index 79c5b199c82c4..4ab9997007f1d 100644 --- a/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrapSimulatorSpec.h +++ b/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrapSimulatorSpec.h @@ -20,6 +20,7 @@ #include "TRDSimulation/TrapSimulator.h" #include "TRDSimulation/TrapConfig.h" #include "DataFormatsTRD/Tracklet64.h" +#include "DataFormatsTRD/Constants.h" #include #include @@ -41,23 +42,20 @@ class TRDDPLTrapSimulatorTask : public o2::framework::Task private: - std::array mTrapSimulator; //the up to 128 trap simulators for a single chamber TrapConfig* mTrapConfig = nullptr; unsigned long mRunNumber = 297595; //run number to anchor simulation to. - int mShowTrackletStats = 1; // show some statistics for each run bool mEnableOnlineGainCorrection{false}; bool mUseMC{false}; // whether or not to use MC labels bool mEnableTrapConfigDump{false}; std::string mTrapConfigName; // the name of the config to be used. std::string mOnlineGainTableName; std::unique_ptr mCalib; // store the calibrations connection to CCDB. Used primarily for the gaintables in line above. - std::chrono::duration mTrapSimTime{0}; // timer for the actual processing in the TRAP chips TrapConfig* getTrapConfig(); void loadTrapConfig(); void loadDefaultTrapConfig(); void setOnlineGainTables(); - void processTRAPchips(int currDetector, int& nTrackletsInTrigRec, std::vector& trapTrackletsAccum, o2::dataformats::MCTruthContainer& lblTracklets, const o2::dataformats::ConstMCTruthContainer* lblDigits); + void processTRAPchips(int& nTracklets, std::vector& trackletsAccum, std::array& trapSimulators, std::vector& digitCounts, std::vector& digitIndices); }; o2::framework::DataProcessorSpec getTRDTrapSimulatorSpec(bool useMC); diff --git a/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx b/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx index 74369a2d6cbc3..3da4d6d85e48b 100644 --- a/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx @@ -13,6 +13,7 @@ #include #include #include +#include #include "TFile.h" @@ -26,7 +27,6 @@ #include "TRDBase/Digit.h" #include "TRDBase/Calibrations.h" #include "DataFormatsTRD/TriggerRecord.h" -#include "DataFormatsTRD/Constants.h" using namespace o2::framework; @@ -143,65 +143,30 @@ void TRDDPLTrapSimulatorTask::setOnlineGainTables() } } -void TRDDPLTrapSimulatorTask::processTRAPchips(int currDetector, int& nTrackletsInTrigRec, std::vector& trapTrackletsAccum, o2::dataformats::MCTruthContainer& lblTracklets, const o2::dataformats::ConstMCTruthContainer* lblDigits) +void TRDDPLTrapSimulatorTask::processTRAPchips(int& nTracklets, std::vector& trackletsAccum, std::array& trapSimulators, std::vector& digitCounts, std::vector& digitIndices) { - // Loop over all TRAP chips of detector number currDetector. - // TRAP chips without input data are skipped - int currStack = (currDetector % NCHAMBERPERSEC) / NLAYER; - int nTrapsMax = (currStack == 2) ? NROBC0 * NMCMROB : NROBC1 * NMCMROB; - for (int iTrap = 0; iTrap < nTrapsMax; ++iTrap) { - if (!mTrapSimulator[iTrap].isDataSet()) { + // TRAP processing for current half chamber + for (int iTrap = 0; iTrap < NMCMHCMAX; ++iTrap) { + if (!trapSimulators[iTrap].isDataSet()) { continue; } - auto timeTrapProcessingStart = std::chrono::high_resolution_clock::now(); - mTrapSimulator[iTrap].filter(); - mTrapSimulator[iTrap].tracklet(); - mTrapSimTime += std::chrono::high_resolution_clock::now() - timeTrapProcessingStart; - auto trackletsOut = mTrapSimulator[iTrap].getTrackletArray64(); - int nTrackletsOut = trackletsOut.size(); - nTrackletsInTrigRec += nTrackletsOut; + trapSimulators[iTrap].filter(); + trapSimulators[iTrap].tracklet(); + auto trackletsOut = trapSimulators[iTrap].getTrackletArray64(); + nTracklets += trackletsOut.size(); + trackletsAccum.insert(trackletsAccum.end(), trackletsOut.begin(), trackletsOut.end()); if (mUseMC) { - auto digitCountOut = mTrapSimulator[iTrap].getTrackletDigitCount(); // number of digits contributing to each tracklet - auto digitIndicesOut = mTrapSimulator[iTrap].getTrackletDigitIndices(); // global indices of the digits composing the tracklets - int currDigitIndex = 0; // count the total number of digits which are associated to tracklets for this TRAP - int trkltIdxStart = trapTrackletsAccum.size(); - for (int iTrklt = 0; iTrklt < nTrackletsOut; ++iTrklt) { - // for each tracklet of this TRAP check the MC labels of the digits which contribute to the tracklet - int tmp = currDigitIndex; - for (int iDigitIndex = tmp; iDigitIndex < tmp + digitCountOut[iTrklt]; ++iDigitIndex) { - if (iDigitIndex == tmp) { - // for the first digit composing the tracklet we don't need to check for duplicate labels - lblTracklets.addElements(trkltIdxStart + iTrklt, lblDigits->getLabels(digitIndicesOut[iDigitIndex])); - } else { - // in case more than one digit composes the tracklet we add only the labels - // from the additional digit(s) which are not already contained in the previous - // digit(s) - auto currentLabels = lblTracklets.getLabels(trkltIdxStart + iTrklt); - auto newLabels = lblDigits->getLabels(digitIndicesOut[iDigitIndex]); - for (const auto& newLabel : newLabels) { - bool isAlreadyIn = false; - for (const auto& currLabel : currentLabels) { - if (currLabel.compare(newLabel)) { - isAlreadyIn = true; - } - } - if (!isAlreadyIn) { - lblTracklets.addElement(trkltIdxStart + iTrklt, newLabel); - } - } - } - ++currDigitIndex; - } - } + auto digitCountOut = trapSimulators[iTrap].getTrackletDigitCount(); + digitCounts.insert(digitCounts.end(), digitCountOut.begin(), digitCountOut.end()); + auto digitIndicesOut = trapSimulators[iTrap].getTrackletDigitIndices(); + digitIndices.insert(digitIndices.end(), digitIndicesOut.begin(), digitIndicesOut.end()); } - trapTrackletsAccum.insert(trapTrackletsAccum.end(), trackletsOut.begin(), trackletsOut.end()); - mTrapSimulator[iTrap].reset(); + trapSimulators[iTrap].reset(); } } void TRDDPLTrapSimulatorTask::init(o2::framework::InitContext& ic) { - mShowTrackletStats = ic.options().get("show-trd-trackletstats"); mTrapConfigName = ic.options().get("trd-trapconfig"); mEnableOnlineGainCorrection = ic.options().get("trd-onlinegaincorrection"); mOnlineGainTableName = ic.options().get("trd-onlinegaintable"); @@ -222,87 +187,128 @@ void TRDDPLTrapSimulatorTask::run(o2::framework::ProcessingContext& pc) LOG(info) << "TRD Trap Simulator Device running over incoming message"; // input - auto inputDigits = pc.inputs().get>("digitinput"); // block of TRD digits - auto inputTriggerRecords = pc.inputs().get>("triggerrecords"); // time and number of digits for each collision - // the above is changed to a vector from a span as the span is constant and cant modify elements. - if (inputDigits.size() == 0 || inputTriggerRecords.size() == 0) { - LOG(warn) << "Did not receive any digits, trigger records, or neither one nor the other. Aborting."; - return; - } - LOG(debug) << "Read in " << inputDigits.size() << " digits"; + auto digits = pc.inputs().get>("digitinput"); // block of TRD digits + auto triggerRecords = pc.inputs().get>("triggerrecords"); // time and number of digits for each collision + LOG(debug) << "Received " << digits.size() << " digits from " << triggerRecords.size() << " collisions"; + // load MC information if label processing is enabeld const o2::dataformats::ConstMCTruthContainer* lblDigitsPtr = nullptr; using lblType = std::decay_t>(""))>; std::optional lblDigits; - if (mUseMC) { lblDigits.emplace(pc.inputs().get>("labelinput")); // MC labels associated to the input digits lblDigitsPtr = &lblDigits.value(); LOG(debug) << "Labels contain " << lblDigitsPtr->getNElements() << " elements with and indexed size of " << lblDigitsPtr->getIndexedSize(); - if (lblDigitsPtr->getIndexedSize() != inputDigits.size()) { - LOG(warn) << "Digits and Labels coming into TrapSimulator are of differing sizes, labels will be jibberish. " << lblDigitsPtr->getIndexedSize() << "!=" << inputDigits.size(); + if (lblDigitsPtr->getIndexedSize() != digits.size()) { + LOG(warn) << "Digits and Labels coming into TrapSimulator are of differing sizes, labels will be jibberish. " << lblDigitsPtr->getIndexedSize() << "!=" << digits.size(); } } - LOG(debug) << "Trigger records are available for " << inputTriggerRecords.size() << " collisions"; // output - std::vector trapTrackletsAccum; // calculated tracklets + std::vector tracklets; // calculated tracklets + o2::dataformats::MCTruthContainer lblTracklets; // MC labels for the tracklets, taken from the digits which make up the tracklet (duplicates are removed) - o2::dataformats::MCTruthContainer lblTracklets; // MC labels for the tracklets, taken from the digits which make up the tracklet (duplicates are removed) + auto timeProcessingStart = std::chrono::high_resolution_clock::now(); // measure total processing time - // sort digits by chamber ID for each collision and keep track in index vector + // sort digits by half chamber ID for each collision and keep track in index vector auto sortStart = std::chrono::high_resolution_clock::now(); - std::vector digitIndices(inputDigits.size()); // digit indices sorted by chamber ID for each time frame - std::iota(digitIndices.begin(), digitIndices.end(), 0); - for (auto& trig : inputTriggerRecords) { - std::stable_sort(std::begin(digitIndices) + trig.getFirstDigit(), std::begin(digitIndices) + trig.getNumberOfDigits() + trig.getFirstDigit(), - [&inputDigits](unsigned int i, unsigned int j) { return inputDigits[i].getDetector() < inputDigits[j].getDetector(); }); + std::vector digitIdxArray(digits.size()); // digit indices sorted by half chamber ID for each time frame + std::iota(digitIdxArray.begin(), digitIdxArray.end(), 0); + for (auto& trig : triggerRecords) { + std::stable_sort(std::begin(digitIdxArray) + trig.getFirstDigit(), std::begin(digitIdxArray) + trig.getNumberOfDigits() + trig.getFirstDigit(), + [&digits](unsigned int i, unsigned int j) { return digits[i].getHCId() < digits[j].getHCId(); }); } - std::chrono::duration sortTime = std::chrono::high_resolution_clock::now() - sortStart; - - // initialize timers - auto timeDigitLoopStart = std::chrono::high_resolution_clock::now(); - std::chrono::duration trapSimAccumulatedTime{}; - mTrapSimTime = std::chrono::duration::zero(); - - for (int iTrig = 0; iTrig < inputTriggerRecords.size(); ++iTrig) { - int nTrackletsInTrigRec = 0; - int currDetector = -1; - for (int iDigit = inputTriggerRecords[iTrig].getFirstDigit(); iDigit < (inputTriggerRecords[iTrig].getFirstDigit() + inputTriggerRecords[iTrig].getNumberOfDigits()); ++iDigit) { - const auto& digit = &inputDigits[digitIndices[iDigit]]; - if (currDetector < 0) { - currDetector = digit->getDetector(); + auto sortTime = std::chrono::high_resolution_clock::now() - sortStart; + + // prepare data structures for accumulating results per collision + std::vector nTracklets(triggerRecords.size()); + std::vector> trackletsAccum; + trackletsAccum.resize(triggerRecords.size()); + std::vector> digitCountsAccum; // holds the number of digits included in each tracklet (therefore has the same number of elements as trackletsAccum) + // digitIndicesAccum holds the global indices of the digits which comprise the tracklets + // with the help of digitCountsAccum one can loop through this vector and find the corresponding digit indices for each tracklet + std::vector> digitIndicesAccum; + digitCountsAccum.resize(triggerRecords.size()); + digitIndicesAccum.resize(triggerRecords.size()); + + auto timeParallelStart = std::chrono::high_resolution_clock::now(); + +#pragma omp parallel for + for (int iTrig = 0; iTrig < triggerRecords.size(); ++iTrig) { + int currHCId = -1; + std::array trapSimulators{}; //the up to 64 trap simulators for a single half chamber + for (int iDigit = triggerRecords[iTrig].getFirstDigit(); iDigit < (triggerRecords[iTrig].getFirstDigit() + triggerRecords[iTrig].getNumberOfDigits()); ++iDigit) { + const auto& digit = &digits[digitIdxArray[iDigit]]; + if (currHCId < 0) { + currHCId = digit->getHCId(); } - if (currDetector != digit->getDetector()) { - // we switch to a new chamber, process all TRAPs of the previous chamber which contain data - processTRAPchips(currDetector, nTrackletsInTrigRec, trapTrackletsAccum, lblTracklets, lblDigitsPtr); - currDetector = digit->getDetector(); + if (currHCId != digit->getHCId()) { + // we switch to a new half chamber, process all TRAPs of the previous half chamber which contain data + processTRAPchips(nTracklets[iTrig], trackletsAccum[iTrig], trapSimulators, digitCountsAccum[iTrig], digitIndicesAccum[iTrig]); + currHCId = digit->getHCId(); } // fill the digit data into the corresponding TRAP chip - int trapIdx = digit->getROB() * NMCMROB + digit->getMCM(); - if (!mTrapSimulator[trapIdx].isDataSet()) { - mTrapSimulator[trapIdx].init(mTrapConfig, digit->getDetector(), digit->getROB(), digit->getMCM()); + int trapIdx = (digit->getROB() / 2) * NMCMROB + digit->getMCM(); + if (!trapSimulators[trapIdx].isDataSet()) { + trapSimulators[trapIdx].init(mTrapConfig, digit->getDetector(), digit->getROB(), digit->getMCM()); + } + trapSimulators[trapIdx].setData(digit->getChannel(), digit->getADC(), digitIdxArray[iDigit]); + } + // take care of the TRAPs for the last half chamber + processTRAPchips(nTracklets[iTrig], trackletsAccum[iTrig], trapSimulators, digitCountsAccum[iTrig], digitIndicesAccum[iTrig]); + } // done with parallel processing + auto parallelTime = std::chrono::high_resolution_clock::now() - timeParallelStart; + + // accumulate results and add MC labels + for (int iTrig = 0; iTrig < triggerRecords.size(); ++iTrig) { + if (mUseMC) { + int currDigitIndex = 0; // counter for all digits which are associated to tracklets + int trkltIdxStart = tracklets.size(); + for (int iTrklt = 0; iTrklt < nTracklets[iTrig]; ++iTrklt) { + int tmp = currDigitIndex; + for (int iDigitIndex = tmp; iDigitIndex < tmp + digitCountsAccum[iTrig][iTrklt]; ++iDigitIndex) { + if (iDigitIndex == tmp) { + // for the first digit composing the tracklet we don't need to check for duplicate labels + lblTracklets.addElements(trkltIdxStart + iTrklt, lblDigitsPtr->getLabels(digitIndicesAccum[iTrig][iDigitIndex])); + } else { + // in case more than one digit composes the tracklet we add only the labels + // from the additional digit(s) which are not already contained in the previous + // digit(s) + auto currentLabels = lblTracklets.getLabels(trkltIdxStart + iTrklt); + auto newLabels = lblDigitsPtr->getLabels(digitIndicesAccum[iTrig][iDigitIndex]); + for (const auto& newLabel : newLabels) { + bool alreadyIn = false; + for (const auto& currLabel : currentLabels) { + if (currLabel.compare(newLabel)) { + alreadyIn = true; + break; + } + } + if (!alreadyIn) { + lblTracklets.addElement(trkltIdxStart + iTrklt, newLabel); + } + } + } + ++currDigitIndex; + } } - mTrapSimulator[trapIdx].setData(digit->getChannel(), digit->getADC(), digitIndices[iDigit]); } - // take care of the TRAPs for the last chamber - processTRAPchips(currDetector, nTrackletsInTrigRec, trapTrackletsAccum, lblTracklets, lblDigitsPtr); - inputTriggerRecords[iTrig].setTrackletRange(trapTrackletsAccum.size() - nTrackletsInTrigRec, nTrackletsInTrigRec); + tracklets.insert(tracklets.end(), trackletsAccum[iTrig].begin(), trackletsAccum[iTrig].end()); + triggerRecords[iTrig].setTrackletRange(tracklets.size() - nTracklets[iTrig], nTracklets[iTrig]); } - LOG(info) << "Trap simulator found " << trapTrackletsAccum.size() << " tracklets from " << inputDigits.size() << " Digits."; + auto processingTime = std::chrono::high_resolution_clock::now() - timeProcessingStart; + + LOG(info) << "Trap simulator found " << tracklets.size() << " tracklets from " << digits.size() << " Digits."; if (mUseMC) { - LOG(info) << "In total " << lblTracklets.getNElements() << " MC labels are associated to the tracklets"; - } - if (mShowTrackletStats > 0) { - std::chrono::duration digitLoopTime = std::chrono::high_resolution_clock::now() - timeDigitLoopStart; - LOG(info) << "Trap Simulator done "; - LOG(info) << "Digit Sorting took " << sortTime.count() << "s"; - LOG(info) << "Digit loop took : " << digitLoopTime.count() << "s"; - LOG(info) << "TRAP processing TrapSimulator::filter() + TrapSimulator::tracklet() took : " << trapSimAccumulatedTime.count() << "s"; + LOG(info) << "In total " << lblTracklets.getNElements() << " MC labels are associated to the " << lblTracklets.getIndexedSize() << " tracklets"; } - pc.outputs().snapshot(Output{"TRD", "TRACKLETS", 0, Lifetime::Timeframe}, trapTrackletsAccum); - pc.outputs().snapshot(Output{"TRD", "TRKTRGRD", 0, Lifetime::Timeframe}, inputTriggerRecords); + LOG(info) << "Total processing time : " << std::chrono::duration_cast(processingTime).count() << "ms"; + LOG(info) << "Digit Sorting took: " << std::chrono::duration_cast(sortTime).count() << "ms"; + LOG(info) << "Processing time for parallel region: " << std::chrono::duration_cast(parallelTime).count() << "ms"; + + pc.outputs().snapshot(Output{"TRD", "TRACKLETS", 0, Lifetime::Timeframe}, tracklets); + pc.outputs().snapshot(Output{"TRD", "TRKTRGRD", 0, Lifetime::Timeframe}, triggerRecords); if (mUseMC) { pc.outputs().snapshot(Output{"TRD", "TRKLABELS", 0, Lifetime::Timeframe}, lblTracklets); } @@ -331,7 +337,6 @@ o2::framework::DataProcessorSpec getTRDTrapSimulatorSpec(bool useMC) outputs, AlgorithmSpec{adaptFromTask(useMC)}, Options{ - {"show-trd-trackletstats", VariantType::Int, 1, {"Display the processing time of the tracklet processing in the TRAPs"}}, {"trd-trapconfig", VariantType::String, "cf_pg-fpnp32_zs-s16-deh_tb30_trkl-b5n-fs1e24-ht200-qs0e24s24e23-pidlinear-pt100_ptrg.r5549", {"Name of the trap config from the CCDB default:cf_pg-fpnp32_zs-s16-deh_tb30_trkl-b5n-fs1e24-ht200-qs0e24s24e23-pidlinear-pt100_ptrg.r5549"}}, {"trd-onlinegaincorrection", VariantType::Bool, false, {"Apply online gain calibrations, mostly for back checking to run2 by setting FGBY to 0"}}, {"trd-onlinegaintable", VariantType::String, "Krypton_2015-02", {"Online gain table to be use, names found in CCDB, obviously trd-onlinegaincorrection must be set as well."}}, From cdee23dbafb29ef93b32501122dc5c1738bb5d7a Mon Sep 17 00:00:00 2001 From: Ole Schmidt Date: Tue, 6 Apr 2021 09:32:15 +0200 Subject: [PATCH 055/770] Include guards for OpenMP --- Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx b/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx index 3da4d6d85e48b..08e72d7ca86d5 100644 --- a/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx @@ -13,7 +13,10 @@ #include #include #include + +#ifdef WITH_OPENMP #include +#endif #include "TFile.h" @@ -233,7 +236,9 @@ void TRDDPLTrapSimulatorTask::run(o2::framework::ProcessingContext& pc) auto timeParallelStart = std::chrono::high_resolution_clock::now(); +#ifdef WITH_OPENMP #pragma omp parallel for +#endif for (int iTrig = 0; iTrig < triggerRecords.size(); ++iTrig) { int currHCId = -1; std::array trapSimulators{}; //the up to 64 trap simulators for a single half chamber From 074d8e1d507533acf55908b68deee31236dc9872 Mon Sep 17 00:00:00 2001 From: Ole Schmidt Date: Tue, 6 Apr 2021 18:36:34 +0200 Subject: [PATCH 056/770] Make thread number configurable --- .../include/TRDWorkflow/TRDTrapSimulatorSpec.h | 1 + .../TRD/workflow/src/TRDTrapSimulatorSpec.cxx | 14 +++++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrapSimulatorSpec.h b/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrapSimulatorSpec.h index 4ab9997007f1d..5fa2d83e6fce9 100644 --- a/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrapSimulatorSpec.h +++ b/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrapSimulatorSpec.h @@ -47,6 +47,7 @@ class TRDDPLTrapSimulatorTask : public o2::framework::Task bool mEnableOnlineGainCorrection{false}; bool mUseMC{false}; // whether or not to use MC labels bool mEnableTrapConfigDump{false}; + int mNumThreads{-1}; // number of threads used for parallel processing std::string mTrapConfigName; // the name of the config to be used. std::string mOnlineGainTableName; std::unique_ptr mCalib; // store the calibrations connection to CCDB. Used primarily for the gaintables in line above. diff --git a/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx b/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx index 08e72d7ca86d5..eeb2fe2ba21d3 100644 --- a/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx @@ -29,6 +29,7 @@ #include "TRDBase/Digit.h" #include "TRDBase/Calibrations.h" +#include "TRDSimulation/TRDSimParams.h" #include "DataFormatsTRD/TriggerRecord.h" using namespace o2::framework; @@ -181,6 +182,16 @@ void TRDDPLTrapSimulatorTask::init(o2::framework::InitContext& ic) mCalib->setCCDBForSimulation(mRunNumber); getTrapConfig(); setOnlineGainTables(); +#ifdef WITH_OPENMP + int askedThreads = TRDSimParams::Instance().digithreads; + int maxThreads = omp_get_max_threads(); + if (askedThreads < 0) { + mNumThreads = maxThreads; + } else { + mNumThreads = std::min(maxThreads, askedThreads); + } + LOG(info) << "Trap simulation running with " << mNumThreads << " threads "; +#endif LOG(info) << "Trap Simulator Device initialised for config : " << mTrapConfigName; } @@ -237,7 +248,8 @@ void TRDDPLTrapSimulatorTask::run(o2::framework::ProcessingContext& pc) auto timeParallelStart = std::chrono::high_resolution_clock::now(); #ifdef WITH_OPENMP -#pragma omp parallel for + omp_set_num_threads(mNumThreads); +#pragma omp parallel for schedule(dynamic) #endif for (int iTrig = 0; iTrig < triggerRecords.size(); ++iTrig) { int currHCId = -1; From f661bf619fa96528ef65fb6a9c81fecfb241d13e Mon Sep 17 00:00:00 2001 From: Ole Schmidt Date: Tue, 6 Apr 2021 18:51:46 +0200 Subject: [PATCH 057/770] Accept configKeyValues in TRAPsim workflow --- Detectors/TRD/workflow/src/TRDTrapSimulatorWorkFlow.cxx | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Detectors/TRD/workflow/src/TRDTrapSimulatorWorkFlow.cxx b/Detectors/TRD/workflow/src/TRDTrapSimulatorWorkFlow.cxx index 6489db574c73a..61e4a047206ed 100644 --- a/Detectors/TRD/workflow/src/TRDTrapSimulatorWorkFlow.cxx +++ b/Detectors/TRD/workflow/src/TRDTrapSimulatorWorkFlow.cxx @@ -67,6 +67,13 @@ void customize(std::vector& workflowoptions) // std::string trapsimconfighelp("Specify the Trap config to use from CCDB yes those long names like cf_pg-fpnp32_zs-s16-deh_tb24_trkl-b2p-fs1e24-ht200-qs0e24s24e23-pidlinear-pt100_ptrg.r5585"); // workflowoptions.push_back(ConfigParamSpec{"trapconfigname", VariantType::Int, -1, {trapsimconfighelp}}); + // option allowing to set parameters + std::string keyvaluehelp("Semicolon separated key=value strings (e.g.: 'TRDSimParams.digithreads=4;...')"); + workflowoptions.push_back( + ConfigParamSpec{"configKeyValues", VariantType::String, "", {keyvaluehelp}}); + workflowoptions.push_back( + ConfigParamSpec{"configFile", VariantType::String, "", {"configuration file for configurable parameters"}}); + // json output // run2 input // trap configuration @@ -83,6 +90,8 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) // at the end. This places the processor at the beginning of the // workflow in the upper left corner of the GUI. // + using namespace o2::conf; + ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); WorkflowSpec specs; auto useMC = !configcontext.options().get("disable-mc"); auto disableRootInput = configcontext.options().get("disable-root-input"); From adb59350356ee43b61b0e60bcd9f7008bf3383af Mon Sep 17 00:00:00 2001 From: Ole Schmidt Date: Tue, 6 Apr 2021 21:12:44 +0200 Subject: [PATCH 058/770] Enable TRD TRAP sim by default, avoid global OpenMP setting --- Detectors/TRD/simulation/src/Digitizer.cxx | 3 +-- Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx | 3 +-- Steer/DigitizerWorkflow/src/SimpleDigitizerWorkflow.cxx | 6 +++--- prodtests/full_system_test.sh | 2 +- 4 files changed, 6 insertions(+), 8 deletions(-) diff --git a/Detectors/TRD/simulation/src/Digitizer.cxx b/Detectors/TRD/simulation/src/Digitizer.cxx index 01a04bf76f75a..f94c6652cfb59 100644 --- a/Detectors/TRD/simulation/src/Digitizer.cxx +++ b/Detectors/TRD/simulation/src/Digitizer.cxx @@ -157,9 +157,8 @@ void Digitizer::process(std::vector const& hits) getHitContainerPerDetector(hits, hitsPerDetector); #ifdef WITH_OPENMP - omp_set_num_threads(mNumThreads); // Loop over all TRD detectors (in a parallel fashion) -#pragma omp parallel for schedule(dynamic) +#pragma omp parallel for schedule(dynamic) num_threads(mNumThreads) #endif for (int det = 0; det < MAXCHAMBER; ++det) { #ifdef WITH_OPENMP diff --git a/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx b/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx index eeb2fe2ba21d3..8e9ae3d3b37c4 100644 --- a/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx @@ -248,8 +248,7 @@ void TRDDPLTrapSimulatorTask::run(o2::framework::ProcessingContext& pc) auto timeParallelStart = std::chrono::high_resolution_clock::now(); #ifdef WITH_OPENMP - omp_set_num_threads(mNumThreads); -#pragma omp parallel for schedule(dynamic) +#pragma omp parallel for schedule(dynamic) num_threads(mNumThreads) #endif for (int iTrig = 0; iTrig < triggerRecords.size(); ++iTrig) { int currHCId = -1; diff --git a/Steer/DigitizerWorkflow/src/SimpleDigitizerWorkflow.cxx b/Steer/DigitizerWorkflow/src/SimpleDigitizerWorkflow.cxx index bc54b8c607584..ea1e554b73287 100644 --- a/Steer/DigitizerWorkflow/src/SimpleDigitizerWorkflow.cxx +++ b/Steer/DigitizerWorkflow/src/SimpleDigitizerWorkflow.cxx @@ -174,7 +174,7 @@ void customize(std::vector& workflowOptions) workflowOptions.push_back(ConfigParamSpec{"use-ccdb-tof", o2::framework::VariantType::Bool, false, {"enable access to ccdb tof calibration objects"}}); // option to use or not use the Trap Simulator after digitisation (debate of digitization or reconstruction is for others) - workflowOptions.push_back(ConfigParamSpec{"enable-trd-trapsim", VariantType::Bool, false, {"enable the trap simulation of the TRD"}}); + workflowOptions.push_back(ConfigParamSpec{"disable-trd-trapsim", VariantType::Bool, false, {"disable the trap simulation of the TRD"}}); } void customize(std::vector& policies) @@ -544,8 +544,8 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) specs.emplace_back(o2::trd::getTRDDigitizerSpec(fanoutsize++, mctruth)); // connect the TRD digit writer specs.emplace_back(o2::trd::getTRDDigitWriterSpec(mctruth)); - auto enableTrapSim = configcontext.options().get("enable-trd-trapsim"); - if (enableTrapSim) { + auto disableTrapSim = configcontext.options().get("disable-trd-trapsim"); + if (!disableTrapSim) { // connect the TRD Trap SimulatorA specs.emplace_back(o2::trd::getTRDTrapSimulatorSpec(mctruth)); // connect to the device to write out the tracklets. diff --git a/prodtests/full_system_test.sh b/prodtests/full_system_test.sh index a608ab6c58d91..a1c3e8c3ccf3f 100755 --- a/prodtests/full_system_test.sh +++ b/prodtests/full_system_test.sh @@ -61,7 +61,7 @@ QED2HAD=$(awk "BEGIN {printf \"%.2f\",`grep xSectionQED qedgenparam.ini | cut -d echo "Obtained ratio of QED to hadronic x-sections = $QED2HAD" >> qedsim.log cd .. -DIGITRDOPTREAL="--configKeyValues \"TRDSimParams.digithreads=${NJOBS}\" --enable-trd-trapsim" +DIGITRDOPTREAL="--configKeyValues \"TRDSimParams.digithreads=${NJOBS}\" " if [ $SPLITTRDDIGI == "1" ]; then DIGITRDOPT="--skipDet TRD" else From c92104f1f6536a9ff117059fd27dae4ac9a27dbe Mon Sep 17 00:00:00 2001 From: zhangbiao-phy <52267892+zhangbiao-phy@users.noreply.github.com> Date: Wed, 7 Apr 2021 20:19:11 +0800 Subject: [PATCH 059/770] PWGHF: Use labeled array for configurable cuts in Jpsi to ee selector (#5768) --- .../include/AnalysisCore/HFSelectorCuts.h | 48 ++++++++++++++- .../PWGHF/HFJpsiToEECandidateSelector.cxx | 50 ++++----------- Analysis/Tasks/PWGHF/taskJpsi.cxx | 61 +++++++++++-------- 3 files changed, 92 insertions(+), 67 deletions(-) diff --git a/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h b/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h index fb1459a6cffd5..0681acc1c27a4 100644 --- a/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h +++ b/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h @@ -22,7 +22,8 @@ enum code { kD0bar = -421, kDPlus = 411, kLambdaCPlus = 4122, - kXiCPlus = 4232 + kXiCPlus = 4232, + kJpsi = 443 }; } @@ -301,5 +302,50 @@ static const std::vector pTBinLabels = { // column labels static const std::vector cutVarLabels = {"m", "pT p", "pT K", "pT Pi", "DCA", "vertex sigma", "decay length", "cos pointing angle"}; } // namespace hf_cuts_xic_topkpi + +namespace hf_cuts_jpsi_toee +{ +static constexpr int npTBins = 9; +static constexpr int nCutVars = 4; +// default values for the pT bin edges (can be used to configure histogram axis) +// offset by 1 from the bin numbers in cuts array +constexpr double pTBins[npTBins + 1] = { + 0, + 0.5, + 1.0, + 2.0, + 3.0, + 4.0, + 5.0, + 7.0, + 10.0, + 15.0, +}; +auto pTBins_v = std::vector{pTBins, pTBins + npTBins + 1}; + +// default values for the cuts +constexpr double cuts[npTBins][nCutVars] = {{0.5, 0.2, 0.4, 1}, /* 0 pTBinLabels = { + "pT bin 0", + "pT bin 1", + "pT bin 2", + "pT bin 3", + "pT bin 4", + "pT bin 5", + "pT bin 6", + "pT bin 7", + "pT bin 8"}; +// column labels +static const std::vector cutVarLabels = {"m", "DCA_xy", "DCA_z", "pT El"}; +} // namespace hf_cuts_jpsi_toee } // namespace o2::analysis #endif diff --git a/Analysis/Tasks/PWGHF/HFJpsiToEECandidateSelector.cxx b/Analysis/Tasks/PWGHF/HFJpsiToEECandidateSelector.cxx index 27b4d410aca08..2b4ce13f48fd8 100644 --- a/Analysis/Tasks/PWGHF/HFJpsiToEECandidateSelector.cxx +++ b/Analysis/Tasks/PWGHF/HFJpsiToEECandidateSelector.cxx @@ -15,26 +15,14 @@ #include "Framework/runDataProcessing.h" #include "Framework/AnalysisTask.h" +#include "AnalysisCore/HFSelectorCuts.h" #include "AnalysisDataModel/HFSecondaryVertex.h" #include "AnalysisDataModel/HFCandidateSelectionTables.h" using namespace o2; using namespace o2::framework; using namespace o2::aod::hf_cand_prong2; - -static const int npTBins = 9; -static const int nCutVars = 4; -//temporary until 2D array in configurable is solved - then move to json -// mass dcaxy dcaz pt_e -constexpr double cuts[npTBins][nCutVars] = - {{0.5, 0.2, 0.4, 1}, /* pt<0.5 */ - {0.5, 0.2, 0.4, 1}, /* 0.5 d_TPCNClsFindablePIDCut{"d_TPCNClsFindablePIDCut", 70., "Lower bound of TPC findable clusters for good PID"}; Configurable d_nSigmaTPC{"d_nSigmaTPC", 3., "Nsigma cut on TPC only"}; - - /// Gets corresponding pT bin from cut file array - /// \param candpT is the pT of the candidate - /// \return corresponding bin number of array - template - int getpTBin(T candpT) - { - double pTBins[npTBins + 1] = {0, 0.5, 1., 2., 3., 4., 5., 7., 10., 15.}; - if (candpT < pTBins[0] || candpT >= pTBins[npTBins]) { - return -1; - } - for (int i = 0; i < npTBins; i++) { - if (candpT < pTBins[i + 1]) { - return i; - } - } - return -1; - } + Configurable> pTBins{"pTBins", std::vector{hf_cuts_jpsi_toee::pTBins_v}, "pT bin limits"}; + Configurable> cuts{"Jpsi_to_ee_cuts", {hf_cuts_jpsi_toee::cuts[0], npTBins, nCutVars, pTBinLabels, cutVarLabels}, "Jpsi candidate selection per pT bin"}; /// Selection on goodness of daughter tracks /// \note should be applied at candidate selection @@ -91,7 +63,7 @@ struct HFJpsiToEECandidateSelector { bool selectionTopol(const T1& hfCandProng2, const T2& trackPositron, const T2& trackElectron) { auto candpT = hfCandProng2.pt(); - int pTBin = getpTBin(candpT); + auto pTBin = findBin(pTBins, candpT); if (pTBin == -1) { return false; } @@ -100,17 +72,17 @@ struct HFJpsiToEECandidateSelector { return false; //check that the candidate pT is within the analysis range } - if (TMath::Abs(InvMassJpsiToEE(hfCandProng2) - RecoDecay::getMassPDG(443)) > cuts[pTBin][0]) { + if (TMath::Abs(InvMassJpsiToEE(hfCandProng2) - RecoDecay::getMassPDG(pdg::code::kJpsi)) > cuts->get(pTBin, "m")) { return false; } - if ((trackElectron.pt() < cuts[pTBin][3]) || (trackPositron.pt() < cuts[pTBin][3])) { + if (trackElectron.pt() < cuts->get(pTBin, "pT El") || trackPositron.pt() < cuts->get(pTBin, "pT El")) { return false; //cut on daughter pT } - if (TMath::Abs(trackElectron.dcaPrim0()) > cuts[pTBin][1] || TMath::Abs(trackPositron.dcaPrim0()) > cuts[pTBin][1]) { + if (TMath::Abs(trackElectron.dcaPrim0()) > cuts->get(pTBin, "DCA_xy") || TMath::Abs(trackPositron.dcaPrim0()) > cuts->get(pTBin, "DCA_xy")) { return false; //cut on daughter dca - need to add secondary vertex constraint here } - if (TMath::Abs(trackElectron.dcaPrim1()) > cuts[pTBin][2] || TMath::Abs(trackPositron.dcaPrim1()) > cuts[pTBin][2]) { + if (TMath::Abs(trackElectron.dcaPrim1()) > cuts->get(pTBin, "DCA_z") || TMath::Abs(trackPositron.dcaPrim1()) > cuts->get(pTBin, "DCA_z")) { return false; //cut on daughter dca - need to add secondary vertex constraint here } @@ -161,7 +133,7 @@ struct HFJpsiToEECandidateSelector { return -1; //no PID info } } - void process(aod::HfCandProng2 const& hfCandProng2s, aod::BigTracksPID const& tracks) + void process(aod::HfCandProng2 const& hfCandProng2s, aod::BigTracksPID const&) { for (auto& hfCandProng2 : hfCandProng2s) { //looping over 2 prong candidates diff --git a/Analysis/Tasks/PWGHF/taskJpsi.cxx b/Analysis/Tasks/PWGHF/taskJpsi.cxx index 96119dfb9d09c..046eb75f4db30 100644 --- a/Analysis/Tasks/PWGHF/taskJpsi.cxx +++ b/Analysis/Tasks/PWGHF/taskJpsi.cxx @@ -16,10 +16,13 @@ /// \author Biao Zhang , CCNU #include "Framework/AnalysisTask.h" #include "Framework/HistogramRegistry.h" +#include "AnalysisCore/HFSelectorCuts.h" #include "AnalysisDataModel/HFSecondaryVertex.h" #include "AnalysisDataModel/HFCandidateSelectionTables.h" using namespace o2; +using namespace o2::analysis; +using namespace o2::analysis::hf_cuts_jpsi_toee; using namespace o2::framework; using namespace o2::aod::hf_cand_prong2; using namespace o2::framework::expressions; @@ -36,53 +39,57 @@ void customize(std::vector& workflowOptions) struct TaskJpsi { HistogramRegistry registry{ "registry", - {{"hmass", "2-prong candidates;inv. mass (#e+ e-) (GeV/#it{c}^{2});entries", {HistType::kTH1F, {{500, 0., 5.}}}}, - {"hptcand", "2-prong candidates;candidate #it{p}_{T} (GeV/#it{c});entries", {HistType::kTH1F, {{100, 0., 10.}}}}, + {{"hptcand", "2-prong candidates;candidate #it{p}_{T} (GeV/#it{c});entries", {HistType::kTH1F, {{100, 0., 10.}}}}, {"hptprong0", "2-prong candidates;prong 0 #it{p}_{T} (GeV/#it{c});entries", {HistType::kTH1F, {{100, 0., 10.}}}}, - {"hptprong1", "2-prong candidates;prong 1 #it{p}_{T} (GeV/#it{c});entries", {HistType::kTH1F, {{100, 0., 10.}}}}, - {"hdeclength", "2-prong candidates;decay length (cm);entries", {HistType::kTH1F, {{200, 0., 2.}}}}, - {"hdeclengthxy", "2-prong candidates;decay length xy (cm);entries", {HistType::kTH1F, {{200, 0., 2.}}}}, - {"hd0Prong0", "2-prong candidates;prong 0 DCAxy to prim. vertex (cm);entries", {HistType::kTH1F, {{100, -1., 1.}}}}, - {"hd0Prong1", "2-prong candidates;prong 1 DCAxy to prim. vertex (cm);entries", {HistType::kTH1F, {{100, -1., 1.}}}}, - {"hd0d0", "2-prong candidates;product of DCAxy to prim. vertex (cm^{2});entries", {HistType::kTH1F, {{500, -1., 1.}}}}, - {"hCPA", "2-prong candidates;cosine of pointing angle;entries", {HistType::kTH1F, {{110, -1.1, 1.1}}}}, - {"hEta", "2-prong candidates;candidate #it{#eta};entries", {HistType::kTH1F, {{100, -2., 2.}}}}, - {"hImpParErr", "2-prong candidates;impact parameter error (cm);entries", {HistType::kTH1F, {{100, -1., 1.}}}}, - {"hDecLenErr", "2-prong candidates;decay length error (cm);entries", {HistType::kTH1F, {{100, 0., 1.}}}}, - {"hDecLenXYErr", "2-prong candidates;decay length xy error (cm);entries", {HistType::kTH1F, {{100, 0., 1.}}}}}}; + {"hptprong1", "2-prong candidates;prong 1 #it{p}_{T} (GeV/#it{c});entries", {HistType::kTH1F, {{100, 0., 10.}}}}}}; Configurable d_selectionFlagJpsi{"d_selectionFlagJpsi", 1, "Selection Flag for Jpsi"}; Configurable cutYCandMax{"cutYCandMax", -1., "max. cand. rapidity"}; + Configurable> bins{"pTBins", std::vector{hf_cuts_jpsi_toee::pTBins_v}, "pT bin limits"}; + + void init(o2::framework::InitContext&) + { + registry.add("hmass", "2-prong candidates;inv. mass (e^{#plus} e^{#minus}) (GeV/#it{c}^{2});entries", {HistType::kTH2F, {{500, 0., 5.}, {(std::vector)bins, "#it{p}_{T} (GeV/#it{c})"}}}); + registry.add("hdeclength", "2-prong candidates;decay length (cm);entries", {HistType::kTH2F, {{200, 0., 2.}, {(std::vector)bins, "#it{p}_{T} (GeV/#it{c})"}}}); + registry.add("hdeclengthxy", "2-prong candidates;decay length xy (cm);entries", {HistType::kTH2F, {{200, 0., 2.}, {(std::vector)bins, "#it{p}_{T} (GeV/#it{c})"}}}); + registry.add("hd0Prong0", "2-prong candidates;prong 0 DCAxy to prim. vertex (cm);entries", {HistType::kTH2F, {{100, -1., 1.}, {(std::vector)bins, "#it{p}_{T} (GeV/#it{c})"}}}); + registry.add("hd0Prong1", "2-prong candidates;prong 1 DCAxy to prim. vertex (cm);entries", {HistType::kTH2F, {{100, -1., 1.}, {(std::vector)bins, "#it{p}_{T} (GeV/#it{c})"}}}); + registry.add("hd0d0", "2-prong candidates;product of DCAxy to prim. vertex (cm^{2});entries", {HistType::kTH2F, {{500, -1., 1.}, {(std::vector)bins, "#it{p}_{T} (GeV/#it{c})"}}}); + registry.add("hCPA", "2-prong candidates;cosine of pointing angle;entries", {HistType::kTH2F, {{110, -1.1, 1.1}, {(std::vector)bins, "#it{p}_{T} (GeV/#it{c})"}}}); + registry.add("hEta", "2-prong candidates;candidate #it{#eta};entries", {HistType::kTH2F, {{100, -2., 2.}, {(std::vector)bins, "#it{p}_{T} (GeV/#it{c})"}}}); + registry.add("hImpParErr", "2-prong candidates;impact parameter error (cm);entries", {HistType::kTH2F, {{100, -1., 1.}, {(std::vector)bins, "#it{p}_{T} (GeV/#it{c})"}}}); + registry.add("hDecLenErr", "2-prong candidates;decay length error (cm);entries", {HistType::kTH2F, {{100, 0., 1.}, {(std::vector)bins, "#it{p}_{T} (GeV/#it{c})"}}}); + registry.add("hDecLenXYErr", "2-prong candidates;decay length xy error (cm);entries", {HistType::kTH2F, {{100, 0., 1.}, {(std::vector)bins, "#it{p}_{T} (GeV/#it{c})"}}}); + } + Filter filterSelectCandidates = (aod::hf_selcandidate_jpsi::isSelJpsiToEE >= d_selectionFlagJpsi); void process(soa::Filtered> const& candidates) // void process(aod::HfCandProng2 const& candidates) { - //Printf("Candidates: %d", candidates.size()); for (auto& candidate : candidates) { if (!(candidate.hfflag() & 1 << JpsiToEE)) { continue; } if (cutYCandMax >= 0. && std::abs(YJpsi(candidate)) > cutYCandMax) { - //Printf("Candidate: Y rejection: %g", YJpsi(candidate)); continue; } - registry.fill(HIST("hmass"), InvMassJpsiToEE(candidate)); + registry.fill(HIST("hmass"), InvMassJpsiToEE(candidate), candidate.pt()); registry.fill(HIST("hptcand"), candidate.pt()); registry.fill(HIST("hptprong0"), candidate.ptProng0()); registry.fill(HIST("hptprong1"), candidate.ptProng1()); - registry.fill(HIST("hdeclength"), candidate.decayLength()); - registry.fill(HIST("hdeclengthxy"), candidate.decayLengthXY()); - registry.fill(HIST("hd0Prong0"), candidate.impactParameter0()); - registry.fill(HIST("hd0Prong1"), candidate.impactParameter1()); - registry.fill(HIST("hd0d0"), candidate.impactParameterProduct()); - registry.fill(HIST("hCPA"), candidate.cpa()); - registry.fill(HIST("hEta"), candidate.eta()); - registry.fill(HIST("hImpParErr"), candidate.errorImpactParameter0()); - registry.fill(HIST("hImpParErr"), candidate.errorImpactParameter1()); - registry.fill(HIST("hDecLenErr"), candidate.errorDecayLength()); - registry.fill(HIST("hDecLenXYErr"), candidate.errorDecayLengthXY()); + registry.fill(HIST("hdeclength"), candidate.decayLength(), candidate.pt()); + registry.fill(HIST("hdeclengthxy"), candidate.decayLengthXY(), candidate.pt()); + registry.fill(HIST("hd0Prong0"), candidate.impactParameter0(), candidate.pt()); + registry.fill(HIST("hd0Prong1"), candidate.impactParameter1(), candidate.pt()); + registry.fill(HIST("hd0d0"), candidate.impactParameterProduct(), candidate.pt()); + registry.fill(HIST("hCPA"), candidate.cpa(), candidate.pt()); + registry.fill(HIST("hEta"), candidate.eta(), candidate.pt()); + registry.fill(HIST("hImpParErr"), candidate.errorImpactParameter0(), candidate.pt()); + registry.fill(HIST("hImpParErr"), candidate.errorImpactParameter1(), candidate.pt()); + registry.fill(HIST("hDecLenErr"), candidate.errorDecayLength(), candidate.pt()); + registry.fill(HIST("hDecLenXYErr"), candidate.errorDecayLengthXY(), candidate.pt()); } } }; From a62b5e8fad2e8722394095c8d758d400362ce5d9 Mon Sep 17 00:00:00 2001 From: Chiara Zampolli Date: Tue, 6 Apr 2021 13:06:12 +0200 Subject: [PATCH 060/770] Fix in script --- Detectors/Calibration/testMacros/runEPNsimulation.sh | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) mode change 100644 => 100755 Detectors/Calibration/testMacros/runEPNsimulation.sh diff --git a/Detectors/Calibration/testMacros/runEPNsimulation.sh b/Detectors/Calibration/testMacros/runEPNsimulation.sh old mode 100644 new mode 100755 index 0aa6cdd2450e5..44c0e8b011ad3 --- a/Detectors/Calibration/testMacros/runEPNsimulation.sh +++ b/Detectors/Calibration/testMacros/runEPNsimulation.sh @@ -1,19 +1,12 @@ #!/bin/bash - -if [ $# -lt 2 ]; then - # if there is no workflow passed, we pass a "default" one - cmd="o2-calibration-data-generator-workflow --lanes 7 --gen-slot $iEPN --gen-norm 3 --mean-latency 100000 --max-timeframes 500 -b | o2-dpl-output-proxy --channel-config "name=downstream,method=connect,address=tcp://localhost:30453,type=push,transport=zeromq" --dataspec downstream:TOF/CALIBDATA -b ; exec bash" -else - cmd=$2 -fi - iEPN=0 xpos_start=100 while [[ $iEPN -lt $1 ]] do echo $iEPN xpos=$((xpos_start+1000*$iEPN)) - xterm -hold -geometry 150x41+$xpos+300 -e bash -c "${cmd}" & + xterm -hold -geometry 150x41+$xpos+300 -e bash -c "echo $iEPN; o2-calibration-data-generator-workflow --lanes 7 --gen-slot $iEPN --gen-norm 3 --mean-latency 100000 --max-timeframes 500 -b | o2-dpl-output-proxy --channel-config "name=downstream,method=connect,address=tcp://localhost:30453,type=push,transport=zeromq" --dataspec downstream:TOF/CALIBDATA -b ; exec bash" & ((iEPN = iEPN +1 )) done + From 28392f7a0def769b879c8c0c2da0eeb270a5336a Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Thu, 8 Apr 2021 01:02:13 +0200 Subject: [PATCH 061/770] add bitwise operations support to expressions (#5877) --- Analysis/Tutorials/src/filters.cxx | 5 + Framework/Core/include/Framework/BasicOps.h | 6 +- .../Core/include/Framework/Expressions.h | 354 ++++-------------- Framework/Core/src/ExpressionHelpers.h | 8 +- Framework/Core/src/Expressions.cxx | 87 ++--- Framework/Core/test/test_Expressions.cxx | 24 ++ 6 files changed, 163 insertions(+), 321 deletions(-) diff --git a/Analysis/Tutorials/src/filters.cxx b/Analysis/Tutorials/src/filters.cxx index f36887ffadee4..db95f797d30fa 100644 --- a/Analysis/Tutorials/src/filters.cxx +++ b/Analysis/Tutorials/src/filters.cxx @@ -10,6 +10,7 @@ #include "Framework/runDataProcessing.h" #include "Framework/AnalysisTask.h" #include "Framework/AnalysisDataModel.h" +#include namespace o2::aod { @@ -67,6 +68,10 @@ struct BTask { Configurable vtxZ{"vtxZ", 10.f, ""}; Filter posZfilter = nabs(aod::collision::posZ) < vtxZ; +#if ARROW_VERSION_MAJOR < 3 +#else + Filter bitwiseFilter = (o2::aod::track::flags & static_cast(o2::aod::track::TPCrefit)) != 0u; +#endif void process(soa::Filtered::iterator const& collision, soa::Filtered> const& tracks) { diff --git a/Framework/Core/include/Framework/BasicOps.h b/Framework/Core/include/Framework/BasicOps.h index f6bbc0ebe4f08..9f914042500e8 100644 --- a/Framework/Core/include/Framework/BasicOps.h +++ b/Framework/Core/include/Framework/BasicOps.h @@ -19,6 +19,9 @@ enum BasicOp : unsigned int { Subtraction, Division, Multiplication, + BitwiseAnd, + BitwiseOr, + BitwiseXor, LessThan, LessThanOrEqual, GreaterThan, @@ -36,7 +39,8 @@ enum BasicOp : unsigned int { Asin, Acos, Atan, - Abs + Abs, + BitwiseNot }; } // namespace o2::framework diff --git a/Framework/Core/include/Framework/Expressions.h b/Framework/Core/include/Framework/Expressions.h index e255029136ff8..f4057ddfd2aa0 100644 --- a/Framework/Core/include/Framework/Expressions.h +++ b/Framework/Core/include/Framework/Expressions.h @@ -59,7 +59,7 @@ struct LiteralStorage { using stored_pack = framework::pack; }; -using LiteralValue = LiteralStorage; +using LiteralValue = LiteralStorage; template constexpr auto selectArrowType() @@ -82,6 +82,10 @@ constexpr auto selectArrowType() return atype::INT16; } else if constexpr (std::is_same_v) { return atype::INT64; + } else if constexpr (std::is_same_v) { + return atype::UINT32; + } else if constexpr (std::is_same_v) { + return atype::UINT64; } else { return atype::NA; } @@ -178,288 +182,81 @@ struct Node { /// overloaded operators to build the tree from an expression -/// literal comparisons -template -inline Node operator>(Node left, T rightValue) -{ - return Node{OpNode{BasicOp::GreaterThan}, std::move(left), LiteralNode{rightValue}}; -} - -template -inline Node operator<(Node left, T rightValue) -{ - return Node{OpNode{BasicOp::LessThan}, std::move(left), LiteralNode{rightValue}}; -} - -template -inline Node operator>=(Node left, T rightValue) -{ - return Node{OpNode{BasicOp::GreaterThanOrEqual}, std::move(left), LiteralNode{rightValue}}; -} - -template -inline Node operator<=(Node left, T rightValue) -{ - return Node{OpNode{BasicOp::LessThanOrEqual}, std::move(left), LiteralNode{rightValue}}; -} - -template -inline Node operator==(Node left, T rightValue) -{ - return Node{OpNode{BasicOp::Equal}, std::move(left), LiteralNode{rightValue}}; -} - -template -inline Node operator!=(Node left, T rightValue) -{ - return Node{OpNode{BasicOp::NotEqual}, std::move(left), LiteralNode{rightValue}}; -} - -template -inline Node operator>(Node left, Configurable rightValue) -{ - return Node{OpNode{BasicOp::GreaterThan}, std::move(left), PlaceholderNode{rightValue}}; -} - -template -inline Node operator<(Node left, Configurable rightValue) -{ - return Node{OpNode{BasicOp::LessThan}, std::move(left), PlaceholderNode{rightValue}}; -} - -template -inline Node operator>=(Node left, Configurable rightValue) -{ - return Node{OpNode{BasicOp::GreaterThanOrEqual}, std::move(left), PlaceholderNode{rightValue}}; -} - -template -inline Node operator<=(Node left, Configurable rightValue) -{ - return Node{OpNode{BasicOp::LessThanOrEqual}, std::move(left), PlaceholderNode{rightValue}}; -} - -template -inline Node operator==(Node left, Configurable rightValue) -{ - return Node{OpNode{BasicOp::Equal}, std::move(left), PlaceholderNode{rightValue}}; -} - -template -inline Node operator!=(Node left, Configurable rightValue) -{ - return Node{OpNode{BasicOp::NotEqual}, std::move(left), PlaceholderNode{rightValue}}; -} - -/// node comparisons -inline Node operator>(Node left, Node right) -{ - return Node{OpNode{BasicOp::GreaterThan}, std::move(left), std::move(right)}; -} - -inline Node operator<(Node left, Node right) -{ - return Node{OpNode{BasicOp::LessThan}, std::move(left), std::move(right)}; -} - -inline Node operator>=(Node left, Node right) -{ - return Node{OpNode{BasicOp::GreaterThanOrEqual}, std::move(left), std::move(right)}; -} - -inline Node operator<=(Node left, Node right) -{ - return Node{OpNode{BasicOp::LessThanOrEqual}, std::move(left), std::move(right)}; -} - -inline Node operator==(Node left, Node right) -{ - return Node{OpNode{BasicOp::Equal}, std::move(left), std::move(right)}; -} - -inline Node operator!=(Node left, Node right) -{ - return Node{OpNode{BasicOp::NotEqual}, std::move(left), std::move(right)}; -} - -/// logical operations -inline Node operator&&(Node left, Node right) -{ - return Node{OpNode{BasicOp::LogicalAnd}, std::move(left), std::move(right)}; -} - -inline Node operator||(Node left, Node right) -{ - return Node{OpNode{BasicOp::LogicalOr}, std::move(left), std::move(right)}; -} - -/// arithmetical operations between nodes -inline Node operator*(Node left, Node right) -{ - return Node{OpNode{BasicOp::Multiplication}, std::move(left), std::move(right)}; -} - -inline Node operator*(BindingNode left, BindingNode right) -{ - return Node{OpNode{BasicOp::Multiplication}, left, right}; -} - -inline Node operator*(BindingNode left, Node right) -{ - return Node{OpNode{BasicOp::Multiplication}, left, std::move(right)}; -} - -inline Node operator/(Node left, Node right) -{ - return Node{OpNode{BasicOp::Division}, std::move(left), std::move(right)}; -} - -inline Node operator/(BindingNode left, Node right) -{ - return Node{OpNode{BasicOp::Division}, left, std::move(right)}; -} - -inline Node operator/(Node left, BindingNode right) -{ - return Node{OpNode{BasicOp::Division}, std::move(left), right}; -} - -inline Node operator/(BindingNode left, BindingNode right) -{ - return Node{OpNode{BasicOp::Division}, left, right}; -} - -inline Node operator+(Node left, Node right) -{ - return Node{OpNode{BasicOp::Addition}, std::move(left), std::move(right)}; -} - -inline Node operator-(Node left, Node right) -{ - return Node{OpNode{BasicOp::Subtraction}, std::move(left), std::move(right)}; -} - -inline Node operator-(BindingNode left, BindingNode right) -{ - return Node{OpNode{BasicOp::Subtraction}, left, right}; -} - -/// arithmetical operations between node and literal -template -inline Node operator*(Node left, T right) -{ - return Node{OpNode{BasicOp::Multiplication}, std::move(left), LiteralNode{right}}; -} - -template -inline Node operator*(T left, Node right) -{ - return Node{OpNode{BasicOp::Multiplication}, LiteralNode{left}, std::move(right)}; -} - -template -inline Node operator/(Node left, T right) -{ - return Node{OpNode{BasicOp::Division}, std::move(left), LiteralNode{right}}; -} - -template -inline Node operator/(T left, Node right) -{ - return Node{OpNode{BasicOp::Division}, LiteralNode{left}, std::move(right)}; -} - -template -inline Node operator+(Node left, T right) -{ - return Node{OpNode{BasicOp::Addition}, std::move(left), LiteralNode{right}}; -} - -template -inline Node operator+(T left, Node right) -{ - return Node{OpNode{BasicOp::Addition}, LiteralNode{left}, std::move(right)}; -} - -template <> -inline Node operator+(Node left, BindingNode right) -{ - return Node{OpNode{BasicOp::Addition}, std::move(left), right}; -} - -template <> -inline Node operator+(BindingNode left, Node right) -{ - return Node{OpNode{BasicOp::Addition}, left, std::move(right)}; -} - -template -inline Node operator-(Node left, T right) -{ - return Node{OpNode{BasicOp::Subtraction}, std::move(left), LiteralNode{right}}; -} - -template -inline Node operator-(T left, Node right) -{ - return Node{OpNode{BasicOp::Subtraction}, LiteralNode{left}, std::move(right)}; -} - -template -inline Node operator*(Node left, Configurable right) -{ - return Node{OpNode{BasicOp::Multiplication}, std::move(left), PlaceholderNode{right}}; -} - -template -inline Node operator*(Configurable left, Node right) -{ - return Node{OpNode{BasicOp::Multiplication}, PlaceholderNode{left}, std::move(right)}; -} - -template -inline Node operator/(Node left, Configurable right) -{ - return Node{OpNode{BasicOp::Division}, std::move(left), PlaceholderNode{right}}; -} - -template -inline Node operator/(Configurable left, Node right) -{ - return Node{OpNode{BasicOp::Division}, PlaceholderNode{left}, std::move(right)}; -} - -template -inline Node operator+(Node left, Configurable right) -{ - return Node{OpNode{BasicOp::Addition}, std::move(left), PlaceholderNode{right}}; -} - -template -inline Node operator+(Configurable left, Node right) -{ - return Node{OpNode{BasicOp::Addition}, PlaceholderNode{left}, std::move(right)}; -} - -template -inline Node operator-(Node left, Configurable right) -{ - return Node{OpNode{BasicOp::Subtraction}, std::move(left), PlaceholderNode{right}}; -} +#define BINARY_OP_NODES(_operator_, _operation_) \ + template \ + inline Node operator _operator_(Node left, T right) \ + { \ + return Node{OpNode{BasicOp::_operation_}, std::move(left), LiteralNode{right}}; \ + } \ + template \ + inline Node operator _operator_(T left, Node right) \ + { \ + return Node{OpNode{BasicOp::_operation_}, LiteralNode{left}, std::move(right)}; \ + } \ + template \ + inline Node operator _operator_(Node left, Configurable right) \ + { \ + return Node{OpNode{BasicOp::_operation_}, std::move(left), PlaceholderNode{right}}; \ + } \ + template \ + inline Node operator _operator_(Configurable left, Node right) \ + { \ + return Node{OpNode{BasicOp::_operation_}, PlaceholderNode{left}, std::move(right)}; \ + } \ + inline Node operator _operator_(Node left, Node right) \ + { \ + return Node{OpNode{BasicOp::_operation_}, std::move(left), std::move(right)}; \ + } \ + inline Node operator _operator_(BindingNode left, BindingNode right) \ + { \ + return Node{OpNode{BasicOp::_operation_}, left, right}; \ + } \ + template <> \ + inline Node operator _operator_(BindingNode left, Node right) \ + { \ + return Node{OpNode{BasicOp::_operation_}, left, std::move(right)}; \ + } \ + template <> \ + inline Node operator _operator_(Node left, BindingNode right) \ + { \ + return Node{OpNode{BasicOp::_operation_}, std::move(left), right}; \ + } \ + \ + template \ + inline Node operator _operator_(Configurable left, BindingNode right) \ + { \ + return Node{OpNode{BasicOp::_operation_}, PlaceholderNode{left}, right}; \ + } \ + template \ + inline Node operator _operator_(BindingNode left, Configurable right) \ + { \ + return Node{OpNode{BasicOp::_operation_}, left, PlaceholderNode{right}}; \ + } -template -inline Node operator-(Configurable left, Node right) -{ - return Node{OpNode{BasicOp::Subtraction}, PlaceholderNode{left}, std::move(right)}; -} -/// semi-binary +BINARY_OP_NODES(&, BitwiseAnd); +BINARY_OP_NODES(^, BitwiseXor); +BINARY_OP_NODES(|, BitwiseOr); +BINARY_OP_NODES(+, Addition); +BINARY_OP_NODES(-, Subtraction); +BINARY_OP_NODES(*, Multiplication); +BINARY_OP_NODES(/, Division); +BINARY_OP_NODES(>, GreaterThan); +BINARY_OP_NODES(>=, GreaterThanOrEqual); +BINARY_OP_NODES(<, LessThan); +BINARY_OP_NODES(<=, LessThanOrEqual); +BINARY_OP_NODES(==, Equal); +BINARY_OP_NODES(!=, NotEqual); +BINARY_OP_NODES(&&, LogicalAnd); +BINARY_OP_NODES(||, LogicalOr); + +/// functions template inline Node npow(Node left, T right) { return Node{OpNode{BasicOp::Power}, std::move(left), LiteralNode{right}}; } -/// unary operations on nodes +/// unary functions on nodes inline Node nsqrt(Node left) { return Node{OpNode{BasicOp::Sqrt}, std::move(left)}; @@ -515,6 +312,11 @@ inline Node natan(Node left) return Node{OpNode{BasicOp::Atan}, std::move(left)}; } +inline Node nbitwise_not(Node left) +{ + return Node{OpNode{BasicOp::BitwiseNot}, std::move(left)}; +} + /// A struct, containing the root of the expression tree struct Filter { Filter(Node&& node_) : node{std::make_unique(std::move(node_))} {} diff --git a/Framework/Core/src/ExpressionHelpers.h b/Framework/Core/src/ExpressionHelpers.h index 730117a2cc756..5f42fef734d27 100644 --- a/Framework/Core/src/ExpressionHelpers.h +++ b/Framework/Core/src/ExpressionHelpers.h @@ -19,13 +19,16 @@ namespace o2::framework::expressions { /// a map between BasicOp and gandiva node definitions /// note that logical 'and' and 'or' are created separately -static std::array binaryOperationsMap = { +static std::array basicOperationsMap = { "and", "or", "add", "subtract", "divide", "multiply", + "bitwise_and", + "bitwise_or", + "bitwise_xor", "less_than", "less_than_or_equal_to", "greater_than", @@ -43,7 +46,8 @@ static std::array binaryOperationsMap = { "asinf", "acosf", "atanf", - "absf"}; + "absf", + "bitwise_not"}; struct DatumSpec { /// datum spec either contains an index, a value of a literal or a binding label diff --git a/Framework/Core/src/Expressions.cxx b/Framework/Core/src/Expressions.cxx index 0596f7aba606b..524679cf0818c 100644 --- a/Framework/Core/src/Expressions.cxx +++ b/Framework/Core/src/Expressions.cxx @@ -28,28 +28,28 @@ namespace o2::framework::expressions namespace { struct LiteralNodeHelper { - DatumSpec operator()(LiteralNode node) const + DatumSpec operator()(LiteralNode const& node) const { return DatumSpec{node.value, node.type}; } }; struct BindingNodeHelper { - DatumSpec operator()(BindingNode node) const + DatumSpec operator()(BindingNode const& node) const { return DatumSpec{node.name, node.hash, node.type}; } }; struct OpNodeHelper { - ColumnOperationSpec operator()(OpNode node) const + ColumnOperationSpec operator()(OpNode const& node) const { return ColumnOperationSpec{node.op}; } }; struct PlaceholderNodeHelper { - DatumSpec operator()(PlaceholderNode node) const + DatumSpec operator()(PlaceholderNode const& node) const { return DatumSpec{node.value, node.type}; } @@ -69,8 +69,12 @@ std::shared_ptr concreteArrowType(atype::type type) return arrow::uint16(); case atype::INT32: return arrow::int32(); + case atype::UINT32: + return arrow::uint32(); case atype::INT64: return arrow::int64(); + case atype::UINT64: + return arrow::uint64(); case atype::FLOAT: return arrow::float32(); case atype::DOUBLE: @@ -161,9 +165,9 @@ Operations createOperations(Filter const& expression) auto processLeaf = [](Node const* const node) { return std::visit( overloaded{ - [lh = LiteralNodeHelper{}](LiteralNode node) { return lh(node); }, - [bh = BindingNodeHelper{}](BindingNode node) { return bh(node); }, - [ph = PlaceholderNodeHelper{}](PlaceholderNode node) { return ph(node); }, + [lh = LiteralNodeHelper{}](LiteralNode const& node) { return lh(node); }, + [bh = BindingNodeHelper{}](BindingNode const& node) { return bh(node); }, + [ph = PlaceholderNodeHelper{}](PlaceholderNode const& node) { return ph(node); }, [](auto&&) { return DatumSpec{}; }}, node->self); }; @@ -261,10 +265,11 @@ Operations createOperations(Filter const& expression) return t1; } - if (t1 == atype::INT32 || t1 == atype::INT8 || t1 == atype::INT16 || t1 == atype::INT64 || t1 == atype::UINT8) { - if (t2 == atype::INT32 || t2 == atype::INT8 || t2 == atype::INT16 || t2 == atype::INT64 || t2 == atype::UINT8) { - return atype::FLOAT; - } + auto isIntType = [](auto t) { + return (t == atype::UINT8) || (t == atype::INT8) || (t == atype::UINT16) || (t == atype::INT16) || (t == atype::UINT32) || (t == atype::INT32) || (t == atype::UINT64) || (t == atype::INT64); + }; + + if (isIntType(t1)) { if (t2 == atype::FLOAT) { return atype::FLOAT; } @@ -273,7 +278,7 @@ Operations createOperations(Filter const& expression) } } if (t1 == atype::FLOAT) { - if (t2 == atype::INT32 || t2 == atype::INT8 || t2 == atype::INT16 || t2 == atype::INT64 || t2 == atype::UINT8) { + if (isIntType(t2)) { return atype::FLOAT; } if (t2 == atype::DOUBLE) { @@ -350,7 +355,7 @@ std::shared_ptr std::shared_ptr createProjector(gandiva::SchemaPtr const& Schema, Projector&& p, gandiva::FieldPtr result) { - return createProjector(std::move(Schema), createOperations(std::move(p)), std::move(result)); + return createProjector(Schema, createOperations(std::move(p)), std::move(result)); } Selection createSelection(std::shared_ptr table, std::shared_ptr gfilter) @@ -429,34 +434,32 @@ gandiva::NodePtr createExpressionTree(Operations const& opSpecs, if (spec.datum.index() == 2) { auto content = std::get(spec.datum); - if (content.index() == 0) { - return gandiva::TreeExprBuilder::MakeLiteral(static_cast(std::get(content))); - } - if (content.index() == 1) { - return gandiva::TreeExprBuilder::MakeLiteral(std::get(content)); - } - if (content.index() == 2) { - return gandiva::TreeExprBuilder::MakeLiteral(std::get(content)); - } - if (content.index() == 3) { - return gandiva::TreeExprBuilder::MakeLiteral(std::get(content)); - } - if (content.index() == 4) { - return gandiva::TreeExprBuilder::MakeLiteral(std::get(content)); - } - if (content.index() == 5) { - return gandiva::TreeExprBuilder::MakeLiteral(std::get(content)); - } - if (content.index() == 6) { - return gandiva::TreeExprBuilder::MakeLiteral(std::get(content)); - } - if (content.index() == 7) { - return gandiva::TreeExprBuilder::MakeLiteral(std::get(content)); - } - if (content.index() == 8) { - return gandiva::TreeExprBuilder::MakeLiteral(std::get(content)); + switch (content.index()) { + case 0: //int + return gandiva::TreeExprBuilder::MakeLiteral(static_cast(std::get(content))); + case 1: //bool + return gandiva::TreeExprBuilder::MakeLiteral(std::get(content)); + case 2: //float + return gandiva::TreeExprBuilder::MakeLiteral(std::get(content)); + case 3: //double + return gandiva::TreeExprBuilder::MakeLiteral(std::get(content)); + case 4: //uint8 + return gandiva::TreeExprBuilder::MakeLiteral(std::get(content)); + case 5: //int64 + return gandiva::TreeExprBuilder::MakeLiteral(std::get(content)); + case 6: //int16 + return gandiva::TreeExprBuilder::MakeLiteral(std::get(content)); + case 7: //uint16 + return gandiva::TreeExprBuilder::MakeLiteral(std::get(content)); + case 8: //int8 + return gandiva::TreeExprBuilder::MakeLiteral(std::get(content)); + case 9: //uint32 + return gandiva::TreeExprBuilder::MakeLiteral(std::get(content)); + case 10: //uint64 + return gandiva::TreeExprBuilder::MakeLiteral(std::get(content)); + default: + throw runtime_error("Malformed LiteralNode"); } - throw runtime_error("Malformed LiteralNode"); } if (spec.datum.index() == 3) { @@ -514,10 +517,10 @@ gandiva::NodePtr createExpressionTree(Operations const& opSpecs, } else if (it->op == BasicOp::Equal || it->op == BasicOp::NotEqual) { insertEqualizeUpcastNode(leftNode, rightNode, it->left.type, it->right.type); } - tree = gandiva::TreeExprBuilder::MakeFunction(binaryOperationsMap[it->op], {leftNode, rightNode}, concreteArrowType(it->type)); + tree = gandiva::TreeExprBuilder::MakeFunction(basicOperationsMap[it->op], {leftNode, rightNode}, concreteArrowType(it->type)); } else { leftNode = insertUpcastNode(leftNode, it->left.type); - tree = gandiva::TreeExprBuilder::MakeFunction(binaryOperationsMap[it->op], {leftNode}, concreteArrowType(it->type)); + tree = gandiva::TreeExprBuilder::MakeFunction(basicOperationsMap[it->op], {leftNode}, concreteArrowType(it->type)); } break; } diff --git a/Framework/Core/test/test_Expressions.cxx b/Framework/Core/test/test_Expressions.cxx index 944c146f4e5c4..3b94548ed0d36 100644 --- a/Framework/Core/test/test_Expressions.cxx +++ b/Framework/Core/test/test_Expressions.cxx @@ -17,6 +17,7 @@ #include "Framework/AnalysisDataModel.h" #include "Framework/AODReaderHelpers.h" #include +#include using namespace o2::framework; using namespace o2::framework::expressions; @@ -177,4 +178,27 @@ BOOST_AUTO_TEST_CASE(TestGandivaTreeCreation) auto projector_b = createProjector(schema2, ptespecs, resfield2); auto schema_p = o2::soa::createSchemaFromColumns(o2::aod::Tracks::persistent_columns_t{}); auto projector_alt = o2::framework::expressions::createProjectors(o2::framework::pack{}, schema_p); + + Filter bitwiseFilter = (o2::aod::track::flags & static_cast(o2::aod::track::TPCrefit)) != 0u; + auto bwf = createOperations(bitwiseFilter); + BOOST_REQUIRE_EQUAL(bwf[0].left, (DatumSpec{1u, atype::UINT32})); + BOOST_REQUIRE_EQUAL(bwf[0].right, (DatumSpec{LiteralNode::var_t{0u}, atype::UINT32})); + BOOST_REQUIRE_EQUAL(bwf[0].result, (DatumSpec{0u, atype::BOOL})); + + BOOST_REQUIRE_EQUAL(bwf[1].left, (DatumSpec{std::string{"fFlags"}, typeid(o2::aod::track::Flags).hash_code(), atype::UINT32})); + BOOST_REQUIRE_EQUAL(bwf[1].right, (DatumSpec{LiteralNode::var_t{static_cast(o2::aod::track::TPCrefit)}, atype::UINT32})); + BOOST_REQUIRE_EQUAL(bwf[1].result, (DatumSpec{1u, atype::UINT32})); + +#if ARROW_VERSION_MAJOR < 3 +#else + auto infield4 = o2::aod::track::Flags::asArrowField(); + auto resfield3 = std::make_shared("out", arrow::boolean()); + auto schema_b = std::make_shared(std::vector{infield4, resfield3}); + auto gandiva_tree3 = createExpressionTree(bwf, schema_b); + BOOST_CHECK_EQUAL(gandiva_tree3->ToString(), "bool not_equal(uint32 bitwise_and((uint32) fFlags, (const uint32) 2), (const uint32) 0)"); + auto condition = expressions::makeCondition(gandiva_tree3); + std::shared_ptr flt; + auto s = gandiva::Filter::Make(schema_b, condition, &flt); + BOOST_REQUIRE(s.ok()); +#endif } From 1ad7a5edd0cd7c788b053b32dcfeca0fdebf0f66 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Thu, 8 Apr 2021 01:05:23 +0200 Subject: [PATCH 062/770] DPL: throw exception if bad type requested for option (#5862) --- Framework/Core/include/Framework/ConfigParamRegistry.h | 1 + 1 file changed, 1 insertion(+) diff --git a/Framework/Core/include/Framework/ConfigParamRegistry.h b/Framework/Core/include/Framework/ConfigParamRegistry.h index 306a77bf06f15..c1fbbe8b3f34c 100644 --- a/Framework/Core/include/Framework/ConfigParamRegistry.h +++ b/Framework/Core/include/Framework/ConfigParamRegistry.h @@ -83,6 +83,7 @@ class ConfigParamRegistry } catch (...) { throw std::invalid_argument(std::string("error parsing option: ") + key); } + throw std::invalid_argument(std::string("bad type for option: ") + key); } private: From 32fb9425115f095b979fc604f9ca584e190948b5 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Thu, 8 Apr 2021 01:07:17 +0200 Subject: [PATCH 063/770] Drop ability of DataHeader to print itself (#5743) This allows us to drop the templated Print policy from the DataHeader.h classes, hopefully simplifying the code. As a replacement for the various print methods one can use DataHeaderHelpers.h in conjuction with the various fmt / Logger.h methods. --- .../Headers/include/Headers/DataHeader.h | 43 +++---------------- DataFormats/Headers/src/DataHeader.cxx | 34 --------------- 2 files changed, 7 insertions(+), 70 deletions(-) diff --git a/DataFormats/Headers/include/Headers/DataHeader.h b/DataFormats/Headers/include/Headers/DataHeader.h index a4741348685e5..1a2c9f8a013eb 100644 --- a/DataFormats/Headers/include/Headers/DataHeader.h +++ b/DataFormats/Headers/include/Headers/DataHeader.h @@ -42,9 +42,7 @@ #include "MemoryResources/Types.h" #include -namespace o2 -{ -namespace header +namespace o2::header { //__________________________________________________________________________________________________ @@ -148,10 +146,6 @@ struct TraitsIntType<4> { using Type = uint32_t; }; -struct defaultPrinter { - void operator()(const char* str) const {} -}; - /// compile time evaluation of a string length, which is either N - 1 or /// shorter if one character in the array has been set to 0. template @@ -253,7 +247,7 @@ struct DescriptorCompareTraits<2> { /// solution is working also for multiples of 64 bit, but then the itg member needs /// to be an array for all. This has not been enabled yet, first the implications /// have to be studied. -template +template struct Descriptor { static_assert(internal::NumberOfActiveBits::value == 1, "Descriptor size is required to be a power of 2"); @@ -351,13 +345,6 @@ struct Descriptor { std::string ret(str, len); return std::move(ret); } - // print function needs to be implemented for every derivation - void print() const - { - // eventually terminate string before printing - PrinterPolicy printer; - printer(str); - }; }; //__________________________________________________________________________________________________ @@ -593,20 +580,8 @@ T stoui(const std::string& str, size_t* pos = nullptr, int base = 10) } }; -//__________________________________________________________________________________________________ -/// this 128 bit type for a header field describing the payload data type -struct printDataDescription { - void operator()(const char* str) const; -}; - -using DataDescription = Descriptor; - -//__________________________________________________________________________________________________ -// 32bit (4 characters) for data origin, ex. the detector or subsystem name -struct printDataOrigin { - void operator()(const char* str) const; -}; -using DataOrigin = Descriptor; +using DataOrigin = Descriptor; +using DataDescription = Descriptor; //__________________________________________________________________________________________________ /// @defgroup data_description_defines Defines for data description @@ -789,7 +764,6 @@ struct DataHeader : public BaseHeader { bool operator==(const DataOrigin&) const; //comparison bool operator==(const DataDescription&) const; //comparison bool operator==(const SerializationMethod&) const; //comparison - void print() const; ///pretty print the contents static const DataHeader* Get(const BaseHeader* baseHeader) { @@ -818,7 +792,6 @@ struct DataIdentifier { } bool operator==(const DataIdentifier&) const; - void print() const; }; //__________________________________________________________________________________________________ @@ -843,12 +816,10 @@ template struct is_descriptor : std::false_type { }; -template -struct is_descriptor> : std::true_type { +template +struct is_descriptor> : std::true_type { }; -} //namespace header - -} //namespace o2 +} //namespace o2::header #endif diff --git a/DataFormats/Headers/src/DataHeader.cxx b/DataFormats/Headers/src/DataHeader.cxx index 0fe5c446cc5a2..33f7f47c70df8 100644 --- a/DataFormats/Headers/src/DataHeader.cxx +++ b/DataFormats/Headers/src/DataHeader.cxx @@ -51,21 +51,6 @@ void o2::header::BaseHeader::throwInconsistentStackError() const throw std::runtime_error("inconsistent header stack, no O2 header at expected offset " + std::to_string(this->headerSize) + "for header of type " + this->description.as()); } -//__________________________________________________________________________________________________ -void o2::header::DataHeader::print() const -{ - printf("Data header version %u, flags: %u\n", headerVersion, flags); - printf(" origin : %s\n", dataOrigin.str); - printf(" serialization: %s\n", payloadSerializationMethod.str); - printf(" description : %s\n", dataDescription.str); - printf(" sub spec. : %llu\n", (long long unsigned int)subSpecification); - printf(" header size : %d\n", headerSize); - printf(" payloadSize : %llu\n", (long long unsigned int)payloadSize); - printf(" firstTFOrbit : %u\n", firstTForbit); - printf(" tfCounter : %u\n", tfCounter); - printf(" runNumber : %u\n", runNumber); -} - //__________________________________________________________________________________________________ bool o2::header::DataHeader::operator==(const DataOrigin& that) const { @@ -98,18 +83,6 @@ bool o2::header::DataHeader::operator==(const DataHeader& that) const subSpecification == that.subSpecification); } -//__________________________________________________________________________________________________ -void o2::header::printDataDescription::operator()(const char* str) const -{ - printf("Data description : %s\n", str); -} - -//__________________________________________________________________________________________________ -void o2::header::printDataOrigin::operator()(const char* str) const -{ - printf("Data origin : %s\n", str); -} - //__________________________________________________________________________________________________ o2::header::DataIdentifier::DataIdentifier() : dataDescription(), dataOrigin() @@ -129,13 +102,6 @@ bool o2::header::DataIdentifier::operator==(const DataIdentifier& other) const return true; } -//__________________________________________________________________________________________________ -void o2::header::DataIdentifier::print() const -{ - dataOrigin.print(); - dataDescription.print(); -} - //__________________________________________________________________________________________________ void o2::header::hexDump(const char* desc, const void* voidaddr, size_t len, size_t max) { From 2164654c676b88091cef248aec020d57430fe749 Mon Sep 17 00:00:00 2001 From: swenzel Date: Thu, 1 Apr 2021 14:29:43 +0200 Subject: [PATCH 064/770] A tool to combine multiple TTrees into one (union of branches) Use cases: - store TPC clusters (per sector) in separate files and later provide a single file that TPC tracking expects. --- Common/Utils/CMakeLists.txt | 5 + Common/Utils/src/TreeMergerTool.cxx | 157 ++++++++++++++++++++++++++++ 2 files changed, 162 insertions(+) create mode 100644 Common/Utils/src/TreeMergerTool.cxx diff --git a/Common/Utils/CMakeLists.txt b/Common/Utils/CMakeLists.txt index 106b76857ac8f..87d6ad4ede1c5 100644 --- a/Common/Utils/CMakeLists.txt +++ b/Common/Utils/CMakeLists.txt @@ -67,3 +67,8 @@ o2_add_test(MemFileHelper LABELS utils SOURCES test/testMemFileHelper.cxx PUBLIC_LINK_LIBRARIES O2::CommonUtils) + +o2_add_executable(treemergertool + COMPONENT_NAME CommonUtils + SOURCES src/TreeMergerTool.cxx + PUBLIC_LINK_LIBRARIES O2::CommonUtils Boost::program_options ROOT::Core) diff --git a/Common/Utils/src/TreeMergerTool.cxx b/Common/Utils/src/TreeMergerTool.cxx new file mode 100644 index 0000000000000..1d6f4c187fcd1 --- /dev/null +++ b/Common/Utils/src/TreeMergerTool.cxx @@ -0,0 +1,157 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +// A utility for the purpose to produce a global merged TTree +// from multiple TTree (containing a subset of branches). +// A typical example is TPC clusterization/digitization: Clusters per TPC +// sector may sit in different files and we want to produce an aggregate TTree +// for further processing. The utility offers options to use TFriends or to make +// a deep copy. + +#include +#include +#include +#include +#include +#include +#include + +struct Options { + std::vector infilenames; + std::string treename; + std::string outfilename; + bool asfriend = false; +}; + +bool parseOptions(int argc, char* argv[], Options& optvalues) +{ + namespace bpo = boost::program_options; + bpo::options_description options( + "A tool to create a single TTree from a list of TTrees (each in its own file).\nMerging is " + "done vertically - over branches - instead over entries (like in a TChain).\nIt corresponds to the TFriend mechanism but makes a deep copy\n" + "(unless the friend is asked).\n\n" + "Allowed options"); + + options.add_options()( + "infiles,i", bpo::value>(&optvalues.infilenames)->multitoken(), "All input files to be merged")( + "treename,t", bpo::value(&optvalues.treename), "Name of tree (assumed same in all files).")( + "outfile,o", bpo::value(&optvalues.outfilename)->default_value(""), "Outfile to be created with merged tree.")( + "asfriend", "If merging is done using the friend mechanism."); + options.add_options()("help,h", "Produce help message."); + + bpo::variables_map vm; + try { + bpo::store(bpo::command_line_parser(argc, argv).options(options).run(), vm); + bpo::notify(vm); + + // help + if (vm.count("help")) { + std::cout << options << std::endl; + return false; + } + if (vm.count("asfriend")) { + optvalues.asfriend = true; + } + + } catch (const bpo::error& e) { + std::cerr << e.what() << "\n\n"; + std::cerr << "Error parsing options; Available options:\n"; + std::cerr << options << std::endl; + return false; + } + return true; +} + +// Checks if all given files have a TTree of this name +// and if all entries are the same +// TODO: add more checks such as for non-overlapping branch names etc. +bool checkFiles(std::vector const& filenames, std::string const& treename) +{ + bool ok = true; + int entries = -1; + for (auto& f : filenames) { + TFile _tmpfile(f.c_str(), "OPEN"); + auto tree = (TTree*)_tmpfile.Get(treename.c_str()); + if (tree == nullptr) { + ok = false; + std::cerr << "File " << f << " doesn't have a tree of name " << treename; + } else { + if (entries == -1) { + entries = tree->GetEntries(); + } else { + if (entries != tree->GetEntries()) { + std::cerr << "Trees have inconsistent number of entries "; + ok = false; + } + } + } + } + return ok; +} + +void merge(Options const& options) +{ + if (options.asfriend) { + // open the output file + auto newfile = TFile::Open(options.outfilename.c_str(), "RECREATE"); + auto newtree = new TTree(options.treename.c_str(), ""); + // add remaining stuff as friend + for (int i = 0; i < options.infilenames.size(); ++i) { + newtree->AddFriend(options.treename.c_str(), options.infilenames[i].c_str()); + } + newfile->Write(); + newfile->Close(); + + // P. Canal suggests that this can be done in the following way to fix the branch names + // in the merged file and to keep only the final file: + //auto mainfile = TFile::Open(firsttreefilename, "UPDATE"); + //auto friendfile = TFile::Open(secondtreefilename, "READ"); + //auto friendtree = ffriendfile>Get(secondtreename); + //mainfile->cd(); + //auto friendcopy = friendtree->CloneTree(-1, "fast"); + //auto maintree = mainfile->Get(firsttreename); + //maintree->AddFriend(friendcopy); + //mainfile->Write(); + } else { + // NOTE: This is functional but potentially slow solution. + // We should adapt this function as soon as more performant + // ways are known. + // See also: https://root-forum.cern.ch/t/make-a-new-ttree-from-a-deep-vertical-union-of-existing-ttrees/44250 + + // open the first Tree + TFile _tmpfile(options.infilenames[0].c_str(), "OPEN"); + auto t1 = (TTree*)_tmpfile.Get(options.treename.c_str()); + + // add remaining stuff as friend + for (int i = 1; i < options.infilenames.size(); ++i) { + t1->AddFriend(options.treename.c_str(), options.infilenames[i].c_str()); + } + ROOT::RDataFrame df(*t1); + df.Snapshot(options.treename, options.outfilename); + } +} + +int main(int argc, char* argv[]) +{ + Options optvalues; + if (!parseOptions(argc, argv, optvalues)) { + return 0; + } + + auto ok = checkFiles(optvalues.infilenames, optvalues.treename); + if (!ok) { + return 1; + } + + // merge files + merge(optvalues); + + return 0; +} From e25e46c5a86ae5ef0b47af0ec5691ef0cb2f184c Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Thu, 8 Apr 2021 10:09:47 +0200 Subject: [PATCH 065/770] DPL: provide a `--spawners ` option (#5881) Similar to --readers allows creating spawners which work in a time-pipelined way. --- Framework/Core/src/WorkflowCustomizationHelpers.cxx | 1 + Framework/Core/src/WorkflowHelpers.cxx | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Framework/Core/src/WorkflowCustomizationHelpers.cxx b/Framework/Core/src/WorkflowCustomizationHelpers.cxx index 9742f8c40c582..5ee63b079b9af 100644 --- a/Framework/Core/src/WorkflowCustomizationHelpers.cxx +++ b/Framework/Core/src/WorkflowCustomizationHelpers.cxx @@ -32,6 +32,7 @@ namespace o2::framework std::vector WorkflowCustomizationHelpers::requiredWorkflowOptions() { return std::vector{{ConfigParamSpec{"readers", VariantType::Int64, 1ll, {"number of parallel readers to use"}}, + ConfigParamSpec{"spawners", VariantType::Int64, 1ll, {"number of parallel spawners to use"}}, ConfigParamSpec{"pipeline", VariantType::String, "", {"override default pipeline size"}}, ConfigParamSpec{"clone", VariantType::String, "", {"clone processors from a template"}}, ConfigParamSpec{"workflow-suffix", VariantType::String, "", {"suffix to add to all dataprocessors"}}, diff --git a/Framework/Core/src/WorkflowHelpers.cxx b/Framework/Core/src/WorkflowHelpers.cxx index f6ff263f46b8e..82a98b3daffc2 100644 --- a/Framework/Core/src/WorkflowHelpers.cxx +++ b/Framework/Core/src/WorkflowHelpers.cxx @@ -409,7 +409,7 @@ void WorkflowHelpers::injectServiceDevices(WorkflowSpec& workflow, ConfigContext } if (aodSpawner.outputs.empty() == false) { - extraSpecs.push_back(aodSpawner); + extraSpecs.push_back(timePipeline(aodSpawner, ctx.options().get("spawners"))); } if (indexBuilder.outputs.empty() == false) { From 9a960a0b7a23017490a9508a2f7297b4565c4850 Mon Sep 17 00:00:00 2001 From: ddobrigk Date: Thu, 8 Apr 2021 05:56:58 -0300 Subject: [PATCH 066/770] Run 2 enums from DataTypes (#5844) * Run 2 enums from DataTypes * Update ALICE3toAO2D.C * Update ALICE3toAO2D.C --- .../AOD/include/UpgradesAODUtils/Run2LikeAO2D.h | 14 +------------- .../Upgrades/ALICE3/TRK/macros/ALICE3toAO2D.C | 9 +++++---- 2 files changed, 6 insertions(+), 17 deletions(-) diff --git a/Detectors/Upgrades/ALICE3/AOD/include/UpgradesAODUtils/Run2LikeAO2D.h b/Detectors/Upgrades/ALICE3/AOD/include/UpgradesAODUtils/Run2LikeAO2D.h index 6ef7f8fbde2b6..b43cf3999fa3b 100644 --- a/Detectors/Upgrades/ALICE3/AOD/include/UpgradesAODUtils/Run2LikeAO2D.h +++ b/Detectors/Upgrades/ALICE3/AOD/include/UpgradesAODUtils/Run2LikeAO2D.h @@ -52,18 +52,6 @@ enum TreeIndex { // Index of the output trees kTrees //N/A }; -enum TrackTypeEnum : uint8_t { - GlobalTrack = 0, - ITSStandalone, - MFTStandalone, - Run2GlobalTrack = 254, - Run2Tracklet = 255 -}; // corresponds to O2/Core/Framework/include/Framework/DataTypes.h -enum TrackFlagsRun2Enum { - ITSrefit = 0x1, - TPCrefit = 0x2, - GoldenChi2 = 0x4 -}; // corresponds to O2/Core/Framework/include/Framework/DataTypes.h enum MCParticleFlags : uint8_t { ProducedInTransport = 1 // Bit 0: 0 = from generator; 1 = from transport }; @@ -309,4 +297,4 @@ struct { } // namespace upgrades_utils } // namespace o2 -#endif \ No newline at end of file +#endif diff --git a/Detectors/Upgrades/ALICE3/TRK/macros/ALICE3toAO2D.C b/Detectors/Upgrades/ALICE3/TRK/macros/ALICE3toAO2D.C index 6174a56b5d0b7..f7ebbe8dc9129 100644 --- a/Detectors/Upgrades/ALICE3/TRK/macros/ALICE3toAO2D.C +++ b/Detectors/Upgrades/ALICE3/TRK/macros/ALICE3toAO2D.C @@ -48,6 +48,7 @@ #include "SimulationDataFormat/MCTruthContainer.h" #include "ReconstructionDataFormats/DCA.h" #include "ReconstructionDataFormats/Vertex.h" +#include "Framework/DataTypes.h" #include "UpgradesAODUtils/Run2LikeAO2D.h" #endif @@ -528,12 +529,12 @@ void ALICE3toAO2D() hPtSpectraFake->Fill(track.getPt()); tracks.fCollisionsID = lEventNumber; - tracks.fTrackType = TrackTypeEnum::Run2GlobalTrack; //Make track selection happy, please + tracks.fTrackType = o2::aod::track::TrackTypeEnum::Run2Track; //Make track selection happy, please tracks.fFlags = 0x0; //Assume it all worked, fool regular selections - tracks.fFlags |= TrackFlagsRun2Enum::ITSrefit; - tracks.fFlags |= TrackFlagsRun2Enum::TPCrefit; - tracks.fFlags |= TrackFlagsRun2Enum::GoldenChi2; + tracks.fFlags |= o2::aod::track::TrackFlagsRun2Enum::ITSrefit; + tracks.fFlags |= o2::aod::track::TrackFlagsRun2Enum::TPCrefit; + tracks.fFlags |= o2::aod::track::TrackFlagsRun2Enum::GoldenChi2; //Main: X, alpha, track params tracks.fX = track.getX(); From f9c10bf9d433ea846cddd480ca87e73f0709017f Mon Sep 17 00:00:00 2001 From: shahoian Date: Thu, 8 Apr 2021 15:54:51 +0200 Subject: [PATCH 067/770] Add extra back-up pattern to .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index ff8b7c86c8974..11b09f52f187f 100644 --- a/.gitignore +++ b/.gitignore @@ -39,6 +39,7 @@ xbuild/ # common editor backups *.swp *~ +\#*\# # doxygen stuff html-doc/ From e684ba815e5fe504718ebaa83c9c013991387bcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADt=20Ku=C4=8Dera?= Date: Thu, 8 Apr 2021 16:19:04 +0200 Subject: [PATCH 068/770] Fix matching bug. (#5884) --- Analysis/Tasks/PWGHF/HFCandidateCreator3Prong.cxx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Analysis/Tasks/PWGHF/HFCandidateCreator3Prong.cxx b/Analysis/Tasks/PWGHF/HFCandidateCreator3Prong.cxx index d5b9967f602a6..324cb7b661ab4 100644 --- a/Analysis/Tasks/PWGHF/HFCandidateCreator3Prong.cxx +++ b/Analysis/Tasks/PWGHF/HFCandidateCreator3Prong.cxx @@ -210,7 +210,8 @@ struct HFCandidateCreator3ProngMC { // Ξc± → p± K∓ π± if (flag == 0) { //Printf("Checking Ξc± → p± K∓ π±"); - if (RecoDecay::getMatchedMCRec(particlesMC, std::move(arrayDaughters), 4232, array{+kProton, -kKPlus, +kPiPlus}, true, &sign) > -1) { + indexRec = RecoDecay::getMatchedMCRec(particlesMC, std::move(arrayDaughters), 4232, array{+kProton, -kKPlus, +kPiPlus}, true, &sign); + if (indexRec > -1) { flag = sign * (1 << XicToPKPi); } } From c39fdb3c485a53ec60fbfcfc74554767f012e2a9 Mon Sep 17 00:00:00 2001 From: shahoian Date: Sun, 4 Apr 2021 00:40:49 +0200 Subject: [PATCH 069/770] MC->raw converters use HBFUtils settings of digitization --- Detectors/CPV/simulation/src/RawCreator.cxx | 11 +++++++---- Detectors/EMCAL/simulation/src/RawCreator.cxx | 11 +++++++---- Detectors/FIT/FDD/simulation/src/digit2raw.cxx | 9 +++++---- Detectors/FIT/FT0/simulation/src/digi2raw.cxx | 9 +++++---- Detectors/FIT/FV0/simulation/src/digit2raw.cxx | 9 +++++---- .../tofworkflow/src/tof-reco-workflow.cxx | 7 +++---- .../HMPID/workflow/src/digits-to-raw-workflow.cxx | 7 +++---- Detectors/ITSMFT/ITS/simulation/CMakeLists.txt | 7 +++++++ Detectors/ITSMFT/ITS/simulation/src/digi2raw.cxx | 9 +++++---- Detectors/ITSMFT/MFT/simulation/src/digi2raw.cxx | 9 +++++---- Detectors/MUON/MCH/Raw/Encoder/Digit/digit2raw.cxx | 9 +++++---- .../MUON/MID/Workflow/src/digits-to-raw-workflow.cxx | 7 +++---- Detectors/PHOS/simulation/src/RawCreator.cxx | 11 +++++++---- Detectors/TOF/simulation/src/digi2raw.cxx | 6 +++--- Detectors/TPC/simulation/run/convertDigitsToRawZS.cxx | 9 +++++---- Detectors/ZDC/simulation/src/digi2raw.cxx | 9 +++++---- 16 files changed, 80 insertions(+), 59 deletions(-) diff --git a/Detectors/CPV/simulation/src/RawCreator.cxx b/Detectors/CPV/simulation/src/RawCreator.cxx index 3a90cd1ddd608..f4cda9cdf11c1 100644 --- a/Detectors/CPV/simulation/src/RawCreator.cxx +++ b/Detectors/CPV/simulation/src/RawCreator.cxx @@ -49,8 +49,7 @@ int main(int argc, const char** argv) add_option("file-for,f", bpo::value()->default_value("all"), "single file per: all,link"); add_option("output-dir,o", bpo::value()->default_value("./"), "output directory for raw data"); add_option("debug,d", bpo::value()->default_value(0), "Select debug output level [0 = no debug output]"); - //add_option("digitization-config,d", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "configKeyValues file from digitization"); - add_option("digitization-config,d", bpo::value()->default_value("none"), "configKeyValues file from digitization"); + add_option("hbfutils-config,u", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "config file for HBFUtils (or none)"); add_option("configKeyValues", bpo::value()->default_value(""), "comma-separated configKeyValues"); opt_all.add(opt_general).add(opt_hidden); @@ -71,9 +70,9 @@ int main(int argc, const char** argv) exit(2); } - std::string confDig = vm["digitization-config"].as(); + std::string confDig = vm["hbfutils-config"].as(); if (!confDig.empty() && confDig != "none") { - o2::conf::ConfigurableParam::updateFromFile(confDig); + o2::conf::ConfigurableParam::updateFromFile(confDig, "HBFUtils"); } o2::conf::ConfigurableParam::updateFromString(vm["configKeyValues"].as()); @@ -112,4 +111,8 @@ int main(int argc, const char** argv) rawwriter.digitsToRaw(*digitbranch, *triggerbranch); } rawwriter.getWriter().writeConfFile("CPV", "RAWDATA", o2::utils::concat_string(outputdir, "/CPVraw.cfg")); + + o2::raw::HBFUtils::Instance().print(); + + return 0; } diff --git a/Detectors/EMCAL/simulation/src/RawCreator.cxx b/Detectors/EMCAL/simulation/src/RawCreator.cxx index 83410766123b2..2b40410b559c6 100644 --- a/Detectors/EMCAL/simulation/src/RawCreator.cxx +++ b/Detectors/EMCAL/simulation/src/RawCreator.cxx @@ -50,8 +50,7 @@ int main(int argc, const char** argv) add_option("file-for,f", bpo::value()->default_value("all"), "single file per: all,subdet,link"); add_option("output-dir,o", bpo::value()->default_value("./"), "output directory for raw data"); add_option("debug,d", bpo::value()->default_value(0), "Select debug output level [0 = no debug output]"); - //add_option("digitization-config,d", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "configKeyValues file from digitization"); - add_option("digitization-config,d", bpo::value()->default_value("none"), "configKeyValues file from digitization"); + add_option("hbfutils-config,u", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "config file for HBFUtils (or none)"); add_option("configKeyValues", bpo::value()->default_value(""), "comma-separated configKeyValues"); opt_all.add(opt_general).add(opt_hidden); @@ -77,9 +76,9 @@ int main(int argc, const char** argv) FairLogger::GetLogger()->SetLogScreenLevel("DEBUG"); } - std::string confDig = vm["digitization-config"].as(); + std::string confDig = vm["hbfutils-config"].as(); if (!confDig.empty() && confDig != "none") { - o2::conf::ConfigurableParam::updateFromFile(confDig); + o2::conf::ConfigurableParam::updateFromFile(confDig, "HBFUtils"); } o2::conf::ConfigurableParam::updateFromString(vm["configKeyValues"].as()); @@ -123,4 +122,8 @@ int main(int argc, const char** argv) rawwriter.digitsToRaw(*digitbranch, *triggerbranch); } rawwriter.getWriter().writeConfFile("EMC", "RAWDATA", o2::utils::concat_string(outputdir, "/EMCraw.cfg")); + + o2::raw::HBFUtils::Instance().print(); + + return 0; } diff --git a/Detectors/FIT/FDD/simulation/src/digit2raw.cxx b/Detectors/FIT/FDD/simulation/src/digit2raw.cxx index 7bc786e916b8d..4c97617125118 100644 --- a/Detectors/FIT/FDD/simulation/src/digit2raw.cxx +++ b/Detectors/FIT/FDD/simulation/src/digit2raw.cxx @@ -52,8 +52,7 @@ int main(int argc, char** argv) uint32_t defRDH = o2::raw::RDHUtils::getVersion(); add_option("rdh-version,r", bpo::value()->default_value(defRDH), "RDH version to use"); add_option("no-empty-hbf,e", bpo::value()->default_value(false)->implicit_value(true), "do not create empty HBF pages (except for HBF starting TF)"); - //add_option("digitization-config,d", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "configKeyValues file from digitization"); - add_option("digitization-config,d", bpo::value()->default_value("none"), "configKeyValues file from digitization"); + add_option("hbfutils-config,u", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "config file for HBFUtils (or none)"); add_option("configKeyValues", bpo::value()->default_value(""), "comma-separated configKeyValues"); opt_all.add(opt_general).add(opt_hidden); @@ -75,9 +74,9 @@ int main(int argc, char** argv) exit(2); } - std::string confDig = vm["digitization-config"].as(); + std::string confDig = vm["hbfutils-config"].as(); if (!confDig.empty() && confDig != "none") { - o2::conf::ConfigurableParam::updateFromFile(confDig); + o2::conf::ConfigurableParam::updateFromFile(confDig, "HBFUtils"); } o2::conf::ConfigurableParam::updateFromString(vm["configKeyValues"].as()); digi2raw(vm["input-file"].as(), @@ -86,6 +85,8 @@ int main(int argc, char** argv) vm["rdh-version"].as(), vm["no-empty-hbf"].as()); + o2::raw::HBFUtils::Instance().print(); + return 0; } diff --git a/Detectors/FIT/FT0/simulation/src/digi2raw.cxx b/Detectors/FIT/FT0/simulation/src/digi2raw.cxx index 576345f801529..54b6096164011 100644 --- a/Detectors/FIT/FT0/simulation/src/digi2raw.cxx +++ b/Detectors/FIT/FT0/simulation/src/digi2raw.cxx @@ -52,8 +52,7 @@ int main(int argc, char** argv) uint32_t defRDH = o2::raw::RDHUtils::getVersion(); add_option("rdh-version,r", bpo::value()->default_value(defRDH), "RDH version to use"); add_option("no-empty-hbf,e", bpo::value()->default_value(false)->implicit_value(true), "do not create empty HBF pages (except for HBF starting TF)"); - //add_option("digitization-config,d", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "configKeyValues file from digitization"); - add_option("digitization-config,d", bpo::value()->default_value("none"), "configKeyValues file from digitization"); + add_option("hbfutils-config,u", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "config file for HBFUtils (or none)"); add_option("configKeyValues", bpo::value()->default_value(""), "comma-separated configKeyValues"); opt_all.add(opt_general).add(opt_hidden); @@ -75,9 +74,9 @@ int main(int argc, char** argv) exit(2); } - std::string confDig = vm["digitization-config"].as(); + std::string confDig = vm["hbfutils-config"].as(); if (!confDig.empty() && confDig != "none") { - o2::conf::ConfigurableParam::updateFromFile(confDig); + o2::conf::ConfigurableParam::updateFromFile(confDig, "HBFUtils"); } o2::conf::ConfigurableParam::updateFromString(vm["configKeyValues"].as()); digi2raw(vm["input-file"].as(), @@ -87,6 +86,8 @@ int main(int argc, char** argv) vm["rdh-version"].as(), vm["no-empty-hbf"].as()); + o2::raw::HBFUtils::Instance().print(); + return 0; } diff --git a/Detectors/FIT/FV0/simulation/src/digit2raw.cxx b/Detectors/FIT/FV0/simulation/src/digit2raw.cxx index 96ae262e87747..4d2b30ae6ca14 100644 --- a/Detectors/FIT/FV0/simulation/src/digit2raw.cxx +++ b/Detectors/FIT/FV0/simulation/src/digit2raw.cxx @@ -52,8 +52,7 @@ int main(int argc, char** argv) uint32_t defRDH = o2::raw::RDHUtils::getVersion(); add_option("rdh-version,r", bpo::value()->default_value(defRDH), "RDH version to use"); add_option("no-empty-hbf,e", bpo::value()->default_value(false)->implicit_value(true), "do not create empty HBF pages (except for HBF starting TF)"); - //add_option("digitization-config,d", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "configKeyValues file from digitization"); - add_option("digitization-config,d", bpo::value()->default_value("none"), "configKeyValues file from digitization"); + add_option("hbfutils-config,u", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "config file for HBFUtils (or none)"); add_option("configKeyValues", bpo::value()->default_value(""), "comma-separated configKeyValues"); opt_all.add(opt_general).add(opt_hidden); @@ -75,9 +74,9 @@ int main(int argc, char** argv) exit(2); } - std::string confDig = vm["digitization-config"].as(); + std::string confDig = vm["hbfutils-config"].as(); if (!confDig.empty() && confDig != "none") { - o2::conf::ConfigurableParam::updateFromFile(confDig); + o2::conf::ConfigurableParam::updateFromFile(confDig, "HBFUtils"); } o2::conf::ConfigurableParam::updateFromString(vm["configKeyValues"].as()); digi2raw(vm["input-file"].as(), @@ -86,6 +85,8 @@ int main(int argc, char** argv) vm["rdh-version"].as(), vm["no-empty-hbf"].as()); + o2::raw::HBFUtils::Instance().print(); + return 0; } diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-reco-workflow.cxx b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-reco-workflow.cxx index 32ed8e4dacf2b..c28c54e19457e 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-reco-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-reco-workflow.cxx @@ -60,8 +60,7 @@ void customize(std::vector& workflowOptions) workflowOptions.push_back(ConfigParamSpec{"disable-row-writing", o2::framework::VariantType::Bool, false, {"disable ROW in Digit writing"}}); workflowOptions.push_back(ConfigParamSpec{"write-decoding-errors", o2::framework::VariantType::Bool, false, {"trace errors in digits output when decoding"}}); workflowOptions.push_back(ConfigParamSpec{"calib-cluster", VariantType::Bool, false, {"to enable calib info production from clusters"}}); - //workflowOptions.push_back(ConfigParamSpec{"digitization-config", o2::framework::VariantType::String, {std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE), "configKeyValues file from digitization, used for raw output only!!!"}}); - workflowOptions.push_back(ConfigParamSpec{"digitization-config", o2::framework::VariantType::String, "none", {"configKeyValues file from digitization, used for raw output only!!!"}}); + workflowOptions.push_back(ConfigParamSpec{"hbfutils-config", o2::framework::VariantType::String, std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE), {"config file for HBFUtils (or none), used for raw output only!!!"}}); workflowOptions.push_back(ConfigParamSpec{"cosmics", VariantType::Bool, false, {"to enable cosmics utils"}}); } @@ -114,9 +113,9 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) } if (outputType.rfind("raw") < outputType.size()) { writeraw = 1; - std::string confDig = cfgc.options().get("digitization-config"); + std::string confDig = cfgc.options().get("hbfutils-config"); if (!confDig.empty() && confDig != "none") { - o2::conf::ConfigurableParam::updateFromFile(confDig); + o2::conf::ConfigurableParam::updateFromFile(confDig, "HBFUtils"); } } if (outputType.rfind("ctf") < outputType.size()) { diff --git a/Detectors/HMPID/workflow/src/digits-to-raw-workflow.cxx b/Detectors/HMPID/workflow/src/digits-to-raw-workflow.cxx index 78fea36312109..cb4fa729bed26 100644 --- a/Detectors/HMPID/workflow/src/digits-to-raw-workflow.cxx +++ b/Detectors/HMPID/workflow/src/digits-to-raw-workflow.cxx @@ -39,8 +39,7 @@ void customize(std::vector& policies) void customize(std::vector& workflowOptions) { std::string keyvaluehelp("Semicolon separated key=value strings ..."); - //workflowOptions.push_back(ConfigParamSpec{"digitization-config", o2::framework::VariantType::String, std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE), "configKeyValues file from digitization, used for raw output only!!!"); - workflowOptions.push_back(o2::framework::ConfigParamSpec{"digitization-config", o2::framework::VariantType::String, "none", {"configKeyValues file from digitization, used for raw output only!!!"}}); + workflowOptions.push_back(o2::framework::ConfigParamSpec{"hbfutils-config", o2::framework::VariantType::String, std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE), {"config file for HBFUtils (or none), used for raw output only!!!"}}); workflowOptions.push_back(o2::framework::ConfigParamSpec{"configKeyValues", o2::framework::VariantType::String, "", {keyvaluehelp}}); } @@ -53,9 +52,9 @@ using namespace o2::framework; WorkflowSpec defineDataProcessing(const ConfigContext& configcontext) { WorkflowSpec specs; - std::string confDig = configcontext.options().get("digitization-config"); + std::string confDig = configcontext.options().get("hbfutils-config"); if (!confDig.empty() && confDig != "none") { - o2::conf::ConfigurableParam::updateFromFile(confDig); + o2::conf::ConfigurableParam::updateFromFile(confDig, "HBFUtils"); } o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); DataProcessorSpec consumer = o2::hmpid::getDigitsToRawSpec(); diff --git a/Detectors/ITSMFT/ITS/simulation/CMakeLists.txt b/Detectors/ITSMFT/ITS/simulation/CMakeLists.txt index 9a0e0525b2018..fbd66ccd7946d 100644 --- a/Detectors/ITSMFT/ITS/simulation/CMakeLists.txt +++ b/Detectors/ITSMFT/ITS/simulation/CMakeLists.txt @@ -25,6 +25,7 @@ o2_data_file(COPY data DESTINATION Detectors/ITS/simulation) o2_add_executable(digi2raw COMPONENT_NAME its + TARGETVARNAME itsdigi2raw_exe SOURCES src/digi2raw.cxx PUBLIC_LINK_LIBRARIES O2::ITSMFTReconstruction O2::DataFormatsITSMFT @@ -34,3 +35,9 @@ o2_add_executable(digi2raw O2::DetectorsCommonDataFormats O2::CommonUtils Boost::program_options) + +if(NOT APPLE) + + set_property(TARGET ${itsdigi2raw_exe} PROPERTY LINK_WHAT_YOU_USE ON) + +endif() diff --git a/Detectors/ITSMFT/ITS/simulation/src/digi2raw.cxx b/Detectors/ITSMFT/ITS/simulation/src/digi2raw.cxx index b1b8328ca09ff..9823f4e342508 100644 --- a/Detectors/ITSMFT/ITS/simulation/src/digi2raw.cxx +++ b/Detectors/ITSMFT/ITS/simulation/src/digi2raw.cxx @@ -62,8 +62,7 @@ int main(int argc, char** argv) add_option("output-dir,o", bpo::value()->default_value("./"), "output directory for raw data"); add_option("rdh-version,r", bpo::value()->default_value(DefRDHVersion), "RDH version to use"); add_option("no-empty-hbf,e", bpo::value()->default_value(false)->implicit_value(true), "do not create empty HBF pages (except for HBF starting TF)"); - //add_option("digitization-config,d", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "configKeyValues file from digitization"); - add_option("digitization-config,d", bpo::value()->default_value("none"), "configKeyValues file from digitization"); + add_option("hbfutils-config,u", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "config file for HBFUtils (or none)"); add_option("configKeyValues", bpo::value()->default_value(""), "comma-separated configKeyValues"); opt_all.add(opt_general).add(opt_hidden); @@ -85,9 +84,9 @@ int main(int argc, char** argv) exit(2); } - std::string confDig = vm["digitization-config"].as(); + std::string confDig = vm["hbfutils-config"].as(); if (!confDig.empty() && confDig != "none") { - o2::conf::ConfigurableParam::updateFromFile(confDig); + o2::conf::ConfigurableParam::updateFromFile(confDig, "HBFUtils"); } o2::conf::ConfigurableParam::updateFromString(vm["configKeyValues"].as()); digi2raw(vm["input-file"].as(), @@ -97,7 +96,9 @@ int main(int argc, char** argv) vm["rdh-version"].as(), vm["no-empty-hbf"].as()); LOG(INFO) << "HBFUtils settings used for conversion:"; + o2::raw::HBFUtils::Instance().print(); + return 0; } diff --git a/Detectors/ITSMFT/MFT/simulation/src/digi2raw.cxx b/Detectors/ITSMFT/MFT/simulation/src/digi2raw.cxx index d5d0c89636d38..d6323e18b1198 100644 --- a/Detectors/ITSMFT/MFT/simulation/src/digi2raw.cxx +++ b/Detectors/ITSMFT/MFT/simulation/src/digi2raw.cxx @@ -60,8 +60,7 @@ int main(int argc, char** argv) uint32_t defRDH = o2::raw::RDHUtils::getVersion(); add_option("rdh-version,r", bpo::value()->default_value(defRDH), "RDH version to use"); add_option("no-empty-hbf,e", bpo::value()->default_value(false)->implicit_value(true), "do not create empty HBF pages (except for HBF starting TF)"); - //add_option("digitization-config,d", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "configKeyValues file from digitization"); - add_option("digitization-config,d", bpo::value()->default_value("none"), "configKeyValues file from digitization"); + add_option("hbfutils-config,u", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "config file for HBFUtils (or none)"); add_option("configKeyValues", bpo::value()->default_value(""), "comma-separated configKeyValues"); opt_all.add(opt_general).add(opt_hidden); @@ -83,9 +82,9 @@ int main(int argc, char** argv) exit(2); } - std::string confDig = vm["digitization-config"].as(); + std::string confDig = vm["hbfutils-config"].as(); if (!confDig.empty() && confDig != "none") { - o2::conf::ConfigurableParam::updateFromFile(confDig); + o2::conf::ConfigurableParam::updateFromFile(confDig, "HBFUtils"); } o2::conf::ConfigurableParam::updateFromString(vm["configKeyValues"].as()); digi2raw(vm["input-file"].as(), @@ -95,7 +94,9 @@ int main(int argc, char** argv) vm["rdh-version"].as(), vm["no-empty-hbf"].as()); LOG(INFO) << "HBFUtils settings used for conversion:"; + o2::raw::HBFUtils::Instance().print(); + return 0; } diff --git a/Detectors/MUON/MCH/Raw/Encoder/Digit/digit2raw.cxx b/Detectors/MUON/MCH/Raw/Encoder/Digit/digit2raw.cxx index 13e3b851363ab..9eacd07fa1707 100644 --- a/Detectors/MUON/MCH/Raw/Encoder/Digit/digit2raw.cxx +++ b/Detectors/MUON/MCH/Raw/Encoder/Digit/digit2raw.cxx @@ -94,8 +94,7 @@ int main(int argc, char* argv[]) ("input-file,i",po::value(&input)->default_value("mchdigits.root"),"input file name") ("configKeyValues", po::value()->default_value(""), "comma-separated configKeyValues") ("no-empty-hbf,e", po::value()->default_value(true), "do not create empty HBF pages (except for HBF starting TF)") - //("digitization-config", po::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "configKeyValues file from digitization") - ("digitization-config", po::value()->default_value("none"), "configKeyValues file from digitization") + ("hbfutils-config", po::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "config file for HBFUtils (or none)") ("verbosity,v",po::value()->default_value("verylow"), "(fair)logger verbosity"); // clang-format on @@ -118,9 +117,9 @@ int main(int argc, char* argv[]) po::notify(vm); - std::string confDig = vm["digitization-config"].as(); + std::string confDig = vm["hbfutils-config"].as(); if (!confDig.empty() && confDig != "none") { - o2::conf::ConfigurableParam::updateFromFile(confDig); + o2::conf::ConfigurableParam::updateFromFile(confDig, "HBFUtils"); } o2::conf::ConfigurableParam::updateFromString(vm["configKeyValues"].as()); @@ -165,5 +164,7 @@ int main(int argc, char* argv[]) digit2raw(input, encoder, paginator); + o2::raw::HBFUtils::Instance().print(); + return 0; } diff --git a/Detectors/MUON/MID/Workflow/src/digits-to-raw-workflow.cxx b/Detectors/MUON/MID/Workflow/src/digits-to-raw-workflow.cxx index ac4a4e60107fa..c4ba816d07097 100644 --- a/Detectors/MUON/MID/Workflow/src/digits-to-raw-workflow.cxx +++ b/Detectors/MUON/MID/Workflow/src/digits-to-raw-workflow.cxx @@ -29,8 +29,7 @@ void customize(std::vector& workflowOptions) { std::string keyvaluehelp("Semicolon separated key=value strings ..."); workflowOptions.push_back(ConfigParamSpec{"configKeyValues", VariantType::String, "", {keyvaluehelp}}); - //workflowOptions.push_back(ConfigParamSpec{"digitization-config", o2::framework::VariantType::String, std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE), "configKeyValues file from digitization, used for raw output only!!!"); - workflowOptions.push_back(ConfigParamSpec{"digitization-config", o2::framework::VariantType::String, "none", {"configKeyValues file from digitization, used for raw output only!!!"}}); + workflowOptions.push_back(ConfigParamSpec{"hbfutils-config", o2::framework::VariantType::String, std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE), {"config file for HBFUtils (or none), used for raw output only!!!"}}); } #include "Framework/runDataProcessing.h" @@ -39,9 +38,9 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { WorkflowSpec specs; - std::string confDig = configcontext.options().get("digitization-config"); + std::string confDig = configcontext.options().get("hbfutils-config"); if (!confDig.empty() && confDig != "none") { - o2::conf::ConfigurableParam::updateFromFile(confDig); + o2::conf::ConfigurableParam::updateFromFile(confDig, "HBFUtils"); } o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); specs.emplace_back(o2::mid::getDigitReaderSpec(false)); diff --git a/Detectors/PHOS/simulation/src/RawCreator.cxx b/Detectors/PHOS/simulation/src/RawCreator.cxx index 1dbd1a65a0310..d9dac3da0356c 100644 --- a/Detectors/PHOS/simulation/src/RawCreator.cxx +++ b/Detectors/PHOS/simulation/src/RawCreator.cxx @@ -49,8 +49,7 @@ int main(int argc, const char** argv) add_option("file-for,f", bpo::value()->default_value("all"), "single file per: all,link"); add_option("output-dir,o", bpo::value()->default_value("./"), "output directory for raw data"); add_option("debug,d", bpo::value()->default_value(0), "Select debug output level [0 = no debug output]"); - //add_option("digitization-config,d", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "configKeyValues file from digitization"); - add_option("digitization-config,d", bpo::value()->default_value("none"), "configKeyValues file from digitization"); + add_option("hbfutils-config,u", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "config file for HBFUtils (or none)"); add_option("configKeyValues", bpo::value()->default_value(""), "comma-separated configKeyValues"); opt_all.add(opt_general).add(opt_hidden); @@ -71,9 +70,9 @@ int main(int argc, const char** argv) exit(2); } - std::string confDig = vm["digitization-config"].as(); + std::string confDig = vm["hbfutils-config"].as(); if (!confDig.empty() && confDig != "none") { - o2::conf::ConfigurableParam::updateFromFile(confDig); + o2::conf::ConfigurableParam::updateFromFile(confDig, "HBFUtils"); } o2::conf::ConfigurableParam::updateFromString(vm["configKeyValues"].as()); @@ -112,4 +111,8 @@ int main(int argc, const char** argv) rawwriter.digitsToRaw(*digitbranch, *triggerbranch); } rawwriter.getWriter().writeConfFile("PHS", "RAWDATA", o2::utils::concat_string(outputdir, "/PHSraw.cfg")); + + o2::raw::HBFUtils::Instance().print(); + + return 0; } diff --git a/Detectors/TOF/simulation/src/digi2raw.cxx b/Detectors/TOF/simulation/src/digi2raw.cxx index b5cf1273da4cb..b24611578b411 100644 --- a/Detectors/TOF/simulation/src/digi2raw.cxx +++ b/Detectors/TOF/simulation/src/digi2raw.cxx @@ -33,8 +33,8 @@ int main(int argc, char** argv) add_option("output-dir,o", bpo::value()->default_value("./"), "output directory for raw data"); add_option("file-for,f", bpo::value()->default_value("cru"), "single file per: all,cru,link"); add_option("configKeyValues", bpo::value()->default_value(""), "comma-separated configKeyValues"); - //add_option("digitization-config,d", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "configKeyValues file from digitization"); - add_option("digitization-config,d", bpo::value()->default_value("none"), "configKeyValues file from digitization"); + //add_option("hbfutils-config,u", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "config file for HBFUtils (or none)"); + add_option("hbfutils-config,u", bpo::value()->default_value("none"), "config file for HBFUtils (or none)"); opt_all.add(opt_general).add(opt_hidden); bpo::store(bpo::command_line_parser(argc, argv).options(opt_all).positional(opt_pos).run(), vm); @@ -56,7 +56,7 @@ int main(int argc, char** argv) auto cmd = o2::utils::concat_string("o2-tof-reco-workflow -b --output-type raw --tof-raw-outdir ", vm["output-dir"].as(), " --tof-raw-file-for ", vm["file-for"].as(), - " --digitization-config ", vm["digitization-config"].as(), + " --hbfutils-config ", vm["hbfutils-config"].as(), R"( --configKeyValues ")", vm["configKeyValues"].as(), '"'); return system(cmd.c_str()); } diff --git a/Detectors/TPC/simulation/run/convertDigitsToRawZS.cxx b/Detectors/TPC/simulation/run/convertDigitsToRawZS.cxx index b07aa9e1e4f73..cb299b8fd55a0 100644 --- a/Detectors/TPC/simulation/run/convertDigitsToRawZS.cxx +++ b/Detectors/TPC/simulation/run/convertDigitsToRawZS.cxx @@ -227,8 +227,7 @@ int main(int argc, char** argv) add_option("stop-page,p", bpo::value()->default_value(false)->implicit_value(true), "HBF stop on separate CRU page"); add_option("no-padding", bpo::value()->default_value(false)->implicit_value(true), "Don't pad pages to 8kb"); uint32_t defRDH = o2::raw::RDHUtils::getVersion(); - //add_option("digitization-config,d", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "configKeyValues file from digitization"); - add_option("digitization-config,d", bpo::value()->default_value("none"), "configKeyValues file from digitization"); + add_option("hbfutils-config,u", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "config file for HBFUtils (or none)"); add_option("rdh-version,r", bpo::value()->default_value(defRDH), "RDH version to use"); add_option("configKeyValues", bpo::value()->default_value(""), "comma-separated configKeyValues"); @@ -251,9 +250,9 @@ int main(int argc, char** argv) exit(2); } - std::string confDig = vm["digitization-config"].as(); + std::string confDig = vm["hbfutils-config"].as(); if (!confDig.empty() && confDig != "none") { - o2::conf::ConfigurableParam::updateFromFile(confDig); + o2::conf::ConfigurableParam::updateFromFile(confDig, "HBFUtils"); } o2::conf::ConfigurableParam::updateFromString(vm["configKeyValues"].as()); convertDigitsToZSfinal( @@ -266,5 +265,7 @@ int main(int argc, char** argv) vm["no-padding"].as(), !vm.count("no-parent-directories")); + o2::raw::HBFUtils::Instance().print(); + return 0; } diff --git a/Detectors/ZDC/simulation/src/digi2raw.cxx b/Detectors/ZDC/simulation/src/digi2raw.cxx index f7ee944c92c0b..f34efd45213fd 100644 --- a/Detectors/ZDC/simulation/src/digi2raw.cxx +++ b/Detectors/ZDC/simulation/src/digi2raw.cxx @@ -60,8 +60,7 @@ int main(int argc, char** argv) add_option("ccdb-url,c", bpo::value()->default_value(""), "url of the ccdb repository"); uint32_t defRDH = o2::raw::RDHUtils::getVersion(); add_option("rdh-version,r", bpo::value()->default_value(defRDH), "RDH version to use"); - //add_option("digitization-config,d", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "configKeyValues file from digitization"); - add_option("digitization-config,d", bpo::value()->default_value("none"), "configKeyValues file from digitization"); + add_option("hbfutils-config,u", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "config file for HBFUtils (or none)"); add_option("configKeyValues", bpo::value()->default_value(""), "comma-separated configKeyValues"); opt_all.add(opt_general).add(opt_hidden); @@ -82,9 +81,9 @@ int main(int argc, char** argv) std::cerr << e.what() << ", application will now exit" << std::endl; exit(2); } - std::string confDig = vm["digitization-config"].as(); + std::string confDig = vm["hbfutils-config"].as(); if (!confDig.empty() && confDig != "none") { - o2::conf::ConfigurableParam::updateFromFile(confDig); + o2::conf::ConfigurableParam::updateFromFile(confDig, "HBFUtils"); } o2::conf::ConfigurableParam::updateFromString(vm["configKeyValues"].as()); @@ -103,6 +102,8 @@ int main(int argc, char** argv) vm["rdh-version"].as(), ccdbHost); + o2::raw::HBFUtils::Instance().print(); + return 0; } From 05912aad1e1b603b8e7a1a5d485731429842ad49 Mon Sep 17 00:00:00 2001 From: shahoian Date: Sun, 4 Apr 2021 00:39:54 +0200 Subject: [PATCH 070/770] Adapt FST to HBFUtils loaded from digitization ini file --- prodtests/full_system_test.sh | 37 +++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/prodtests/full_system_test.sh b/prodtests/full_system_test.sh index a1c3e8c3ccf3f..8306f4604daba 100755 --- a/prodtests/full_system_test.sh +++ b/prodtests/full_system_test.sh @@ -33,6 +33,8 @@ NOMCLABELS="--disable-mc" O2SIMSEED=${O2SIMSEED:--1} SPLITTRDDIGI=${SPLITTRDDIGI:-1} NHBPERTF=${NHBPERTF:-128} +RUNFIRSTORBIT=${RUNFIRSTORBIT:-0} +FIRSTSAMPLEDORBIT=${FIRSTSAMPLEDORBIT:-0} # allow skipping JOBUTILS_SKIPDONE=ON @@ -51,6 +53,9 @@ echo "versions,${TAG} alidist=\"${ALIDISTCOMMIT}\",O2=\"${O2COMMIT}\" " > ${METR GLOBALDPLOPT="-b" # --monitoring-backend no-op:// is currently removed due to https://alice.its.cern.ch/jira/browse/O2-1887 +HBFUTILPARAMS="HBFUtils.nHBFPerTF=${NHBPERTF};HBFUtils.orbitFirst=${RUNFIRSTORBIT};HBFUtils.orbitFirstSampled=${FIRSTSAMPLEDORBIT}" +[ "0$ALLOW_MULTIPLE_TF" != "01" ] && HBFUTILPARAMS+=";HBFUtils.maxNOrbits=${NHBPERTF};" + ulimit -n 4096 # Make sure we can open sufficiently many files [ $? == 0 ] || (echo Failed setting ulimit && exit 1) mkdir -p qed @@ -61,9 +66,9 @@ QED2HAD=$(awk "BEGIN {printf \"%.2f\",`grep xSectionQED qedgenparam.ini | cut -d echo "Obtained ratio of QED to hadronic x-sections = $QED2HAD" >> qedsim.log cd .. -DIGITRDOPTREAL="--configKeyValues \"TRDSimParams.digithreads=${NJOBS}\" " +DIGITRDOPTREAL="--configKeyValues \"${HBFUTILPARAMS};TRDSimParams.digithreads=${NJOBS}\" --enable-trd-trapsim" if [ $SPLITTRDDIGI == "1" ]; then - DIGITRDOPT="--skipDet TRD" + DIGITRDOPT="--configKeyValues \"${HBFUTILPARAMS}\" --skipDet TRD" else DIGITRDOPT=$DIGITRDOPTREAL fi @@ -81,21 +86,19 @@ if [ "0$GENERATE_ITS_DICTIONARY" == "01" ]; then fi mkdir -p raw -HBFUTILPARAMS="HBFUtils.nHBFPerTF=${NHBPERTF};HBFUtils.orbitFirst=0;" -[ "0$ALLOW_MULTIPLE_TF" != "01" ] && HBFUTILPARAMS+="HBFUtils.maxNOrbits=${NHBPERTF};" -taskwrapper itsraw.log o2-its-digi2raw --file-for link --configKeyValues \"$HBFUTILPARAMS\" -o raw/ITS -taskwrapper mftraw.log o2-mft-digi2raw --file-for link --configKeyValues \"$HBFUTILPARAMS\" -o raw/MFT -taskwrapper ft0raw.log o2-ft0-digi2raw --file-per-link --configKeyValues \"$HBFUTILPARAMS\" -o raw/FT0 -taskwrapper fv0raw.log o2-fv0-digi2raw --file-per-link --configKeyValues \"$HBFUTILPARAMS\" -o raw/FV0 -taskwrapper fddraw.log o2-fdd-digit2raw --file-per-link --configKeyValues \"$HBFUTILPARAMS\" -o raw/FDD -taskwrapper tpcraw.log o2-tpc-digits-to-rawzs --file-for link --configKeyValues \"$HBFUTILPARAMS\" -i tpcdigits.root -o raw/TPC -taskwrapper tofraw.log o2-tof-reco-workflow ${GLOBALDPLOPT} --tof-raw-file-for link --configKeyValues \"$HBFUTILPARAMS\" --output-type raw --tof-raw-outdir raw/TOF -taskwrapper midraw.log o2-mid-digits-to-raw-workflow ${GLOBALDPLOPT} --mid-raw-outdir raw/MID --mid-raw-perlink --configKeyValues \"$HBFUTILPARAMS\" -taskwrapper emcraw.log o2-emcal-rawcreator --file-for link --configKeyValues \"$HBFUTILPARAMS\" -o raw/EMC -taskwrapper phsraw.log o2-phos-digi2raw --file-for link --configKeyValues \"$HBFUTILPARAMS\" -o raw/PHS -taskwrapper cpvraw.log o2-cpv-digi2raw --file-for link --configKeyValues \"$HBFUTILPARAMS\" -o raw/CPV -taskwrapper zdcraw.log o2-zdc-digi2raw --file-per-link --configKeyValues \"$HBFUTILPARAMS\" -o raw/ZDC -taskwrapper hmpraw.log o2-hmpid-digits-to-raw-workflow --file-for link --configKeyValues \"$HBFUTILPARAMS\" --outdir raw/HMP +taskwrapper itsraw.log o2-its-digi2raw --file-for link -o raw/ITS +taskwrapper mftraw.log o2-mft-digi2raw --file-for link -o raw/MFT +taskwrapper ft0raw.log o2-ft0-digi2raw --file-per-link -o raw/FT0 +taskwrapper fv0raw.log o2-fv0-digi2raw --file-per-link -o raw/FV0 +taskwrapper fddraw.log o2-fdd-digit2raw --file-per-link -o raw/FDD +taskwrapper tpcraw.log o2-tpc-digits-to-rawzs --file-for link -i tpcdigits.root -o raw/TPC +taskwrapper tofraw.log o2-tof-reco-workflow ${GLOBALDPLOPT} --tof-raw-file-for link --output-type raw --tof-raw-outdir raw/TOF +taskwrapper midraw.log o2-mid-digits-to-raw-workflow ${GLOBALDPLOPT} --mid-raw-outdir raw/MID --mid-raw-perlink +taskwrapper emcraw.log o2-emcal-rawcreator --file-for link -o raw/EMC +taskwrapper phsraw.log o2-phos-digi2raw --file-for link -o raw/PHS +taskwrapper cpvraw.log o2-cpv-digi2raw --file-for link -o raw/CPV +taskwrapper zdcraw.log o2-zdc-digi2raw --file-per-link -o raw/ZDC +taskwrapper hmpraw.log o2-hmpid-digits-to-raw-workflow --file-for link --outdir raw/HMP cat raw/*/*.cfg > rawAll.cfg if [ "0$DISABLE_PROCESSING" == "01" ]; then From ed5e155c02c4ede55c0d6048e0a951a88889701f Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 7 Apr 2021 14:41:33 +0200 Subject: [PATCH 071/770] GPU: Fix alignment violation --- GPU/GPUTracking/utils/strtag.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/GPU/GPUTracking/utils/strtag.h b/GPU/GPUTracking/utils/strtag.h index bf8a92ee2e0ff..561465a6919ed 100644 --- a/GPU/GPUTracking/utils/strtag.h +++ b/GPU/GPUTracking/utils/strtag.h @@ -23,7 +23,11 @@ constexpr T qStr2Tag(const char* str) if (strlen(str) != sizeof(T)) { throw std::runtime_error("Invalid tag length"); } - return *(T*)str; + T tmp; + for (unsigned int i = 0; i < sizeof(T); i++) { + ((char*)&tmp)[i] = str[i]; + } + return tmp; } template From 734180337bbd085eec7a36674b2baae4bac1eb7f Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 7 Apr 2021 14:53:03 +0200 Subject: [PATCH 072/770] GPU: Silence sanitizer warning --- GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.cxx b/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.cxx index a29c38a53bcad..6bc5824385ecd 100644 --- a/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.cxx +++ b/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.cxx @@ -188,7 +188,7 @@ GPUdii() void GPUTPCCompressionKernels::ThreadclusterOffset[iSlice][iRow]; const int idOffsetOut = clusters->clusterOffset[iSlice][iRow] * compressor.mMaxClusterFactorBase1024 / 1024; - const int idOffsetOutMax = clusters->clusterOffset[iSlice][iRow + 1] * compressor.mMaxClusterFactorBase1024 / 1024; + const int idOffsetOutMax = ((const unsigned int*)clusters->clusterOffset[iSlice])[iRow + 1] * compressor.mMaxClusterFactorBase1024 / 1024; // Array out of bounds access is ok, since it goes to the correct nClustersTotal if (iThread == nThreads - 1) { smem.nCount = 0; } From 21bda560f84086fc07aac6f9e4dca751664c64d5 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 7 Apr 2021 18:07:41 +0200 Subject: [PATCH 073/770] GPU: 0 is a valid row for looper following --- GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx | 4 ++-- GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx index 4cbd2293b79a8..b174c373b4e26 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx @@ -634,7 +634,7 @@ GPUdii() void GPUTPCGMTrackParam::RefitLoop(const GPUTPCGMMerger* GPUrestrict() GPUTPCGMLoopData& data = Merger->LoopData()[loopIdx]; prop.SetTrack(&data.param, data.alpha); - if (data.toRow == 0) { + if (data.toSlice == -1) { data.param.AttachClustersMirror<1>(Merger, data.slice, data.row, data.track, data.toY, prop, true); } else { data.param.FollowCircle<1>(Merger, prop, data.slice, data.row, data.track, data.toAlpha, data.toY, data.toX, data.toSlice, data.toRow, data.inFlyDirection, true); @@ -753,7 +753,7 @@ GPUdni() void GPUTPCGMTrackParam::AttachClustersMirror(const GPUTPCGMMerger* GPU return; } if (Merger->Param().rec.loopInterpolationInExtraPass && phase2 == false) { - StoreAttachMirror(Merger, slice, iRow, iTrack, 0, toY, 0, 0, 0, 0, prop.GetAlpha()); + StoreAttachMirror(Merger, slice, iRow, iTrack, 0, toY, 0, -1, 0, 0, prop.GetAlpha()); return; } float X = mP[2] > 0 ? mP[0] : -mP[0]; diff --git a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h index 96f95a01876b3..2797fa2840676 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h +++ b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h @@ -244,7 +244,7 @@ struct GPUTPCGMLoopData { float toAlpha; unsigned char slice; unsigned char row; - unsigned char toSlice; + char toSlice; unsigned char toRow; unsigned char inFlyDirection; }; From 7a585699e0671d35dd87f1189d21d641baf1d3b4 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 7 Apr 2021 23:22:20 +0200 Subject: [PATCH 074/770] GPU: Fix typo, toX and toY were swapped --- GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx index b174c373b4e26..c9dac41b3a7c0 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx @@ -637,7 +637,7 @@ GPUdii() void GPUTPCGMTrackParam::RefitLoop(const GPUTPCGMMerger* GPUrestrict() if (data.toSlice == -1) { data.param.AttachClustersMirror<1>(Merger, data.slice, data.row, data.track, data.toY, prop, true); } else { - data.param.FollowCircle<1>(Merger, prop, data.slice, data.row, data.track, data.toAlpha, data.toY, data.toX, data.toSlice, data.toRow, data.inFlyDirection, true); + data.param.FollowCircle<1>(Merger, prop, data.slice, data.row, data.track, data.toAlpha, data.toX, data.toY, data.toSlice, data.toRow, data.inFlyDirection, true); } } From 6915885a156e6dbdfffb37784fc4fe763b088ea1 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 7 Apr 2021 23:24:22 +0200 Subject: [PATCH 075/770] GPU: Consistently use "< 0" to avoid the corner case "== 0" --- GPU/GPUTracking/Merger/GPUTPCGMPropagator.cxx | 2 +- GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/GPU/GPUTracking/Merger/GPUTPCGMPropagator.cxx b/GPU/GPUTracking/Merger/GPUTPCGMPropagator.cxx index ea7659578305f..41215d339d72e 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMPropagator.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMPropagator.cxx @@ -121,7 +121,7 @@ GPUd() int GPUTPCGMPropagator::RotateToAlpha(float newAlpha) CAMath::SinCos(newAlpha, newSinAlpha, newCosAlpha); float cc = newCosAlpha * mCosAlpha + newSinAlpha * mSinAlpha; // cos(newAlpha - mAlpha); - float ss = newSinAlpha * mCosAlpha - newCosAlpha * mSinAlpha; //sin(newAlpha - mAlpha); + float ss = newSinAlpha * mCosAlpha - newCosAlpha * mSinAlpha; // sin(newAlpha - mAlpha); GPUTPCGMPhysicalTrackModel t0 = mT0; diff --git a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx index c9dac41b3a7c0..71c3b87c3f6fe 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx @@ -661,7 +661,7 @@ GPUdic(0, 1) int GPUTPCGMTrackParam::FollowCircle(const GPUTPCGMMerger* GPUrestr } bool up = (mP[2] < 0) ^ right; int targetRow = up ? (GPUCA_ROW_COUNT - 1) : 0; - float lrFactor = mP[2] > 0 ? 1.f : -1.f; // right ^ down + float lrFactor = mP[2] < 0 ? -1.f : 1.f; // !(right ^ down) // TODO: shouldn't it be "right ? 1.f : -1.f", but that gives worse results... // clang-format off CADEBUG(printf("CIRCLE Track %d: Slice %d Alpha %f X %f Y %f Z %f SinPhi %f DzDs %f - Next hit: Slice %d Alpha %f X %f Y %f - Right %d Up %d dAlpha %f lrFactor %f\n", iTrack, slice, prop.GetAlpha(), mX, mP[0], mP[1], mP[2], mP[3], toSlice, toAlpha, toX, toY, (int)right, (int)up, dAlpha, lrFactor)); // clang-format on @@ -680,8 +680,7 @@ GPUdic(0, 1) int GPUTPCGMTrackParam::FollowCircle(const GPUTPCGMMerger* GPUrestr return 1; } CADEBUG(printf("Propagated to y = %f: X %f Z %f SinPhi %f\n", mX, mP[0], mP[1], mP[2])); - int found = 0; - for (int j = 0; j < GPUCA_ROW_COUNT && found < 3; j++) { + for (int j = 0; j < GPUCA_ROW_COUNT; j++) { float rowX = Merger->Param().tpcGeometry.Row2X(j); if (CAMath::Abs(rowX - (-mP[0] * lrFactor)) < 1.5f) { CADEBUG(printf("Attempt row %d (Y %f Z %f)\n", j, mX * lrFactor, mP[1])); From 0698e9863d687b71176bd3bb831a97f3af2b31e9 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 7 Apr 2021 23:46:21 +0200 Subject: [PATCH 076/770] GPU: Use float CAMath::Pi() instead of M_PI, which is double --- GPU/GPUTracking/Merger/GPUTPCGMPropagator.cxx | 10 ++++---- GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx | 14 +++++------ GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h | 8 +++---- GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx | 24 +++++++++---------- GPU/GPUTracking/display/GPUDisplay.cxx | 20 ++++++++-------- 5 files changed, 38 insertions(+), 38 deletions(-) diff --git a/GPU/GPUTracking/Merger/GPUTPCGMPropagator.cxx b/GPU/GPUTracking/Merger/GPUTPCGMPropagator.cxx index 41215d339d72e..f4747bd1437fb 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMPropagator.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMPropagator.cxx @@ -940,12 +940,12 @@ GPUd() void GPUTPCGMPropagator::Rotate180() mT->QPt() = -mT->QPt(); mT->DzDs() = -mT->DzDs(); - mAlpha = mAlpha + M_PI; - while (mAlpha >= M_PI) { - mAlpha -= 2 * M_PI; + mAlpha = mAlpha + CAMath::Pi(); + while (mAlpha >= CAMath::Pi()) { + mAlpha -= CAMath::TwoPi(); } - while (mAlpha < -M_PI) { - mAlpha += 2 * M_PI; + while (mAlpha < -CAMath::Pi()) { + mAlpha += CAMath::TwoPi(); } mCosAlpha = -mCosAlpha; mSinAlpha = -mSinAlpha; diff --git a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx index 71c3b87c3f6fe..415fa6414d5bb 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx @@ -655,7 +655,7 @@ GPUdic(0, 1) int GPUTPCGMTrackParam::FollowCircle(const GPUTPCGMMerger* GPUrestr bool right; float dAlpha = toAlpha - prop.GetAlpha(); if (CAMath::Abs(dAlpha) > 0.001f) { - right = CAMath::Abs(dAlpha) < M_PI ? (dAlpha > 0) : (dAlpha < 0); + right = CAMath::Abs(dAlpha) < CAMath::Pi() ? (dAlpha > 0) : (dAlpha < 0); } else { right = toY > mP[0]; } @@ -667,16 +667,16 @@ GPUdic(0, 1) int GPUTPCGMTrackParam::FollowCircle(const GPUTPCGMMerger* GPUrestr // clang-format on AttachClustersPropagate(Merger, slice, iRow, targetRow, iTrack, false, prop, inFlyDirection, 0.7f); - if (prop.RotateToAlpha(prop.GetAlpha() + (M_PI / 2.f) * lrFactor)) { + if (prop.RotateToAlpha(prop.GetAlpha() + (CAMath::Pi() / 2.f) * lrFactor)) { return 1; } - CADEBUG(printf("Rotated: X %f Y %f Z %f SinPhi %f (Alpha %f / %f)\n", mP[0], mX, mP[1], mP[2], prop.GetAlpha(), prop.GetAlpha() + M_PI / 2.f)); + CADEBUG(printf("Rotated: X %f Y %f Z %f SinPhi %f (Alpha %f / %f)\n", mP[0], mX, mP[1], mP[2], prop.GetAlpha(), prop.GetAlpha() + CAMath::Pi() / 2.f)); while (slice != toSlice || FollowCircleChk(lrFactor, toY, toX, up, right)) { while ((slice != toSlice) ? (CAMath::Abs(mX) <= CAMath::Abs(mP[0]) * CAMath::Tan(kSectAngle / 2.f)) : FollowCircleChk(lrFactor, toY, toX, up, right)) { int err = prop.PropagateToXAlpha(mX + 1.f, prop.GetAlpha(), inFlyDirection); if (err) { CADEBUG(printf("propagation error (%d)\n", err)); - prop.RotateToAlpha(prop.GetAlpha() - (M_PI / 2.f) * lrFactor); + prop.RotateToAlpha(prop.GetAlpha() - (CAMath::Pi() / 2.f) * lrFactor); return 1; } CADEBUG(printf("Propagated to y = %f: X %f Z %f SinPhi %f\n", mX, mP[0], mP[1], mP[2])); @@ -701,9 +701,9 @@ GPUdic(0, 1) int GPUTPCGMTrackParam::FollowCircle(const GPUTPCGMMerger* GPUrestr } } CADEBUG(printf("Rotating to slice %d\n", slice)); - if (prop.RotateToAlpha(param.Alpha(slice) + (M_PI / 2.f) * lrFactor)) { + if (prop.RotateToAlpha(param.Alpha(slice) + (CAMath::Pi() / 2.f) * lrFactor)) { CADEBUG(printf("rotation error\n")); - prop.RotateToAlpha(prop.GetAlpha() - (M_PI / 2.f) * lrFactor); + prop.RotateToAlpha(prop.GetAlpha() - (CAMath::Pi() / 2.f) * lrFactor); return 1; } CADEBUG(printf("After Rotatin Alpha %f Position X %f Y %f Z %f SinPhi %f\n", prop.GetAlpha(), mP[0], mX, mP[1], mP[2])); @@ -711,7 +711,7 @@ GPUdic(0, 1) int GPUTPCGMTrackParam::FollowCircle(const GPUTPCGMMerger* GPUrestr } CADEBUG(printf("Rotating back\n")); for (int i = 0; i < 2; i++) { - if (prop.RotateToAlpha(prop.GetAlpha() + (M_PI / 2.f) * lrFactor) == 0) { + if (prop.RotateToAlpha(prop.GetAlpha() + (CAMath::Pi() / 2.f) * lrFactor) == 0) { break; } if (i) { diff --git a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h index 2797fa2840676..5993bcac1d4f7 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h +++ b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h @@ -181,10 +181,10 @@ class GPUTPCGMTrackParam } GPUdi() static void NormalizeAlpha(float& alpha) { - if (alpha > M_PI) { - alpha -= 2 * M_PI; - } else if (alpha <= -M_PI) { - alpha += 2 * M_PI; + if (alpha > CAMath::Pi()) { + alpha -= CAMath::TwoPi(); + } else if (alpha <= -CAMath::Pi()) { + alpha += CAMath::TwoPi(); } } diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx index 3471036b8e6d3..838fec471e870 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx @@ -664,7 +664,7 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK int currIdx = candidateIdxOffset + iLayer % 2; int nextIdx = candidateIdxOffset + (iLayer + 1) % 2; pad = mGeo->GetPadPlane(iLayer, 0); - float tilt = CAMath::Tan(M_PI / 180.f * pad->GetTiltingAngle()); // tilt is signed! + float tilt = CAMath::Tan(CAMath::Pi() / 180.f * pad->GetTiltingAngle()); // tilt is signed! const float zMaxTRD = pad->GetRow0(); // -------------------------------------------------------------------------------- @@ -1125,10 +1125,10 @@ GPUd() bool GPUTRDTracker_t::AdjustSector(PROP* prop, TRDTRK* t) c } int sign = (y > 0) ? 1 : -1; float alphaNew = alphaCurr + alpha * sign; - if (alphaNew > M_PI) { - alphaNew -= 2 * M_PI; - } else if (alphaNew < -M_PI) { - alphaNew += 2 * M_PI; + if (alphaNew > CAMath::Pi()) { + alphaNew -= 2 * CAMath::Pi(); + } else if (alphaNew < -CAMath::Pi()) { + alphaNew += 2 * CAMath::Pi(); } if (!prop->rotate(alphaNew)) { return false; @@ -1149,11 +1149,11 @@ GPUd() int GPUTRDTracker_t::GetSector(float alpha) const // TRD sector number for reference system alpha //-------------------------------------------------------------------- if (alpha < 0) { - alpha += 2.f * M_PI; - } else if (alpha >= 2.f * M_PI) { - alpha -= 2.f * M_PI; + alpha += 2.f * CAMath::Pi(); + } else if (alpha >= 2.f * CAMath::Pi()) { + alpha -= 2.f * CAMath::Pi(); } - return (int)(alpha * kNSectors / (2.f * M_PI)); + return (int)(alpha * kNSectors / (2.f * CAMath::Pi())); } template @@ -1162,9 +1162,9 @@ GPUd() float GPUTRDTracker_t::GetAlphaOfSector(const int sec) cons //-------------------------------------------------------------------- // rotation angle for TRD sector sec //-------------------------------------------------------------------- - float alpha = 2.0f * M_PI / (float)kNSectors * ((float)sec + 0.5f); - if (alpha > M_PI) { - alpha -= 2 * M_PI; + float alpha = 2.0f * CAMath::Pi() / (float)kNSectors * ((float)sec + 0.5f); + if (alpha > CAMath::Pi()) { + alpha -= 2 * CAMath::Pi(); } return alpha; } diff --git a/GPU/GPUTracking/display/GPUDisplay.cxx b/GPU/GPUTracking/display/GPUDisplay.cxx index 22c2988488555..cb77852970039 100644 --- a/GPU/GPUTracking/display/GPUDisplay.cxx +++ b/GPU/GPUTracking/display/GPUDisplay.cxx @@ -192,7 +192,7 @@ void GPUDisplay::SetCollisionFirstCluster(unsigned int collision, int slice, int void GPUDisplay::mAnimationCloseAngle(float& newangle, float lastAngle) { - const float delta = lastAngle > newangle ? (2 * M_PI) : (-2 * M_PI); + const float delta = lastAngle > newangle ? (2 * CAMath::Pi()) : (-2 * CAMath::Pi()); while (fabsf(newangle + delta - lastAngle) < fabsf(newangle - lastAngle)) { newangle += delta; } @@ -1039,7 +1039,7 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s } x = trkParam.X() + 1.f; if (!mPropagateLoopers) { - float diff = fabsf(alpha - param().Alpha(slice)) / (2. * M_PI); + float diff = fabsf(alpha - param().Alpha(slice)) / (2. * CAMath::Pi()); diff -= floor(diff); if (diff > 0.25 && diff < 0.75) { break; @@ -1135,7 +1135,7 @@ GPUDisplay::vboList GPUDisplay::DrawGridTRD(int sector) int trdsector = NSLICES / 2 - 1 - sector; float alpha = geo->GetAlpha() / 2.f + geo->GetAlpha() * trdsector; if (trdsector >= 9) { - alpha -= 2 * M_PI; + alpha -= 2 * CAMath::Pi(); } for (int iLy = 0; iLy < GPUTRDTracker::EGPUTRDTracker::kNLayers; ++iLy) { for (int iStack = 0; iStack < GPUTRDTracker::EGPUTRDTracker::kNStacks; ++iStack) { @@ -1433,7 +1433,7 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) if (mCfg.animationMode != 6) { if (mCfg.animationMode & 1) // Rotation from euler angles { - nextViewMatrix = nextViewMatrix * HMM_Rotate(-vals[4] * 180.f / M_PI, {1, 0, 0}) * HMM_Rotate(vals[5] * 180.f / M_PI, {0, 1, 0}) * HMM_Rotate(-vals[6] * 180.f / M_PI, {0, 0, 1}); + nextViewMatrix = nextViewMatrix * HMM_Rotate(-vals[4] * 180.f / CAMath::Pi(), {1, 0, 0}) * HMM_Rotate(vals[5] * 180.f / CAMath::Pi(), {0, 1, 0}) * HMM_Rotate(-vals[6] * 180.f / CAMath::Pi(), {0, 0, 1}); } else { // Rotation from quaternion const float mag = sqrtf(vals[4] * vals[4] + vals[5] * vals[5] + vals[6] * vals[6] + vals[7] * vals[7]); if (mag < 0.0001) { @@ -1536,7 +1536,7 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) phi += moveX * 0.1f; float theta = atan2f(mXYZ[1], r2); theta -= moveY * 0.1f; - const float max_theta = M_PI / 2 - 0.01; + const float max_theta = CAMath::Pi() / 2 - 0.01; if (theta >= max_theta) { theta = max_theta; } else if (theta <= -max_theta) { @@ -1571,7 +1571,7 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) nextViewMatrix = nextViewMatrix * mViewMatrix; // Apply previous translation / rotation if (yUp) { calcXYZ(&nextViewMatrix.Elements[0][0]); - nextViewMatrix = HMM_Rotate(mAngle[2] * 180.f / M_PI, {0, 0, 1}) * nextViewMatrix; + nextViewMatrix = HMM_Rotate(mAngle[2] * 180.f / CAMath::Pi(), {0, 0, 1}) * nextViewMatrix; } if (rotateModel) { if (rotYaw != 0.f) { @@ -1744,9 +1744,9 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) float alpha = atan2f(mc.y, mc.x); if (alpha < 0) { - alpha += 2 * M_PI; + alpha += 2 * CAMath::Pi(); } - int slice = alpha / (2 * M_PI) * 18; + int slice = alpha / (2 * CAMath::Pi()) * 18; if (mc.z < 0) { slice += 18; } @@ -2124,8 +2124,8 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) sprintf(info, "FPS: %6.2f (Slice: %d, 1:Clusters %d, 2:Prelinks %d, 3:Links %d, 4:Seeds %d, 5:Tracklets %d, 6:Tracks %d, 7:GTracks %d, 8:Merger %d) (%d frames, %d draw calls) " "(X %1.2f Y %1.2f Z %1.2f / R %1.2f Phi %1.1f Theta %1.1f) / Yaw %1.1f Pitch %1.1f Roll %1.1f)", - fps, mCfg.drawSlice, mCfg.drawClusters, mCfg.drawInitLinks, mCfg.drawLinks, mCfg.drawSeeds, mCfg.drawTracklets, mCfg.drawTracks, mCfg.drawGlobalTracks, mCfg.drawFinal, mFramesDone, mNDrawCalls, mXYZ[0], mXYZ[1], mXYZ[2], mRPhiTheta[0], mRPhiTheta[1] * 180 / M_PI, - mRPhiTheta[2] * 180 / M_PI, mAngle[1] * 180 / M_PI, mAngle[0] * 180 / M_PI, mAngle[2] * 180 / M_PI); + fps, mCfg.drawSlice, mCfg.drawClusters, mCfg.drawInitLinks, mCfg.drawLinks, mCfg.drawSeeds, mCfg.drawTracklets, mCfg.drawTracks, mCfg.drawGlobalTracks, mCfg.drawFinal, mFramesDone, mNDrawCalls, mXYZ[0], mXYZ[1], mXYZ[2], mRPhiTheta[0], mRPhiTheta[1] * 180 / CAMath::Pi(), + mRPhiTheta[2] * 180 / CAMath::Pi(), mAngle[1] * 180 / CAMath::Pi(), mAngle[0] * 180 / CAMath::Pi(), mAngle[2] * 180 / CAMath::Pi()); if (fpstime > 1.) { if (mPrintInfoText & 2) { GPUInfo("%s", info); From c24c5962a039570fd8c0ca4872bb83e2c28c7d69 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Fri, 9 Apr 2021 09:14:54 +0200 Subject: [PATCH 077/770] PWGHF: fix off-by-one bug in findBin() (#5885) * fix off-by-one bug in findBin() * Use c++ algorithms directly * remove redundant check --- .../include/AnalysisCore/HFSelectorCuts.h | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) diff --git a/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h b/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h index 0681acc1c27a4..4bc1ded308ffc 100644 --- a/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h +++ b/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h @@ -37,24 +37,7 @@ int findBin(o2::framework::Configurable> const& bins, T2 value) if (value >= bins->back()) { return -1; } - int step; - int bin = 0; - int count = bins->size(); - - while (count > 0) { - step = count / 2; - bin += step; - if (bins->operator[](bin) <= value) { - count -= step + 1; - } else { - bin -= step; - count = step; - } - } - if (bin == bins->size()) { - bin = 0; - } - return bin - 1; + return std::distance(bins->begin(), std::upper_bound(bins->begin(), bins->end(), value)) - 1; } // namespace per channel From 1573c7673d020e475d0e8e3a6de401dfbd79fcca Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Sat, 3 Apr 2021 00:34:47 +0200 Subject: [PATCH 078/770] DPL: allow custom orbit when using timer / enumeration The firstTForbit field is now given by the formula: firstTForbit = orbit-offset-enumeration + orbit-multiplier-enumeration + dh.tfCounter for the enumeration and timer cases. One can use, e.g.: --orbit-offset-enumeration and --orbit-multiplier-enumeration on the command line to affect the two parameters. --- .../include/Framework/ConfigParamsHelper.h | 4 ++ .../include/Framework/DataDescriptorMatcher.h | 7 ++++ .../include/Framework/ExpirationHandler.h | 16 ++++---- .../Core/include/Framework/LifetimeHelpers.h | 3 +- .../Core/include/Framework/TimesliceIndex.inc | 4 +- Framework/Core/src/ConfigParamsHelper.cxx | 10 +++++ Framework/Core/src/DataDescriptorMatcher.cxx | 4 +- Framework/Core/src/DataRelayer.cxx | 3 +- Framework/Core/src/DeviceSpecHelpers.cxx | 17 +++++--- Framework/Core/src/LifetimeHelpers.cxx | 39 ++++++++++++++----- Framework/Core/src/WorkflowHelpers.cxx | 5 +++ .../Core/src/WorkflowSerializationHelpers.cxx | 2 +- 12 files changed, 83 insertions(+), 31 deletions(-) diff --git a/Framework/Core/include/Framework/ConfigParamsHelper.h b/Framework/Core/include/Framework/ConfigParamsHelper.h index 91e31650510ed..6915f2247ba44 100644 --- a/Framework/Core/include/Framework/ConfigParamsHelper.h +++ b/Framework/Core/include/Framework/ConfigParamsHelper.h @@ -36,6 +36,10 @@ struct ConfigParamsHelper { options_description& options, boost::program_options::options_description vetos = options_description()); + /// Add the ConfigParamSpec @a spec to @a specs if there is no parameter with + /// the same name already. + static void addOptionIfMissing(std::vector& specs, ConfigParamSpec spec); + /// populate boost program options for a complete workflow template static boost::program_options::options_description diff --git a/Framework/Core/include/Framework/DataDescriptorMatcher.h b/Framework/Core/include/Framework/DataDescriptorMatcher.h index 0708dd3197347..87015b89c936a 100644 --- a/Framework/Core/include/Framework/DataDescriptorMatcher.h +++ b/Framework/Core/include/Framework/DataDescriptorMatcher.h @@ -41,6 +41,13 @@ struct ContextRef { inline bool operator==(ContextRef const& other) const; }; +/// Special positions for variables in context. +enum ContextPos { + STARTTIME_POS = 0, /// The DataProcessingHeader::startTime associated to the timeslice + TFCOUNTER_POS = 14, /// The DataHeader::tfCounter associated to the timeslice + FIRSTTFORBIT_POS = 15 /// The DataHeader::firstTFOrbit associated to the timeslice +}; + /// An element of the matching context. Context itself is really a vector of /// those. It's up to the matcher builder to build the vector in a suitable way. /// We do not have any float in the value, because AFAICT there is no need for diff --git a/Framework/Core/include/Framework/ExpirationHandler.h b/Framework/Core/include/Framework/ExpirationHandler.h index 82e609cc6bd13..217ae16932b42 100644 --- a/Framework/Core/include/Framework/ExpirationHandler.h +++ b/Framework/Core/include/Framework/ExpirationHandler.h @@ -8,17 +8,16 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef FRAMEWORK_EXPIRATIONHANDLER_H -#define FRAMEWORK_EXPIRATIONHANDLER_H +#ifndef O2_FRAMEWORK_EXPIRATIONHANDLER_H_ +#define O2_FRAMEWORK_EXPIRATIONHANDLER_H_ #include "Framework/Lifetime.h" #include "Framework/RoutingIndices.h" +#include "Framework/DataDescriptorMatcher.h" #include #include -namespace o2 -{ -namespace framework +namespace o2::framework { struct PartRef; @@ -29,7 +28,7 @@ struct TimesliceSlot; struct ExpirationHandler { using Creator = std::function; using Checker = std::function; - using Handler = std::function; + using Handler = std::function; RouteIndex routeIndex; Lifetime lifetime; @@ -38,7 +37,6 @@ struct ExpirationHandler { Handler handler; }; -} // namespace framework -} // namespace o2 +} // namespace o2::framework -#endif // FRAMEWORK_EXPIRATIONHANDLER_H +#endif // O2_FRAMEWORK_EXPIRATIONHANDLER_H_ diff --git a/Framework/Core/include/Framework/LifetimeHelpers.h b/Framework/Core/include/Framework/LifetimeHelpers.h index c6e4d24687736..2acc60a30fc66 100644 --- a/Framework/Core/include/Framework/LifetimeHelpers.h +++ b/Framework/Core/include/Framework/LifetimeHelpers.h @@ -76,7 +76,8 @@ struct LifetimeHelpers { /// dataOrigin, dataDescrition and dataSpecification of the given @a route. /// The payload of each message will contain an incremental number for each /// message being created. - static ExpirationHandler::Handler enumerate(ConcreteDataMatcher const& spec, std::string const& sourceChannel); + static ExpirationHandler::Handler enumerate(ConcreteDataMatcher const& spec, std::string const& sourceChannel, + int64_t orbitOffset, int64_t orbitMultiplier); /// Create a dummy (empty) message every time a record expires, suing @a spec /// as content of the payload. diff --git a/Framework/Core/include/Framework/TimesliceIndex.inc b/Framework/Core/include/Framework/TimesliceIndex.inc index 96d912b398b65..bbcd91df5b514 100644 --- a/Framework/Core/include/Framework/TimesliceIndex.inc +++ b/Framework/Core/include/Framework/TimesliceIndex.inc @@ -122,7 +122,7 @@ inline uint32_t TimesliceIndex::getFirstTFOrbitForSlot(TimesliceSlot slot) const { assert(mVariables.size() > slot.index); // firstTForbit is always at register 15 - auto pval = std::get_if(&mVariables[slot.index].get(15)); + auto pval = std::get_if(&mVariables[slot.index].get(data_matcher::FIRSTTFORBIT_POS)); if (pval == nullptr) { return -1; } @@ -132,7 +132,7 @@ inline uint32_t TimesliceIndex::getFirstTFOrbitForSlot(TimesliceSlot slot) const inline uint32_t TimesliceIndex::getFirstTFCounterForSlot(TimesliceSlot slot) const { assert(mVariables.size() > slot.index); - // firstTForbit is always at register 15 + // tfCounter is always at register 14 auto pval = std::get_if(&mVariables[slot.index].get(14)); if (pval == nullptr) { return -1; diff --git a/Framework/Core/src/ConfigParamsHelper.cxx b/Framework/Core/src/ConfigParamsHelper.cxx index 4ee2ae1fa994d..8d4d5c477a94a 100644 --- a/Framework/Core/src/ConfigParamsHelper.cxx +++ b/Framework/Core/src/ConfigParamsHelper.cxx @@ -89,6 +89,16 @@ void ConfigParamsHelper::populateBoostProgramOptions( } } +void ConfigParamsHelper::addOptionIfMissing(std::vector& specs, ConfigParamSpec spec) +{ + for (auto& old : specs) { + if (old.name == spec.name) { + return; + } + } + specs.push_back(spec); +} + /// populate boost program options making all options of type string /// this is used for filtering the command line argument bool ConfigParamsHelper::dpl2BoostOptions(const std::vector& spec, diff --git a/Framework/Core/src/DataDescriptorMatcher.cxx b/Framework/Core/src/DataDescriptorMatcher.cxx index 47a1df91589f4..58a6426673330 100644 --- a/Framework/Core/src/DataDescriptorMatcher.cxx +++ b/Framework/Core/src/DataDescriptorMatcher.cxx @@ -106,9 +106,9 @@ bool StartTimeValueMatcher::match(header::DataHeader const& dh, DataProcessingHe } context.put({ref->index, dph.startTime / mScale}); // We always put in 14 the tfCounter - context.put({14, dh.tfCounter}); + context.put({TFCOUNTER_POS, dh.tfCounter}); // We always put in 15 the firstTForbit - context.put({15, dh.firstTForbit}); + context.put({FIRSTTFORBIT_POS, dh.firstTForbit}); return true; } else if (auto v = std::get_if(&mValue)) { return (dph.startTime / mScale) == *v; diff --git a/Framework/Core/src/DataRelayer.cxx b/Framework/Core/src/DataRelayer.cxx index 2fe1c6f6c4daa..c27ae2d6f84c6 100644 --- a/Framework/Core/src/DataRelayer.cxx +++ b/Framework/Core/src/DataRelayer.cxx @@ -108,6 +108,7 @@ DataRelayer::ActivityStats DataRelayer::processDanglingInputs(std::vector("orbit-offset-enumeration"); + size_t orbitMultiplier = config.get("orbit-multiplier-enumeration"); + return LifetimeHelpers::enumerate(matcher, sourceChannel, orbitOffset, orbitMultiplier); }; } @@ -222,17 +227,17 @@ struct ExpirationHandlerHelpers { { try { ConcreteDataMatcher concrete = DataSpecUtils::asConcreteDataMatcher(spec); - return [concrete, sourceChannel](DeviceState&, ConfigParamRegistry const&) { + return [concrete, sourceChannel](DeviceState&, ConfigParamRegistry const& config) { return LifetimeHelpers::dummy(concrete, sourceChannel); }; } catch (...) { ConcreteDataTypeMatcher dataType = DataSpecUtils::asConcreteDataTypeMatcher(spec); ConcreteDataMatcher concrete{dataType.origin, dataType.description, 0xdeadbeef}; - return [concrete, sourceChannel](DeviceState&, ConfigParamRegistry const&) { + return [concrete, sourceChannel](DeviceState&, ConfigParamRegistry const& config) { return LifetimeHelpers::dummy(concrete, sourceChannel); }; + // We copy the matcher to avoid lifetime issues. } - // We copy the matcher to avoid lifetime issues. } }; diff --git a/Framework/Core/src/LifetimeHelpers.cxx b/Framework/Core/src/LifetimeHelpers.cxx index 3c4d7dfc485e3..ebfa6e44aa9a9 100644 --- a/Framework/Core/src/LifetimeHelpers.cxx +++ b/Framework/Core/src/LifetimeHelpers.cxx @@ -11,6 +11,7 @@ #include "Framework/DataProcessingHeader.h" #include "Framework/InputSpec.h" #include "Framework/LifetimeHelpers.h" +#include "Framework/DataDescriptorMatcher.h" #include "Framework/Logger.h" #include "Framework/RawDeviceService.h" #include "Framework/ServiceRegistry.h" @@ -143,7 +144,7 @@ ExpirationHandler::Checker LifetimeHelpers::expireTimed(std::chrono::microsecond /// expires via this mechanism). ExpirationHandler::Handler LifetimeHelpers::doNothing() { - return [](ServiceRegistry&, PartRef& ref, uint64_t) -> void { return; }; + return [](ServiceRegistry&, PartRef& ref, uint64_t, data_matcher::VariableContext&) -> void { return; }; } // We simply put everything in a stringstream and read it afterwards. @@ -188,7 +189,7 @@ ExpirationHandler::Handler if (matcher == nullptr) { throw runtime_error("InputSpec for Conditions must be fully qualified"); } - return [spec, matcher, sourceChannel, serverUrl = prefix, overrideTimestampMilliseconds](ServiceRegistry& services, PartRef& ref, uint64_t timestamp) -> void { + return [spec, matcher, sourceChannel, serverUrl = prefix, overrideTimestampMilliseconds](ServiceRegistry& services, PartRef& ref, uint64_t timestamp, data_matcher::VariableContext&) -> void { // We should invoke the handler only once. assert(!ref.header); assert(!ref.payload); @@ -265,7 +266,7 @@ ExpirationHandler::Handler /// FIXME: provide a way to customise the histogram from the configuration. ExpirationHandler::Handler LifetimeHelpers::fetchFromQARegistry() { - return [](ServiceRegistry&, PartRef& ref, uint64_t) -> void { + return [](ServiceRegistry&, PartRef& ref, uint64_t, data_matcher::VariableContext&) -> void { throw runtime_error("fetchFromQARegistry: Not yet implemented"); return; }; @@ -276,18 +277,19 @@ ExpirationHandler::Handler LifetimeHelpers::fetchFromQARegistry() /// FIXME: provide a way to customise the histogram from the configuration. ExpirationHandler::Handler LifetimeHelpers::fetchFromObjectRegistry() { - return [](ServiceRegistry&, PartRef& ref, uint64_t) -> void { + return [](ServiceRegistry&, PartRef& ref, uint64_t, data_matcher::VariableContext&) -> void { throw runtime_error("fetchFromObjectRegistry: Not yet implemented"); return; }; } /// Enumerate entries on every invokation. -ExpirationHandler::Handler LifetimeHelpers::enumerate(ConcreteDataMatcher const& matcher, std::string const& sourceChannel) +ExpirationHandler::Handler LifetimeHelpers::enumerate(ConcreteDataMatcher const& matcher, std::string const& sourceChannel, + int64_t orbitOffset, int64_t orbitMultiplier) { using counter_t = int64_t; auto counter = std::make_shared(0); - auto f = [matcher, counter, sourceChannel](ServiceRegistry& services, PartRef& ref, uint64_t timestamp) -> void { + return [matcher, counter, sourceChannel, orbitOffset, orbitMultiplier](ServiceRegistry& services, PartRef& ref, uint64_t timestamp, data_matcher::VariableContext& variables) -> void { // We should invoke the handler only once. assert(!ref.header); assert(!ref.payload); @@ -299,6 +301,10 @@ ExpirationHandler::Handler LifetimeHelpers::enumerate(ConcreteDataMatcher const& dh.subSpecification = matcher.subSpec; dh.payloadSize = sizeof(counter_t); dh.payloadSerializationMethod = gSerializationMethodNone; + dh.tfCounter = timestamp; + dh.firstTForbit = timestamp * orbitMultiplier + orbitOffset; + variables.put({data_matcher::FIRSTTFORBIT_POS, dh.firstTForbit}); + variables.put({data_matcher::TFCOUNTER_POS, dh.tfCounter}); DataProcessingHeader dph{timestamp, 1}; @@ -312,7 +318,6 @@ ExpirationHandler::Handler LifetimeHelpers::enumerate(ConcreteDataMatcher const& ref.payload = std::move(payload); (*counter)++; }; - return f; } /// Create a dummy message with the provided ConcreteDataMatcher @@ -320,7 +325,7 @@ ExpirationHandler::Handler LifetimeHelpers::dummy(ConcreteDataMatcher const& mat { using counter_t = int64_t; auto counter = std::make_shared(0); - auto f = [matcher, counter, sourceChannel](ServiceRegistry& services, PartRef& ref, uint64_t timestamp) -> void { + auto f = [matcher, counter, sourceChannel](ServiceRegistry& services, PartRef& ref, uint64_t timestamp, data_matcher::VariableContext& variables) -> void { // We should invoke the handler only once. assert(!ref.header); assert(!ref.payload); @@ -332,7 +337,23 @@ ExpirationHandler::Handler LifetimeHelpers::dummy(ConcreteDataMatcher const& mat dh.subSpecification = matcher.subSpec; dh.payloadSize = 0; dh.payloadSerializationMethod = gSerializationMethodNone; - dh.tfCounter = timestamp; + + { + auto pval = std::get_if(&variables.get(data_matcher::FIRSTTFORBIT_POS)); + if (pval == nullptr) { + dh.firstTForbit = -1; + } else { + dh.firstTForbit = *pval; + } + } + { + auto pval = std::get_if(&variables.get(data_matcher::TFCOUNTER_POS)); + if (pval == nullptr) { + dh.tfCounter = timestamp; + } else { + dh.tfCounter = *pval; + } + } DataProcessingHeader dph{timestamp, 1}; diff --git a/Framework/Core/src/WorkflowHelpers.cxx b/Framework/Core/src/WorkflowHelpers.cxx index 82a98b3daffc2..f9bd3c7d134d7 100644 --- a/Framework/Core/src/WorkflowHelpers.cxx +++ b/Framework/Core/src/WorkflowHelpers.cxx @@ -11,6 +11,7 @@ #include "Framework/AlgorithmSpec.h" #include "Framework/AODReaderHelpers.h" #include "Framework/ChannelMatching.h" +#include "Framework/ConfigParamsHelper.h" #include "Framework/CommonDataProcessors.h" #include "Framework/ConfigContext.h" #include "Framework/DeviceSpec.h" @@ -263,6 +264,8 @@ void WorkflowHelpers::injectServiceDevices(WorkflowSpec& workflow, ConfigContext {ConfigParamSpec{"aod-file", VariantType::String, {"Input AOD file"}}, ConfigParamSpec{"aod-reader-json", VariantType::String, {"json configuration file"}}, ConfigParamSpec{"time-limit", VariantType::Int64, 0ll, {"Maximum run time limit in seconds"}}, + ConfigParamSpec{"orbit-offset-enumeration", VariantType::Int64, 0ll, {"initial value for the orbit"}}, + ConfigParamSpec{"orbit-multiplier-enumeration", VariantType::Int64, 0ll, {"multiplier to get the orbit from the counter"}}, ConfigParamSpec{"start-value-enumeration", VariantType::Int64, 0ll, {"initial value for the enumeration"}}, ConfigParamSpec{"end-value-enumeration", VariantType::Int64, -1ll, {"final value for the enumeration"}}, ConfigParamSpec{"step-value-enumeration", VariantType::Int64, 1ll, {"step between one value and the other"}}}, @@ -289,6 +292,8 @@ void WorkflowHelpers::injectServiceDevices(WorkflowSpec& workflow, ConfigContext std::string prefix = "internal-dpl-"; if (processor.inputs.empty() && processor.name.compare(0, prefix.size(), prefix) != 0) { processor.inputs.push_back(InputSpec{"enumeration", "DPL", "ENUM", static_cast(compile_time_hash(processor.name.c_str())), Lifetime::Enumeration}); + ConfigParamsHelper::addOptionIfMissing(processor.options, ConfigParamSpec{"orbit-offset-enumeration", VariantType::Int64, 0ll, {"1st injected orbit"}}); + ConfigParamsHelper::addOptionIfMissing(processor.options, ConfigParamSpec{"orbit-multiplier-enumeration", VariantType::Int64, 0ll, {"orbits/TForbit"}}); processor.options.push_back(ConfigParamSpec{"start-value-enumeration", VariantType::Int64, 0ll, {"initial value for the enumeration"}}); processor.options.push_back(ConfigParamSpec{"end-value-enumeration", VariantType::Int64, -1ll, {"final value for the enumeration"}}); processor.options.push_back(ConfigParamSpec{"step-value-enumeration", VariantType::Int64, 1ll, {"step between one value and the other"}}); diff --git a/Framework/Core/src/WorkflowSerializationHelpers.cxx b/Framework/Core/src/WorkflowSerializationHelpers.cxx index a99ea86bbddb9..7be2ac75ddddd 100644 --- a/Framework/Core/src/WorkflowSerializationHelpers.cxx +++ b/Framework/Core/src/WorkflowSerializationHelpers.cxx @@ -765,7 +765,7 @@ void WorkflowSerializationHelpers::dump(std::ostream& out, w.Key("options"); w.StartArray(); for (auto& option : processor.options) { - if (option.name == "start-value-enumeration" || option.name == "end-value-enumeration" || option.name == "step-value-enumeration") { + if (option.name == "start-value-enumeration" || option.name == "end-value-enumeration" || option.name == "step-value-enumeration" || option.name == "orbit-offset-enumeration" || option.name == "orbit-multiplier-enumeration") { continue; } w.StartObject(); From 166a85888b3b43b15fa4eeb68e45f6885da81fe2 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Fri, 9 Apr 2021 10:07:47 +0200 Subject: [PATCH 079/770] Allow cleaning pr check from github actions Similar to the alidist one, but with AliceO2 defaults. --- .github/workflows/clean-pr-checks.yml | 66 +++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 .github/workflows/clean-pr-checks.yml diff --git a/.github/workflows/clean-pr-checks.yml b/.github/workflows/clean-pr-checks.yml new file mode 100644 index 0000000000000..6cdb1c41b40e3 --- /dev/null +++ b/.github/workflows/clean-pr-checks.yml @@ -0,0 +1,66 @@ +name: Clean PR checks +on: + workflow_dispatch: + inputs: + pr: + description: PR to be cleaned + required: true + checks: + description: Checks to be cleaned + required: true + default: 'build/AliceO2/O2/o2/macOS,build/O2/fullCI,build/O2/o2' + owner: + description: Organization + required: true + default: 'AliceO2Group' + repo: + description: Repository + required: true + default: 'AliceO2' +jobs: + cleanup_pr_checks: + runs-on: ubuntu-latest + steps: + - name: Set up Python 3.7 + uses: actions/setup-python@v1 + with: + python-version: 3.7 + - name: Install ali-bot + run: | + sudo apt-get update + sudo apt-get install libsasl2-dev python-dev libldap2-dev libssl-dev + python -m pip install --upgrade pip + pip install git+https://github.com/alisw/ali-bot@master + - uses: octokit/graphql-action@v2.x + id: get_last_commit_for_pr + with: + query: | + { + repository(owner: "${{ github.event.inputs.owner }}", name: "${{ github.event.inputs.repo }}") { + url + pullRequest(number:${{ github.event.inputs.pr }}) { + commits(last: 1) { + nodes { + commit { + oid + } + } + } + } + } + } + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Cleanup tests + run: |- + set -x + cat <<\EOF > results.json + ${{ steps.get_last_commit_for_pr.outputs.data }} + EOF + COMMIT=$(jq -r '.repository.pullRequest.commits.nodes[].commit.oid' results.json) + echo $COMMIT + for check in `echo ${{ github.event.inputs.checks }} | tr , \\\\n`; do + set-github-status -c ${{ github.event.inputs.owner }}/${{ github.event.inputs.repo }}@$COMMIT -s $check/pending + done + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From d9dceeb729482a20aa901d0aaf1fd09a88c579ec Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Fri, 9 Apr 2021 10:27:52 +0200 Subject: [PATCH 080/770] Delete duplicate file. --- .github/workflows/clean-pr-checks.yml | 66 --------------------------- 1 file changed, 66 deletions(-) delete mode 100644 .github/workflows/clean-pr-checks.yml diff --git a/.github/workflows/clean-pr-checks.yml b/.github/workflows/clean-pr-checks.yml deleted file mode 100644 index 6cdb1c41b40e3..0000000000000 --- a/.github/workflows/clean-pr-checks.yml +++ /dev/null @@ -1,66 +0,0 @@ -name: Clean PR checks -on: - workflow_dispatch: - inputs: - pr: - description: PR to be cleaned - required: true - checks: - description: Checks to be cleaned - required: true - default: 'build/AliceO2/O2/o2/macOS,build/O2/fullCI,build/O2/o2' - owner: - description: Organization - required: true - default: 'AliceO2Group' - repo: - description: Repository - required: true - default: 'AliceO2' -jobs: - cleanup_pr_checks: - runs-on: ubuntu-latest - steps: - - name: Set up Python 3.7 - uses: actions/setup-python@v1 - with: - python-version: 3.7 - - name: Install ali-bot - run: | - sudo apt-get update - sudo apt-get install libsasl2-dev python-dev libldap2-dev libssl-dev - python -m pip install --upgrade pip - pip install git+https://github.com/alisw/ali-bot@master - - uses: octokit/graphql-action@v2.x - id: get_last_commit_for_pr - with: - query: | - { - repository(owner: "${{ github.event.inputs.owner }}", name: "${{ github.event.inputs.repo }}") { - url - pullRequest(number:${{ github.event.inputs.pr }}) { - commits(last: 1) { - nodes { - commit { - oid - } - } - } - } - } - } - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - name: Cleanup tests - run: |- - set -x - cat <<\EOF > results.json - ${{ steps.get_last_commit_for_pr.outputs.data }} - EOF - COMMIT=$(jq -r '.repository.pullRequest.commits.nodes[].commit.oid' results.json) - echo $COMMIT - for check in `echo ${{ github.event.inputs.checks }} | tr , \\\\n`; do - set-github-status -c ${{ github.event.inputs.owner }}/${{ github.event.inputs.repo }}@$COMMIT -s $check/pending - done - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 3135f26e704adf76391045c684dc408eb099a0c0 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Wed, 7 Apr 2021 22:37:35 +0200 Subject: [PATCH 081/770] DPL: correctly report uint32 metrics for DataRelayer --- Framework/Core/src/DataRelayer.cxx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Framework/Core/src/DataRelayer.cxx b/Framework/Core/src/DataRelayer.cxx index c27ae2d6f84c6..12ccbccb2d81e 100644 --- a/Framework/Core/src/DataRelayer.cxx +++ b/Framework/Core/src/DataRelayer.cxx @@ -180,6 +180,8 @@ void sendVariableContextMetrics(VariableContext& context, TimesliceSlot slot, auto& var = context.get(i); if (auto pval = std::get_if(&var)) { metrics.send(monitoring::Metric{std::to_string(*pval), names[16 * slot.index + i]}); + } else if (auto pval = std::get_if(&var)) { + metrics.send(monitoring::Metric{std::to_string(*pval), names[16 * slot.index + i]}); } else if (auto pval2 = std::get_if(&var)) { metrics.send(monitoring::Metric{*pval2, names[16 * slot.index + i]}); } else { From 7476c0f3f2c60fb54c7cbe525cf59be9215728c5 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Wed, 7 Apr 2021 22:52:10 +0200 Subject: [PATCH 082/770] DPL GUI: better display of variable context --- .../src/FrameworkGUIDataRelayerUsage.cxx | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/Framework/GUISupport/src/FrameworkGUIDataRelayerUsage.cxx b/Framework/GUISupport/src/FrameworkGUIDataRelayerUsage.cxx index 46973ec78a9e1..8350b0dc5fa11 100644 --- a/Framework/GUISupport/src/FrameworkGUIDataRelayerUsage.cxx +++ b/Framework/GUISupport/src/FrameworkGUIDataRelayerUsage.cxx @@ -11,8 +11,10 @@ #include #include "Framework/DeviceMetricsInfo.h" #include "Framework/DeviceInfo.h" +#include "Framework/DataDescriptorMatcher.h" #include "PaletteHelpers.h" #include +#include #include static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); } @@ -141,10 +143,22 @@ void displayDataRelayer(DeviceMetricsInfo const& metrics, MetricInfo const& metricInfo = metrics.metrics[variablesIndex.indexes[idx]]; assert(metricInfo.storeIdx < metrics.stringMetrics.size()); auto& data = metrics.stringMetrics[metricInfo.storeIdx]; - if (vi == 0) { - ImGui::Text("$%zu (timeslice): %s", vi, data[(metricInfo.pos - 1) % data.size()].data); - } else { - ImGui::Text("$%zu: %s", vi, data[(metricInfo.pos - 1) % data.size()].data); + char const* value = data[(metricInfo.pos - 1) % data.size()].data; + if (strncmp("null", value, 4) == 0) { + continue; + } + switch (vi) { + case o2::framework::data_matcher::STARTTIME_POS: + ImGui::Text("$%zu (startTime): %s", vi, value); + break; + case o2::framework::data_matcher::TFCOUNTER_POS: + ImGui::Text("$%zu (tfCounter): %s", vi, value); + break; + case o2::framework::data_matcher::FIRSTTFORBIT_POS: + ImGui::Text("$%zu (firstTFOrbit): %s", vi, value); + break; + default: + ImGui::Text("$%zu: %s", vi, value); } } ImGui::EndTooltip(); From add267ad8b14a1050c02a5a5ce1ba5881c32d796 Mon Sep 17 00:00:00 2001 From: shahoian Date: Fri, 9 Apr 2021 16:34:49 +0200 Subject: [PATCH 083/770] CTF name contains run, TF 1st orbit and ID, + misc fixes --- .../Common/include/DetectorsCommonDataFormats/NameConf.h | 2 +- DataFormats/Detectors/Common/src/NameConf.cxx | 4 ++-- Detectors/CTF/workflow/src/CTFWriterSpec.cxx | 8 +++----- prodtests/full-system-test/dpl-workflow.sh | 3 ++- prodtests/full_system_test.sh | 4 +++- 5 files changed, 11 insertions(+), 10 deletions(-) diff --git a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h index c089c1008efba..5565271ae133a 100644 --- a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h +++ b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h @@ -101,7 +101,7 @@ class NameConf static constexpr std::string_view CTFTREENAME = "ctf"; // hardcoded // CTF Filename - static std::string getCTFFileName(long id, const std::string_view prefix = "o2_ctf"); + static std::string getCTFFileName(uint32_t run, uint32_t orb, uint32_t id, const std::string_view prefix = "o2_ctf"); private: // unmodifiable constants used to construct filenames etc diff --git a/DataFormats/Detectors/Common/src/NameConf.cxx b/DataFormats/Detectors/Common/src/NameConf.cxx index 696b6b3ca5a0f..ae8b2d6ee9bf6 100644 --- a/DataFormats/Detectors/Common/src/NameConf.cxx +++ b/DataFormats/Detectors/Common/src/NameConf.cxx @@ -85,7 +85,7 @@ std::string NameConf::getMatLUTFileName(const std::string_view prefix) return o2::utils::concat_string(prefix, MATBUDLUT, ".root"); } -std::string NameConf::getCTFFileName(long id, const std::string_view prefix) +std::string NameConf::getCTFFileName(uint32_t run, uint32_t orb, uint32_t id, const std::string_view prefix) { - return o2::utils::concat_string(prefix, "_", fmt::format("{:010d}", id), ".root"); + return o2::utils::concat_string(prefix, "_", fmt::format("run{:08d}_orbit{:010d}_tf{:010d}", run, orb, id), ".root"); } diff --git a/Detectors/CTF/workflow/src/CTFWriterSpec.cxx b/Detectors/CTF/workflow/src/CTFWriterSpec.cxx index 272da0eda2dc6..56415ce1f30b4 100644 --- a/Detectors/CTF/workflow/src/CTFWriterSpec.cxx +++ b/Detectors/CTF/workflow/src/CTFWriterSpec.cxx @@ -200,19 +200,17 @@ void CTFWriterSpec::run(ProcessingContext& pc) { auto cput = mTimer.CpuTime(); mTimer.Start(false); - auto tfOrb = DataRefUtils::getHeader(pc.inputs().getByPos(0))->firstTForbit; + const auto dh = DataRefUtils::getHeader(pc.inputs().getByPos(0)); std::unique_ptr fileOut; std::unique_ptr treeOut; if (mWriteCTF) { - // fileOut.reset(TFile::Open(o2::base::NameConf::getCTFFileName(tfOrb).c_str(), "recreate")); - // RS Until the DPL will propagate the firstTForbit, we will use simple counter in CTF file name to avoid overwriting in case of multiple TFs - fileOut.reset(TFile::Open(o2::base::NameConf::getCTFFileName(mNTF).c_str(), "recreate")); + fileOut.reset(TFile::Open(o2::base::NameConf::getCTFFileName(dh->runNumber, dh->firstTForbit, dh->tfCounter).c_str(), "recreate")); treeOut = std::make_unique(std::string(o2::base::NameConf::CTFTREENAME).c_str(), "O2 CTF tree"); } // create header - CTFHeader header{mRun, tfOrb}; + CTFHeader header{mRun, dh->firstTForbit}; processDet(pc, DetID::ITS, header, treeOut.get()); processDet(pc, DetID::MFT, header, treeOut.get()); diff --git a/prodtests/full-system-test/dpl-workflow.sh b/prodtests/full-system-test/dpl-workflow.sh index f70d427a7aea0..fc4851f0ec005 100755 --- a/prodtests/full-system-test/dpl-workflow.sh +++ b/prodtests/full-system-test/dpl-workflow.sh @@ -84,7 +84,8 @@ fi if [ $CTFINPUT == 1 ]; then TPC_INPUT=compressed-clusters-ctf TOF_INPUT=digits - WORKFLOW="o2-ctf-reader-workflow --ctf-input o2_ctf_0000000000.root --onlyDet $CTF_DETECTORS $ARGS_ALL | " + CTFName=`ls -t o2_ctf_*.root | head -n1` + WORKFLOW="o2-ctf-reader-workflow --ctf-input ${CTFName} --onlyDet $CTF_DETECTORS $ARGS_ALL | " elif [ $EXTINPUT == 1 ]; then WORKFLOW="o2-dpl-raw-proxy $ARGS_ALL --dataspec \"FLP:FLP/DISTSUBTIMEFRAME/0;B:TPC/RAWDATA;C:ITS/RAWDATA;D:TOF/RAWDATA;D:MFT/RAWDATA;E:FT0/RAWDATA;F:MID/RAWDATA;G:EMC/RAWDATA;H:PHS/RAWDATA;I:CPV/RAWDATA;J:ZDC/RAWDATA;K:HMP/RAWDATA;L:FDD/RAWDATA\" --channel-config \"name=readout-proxy,type=pull,method=connect,address=ipc://@stfb-to-dpl,transport=shmem,rateLogging=0\" | " else diff --git a/prodtests/full_system_test.sh b/prodtests/full_system_test.sh index 8306f4604daba..2262f1c2c8302 100755 --- a/prodtests/full_system_test.sh +++ b/prodtests/full_system_test.sh @@ -36,6 +36,8 @@ NHBPERTF=${NHBPERTF:-128} RUNFIRSTORBIT=${RUNFIRSTORBIT:-0} FIRSTSAMPLEDORBIT=${FIRSTSAMPLEDORBIT:-0} +[ "$FIRSTSAMPLEDORBIT" -lt "$RUNFIRSTORBIT" ] && FIRSTSAMPLEDORBIT=$RUNFIRSTORBIT + # allow skipping JOBUTILS_SKIPDONE=ON # enable memory monitoring (independent on whether DPL or not) @@ -66,7 +68,7 @@ QED2HAD=$(awk "BEGIN {printf \"%.2f\",`grep xSectionQED qedgenparam.ini | cut -d echo "Obtained ratio of QED to hadronic x-sections = $QED2HAD" >> qedsim.log cd .. -DIGITRDOPTREAL="--configKeyValues \"${HBFUTILPARAMS};TRDSimParams.digithreads=${NJOBS}\" --enable-trd-trapsim" +DIGITRDOPTREAL="--configKeyValues \"${HBFUTILPARAMS};TRDSimParams.digithreads=${NJOBS}\" " if [ $SPLITTRDDIGI == "1" ]; then DIGITRDOPT="--configKeyValues \"${HBFUTILPARAMS}\" --skipDet TRD" else From f6a128f5006cfb0abf5d69d57ed245a07eb09418 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Sat, 10 Apr 2021 08:56:23 +0200 Subject: [PATCH 084/770] Clean also build/O2/fullCI by default --- .github/workflows/clean-test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clean-test.yml b/.github/workflows/clean-test.yml index 270ea519191e2..656f4e31caf22 100644 --- a/.github/workflows/clean-test.yml +++ b/.github/workflows/clean-test.yml @@ -8,7 +8,7 @@ on: checks: description: Checks to be cleaned required: true - default: 'build/O2/o2,build/O2/gpu,build/AliceO2/O2/o2/macOS,build/o2checkcode/o2' + default: 'build/O2/o2,build/O2/gpu,build/AliceO2/O2/o2/macOS,build/o2checkcode/o2,build/O2/fullCI' owner: description: Organization required: true From 0ab06ad1c28068192aa1743a49d96ea668bc7170 Mon Sep 17 00:00:00 2001 From: Sandro Wenzel Date: Fri, 9 Apr 2021 21:58:38 +0200 Subject: [PATCH 085/770] jobutils: Detect libc++abi exception --- Utilities/Tools/jobutils.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/Utilities/Tools/jobutils.sh b/Utilities/Tools/jobutils.sh index c79d656af5ea1..f01fa72c0f11d 100644 --- a/Utilities/Tools/jobutils.sh +++ b/Utilities/Tools/jobutils.sh @@ -178,6 +178,7 @@ taskwrapper() { -e \"bus error\" \ -e \"Assertion.*failed\" \ -e \"Fatal in\" \ + -e \"libc++abi.*terminating\" \ -e \"There was a crash.\"" grepcommand="grep -H ${pattern} $logfile ${JOBUTILS_JOB_SUPERVISEDFILES} >> encountered_exceptions_list 2>/dev/null" From f9ba163c72754b855c2d066955c3be63ff462822 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Sat, 10 Apr 2021 08:33:45 +0200 Subject: [PATCH 086/770] DPL: do not allocate handle in separate thread --- Framework/Core/src/DataProcessingDevice.cxx | 24 ++++++++++----------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Framework/Core/src/DataProcessingDevice.cxx b/Framework/Core/src/DataProcessingDevice.cxx index 3e7e898fbabfa..928bf1751f198 100644 --- a/Framework/Core/src/DataProcessingDevice.cxx +++ b/Framework/Core/src/DataProcessingDevice.cxx @@ -262,20 +262,20 @@ void DataProcessingDevice::Init() mState.inputChannelInfos[ci].state = InputChannelState::Pull; } } + uv_async_t* wakeHandle = (uv_async_t*)malloc(sizeof(uv_async_t)); + assert(mState.loop); + int res = uv_async_init(mState.loop, wakeHandle, nullptr); + if (res < 0) { + LOG(ERROR) << "Unable to initialise subscription"; + } + /// This should post a message on the queue... - SubscribeToNewTransition("dpl", [loop = mState.loop](fair::mq::Transition t) { - if (loop) { - uv_async_t handle; - int res = uv_async_init(loop, &handle, nullptr); - if (res < 0) { - LOG(ERROR) << "Unable to initialise subscription"; - } - res = uv_async_send(&handle); - if (res < 0) { - LOG(ERROR) << "Unable to notify subscription"; - } - LOG(debug) << "State transition requested"; + SubscribeToNewTransition("dpl", [wakeHandle](fair::mq::Transition t) { + int res = uv_async_send(wakeHandle); + if (res < 0) { + LOG(ERROR) << "Unable to notify subscription"; } + LOG(debug) << "State transition requested"; }); } From d3def8ac267f315228a405f310b61b3bac8948a9 Mon Sep 17 00:00:00 2001 From: shahoian Date: Sat, 10 Apr 2021 18:12:22 +0200 Subject: [PATCH 087/770] AutoSave option for RootTreeWriter --autosave option allows to save the tree after every n events. The default is -1 (autosave off), can be changed in the MakeRootTreeWriterSpec constructor by providing an integer argument coming after (not necessarilly immidiately) the number or events. --- .../include/DPLUtils/MakeRootTreeWriterSpec.h | 26 ++++++++++++++++--- .../Utils/include/DPLUtils/RootTreeWriter.h | 11 ++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/Framework/Utils/include/DPLUtils/MakeRootTreeWriterSpec.h b/Framework/Utils/include/DPLUtils/MakeRootTreeWriterSpec.h index b580d989f9bd3..27cfc338b3b92 100644 --- a/Framework/Utils/include/DPLUtils/MakeRootTreeWriterSpec.h +++ b/Framework/Utils/include/DPLUtils/MakeRootTreeWriterSpec.h @@ -64,6 +64,7 @@ namespace framework /// --outfile /// --treename /// --nevents +/// --autosave /// --terminate /// /// \par @@ -73,8 +74,10 @@ namespace framework /// \par Constructor arguments: /// Default file name can be configured alone, tree name can only be specified after /// file name. The default number of events can be specified at arbitrary place between -/// process name and branch configuration. The process will signal to the DPL that it -/// is ready for termination. +/// process name and branch configuration. The number of events triggering autosaving +/// (by default - off) can be also specified in the constructor as an integer argument +/// coming after (not necessarilly immidiately) the number or events. The process will +/// signal to the DPL that it is ready for termination. /// /// \par Termination policy: /// The configurable termination policy specifies what to signal to the DPL when the event @@ -334,6 +337,8 @@ class MakeRootTreeWriterSpec std::vector> branchNameOptions; // number of events to be processed int nEvents = -1; + // autosave every nEventsAutoSave events + int nEventsAutoSave = -1; // starting with all inputs, every input which has been indicated 'ready' is removed std::unordered_set activeInputs; // event counter @@ -372,6 +377,7 @@ class MakeRootTreeWriterSpec << "different branches on the same input. Be aware that the --nevents option might lead to incomplete\n" << "data in the output file as the number of processed input sets is counted"; } + processAttributes->nEventsAutoSave = ic.options().get("autosave"); try { processAttributes->terminationPolicy = TerminationPolicyMap.at(ic.options().get("terminate")); } catch (std::out_of_range&) { @@ -404,6 +410,7 @@ class MakeRootTreeWriterSpec auto& activeInputs = processAttributes->activeInputs; auto& counter = processAttributes->counter; auto& nEvents = processAttributes->nEvents; + auto& nEventsAutoSave = processAttributes->nEventsAutoSave; if (writer->isClosed()) { return; } @@ -459,6 +466,8 @@ class MakeRootTreeWriterSpec if ((nEvents >= 0 && counter == nEvents) || checkReady(pc.inputs())) { writer->close(); pc.services().get().readyToQuit(terminationPolicy == TerminationPolicy::Workflow ? QuitRequest::All : QuitRequest::Me); + } else if (nEventsAutoSave > 0 && counter && (counter % nEventsAutoSave) == 0) { + writer->autoSave(); } }; @@ -471,6 +480,7 @@ class MakeRootTreeWriterSpec {"treename", VariantType::String, mDefaultTreeName.c_str(), {"Name of tree"}}, {"treetitle", VariantType::String, mDefaultTreeTitle.c_str(), {"Title of tree"}}, {"nevents", VariantType::Int, mDefaultNofEvents, {"Number of events to execute"}}, + {"autosave", VariantType::Int, mDefaultAutoSave, {"Autosave after number of events"}}, {"terminate", VariantType::String, mDefaultTerminationPolicy.c_str(), {"Terminate the 'process' or 'workflow'"}}, }; for (size_t branchIndex = 0; branchIndex < mBranchNameOptions.size(); branchIndex++) { @@ -521,8 +531,14 @@ class MakeRootTreeWriterSpec void parseConstructorArgs(int arg, Args&&... args) { static_assert(N == 0, "wrong argument order, default file and tree options must come before branch specs"); - mDefaultNofEvents = arg; - + if (mNIntArgCounter == 0) { + mDefaultNofEvents = arg; + } else if (mNIntArgCounter == 1) { + mDefaultAutoSave = arg; + } else { + throw std::logic_error("Too many integer arguments in the constructor"); + } + mNIntArgCounter++; parseConstructorArgs(std::forward(args)...); } @@ -620,10 +636,12 @@ class MakeRootTreeWriterSpec std::string mDefaultTreeName; std::string mDefaultTreeTitle; int mDefaultNofEvents = -1; + int mDefaultAutoSave = -1; std::string mDefaultTerminationPolicy = "process"; TerminationCondition mTerminationCondition; Preprocessor mPreprocessor; size_t mNofBranches = 0; + int mNIntArgCounter = 0; CustomClose mCustomClose; }; } // namespace framework diff --git a/Framework/Utils/include/DPLUtils/RootTreeWriter.h b/Framework/Utils/include/DPLUtils/RootTreeWriter.h index 69a1d86e0cfc8..ac0108155678b 100644 --- a/Framework/Utils/include/DPLUtils/RootTreeWriter.h +++ b/Framework/Utils/include/DPLUtils/RootTreeWriter.h @@ -363,6 +363,17 @@ class RootTreeWriter mFile.reset(nullptr); } + /// autosave the tree + void autoSave() + { + if (mIsClosed || !mFile) { + return; + } + mTree->SetEntries(); + LOG(INFO) << "Autosaving " << mTree->GetName() << " at entry " << mTree->GetEntries(); + mTree->AutoSave("overwrite"); + } + bool isClosed() const { return mIsClosed; From f0575b3ed2e88c4400789bd68807033a4ee35e4f Mon Sep 17 00:00:00 2001 From: shahoian Date: Sat, 10 Apr 2021 18:13:02 +0200 Subject: [PATCH 088/770] Cosmics writer: example of AutoSave request in MakeRootTreeWriterSpec --- Detectors/GlobalTrackingWorkflow/src/TrackCosmicsWriterSpec.cxx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Detectors/GlobalTrackingWorkflow/src/TrackCosmicsWriterSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/TrackCosmicsWriterSpec.cxx index ef7c55b656b99..d6e468b56a58f 100644 --- a/Detectors/GlobalTrackingWorkflow/src/TrackCosmicsWriterSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/TrackCosmicsWriterSpec.cxx @@ -37,6 +37,8 @@ DataProcessorSpec getTrackCosmicsWriterSpec(bool useMC) return MakeRootTreeWriterSpec("cosmic-track-writer", "cosmics.root", "cosmics", + -1, // do not limit number of events to store + 100, // periodically autosave BranchDefinition{InputSpec{"tracks", "GLO", "COSMICTRC", 0}, "tracks", "tracks-branch-name", From 1a14018516b97c41e4a33f9c4f2fc4c0f7cdfd18 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Sun, 11 Apr 2021 00:40:27 +0200 Subject: [PATCH 089/770] StepTHn: use AddAt rather than Get+Set (#5897) --- Framework/Core/include/Framework/StepTHn.h | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/Framework/Core/include/Framework/StepTHn.h b/Framework/Core/include/Framework/StepTHn.h index 71f1288b06533..4a33cb8714e41 100644 --- a/Framework/Core/include/Framework/StepTHn.h +++ b/Framework/Core/include/Framework/StepTHn.h @@ -43,6 +43,9 @@ class StepTHn : public TNamed } return mTarget[step]; } + + virtual void AddAt(TArray* array, Double_t c, Int_t i) = 0; + Int_t getNSteps() { return mNSteps; } Int_t getNVar() { return mNVars; } @@ -93,6 +96,11 @@ class StepTHnT : public StepTHn StepTHnT(const char* name, const char* title, const int nSteps, const int nAxes, const int* nBins, const double* xmin, const double* xmax); ~StepTHnT() override = default; + void AddAt(TArray* a, double c, int bin) final + { + static_cast(a)->AddAt(c, bin); + } + protected: TArray* createArray(const TArray* src = nullptr) const override { @@ -186,10 +194,9 @@ void StepTHn::Fill(Int_t istep, const Ts&... valuesAndWeight) } } - // TODO probably slow; add StepTHnT::add ? - mValues[istep]->SetAt(mValues[istep]->GetAt(bin) + weight, bin); + this->AddAt(mValues[istep], weight, bin); if (mSumw2[istep]) { - mSumw2[istep]->SetAt(mSumw2[istep]->GetAt(bin) + weight, bin); + this->AddAt(mSumw2[istep], weight, bin); } } From a2c536bac7840b95b4341a23ae6178cd505ec112 Mon Sep 17 00:00:00 2001 From: sevdokim <30727271+sevdokim@users.noreply.github.com> Date: Sun, 11 Apr 2021 15:49:36 +0200 Subject: [PATCH 090/770] CPV fix simulation workflow (#5887) * Fixed CPV simulation workflow * applied clang-format * fix for ~statement should be inside braces~ mumbling Co-authored-by: sevdokim --- .../CPV/base/include/CPVBase/CPVSimParams.h | 40 +++--- .../CPV/calib/include/CPVCalib/Pedestals.h | 13 +- Detectors/CPV/calib/src/CalibParams.cxx | 2 +- Detectors/CPV/calib/src/Pedestals.cxx | 38 +++++- .../include/CPVSimulation/Digitizer.h | 13 +- .../include/CPVSimulation/RawWriter.h | 2 + Detectors/CPV/simulation/src/Detector.cxx | 1 - Detectors/CPV/simulation/src/Digitizer.cxx | 80 ++++++++---- Detectors/CPV/simulation/src/RawWriter.cxx | 24 +++- Detectors/CPV/testsimulation/CMakeLists.txt | 5 + Detectors/CPV/testsimulation/plot_clu_cpv.C | 118 ++++++++++++++++++ Detectors/CPV/testsimulation/plot_dig_cpv.C | 55 +++++--- Detectors/CPV/testsimulation/plot_hit_cpv.C | 2 +- .../CPVWorkflow/RawToDigitConverterSpec.h | 3 + .../workflow/src/RawToDigitConverterSpec.cxx | 47 ++++++- 15 files changed, 359 insertions(+), 84 deletions(-) create mode 100644 Detectors/CPV/testsimulation/plot_clu_cpv.C diff --git a/Detectors/CPV/base/include/CPVBase/CPVSimParams.h b/Detectors/CPV/base/include/CPVBase/CPVSimParams.h index 818b498662c5e..eb83ad2431ce3 100644 --- a/Detectors/CPV/base/include/CPVBase/CPVSimParams.h +++ b/Detectors/CPV/base/include/CPVBase/CPVSimParams.h @@ -30,7 +30,7 @@ struct CPVSimParams : public o2::conf::ConfigurableParamHelper { float mPadSizeX = 1.13; ///< overall size of CPV active size float mPadSizeZ = 2.1093; ///< in phi and z directions float mDetR = 0.1; ///< Relative energy fluctuation in track for 100 e- - float mdEdx = 4.0; ///< Average energy loss in CPV; + float mdEdx = 400.0; ///< Average energy loss in CPV (arbitrary units); int mNgamz = 5; ///< Ionization size in Z int mNgamx = 9; ///< Ionization size in Phi float mCPVGasThickness = 1.3; ///< width of ArC02 gas gap @@ -38,26 +38,28 @@ struct CPVSimParams : public o2::conf::ConfigurableParamHelper { float mB = 0.7; ///< Parameter to model CPV response //Parameters used in electronic noise calculation and thresholds (Digitizer) - float mReadoutTime = 5.; ///< Read-out time in ns for default simulaionts - float mDeadTime = 20.; ///< PHOS dead time (includes Read-out time i.e. mDeadTime>=mReadoutTime) - float mReadoutTimePU = 2000.; ///< Read-out time in ns if pileup simulation on in DigitizerSpec - float mDeadTimePU = 30000.; ///< PHOS dead time if pileup simulation on in DigitizerSpec - bool mApplyDigitization = true; ///< if energy digitization should be applied - float mZSthreshold = 0.01; ///< Zero Suppression threshold - float mADCWidth = 0.005; ///< Widht of ADC channel used for energy digitization - float mNoise = 0.01; ///< charge noise in one pad - float mCoeffToNanoSecond = 1.e+9; ///< Conversion for time units - float mSortingDelta = 0.1; ///< used in sorting clusters inverse sorting band in cm + float mReadoutTime = 5.; ///< Read-out time in ns for default simulaionts + float mDeadTime = 20.; ///< PHOS dead time (includes Read-out time i.e. mDeadTime>=mReadoutTime) + float mReadoutTimePU = 2000.; ///< Read-out time in ns if pileup simulation on in DigitizerSpec + float mDeadTimePU = 30000.; ///< PHOS dead time if pileup simulation on in DigitizerSpec + bool mApplyDigitization = true; ///< if energy digitization should be applied + //float mZSthreshold = 0.01; ///< Zero Suppression threshold + float mZSnSigmas = 3.; ///< Zero Suppression threshold + //float mADCWidth = 0.005; ///< Widht of ADC channel used for energy digitization + //float mNoise = 0.01; ///< charge noise in one pad + //float mCoeffToNanoSecond = 1.e+9; ///< Conversion for time units + float mSortingDelta = 0.1; ///< used in sorting clusters inverse sorting band in cm //Parameters used in clusterization - float mDigitMinEnergy = 0.01; ///< Minimal amplitude of a digit to be used in cluster - float mClusteringThreshold = 0.050; ///< Seed digit minimal amplitude - float mUnfogingEAccuracy = 1.e-3; ///< Accuracy of energy calculation in unfoding prosedure (GeV) - float mUnfogingXZAccuracy = 1.e-1; ///< Accuracy of position calculation in unfolding procedure (cm) - float mLocalMaximumCut = 0.030; ///< Threshold to separate local maxima - float mLogWeight = 4.5; ///< weight in cluster center of gravity calculation - int mNMaxIterations = 10; ///< Maximal number of iterations in unfolding procedure - bool mUnfoldClusters = false; ///< Perform cluster unfolding? + //float mDigitMinEnergy = 0.01; ///< Minimal amplitude of a digit to be used in cluster + float mDigitMinEnergy = 5.; ///< Minimal amplitude of a digit to be used in cluster + float mClusteringThreshold = 10.; ///< Seed digit minimal amplitude + float mUnfogingEAccuracy = 1.e-3; ///< Accuracy of energy calculation in unfoding prosedure (GeV) + float mUnfogingXZAccuracy = 1.e-1; ///< Accuracy of position calculation in unfolding procedure (cm) + float mLocalMaximumCut = 0.030; ///< Threshold to separate local maxima + float mLogWeight = 4.5; ///< weight in cluster center of gravity calculation + int mNMaxIterations = 10; ///< Maximal number of iterations in unfolding procedure + bool mUnfoldClusters = false; ///< Perform cluster unfolding? inline float CellWr() const { return 0.5 * mPadSizeX; } ///< Distance between wires (2 wires above 1 pad) diff --git a/Detectors/CPV/calib/include/CPVCalib/Pedestals.h b/Detectors/CPV/calib/include/CPVCalib/Pedestals.h index a23f85536c901..911f03054c2db 100644 --- a/Detectors/CPV/calib/include/CPVCalib/Pedestals.h +++ b/Detectors/CPV/calib/include/CPVCalib/Pedestals.h @@ -22,6 +22,7 @@ #include "TObject.h" class TH1; +class TH1F; namespace o2 { @@ -45,22 +46,26 @@ class Pedestals /// \param cellID Absolute ID of cell /// \return pedestal for the cell short getPedestal(short cellID) const { return short(mPedestals.at(cellID)); } + float getPedSigma(short cellID) const { return mPedSigmas.at(cellID); } /// \brief Set pedestal /// \param cellID Absolute ID of cell /// \param c is the pedestal (expected to be in range <254) - void setPedestal(short cellID, short c) { mPedestals[cellID] = static_cast(c); } + void setPedestal(short cellID, short c) { mPedestals[cellID] = (c > 0 && c < 511) ? c : mPedestals[cellID]; } + void setPedSigma(short cellID, float c) { mPedSigmas[cellID] = (c > 0) ? c : mPedSigmas[cellID]; } /// \brief Set pedestals from 1D histogram with cell absId in x axis /// \param 1D(NCHANNELS) histogram with calibration coefficients /// \return Is successful bool setPedestals(TH1* h); + bool setPedSigmas(TH1F* h); private: - static constexpr short NCHANNELS = 23040; ///< Number of channels in 3 modules starting from 0 - std::array mPedestals; ///< Container for pedestals + static constexpr short NCHANNELS = 23040; ///< Number of channels in 3 modules starting from 0 + std::array mPedestals; ///< Container for pedestals + std::array mPedSigmas; ///< Container for pedestal sigmas - ClassDefNV(Pedestals, 1); + ClassDefNV(Pedestals, 2); }; } // namespace cpv diff --git a/Detectors/CPV/calib/src/CalibParams.cxx b/Detectors/CPV/calib/src/CalibParams.cxx index 1be71c1b260b2..4276a5d62b15f 100644 --- a/Detectors/CPV/calib/src/CalibParams.cxx +++ b/Detectors/CPV/calib/src/CalibParams.cxx @@ -22,7 +22,7 @@ using namespace o2::cpv; CalibParams::CalibParams(short /*dummy*/) { //produce reasonable objest for test purposes - mGainCalib.fill(0.01); + mGainCalib.fill(1.); } bool CalibParams::setGain(TH2* h, short module) diff --git a/Detectors/CPV/calib/src/Pedestals.cxx b/Detectors/CPV/calib/src/Pedestals.cxx index eb04ce5ff594e..3f4f6ee39e811 100644 --- a/Detectors/CPV/calib/src/Pedestals.cxx +++ b/Detectors/CPV/calib/src/Pedestals.cxx @@ -11,15 +11,17 @@ #include "CPVCalib/Pedestals.h" #include "FairLogger.h" #include +#include using namespace o2::cpv; Pedestals::Pedestals(int /*dummy*/) { //produce reasonable objest for test purposes - mPedestals.fill(40); + mPedestals.fill(200); //typical pedestal value + mPedSigmas.fill(1.5); //typical pedestal sigma } - +//______________________________________________________________________________ bool Pedestals::setPedestals(TH1* h) { if (!h) { @@ -33,11 +35,37 @@ bool Pedestals::setPedestals(TH1* h) } for (short i = 1; i <= NCHANNELS; i++) { - if (h->GetBinContent(i) > 255) { - LOG(ERROR) << "pedestal value too large:" << h->GetBinContent(i) << "can not be stored in char"; + if (h->GetBinContent(i) > 511) { + LOG(ERROR) << "setPedestals : pedestal value = " << h->GetBinContent(i) + << " in channel " << i + << " exceeds max possible value 511 (limited by CPV electronics)"; + continue; + } + mPedestals[i] = short(h->GetBinContent(i)); + } + return true; +} +//_______________________________________________________________________________ +bool Pedestals::setPedSigmas(TH1F* h) +{ + if (!h) { + LOG(ERROR) << "no input histogam"; + return false; + } + + if (h->GetNbinsX() != NCHANNELS) { + LOG(ERROR) << "Wrong dimentions of input histogram:" << h->GetNbinsX() << " instead of " << NCHANNELS; + return false; + } + + for (short i = 1; i <= NCHANNELS; i++) { + if (h->GetBinContent(i) < 0) { + LOG(ERROR) << "pedestal sigma = " << h->GetBinContent(i) + << " in channel " << i + << " cannot be less than 0"; continue; } - mPedestals[i] = char(h->GetBinContent(i)); + mPedSigmas[i] = float(h->GetBinContent(i)); } return true; } diff --git a/Detectors/CPV/simulation/include/CPVSimulation/Digitizer.h b/Detectors/CPV/simulation/include/CPVSimulation/Digitizer.h index 10dfc44b893b3..adb199b353a27 100644 --- a/Detectors/CPV/simulation/include/CPVSimulation/Digitizer.h +++ b/Detectors/CPV/simulation/include/CPVSimulation/Digitizer.h @@ -14,6 +14,8 @@ #include "DataFormatsCPV/Digit.h" #include "CPVBase/Geometry.h" #include "CPVCalib/CalibParams.h" +#include "CPVCalib/Pedestals.h" +#include "CPVCalib/BadChannelMap.h" #include "CPVBase/Hit.h" #include "SimulationDataFormat/MCCompLabel.h" #include "SimulationDataFormat/MCTruthContainer.h" @@ -39,15 +41,16 @@ class Digitizer : public TObject int source, int entry, double dt); protected: - float uncalibrate(float e, int absId); - float simulateNoise(); + float simulatePedestalNoise(int absId); private: static constexpr short NCHANNELS = 23040; //128*60*3: toatl number of CPV channels std::unique_ptr mCalibParams; /// Calibration coefficients - std::array mArrayD; - - ClassDefOverride(Digitizer, 2); + std::unique_ptr mPedestals; /// Pedestals + std::unique_ptr mBadMap; /// Bad channel map + std::array mArrayD; ///array of digits (for inner use) + std::array mDigitThresholds; + ClassDefOverride(Digitizer, 3); }; } // namespace cpv } // namespace o2 diff --git a/Detectors/CPV/simulation/include/CPVSimulation/RawWriter.h b/Detectors/CPV/simulation/include/CPVSimulation/RawWriter.h index 0083572838c84..ec407f91bf0dd 100644 --- a/Detectors/CPV/simulation/include/CPVSimulation/RawWriter.h +++ b/Detectors/CPV/simulation/include/CPVSimulation/RawWriter.h @@ -26,6 +26,7 @@ #include "DataFormatsCPV/Digit.h" #include "DataFormatsCPV/TriggerRecord.h" #include "CPVCalib/CalibParams.h" +#include "CPVCalib/Pedestals.h" namespace o2 { @@ -78,6 +79,7 @@ class RawWriter FileFor_t mFileFor = FileFor_t::kFullDet; ///< Granularity of the output files std::string mOutputLocation = "./"; ///< Rawfile name std::unique_ptr mCalibParams; ///< CPV calibration + std::unique_ptr mPedestals; ///< CPV pedestals std::vector mPayload; ///< Payload to be written gsl::span mDigits; ///< Digits input vector - must be in digitized format including the time response std::unique_ptr mRawWriter; ///< Raw writer diff --git a/Detectors/CPV/simulation/src/Detector.cxx b/Detectors/CPV/simulation/src/Detector.cxx index 0bc36e4b0e9ac..98ce6f20f3f38 100644 --- a/Detectors/CPV/simulation/src/Detector.cxx +++ b/Detectors/CPV/simulation/src/Detector.cxx @@ -261,7 +261,6 @@ Bool_t Detector::ProcessHits(FairVolume* v) // Now calculate pad response double qpad = padResponseFunction(qhit, zg, xg); - qpad += cpvparam.mNoise * rnor2; if (qpad < 0) { continue; } diff --git a/Detectors/CPV/simulation/src/Digitizer.cxx b/Detectors/CPV/simulation/src/Digitizer.cxx index 2d0bc19d1227a..a17a9ddf62391 100644 --- a/Detectors/CPV/simulation/src/Digitizer.cxx +++ b/Detectors/CPV/simulation/src/Digitizer.cxx @@ -31,7 +31,8 @@ void Digitizer::init() mCalibParams.reset(new CalibParams(1)); // test default calibration LOG(INFO) << "[CPVDigitizer] No reading calibration from ccdb requested, set default"; } else { - LOG(INFO) << "[CPVDigitizer] can not gey calibration object from ccdb yet"; + LOG(INFO) << "[CPVDigitizer] can not get calibration object from ccdb yet. Using default"; + mCalibParams.reset(new CalibParams(1)); // test default calibration // o2::ccdb::CcdbApi ccdb; // std::map metadata; // do we want to store any meta data? // ccdb.init("http://ccdb-test.cern.ch:8080"); // or http://localhost:8080 for a local installation @@ -41,6 +42,45 @@ void Digitizer::init() // } } } + if (!mPedestals) { + if (o2::cpv::CPVSimParams::Instance().mCCDBPath.compare("localtest") == 0) { + mPedestals.reset(new Pedestals(1)); // test default calibration + LOG(INFO) << "[CPVDigitizer] No reading calibration from ccdb requested, set default"; + } else { + LOG(INFO) << "[CPVDigitizer] can not get pedestal object from ccdb yet. Using default"; + mPedestals.reset(new Pedestals(1)); // test default calibration + // o2::ccdb::CcdbApi ccdb; + // std::map metadata; // do we want to store any meta data? + // ccdb.init("http://ccdb-test.cern.ch:8080"); // or http://localhost:8080 for a local installation + // mPedestals = ccdb.retrieveFromTFileAny("CPV/Calib", metadata, mEventTime); + // if (!mPedestals) { + // LOG(FATAL) << "[CPVDigitizer] can not get calibration object from ccdb"; + // } + } + } + if (!mBadMap) { + if (o2::cpv::CPVSimParams::Instance().mCCDBPath.compare("localtest") == 0) { + mBadMap.reset(new BadChannelMap(1)); // test default calibration + LOG(INFO) << "[CPVDigitizer] No reading calibration from ccdb requested, set default"; + } else { + LOG(INFO) << "[CPVDigitizer] can not get bad channel map object from ccdb yet. Using default"; + mBadMap.reset(new BadChannelMap(1)); // test default calibration + // o2::ccdb::CcdbApi ccdb; + // std::map metadata; // do we want to store any meta data? + // ccdb.init("http://ccdb-test.cern.ch:8080"); // or http://localhost:8080 for a local installation + // mBadMap = ccdb.retrieveFromTFileAny("CPV/Calib", metadata, mEventTime); + // if (!mBadMap) { + // LOG(FATAL) << "[CPVDigitizer] can not get calibration object from ccdb"; + // } + } + } + + //signal thresolds for digits + //note that digits are calibrated objects + for (int i = 0; i < NCHANNELS; i++) { + mDigitThresholds[i] = o2::cpv::CPVSimParams::Instance().mZSnSigmas * + mPedestals->getPedSigma(i) * mCalibParams->getGain(i); + } } //_______________________________________________________________________ @@ -60,14 +100,11 @@ void Digitizer::processHits(const std::vector* hits, const std::vector o2::cpv::CPVSimParams::Instance().mZSthreshold) { - mArrayD[i].setAmplitude(energy); - mArrayD[i].setAbsId(i); - } + float amplitude = simulatePedestalNoise(i); + mArrayD[i].setAmplitude(amplitude); + mArrayD[i].setAbsId(i); } } else { //if digits exist, no noise should be added for (auto& dBg : digitsBg) { //digits are sorted and unique @@ -79,12 +116,12 @@ void Digitizer::processHits(const std::vector* hits, const std::vector 0) { - mArrayD[i].setAmplitude(mArrayD[i].getAmplitude() + uncalibrate(h.GetEnergyLoss(), i)); + mArrayD[i].setAmplitude(mArrayD[i].getAmplitude() + h.GetEnergyLoss()); } else { - mArrayD[i].setAmplitude(uncalibrate(h.GetEnergyLoss(), i)); + mArrayD[i].setAmplitude(h.GetEnergyLoss()); mArrayD[i].setAbsId(i); } - if (mArrayD[i].getAmplitude() > o2::cpv::CPVSimParams::Instance().mZSthreshold) { + if (mArrayD[i].getAmplitude() > mDigitThresholds[i]) { int labelIndex = mArrayD[i].getLabel(); if (labelIndex == -1) { //no digit or noisy labelIndex = labels.getIndexedSize(); @@ -109,23 +146,22 @@ void Digitizer::processHits(const std::vector* hits, const std::vector o2::cpv::CPVSimParams::Instance().mZSthreshold) { + if (!mBadMap->isChannelGood(i)) { + continue; //bad channel -> skip this digit + } + if (mArrayD[i].getAmplitude() > mDigitThresholds[i]) { digitsOut.push_back(mArrayD[i]); } } } -float Digitizer::simulateNoise() { return gRandom->Gaus(0., o2::cpv::CPVSimParams::Instance().mNoise); } - -//_______________________________________________________________________ -float Digitizer::uncalibrate(const float e, const int absId) +float Digitizer::simulatePedestalNoise(int absId) { - // Decalibrate CPV digit, i.e. transform from amplitude to ADC counts a factor read from CDB - float calib = mCalibParams->getGain(absId); - if (calib > 0) { - return e / calib; - } else { - return 0; // TODO apply de-calibration from OCDB + //this function is to simulate pedestal and its noise (ADC counts) + if (absId < 0 || absId >= NCHANNELS) { + return 0.; } + return gRandom->Gaus(0, mPedestals->getPedSigma(absId) * mCalibParams->getGain(absId)); } diff --git a/Detectors/CPV/simulation/src/RawWriter.cxx b/Detectors/CPV/simulation/src/RawWriter.cxx index 533e48d2a6079..ce77135949549 100644 --- a/Detectors/CPV/simulation/src/RawWriter.cxx +++ b/Detectors/CPV/simulation/src/RawWriter.cxx @@ -60,6 +60,28 @@ void RawWriter::digitsToRaw(gsl::span digitsbranch, gsl::span(1); // test default calibration + LOG(INFO) << "[RawWriter] No reading calibration from ccdb requested, set default"; + } else { + LOG(INFO) << "[RawWriter] getting calibration object from ccdb"; + o2::ccdb::CcdbApi ccdb; + std::map metadata; + ccdb.init("http://ccdb-test.cern.ch:8080"); // or http://localhost:8080 for a local installation + auto tr = triggerbranch.begin(); + double eventTime = -1; + // if(tr!=triggerbranch.end()){ + // eventTime = (*tr).getBCData().getTimeNS() ; + // } + //add copy constructor if necessary + // mPedestals = std::make_unique(ccdb.retrieveFromTFileAny("CPV/Calib", metadata, eventTime)); + if (!mPedestals) { + LOG(FATAL) << "[RawWriter] can not get calibration object from ccdb"; + } + } + } + for (auto trg : triggerbranch) { processTrigger(digitsbranch, trg); } @@ -84,7 +106,7 @@ bool RawWriter::processTrigger(const gsl::span digitsbranch, con o2::cpv::Geometry::absIdToHWaddress(absId, ccId, dil, gas, pad); //Convert Amp to ADC counts - short charge = dig.getAmplitude() / mCalibParams->getGain(absId); + short charge = dig.getAmplitude() / mCalibParams->getGain(absId) + mPedestals->getPedestal(absId); if (charge > 4095) { charge = 4095; } diff --git a/Detectors/CPV/testsimulation/CMakeLists.txt b/Detectors/CPV/testsimulation/CMakeLists.txt index c79c68e23f613..8a8dd8f9da37c 100644 --- a/Detectors/CPV/testsimulation/CMakeLists.txt +++ b/Detectors/CPV/testsimulation/CMakeLists.txt @@ -21,3 +21,8 @@ o2_add_test_root_macro(plot_hit_cpv.C o2_add_test_root_macro(plot_dig_cpv.C PUBLIC_LINK_LIBRARIES FairRoot::Base O2::CPVSimulation LABELS cpv) + +o2_add_test_root_macro(plot_clu_cpv.C + PUBLIC_LINK_LIBRARIES FairRoot::Base O2::CPVSimulation + LABELS cpv) + diff --git a/Detectors/CPV/testsimulation/plot_clu_cpv.C b/Detectors/CPV/testsimulation/plot_clu_cpv.C new file mode 100644 index 0000000000000..a3d899640c1bc --- /dev/null +++ b/Detectors/CPV/testsimulation/plot_clu_cpv.C @@ -0,0 +1,118 @@ +#if !defined(__CLING__) || defined(__ROOTCLING__) +#include +#include + +#include "TROOT.h" +#include +#include "TCanvas.h" +#include "TH2.h" +//#include "DataFormatsParameters/GRPObject.h" +#include "FairFileSource.h" +#include "FairLogger.h" +#include "FairRunAna.h" +//#include "FairRuntimeDb.h" +#include "FairParRootFileIo.h" +#include "FairSystemInfo.h" +#include "SimulationDataFormat/MCCompLabel.h" + +#include "DataFormatsCPV/Cluster.h" +#include "CPVBase/Geometry.h" +#endif + +void plot_clu_cpv(std::string inputfile = "cpvclusters.root", int ifirst = 0, int ilast = -1) +{ + // macros to plot CPV clusters + + // Clusters + TFile* file0 = TFile::Open(inputfile.data()); + std::cout << " Open clusters file " << inputfile << std::endl; + TTree* cluTree = (TTree*)gFile->Get("o2sim"); + std::vector* mClustersArray = nullptr; + cluTree->SetBranchAddress("CPVCluster", &mClustersArray); + + if (!mClustersArray) { + std::cout << "CPV clusters not found in the file. Exiting ..." << std::endl; + return; + } + + TH1F* hClusterTotEnergy[5]; + TH1F* hClusterMaxEnergy[5]; + TH1F* hClusterSize[5]; + TH1F* hClusterSizeX[5]; + TH1F* hClusterSizeZ[5]; + + TH2D* vMod[5][1000] = {0}; + int primLabels[5][1000]; + for (int mod = 2; mod < 5; mod++) { + hClusterTotEnergy[mod] = new TH1F(Form("hClusterTotEnergy%d", mod), + Form("Cluster Total Energy mod %d", mod), 10000, 0, 10000); + hClusterMaxEnergy[mod] = new TH1F(Form("hClusterMaxEnergy%d", mod), + Form("Cluster Max Energy mod %d", mod), 10000, 0, 10000); + hClusterSize[mod] = new TH1F(Form("hClusterSize%d", mod), + Form("Cluster Size mod %d", mod), 100, 0, 100); + hClusterSizeX[mod] = new TH1F(Form("hClusterSizeX%d", mod), + Form("Cluster SizeX mod %d", mod), 100, 0, 100); + hClusterSizeZ[mod] = new TH1F(Form("hClusterSizeZ%d", mod), + Form("Cluster SizeZ mod %d", mod), 100, 0, 100); + + for (int j = 0; j < 100; j++) + primLabels[mod][j] = -1; + } + + int nEntries = cluTree->GetEntriesFast(); + if (ilast < 0) + ilast = nEntries; + if (ilast > nEntries) + ilast = nEntries; + + for (int ievent = ifirst; ievent < ilast; ievent++) { + cluTree->GetEvent(ievent); + + std::vector::const_iterator it; + std::cout << "I start cluster cycling (record #" << ievent << " in o2sim tree)" << std::endl; + + for (it = mClustersArray->begin(); it != mClustersArray->end(); it++) { + float en = (*it).getEnergy(); + float posX, posZ; + (*it).getLocalPosition(posX, posZ); + int cluSize = (*it).getMultiplicity(); + int mod = (*it).getModule(); + if (!vMod[mod][0]) { + gROOT->cd(); + vMod[mod][0] = + new TH2D(Form("hMod%d_prim%d", mod, 0), Form("hMod%d_prim%d", mod, 0), + 100, -100., 100., 100, -100., 100.); + } + vMod[mod][0]->Fill(posX, posZ, en); + hClusterTotEnergy[mod]->Fill(en); + hClusterSize[mod]->Fill(cluSize); + } + + std::cout << "I finish cycling clusters" << std::endl; + } + TCanvas* c[5]; + TH2D* box = new TH2D("box", "CPV module", 100, -100., 100., 100, -100., 100.); + TCanvas* cTotEn = new TCanvas(); + cTotEn->Divide(3, 1); + TCanvas* cSize = new TCanvas(); + cSize->Divide(3, 1); + + for (int mod = 2; mod < 5; mod++) { + c[mod] = + new TCanvas(Form("ClusterInMod%d", mod), Form("CPV clusters in module %d", mod), 10 * mod, 0, 600 + 10 * mod, 400); + box->Draw(); + int j = 0; + while (vMod[mod][j]) { + vMod[mod][j]->SetLineColor(j + 1); + if (j == 0) + vMod[mod][j]->Draw("box"); + else + vMod[mod][j]->Draw("boxsame"); + j++; + } + cTotEn->cd(mod - 1); + hClusterTotEnergy[mod]->Draw(); + cSize->cd(mod - 1); + hClusterSize[mod]->Draw(); + } +} diff --git a/Detectors/CPV/testsimulation/plot_dig_cpv.C b/Detectors/CPV/testsimulation/plot_dig_cpv.C index 23e4b98963db0..e66b4ef438221 100644 --- a/Detectors/CPV/testsimulation/plot_dig_cpv.C +++ b/Detectors/CPV/testsimulation/plot_dig_cpv.C @@ -6,6 +6,7 @@ #include #include "TCanvas.h" #include "TH2.h" +#include "TH1.h" //#include "DataFormatsParameters/GRPObject.h" #include "FairFileSource.h" #include "FairLogger.h" @@ -21,11 +22,11 @@ void plot_dig_cpv(int ievent = 0, std::string inputfile = "o2dig.root") { - // macros to plot CPV hits + // macros to plot CPV digits - // Hits - TFile* file0 = TFile::Open("o2dig.root"); - std::cout << " Open hits file " << inputfile << std::endl; + // Digits + TFile* file0 = TFile::Open(inputfile.data()); + std::cout << " Open digits file " << inputfile << std::endl; TTree* hitTree = (TTree*)gFile->Get("o2sim"); std::vector* mDigitsArray = nullptr; hitTree->SetBranchAddress("CPVDigit", &mDigitsArray); @@ -36,47 +37,58 @@ void plot_dig_cpv(int ievent = 0, std::string inputfile = "o2dig.root") } hitTree->GetEvent(ievent); - TH2D* vMod[5][100] = {0}; - int primLabels[5][100]; - for (int mod = 1; mod < 5; mod++) + TH1F* hDigitAmplitude[5]; + TH2D* vMod[5][1000] = {0}; + int primLabels[5][1000]; + for (int mod = 1; mod < 5; mod++) { + hDigitAmplitude[mod] = new TH1F(Form("hDigitAmplitude_mod%d", mod), + Form("Digit amplitudes in module %d", mod), + 4096, 0., 4096.); for (int j = 0; j < 100; j++) primLabels[mod][j] = -1; + } std::vector::const_iterator it; short relId[3]; + std::cout << "I start digit cycling" << std::endl; for (it = mDigitsArray->begin(); it != mDigitsArray->end(); it++) { short absId = (*it).getAbsId(); float en = (*it).getAmplitude(); int lab = (*it).getLabel(); //TODO + //std::cout << "label = " << lab << std::endl; o2::cpv::Geometry::absToRelNumbering(absId, relId); + hDigitAmplitude[relId[0]]->Fill(en); // check, if this label already exist int j = 0; bool found = false; - while (primLabels[relId[0]][j] >= -2) { - if (primLabels[relId[0]][j] == lab) { - found = true; - break; - } else { - j++; - } - } + //no labels for the time being + // while (primLabels[relId[0]][j] >= -2) { + // if (primLabels[relId[0]][j] == lab) { + // found = true; + // break; + // } else { + // j++; + // } + // } if (!found) { primLabels[relId[0]][j] = lab; } if (!vMod[relId[0]][j]) { gROOT->cd(); vMod[relId[0]][j] = - new TH2D(Form("hMod%d_prim%d", relId[0], j), Form("hMod%d_prim%d", relId[0], j), 60, 0., 60., 128, 0., 128.); + new TH2D(Form("hMod%d_prim%d", relId[0], j), Form("hMod%d_prim%d", relId[0], j), 128, 0., 128., 60, 0., 60.); } vMod[relId[0]][j]->Fill(relId[1] - 0.5, relId[2] - 0.5, en); } - TCanvas* c[5]; - TH2D* box = new TH2D("box", "CPV module", 60, 0., 60., 128, 0., 128.); - for (int mod = 1; mod < 5; mod++) { + std::cout << "I finish cycling digits" << std::endl; + + TCanvas *c[5], *c_ampl[5]; + TH2D* box = new TH2D("box", "CPV module", 128, 0., 128., 60, 0., 60.); + for (int mod = 2; mod < 5; mod++) { c[mod] = - new TCanvas(Form("DigitInMod%d", mod), Form("CPV hits in module %d", mod), 10 * mod, 0, 600 + 10 * mod, 400); + new TCanvas(Form("DigitInMod%d", mod), Form("CPV digits in module %d", mod), 10 * mod, 0, 600 + 10 * mod, 400); box->Draw(); int j = 0; while (vMod[mod][j]) { @@ -87,5 +99,8 @@ void plot_dig_cpv(int ievent = 0, std::string inputfile = "o2dig.root") vMod[mod][j]->Draw("boxsame"); j++; } + c_ampl[mod] = new TCanvas(Form("DigitAmplitudes_%d", mod), Form("DigitAmplitudes_%d", mod), + 10 * mod + 800, 0, 600 + 10 * mod + 200, 400); + hDigitAmplitude[mod]->Draw(); } } diff --git a/Detectors/CPV/testsimulation/plot_hit_cpv.C b/Detectors/CPV/testsimulation/plot_hit_cpv.C index cb883f2fa5f91..5be311e7eb953 100644 --- a/Detectors/CPV/testsimulation/plot_hit_cpv.C +++ b/Detectors/CPV/testsimulation/plot_hit_cpv.C @@ -72,7 +72,7 @@ void plot_hit_cpv(int ievent = 0, std::string inputprefix = "o2sim") if (!vMod[relId[0]][j]) { gROOT->cd(); vMod[relId[0]][j] = - new TH2D(Form("hMod%d_prim%d", relId[0], j), Form("hMod%d_prim%d", relId[0], j), 60, 0., 60., 128, 0., 128.); + new TH2D(Form("hMod%d_prim%d", relId[0], j), Form("hMod%d_prim%d", relId[0], j), 128, 0., 128., 60, 0., 60.); } vMod[relId[0]][j]->Fill(relId[1] - 0.5, relId[2] - 0.5, en); } diff --git a/Detectors/CPV/workflow/include/CPVWorkflow/RawToDigitConverterSpec.h b/Detectors/CPV/workflow/include/CPVWorkflow/RawToDigitConverterSpec.h index 78764982c9ebe..d44ce0aa8bc6b 100644 --- a/Detectors/CPV/workflow/include/CPVWorkflow/RawToDigitConverterSpec.h +++ b/Detectors/CPV/workflow/include/CPVWorkflow/RawToDigitConverterSpec.h @@ -16,6 +16,7 @@ #include "DataFormatsCPV/TriggerRecord.h" #include "CPVCalib/CalibParams.h" #include "CPVCalib/BadChannelMap.h" +#include "CPVCalib/Pedestals.h" #include "CPVReconstruction/RawDecoder.h" namespace o2 @@ -62,7 +63,9 @@ class RawToDigitConverterSpec : public framework::Task private: int mDDL = 15; + bool mIsPedestalData; ///< No subtract pedestals if true std::unique_ptr mCalibParams; ///< CPV calibration + std::unique_ptr mPedestals; ///< CPV pedestals std::unique_ptr mBadMap; ///< BadMap std::vector mOutputDigits; ///< Container with output cells std::vector mOutputTriggerRecords; ///< Container with output cells diff --git a/Detectors/CPV/workflow/src/RawToDigitConverterSpec.cxx b/Detectors/CPV/workflow/src/RawToDigitConverterSpec.cxx index 3c18ba36b3a83..365421ed4c066 100644 --- a/Detectors/CPV/workflow/src/RawToDigitConverterSpec.cxx +++ b/Detectors/CPV/workflow/src/RawToDigitConverterSpec.cxx @@ -29,6 +29,15 @@ void RawToDigitConverterSpec::init(framework::InitContext& ctx) { mDDL = ctx.options().get("DDL"); LOG(DEBUG) << "Initialize converter "; + + //Read command-line options + //Pedestal flag (on/off) + std::string optPedestal(""); + if (ctx.options().isSet("pedestal")) { + optPedestal = ctx.options().get("pedestal"); + } + LOG(INFO) << "Pedestal data: " << optPedestal; + mIsPedestalData = optPedestal == "on" ? true : false; } void RawToDigitConverterSpec::run(framework::ProcessingContext& ctx) @@ -81,6 +90,28 @@ void RawToDigitConverterSpec::run(framework::ProcessingContext& ctx) } } + if (!mPedestals && !mIsPedestalData) { + if (o2::cpv::CPVSimParams::Instance().mCCDBPath.compare("localtest") == 0) { + mPedestals = std::make_unique(1); // test default calibration + LOG(INFO) << "No reading calibration from ccdb requested, set default"; + } else { + LOG(INFO) << "Getting calibration object from ccdb"; + //TODO: configuring ccdb address from config file, readign proper calibration/BadMap and updateing if necessary + o2::ccdb::CcdbApi ccdb; + std::map metadata; + ccdb.init("http://ccdb-test.cern.ch:8080"); // or http://localhost:8080 for a local installation + // auto tr = triggerbranch.begin(); + // double eventTime = -1; + // if(tr!=triggerbranch.end()){ + // eventTime = (*tr).getBCData().getTimeNS() ; + // } + // mPedestals = ccdb.retrieveFromTFileAny("CPV/Calib", metadata, eventTime); + // if (!mPedestals) { + // LOG(FATAL) << "Can not get calibration object from ccdb"; + // } + } + } + for (const auto& rawData : framework::InputRecordWalker(ctx.inputs())) { // enum RawErrorType_t { @@ -155,12 +186,18 @@ void RawToDigitConverterSpec::run(framework::ProcessingContext& ctx) for (uint32_t adch : decoder.getDigits()) { AddressCharge ac = {adch}; unsigned short absId = ac.Address; - //test bad map - if (mBadMap->isChannelGood(absId)) { - if (ac.Charge > o2::cpv::CPVSimParams::Instance().mZSthreshold) { - float amp = mCalibParams->getGain(absId) * ac.Charge; - currentDigitContainer->emplace_back(absId, amp, -1); + //if we deal with non-pedestal data? + if (!mIsPedestalData) { //not a pedestal data + //test bad map + if (mBadMap->isChannelGood(absId)) { + //we need to subtract pedestal from amplidute and calibrate it + float amp = mCalibParams->getGain(absId) * (ac.Charge - mPedestals->getPedestal(absId)); + if (amp > 0) { + currentDigitContainer->emplace_back(absId, amp, -1); + } } + } else { //pedestal data, no calibration needed. + currentDigitContainer->emplace_back(absId, (float)ac.Charge, -1); } } //Check and send list of hwErrors From 457ac9945a2b660262e93d5ca5c1d23e3cd87645 Mon Sep 17 00:00:00 2001 From: Matteo Concas Date: Sat, 10 Apr 2021 14:21:57 +0200 Subject: [PATCH 091/770] Fix for index shift in detector list --- .../Common/include/DetectorsCommonDataFormats/SimTraits.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/SimTraits.h b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/SimTraits.h index d2a0e80ddac45..0bf0e5b87e158 100644 --- a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/SimTraits.h +++ b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/SimTraits.h @@ -86,7 +86,8 @@ class SimTraits /*FT0*/ VS{ "FT0Hit" }, /*FV0*/ VS{ "FV0Hit" }, /*FDD*/ VS{ "FDDHit" }, - /*ACO*/ VS{ "ACOHit" } + /*ACO*/ VS{ "ACOHit" }, + /*CTP*/ VS{ "CTPHit" } #ifdef ENABLE_UPGRADES , /*IT3*/ VS{ "IT3Hit" }, From af7dd4d13a49a5d105e25dba87d522649c9ff98f Mon Sep 17 00:00:00 2001 From: shahoian Date: Sun, 11 Apr 2021 03:52:51 +0200 Subject: [PATCH 092/770] ConfigurableParam::updateFromFile may skip already touched params --- .../Utils/include/CommonUtils/ConfigurableParam.h | 2 +- Common/Utils/src/ConfigurableParam.cxx | 14 ++++++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/Common/Utils/include/CommonUtils/ConfigurableParam.h b/Common/Utils/include/CommonUtils/ConfigurableParam.h index 0c3cbe0fd6aed..fe8def62e1e2f 100644 --- a/Common/Utils/include/CommonUtils/ConfigurableParam.h +++ b/Common/Utils/include/CommonUtils/ConfigurableParam.h @@ -242,7 +242,7 @@ class ConfigurableParam // provide a path to a configuration file with ConfigurableParam key/values // If nonempty comma-separated paramsList is provided, only those params will // be updated, absence of data for any of requested params will lead to fatal - static void updateFromFile(std::string const&, std::string const& paramsList = ""); + static void updateFromFile(std::string const&, std::string const& paramsList = "", bool unchangedOnly = false); protected: // constructor is doing nothing else but diff --git a/Common/Utils/src/ConfigurableParam.cxx b/Common/Utils/src/ConfigurableParam.cxx index b6e50481b0ad5..f89838758a710 100644 --- a/Common/Utils/src/ConfigurableParam.cxx +++ b/Common/Utils/src/ConfigurableParam.cxx @@ -395,7 +395,9 @@ void ConfigurableParam::printAllRegisteredParamNames() // It can be in JSON or INI format. // If nonempty comma-separated paramsList is provided, only those params will // be updated, absence of data for any of requested params will lead to fatal -void ConfigurableParam::updateFromFile(std::string const& configFile, std::string const& paramsList) +// If unchangedOnly is true, then only those parameters whose provenance is kCODE will be updated +// (to allow prefernce of run-time settings) +void ConfigurableParam::updateFromFile(std::string const& configFile, std::string const& paramsList, bool unchangedOnly) { if (!sIsFullyInitialized) { initialize(); @@ -413,7 +415,9 @@ void ConfigurableParam::updateFromFile(std::string const& configFile, std::strin auto request = splitString(paramsList, ',', true); std::unordered_map requestMap; for (const auto& par : request) { - requestMap[par] = 0; + if (!par.empty()) { + requestMap[par] = 0; + } } try { @@ -430,8 +434,10 @@ void ConfigurableParam::updateFromFile(std::string const& configFile, std::strin auto name = subKey.first; auto value = subKey.second.get_value(); std::string key = mainKey + "." + name; - std::pair pair = std::make_pair(key, trimSpace(value)); - keyValPairs.push_back(pair); + if (!unchangedOnly || getProvenance(key) == kCODE) { + std::pair pair = std::make_pair(key, trimSpace(value)); + keyValPairs.push_back(pair); + } } } } catch (std::exception const& error) { From daacff568958ab4ab78fbef2cf0608675464bc2e Mon Sep 17 00:00:00 2001 From: shahoian Date: Sun, 11 Apr 2021 03:54:41 +0200 Subject: [PATCH 093/770] Always set ConfigurableParam provenance, add provenance getter --- .../include/CommonUtils/ConfigurableParam.h | 19 ++++-- .../CommonUtils/ConfigurableParamHelper.h | 7 ++ Common/Utils/src/ConfigurableParam.cxx | 66 ++++++++++++------- 3 files changed, 63 insertions(+), 29 deletions(-) diff --git a/Common/Utils/include/CommonUtils/ConfigurableParam.h b/Common/Utils/include/CommonUtils/ConfigurableParam.h index fe8def62e1e2f..fd3e5dc4bad89 100644 --- a/Common/Utils/include/CommonUtils/ConfigurableParam.h +++ b/Common/Utils/include/CommonUtils/ConfigurableParam.h @@ -143,6 +143,12 @@ class ConfigurableParam /* can add more modes here */ }; + enum class EParamUpdateStatus { + Changed, // param was successfully changed + Unchanged, // param was not changed: new value is the same as previous + Failed // failed to update param + }; + static std::string toString(EParamProvenance p) { static std::array names = {"CODE", "CCDB", "RT"}; @@ -155,6 +161,11 @@ class ConfigurableParam // print the current keys and values to screen (optionally with provenance information) virtual void printKeyValues(bool showprov = true) const = 0; + // return the provenance of the member key + virtual EParamProvenance getMemberProvenance(const std::string& key) const = 0; + + static EParamProvenance getProvenance(const std::string& key); + static void printAllRegisteredParamNames(); static void printAllKeyValuePairs(); @@ -189,7 +200,7 @@ class ConfigurableParam if (sPtree->get_optional(key).is_initialized()) { sPtree->put(key, x); auto changed = updateThroughStorageMap(mainkey, subkey, typeid(T), (void*)&x); - if (changed) { + if (changed != EParamUpdateStatus::Failed) { sValueProvenanceMap->find(key)->second = kRT; // set to runtime } } @@ -210,7 +221,7 @@ class ConfigurableParam if (sPtree->get_optional(key).is_initialized()) { sPtree->put(key, valuestring); auto changed = updateThroughStorageMapWithConversion(key, valuestring); - if (changed) { + if (changed != EParamUpdateStatus::Failed) { sValueProvenanceMap->find(key)->second = kRT; // set to runtime } } @@ -252,8 +263,8 @@ class ConfigurableParam friend std::ostream& operator<<(std::ostream& out, const ConfigurableParam& me); static void initPropertyTree(); - static bool updateThroughStorageMap(std::string, std::string, std::type_info const&, void*); - static bool updateThroughStorageMapWithConversion(std::string const&, std::string const&); + static EParamUpdateStatus updateThroughStorageMap(std::string, std::string, std::type_info const&, void*); + static EParamUpdateStatus updateThroughStorageMapWithConversion(std::string const&, std::string const&); virtual ~ConfigurableParam() = default; diff --git a/Common/Utils/include/CommonUtils/ConfigurableParamHelper.h b/Common/Utils/include/CommonUtils/ConfigurableParamHelper.h index 0a3ca1303af72..fd8d7dea04ea3 100644 --- a/Common/Utils/include/CommonUtils/ConfigurableParamHelper.h +++ b/Common/Utils/include/CommonUtils/ConfigurableParamHelper.h @@ -82,6 +82,13 @@ class ConfigurableParamHelper : virtual public ConfigurableParam return P::sKey; } + // ---------------------------------------------------------------- + // get the provenace of the member with given key + EParamProvenance getMemberProvenance(const std::string& key) const final + { + return getProvenance(getName() + '.' + key); + } + // ---------------------------------------------------------------- // one of the key methods, using introspection to print itself diff --git a/Common/Utils/src/ConfigurableParam.cxx b/Common/Utils/src/ConfigurableParam.cxx index f89838758a710..8b87114f59ef4 100644 --- a/Common/Utils/src/ConfigurableParam.cxx +++ b/Common/Utils/src/ConfigurableParam.cxx @@ -313,6 +313,20 @@ void ConfigurableParam::printAllKeyValuePairs() // ------------------------------------------------------------------ +ConfigurableParam::EParamProvenance ConfigurableParam::getProvenance(const std::string& key) +{ + if (!sIsFullyInitialized) { + initialize(); + } + auto iter = sValueProvenanceMap->find(key); + if (iter == sValueProvenanceMap->end()) { + throw std::runtime_error(fmt::format("provenace of unknown {:s} parameter is requested", key)); + } + return iter->second; +} + +// ------------------------------------------------------------------ + // evidently this could be a local file or an OCDB server // ... we need to generalize this ... but ok for demonstration purposes void ConfigurableParam::toCCDB(std::string filename) @@ -612,24 +626,24 @@ bool isMemblockDifferent(void const* block1, void const* block2) // copies data from one place to other and returns // true of data was actually changed template -bool Copy(void const* addr, void* targetaddr) +ConfigurableParam::EParamUpdateStatus Copy(void const* addr, void* targetaddr) { if (isMemblockDifferent(addr, targetaddr)) { std::memcpy(targetaddr, addr, sizeof(T)); - return true; + return ConfigurableParam::EParamUpdateStatus::Changed; } - return false; + return ConfigurableParam::EParamUpdateStatus::Unchanged; } -bool ConfigurableParam::updateThroughStorageMap(std::string mainkey, std::string subkey, std::type_info const& tinfo, - void* addr) +ConfigurableParam::EParamUpdateStatus ConfigurableParam::updateThroughStorageMap(std::string mainkey, std::string subkey, std::type_info const& tinfo, + void* addr) { // check if key_exists auto key = mainkey + "." + subkey; auto iter = sKeyToStorageMap->find(key); if (iter == sKeyToStorageMap->end()) { LOG(WARN) << "Cannot update parameter " << key << " not found"; - return false; + return ConfigurableParam::EParamUpdateStatus::Failed; } // the type we need to convert to @@ -638,7 +652,7 @@ bool ConfigurableParam::updateThroughStorageMap(std::string mainkey, std::string // check that type matches if (iter->second.first != tinfo) { LOG(WARN) << "Types do not match; cannot update value"; - return false; + return ConfigurableParam::EParamUpdateStatus::Failed; } auto targetaddress = iter->second.second; @@ -749,72 +763,74 @@ bool ConfigurableParam::updateThroughStorageMap(std::string mainkey, std::string break; } } - return false; + return ConfigurableParam::EParamUpdateStatus::Failed; } template -bool ConvertAndCopy(std::string const& valuestring, void* targetaddr) +ConfigurableParam::EParamUpdateStatus ConvertAndCopy(std::string const& valuestring, void* targetaddr) { auto addr = boost::lexical_cast(valuestring); if (isMemblockDifferent(targetaddr, (void*)&addr)) { std::memcpy(targetaddr, (void*)&addr, sizeof(T)); - return true; + return ConfigurableParam::EParamUpdateStatus::Changed; } - return false; + return ConfigurableParam::EParamUpdateStatus::Unchanged; } + // special version for std::string template <> -bool ConvertAndCopy(std::string const& valuestring, void* targetaddr) +ConfigurableParam::EParamUpdateStatus ConvertAndCopy(std::string const& valuestring, void* targetaddr) { std::string& target = *((std::string*)targetaddr); if (target.compare(valuestring) != 0) { // the targetaddr is a std::string to which we can simply assign // and all the magic will happen internally target = valuestring; - return true; + return ConfigurableParam::EParamUpdateStatus::Changed; } - return false; + return ConfigurableParam::EParamUpdateStatus::Unchanged; } // special version for char and unsigned char since we are interested in the numeric // meaning of char as an 8-bit integer (boost lexical cast is assigning the string as a character i// nterpretation template <> -bool ConvertAndCopy(std::string const& valuestring, void* targetaddr) +ConfigurableParam::EParamUpdateStatus ConvertAndCopy(std::string const& valuestring, void* targetaddr) { int intvalue = boost::lexical_cast(valuestring); if (intvalue > std::numeric_limits::max() || intvalue < std::numeric_limits::min()) { LOG(ERROR) << "Cannot assign " << valuestring << " to a char variable"; - return false; + return ConfigurableParam::EParamUpdateStatus::Failed; } char addr = intvalue; if (isMemblockDifferent(targetaddr, (void*)&addr)) { std::memcpy(targetaddr, (void*)&addr, sizeof(char)); - return true; + return ConfigurableParam::EParamUpdateStatus::Changed; } - return false; + return ConfigurableParam::EParamUpdateStatus::Unchanged; } + template <> -bool ConvertAndCopy(std::string const& valuestring, void* targetaddr) +ConfigurableParam::EParamUpdateStatus ConvertAndCopy(std::string const& valuestring, void* targetaddr) { unsigned int intvalue = boost::lexical_cast(valuestring); if (intvalue > std::numeric_limits::max() || intvalue < std::numeric_limits::min()) { LOG(ERROR) << "Cannot assign " << valuestring << " to an unsigned char variable"; - return false; + return ConfigurableParam::EParamUpdateStatus::Failed; } unsigned char addr = intvalue; if (isMemblockDifferent(targetaddr, (void*)&addr)) { std::memcpy(targetaddr, (void*)&addr, sizeof(unsigned char)); - return true; + return ConfigurableParam::EParamUpdateStatus::Changed; } - return false; + return ConfigurableParam::EParamUpdateStatus::Unchanged; } -bool ConfigurableParam::updateThroughStorageMapWithConversion(std::string const& key, std::string const& valuestring) +ConfigurableParam::EParamUpdateStatus ConfigurableParam::updateThroughStorageMapWithConversion(std::string const& key, std::string const& valuestring) { // check if key_exists auto iter = sKeyToStorageMap->find(key); if (iter == sKeyToStorageMap->end()) { LOG(WARN) << "Cannot update parameter " << key << " (parameter not found) "; - return false; + return ConfigurableParam::EParamUpdateStatus::Failed; } auto targetaddress = iter->second.second; @@ -936,7 +952,7 @@ bool ConfigurableParam::updateThroughStorageMapWithConversion(std::string const& break; } } - return false; + return ConfigurableParam::EParamUpdateStatus::Failed; } } // namespace conf From 5b0cba69a06e15419b0cbfb6e1f9afb40ecbbc43 Mon Sep 17 00:00:00 2001 From: Francesco Noferini Date: Mon, 12 Apr 2021 00:22:47 +0200 Subject: [PATCH 094/770] fix for TOF cosmic calib (#5895) * fix for TOF cosmic calib * suppress unneeded dereferencing, [] instead of at() --- .../TOF/reconstruction/src/CosmicProcessor.cxx | 16 +++++++++++++--- .../TOF/workflow/src/TOFClusterizerSpec.cxx | 8 ++++---- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/Detectors/TOF/reconstruction/src/CosmicProcessor.cxx b/Detectors/TOF/reconstruction/src/CosmicProcessor.cxx index 5ad32d7ceddd9..447ea3e982c2e 100644 --- a/Detectors/TOF/reconstruction/src/CosmicProcessor.cxx +++ b/Detectors/TOF/reconstruction/src/CosmicProcessor.cxx @@ -22,13 +22,17 @@ using namespace o2::tof; void CosmicProcessor::clear() { mCosmicInfo.clear(); - for (int i = 0; i < Geo::NCHANNELS; i++) { - mCounters[i] = 0; - } + mCosmicInfo.reserve(5200); + + memset(mCounters, 0, sizeof(int) * Geo::NCHANNELS); } //__________________________________________________ void CosmicProcessor::process(DigitDataReader& reader, bool fill) { + if (mCosmicInfo.size() > 5000) { + return; + } + TStopwatch timerProcess; timerProcess.Start(); @@ -39,6 +43,8 @@ void CosmicProcessor::process(DigitDataReader& reader, bool fill) int ndig = array->size(); int ndig2 = ndig * fill; + int npair = 0; + int bcdist = 200; float thr = 5000000; // in ps @@ -46,6 +52,9 @@ void CosmicProcessor::process(DigitDataReader& reader, bool fill) float pos1[3], pos2[3]; for (int i = 0; i < ndig; i++) { + if (npair >= 150) { + break; + } auto& dig1 = (*array)[i]; int ch1 = dig1.getChannel(); mCounters[ch1]++; @@ -100,6 +109,7 @@ void CosmicProcessor::process(DigitDataReader& reader, bool fill) continue; } + npair++; mCosmicInfo.emplace_back(ch1, ch2, dtime, tot1, tot2, l, tm1, tm2); } } diff --git a/Detectors/TOF/workflow/src/TOFClusterizerSpec.cxx b/Detectors/TOF/workflow/src/TOFClusterizerSpec.cxx index 2a5bae3674ff4..61d265f48893e 100644 --- a/Detectors/TOF/workflow/src/TOFClusterizerSpec.cxx +++ b/Detectors/TOF/workflow/src/TOFClusterizerSpec.cxx @@ -75,7 +75,7 @@ class TOFDPLClustererTask mTimer.Start(false); // get digit data auto digits = pc.inputs().get>("tofdigits"); - auto row = pc.inputs().get*>("readoutwin"); + auto row = pc.inputs().get>("readoutwin"); const auto* dh = o2::header::get(pc.inputs().getByPos(0).header); mClusterer.setFirstOrbit(dh->firstTForbit); @@ -128,9 +128,9 @@ class TOFDPLClustererTask mCosmicProcessor.clear(); } - for (int i = 0; i < row->size(); i++) { - //printf("# TOF readout window for clusterization = %d/%lu (N digits = %d)\n", i, row->size(), row->at(i).size()); - auto digitsRO = row->at(i).getBunchChannelData(digits); + for (int i = 0; i < row.size(); i++) { + //printf("# TOF readout window for clusterization = %d/%lu (N digits = %d)\n", i, row.size(), row[i].size()); + auto digitsRO = row[i].getBunchChannelData(digits); mReader.setDigitArray(&digitsRO); if (mIsCosmic) { From e1e69b75b7bca1d9f769bbd4b84910c9c92afdeb Mon Sep 17 00:00:00 2001 From: Artur Furs <9881239+afurs@users.noreply.github.com> Date: Mon, 12 Apr 2021 10:37:53 +0300 Subject: [PATCH 095/770] FIT: Large opitmisation(RawReader) and type checking(DataBlockWrapper) for FITRaw, 'expired message' mechanism for FT0 DPL workflow (#5858) * FT0 LUT prepared as Singleton for DigitBlockFT0 usage * Large optimization for RawReader in FITRaw library * Use 'expired messages' mechanism for FT0 raw data decoder (taken from ITS/MFT) * Mechanism for type checking in DataBlockWrapper, within FITRaw lib * new LUT * Test executable for FT0(raw2digit) Test executable for FT0(raw2digit) * Hotfix for newLUT branch Hotfix for newLUT branch * Hotfix(braces added) Hotfix(braces added) Hotfix(braces added) Hotfix(braces added) Co-authored-by: Alla Maevskaya --- .../FDD/include/DataFormatsFDD/RawEventData.h | 12 +- .../FT0/include/DataFormatsFT0/LookUpTable.h | 99 +++++--- .../FT0/include/DataFormatsFT0/RawEventData.h | 17 +- .../FV0/include/DataFormatsFV0/RawEventData.h | 4 +- .../FDD/raw/include/FDDRaw/DigitBlockFDD.h | 2 +- .../FDD/raw/include/FDDRaw/RawReaderFDDBase.h | 10 +- .../include/FDDWorkflow/RawDataReaderSpec.h | 2 +- .../files/FT0ChannelsTable.02.0.4.2021.txt | 230 ++++++++++++++++++ .../FT0/raw/include/FT0Raw/DigitBlockFT0.h | 8 +- .../FT0/raw/include/FT0Raw/RawReaderFT0Base.h | 15 +- .../FIT/FT0/reconstruction/CMakeLists.txt | 7 + .../include/FT0Reconstruction/ReadRaw.h | 5 +- .../FIT/FT0/reconstruction/src/ReadRaw.cxx | 27 +- .../FT0/reconstruction/src/test-raw2digit.cxx | 119 +++++++++ .../include/FT0Simulation/Digits2Raw.h | 4 +- .../FIT/FT0/simulation/src/Digits2Raw.cxx | 79 ++++-- .../FT0Workflow/FT0DataReaderDPLSpec.h | 40 ++- .../include/FT0Workflow/FT0Workflow.h | 2 +- .../include/FT0Workflow/RawReaderFT0.h | 19 +- .../FIT/FT0/workflow/src/FT0Workflow.cxx | 6 +- .../FIT/FT0/workflow/src/ft0-flp-workflow.cxx | 4 +- Detectors/FIT/macros/uploadLookUpTable.C | 29 +-- .../FIT/raw/include/FITRaw/DataBlockBase.h | 81 +++++- .../FIT/raw/include/FITRaw/DigitBlockBase.h | 4 +- .../FIT/raw/include/FITRaw/RawReaderBase.h | 56 +++-- 25 files changed, 711 insertions(+), 170 deletions(-) create mode 100644 Detectors/FIT/FT0/base/files/FT0ChannelsTable.02.0.4.2021.txt create mode 100644 Detectors/FIT/FT0/reconstruction/src/test-raw2digit.cxx diff --git a/DataFormats/Detectors/FIT/FDD/include/DataFormatsFDD/RawEventData.h b/DataFormats/Detectors/FIT/FDD/include/DataFormatsFDD/RawEventData.h index 9764e23809afb..b60f1981e9fbf 100644 --- a/DataFormats/Detectors/FIT/FDD/include/DataFormatsFDD/RawEventData.h +++ b/DataFormats/Detectors/FIT/FDD/include/DataFormatsFDD/RawEventData.h @@ -32,8 +32,8 @@ namespace fdd struct EventHeader { static constexpr size_t PayloadSize = 16; //should be equal to 10 static constexpr size_t PayloadPerGBTword = 16; //should be equal to 10 - static constexpr int MinNelements = 1; - static constexpr int MaxNelements = 1; + static constexpr size_t MinNelements = 1; + static constexpr size_t MaxNelements = 1; union { uint64_t word[2] = {}; struct { @@ -55,8 +55,8 @@ struct EventHeader { struct EventData { static constexpr size_t PayloadSize = 5; static constexpr size_t PayloadPerGBTword = 10; - static constexpr int MinNelements = 1; //additional static field - static constexpr int MaxNelements = 12; + static constexpr size_t MinNelements = 1; //additional static field + static constexpr size_t MaxNelements = 12; // static constexpr int BitFlagPos = 25; // position of first bit flag(numberADC) @@ -103,8 +103,8 @@ struct EventData { struct TCMdata { static constexpr size_t PayloadSize = 16; //should be equal to 10 static constexpr size_t PayloadPerGBTword = 16; //should be equal to 10 - static constexpr int MinNelements = 1; - static constexpr int MaxNelements = 1; + static constexpr size_t MinNelements = 1; + static constexpr size_t MaxNelements = 1; union { uint64_t word[2] = {0}; struct { diff --git a/DataFormats/Detectors/FIT/FT0/include/DataFormatsFT0/LookUpTable.h b/DataFormats/Detectors/FIT/FT0/include/DataFormatsFT0/LookUpTable.h index 7c9553ce8c3c4..fcc4268871210 100644 --- a/DataFormats/Detectors/FIT/FT0/include/DataFormatsFT0/LookUpTable.h +++ b/DataFormats/Detectors/FIT/FT0/include/DataFormatsFT0/LookUpTable.h @@ -33,6 +33,7 @@ #include #include #include +#include namespace o2 { @@ -41,7 +42,8 @@ namespace ft0 struct Topo { int mPM = 0; int mMCP = 0; - ClassDefNV(Topo, 1); + int mEP = 0; + ClassDefNV(Topo, 2); }; // enum class Side : char { A, C }; @@ -51,39 +53,55 @@ struct Topo { // }; struct HVchannel { - enum class HVBoard : uint8_t { NA, + /* enum class HVBoard : uint8_t { NA, A_out, A_in, C_up, C_down, - C_mid }; + C_mid };*/ + uint8_t channel; Topo pm; - HVBoard HV_board; + std::string HV_board; uint8_t HV_channel; std::string MCP_SN; std::string HV_cabel; std::string signal_cable; + std::string EP; - ClassDefNV(HVchannel, 1); + ClassDefNV(HVchannel, 2); }; inline bool operator<(Topo const& a, Topo const& b) { - return (a.mPM < b.mPM || (a.mPM == b.mPM && a.mMCP < b.mMCP)); + /* return (a.mPM < b.mPM || (a.mPM == b.mPM && a.mMCP < b.mMCP)); */ + auto t = [](Topo const& x) -> decltype(auto) { return std::tie(x.mPM, x.mMCP, x.mEP); }; + return t(a) < t(b); } inline o2::ft0::Topo read_Topo(std::string_view str) { - assert(str.substr(0, 2) == "PM" && str[4] == '/' && str[5] == 'C' && str[6] == 'h'); + assert(str.substr(0, 2) == "PM"); // && str[4] == '/' && str[5] == 'C' && str[6] == 'h'); char side = str[2]; - uint8_t pm_num = str[3] - '0'; - uint8_t pm_ch = (str[7] - '0') * 10 + (str[8] - '0') - 1; - assert(side == 'A' || side == 'C'); - if (str.substr(0, 4) == "PMA9") { - pm_num = 18; + char* ptr; + uint8_t pm_num = std::strtol(str.data() + 3, &ptr, 10); // = str[3] - '0'; + /* auto res = std::from_chars(str.data()+3, str.data()+3+str.size(), pm_num); */ + /* if (res.ec != std::errc() || res.ptr[0] != '/') */ + if (errno || ptr[0] != '/') { + throw std::invalid_argument("Cannot read pm_num"); + } + if (ptr[1] != 'C' || ptr[2] != 'h') { + throw std::invalid_argument("Expected 'Ch'"); + } + uint8_t pm_ch = std::strtol(ptr + 3, &ptr, 10); + // = (str[7] - '0') * 10 + (str[8] - '0') - 1; + /* res = std::from_chars(res.ptr+3, res.ptr+3+str.size(), pm_ch); */ + uint8_t ep = side == 'C' ? 1 : 0; + if (errno) { + throw std::invalid_argument("Cannot read pm_ch"); } - return Topo{(side == 'C' ? 8 : 0) + pm_num, pm_ch}; + assert(side == 'A' || side == 'C'); + return Topo{pm_num, pm_ch, ep}; } class LookUpTable @@ -92,6 +110,7 @@ class LookUpTable using CcdbApi = o2::ccdb::CcdbApi; static constexpr int NUMBER_OF_MCPs = 12; static constexpr int NUMBER_OF_PMs = 19; + static constexpr int TCM_channel = 228; public: /// @@ -101,33 +120,32 @@ class LookUpTable // LookUpTable() = default; explicit LookUpTable(std::vector const& topoVector) - : mTopoVector(topoVector), mInvTopo(topoVector.size()) + : mTopoVector(topoVector), mInvTopo(NUMBER_OF_MCPs * 16 * 2) { for (size_t channel = 0; channel < mTopoVector.size(); ++channel) { - mInvTopo.at(getIdx(mTopoVector[channel].mPM, mTopoVector[channel].mMCP)) = + mInvTopo.at(getIdx(mTopoVector[channel].mPM, mTopoVector[channel].mMCP, mTopoVector[channel].mEP)) = channel; } } LookUpTable() = default; ~LookUpTable() = default; - HVchannel mHVchannel; + int getTCMchannel() const + { + return TCM_channel; + } void printFullMap() const { for (size_t channel = 0; channel < mTopoVector.size(); ++channel) { std::cout << channel << "\t : PM \t" << mTopoVector[channel].mPM - << " MCP \t" << mTopoVector[channel].mMCP << std::endl; - } - for (size_t idx = 0; idx < mInvTopo.size(); ++idx) { - std::cout << "PM \t" << getLinkFromIdx(mInvTopo[idx]) << " MCP \t" - << getMCPFromIdx(mInvTopo[idx]) << std::endl; + << " MCP \t" << mTopoVector[channel].mMCP << " EP \t " << mTopoVector[channel].mEP << std::endl; } } - int getChannel(int link, int mcp) const + int getChannel(int link, int mcp, int ep) const { - return mInvTopo[getIdx(link, mcp)]; + return mInvTopo[getIdx(link, mcp, ep)]; } int getLink(int channel) const @@ -138,6 +156,10 @@ class LookUpTable { return mTopoVector[channel].mMCP; } + int getEP(int channel) const + { + return mTopoVector[channel].mEP; + } static o2::ft0::LookUpTable linear() { @@ -174,7 +196,8 @@ class LookUpTable int channel; std::string pm, pm_channel, hv_board, hv_channel, mcp_sn, hv_cable, signal_cable; std::getline(infile, pm); // skip one line - while (infile >> channel >> pm >> pm_channel >> hv_board >> hv_channel >> mcp_sn >> hv_cable >> signal_cable) { + std::string line; + while (std::getline(infile, line) && std::istringstream(line) >> channel >> pm >> pm_channel >> hv_board >> hv_channel >> mcp_sn >> hv_cable >> signal_cable) { lut_data[channel] = read_Topo(pm_channel); } return o2::ft0::LookUpTable{lut_data}; @@ -197,6 +220,7 @@ class LookUpTable o2::ft0::Topo topo = chan.pm; lut_data[chan.channel] = topo; } + std::cout << "lut_data.size " << lut_data.size() << std::endl; return o2::ft0::LookUpTable{lut_data}; } @@ -204,13 +228,31 @@ class LookUpTable std::vector mTopoVector; std::vector mInvTopo; - static int getIdx(int link, int mcp) + static int getIdx(int link, int mcp, int ep) { assert(mcp < NUMBER_OF_MCPs); - return link * NUMBER_OF_MCPs + mcp; + return (link + ep * 16) * NUMBER_OF_MCPs + mcp; + } + static int getLinkFromIdx(int idx) + { + int link; + if (idx > 95) { + link = (idx - 96) / NUMBER_OF_MCPs; + } else { + link = idx / NUMBER_OF_MCPs; + } + return link; + } + static int getEPFromIdx(int idx) + { + if (idx < 96 || idx > 215) { + return 0; + } else { + return 1; + } } - static int getLinkFromIdx(int idx) { return idx / NUMBER_OF_MCPs; } - static int getMCPFromIdx(int idx) { return idx % NUMBER_OF_MCPs; } + + static int getMCPFromIdx(int idx) { return idx % NUMBER_OF_MCPs + 1; } ClassDefNV(LookUpTable, 2); }; @@ -222,7 +264,6 @@ class SingleLUT : public LookUpTable SingleLUT() : LookUpTable(LookUpTable::readTable()) {} SingleLUT(const SingleLUT&) = delete; SingleLUT& operator=(SingleLUT&) = delete; - public: static SingleLUT& Instance() { diff --git a/DataFormats/Detectors/FIT/FT0/include/DataFormatsFT0/RawEventData.h b/DataFormats/Detectors/FIT/FT0/include/DataFormatsFT0/RawEventData.h index cd27075526e04..b26f4402bc912 100644 --- a/DataFormats/Detectors/FIT/FT0/include/DataFormatsFT0/RawEventData.h +++ b/DataFormats/Detectors/FIT/FT0/include/DataFormatsFT0/RawEventData.h @@ -38,8 +38,8 @@ constexpr size_t sizeWord = 16; struct EventHeader { static constexpr size_t PayloadSize = 16; //should be equal to 10 static constexpr size_t PayloadPerGBTword = 16; //should be equal to 10 - static constexpr int MinNelements = 1; - static constexpr int MaxNelements = 1; + static constexpr size_t MinNelements = 1; + static constexpr size_t MaxNelements = 1; union { uint64_t word[2] = {}; struct { @@ -62,8 +62,8 @@ struct EventHeader { struct EventData { static constexpr size_t PayloadSize = 5; static constexpr size_t PayloadPerGBTword = 10; - static constexpr int MinNelements = 1; //additional static field - static constexpr int MaxNelements = 12; + static constexpr size_t MinNelements = 1; //additional static field + static constexpr size_t MaxNelements = 12; // static constexpr int BitFlagPos = 25; // position of first bit flag(numberADC) @@ -115,8 +115,8 @@ struct EventData { struct TCMdata { static constexpr size_t PayloadSize = 16; //should be equal to 10 static constexpr size_t PayloadPerGBTword = 16; //should be equal to 10 - static constexpr int MinNelements = 1; - static constexpr int MaxNelements = 1; + static constexpr size_t MinNelements = 1; + static constexpr size_t MaxNelements = 1; uint64_t orA : 1, // 0 bit (0 byte) orC : 1, //1 bit sCen : 1, //2 bit @@ -163,8 +163,8 @@ struct TCMdata { struct TCMdataExtended { static constexpr size_t PayloadSize = 4; static constexpr size_t PayloadPerGBTword = 10; - static constexpr int MinNelements = 0; - static constexpr int MaxNelements = 20; + static constexpr size_t MinNelements = 0; + static constexpr size_t MaxNelements = 20; union { uint32_t word[1] = {}; uint32_t triggerWord; @@ -259,6 +259,7 @@ class DataPageWriter str.write(reinterpret_cast(&mRDH), sizeof(mRDH)); str.write(mPages[page].data(), mPages[page].size()); mRDH.pageCnt++; + LOG(INFO) << " header " << mRDH.linkID << " end " << mRDH.endPointID; } if (!mPages.empty()) { mRDH.memorySize = mRDH.headerSize; diff --git a/DataFormats/Detectors/FIT/FV0/include/DataFormatsFV0/RawEventData.h b/DataFormats/Detectors/FIT/FV0/include/DataFormatsFV0/RawEventData.h index 6afa24b608005..315f9ee35cc13 100644 --- a/DataFormats/Detectors/FIT/FV0/include/DataFormatsFV0/RawEventData.h +++ b/DataFormats/Detectors/FIT/FV0/include/DataFormatsFV0/RawEventData.h @@ -29,7 +29,7 @@ namespace o2 namespace fv0 { struct EventHeader { - static constexpr int PayloadSize = 16; + static constexpr size_t PayloadSize = 16; union { uint64_t word[2] = {}; struct { @@ -82,7 +82,7 @@ struct EventData { }; struct TCMdata { - static constexpr int PayloadSize = 16; + static constexpr size_t PayloadSize = 16; union { uint64_t word[2] = {0}; struct { diff --git a/Detectors/FIT/FDD/raw/include/FDDRaw/DigitBlockFDD.h b/Detectors/FIT/FDD/raw/include/FDDRaw/DigitBlockFDD.h index 8893b7b5e4533..34c57260d15ed 100644 --- a/Detectors/FIT/FDD/raw/include/FDDRaw/DigitBlockFDD.h +++ b/Detectors/FIT/FDD/raw/include/FDDRaw/DigitBlockFDD.h @@ -57,7 +57,7 @@ class DigitBlockFDD : public DigitBlockBase static int sEventID; template - void processDigits(DataBlockType& dataBlock, int linkID) + void processDigits(DataBlockType& dataBlock, int linkID, int ep) { if constexpr (std::is_same::value) { //Filling data from PM for (int iEventData = 0; iEventData < dataBlock.DataBlockWrapper::mNelements; iEventData++) { diff --git a/Detectors/FIT/FDD/raw/include/FDDRaw/RawReaderFDDBase.h b/Detectors/FIT/FDD/raw/include/FDDRaw/RawReaderFDDBase.h index 977e10493cfbf..7891293310e25 100644 --- a/Detectors/FIT/FDD/raw/include/FDDRaw/RawReaderFDDBase.h +++ b/Detectors/FIT/FDD/raw/include/FDDRaw/RawReaderFDDBase.h @@ -41,21 +41,21 @@ namespace fdd // Common raw reader for FDD template -class RawReaderFDDBase : public RawReaderBase +class RawReaderFDDBase : public RawReaderBase { public: - typedef RawReaderBase RawReaderBaseType; + typedef RawReaderBase RawReaderBaseType; RawReaderFDDBase() = default; ~RawReaderFDDBase() = default; //deserialize payload to raw data blocks and proccesss them to digits - void process(int linkID, gsl::span payload) + void process(int linkID, gsl::span payload, int ep) { if (0 <= linkID && linkID < 2) { //PM data proccessing - RawReaderBaseType::template processBinaryData(payload, linkID); + RawReaderBaseType::template processBinaryData(payload, linkID, 0); } else if (linkID == 2) { //TCM data proccessing - RawReaderBaseType::template processBinaryData(payload, linkID); + RawReaderBaseType::template processBinaryData(payload, linkID, 0); } else { //put here code in case of bad rdh.linkID value LOG(INFO) << "WARNING! WRONG LINK ID! " << linkID; diff --git a/Detectors/FIT/FDD/workflow/include/FDDWorkflow/RawDataReaderSpec.h b/Detectors/FIT/FDD/workflow/include/FDDWorkflow/RawDataReaderSpec.h index 51ea363b7840c..0cb7bb95a6f2d 100644 --- a/Detectors/FIT/FDD/workflow/include/FDDWorkflow/RawDataReaderSpec.h +++ b/Detectors/FIT/FDD/workflow/include/FDDWorkflow/RawDataReaderSpec.h @@ -52,7 +52,7 @@ class RawDataReaderSpec : public Task count++; auto rdhPtr = it.get_if(); gsl::span payload(it.data(), it.size()); - mRawReader.process(rdhPtr->linkID, payload); + mRawReader.process(rdhPtr->linkID, payload, int(0)); } LOG(INFO) << "Pages: " << count; mRawReader.accumulateDigits(); diff --git a/Detectors/FIT/FT0/base/files/FT0ChannelsTable.02.0.4.2021.txt b/Detectors/FIT/FT0/base/files/FT0ChannelsTable.02.0.4.2021.txt new file mode 100644 index 0000000000000..8e8f3930f944c --- /dev/null +++ b/Detectors/FIT/FT0/base/files/FT0ChannelsTable.02.0.4.2021.txt @@ -0,0 +1,230 @@ +channel # PM PM channel HV board HV channel MCP S/N HV cable signal cable EndPoint/Link +0 A0 PMA0/Ch01 0 HVA0/03 N/A FTA-D2 FTA-D2-? 0/0 +1 A0 PMA0/Ch02 0 HVA0/03 N/A FTA-D2 FTA-D2-? 0/0 +2 A0 PMA0/Ch03 0 HVA0/03 N/A FTA-D2 FTA-D2-? 0/0 +3 A0 PMA0/Ch04 0 HVA0/03 N/A FTA-D2 FTA-D2-? 0/0 +4 A0 PMA0/Ch05 0 HVA0/02 N/A FTA-D1 FTA-D1-? 0/0 +5 A0 PMA0/Ch06 0 HVA0/02 N/A FTA-D1 FTA-D1-? 0/0 +6 A0 PMA0/Ch07 0 HVA0/02 N/A FTA-D1 FTA-D1-? 0/0 +7 A0 PMA0/Ch08 0 HVA0/02 N/A FTA-D1 FTA-D1-? 0/0 +8 A0 PMA0/Ch09 0 HVA0/07 N/A FTA-E1 FTA-E1-? 0/0 +9 A0 PMA0/Ch10 0 HVA0/07 N/A FTA-E1 FTA-E1-? 0/0 +10 A0 PMA0/Ch11 0 HVA0/07 N/A FTA-E1 FTA-E1-? 0/0 +11 A0 PMA0/Ch12 0 HVA0/07 N/A FTA-E1 FTA-E1-? 0/0 +12 A1 PMA1/Ch01 0 HVA0/04 N/A FTA-D3 FTA-D3-? 0/1 +13 A1 PMA1/Ch02 0 HVA0/04 N/A FTA-D3 FTA-D3-? 0/1 +14 A1 PMA1/Ch03 0 HVA0/04 N/A FTA-D3 FTA-D3-? 0/1 +15 A1 PMA1/Ch04 0 HVA0/04 N/A FTA-D3 FTA-D3-? 0/1 +16 A1 PMA1/Ch05 0 HVA0/08 N/A FTA-E2 FTA-E2-? 0/1 +17 A1 PMA1/Ch06 0 HVA0/08 N/A FTA-E2 FTA-E2-? 0/1 +18 A1 PMA1/Ch07 0 HVA0/08 N/A FTA-E2 FTA-E2-? 0/1 +19 A1 PMA1/Ch08 0 HVA0/08 N/A FTA-E2 FTA-E2-? 0/1 +20 A1 PMA1/Ch09 0 HVA0/09 N/A FTA-E3 FTA-E3-? 0/1 +21 A1 PMA1/Ch10 0 HVA0/09 N/A FTA-E3 FTA-E3-? 0/1 +22 A1 PMA1/Ch11 0 HVA0/09 N/A FTA-E3 FTA-E3-? 0/1 +23 A1 PMA1/Ch12 0 HVA0/09 N/A FTA-E3 FTA-E3-? 0/1 +24 A2 PMA2/Ch01 0 HVA0/05 N/A FTA-D4 FTA-D4-? 0/2 +25 A2 PMA2/Ch02 0 HVA0/05 N/A FTA-D4 FTA-D4-? 0/2 +26 A2 PMA2/Ch03 0 HVA0/05 N/A FTA-D4 FTA-D4-? 0/2 +27 A2 PMA2/Ch04 0 HVA0/05 N/A FTA-D4 FTA-D4-? 0/2 +28 A2 PMA2/Ch05 0 HVA0/10 N/A FTA-E4 FTA-E4-? 0/2 +29 A2 PMA2/Ch06 0 HVA0/10 N/A FTA-E4 FTA-E4-? 0/2 +30 A2 PMA2/Ch07 0 HVA0/10 N/A FTA-E4 FTA-E4-? 0/2 +31 A2 PMA2/Ch08 0 HVA0/10 N/A FTA-E4 FTA-E4-? 0/2 +32 A2 PMA2/Ch09 0 HVA0/11 N/A FTA-E5 FTA-E5-? 0/2 +33 A2 PMA2/Ch10 0 HVA0/11 N/A FTA-E5 FTA-E5-? 0/2 +34 A2 PMA2/Ch11 0 HVA0/11 N/A FTA-E5 FTA-E5-? 0/2 +35 A2 PMA2/Ch12 0 HVA0/11 N/A FTA-E5 FTA-E5-? 0/2 +36 A3 PMA3/Ch01 0 HVA0/00 N/A FTA-C4 FTA-C4-? 0/3 +37 A3 PMA3/Ch02 0 HVA0/00 N/A FTA-C4 FTA-C4-? 0/3 +38 A3 PMA3/Ch03 0 HVA0/00 N/A FTA-C4 FTA-C4-? 0/3 +39 A3 PMA3/Ch04 0 HVA0/00 N/A FTA-C4 FTA-C4-? 0/3 +40 A3 PMA3/Ch05 0 HVA0/06 N/A FTA-D5 FTA-D5-? 0/3 +41 A3 PMA3/Ch06 0 HVA0/06 N/A FTA-D5 FTA-D5-? 0/3 +42 A3 PMA3/Ch07 0 HVA0/06 N/A FTA-D5 FTA-D5-? 0/3 +43 A3 PMA3/Ch08 0 HVA0/06 N/A FTA-D5 FTA-D5-? 0/3 +44 A3 PMA3/Ch09 0 HVA0/01 N/A FTA-C5 FTA-C5-? 0/3 +45 A3 PMA3/Ch10 0 HVA0/01 N/A FTA-C5 FTA-C5-? 0/3 +46 A3 PMA3/Ch11 0 HVA0/01 N/A FTA-C5 FTA-C5-? 0/3 +47 A3 PMA3/Ch12 0 HVA0/01 N/A FTA-C5 FTA-C5-? 0/3 +48 A4 PMA4/Ch01 1 HVA1/08 N/A FTA-B4 FTA-B4-? 0/4 +49 A4 PMA4/Ch02 1 HVA1/08 N/A FTA-B4 FTA-B4-? 0/4 +50 A4 PMA4/Ch03 1 HVA1/08 N/A FTA-B4 FTA-B4-? 0/4 +51 A4 PMA4/Ch04 1 HVA1/08 N/A FTA-B4 FTA-B4-? 0/4 +52 A4 PMA4/Ch05 1 HVA1/09 N/A FTA-B5 FTA-B5-? 0/4 +53 A4 PMA4/Ch06 1 HVA1/09 N/A FTA-B5 FTA-B5-? 0/4 +54 A4 PMA4/Ch07 1 HVA1/09 N/A FTA-B5 FTA-B5-? 0/4 +55 A4 PMA4/Ch08 1 HVA1/09 N/A FTA-B5 FTA-B5-? 0/4 +56 A4 PMA4/Ch09 1 HVA1/04 N/A FTA-A5 FTA-A5-? 0/4 +57 A4 PMA4/Ch10 1 HVA1/04 N/A FTA-A5 FTA-A5-? 0/4 +58 A4 PMA4/Ch11 1 HVA1/04 N/A FTA-A5 FTA-A5-? 0/4 +59 A4 PMA4/Ch12 1 HVA1/04 N/A FTA-A5 FTA-A5-? 0/4 +60 A5 PMA5/Ch01 1 HVA1/07 N/A FTA-B3 FTA-B3-? 0/5 +61 A5 PMA5/Ch02 1 HVA1/07 N/A FTA-B3 FTA-B3-? 0/5 +62 A5 PMA5/Ch03 1 HVA1/07 N/A FTA-B3 FTA-B3-? 0/5 +63 A5 PMA5/Ch04 1 HVA1/07 N/A FTA-B3 FTA-B3-? 0/5 +64 A5 PMA5/Ch05 1 HVA1/03 N/A FTA-A4 FTA-A4-? 0/5 +65 A5 PMA5/Ch06 1 HVA1/03 N/A FTA-A4 FTA-A4-? 0/5 +66 A5 PMA5/Ch07 1 HVA1/03 N/A FTA-A4 FTA-A4-? 0/5 +67 A5 PMA5/Ch08 1 HVA1/03 N/A FTA-A4 FTA-A4-? 0/5 +68 A5 PMA5/Ch09 1 HVA1/02 N/A FTA-A3 FTA-A3-? 0/5 +69 A5 PMA5/Ch10 1 HVA1/02 N/A FTA-A3 FTA-A3-? 0/5 +70 A5 PMA5/Ch11 1 HVA1/02 N/A FTA-A3 FTA-A3-? 0/5 +71 A5 PMA5/Ch12 1 HVA1/02 N/A FTA-A3 FTA-A3-? 0/5 +72 A6 PMA6/Ch01 1 HVA1/06 N/A FTA-B2 FTA-B2-? 0/6 +73 A6 PMA6/Ch02 1 HVA1/06 N/A FTA-B2 FTA-B2-? 0/6 +74 A6 PMA6/Ch03 1 HVA1/06 N/A FTA-B2 FTA-B2-? 0/6 +75 A6 PMA6/Ch04 1 HVA1/06 N/A FTA-B2 FTA-B2-? 0/6 +76 A6 PMA6/Ch05 1 HVA1/01 N/A FTA-A2 FTA-A2-? 0/6 +77 A6 PMA6/Ch06 1 HVA1/01 N/A FTA-A2 FTA-A2-? 0/6 +78 A6 PMA6/Ch07 1 HVA1/01 N/A FTA-A2 FTA-A2-? 0/6 +79 A6 PMA6/Ch08 1 HVA1/01 N/A FTA-A2 FTA-A2-? 0/6 +80 A6 PMA6/Ch09 1 HVA1/00 N/A FTA-A1 FTA-A1-? 0/6 +81 A6 PMA6/Ch10 1 HVA1/00 N/A FTA-A1 FTA-A1-? 0/6 +82 A6 PMA6/Ch11 1 HVA1/00 N/A FTA-A1 FTA-A1-? 0/6 +83 A6 PMA6/Ch12 1 HVA1/00 N/A FTA-A1 FTA-A1-? 0/6 +84 A7 PMA7/Ch01 1 HVA1/11 N/A FTA-C2 FTA-C2-? 0/7 +85 A7 PMA7/Ch02 1 HVA1/11 N/A FTA-C2 FTA-C2-? 0/7 +86 A7 PMA7/Ch03 1 HVA1/11 N/A FTA-C2 FTA-C2-? 0/7 +87 A7 PMA7/Ch04 1 HVA1/11 N/A FTA-C2 FTA-C2-? 0/7 +88 A7 PMA7/Ch05 1 HVA1/05 N/A FTA-B1 FTA-B1-? 0/7 +89 A7 PMA7/Ch06 1 HVA1/05 N/A FTA-B1 FTA-B1-? 0/7 +90 A7 PMA7/Ch07 1 HVA1/05 N/A FTA-B1 FTA-B1-? 0/7 +91 A7 PMA7/Ch08 1 HVA1/05 N/A FTA-B1 FTA-B1-? 0/7 +92 A7 PMA7/Ch09 1 HVA1/10 N/A FTA-C1 FTA-C1-? 0/7 +93 A7 PMA7/Ch10 1 HVA1/10 N/A FTA-C1 FTA-C1-? 0/7 +94 A7 PMA7/Ch11 1 HVA1/10 N/A FTA-C1 FTA-C1-? 0/7 +95 A7 PMA7/Ch12 1 HVA1/10 N/A FTA-C1 FTA-C1-? 0/7 +96 C0 PMC0/Ch01 2 HVC2/03 2119 FTC-B3 FTC-B3-2 1/0 +97 C0 PMC0/Ch02 2 HVC2/03 2119 FTC-B3 FTC-B3-1 1/0 +98 C0 PMC0/Ch03 2 HVC2/03 2119 FTC-B3 FTC-B3-3 1/0 +99 C0 PMC0/Ch04 2 HVC2/03 2119 FTC-B3 FTC-B3-4 1/0 +100 C0 PMC0/Ch05 2 HVC2/01 2147 FTC-A3 FTC-A3-2 1/0 +101 C0 PMC0/Ch06 2 HVC2/01 2147 FTC-A3 FTC-A3-1 1/0 +102 C0 PMC0/Ch07 2 HVC2/01 2147 FTC-A3 FTC-A3-3 1/0 +103 C0 PMC0/Ch08 2 HVC2/01 2147 FTC-A3 FTC-A3-4 1/0 +104 C0 PMC0/Ch09 2 HVC2/00 2129 FTC-A2 FTC-A2-2 1/0 +105 C0 PMC0/Ch10 2 HVC2/00 2129 FTC-A2 FTC-A2-1 1/0 +106 C0 PMC0/Ch11 2 HVC2/00 2129 FTC-A2 FTC-A2-3 1/0 +107 C0 PMC0/Ch12 2 HVC2/00 2129 FTC-A2 FTC-A2-4 1/0 +108 C1 PMC1/Ch01 2 HVC2/05 2123 FTC-C2 FTC-C2-1 1/1 +109 C1 PMC1/Ch02 2 HVC2/05 2123 FTC-C2 FTC-C2-2 1/1 +110 C1 PMC1/Ch03 2 HVC2/05 2123 FTC-C2 FTC-C2-4 1/1 +111 C1 PMC1/Ch04 2 HVC2/05 2123 FTC-C2 FTC-C2-3 1/1 +112 C1 PMC1/Ch05 2 HVC2/04 2127 FTC-C1 FTC-C1-1 1/1 +113 C1 PMC1/Ch06 2 HVC2/04 2127 FTC-C1 FTC-C1-2 1/1 +114 C1 PMC1/Ch07 2 HVC2/04 2127 FTC-C1 FTC-C1-4 1/1 +115 C1 PMC1/Ch08 2 HVC2/04 2127 FTC-C1 FTC-C1-3 1/1 +116 C1 PMC1/Ch09 2 HVC2/02 2118 FTC-B1 FTC-B1-2 1/1 +117 C1 PMC1/Ch10 2 HVC2/02 2118 FTC-B1 FTC-B1-3 1/1 +118 C1 PMC1/Ch11 2 HVC2/02 2118 FTC-B1 FTC-B1-1 1/1 +119 C1 PMC1/Ch12 2 HVC2/02 2118 FTC-B1 FTC-B1-4 1/1 +120 C2 PMC2/Ch01 2 HVC2/07 2128 FTC-D2 FTC-D2-4 1/2 +121 C2 PMC2/Ch02 2 HVC2/07 2128 FTC-D2 FTC-D2-3 1/2 +122 C2 PMC2/Ch03 2 HVC2/07 2128 FTC-D2 FTC-D2-1 1/2 +123 C2 PMC2/Ch04 2 HVC2/07 2128 FTC-D2 FTC-D2-2 1/2 +124 C2 PMC2/Ch05 2 HVC2/06 2145 FTC-D1 FTC-D1-4 1/2 +125 C2 PMC2/Ch06 2 HVC2/06 2145 FTC-D1 FTC-D1-3 1/2 +126 C2 PMC2/Ch07 2 HVC2/06 2145 FTC-D1 FTC-D1-1 1/2 +127 C2 PMC2/Ch08 2 HVC2/06 2145 FTC-D1 FTC-D1-2 1/2 +128 C2 PMC2/Ch09 2 HVC2/08 2125 FTC-E1 FTC-E1-2 1/2 +129 C2 PMC2/Ch10 2 HVC2/08 2125 FTC-E1 FTC-E1-1 1/2 +130 C2 PMC2/Ch11 2 HVC2/08 2125 FTC-E1 FTC-E1-3 1/2 +131 C2 PMC2/Ch12 2 HVC2/08 2125 FTC-E1 FTC-E1-4 1/2 +132 C3 PMC3/Ch01 2 HVC2/09 2130 FTC-E3 FTC-E3-1 1/3 +133 C3 PMC3/Ch02 2 HVC2/09 2130 FTC-E3 FTC-E3-2 1/3 +134 C3 PMC3/Ch03 2 HVC2/09 2130 FTC-E3 FTC-E3-4 1/3 +135 C3 PMC3/Ch04 2 HVC2/09 2130 FTC-E3 FTC-E3-3 1/3 +136 C3 PMC3/Ch05 2 HVC2/11 2149 FTC-F3 FTC-F3-1 1/3 +137 C3 PMC3/Ch06 2 HVC2/11 2149 FTC-F3 FTC-F3-2 1/3 +138 C3 PMC3/Ch07 2 HVC2/11 2149 FTC-F3 FTC-F3-4 1/3 +139 C3 PMC3/Ch08 2 HVC2/11 2149 FTC-F3 FTC-F3-3 1/3 +140 C3 PMC3/Ch09 2 HVC2/10 2134 FTC-F2 FTC-F2-1 1/3 +141 C3 PMC3/Ch10 2 HVC2/10 2134 FTC-F2 FTC-F2-2 1/3 +142 C3 PMC3/Ch11 2 HVC2/10 2134 FTC-F2 FTC-F2-4 1/3 +143 C3 PMC3/Ch12 2 HVC2/10 2134 FTC-F2 FTC-F2-3 1/3 +144 C4 PMC4/Ch01 3 HVC3/08 2137 FTC-E4 FTC-E4-2 1/4 +145 C4 PMC4/Ch02 3 HVC3/08 2137 FTC-E4 FTC-E4-1 1/4 +146 C4 PMC4/Ch03 3 HVC3/08 2137 FTC-E4 FTC-E4-3 1/4 +147 C4 PMC4/Ch04 3 HVC3/08 2137 FTC-E4 FTC-E4-4 1/4 +148 C4 PMC4/Ch05 3 HVC3/10 2152 FTC-F4 FTC-F4-2 1/4 +149 C4 PMC4/Ch06 3 HVC3/10 2152 FTC-F4 FTC-F4-1 1/4 +150 C4 PMC4/Ch07 3 HVC3/10 2152 FTC-F4 FTC-F4-3 1/4 +151 C4 PMC4/Ch08 3 HVC3/10 2152 FTC-F4 FTC-F4-4 1/4 +152 C4 PMC4/Ch09 3 HVC3/11 2142 FTC-F5 FTC-F5-2 1/4 +153 C4 PMC4/Ch10 3 HVC3/11 2142 FTC-F5 FTC-F5-1 1/4 +154 C4 PMC4/Ch11 3 HVC3/11 2142 FTC-F5 FTC-F5-3 1/4 +155 C4 PMC4/Ch12 3 HVC3/11 2142 FTC-F5 FTC-F5-4 1/4 +156 C5 PMC5/Ch01 3 HVC3/06 2157 FTC-D5 FTC-D5-1 1/5 +157 C5 PMC5/Ch02 3 HVC3/06 2157 FTC-D5 FTC-D5-2 1/5 +158 C5 PMC5/Ch03 3 HVC3/06 2157 FTC-D5 FTC-D5-4 1/5 +159 C5 PMC5/Ch04 3 HVC3/06 2157 FTC-D5 FTC-D5-3 1/5 +160 C5 PMC5/Ch05 3 HVC3/07 2167 FTC-D6 FTC-D6-1 1/5 +161 C5 PMC5/Ch06 3 HVC3/07 2167 FTC-D6 FTC-D6-2 1/5 +162 C5 PMC5/Ch07 3 HVC3/07 2167 FTC-D6 FTC-D6-4 1/5 +163 C5 PMC5/Ch08 3 HVC3/07 2167 FTC-D6 FTC-D6-3 1/5 +164 C5 PMC5/Ch09 3 HVC3/09 2165 FTC-E6 FTC-E6-2 1/5 +165 C5 PMC5/Ch10 3 HVC3/09 2165 FTC-E6 FTC-E6-3 1/5 +166 C5 PMC5/Ch11 3 HVC3/09 2165 FTC-E6 FTC-E6-1 1/5 +167 C5 PMC5/Ch12 3 HVC3/09 2165 FTC-E6 FTC-E6-4 1/5 +168 C6 PMC6/Ch01 3 HVC3/04 2148 FTC-C5 FTC-C5-4 1/6 +169 C6 PMC6/Ch02 3 HVC3/04 2148 FTC-C5 FTC-C5-3 1/6 +170 C6 PMC6/Ch03 3 HVC3/04 2148 FTC-C5 FTC-C5-1 1/6 +171 C6 PMC6/Ch04 3 HVC3/04 2148 FTC-C5 FTC-C5-2 1/6 +172 C6 PMC6/Ch05 3 HVC3/05 2162 FTC-C6 FTC-C6-4 1/6 +173 C6 PMC6/Ch06 3 HVC3/05 2162 FTC-C6 FTC-C6-3 1/6 +174 C6 PMC6/Ch07 3 HVC3/05 2162 FTC-C6 FTC-C6-1 1/6 +175 C6 PMC6/Ch08 3 HVC3/05 2162 FTC-C6 FTC-C6-2 1/6 +176 C6 PMC6/Ch09 3 HVC3/03 2144 FTC-B6 FTC-B6-2 1/6 +177 C6 PMC6/Ch10 3 HVC3/03 2144 FTC-B6 FTC-B6-1 1/6 +178 C6 PMC6/Ch11 3 HVC3/03 2144 FTC-B6 FTC-B6-3 1/6 +179 C6 PMC6/Ch12 3 HVC3/03 2144 FTC-B6 FTC-B6-4 1/6 +180 C7 PMC7/Ch01 3 HVC3/02 2136 FTC-B4 FTC-B4-1 1/7 +181 C7 PMC7/Ch02 3 HVC3/02 2136 FTC-B4 FTC-B4-2 1/7 +182 C7 PMC7/Ch03 3 HVC3/02 2136 FTC-B4 FTC-B4-4 1/7 +183 C7 PMC7/Ch04 3 HVC3/02 2136 FTC-B4 FTC-B4-3 1/7 +184 C7 PMC7/Ch05 3 HVC3/00 2151 FTC-A4 FTC-A4-1 1/7 +185 C7 PMC7/Ch06 3 HVC3/00 2151 FTC-A4 FTC-A4-2 1/7 +186 C7 PMC7/Ch07 3 HVC3/00 2151 FTC-A4 FTC-A4-4 1/7 +187 C7 PMC7/Ch08 3 HVC3/00 2151 FTC-A4 FTC-A4-3 1/7 +188 C7 PMC7/Ch09 3 HVC3/01 2141 FTC-A5 FTC-A5-1 1/7 +189 C7 PMC7/Ch10 3 HVC3/01 2141 FTC-A5 FTC-A5-2 1/7 +190 C7 PMC7/Ch11 3 HVC3/01 2141 FTC-A5 FTC-A5-4 1/7 +191 C7 PMC7/Ch12 3 HVC3/01 2141 FTC-A5 FTC-A5-3 1/7 +192 C8 PMC8/Ch01 4 HVC4/00 2121 FTC-B2 FTC-B2-2 1/8 +193 C8 PMC8/Ch02 4 HVC4/00 2121 FTC-B2 FTC-B2-3 1/8 +194 C8 PMC8/Ch03 4 HVC4/00 2121 FTC-B2 FTC-B2-1 1/8 +195 C8 PMC8/Ch04 4 HVC4/00 2121 FTC-B2 FTC-B2-4 1/8 +196 C8 PMC8/Ch05 4 HVC4/01 2133 FTC-E2 FTC-E2-1 1/8 +197 C8 PMC8/Ch06 4 HVC4/01 2133 FTC-E2 FTC-E2-2 1/8 +198 C8 PMC8/Ch07 4 HVC4/01 2133 FTC-E2 FTC-E2-4 1/8 +199 C8 PMC8/Ch08 4 HVC4/01 2133 FTC-E2 FTC-E2-3 1/8 +200 C8 PMC8/Ch09 N/A N/A N/A N/A N/A 1/8 +201 C8 PMC8/Ch10 N/A N/A N/A N/A N/A 1/8 +202 C8 PMC8/Ch11 N/A N/A N/A N/A N/A 1/8 +203 C8 PMC8/Ch12 N/A N/A N/A N/A N/A 1/8 +204 C9 PMC9/Ch01 4 HVC4/02 2158 FTC-E5 FTC-E5-2 1/9 +205 C9 PMC9/Ch02 4 HVC4/02 2158 FTC-E5 FTC-E5-3 1/9 +206 C9 PMC9/Ch03 4 HVC4/02 2158 FTC-E5 FTC-E5-1 1/9 +207 C9 PMC9/Ch04 4 HVC4/02 2158 FTC-E5 FTC-E5-4 1/9 +208 C9 PMC9/Ch05 4 HVC4/03 2143 FTC-B5 FTC-B5-1 1/9 +209 C9 PMC9/Ch06 4 HVC4/03 2143 FTC-B5 FTC-B5-2 1/9 +210 C9 PMC9/Ch07 4 HVC4/03 2143 FTC-B5 FTC-B5-4 1/9 +211 C9 PMC9/Ch08 4 HVC4/03 2143 FTC-B5 FTC-B5-3 1/9 +212 C9 PMC9/Ch09 N/A N/A N/A N/A N/A 1/9 +213 C9 PMC9/Ch10 N/A N/A N/A N/A N/A 1/9 +214 C9 PMC9/Ch11 N/A N/A N/A N/A N/A 1/9 +215 C9 PMC9/Ch12 N/A N/A N/A N/A N/A 1/9 +216 A9 PMA9/Ch01 4 HVCM/12 N/A FT0-LCS FTA-LCS 0/9 +217 A9 PMA9/Ch02 4 HVCM/12 N/A FT0-LCS FTA-LCS-H 0/9 +218 A9 PMA9/Ch03 4 HVCM/12 N/A FT0-LCS FTC-LCS 0/9 +219 A9 PMA9/Ch04 4 HVCM/12 N/A FT0-LCS FTC-LCS-H 0/9 +220 A9 PMA9/Ch05 4 HVCM/12 N/A FT0-LCS FTA-LCS 0/9 +221 A9 PMA9/Ch06 4 HVCM/12 N/A FT0-LCS FTA-LCS-H 0/9 +222 A9 PMA9/Ch07 4 HVCM/12 N/A FT0-LCS FTC-LCS 0/9 +223 A9 PMA9/Ch08 4 HVCM/12 N/A FT0-LCS FTC-LCS-H 0/9 +224 A9 PMA9/Ch09 4 HVCM/12 N/A FT0-LCS FTA-LCS 0/9 +225 A9 PMA9/Ch10 4 HVCM/12 N/A FT0-LCS FTA-LCS-H 0/9 +226 A9 PMA9/Ch11 4 HVCM/12 N/A FT0-LCS FTC-LCS 0/9 +227 A9 PMA9/Ch12 4 HVCM/12 N/A FT0-LCS FTC-LCS-H 0/9 +228 A11 PMA11/Ch01 N/A N/A N/A N/A N/A 0/11 diff --git a/Detectors/FIT/FT0/raw/include/FT0Raw/DigitBlockFT0.h b/Detectors/FIT/FT0/raw/include/FT0Raw/DigitBlockFT0.h index 5e30321e0673a..25eda04ea5ff8 100644 --- a/Detectors/FIT/FT0/raw/include/FT0Raw/DigitBlockFT0.h +++ b/Detectors/FIT/FT0/raw/include/FT0Raw/DigitBlockFT0.h @@ -56,11 +56,11 @@ class DigitBlockFT0 : public DigitBlockBase static int sEventID; template - void processDigits(DataBlockType& dataBlock, int linkID) + void processDigits(DataBlockType& dataBlock, int linkID, int ep) { if constexpr (std::is_same::value) { //Filling data from PM for (int iEventData = 0; iEventData < dataBlock.DataBlockWrapper::mNelements; iEventData++) { - mVecChannelData.emplace_back(uint8_t(o2::ft0::SingleLUT::Instance().getChannel(linkID, dataBlock.DataBlockWrapper::mData[iEventData].channelID)), + mVecChannelData.emplace_back(uint8_t(o2::ft0::SingleLUT::Instance().getChannel(linkID, dataBlock.DataBlockWrapper::mData[iEventData].channelID, ep)), int(dataBlock.DataBlockWrapper::mData[iEventData].time), int(dataBlock.DataBlockWrapper::mData[iEventData].charge), dataBlock.DataBlockWrapper::mData[iEventData].getFlagWord()); @@ -148,11 +148,11 @@ class DigitBlockFT0ext : public DigitBlockBase static int sEventID; template - void processDigits(DataBlockType& dataBlock, int linkID) + void processDigits(DataBlockType& dataBlock, int linkID, int ep) { if constexpr (std::is_same::value) { //Filling data from PM for (int iEventData = 0; iEventData < dataBlock.DataBlockWrapper::mNelements; iEventData++) { - mVecChannelData.emplace_back(uint8_t(o2::ft0::SingleLUT::Instance().getChannel(linkID, dataBlock.DataBlockWrapper::mData[iEventData].channelID)), + mVecChannelData.emplace_back(uint8_t(o2::ft0::SingleLUT::Instance().getChannel(linkID, dataBlock.DataBlockWrapper::mData[iEventData].channelID, ep)), int(dataBlock.DataBlockWrapper::mData[iEventData].time), int(dataBlock.DataBlockWrapper::mData[iEventData].charge), dataBlock.DataBlockWrapper::mData[iEventData].getFlagWord()); diff --git a/Detectors/FIT/FT0/raw/include/FT0Raw/RawReaderFT0Base.h b/Detectors/FIT/FT0/raw/include/FT0Raw/RawReaderFT0Base.h index 810bcad5d60fd..8cc8110b8452f 100644 --- a/Detectors/FIT/FT0/raw/include/FT0Raw/RawReaderFT0Base.h +++ b/Detectors/FIT/FT0/raw/include/FT0Raw/RawReaderFT0Base.h @@ -41,21 +41,22 @@ namespace ft0 // Common raw reader for FT0 template -class RawReaderFT0Base : public RawReaderBase +class RawReaderFT0Base : public RawReaderBase { public: - typedef RawReaderBase RawReaderBaseType; + typedef RawReaderBase RawReaderBaseType; RawReaderFT0Base() = default; ~RawReaderFT0Base() = default; //deserialize payload to raw data blocks and proccesss them to digits - void process(int linkID, gsl::span payload) + void process(int linkID, gsl::span payload, int ep) { - if (0 <= linkID && linkID < 19) { + int linkTCM = 11; + if (0 <= linkID && linkID != linkTCM) { //PM data proccessing - RawReaderBaseType::template processBinaryData(payload, linkID); - } else if (linkID == 19) { + RawReaderBaseType::template processBinaryData(payload, linkID, ep); + } else if (linkID == linkTCM && ep == 0) { //TCM data proccessing - RawReaderBaseType::template processBinaryData(payload, linkID); + RawReaderBaseType::template processBinaryData(payload, linkID, ep); } else { //put here code in case of bad rdh.linkID value LOG(INFO) << "WARNING! WRONG LINK ID! " << linkID; diff --git a/Detectors/FIT/FT0/reconstruction/CMakeLists.txt b/Detectors/FIT/FT0/reconstruction/CMakeLists.txt index aeae53bb97777..568ccbb3587a0 100644 --- a/Detectors/FIT/FT0/reconstruction/CMakeLists.txt +++ b/Detectors/FIT/FT0/reconstruction/CMakeLists.txt @@ -36,3 +36,10 @@ o2_add_executable( COMPONENT_NAME ft0 SOURCES src/test-raw-conversion.cxx PUBLIC_LINK_LIBRARIES O2::FT0Reconstruction) + + +o2_add_executable( + test-raw2digit + COMPONENT_NAME ft0 + SOURCES src/test-raw2digit.cxx + PUBLIC_LINK_LIBRARIES O2::FT0Reconstruction) \ No newline at end of file diff --git a/Detectors/FIT/FT0/reconstruction/include/FT0Reconstruction/ReadRaw.h b/Detectors/FIT/FT0/reconstruction/include/FT0Reconstruction/ReadRaw.h index 8b4620c443711..5f33e3f34629b 100644 --- a/Detectors/FIT/FT0/reconstruction/include/FT0Reconstruction/ReadRaw.h +++ b/Detectors/FIT/FT0/reconstruction/include/FT0Reconstruction/ReadRaw.h @@ -43,7 +43,7 @@ class ReadRaw static constexpr int Nchannels_FT0 = 208; static constexpr int Nchannels_PM = 12; static constexpr int NPMs = 20; - static constexpr int LinkTCM = 19; + // static constexpr int LinkTCM = 19; static constexpr float MV_2_Nchannels = 2.2857143; //7 mV ->16channels static constexpr float CFD_NS_2_Nchannels = 76.804916; //1000.(ps)/13.02(channel); //static constexpr int GBTWORDSIZE = 80; //real size @@ -69,6 +69,7 @@ class ReadRaw char* mBuffer = nullptr; std::vector mBufferLocal; long mSize; + int mLinkTCM; std::map mDigitAccum; // digit accumulator template TBranch* getOrMakeBranch(TTree& tree, std::string brname, T* ptr) @@ -81,7 +82,7 @@ class ReadRaw return tree.Branch(brname.c_str(), ptr); } - ClassDefNV(ReadRaw, 1); + ClassDefNV(ReadRaw, 2); }; } // namespace ft0 diff --git a/Detectors/FIT/FT0/reconstruction/src/ReadRaw.cxx b/Detectors/FIT/FT0/reconstruction/src/ReadRaw.cxx index 485416db39007..e21d75ac05430 100644 --- a/Detectors/FIT/FT0/reconstruction/src/ReadRaw.cxx +++ b/Detectors/FIT/FT0/reconstruction/src/ReadRaw.cxx @@ -76,6 +76,7 @@ ReadRaw::ReadRaw(const std::string fileRaw, std::string fileDataOut) mFileDest.exceptions(std::ios_base::failbit | std::ios_base::badbit); mFileDest.open(fileRaw, std::fstream::in | std::fstream::binary); o2::ft0::LookUpTable lut{LookUpTable::readTable()}; + mLinkTCM = lut.getLink(lut.getTCMchannel()); ReadRaw::readData(fileRaw.c_str(), lut); ReadRaw::writeDigits(fileDataOut.data()); } @@ -98,6 +99,17 @@ void ReadRaw::readData(const std::string fileRaw, const o2::ft0::LookUpTable& lu mFileDest.seekg(0); LOG(DEBUG) << "SizeFile " << sizeFile; + for (int ilink = 0; ilink < 8; ilink++) { + for (int ich = 0; ich < 12; ich++) { + LOG(INFO) << " ep 0 " << ilink << " " << ich << " " << lut.getChannel(ilink, ich + 1, int(0)); + } + } + for (int ilink = 0; ilink < 10; ilink++) { + for (int ich = 0; ich < 12; ich++) { + LOG(INFO) << " ep 1 " << ilink << " " << ich << " " << lut.getChannel(ilink, ich + 1, int(1)); + } + } + // read content of infile long posInFile = 0; while (posInFile < sizeFile - sizeof(mRDH)) { @@ -111,6 +123,7 @@ void ReadRaw::readData(const std::string fileRaw, const o2::ft0::LookUpTable& lu int numPage = RDHUtils::getPageCounter(mRDH); int offset = RDHUtils::getOffsetToNext(mRDH); int link = RDHUtils::getLinkID(mRDH); + int ep = RDHUtils::getEndPointID(mRDH); if (nwords <= sizeof(mRDH)) { posInFile += RDHUtils::getOffsetToNext(mRDH); LOG(INFO) << " next RDH"; @@ -122,18 +135,18 @@ void ReadRaw::readData(const std::string fileRaw, const o2::ft0::LookUpTable& lu while (pos < nwords) { mFileDest.read(reinterpret_cast(&mEventHeader), sizeof(mEventHeader)); pos += sizeof(mEventHeader); - LOG(DEBUG) << "read header for " << link << "word " << (int)mEventHeader.nGBTWords << " orbit " << int(mEventHeader.orbit) << " BC " << int(mEventHeader.bc) << " pos " << pos << " posinfile " << posInFile; + LOG(DEBUG) << "read header for " << link << "word " << (int)mEventHeader.nGBTWords << " orbit " << int(mEventHeader.orbit) << " BC " << int(mEventHeader.bc) << " pos " << pos << " posinfile " << posInFile << " endPoint " << int(ep); o2::InteractionRecord intrec{uint16_t(mEventHeader.bc), uint32_t(mEventHeader.orbit)}; auto [digitIter, isNew] = mDigitAccum.try_emplace(intrec); if (isNew) { double eventTime = intrec.bc2ns(); - LOG(DEBUG) << "new intrec " << intrec.orbit << " " << intrec.bc << " link " << link; + LOG(INFO) << "new intrec " << intrec.orbit << " " << intrec.bc << " link " << link << " EP " << ep; o2::ft0::DigitsTemp& digit = digitIter->second; digit.setTime(eventTime); digit.setInteractionRecord(intrec); } chDgDataArr = &digitIter->second.getChDgData(); //&mDigitsTemp.getChDgData(); - if (link == LinkTCM) { + if (link == mLinkTCM) { mFileDest.read(reinterpret_cast(&mTCMdata), sizeof(mTCMdata)); pos += sizeof(mTCMdata); digitIter->second.setTriggers(Bool_t(mTCMdata.orA), Bool_t(mTCMdata.orC), Bool_t(mTCMdata.vertex), Bool_t(mTCMdata.sCen), Bool_t(mTCMdata.cen), uint8_t(mTCMdata.nChanA), uint8_t(mTCMdata.nChanC), int32_t(mTCMdata.amplA), int32_t(mTCMdata.amplC), int16_t(mTCMdata.timeA), int16_t(mTCMdata.timeC)); @@ -144,21 +157,21 @@ void ReadRaw::readData(const std::string fileRaw, const o2::ft0::LookUpTable& lu } for (int i = 0; i < mEventHeader.nGBTWords; ++i) { mFileDest.read(reinterpret_cast(&mEventData[2 * i]), o2::ft0::EventData::PayloadSizeFirstWord); - chDgDataArr->emplace_back(lut.getChannel(link, int(mEventData[2 * i].channelID)), + chDgDataArr->emplace_back(lut.getChannel(link, int(mEventData[2 * i].channelID), ep), int(mEventData[2 * i].time), int(mEventData[2 * i].charge), int(mEventData[2 * i].numberADC)); pos += o2::ft0::EventData::PayloadSizeFirstWord; - LOG(INFO) << " read 1st word channelID " << int(mEventData[2 * i].channelID) << " charge " << mEventData[2 * i].charge << " time " << mEventData[2 * i].time << " PM " << link << " lut channel " << lut.getChannel(link, int(mEventData[2 * i].channelID)) << " pos " << pos; + LOG(INFO) << " read 1st word channelID " << int(mEventData[2 * i].channelID) << " charge " << mEventData[2 * i].charge << " time " << mEventData[2 * i].time << " PM " << link << " lut channel " << lut.getChannel(link, int(mEventData[2 * i].channelID), ep) << " pos " << pos; mFileDest.read(reinterpret_cast(&mEventData[2 * i + 1]), EventData::PayloadSizeSecondWord); pos += o2::ft0::EventData::PayloadSizeSecondWord; - LOG(INFO) << "read 2nd word channel " << int(mEventData[2 * i + 1].channelID) << " charge " << int(mEventData[2 * i + 1].charge) << " time " << mEventData[2 * i + 1].time << " PM " << link << " lut channel " << lut.getChannel(link, int(mEventData[2 * i + 1].channelID)) << " pos " << pos; + LOG(INFO) << "read 2nd word channel " << int(mEventData[2 * i + 1].channelID) << " charge " << int(mEventData[2 * i + 1].charge) << " time " << mEventData[2 * i + 1].time << " PM " << link << " lut channel " << lut.getChannel(link, int(mEventData[2 * i + 1].channelID), ep) << " pos " << pos; if (mEventData[2 * i + 1].charge <= 0 && mEventData[2 * i + 1].channelID <= 0 && mEventData[2 * i + 1].time <= 0) { continue; } - chDgDataArr->emplace_back(lut.getChannel(link, int(mEventData[2 * i + 1].channelID)), + chDgDataArr->emplace_back(lut.getChannel(link, int(mEventData[2 * i + 1].channelID), ep), int(mEventData[2 * i + 1].time), int(mEventData[2 * i + 1].charge), int(mEventData[2 * i + 1].numberADC)); diff --git a/Detectors/FIT/FT0/reconstruction/src/test-raw2digit.cxx b/Detectors/FIT/FT0/reconstruction/src/test-raw2digit.cxx new file mode 100644 index 0000000000000..cb963083f3dce --- /dev/null +++ b/Detectors/FIT/FT0/reconstruction/src/test-raw2digit.cxx @@ -0,0 +1,119 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include +#include +#include "DetectorsCommonDataFormats/NameConf.h" +#include "Framework/Logger.h" +#include "DataFormatsFT0/Digit.h" +#include +#include + +using namespace o2::ft0; +int main() +{ + struct EventFT0_t { + o2::ft0::Digit mDigit; + std::vector mVecChannelData; + bool operator==(const EventFT0_t& other) const + { + return mDigit == other.mDigit && mVecChannelData == other.mVecChannelData; + } + void print() const + { + std::cout << std::endl; + std::cout << "------DIGITS--------\n"; + std::cout << "ref: " << mDigit.ref.getFirstEntry() << "|" << mDigit.ref.getEntries(); + std::cout << "\nbc-orbit: " << mDigit.mIntRecord.bc << "|" << mDigit.mIntRecord.orbit; + //std::cout<<"\nmEventStatus: "<< static_cast(mDigit.mEventStatus);//Excluded, init problem + std::cout << "\nTriggers\n"; + std::cout << "triggersignals: " << static_cast(mDigit.mTriggers.triggersignals); + std::cout << "\nnChanA: " << static_cast(mDigit.mTriggers.nChanA); + std::cout << "\nnChanC: " << static_cast(mDigit.mTriggers.nChanC); + std::cout << "\namplA: " << mDigit.mTriggers.amplA << std::endl; + std::cout << "amplC: " << mDigit.mTriggers.amplC << std::endl; + std::cout << "timeA: " << mDigit.mTriggers.timeA << std::endl; + std::cout << "timeC: " << mDigit.mTriggers.timeC << std::endl; + std::cout << "------CHANNEL DATA--------"; + for (const auto& entry : mVecChannelData) { + std::cout << "\nChId: " << static_cast(entry.ChId); + //std::cout<<"\nChainQTC: "<< static_cast(entry.ChainQTC);//Excluded, init problem + std::cout << "\nCFDTime: " << entry.CFDTime << std::endl; + std::cout << "QTCAmpl: " << entry.QTCAmpl << std::endl; + std::cout << "-------------------------"; + } + } + }; + std::vector vecTotalEvents, vecTotalEvents2; + gSystem->Exec("$O2_ROOT/bin/o2-sim -n 10 -m FT0 -g pythia8"); + gSystem->Exec("$O2_ROOT/bin/o2-sim-digitizer-workflow -b"); + TFile flIn("ft0digits.root"); + std::unique_ptr treeInput((TTree*)flIn.Get("o2sim")); + std::vector vecDigits; + std::vector* ptrVecDigits = &vecDigits; + std::vector vecChannelData; + std::vector* ptrVecChannelData = &vecChannelData; + treeInput->SetBranchAddress("FT0DIGITSBC", &ptrVecDigits); + treeInput->SetBranchAddress("FT0DIGITSCH", &ptrVecChannelData); + std::cout << "Tree nEntries:" << treeInput->GetEntries() << std::endl; + for (int iEvent = 0; iEvent < treeInput->GetEntries(); iEvent++) { //Iterating TFs in tree + treeInput->GetEntry(iEvent); + for (const auto& digit : (*ptrVecDigits)) { //Iterating over all digits in given TF + auto itBegin = ptrVecChannelData->begin(); + std::advance(itBegin, digit.ref.getFirstEntry()); + auto itEnd = ptrVecChannelData->begin(); + std::advance(itEnd, digit.ref.getFirstEntry() + digit.ref.getEntries()); + //Event within given TF + auto eventFT0 = EventFT0_t{digit, std::vector{itBegin, itEnd}}; + vecTotalEvents.push_back(eventFT0); + } + } + std::cout << "\n===================================\n"; + for (auto const& entry : vecTotalEvents) { + entry.print(); + } + std::cout << "\n===================================\n"; + + std::cout << "\nTOTAL EVENTS: " << vecTotalEvents.size() << std::endl; + std::cout << "Simulation completed!" << std::endl; + gSystem->Exec("$O2_ROOT/bin/o2-ft0-digi2raw --configKeyValues \"HBFUtils.nHBFPerTF=128;HBFUtils.orbitFirst=0\""); + gSystem->Exec("$O2_ROOT/bin/o2-raw-file-reader-workflow -b --input-conf FT0raw.cfg --configKeyValues \"HBFUtils.nHBFPerTF=128;HBFUtils.orbitFirst=0\"|$O2_ROOT/bin/o2-ft0-flp-dpl-workflow -b"); + TFile flIn2("o2_ft0digits.root"); + std::unique_ptr treeInput2((TTree*)flIn2.Get("o2sim")); + std::cout << "Reconstruction completed!" << std::endl; + + treeInput2->SetBranchAddress("FT0DIGITSBC", &ptrVecDigits); + treeInput2->SetBranchAddress("FT0DIGITSCH", &ptrVecChannelData); + std::cout << "Tree nEntries: " << treeInput2->GetEntries() << std::endl; + for (int iEvent = 0; iEvent < treeInput2->GetEntries(); iEvent++) { //Iterating TFs in tree + treeInput2->GetEntry(iEvent); + for (const auto& digit : (*ptrVecDigits)) { //Iterating over all digits in given TF + auto itBegin = ptrVecChannelData->begin(); + std::advance(itBegin, digit.ref.getFirstEntry()); + auto itEnd = ptrVecChannelData->begin(); + std::advance(itEnd, digit.ref.getFirstEntry() + digit.ref.getEntries()); + //Event within given TF + auto eventFT0 = EventFT0_t{digit, std::vector{itBegin, itEnd}}; + vecTotalEvents2.push_back(eventFT0); + } + } + std::cout << "\n===================================\n"; + for (auto const& entry : vecTotalEvents2) { + entry.print(); + } + std::cout << "\n===================================\n"; + std::cout << "\nTOTAL EVENTS: " << vecTotalEvents2.size() << std::endl; + if (vecTotalEvents == vecTotalEvents2) { + std::cout << "TEST IS OK!\n"; + } else { + std::cout << "ERROR!\n"; + } + return 0; +} diff --git a/Detectors/FIT/FT0/simulation/include/FT0Simulation/Digits2Raw.h b/Detectors/FIT/FT0/simulation/include/FT0Simulation/Digits2Raw.h index 0f7838ea55069..d4c16d0587098 100644 --- a/Detectors/FIT/FT0/simulation/include/FT0Simulation/Digits2Raw.h +++ b/Detectors/FIT/FT0/simulation/include/FT0Simulation/Digits2Raw.h @@ -42,7 +42,6 @@ class Digits2Raw static constexpr int Nchannels_FT0 = 208; static constexpr int Nchannels_PM = 12; - static constexpr int LinkTCM = 19; static constexpr int NPMs = 20; static constexpr int GBTWordSize = 128; // with padding static constexpr int Max_Page_size = 8192; @@ -80,10 +79,11 @@ class Digits2Raw uint16_t mCruID = 0; uint32_t mEndPointID = 0; uint64_t mFeeID = 0; + int mLinkTCM; ///////////////////////////////////////////////// - ClassDefNV(Digits2Raw, 1); + ClassDefNV(Digits2Raw, 2); }; } // namespace ft0 diff --git a/Detectors/FIT/FT0/simulation/src/Digits2Raw.cxx b/Detectors/FIT/FT0/simulation/src/Digits2Raw.cxx index 3eee46af097cb..ed10600a7df46 100644 --- a/Detectors/FIT/FT0/simulation/src/Digits2Raw.cxx +++ b/Detectors/FIT/FT0/simulation/src/Digits2Raw.cxx @@ -95,21 +95,33 @@ void Digits2Raw::readDigits(const std::string& outDir, const std::string& fileDi } */ o2::ft0::LookUpTable lut{o2::ft0::LookUpTable::readTable()}; + mLinkTCM = lut.getLink(lut.getTCMchannel()); LOG(INFO) << " ##### LookUp set "; - std::string outd = outDir; if (outd.back() != '/') { outd += '/'; } using namespace o2::raw; - for (int ilink = 0; ilink < NPMs; ++ilink) { - mLinkID = uint32_t(ilink); - mFeeID = uint64_t(ilink); - mCruID = uint16_t(0); - mEndPointID = uint32_t(0); + for (int ilink = 0; ilink < NPMs - 1; ++ilink) { + if (ilink < 8) { + mLinkID = uint32_t(ilink); + mCruID = uint16_t(0); + mEndPointID = uint32_t(0); + mFeeID = uint64_t(ilink); + } else { + mLinkID = uint32_t(ilink) - 8; + mCruID = uint16_t(0); + mEndPointID = uint32_t(1); + mFeeID = uint64_t(ilink); + } std::string outFileLink = mOutputPerLink ? o2::utils::concat_string(outDir, "ft0_link", std::to_string(ilink), ".raw") : o2::utils::concat_string(outDir, "ft0.raw"); mWriter.registerLink(mFeeID, mCruID, mLinkID, mEndPointID, outFileLink); + LOG(INFO) << " registered links " << mLinkID << " endpoint " << mEndPointID; } + //TCM + std::string outFileLink = mOutputPerLink ? o2::utils::concat_string(outDir, "ft0_link", std::to_string(mLinkTCM), ".raw") : o2::utils::concat_string(outDir, "ft0.raw"); + mWriter.registerLink(mLinkTCM + 8, mCruID, mLinkTCM, 0, outFileLink); + LOG(INFO) << " registered link TCM " << mLinkTCM; TFile* fdig = TFile::Open(fileDigitsName.data()); assert(fdig != nullptr); @@ -151,14 +163,16 @@ void Digits2Raw::convertDigits(o2::ft0::Digit bcdigits, // check empty event int oldlink = -1; + int oldendpoint = -1; int nchannels = 0; int nch = pmchannels.size(); for (int ich = 0; ich < nch; ich++) { int nlink = lut.getLink(pmchannels[ich].ChId); + int ep = lut.getEP(pmchannels[ich].ChId); if (nlink != oldlink) { if (oldlink >= 0) { uint nGBTWords = uint((nchannels + 1) / 2); - LOG(DEBUG) << " oldlink " << oldlink << " nGBTWords " << nGBTWords; + LOG(INFO) << " oldlink " << oldlink << " old EP " << oldendpoint << " nGBTWords " << nGBTWords << " new link " << nlink << " ep " << ep; if ((nchannels % 2) == 1) { mRawEventData.mEventData[nchannels] = {}; } @@ -166,12 +180,18 @@ void Digits2Raw::convertDigits(o2::ft0::Digit bcdigits, auto data = mRawEventData.to_vector(false); mLinkID = uint32_t(oldlink); mFeeID = uint64_t(oldlink); + mEndPointID = uint32_t(oldendpoint); + if (mEndPointID == 1) { + mFeeID += 8; + } + LOG(INFO) << " new link start " << mFeeID << " " << mCruID << " " << mLinkID << " " << mEndPointID; mWriter.addData(mFeeID, mCruID, mLinkID, mEndPointID, intRecord, data); } oldlink = nlink; + oldendpoint = ep; mRawEventData.mEventHeader = makeGBTHeader(nlink, intRecord); nchannels = 0; - LOG(DEBUG) << " switch to new link " << nlink; + LOG(INFO) << " switch to new link " << nlink << " EP " << ep; } auto& newData = mRawEventData.mEventData[nchannels]; bool isAside = (pmchannels[ich].ChId < 96); @@ -179,7 +199,8 @@ void Digits2Raw::convertDigits(o2::ft0::Digit bcdigits, newData.time = pmchannels[ich].CFDTime; newData.generateFlags(); newData.channelID = lut.getMCP(pmchannels[ich].ChId); - LOG(DEBUG) << "packed GBT " << nlink << " channelID " << (int)newData.channelID << " charge " << newData.charge << " time " << newData.time << " chain " << int(newData.numberADC) << " size " << sizeof(newData); + LOG(DEBUG) << " ID " << int(pmchannels[ich].ChId) << " packed GBT " << nlink << " channelID " << (int)newData.channelID << " charge " << newData.charge << " time " << newData.time << " chain " << int(newData.numberADC) + << " size " << sizeof(newData) << " mEndPointID " << ep; nchannels++; } // fill mEventData[nchannels] with 0s to flag that this is a dummy data @@ -191,10 +212,14 @@ void Digits2Raw::convertDigits(o2::ft0::Digit bcdigits, auto datalast = mRawEventData.to_vector(false); mLinkID = uint32_t(oldlink); mFeeID = uint64_t(oldlink); + mEndPointID = uint32_t(oldendpoint); + if (mEndPointID == 1) { + mFeeID += 8; + } mWriter.addData(mFeeID, mCruID, mLinkID, mEndPointID, intRecord, datalast); - LOG(DEBUG) << " last " << oldlink; + LOG(DEBUG) << " last " << mFeeID << " " << mCruID << " " << mLinkID << " " << mEndPointID; //TCM - mRawEventData.mEventHeader = makeGBTHeader(LinkTCM, intRecord); //TCM + mRawEventData.mEventHeader = makeGBTHeader(mLinkTCM, intRecord); //TCM mRawEventData.mEventHeader.nGBTWords = 1; auto& tcmdata = mRawEventData.mTCMdata; mTriggers = bcdigits.getTriggers(); @@ -218,25 +243,27 @@ void Digits2Raw::convertDigits(o2::ft0::Digit bcdigits, tcmdata.amplC = ampC; tcmdata.timeA = mTriggers.timeA; tcmdata.timeC = mTriggers.timeC; - LOG(DEBUG) << " TCM triggers read " - << " time A " << mTriggers.timeA << " time C " << mTriggers.timeC - << " amp A " << ampA << " amp C " << ampC - << " N A " << int(mTriggers.nChanA) << " N C " << int(mTriggers.nChanC) - << " trig " - << " ver " << mTriggers.getVertex() << " A " << mTriggers.getOrA() << " C " << mTriggers.getOrC(); + LOG(INFO) << " TCM triggers read " + << " time A " << mTriggers.timeA << " time C " << mTriggers.timeC + << " amp A " << ampA << " amp C " << ampC + << " N A " << int(mTriggers.nChanA) << " N C " << int(mTriggers.nChanC) + << " trig " + << " ver " << mTriggers.getVertex() << " A " << mTriggers.getOrA() << " C " << mTriggers.getOrC(); - LOG(DEBUG) << "TCMdata" - << " time A " << tcmdata.timeA << " time C " << tcmdata.timeC - << " amp A " << tcmdata.amplA << " amp C " << tcmdata.amplC - << " N A " << int(tcmdata.nChanA) << " N C " << int(tcmdata.nChanC) - << " trig " - << " ver " << tcmdata.vertex << " A " << tcmdata.orA << " C " << tcmdata.orC - << " size " << sizeof(tcmdata); + LOG(INFO) << "TCMdata" + << " time A " << tcmdata.timeA << " time C " << tcmdata.timeC + << " amp A " << tcmdata.amplA << " amp C " << tcmdata.amplC + << " N A " << int(tcmdata.nChanA) << " N C " << int(tcmdata.nChanC) + << " trig " + << " ver " << tcmdata.vertex << " A " << tcmdata.orA << " C " << tcmdata.orC + << " size " << sizeof(tcmdata); auto data = mRawEventData.to_vector(1); - mLinkID = uint32_t(LinkTCM); - mFeeID = uint64_t(LinkTCM); + mLinkID = uint32_t(mLinkTCM); + mFeeID = uint64_t(mLinkTCM) + 8; + mEndPointID = 0; mWriter.addData(mFeeID, mCruID, mLinkID, mEndPointID, intRecord, data); + LOG(DEBUG) << " TCM " << mFeeID << " " << mCruID << " " << mLinkID << " " << mEndPointID; } //_____________________________________________________________________________________ diff --git a/Detectors/FIT/FT0/workflow/include/FT0Workflow/FT0DataReaderDPLSpec.h b/Detectors/FIT/FT0/workflow/include/FT0Workflow/FT0DataReaderDPLSpec.h index 3925995bab968..c69e4b838006a 100644 --- a/Detectors/FIT/FT0/workflow/include/FT0Workflow/FT0DataReaderDPLSpec.h +++ b/Detectors/FIT/FT0/workflow/include/FT0Workflow/FT0DataReaderDPLSpec.h @@ -12,7 +12,7 @@ #ifndef O2_FT0DATAREADERDPLSPEC_H #define O2_FT0DATAREADERDPLSPEC_H - +#include "DataFormatsFT0/LookUpTable.h" #include "Framework/DataProcessorSpec.h" #include "Framework/Task.h" #include "Framework/CallbackService.h" @@ -23,7 +23,7 @@ #include "Framework/WorkflowSpec.h" #include "Framework/SerializationMethods.h" #include "DPLUtils/DPLRawParser.h" - +#include "Framework/InputRecordWalker.h" #include #include #include @@ -40,36 +40,54 @@ class FT0DataReaderDPLSpec : public Task FT0DataReaderDPLSpec(const RawReader& rawReader) : mRawReader(rawReader) {} FT0DataReaderDPLSpec() = default; ~FT0DataReaderDPLSpec() override = default; - void init(InitContext& ic) final {} + typedef RawReader RawReader_t; + void init(InitContext& ic) final { o2::ft0::SingleLUT::Instance().printFullMap(); } void run(ProcessingContext& pc) final { - DPLRawParser parser(pc.inputs()); - mRawReader.clear(); - LOG(INFO) << "FT0DataReaderDPLSpec"; - uint64_t count = 0; + // if we see requested data type input with 0xDEADBEEF subspec and 0 payload this means that the "delayed message" + // mechanism created it in absence of real data from upstream. Processor should send empty output to not block the workflow + { + std::vector dummy{InputSpec{"dummy", ConcreteDataMatcher{o2::header::gDataOriginFT0, o2::header::gDataDescriptionRawData, 0xDEADBEEF}}}; + for (const auto& ref : InputRecordWalker(pc.inputs(), dummy)) { + const auto dh = o2::framework::DataRefUtils::getHeader(ref); + if (dh->payloadSize == 0) { + LOGP(WARNING, "Found input [{}/{}/{:#x}] TF#{} 1st_orbit:{} Payload {} : assuming no payload for all links in this TF", + dh->dataOrigin.str, dh->dataDescription.str, dh->subSpecification, dh->tfCounter, dh->firstTForbit, dh->payloadSize); + return; + } + } + } + std::vector filter{InputSpec{"filter", ConcreteDataTypeMatcher{o2::header::gDataOriginFT0, o2::header::gDataDescriptionRawData}, Lifetime::Timeframe}}; + DPLRawParser parser(pc.inputs(), filter); + std::size_t count = 0; for (auto it = parser.begin(), end = parser.end(); it != end; ++it) { //Proccessing each page count++; auto rdhPtr = it.get_if(); gsl::span payload(it.data(), it.size()); - mRawReader.process(rdhPtr->linkID, payload); + mRawReader.process(rdhPtr->linkID, payload, rdhPtr->endPointID); } LOG(INFO) << "Pages: " << count; mRawReader.accumulateDigits(); mRawReader.makeSnapshot(pc); + mRawReader.clear(); } - RawReader mRawReader; + RawReader_t mRawReader; }; template -framework::DataProcessorSpec getFT0DataReaderDPLSpec(const RawReader& rawReader) +framework::DataProcessorSpec getFT0DataReaderDPLSpec(const RawReader& rawReader, bool askSTFDist) { LOG(INFO) << "DataProcessorSpec initDataProcSpec() for RawReaderFT0"; std::vector outputSpec; RawReader::prepareOutputSpec(outputSpec); + std::vector inputSpec{{"STF", ConcreteDataTypeMatcher{o2::header::gDataOriginFT0, "RAWDATA"}, Lifetime::Optional}}; + if (askSTFDist) { + inputSpec.emplace_back("STFDist", "FLP", "DISTSUBTIMEFRAME", 0, Lifetime::Timeframe); + } return DataProcessorSpec{ "ft0-datareader-dpl", - o2::framework::select("TF:FT0/RAWDATA"), + inputSpec, outputSpec, adaptFromTask>(rawReader), Options{}}; diff --git a/Detectors/FIT/FT0/workflow/include/FT0Workflow/FT0Workflow.h b/Detectors/FIT/FT0/workflow/include/FT0Workflow/FT0Workflow.h index f2cd562af2e02..995d2157c39e5 100644 --- a/Detectors/FIT/FT0/workflow/include/FT0Workflow/FT0Workflow.h +++ b/Detectors/FIT/FT0/workflow/include/FT0Workflow/FT0Workflow.h @@ -21,7 +21,7 @@ namespace ft0 { framework::WorkflowSpec getFT0Workflow(bool isExtendedMode, bool useProcess, bool dumpProcessor, bool dumpReader, - bool disableRootOut); + bool disableRootOut, bool askSTFDist); } // namespace ft0 } // namespace o2 #endif diff --git a/Detectors/FIT/FT0/workflow/include/FT0Workflow/RawReaderFT0.h b/Detectors/FIT/FT0/workflow/include/FT0Workflow/RawReaderFT0.h index bd0e99b7e2978..472d0518418a7 100644 --- a/Detectors/FIT/FT0/workflow/include/FT0Workflow/RawReaderFT0.h +++ b/Detectors/FIT/FT0/workflow/include/FT0Workflow/RawReaderFT0.h @@ -92,12 +92,13 @@ class RawReaderFT0 : public RawReaderFT0BaseNorm }; //Extended TCM mode (additional raw data struct) +template class RawReaderFT0ext : public RawReaderFT0BaseExt { public: RawReaderFT0ext(bool dumpData) : mDumpData(dumpData) {} RawReaderFT0ext(const RawReaderFT0ext&) = default; - + static constexpr bool sUseTrgInput = useTrgInput; RawReaderFT0ext() = default; ~RawReaderFT0ext() = default; void clear() @@ -105,10 +106,17 @@ class RawReaderFT0ext : public RawReaderFT0BaseExt mVecDigitsExt.clear(); mVecChannelData.clear(); mVecTrgExt.clear(); + if constexpr (sUseTrgInput) { + mVecTriggerInput.clear(); + } } void accumulateDigits() { - getDigits(mVecDigitsExt, mVecChannelData, mVecTrgExt); + if constexpr (sUseTrgInput) { + getDigits(mVecDigitsExt, mVecChannelData, mVecTrgExt, mVecTriggerInput); + } else { + getDigits(mVecDigitsExt, mVecChannelData, mVecTrgExt); + } LOG(INFO) << "Number of Digits: " << mVecDigitsExt.size(); LOG(INFO) << "Number of ChannelData: " << mVecChannelData.size(); LOG(INFO) << "Number of TriggerExt: " << mVecTrgExt.size(); @@ -121,17 +129,24 @@ class RawReaderFT0ext : public RawReaderFT0BaseExt outputSpec.emplace_back(o2::header::gDataOriginFT0, "DIGITSBC", 0, o2::framework::Lifetime::Timeframe); outputSpec.emplace_back(o2::header::gDataOriginFT0, "DIGITSCH", 0, o2::framework::Lifetime::Timeframe); outputSpec.emplace_back(o2::header::gDataOriginFT0, "DIGITSTRGEXT", 0, o2::framework::Lifetime::Timeframe); + if constexpr (sUseTrgInput) { + outputSpec.emplace_back(o2::header::gDataOriginFT0, "TRIGGERINPUT", 0, o2::framework::Lifetime::Timeframe); + } } void makeSnapshot(o2::framework::ProcessingContext& pc) { pc.outputs().snapshot(o2::framework::Output{o2::header::gDataOriginFT0, "DIGITSBC", 0, o2::framework::Lifetime::Timeframe}, mVecDigitsExt); pc.outputs().snapshot(o2::framework::Output{o2::header::gDataOriginFT0, "DIGITSCH", 0, o2::framework::Lifetime::Timeframe}, mVecChannelData); pc.outputs().snapshot(o2::framework::Output{o2::header::gDataOriginFT0, "DIGITSTRGEXT", 0, o2::framework::Lifetime::Timeframe}, mVecTrgExt); + if constexpr (sUseTrgInput) { + pc.outputs().snapshot(o2::framework::Output{o2::header::gDataOriginFT0, "TRIGGERINPUT", 0, o2::framework::Lifetime::Timeframe}, mVecTriggerInput); + } } bool mDumpData; std::vector mVecDigitsExt; std::vector mVecChannelData; std::vector mVecTrgExt; + std::vector mVecTriggerInput; }; } // namespace ft0 diff --git a/Detectors/FIT/FT0/workflow/src/FT0Workflow.cxx b/Detectors/FIT/FT0/workflow/src/FT0Workflow.cxx index 0655f067805a5..7634e0aa2997a 100644 --- a/Detectors/FIT/FT0/workflow/src/FT0Workflow.cxx +++ b/Detectors/FIT/FT0/workflow/src/FT0Workflow.cxx @@ -22,14 +22,14 @@ namespace ft0 framework::WorkflowSpec getFT0Workflow(bool isExtendedMode, bool useProcess, bool dumpProcessor, bool dumpReader, - bool disableRootOut) + bool disableRootOut, bool askSTFDist) { LOG(INFO) << "framework::WorkflowSpec getFT0Workflow"; framework::WorkflowSpec specs; if (isExtendedMode) { - specs.emplace_back(o2::ft0::getFT0DataReaderDPLSpec(RawReaderFT0ext{dumpReader})); + specs.emplace_back(o2::ft0::getFT0DataReaderDPLSpec(RawReaderFT0ext{dumpReader}, askSTFDist)); } else { - specs.emplace_back(o2::ft0::getFT0DataReaderDPLSpec(RawReaderFT0{dumpReader})); + specs.emplace_back(o2::ft0::getFT0DataReaderDPLSpec(RawReaderFT0{dumpReader}, askSTFDist)); } if (useProcess) { specs.emplace_back(o2::ft0::getFT0DataProcessDPLSpec(dumpProcessor)); diff --git a/Detectors/FIT/FT0/workflow/src/ft0-flp-workflow.cxx b/Detectors/FIT/FT0/workflow/src/ft0-flp-workflow.cxx index 4cbbb8ca35471..cd846a5141dc8 100644 --- a/Detectors/FIT/FT0/workflow/src/ft0-flp-workflow.cxx +++ b/Detectors/FIT/FT0/workflow/src/ft0-flp-workflow.cxx @@ -46,6 +46,7 @@ void customize(std::vector& workflowOptions) o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}); + workflowOptions.push_back(ConfigParamSpec{"ignore-dist-stf", VariantType::Bool, false, {"do not subscribe to FLP/DISTSUBTIMEFRAME/0 message (no lost TF recovery)"}}); } // ------------------------------------------------------------------ @@ -60,6 +61,7 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) auto dumpReader = configcontext.options().get("dump-blocks-reader"); auto isExtendedMode = configcontext.options().get("tcm-extended-mode"); auto disableRootOut = configcontext.options().get("disable-root-output"); + auto askSTFDist = !configcontext.options().get("ignore-dist-stf"); LOG(INFO) << "WorkflowSpec FLPWorkflow"; - return std::move(o2::ft0::getFT0Workflow(isExtendedMode, useProcessor, dumpProcessor, dumpReader, disableRootOut)); + return std::move(o2::ft0::getFT0Workflow(isExtendedMode, useProcessor, dumpProcessor, dumpReader, disableRootOut, askSTFDist)); } diff --git a/Detectors/FIT/macros/uploadLookUpTable.C b/Detectors/FIT/macros/uploadLookUpTable.C index b00dc587532a4..c07162b9fa4ea 100644 --- a/Detectors/FIT/macros/uploadLookUpTable.C +++ b/Detectors/FIT/macros/uploadLookUpTable.C @@ -8,29 +8,31 @@ #include #include -o2::ft0::HVchannel::HVBoard readHVBoard(std::string_view str); -o2::ft0::Topo read_Topo(std::string_view str); +//o2::ft0::HVchannel::HVBoard readHVBoard(std::string_view str); void uploadLookUpTable() { using o2::ccdb::BasicCCDBManager; using o2::ccdb::CcdbApi; + using namespace o2::ft0; - // std::ifstream f{filename.data()}; - std::ifstream f{"FT0ChannelsTable.txt"}; + std::ifstream f{"/home/alla/aliO2/O2/Detectors/FIT/FT0/base/files/FT0ChannelsTable.02.0.4.2021.txt"}; int channel; - std::string pm, pm_channel, hv_board, hv_channel, mcp_sn, hv_cable, signal_cable; + std::string pm, pm_channel, hv_board, hv_channel, mcp_sn, hv_cable, signal_cable, ep_PM; std::vector table; std::getline(f, pm); // skip one line - while (f >> channel >> pm >> pm_channel >> hv_board >> hv_channel >> mcp_sn >> hv_cable >> signal_cable) { + std::string line; + while (std::getline(f, line) && (std::istringstream(line) >> channel >> pm >> pm_channel >> hv_board >> hv_channel >> mcp_sn >> hv_cable >> signal_cable >> ep_PM)) { o2::ft0::HVchannel chan; chan.channel = channel; assert(std::string_view(pm_channel).substr(2, 2) == pm); chan.pm = read_Topo(pm_channel); - chan.HV_board = readHVBoard(hv_board); + chan.HV_board = hv_board; //readHVBoard(hv_board); chan.MCP_SN = mcp_sn; chan.HV_cabel = hv_cable; chan.signal_cable = signal_cable; + chan.EP = ep_PM; + LOG(INFO) << "read channel " << int(chan.channel); table.emplace_back(chan); } CcdbApi api; @@ -39,7 +41,7 @@ void uploadLookUpTable() // store abitrary user object in strongly typed manner api.storeAsTFileAny(&table, "FT0/LookUpTable", metadata); } - +/* o2::ft0::HVchannel::HVBoard readHVBoard(std::string_view str) { using HVBoard = o2::ft0::HVchannel::HVBoard; @@ -59,13 +61,4 @@ o2::ft0::HVchannel::HVBoard readHVBoard(std::string_view str) std::cerr << "Unknown HVBoard " << str << "\n"; std::abort(); } -} -o2::ft0::Topo read_Topo(std::string_view str) -{ - assert(str.substr(0, 2) == "PM" && str[4] == '/' && str[5] == 'C' && str[6] == 'h'); - char side = str[2]; - uint8_t pm_num = str[3] - '0'; - uint8_t pm_ch = (str[7] - '0') * 10 + (str[8] - '0'); - assert(side == 'A' || side == 'C'); - return {(side == 'C' ? 10 : 0) + pm_num, pm_ch}; -} +*/ diff --git a/Detectors/FIT/raw/include/FITRaw/DataBlockBase.h b/Detectors/FIT/raw/include/FITRaw/DataBlockBase.h index f18e3db24e154..9753bc60c5aef 100644 --- a/Detectors/FIT/raw/include/FITRaw/DataBlockBase.h +++ b/Detectors/FIT/raw/include/FITRaw/DataBlockBase.h @@ -40,6 +40,7 @@ #include #include #include "CommonDataFormat/InteractionRecord.h" +#include "Headers/RAWDataHeader.h" #include #include #include @@ -49,7 +50,7 @@ #include #include #include - +#include namespace o2 { namespace fit @@ -57,14 +58,74 @@ namespace fit using namespace std; +static constexpr size_t SIZE_WORD = 16; // should be changed to gloabal variable +static constexpr size_t SIZE_MAX_PAGE = 8192; // should be changed to gloabal variable +static constexpr size_t SIZE_MAX_PAYLOAD = SIZE_MAX_PAGE - sizeof(o2::header::RAWDataHeader); // should be changed to gloabal variable + template +struct DataBlockHelper { + template + struct CheckTypeMaxNelem : std::false_type { + }; + template + struct CheckTypeMaxNelem::value>> : std::true_type { + }; + + template + struct CheckTypeMinNelem : std::false_type { + }; + template + struct CheckTypeMinNelem::value>> : std::true_type { + }; + + template + struct CheckTypePayloadSize : std::false_type { + }; + template + struct CheckTypePayloadSize::value>> : std::true_type { + }; + + template + struct CheckTypePayloadPerGBTword : std::false_type { + }; + template + struct CheckTypePayloadPerGBTword::value>> : std::true_type { + }; + + template + struct CheckMaxElemSize : std::false_type { + }; + template + struct CheckMaxElemSize> : std::true_type { + }; + + template + struct CheckNelemRange : std::false_type { + }; + template + struct CheckNelemRange= T::MinNelements)>> : std::true_type { + }; + + static constexpr bool check() + { + static_assert(CheckTypeMaxNelem::value, "Error! MaxNelements type should be \"static constexpr std::size_t\"!"); + static_assert(CheckTypeMinNelem::value, "Error! MinNelements type should be \"static constexpr std::size_t\"!"); + static_assert(CheckTypePayloadSize::value, "Error! PayloadSize type should be \"static constexpr std::size_t\"!"); + static_assert(CheckTypePayloadPerGBTword::value, "Error! PayloadPerGBTword type should be \"static constexpr std::size_t\"!"); + static_assert(CheckMaxElemSize::value, "Error! Check maximum number of elements, they are larger than payload size!"); + static_assert(CheckNelemRange::value, "Error! Check range for number of elements, max should be bigger or equal to min!"); + return CheckTypeMaxNelem::value && CheckTypeMinNelem::value && CheckTypePayloadSize::value && CheckTypePayloadPerGBTword::value && CheckMaxElemSize::value && CheckNelemRange::value; + } +}; + +template ::check()>> struct DataBlockWrapper { DataBlockWrapper() = default; DataBlockWrapper(const DataBlockWrapper&) = default; - static constexpr size_t sizeWord = 16; // should be changed to gloabal variable - std::vector serialize(int nWords) + + std::vector serialize(size_t nWords) { - std::vector vecBytes(sizeWord * nWords); + std::vector vecBytes(SIZE_WORD * nWords); uint8_t* srcAddress = (uint8_t*)mData; if (nWords == 0 || nWords > MaxNwords) { return std::move(vecBytes); @@ -83,7 +144,7 @@ struct DataBlockWrapper { { mNelements = 0; mNwords = 0; - if (nWords < MinNwords || nWords > MaxNwords || inputBytes.size() - srcPos < nWords * sizeWord) { + if (nWords < MinNwords || nWords > MaxNwords || inputBytes.size() - srcPos < nWords * SIZE_WORD) { //in case of bad fields responsible for deserialization logic, byte position will be pushed to the end of binary sequence srcPos = inputBytes.size(); mIsIncorrect = true; @@ -98,14 +159,14 @@ struct DataBlockWrapper { memcpy(destAddress + std::get(sByteLookupTable[iStep]), inputBytes.data() + std::get(sByteLookupTable[iStep]) + srcPos, std::get(sByteLookupTable[iStep])); countBytes += std::get(sByteLookupTable[iStep]); } - srcPos += mNwords * sizeWord; + srcPos += mNwords * SIZE_WORD; } static constexpr int MaxNwords = T::PayloadSize * T::MaxNelements / T::PayloadPerGBTword + (T::PayloadSize * T::MaxNelements % T::PayloadPerGBTword > 0); //calculating max GBT words per block - static constexpr int MaxNbytes = sizeWord * MaxNwords; + static constexpr int MaxNbytes = SIZE_WORD * MaxNwords; static constexpr int MinNwords = T::PayloadSize * T::MinNelements / T::PayloadPerGBTword + (T::PayloadSize * T::MinNelements % T::PayloadPerGBTword > 0); //calculating min GBT words per block - static constexpr int MinNbytes = sizeWord * MinNwords; + static constexpr int MinNbytes = SIZE_WORD * MinNwords; //get number of byte reading steps static constexpr size_t getNsteps() @@ -158,7 +219,7 @@ struct DataBlockWrapper { size_t srcBytePos = 0; size_t payloadFull = T::MaxNelements * T::PayloadSize; - size_t bytesInWord = sizeWord; + size_t bytesInWord = SIZE_WORD; size_t payloadInWord = T::PayloadPerGBTword; size_t payloadPerElem = T::PayloadSize; @@ -205,7 +266,7 @@ struct DataBlockWrapper { destBytePosPerElem = countElement * sizeof(T); } if (bytesInWord == 0) { - bytesInWord = sizeWord; + bytesInWord = SIZE_WORD; countWord++; } } diff --git a/Detectors/FIT/raw/include/FITRaw/DigitBlockBase.h b/Detectors/FIT/raw/include/FITRaw/DigitBlockBase.h index 5fd2d2738c8d8..8c9b8dfabe89b 100644 --- a/Detectors/FIT/raw/include/FITRaw/DigitBlockBase.h +++ b/Detectors/FIT/raw/include/FITRaw/DigitBlockBase.h @@ -37,9 +37,9 @@ class DigitBlockBase //:public DigitBlock DigitBlockBase(const DigitBlockBase& other) = default; ~DigitBlockBase() = default; template - void process(DataBlockType& dataBlock, int linkID) + void process(DataBlockType& dataBlock, int linkID, int ep) { - static_cast(this)->processDigits(dataBlock, linkID); + static_cast(this)->processDigits(dataBlock, linkID, ep); } template void pop(std::vector&... vecDigits) diff --git a/Detectors/FIT/raw/include/FITRaw/RawReaderBase.h b/Detectors/FIT/raw/include/FITRaw/RawReaderBase.h index b0e75db3eacc9..b6a30c6a4ce1b 100644 --- a/Detectors/FIT/raw/include/FITRaw/RawReaderBase.h +++ b/Detectors/FIT/raw/include/FITRaw/RawReaderBase.h @@ -18,8 +18,15 @@ #ifndef ALICEO2_FIT_RAWREADERBASE_H_ #define ALICEO2_FIT_RAWREADERBASE_H_ #include +#include #include #include +#include + +#include +#include +#include +#include #include #include @@ -31,29 +38,35 @@ namespace o2 { namespace fit { -template +template class RawReaderBase { public: RawReaderBase() = default; ~RawReaderBase() = default; - + typedef boost::mpl::vector VecDataBlocks_t; + std::tuple...> mTupleVecDataBlocks; std::map mMapDigits; - + template + constexpr std::vector& getVecDataBlocks() + { + typedef typename boost::mpl::find::type it_t; + return std::get(mTupleVecDataBlocks); + } //decoding binary data into data blocks template size_t decodeBlocks(const gsl::span binaryPayload, std::vector& vecDataBlocks) { size_t srcPos = 0; - while (srcPos < binaryPayload.size()) { //checking element - DataBlockType dataBlock{}; - dataBlock.decodeBlock(binaryPayload, srcPos); - srcPos += dataBlock.mSize; - if (dataBlock.isCorrect()) { - vecDataBlocks.push_back(dataBlock); //change to in-place construction? TODO - } else { - LOG(WARNING) << "INCORRECT DATA BLOCK! Byte position: " << srcPos - dataBlock.mSize << " | " << binaryPayload.size() << " | " << dataBlock.mSize; - dataBlock.print(); + while (srcPos < binaryPayload.size()) { + auto& refDataBlock = vecDataBlocks.emplace_back(); + refDataBlock.decodeBlock(binaryPayload, srcPos); + srcPos += refDataBlock.mSize; + if (!refDataBlock.isCorrect()) { + LOG(WARNING) << "INCORRECT DATA BLOCK! Byte position: " << srcPos - refDataBlock.mSize << " | Payload size: " << binaryPayload.size() << " | DataBlock size" << refDataBlock.mSize; + refDataBlock.print(); + vecDataBlocks.pop_back(); + return srcPos; } } return srcPos; @@ -61,23 +74,17 @@ class RawReaderBase //processing data blocks into digits template - void processBinaryData(gsl::span payload, int linkID) + void processBinaryData(gsl::span payload, int linkID, int ep) { - std::vector vecDataBlocks; + auto& vecDataBlocks = getVecDataBlocks(); auto srcPos = decodeBlocks(payload, vecDataBlocks); - for (auto& dataBlock : vecDataBlocks) { auto intRec = dataBlock.getInteractionRecord(); auto [digitIter, isNew] = mMapDigits.try_emplace(intRec, intRec); - digitIter->second.template process(dataBlock, linkID); + digitIter->second.template process(dataBlock, linkID, ep); } + vecDataBlocks.clear(); } - /* - void process(int linkID, gsl::span payload) - { - static_cast(this)->processDigits(linkID,payload); - } - */ //pop digits template int getDigits(std::vector&... vecDigit) @@ -89,6 +96,11 @@ class RawReaderBase mMapDigits.clear(); return digitCounter; } + + private: + //Check for unique DataBlock classes + //Line below will not be compiled in case of duplicates among DataBlockTypes + typedef std::void_t, DataBlockTypes>::value == 1>...> CheckUniqueTypes; }; } // namespace fit From 83c53c16ec120de7c6b2e0aa97005a7f0553c0af Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Mon, 12 Apr 2021 10:02:48 +0200 Subject: [PATCH 096/770] Revert "StepTHn: use AddAt rather than Get+Set (#5897)" (#5910) This reverts commit bbc73979252cfb546a998d73f2713fb75c0325b6. --- Framework/Core/include/Framework/StepTHn.h | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/Framework/Core/include/Framework/StepTHn.h b/Framework/Core/include/Framework/StepTHn.h index 4a33cb8714e41..71f1288b06533 100644 --- a/Framework/Core/include/Framework/StepTHn.h +++ b/Framework/Core/include/Framework/StepTHn.h @@ -43,9 +43,6 @@ class StepTHn : public TNamed } return mTarget[step]; } - - virtual void AddAt(TArray* array, Double_t c, Int_t i) = 0; - Int_t getNSteps() { return mNSteps; } Int_t getNVar() { return mNVars; } @@ -96,11 +93,6 @@ class StepTHnT : public StepTHn StepTHnT(const char* name, const char* title, const int nSteps, const int nAxes, const int* nBins, const double* xmin, const double* xmax); ~StepTHnT() override = default; - void AddAt(TArray* a, double c, int bin) final - { - static_cast(a)->AddAt(c, bin); - } - protected: TArray* createArray(const TArray* src = nullptr) const override { @@ -194,9 +186,10 @@ void StepTHn::Fill(Int_t istep, const Ts&... valuesAndWeight) } } - this->AddAt(mValues[istep], weight, bin); + // TODO probably slow; add StepTHnT::add ? + mValues[istep]->SetAt(mValues[istep]->GetAt(bin) + weight, bin); if (mSumw2[istep]) { - this->AddAt(mSumw2[istep], weight, bin); + mSumw2[istep]->SetAt(mSumw2[istep]->GetAt(bin) + weight, bin); } } From 548a3e8cf1a15a45d37c3384e66cc092d14cc93f Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Mon, 12 Apr 2021 11:10:25 +0200 Subject: [PATCH 097/770] Drop obsolete tests from cleanup action --- .github/workflows/clean-test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clean-test.yml b/.github/workflows/clean-test.yml index 656f4e31caf22..b26bc3269b04e 100644 --- a/.github/workflows/clean-test.yml +++ b/.github/workflows/clean-test.yml @@ -8,7 +8,7 @@ on: checks: description: Checks to be cleaned required: true - default: 'build/O2/o2,build/O2/gpu,build/AliceO2/O2/o2/macOS,build/o2checkcode/o2,build/O2/fullCI' + default: 'build/O2/o2,build/AliceO2/O2/o2/macOS,build/O2/fullCI' owner: description: Organization required: true From c56958b492644a195342e613e18ed5f92c7125cc Mon Sep 17 00:00:00 2001 From: shahoian Date: Sun, 11 Apr 2021 03:58:48 +0200 Subject: [PATCH 098/770] Helper class to inject HBFUtil params to root-file driven reco workflows --- Detectors/Raw/CMakeLists.txt | 3 +- .../DetectorsRaw/HBFUtilsInitializer.h | 44 ++++++++++++++ Detectors/Raw/src/HBFUtilsInitializer.cxx | 59 +++++++++++++++++++ 3 files changed, 105 insertions(+), 1 deletion(-) create mode 100644 Detectors/Raw/include/DetectorsRaw/HBFUtilsInitializer.h create mode 100644 Detectors/Raw/src/HBFUtilsInitializer.cxx diff --git a/Detectors/Raw/CMakeLists.txt b/Detectors/Raw/CMakeLists.txt index 6a874b7da6d99..1ced5d24283cc 100644 --- a/Detectors/Raw/CMakeLists.txt +++ b/Detectors/Raw/CMakeLists.txt @@ -14,7 +14,8 @@ o2_add_library(DetectorsRaw src/SimpleRawReader.cxx src/SimpleSTF.cxx src/HBFUtils.cxx - src/RDHUtils.cxx + src/RDHUtils.cxx + src/HBFUtilsInitializer.cxx PUBLIC_LINK_LIBRARIES FairRoot::Base O2::Headers O2::CommonDataFormat diff --git a/Detectors/Raw/include/DetectorsRaw/HBFUtilsInitializer.h b/Detectors/Raw/include/DetectorsRaw/HBFUtilsInitializer.h new file mode 100644 index 0000000000000..46ee322e3982f --- /dev/null +++ b/Detectors/Raw/include/DetectorsRaw/HBFUtilsInitializer.h @@ -0,0 +1,44 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +// @brief Aux.class initialize HBFUtils +// @author ruben.shahoyan@cern.ch + +#ifndef _O2_HBFUTILS_INITIALIZER_ +#define _O2_HBFUTILS_INITIALIZER_ + +#include + +namespace o2 +{ + +namespace framework +{ +class ConfigContext; +class DataProcessorSpec; +class ConfigParamSpec; +using WorkflowSpec = std::vector; +} // namespace framework + +namespace raw +{ + +struct HBFUtilsInitializer { + static constexpr char HBFConfOpt[] = "hbfutils-config"; + + HBFUtilsInitializer(const o2::framework::ConfigContext& configcontext, o2::framework::WorkflowSpec& wf); + + static void addConfigOption(std::vector& opts); +}; + +} // namespace raw +} // namespace o2 + +#endif diff --git a/Detectors/Raw/src/HBFUtilsInitializer.cxx b/Detectors/Raw/src/HBFUtilsInitializer.cxx new file mode 100644 index 0000000000000..b82be031124ae --- /dev/null +++ b/Detectors/Raw/src/HBFUtilsInitializer.cxx @@ -0,0 +1,59 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +// @brief Aux.class initialize HBFUtils +// @author ruben.shahoyan@cern.ch + +#include "DetectorsRaw/HBFUtilsInitializer.h" +#include "DetectorsRaw/HBFUtils.h" +#include "CommonUtils/ConfigurableParam.h" +#include "DetectorsCommonDataFormats/NameConf.h" +#include "Framework/ConfigContext.h" +#include "Framework/WorkflowSpec.h" +#include "Framework/ConfigParamSpec.h" +#include "Framework/ConfigParamsHelper.h" +#include "Framework/Logger.h" + +using namespace o2::raw; +namespace o2f = o2::framework; + +/// If the workflow has devices w/o inputs, we assume that these are data readers in root-file based workflow. +/// In this case this class will configure these devices DataHeader.firstTForbit generator to provide orbit according to HBFUtil setings +/// In case the configcontext has relevant option, the HBFUtils will be beforehand updated from the file indicated by this option. +/// (only those fields of HBFUtils which were not modified before, e.g. by ConfigurableParam::updateFromString) + +HBFUtilsInitializer::HBFUtilsInitializer(const o2f::ConfigContext& configcontext, o2f::WorkflowSpec& wf) +{ + auto updateHBFUtils = [&configcontext]() { + static bool done = false; + if (!done) { + bool helpasked = configcontext.helpOnCommandLine(); // if help is asked, don't take for granted that the ini file is there, don't produce an error if it is not! + std::string conf = configcontext.options().isSet(HBFConfOpt) ? configcontext.options().get(HBFConfOpt) : ""; + if (!conf.empty() && conf != "none" && !(helpasked && !o2::base::NameConf::pathExists(conf))) { + o2::conf::ConfigurableParam::updateFromFile(conf, "HBFUtils", true); // update only those values which were not touched yet (provenance == kCODE) + } + done = true; + } + }; + + const auto& hbfu = o2::raw::HBFUtils::Instance(); + for (auto& spec : wf) { + if (spec.inputs.empty()) { + updateHBFUtils(); + o2f::ConfigParamsHelper::addOptionIfMissing(spec.options, o2f::ConfigParamSpec{"orbit-offset-enumeration", o2f::VariantType::Int64, int64_t(hbfu.getFirstIRofTF({0, hbfu.orbitFirstSampled}).orbit), {"1st injected orbit"}}); + o2f::ConfigParamsHelper::addOptionIfMissing(spec.options, o2f::ConfigParamSpec{"orbit-multiplier-enumeration", o2f::VariantType::Int64, int64_t(hbfu.nHBFPerTF), {"orbits/TF"}}); + } + } +} + +void HBFUtilsInitializer::addConfigOption(std::vector& opts) +{ + o2f::ConfigParamsHelper::addOptionIfMissing(opts, o2f::ConfigParamSpec{HBFConfOpt, o2f::VariantType::String, std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE), {"configKeyValues file for HBFUtils (or none)"}}); +} From 3269de866c0b03a783a4d06dca0886bbe0b0c16a Mon Sep 17 00:00:00 2001 From: shahoian Date: Sun, 4 Apr 2021 01:51:44 +0200 Subject: [PATCH 099/770] DH.firstTForbit configuration for root-file driven reco workflows All reco. workflows, when reading data from root files, will try to read the config files used for digitization in order to set up correct DataHeader::firstTForbit propagation. The initial value of firstTForbit will correspond to 1st orbit of the TF containing the HBFUtils::orbitFirstSampled (orbit from which interaction sampling started in digitization), in case of mutiple TFs it will be incremented by HBFUtils::nHBFPerTF. The HBFUtils.. setting provided from the command line will override those loaded from the config file. By default the o2simdigitizerworkflow_configuration.ini written during digitization will be loaded, can be overriden by --hbfutils-config . Reading of config file can be disable by providing option --hbfutils-config none --- .../EMCAL/workflow/src/emc-reco-workflow.cxx | 22 ++++++--- .../FDD/workflow/src/fdd-reco-workflow.cxx | 25 ++++++---- .../FT0/workflow/src/ft0-reco-workflow.cxx | 25 ++++++---- .../src/cosmics-match-workflow.cxx | 8 +++- .../src/primary-vertexing-workflow.cxx | 7 +++ .../src/secondary-vertexing-workflow.cxx | 7 +++ .../src/tpcits-match-workflow.cxx | 11 ++++- .../tofworkflow/src/tof-matcher-global.cxx | 31 ++++++++----- .../tofworkflow/src/tof-matcher-tpc.cxx | 33 ++++++++----- .../tofworkflow/src/tof-reco-workflow.cxx | 46 ++++++++++--------- .../src/tpc-interpolation-workflow.cxx | 23 +++++++--- .../workflow/src/digits-to-raw-workflow.cxx | 12 +++-- .../ITS/workflow/src/its-reco-workflow.cxx | 24 ++++++---- .../MFT/workflow/src/mft-reco-workflow.cxx | 17 ++++--- Detectors/MUON/MCH/Workflow/CMakeLists.txt | 2 +- .../Workflow/src/digits-reader-workflow.cxx | 27 +++++++++-- .../Workflow/src/digits-reader-workflow.cxx | 15 +++++- .../PHOS/workflow/src/phos-reco-workflow.cxx | 20 +++++--- .../TPC/workflow/src/tpc-reco-workflow.cxx | 34 ++++++++------ .../workflow/src/trd-tracking-workflow.cxx | 27 +++++++---- 20 files changed, 286 insertions(+), 130 deletions(-) diff --git a/Detectors/EMCAL/workflow/src/emc-reco-workflow.cxx b/Detectors/EMCAL/workflow/src/emc-reco-workflow.cxx index b4579e5848808..f52babc6e9c7d 100644 --- a/Detectors/EMCAL/workflow/src/emc-reco-workflow.cxx +++ b/Detectors/EMCAL/workflow/src/emc-reco-workflow.cxx @@ -17,6 +17,7 @@ #include "Framework/ConfigParamSpec.h" #include "EMCALWorkflow/RecoWorkflow.h" #include "Algorithm/RangeTokenizer.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" #include #include @@ -32,8 +33,12 @@ void customize(std::vector& workflowOptions) {"enable-digits-printer", o2::framework::VariantType::Bool, false, {"enable digits printer component"}}, {"disable-root-input", o2::framework::VariantType::Bool, false, {"do not initialize root files readers"}}, {"disable-root-output", o2::framework::VariantType::Bool, false, {"do not initialize root file writers"}}, + {"configKeyValues", o2::framework::VariantType::String, "", {"Semicolon separated key=value strings"}}, {"disable-mc", o2::framework::VariantType::Bool, false, {"disable sending of MC information"}}, }; + + o2::raw::HBFUtilsInitializer::addConfigOption(options); + std::swap(workflowOptions, options); } @@ -54,10 +59,15 @@ void customize(std::vector& workflowOptions) o2::framework::WorkflowSpec defineDataProcessing(o2::framework::ConfigContext const& cfgc) { //bla - return o2::emcal::reco_workflow::getWorkflow(not cfgc.options().get("disable-mc"), // - cfgc.options().get("enable-digits-printer"), // - cfgc.options().get("input-type"), // - cfgc.options().get("output-type"), // - cfgc.options().get("disable-root-input"), - cfgc.options().get("disable-root-output")); + auto wf = o2::emcal::reco_workflow::getWorkflow(not cfgc.options().get("disable-mc"), // + cfgc.options().get("enable-digits-printer"), // + cfgc.options().get("input-type"), // + cfgc.options().get("output-type"), // + cfgc.options().get("disable-root-input"), + cfgc.options().get("disable-root-output")); + + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(cfgc, wf); + + return std::move(wf); } diff --git a/Detectors/FIT/FDD/workflow/src/fdd-reco-workflow.cxx b/Detectors/FIT/FDD/workflow/src/fdd-reco-workflow.cxx index fd0895819f5b5..35ea032f8c5cb 100644 --- a/Detectors/FIT/FDD/workflow/src/fdd-reco-workflow.cxx +++ b/Detectors/FIT/FDD/workflow/src/fdd-reco-workflow.cxx @@ -11,6 +11,7 @@ #include "FDDWorkflow/RecoWorkflow.h" #include "Framework/ConfigParamRegistry.h" #include "CommonUtils/ConfigurableParam.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" using namespace o2::framework; @@ -20,14 +21,15 @@ using namespace o2::framework; void customize(std::vector& workflowOptions) { // option allowing to set parameters - workflowOptions.push_back(ConfigParamSpec{ - "disable-mc", o2::framework::VariantType::Bool, false, {"disable MC propagation even if available"}}); - workflowOptions.push_back(ConfigParamSpec{ - "disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}); - workflowOptions.push_back(ConfigParamSpec{ - "disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}); - std::string keyvaluehelp("Semicolon separated key=value strings ..."); - workflowOptions.push_back(ConfigParamSpec{"configKeyValues", VariantType::String, "", {keyvaluehelp}}); + std::vector options{ + {"disable-mc", o2::framework::VariantType::Bool, false, {"disable MC propagation even if available"}}, + {"disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}, + {"disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}, + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}}; + + o2::raw::HBFUtilsInitializer::addConfigOption(options); + + std::swap(workflowOptions, options); } // ------------------------------------------------------------------ @@ -45,5 +47,10 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) auto disableRootInp = configcontext.options().get("disable-root-input"); auto disableRootOut = configcontext.options().get("disable-root-output"); - return std::move(o2::fdd::getRecoWorkflow(useMC, disableRootInp, disableRootOut)); + auto wf = o2::fdd::getRecoWorkflow(useMC, disableRootInp, disableRootOut); + + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(configcontext, wf); + + return std::move(wf); } diff --git a/Detectors/FIT/FT0/workflow/src/ft0-reco-workflow.cxx b/Detectors/FIT/FT0/workflow/src/ft0-reco-workflow.cxx index 9cfe9732aaa21..a63dee708bac4 100644 --- a/Detectors/FIT/FT0/workflow/src/ft0-reco-workflow.cxx +++ b/Detectors/FIT/FT0/workflow/src/ft0-reco-workflow.cxx @@ -10,6 +10,7 @@ #include "FT0Workflow/RecoWorkflow.h" #include "CommonUtils/ConfigurableParam.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" using namespace o2::framework; @@ -19,14 +20,15 @@ using namespace o2::framework; void customize(std::vector& workflowOptions) { // option allowing to set parameters - workflowOptions.push_back(ConfigParamSpec{ - "disable-mc", o2::framework::VariantType::Bool, false, {"disable MC propagation even if available"}}); - workflowOptions.push_back(ConfigParamSpec{ - "disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}); - workflowOptions.push_back(ConfigParamSpec{ - "disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}); - std::string keyvaluehelp("Semicolon separated key=value strings ..."); - workflowOptions.push_back(ConfigParamSpec{"configKeyValues", VariantType::String, "", {keyvaluehelp}}); + std::vector options{ + {"disable-mc", o2::framework::VariantType::Bool, false, {"disable MC propagation even if available"}}, + {"disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}, + {"disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}, + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}}; + + o2::raw::HBFUtilsInitializer::addConfigOption(options); + + std::swap(workflowOptions, options); } // ------------------------------------------------------------------ @@ -46,5 +48,10 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) auto disableRootOut = configcontext.options().get("disable-root-output"); LOG(INFO) << "WorkflowSpec getRecoWorkflow useMC " << useMC; - return std::move(o2::fit::getRecoWorkflow(useMC, disableRootInp, disableRootOut)); + auto wf = o2::fit::getRecoWorkflow(useMC, disableRootInp, disableRootOut); + + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(configcontext, wf); + + return std::move(wf); } diff --git a/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx index cb75804ab3b88..4ef0b738ba2aa 100644 --- a/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx @@ -25,6 +25,7 @@ #include "GlobalTrackingWorkflow/CosmicsMatchingSpec.h" #include "GlobalTrackingWorkflow/TrackCosmicsWriterSpec.h" #include "Algorithm/RangeTokenizer.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" using namespace o2::framework; using DetID = o2::detectors::DetID; @@ -42,6 +43,8 @@ void customize(std::vector& workflowOptions) {"track-sources", VariantType::String, std::string{GID::ALL}, {"comma-separated list of sources to use"}}, {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings ..."}}}; + o2::raw::HBFUtilsInitializer::addConfigOption(options); + std::swap(workflowOptions, options); } @@ -129,5 +132,8 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) specs.emplace_back(o2::globaltracking::getTrackCosmicsWriterSpec(useMC)); } - return specs; + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(configcontext, specs); + + return std::move(specs); } diff --git a/Detectors/GlobalTrackingWorkflow/src/primary-vertexing-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/primary-vertexing-workflow.cxx index 941db04f7747a..bd5818228bf89 100644 --- a/Detectors/GlobalTrackingWorkflow/src/primary-vertexing-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/primary-vertexing-workflow.cxx @@ -18,6 +18,7 @@ #include "TOFWorkflowUtils/ClusterReaderSpec.h" #include "FT0Workflow/RecPointReaderSpec.h" #include "ReconstructionDataFormats/GlobalTrackID.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" #include "DetectorsCommonDataFormats/DetID.h" #include "CommonUtils/ConfigurableParam.h" #include "Framework/CompletionPolicy.h" @@ -41,6 +42,8 @@ void customize(std::vector& workflowOptions) {"vetex-track-matching-sources", VariantType::String, std::string{GID::ALL}, {"comma-separated list of sources to use in vertex-track associations or \"none\" to disable matching"}}, {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings ..."}}}; + o2::raw::HBFUtilsInitializer::addConfigOption(options); + std::swap(workflowOptions, options); } @@ -107,5 +110,9 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) if (!disableRootOut) { specs.emplace_back(o2::vertexing::getPrimaryVertexWriterSpec(srcVT.none(), useMC)); } + + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(configcontext, specs); + return std::move(specs); } diff --git a/Detectors/GlobalTrackingWorkflow/src/secondary-vertexing-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/secondary-vertexing-workflow.cxx index 6b99862cda3bb..f068109e489f8 100644 --- a/Detectors/GlobalTrackingWorkflow/src/secondary-vertexing-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/secondary-vertexing-workflow.cxx @@ -19,6 +19,7 @@ #include "ReconstructionDataFormats/GlobalTrackID.h" #include "DetectorsCommonDataFormats/DetID.h" #include "CommonUtils/ConfigurableParam.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" #include "Framework/CompletionPolicy.h" #include "Framework/ConfigParamSpec.h" @@ -38,6 +39,8 @@ void customize(std::vector& workflowOptions) {"disable-cascade-finder", o2::framework::VariantType::Bool, false, {"do not run cascade finder"}}, {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings ..."}}}; + o2::raw::HBFUtilsInitializer::addConfigOption(options); + std::swap(workflowOptions, options); } @@ -85,5 +88,9 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) if (!disableRootOut) { specs.emplace_back(o2::vertexing::getSecondaryVertexWriterSpec()); } + + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(configcontext, specs); + return std::move(specs); } diff --git a/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx index 0a1025134841b..e4c5a5571415a 100644 --- a/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx @@ -12,6 +12,7 @@ #include "CommonUtils/ConfigurableParam.h" #include "Framework/CompletionPolicy.h" #include "TPCWorkflow/TPCSectorCompletionPolicy.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" using namespace o2::framework; @@ -29,6 +30,8 @@ void customize(std::vector& workflowOptions) {"produce-calibration-data", o2::framework::VariantType::Bool, false, {"produce output for TPC vdrift calibration"}}, {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings ..."}}}; + o2::raw::HBFUtilsInitializer::addConfigOption(options); + std::swap(workflowOptions, options); } @@ -59,5 +62,11 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) auto disableRootInp = configcontext.options().get("disable-root-input"); auto disableRootOut = configcontext.options().get("disable-root-output"); auto calib = configcontext.options().get("produce-calibration-data"); - return std::move(o2::globaltracking::getMatchTPCITSWorkflow(useFT0, useMC, disableRootInp, disableRootOut, calib)); + + auto wf = o2::globaltracking::getMatchTPCITSWorkflow(useFT0, useMC, disableRootInp, disableRootOut, calib); + + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(configcontext, wf); + + return std::move(wf); } diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-global.cxx b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-global.cxx index c6939c6842e2f..8db17a14a17c4 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-global.cxx +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-global.cxx @@ -25,6 +25,7 @@ #include "FairLogger.h" #include "CommonUtils/ConfigurableParam.h" #include "DetectorsCommonDataFormats/NameConf.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" // FIT #include "FT0Workflow/RecPointReaderSpec.h" @@ -37,17 +38,22 @@ // including Framework/runDataProcessing void customize(std::vector& workflowOptions) { - workflowOptions.push_back(ConfigParamSpec{"input-type", o2::framework::VariantType::String, "clusters,tracks", {"clusters, tracks, fit"}}); - workflowOptions.push_back(ConfigParamSpec{"output-type", o2::framework::VariantType::String, "matching-info,calib-info", {"matching-info, calib-info"}}); - workflowOptions.push_back(ConfigParamSpec{"disable-mc", o2::framework::VariantType::Bool, false, {"disable sending of MC information, TBI"}}); - workflowOptions.push_back(ConfigParamSpec{"tof-sectors", o2::framework::VariantType::String, "0-17", {"TOF sector range, e.g. 5-7,8,9 ,TBI"}}); - workflowOptions.push_back(ConfigParamSpec{"tof-lanes", o2::framework::VariantType::Int, 1, {"number of parallel lanes up to the matcher, TBI"}}); - workflowOptions.push_back(ConfigParamSpec{"use-ccdb", o2::framework::VariantType::Bool, false, {"enable access to ccdb tof calibration objects"}}); - workflowOptions.push_back(ConfigParamSpec{"use-fit", o2::framework::VariantType::Bool, false, {"enable access to fit info for calibration"}}); - workflowOptions.push_back(ConfigParamSpec{"input-desc", o2::framework::VariantType::String, "CRAWDATA", {"Input specs description string"}}); - workflowOptions.push_back(ConfigParamSpec{"disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}); - workflowOptions.push_back(ConfigParamSpec{"disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}); - workflowOptions.push_back(ConfigParamSpec{"configKeyValues", o2::framework::VariantType::String, "", {"Semicolon separated key=value strings ..."}}); + std::vector options{ + {"input-type", o2::framework::VariantType::String, "clusters,tracks", {"clusters, tracks, fit"}}, + {"output-type", o2::framework::VariantType::String, "matching-info,calib-info", {"matching-info, calib-info"}}, + {"disable-mc", o2::framework::VariantType::Bool, false, {"disable sending of MC information, TBI"}}, + {"tof-sectors", o2::framework::VariantType::String, "0-17", {"TOF sector range, e.g. 5-7,8,9 ,TBI"}}, + {"tof-lanes", o2::framework::VariantType::Int, 1, {"number of parallel lanes up to the matcher, TBI"}}, + {"use-ccdb", o2::framework::VariantType::Bool, false, {"enable access to ccdb tof calibration objects"}}, + {"use-fit", o2::framework::VariantType::Bool, false, {"enable access to fit info for calibration"}}, + {"input-desc", o2::framework::VariantType::String, "CRAWDATA", {"Input specs description string"}}, + {"disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}, + {"disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}, + {"configKeyValues", o2::framework::VariantType::String, "", {"Semicolon separated key=value strings ..."}}}; + + o2::raw::HBFUtilsInitializer::addConfigOption(options); + + std::swap(workflowOptions, options); } #include "Framework/runDataProcessing.h" // the main driver @@ -149,5 +155,8 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) } LOG(INFO) << "Number of active devices = " << specs.size(); + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(cfgc, specs); + return std::move(specs); } diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-tpc.cxx b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-tpc.cxx index a79e3194e6d6f..68f22d7f74b8d 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-tpc.cxx +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-tpc.cxx @@ -27,6 +27,7 @@ #include "TPCWorkflow/TrackReaderSpec.h" #include "TPCWorkflow/PublisherSpec.h" #include "TPCWorkflow/ClusterSharingMapSpec.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" // GRP #include "DataFormatsParameters/GRPObject.h" @@ -42,18 +43,23 @@ // including Framework/runDataProcessing void customize(std::vector& workflowOptions) { - workflowOptions.push_back(ConfigParamSpec{"output-type", o2::framework::VariantType::String, "matching-info", {"matching-info, calib-info"}}); - workflowOptions.push_back(ConfigParamSpec{"disable-mc", o2::framework::VariantType::Bool, false, {"disable sending of MC information, TBI"}}); - workflowOptions.push_back(ConfigParamSpec{"tof-sectors", o2::framework::VariantType::String, "0-17", {"TOF sector range, e.g. 5-7,8,9 ,TBI"}}); - workflowOptions.push_back(ConfigParamSpec{"tof-lanes", o2::framework::VariantType::Int, 1, {"number of parallel lanes up to the matcher, TBI"}}); - workflowOptions.push_back(ConfigParamSpec{"use-ccdb", o2::framework::VariantType::Bool, false, {"enable access to ccdb tof calibration objects"}}); - workflowOptions.push_back(ConfigParamSpec{"use-fit", o2::framework::VariantType::Bool, false, {"enable access to fit info for calibration"}}); - workflowOptions.push_back(ConfigParamSpec{"input-desc", o2::framework::VariantType::String, "CRAWDATA", {"Input specs description string"}}); - workflowOptions.push_back(ConfigParamSpec{"tpc-refit", o2::framework::VariantType::Bool, false, {"refit matched TPC tracks"}}); - workflowOptions.push_back(ConfigParamSpec{"disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}); - workflowOptions.push_back(ConfigParamSpec{"disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}); - workflowOptions.push_back(ConfigParamSpec{"cosmics", o2::framework::VariantType::Bool, false, {"reco for cosmics"}}); - workflowOptions.push_back(ConfigParamSpec{"configKeyValues", o2::framework::VariantType::String, "", {"Semicolon separated key=value strings ..."}}); + std::vector options{ + {"output-type", o2::framework::VariantType::String, "matching-info", {"matching-info, calib-info"}}, + {"disable-mc", o2::framework::VariantType::Bool, false, {"disable sending of MC information, TBI"}}, + {"tof-sectors", o2::framework::VariantType::String, "0-17", {"TOF sector range, e.g. 5-7,8,9 ,TBI"}}, + {"tof-lanes", o2::framework::VariantType::Int, 1, {"number of parallel lanes up to the matcher, TBI"}}, + {"use-ccdb", o2::framework::VariantType::Bool, false, {"enable access to ccdb tof calibration objects"}}, + {"use-fit", o2::framework::VariantType::Bool, false, {"enable access to fit info for calibration"}}, + {"input-desc", o2::framework::VariantType::String, "CRAWDATA", {"Input specs description string"}}, + {"tpc-refit", o2::framework::VariantType::Bool, false, {"refit matched TPC tracks"}}, + {"disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}, + {"disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}, + {"cosmics", o2::framework::VariantType::Bool, false, {"reco for cosmics"}}, + {"configKeyValues", o2::framework::VariantType::String, "", {"Semicolon separated key=value strings ..."}}}; + + o2::raw::HBFUtilsInitializer::addConfigOption(options); + + std::swap(workflowOptions, options); } #include "Framework/runDataProcessing.h" // the main driver @@ -163,5 +169,8 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) LOG(INFO) << "Number of active devices = " << specs.size(); + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(cfgc, specs); + return std::move(specs); } diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-reco-workflow.cxx b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-reco-workflow.cxx index c28c54e19457e..5b07c20c2db69 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-reco-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-reco-workflow.cxx @@ -33,6 +33,7 @@ #include "FairLogger.h" #include "CommonUtils/ConfigurableParam.h" #include "DetectorsCommonDataFormats/NameConf.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" // FIT #include "FT0Workflow/RecPointReaderSpec.h" @@ -45,23 +46,27 @@ // including Framework/runDataProcessing void customize(std::vector& workflowOptions) { - workflowOptions.push_back(ConfigParamSpec{"input-type", o2::framework::VariantType::String, "digits", {"digits, raw, clusters"}}); - workflowOptions.push_back(ConfigParamSpec{"output-type", o2::framework::VariantType::String, "clusters,matching-info,calib-info", {"digits, clusters, matching-info, calib-info, raw, ctf"}}); - workflowOptions.push_back(ConfigParamSpec{"disable-mc", o2::framework::VariantType::Bool, false, {"disable sending of MC information, TBI"}}); - workflowOptions.push_back(ConfigParamSpec{"tof-sectors", o2::framework::VariantType::String, "0-17", {"TOF sector range, e.g. 5-7,8,9 ,TBI"}}); - workflowOptions.push_back(ConfigParamSpec{"tof-lanes", o2::framework::VariantType::Int, 1, {"number of parallel lanes up to the matcher, TBI"}}); - workflowOptions.push_back(ConfigParamSpec{"use-ccdb", o2::framework::VariantType::Bool, false, {"enable access to ccdb tof calibration objects"}}); - workflowOptions.push_back(ConfigParamSpec{"use-fit", o2::framework::VariantType::Bool, false, {"enable access to fit info for calibration"}}); - workflowOptions.push_back(ConfigParamSpec{"input-desc", o2::framework::VariantType::String, "CRAWDATA", {"Input specs description string"}}); - workflowOptions.push_back(ConfigParamSpec{"disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}); - workflowOptions.push_back(ConfigParamSpec{"disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}); - workflowOptions.push_back(ConfigParamSpec{"conet-mode", o2::framework::VariantType::Bool, false, {"enable conet mode"}}); - workflowOptions.push_back(ConfigParamSpec{"configKeyValues", o2::framework::VariantType::String, "", {"Semicolon separated key=value strings ..."}}); - workflowOptions.push_back(ConfigParamSpec{"disable-row-writing", o2::framework::VariantType::Bool, false, {"disable ROW in Digit writing"}}); - workflowOptions.push_back(ConfigParamSpec{"write-decoding-errors", o2::framework::VariantType::Bool, false, {"trace errors in digits output when decoding"}}); - workflowOptions.push_back(ConfigParamSpec{"calib-cluster", VariantType::Bool, false, {"to enable calib info production from clusters"}}); - workflowOptions.push_back(ConfigParamSpec{"hbfutils-config", o2::framework::VariantType::String, std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE), {"config file for HBFUtils (or none), used for raw output only!!!"}}); - workflowOptions.push_back(ConfigParamSpec{"cosmics", VariantType::Bool, false, {"to enable cosmics utils"}}); + std::vector options{ + {"input-type", o2::framework::VariantType::String, "digits", {"digits, raw, clusters"}}, + {"output-type", o2::framework::VariantType::String, "clusters,matching-info,calib-info", {"digits, clusters, matching-info, calib-info, raw, ctf"}}, + {"disable-mc", o2::framework::VariantType::Bool, false, {"disable sending of MC information, TBI"}}, + {"tof-sectors", o2::framework::VariantType::String, "0-17", {"TOF sector range, e.g. 5-7,8,9 ,TBI"}}, + {"tof-lanes", o2::framework::VariantType::Int, 1, {"number of parallel lanes up to the matcher, TBI"}}, + {"use-ccdb", o2::framework::VariantType::Bool, false, {"enable access to ccdb tof calibration objects"}}, + {"use-fit", o2::framework::VariantType::Bool, false, {"enable access to fit info for calibration"}}, + {"input-desc", o2::framework::VariantType::String, "CRAWDATA", {"Input specs description string"}}, + {"disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}, + {"disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}, + {"conet-mode", o2::framework::VariantType::Bool, false, {"enable conet mode"}}, + {"configKeyValues", o2::framework::VariantType::String, "", {"Semicolon separated key=value strings ..."}}, + {"disable-row-writing", o2::framework::VariantType::Bool, false, {"disable ROW in Digit writing"}}, + {"write-decoding-errors", o2::framework::VariantType::Bool, false, {"trace errors in digits output when decoding"}}, + {"calib-cluster", VariantType::Bool, false, {"to enable calib info production from clusters"}}, + {"cosmics", VariantType::Bool, false, {"to enable cosmics utils"}}}; + + o2::raw::HBFUtilsInitializer::addConfigOption(options); + + std::swap(workflowOptions, options); } #include "Framework/runDataProcessing.h" // the main driver @@ -113,10 +118,6 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) } if (outputType.rfind("raw") < outputType.size()) { writeraw = 1; - std::string confDig = cfgc.options().get("hbfutils-config"); - if (!confDig.empty() && confDig != "none") { - o2::conf::ConfigurableParam::updateFromFile(confDig, "HBFUtils"); - } } if (outputType.rfind("ctf") < outputType.size()) { writectf = 1; @@ -225,5 +226,8 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) LOG(INFO) << "Number of active devices = " << specs.size(); + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(cfgc, specs); + return std::move(specs); } diff --git a/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/tpc-interpolation-workflow.cxx b/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/tpc-interpolation-workflow.cxx index 059eae8df5d8f..1cbbbbc62aaca 100644 --- a/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/tpc-interpolation-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/tpc-interpolation-workflow.cxx @@ -12,6 +12,7 @@ #include "CommonUtils/ConfigurableParam.h" #include "Framework/CompletionPolicy.h" #include "TPCWorkflow/TPCSectorCompletionPolicy.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" using namespace o2::framework; @@ -21,12 +22,14 @@ using namespace o2::framework; void customize(std::vector& workflowOptions) { // option allowing to set parameters - workflowOptions.push_back(ConfigParamSpec{ - "disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}); - workflowOptions.push_back(ConfigParamSpec{ - "disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}); - std::string keyvaluehelp("Semicolon separated key=value strings ..."); - workflowOptions.push_back(ConfigParamSpec{"configKeyValues", VariantType::String, "", {keyvaluehelp}}); + std::vector options{ + {"disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}, + {"disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}, + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings ..."}}}; + + o2::raw::HBFUtilsInitializer::addConfigOption(options); + + std::swap(workflowOptions, options); } // the matcher process requires the TPC sector completion to trigger and data on @@ -52,5 +55,11 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) o2::conf::ConfigurableParam::writeINI("o2tpcinterpolation-workflow_configuration.ini"); auto disableRootInp = configcontext.options().get("disable-root-input"); auto disableRootOut = configcontext.options().get("disable-root-output"); - return std::move(o2::tpc::getTPCInterpolationWorkflow(disableRootInp, disableRootOut)); + + auto wf = o2::tpc::getTPCInterpolationWorkflow(disableRootInp, disableRootOut); + + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(configcontext, wf); + + return std::move(wf); } diff --git a/Detectors/HMPID/workflow/src/digits-to-raw-workflow.cxx b/Detectors/HMPID/workflow/src/digits-to-raw-workflow.cxx index cb4fa729bed26..a1cd50bf99009 100644 --- a/Detectors/HMPID/workflow/src/digits-to-raw-workflow.cxx +++ b/Detectors/HMPID/workflow/src/digits-to-raw-workflow.cxx @@ -26,6 +26,7 @@ #include "Framework/Variant.h" #include "CommonUtils/ConfigurableParam.h" #include "DetectorsCommonDataFormats/NameConf.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" // customize the completion policy void customize(std::vector& policies) @@ -39,8 +40,9 @@ void customize(std::vector& policies) void customize(std::vector& workflowOptions) { std::string keyvaluehelp("Semicolon separated key=value strings ..."); - workflowOptions.push_back(o2::framework::ConfigParamSpec{"hbfutils-config", o2::framework::VariantType::String, std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE), {"config file for HBFUtils (or none), used for raw output only!!!"}}); workflowOptions.push_back(o2::framework::ConfigParamSpec{"configKeyValues", o2::framework::VariantType::String, "", {keyvaluehelp}}); + + o2::raw::HBFUtilsInitializer::addConfigOption(workflowOptions); } #include "Framework/runDataProcessing.h" @@ -52,12 +54,12 @@ using namespace o2::framework; WorkflowSpec defineDataProcessing(const ConfigContext& configcontext) { WorkflowSpec specs; - std::string confDig = configcontext.options().get("hbfutils-config"); - if (!confDig.empty() && confDig != "none") { - o2::conf::ConfigurableParam::updateFromFile(confDig, "HBFUtils"); - } o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); DataProcessorSpec consumer = o2::hmpid::getDigitsToRawSpec(); specs.push_back(consumer); + + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(configcontext, specs); + return specs; } diff --git a/Detectors/ITSMFT/ITS/workflow/src/its-reco-workflow.cxx b/Detectors/ITSMFT/ITS/workflow/src/its-reco-workflow.cxx index ded6f23186131..3280db7cb1f17 100644 --- a/Detectors/ITSMFT/ITS/workflow/src/its-reco-workflow.cxx +++ b/Detectors/ITSMFT/ITS/workflow/src/its-reco-workflow.cxx @@ -12,6 +12,7 @@ #include "CommonUtils/ConfigurableParam.h" #include "ITStracking/TrackingConfigParam.h" #include "ITStracking/Configuration.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" #include "GPUO2Interface.h" #include "GPUReconstruction.h" @@ -33,12 +34,12 @@ void customize(std::vector& workflowOptions) {"trackerCA", o2::framework::VariantType::Bool, false, {"use trackerCA (default: trackerCM)"}}, {"tracking-mode", o2::framework::VariantType::String, "sync", {"sync,async,cosmics"}}, {"entropy-encoding", o2::framework::VariantType::Bool, false, {"produce entropy encoded data"}}, + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}, {"gpuDevice", o2::framework::VariantType::Int, 1, {"use gpu device: CPU=1,CUDA=2,HIP=3 (default: CPU)"}}}; - std::swap(workflowOptions, options); + o2::raw::HBFUtilsInitializer::addConfigOption(options); - std::string keyvaluehelp("Semicolon separated key=value strings (e.g.: 'ITSDigitizerParam.roFrameLength=6000.;...')"); - workflowOptions.push_back(ConfigParamSpec{"configKeyValues", VariantType::String, "", {keyvaluehelp}}); + std::swap(workflowOptions, options); } // ------------------------------------------------------------------ @@ -49,10 +50,6 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { // Update the (declared) parameters if changed from the command line - o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); - // write the configuration used for the digitizer workflow - o2::conf::ConfigurableParam::writeINI("o2itsrecoflow_configuration.ini"); - auto useMC = !configcontext.options().get("disable-mc"); auto useCAtracker = configcontext.options().get("trackerCA"); auto trmode = configcontext.options().get("tracking-mode"); @@ -67,5 +64,16 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) LOG(ERROR) << "requested CookedTracker supports only sync tracking-mode, use --trackerCA"; throw std::runtime_error("incompatible options provided"); } - return std::move(o2::its::reco_workflow::getWorkflow(useMC, useCAtracker, trmode, gpuDevice, extDigits, extClusters, disableRootOutput, eencode)); + + o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); + + auto wf = o2::its::reco_workflow::getWorkflow(useMC, useCAtracker, trmode, gpuDevice, extDigits, extClusters, disableRootOutput, eencode); + + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(configcontext, wf); + + // write the configuration used for the reco workflow + o2::conf::ConfigurableParam::writeINI("o2itsrecoflow_configuration.ini"); + + return std::move(wf); } diff --git a/Detectors/ITSMFT/MFT/workflow/src/mft-reco-workflow.cxx b/Detectors/ITSMFT/MFT/workflow/src/mft-reco-workflow.cxx index b0a2776d132cc..ee1d26fccd876 100644 --- a/Detectors/ITSMFT/MFT/workflow/src/mft-reco-workflow.cxx +++ b/Detectors/ITSMFT/MFT/workflow/src/mft-reco-workflow.cxx @@ -10,6 +10,7 @@ #include "MFTWorkflow/RecoWorkflow.h" #include "CommonUtils/ConfigurableParam.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" using namespace o2::framework; @@ -21,13 +22,12 @@ void customize(std::vector& workflowOptions) {"digits-from-upstream", o2::framework::VariantType::Bool, false, {"digits will be provided from upstream, skip digits reader"}}, {"clusters-from-upstream", o2::framework::VariantType::Bool, false, {"clusters will be provided from upstream, skip clusterizer"}}, {"disable-root-output", o2::framework::VariantType::Bool, false, {"do not write output root files"}}, - {"disable-mc", o2::framework::VariantType::Bool, false, {"disable MC propagation even if available"}}}; + {"disable-mc", o2::framework::VariantType::Bool, false, {"disable MC propagation even if available"}}, + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}}; - std::swap(workflowOptions, options); - - std::string keyvaluehelp("Semicolon separated key=value strings (e.g.: 'ITSDigitizerParam.roFrameLength=6000.;...')"); + o2::raw::HBFUtilsInitializer::addConfigOption(options); - workflowOptions.push_back(ConfigParamSpec{"configKeyValues", VariantType::String, "", {keyvaluehelp}}); + std::swap(workflowOptions, options); } #include "Framework/runDataProcessing.h" @@ -44,5 +44,10 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) auto extClusters = configcontext.options().get("clusters-from-upstream"); auto disableRootOutput = configcontext.options().get("disable-root-output"); - return std::move(o2::mft::reco_workflow::getWorkflow(useMC, extDigits, extClusters, disableRootOutput)); + auto wf = o2::mft::reco_workflow::getWorkflow(useMC, extDigits, extClusters, disableRootOutput); + + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(configcontext, wf); + + return std::move(wf); } diff --git a/Detectors/MUON/MCH/Workflow/CMakeLists.txt b/Detectors/MUON/MCH/Workflow/CMakeLists.txt index dff4cb57ab3eb..fede649045e40 100644 --- a/Detectors/MUON/MCH/Workflow/CMakeLists.txt +++ b/Detectors/MUON/MCH/Workflow/CMakeLists.txt @@ -56,7 +56,7 @@ o2_add_executable( digits-reader-workflow SOURCES src/DigitSamplerSpec.cxx src/digits-reader-workflow.cxx COMPONENT_NAME mch - PUBLIC_LINK_LIBRARIES O2::Framework O2::DataFormatsMCH O2::MCHBase O2::MCHMappingImpl3) + PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsRaw O2::DataFormatsMCH O2::MCHBase O2::MCHMappingImpl3) o2_add_executable( preclusters-sink-workflow diff --git a/Detectors/MUON/MCH/Workflow/src/digits-reader-workflow.cxx b/Detectors/MUON/MCH/Workflow/src/digits-reader-workflow.cxx index fbbf0583d6af9..2bb49dc00ca02 100644 --- a/Detectors/MUON/MCH/Workflow/src/digits-reader-workflow.cxx +++ b/Detectors/MUON/MCH/Workflow/src/digits-reader-workflow.cxx @@ -15,12 +15,33 @@ /// \author Andrea Ferrero, CEA #include "Framework/runDataProcessing.h" - +#include "CommonUtils/ConfigurableParam.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" #include "DigitSamplerSpec.h" using namespace o2::framework; -WorkflowSpec defineDataProcessing(const ConfigContext&) +// we need to add workflow options before including Framework/runDataProcessing +void customize(std::vector& workflowOptions) { - return WorkflowSpec{o2::mch::getDigitSamplerSpec()}; + std::vector options{ + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}}; + + o2::raw::HBFUtilsInitializer::addConfigOption(options); + + std::swap(workflowOptions, options); +} + +#include "Framework/runDataProcessing.h" + +WorkflowSpec defineDataProcessing(const ConfigContext& configcontext) +{ + o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); + + WorkflowSpec wf{o2::mch::getDigitSamplerSpec()}; + + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(configcontext, wf); + + return std::move(wf); } diff --git a/Detectors/MUON/MID/Workflow/src/digits-reader-workflow.cxx b/Detectors/MUON/MID/Workflow/src/digits-reader-workflow.cxx index fed38802c2c04..beabde191a115 100644 --- a/Detectors/MUON/MID/Workflow/src/digits-reader-workflow.cxx +++ b/Detectors/MUON/MID/Workflow/src/digits-reader-workflow.cxx @@ -23,6 +23,8 @@ #include "MIDSimulation/MCLabel.h" #include "MIDWorkflow/DigitReaderSpec.h" #include "MIDWorkflow/ZeroSuppressionSpec.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" +#include "CommonUtils/ConfigurableParam.h" using namespace o2::framework; @@ -31,8 +33,12 @@ void customize(std::vector& workflowOptions) { std::vector options{ {"disable-mc", VariantType::Bool, false, {"Do not propagate MC info"}}, - {"disable-zero-suppression", VariantType::Bool, false, {"Do not apply zero suppression"}}}; - workflowOptions.insert(workflowOptions.end(), options.begin(), options.end()); + {"disable-zero-suppression", VariantType::Bool, false, {"Do not apply zero suppression"}}, + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}}; + + o2::raw::HBFUtilsInitializer::addConfigOption(options); + + std::swap(workflowOptions, options); } #include "Framework/runDataProcessing.h" @@ -42,11 +48,16 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) bool disableZS = cfgc.options().get("disable-zero-suppression"); bool useMC = !cfgc.options().get("disable-mc"); + o2::conf::ConfigurableParam::updateFromString(cfgc.options().get("configKeyValues")); + WorkflowSpec specs; specs.emplace_back(o2::mid::getDigitReaderSpec(useMC, disableZS ? "DATA" : "DATAMC")); if (!disableZS) { specs.emplace_back(o2::mid::getZeroSuppressionSpec(useMC)); } + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(cfgc, specs); + return specs; } diff --git a/Detectors/PHOS/workflow/src/phos-reco-workflow.cxx b/Detectors/PHOS/workflow/src/phos-reco-workflow.cxx index c37909c1c21d9..26de9a091ed52 100644 --- a/Detectors/PHOS/workflow/src/phos-reco-workflow.cxx +++ b/Detectors/PHOS/workflow/src/phos-reco-workflow.cxx @@ -18,6 +18,7 @@ #include "PHOSWorkflow/RecoWorkflow.h" #include "Algorithm/RangeTokenizer.h" #include "CommonUtils/ConfigurableParam.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" #include #include @@ -34,6 +35,9 @@ void customize(std::vector& workflowOptions) {"disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input reader"}}, {"disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writer"}}, {"configKeyValues", o2::framework::VariantType::String, "", {"Semicolon separated key=value strings ..."}}}; + + o2::raw::HBFUtilsInitializer::addConfigOption(options); + std::swap(workflowOptions, options); } @@ -57,10 +61,14 @@ o2::framework::WorkflowSpec defineDataProcessing(o2::framework::ConfigContext co // Update the (declared) parameters if changed from the command line o2::conf::ConfigurableParam::updateFromString(cfgc.options().get("configKeyValues")); - return o2::phos::reco_workflow::getWorkflow(cfgc.options().get("disable-root-input"), - cfgc.options().get("disable-root-output"), - !cfgc.options().get("disable-mc"), // - cfgc.options().get("input-type"), // - cfgc.options().get("output-type") // - ); + auto wf = o2::phos::reco_workflow::getWorkflow(cfgc.options().get("disable-root-input"), + cfgc.options().get("disable-root-output"), + !cfgc.options().get("disable-mc"), // + cfgc.options().get("input-type"), // + cfgc.options().get("output-type")); + + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(cfgc, wf); + + return std::move(wf); } diff --git a/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx b/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx index ea1d4acbd8336..38e0fece3b9ff 100644 --- a/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx +++ b/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx @@ -25,6 +25,7 @@ #include "DataFormatsTPC/TPCSectorHeader.h" #include "Algorithm/RangeTokenizer.h" #include "CommonUtils/ConfigurableParam.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" #include #include @@ -60,6 +61,8 @@ void customize(std::vector& workflowOptions) {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings (e.g.: 'TPCHwClusterer.peakChargeThreshold=4;...')"}}, {"configFile", VariantType::String, "", {"configuration file for configurable parameters"}}}; + o2::raw::HBFUtilsInitializer::addConfigOption(options); + std::swap(workflowOptions, options); } @@ -146,18 +149,23 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) } bool doMC = not cfgc.options().get("disable-mc"); - return o2::tpc::reco_workflow::getWorkflow(&gPolicyData, // - tpcSectors, // sector configuration - gTpcSectorMask, // same as bitmask - laneConfiguration, // lane configuration - doMC, // - nLanes, // - inputType, // - cfgc.options().get("output-type"), // - !cfgc.options().get("no-ca-clusterer"), // - !cfgc.options().get("no-tpc-zs-on-the-fly"), // - cfgc.options().get("zs-10bit"), // - cfgc.options().get("zs-threshold"), // - !cfgc.options().get("ignore-dist-stf") // + auto wf = o2::tpc::reco_workflow::getWorkflow(&gPolicyData, // + tpcSectors, // sector configuration + gTpcSectorMask, // same as bitmask + laneConfiguration, // lane configuration + doMC, // + nLanes, // + inputType, // + cfgc.options().get("output-type"), // + !cfgc.options().get("no-ca-clusterer"), // + !cfgc.options().get("no-tpc-zs-on-the-fly"), // + cfgc.options().get("zs-10bit"), // + cfgc.options().get("zs-threshold"), // + !cfgc.options().get("ignore-dist-stf") // ); + + // write the configuration used for the digitizer workflow + o2::conf::ConfigurableParam::writeINI("o2tpcrecoflow_configuration.ini"); + + return std::move(wf); } diff --git a/Detectors/TRD/workflow/src/trd-tracking-workflow.cxx b/Detectors/TRD/workflow/src/trd-tracking-workflow.cxx index 21bd0e7e01d9e..49782fdba0a1f 100644 --- a/Detectors/TRD/workflow/src/trd-tracking-workflow.cxx +++ b/Detectors/TRD/workflow/src/trd-tracking-workflow.cxx @@ -11,6 +11,7 @@ #include "TRDWorkflow/TRDTrackingWorkflow.h" #include "CommonUtils/ConfigurableParam.h" #include "Framework/CompletionPolicy.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" using namespace o2::framework; @@ -20,14 +21,16 @@ using namespace o2::framework; void customize(std::vector& workflowOptions) { // option allowing to set parameters - workflowOptions.push_back(ConfigParamSpec{"disable-mc", o2::framework::VariantType::Bool, false, {"Disable MC labels"}}); - workflowOptions.push_back(ConfigParamSpec{"use-tracklet-transformer", VariantType::Bool, false, {"Use calibrated tracklets instead raw Tracklet64"}}); - workflowOptions.push_back(ConfigParamSpec{ - "disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}); - workflowOptions.push_back(ConfigParamSpec{ - "disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}); - std::string keyvaluehelp("Semicolon separated key=value strings ..."); - workflowOptions.push_back(ConfigParamSpec{"configKeyValues", VariantType::String, "", {keyvaluehelp}}); + std::vector options{ + {"disable-mc", o2::framework::VariantType::Bool, false, {"Disable MC labels"}}, + {"use-tracklet-transformer", VariantType::Bool, false, {"Use calibrated tracklets instead raw Tracklet64"}}, + {"disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}, + {"disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}, + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}}; + + o2::raw::HBFUtilsInitializer::addConfigOption(options); + + std::swap(workflowOptions, options); } // ------------------------------------------------------------------ @@ -43,5 +46,11 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) auto disableRootInp = configcontext.options().get("disable-root-input"); auto disableRootOut = configcontext.options().get("disable-root-output"); auto useTrackletTransformer = configcontext.options().get("use-tracklet-transformer"); - return std::move(o2::trd::getTRDTrackingWorkflow(disableRootInp, disableRootOut, useTrackletTransformer)); + + auto wf = o2::trd::getTRDTrackingWorkflow(disableRootInp, disableRootOut, useTrackletTransformer); + + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(configcontext, wf); + + return std::move(wf); } From 80b6dba12979f6a9561a28f6f02b3939e1d4c0a0 Mon Sep 17 00:00:00 2001 From: shahoian Date: Sun, 11 Apr 2021 21:00:15 +0200 Subject: [PATCH 100/770] Rename hmpid::Event to Trigger, use mDataRange for digits indexing --- DataFormats/Detectors/HMPID/CMakeLists.txt | 4 +- .../HMPID/include/DataFormatsHMP/Digit.h | 14 +++--- .../HMPID/include/DataFormatsHMP/Trigger.h | 47 ++++++++----------- .../HMPID/src/DataFormatsHMPLinkDef.h | 4 +- DataFormats/Detectors/HMPID/src/Trigger.cxx | 6 +-- .../include/HMPIDWorkflow/RawToDigitsSpec.h | 2 +- .../include/HMPIDWorkflow/WriteRawFileSpec.h | 2 +- .../HMPID/workflow/src/DigitsToRawSpec.cxx | 14 +++--- .../HMPID/workflow/src/RawToDigitsSpec.cxx | 40 ++++++++-------- .../HMPID/workflow/src/WriteRawFileSpec.cxx | 9 ++-- .../src/HMPIDDigitWriterSpec.h | 2 +- .../src/HMPIDDigitizerSpec.cxx | 5 +- 12 files changed, 71 insertions(+), 78 deletions(-) diff --git a/DataFormats/Detectors/HMPID/CMakeLists.txt b/DataFormats/Detectors/HMPID/CMakeLists.txt index 4ff82f9474eb8..2bf771ca8a051 100644 --- a/DataFormats/Detectors/HMPID/CMakeLists.txt +++ b/DataFormats/Detectors/HMPID/CMakeLists.txt @@ -9,7 +9,9 @@ # submit itself to any jurisdiction. o2_add_library(DataFormatsHMP - SOURCES src/Digit.cxx src/Cluster.cxx src/Trigger.cxx + SOURCES src/Digit.cxx + src/Cluster.cxx + src/Trigger.cxx PUBLIC_LINK_LIBRARIES O2::ReconstructionDataFormats O2::HMPIDBase O2::CommonDataFormat diff --git a/DataFormats/Detectors/HMPID/include/DataFormatsHMP/Digit.h b/DataFormats/Detectors/HMPID/include/DataFormatsHMP/Digit.h index fc7708bf23f5a..759793af67c75 100644 --- a/DataFormats/Detectors/HMPID/include/DataFormatsHMP/Digit.h +++ b/DataFormats/Detectors/HMPID/include/DataFormatsHMP/Digit.h @@ -78,11 +78,8 @@ class Digit // Getter & Setters uint16_t getCharge() const { return mQ; } - void setCharge(uint16_t Q) - { - mQ = Q; - return; - }; + void setCharge(uint16_t Q) { mQ = Q; }; + int getPadID() const { return mCh << 24 | mPh << 16 | mX << 8 | mY; } void setPadID(uint32_t pad) { @@ -90,7 +87,6 @@ class Digit mPh = (pad & 0x00FF0000) >> 16; mX = (pad & 0x0000FF00) >> 8; mY = (pad & 0x000000FF); - return; }; bool isValid() { return (mCh == 0xFF ? true : false); }; @@ -118,6 +114,12 @@ class Digit } void subCharge(float q) { mQ -= q; } + uint16_t getQ() const { return mQ; } + uint8_t getCh() const { return mCh; } + uint8_t getPh() const { return mPh; } + uint8_t getX() const { return mX; } + uint8_t getY() const { return mY; } + public: // Members uint16_t mQ = 0; diff --git a/DataFormats/Detectors/HMPID/include/DataFormatsHMP/Trigger.h b/DataFormats/Detectors/HMPID/include/DataFormatsHMP/Trigger.h index 851854bd3c21b..e0f59fad6d511 100644 --- a/DataFormats/Detectors/HMPID/include/DataFormatsHMP/Trigger.h +++ b/DataFormats/Detectors/HMPID/include/DataFormatsHMP/Trigger.h @@ -19,6 +19,7 @@ #include #include "CommonDataFormat/InteractionRecord.h" +#include "CommonDataFormat/RangeReference.h" namespace o2 { @@ -26,24 +27,25 @@ namespace hmpid { /// \class Trigger /// \brief HMPID Trigger declaration -class Event +class Trigger { + using DataRange = o2::dataformats::RangeReference; + public: static inline uint64_t getTriggerID(uint32_t Orbit, uint16_t BC) { return ((Orbit << 12) | (0x0FFF & BC)); }; public: - Event() = default; - Event(InteractionRecord ir, int32_t first, int32_t last) - { - mIr.bc = ir.bc; - mIr.orbit = ir.orbit; - mFirstDigit = first; - mLastDigit = last; - }; + Trigger() = default; + Trigger(InteractionRecord ir, int32_t first, int32_t n) : mIr(ir), mDataRange(first, n) {} + const InteractionRecord& getIr() const { return mIr; }; uint32_t getOrbit() const { return mIr.orbit; }; uint16_t getBc() const { return mIr.bc; }; uint64_t getTriggerID() const { return ((mIr.orbit << 12) | (0x0FFF & mIr.bc)); }; + void setDataRange(int firstentry, int nentries) { mDataRange.set(firstentry, nentries); } + int getNumberOfObjects() const { return mDataRange.getEntries(); } + int getFirstEntry() const { return mDataRange.getFirstEntry(); } + int getLastEntry() const { return mDataRange.getFirstEntry() + mDataRange.getEntries() - 1; } void setOrbit(uint32_t orbit) { mIr.orbit = orbit; @@ -60,33 +62,24 @@ class Event mIr.bc = (trigger & 0x0FFF); return; } - void setDigitsPointer(int32_t first, int32_t last) - { - mFirstDigit = first; - mLastDigit = last; - return; - } // Operators definition ! - friend inline bool operator<(const Event& l, const Event& r) { return l.getTriggerID() < r.getTriggerID(); }; - friend inline bool operator==(const Event& l, const Event& r) { return l.getTriggerID() == r.getTriggerID(); }; - friend inline bool operator>(const Event& l, const Event& r) { return r < l; }; - friend inline bool operator<=(const Event& l, const Event& r) { return !(l > r); }; - friend inline bool operator>=(const Event& l, const Event& r) { return !(l < r); }; - friend inline bool operator!=(const Event& l, const Event& r) { return !(l == r); }; + friend inline bool operator<(const Trigger& l, const Trigger& r) { return l.getTriggerID() < r.getTriggerID(); }; + friend inline bool operator==(const Trigger& l, const Trigger& r) { return l.getTriggerID() == r.getTriggerID(); }; + friend inline bool operator>(const Trigger& l, const Trigger& r) { return r < l; }; + friend inline bool operator<=(const Trigger& l, const Trigger& r) { return !(l > r); }; + friend inline bool operator>=(const Trigger& l, const Trigger& r) { return !(l < r); }; + friend inline bool operator!=(const Trigger& l, const Trigger& r) { return !(l == r); }; // Digit ASCII format (Orbit,BunchCrossing)[LHC Time nSec] - friend std::ostream& operator<<(std::ostream& os, const Event& d); - - public: - int32_t mFirstDigit = 0; - int32_t mLastDigit = -1; + friend std::ostream& operator<<(std::ostream& os, const Trigger& d); private: // Members InteractionRecord mIr; + DataRange mDataRange; /// Index of the triggering event (event index and first entry in the container) - ClassDefNV(Event, 2); + ClassDefNV(Trigger, 2); }; } // namespace hmpid diff --git a/DataFormats/Detectors/HMPID/src/DataFormatsHMPLinkDef.h b/DataFormats/Detectors/HMPID/src/DataFormatsHMPLinkDef.h index cd0af6426635a..85be7c72839f9 100644 --- a/DataFormats/Detectors/HMPID/src/DataFormatsHMPLinkDef.h +++ b/DataFormats/Detectors/HMPID/src/DataFormatsHMPLinkDef.h @@ -20,7 +20,7 @@ #pragma link C++ class vector < o2::hmpid::HitType> + ; #pragma link C++ class o2::hmpid::Cluster + ; #pragma link C++ class vector < o2::hmpid::Cluster> + ; -#pragma link C++ class o2::hmpid::Event + ; -#pragma link C++ class vector < o2::hmpid::Event> + ; +#pragma link C++ class o2::hmpid::Trigger + ; +#pragma link C++ class vector < o2::hmpid::Trigger> + ; #endif diff --git a/DataFormats/Detectors/HMPID/src/Trigger.cxx b/DataFormats/Detectors/HMPID/src/Trigger.cxx index fb4edbafe044c..78d5aeab9f756 100644 --- a/DataFormats/Detectors/HMPID/src/Trigger.cxx +++ b/DataFormats/Detectors/HMPID/src/Trigger.cxx @@ -22,7 +22,7 @@ #include #include "DataFormatsHMP/Trigger.h" -ClassImp(o2::hmpid::Event); +ClassImp(o2::hmpid::Trigger); namespace o2 { @@ -30,9 +30,9 @@ namespace hmpid { // Digit ASCCI format Dump := (Orbit,BC @ LHCtime ns) [first_digit_idx .. last_digit_idx] -std::ostream& operator<<(std::ostream& os, const o2::hmpid::Event& d) +std::ostream& operator<<(std::ostream& os, const o2::hmpid::Trigger& d) { - os << "(" << d.mIr.orbit << "," << d.mIr.bc << " @ " << d.mIr.bc2ns() << " ns) [" << d.mFirstDigit << " .. " << d.mLastDigit << "]"; + os << "(" << d.mIr.orbit << "," << d.mIr.bc << " @ " << d.mIr.bc2ns() << " ns) [" << d.mDataRange.getFirstEntry() << "," << d.mDataRange.getEntries() << "]"; return os; }; diff --git a/Detectors/HMPID/workflow/include/HMPIDWorkflow/RawToDigitsSpec.h b/Detectors/HMPID/workflow/include/HMPIDWorkflow/RawToDigitsSpec.h index c6e9ffb71809a..e919c8b6bb58a 100644 --- a/Detectors/HMPID/workflow/include/HMPIDWorkflow/RawToDigitsSpec.h +++ b/Detectors/HMPID/workflow/include/HMPIDWorkflow/RawToDigitsSpec.h @@ -51,7 +51,7 @@ class RawToDigitsTask : public framework::Task o2::raw::RawFileReader mReader; o2::hmpid::HmpidDecoder2* mDecod; std::vector mAccumulateDigits; - std::vector mEvents; + std::vector mEvents; long mDigitsReceived; long mFramesReceived; diff --git a/Detectors/HMPID/workflow/include/HMPIDWorkflow/WriteRawFileSpec.h b/Detectors/HMPID/workflow/include/HMPIDWorkflow/WriteRawFileSpec.h index d00b962008ed4..808e6aa5f22bb 100644 --- a/Detectors/HMPID/workflow/include/HMPIDWorkflow/WriteRawFileSpec.h +++ b/Detectors/HMPID/workflow/include/HMPIDWorkflow/WriteRawFileSpec.h @@ -38,7 +38,7 @@ class WriteRawFileTask : public framework::Task // static bool eventEquipPadsComparision(o2::hmpid::Digit d1, o2::hmpid::Digit d2); std::string mBaseFileName = ""; std::vector mDigits; - std::vector mEvents; + std::vector mEvents; bool mSkipEmpty = false; bool mFixedPacketLenght = false; bool mOrderTheEvents = true; diff --git a/Detectors/HMPID/workflow/src/DigitsToRawSpec.cxx b/Detectors/HMPID/workflow/src/DigitsToRawSpec.cxx index 991922fb45e25..cd58458a6dff6 100644 --- a/Detectors/HMPID/workflow/src/DigitsToRawSpec.cxx +++ b/Detectors/HMPID/workflow/src/DigitsToRawSpec.cxx @@ -12,7 +12,7 @@ /// \author Antonio Franco - INFN Bari /// \version 1.0 /// \date 01 feb 2021 -/// \brief Implementation of a data processor to produce raw files from a Digits/Event root file +/// \brief Implementation of a data processor to produce raw files from a Digits/Trigger root file /// #include @@ -108,7 +108,7 @@ void DigitsToRawSpec::readRootFile() { std::vector digitsPerEvent; std::vector digits, *hmpBCDataPtr = &digits; - std::vector interactions, *interactionsPtr = &interactions; + std::vector interactions, *interactionsPtr = &interactions; // Keeps the Interactions ! mDigTree->SetBranchAddress("InteractionRecords", &interactionsPtr); @@ -135,9 +135,9 @@ void DigitsToRawSpec::readRootFile() if (mDumpDigits) { // we want the dump of digits ? std::ofstream dumpfile; dumpfile.open("/tmp/hmpDumpDigits.dat"); - for (o2::hmpid::Event e : interactions) { - dumpfile << "Event Orbit=" << e.getOrbit() << " BC=" << e.getBc() << std::endl; - for (int i = e.mFirstDigit; i <= e.mLastDigit; i++) { + for (o2::hmpid::Trigger& e : interactions) { + dumpfile << "Trigger Orbit=" << e.getOrbit() << " BC=" << e.getBc() << std::endl; + for (int i = e.getFirstEntry(); i <= e.getLastEntry(); i++) { dumpfile << digits.at(i) << std::endl; } } @@ -145,10 +145,10 @@ void DigitsToRawSpec::readRootFile() } // ready to operate LOG(INFO) << "For the entry = " << ient << " there are " << nbc << " DIGITS stored."; - for (o2::hmpid::Event e : interactions) { + for (o2::hmpid::Trigger& e : interactions) { mEventsReceived++; digitsPerEvent.clear(); - for (int i = e.mFirstDigit; i <= e.mLastDigit; i++) { + for (int i = e.getFirstEntry(); i <= e.getLastEntry(); i++) { digitsPerEvent.push_back(digits[i]); } LOG(DEBUG) << "Orbit =" << e.getOrbit() << " BC =" << e.getBc() << " Digits =" << digitsPerEvent.size(); diff --git a/Detectors/HMPID/workflow/src/RawToDigitsSpec.cxx b/Detectors/HMPID/workflow/src/RawToDigitsSpec.cxx index 2e7e6d1bc4549..c7aa78137494d 100644 --- a/Detectors/HMPID/workflow/src/RawToDigitsSpec.cxx +++ b/Detectors/HMPID/workflow/src/RawToDigitsSpec.cxx @@ -140,9 +140,9 @@ void RawToDigitsTask::run(framework::ProcessingContext& pc) } int first = mAccumulateDigits.size(); mAccumulateDigits.insert(mAccumulateDigits.end(), mDecod->mDigits.begin(), mDecod->mDigits.end()); - int last = mAccumulateDigits.size() - 1; - if (last >= first) { - mEvents.push_back(o2::hmpid::Event(mDecod->mIntReco, (uint32_t)first, (uint32_t)last)); + int last = mAccumulateDigits.size(); + if (last > first) { + mEvents.emplace_back(o2::hmpid::Trigger{mDecod->mIntReco, first, last - first}); mDigitsReceived += mDecod->mDigits.size(); } mFramesReceived++; @@ -200,9 +200,9 @@ void RawToDigitsTask::parseNoTF() } int first = mAccumulateDigits.size(); mAccumulateDigits.insert(mAccumulateDigits.end(), mDecod->mDigits.begin(), mDecod->mDigits.end()); - int last = mAccumulateDigits.size() - 1; - if (last >= first) { - mEvents.push_back(o2::hmpid::Event(mDecod->mIntReco, (uint32_t)first, (uint32_t)last)); + int last = mAccumulateDigits.size(); + if (last > first) { + mEvents.emplace_back(mDecod->mIntReco, first, last - first); mDigitsReceived += mDecod->mDigits.size(); } mFramesReceived++; @@ -236,7 +236,7 @@ void RawToDigitsTask::writeResults() /* ------ ROOT file version 1 ---------- o2::hmpid::Digit digit; - o2::hmpid::Event event; + o2::hmpid::Trigger event; TString filename; TString tit; @@ -250,23 +250,22 @@ void RawToDigitsTask::writeResults() theTree = new TTree("o2hmp", tit); theDigits = theTree->Branch("HMPDigit", &digit, sizeof(o2::hmpid::Digit), 1); - theEvents = theTree->Branch("InteractionRecords", &event, sizeof(o2::hmpid::Event), 1); + theEvents = theTree->Branch("InteractionRecords", &event, sizeof(o2::hmpid::Trigger), 1); - o2::hmpid::Event prevEvent = mEvents[0]; + o2::hmpid::Trigger prevEvent = mEvents[0]; uint32_t theFirstDigit = 0; uint32_t theLastDigit = 0; for (int e = 0; e < mEvents.size(); e++) { LOG(INFO) << "Manage event " << mEvents[e]; if (prevEvent != mEvents[e]) { // changes the event Flush It event = prevEvent; - event.mFirstDigit = theFirstDigit; - event.mLastDigit = theLastDigit-1; + event.setDataRange(theFirstDigit, theLastDigit-theFirstDigit); theEvents->Fill(); theFirstDigit = theLastDigit; prevEvent = mEvents[e]; } - int first = mEvents[e].mFirstDigit; - int last = mEvents[e].mLastDigit; + int first = mEvents[e].getFirstEntry(); + int last = mEvents[e].getLastEntry(); for(int idx = first; idx <= last; idx++) { digit = mAccumulateDigits[idx]; theDigits->Fill(); @@ -274,8 +273,7 @@ void RawToDigitsTask::writeResults() } } event = prevEvent; - event.mFirstDigit = theFirstDigit; - event.mLastDigit = theLastDigit-1; + event.setDataRange(theFirstDigit, theLastDigit-theFirstDigit); theEvents->Fill(); theTree->Write(); mfileOut.Close(); @@ -286,7 +284,7 @@ void RawToDigitsTask::writeResults() TString tit; std::vector digitVec; - std::vector eventVec; + std::vector eventVec; filename = TString::Format("%s", mOutRootFileName.c_str()); LOG(INFO) << "Create the ROOT file " << filename.Data(); @@ -298,24 +296,24 @@ void RawToDigitsTask::writeResults() theTree->Branch("HMPIDDigits", &digitVec); // builds the two arranged vectors of objects - o2::hmpid::Event prevEvent = mEvents[0]; + o2::hmpid::Trigger prevEvent = mEvents[0]; uint32_t theFirstDigit = 0; uint32_t theLastDigit = 0; for (int e = 0; e < mEvents.size(); e++) { LOG(DEBUG) << "Manage event " << mEvents[e]; if (prevEvent != mEvents[e]) { // changes the event Flush It - eventVec.push_back(o2::hmpid::Event(o2::InteractionRecord(prevEvent.getBc(), prevEvent.getOrbit()), theFirstDigit, theLastDigit - 1)); + eventVec.emplace_back(o2::InteractionRecord(prevEvent.getBc(), prevEvent.getOrbit()), theFirstDigit, theLastDigit - theFirstDigit); theFirstDigit = theLastDigit; prevEvent = mEvents[e]; } - int first = mEvents[e].mFirstDigit; - int last = mEvents[e].mLastDigit; + int first = mEvents[e].getFirstEntry(); + int last = mEvents[e].getLastEntry(); for (int idx = first; idx <= last; idx++) { digitVec.push_back(mAccumulateDigits[idx]); theLastDigit++; } } - eventVec.push_back(o2::hmpid::Event(o2::InteractionRecord(prevEvent.getBc(), prevEvent.getOrbit()), theFirstDigit, theLastDigit - 1)); + eventVec.emplace_back(o2::InteractionRecord(prevEvent.getBc(), prevEvent.getOrbit()), theFirstDigit, theLastDigit - theFirstDigit); theTree->Fill(); theTree->Write(); mfileOut.Close(); diff --git a/Detectors/HMPID/workflow/src/WriteRawFileSpec.cxx b/Detectors/HMPID/workflow/src/WriteRawFileSpec.cxx index ea3419ef33f58..74d8dfa6f64d1 100644 --- a/Detectors/HMPID/workflow/src/WriteRawFileSpec.cxx +++ b/Detectors/HMPID/workflow/src/WriteRawFileSpec.cxx @@ -15,7 +15,7 @@ /// \brief Implementation of a data processor to produce raw files from a Digits stream /// -#include "../include/HMPIDWorkflow/WriteRawFileSpec.h" +#include "HMPIDWorkflow/WriteRawFileSpec.h" #include #include @@ -97,8 +97,7 @@ void WriteRawFileTask::run(framework::ProcessingContext& pc) if (mOrderTheEvents) { int first = mDigits.size(); mDigits.insert(mDigits.end(), digits.begin(), digits.end()); - int last = mDigits.size() - 1; - mEvents.push_back({intReco, first, last}); + mEvents.push_back({intReco, first, int(mDigits.size() - first)}); } else { mCod->codeEventChunkDigits(digits, intReco); } @@ -120,7 +119,7 @@ void WriteRawFileTask::endOfStream(framework::EndOfStreamContext& ec) uint32_t orbit = mEvents[0].getOrbit(); uint16_t bc = mEvents[0].getBc(); for (int idx = 0; idx < mEvents.size(); idx++) { - if (mSkipEmpty && (mEvents[idx].mLastDigit < mEvents[idx].mFirstDigit || mEvents[idx].getOrbit() == 0)) { + if (mSkipEmpty && (mEvents[idx].getNumberOfObjects() == 0 || mEvents[idx].getOrbit() == 0)) { continue; } if (mEvents[idx].getOrbit() != orbit || mEvents[idx].getBc() != bc) { @@ -130,7 +129,7 @@ void WriteRawFileTask::endOfStream(framework::EndOfStreamContext& ec) orbit = mEvents[idx].getOrbit(); bc = mEvents[idx].getBc(); } - for (int i = mEvents[idx].mFirstDigit; i <= mEvents[idx].mLastDigit; i++) { + for (int i = mEvents[idx].getFirstEntry(); i <= mEvents[idx].getLastEntry(); i++) { dig.push_back(mDigits[i]); } } diff --git a/Steer/DigitizerWorkflow/src/HMPIDDigitWriterSpec.h b/Steer/DigitizerWorkflow/src/HMPIDDigitWriterSpec.h index 35ae3d46d86f0..058dc3e1f6759 100644 --- a/Steer/DigitizerWorkflow/src/HMPIDDigitWriterSpec.h +++ b/Steer/DigitizerWorkflow/src/HMPIDDigitWriterSpec.h @@ -36,7 +36,7 @@ o2::framework::DataProcessorSpec getHMPIDDigitWriterSpec(bool mctruth = true) "o2sim", 1, BranchDefinition>{InputSpec{"digitinput", "HMP", "DIGITS"}, "HMPDigit"}, - BranchDefinition>{InputSpec{"interactionrecods", "HMP", "INTRECORDS"}, "InteractionRecords"}, + BranchDefinition>{InputSpec{"interactionrecods", "HMP", "INTRECORDS"}, "InteractionRecords"}, BranchDefinition>{InputSpec{"labelinput", "HMP", "DIGITLBL"}, "HMPDigitLabels", mctruth ? 1 : 0})(); } diff --git a/Steer/DigitizerWorkflow/src/HMPIDDigitizerSpec.cxx b/Steer/DigitizerWorkflow/src/HMPIDDigitizerSpec.cxx index 33a7bffa989ba..f28d1033a89be 100644 --- a/Steer/DigitizerWorkflow/src/HMPIDDigitizerSpec.cxx +++ b/Steer/DigitizerWorkflow/src/HMPIDDigitizerSpec.cxx @@ -80,12 +80,11 @@ class HMPIDDPLDigitizerTask : public o2::base::BaseDPLDigitizer LOG(INFO) << "NUMBER OF LABEL OBTAINED " << mLabels.getNElements(); int32_t first = digitsAccum.size(); // this is the first std::copy(mDigits.begin(), mDigits.end(), std::back_inserter(digitsAccum)); - int32_t last = digitsAccum.size() - 1; // this is the last labelAccum.mergeAtBack(mLabels); // save info for the triggers accepted LOG(INFO) << "Trigger Orbit :" << mDigitizer.getOrbit() << " BC:" << mDigitizer.getBc(); - mIntRecord.push_back(o2::hmpid::Event(o2::InteractionRecord(mDigitizer.getBc(), mDigitizer.getOrbit()), first, last)); + mIntRecord.push_back(o2::hmpid::Trigger(o2::InteractionRecord(mDigitizer.getBc(), mDigitizer.getOrbit()), first, digitsAccum.size() - first)); }; // loop over all composite collisions given from context @@ -142,7 +141,7 @@ class HMPIDDPLDigitizerTask : public o2::base::BaseDPLDigitizer std::vector mSimChains; std::vector mDigits; o2::dataformats::MCTruthContainer mLabels; // labels which get filled - std::vector mIntRecord; + std::vector mIntRecord; // RS: at the moment using hardcoded flag for continuous readout o2::parameters::GRPObject::ROMode mROMode = o2::parameters::GRPObject::CONTINUOUS; // readout mode From 1819d147fa627289f9e3843ea9e173075e14fa23 Mon Sep 17 00:00:00 2001 From: shahoian Date: Sun, 11 Apr 2021 21:02:02 +0200 Subject: [PATCH 101/770] Multiple fixes in HMPID Raw->Digit Add expired messages mechanism, fix input specs, suppress unneeded inputs --- .../include/HMPIDWorkflow/DataDecoderSpec.h | 2 +- .../HMPID/workflow/src/DataDecoderSpec.cxx | 29 ++++++++++++++----- .../src/raw-to-digits-stream-workflow.cxx | 4 ++- 3 files changed, 26 insertions(+), 9 deletions(-) diff --git a/Detectors/HMPID/workflow/include/HMPIDWorkflow/DataDecoderSpec.h b/Detectors/HMPID/workflow/include/HMPIDWorkflow/DataDecoderSpec.h index db5b7c4525b74..5ff1cd35e606e 100644 --- a/Detectors/HMPID/workflow/include/HMPIDWorkflow/DataDecoderSpec.h +++ b/Detectors/HMPID/workflow/include/HMPIDWorkflow/DataDecoderSpec.h @@ -45,7 +45,7 @@ class DataDecoderTask : public framework::Task ExecutionTimer mExTimer; }; -o2::framework::DataProcessorSpec getDecodingSpec(std::string inputSpec = "TF:HMP/RAWDATA"); +o2::framework::DataProcessorSpec getDecodingSpec(bool askSTFDist); } // end namespace hmpid } // end namespace o2 diff --git a/Detectors/HMPID/workflow/src/DataDecoderSpec.cxx b/Detectors/HMPID/workflow/src/DataDecoderSpec.cxx index df09358548eeb..837a6bb92c940 100644 --- a/Detectors/HMPID/workflow/src/DataDecoderSpec.cxx +++ b/Detectors/HMPID/workflow/src/DataDecoderSpec.cxx @@ -37,6 +37,7 @@ #include "Framework/Task.h" #include "Framework/WorkflowSpec.h" #include "Framework/Logger.h" +#include "Framework/InputRecordWalker.h" #include "Headers/RAWDataHeader.h" #include "DetectorsRaw/RDHUtils.h" @@ -159,6 +160,21 @@ void DataDecoderTask::decodeTF(framework::ProcessingContext& pc) // get the input buffer auto& inputs = pc.inputs(); + + // if we see requested data type input with 0xDEADBEEF subspec and 0 payload this means that the "delayed message" + // mechanism created it in absence of real data from upstream. Processor should send empty output to not block the workflow + { + std::vector dummy{InputSpec{"dummy", ConcreteDataMatcher{"HMP", "RAWDATA", 0xDEADBEEF}}}; + for (const auto& ref : InputRecordWalker(inputs, dummy)) { + const auto dh = o2::framework::DataRefUtils::getHeader(ref); + if (dh->payloadSize == 0) { + LOGP(WARNING, "Found input [{}/{}/{:#x}] TF#{} 1st_orbit:{} Payload {} : assuming no payload for all links in this TF", + dh->dataOrigin.str, dh->dataDescription.str, dh->subSpecification, dh->tfCounter, dh->firstTForbit, dh->payloadSize); + return; + } + } + } + DPLRawParser parser(inputs, o2::framework::select("TF:HMP/RAWDATA")); mDeco->mDigits.clear(); for (auto it = parser.begin(), end = parser.end(); it != end; ++it) { @@ -253,14 +269,13 @@ void DataDecoderTask::decodeRawFile(framework::ProcessingContext& pc) } //_________________________________________________________________________________________________ -o2::framework::DataProcessorSpec getDecodingSpec(std::string inputSpec) +o2::framework::DataProcessorSpec getDecodingSpec(bool askDISTSTF) { std::vector inputs; - inputs.emplace_back("TF", o2::framework::ConcreteDataTypeMatcher{"HMP", "RAWDATA"}, o2::framework::Lifetime::Timeframe); - inputs.emplace_back("file", o2::framework::ConcreteDataTypeMatcher{"ROUT", "RAWDATA"}, o2::framework::Lifetime::Timeframe); - // inputs.emplace_back("readout", o2::header::gDataOriginHMP, "RAWDATA", 0, Lifetime::Timeframe); - // inputs.emplace_back("readout", o2::header::gDataOriginHMP, "RAWDATA", 0, Lifetime::Timeframe); - // inputs.emplace_back("rawfile", o2::header::gDataOriginHMP, "RAWDATA", 0, Lifetime::Timeframe); + inputs.emplace_back("TF", o2::framework::ConcreteDataTypeMatcher{"HMP", "RAWDATA"}, o2::framework::Lifetime::Optional); + if (askDISTSTF) { + inputs.emplace_back("stdDist", "FLP", "DISTSUBTIMEFRAME", 0, Lifetime::Timeframe); + } std::vector outputs; outputs.emplace_back("HMP", "DIGITS", 0, o2::framework::Lifetime::Timeframe); @@ -268,7 +283,7 @@ o2::framework::DataProcessorSpec getDecodingSpec(std::string inputSpec) return DataProcessorSpec{ "HMP-RawStreamDecoder", - o2::framework::select(inputSpec.c_str()), + inputs, outputs, AlgorithmSpec{adaptFromTask()}, Options{{"result-file", VariantType::String, "/tmp/hmpRawDecodeResults", {"Base name of the decoding results files."}}, diff --git a/Detectors/HMPID/workflow/src/raw-to-digits-stream-workflow.cxx b/Detectors/HMPID/workflow/src/raw-to-digits-stream-workflow.cxx index 1f5487550bd53..8c3d00d5be0a2 100644 --- a/Detectors/HMPID/workflow/src/raw-to-digits-stream-workflow.cxx +++ b/Detectors/HMPID/workflow/src/raw-to-digits-stream-workflow.cxx @@ -49,6 +49,7 @@ void customize(std::vector& workflowOptions) { std::string keyvaluehelp("Semicolon separated key=value strings ..."); workflowOptions.push_back(o2::framework::ConfigParamSpec{"configKeyValues", o2::framework::VariantType::String, "", {keyvaluehelp}}); + workflowOptions.push_back(o2::framework::ConfigParamSpec{"ignore-dist-stf", o2::framework::VariantType::Bool, false, {"do not subscribe to FLP/DISTSUBTIMEFRAME/0 message (no lost TF recovery)"}}); } #include "Framework/runDataProcessing.h" @@ -61,7 +62,8 @@ WorkflowSpec defineDataProcessing(const ConfigContext& cx) { WorkflowSpec specs; o2::conf::ConfigurableParam::updateFromString(cx.options().get("configKeyValues")); - DataProcessorSpec producer = o2::hmpid::getDecodingSpec(); + auto askSTFDist = !cx.options().get("ignore-dist-stf"); + DataProcessorSpec producer = o2::hmpid::getDecodingSpec(askSTFDist); specs.push_back(producer); return specs; } From 7883a0cff1a962b81517c2f0ef432b18322404a1 Mon Sep 17 00:00:00 2001 From: shahoian Date: Sun, 11 Apr 2021 21:03:07 +0200 Subject: [PATCH 102/770] HMPID CTF added --- DataFormats/Detectors/HMPID/CMakeLists.txt | 4 +- .../HMPID/include/DataFormatsHMP/CTF.h | 56 +++++ DataFormats/Detectors/HMPID/src/CTF.cxx | 15 ++ .../HMPID/src/DataFormatsHMPLinkDef.h | 4 + Detectors/HMPID/reconstruction/CMakeLists.txt | 2 + .../include/HMPIDReconstruction/CTFCoder.h | 158 ++++++++++++ .../include/HMPIDReconstruction/CTFHelper.h | 225 ++++++++++++++++++ .../HMPID/reconstruction/src/CTFCoder.cxx | 79 ++++++ .../HMPID/reconstruction/src/CTFHelper.cxx | 15 ++ Detectors/HMPID/workflow/CMakeLists.txt | 13 +- .../HMPIDWorkflow/EntropyDecoderSpec.h | 31 +++ .../HMPIDWorkflow/EntropyEncoderSpec.h | 31 +++ .../HMPID/workflow/src/EntropyDecoderSpec.cxx | 95 ++++++++ .../HMPID/workflow/src/EntropyEncoderSpec.cxx | 95 ++++++++ .../workflow/src/entropy-encoder-workflow.cxx | 39 +++ 15 files changed, 860 insertions(+), 2 deletions(-) create mode 100644 DataFormats/Detectors/HMPID/include/DataFormatsHMP/CTF.h create mode 100644 DataFormats/Detectors/HMPID/src/CTF.cxx create mode 100644 Detectors/HMPID/reconstruction/include/HMPIDReconstruction/CTFCoder.h create mode 100644 Detectors/HMPID/reconstruction/include/HMPIDReconstruction/CTFHelper.h create mode 100644 Detectors/HMPID/reconstruction/src/CTFCoder.cxx create mode 100644 Detectors/HMPID/reconstruction/src/CTFHelper.cxx create mode 100644 Detectors/HMPID/workflow/include/HMPIDWorkflow/EntropyDecoderSpec.h create mode 100644 Detectors/HMPID/workflow/include/HMPIDWorkflow/EntropyEncoderSpec.h create mode 100644 Detectors/HMPID/workflow/src/EntropyDecoderSpec.cxx create mode 100644 Detectors/HMPID/workflow/src/EntropyEncoderSpec.cxx create mode 100644 Detectors/HMPID/workflow/src/entropy-encoder-workflow.cxx diff --git a/DataFormats/Detectors/HMPID/CMakeLists.txt b/DataFormats/Detectors/HMPID/CMakeLists.txt index 2bf771ca8a051..9479d9163efb5 100644 --- a/DataFormats/Detectors/HMPID/CMakeLists.txt +++ b/DataFormats/Detectors/HMPID/CMakeLists.txt @@ -12,6 +12,7 @@ o2_add_library(DataFormatsHMP SOURCES src/Digit.cxx src/Cluster.cxx src/Trigger.cxx + src/CTF.cxx PUBLIC_LINK_LIBRARIES O2::ReconstructionDataFormats O2::HMPIDBase O2::CommonDataFormat @@ -22,4 +23,5 @@ o2_target_root_dictionary(DataFormatsHMP include/DataFormatsHMP/Digit.h include/DataFormatsHMP/Trigger.h include/DataFormatsHMP/Cluster.h - include/DataFormatsHMP/Hit.h) + include/DataFormatsHMP/Hit.h + include/DataFormatsHMP/CTF.h) diff --git a/DataFormats/Detectors/HMPID/include/DataFormatsHMP/CTF.h b/DataFormats/Detectors/HMPID/include/DataFormatsHMP/CTF.h new file mode 100644 index 0000000000000..1c538edc540c5 --- /dev/null +++ b/DataFormats/Detectors/HMPID/include/DataFormatsHMP/CTF.h @@ -0,0 +1,56 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file CTF.h +/// \author ruben.shahoyan@cern.ch +/// \brief Definitions for HMPID CTF data + +#ifndef O2_HMP_CTF_H +#define O2_HMP_CTF_H + +#include +#include +#include "DetectorsCommonDataFormats/EncodedBlocks.h" + +namespace o2 +{ +namespace hmpid +{ + +/// Header for a single CTF +struct CTFHeader { + uint32_t nTriggers = 0; /// number of triggers + uint32_t nDigits = 0; /// number of digits + uint32_t firstOrbit = 0; /// orbit of 1st trigger + uint16_t firstBC = 0; /// bc of 1st trigger + + ClassDefNV(CTFHeader, 1); +}; + +/// wrapper for the Entropy-encoded triggers and cells of the TF +struct CTF : public o2::ctf::EncodedBlocks { + + static constexpr size_t N = getNBlocks(); + enum Slots { BLC_bcIncTrig, + BLC_orbitIncTrig, + BLC_entriesDig, + BLC_ChID, // digits sorted in ChamberID -> 1st entry of trigger keeps abs ChID, then increments + BLC_Q, + BLC_Ph, + BLC_X, + BLC_Y + }; + ClassDefNV(CTF, 1); +}; + +} // namespace hmpid +} // namespace o2 + +#endif diff --git a/DataFormats/Detectors/HMPID/src/CTF.cxx b/DataFormats/Detectors/HMPID/src/CTF.cxx new file mode 100644 index 0000000000000..3a7628fecad8b --- /dev/null +++ b/DataFormats/Detectors/HMPID/src/CTF.cxx @@ -0,0 +1,15 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include +#include +#include "DataFormatsHMP/CTF.h" + +using namespace o2::hmpid; diff --git a/DataFormats/Detectors/HMPID/src/DataFormatsHMPLinkDef.h b/DataFormats/Detectors/HMPID/src/DataFormatsHMPLinkDef.h index 85be7c72839f9..0990cbcc8f78d 100644 --- a/DataFormats/Detectors/HMPID/src/DataFormatsHMPLinkDef.h +++ b/DataFormats/Detectors/HMPID/src/DataFormatsHMPLinkDef.h @@ -23,4 +23,8 @@ #pragma link C++ class o2::hmpid::Trigger + ; #pragma link C++ class vector < o2::hmpid::Trigger> + ; +#pragma link C++ struct o2::hmpid::CTFHeader + ; +#pragma link C++ struct o2::hmpid::CTF + ; +#pragma link C++ class o2::ctf::EncodedBlocks < o2::hmpid::CTFHeader, 8, uint32_t> + ; + #endif diff --git a/Detectors/HMPID/reconstruction/CMakeLists.txt b/Detectors/HMPID/reconstruction/CMakeLists.txt index c695ce348e459..e7909e953f2fe 100644 --- a/Detectors/HMPID/reconstruction/CMakeLists.txt +++ b/Detectors/HMPID/reconstruction/CMakeLists.txt @@ -12,6 +12,8 @@ o2_add_library(HMPIDReconstruction SOURCES src/Clusterer.cxx src/HmpidDecoder2.cxx src/HmpidEquipment.cxx + src/CTFHelper.cxx + src/CTFCoder.cxx PUBLIC_LINK_LIBRARIES O2::HMPIDBase O2::DataFormatsHMP O2::HMPIDSimulation) diff --git a/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/CTFCoder.h b/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/CTFCoder.h new file mode 100644 index 0000000000000..805dde7cae2d1 --- /dev/null +++ b/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/CTFCoder.h @@ -0,0 +1,158 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file CTFCoder.h +/// \author ruben.shahoyan@cern.ch +/// \brief class for entropy encoding/decoding of HMPID data + +#ifndef O2_HMPID_CTFCODER_H +#define O2_HMPID_CTFCODER_H + +#include +#include +#include +#include +#include "DataFormatsHMP/CTF.h" +#include "DetectorsCommonDataFormats/DetID.h" +#include "DetectorsBase/CTFCoderBase.h" +#include "rANS/rans.h" +#include "HMPIDReconstruction/CTFHelper.h" + +class TTree; + +namespace o2 +{ +namespace hmpid +{ + +class CTFCoder : public o2::ctf::CTFCoderBase +{ + public: + CTFCoder() : o2::ctf::CTFCoderBase(CTF::getNBlocks(), o2::detectors::DetID::HMP) {} + ~CTFCoder() = default; + + /// entropy-encode data to buffer with CTF + template + void encode(VEC& buff, const gsl::span& trigData, const gsl::span& digData); + + /// entropy decode data from buffer with CTF + template + void decode(const CTF::base& ec, VTRG& trigVec, VDIG& digVec); + + void createCoders(const std::string& dictPath, o2::ctf::CTFCoderBase::OpType op); + + private: + void appendToTree(TTree& tree, CTF& ec); + void readFromTree(TTree& tree, int entry, std::vector& trigVec, std::vector& digVec); +}; + +/// entropy-encode digits and to buffer with CTF +template +void CTFCoder::encode(VEC& buff, const gsl::span& trigData, const gsl::span& digData) +{ + using MD = o2::ctf::Metadata::OptStore; + // what to do which each field: see o2::ctd::Metadata explanation + constexpr MD optField[CTF::getNBlocks()] = { + MD::EENCODE, // BLC_bcIncTrig + MD::EENCODE, // BLC_orbitIncTrig + MD::EENCODE, // BLC_entriesDig + MD::EENCODE, // BLC_ChID + MD::EENCODE, // BLC_Q + MD::EENCODE, // BLC_Ph + MD::EENCODE, // BLC_X + MD::EENCODE // BLC_Y + }; + + CTFHelper helper(trigData, digData); + + // book output size with some margin + auto szIni = sizeof(CTFHeader) + helper.getSize() * 2. / 3; // will be autoexpanded if needed + buff.resize(szIni); + + auto ec = CTF::create(buff); + using ECB = CTF::base; + + ec->setHeader(helper.createHeader()); + ec->getANSHeader().majorVersion = 0; + ec->getANSHeader().minorVersion = 1; + // at every encoding the buffer might be autoexpanded, so we don't work with fixed pointer ec +#define ENCODEHMP(beg, end, slot, bits) CTF::get(buff.data())->encode(beg, end, int(slot), bits, optField[int(slot)], &buff, mCoders[int(slot)].get()); + // clang-format off + ENCODEHMP(helper.begin_bcIncTrig(), helper.end_bcIncTrig(), CTF::BLC_bcIncTrig, 0); + ENCODEHMP(helper.begin_orbitIncTrig(), helper.end_orbitIncTrig(), CTF::BLC_orbitIncTrig, 0); + ENCODEHMP(helper.begin_entriesDig(), helper.end_entriesDig(), CTF::BLC_entriesDig, 0); + + ENCODEHMP(helper.begin_ChID(), helper.end_ChID(), CTF::BLC_ChID, 0); + ENCODEHMP(helper.begin_Q(), helper.end_Q(), CTF::BLC_Q, 0); + ENCODEHMP(helper.begin_Ph(), helper.end_Ph(), CTF::BLC_Ph, 0); + ENCODEHMP(helper.begin_X(), helper.end_X(), CTF::BLC_X, 0); + ENCODEHMP(helper.begin_Y(), helper.end_Y(), CTF::BLC_Y, 0); + + // clang-format on + CTF::get(buff.data())->print(getPrefix()); +} + +/// decode entropy-encoded data to digits +template +void CTFCoder::decode(const CTF::base& ec, VTRG& trigVec, VDIG& digVec) +{ + auto header = ec.getHeader(); + ec.print(getPrefix()); + std::vector bcInc, q; + std::vector orbitInc, entriesDig; + std::vector chID, ph, x, y; + +#define DECODEHMP(part, slot) ec.decode(part, int(slot), mCoders[int(slot)].get()) + // clang-format off + DECODEHMP(bcInc, CTF::BLC_bcIncTrig); + DECODEHMP(orbitInc, CTF::BLC_orbitIncTrig); + DECODEHMP(entriesDig, CTF::BLC_entriesDig); + + DECODEHMP(chID, CTF::BLC_ChID); + DECODEHMP(q, CTF::BLC_Q); + DECODEHMP(ph, CTF::BLC_Ph); + DECODEHMP(x, CTF::BLC_X); + DECODEHMP(y, CTF::BLC_Y); + // clang-format on + // + trigVec.clear(); + digVec.clear(); + trigVec.reserve(header.nTriggers); + digVec.reserve(header.nDigits); + + uint32_t digCount = 0; + o2::InteractionRecord ir(header.firstBC, header.firstOrbit); + + for (uint32_t itrig = 0; itrig < header.nTriggers; itrig++) { + // restore TrigRecord + if (orbitInc[itrig]) { // non-0 increment => new orbit + ir.bc = bcInc[itrig]; // bcInc has absolute meaning + ir.orbit += orbitInc[itrig]; + } else { + ir.bc += bcInc[itrig]; + } + + uint32_t firstEntryDig = digVec.size(); + int8_t chid = 0; + for (uint32_t id = 0; id < entriesDig[itrig]; id++) { + chid += chID[digCount]; // 1st digit of trigger was encoded with abs ChID, then increments + auto& dig = digVec.emplace_back(chid, ph[digCount], x[digCount], y[digCount], q[digCount]); + digCount++; + } + + trigVec.emplace_back(ir, firstEntryDig, entriesDig[itrig]); + } + assert(digCount == header.nDigits); +} + +} // namespace hmpid +} // namespace o2 + +#endif // O2_HMP_CTFCODER_H diff --git a/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/CTFHelper.h b/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/CTFHelper.h new file mode 100644 index 0000000000000..e8fb092db9576 --- /dev/null +++ b/Detectors/HMPID/reconstruction/include/HMPIDReconstruction/CTFHelper.h @@ -0,0 +1,225 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file CTFHelper.h +/// \author ruben.shahoyan@cern.ch +/// \brief Helper for HMPID CTF creation + +#ifndef O2_HMPID_CTF_HELPER_H +#define O2_HMPID_CTF_HELPER_H + +#include "DataFormatsHMP/CTF.h" +#include "DataFormatsHMP/Trigger.h" +#include "DataFormatsHMP/Digit.h" +#include + +namespace o2 +{ +namespace hmpid +{ + +class CTFHelper +{ + + public: + CTFHelper(const gsl::span& trgRec, + const gsl::span& digData) + : mTrigRec(trgRec), mDigData(digData), mDigStart(digData.size()) + { + // flag start of new trigger for digits + for (const auto& trg : mTrigRec) { + if (trg.getNumberOfObjects()) { + mDigStart[trg.getFirstEntry()] = true; + } + } + } + + CTFHeader createHeader() + { + CTFHeader h{uint32_t(mTrigRec.size()), uint32_t(mDigData.size()), 0, 0}; + if (mTrigRec.size()) { + h.firstOrbit = mTrigRec[0].getOrbit(); + h.firstBC = mTrigRec[0].getBc(); + } + return h; + } + + size_t getSize() const { return mTrigRec.size() * sizeof(Trigger) + mDigData.size() * sizeof(Digit); } + + //>>> =========================== ITERATORS ======================================== + template + class _Iter + { + public: + using difference_type = int64_t; + using value_type = T; + using pointer = const T*; + using reference = const T&; + using iterator_category = std::random_access_iterator_tag; + + _Iter(const gsl::span& data, bool end = false) : mData(data), mIndex(end ? M * data.size() : 0){}; + _Iter() = default; + + const I& operator++() + { + ++mIndex; + return (I&)(*this); + } + + const I& operator--() + { + mIndex--; + return (I&)(*this); + } + + difference_type operator-(const I& other) const { return mIndex - other.mIndex; } + + difference_type operator-(size_t idx) const { return mIndex - idx; } + + const I& operator-(size_t idx) + { + mIndex -= idx; + return (I&)(*this); + } + + bool operator!=(const I& other) const { return mIndex != other.mIndex; } + bool operator==(const I& other) const { return mIndex == other.mIndex; } + bool operator>(const I& other) const { return mIndex > other.mIndex; } + bool operator<(const I& other) const { return mIndex < other.mIndex; } + + protected: + gsl::span mData{}; + size_t mIndex = 0; + }; + + //_______________________________________________ + // BC difference wrt previous if in the same orbit, otherwise the abs.value. + // For the very 1st entry return 0 (diff wrt 1st BC in the CTF header) + class Iter_bcIncTrig : public _Iter + { + public: + using _Iter::_Iter; + value_type operator*() const + { + if (mIndex) { + if (mData[mIndex].getOrbit() == mData[mIndex - 1].getOrbit()) { + return mData[mIndex].getBc() - mData[mIndex - 1].getBc(); + } else { + return mData[mIndex].getBc(); + } + } + return 0; + } + }; + + //_______________________________________________ + // Orbit difference wrt previous. For the very 1st entry return 0 (diff wrt 1st BC in the CTF header) + class Iter_orbitIncTrig : public _Iter + { + public: + using _Iter::_Iter; + value_type operator*() const { return mIndex ? mData[mIndex].getOrbit() - mData[mIndex - 1].getOrbit() : 0; } + }; + + //_______________________________________________ + // Number of digits for trigger + class Iter_entriesDig : public _Iter + { + public: + using _Iter::_Iter; + value_type operator*() const { return mData[mIndex].getNumberOfObjects(); } + }; + + //_______________________________________________ + class Iter_ChID : public _Iter + { + private: + const std::vector* mTrigStart{nullptr}; + + public: + using _Iter::_Iter; + Iter_ChID(const std::vector* ts, const gsl::span& data, bool end) : mTrigStart(ts), _Iter(data, end) {} + Iter_ChID() = default; + + // assume sorting in ChID: for the 1st digit of the trigger return the abs ChID, for the following ones: difference to previous ChID + value_type operator*() const + { + return (*mTrigStart)[mIndex] ? mData[mIndex].getCh() : mData[mIndex].getCh() - mData[mIndex - 1].getCh(); + } + }; + + //_______________________________________________ + class Iter_Q : public _Iter + { + public: + using _Iter::_Iter; + value_type operator*() const { return mData[mIndex].getQ(); } + }; + + //_______________________________________________ + class Iter_Ph : public _Iter + { + public: + using _Iter::_Iter; + value_type operator*() const { return mData[mIndex].getPh(); } + }; + + //_______________________________________________ + class Iter_X : public _Iter + { + public: + using _Iter::_Iter; + value_type operator*() const { return mData[mIndex].getX(); } + }; + + //_______________________________________________ + class Iter_Y : public _Iter + { + public: + using _Iter::_Iter; + value_type operator*() const { return mData[mIndex].getY(); } + }; + + //<<< =========================== ITERATORS ======================================== + + Iter_bcIncTrig begin_bcIncTrig() const { return Iter_bcIncTrig(mTrigRec, false); } + Iter_bcIncTrig end_bcIncTrig() const { return Iter_bcIncTrig(mTrigRec, true); } + + Iter_orbitIncTrig begin_orbitIncTrig() const { return Iter_orbitIncTrig(mTrigRec, false); } + Iter_orbitIncTrig end_orbitIncTrig() const { return Iter_orbitIncTrig(mTrigRec, true); } + + Iter_entriesDig begin_entriesDig() const { return Iter_entriesDig(mTrigRec, false); } + Iter_entriesDig end_entriesDig() const { return Iter_entriesDig(mTrigRec, true); } + + Iter_ChID begin_ChID() const { return Iter_ChID(&mDigStart, mDigData, false); } + Iter_ChID end_ChID() const { return Iter_ChID(&mDigStart, mDigData, true); } + + Iter_Q begin_Q() const { return Iter_Q(mDigData, false); } + Iter_Q end_Q() const { return Iter_Q(mDigData, true); } + + Iter_Ph begin_Ph() const { return Iter_Ph(mDigData, false); } + Iter_Ph end_Ph() const { return Iter_Ph(mDigData, true); } + + Iter_X begin_X() const { return Iter_X(mDigData, false); } + Iter_X end_X() const { return Iter_X(mDigData, true); } + + Iter_Y begin_Y() const { return Iter_Y(mDigData, false); } + Iter_Y end_Y() const { return Iter_Y(mDigData, true); } + + private: + const gsl::span mTrigRec; + const gsl::span mDigData; + std::vector mDigStart; +}; + +} // namespace hmpid +} // namespace o2 + +#endif diff --git a/Detectors/HMPID/reconstruction/src/CTFCoder.cxx b/Detectors/HMPID/reconstruction/src/CTFCoder.cxx new file mode 100644 index 0000000000000..405acb62f4140 --- /dev/null +++ b/Detectors/HMPID/reconstruction/src/CTFCoder.cxx @@ -0,0 +1,79 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file CTFCoder.cxx +/// \author ruben.shahoyan@cern.ch +/// \brief class for entropy encoding/decoding of HMP data + +#include "HMPIDReconstruction/CTFCoder.h" +#include "CommonUtils/StringUtils.h" +#include + +using namespace o2::hmpid; + +///___________________________________________________________________________________ +// Register encoded data in the tree (Fill is not called, will be done by caller) +void CTFCoder::appendToTree(TTree& tree, CTF& ec) +{ + ec.appendToTree(tree, mDet.getName()); +} + +///___________________________________________________________________________________ +// extract and decode data from the tree +void CTFCoder::readFromTree(TTree& tree, int entry, std::vector& trigVec, std::vector& digVec) +{ + assert(entry >= 0 && entry < tree.GetEntries()); + CTF ec; + ec.readFromTree(tree, mDet.getName(), entry); + decode(ec, trigVec, digVec); +} + +///________________________________ +void CTFCoder::createCoders(const std::string& dictPath, o2::ctf::CTFCoderBase::OpType op) +{ + bool mayFail = true; // RS FIXME if the dictionary file is not there, do not produce exception + auto buff = readDictionaryFromFile(dictPath, mayFail); + if (!buff.size()) { + if (mayFail) { + return; + } + throw std::runtime_error("Failed to create CTF dictionaty"); + } + const auto* ctf = CTF::get(buff.data()); + + auto getFreq = [ctf](CTF::Slots slot) -> o2::rans::FrequencyTable { + o2::rans::FrequencyTable ft; + auto bl = ctf->getBlock(slot); + auto md = ctf->getMetadata(slot); + ft.addFrequencies(bl.getDict(), bl.getDict() + bl.getNDict(), md.min, md.max); + return std::move(ft); + }; + auto getProbBits = [ctf](CTF::Slots slot) -> int { + return ctf->getMetadata(slot).probabilityBits; + }; + + // just to get types + uint16_t bcInc, HCIDTrk, q; + uint32_t orbitInc, entriesDig; + uint8_t chID, ph, x, y; + +#define MAKECODER(part, slot) createCoder(op, getFreq(slot), getProbBits(slot), int(slot)) + // clang-format off + MAKECODER(bcInc, CTF::BLC_bcIncTrig); + MAKECODER(orbitInc, CTF::BLC_orbitIncTrig); + MAKECODER(entriesDig, CTF::BLC_entriesDig); + + MAKECODER(chID, CTF::BLC_ChID); + MAKECODER(q, CTF::BLC_Q); + MAKECODER(ph, CTF::BLC_Ph); + MAKECODER(x, CTF::BLC_X); + MAKECODER(y, CTF::BLC_Y); + // clang-format on +} diff --git a/Detectors/HMPID/reconstruction/src/CTFHelper.cxx b/Detectors/HMPID/reconstruction/src/CTFHelper.cxx new file mode 100644 index 0000000000000..3ce24fcba0c49 --- /dev/null +++ b/Detectors/HMPID/reconstruction/src/CTFHelper.cxx @@ -0,0 +1,15 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file CTFHelper.cxx +/// \author ruben.shahoyan@cern.ch +/// \brief Helper for HMPID CTF creation + +#include "HMPIDReconstruction/CTFHelper.h" diff --git a/Detectors/HMPID/workflow/CMakeLists.txt b/Detectors/HMPID/workflow/CMakeLists.txt index c851f6ddbeb67..ad101cb219cd4 100644 --- a/Detectors/HMPID/workflow/CMakeLists.txt +++ b/Detectors/HMPID/workflow/CMakeLists.txt @@ -16,6 +16,9 @@ o2_add_library(HMPIDWorkflow src/RawToDigitsSpec.cxx src/ReadRawFileSpec.cxx src/WriteRawFileSpec.cxx + src/EntropyEncoderSpec.cxx + src/EntropyDecoderSpec.cxx + PUBLIC_LINK_LIBRARIES O2::Framework O2::CCDB O2::DPLUtils @@ -29,6 +32,10 @@ o2_add_library(HMPIDWorkflow # COMPONENT_NAME hmpid # SOURCES src/HMPIDRecoWorkflow.cxx # PUBLIC_LINK_LIBRARIES O2::HMPIDWorkflow) +o2_add_executable(entropy-encoder-workflow + COMPONENT_NAME hhmpid + SOURCES src/entropy-encoder-workflow.cxx + PUBLIC_LINK_LIBRARIES O2::HMPIDWorkflow) o2_add_executable(read-raw-file-stream-workflow COMPONENT_NAME hmpid @@ -64,4 +71,8 @@ o2_add_executable(digits-to-raw-stream-workflow COMPONENT_NAME hmpid SOURCES src/digits-to-raw-stream-workflow.cxx PUBLIC_LINK_LIBRARIES O2::HMPIDWorkflow) - \ No newline at end of file + +o2_add_executable(entropy-encoder-workflow + COMPONENT_NAME hmpid + SOURCES src/entropy-encoder-workflow.cxx + PUBLIC_LINK_LIBRARIES O2::HMPIDWorkflow) diff --git a/Detectors/HMPID/workflow/include/HMPIDWorkflow/EntropyDecoderSpec.h b/Detectors/HMPID/workflow/include/HMPIDWorkflow/EntropyDecoderSpec.h new file mode 100644 index 0000000000000..bbd90d3a3c4b8 --- /dev/null +++ b/Detectors/HMPID/workflow/include/HMPIDWorkflow/EntropyDecoderSpec.h @@ -0,0 +1,31 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file EntropyDecoderSpec.h +/// @brief Convert CTF (EncodedBlocks) to HMP digit/tracklets stream + +#ifndef O2_HMP_ENTROPYDECODER_SPEC +#define O2_HMP_ENTROPYDECODER_SPEC + +#include "Framework/DataProcessorSpec.h" +#include "Framework/Task.h" + +namespace o2 +{ +namespace hmpid +{ + +/// create a processor spec +framework::DataProcessorSpec getEntropyDecoderSpec(); + +} // namespace hmpid +} // namespace o2 + +#endif diff --git a/Detectors/HMPID/workflow/include/HMPIDWorkflow/EntropyEncoderSpec.h b/Detectors/HMPID/workflow/include/HMPIDWorkflow/EntropyEncoderSpec.h new file mode 100644 index 0000000000000..d5948f00f3887 --- /dev/null +++ b/Detectors/HMPID/workflow/include/HMPIDWorkflow/EntropyEncoderSpec.h @@ -0,0 +1,31 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file EntropyEncoderSpec.h +/// @brief Convert HMP data to CTF (EncodedBlocks) + +#ifndef O2_HMP_ENTROPYENCODER_SPEC +#define O2_HMP_ENTROPYENCODER_SPEC + +#include "Framework/DataProcessorSpec.h" +#include "Framework/Task.h" + +namespace o2 +{ +namespace hmpid +{ + +/// create a processor spec +framework::DataProcessorSpec getEntropyEncoderSpec(); + +} // namespace hmpid +} // namespace o2 + +#endif diff --git a/Detectors/HMPID/workflow/src/EntropyDecoderSpec.cxx b/Detectors/HMPID/workflow/src/EntropyDecoderSpec.cxx new file mode 100644 index 0000000000000..a5264b3ee4e8d --- /dev/null +++ b/Detectors/HMPID/workflow/src/EntropyDecoderSpec.cxx @@ -0,0 +1,95 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file EntropyDecoderSpec.cxx + +#include + +#include "Framework/ControlService.h" +#include "Framework/ConfigParamRegistry.h" +#include "HMPIDWorkflow/EntropyDecoderSpec.h" +#include "HMPIDReconstruction/CTFCoder.h" +#include + +using namespace o2::framework; + +namespace o2 +{ +namespace hmpid +{ + +class EntropyDecoderSpec : public o2::framework::Task +{ + public: + EntropyDecoderSpec(); + ~EntropyDecoderSpec() override = default; + void run(o2::framework::ProcessingContext& pc) final; + void init(o2::framework::InitContext& ic) final; + void endOfStream(o2::framework::EndOfStreamContext& ec) final; + + private: + o2::hmpid::CTFCoder mCTFCoder; + TStopwatch mTimer; +}; + +EntropyDecoderSpec::EntropyDecoderSpec() +{ + mTimer.Stop(); + mTimer.Reset(); +} + +void EntropyDecoderSpec::init(o2::framework::InitContext& ic) +{ + std::string dictPath = ic.options().get("hmpid-ctf-dictionary"); + if (!dictPath.empty() && dictPath != "none") { + mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Decoder); + } +} + +void EntropyDecoderSpec::run(ProcessingContext& pc) +{ + auto cput = mTimer.CpuTime(); + mTimer.Start(false); + + auto buff = pc.inputs().get>("ctf"); + + auto& triggers = pc.outputs().make>(OutputRef{"triggers"}); + auto& digits = pc.outputs().make>(OutputRef{"digits"}); + + // since the buff is const, we cannot use EncodedBlocks::relocate directly, instead we wrap its data to another flat object + const auto ctfImage = o2::hmpid::CTF::getImage(buff.data()); + mCTFCoder.decode(ctfImage, triggers, digits); + + mTimer.Stop(); + LOG(INFO) << "Decoded " << digits.size() << " HMPID digits in " << triggers.size() << " triggers in " << mTimer.CpuTime() - cput << " s"; +} + +void EntropyDecoderSpec::endOfStream(EndOfStreamContext& ec) +{ + LOGF(INFO, "HMPID Entropy Decoding total timing: Cpu: %.3e Real: %.3e s in %d slots", + mTimer.CpuTime(), mTimer.RealTime(), mTimer.Counter() - 1); +} + +DataProcessorSpec getEntropyDecoderSpec() +{ + std::vector outputs{ + OutputSpec{{"triggers"}, "HMP", "INTRECORDS", 0, Lifetime::Timeframe}, + OutputSpec{{"digits"}, "HMP", "DIGITS", 0, Lifetime::Timeframe}}; + + return DataProcessorSpec{ + "hmpid-entropy-decoder", + Inputs{InputSpec{"ctf", "HMP", "CTFDATA", 0, Lifetime::Timeframe}}, + outputs, + AlgorithmSpec{adaptFromTask()}, + Options{{"hmpid-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF decoding dictionary"}}}}; +} + +} // namespace hmpid +} // namespace o2 diff --git a/Detectors/HMPID/workflow/src/EntropyEncoderSpec.cxx b/Detectors/HMPID/workflow/src/EntropyEncoderSpec.cxx new file mode 100644 index 0000000000000..fb5472a013496 --- /dev/null +++ b/Detectors/HMPID/workflow/src/EntropyEncoderSpec.cxx @@ -0,0 +1,95 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file EntropyEncoderSpec.cxx + +#include + +#include "Framework/ControlService.h" +#include "Framework/ConfigParamRegistry.h" +#include "HMPIDWorkflow/EntropyEncoderSpec.h" +#include "HMPIDReconstruction/CTFCoder.h" +#include "DetectorsCommonDataFormats/DetID.h" +#include + +using namespace o2::framework; + +namespace o2 +{ +namespace hmpid +{ + +class EntropyEncoderSpec : public o2::framework::Task +{ + public: + EntropyEncoderSpec(); + ~EntropyEncoderSpec() override = default; + void run(o2::framework::ProcessingContext& pc) final; + void init(o2::framework::InitContext& ic) final; + void endOfStream(o2::framework::EndOfStreamContext& ec) final; + + private: + o2::hmpid::CTFCoder mCTFCoder; + TStopwatch mTimer; +}; + +EntropyEncoderSpec::EntropyEncoderSpec() +{ + mTimer.Stop(); + mTimer.Reset(); +} + +void EntropyEncoderSpec::init(o2::framework::InitContext& ic) +{ + std::string dictPath = ic.options().get("hmpid-ctf-dictionary"); + if (!dictPath.empty() && dictPath != "none") { + mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Encoder); + } +} + +void EntropyEncoderSpec::run(ProcessingContext& pc) +{ + auto cput = mTimer.CpuTime(); + mTimer.Start(false); + auto triggers = pc.inputs().get>("triggers"); + auto digits = pc.inputs().get>("digits"); + + auto& buffer = pc.outputs().make>(Output{"HMP", "CTFDATA", 0, Lifetime::Timeframe}); + mCTFCoder.encode(buffer, triggers, digits); + auto eeb = CTF::get(buffer.data()); // cast to container pointer + eeb->compactify(); // eliminate unnecessary padding + buffer.resize(eeb->size()); // shrink buffer to strictly necessary size + // eeb->print(); + mTimer.Stop(); + LOG(INFO) << "Created encoded data of size " << eeb->size() << " for HMPID in " << mTimer.CpuTime() - cput << " s"; +} + +void EntropyEncoderSpec::endOfStream(EndOfStreamContext& ec) +{ + LOGF(INFO, "HMPID Entropy Encoding total timing: Cpu: %.3e Real: %.3e s in %d slots", + mTimer.CpuTime(), mTimer.RealTime(), mTimer.Counter() - 1); +} + +DataProcessorSpec getEntropyEncoderSpec() +{ + std::vector inputs; + inputs.emplace_back("triggers", "HMP", "INTRECORDS", 0, Lifetime::Timeframe); + inputs.emplace_back("digits", "HMP", "DIGITS", 0, Lifetime::Timeframe); + + return DataProcessorSpec{ + "hmpid-entropy-encoder", + inputs, + Outputs{{"HMP", "CTFDATA", 0, Lifetime::Timeframe}}, + AlgorithmSpec{adaptFromTask()}, + Options{{"hmpid-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF encoding dictionary"}}}}; +} + +} // namespace hmpid +} // namespace o2 diff --git a/Detectors/HMPID/workflow/src/entropy-encoder-workflow.cxx b/Detectors/HMPID/workflow/src/entropy-encoder-workflow.cxx new file mode 100644 index 0000000000000..b45df80fb266a --- /dev/null +++ b/Detectors/HMPID/workflow/src/entropy-encoder-workflow.cxx @@ -0,0 +1,39 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "HMPIDWorkflow/EntropyEncoderSpec.h" +#include "CommonUtils/ConfigurableParam.h" +#include "Framework/ConfigParamSpec.h" + +using namespace o2::framework; + +// ------------------------------------------------------------------ + +// we need to add workflow options before including Framework/runDataProcessing +void customize(std::vector& workflowOptions) +{ + // option allowing to set parameters + std::vector options{ConfigParamSpec{"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}}; + + std::swap(workflowOptions, options); +} + +// ------------------------------------------------------------------ + +#include "Framework/runDataProcessing.h" + +WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) +{ + WorkflowSpec wf; + // Update the (declared) parameters if changed from the command line + o2::conf::ConfigurableParam::updateFromString(cfgc.options().get("configKeyValues")); + wf.emplace_back(o2::hmpid::getEntropyEncoderSpec()); + return wf; +} From cb21c05a90a6bee4457247765e0104bc93255e60 Mon Sep 17 00:00:00 2001 From: shahoian Date: Sun, 11 Apr 2021 21:37:08 +0200 Subject: [PATCH 103/770] Add HMPID to CTF workflows + CTF unit test --- Detectors/CTF/CMakeLists.txt | 8 ++ Detectors/CTF/test/test_ctf_io_hmpid.cxx | 103 ++++++++++++++++++ Detectors/CTF/workflow/CMakeLists.txt | 4 +- Detectors/CTF/workflow/src/CTFReaderSpec.cxx | 8 ++ Detectors/CTF/workflow/src/CTFWriterSpec.cxx | 4 + .../CTF/workflow/src/ctf-reader-workflow.cxx | 4 + 6 files changed, 130 insertions(+), 1 deletion(-) create mode 100644 Detectors/CTF/test/test_ctf_io_hmpid.cxx diff --git a/Detectors/CTF/CMakeLists.txt b/Detectors/CTF/CMakeLists.txt index a4dae5d3c104c..389aabf2bca7c 100644 --- a/Detectors/CTF/CMakeLists.txt +++ b/Detectors/CTF/CMakeLists.txt @@ -95,3 +95,11 @@ o2_add_test(trd SOURCES test/test_ctf_io_trd.cxx COMPONENT_NAME ctf LABELS ctf) + +o2_add_test(hmpid + PUBLIC_LINK_LIBRARIES O2::CTFWorkflow + O2::DataFormatsHMP + O2::HMPIDReconstruction + SOURCES test/test_ctf_io_hmpid.cxx + COMPONENT_NAME ctf + LABELS ctf) diff --git a/Detectors/CTF/test/test_ctf_io_hmpid.cxx b/Detectors/CTF/test/test_ctf_io_hmpid.cxx new file mode 100644 index 0000000000000..bbbb2a2a07064 --- /dev/null +++ b/Detectors/CTF/test/test_ctf_io_hmpid.cxx @@ -0,0 +1,103 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#define BOOST_TEST_MODULE Test HMPIDCTFIO +#define BOOST_TEST_MAIN +#define BOOST_TEST_DYN_LINK +#include +#include "DetectorsCommonDataFormats/NameConf.h" +#include "HMPIDReconstruction/CTFCoder.h" +#include "DataFormatsHMP/CTF.h" +#include "Framework/Logger.h" +#include +#include +#include +#include +#include + +using namespace o2::hmpid; + +BOOST_AUTO_TEST_CASE(CTFTest) +{ + std::vector triggers; + std::vector digits; + TStopwatch sw; + sw.Start(); + o2::InteractionRecord ir(0, 0); + Digit clu; + for (int irof = 0; irof < 1000; irof++) { + ir += 1 + gRandom->Integer(200); + + auto start = digits.size(); + uint8_t chID = 0; + int n = 0; + while ((chID += gRandom->Integer(10)) < 0xff) { + uint16_t q = gRandom->Integer(0xffff); + uint8_t ph = gRandom->Integer(0xff); + uint8_t x = gRandom->Integer(0xff); + uint8_t y = gRandom->Integer(0xff); + digits.emplace_back(chID, ph, x, y, q); + } + triggers.emplace_back(ir, start, digits.size() - start); + } + + sw.Start(); + std::vector vec; + { + CTFCoder coder; + coder.encode(vec, triggers, digits); // compress + } + sw.Stop(); + LOG(INFO) << "Compressed in " << sw.CpuTime() << " s"; + + // writing + { + sw.Start(); + auto* ctfImage = o2::hmpid::CTF::get(vec.data()); + TFile flOut("test_ctf_hmpid.root", "recreate"); + TTree ctfTree(std::string(o2::base::NameConf::CTFTREENAME).c_str(), "O2 CTF tree"); + ctfImage->print(); + ctfImage->appendToTree(ctfTree, "HMP"); + ctfTree.Write(); + sw.Stop(); + LOG(INFO) << "Wrote to tree in " << sw.CpuTime() << " s"; + } + + // reading + vec.clear(); + LOG(INFO) << "Start reading from tree "; + { + sw.Start(); + TFile flIn("test_ctf_hmpid.root"); + std::unique_ptr tree((TTree*)flIn.Get(std::string(o2::base::NameConf::CTFTREENAME).c_str())); + BOOST_CHECK(tree); + o2::hmpid::CTF::readFromTree(vec, *(tree.get()), "HMP"); + sw.Stop(); + LOG(INFO) << "Read back from tree in " << sw.CpuTime() << " s"; + } + + std::vector triggersD; + std::vector digitsD; + + sw.Start(); + const auto ctfImage = o2::hmpid::CTF::getImage(vec.data()); + { + CTFCoder coder; + coder.decode(ctfImage, triggersD, digitsD); // decompress + } + sw.Stop(); + LOG(INFO) << "Decompressed in " << sw.CpuTime() << " s"; + + BOOST_CHECK(triggersD.size() == triggers.size()); + BOOST_CHECK(digitsD.size() == digits.size()); + + BOOST_TEST(triggersD == triggers, boost::test_tools::per_element()); + BOOST_TEST(digitsD == digits, boost::test_tools::per_element()); +} diff --git a/Detectors/CTF/workflow/CMakeLists.txt b/Detectors/CTF/workflow/CMakeLists.txt index 4d38a4ce0a6a0..ea5dcdfe51f98 100644 --- a/Detectors/CTF/workflow/CMakeLists.txt +++ b/Detectors/CTF/workflow/CMakeLists.txt @@ -23,7 +23,8 @@ o2_add_library(CTFWorkflow O2::DataFormatsMID O2::DataFormatsPHOS O2::DataFormatsCPV - O2::DataFormatsZDC + O2::DataFormatsZDC + O2::DataFormatsHMP O2::DataFormatsParameters O2::ITSMFTWorkflow O2::TPCWorkflow @@ -37,6 +38,7 @@ o2_add_library(CTFWorkflow O2::PHOSWorkflow O2::CPVWorkflow O2::ZDCWorkflow + O2::HMPIDWorkflow O2::Algorithm O2::CommonUtils) diff --git a/Detectors/CTF/workflow/src/CTFReaderSpec.cxx b/Detectors/CTF/workflow/src/CTFReaderSpec.cxx index f4de4209f94b4..6e1d62e3a3c4c 100644 --- a/Detectors/CTF/workflow/src/CTFReaderSpec.cxx +++ b/Detectors/CTF/workflow/src/CTFReaderSpec.cxx @@ -35,6 +35,7 @@ #include "DataFormatsPHOS/CTF.h" #include "DataFormatsCPV/CTF.h" #include "DataFormatsZDC/CTF.h" +#include "DataFormatsHMP/CTF.h" #include "Algorithm/RangeTokenizer.h" #include @@ -224,6 +225,13 @@ void CTFReaderSpec::run(ProcessingContext& pc) setFirstTFOrbit(det.getName()); } + det = DetID::HMP; + if (detsTF[det]) { + auto& bufVec = pc.outputs().make>({det.getName()}, sizeof(o2::hmpid::CTF)); + o2::hmpid::CTF::readFromTree(bufVec, *(tree.get()), det.getName()); + setFirstTFOrbit(det.getName()); + } + mTimer.Stop(); LOG(INFO) << "Read CTF " << inputFile << " in " << mTimer.CpuTime() - cput << " s"; diff --git a/Detectors/CTF/workflow/src/CTFWriterSpec.cxx b/Detectors/CTF/workflow/src/CTFWriterSpec.cxx index 56415ce1f30b4..7d409b29c3559 100644 --- a/Detectors/CTF/workflow/src/CTFWriterSpec.cxx +++ b/Detectors/CTF/workflow/src/CTFWriterSpec.cxx @@ -24,6 +24,7 @@ #include "DataFormatsITSMFT/CTF.h" #include "DataFormatsTPC/CTF.h" #include "DataFormatsTRD/CTF.h" +#include "DataFormatsHMP/CTF.h" #include "DataFormatsFT0/CTF.h" #include "DataFormatsFV0/CTF.h" #include "DataFormatsFDD/CTF.h" @@ -225,6 +226,7 @@ void CTFWriterSpec::run(ProcessingContext& pc) processDet(pc, DetID::PHS, header, treeOut.get()); processDet(pc, DetID::CPV, header, treeOut.get()); processDet(pc, DetID::ZDC, header, treeOut.get()); + processDet(pc, DetID::HMP, header, treeOut.get()); mTimer.Stop(); @@ -299,6 +301,8 @@ void CTFWriterSpec::storeDictionaries() storeDictionary(DetID::PHS, header); storeDictionary(DetID::CPV, header); storeDictionary(DetID::ZDC, header); + storeDictionary(DetID::HMP, header); + // close remnants if (mDictTreeOut) { closeDictionaryTreeAndFile(header); diff --git a/Detectors/CTF/workflow/src/ctf-reader-workflow.cxx b/Detectors/CTF/workflow/src/ctf-reader-workflow.cxx index 3a95dea6e9117..ae88bd74b817a 100644 --- a/Detectors/CTF/workflow/src/ctf-reader-workflow.cxx +++ b/Detectors/CTF/workflow/src/ctf-reader-workflow.cxx @@ -23,6 +23,7 @@ #include "ITSMFTWorkflow/EntropyDecoderSpec.h" #include "TPCWorkflow/EntropyDecoderSpec.h" #include "TRDWorkflow/EntropyDecoderSpec.h" +#include "HMPIDWorkflow/EntropyDecoderSpec.h" #include "FT0Workflow/EntropyDecoderSpec.h" #include "FV0Workflow/EntropyDecoderSpec.h" #include "FDDWorkflow/EntropyDecoderSpec.h" @@ -112,6 +113,9 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) if (dets[DetID::ZDC]) { specs.push_back(o2::zdc::getEntropyDecoderSpec()); } + if (dets[DetID::HMP]) { + specs.push_back(o2::hmpid::getEntropyDecoderSpec()); + } return std::move(specs); } From e7a4d25d064847fcd64baa7f7e9359a2082a8e60 Mon Sep 17 00:00:00 2001 From: Ruben Shahoyan Date: Mon, 12 Apr 2021 20:54:45 +0200 Subject: [PATCH 104/770] HBFUtils.nHBFperTF is stored in GRP, re-set default to 256 (#5901) * HBFUtils.nHBFperTF is stored in GRP, re-set default to 256 * dummy commit to trigger CI Co-authored-by: shahoian --- .../include/DataFormatsParameters/GRPObject.h | 10 +++++++--- DataFormats/Parameters/src/GRPObject.cxx | 2 +- Detectors/Raw/include/DetectorsRaw/HBFUtils.h | 2 +- Steer/DigitizerWorkflow/src/GRPUpdaterSpec.cxx | 3 ++- 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/DataFormats/Parameters/include/DataFormatsParameters/GRPObject.h b/DataFormats/Parameters/include/DataFormatsParameters/GRPObject.h index c7054c69074b6..6e001febe44ae 100644 --- a/DataFormats/Parameters/include/DataFormatsParameters/GRPObject.h +++ b/DataFormats/Parameters/include/DataFormatsParameters/GRPObject.h @@ -53,6 +53,9 @@ class GRPObject void setTimeStart(timePoint t) { mTimeStart = t; } void setTimeEnd(timePoint t) { mTimeEnd = t; } + void setNHBFPerTF(uint32_t n) { mNHBFPerTF = n; } + uint32_t getNHBFPerTF() const { return mNHBFPerTF; } + void setFirstOrbit(uint32_t o) { mFirstOrbit = o; } uint32_t getFirstOrbit() const { return mFirstOrbit; } @@ -138,10 +141,11 @@ class GRPObject static GRPObject* loadFrom(const std::string& grpFileName, const std::string& grpName = "GRP"); private: - timePoint mTimeStart = 0; ///< DAQ_time_start entry from DAQ logbook - timePoint mTimeEnd = 0; ///< DAQ_time_end entry from DAQ logbook + timePoint mTimeStart = 0; ///< DAQ_time_start entry from DAQ logbook + timePoint mTimeEnd = LONG_MAX; ///< DAQ_time_end entry from DAQ logbook - uint32_t mFirstOrbit = 0; /// 1st orbit of the 1st TF, in the MC set at digitization // RS Not sure it will stay in GRP, may go to some CTP object + uint32_t mFirstOrbit = 0; /// 1st orbit of the 1st TF, in the MC set at digitization // RS Not sure it will stay in GRP, may go to some CTP object + uint32_t mNHBFPerTF = 256; /// Number of HBFrames per TF DetID::mask_t mDetsReadout; ///< mask of detectors which are read out DetID::mask_t mDetsContinuousRO; ///< mask of detectors read out in continuos mode diff --git a/DataFormats/Parameters/src/GRPObject.cxx b/DataFormats/Parameters/src/GRPObject.cxx index 68c81689f0462..9eb6f09629e77 100644 --- a/DataFormats/Parameters/src/GRPObject.cxx +++ b/DataFormats/Parameters/src/GRPObject.cxx @@ -50,7 +50,7 @@ void GRPObject::print() const printf("Start: %s", std::ctime(&t)); t = mTimeEnd; // system_clock::to_time_t(mTimeEnd); printf("End : %s", std::ctime(&t)); - printf("1st orbit: %u\n", mFirstOrbit); + printf("1st orbit: %u, %u orbits per TF\n", mFirstOrbit, mNHBFPerTF); printf("Beam0: Z:A = %3d:%3d, Energy = %.3f\n", getBeamZ(BeamClockWise), getBeamA(BeamClockWise), getBeamEnergyPerNucleon(BeamClockWise)); printf("Beam1: Z:A = %3d:%3d, Energy = %.3f\n", getBeamZ(BeamAntiClockWise), getBeamA(BeamAntiClockWise), diff --git a/Detectors/Raw/include/DetectorsRaw/HBFUtils.h b/Detectors/Raw/include/DetectorsRaw/HBFUtils.h index b8a0ad0f36496..8a7af53e60022 100644 --- a/Detectors/Raw/include/DetectorsRaw/HBFUtils.h +++ b/Detectors/Raw/include/DetectorsRaw/HBFUtils.h @@ -125,7 +125,7 @@ struct HBFUtils : public o2::conf::ConfigurableParamHelper { void print() const { printKeyValues(true); } - int nHBFPerTF = 128; ///< number of orbits per BC + int nHBFPerTF = 256; ///< number of orbits per BC uint32_t orbitFirst = 0; ///< orbit of 1st TF of the run // used for MC diff --git a/Steer/DigitizerWorkflow/src/GRPUpdaterSpec.cxx b/Steer/DigitizerWorkflow/src/GRPUpdaterSpec.cxx index 2506067113448..466cec1b3c7f9 100644 --- a/Steer/DigitizerWorkflow/src/GRPUpdaterSpec.cxx +++ b/Steer/DigitizerWorkflow/src/GRPUpdaterSpec.cxx @@ -52,7 +52,7 @@ class GRPDPLUpdatedTask TFile flGRP(mGRPFileName.c_str(), "update"); if (flGRP.IsZombie()) { - LOG(ERROR) << "Failed to open in update mode " << mGRPFileName; + LOG(ERROR) << "Failed to open in update mode " << mGRPFileName; return; } std::unique_ptr grp(static_cast(flGRP.GetObjectChecked(grpName.c_str(), GRP::Class()))); @@ -65,6 +65,7 @@ class GRPDPLUpdatedTask grp->setDetROMode(det, roMode); } grp->setFirstOrbit(o2::raw::HBFUtils::Instance().orbitFirst); + grp->setNHBFPerTF(o2::raw::HBFUtils::Instance().nHBFPerTF); LOG(INFO) << "Updated GRP in " << mGRPFileName << " for detectors RO mode and 1st orbit of the run"; grp->print(); flGRP.WriteObjectAny(grp.get(), grp->Class(), grpName.c_str()); From 9f796adec4fd482c0b2545c8c42963edbd9cb13d Mon Sep 17 00:00:00 2001 From: peressounko Date: Tue, 13 Apr 2021 02:29:28 +0300 Subject: [PATCH 105/770] First implementation of PHOS trigger (#5821) Implementation of calibration devices Co-authored-by: Dmitri Peresunko --- .../PHOS/include/DataFormatsPHOS/Cell.h | 3 +- .../PHOS/include/DataFormatsPHOS/Cluster.h | 6 +- .../PHOS/include/DataFormatsPHOS/Digit.h | 14 +- DataFormats/Detectors/PHOS/src/Cell.cxx | 21 +- DataFormats/Detectors/PHOS/src/Digit.cxx | 5 + Detectors/CTF/test/test_ctf_io_phos.cxx | 4 +- Detectors/PHOS/README.md | 14 + Detectors/PHOS/base/README.md | 26 ++ .../PHOS/base/include/PHOSBase/Geometry.h | 6 + .../PHOS/base/include/PHOSBase/Mapping.h | 14 +- .../base/include/PHOSBase/PHOSSimParams.h | 3 + Detectors/PHOS/base/src/Geometry.cxx | 37 +++ Detectors/PHOS/base/src/Mapping.cxx | 30 +- Detectors/PHOS/calib/CMakeLists.txt | 2 + .../calib/PHOSCalibWorkflow/CMakeLists.txt | 22 +- .../include/PHOSCalibWorkflow/ETCalibHistos.h | 170 +++++++++++ .../PHOSCalibWorkflow/PHOSCalibCollector.h | 195 ------------ .../PHOSCalibWorkflow/PHOSEnergyCalibDevice.h | 64 ++++ .../PHOSCalibWorkflow/PHOSEnergyCalibrator.h | 158 ++++++++++ .../PHOSHGLGRatioCalibDevice.h | 17 +- .../PHOSPedestalCalibDevice.h | 22 +- .../PHOSRunbyrunCalibDevice.h | 57 ++++ .../PHOSRunbyrunCalibrator.h | 110 +++++++ .../PHOSCalibWorkflow/PHOSTurnonCalibDevice.h | 58 ++++ .../PHOSCalibWorkflow/PHOSTurnonCalibrator.h | 104 +++++++ .../include/PHOSCalibWorkflow/RingBuffer.h | 81 +++++ .../include/PHOSCalibWorkflow/TurnOnHistos.h | 114 +++++++ ...ollector.cxx => PHOSBadMapCalibDevice.cxx} | 0 .../src/PHOSCalibWorkflowLinkDef.h | 20 +- .../src/PHOSEnergyCalibDevice.cxx | 107 +++++++ .../src/PHOSEnergyCalibrator.cxx | 233 ++++++++++++++ .../src/PHOSHGLGRatioCalibDevice.cxx | 257 +++++++--------- .../src/PHOSPedestalCalibDevice.cxx | 200 +++++------- .../src/PHOSRunbyrunCalibDevice.cxx | 105 +++++++ .../src/PHOSRunbyrunCalibrator.cxx | 285 ++++++++++++++++++ .../src/PHOSTurnonCalibDevice.cxx | 104 +++++++ .../src/PHOSTurnonCalibrator.cxx | 201 ++++++++++++ .../PHOSCalibWorkflow/src/TurnOnHistos.cxx | 27 ++ .../src/phos-calib-workflow.cxx | 44 ++- Detectors/PHOS/calib/README.md | 68 +++++ .../calib/include/PHOSCalib/BadChannelMap.h | 9 - .../calib/include/PHOSCalib/CalibParams.h | 2 + .../PHOS/calib/include/PHOSCalib/Pedestals.h | 29 +- .../PHOS/calib/include/PHOSCalib/TriggerMap.h | 111 +++++++ Detectors/PHOS/calib/src/PHOSCalibLinkDef.h | 16 +- Detectors/PHOS/calib/src/TriggerMap.cxx | 95 ++++++ .../include/PHOSReconstruction/Clusterer.h | 9 +- .../include/PHOSReconstruction/FullCluster.h | 2 + .../PHOS/reconstruction/src/Clusterer.cxx | 90 ++++-- .../include/PHOSSimulation/Digitizer.h | 4 + .../include/PHOSSimulation/RawWriter.h | 2 + Detectors/PHOS/simulation/src/Digitizer.cxx | 92 ++++++ Detectors/PHOS/simulation/src/RawWriter.cxx | 188 ++++++++++-- .../include/PHOSWorkflow/ClusterizerSpec.h | 12 +- .../PHOSWorkflow/RawToCellConverterSpec.h | 2 + .../include/PHOSWorkflow/RecoWorkflow.h | 6 +- .../PHOS/workflow/src/CellConverterSpec.cxx | 51 ++-- .../PHOS/workflow/src/ClusterizerSpec.cxx | 29 +- .../workflow/src/RawToCellConverterSpec.cxx | 120 +++++++- Detectors/PHOS/workflow/src/RecoWorkflow.cxx | 9 +- Detectors/PHOS/workflow/src/WriterSpec.cxx | 4 +- .../PHOS/workflow/src/phos-reco-workflow.cxx | 9 +- 62 files changed, 3240 insertions(+), 659 deletions(-) create mode 100644 Detectors/PHOS/README.md create mode 100644 Detectors/PHOS/base/README.md create mode 100644 Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/ETCalibHistos.h delete mode 100644 Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSCalibCollector.h create mode 100644 Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSEnergyCalibDevice.h create mode 100644 Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSEnergyCalibrator.h create mode 100644 Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSRunbyrunCalibDevice.h create mode 100644 Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSRunbyrunCalibrator.h create mode 100644 Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSTurnonCalibDevice.h create mode 100644 Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSTurnonCalibrator.h create mode 100644 Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/RingBuffer.h create mode 100644 Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/TurnOnHistos.h rename Detectors/PHOS/calib/PHOSCalibWorkflow/src/{PHOSCalibCollector.cxx => PHOSBadMapCalibDevice.cxx} (100%) create mode 100644 Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSEnergyCalibDevice.cxx create mode 100644 Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSEnergyCalibrator.cxx create mode 100644 Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSRunbyrunCalibDevice.cxx create mode 100644 Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSRunbyrunCalibrator.cxx create mode 100644 Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSTurnonCalibDevice.cxx create mode 100644 Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSTurnonCalibrator.cxx create mode 100644 Detectors/PHOS/calib/PHOSCalibWorkflow/src/TurnOnHistos.cxx create mode 100644 Detectors/PHOS/calib/README.md create mode 100644 Detectors/PHOS/calib/include/PHOSCalib/TriggerMap.h create mode 100644 Detectors/PHOS/calib/src/TriggerMap.cxx diff --git a/DataFormats/Detectors/PHOS/include/DataFormatsPHOS/Cell.h b/DataFormats/Detectors/PHOS/include/DataFormatsPHOS/Cell.h index 290358ae4d560..809296a48eace 100644 --- a/DataFormats/Detectors/PHOS/include/DataFormatsPHOS/Cell.h +++ b/DataFormats/Detectors/PHOS/include/DataFormatsPHOS/Cell.h @@ -34,7 +34,8 @@ constexpr float kTime0 = 150.e-9; //-Minimal time to be digitized enum ChannelType_t { HIGH_GAIN, ///< High gain channel LOW_GAIN, ///< Low gain channel - TRU ///< TRU channel + TRU2x2, ///< TRU channel, 2x2 trigger + TRU4x4 ///< TRU channel, 4x4 trigger }; class Cell diff --git a/DataFormats/Detectors/PHOS/include/DataFormatsPHOS/Cluster.h b/DataFormats/Detectors/PHOS/include/DataFormatsPHOS/Cluster.h index 6cab0d2f4719e..0a15562d1f40a 100644 --- a/DataFormats/Detectors/PHOS/include/DataFormatsPHOS/Cluster.h +++ b/DataFormats/Detectors/PHOS/include/DataFormatsPHOS/Cluster.h @@ -64,10 +64,14 @@ class Cluster float getTime() const { return mTime; } + char firedTrigger() const { return mFiredTrigger; } + void setFiredTrigger(char t) { mFiredTrigger = t; } + protected: char mMulDigit = 0; ///< Digit nultiplicity char mModule = 0; ///< Module number char mNExMax = -1; ///< number of (Ex-)maxima before unfolding + char mFiredTrigger = 0; ///< matched with PHOS trigger: 0 no match, bit 1 with 2x2, bit 2 with 4x4 float mLocalPosX = 0.; ///< Center of gravity position in local module coordunates (phi direction) float mLocalPosZ = 0.; ///< Center of gravity position in local module coordunates (z direction) float mFullEnergy = 0.; ///< full energy of a shower @@ -78,7 +82,7 @@ class Cluster float mTime = 0.; ///< Time of the digit with maximal energy deposition float mDistToBadChannel = 999; ///< Distance to nearest bad crystal - ClassDefNV(Cluster, 2); + ClassDefNV(Cluster, 3); }; } // namespace phos } // namespace o2 diff --git a/DataFormats/Detectors/PHOS/include/DataFormatsPHOS/Digit.h b/DataFormats/Detectors/PHOS/include/DataFormatsPHOS/Digit.h index f68d55ed5a61b..e2c35fbf85458 100644 --- a/DataFormats/Detectors/PHOS/include/DataFormatsPHOS/Digit.h +++ b/DataFormats/Detectors/PHOS/include/DataFormatsPHOS/Digit.h @@ -38,6 +38,10 @@ class Digit : public DigitBase /// particle in case of MC \return constructed Digit Digit(short cell, float amplitude, float time, int label); + /// \brief Contructor for TRU Digits + /// \param cell truId of a tile, amplitude energy deposited in a tile, time, triggerType 2x2 or 4x4, dummy label + Digit(short cell, float amplitude, float time, bool isTrigger2x2, int label); + /// \brief Digit constructor from Hit /// \param PHOS Hit /// \return constructed Digit @@ -94,10 +98,16 @@ class Digit : public DigitBase void addEnergyTime(float energy, float time); + // true if tru and not readount digit + bool isTRU() const { return mAbsId >= NREADOUTCHANNELS; } + /// \brief Absolute sell id short getAbsId() const { return mAbsId; } void setAbsId(short cellId) { mAbsId = cellId; } + short getTRUId() const { return mAbsId - NREADOUTCHANNELS; } + void setTRUId(short cellId) { mAbsId = cellId + NREADOUTCHANNELS; } + /// \brief Energy deposited in a cell float getAmplitude() const { return mAmplitude; } void setAmplitude(float amplitude) { mAmplitude = amplitude; } @@ -110,6 +120,8 @@ class Digit : public DigitBase bool isHighGain() const { return mIsHighGain; } void setHighGain(Bool_t isHG) { mIsHighGain = isHG; } + bool is2x2Tile() { return isTRU() && isHighGain(); } + /// \brief index of entry in MCLabels array /// \return ndex of entry in MCLabels array int getLabel() const { return mLabel; } @@ -127,7 +139,7 @@ class Digit : public DigitBase void PrintStream(std::ostream& stream) const; private: - // friend class boost::serialization::access; + static constexpr short NREADOUTCHANNELS = 14337; ///< Number of channels starting from 1 bool mIsHighGain = true; ///< High Gain or Low Gain channel (for calibration) short mAbsId = 0; ///< cell index (absolute cell ID) diff --git a/DataFormats/Detectors/PHOS/src/Cell.cxx b/DataFormats/Detectors/PHOS/src/Cell.cxx index 8df065dcd37b1..320c76d9656f1 100644 --- a/DataFormats/Detectors/PHOS/src/Cell.cxx +++ b/DataFormats/Detectors/PHOS/src/Cell.cxx @@ -22,7 +22,7 @@ using namespace o2::phos; Cell::Cell(short absId, float energy, float time, ChannelType_t ctype) { - if (ctype == ChannelType_t::TRU) { + if (ctype == ChannelType_t::TRU2x2 || ctype == ChannelType_t::TRU4x4) { setTRUId(absId); } else { setAbsId(absId); @@ -127,9 +127,11 @@ void Cell::setType(ChannelType_t ctype) { switch (ctype) { case ChannelType_t::HIGH_GAIN: + case ChannelType_t::TRU2x2: setHighGain(); break; case ChannelType_t::LOW_GAIN: + case ChannelType_t::TRU4x4: setLowGain(); break; default:; @@ -138,12 +140,19 @@ void Cell::setType(ChannelType_t ctype) ChannelType_t Cell::getType() const { - if (getHighGain()) { - return ChannelType_t::HIGH_GAIN; - } else if (getTRU()) { - return ChannelType_t::TRU; + if (getTRU()) { + if (getHighGain()) { + return ChannelType_t::TRU2x2; + } else { + return ChannelType_t::TRU4x4; + } + } else { + if (getHighGain()) { + return ChannelType_t::HIGH_GAIN; + } else { + return ChannelType_t::LOW_GAIN; + } } - return ChannelType_t::LOW_GAIN; } void Cell::setLowGain() diff --git a/DataFormats/Detectors/PHOS/src/Digit.cxx b/DataFormats/Detectors/PHOS/src/Digit.cxx index 8cf06d0ba4e7d..f9b3e7d13a5fe 100644 --- a/DataFormats/Detectors/PHOS/src/Digit.cxx +++ b/DataFormats/Detectors/PHOS/src/Digit.cxx @@ -21,6 +21,11 @@ Digit::Digit(short absId, float amplitude, float time, int label) : DigitBase(time), mAmplitude(amplitude), mTime(time), mAbsId(absId), mLabel(label) { } +Digit::Digit(short truId, float amplitude, float time, bool isTrigger2x2, int /*dummy*/) + : DigitBase(time), mAmplitude(amplitude), mTime(time), mAbsId(truId + NREADOUTCHANNELS), mLabel(-1) +{ + setHighGain(isTrigger2x2); +} Digit::Digit(const Hit& hit, int label) : mAbsId(hit.GetDetectorID()), mAmplitude(hit.GetEnergyLoss()), mTime(hit.GetTime()), mLabel(label) { } diff --git a/Detectors/CTF/test/test_ctf_io_phos.cxx b/Detectors/CTF/test/test_ctf_io_phos.cxx index 964eca2dcaa5d..92cdb75422876 100644 --- a/Detectors/CTF/test/test_ctf_io_phos.cxx +++ b/Detectors/CTF/test/test_ctf_io_phos.cxx @@ -37,8 +37,8 @@ BOOST_AUTO_TEST_CASE(CTFTest) auto start = cells.size(); int n = 1 + gRandom->Poisson(100); for (int i = n; i--;) { - ChannelType_t tp = gRandom->Rndm() > 0.5 ? TRU : (gRandom->Rndm() > 0.5 ? HIGH_GAIN : LOW_GAIN); - uint16_t id = tp == TRU ? 3000 : gRandom->Integer(kNmaxCell); + ChannelType_t tp = gRandom->Rndm() > 0.5 ? (gRandom->Rndm() > 0.5 ? TRU2x2 : TRU4x4) : (gRandom->Rndm() > 0.5 ? HIGH_GAIN : LOW_GAIN); + uint16_t id = (tp == TRU2x2 || tp == TRU4x4) ? 3000 : gRandom->Integer(kNmaxCell); float timeCell = gRandom->Rndm() * 3.00e-07 - 0.3e-9; float en = gRandom->Rndm() * 160.; cells.emplace_back(id, en, timeCell, tp); diff --git a/Detectors/PHOS/README.md b/Detectors/PHOS/README.md new file mode 100644 index 0000000000000..e3b9d18f86db0 --- /dev/null +++ b/Detectors/PHOS/README.md @@ -0,0 +1,14 @@ + + +# PHOS + +This is a top page for the PHOS detector documentation. + + \ No newline at end of file diff --git a/Detectors/PHOS/base/README.md b/Detectors/PHOS/base/README.md new file mode 100644 index 0000000000000..57abc096aaf21 --- /dev/null +++ b/Detectors/PHOS/base/README.md @@ -0,0 +1,26 @@ + + +# PHOS geometry + +Module numbering: start from module 0 (non-existing), 1 (half-module), 2 (bottom),... 4(highest) + +All channels have unique absId: start from 1 till 4*64*56. Numbering in each module starts at bottom left and first go in z direction: + 56 112 3584 + ... ... ... + 1 57 ...3529 + +One can use also relative numbering relid[3]: +(module number[0...3], iphi[1...64], iz[1...56]) + + Then TRU channels go 112 per branch, 2 branches per ddl +tru channels have absId after readout channels: + absId = getTotalNCells() + TRUabsId ; + relId for TRU + relid: [DDL id=0..13] [x in 2x2 system: 0..7] [z in 2x2 system 0..27] + +Mapping is realized with class Mapping and mapping files are stored as MODxRCUy.data + + \ No newline at end of file diff --git a/Detectors/PHOS/base/include/PHOSBase/Geometry.h b/Detectors/PHOS/base/include/PHOSBase/Geometry.h index 16deaac42e10b..2d5b810df73b5 100644 --- a/Detectors/PHOS/base/include/PHOSBase/Geometry.h +++ b/Detectors/PHOS/base/include/PHOSBase/Geometry.h @@ -106,6 +106,12 @@ class Geometry static void absIdToRelPosInModule(short absId, float& x, float& z); static bool relToAbsNumbering(const char* RelId, short& AbsId); + //Converters for TRU digits + static bool truAbsToRelNumbering(short truId, char* relid); + static short truRelToAbsNumbering(const char* relId); + static bool truRelId2RelId(const char* truRelId, char* relId); + static short relPosToTruId(char mod, float x, float z, short& ddl); + //local position to absId static void relPosToAbsId(char module, float x, float z, short& absId); diff --git a/Detectors/PHOS/base/include/PHOSBase/Mapping.h b/Detectors/PHOS/base/include/PHOSBase/Mapping.h index ea3b5a9080871..8ce067d5438df 100644 --- a/Detectors/PHOS/base/include/PHOSBase/Mapping.h +++ b/Detectors/PHOS/base/include/PHOSBase/Mapping.h @@ -38,10 +38,13 @@ class Mapping kWrongAbsId, kWrongCaloFlag, kNotInitialized }; - static constexpr short NCHANNELS = 14337; ///< Number of channels starting from 1 - static constexpr short NHWPERDDL = 2048; ///< Number of HW addressed per DDL - static constexpr short NMaxHWAddress = 3929; ///< Maximal HW address (size of array) - static constexpr short NDDL = 14; ///< Total number of DDLs + static constexpr short NCHANNELS = 14337; ///< Number of channels starting from 1 + static constexpr short NHWPERDDL = 2048; ///< Number of HW addressed per DDL + static constexpr short NMaxHWAddress = 3929; ///< Maximal HW address (size of array) + static constexpr short NDDL = 14; ///< Total number of DDLs + static constexpr short NTRUBranchReadoutChannels = 112; ///< Number of TRU readout channels per branch + static constexpr short NTRUReadoutChannels = 3136; ///< Total number of TRU readout channels + static constexpr short TRUFinalProductionChannel = 123; // The last channel of production bits, contains markesr to choose between 2x2 and 4x4 algorithm enum CaloFlag { kHighGain, kLowGain, @@ -65,6 +68,9 @@ class Mapping ErrorStatus setMapping(); + //Select TRU readout channels or TRU flag channels + static bool isTRUReadoutchannel(short hwAddress) { return (hwAddress < 112) || (hwAddress > 2048 && hwAddress < 2048 + 112); } + protected: /// \brief Construct vector for conversion only if necessary ErrorStatus constructAbsToHWMatrix(); diff --git a/Detectors/PHOS/base/include/PHOSBase/PHOSSimParams.h b/Detectors/PHOS/base/include/PHOSBase/PHOSSimParams.h index 86e8e911d8ef1..bba0639e65de7 100644 --- a/Detectors/PHOS/base/include/PHOSBase/PHOSSimParams.h +++ b/Detectors/PHOS/base/include/PHOSBase/PHOSSimParams.h @@ -54,6 +54,9 @@ struct PHOSSimParams : public o2::conf::ConfigurableParamHelper { float mMinNoiseTime = -200.; ///< minimum time in noise channels (in ns) float mMaxNoiseTime = 2000.; ///< minimum time in noise channels (in ns) + float mTrig2x2MinThreshold = 800.; ///< threshold to simulate 2x2 trigger turn-on curve (in ADC counts~0.005 GeV/count!) + float mTrig4x4MinThreshold = 900.; ///< threshold to simulate 4x4 trigger turn-on curve (in ADC counts!) + //Parameters used in Raw simulation float mSampleDecayTime = 0.091; ///< Time parameter in Gamma2 function (1/tau, 100.e-9/2.1e-6) diff --git a/Detectors/PHOS/base/src/Geometry.cxx b/Detectors/PHOS/base/src/Geometry.cxx index e7db51b3547d9..2be47cb493d66 100644 --- a/Detectors/PHOS/base/src/Geometry.cxx +++ b/Detectors/PHOS/base/src/Geometry.cxx @@ -25,6 +25,11 @@ ClassImp(Geometry); // ... ... ... // 1 57 ...3529 // relid[3]: (module number[0...3], iphi[1...64], iz[1...56]) +// +// Then TRU channels go 112 per branch, 2 branches per ddl +// absId = getTotalNCells() + TRUabsId ; +// relId for TRU +// relid: [DDL id=0..13] [x in 2x2 system: 0..7] [z in 2x2 system 0..27] TODO: verify with real TRU data!!! // these initialisations are needed for a singleton Geometry* Geometry::sGeom = nullptr; @@ -76,6 +81,38 @@ bool Geometry::absToRelNumbering(short absId, char* relid) return true; } +bool Geometry::truAbsToRelNumbering(short truId, char* relid) +{ + //convert trigger cell Id to + relid[0] = truId / 224; //2*112 channels // DDL id + truId = truId % 224; + relid[1] = truId % 8; // x index in TRU internal 2x2 coordinate system + relid[2] = truId / 8; // z index in TRU internal 2x2 coordinate system + return true; +} +short Geometry::truRelToAbsNumbering(const char* relId) +{ + return relId[0] * 224 + // the offset of PHOS modules + relId[1] + // the offset along phi + relId[2] * 8; // the offset along z +} +bool Geometry::truRelId2RelId(const char* truRelId, char* relId) +{ + relId[0] = (truRelId[0] + 2) / 4; + relId[1] = ((truRelId[0] + 2) % 4) * 16 + truRelId[1] * 2 + 1; + relId[2] = truRelId[2] * 2 + 1; + return true; +} +short Geometry::relPosToTruId(char mod, float x, float z, short& ddl) +{ + //tranform local cluster coordinates to truId + const float cellStep = 2.25; + char relid[3] = {mod, static_cast(ceil(x / cellStep + 32.5)), static_cast(ceil(z / cellStep + 28.5))}; + ddl = mod / 4 + relid[1] / 16 - 2; + char truid[3] = {static_cast(ddl), static_cast((relid[1] % 16) / 2), static_cast(relid[2] / 2)}; + return truRelToAbsNumbering(truid); +} + char Geometry::absIdToModule(short absId) { const short nZ = 56; diff --git a/Detectors/PHOS/base/src/Mapping.cxx b/Detectors/PHOS/base/src/Mapping.cxx index d88e203aa5329..45f1832616112 100644 --- a/Detectors/PHOS/base/src/Mapping.cxx +++ b/Detectors/PHOS/base/src/Mapping.cxx @@ -35,6 +35,11 @@ Mapping::ErrorStatus Mapping::hwToAbsId(short ddl, short hwAddr, short& absId, C if (ddl < 0 || ddl > 14) { return kWrongDDL; } + if ((hwAddr >= 112 && hwAddr < 128) || (hwAddr >= 2159 && hwAddr < 2176)) { //TRU flags + caloFlag = kTRU; + absId = -1; + return kOK; + } if (hwAddr < 0 || hwAddr >= NMaxHWAddress) { return kWrongHWAddress; } @@ -140,26 +145,33 @@ Mapping::ErrorStatus Mapping::setMapping() return kNotInitialized; } - if (caloFlag == 2) { //TODO!!!! TRU mapping not known yet - continue; - } - //convert ddl, col,raw caloFlag to AbsId // Converts the absolute numbering into the following array // relid[0] = PHOS Module number // relid[1] = Row number inside a PHOS module (Phi coordinate) // relid[2] = Column number inside a PHOS module (Z coordinate) short ddl = 4 * m + i - 2; - - char relid[3] = {static_cast(m), static_cast(row + 1), static_cast(col + 1)}; - short absId; - geom->relToAbsNumbering(relid, absId); - if (ddl < 0 || ddl >= NDDL) { LOG(FATAL) << "Wrong ddl address found (" << ddl << "). Module= " << m << " RCU =" << i; return kNotInitialized; } + short absId; + if (caloFlag < 2) { //readout channels + char relid[3] = {static_cast(m), static_cast(row + 1), static_cast(col + 1)}; + geom->relToAbsNumbering(relid, absId); + } else { //TRU channels + if (isTRUReadoutchannel(hwAddress)) { + if (hwAddress < 2048) { //branch 28<=z<56 + absId = ddl * 2 * NTRUBranchReadoutChannels + hwAddress; + } else { //branch 0<=z<28 + absId = (ddl * 2 + 1) * NTRUBranchReadoutChannels + hwAddress - 2048; + } + } else { //TRU flag channels, no absId + continue; + } + } + mAbsId[ddl][hwAddress] = absId; mCaloFlag[ddl][hwAddress] = (CaloFlag)caloFlag; mAbsToHW[absId][caloFlag][0] = ddl; diff --git a/Detectors/PHOS/calib/CMakeLists.txt b/Detectors/PHOS/calib/CMakeLists.txt index 08839b7aa5c4a..7619aace62890 100644 --- a/Detectors/PHOS/calib/CMakeLists.txt +++ b/Detectors/PHOS/calib/CMakeLists.txt @@ -13,6 +13,7 @@ o2_add_library(PHOSCalib src/CalibParams.cxx src/Pedestals.cxx src/CalibDB.cxx + src/TriggerMap.cxx PUBLIC_LINK_LIBRARIES O2::CCDB O2::PHOSBase) o2_target_root_dictionary(PHOSCalib @@ -20,6 +21,7 @@ o2_target_root_dictionary(PHOSCalib include/PHOSCalib/CalibParams.h include/PHOSCalib/Pedestals.h include/PHOSCalib/CalibDB.h + include/PHOSCalib/TriggerMap.h LINKDEF src/PHOSCalibLinkDef.h) add_subdirectory(PHOSCalibWorkflow) diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/CMakeLists.txt b/Detectors/PHOS/calib/PHOSCalibWorkflow/CMakeLists.txt index 40a70f4a614e4..a1415fd20fd8d 100644 --- a/Detectors/PHOS/calib/PHOSCalibWorkflow/CMakeLists.txt +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/CMakeLists.txt @@ -11,7 +11,13 @@ o2_add_library(PHOSCalibWorkflow SOURCES src/PHOSPedestalCalibDevice.cxx src/PHOSHGLGRatioCalibDevice.cxx - src/PHOSCalibCollector.cxx + src/PHOSEnergyCalibrator.cxx + src/PHOSEnergyCalibDevice.cxx + src/TurnOnHistos.cxx + src/PHOSTurnonCalibDevice.cxx + src/PHOSTurnonCalibrator.cxx + src/PHOSRunbyrunCalibrator.cxx + src/PHOSRunbyrunCalibDevice.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DataFormatsPHOS O2::DetectorsRaw @@ -19,6 +25,20 @@ o2_add_library(PHOSCalibWorkflow O2::PHOSCalib O2::DetectorsCalibration) +o2_target_root_dictionary(PHOSCalibWorkflow + HEADERS include/PHOSCalibWorkflow/PHOSPedestalCalibDevice.h + include/PHOSCalibWorkflow/PHOSHGLGRatioCalibDevice.h + include/PHOSCalibWorkflow/PHOSTurnonCalibrator.h + include/PHOSCalibWorkflow/RingBuffer.h + include/PHOSCalibWorkflow/ETCalibHistos.h + include/PHOSCalibWorkflow/PHOSEnergyCalibrator.h + include/PHOSCalibWorkflow/PHOSEnergyCalibDevice.h + include/PHOSCalibWorkflow/TurnOnHistos.h + include/PHOSCalibWorkflow/PHOSTurnonCalibrator.h + include/PHOSCalibWorkflow/PHOSTurnonCalibDevice.h + include/PHOSCalibWorkflow/PHOSRunbyrunCalibrator.h + include/PHOSCalibWorkflow/PHOSRunbyrunCalibDevice.h + LINKDEF src/PHOSCalibWorkflowLinkDef.h) o2_add_executable(calib-workflow COMPONENT_NAME phos diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/ETCalibHistos.h b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/ETCalibHistos.h new file mode 100644 index 0000000000000..b4ef9e898509f --- /dev/null +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/ETCalibHistos.h @@ -0,0 +1,170 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \class ETCalibHistos +/// \brief container to store calibration info for time and energy calibration +/// \author Dmitri Peresunko, RRC Kurchatov institute +/// \since Apr. 1, 2021 +/// +/// + +#ifndef PHOS_ETCALIBHISTOS_H +#define PHOS_ETCALIBHISTOS_H + +#include +#include +#include "TObject.h" + +namespace o2 +{ + +namespace phos +{ + +class ETCalibHistos +{ + public: + //Histogram kinds to be filled + enum hnames { kReInvMassPerCell, + kMiInvMassPerCell, + kReInvMassNonlin, + kMiInvMassNonlin, + kTimeHGPerCell, + kTimeLGPerCell, + kTimeHGSlewing, + kTimeLGSlewing }; + static constexpr int nChannels = 14336 - 1793; //4 full modules -1/2 + static constexpr int offset = 1793; //1/2 full module + //mgg histos + static constexpr int nMass = 150.; + static constexpr float massMax = 0.3; + static constexpr float dm = massMax / nMass; + //time histograms + static constexpr int nTime = 200; + static constexpr float timeMin = -100.e-9; + static constexpr float timeMax = 100.e-9; + static constexpr float dt = (timeMax - timeMin) / nTime; + + //pt + static constexpr int npt = 200; + static constexpr float ptMax = 20; + static constexpr float dpt = ptMax / npt; + + /// \brief Constructor + ETCalibHistos() = default; + + ETCalibHistos& operator=(const ETCalibHistos& other) = default; + + /// \brief Destructor + ~ETCalibHistos() = default; + + /// \brief Merge statistics in two containers + /// \param other Another container to be added to current + void merge(ETCalibHistos& other) + { + for (int i = nChannels; --i;) { + for (int j = nMass; --j;) { + mReInvMassPerCell[i][j] += other.mReInvMassPerCell[i][j]; + mMiInvMassPerCell[i][j] += other.mMiInvMassPerCell[i][j]; + } + for (int j = nTime; --j;) { + mTimeHGPerCell[i][j] += other.mTimeHGPerCell[i][j]; + mTimeLGPerCell[i][j] += other.mTimeLGPerCell[i][j]; + } + } + for (int i = npt; --i;) { + for (int j = nMass; --j;) { + mReInvMassNonlin[i][j] += other.mReInvMassNonlin[i][j]; + mMiInvMassNonlin[i][j] += other.mMiInvMassNonlin[i][j]; + } + for (int j = nTime; --j;) { + mTimeHGSlewing[i][j] += other.mTimeHGSlewing[i][j]; + mTimeLGSlewing[i][j] += other.mTimeLGSlewing[i][j]; + } + } + } + + void fill(int kind, float x, float y) + { + if (kind == kReInvMassNonlin || kind == kMiInvMassNonlin) { + int i = int(x / dm); + int j = int(y / dpt); + if (i < nMass && j < npt) { + if (kind == kReInvMassNonlin) { + mReInvMassNonlin[i][j]++; + } else { + mMiInvMassNonlin[i][j]++; + } + } + } + if (kind == kTimeHGSlewing || kind == kTimeLGSlewing) { + int i = int((x - timeMin) / dt); + int j = int(y / dpt); + if (i >= 0 && i < nTime && j < npt) { + if (kind == kTimeHGSlewing) { + mTimeHGSlewing[i][j]++; + } else { + mTimeHGSlewing[i][j]++; + } + } + } + } + void fill(int kind, int x, float y) + { + if (kind == kReInvMassPerCell || kind == kMiInvMassPerCell) { + int j = int(y / dm); + if (j < nMass) { + if (kind == kReInvMassPerCell) { + mReInvMassPerCell[x - offset][j]++; + } else { + mMiInvMassPerCell[x - offset][j]++; + } + } + } + if (kind == kTimeHGPerCell || kind == kTimeLGPerCell) { + int j = int((y - timeMin) / dt); + if (j >= 0 && j < nTime) { + if (kind == kTimeHGPerCell) { + mTimeHGPerCell[x - offset][j]++; + } else { + mTimeLGPerCell[x - offset][j]++; + } + } + } + } + void reset() + { + memset(&mReInvMassPerCell, 0, sizeof(mReInvMassPerCell)); + memset(&mMiInvMassPerCell, 0, sizeof(mMiInvMassPerCell)); + memset(&mReInvMassNonlin, 0, sizeof(mReInvMassNonlin)); + memset(&mMiInvMassNonlin, 0, sizeof(mMiInvMassNonlin)); + memset(&mTimeHGPerCell, 0, sizeof(mTimeHGPerCell)); + memset(&mTimeLGPerCell, 0, sizeof(mTimeLGPerCell)); + memset(&mTimeHGSlewing, 0, sizeof(mTimeHGSlewing)); + memset(&mTimeLGSlewing, 0, sizeof(mTimeLGSlewing)); + } + + public: + std::array, nChannels> mReInvMassPerCell; ///< inv mass per cell + std::array, nChannels> mMiInvMassPerCell; ///< inv mass per cell + std::array, nMass> mReInvMassNonlin; ///< inv mass vs pT + std::array, nMass> mMiInvMassNonlin; ///< inv mass vs pT + std::array, nChannels> mTimeHGPerCell; ///< time per cell + std::array, nChannels> mTimeLGPerCell; ///< time per cell + std::array, nTime> mTimeHGSlewing; ///< time vs pT + std::array, nTime> mTimeLGSlewing; ///< time vs pT + + ClassDefNV(ETCalibHistos, 1); +}; + +} // namespace phos + +} // namespace o2 +#endif diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSCalibCollector.h b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSCalibCollector.h deleted file mode 100644 index 7c467b50e91a8..0000000000000 --- a/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSCalibCollector.h +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -#ifndef O2_PHOS_CALIB_COLLECTOR_H -#define O2_PHOS_CALIB_COLLECTOR_H - -/// @file PHOSCalibCollectorSpec.h -/// @brief Device to collect information for PHOS energy and time calibration. - -#include "Framework/Task.h" -#include "Framework/ProcessingContext.h" -#include "Framework/WorkflowSpec.h" -#include "PHOSReconstruction/FullCluster.h" -#include "PHOSCalib/CalibParams.h" -#include "PHOSCalib/BadChannelMap.h" -#include "PHOSBase/Geometry.h" - -#include -#include -#include -#include - -using namespace o2::framework; - -namespace o2 -{ -namespace phos -{ - -// structure used to store digit info for re-calibration -union CalibDigit { - uint32_t mDataWord; - struct { - uint32_t mAddress : 14; ///< Bits 0 - 13: Hardware address - uint32_t mAdcAmp : 10; ///< Bits 14 - 23: ADC counts - uint32_t mHgLg : 1; ///< Bit 24: LG/HG - uint32_t mBadChannel : 1; ///< Bit 25: Bad channel status - uint32_t mCluster : 6; ///< Bits 26-32: index of cluster in event - }; -}; -// Event header for energy calibraton. Allow accessing external info with vertex position and collision time -union EventHeader { - uint32_t mDataWord; - struct { - uint32_t mMarker : 14; ///< Bits 0 - 13: non-existing address to separate events 16383 - uint32_t mBC : 18; ///< Bits 14-32: event BC (16bit in InterationRecord. Orbit (32bit) will be stored in next word) - }; -}; - -// For real/mixed distribution calculation -class RungBuffer -{ - public: - RungBuffer() = default; - ~RungBuffer() = default; - - short size() - { - if (mFilled) { - return kBufferSize; - } else { - return mCurrent; - } - } - void addEntry(TLorentzVector& v) - { - mBuffer[mCurrent] = v; - mCurrent++; - if (mCurrent >= kBufferSize) { - mFilled = true; - mCurrent -= kBufferSize; - } - } - const TLorentzVector getEntry(short index) - { - //get entry from (mCurrent-1) corresponding to index=size()-1 down to size - if (mFilled) { - index += mCurrent; - } - index = index % kBufferSize; - return mBuffer[index]; - } - //mark that next added entry will be from next event - void startNewEvent() { mStartCurrentEvent = mCurrent; } - - bool isCurrentEvent(short index) - { - if (mCurrent >= mStartCurrentEvent) { - return (index >= mStartCurrentEvent && index < mCurrent); - } else { - return (index >= mStartCurrentEvent || index < mCurrent); - } - } - - private: - static constexpr short kBufferSize = 100; ///< Total size of the buffer - std::array mBuffer; ///< buffer - bool mFilled = false; ///< if buffer fully filled - short mCurrent = 0; ///< where next object will be added - short mStartCurrentEvent = 0; ///< start of current event -}; - -class PHOSCalibCollector : public o2::framework::Task -{ - - //Histogram kinds to be filled - enum hnames { kReInvMassPerCell, - kMiInvMassPerCell, - kReInvMassNonlin, - kMiInvMassNonlin, - kTimeHGPerCell, - kTimeLGPerCell, - kTimeHGSlewing, - kTimeLGSlewing }; - - public: - PHOSCalibCollector() = default; - PHOSCalibCollector(short mode) : mMode(mode) {} - - ~PHOSCalibCollector() override = default; - - void init(o2::framework::InitContext& ic) final; - - void run(o2::framework::ProcessingContext& pc) final; - - void endOfStream(o2::framework::EndOfStreamContext& ec) final; - - protected: - /// Scan input clusters fill histograms and prepare calibDigits - void scanClusters(o2::framework::ProcessingContext& pc); - - /// Read and scan previously stored calibDigits - void readDigits(); - - //construct new cluster from digits - //no need to reclusterize as digits wrote in order. - bool nextCluster(std::vector::const_iterator digIt, std::vector::const_iterator digEnd, FullCluster& clu, bool& isNewEvent); - - /// Fill histograns for one cluster - void fillTimeMassHisto(const FullCluster& clu); - - /// Check cluster properties and bad map - bool checkCluster(const FullCluster& clu); - - /// Write selected digits - void writeOutputs(); - - /// Evaluate calibrations from inv masses - void calculateCalibrations() {} - - // Compare calibration to previous TODO! - void compareCalib() {} - - //Check if cluster OK - bool checkCluster(FullCluster& clu); - - // Send results to (temporary of final CCDB) and to QC - void sendOutput(DataAllocator& out); - - private: - static constexpr short kMaxCluInEvent = 64; /// maximal number of clusters per event to separate digits from them (6 bits in digit map) - short mMode = 0; /// modes 0: collect new data; 1: re-scan data with new calibration; 2: produce new calibration - uint32_t mEvBC = 0; - uint32_t mEvOrbit = 0; - uint32_t mEvent = 0; - float mPtMin = 1.5; /// minimal energy to fill inv. mass histo - float mEminHGTime = 1.5; - float mEminLGTime = 5.; - std::vector mDigits; /// list of calibration digits to fill - std::vector mHistos; /// list of histos to fill - std::unique_ptr mBuffer; /// Buffer for current and previous events - std::unique_ptr mCalibParams; /// Final calibration object - std::unique_ptr mBadMap; /// Final calibration object - Geometry* mGeom; /// Pointer to PHOS singleton geometry - TVector3 mVertex; - std::string mdigitsfilename = ""; - std::string mhistosfilename = ""; - std::string mdigitsfilelist = ""; - std::string mfilenameCalib = ""; - ClassDefNV(PHOSCalibCollector, 1); -}; - -o2::framework::DataProcessorSpec getPHOSCalibCollectorDeviceSpec(int mode); - -} // namespace phos -} // namespace o2 - -#endif diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSEnergyCalibDevice.h b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSEnergyCalibDevice.h new file mode 100644 index 0000000000000..742c64f9ec21f --- /dev/null +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSEnergyCalibDevice.h @@ -0,0 +1,64 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_CALIBRATION_PHOSENERGY_CALIBDEV_H +#define O2_CALIBRATION_PHOSENERGY_CALIBDEV_H + +/// @file PHOSEnergyCalibDevice.h +/// @brief Device to collect histos and digits for PHOS energy and time calibration. + +#include "Framework/Task.h" +#include "Framework/WorkflowSpec.h" +#include "Framework/ProcessingContext.h" +#include "Framework/WorkflowSpec.h" +#include "PHOSReconstruction/FullCluster.h" +#include "PHOSCalib/BadChannelMap.h" +#include "PHOSCalib/CalibParams.h" +#include "PHOSCalibWorkflow/PHOSEnergyCalibrator.h" + +using namespace o2::framework; + +namespace o2 +{ +namespace phos +{ + +class PHOSEnergyCalibDevice : public o2::framework::Task +{ + public: + explicit PHOSEnergyCalibDevice(bool useCCDB, std::string path, std::string digitspath) : mUseCCDB(useCCDB), mCCDBPath(path), mdigitsfilename(digitspath) {} + + void init(o2::framework::InitContext& ic) final; + + void run(o2::framework::ProcessingContext& pc) final; + + void endOfStream(o2::framework::EndOfStreamContext& ec) final; + + protected: + private: + static constexpr short kMaxCluInEvent = 64; /// maximal number of clusters per event to separate digits from them (6 bits in digit map) + bool mUseCCDB = false; + std::string mCCDBPath{"http://ccdb-test.cern.ch:8080"}; ///< CCDB server path + std::string mdigitsfilename = "./CalibDigits.root"; + long mRunStartTime = 0; /// start time of the run (sec) + float mPtMin = 1.5; /// minimal energy to fill inv. mass histo + float mEminHGTime = 1.5; + float mEminLGTime = 5.; + std::unique_ptr mCalibrator; /// Agregator of calibration TimeFrameSlots + std::unique_ptr mBadMap; /// Latest bad channels map + std::unique_ptr mCalibParams; /// Latest bad channels map + ClassDefNV(PHOSEnergyCalibDevice, 1); +}; + +o2::framework::DataProcessorSpec getPHOSEnergyCalibDeviceSpec(bool useCCDB, std::string path, std::string digitspath); +} // namespace phos +} // namespace o2 + +#endif diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSEnergyCalibrator.h b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSEnergyCalibrator.h new file mode 100644 index 0000000000000..a412f0144a4ce --- /dev/null +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSEnergyCalibrator.h @@ -0,0 +1,158 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_CALIBRATION_PHOSENERGY_CALIBRATOR_H +#define O2_CALIBRATION_PHOSENERGY_CALIBRATOR_H + +/// @file PHOSEnergyCalibtor.h +/// @brief Device to collect energy and time PHOS energy and time calibration. + +#include "Framework/Task.h" +#include "Framework/WorkflowSpec.h" +#include "DetectorsCalibration/TimeSlotCalibration.h" +#include "DataFormatsPHOS/TriggerRecord.h" +#include "PHOSReconstruction/FullCluster.h" +#include "PHOSCalibWorkflow/RingBuffer.h" +#include "PHOSCalib/CalibParams.h" +#include "PHOSCalib/BadChannelMap.h" +#include "PHOSBase/Geometry.h" +#include "PHOSCalibWorkflow/ETCalibHistos.h" + +#include +#include +#include +#include + +using namespace o2::framework; + +namespace o2 +{ +namespace phos +{ + +// structure used to store digit info for re-calibration +union CalibDigit { + uint32_t mDataWord; + struct { + uint32_t mAddress : 14; ///< Bits 0 - 13: Hardware address + uint32_t mAdcAmp : 10; ///< Bits 14 - 23: ADC counts + uint32_t mHgLg : 1; ///< Bit 24: LG/HG + uint32_t mCluster : 7; ///< Bits 25-32: index of cluster in event + }; +}; +// Event header for energy calibraton. Allow accessing external info with vertex position and collision time +union EventHeader { + uint32_t mDataWord; + struct { + uint32_t mMarker : 14; ///< Bits 0 - 13: non-existing address to separate events 16383 + uint32_t mBC : 18; ///< Bits 14-32: event BC (16bit in InterationRecord. Orbit (32bit) will be stored in next word) + }; +}; + +class PHOSEnergySlot +{ + + public: + static constexpr short kMaxCluInEvent = 128; /// maximal number of clusters per event to separate digits from them (7 bits in digit map) + + PHOSEnergySlot(); + PHOSEnergySlot(const PHOSEnergySlot& other); + + ~PHOSEnergySlot() = default; + + void print() const; + void fill(const std::vector& clusters, const gsl::span& cluTR); + void fill(const gsl::span& /*c*/){}; //not used + void merge(const PHOSEnergySlot* /*prev*/) {} //not used + void clear(); + + ETCalibHistos& getCollectedHistos() { return mHistos; } + std::vector& getCollectedDigits() { return mDigits; } + + void setRunStartTime(long tf) { mRunStartTime = tf; } + void setCalibration(CalibParams& c) { mCalibParams.reset(new CalibParams(c)); } + void setBadMap(BadChannelMap& map) { mBadMap.reset(new BadChannelMap(map)); } + void setCuts(float ptMin, float eminHGTime, float eminLGTime) + { + mPtMin = ptMin; + mEminHGTime = eminHGTime; + mEminLGTime = eminLGTime; + } + + private: + void fillTimeMassHisto(const FullCluster& clu); + bool checkCluster(const FullCluster& clu); + + long mRunStartTime = 0; /// start time of the run (sec) + std::unique_ptr mBuffer; /// Buffer for current and previous events + std::unique_ptr mCalibParams; /// Final calibration object + std::unique_ptr mBadMap; /// Final calibration object + Geometry* mGeom; /// Pointer to PHOS singleton geometry + TVector3 mVertex; + ETCalibHistos mHistos; /// final histograms + uint32_t mEvBC = 0; + uint32_t mEvOrbit = 0; + uint32_t mEvent = 0; + float mPtMin = 1.5; /// minimal energy to fill inv. mass histo + float mEminHGTime = 1.5; + float mEminLGTime = 5.; + std::vector mDigits; /// list of calibration digits to fill + + ClassDefNV(PHOSEnergySlot, 1); +}; + +class PHOSEnergyCalibrator final : public o2::calibration::TimeSlotCalibration +{ + using Slot = o2::calibration::TimeSlot; + + public: + PHOSEnergyCalibrator(); + + bool hasEnoughData(const Slot& slot) const final { return true; } //no need to merge Slots + void initOutput() final {} + void finalizeSlot(Slot& slot) final; + Slot& emplaceNewSlot(bool front, uint64_t tstart, uint64_t tend) final; + bool process(uint64_t tf, const std::vector& clusters, const gsl::span& cluTR); + + void endOfStream(); + + void setOutDigitsFile(std::string& name) { mdigitsfilename = name; }; + void setCalibration(CalibParams& c) { mCalibParams.reset(new CalibParams(c)); } + void setBadMap(BadChannelMap& map) { mBadMap.reset(new BadChannelMap(map)); } + void setCuts(float ptMin, float eminHGTime, float eminLGTime) + { + mPtMin = ptMin; + mEminHGTime = eminHGTime; + mEminLGTime = eminLGTime; + } + + private: + bool calculateCalibrations(); + + private: + std::string mdigitsfilename = "CalibDigits.root"; + long mRunStartTime = 0; /// start time of the run (sec) + int mChank = 0; /// Number of digits chanks (==TF) wrote to file + float mPtMin = 1.5; /// minimal energy to fill inv. mass histo + float mEminHGTime = 1.5; + float mEminLGTime = 5.; + std::unique_ptr mCalibParams; /// Current calibration object + std::unique_ptr mBadMap; /// Current BadMap + ETCalibHistos mHistos; /// final histograms + std::vector mDigits; /// list of calibration digits to fill + std::unique_ptr mFout; /// file to write calib digits + + ClassDefOverride(PHOSEnergyCalibrator, 1); +}; + +} // namespace phos +} // namespace o2 + +#endif diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSHGLGRatioCalibDevice.h b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSHGLGRatioCalibDevice.h index 34609ffd37056..228f8a20a6381 100644 --- a/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSHGLGRatioCalibDevice.h +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSHGLGRatioCalibDevice.h @@ -42,7 +42,7 @@ class PHOSHGLGRatioCalibDevice : public o2::framework::Task }; public: - explicit PHOSHGLGRatioCalibDevice(bool useCCDB, bool forceUpdate, std::string path) : mUseCCDB(useCCDB), mForceUpdate(forceUpdate), mPath(path) {} + explicit PHOSHGLGRatioCalibDevice(bool useCCDB, bool forceUpdate, std::string path) : mUseCCDB(useCCDB), mForceUpdate(forceUpdate), mCCDBPath(path) {} void init(o2::framework::InitContext& ic) final; void run(o2::framework::ProcessingContext& pc) final; @@ -61,16 +61,15 @@ class PHOSHGLGRatioCalibDevice : public o2::framework::Task bool mUseCCDB = false; bool mForceUpdate = false; /// Update CCDB even if difference to current is large bool mUpdateCCDB = true; /// set is close to current and can update it - std::string mPath{"./"}; /// path and name of file with collected histograms - std::unique_ptr mCalibParams; /// Final calibration object + static constexpr short kMinorChange = 10; /// ignore if number of channels changed smaller than... + long mRunStartTime = 0; /// start time of the run (sec) + std::string mCCDBPath{"http://ccdb-test.cern.ch:8080"}; ///< CCDB server path + std::unique_ptr mCalibParams; //! Final calibration object short mMinLG = 20; /// minimal LG ampl used in ratio short minimalStatistics = 100; /// minimal statistics per channel - std::map mMapPairs; /// HG/LG pair - std::unique_ptr mMapping; /// Mapping - std::unique_ptr mRawFitter; /// Sample fitting class - std::unique_ptr mCalibObject; /// Final calibration object - std::unique_ptr mhRatio; /// Histogram with ratios - std::array mRatioDiff; /// Ratio variation wrt previous map + std::map mMapPairs; //! HG/LG pair + std::unique_ptr mhRatio; //! Histogram with ratios + std::array mRatioDiff; //! Ratio variation wrt previous map }; DataProcessorSpec getHGLGRatioCalibSpec(bool useCCDB, bool forceUpdate, std::string path); diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSPedestalCalibDevice.h b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSPedestalCalibDevice.h index 9fb55dd55d19b..b1bff6c2fdb0a 100644 --- a/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSPedestalCalibDevice.h +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSPedestalCalibDevice.h @@ -34,7 +34,7 @@ class PHOSPedestalCalibDevice : public o2::framework::Task { public: - explicit PHOSPedestalCalibDevice(bool useCCDB, bool forceUpdate, std::string path) : mUseCCDB(useCCDB), mForceUpdate(forceUpdate), mPath(path) {} + explicit PHOSPedestalCalibDevice(bool useCCDB, bool forceUpdate, std::string path) : mUseCCDB(useCCDB), mForceUpdate(forceUpdate), mCCDBPath(path) {} void init(o2::framework::InitContext& ic) final; @@ -54,17 +54,15 @@ class PHOSPedestalCalibDevice : public o2::framework::Task bool mUpdateCCDB = true; /// set is close to current and can update it static constexpr short kMinorChange = 10; /// ignore if number of channels changed smaller than... long mRunStartTime = 0; /// start time of the run (sec) - std::string mPath{"./"}; ///< path and name of file with collected histograms - std::unique_ptr mPedestals; /// Final calibration object - std::unique_ptr mOldPed; /// Pedestals currently stored in CCDB for comparisoin - std::unique_ptr mMapping; /// Mapping - std::unique_ptr mRawFitter; /// Sample fitting class - std::unique_ptr mMeanHG; /// Mean values in High Gain channels - std::unique_ptr mMeanLG; /// RMS of values in High Gain channels - std::unique_ptr mRMSHG; /// Mean values in Low Gain channels - std::unique_ptr mRMSLG; /// RMS of values in Low Gain channels - std::array mPedHGDiff; /// Pedestal variation wrt previous map - std::array mPedLGDiff; /// Pedestal variation wrt previous map + std::string mCCDBPath{"http://ccdb-test.cern.ch:8080"}; /// CCDB path to retrieve current CCDB objects for comparison + std::unique_ptr mPedestals; //! Final calibration object + std::unique_ptr mOldPed; //! Pedestals currently stored in CCDB for comparisoin + std::unique_ptr mMeanHG; //! Mean values in High Gain channels + std::unique_ptr mMeanLG; //! RMS of values in High Gain channels + std::unique_ptr mRMSHG; //! Mean values in Low Gain channels + std::unique_ptr mRMSLG; //! RMS of values in Low Gain channels + std::array mPedHGDiff; //! Pedestal variation wrt previous map + std::array mPedLGDiff; //! Pedestal variation wrt previous map }; o2::framework::DataProcessorSpec getPedestalCalibSpec(bool useCCDB, bool forceUpdate, std::string path); diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSRunbyrunCalibDevice.h b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSRunbyrunCalibDevice.h new file mode 100644 index 0000000000000..9973622f4d3c9 --- /dev/null +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSRunbyrunCalibDevice.h @@ -0,0 +1,57 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_CALIBRATION_PHOSRUNBYRUN_CALIBDEV_H +#define O2_CALIBRATION_PHOSRUNBYRUN_CALIBDEV_H + +/// @file PHOSRunbyrunCalibDevice.h +/// @brief Device to calculate PHOS energy run by run corrections + +#include "Framework/Task.h" +#include "Framework/WorkflowSpec.h" +#include "Framework/ProcessingContext.h" +#include "PHOSCalib/BadChannelMap.h" +#include "PHOSCalibWorkflow/PHOSRunbyrunCalibrator.h" +#include "DataFormatsPHOS/Cluster.h" + +using namespace o2::framework; + +namespace o2 +{ +namespace phos +{ + +class PHOSRunbyrunCalibDevice +{ + public: + PHOSRunbyrunCalibDevice() = default; + + void init(o2::framework::InitContext& ic); + + void run(o2::framework::ProcessingContext& pc); + + void endOfStream(o2::framework::EndOfStreamContext& ec); + + protected: + bool checkFitResult(); + + private: + bool mUseCCDB = false; + long mRunStartTime = 0; /// start time of the run (sec) + std::string mCCDBPath{"http://ccdb-test.cern.ch:8080"}; /// CCDB path to retrieve current CCDB objects for comparison + std::array mRunByRun; /// Final calibration object + std::unique_ptr mCalibrator; /// Agregator of calibration TimeFrameSlots +}; + +o2::framework::DataProcessorSpec getPHOSRunbyrunCalibDeviceSpec(bool useCCDB, std::string path); +} // namespace phos +} // namespace o2 + +#endif diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSRunbyrunCalibrator.h b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSRunbyrunCalibrator.h new file mode 100644 index 0000000000000..c5fd2acfc19f1 --- /dev/null +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSRunbyrunCalibrator.h @@ -0,0 +1,110 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_CALIBRATION_PHOSRUNBYRUN_CALIBRATOR_H +#define O2_CALIBRATION_PHOSRUNBYRUN_CALIBRATOR_H + +/// @file PHOSRunbyrunCalibDevice.h +/// @brief Device to calculate PHOS energy run by run corrections + +#include "Framework/Task.h" +#include "Framework/ProcessingContext.h" +#include "PHOSCalib/BadChannelMap.h" +#include "DetectorsCalibration/TimeSlotCalibration.h" +#include +#include "TH1.h" +#include "PHOSCalibWorkflow/RingBuffer.h" +#include "PHOSReconstruction/FullCluster.h" +#include "DataFormatsPHOS/TriggerRecord.h" +#include "PHOSBase/Geometry.h" + +using namespace o2::framework; + +namespace o2 +{ +namespace phos +{ + +class PHOSRunbyrunSlot +{ + public: + using boostHisto = boost::histogram::histogram>, boost::histogram::unlimited_storage>>; + + PHOSRunbyrunSlot(bool useCCDB, std::string path); + PHOSRunbyrunSlot(const PHOSRunbyrunSlot& other); + + ~PHOSRunbyrunSlot() = default; + + void print() const; + void fill(const std::vector& clusters, const gsl::span& trs); + void fill(const gsl::span& /*clusters*/){}; //not used + void merge(const PHOSRunbyrunSlot* prev); + void clear(); + + boostHisto& getCollectedHistos(int m) { return mReMi[m]; } + + void setRunStartTime(long tf) { mRunStartTime = tf; } + + private: + bool checkCluster(const FullCluster& clu); + + private: + bool mUseCCDB = false; + long mRunStartTime = 0; /// start time of the run (sec) + float mPtCut = 1.5; /// ptmin of a pair cut (GeV/c) + std::string mCCDBPath{"http://ccdb-test.cern.ch:8080"}; /// CCDB path to retrieve current CCDB objects for comparison + std::array mReMi; /// Real and Mixed inv mass distributions per module + std::unique_ptr mBuffer; /// Buffer for current and previous events + std::unique_ptr mBadMap; /// Latest bad channels map + + ClassDefNV(PHOSRunbyrunSlot, 1); +}; + +//========================================================================================== +class PHOSRunbyrunCalibrator final : public o2::calibration::TimeSlotCalibration +{ + using Slot = o2::calibration::TimeSlot; + + public: + PHOSRunbyrunCalibrator(); + ~PHOSRunbyrunCalibrator() final; + + bool hasEnoughData(const Slot& slot) const final; + void initOutput() final; + void finalizeSlot(Slot& slot) final; + Slot& emplaceNewSlot(bool front, uint64_t tstart, uint64_t tend) final; + bool process(uint64_t tf, const std::vector& clu, const gsl::span& trs); + + std::array getCalibration() { return mRunByRun; } + void endOfStream(); + + //Functions used in histo fittings + double CBRatio(double* x, double* p); + double CBSignal(double* x, double* p); + double bg(double* x, double* p); + + private: + void scanClusters(o2::framework::ProcessingContext& pc); + bool checkCluster(const FullCluster& clu); + + private: + bool mUseCCDB = false; + long mRunStartTime = 0; /// start time of the run (sec) + std::string mCCDBPath{"http://ccdb-test.cern.ch:8080"}; /// CCDB path to retrieve current CCDB objects for comparison + std::array mRunByRun; /// Final calibration object + std::array mReMi; /// Real and Mixed inv mass distributions per module + + ClassDefOverride(PHOSRunbyrunCalibrator, 1); +}; + +} // namespace phos +} // namespace o2 + +#endif diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSTurnonCalibDevice.h b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSTurnonCalibDevice.h new file mode 100644 index 0000000000000..d42f4b80a846d --- /dev/null +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSTurnonCalibDevice.h @@ -0,0 +1,58 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_CALIBRATION_PHOSTURNON_CALIBDEV_H +#define O2_CALIBRATION_PHOSTURNON_CALIBDEV_H + +/// @file PHOSTurnonCalibDevice.h +/// @brief Device to calculate PHOS turn-on curves and trigger map + +#include "Framework/Task.h" +#include "Framework/WorkflowSpec.h" +#include "DataFormatsPHOS/TriggerRecord.h" +#include "DataFormatsPHOS/Cell.h" +#include "DataFormatsPHOS/Cluster.h" +#include "PHOSCalib/TriggerMap.h" +#include "PHOSCalibWorkflow/PHOSTurnonCalibrator.h" + +using namespace o2::framework; + +namespace o2 +{ +namespace phos +{ + +class PHOSTurnonCalibDevice : public o2::framework::Task +{ + public: + explicit PHOSTurnonCalibDevice(bool useCCDB, std::string path) : mUseCCDB(useCCDB), mCCDBPath(path) {} + + void init(o2::framework::InitContext& ic) final; + + void run(o2::framework::ProcessingContext& pc) final; + + void endOfStream(o2::framework::EndOfStreamContext& ec) final; + + protected: + bool checkFitResult() { return true; } //TODO!! implement true check + + private: + bool mUseCCDB = false; + std::string mCCDBPath{"http://ccdb-test.cern.ch:8080"}; ///< CCDB server path + long mRunStartTime = 0; /// start time of the run (sec) + std::unique_ptr mTriggerMap; /// Final calibration object + std::unique_ptr mCalibrator; /// Agregator of calibration TimeFrameSlots +}; + +o2::framework::DataProcessorSpec getPHOSTurnonCalibDeviceSpec(bool useCCDB, std::string path); +} // namespace phos +} // namespace o2 + +#endif diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSTurnonCalibrator.h b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSTurnonCalibrator.h new file mode 100644 index 0000000000000..86adc28d95b69 --- /dev/null +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/PHOSTurnonCalibrator.h @@ -0,0 +1,104 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_CALIBRATION_PHOSTURNON_CALIBRATOR_H +#define O2_CALIBRATION_PHOSTURNON_CALIBRATOR_H + +/// @file PHOSTurnonCalibrator.h +/// @brief Device to calculate PHOS turn-on curve and bad map + +#include "Framework/Task.h" +#include "Framework/WorkflowSpec.h" +#include "DetectorsCalibration/TimeSlotCalibration.h" +#include "DataFormatsPHOS/Cell.h" +#include "DataFormatsPHOS/TriggerRecord.h" +#include "PHOSReconstruction/FullCluster.h" +#include "PHOSCalib/TriggerMap.h" +#include "PHOSCalibWorkflow/TurnOnHistos.h" + +using namespace o2::framework; + +namespace o2 +{ +namespace phos +{ + +class PHOSTurnonSlot +{ + public: + static constexpr short NCHANNELS = 3136; ///< Number of trigger channels + + PHOSTurnonSlot(bool useCCDB, std::string path); + PHOSTurnonSlot(const PHOSTurnonSlot& other); + + ~PHOSTurnonSlot() = default; + + void print() const; + void fill(const gsl::span& cells, const gsl::span& trs, + const std::vector& clusters, const gsl::span& cluTR); + void fill(const gsl::span& /*cells*/){}; //not used + void merge(const PHOSTurnonSlot* /*prev*/) {} //not used + void clear(); + + TurnOnHistos& getCollectedHistos() { return *mTurnOnHistos; } + + void setRunStartTime(long tf) { mRunStartTime = tf; } + + private: + void scanClusters(const gsl::span& cells, const TriggerRecord& celltr, + const std::vector& clusters, const TriggerRecord& clutr); + + private: + bool mUseCCDB = false; + long mRunStartTime = 0; /// start time of the run (sec) + std::string mCCDBPath{"http://ccdb-test.cern.ch:8080"}; ///< CCDB server path + std::bitset mFiredTiles; //! Container for bad trigger cells, 1 means bad sell + std::bitset mNoisyTiles; //! Container for bad trigger cells, 1 means bad sell + std::unique_ptr mTurnOnHistos; //! Collection of histos to fill + + ClassDefNV(PHOSTurnonSlot, 1); +}; + +//========================================================================================== +class PHOSTurnonCalibrator final : public o2::calibration::TimeSlotCalibration +{ + using Slot = o2::calibration::TimeSlot; + + public: + PHOSTurnonCalibrator() = default; + + bool hasEnoughData(const Slot& slot) const final { return true; } //no need to merge Slots + void initOutput() final {} + void finalizeSlot(Slot& slot) final; + Slot& emplaceNewSlot(bool front, uint64_t tstart, uint64_t tend) final; + bool process(uint64_t tf, const gsl::span& cells, const gsl::span& trs, + const std::vector& clusters, const gsl::span& cluTR); + + TriggerMap& getCalibration() { return *mTriggerMap; } + void endOfStream(); + + private: + bool calculateCalibrations(); + + private: + bool mUseCCDB = false; + long mRunStartTime = 0; /// start time of the run (sec) + std::string mCCDBPath{"http://ccdb-test.cern.ch:8080"}; /// CCDB path to retrieve current CCDB objects for comparison + std::unique_ptr mTurnOnHistos; //! Collection of histos to fill + std::unique_ptr mTriggerMap; + + ClassDefOverride(PHOSTurnonCalibrator, 1); +}; + +o2::framework::DataProcessorSpec getPHOSTunronCalibDeviceSpec(bool useCCDB, std::string path); +} // namespace phos +} // namespace o2 + +#endif \ No newline at end of file diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/RingBuffer.h b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/RingBuffer.h new file mode 100644 index 0000000000000..14e345c57edcd --- /dev/null +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/RingBuffer.h @@ -0,0 +1,81 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_CALIBRATION_PHOS_RINGBUFFER_H +#define O2_CALIBRATION_PHOS_RINGBUFFER_H + +/// @file RingBuffer.h +/// @brief Device to collect energy and time PHOS energy and time calibration. + +#include +#include +#include + +namespace o2 +{ +namespace phos +{ + +// For real/mixed distribution calculation +class RingBuffer +{ + public: + RingBuffer() = default; + ~RingBuffer() = default; + + short size() + { + if (mFilled) { + return kBufferSize; + } else { + return mCurrent; + } + } + void addEntry(TLorentzVector& v) + { + mBuffer[mCurrent] = v; + mCurrent++; + if (mCurrent >= kBufferSize) { + mFilled = true; + mCurrent -= kBufferSize; + } + } + const TLorentzVector& getEntry(short index) const + { + //get entry from (mCurrent-1) corresponding to index=size()-1 down to size + if (mFilled) { + index += mCurrent; + } + index = index % kBufferSize; + return mBuffer[index]; + } + //mark that next added entry will be from next event + void startNewEvent() { mStartCurrentEvent = mCurrent; } + + bool isCurrentEvent(short index) const + { + if (mCurrent >= mStartCurrentEvent) { + return (index >= mStartCurrentEvent && index < mCurrent); + } else { + return (index >= mStartCurrentEvent || index < mCurrent); + } + } + + private: + static constexpr short kBufferSize = 100; ///< Total size of the buffer + std::array mBuffer; ///< buffer + bool mFilled = false; ///< if buffer fully filled + short mCurrent = 0; ///< where next object will be added + short mStartCurrentEvent = 0; ///< start of current event +}; +} // namespace phos +} // namespace o2 + +#endif diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/TurnOnHistos.h b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/TurnOnHistos.h new file mode 100644 index 0000000000000..32af2d3e0b7ce --- /dev/null +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/include/PHOSCalibWorkflow/TurnOnHistos.h @@ -0,0 +1,114 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \class TurnOnHistos +/// \brief transient CCDB container to collect histos for calculation of trigger maps and turn-on curves +/// \author Dmitri Peresunko, RRC Kurchatov institute +/// \since Apr. 1, 2021 +/// +/// + +#ifndef PHOS_TURNONHISTOS_H +#define PHOS_TURNONHISTOS_H + +#include +#include +#include "TObject.h" + +namespace o2 +{ + +namespace phos +{ + +class TurnOnHistos +{ + public: + //class to collect statistics to calculate trigger turn-on curves and trigger bad maps + static constexpr short NCHANNELS = 3136; ///< Number of trigger channels + static constexpr short NDDL = 14; ///< Number of DDLs + static constexpr short Npt = 200; ///< Number of bins in pt distribution + static constexpr float dpt = 0.1; ///< bin width + + /// \brief Constructor + TurnOnHistos() = default; + + TurnOnHistos& operator=(const TurnOnHistos& other) = default; + + /// \brief Destructor + ~TurnOnHistos() = default; + + /// \brief Merge statistics in two containers + /// \param other Another container to be added to current + void merge(TurnOnHistos& other); + + /// \brief Fill spectum of all clusters + /// \param ddl ddl ID + /// \param e cluster energy + void fillTotSp(short ddl, float e) + { + short bin = e / dpt; + if (bin < Npt) { + mTotSp[ddl][bin]++; + } + } + + /// \brief Fill spectum of clusters fired trigger + /// \param ddl ddl ID + /// \param e cluster energy + void fillFiredSp(short ddl, float e) + { + short bin = e / dpt; + if (bin < Npt) { + mTrSp[ddl][bin]++; + } + } + + /// \brief Collects entries in good map + /// \param bitset with channels fired in event + void fillFiredMap(const std::bitset& bs) + { + for (short i = NCHANNELS; --i;) { + if (bs[i]) { + mGoodMap[i]++; + } + } + } + + /// \brief Collects entries in noisy map + /// \param bitset with channels fired in event + void fillNoisyMap(const std::bitset& bs) + { + for (short i = NCHANNELS; --i;) { + if (bs[i]) { + mNoisyMap[i]++; + } + } + } + + //getters now + const std::array& getTotSpectrum(short ddl) const { return mTotSp[ddl]; } + const std::array& getTrSpectrum(short ddl) const { return mTrSp[ddl]; } + const std::array& getGoodMap() const { return mGoodMap; } + const std::array& getNoisyMap() const { return mNoisyMap; } + + private: + std::array mGoodMap; ///< Container to collect entries in good map + std::array mNoisyMap; ///< Container to collect entries in noisy map + std::array, NDDL> mTotSp; ///< Spectrum of all clusters + std::array, NDDL> mTrSp; ///< Spectrum of fired trigger cl. + + ClassDefNV(TurnOnHistos, 1); +}; + +} // namespace phos + +} // namespace o2 +#endif diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSCalibCollector.cxx b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSBadMapCalibDevice.cxx similarity index 100% rename from Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSCalibCollector.cxx rename to Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSBadMapCalibDevice.cxx diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSCalibWorkflowLinkDef.h b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSCalibWorkflowLinkDef.h index 0a49a2f4deae1..1502107b76e10 100644 --- a/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSCalibWorkflowLinkDef.h +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSCalibWorkflowLinkDef.h @@ -14,6 +14,24 @@ #pragma link off all classes; #pragma link off all functions; -#pragma link C++ class o2::phos::PHOSPedestalCalibDevice+; +#pragma link C++ class o2::phos::PHOSPedestalCalibDevice + ; +#pragma link C++ class o2::phos::PHOSHGLGRatioCalibDevice + ; +#pragma link C++ class o2::phos::ETCalibHistos + ; +#pragma link C++ class o2::phos::PHOSEnergySlot + ; +#pragma link C++ class o2::phos::PHOSEnergyCalibrator + ; +#pragma link C++ class o2::phos::PHOSEnergyCalibDevice + ; +#pragma link C++ class o2::calibration::TimeSlot < o2::phos::PHOSEnergySlot> + ; +#pragma link C++ class o2::calibration::TimeSlotCalibration < o2::phos::FullCluster, o2::phos::PHOSEnergySlot> + ; +#pragma link C++ class o2::phos::TurnOnHistos + ; +#pragma link C++ class o2::phos::PHOSTurnonSlot + ; +#pragma link C++ class o2::phos::PHOSTurnonCalibrator + ; +#pragma link C++ class o2::phos::PHOSTurnonCalibDevice + ; +#pragma link C++ class o2::calibration::TimeSlot < o2::phos::PHOSTurnonSlot> + ; +#pragma link C++ class o2::calibration::TimeSlotCalibration < o2::phos::FullCluster, o2::phos::PHOSTurnonSlot> + ; +#pragma link C++ class o2::phos::PHOSRunbyrunSlot + ; +#pragma link C++ class o2::phos::PHOSRunbyrunCalibrator + ; +#pragma link C++ class o2::phos::PHOSRunbyrunCalibDevice + ; +#pragma link C++ class o2::calibration::TimeSlot < o2::phos::PHOSRunbyrunSlot> + ; +#pragma link C++ class o2::calibration::TimeSlotCalibration < o2::phos::FullCluster, o2::phos::PHOSRunbyrunSlot> + ; #endif diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSEnergyCalibDevice.cxx b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSEnergyCalibDevice.cxx new file mode 100644 index 0000000000000..7073f6804da61 --- /dev/null +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSEnergyCalibDevice.cxx @@ -0,0 +1,107 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "PHOSCalibWorkflow/PHOSEnergyCalibDevice.h" +#include "DataFormatsPHOS/TriggerRecord.h" +#include "Framework/ConfigParamRegistry.h" +#include "CCDB/CcdbApi.h" +#include "CCDB/CcdbObjectInfo.h" +#include "DetectorsCalibration/Utils.h" +#include "Framework/ControlService.h" + +#include "FairLogger.h" +#include + +using namespace o2::phos; + +void PHOSEnergyCalibDevice::init(o2::framework::InitContext& ic) +{ + mCalibrator.reset(new PHOSEnergyCalibrator()); + + //TODO!!! read configuration + // mPtMin,mEminHGTime,mEminLGTime + + //Configure output Digits file + mCalibrator->setOutDigitsFile(mdigitsfilename); + + //read calibration and bad map objects and send them to calibrator + if (!mBadMap) { + if (mUseCCDB) { + LOG(INFO) << "Retrieving BadMap from CCDB"; + o2::ccdb::CcdbApi ccdb; + ccdb.init(mCCDBPath); // or http://localhost:8080 for a local installation + std::map metadata; + mBadMap.reset(ccdb.retrieveFromTFileAny("PHS/Calib/BadChannels", metadata, mRunStartTime)); + + if (!mBadMap) { //was not read from CCDB, but expected + LOG(FATAL) << "Can not read BadMap from CCDB, you may use --not-use-ccdb option to create default bad map"; + } + //same for calibration + + mCalibParams.reset(ccdb.retrieveFromTFileAny("PHS/Calib/CalibParams", metadata, mRunStartTime)); + if (!mCalibParams) { //was not read from CCDB, but expected + LOG(FATAL) << "Can not read current CalibParams from ccdb"; + } + } else { + LOG(INFO) << "Do not use CCDB, create default BadMap and calibration"; + mBadMap.reset(new BadChannelMap(1)); + mCalibParams.reset(new CalibParams(1)); + } + } + mCalibrator->setBadMap(*mBadMap); + mCalibrator->setCalibration(*mCalibParams); + mCalibrator->setCuts(mPtMin, mEminHGTime, mEminLGTime); + + //Create geometry instance (inclusing reading mis-alignement) + //instance will be pick up by Calibrator + Geometry::GetInstance("Run3"); +} + +void PHOSEnergyCalibDevice::run(o2::framework::ProcessingContext& pc) +{ + //TODO! extract vertex information and send to Calibrator + auto tfcounter = o2::header::get(pc.inputs().get("clusters").header)->startTime; // is this the timestamp of the current TF? + auto clusters = pc.inputs().get>("clusters"); + auto cluTR = pc.inputs().get>("clusterTriggerRecords"); + + LOG(INFO) << "[PHOSEnergyCalibDevice - run] Received " << clusters.size() << " clusters and " << clusters.size() << " clusters, running calibration"; + + mCalibrator->process(tfcounter, clusters, cluTR); +} + +void PHOSEnergyCalibDevice::endOfStream(o2::framework::EndOfStreamContext& ec) +{ + constexpr uint64_t INFINITE_TF = 0xffffffffffffffff; + mCalibrator->checkSlotsToFinalize(INFINITE_TF); + mCalibrator->endOfStream(); +} + +o2::framework::DataProcessorSpec o2::phos::getPHOSEnergyCalibDeviceSpec(bool useCCDB, std::string path, std::string digitspath) +{ + + std::vector inputs; + inputs.emplace_back("clusters", o2::header::gDataOriginPHS, "CLUSTERS", 0, o2::framework::Lifetime::Timeframe); + inputs.emplace_back("clusterTriggerRecords", o2::header::gDataOriginPHS, "CLUSTERTRIGREC", 0, o2::framework::Lifetime::Timeframe); + + using clbUtils = o2::calibration::Utils; + std::vector outputs; + outputs.emplace_back( + ConcreteDataTypeMatcher{clbUtils::gDataOriginCLB, clbUtils::gDataDescriptionCLBPayload}); + outputs.emplace_back( + ConcreteDataTypeMatcher{clbUtils::gDataOriginCLB, clbUtils::gDataDescriptionCLBInfo}); + //stream for QC data + //outputs.emplace_back("PHS", "TRIGGERQC", 0, o2::framework::Lifetime::Timeframe); + + return o2::framework::DataProcessorSpec{"PHOSEnergyCalibDevice", + inputs, + outputs, + o2::framework::adaptFromTask(useCCDB, path, digitspath), + o2::framework::Options{}}; +} diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSEnergyCalibrator.cxx b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSEnergyCalibrator.cxx new file mode 100644 index 0000000000000..316d5a90808ee --- /dev/null +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSEnergyCalibrator.cxx @@ -0,0 +1,233 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "PHOSCalibWorkflow/PHOSEnergyCalibrator.h" +#include "DataFormatsPHOS/TriggerRecord.h" +#include "Framework/ConfigParamRegistry.h" +#include "DetectorsCalibration/Utils.h" +#include "Framework/ControlService.h" + +#include "FairLogger.h" +#include // std::ifstream + +using namespace o2::phos; + +PHOSEnergySlot::PHOSEnergySlot() +{ + mHistos.reset(); + mBuffer.reset(new RingBuffer()); + mGeom = Geometry::GetInstance(); +} + +void PHOSEnergySlot::print() const +{ + LOG(INFO) << "Collected " << mDigits.size() << " CalibDigits"; +} + +void PHOSEnergySlot::fill(const std::vector& clusters, const gsl::span& cluTR) +{ + //Scan current list of clusters + //Fill time, non-linearity and mgg histograms + //Fill list of re-calibraiable digits + for (auto& tr : cluTR) { + + //Mark new event + //First goes new event marker + BC (16 bit), next word orbit (32 bit) + EventHeader h = {0}; + h.mMarker = 16383; + h.mBC = tr.getBCData().bc; + mDigits.push_back(h.mDataWord); + mDigits.push_back(tr.getBCData().orbit); + + int iclu = 0; + int firstCluInEvent = tr.getFirstEntry(); + int lastCluInEvent = firstCluInEvent + tr.getNumberOfObjects(); + + mBuffer->startNewEvent(); // mark stored clusters to be used for Mixing + for (int i = firstCluInEvent; i < lastCluInEvent; i++) { + const FullCluster& clu = clusters[i]; + + fillTimeMassHisto(clu); + // bool isGood = checkCluster(clu); + + auto cluList = clu.getElementList(); + for (auto ce = cluList->begin(); ce != cluList->end(); ce++) { + short absId = ce->absId; + //Fill cells from cluster for next iterations + short adcCounts = ce->energy / mCalibParams->getGain(absId); + // Need to chale LG gain too to fit dynamic range + if (!ce->isHG) { + adcCounts /= mCalibParams->getHGLGRatio(absId); + } + CalibDigit d = {0}; + d.mAddress = absId; + d.mAdcAmp = adcCounts; + d.mHgLg = ce->isHG; + d.mCluster = (i - firstCluInEvent) % kMaxCluInEvent; + mDigits.push_back(d.mDataWord); + if (i - firstCluInEvent > kMaxCluInEvent) { + //Normally this is not critical as indexes are used "locally", i.e. are compared to previous/next + LOG(INFO) << "Too many clusters per event:" << i - firstCluInEvent << ", apply more strict selection; clusters with same indexes will appear"; + } + } + } + } +} +void PHOSEnergySlot::clear() +{ + mHistos.reset(); + mDigits.clear(); +} + +void PHOSEnergySlot::fillTimeMassHisto(const FullCluster& clu) +{ + // Fill time distributions only for cells in cluster + auto cluList = clu.getElementList(); + for (auto ce = cluList->begin(); ce != cluList->end(); ce++) { + short absId = ce->absId; + if (ce->isHG) { + if (ce->energy > mEminHGTime) { + mHistos.fill(ETCalibHistos::kTimeHGPerCell, absId, ce->time); + } + mHistos.fill(ETCalibHistos::kTimeHGSlewing, ce->time, ce->energy); + } else { + if (ce->energy > mEminLGTime) { + mHistos.fill(ETCalibHistos::kTimeLGPerCell, absId, ce->time); + } + mHistos.fill(ETCalibHistos::kTimeLGSlewing, ce->time, ce->energy); + } + } + + //Real and Mixed inv mass distributions + // prepare TLorentsVector + float posX, posZ; + clu.getLocalPosition(posX, posZ); + TVector3 vec3; + mGeom->local2Global(clu.module(), posX, posZ, vec3); + vec3 -= mVertex; + float e = clu.getEnergy(); + short absId; + mGeom->relPosToAbsId(clu.module(), posX, posZ, absId); + + vec3 *= 1. / vec3.Mag(); + TLorentzVector v(vec3.X() * e, vec3.Y() * e, vec3.Z() * e, e); + // Fill calibration histograms for all cells, even bad, but partners in inv, mass should be good + bool isGood = checkCluster(clu); + for (short ip = mBuffer->size(); ip--;) { + const TLorentzVector& vp = mBuffer->getEntry(ip); + TLorentzVector sum = v + vp; + if (mBuffer->isCurrentEvent(ip)) { //same (real) event + if (isGood) { + mHistos.fill(ETCalibHistos::kReInvMassNonlin, e, sum.M()); + } + if (sum.Pt() > mPtMin) { + mHistos.fill(ETCalibHistos::kReInvMassPerCell, absId, sum.M()); + } + } else { //Mixed + if (isGood) { + mHistos.fill(ETCalibHistos::kMiInvMassNonlin, e, sum.M()); + } + if (sum.Pt() > mPtMin) { + mHistos.fill(ETCalibHistos::kMiInvMassPerCell, absId, sum.M()); + } + } + } + + //Add to list ot partners only if cluster is good + if (isGood) { + mBuffer->addEntry(v); + } +} + +bool PHOSEnergySlot::checkCluster(const FullCluster& clu) +{ + //First check BadMap + float posX, posZ; + clu.getLocalPosition(posX, posZ); + short absId; + Geometry::relPosToAbsId(clu.module(), posX, posZ, absId); + if (!mBadMap->isChannelGood(absId)) { + return false; + } + + return (clu.getEnergy() > 0.3 && clu.getMultiplicity() > 1); +} + +//================================================== + +using es = o2::phos::PHOSEnergySlot; +using Slot = o2::calibration::TimeSlot; +PHOSEnergyCalibrator::PHOSEnergyCalibrator() +{ + // create final histos + mHistos.reset(); +} +PHOSEnergySlot::PHOSEnergySlot(const PHOSEnergySlot& other) +{ + mRunStartTime = other.mRunStartTime; + mBuffer.reset(new RingBuffer()); + mCalibParams.reset(new CalibParams(*(other.mCalibParams))); + mBadMap.reset(new BadChannelMap(*(other.mBadMap))); + mEvBC = other.mEvBC; + mEvOrbit = other.mEvOrbit; + mEvent = 0; + mPtMin = other.mPtMin; + mEminHGTime = other.mEminHGTime; + mEminLGTime = other.mEminLGTime; + mDigits.clear(); + mHistos.reset(); +} + +void PHOSEnergyCalibrator::finalizeSlot(Slot& slot) +{ + + // Extract results for the single slot + es* c = slot.getContainer(); + LOG(INFO) << "Finalize slot " << slot.getTFStart() << " <= TF <= " << slot.getTFEnd(); + //Add histos + mHistos.merge(c->getCollectedHistos()); + //Add collected Digits + auto tmpD = c->getCollectedDigits(); + //Add to list or write to file directly? + if (!mFout) { //not open yet? + LOG(INFO) << "Writing CalibDigits to file " << mdigitsfilename.data(); + mFout.reset(TFile::Open(mdigitsfilename.data(), "recreate")); + } + int nbites = mFout->WriteObjectAny(&tmpD, "std::vector", Form("Digits%d", mChank++)); + LOG(INFO) << "Writing " << tmpD.size() << " CalibDigits, wrote " << nbites << "bytes"; + c->clear(); +} + +Slot& PHOSEnergyCalibrator::emplaceNewSlot(bool front, uint64_t tstart, uint64_t tend) +{ + auto& cont = getSlots(); + auto& slot = front ? cont.emplace_front(tstart, tend) : cont.emplace_back(tstart, tend); + slot.setContainer(std::make_unique()); + slot.getContainer()->setBadMap(*mBadMap); + slot.getContainer()->setCalibration(*mCalibParams); + slot.getContainer()->setCuts(mPtMin, mEminHGTime, mEminLGTime); + return slot; +} + +bool PHOSEnergyCalibrator::process(uint64_t tf, const std::vector& clusters, + const gsl::span& cluTR) +{ + // process current TF + //First receive bad map and calibration if not received yet + + auto& slotTF = getSlotForTF(tf); + slotTF.getContainer()->setRunStartTime(tf); + slotTF.getContainer()->fill(clusters, cluTR); + return true; +} + +void PHOSEnergyCalibrator::endOfStream() +{ +} diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSHGLGRatioCalibDevice.cxx b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSHGLGRatioCalibDevice.cxx index b4105341771b7..b1d9456bfb8bf 100644 --- a/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSHGLGRatioCalibDevice.cxx +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSHGLGRatioCalibDevice.cxx @@ -11,19 +11,16 @@ #include "PHOSCalibWorkflow/PHOSHGLGRatioCalibDevice.h" #include "CCDB/CcdbApi.h" #include "CCDB/CcdbObjectInfo.h" +#include #include "FairLogger.h" #include "CommonDataFormat/InteractionRecord.h" +#include "DetectorsCalibration/Utils.h" #include "Framework/ConfigParamRegistry.h" #include "Framework/ControlService.h" #include "Framework/WorkflowSpec.h" #include "DataFormatsPHOS/TriggerRecord.h" -#include "DetectorsRaw/RDHUtils.h" -#include "Framework/InputRecordWalker.h" +#include "DataFormatsPHOS/Cell.h" #include "PHOSBase/Mapping.h" -#include "PHOSReconstruction/Bunch.h" -#include "PHOSReconstruction/AltroDecoder.h" -#include "PHOSReconstruction/RawDecodingError.h" -#include #include #include @@ -32,109 +29,51 @@ using namespace o2::phos; void PHOSHGLGRatioCalibDevice::init(o2::framework::InitContext& ic) { - mMapping.reset(new o2::phos::Mapping("")); - if (!mMapping) { - LOG(FATAL) << "Failed to initialize mapping"; - } - if (mMapping->setMapping() != o2::phos::Mapping::kOK) { - LOG(ERROR) << "Failed to construct mapping"; - } - mRawFitter.reset(new o2::phos::CaloRawFitter()); - //Create histograms for mean and RMS short n = o2::phos::Mapping::NCHANNELS; mhRatio.reset(new TH2F("HGLGRatio", "HGLGRatio", n, 0.5, n + 0.5, 100, 10., 20.)); + mCalibParams.reset(new CalibParams()); } void PHOSHGLGRatioCalibDevice::run(o2::framework::ProcessingContext& ctx) { - // - for (const auto& rawData : framework::InputRecordWalker(ctx.inputs())) { - - o2::phos::RawReaderMemory rawreader(o2::framework::DataRefUtils::as(rawData)); - - // loop over all the DMA pages - while (rawreader.hasNext()) { - mMapPairs.clear(); + // scan Cells stream, collect HG/LG pairs + if (mRunStartTime == 0) { + mRunStartTime = o2::header::get(ctx.inputs().get("cellTriggerRecords").header)->startTime; + } - try { - rawreader.next(); - } catch (RawDecodingError::ErrorType_t e) { - LOG(ERROR) << "Raw decoding error " << (int)e; - //if problem in header, abandon this page - if (e == RawDecodingError::ErrorType_t::PAGE_NOTFOUND || - e == RawDecodingError::ErrorType_t::HEADER_DECODING || - e == RawDecodingError::ErrorType_t::HEADER_INVALID) { - break; + auto cells = ctx.inputs().get>("cells"); + LOG(DEBUG) << "[PHOSHGLGRatioCalibDevice - run] Received " << cells.size() << " cells, running calibration ..."; + auto cellsTR = ctx.inputs().get>("cellTriggerRecords"); + for (const auto& tr : cellsTR) { + int firstCellInEvent = tr.getFirstEntry(); + int lastCellInEvent = firstCellInEvent + tr.getNumberOfObjects(); + mMapPairs.clear(); + + for (int i = firstCellInEvent; i < lastCellInEvent; i++) { + const Cell c = cells[i]; + + auto search = mMapPairs.find(c.getAbsId()); + if (search != mMapPairs.end()) { //exist + if (c.getHighGain()) { + search->second.mHGAmp = c.getEnergy(); } - //if problem in payload, try to continue - continue; - } - auto& header = rawreader.getRawHeader(); - auto triggerBC = o2::raw::RDHUtils::getTriggerBC(header); - auto triggerOrbit = o2::raw::RDHUtils::getTriggerOrbit(header); - auto ddl = o2::raw::RDHUtils::getFEEID(header); - - o2::InteractionRecord currentIR(triggerBC, triggerOrbit); - - if (ddl > o2::phos::Mapping::NDDL) { //only 14 correct DDLs - LOG(ERROR) << "DDL=" << ddl; - continue; //skip STU ddl - } - // use the altro decoder to decode the raw data, and extract the RCU trailer - o2::phos::AltroDecoder decoder(rawreader); - AltroDecoderError::ErrorType_t err = decoder.decode(); - - if (err != AltroDecoderError::kOK) { - LOG(ERROR) << "Errror " << err << " in decoding DDL" << ddl; - } - auto& rcu = decoder.getRCUTrailer(); - auto& channellist = decoder.getChannels(); - // Loop over all the channels for this RCU - for (auto& chan : channellist) { - short absId; - Mapping::CaloFlag caloFlag; - short fee; - Mapping::ErrorStatus s = mMapping->hwToAbsId(ddl, chan.getHardwareAddress(), absId, caloFlag); - if (s != Mapping::ErrorStatus::kOK) { - LOG(ERROR) << "Error in mapping" - << " ddl=" << ddl << " hwaddress " << chan.getHardwareAddress(); - continue; + if (c.getLowGain()) { + search->second.mLGAmp = c.getEnergy(); } - if (caloFlag != Mapping::kTRU) { //HighGain or LowGain - CaloRawFitter::FitStatus fitResults = mRawFitter->evaluate(chan.getBunches()); - if (fitResults == CaloRawFitter::FitStatus::kOK || fitResults == CaloRawFitter::FitStatus::kNoTime) { - for (int is = 0; is < mRawFitter->getNsamples(); is++) { - //if map entry already exist, fill second part, otherwise fill first map - if (mRawFitter->isOverflow(is)) { - continue; - } - auto search = mMapPairs.find(absId); - if (search != mMapPairs.end()) { //exist - if (caloFlag == Mapping::kHighGain) { - search->second.mHGAmp = mRawFitter->getAmp(is); - } - if (caloFlag == Mapping::kLowGain) { - search->second.mLGAmp = mRawFitter->getAmp(is); - } - - } else { - PairAmp pa = {0}; - if (caloFlag == Mapping::kHighGain) { - pa.mHGAmp = mRawFitter->getAmp(is); - } - if (caloFlag == Mapping::kLowGain) { - pa.mLGAmp = mRawFitter->getAmp(is); - } - mMapPairs.insert({absId, pa}); - } - } - } + } else { + PairAmp pa = {0}; + if (c.getHighGain()) { + pa.mHGAmp = c.getEnergy(); + } + if (c.getLowGain()) { + pa.mLGAmp = c.getEnergy(); } + mMapPairs.insert({c.getAbsId(), pa}); } - fillRatios(); - } //RawReader::hasNext + } + fillRatios(); } } void PHOSHGLGRatioCalibDevice::endOfStream(o2::framework::EndOfStreamContext& ec) @@ -144,7 +83,6 @@ void PHOSHGLGRatioCalibDevice::endOfStream(o2::framework::EndOfStreamContext& ec //calculate stuff here calculateRatios(); checkRatios(); - sendOutput(ec.outputs()); } @@ -164,7 +102,6 @@ void PHOSHGLGRatioCalibDevice::calculateRatios() // Calculate mean of the ratio int n = o2::phos::Mapping::NCHANNELS; if (mhRatio->Integral() > 2 * minimalStatistics * n) { //average per channel - mCalibParams.reset(new CalibParams()); TF1* fitFunc = new TF1("fitFunc", "gaus", 0., 4000.); fitFunc->SetParameters(1., 200., 60.); @@ -185,83 +122,101 @@ void PHOSHGLGRatioCalibDevice::calculateRatios() } void PHOSHGLGRatioCalibDevice::checkRatios() { - //Compare pedestals to current ones stored in CCDB - //and send difference to QC to check + //Compare ratios to current ones stored in CCDB if (!mUseCCDB) { mUpdateCCDB = true; return; } - // //TODO: - // //Get current map - // int nChanged=0; - // for(short i=o2::phos::Mapping::NCHANNELS; --i;){ - // short dp=2; - // if(oldPed.mCalibParams->setHGLGRatio(i)>0){ - // dp = mCalibParams->setHGLGRatio(i)/oldPed.mCalibParams->setHGLGRatio(i); - // } - // mRatioDiff[i]=dp ; - // if(abs(dp-1.)>0.1){ //not a fluctuation - // nChanged++; - // } - // if(nChanged>kMinorChange){ //serious change, do not update CCDB automatically, use "force" option to overwrite - // mUpdateCCDB=false; - // } - // else{ - // mUpdateCCDB=true; - // } + LOG(INFO) << "Retrieving current HG/LG ratio from CCDB"; + //Read current padestals for comarison + o2::ccdb::CcdbApi ccdb; + ccdb.init(mCCDBPath); // or http://localhost:8080 for a local installation + std::map metadata; + auto* currentCalibParams = ccdb.retrieveFromTFileAny("PHS/Calib/CalibParams", metadata, mRunStartTime); + + if (!currentCalibParams) { //was not read from CCDB, but expected + mUpdateCCDB = true; + LOG(ERROR) << "Can not read current CalibParams from ccdb"; + return; + } + + LOG(INFO) << "Got current calibration from CCDB"; + + //Compare to current + int nChanged = 0; + for (short i = o2::phos::Mapping::NCHANNELS; i > 1792; i--) { + short dp = 2; + if (currentCalibParams->getHGLGRatio(i) > 0) { + dp = mCalibParams->getHGLGRatio(i) / currentCalibParams->getHGLGRatio(i); + } + mRatioDiff[i] = dp; + if (abs(dp - 1.) > 0.1) { //not a fluctuation + nChanged++; + } + //Copy other stuff from the current CalibParams to new one + mCalibParams->setGain(i, currentCalibParams->getGain(i)); + mCalibParams->setHGTimeCalib(i, currentCalibParams->getHGTimeCalib(i)); + mCalibParams->setLGTimeCalib(i, currentCalibParams->getLGTimeCalib(i)); + } + LOG(INFO) << nChanged << "channels changed more that 1 ADC channel"; + if (nChanged > kMinorChange) { //serious change, do not update CCDB automatically, use "force" option to overwrite + LOG(ERROR) << "too many channels changed: " << nChanged << " (threshold " << kMinorChange << ")"; + if (!mForceUpdate) { + LOG(ERROR) << "you may use --forceupdate option to force updating ccdb"; + } + mUpdateCCDB = false; + } else { + mUpdateCCDB = true; + } } void PHOSHGLGRatioCalibDevice::sendOutput(DataAllocator& output) { + // extract CCDB infos and calibration objects, convert it to TMemFile and send them to the output - // TODO in principle, this routine is generic, can be moved to Utils.h - // using clbUtils = o2::calibration::Utils; - if (mUpdateCCDB || mForceUpdate) { + if (mUseCCDB && (mUpdateCCDB || mForceUpdate)) { // prepare all info to be sent to CCDB - o2::ccdb::CcdbObjectInfo info; - auto image = o2::ccdb::CcdbApi::createObjectImage(mCalibParams.get(), &info); - auto flName = o2::ccdb::CcdbApi::generateFileName("CalibParams"); - info.setPath("PHOS/Calib/CalibParams"); - info.setObjectType("CalibParams"); - info.setFileName(flName); - // TODO: should be changed to time of the run - const auto now = std::chrono::system_clock::now(); - long timeStart = std::chrono::duration_cast(now.time_since_epoch()).count(); - info.setStartValidityTimestamp(timeStart); - info.setEndValidityTimestamp(99999999999999); std::map md; + o2::ccdb::CcdbObjectInfo info("PHS/Calib/CalibParams", "CalibParams", flName, md, mRunStartTime, 99999999999999); info.setMetaData(md); + auto image = o2::ccdb::CcdbApi::createObjectImage(mCalibParams.get(), &info); - LOG(INFO) << "Sending object PHOS/Calib/CalibParams"; + LOG(INFO) << "Sending object " << info.getPath() << "/" << info.getFileName() + << " of size " << image->size() + << " bytes, valid for " << info.getStartValidityTimestamp() + << " : " << info.getEndValidityTimestamp(); - // header::DataHeader::SubSpecificationType subSpec{(header::DataHeader::SubSpecificationType)0}; - // output.snapshot(Output{o2::calibration::Utils::gDataOriginCLB, o2::calibration::Utils::gDataDescriptionCLBPayload, subSpec}, *image.get()); - // output.snapshot(Output{o2::calibration::Utils::gDataOriginCLB, o2::calibration::Utils::gDataDescriptionCLBInfo, subSpec}, info); + header::DataHeader::SubSpecificationType subSpec{(header::DataHeader::SubSpecificationType)0}; + output.snapshot(Output{o2::calibration::Utils::gDataOriginCLB, o2::calibration::Utils::gDataDescriptionCLBPayload, subSpec}, *image.get()); + output.snapshot(Output{o2::calibration::Utils::gDataOriginCLB, o2::calibration::Utils::gDataDescriptionCLBInfo, subSpec}, info); } //Anyway send change to QC - LOG(INFO) << "[PHOSPedestalCalibDevice - run] Writing "; - output.snapshot(o2::framework::Output{"PHS", "HGLGRATIODIFF", 0, o2::framework::Lifetime::Timeframe}, mRatioDiff); - - //Write pedestal distributions to calculate bad map - std::string filename = mPath + "PHOSHGLHRatio.root"; - TFile f(filename.data(), "RECREATE"); - mhRatio->Write(); - f.Close(); + LOG(INFO) << "[PHOSHGLGRatioCalibDevice - sendOutput] Sending QC "; + if (mUseCCDB) { //can get previous calibration + output.snapshot(o2::framework::Output{"PHS", "HGLGRATIODIFF", 0, o2::framework::Lifetime::Timeframe}, mRatioDiff); + } } DataProcessorSpec o2::phos::getHGLGRatioCalibSpec(bool useCCDB, bool forceUpdate, std::string path) { - std::vector inputs; - inputs.emplace_back("RAWDATA", o2::framework::ConcreteDataTypeMatcher{"PHS", "RAWDATA"}, o2::framework::Lifetime::Timeframe); - - std::vector outputs; - outputs.emplace_back("PHS", "HGLGRATIO", 0, o2::framework::Lifetime::Timeframe); - outputs.emplace_back("PHS", "HGLGRATIODIFF", 0, o2::framework::Lifetime::Timeframe); + std::vector inputs; + inputs.emplace_back("cells", o2::header::gDataOriginPHS, "CELLS", 0, o2::framework::Lifetime::Timeframe); + inputs.emplace_back("cellTriggerRecords", o2::header::gDataOriginPHS, "CELLTRIGREC", 0, o2::framework::Lifetime::Timeframe); + + using clbUtils = o2::calibration::Utils; + std::vector outputs; + if (useCCDB) { + outputs.emplace_back( + ConcreteDataTypeMatcher{clbUtils::gDataOriginCLB, clbUtils::gDataDescriptionCLBPayload}); + outputs.emplace_back( + ConcreteDataTypeMatcher{clbUtils::gDataOriginCLB, clbUtils::gDataDescriptionCLBInfo}); + outputs.emplace_back("PHS", "HGLGRATIODIFF", 0, o2::framework::Lifetime::Timeframe); + } return o2::framework::DataProcessorSpec{"HGLGRatioCalibSpec", inputs, outputs, - o2::framework::adaptFromTask(useCCDB, forceUpdate, path), + o2::framework::adaptFromTask(useCCDB, forceUpdate, path), o2::framework::Options{}}; } diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSPedestalCalibDevice.cxx b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSPedestalCalibDevice.cxx index 894de652cf19c..775b1e7d82698 100644 --- a/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSPedestalCalibDevice.cxx +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSPedestalCalibDevice.cxx @@ -19,12 +19,8 @@ #include "Framework/ControlService.h" #include "Framework/WorkflowSpec.h" #include "DataFormatsPHOS/TriggerRecord.h" -#include "DetectorsRaw/RDHUtils.h" -#include "Framework/InputRecordWalker.h" +#include "DataFormatsPHOS/Cell.h" #include "PHOSBase/Mapping.h" -#include "PHOSReconstruction/Bunch.h" -#include "PHOSReconstruction/AltroDecoder.h" -#include "PHOSReconstruction/RawDecodingError.h" #include using namespace o2::phos; @@ -32,17 +28,6 @@ using namespace o2::phos; void PHOSPedestalCalibDevice::init(o2::framework::InitContext& ic) { - mMapping.reset(new o2::phos::Mapping("")); - if (mMapping.get() == nullptr) { - LOG(FATAL) << "Failed to initialize mapping"; - } - if (mMapping->setMapping() != o2::phos::Mapping::kOK) { - LOG(ERROR) << "Failed to construct mapping"; - } - - mRawFitter.reset(new o2::phos::CaloRawFitter()); - mRawFitter->setPedestal(); // work in pedestal evaluation mode - //Create histograms for mean and RMS short n = o2::phos::Mapping::NCHANNELS; mMeanHG.reset(new TH2F("MeanHighGain", "MeanHighGain", n, 0.5, n + 0.5, 100, 0., 100.)); @@ -53,83 +38,27 @@ void PHOSPedestalCalibDevice::init(o2::framework::InitContext& ic) void PHOSPedestalCalibDevice::run(o2::framework::ProcessingContext& ctx) { + // scan Cells stream, collect mean and RMS then calculateaverage and post + if (mRunStartTime == 0) { + mRunStartTime = o2::header::get(ctx.inputs().get("cellTriggerRecords").header)->startTime; + } - //Read current padestals for comarison - // if (mUseCCDB && mOldPed.get()==nullptr) { - // mOldPed.reset(std::move(ctx.inputs().get("oldPedestals"))); - // } - - // - for (const auto& rawData : framework::InputRecordWalker(ctx.inputs())) { - - o2::phos::RawReaderMemory rawreader(o2::framework::DataRefUtils::as(rawData)); - - // loop over all the DMA pages - while (rawreader.hasNext()) { - try { - rawreader.next(); - } catch (RawDecodingError::ErrorType_t e) { - LOG(ERROR) << "Raw decoding error " << (int)e; - //if problem in header, abandon this page - if (e == RawDecodingError::ErrorType_t::PAGE_NOTFOUND || - e == RawDecodingError::ErrorType_t::HEADER_DECODING || - e == RawDecodingError::ErrorType_t::HEADER_INVALID) { - break; - } - //if problem in payload, try to continue - continue; - } - auto& header = rawreader.getRawHeader(); - auto triggerBC = o2::raw::RDHUtils::getTriggerBC(header); - auto triggerOrbit = o2::raw::RDHUtils::getTriggerOrbit(header); - auto ddl = o2::raw::RDHUtils::getFEEID(header); - - if (mRunStartTime == 0) { - o2::InteractionRecord currentIR(triggerBC, triggerOrbit); - mRunStartTime = long(currentIR.bc2ns() * 1.e-9); - } - - if (ddl > o2::phos::Mapping::NDDL) { //only 14 correct DDLs - LOG(ERROR) << "DDL=" << ddl; - continue; //skip STU ddl - } - // use the altro decoder to decode the raw data, and extract the RCU trailer - o2::phos::AltroDecoder decoder(rawreader); - AltroDecoderError::ErrorType_t err = decoder.decode(); - - if (err != AltroDecoderError::kOK) { - LOG(ERROR) << "Errror " << err << " in decoding DDL" << ddl; + auto cells = ctx.inputs().get>("cells"); + LOG(DEBUG) << "[PHOSPedestalCalibDevice - run] Received " << cells.size() << " cells, running calibration ..."; + auto cellsTR = ctx.inputs().get>("cellTriggerRecords"); + for (const auto& tr : cellsTR) { + int firstCellInEvent = tr.getFirstEntry(); + int lastCellInEvent = firstCellInEvent + tr.getNumberOfObjects(); + for (int i = firstCellInEvent; i < lastCellInEvent; i++) { + const Cell c = cells[i]; + if (c.getHighGain()) { + mMeanHG->Fill(c.getAbsId(), c.getEnergy()); + mRMSHG->Fill(c.getAbsId(), 1.e+7 * c.getTime()); + } else { + mMeanLG->Fill(c.getAbsId(), c.getEnergy()); + mRMSLG->Fill(c.getAbsId(), 1.e+7 * c.getTime()); } - auto& rcu = decoder.getRCUTrailer(); - auto& channellist = decoder.getChannels(); - // Loop over all the channels for this RCU - for (auto& chan : channellist) { - short absId; - Mapping::CaloFlag caloFlag; - short fee; - Mapping::ErrorStatus s = mMapping->hwToAbsId(ddl, chan.getHardwareAddress(), absId, caloFlag); - if (s != Mapping::ErrorStatus::kOK) { - LOG(ERROR) << "Error in mapping" - << " ddl=" << ddl << " hwaddress " << chan.getHardwareAddress(); - continue; - } - if (caloFlag != Mapping::kTRU) { //HighGain or LowGain - CaloRawFitter::FitStatus fitResults = mRawFitter->evaluate(chan.getBunches()); - if (fitResults == CaloRawFitter::FitStatus::kOK || fitResults == CaloRawFitter::FitStatus::kNoTime) { - //TODO: which results should be accepted? full configurable list - for (int is = 0; is < mRawFitter->getNsamples(); is++) { - if (caloFlag == Mapping::kHighGain) { - mMeanHG->Fill(absId, mRawFitter->getAmp(is)); - mRMSHG->Fill(absId, mRawFitter->getTime(is)); - } else { - mMeanLG->Fill(absId, mRawFitter->getAmp(is)); - mRMSLG->Fill(absId, mRawFitter->getTime(is)); - } - } - } - } - } - } //RawReader::hasNext + } } } @@ -139,32 +68,26 @@ void PHOSPedestalCalibDevice::endOfStream(o2::framework::EndOfStreamContext& ec) LOG(INFO) << "[PHOSPedestalCalibDevice - endOfStream]"; //calculate stuff here calculatePedestals(); - checkPedestals(); - sendOutput(ec.outputs()); } void PHOSPedestalCalibDevice::sendOutput(DataAllocator& output) { + // extract CCDB infos and calibration objects, convert it to TMemFile and send them to the output - // TODO in principle, this routine is generic, can be moved to Utils.h - // using clbUtils = o2::calibration::Utils; - if (mUpdateCCDB || mForceUpdate) { + if (mUseCCDB && (mUpdateCCDB || mForceUpdate)) { // prepare all info to be sent to CCDB - o2::ccdb::CcdbObjectInfo info; - auto image = o2::ccdb::CcdbApi::createObjectImage(mPedestals.get(), &info); - auto flName = o2::ccdb::CcdbApi::generateFileName("Pedestals"); - info.setPath("PHOS/Calib/Pedestals"); - info.setObjectType("Pedestals"); - info.setFileName(flName); - info.setStartValidityTimestamp(mRunStartTime); - info.setEndValidityTimestamp(99999999999999); std::map md; + o2::ccdb::CcdbObjectInfo info("PHS/Calib/Pedestals", "Pedestals", flName, md, mRunStartTime, 99999999999999); info.setMetaData(md); + auto image = o2::ccdb::CcdbApi::createObjectImage(mPedestals.get(), &info); - LOG(INFO) << "Sending object PHOS/Calib/Pedestals"; + LOG(INFO) << "Sending object " << info.getPath() << "/" << info.getFileName() + << " of size " << image->size() + << " bytes, valid for " << info.getStartValidityTimestamp() + << " : " << info.getEndValidityTimestamp(); header::DataHeader::SubSpecificationType subSpec{(header::DataHeader::SubSpecificationType)0}; output.snapshot(Output{o2::calibration::Utils::gDataOriginCLB, o2::calibration::Utils::gDataDescriptionCLBPayload, subSpec}, *image.get()); @@ -172,18 +95,10 @@ void PHOSPedestalCalibDevice::sendOutput(DataAllocator& output) } //Anyway send change to QC LOG(INFO) << "[PHOSPedestalCalibDevice - run] Sending QC "; - output.snapshot(o2::framework::Output{"PHS", "PEDDIFF", 0, o2::framework::Lifetime::Timeframe}, mPedHGDiff); - output.snapshot(o2::framework::Output{"PHS", "PEDDIFF", 0, o2::framework::Lifetime::Timeframe}, mPedLGDiff); - - LOG(INFO) << "[PHOSPedestalCalibDevice - run] Writing "; - //Write pedestal distributions to calculate bad map - std::string filename = mPath + "PHOSPedestals.root"; - TFile f(filename.data(), "RECREATE"); - mMeanHG->Write(); - mMeanLG->Write(); - mRMSHG->Write(); - mRMSLG->Write(); - f.Close(); + if (mUseCCDB) { //can get previous calibration + output.snapshot(o2::framework::Output{"PHS", "PEDDIFF", 0, o2::framework::Lifetime::Timeframe}, mPedHGDiff); + output.snapshot(o2::framework::Output{"PHS", "PEDDIFF", 0, o2::framework::Lifetime::Timeframe}, mPedLGDiff); + } } void PHOSPedestalCalibDevice::calculatePedestals() @@ -201,38 +116,57 @@ void PHOSPedestalCalibDevice::calculatePedestals() a = pr->GetMean(); mPedestals->setLGPedestal(i - 1, std::min(255, int(a))); pr->Delete(); + pr = mRMSHG->ProjectionY(Form("projRMS%d", i), i, i); + a = pr->GetMean(); + mPedestals->setHGRMS(i - 1, a); + pr->Delete(); + pr = mRMSLG->ProjectionY(Form("projRMSLG%d", i), i, i); + a = pr->GetMean(); + mPedestals->setLGRMS(i - 1, a); + pr->Delete(); } } void PHOSPedestalCalibDevice::checkPedestals() { - //Compare pedestals to current ones stored in CCDB - //and send difference to QC to check if (!mUseCCDB) { mUpdateCCDB = true; return; } + LOG(INFO) << "Retrieving current Pedestals from CCDB"; + //Read current padestals for comarison + o2::ccdb::CcdbApi ccdb; + ccdb.init(mCCDBPath); // or http://localhost:8080 for a local installation + std::map metadata; + auto* currentPedestals = ccdb.retrieveFromTFileAny("PHS/Calib/Pedestals", metadata, mRunStartTime); - if (mOldPed.get() == nullptr) { //was not read from CCDB, but expected - mUpdateCCDB = false; + if (!currentPedestals) { //was not read from CCDB, but expected + mUpdateCCDB = true; return; } + LOG(INFO) << "Got current Pedestals from CCDB"; + //Compare to current int nChanged = 0; - for (short i = o2::phos::Mapping::NCHANNELS; --i;) { - short dp = mPedestals->getHGPedestal(i) - mOldPed->getHGPedestal(i); + for (short i = o2::phos::Mapping::NCHANNELS; i > 1792; i--) { + short dp = mPedestals->getHGPedestal(i) - currentPedestals->getHGPedestal(i); mPedHGDiff[i] = dp; if (abs(dp) > 1) { //not a fluctuation nChanged++; } - dp = mPedestals->getLGPedestal(i) - mOldPed->getLGPedestal(i); + dp = mPedestals->getLGPedestal(i) - currentPedestals->getLGPedestal(i); mPedLGDiff[i] = dp; if (abs(dp) > 1) { //not a fluctuation nChanged++; } } + LOG(INFO) << nChanged << "channels changed more that 1 ADC channel"; if (nChanged > kMinorChange) { //serious change, do not update CCDB automatically, use "force" option to overwrite + LOG(ERROR) << "too many channels changed: " << nChanged << " (threshold not more than " << kMinorChange << ")"; + if (!mForceUpdate) { + LOG(ERROR) << "you may use --forceupdate option to force updating ccdb"; + } mUpdateCCDB = false; } else { mUpdateCCDB = true; @@ -243,16 +177,18 @@ o2::framework::DataProcessorSpec o2::phos::getPedestalCalibSpec(bool useCCDB, bo { std::vector inputs; - inputs.emplace_back("RAWDATA", o2::framework::ConcreteDataTypeMatcher{"PHS", "RAWDATA"}, o2::framework::Lifetime::Timeframe); + inputs.emplace_back("cells", o2::header::gDataOriginPHS, "CELLS", 0, o2::framework::Lifetime::Timeframe); + inputs.emplace_back("cellTriggerRecords", o2::header::gDataOriginPHS, "CELLTRIGREC", 0, o2::framework::Lifetime::Timeframe); + + using clbUtils = o2::calibration::Utils; + std::vector outputs; if (useCCDB) { - // inputs.emplace_back("oldPedestals", "PHOS", "Pedestals"); - inputs.emplace_back("oldPedestals", o2::header::gDataOriginPHS, "Pedestals"); + outputs.emplace_back( + ConcreteDataTypeMatcher{clbUtils::gDataOriginCLB, clbUtils::gDataDescriptionCLBPayload}); + outputs.emplace_back( + ConcreteDataTypeMatcher{clbUtils::gDataOriginCLB, clbUtils::gDataDescriptionCLBInfo}); + outputs.emplace_back("PHS", "PEDDIFF", 0, o2::framework::Lifetime::Timeframe); } - - std::vector outputs; - outputs.emplace_back("PHS", "PEDCALIBS", 0, o2::framework::Lifetime::Timeframe); - outputs.emplace_back("PHS", "PEDDIFF", 0, o2::framework::Lifetime::Timeframe); - return o2::framework::DataProcessorSpec{"PedestalCalibSpec", inputs, outputs, diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSRunbyrunCalibDevice.cxx b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSRunbyrunCalibDevice.cxx new file mode 100644 index 0000000000000..b2dd0224521db --- /dev/null +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSRunbyrunCalibDevice.cxx @@ -0,0 +1,105 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "PHOSCalibWorkflow/PHOSRunbyrunCalibDevice.h" +#include "Framework/ConfigParamRegistry.h" +#include "CCDB/CcdbApi.h" +#include "CCDB/CcdbObjectInfo.h" +#include "DetectorsCalibration/Utils.h" +#include "Framework/ControlService.h" + +#include "FairLogger.h" + +using namespace o2::phos; + +void PHOSRunbyrunCalibDevice::init(o2::framework::InitContext& ic) +{ + // int slotL = ic.options().get("tf-per-slot"); + // int delay = ic.options().get("max-delay"); + mCalibrator.reset(new PHOSRunbyrunCalibrator()); + + // mCalibrator->setSlotLength(slotL); + // mCalibrator->setMaxSlotsDelay(delay); + mCalibrator->setUpdateAtTheEndOfRunOnly(); +} +void PHOSRunbyrunCalibDevice::run(o2::framework::ProcessingContext& pc) +{ + auto tfcounter = o2::header::get(pc.inputs().get("clusters").header)->startTime; // is this the timestamp of the current TF? + auto clusters = pc.inputs().get>("clusters"); + auto cluTR = pc.inputs().get>("cluTR"); + LOG(INFO) << "Processing TF with " << clusters.size() << " clusters and " << cluTR.size() << " TriggerRecords"; + mCalibrator->process(tfcounter, clusters, cluTR); +} + +void PHOSRunbyrunCalibDevice::endOfStream(o2::framework::EndOfStreamContext& ec) +{ + constexpr uint64_t INFINITE_TF = 0xffffffffffffffff; + mCalibrator->checkSlotsToFinalize(INFINITE_TF); + mCalibrator->endOfStream(); + mRunByRun = mCalibrator->getCalibration(); + if (checkFitResult()) { + LOG(INFO) << "End of stream reached, sending output to CCDB"; + // prepare all info to be sent to CCDB + auto flName = o2::ccdb::CcdbApi::generateFileName("Runbyrun"); + std::map md; + o2::ccdb::CcdbObjectInfo info("PHS/Calib/Runbyrun", "Runbyrun", flName, md, mRunStartTime, INFINITE_TF); + info.setMetaData(md); + auto image = o2::ccdb::CcdbApi::createObjectImage(&mRunByRun, &info); + + LOG(INFO) << "Sending object " << info.getPath() << "/" << info.getFileName() + << " of size " << image->size() + << " bytes, valid for " << info.getStartValidityTimestamp() + << " : " << info.getEndValidityTimestamp(); + + header::DataHeader::SubSpecificationType subSpec{(header::DataHeader::SubSpecificationType)0}; + ec.outputs().snapshot(Output{o2::calibration::Utils::gDataOriginCLB, o2::calibration::Utils::gDataDescriptionCLBPayload, subSpec}, *image.get()); + ec.outputs().snapshot(Output{o2::calibration::Utils::gDataOriginCLB, o2::calibration::Utils::gDataDescriptionCLBInfo, subSpec}, info); + } else { + LOG(ERROR) << "Incorrect fit results: " << mRunByRun[0] << "+-" << mRunByRun[1] << ", " + << mRunByRun[2] << "+-" << mRunByRun[3] << ", " + << mRunByRun[4] << "+-" << mRunByRun[5] << ", " + << mRunByRun[6] << "+-" << mRunByRun[7]; + } + //TODO! Send mRunByRun for QC and trending plots + // + + //Get ready for next run + mCalibrator->initOutput(); // reset the outputs once they are already sent +} +bool PHOSRunbyrunCalibDevice::checkFitResult() +{ + bool res = true; + const float massmin = 0.125; + const float massmax = 0.155; + for (int mod = 0; mod < 4; mod++) { + res &= mRunByRun[2 * mod] < massmax && mRunByRun[2 * mod] > massmin; + } + return res; +} + +o2::framework::DataProcessorSpec o2::phos::getPHOSRunbyrunCalibDeviceSpec(bool useCCDB, std::string path) +{ + + std::vector outputs; + outputs.emplace_back("PHS", "RUNBYRUNHISTOS", 0, o2::framework::Lifetime::Timeframe); + outputs.emplace_back(ConcreteDataTypeMatcher{o2::calibration::Utils::gDataOriginCLB, o2::calibration::Utils::gDataDescriptionCLBPayload}); + outputs.emplace_back(ConcreteDataTypeMatcher{o2::calibration::Utils::gDataOriginCLB, o2::calibration::Utils::gDataDescriptionCLBInfo}); + + std::vector inputs; + inputs.emplace_back("clusters", "PHS", "CLUSTERS"); + inputs.emplace_back("cluTR", "PHS", "CLUSTERTRIGREC"); + + return DataProcessorSpec{ + "calib-phos-runbyrun", + inputs, + outputs, + AlgorithmSpec{adaptFromTask()}, + Options{}}; +} diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSRunbyrunCalibrator.cxx b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSRunbyrunCalibrator.cxx new file mode 100644 index 0000000000000..37b486c547abd --- /dev/null +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSRunbyrunCalibrator.cxx @@ -0,0 +1,285 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "PHOSCalibWorkflow/PHOSRunbyrunCalibrator.h" +#include "DataFormatsPHOS/TriggerRecord.h" +#include "Framework/ConfigParamRegistry.h" +#include "CCDB/CcdbApi.h" +#include "CCDB/CcdbObjectInfo.h" +#include "Framework/ControlService.h" +#include "TFile.h" +#include "TF1.h" + +#include "FairLogger.h" + +using namespace o2::phos; + +using Slot = o2::calibration::TimeSlot; + +PHOSRunbyrunSlot::PHOSRunbyrunSlot(bool useCCDB, std::string path) : mUseCCDB(useCCDB), mCCDBPath(path) +{ + const int nMass = 150.; + const float massMax = 0.3; + for (int mod = 0; mod < 4; mod++) { + mReMi[2 * mod] = boost::histogram::make_histogram(boost::histogram::axis::regular<>(nMass, 0., massMax, "mgg")); + mReMi[2 * mod + 1] = boost::histogram::make_histogram(boost::histogram::axis::regular<>(nMass, 0., massMax, "mgg")); + } + mBuffer.reset(new RingBuffer()); +} +PHOSRunbyrunSlot::PHOSRunbyrunSlot(const PHOSRunbyrunSlot& other) +{ + mUseCCDB = other.mUseCCDB; + mRunStartTime = other.mUseCCDB; + mCCDBPath = other.mCCDBPath; + const int nMass = 150.; + const float massMax = 0.3; + for (int mod = 0; mod < 4; mod++) { + mReMi[2 * mod] = boost::histogram::make_histogram(boost::histogram::axis::regular<>(nMass, 0., massMax, "mgg")); + mReMi[2 * mod + 1] = boost::histogram::make_histogram(boost::histogram::axis::regular<>(nMass, 0., massMax, "mgg")); + } + mBuffer.reset(new RingBuffer()); + mBadMap = nullptr; +} + +void PHOSRunbyrunSlot::print() const +{ + // to print number of entries in pi0 region + double s[4]; + for (int mod = 0; mod < 4; mod++) { + s[mod] = boost::histogram::algorithm::sum(mReMi[2 * mod]); + } + LOG(INFO) << "Total number of entries in pi0 region: " << s[0] << "," << s[1] << "," << s[2] << "," << s[3]; +} + +void PHOSRunbyrunSlot::fill(const std::vector& clusters, const gsl::span& trs) +{ + if (!mBadMap) { + if (mUseCCDB) { + LOG(INFO) << "Retrieving BadMap from CCDB"; + o2::ccdb::CcdbApi ccdb; + ccdb.init(mCCDBPath); // or http://localhost:8080 for a local installation + std::map metadata; + mBadMap.reset(ccdb.retrieveFromTFileAny("PHS/Calib/BadChannels", metadata, mRunStartTime)); + + if (!mBadMap) { //was not read from CCDB, but expected + LOG(FATAL) << "Can not read BadMap from CCDB, you may use --not-use-ccdb option to create default bad map"; + } + } else { + LOG(INFO) << "Do not use CCDB, create default BadMap"; + mBadMap.reset(new BadChannelMap()); + } + } + + for (auto& tr : trs) { + + int firstCluInEvent = tr.getFirstEntry(); + int lastCluInEvent = firstCluInEvent + tr.getNumberOfObjects(); + + //TODO!!! Get MFT0 vertex + TVector3 vertex = {0., 0., 0.}; + mBuffer->startNewEvent(); // mark stored clusters to be used for Mixing + for (int i = firstCluInEvent; i < lastCluInEvent; i++) { + const FullCluster& clu = clusters[i]; + + if (!checkCluster(clu)) { + continue; + } + // prepare TLorentsVector + float posX, posZ; + clu.getLocalPosition(posX, posZ); + TVector3 vec3; + Geometry::GetInstance("Run3")->local2Global(clu.module(), posX, posZ, vec3); + vec3 -= vertex; + float e = clu.getEnergy(); + vec3 *= 1. / vec3.Mag(); + TLorentzVector v(vec3.X() * e, vec3.Y() * e, vec3.Z() * e, e); + for (short ip = mBuffer->size(); ip--;) { + const TLorentzVector& vp = mBuffer->getEntry(ip); + TLorentzVector sum = v + vp; + if (sum.Pt() > mPtCut) { + if (mBuffer->isCurrentEvent(ip)) { //same (real) event + mReMi[2 * clu.module()](sum.M()); // put all high-pt pairs to bin 4-6 GeV + } else { //Mixed + mReMi[2 * clu.module() + 1](sum.M()); // put all high-pt pairs to bin 4-6 GeV + } + } + } + mBuffer->addEntry(v); + } + } +} +void PHOSRunbyrunSlot::merge(const PHOSRunbyrunSlot* prev) +{ + //Not used +} +bool PHOSRunbyrunSlot::checkCluster(const FullCluster& clu) +{ + //First check BadMap + float posX, posZ; + clu.getLocalPosition(posX, posZ); + short absId; + Geometry::relPosToAbsId(clu.module(), posX, posZ, absId); + if (!mBadMap->isChannelGood(absId)) { + return false; + } + return (clu.getEnergy() > 0.3 && clu.getMultiplicity() > 1); +} +void PHOSRunbyrunSlot::clear() +{ + for (int mod = 0; mod < 8; mod++) { + mReMi[mod].reset(); + } +} + +//============================================================== + +PHOSRunbyrunCalibrator::PHOSRunbyrunCalibrator() +{ + const int nMass = 150.; + const float massMax = 0.3; + for (int mod = 0; mod < 4; mod++) { + mReMi[2 * mod] = new TH1F(Form("hReInvMassMod%d", mod), "Real inv. mass per module", nMass, 0., massMax); + mReMi[2 * mod + 1] = new TH1F(Form("hMiInvMassMod%d", mod), "Mixed inv. mass per module", nMass, 0., massMax); + } +} +PHOSRunbyrunCalibrator::~PHOSRunbyrunCalibrator() +{ + for (int mod = 0; mod < 8; mod++) { + if (mReMi[mod]) { + mReMi[mod]->Delete(); + mReMi[mod] = nullptr; + } + } +} + +bool PHOSRunbyrunCalibrator::hasEnoughData(const Slot& slot) const +{ + //otherwize will be merged with next Slot + return true; +} +void PHOSRunbyrunCalibrator::initOutput() +{ +} +void PHOSRunbyrunCalibrator::finalizeSlot(Slot& slot) +{ + + // Extract results for the single slot + PHOSRunbyrunSlot* c = slot.getContainer(); + LOG(INFO) << "Finalize slot " << slot.getTFStart() << " <= TF <= " << slot.getTFEnd(); + //Add histos + for (int mod = 0; mod < 8; mod++) { + PHOSRunbyrunSlot::boostHisto& tmp = c->getCollectedHistos(mod); + int indx = 1; + for (auto&& x : boost::histogram::indexed(tmp)) { + mReMi[mod]->SetBinContent(indx, x.get() + mReMi[mod]->GetBinContent(indx)); + indx++; + } + } + c->clear(); +} + +Slot& PHOSRunbyrunCalibrator::emplaceNewSlot(bool front, uint64_t tstart, uint64_t tend) +{ + + auto& cont = getSlots(); + auto& slot = front ? cont.emplace_front(tstart, tend) : cont.emplace_back(tstart, tend); + slot.setContainer(std::make_unique(mUseCCDB, mCCDBPath)); + return slot; +} + +bool PHOSRunbyrunCalibrator::process(uint64_t tf, const std::vector& clu, const gsl::span& tr) +{ + // if (!mUpdateAtTheEndOfRunOnly) { + // int maxDelay = mMaxSlotsDelay * mSlotLength; + // // if (tf tf + maxDelay)) { // ignore TF + // if (maxDelay != 0 && (tf < mLastClosedTF || (!mSlots.empty() && getLastSlot().getTFStart() > tf + maxDelay))) { // ignore TF + // LOG(INFO) << "Ignoring TF " << tf; + // return false; + // } + + // // check if some slots are done + // checkSlotsToFinalize(tf, maxDelay); + // } + + // process current TF + auto& slotTF = getSlotForTF(tf); + slotTF.getContainer()->setRunStartTime(tf); + slotTF.getContainer()->fill(clu, tr); + + return true; +} +void PHOSRunbyrunCalibrator::endOfStream() +{ + //Merge collected in different slots histograms + TF1 fRatio("ratio", this, &PHOSRunbyrunCalibrator::CBRatio, 0, 1, 6, "PHOSRunbyrunCalibrator", "CBRatio"); + TF1 fBg("background", this, &PHOSRunbyrunCalibrator::bg, 0, 1, 6, "PHOSRunbyrunCalibrator", "bg"); + TF1 fSignal("signal", this, &PHOSRunbyrunCalibrator::CBSignal, 0, 1, 6, "PHOSRunbyrunCalibrator", "CBSignal"); + //fit inv mass distributions + TFile fout("mgg.root", "recreate"); + for (int mod = 0; mod < 4; mod++) { + mReMi[2 * mod]->Sumw2(); + mReMi[2 * mod + 1]->Sumw2(); + TH1D* tmp = (TH1D*)mReMi[2 * mod]->Clone("Ratio"); + tmp->Divide(mReMi[2 * mod + 1]); + fRatio.SetParameters(1., 0.134, 0.005, 0.01, 0., 0.); + tmp->Fit(&fRatio, "q", "", 0.07, 0.22); + fBg.SetParameters(fRatio.GetParameter(3), fRatio.GetParameter(4), fRatio.GetParameter(5)); + mReMi[2 * mod + 1]->Multiply(&fBg); + // mReMi[2*mod]->Add(mReMi[2*mod+1],-1.) ; + fSignal.SetParameters(0.3 * mReMi[2 * mod]->Integral(65, 67, ""), 0.135, 0.005); + mReMi[2 * mod]->Fit(&fSignal, "q", "", 0.07, 0.22); + mRunByRun[2 * mod] = fSignal.GetParameter(1); + mRunByRun[2 * mod + 1] = fSignal.GetParError(1); + tmp->Write(); + mReMi[2 * mod]->Write(); + mReMi[2 * mod + 1]->Write(); + delete tmp; + //Clear before next period? + mReMi[2 * mod]->Reset(); + mReMi[2 * mod + 1]->Reset(); + } + fout.Close(); +} +double PHOSRunbyrunCalibrator::CBRatio(double* x, double* par) +{ + double m = par[1]; + double s = par[2]; + const double n = 4.1983; + const double a = 1.5; + const double A = TMath::Power((n / TMath::Abs(a)), n) * TMath::Exp(-a * a / 2); + const double B = n / TMath::Abs(a) - TMath::Abs(a); + double dx = (x[0] - m) / s; + if (dx > -a) { + return par[0] * exp(-dx * dx / 2.) + + par[3] + par[4] * x[0] + par[5] * x[0] * x[0]; + } else { + return par[0] * A * TMath::Power((B - dx), -n) + + par[3] + par[4] * x[0] + par[5] * x[0] * x[0]; + } +} +double PHOSRunbyrunCalibrator::CBSignal(double* x, double* par) +{ + double m = par[1]; + double s = par[2]; + const double n = 4.1983; + const double a = 1.5; + const double A = TMath::Power((n / TMath::Abs(a)), n) * TMath::Exp(-a * a / 2); + const double B = n / TMath::Abs(a) - TMath::Abs(a); + double dx = (x[0] - m) / s; + if (dx > -a) { + return par[0] * exp(-dx * dx / 2.) + par[3]; + } else { + return par[0] * A * TMath::Power((B - dx), -n) + par[3]; + } +} +double PHOSRunbyrunCalibrator::bg(double* x, double* par) +{ + return par[0] + par[1] * x[0] + par[2] * x[0] * x[0]; +} \ No newline at end of file diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSTurnonCalibDevice.cxx b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSTurnonCalibDevice.cxx new file mode 100644 index 0000000000000..9a3650c8ca15a --- /dev/null +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSTurnonCalibDevice.cxx @@ -0,0 +1,104 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "PHOSCalibWorkflow/PHOSTurnonCalibDevice.h" +#include "PHOSCalibWorkflow/TurnOnHistos.h" +#include "Framework/ConfigParamRegistry.h" +#include "CCDB/CcdbApi.h" +#include "CCDB/CcdbObjectInfo.h" +#include "DetectorsCalibration/Utils.h" +#include "Framework/ControlService.h" + +#include "TF1.h" +#include "TH1.h" +#include "TGraphAsymmErrors.h" + +#include "FairLogger.h" +#include // std::ifstream + +using namespace o2::phos; + +void PHOSTurnonCalibDevice::init(o2::framework::InitContext& ic) +{ + // int slotL = ic.options().get("tf-per-slot"); + // int delay = ic.options().get("max-delay"); + mCalibrator.reset(new PHOSTurnonCalibrator()); + + // mCalibrator->setSlotLength(slotL); + // mCalibrator->setMaxSlotsDelay(delay); + mCalibrator->setUpdateAtTheEndOfRunOnly(); +} +void PHOSTurnonCalibDevice::run(o2::framework::ProcessingContext& pc) +{ + auto tfcounter = o2::header::get(pc.inputs().get("clusters").header)->startTime; // is this the timestamp of the current TF? + auto cells = pc.inputs().get>("cells"); + auto cellTR = pc.inputs().get>("cellTriggerRecords"); + auto clusters = pc.inputs().get>("clusters"); + auto cluTR = pc.inputs().get>("clusterTriggerRecords"); + + LOG(INFO) << "[PHOSTurnonCalibDevice - run] Received " << cells.size() << " cells and " << clusters.size() << " clusters, running calibration"; + + mCalibrator->process(tfcounter, cells, cellTR, clusters, cluTR); +} + +void PHOSTurnonCalibDevice::endOfStream(o2::framework::EndOfStreamContext& ec) +{ + constexpr uint64_t INFINITE_TF = 0xffffffffffffffff; + mCalibrator->checkSlotsToFinalize(INFINITE_TF); + mCalibrator->endOfStream(); + mTriggerMap.reset(new TriggerMap(mCalibrator->getCalibration())); + if (checkFitResult()) { + //Calculate and send final object to CCDB + auto flName = o2::ccdb::CcdbApi::generateFileName("TriggerMap"); + std::map md; + o2::ccdb::CcdbObjectInfo info("PHS/Calib/TriggerMap", "TriggerMap", flName, md, mRunStartTime, 99999999999999); + info.setMetaData(md); + auto image = o2::ccdb::CcdbApi::createObjectImage(mTriggerMap.get(), &info); + + LOG(INFO) << "Sending object " << info.getPath() << "/" << info.getFileName() + << " of size " << image->size() + << " bytes, valid for " << info.getStartValidityTimestamp() + << " : " << info.getEndValidityTimestamp(); + + header::DataHeader::SubSpecificationType subSpec{(header::DataHeader::SubSpecificationType)0}; + ec.outputs().snapshot(Output{o2::calibration::Utils::gDataOriginCLB, o2::calibration::Utils::gDataDescriptionCLBPayload, subSpec}, *image.get()); + ec.outputs().snapshot(Output{o2::calibration::Utils::gDataOriginCLB, o2::calibration::Utils::gDataDescriptionCLBInfo, subSpec}, info); + } else { + LOG(ERROR) << "Incorrect fit results"; + } + // //Send result to QC + // ec.outputs().snapshot(o2::framework::Output{"PHS", "TRIGMAPDIFF", 0, o2::framework::Lifetime::Timeframe}, mTrigMapDiff); + // ec.outputs().snapshot(o2::framework::Output{"PHS", "TURNONDIFF", 0, o2::framework::Lifetime::Timeframe}, mTurnOnDiff); +} + +o2::framework::DataProcessorSpec o2::phos::getPHOSTurnonCalibDeviceSpec(bool useCCDB, std::string path) +{ + + std::vector inputs; + inputs.emplace_back("cells", o2::header::gDataOriginPHS, "CELLS", 0, o2::framework::Lifetime::Timeframe); + inputs.emplace_back("cellTriggerRecords", o2::header::gDataOriginPHS, "CELLTRIGREC", 0, o2::framework::Lifetime::Timeframe); + inputs.emplace_back("clusters", o2::header::gDataOriginPHS, "CLUSTERS", 0, o2::framework::Lifetime::Timeframe); + inputs.emplace_back("clusterTriggerRecords", o2::header::gDataOriginPHS, "CLUSTERTRIGREC", 0, o2::framework::Lifetime::Timeframe); + + using clbUtils = o2::calibration::Utils; + std::vector outputs; + outputs.emplace_back( + ConcreteDataTypeMatcher{clbUtils::gDataOriginCLB, clbUtils::gDataDescriptionCLBPayload}); + outputs.emplace_back( + ConcreteDataTypeMatcher{clbUtils::gDataOriginCLB, clbUtils::gDataDescriptionCLBInfo}); + //stream for QC data + //outputs.emplace_back("PHS", "TRIGGERQC", 0, o2::framework::Lifetime::Timeframe); + + return o2::framework::DataProcessorSpec{"PHOSTurnonCalibDevice", + inputs, + outputs, + o2::framework::adaptFromTask(useCCDB, path), + o2::framework::Options{}}; +} diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSTurnonCalibrator.cxx b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSTurnonCalibrator.cxx new file mode 100644 index 0000000000000..3df0cdf981889 --- /dev/null +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/PHOSTurnonCalibrator.cxx @@ -0,0 +1,201 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "PHOSCalibWorkflow/PHOSTurnonCalibrator.h" +#include "PHOSCalibWorkflow/TurnOnHistos.h" +#include "PHOSBase/Geometry.h" +#include "Framework/ConfigParamRegistry.h" +#include "DetectorsCalibration/Utils.h" +#include "Framework/ControlService.h" +#include "CCDB/CcdbApi.h" +#include "CCDB/CcdbObjectInfo.h" + +#include "TF1.h" +#include "TH1.h" +#include "TGraphAsymmErrors.h" + +#include "FairLogger.h" +#include // std::ifstream + +using namespace o2::phos; + +PHOSTurnonSlot::PHOSTurnonSlot(bool useCCDB, std::string path) : mUseCCDB(useCCDB), mCCDBPath(path) +{ + mFiredTiles.reset(); + mNoisyTiles.reset(); + mTurnOnHistos.reset(new TurnOnHistos()); +} +PHOSTurnonSlot::PHOSTurnonSlot(const PHOSTurnonSlot& other) +{ + mUseCCDB = other.mUseCCDB; + mRunStartTime = other.mUseCCDB; + mCCDBPath = other.mCCDBPath; + mFiredTiles.reset(); + mNoisyTiles.reset(); + mTurnOnHistos.reset(new TurnOnHistos()); +} + +void PHOSTurnonSlot::print() const +{ + for (short ddl = 0; ddl < 14; ddl++) { + const std::array& all = mTurnOnHistos->getTotSpectrum(ddl); + const std::array& tr = mTurnOnHistos->getTrSpectrum(ddl); + float sumAll = 0, sumTr = 0.; + for (int i = 0; i < TurnOnHistos::Npt; i++) { + sumAll += all[i]; + sumTr += tr[i]; + } + LOG(INFO) << "DDL " << ddl << " total entries " << sumAll << " trigger clusters " << sumTr; + } +} +void PHOSTurnonSlot::fill(const gsl::span& cells, const gsl::span& cellTR, + const std::vector& clusters, const gsl::span& cluTR) +{ + + auto ctr = cellTR.begin(); + auto clutr = cluTR.begin(); + while (ctr != cellTR.end() && clutr != cluTR.end()) { + // + //TODO! select NOT PHOS triggered events + // DataProcessingHeader:: + // + if (ctr->getBCData() != clutr->getBCData()) { + LOG(ERROR) << "Different TrigRecords for cells:" << ctr->getBCData() << " and clusters:" << clutr->getBCData(); + //TODO: Try to recover by increasing smaller TR? + } + scanClusters(cells, *ctr, clusters, *clutr); + ctr++; + clutr++; + } +} +void PHOSTurnonSlot::clear() +{ + mFiredTiles.reset(); + mNoisyTiles.reset(); + mTurnOnHistos.reset(); +} +void PHOSTurnonSlot::scanClusters(const gsl::span& cells, const TriggerRecord& celltr, + const std::vector& clusters, const TriggerRecord& clutr) +{ + //First fill map of expected tiles from TRU cells + mNoisyTiles.reset(); + int firstCellInEvent = celltr.getFirstEntry(); + int lastCellInEvent = firstCellInEvent + celltr.getNumberOfObjects(); + for (int i = firstCellInEvent; i < lastCellInEvent; i++) { + const Cell& c = cells[i]; + if (c.getTRU()) { + mNoisyTiles.set(c.getTRUId()); + } + } + + //Copy to have good and noisy map + + mFiredTiles.reset(); + char mod; + float x, z; + short ddl; + int firstCluInEvent = clutr.getFirstEntry(); + int lastCluInEvent = firstCluInEvent + clutr.getNumberOfObjects(); + for (int i = firstCluInEvent; i < lastCluInEvent; i++) { + const FullCluster& clu = clusters[i]; + mod = clu.module(); + clu.getLocalPosition(x, z); + short truId = Geometry::relPosToTruId(mod, x, z, ddl); + //TODO!!! if(map.isGood2x2(truId)){ + mTurnOnHistos->fillTotSp(ddl, clu.getEnergy()); + if (clu.firedTrigger() & 1) { //Bit 1: 2x2, bit 2 4x4 //TODO: do we need separate 2x2 and 4x4 spectra? Switch? + mTurnOnHistos->fillFiredSp(ddl, clu.getEnergy()); + //Fill trigger map + mFiredTiles.set(truId); + } + // } + } + //Fill final good and noisy maps + mTurnOnHistos->fillFiredMap(mFiredTiles); + mNoisyTiles ^= mFiredTiles; + mTurnOnHistos->fillNoisyMap(mFiredTiles); +} +//============================================== + +void PHOSTurnonCalibrator::finalizeSlot(Slot& slot) +{ + // Extract results for the single slot + //if not ready yet, prepare containers + if (!mTurnOnHistos) { + mTurnOnHistos.reset(new TurnOnHistos()); + } + PHOSTurnonSlot* c = slot.getContainer(); + LOG(INFO) << "Finalize slot " << slot.getTFStart() << " <= TF <= " << slot.getTFEnd(); + //Add histos + for (int mod = 0; mod < 8; mod++) { + mTurnOnHistos->merge(c->getCollectedHistos()); + } + c->clear(); +} +PHOSTurnonCalibrator::Slot& PHOSTurnonCalibrator::emplaceNewSlot(bool front, uint64_t tstart, uint64_t tend) +{ + + auto& cont = getSlots(); + auto& slot = front ? cont.emplace_front(tstart, tend) : cont.emplace_back(tstart, tend); + slot.setContainer(std::make_unique(mUseCCDB, mCCDBPath)); + return slot; +} + +bool PHOSTurnonCalibrator::process(uint64_t tf, const gsl::span& cells, const gsl::span& cellTR, + const std::vector& clusters, const gsl::span& cluTR) +{ + // process current TF + auto& slotTF = getSlotForTF(tf); + slotTF.getContainer()->setRunStartTime(tf); + slotTF.getContainer()->fill(cells, cellTR, clusters, cluTR); + + return true; +} + +void PHOSTurnonCalibrator::endOfStream() +{ + //Use stored histos to calculate maps and turn-on curves + //return true of successful + + //extract TOC + if (!mTriggerMap) { + mTriggerMap.reset(new TriggerMap()); + } + TF1* th = new TF1("aTh", "[0]/(TMath::Exp(([1]-x)/[2])+1.)+(1.-[0])/(TMath::Exp(([3]-x)/[2])+1.)", 0., 40.); + std::array, TurnOnHistos::NDDL> params; + for (int ddl = 0; ddl < TurnOnHistos::NDDL; ddl++) { + TH1F hF("fired", "fired", 200, 0., 20.); + TH1F hA("all", "all", 200, 0., 20.); + const std::array& vf = mTurnOnHistos->getTrSpectrum(ddl); + const std::array& va = mTurnOnHistos->getTotSpectrum(ddl); + for (int i = 0; i < 200; i++) { + hF.SetBinContent(i + 1, vf[i]); + hA.SetBinContent(i + 1, va[i]); + } + hF.Sumw2(); + hA.Sumw2(); + + TGraphAsymmErrors* gr = new TGraphAsymmErrors(&hF, &hA); + th->SetParameters(0.9, 3.5, 0.3, 7.5, 0.6); + gr->Fit(th, "Q", "", 2., 20.); + gr->SetName(Form("DDL_%d", ddl)); + gr->SetTitle(Form("DDL %d", ddl)); + //TODO!!! Add TGraph with fit to list of objects to send to QC + double* par = th->GetParameters(); + for (int i = 0; i < 10; i++) { + params[ddl][i] = par[i]; + } + } + std::string_view versionName{"default"}; + mTriggerMap->addTurnOnCurvesParams(versionName, params); + //TODO: calculate bad map + //and fill object + //mTriggerMap->addBad2x2Channel(short cellID) ; +} diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/src/TurnOnHistos.cxx b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/TurnOnHistos.cxx new file mode 100644 index 0000000000000..30b55c5f002d1 --- /dev/null +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/TurnOnHistos.cxx @@ -0,0 +1,27 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "PHOSCalibWorkflow/TurnOnHistos.h" + +using namespace o2::phos; + +void TurnOnHistos::merge(TurnOnHistos& other) +{ + for (int i = NCHANNELS; --i;) { + mGoodMap[i] += other.mGoodMap[i]; + mNoisyMap[i] += other.mNoisyMap[i]; + } + for (int i = NDDL; --i;) { + for (int j = Npt; --j;) { + mTotSp[i][j] += other.mTotSp[i][j]; + mTrSp[i][j] += other.mTrSp[i][j]; + } + } +} diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/src/phos-calib-workflow.cxx b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/phos-calib-workflow.cxx index 1ecb5ddc8df92..b25b6254eaac4 100644 --- a/Detectors/PHOS/calib/PHOSCalibWorkflow/src/phos-calib-workflow.cxx +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/phos-calib-workflow.cxx @@ -10,7 +10,9 @@ #include "PHOSCalibWorkflow/PHOSPedestalCalibDevice.h" #include "PHOSCalibWorkflow/PHOSHGLGRatioCalibDevice.h" -#include "PHOSCalibWorkflow/PHOSCalibCollector.h" +#include "PHOSCalibWorkflow/PHOSEnergyCalibDevice.h" +#include "PHOSCalibWorkflow/PHOSTurnonCalibDevice.h" +#include "PHOSCalibWorkflow/PHOSRunbyrunCalibDevice.h" #include "Framework/DataProcessorSpec.h" using namespace o2::framework; @@ -19,13 +21,18 @@ using namespace o2::framework; void customize(std::vector& workflowOptions) { // option allowing to set parameters - workflowOptions.push_back(ConfigParamSpec{"use-ccdb", o2::framework::VariantType::Bool, false, {"enable access to ccdb phos calibration objects"}}); - workflowOptions.push_back(ConfigParamSpec{"forceupdate", o2::framework::VariantType::Bool, false, {"update ccdb even difference to previous object large"}}); + // which method should be called workflowOptions.push_back(ConfigParamSpec{"pedestals", o2::framework::VariantType::Bool, false, {"do pedestal calculation"}}); workflowOptions.push_back(ConfigParamSpec{"hglgratio", o2::framework::VariantType::Bool, false, {"do HG/LG ratio calculation"}}); - workflowOptions.push_back(ConfigParamSpec{"etree", o2::framework::VariantType::Int, -1, {"collect tree for E calib (0: data scan, 1: iteration, 2: CalibParam calculaion)"}}); + workflowOptions.push_back(ConfigParamSpec{"turnon", o2::framework::VariantType::Bool, false, {"scan trigger turn-on curves"}}); + workflowOptions.push_back(ConfigParamSpec{"runbyrun", o2::framework::VariantType::Bool, false, {"do run by run correction calculation"}}); + workflowOptions.push_back(ConfigParamSpec{"energy", o2::framework::VariantType::Bool, false, {"collect tree for E calib"}}); workflowOptions.push_back(ConfigParamSpec{"badmap", o2::framework::VariantType::Bool, false, {"do bad map calculation"}}); - workflowOptions.push_back(ConfigParamSpec{"path", o2::framework::VariantType::String, "./", {"path to store temp files"}}); + // + workflowOptions.push_back(ConfigParamSpec{"not-use-ccdb", o2::framework::VariantType::Bool, false, {"enable access to ccdb phos calibration objects"}}); + workflowOptions.push_back(ConfigParamSpec{"forceupdate", o2::framework::VariantType::Bool, false, {"update ccdb even difference to previous object large"}}); + workflowOptions.push_back(ConfigParamSpec{"ccdbpath", o2::framework::VariantType::String, "http://ccdb-test.cern.ch:8080", {"CCDB address to get current objects"}}); + workflowOptions.push_back(ConfigParamSpec{"digitspath", o2::framework::VariantType::String, "./CalibDigits.root", {"path and name of file to store calib. digits"}}); } // ------------------------------------------------------------------ @@ -35,13 +42,16 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { WorkflowSpec specs; - auto useCCDB = configcontext.options().get("use-ccdb"); - auto forceUpdate = configcontext.options().get("forceupdate"); auto doPedestals = configcontext.options().get("pedestals"); auto doHgLgRatio = configcontext.options().get("hglgratio"); - auto doEtree = configcontext.options().get("etree"); + auto doTurnOn = configcontext.options().get("turnon"); + auto doRunbyrun = configcontext.options().get("runbyrun"); + auto doEnergy = configcontext.options().get("energy"); auto doBadMap = configcontext.options().get("badmap"); - auto path = configcontext.options().get("path"); + auto useCCDB = !configcontext.options().get("not-use-ccdb"); + auto forceUpdate = configcontext.options().get("forceupdate"); + auto path = configcontext.options().get("ccdbpath"); + auto dpath = configcontext.options().get("digitspath"); if (doPedestals && doHgLgRatio) { LOG(FATAL) << "Can not run pedestal and HG/LG calibration simulteneously"; } @@ -57,14 +67,22 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) specs.emplace_back(o2::phos::getHGLGRatioCalibSpec(useCCDB, forceUpdate, path)); } } + if (doEnergy) { + LOG(INFO) << "Filling tree for energy and time calibration "; + specs.emplace_back(o2::phos::getPHOSEnergyCalibDeviceSpec(useCCDB, path, dpath)); + } + if (doTurnOn) { + LOG(INFO) << "TurnOn curves calculation"; + specs.emplace_back(o2::phos::getPHOSTurnonCalibDeviceSpec(useCCDB, path)); + } + if (doRunbyrun) { + LOG(INFO) << "Run by run correction calculation on "; + specs.emplace_back(o2::phos::getPHOSRunbyrunCalibDeviceSpec(useCCDB, path)); + } if (doBadMap) { LOG(INFO) << "bad map calculation "; short m = 0; // specs.emplace_back(o2::phos::getBadMapCalibSpec(useCCDB,forceUpdate,path,m)); } - if (doEtree >= 0) { - LOG(INFO) << "Filling tree for energy and time calibration "; - specs.emplace_back(o2::phos::getPHOSCalibCollectorDeviceSpec(doEtree)); - } return specs; } diff --git a/Detectors/PHOS/calib/README.md b/Detectors/PHOS/calib/README.md new file mode 100644 index 0000000000000..82285476d6da9 --- /dev/null +++ b/Detectors/PHOS/calib/README.md @@ -0,0 +1,68 @@ + + +# PHOS calibration objects + +The following objects are used for PHOS calibration +## Pedestals +Calculated during dedicate runs with and used for FEE configuration in later physics runs + +## CalibParams +Include channel-by channel gain parameters, High Gain/Low Gain ratio and time offsets for High Gain and Low Gain channels separately. + +## TriggerMap +Object contains trigger bad map and 14 parameterizations of L0 turn-on curves (one for each DDL) + +## Runbyrun +Time-dependent energy scale corrections, one number per module (plus uncertainty of the fitting procedure) + +## BadChannelMap +Bad channels map used in reconstruction and simulation. Caclulated by combining inputs from pedestal, noisy, LED and physics runs and DCS configuration + +# Calibration procedures + +## Pedestal calculation +Dedicated pedestal runs (trigger rate ~10 Hz) and length ~100 s to collect ~1000 events. Analyzed with class PHOSPedestalCalibDevice which uses as input vector of o2::phos::Cell, produced with raw to cell converted with option --pedestal. In this conficuration Cell::Energy contains mean and Cell::Time contains RMS of pedestal. +``` cpp +o2-raw-file-reader-workflow --input-conf PHSraw.cfg | +o2-phos-reco-workflow --input-type raw --output-type cells --disable-root-output --pedestal on | +o2-phos-calib-workflow --pedestals +``` + +# High Gain/Low Gain ratio calculation +Dedicated LED runs (trigger rate ~1000 Hz) and length ~100 s to collect 10^5 events. Analyzed with class PHOSHGLGRatioCalibDevice which uses output of standard reconstruction but wich switched off merging of HG and LG channels: +``` cpp +o2-raw-file-reader-workflow --input-conf PHSraw.cfg | +o2-phos-reco-workflow --input-type raw --output-type cells --disable-root-output --keepHGLG on | +o2-phos-calib-workflow --hglgratio +``` +## Turn-on curve and trigger bad map calculation +Run over physics run, selecting events not marked as PHOS L0 trigger. Performed with classes PHOSTurnonCalibDevice and PHOSTurnonCalibrator. Stores transient object to CCDB if sufficient statistics not collected yet or calculates TriggerMap objects and stores it at CCDB. Uses list of Cells and FullClusters as input. Running on MC digits +``` cpp +o2-phos-reco-workflow --input-type digits --output-type cells --disable-root-output | +o2-phos-reco-workflow --input-type cells --output-type clusters --fullclu-output --disable-root-output --disable-root-input | +o2-phos-calib-workflow --turnon +``` + +## Run-by-run correction +Calculated pi0 peak position in each module in current run (or equivavlt period). Use list of FullClusters as input and produce 8 numbers: peak position and fit uncertainties for each module. Run as +``` cpp +o2-phos-reco-workflow --input-type digits --output-type cells --disable-root-output | +o2-phos-reco-workflow --input-type cells --output-type clusters --fullclu-output --disable-root-output --disable-root-input | +o2-phos-calib-workflow --runbyrun +``` + +## Energy and time calibration +Relative energy scale per channel and time offsets for High Gain and Low Gain channels is calculated with iterative procedure. At the first step physics (better PHOS triggered) data are scanned and list of digits contributed to PHOS clusters are stored in local root files on EPN. digits are packed as std::vector and simutaneously a list of inv. mass and time histograms are filled. Then new calibration coefficients are calculated from collected histograms and list of clusters re-scanned with new calibration. Few (~5) iterations is necessary to reach final accuracy. First scan is ran as +``` cpp +o2-phos-reco-workflow --input-type digits --output-type cells --disable-root-output | +o2-phos-reco-workflow --input-type cells --output-type clusters --fullclu-output --disable-root-output --disable-root-input | +o2-phos-calib-workflow --not-use-ccdb --energy +``` + +## Bad map calculation + + + diff --git a/Detectors/PHOS/calib/include/PHOSCalib/BadChannelMap.h b/Detectors/PHOS/calib/include/PHOSCalib/BadChannelMap.h index 31fa0688f498c..f5e4e216d65b8 100644 --- a/Detectors/PHOS/calib/include/PHOSCalib/BadChannelMap.h +++ b/Detectors/PHOS/calib/include/PHOSCalib/BadChannelMap.h @@ -85,19 +85,10 @@ class BadChannelMap /// \brief Add bad cell to the container /// \param channelID Absolute ID of the bad channel /// \param mask type of the bad channel - /// - /// Adding new bad channel to the container. In case a cell - /// with the same ID is already present in the container, - /// the mask status is updated. Otherwise it is added. - /// - /// Only bad or warm cells are added to the container. In case - /// the mask type is GOOD_CELL, the entry is removed from the - /// container if present before, otherwise the cell is ignored. void addBadChannel(short channelID) { mBadCells.set(channelID - OFFSET); } //set bit to true /// \brief Mark channel as good /// \param channelID Absolute ID of the channel - /// /// Setting channel as good. void setChannelGood(short channelID) { mBadCells.set(channelID - OFFSET, false); } diff --git a/Detectors/PHOS/calib/include/PHOSCalib/CalibParams.h b/Detectors/PHOS/calib/include/PHOSCalib/CalibParams.h index 2be5da09bf003..4b26d1f8a878e 100644 --- a/Detectors/PHOS/calib/include/PHOSCalib/CalibParams.h +++ b/Detectors/PHOS/calib/include/PHOSCalib/CalibParams.h @@ -38,6 +38,8 @@ class CalibParams /// \brief Constructor for tests CalibParams(int test); + CalibParams& operator=(const CalibParams& other) = default; + /// \brief Destructor ~CalibParams() = default; diff --git a/Detectors/PHOS/calib/include/PHOSCalib/Pedestals.h b/Detectors/PHOS/calib/include/PHOSCalib/Pedestals.h index a893f36680c22..0162d1ae60ae7 100644 --- a/Detectors/PHOS/calib/include/PHOSCalib/Pedestals.h +++ b/Detectors/PHOS/calib/include/PHOSCalib/Pedestals.h @@ -83,13 +83,36 @@ class Pedestals /// \return Is successful bool setLGPedestals(TH1* h); + /// \brief Get pedestal RMS + /// \param cellID Absolute ID of cell + /// \return pedestal RMS for the cell + float getHGRMS(short cellID) const { return float(mHGRMS.at(cellID - OFFSET)) / RMSCOMPRESS; } + + /// \brief Set pedestal RMS + /// \param cellID Absolute ID of cell + /// \param c is the pedestal RMS (expected to be in range 0..5, larger values=bad channel=overflow) + void setHGRMS(short cellID, float c) { mHGRMS[cellID - OFFSET] = static_cast(c * RMSCOMPRESS); } + + /// \brief Get pedestal + /// \param cellID Absolute ID of cell + /// \return pedestal RMS for the LG cell + float getLGRMS(short cellID) const { return float(mLGRMS.at(cellID - OFFSET)) / RMSCOMPRESS; } + + /// \brief Set LG pedestal RMS + /// \param cellID Absolute ID of cell + /// \param c is the pedestal RMS (expected to be in range 0..5, larger values=bad channel=overflow) + void setLGRMS(short cellID, float c) { mLGRMS[cellID - OFFSET] = static_cast(c * RMSCOMPRESS); } + private: static constexpr short NCHANNELS = 14337; ///< Number of channels starting from 1 static constexpr short OFFSET = 1793; ///< Non-existing channels 56*64*1.5+1 - std::array mHGPedestals; ///< Container for pedestals - std::array mLGPedestals; ///< Container for pedestals + static constexpr short RMSCOMPRESS = 50; ///< Conversion to store float RMS in range ~[0..5] in uchar + std::array mHGPedestals; ///< Container for HG pedestals + std::array mLGPedestals; ///< Container for LG pedestals + std::array mHGRMS; ///< Container for RMS of HG pedestals + std::array mLGRMS; ///< Container for RMS of LG pedestals - ClassDefNV(Pedestals, 2); + ClassDefNV(Pedestals, 3); }; } // namespace phos diff --git a/Detectors/PHOS/calib/include/PHOSCalib/TriggerMap.h b/Detectors/PHOS/calib/include/PHOSCalib/TriggerMap.h new file mode 100644 index 0000000000000..1d33127901fca --- /dev/null +++ b/Detectors/PHOS/calib/include/PHOSCalib/TriggerMap.h @@ -0,0 +1,111 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \class TRIGGERMAP +/// \brief CCDB container for trigger bad map and turn-on curves +/// \author Dmitri Peresunko, RRC Kurchatov institute +/// \since March 20, 2021 +/// +/// + +#ifndef PHOS_TRIGGERMAP_H +#define PHOS_TRIGGERMAP_H + +#include +#include +#include "TObject.h" + +class TH1; + +namespace o2 +{ + +namespace phos +{ + +class TriggerMap +{ + public: + /// \brief Constructor + TriggerMap() = default; + + /// \brief Constructor for tests + TriggerMap(int test); + + TriggerMap& operator=(const TriggerMap& other) = default; + + /// \brief Destructor + ~TriggerMap() = default; + + /// \brief tests if cell is in active trigger region + /// \param cellID Absolute ID of cell + /// \return true if cell is in active trigger region + bool isGood2x2(short cellID) const { return !mTrigger2x2Map.test(cellID); } + + /// \brief Add bad triger cell to the container + /// \param cellID Absolute ID of the bad channel + void addBad2x2Channel(short cellID) { mTrigger2x2Map.set(cellID); } //set bit to true + + /// \brief Mark trigger channel as good + /// \param cellID Absolute ID of the channel + void set2x2ChannelGood(short cellID) { mTrigger2x2Map.set(cellID, false); } + + /// \brief tests if cell is in active trigger region + /// \param cellID Absolute ID of cell + /// \return true if cell is in active trigger region + bool isGood4x4(short cellID) const { return !mTrigger4x4Map.test(cellID); } + + /// \brief Add bad triger cell to the container + /// \param cellID Absolute ID of the bad channel + void addBad4x4Channel(short cellID) { mTrigger4x4Map.set(cellID); } //set bit to true + + /// \brief Mark trigger channel as good + /// \param cellID Absolute ID of the channel + void set4x4ChannelGood(short cellID) { mTrigger2x2Map.set(cellID, false); } + + void setTurnOnCurvesVestion(int v = 0); + + /// \brief random return true with probability to fire trigger + /// \param a amplitude of trigger tile + /// \param iTRU,ix,iz coordinates of trigger tile + bool isFiredMC2x2(float a, short iTRU, short ix, short iz) const; + + /// \brief random return true with probability to fire trigger + /// \param a amplitude of trigger tile + /// \param iTRU,ix,iz coordinates of trigger tile + bool isFiredMC4x4(float a, short iTRU, short ix, short iz) const; + + bool try2x2(float a, short iTRU) const; + bool try4x4(float a, short iTRU) const; + + void addTurnOnCurvesParams(std::string_view versionName, std::array, 14>& params); + bool selectTurnOnCurvesParams(std::string_view versionName); + + float L0triggerProbability(float e, short ddl) const; + + private: + static constexpr short NCHANNELS = 3136; ///< Number of trigger channels + std::bitset mTrigger2x2Map; ///< Container for bad trigger cells, 1 means bad sell + std::bitset mTrigger4x4Map; ///< Container for bad trigger cells, 1 means bad sell + + short mVersion; //current parameterization of turn-on curves + static constexpr short NDDL = 14; ///< Non-existing channels 56*64*1.5+1 + static constexpr short NMAXPAR = 10; ///< Non-existing channels 56*64*1.5+1 + std::vector mParamDescr; ///< Names of available parameterizations + std::vector, NDDL>> mParamSets; + std::array, NDDL> mCurrentSet; + + ClassDefNV(TriggerMap, 1); +}; + +} // namespace phos + +} // namespace o2 +#endif diff --git a/Detectors/PHOS/calib/src/PHOSCalibLinkDef.h b/Detectors/PHOS/calib/src/PHOSCalibLinkDef.h index 0a21620b2b605..8e432ef20a930 100644 --- a/Detectors/PHOS/calib/src/PHOSCalibLinkDef.h +++ b/Detectors/PHOS/calib/src/PHOSCalibLinkDef.h @@ -14,12 +14,14 @@ #pragma link off all classes; #pragma link off all functions; -#pragma link C++ class o2::phos::CalibDB+; -#pragma link C++ class o2::phos::BadChannelMap+; -#pragma link C++ class o2::TObjectWrapper+; -#pragma link C++ class o2::phos::CalibParams+; -#pragma link C++ class o2::TObjectWrapper+; -#pragma link C++ class o2::phos::Pedestals+; -#pragma link C++ class o2::TObjectWrapper+; +#pragma link C++ class o2::phos::CalibDB + ; +#pragma link C++ class o2::phos::BadChannelMap + ; +#pragma link C++ class o2::TObjectWrapper < o2::phos::BadChannelMap> + ; +#pragma link C++ class o2::phos::CalibParams + ; +#pragma link C++ class o2::TObjectWrapper < o2::phos::CalibParams> + ; +#pragma link C++ class o2::phos::Pedestals + ; +#pragma link C++ class o2::TObjectWrapper < o2::phos::Pedestals> + ; +#pragma link C++ class o2::phos::TriggerMap + ; +#pragma link C++ class o2::TObjectWrapper < o2::phos::TriggerMap> + ; #endif diff --git a/Detectors/PHOS/calib/src/TriggerMap.cxx b/Detectors/PHOS/calib/src/TriggerMap.cxx new file mode 100644 index 0000000000000..905597689a9ff --- /dev/null +++ b/Detectors/PHOS/calib/src/TriggerMap.cxx @@ -0,0 +1,95 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "PHOSBase/Geometry.h" +#include "PHOSCalib/TriggerMap.h" + +#include "FairLogger.h" + +#include +#include + +#include + +using namespace o2::phos; + +TriggerMap::TriggerMap(int param) : mVersion(param) +{ + if (mVersion >= mParamDescr.size()) { + LOG(ERROR) << "impossible parameterization " << mVersion; + LOG(ERROR) << "Available are:"; + for (int i = 0; i < mParamDescr.size(); i++) { + LOG(ERROR) << i << " : " << mParamDescr[i]; + } + return; + } + LOG(INFO) << "Will use parameterization " << mParamDescr[mVersion]; + mCurrentSet = mParamSets[mVersion]; +} + +void TriggerMap::addTurnOnCurvesParams(std::string_view versionName, std::array, 14>& params) +{ + mParamDescr.emplace_back(versionName); + mParamSets.emplace_back(params); +} + +bool TriggerMap::selectTurnOnCurvesParams(std::string_view versionName) +{ + mVersion = 0; + while (mVersion < mParamDescr.size()) { + if (versionName.compare(mParamDescr[mVersion]) == 0.) { + return true; + } + mVersion++; + } + mVersion = 0; + LOG(ERROR) << "Can not fine parameterization " << versionName; + LOG(ERROR) << "Available are:"; + for (int i = 0; i < mParamDescr.size(); i++) { + LOG(ERROR) << i << " : " << mParamDescr[i]; + } + return false; +} + +float TriggerMap::L0triggerProbability(float e, short ddl) const +{ + + if (mCurrentSet.size() == 0) { + LOG(ERROR) << "Parameteriztion not chosen"; + return 0; + } + if (mVersion == 0) { + return mCurrentSet[ddl][0] / (TMath::Exp((mCurrentSet[ddl][1] - e) / mCurrentSet[ddl][2]) + 1.) + + (1. - mCurrentSet[ddl][0]) / (TMath::Exp((mCurrentSet[ddl][3] - e) / mCurrentSet[ddl][4]) + 1.); + } else { + return 0; + } +} +bool TriggerMap::isFiredMC2x2(float a, short iTRU, short ix, short iz) const +{ + char truRelId[3] = {char(iTRU), char(ix), char(iz)}; + short tileId = Geometry::truRelToAbsNumbering(truRelId); + return isGood2x2(tileId) && try2x2(a, iTRU); +} + +bool TriggerMap::isFiredMC4x4(float a, short iTRU, short ix, short iz) const +{ + char truRelId[3] = {char(iTRU), char(ix), char(iz)}; + short tileId = Geometry::truRelToAbsNumbering(truRelId); + return isGood4x4(tileId) && try4x4(a, iTRU); +} +bool TriggerMap::try2x2(float a, short iTRU) const +{ + return gRandom->Uniform() < L0triggerProbability(a, iTRU); +} +bool TriggerMap::try4x4(float a, short iTRU) const +{ + return gRandom->Uniform() < L0triggerProbability(a, iTRU); +} diff --git a/Detectors/PHOS/reconstruction/include/PHOSReconstruction/Clusterer.h b/Detectors/PHOS/reconstruction/include/PHOSReconstruction/Clusterer.h index ba20f91666835..6b16274cb98b7 100644 --- a/Detectors/PHOS/reconstruction/include/PHOSReconstruction/Clusterer.h +++ b/Detectors/PHOS/reconstruction/include/PHOSReconstruction/Clusterer.h @@ -37,15 +37,15 @@ class Clusterer void initialize(); void process(gsl::span digits, gsl::span dtr, const o2::dataformats::MCTruthContainer* dmc, - std::vector* clusters, std::vector* rigRec, + std::vector* clusters, std::vector* fullclusters, std::vector* rigRec, o2::dataformats::MCTruthContainer* cluMC); void processCells(gsl::span digits, gsl::span dtr, const o2::dataformats::MCTruthContainer* dmc, - std::vector* clusters, std::vector* rigRec, + std::vector* clusters, std::vector* fullclusters, std::vector* rigRec, o2::dataformats::MCTruthContainer* cluMC); void makeClusters(gsl::span digits); - void evalCluProperties(gsl::span digits, std::vector* clusters, + void evalCluProperties(gsl::span digits, std::vector* clusters, std::vector* fullclusters, const o2::dataformats::MCTruthContainer* dmc, o2::dataformats::MCTruthContainer* cluMC); @@ -54,6 +54,8 @@ class Clusterer void makeUnfoldings(gsl::span digits); // Find and unfold clusters with few local maxima void unfoldOneCluster(FullCluster& iniClu, char nMax, gsl::span digitId, gsl::span digits); + void setFullOutput(bool useFullClusters = true) { mFullCluOutput = useFullClusters; } + protected: void convertCellsToDigits(gsl::span cells, int firstCellInEvent, int lastCellInEvent); @@ -75,6 +77,7 @@ class Clusterer protected: bool mProcessMC = false; int miCellLabel = 0; + bool mFullCluOutput = false; ///< Write output full of reduced (no contributed digits) clusters Geometry* mPHOSGeom = nullptr; ///< PHOS geometry std::unique_ptr mCalibParams; ///! Calibration coefficients std::unique_ptr mBadMap; ///! Bad map diff --git a/Detectors/PHOS/reconstruction/include/PHOSReconstruction/FullCluster.h b/Detectors/PHOS/reconstruction/include/PHOSReconstruction/FullCluster.h index 75dfc56f96e7a..6c463fce06891 100644 --- a/Detectors/PHOS/reconstruction/include/PHOSReconstruction/FullCluster.h +++ b/Detectors/PHOS/reconstruction/include/PHOSReconstruction/FullCluster.h @@ -46,6 +46,8 @@ class FullCluster : public Cluster FullCluster() = default; FullCluster(short digitAbsId, float energy, float time, int label, float scale); + FullCluster(const FullCluster& clu) = default; + ~FullCluster() = default; /// \brief Method to add digit to a cluster diff --git a/Detectors/PHOS/reconstruction/src/Clusterer.cxx b/Detectors/PHOS/reconstruction/src/Clusterer.cxx index 24458b3fc359e..861467e374bf5 100644 --- a/Detectors/PHOS/reconstruction/src/Clusterer.cxx +++ b/Detectors/PHOS/reconstruction/src/Clusterer.cxx @@ -38,10 +38,14 @@ void Clusterer::initialize() //____________________________________________________________________________ void Clusterer::process(gsl::span digits, gsl::span dtr, const o2::dataformats::MCTruthContainer* dmc, - std::vector* clusters, std::vector* trigRec, + std::vector* clusters, std::vector* fullclusters, std::vector* trigRec, o2::dataformats::MCTruthContainer* cluMC) { - clusters->clear(); //final out list of clusters + if (mFullCluOutput) { + fullclusters->clear(); //final out list of clusters + } else { + clusters->clear(); //final out list of clusters + } trigRec->clear(); cluMC->clear(); mProcessMC = (dmc != nullptr); @@ -49,7 +53,13 @@ void Clusterer::process(gsl::span digits, gsl::spansize(); + int indexStart; + if (mFullCluOutput) { + indexStart = fullclusters->size(); //final out list of clusters + } else { + indexStart = clusters->size(); //final out list of clusters + } + mClusters.clear(); // internal list of FullClusters LOG(DEBUG) << "Starting clusteriztion digits from " << mFirstDigitInEvent << " to " << mLastDigitInEvent; @@ -86,21 +96,28 @@ void Clusterer::process(gsl::span digits, gsl::spansize(); - - trigRec->emplace_back(tr.getBCData(), indexStart, clusters->size() - indexStart); + evalCluProperties(digits, clusters, fullclusters, dmc, cluMC); + if (mFullCluOutput) { + LOG(DEBUG) << "Found clusters from " << indexStart << " to " << fullclusters->size(); + trigRec->emplace_back(tr.getBCData(), indexStart, fullclusters->size() - indexStart); + } else { + LOG(DEBUG) << "Found clusters from " << indexStart << " to " << clusters->size(); + trigRec->emplace_back(tr.getBCData(), indexStart, clusters->size() - indexStart); + } } } //____________________________________________________________________________ void Clusterer::processCells(gsl::span cells, gsl::span ctr, const o2::dataformats::MCTruthContainer* dmc, - std::vector* clusters, std::vector* trigRec, + std::vector* clusters, std::vector* fullclusters, std::vector* trigRec, o2::dataformats::MCTruthContainer* cluMC) { // Transform input Cells to digits and run standard recontruction - clusters->clear(); //final out list of clusters + if (mFullCluOutput) { + fullclusters->clear(); //final out list of clusters + } else { + clusters->clear(); //final out list of clusters + } trigRec->clear(); cluMC->clear(); mProcessMC = (dmc != nullptr); @@ -108,7 +125,12 @@ void Clusterer::processCells(gsl::span cells, gsl::spansize(); + int indexStart; + if (mFullCluOutput) { + indexStart = fullclusters->size(); //final out list of clusters + } else { + indexStart = clusters->size(); //final out list of clusters + } mClusters.clear(); // internal list of FullClusters LOG(DEBUG) << "Starting clusteriztion cells from " << mFirstDigitInEvent << " to " << mLastDigitInEvent; @@ -144,11 +166,15 @@ void Clusterer::processCells(gsl::span cells, gsl::spansize(); + evalCluProperties(mDigits, clusters, fullclusters, dmc, cluMC); - trigRec->emplace_back(tr.getBCData(), indexStart, clusters->size() - indexStart); + if (mFullCluOutput) { + LOG(DEBUG) << "Found clusters from " << indexStart << " to " << fullclusters->size(); + trigRec->emplace_back(tr.getBCData(), indexStart, fullclusters->size() - indexStart); + } else { + LOG(DEBUG) << "Found clusters from " << indexStart << " to " << clusters->size(); + trigRec->emplace_back(tr.getBCData(), indexStart, clusters->size() - indexStart); + } } } //____________________________________________________________________________ @@ -161,9 +187,13 @@ void Clusterer::convertCellsToDigits(gsl::span cells, int firstCellI } for (int i = firstCellInEvent; i < lastCellInEvent; i++) { const Cell c = cells[i]; - //short cell, float amplitude, float time, int label - mDigits.emplace_back(c.getAbsId(), c.getEnergy(), c.getTime(), i); - mDigits.back().setHighGain(c.getHighGain()); + if (c.getTRU()) { //TRU digit + mDigits.emplace_back(c.getTRUId(), c.getEnergy(), c.getTime(), c.getHighGain(), -1); + } else { + //short cell, float amplitude, float time, int label + mDigits.emplace_back(c.getAbsId(), c.getEnergy(), c.getTime(), i); + mDigits.back().setHighGain(c.getHighGain()); + } } mFirstDigitInEvent = 0; mLastDigitInEvent = mDigits.size(); @@ -186,6 +216,9 @@ void Clusterer::makeClusters(gsl::span digits) } const Digit& digitSeed = digits[i]; + if (digitSeed.isTRU()) { + continue; + } float digitSeedEnergy = calibrate(digitSeed.getAmplitude(), digitSeed.getAbsId()); if (isBadChannel(digitSeed.getAbsId())) { digitSeedEnergy = 0.; @@ -219,6 +252,9 @@ void Clusterer::makeClusters(gsl::span digits) continue; // look through remaining digits } const Digit* digitN = &(digits[j]); + if (digitN->isTRU()) { + continue; + } float digitNEnergy = calibrate(digitN->getAmplitude(), digitN->getAbsId()); if (isBadChannel(digitN->getAbsId())) { //remove digit digitNEnergy = 0.; @@ -416,13 +452,19 @@ void Clusterer::unfoldOneCluster(FullCluster& iniClu, char nMax, gsl::span } //____________________________________________________________________________ -void Clusterer::evalCluProperties(gsl::span digits, std::vector* clusters, +void Clusterer::evalCluProperties(gsl::span digits, std::vector* clusters, std::vector* fullclusters, const o2::dataformats::MCTruthContainer* dmc, o2::dataformats::MCTruthContainer* cluMC) { - if (clusters->capacity() - clusters->size() < mClusters.size()) { //avoid expanding vector per element - clusters->reserve(clusters->size() + mClusters.size()); + if (mFullCluOutput) { + if (fullclusters->capacity() - fullclusters->size() < mClusters.size()) { //avoid expanding vector per element + fullclusters->reserve(fullclusters->size() + mClusters.size()); + } + } else { + if (clusters->capacity() - clusters->size() < mClusters.size()) { //avoid expanding vector per element + clusters->reserve(clusters->size() + mClusters.size()); + } } int labelIndex = 0; @@ -444,7 +486,11 @@ void Clusterer::evalCluProperties(gsl::span digits, std::vectorevalAll(); if (clu->getEnergy() > 1.e-4) { //Non-empty cluster - clusters->emplace_back(*clu); + if (mFullCluOutput) { + fullclusters->emplace_back(*clu); + } else { + clusters->emplace_back(*clu); + } if (mProcessMC) { //Handle labels //Calculate list of primaries diff --git a/Detectors/PHOS/simulation/include/PHOSSimulation/Digitizer.h b/Detectors/PHOS/simulation/include/PHOSSimulation/Digitizer.h index fef416c3d5d54..681bd03803c94 100644 --- a/Detectors/PHOS/simulation/include/PHOSSimulation/Digitizer.h +++ b/Detectors/PHOS/simulation/include/PHOSSimulation/Digitizer.h @@ -14,6 +14,7 @@ #include "DataFormatsPHOS/Digit.h" #include "PHOSBase/Geometry.h" #include "PHOSCalib/CalibParams.h" +#include "PHOSCalib/TriggerMap.h" #include "PHOSBase/Hit.h" #include "DataFormatsPHOS/MCLabel.h" #include "SimulationDataFormat/MCTruthContainer.h" @@ -51,7 +52,10 @@ class Digitizer : public TObject static constexpr short NCHANNELS = 12544; ///< Number of channels starting from 56*64*(4-0.5) static constexpr short OFFSET = 1793; ///< Non-existing channels 56*64*0.5+1 bool mProcessMC = true; + bool mTrig2x2 = true; ///< simulate 2x2 PHOS trigger + bool mTrig4x4 = false; ///< simulate 4x4 PHOS trigger std::unique_ptr mCalibParams; /// Calibration coefficients + std::unique_ptr mTrigUtils; /// trigger bad map and turn-on curves std::array mArrayD; ClassDefOverride(Digitizer, 4); diff --git a/Detectors/PHOS/simulation/include/PHOSSimulation/RawWriter.h b/Detectors/PHOS/simulation/include/PHOSSimulation/RawWriter.h index 2ed3a643599c9..9474c64ddb5a7 100644 --- a/Detectors/PHOS/simulation/include/PHOSSimulation/RawWriter.h +++ b/Detectors/PHOS/simulation/include/PHOSSimulation/RawWriter.h @@ -75,6 +75,7 @@ class RawWriter std::vector& trailer, std::vector& header) const; protected: + void createTRUBunches(short truId, const std::vector& channelDigits, std::vector& bunchs); void createRawBunches(short absId, const std::vector& digits, std::vector& bunchHG, std::vector& bunchLG, bool& isLGFilled); @@ -92,6 +93,7 @@ class RawWriter std::unique_ptr mCalibParams; ///< PHOS calibration gsl::span mDigits; ///< Digits input vector - must be in digitized format including the time response std::vector mSRUdata; ///< Internal helper of digits assigned to SRUs + std::vector mTRUdata; ///< Internal helper of digits assigned to TRUs std::unique_ptr mRawWriter; ///< Raw writer ClassDefNV(RawWriter, 1); diff --git a/Detectors/PHOS/simulation/src/Digitizer.cxx b/Detectors/PHOS/simulation/src/Digitizer.cxx index 65bb360c0fe08..feaa3db3e49c3 100644 --- a/Detectors/PHOS/simulation/src/Digitizer.cxx +++ b/Detectors/PHOS/simulation/src/Digitizer.cxx @@ -42,6 +42,14 @@ void Digitizer::init() // } } } + if (!mTrigUtils) { + if (o2::phos::PHOSSimParams::Instance().mCCDBPath.compare("localtest") == 0) { + mTrigUtils.reset(new TriggerMap(0)); // test default calibration + LOG(INFO) << "[PHOSDigitizer] No reading trigger map from ccdb requested, set default"; + } else { + LOG(ERROR) << "[PHOSDigitizer] can not get trigger map object from ccdb yet"; + } + } } //_______________________________________________________________________ @@ -145,6 +153,90 @@ void Digitizer::processHits(const std::vector* hits, const std::vectorisGood2x2(tileId)) { + continue; + } + char relId[3]; + Geometry::truRelId2RelId(truRelId, relId); + short i1, i2, i3, i4; + Geometry::relToAbsNumbering(relId, i1); + relId[1] = relId[1] + 1; + Geometry::relToAbsNumbering(relId, i2); + relId[2] = relId[2] + 1; + Geometry::relToAbsNumbering(relId, i4); + relId[1] = relId[1] - 1; + Geometry::relToAbsNumbering(relId, i3); + sum2x2[ix][iz] = mArrayD[i1 - OFFSET].getAmplitude() + mArrayD[i2 - OFFSET].getAmplitude() + + mArrayD[i3 - OFFSET].getAmplitude() + mArrayD[i4 - OFFSET].getAmplitude(); + float ampMax = mArrayD[i1 - OFFSET].getAmplitude(); + tt = mArrayD[i1 - OFFSET].getTime(); + if (mArrayD[i2 - OFFSET].getAmplitude() > ampMax) { + ampMax = mArrayD[i2 - OFFSET].getAmplitude(); + tt = mArrayD[i2 - OFFSET].getTime(); + } + if (mArrayD[i3 - OFFSET].getAmplitude() > ampMax) { + ampMax = mArrayD[i3 - OFFSET].getAmplitude(); + tt = mArrayD[i3 - OFFSET].getTime(); + } + if (mArrayD[i4 - OFFSET].getAmplitude() > ampMax) { + tt = mArrayD[i4 - OFFSET].getTime(); + } + time2x2[ix][iz] = tt; + if (mTrig2x2) { + if (sum2x2[ix][iz] > PHOSSimParams::Instance().mTrig2x2MinThreshold) { //do not test (slow) probability function with soft tiles + mL0Fired |= mTrigUtils->isFiredMC2x2(sum2x2[ix][iz], iTRU, short(ix), short(iz)); + //add TRU digit. Note that only tiles with E>mTrigMinThreshold added! + digitsOut.emplace_back(tileId, sum2x2[ix][iz], tt, true, -1); + } + } + } + } + + if (mTrig4x4) { + for (char ix = 0; ix < nxTRU - 1; ix++) { + for (char iz = 0; iz < nzTRU - 1; iz++) { + char truRelId[3] = {iTRU, ix, iz}; + short tileId = Geometry::truRelToAbsNumbering(truRelId); + if (!mTrigUtils->isGood4x4(tileId)) { + continue; + } + float sum4x4 = sum2x2[ix][iz] + sum2x2[ix][iz + 1] + sum2x2[ix + 1][iz] + sum2x2[ix + 1][iz + 1]; + if (sum4x4 > PHOSSimParams::Instance().mTrig4x4MinThreshold) { //do not test (slow) probability function with soft tiles + mL0Fired |= mTrigUtils->isFiredMC4x4(sum4x4, iTRU, short(ix), short(iz)); + //Add TRU digit short cell, float amplitude, float time, int label + tt = time2x2[ix][iz]; + float ampMax = sum2x2[ix][iz]; + if (sum2x2[ix][iz + 1] > ampMax) { + ampMax = sum2x2[ix][iz + 1]; + tt = sum2x2[ix][iz + 1]; + } + if (sum2x2[ix + 1][iz] > ampMax) { + ampMax = sum2x2[ix + 1][iz]; + tt = sum2x2[ix + 1][iz]; + } + if (sum2x2[ix + 1][iz + 1] > ampMax) { + tt = sum2x2[ix][iz + 1]; + } + digitsOut.emplace_back(tileId, sum4x4, tt, false, -1); + } + } + } + } + } + for (int i = 0; i < NCHANNELS; i++) { if (mArrayD[i].getAmplitude() > PHOSSimParams::Instance().mZSthreshold) { digitsOut.push_back(mArrayD[i]); diff --git a/Detectors/PHOS/simulation/src/RawWriter.cxx b/Detectors/PHOS/simulation/src/RawWriter.cxx index f31c0832b2fdb..1dadda93942bd 100644 --- a/Detectors/PHOS/simulation/src/RawWriter.cxx +++ b/Detectors/PHOS/simulation/src/RawWriter.cxx @@ -51,11 +51,15 @@ void RawWriter::init() mRawWriter->registerLink(iddl, crorc, link, 0, rawfilename.data()); } - // initialize containers for SRU + // initialize containers for SRU and TRU for (auto isru = 0; isru < o2::phos::Mapping::NDDL; isru++) { SRUDigitContainer srucont; srucont.mSRUid = isru; mSRUdata.push_back(srucont); + + SRUDigitContainer trucont; + trucont.mSRUid = isru; + mTRUdata.push_back(trucont); } } @@ -94,41 +98,153 @@ bool RawWriter::processTrigger(const gsl::span digitsbranch, co srucont->mChannels.clear(); srucont++; } - std::vector* digitsList; + auto trucont = mTRUdata.begin(); + while (trucont != mTRUdata.end()) { + trucont->mChannels.clear(); + trucont++; + } for (auto& dig : gsl::span(digitsbranch.data() + trg.getFirstEntry(), trg.getNumberOfObjects())) { - short absId = dig.getAbsId(); - short ddl, hwAddrHG; - //get ddl and High Gain hw addresses - if (mMapping->absIdTohw(absId, 0, ddl, hwAddrHG) != o2::phos::Mapping::kOK) { - LOG(ERROR) << "Wrong AbsId" << absId; - } - - //Collect possible several digits (signal+pileup) into one map record - auto celldata = mSRUdata[ddl].mChannels.find(absId); - if (celldata == mSRUdata[ddl].mChannels.end()) { - const auto it = mSRUdata[ddl].mChannels.insert(celldata, {absId, std::vector()}); - it->second.push_back(&dig); + if (dig.isTRU()) { + short absId = dig.getTRUId(); + short ddl, hwAddr; + //get ddl and High Gain hw addresses + if (mMapping->absIdTohw(absId, Mapping::kTRU, ddl, hwAddr) != o2::phos::Mapping::kOK) { + LOG(ERROR) << "Wrong truId" << absId; + } + //Collect possible several digits (signal+pileup) into one map record + auto celldata = mTRUdata[ddl].mChannels.find(absId); + if (celldata == mTRUdata[ddl].mChannels.end()) { + const auto it = mTRUdata[ddl].mChannels.insert(celldata, {absId, std::vector()}); + it->second.push_back(&dig); + } else { + celldata->second.push_back(&dig); + } } else { - celldata->second.push_back(&dig); + short absId = dig.getAbsId(); + short ddl, hwAddr; + //get ddl and High Gain hw addresses + if (mMapping->absIdTohw(absId, Mapping::kHighGain, ddl, hwAddr) != o2::phos::Mapping::kOK) { + LOG(ERROR) << "Wrong AbsId" << absId; + } + + //Collect possible several digits (signal+pileup) into one map record + auto celldata = mSRUdata[ddl].mChannels.find(absId); + if (celldata == mSRUdata[ddl].mChannels.end()) { + const auto it = mSRUdata[ddl].mChannels.insert(celldata, {absId, std::vector()}); + it->second.push_back(&dig); + } else { + celldata->second.push_back(&dig); + } } } // Create and fill DMA pages for each channel std::vector rawbunches; std::vector payload; - std::vector rawbunchesHG, rawbunchesLG; + std::vector rawbunchesTRU, rawbunchesHG, rawbunchesLG; - for (srucont = mSRUdata.begin(); srucont != mSRUdata.end(); srucont++) { - short ddl = srucont->mSRUid; + for (short ddl = 0; ddl < o2::phos::Mapping::NDDL; ddl++) { payload.clear(); + //Create trigger + //Trigger mask + short trmask[2 * Mapping::NTRUBranchReadoutChannels] = {0}; //Time bin in which trigger was fired. + for (auto ch = mTRUdata[ddl].mChannels.cbegin(); ch != mTRUdata[ddl].mChannels.cend(); ch++) { + short truId = ch->first; + short hwAddr, iddl; //High gain always filled + if ((mMapping->absIdTohw(truId, Mapping::kTRU, iddl, hwAddr) != o2::phos::Mapping::kOK) || iddl != ddl) { + LOG(ERROR) << "Wrong truId" << truId << "iDDL=" << iddl << "!=" << ddl; + } + rawbunchesTRU.clear(); + createTRUBunches(truId, ch->second, rawbunchesTRU); + rawbunches.clear(); + for (auto& bunch : rawbunchesTRU) { + rawbunches.push_back(bunch.mADCs.size() + 2); + rawbunches.push_back(bunch.mStarttime); + for (auto adc : bunch.mADCs) { + rawbunches.push_back(adc); + } + trmask[truId % (2 * Mapping::NTRUBranchReadoutChannels)] = bunch.mStarttime + 1; //need last tile (inverse time order) + } + if (rawbunches.size() == 0) { + continue; + } + auto encodedbunches = encodeBunchData(rawbunches); + ChannelHeader chanhead = {0}; + chanhead.mHardwareAddress = hwAddr; + chanhead.mPayloadSize = rawbunches.size(); + chanhead.mMark = 1; //mark channel header + char* chanheadwords = reinterpret_cast(&chanhead.mDataWord); + for (int iword = 0; iword < sizeof(ChannelHeader) / sizeof(char); iword++) { + payload.emplace_back(chanheadwords[iword]); + } + + char* channelwords = reinterpret_cast(encodedbunches.data()); + for (auto iword = 0; iword < encodedbunches.size() * sizeof(int) / sizeof(char); iword++) { + payload.emplace_back(channelwords[iword]); + } + } + if (mTRUdata[ddl].mChannels.size()) { // if there are TRU digits, fill trigger flags + short chan = 0; + std::vector a; + for (short chan = 0; chan < Mapping::NTRUBranchReadoutChannels; chan++) { + if (trmask[chan] > 0) { + while (a.size() < trmask[chan]) { + a.push_back(0); + } + a[trmask[chan] - 1] |= (1 << (chan % 10)); //Fill mask for a given channel + } + if (chan % 10 == 9 || chan + 1 == Mapping::NTRUBranchReadoutChannels) { + auto encodedbunches = encodeBunchData(a); + ChannelHeader chanhead = {0}; + chanhead.mHardwareAddress = 112 + chan / 10; + chanhead.mPayloadSize = a.size(); + chanhead.mMark = 1; //mark channel header + char* chanheadwords = reinterpret_cast(&chanhead.mDataWord); + for (int iword = 0; iword < sizeof(ChannelHeader) / sizeof(char); iword++) { + payload.emplace_back(chanheadwords[iword]); + } + char* channelwords = reinterpret_cast(encodedbunches.data()); + for (auto iword = 0; iword < encodedbunches.size() * sizeof(int) / sizeof(char); iword++) { + payload.emplace_back(channelwords[iword]); + } + a.clear(); + } + } + //second branch + for (short i = 0; i < Mapping::NTRUBranchReadoutChannels; i++) { + short chan = i + Mapping::NTRUBranchReadoutChannels; + if (trmask[chan] > 0) { + while (a.size() < trmask[chan]) { + a.push_back(0); + } + a[trmask[chan] - 1] |= (1 << (i % 10)); //Fill mask for a given channel + } + if (i % 10 == 9 || i + 1 == Mapping::NTRUBranchReadoutChannels) { + auto encodedbunches = encodeBunchData(a); + ChannelHeader chanhead = {0}; + chanhead.mHardwareAddress = 2048 + 112 + i / 10; + chanhead.mPayloadSize = a.size(); + chanhead.mMark = 1; //mark channel header + char* chanheadwords = reinterpret_cast(&chanhead.mDataWord); + for (int iword = 0; iword < sizeof(ChannelHeader) / sizeof(char); iword++) { + payload.emplace_back(chanheadwords[iword]); + } + char* channelwords = reinterpret_cast(encodedbunches.data()); + for (auto iword = 0; iword < encodedbunches.size() * sizeof(int) / sizeof(char); iword++) { + payload.emplace_back(channelwords[iword]); + } + a.clear(); + } + } + } - for (auto ch = srucont->mChannels.cbegin(); ch != srucont->mChannels.cend(); ch++) { + for (auto ch = mSRUdata[ddl].mChannels.cbegin(); ch != mSRUdata[ddl].mChannels.cend(); ch++) { // Find out hardware address of the channel bool isLGfilled = 0; createRawBunches(ch->first, ch->second, rawbunchesHG, rawbunchesLG, isLGfilled); short hwAddrHG; //High gain always filled - if (mMapping->absIdTohw(ch->first, 0, ddl, hwAddrHG) != o2::phos::Mapping::kOK) { + if (mMapping->absIdTohw(ch->first, Mapping::kHighGain, ddl, hwAddrHG) != o2::phos::Mapping::kOK) { LOG(ERROR) << "Wrong AbsId" << ch->first; } rawbunches.clear(); @@ -204,6 +320,38 @@ bool RawWriter::processTrigger(const gsl::span digitsbranch, co } return true; } +void RawWriter::createTRUBunches(short truId, const std::vector& channelDigits, + std::vector& bunchs) +{ + + AltroBunch currentBunch; + std::vector samples; + float maxAmp = 0; + for (auto dig : channelDigits) { + float ampADC = dig->getAmplitude(); // Digits amplitude already in ADC channels + short time = short(dig->getTime() / 25.); // digit time in nc, convert to bunch crossings (25ns), max readout time 3 mks + if (time > 120) { + time = 120; + } + if (time < 0) { + time = 0; + } + if (maxAmp < ampADC) { + currentBunch.mStarttime = time; + maxAmp = ampADC; + } + while (samples.size() <= time) { + samples.push_back(0); + } + samples[time] = ampADC; + } + + //Note reverse time order + for (int i = samples.size(); i--;) { + currentBunch.mADCs.emplace_back(samples[i]); + } + bunchs.push_back(currentBunch); +} void RawWriter::createRawBunches(short absId, const std::vector& channelDigits, std::vector& bunchHG, std::vector& bunchLG, bool& isLGFilled) diff --git a/Detectors/PHOS/workflow/include/PHOSWorkflow/ClusterizerSpec.h b/Detectors/PHOS/workflow/include/PHOSWorkflow/ClusterizerSpec.h index 1268511c9c6e5..3b67518afc0f9 100644 --- a/Detectors/PHOS/workflow/include/PHOSWorkflow/ClusterizerSpec.h +++ b/Detectors/PHOS/workflow/include/PHOSWorkflow/ClusterizerSpec.h @@ -39,7 +39,7 @@ class ClusterizerSpec : public framework::Task { public: /// \brief Constructor - ClusterizerSpec(bool propagateMC, bool scanDigits) : framework::Task(), mPropagateMC(propagateMC), mUseDigits(scanDigits) {} + ClusterizerSpec(bool propagateMC, bool scanDigits, bool outputFullClu) : framework::Task(), mPropagateMC(propagateMC), mUseDigits(scanDigits), mFullCluOutput(outputFullClu) {} /// \brief Destructor ~ClusterizerSpec() override = default; @@ -57,10 +57,12 @@ class ClusterizerSpec : public framework::Task void run(framework::ProcessingContext& ctx) final; private: - bool mPropagateMC = false; ///< Switch whether to process MC true labels - bool mUseDigits = false; + bool mPropagateMC = false; ///< Switch whether to process MC true labels + bool mUseDigits = false; ///< Make clusters from digits or cells + bool mFullCluOutput = false; ///< Write full of reduced (no contributed digits) clusters o2::phos::Clusterer mClusterizer; ///< Clusterizer object std::vector mOutputClusters; + std::vector mOutputFullClusters; std::vector mOutputClusterTrigRecs; o2::dataformats::MCTruthContainer mOutputTruthCont; }; @@ -68,8 +70,8 @@ class ClusterizerSpec : public framework::Task /// \brief Creating DataProcessorSpec for the PHOS Clusterizer Spec /// /// Refer to ClusterizerSpec::run for input and output specs -framework::DataProcessorSpec getClusterizerSpec(bool propagateMC); -framework::DataProcessorSpec getCellClusterizerSpec(bool propagateMC); +framework::DataProcessorSpec getClusterizerSpec(bool propagateMC, bool fillFullClu); +framework::DataProcessorSpec getCellClusterizerSpec(bool propagateMC, bool fillFullClu); } // namespace reco_workflow diff --git a/Detectors/PHOS/workflow/include/PHOSWorkflow/RawToCellConverterSpec.h b/Detectors/PHOS/workflow/include/PHOSWorkflow/RawToCellConverterSpec.h index 9244c4fd339ca..6246c89144f51 100644 --- a/Detectors/PHOS/workflow/include/PHOSWorkflow/RawToCellConverterSpec.h +++ b/Detectors/PHOS/workflow/include/PHOSWorkflow/RawToCellConverterSpec.h @@ -60,6 +60,8 @@ class RawToCellConverterSpec : public framework::Task protected: /// \brief simple check of HW address char CheckHWAddress(short ddl, short hwAddress, short& fee); + void readTRUDigit(const std::vector& bunchlist, short absId, short timebin, std::shared_ptr>& currentTRUContainer); + void readTRUFlags(short hwAddress, const std::vector& bunchlist, std::shared_ptr>& currentTRUFlags); private: bool mFillChi2 = false; ///< Fill output with quality of samples diff --git a/Detectors/PHOS/workflow/include/PHOSWorkflow/RecoWorkflow.h b/Detectors/PHOS/workflow/include/PHOSWorkflow/RecoWorkflow.h index 8e94cad70672e..76c833cc88336 100644 --- a/Detectors/PHOS/workflow/include/PHOSWorkflow/RecoWorkflow.h +++ b/Detectors/PHOS/workflow/include/PHOSWorkflow/RecoWorkflow.h @@ -41,9 +41,9 @@ enum struct OutputType { Digits, framework::WorkflowSpec getWorkflow(bool disableRootInp, bool disableRootOut, bool propagateMC = true, - std::string const& cfgInput = "hits", // - std::string const& cfgOutput = "clusters" // -); + std::string const& cfgInput = "hits", // + std::string const& cfgOutput = "clusters", // + bool fullCluOut = false); } // namespace reco_workflow } // namespace phos diff --git a/Detectors/PHOS/workflow/src/CellConverterSpec.cxx b/Detectors/PHOS/workflow/src/CellConverterSpec.cxx index 45426fef5c4f3..57b84837c7d8b 100644 --- a/Detectors/PHOS/workflow/src/CellConverterSpec.cxx +++ b/Detectors/PHOS/workflow/src/CellConverterSpec.cxx @@ -84,33 +84,38 @@ void CellConverterSpec::run(framework::ProcessingContext& ctx) for (int i = iFirstDigit; i < iLastDigit; i++) { const auto& dig = digits.at(i); - //apply filter - if (!mBadMap->isChannelGood(dig.getAbsId())) { - continue; - } - - ChannelType_t chantype; - if (dig.isHighGain()) { - chantype = ChannelType_t::HIGH_GAIN; + if (dig.isTRU()) { + ChannelType_t chantype; + if (dig.isHighGain()) { + chantype = ChannelType_t::TRU2x2; + } else { + chantype = ChannelType_t::TRU4x4; + } + mOutputCells.emplace_back(dig.getAbsId(), dig.getAmplitude(), dig.getTime(), chantype); } else { - chantype = ChannelType_t::LOW_GAIN; - } - - // TODO!!! TRU copying... - // if (dig.getTRU()) - // chantype = ChannelType_t::TRU; + //apply filter + if (!mBadMap->isChannelGood(dig.getAbsId())) { + continue; + } - mOutputCells.emplace_back(dig.getAbsId(), dig.getAmplitude(), dig.getTime(), chantype); - if (mPropagateMC) { //copy MC info, - int iLab = dig.getLabel(); - if (iLab > -1) { - mOutputTruthCont.addElements(icell, truthcont->getLabels(iLab)); + ChannelType_t chantype; + if (dig.isHighGain()) { + chantype = ChannelType_t::HIGH_GAIN; } else { - MCLabel label(0, 0, 0, true, 0); - label.setNoise(); - mOutputTruthCont.addElement(icell, label); + chantype = ChannelType_t::LOW_GAIN; + } + mOutputCells.emplace_back(dig.getAbsId(), dig.getAmplitude(), dig.getTime(), chantype); + if (mPropagateMC) { //copy MC info, + int iLab = dig.getLabel(); + if (iLab > -1) { + mOutputTruthCont.addElements(icell, truthcont->getLabels(iLab)); + } else { + MCLabel label(0, 0, 0, true, 0); + label.setNoise(); + mOutputTruthCont.addElement(icell, label); + } + icell++; } - icell++; } } mOutputCellTrigRecs.emplace_back(tr.getBCData(), indexStart, mOutputCells.size() - indexStart); diff --git a/Detectors/PHOS/workflow/src/ClusterizerSpec.cxx b/Detectors/PHOS/workflow/src/ClusterizerSpec.cxx index de4e715c42b82..3bc4d1dc66852 100644 --- a/Detectors/PHOS/workflow/src/ClusterizerSpec.cxx +++ b/Detectors/PHOS/workflow/src/ClusterizerSpec.cxx @@ -23,6 +23,7 @@ void ClusterizerSpec::init(framework::InitContext& ctx) // Initialize clusterizer and link geometry mClusterizer.initialize(); + mClusterizer.setFullOutput(mFullCluOutput); } void ClusterizerSpec::run(framework::ProcessingContext& ctx) @@ -45,9 +46,9 @@ void ClusterizerSpec::run(framework::ProcessingContext& ctx) // const o2::dataformats::MCTruthContainer* truthcont=nullptr; if (mPropagateMC) { std::unique_ptr> truthcont(ctx.inputs().get*>("digitsmctr")); - mClusterizer.process(digits, digitsTR, truthcont.get(), &mOutputClusters, &mOutputClusterTrigRecs, &mOutputTruthCont); // Find clusters on digits (pass by ref) + mClusterizer.process(digits, digitsTR, truthcont.get(), &mOutputClusters, &mOutputFullClusters, &mOutputClusterTrigRecs, &mOutputTruthCont); // Find clusters on digits (pass by ref) } else { - mClusterizer.process(digits, digitsTR, nullptr, &mOutputClusters, &mOutputClusterTrigRecs, &mOutputTruthCont); // Find clusters on digits (pass by ref) + mClusterizer.process(digits, digitsTR, nullptr, &mOutputClusters, &mOutputFullClusters, &mOutputClusterTrigRecs, &mOutputTruthCont); // Find clusters on digits (pass by ref) } } else { @@ -61,9 +62,9 @@ void ClusterizerSpec::run(framework::ProcessingContext& ctx) if (mPropagateMC) { std::unique_ptr> truthcont(ctx.inputs().get*>("cellsmctr")); // truthmap = ctx.inputs().get>("cellssmcmap"); - mClusterizer.processCells(cells, cellsTR, truthcont.get(), &mOutputClusters, &mOutputClusterTrigRecs, &mOutputTruthCont); // Find clusters on digits (pass by ref) + mClusterizer.processCells(cells, cellsTR, truthcont.get(), &mOutputClusters, &mOutputFullClusters, &mOutputClusterTrigRecs, &mOutputTruthCont); // Find clusters on digits (pass by ref) } else { - mClusterizer.processCells(cells, cellsTR, nullptr, &mOutputClusters, &mOutputClusterTrigRecs, &mOutputTruthCont); // Find clusters on digits (pass by ref) + mClusterizer.processCells(cells, cellsTR, nullptr, &mOutputClusters, &mOutputFullClusters, &mOutputClusterTrigRecs, &mOutputTruthCont); // Find clusters on digits (pass by ref) } } @@ -72,15 +73,19 @@ void ClusterizerSpec::run(framework::ProcessingContext& ctx) } else { LOG(DEBUG) << "[PHOSClusterizer - run] Writing " << mOutputClusters.size() << " clusters and " << mOutputClusterTrigRecs.size() << " TR"; } - ctx.outputs().snapshot(o2::framework::Output{"PHS", "CLUSTERS", 0, o2::framework::Lifetime::Timeframe}, mOutputClusters); - ctx.outputs().snapshot(o2::framework::Output{"PHS", "CLUSTERTRIGRECS", 0, o2::framework::Lifetime::Timeframe}, mOutputClusterTrigRecs); + if (mFullCluOutput) { + ctx.outputs().snapshot(o2::framework::Output{"PHS", "CLUSTERS", 0, o2::framework::Lifetime::Timeframe}, mOutputFullClusters); + } else { + ctx.outputs().snapshot(o2::framework::Output{"PHS", "CLUSTERS", 0, o2::framework::Lifetime::Timeframe}, mOutputClusters); + } + ctx.outputs().snapshot(o2::framework::Output{"PHS", "CLUSTERTRIGREC", 0, o2::framework::Lifetime::Timeframe}, mOutputClusterTrigRecs); if (mPropagateMC) { ctx.outputs().snapshot(o2::framework::Output{"PHS", "CLUSTERTRUEMC", 0, o2::framework::Lifetime::Timeframe}, mOutputTruthCont); } ctx.services().get().readyToQuit(framework::QuitRequest::Me); } -o2::framework::DataProcessorSpec o2::phos::reco_workflow::getClusterizerSpec(bool propagateMC) +o2::framework::DataProcessorSpec o2::phos::reco_workflow::getClusterizerSpec(bool propagateMC, bool fullClu) { std::vector inputs; std::vector outputs; @@ -90,7 +95,7 @@ o2::framework::DataProcessorSpec o2::phos::reco_workflow::getClusterizerSpec(boo inputs.emplace_back("digitsmctr", "PHS", "DIGITSMCTR", 0, o2::framework::Lifetime::Timeframe); } outputs.emplace_back("PHS", "CLUSTERS", 0, o2::framework::Lifetime::Timeframe); - outputs.emplace_back("PHS", "CLUSTERTRIGRECS", 0, o2::framework::Lifetime::Timeframe); + outputs.emplace_back("PHS", "CLUSTERTRIGREC", 0, o2::framework::Lifetime::Timeframe); if (propagateMC) { outputs.emplace_back("PHS", "CLUSTERTRUEMC", 0, o2::framework::Lifetime::Timeframe); } @@ -98,10 +103,10 @@ o2::framework::DataProcessorSpec o2::phos::reco_workflow::getClusterizerSpec(boo return o2::framework::DataProcessorSpec{"PHOSClusterizerSpec", inputs, outputs, - o2::framework::adaptFromTask(propagateMC, true)}; + o2::framework::adaptFromTask(propagateMC, true, fullClu)}; } -o2::framework::DataProcessorSpec o2::phos::reco_workflow::getCellClusterizerSpec(bool propagateMC) +o2::framework::DataProcessorSpec o2::phos::reco_workflow::getCellClusterizerSpec(bool propagateMC, bool fullClu) { //Cluaterizer with cell input std::vector inputs; @@ -112,7 +117,7 @@ o2::framework::DataProcessorSpec o2::phos::reco_workflow::getCellClusterizerSpec inputs.emplace_back("cellsmctr", "PHS", "CELLSMCTR", 0, o2::framework::Lifetime::Timeframe); } outputs.emplace_back("PHS", "CLUSTERS", 0, o2::framework::Lifetime::Timeframe); - outputs.emplace_back("PHS", "CLUSTERTRIGRECS", 0, o2::framework::Lifetime::Timeframe); + outputs.emplace_back("PHS", "CLUSTERTRIGREC", 0, o2::framework::Lifetime::Timeframe); if (propagateMC) { outputs.emplace_back("PHS", "CLUSTERTRUEMC", 0, o2::framework::Lifetime::Timeframe); } @@ -120,5 +125,5 @@ o2::framework::DataProcessorSpec o2::phos::reco_workflow::getCellClusterizerSpec return o2::framework::DataProcessorSpec{"PHOSClusterizerSpec", inputs, outputs, - o2::framework::adaptFromTask(propagateMC, false)}; + o2::framework::adaptFromTask(propagateMC, false, fullClu)}; } diff --git a/Detectors/PHOS/workflow/src/RawToCellConverterSpec.cxx b/Detectors/PHOS/workflow/src/RawToCellConverterSpec.cxx index 5363b52934d3c..5b5d908897dfe 100644 --- a/Detectors/PHOS/workflow/src/RawToCellConverterSpec.cxx +++ b/Detectors/PHOS/workflow/src/RawToCellConverterSpec.cxx @@ -78,7 +78,7 @@ void RawToCellConverterSpec::init(framework::InitContext& ctx) LOG(INFO) << "Fit quality output will be filled"; } - mCombineGHLG = (ctx.options().get("keepGHLG").compare("on") != 0); + mCombineGHLG = (ctx.options().get("keepHGLG").compare("on") != 0); if (!mCombineGHLG) { LOG(INFO) << "Both HighGain and LowGain will be kept"; } @@ -93,7 +93,9 @@ void RawToCellConverterSpec::init(framework::InitContext& ctx) void RawToCellConverterSpec::run(framework::ProcessingContext& ctx) { // Cache cells from bunch crossings as the component reads timeframes from many links consecutively - std::map>> cellBuffer; // Internal cell buffer/ + std::map>> cellBuffer; // Internal cell buffer/ + std::map>> truBuffer; // trigger cell buffer/ + std::map>> truFlagBuffer; // int firstEntry = 0; mOutputHWErrors.clear(); if (mFillChi2) { @@ -135,6 +137,23 @@ void RawToCellConverterSpec::run(framework::ProcessingContext& ctx) } else { currentCellContainer = found->second; } + std::shared_ptr> currentTRUContainer; + auto found2 = truBuffer.find(currentIR); + if (found2 == truBuffer.end()) { + currentTRUContainer = std::make_shared>(); + truBuffer[currentIR] = currentTRUContainer; + } else { + currentTRUContainer = found2->second; + } + std::shared_ptr> currentTRUFlags; + auto found3 = truFlagBuffer.find(currentIR); + if (found3 == truFlagBuffer.end()) { + currentTRUFlags = std::make_shared>(); + truFlagBuffer[currentIR] = currentTRUFlags; + } else { + currentTRUFlags = found3->second; + } + if (ddl > o2::phos::Mapping::NDDL) { //only 14 correct DDLs LOG(ERROR) << "DDL=" << ddl; mOutputHWErrors.emplace_back(15, 16, char(ddl)); //Add non-existing DDL as DDL 15 @@ -199,6 +218,18 @@ void RawToCellConverterSpec::run(framework::ProcessingContext& ctx) currentCellContainer->emplace_back(absId, mRawFitter->getAmp(0), 1.e-7 * mRawFitter->getTime(0), (ChannelType_t)caloFlag); } } + } else { //decode TRU digits + // Channels in TRU: + // There are 112 readout channels and 12 channels reserved for production flags: + // Channels 0-111: channel data readout + // Channels 112-123: production flags + if (Mapping::isTRUReadoutchannel(chan.getHardwareAddress())) { + mMapping->hwToAbsId(ddl, chan.getHardwareAddress(), absId, caloFlag); + short timeBin = chan.getBunches().back().getStartTime(); // Find the time bin of the first time step + readTRUDigit(chan.getBunches(), absId, timeBin, currentTRUContainer); + } else { + readTRUFlags(chan.getHardwareAddress(), chan.getBunches(), currentTRUFlags); + } } } } //RawReader::hasNext @@ -245,11 +276,31 @@ void RawToCellConverterSpec::run(framework::ProcessingContext& ctx) } } + //Add trigger cells + //if trigger cell exists and the trigger flag true -add it + auto found2 = truBuffer.find(bc); + auto found3 = truFlagBuffer.find(bc); + if (found2 != truBuffer.end() && found3 != truFlagBuffer.end()) { + auto currentTRUContainer = found2->second; + auto currentTRUFlags = found3->second; + bool is4x4Trigger = (*currentTRUFlags)[Mapping::NTRUReadoutChannels]; + for (Cell c : *currentTRUContainer) { + if ((*currentTRUFlags)[c.getAbsId()]) { //there is corresponding flag + if (is4x4Trigger) { + c.setType(ChannelType_t::TRU4x4); + } else { + c.setType(ChannelType_t::TRU2x2); + } + mOutputCells.push_back(c); + } + } + } + mOutputTriggerRecords.emplace_back(bc, prevCellSize, mOutputCells.size() - prevCellSize); } cellBuffer.clear(); - LOG(INFO) << "[PHOSRawToCellConverter - run] Writing " << mOutputCells.size() << " cells ..."; + LOG(DEBUG) << "[PHOSRawToCellConverter - run] Writing " << mOutputCells.size() << " cells ..."; ctx.outputs().snapshot(o2::framework::Output{"PHS", "CELLS", 0, o2::framework::Lifetime::Timeframe}, mOutputCells); ctx.outputs().snapshot(o2::framework::Output{"PHS", "CELLTRIGREC", 0, o2::framework::Lifetime::Timeframe}, mOutputTriggerRecords); ctx.outputs().snapshot(o2::framework::Output{"PHS", "RAWHWERRORS", 0, o2::framework::Lifetime::Timeframe}, mOutputHWErrors); @@ -257,6 +308,67 @@ void RawToCellConverterSpec::run(framework::ProcessingContext& ctx) ctx.outputs().snapshot(o2::framework::Output{"PHS", "CELLFITQA", 0, o2::framework::Lifetime::Timeframe}, mOutputFitChi); } } +void RawToCellConverterSpec::readTRUDigit(const std::vector& bunchlist, short absId, short timebin, std::shared_ptr>& currentTRUContainer) +{ + + // TRU Channel data: + // The channel data is read one channel at a time + int smax = 0, tmax = 0; + for (auto b : bunchlist) { + short timeBin = b.getStartTime(); + const std::vector& signal = b.getADC(); + // Loop over all the time steps in the signal + for (std::vector::const_reverse_iterator it = signal.rbegin(); it != signal.rend(); ++it) { + if (*it > smax) { + smax = *it; + tmax = timeBin; + } + timeBin++; + } + } + currentTRUContainer->emplace_back(absId, smax, tmax * 1.e-9, TRU2x2); //add TRU cells +} +void RawToCellConverterSpec::readTRUFlags(short hwAddress, const std::vector& bunchlist, std::shared_ptr>& currentTRUFlags) +{ + // Production flags: + // Production flags are supplied in channels 112 - 123 + // Each of the channels is 10 bit wide + // The bits inside the channel (indexing starting from the first bit of channel 112) is as follows: + // Bits 0-111: Trigger flags for corresponding channel index + // If using 4x4 algorithm, only 91 first bits are used of these + // Bit 112: Marker for 4x4 algorithm (1 active, 0 not active) + // Bit 113: Marker for 2x2 algorithm (1 active, 0 not active) + // Bit 114: Global L0 OR of all patches in the TRU + + for (auto b : bunchlist) { + short timeBin = b.getStartTime(); + const std::vector& signal = b.getADC(); + // Loop over all the time steps in the signal + for (std::vector::const_reverse_iterator it = signal.rbegin(); it != signal.rend(); ++it, ++timeBin) { + + // If bit 112 is 1, we are considering 4x4 algorithm + if (hwAddress == Mapping::TRUFinalProductionChannel) { + (*currentTRUFlags)[Mapping::NTRUReadoutChannels] = (*it & (1 << 2)); // Check the bit number 112 + } + const int kWordLength = 10; // Length of one data word in TRU raw data + + // Assign the bits in the words to corresponding channels + for (Int_t bitIndex = 0; bitIndex < kWordLength; bitIndex++) { + // Find the correct channel number assuming that + // hwAddress 112 = bits 0-9 corresponding trigger flags in channels 0-9 + // hwAddress 113 = bits 10-19 corresponding trigger flags in channels 10-19 + // and so on + short channel; + if (hwAddress < 128) { + channel = (hwAddress - Mapping::NTRUBranchReadoutChannels) * kWordLength + bitIndex; + } else { + channel = 112 + (hwAddress - 2048 - Mapping::NTRUBranchReadoutChannels) * kWordLength + bitIndex; //branch 0 + } + (*currentTRUFlags)[channel] = (*currentTRUFlags)[channel] | (*it & (1 << bitIndex)); + } // Bits in one word + } // Length of signal + } +} char RawToCellConverterSpec::CheckHWAddress(short ddl, short hwAddr, short& fee) { @@ -300,6 +412,6 @@ o2::framework::DataProcessorSpec o2::phos::reco_workflow::getRawToCellConverterS {"fitmethod", o2::framework::VariantType::String, "default", {"Fit method (default or fast)"}}, {"mappingpath", o2::framework::VariantType::String, "", {"Path to mapping files"}}, {"fillchi2", o2::framework::VariantType::String, "off", {"Fill sample qualities on/off"}}, - {"keepGHLG", o2::framework::VariantType::String, "off", {"keep HighGain and Low Gain signals on/off"}}, + {"keepHGLG", o2::framework::VariantType::String, "off", {"keep HighGain and Low Gain signals on/off"}}, {"pedestal", o2::framework::VariantType::String, "off", {"Analyze as pedestal run on/off"}}}}; } diff --git a/Detectors/PHOS/workflow/src/RecoWorkflow.cxx b/Detectors/PHOS/workflow/src/RecoWorkflow.cxx index a970a6c3d4c16..6c5644f13a5c9 100644 --- a/Detectors/PHOS/workflow/src/RecoWorkflow.cxx +++ b/Detectors/PHOS/workflow/src/RecoWorkflow.cxx @@ -56,7 +56,8 @@ o2::framework::WorkflowSpec getWorkflow(bool disableRootInp, bool disableRootOut, bool propagateMC, std::string const& cfgInput, - std::string const& cfgOutput) + std::string const& cfgOutput, + bool fullCluOut) { InputType inputType; @@ -89,7 +90,7 @@ o2::framework::WorkflowSpec getWorkflow(bool disableRootInp, } if (isEnabled(OutputType::Clusters)) { specs.emplace_back(o2::phos::reco_workflow::getRawToCellConverterSpec()); - specs.emplace_back(o2::phos::reco_workflow::getCellClusterizerSpec(false)); //no MC propagation + specs.emplace_back(o2::phos::reco_workflow::getCellClusterizerSpec(false, fullCluOut)); //no MC propagation if (!disableRootOut) { specs.emplace_back(o2::phos::getClusterWriterSpec(false)); } @@ -109,7 +110,7 @@ o2::framework::WorkflowSpec getWorkflow(bool disableRootInp, } } else { if (isEnabled(OutputType::Clusters)) { - specs.emplace_back(o2::phos::reco_workflow::getClusterizerSpec(propagateMC)); + specs.emplace_back(o2::phos::reco_workflow::getClusterizerSpec(propagateMC, fullCluOut)); if (!disableRootOut) { specs.emplace_back(o2::phos::getClusterWriterSpec(propagateMC)); } @@ -124,7 +125,7 @@ o2::framework::WorkflowSpec getWorkflow(bool disableRootInp, } if (isEnabled(OutputType::Clusters)) { // add clusterizer - specs.emplace_back(o2::phos::reco_workflow::getCellClusterizerSpec(propagateMC)); + specs.emplace_back(o2::phos::reco_workflow::getCellClusterizerSpec(propagateMC, fullCluOut)); if (!disableRootOut) { specs.emplace_back(o2::phos::getClusterWriterSpec(propagateMC)); } diff --git a/Detectors/PHOS/workflow/src/WriterSpec.cxx b/Detectors/PHOS/workflow/src/WriterSpec.cxx index e3eb8f77d7100..c3cc63f56c4ad 100644 --- a/Detectors/PHOS/workflow/src/WriterSpec.cxx +++ b/Detectors/PHOS/workflow/src/WriterSpec.cxx @@ -51,7 +51,7 @@ DataProcessorSpec getClusterWriterSpec(bool useMC) MakeRootTreeWriterSpec::TreeAttributes{"o2sim", "Tree with PHOS clusters"}, BranchDefinition{InputSpec{"clus", "PHS", "CLUSTERS", 0}, "PHOSCluster", ClustersSizeGetter}, - BranchDefinition{InputSpec{"clusRecs", "PHS", "CLUSTERTRIGRECS", 0}, + BranchDefinition{InputSpec{"clusRecs", "PHS", "CLUSTERTRIGREC", 0}, "PHOSClusterTrigRec"}, BranchDefinition{InputSpec{"clusMC", "PHS", "CLUSTERTRUEMC", 0}, "PHOSClusterTrueMC"})(); @@ -61,7 +61,7 @@ DataProcessorSpec getClusterWriterSpec(bool useMC) MakeRootTreeWriterSpec::TreeAttributes{"o2sim", "Tree with PHOS clusters"}, BranchDefinition{InputSpec{"clus", "PHS", "CLUSTERS", 0}, "PHOSCluster", ClustersSizeGetter}, - BranchDefinition{InputSpec{"clusRecs", "PHS", "CLUSTERTRIGRECS", 0}, + BranchDefinition{InputSpec{"clusRecs", "PHS", "CLUSTERTRIGREC", 0}, "PHOSClusterTrigRec"})(); } } diff --git a/Detectors/PHOS/workflow/src/phos-reco-workflow.cxx b/Detectors/PHOS/workflow/src/phos-reco-workflow.cxx index 26de9a091ed52..8196173d49965 100644 --- a/Detectors/PHOS/workflow/src/phos-reco-workflow.cxx +++ b/Detectors/PHOS/workflow/src/phos-reco-workflow.cxx @@ -34,6 +34,7 @@ void customize(std::vector& workflowOptions) {"disable-mc", o2::framework::VariantType::Bool, false, {"disable sending of MC information"}}, {"disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input reader"}}, {"disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writer"}}, + {"fullclu-output", o2::framework::VariantType::Bool, false, {"compact of full (with contr. digits) clusters output"}}, {"configKeyValues", o2::framework::VariantType::String, "", {"Semicolon separated key=value strings ..."}}}; o2::raw::HBFUtilsInitializer::addConfigOption(options); @@ -63,10 +64,10 @@ o2::framework::WorkflowSpec defineDataProcessing(o2::framework::ConfigContext co auto wf = o2::phos::reco_workflow::getWorkflow(cfgc.options().get("disable-root-input"), cfgc.options().get("disable-root-output"), - !cfgc.options().get("disable-mc"), // - cfgc.options().get("input-type"), // - cfgc.options().get("output-type")); - + !cfgc.options().get("disable-mc"), + cfgc.options().get("input-type"), + cfgc.options().get("output-type"), + cfgc.options().get("fullclu-output")); // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit o2::raw::HBFUtilsInitializer hbfIni(cfgc, wf); From 7e3fafef418f67c4bf808768d390b173eaddfb55 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Tue, 13 Apr 2021 07:46:32 +0200 Subject: [PATCH 106/770] DPL GUI: report correct status when done (#5883) Now a device will send a "DONE" metric associated to a given input in a slot which was processed. This way we can show a green square for completed computations, rather than a RUNNING one. Notice that due to the way the data relaying works, a DONE slot is really already empty and ready to accept new data, so we only show it as green for a single iteration and then we switch it to EMPTY. --- .../Core/include/Framework/DataRelayer.h | 12 ++++++- Framework/Core/src/DataProcessingDevice.cxx | 5 +++ Framework/Core/src/DataRelayer.cxx | 32 ++++++++++++++++--- 3 files changed, 44 insertions(+), 5 deletions(-) diff --git a/Framework/Core/include/Framework/DataRelayer.h b/Framework/Core/include/Framework/DataRelayer.h index 5b709d360f1a4..54fe5f92f2f8f 100644 --- a/Framework/Core/include/Framework/DataRelayer.h +++ b/Framework/Core/include/Framework/DataRelayer.h @@ -41,6 +41,13 @@ struct DataRelayerStats { uint64_t relayedMessages = 0; /// How many messages have been successfully relayed }; +enum struct CacheEntryStatus : int { + EMPTY, + PENDING, + RUNNING, + DONE +}; + class DataRelayer { public: @@ -107,6 +114,9 @@ class DataRelayer /// so that we can mutex on it. TimesliceId getTimesliceForSlot(TimesliceSlot slot); + /// Mark a given slot as done so that the GUI + /// can reflect that. + void updateCacheStatus(TimesliceSlot slot, CacheEntryStatus oldStatus, CacheEntryStatus newStatus); /// Get the firstTFOrbit associate to a given slot. uint32_t getFirstTFOrbitForSlot(TimesliceSlot slot); /// Get the firstTFCounter associate to a given slot. @@ -131,7 +141,7 @@ class DataRelayer std::vector mDistinctRoutesIndex; std::vector mInputMatchers; std::vector mVariableContextes; - std::vector mCachedStateMetrics; + std::vector mCachedStateMetrics; static std::vector sMetricsNames; static std::vector sVariablesMetricsNames; diff --git a/Framework/Core/src/DataProcessingDevice.cxx b/Framework/Core/src/DataProcessingDevice.cxx index 928bf1751f198..9eac7270756b5 100644 --- a/Framework/Core/src/DataProcessingDevice.cxx +++ b/Framework/Core/src/DataProcessingDevice.cxx @@ -838,6 +838,10 @@ bool DataProcessingDevice::tryDispatchComputation(DataProcessorContext& context, return InputRecord{spec->inputs, std::move(span)}; }; + auto markInputsAsDone = [&relayer = context.relayer](TimesliceSlot slot) -> void { + relayer->updateCacheStatus(slot, CacheEntryStatus::RUNNING, CacheEntryStatus::DONE); + }; + // I need a preparation step which gets the current timeslice id and // propagates it to the various contextes (i.e. the actual entities which // create messages) because the messages need to have the timeslice id into @@ -1025,6 +1029,7 @@ bool DataProcessingDevice::tryDispatchComputation(DataProcessorContext& context, continue; } } + markInputsAsDone(action.slot); uint64_t tStart = uv_hrtime(); preUpdateStats(action, record, tStart); diff --git a/Framework/Core/src/DataRelayer.cxx b/Framework/Core/src/DataRelayer.cxx index 12ccbccb2d81e..134168347584f 100644 --- a/Framework/Core/src/DataRelayer.cxx +++ b/Framework/Core/src/DataRelayer.cxx @@ -255,7 +255,7 @@ DataRelayer::RelayChoice assert(numInputTypes * slot.index < cache.size()); for (size_t ai = slot.index * numInputTypes, ae = ai + numInputTypes; ai != ae; ++ai) { cache[ai].clear(); - cachedStateMetrics[ai] = 0; + cachedStateMetrics[ai] = CacheEntryStatus::EMPTY; } }; @@ -268,7 +268,7 @@ DataRelayer::RelayChoice &metrics](TimesliceId timeslice, int input, TimesliceSlot slot) { auto cacheIdx = numInputTypes * slot.index + input; std::vector& parts = cache[cacheIdx].parts; - cachedStateMetrics[cacheIdx] = 1; + cachedStateMetrics[cacheIdx] = CacheEntryStatus::PENDING; // TODO: make sure that multiple parts can only be added within the same call of // DataRelayer::relay PartRef entry{std::move(header), std::move(payload)}; @@ -488,6 +488,25 @@ void DataRelayer::getReadyToProcess(std::vector& comp } } +void DataRelayer::updateCacheStatus(TimesliceSlot slot, CacheEntryStatus oldStatus, CacheEntryStatus newStatus) +{ + std::scoped_lock lock(mMutex); + const auto numInputTypes = mDistinctRoutesIndex.size(); + auto& index = mTimesliceIndex; + + auto markInputDone = [&cachedStateMetrics = mCachedStateMetrics, + &index, &numInputTypes](TimesliceSlot s, size_t arg, CacheEntryStatus oldStatus, CacheEntryStatus newStatus) { + auto cacheId = s.index * numInputTypes + arg; + if (cachedStateMetrics[cacheId] == oldStatus) { + cachedStateMetrics[cacheId] = newStatus; + } + }; + + for (size_t ai = 0, ae = numInputTypes; ai != ae; ++ai) { + markInputDone(slot, ai, oldStatus, newStatus); + } +} + std::vector DataRelayer::getInputsForTimeslice(TimesliceSlot slot) { std::scoped_lock lock(mMutex); @@ -512,7 +531,7 @@ std::vector DataRelayer::getInputsForTimeslice(Timesl &cachedStateMetrics = mCachedStateMetrics, &cache, &index, &numInputTypes, &metrics](TimesliceSlot s, size_t arg) { auto cacheId = s.index * numInputTypes + arg; - cachedStateMetrics[cacheId] = 2; + cachedStateMetrics[cacheId] = CacheEntryStatus::RUNNING; // TODO: in the original implementation of the cache, there have been only two messages per entry, // check if the 2 above corresponds to the number of messages. if (cache[cacheId].size() > 0) { @@ -634,7 +653,12 @@ void DataRelayer::sendContextState() mMetrics, sVariablesMetricsNames); } for (size_t si = 0; si < mCachedStateMetrics.size(); ++si) { - mMetrics.send({mCachedStateMetrics[si], sMetricsNames[si]}); + mMetrics.send({static_cast(mCachedStateMetrics[si]), sMetricsNames[si]}); + // Anything which is done is actually already empty, + // so after we report it we mark it as such. + if (mCachedStateMetrics[si] == CacheEntryStatus::DONE) { + mCachedStateMetrics[si] = CacheEntryStatus::EMPTY; + } } } From f2ce9fb8af23e90004fae9669abcaf5ddd328a8a Mon Sep 17 00:00:00 2001 From: Ionut Cristian Arsene Date: Tue, 13 Apr 2021 08:34:09 +0200 Subject: [PATCH 107/770] =?UTF-8?q?=EF=BF=BC=20Several=20changes=20(add=20?= =?UTF-8?q?support=20for=20MUON=20Run3=20data=20model,=20removed=20TaskNam?= =?UTF-8?q?e,=20etc.)=20(#5914)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Several changes (add support for MUON Run3 data model, removed TaskName, etc) * clang changes * a few fixes and changes of task names to avoid name conflicts Co-authored-by: Ionut Arsene --- .../AnalysisDataModel/ReducedInfoTables.h | 39 +++-- .../PWGDQ/include/PWGDQCore/CutsLibrary.h | 137 ++++++++++++++++- .../include/PWGDQCore/HistogramsLibrary.h | 48 +++++- Analysis/PWGDQ/include/PWGDQCore/VarManager.h | 142 +++++++++++++++--- Analysis/PWGDQ/src/VarManager.cxx | 8 +- Analysis/Tasks/PWGDQ/dileptonEE.cxx | 12 +- Analysis/Tasks/PWGDQ/dileptonMuMu.cxx | 21 ++- Analysis/Tasks/PWGDQ/filterPP.cxx | 13 +- Analysis/Tasks/PWGDQ/tableMaker.cxx | 69 ++++++--- Analysis/Tasks/PWGDQ/tableMakerMuon_pp.cxx | 24 ++- Analysis/Tasks/PWGDQ/tableReader.cxx | 33 ++-- 11 files changed, 430 insertions(+), 116 deletions(-) diff --git a/Analysis/DataModel/include/AnalysisDataModel/ReducedInfoTables.h b/Analysis/DataModel/include/AnalysisDataModel/ReducedInfoTables.h index af31b3b09f2b6..1ce0c10c9a860 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/ReducedInfoTables.h +++ b/Analysis/DataModel/include/AnalysisDataModel/ReducedInfoTables.h @@ -46,7 +46,7 @@ DECLARE_SOA_TABLE(ReducedEvents, "AOD", "REDUCEDEVENT", o2::soa::Index<>, collision::PosX, collision::PosY, collision::PosZ, collision::NumContrib); DECLARE_SOA_TABLE(ReducedEventsExtended, "AOD", "REEXTENDED", - bc::GlobalBC, bc::TriggerMask, reducedevent::TriggerAlias, cent::CentV0M); + bc::GlobalBC, bc::TriggerMask, timestamp::Timestamp, reducedevent::TriggerAlias, cent::CentV0M); DECLARE_SOA_TABLE(ReducedEventsVtxCov, "AOD", "REVTXCOV", collision::CovXX, collision::CovXY, collision::CovXZ, @@ -63,7 +63,6 @@ DECLARE_SOA_INDEX_COLUMN(ReducedEvent, reducedevent); DECLARE_SOA_COLUMN(Idx, idx, uint16_t); // ---- flags reserved for storing various information during filtering DECLARE_SOA_COLUMN(FilteringFlags, filteringFlags, uint64_t); -// BIT 0: track is from MUON arm (if not toggled then this is a barrel track) // ----------------------------------------------------- DECLARE_SOA_COLUMN(Pt, pt, float); DECLARE_SOA_COLUMN(Eta, eta, float); @@ -93,11 +92,11 @@ DECLARE_SOA_TABLE(ReducedTracksBarrel, "AOD", "RTBARREL", track::ITSClusterMap, track::ITSChi2NCl, track::TPCNClsFindable, track::TPCNClsFindableMinusFound, track::TPCNClsFindableMinusCrossedRows, track::TPCNClsShared, track::TPCChi2NCl, - track::TRDChi2, track::TOFChi2, track::Length, reducedtrack::DcaXY, reducedtrack::DcaZ, + track::TRDChi2, track::TRDPattern, track::TOFChi2, track::Length, reducedtrack::DcaXY, reducedtrack::DcaZ, track::TPCNClsFound, track::TPCNClsCrossedRows); -// barrel covariance matrix +// barrel covariance matrix TODO: add all the elements required for secondary vertexing DECLARE_SOA_TABLE(ReducedTracksBarrelCov, "AOD", "RTBARRELCOV", track::CYY, track::CZZ, track::CSnpSnp, track::CTglTgl, track::C1Pt21Pt2); @@ -107,18 +106,16 @@ DECLARE_SOA_TABLE(ReducedTracksBarrelPID, "AOD", "RTBARRELPID", track::TPCSignal, pidtpc::TPCNSigmaEl, pidtpc::TPCNSigmaMu, pidtpc::TPCNSigmaPi, pidtpc::TPCNSigmaKa, pidtpc::TPCNSigmaPr, - pidtpc::TPCNSigmaDe, pidtpc::TPCNSigmaTr, pidtpc::TPCNSigmaHe, pidtpc::TPCNSigmaAl, - track::TOFSignal, pidtofbeta::Beta, + pidtofbeta::Beta, pidtof::TOFNSigmaEl, pidtof::TOFNSigmaMu, pidtof::TOFNSigmaPi, pidtof::TOFNSigmaKa, pidtof::TOFNSigmaPr, - pidtof::TOFNSigmaDe, pidtof::TOFNSigmaTr, pidtof::TOFNSigmaHe, pidtof::TOFNSigmaAl, track::TRDSignal); // muon quantities namespace reducedmuon { DECLARE_SOA_INDEX_COLUMN(ReducedEvent, reducedevent); -DECLARE_SOA_COLUMN(FilteringFlags, filteringFlags, uint64_t); +DECLARE_SOA_COLUMN(FilteringFlags, filteringFlags, uint8_t); // the (pt,eta,phi,sign) will be computed in the skimming task DECLARE_SOA_COLUMN(Pt, pt, float); DECLARE_SOA_COLUMN(Eta, eta, float); @@ -130,6 +127,7 @@ DECLARE_SOA_DYNAMIC_COLUMN(Pz, pz, [](float pt, float eta) -> float { return pt DECLARE_SOA_DYNAMIC_COLUMN(Pmom, pmom, [](float pt, float eta) -> float { return pt * std::cosh(eta); }); } // namespace reducedmuon +// Muon track kinematics DECLARE_SOA_TABLE(ReducedMuons, "AOD", "RTMUON", o2::soa::Index<>, reducedmuon::ReducedEventId, reducedmuon::FilteringFlags, reducedmuon::Pt, reducedmuon::Eta, reducedmuon::Phi, reducedmuon::Sign, @@ -138,13 +136,21 @@ DECLARE_SOA_TABLE(ReducedMuons, "AOD", "RTMUON", reducedmuon::Pz, reducedmuon::Pmom); -DECLARE_SOA_TABLE(ReducedMuonsExtended, "AOD", "RTMUONEXTENDED", - muon::InverseBendingMomentum, - muon::ThetaX, muon::ThetaY, muon::ZMu, - muon::BendingCoor, muon::NonBendingCoor, - muon::Chi2, muon::Chi2MatchTrigger, - muon::RAtAbsorberEnd, - muon::PDca); +// Muon track quality details +DECLARE_SOA_TABLE(ReducedMuonsExtra, "AOD", "RTMUONEXTRA", + muon::InverseBendingMomentum, muon::ThetaX, muon::ThetaY, muon::ZMu, muon::BendingCoor, muon::NonBendingCoor, + muon::Chi2, muon::Chi2MatchTrigger); + +// TODO: tables to be used once new AO2Ds are created +/*DECLARE_SOA_TABLE(ReducedMuonsExtra, "AOD", "RTMUONEXTRA", + fwdtrack::NClusters, fwdtrack::PDca, fwdtrack::RAtAbsorberEnd, + fwdtrack::Chi2, fwdtrack::Chi2MatchMCHMID, fwdtrack::Chi2MatchMCHMFT, + fwdtrack::MatchScoreMCHMFT, fwdtrack::MatchMFTTrackID, fwdtrack::MatchMCHTrackID); +// Muon covariance, TODO: the rest of the matrix should be added when needed +DECLARE_SOA_TABLE(ReducedMuonsCov, "AOD", "RTMUONCOV", + aod::fwdtrack::CXX, aod::fwdtrack::CYY, aod::fwdtrack::CPhiPhi, + aod::fwdtrack::CTglTgl, aod::fwdtrack::C1Pt21Pt2); +*/ // pair information namespace reducedpair @@ -177,7 +183,8 @@ using ReducedTrackBarrel = ReducedTracksBarrel::iterator; using ReducedTrackBarrelCov = ReducedTracksBarrelCov::iterator; using ReducedTrackBarrelPID = ReducedTracksBarrelPID::iterator; using ReducedMuon = ReducedMuons::iterator; -using ReducedMuonExtended = ReducedMuonsExtended::iterator; +using ReducedMuonExtra = ReducedMuonsExtra::iterator; +//using ReducedMuonCov = ReducedMuonsCov::iterator; using Dilepton = Dileptons::iterator; } // namespace o2::aod diff --git a/Analysis/PWGDQ/include/PWGDQCore/CutsLibrary.h b/Analysis/PWGDQ/include/PWGDQCore/CutsLibrary.h index 999668f2644c8..9ebab06721768 100644 --- a/Analysis/PWGDQ/include/PWGDQCore/CutsLibrary.h +++ b/Analysis/PWGDQ/include/PWGDQCore/CutsLibrary.h @@ -29,7 +29,7 @@ AnalysisCompositeCut* o2::aod::dqcuts::GetCompositeCut(const char* cutName) // define composie cuts, typically combinations of all the ingredients needed for a full cut // // TODO: Agree on some conventions for the naming - // Possibly think of possible customization of the predefined cuts + // Think of possible customization of the predefined cuts via names AnalysisCompositeCut* cut = new AnalysisCompositeCut(cutName, cutName); std::string nameStr = cutName; @@ -42,7 +42,7 @@ AnalysisCompositeCut* o2::aod::dqcuts::GetCompositeCut(const char* cutName) } if (!nameStr.compare("jpsiPID1")) { - cut->AddCut(GetAnalysisCut("jpsiStandardKine")); + cut->AddCut(GetAnalysisCut("jpsiStandardKine")); // standard kine cuts usually are applied via Filter in the task cut->AddCut(GetAnalysisCut("electronStandardQuality")); cut->AddCut(GetAnalysisCut("standardPrimaryTrack")); cut->AddCut(GetAnalysisCut("electronPID1")); @@ -57,6 +57,75 @@ AnalysisCompositeCut* o2::aod::dqcuts::GetCompositeCut(const char* cutName) return cut; } + if (!nameStr.compare("jpsiPIDnsigma")) { + cut->AddCut(GetAnalysisCut("jpsiStandardKine")); + cut->AddCut(GetAnalysisCut("electronStandardQuality")); + cut->AddCut(GetAnalysisCut("standardPrimaryTrack")); + cut->AddCut(GetAnalysisCut("electronPIDnsigma")); + return cut; + } + + //--------------------------------------------------------------------------------------- + // NOTE: Below there are several TPC pid cuts used for studies of the dE/dx degradation + // and its impact on the high lumi pp quarkonia triggers + // To be removed when not needed anymore + if (!nameStr.compare("jpsiPID1Randomized")) { + cut->AddCut(GetAnalysisCut("jpsiStandardKine")); // standard kine cuts usually are applied via Filter in the task + cut->AddCut(GetAnalysisCut("electronStandardQuality")); + cut->AddCut(GetAnalysisCut("standardPrimaryTrack")); + cut->AddCut(GetAnalysisCut("electronPID1randomized")); + return cut; + } + + if (!nameStr.compare("jpsiPID2Randomized")) { + cut->AddCut(GetAnalysisCut("jpsiStandardKine")); + cut->AddCut(GetAnalysisCut("electronStandardQuality")); + cut->AddCut(GetAnalysisCut("standardPrimaryTrack")); + cut->AddCut(GetAnalysisCut("electronPID2randomized")); + return cut; + } + + if (!nameStr.compare("jpsiPIDnsigmaRandomized")) { + cut->AddCut(GetAnalysisCut("jpsiStandardKine")); + cut->AddCut(GetAnalysisCut("electronStandardQuality")); + cut->AddCut(GetAnalysisCut("standardPrimaryTrack")); + cut->AddCut(GetAnalysisCut("electronPIDnsigmaRandomized")); + return cut; + } + + if (!nameStr.compare("jpsiPIDworseRes")) { + cut->AddCut(GetAnalysisCut("jpsiStandardKine")); + cut->AddCut(GetAnalysisCut("electronStandardQuality")); + cut->AddCut(GetAnalysisCut("standardPrimaryTrack")); + cut->AddCut(GetAnalysisCut("electronPIDworseRes")); + return cut; + } + + if (!nameStr.compare("jpsiPIDshift")) { + cut->AddCut(GetAnalysisCut("jpsiStandardKine")); + cut->AddCut(GetAnalysisCut("electronStandardQuality")); + cut->AddCut(GetAnalysisCut("standardPrimaryTrack")); + cut->AddCut(GetAnalysisCut("electronPIDshift")); + return cut; + } + + if (!nameStr.compare("jpsiPID1shiftUp")) { + cut->AddCut(GetAnalysisCut("jpsiStandardKine")); + cut->AddCut(GetAnalysisCut("electronStandardQuality")); + cut->AddCut(GetAnalysisCut("standardPrimaryTrack")); + cut->AddCut(GetAnalysisCut("electronPID1shiftUp")); + return cut; + } + + if (!nameStr.compare("jpsiPID1shiftDown")) { + cut->AddCut(GetAnalysisCut("jpsiStandardKine")); + cut->AddCut(GetAnalysisCut("electronStandardQuality")); + cut->AddCut(GetAnalysisCut("standardPrimaryTrack")); + cut->AddCut(GetAnalysisCut("electronPID1shiftDown")); + return cut; + } + // ------------------------------------------------------------------------------------------------- + if (!nameStr.compare("lmeePID_TPChadrejTOFrec")) { cut->AddCut(GetAnalysisCut("lmeeStandardKine")); cut->AddCut(GetAnalysisCut("TightGlobalTrack")); @@ -173,6 +242,11 @@ AnalysisCut* o2::aod::dqcuts::GetAnalysisCut(const char* cutName) return cut; } + if (!nameStr.compare("eventStandardNoINT7")) { + cut->AddCut(VarManager::kVtxZ, -10.0, 10.0); + return cut; + } + if (!nameStr.compare("int7vtxZ5")) { cut->AddCut(VarManager::kVtxZ, -5.0, 5.0); cut->AddCut(VarManager::kIsINT7, 0.5, 1.5); @@ -225,19 +299,76 @@ AnalysisCut* o2::aod::dqcuts::GetAnalysisCut(const char* cutName) } TF1* cutLow1 = new TF1("cutLow1", "pol1", 0., 10.); - cutLow1->SetParameters(130., -40.0); if (!nameStr.compare("electronPID1")) { + cutLow1->SetParameters(130., -40.0); cut->AddCut(VarManager::kTPCsignal, 70., 100.); cut->AddCut(VarManager::kTPCsignal, cutLow1, 100.0, false, VarManager::kPin, 0.5, 3.0); return cut; } + if (!nameStr.compare("electronPID1shiftUp")) { + cut->AddCut(VarManager::kTPCsignal, 70. - 0.85, 100. - 0.85); + cutLow1->SetParameters(130. - 0.85, -40.0); + cut->AddCut(VarManager::kTPCsignal, cutLow1, 100.0 - 0.85, false, VarManager::kPin, 0.5, 3.0); + return cut; + } + + if (!nameStr.compare("electronPID1shiftDown")) { + cut->AddCut(VarManager::kTPCsignal, 70.0 + 0.85, 100.0 + 0.85); + cutLow1->SetParameters(130. + 0.85, -40.0); + cut->AddCut(VarManager::kTPCsignal, cutLow1, 100.0 + 0.85, false, VarManager::kPin, 0.5, 3.0); + return cut; + } + + if (!nameStr.compare("electronPID1randomized")) { + cutLow1->SetParameters(130., -40.0); + cut->AddCut(VarManager::kTPCsignalRandomized, 70., 100.); + cut->AddCut(VarManager::kTPCsignalRandomized, cutLow1, 100.0, false, VarManager::kPin, 0.5, 3.0); + return cut; + } + if (!nameStr.compare("electronPID2")) { + cutLow1->SetParameters(130., -40.0); cut->AddCut(VarManager::kTPCsignal, 73., 100.); cut->AddCut(VarManager::kTPCsignal, cutLow1, 100.0, false, VarManager::kPin, 0.5, 3.0); return cut; } + if (!nameStr.compare("electronPID2randomized")) { + cutLow1->SetParameters(130., -40.0); + cut->AddCut(VarManager::kTPCsignalRandomized, 73., 100.); + cut->AddCut(VarManager::kTPCsignalRandomized, cutLow1, 100.0, false, VarManager::kPin, 0.5, 3.0); + return cut; + } + + if (!nameStr.compare("electronPIDnsigma")) { + cut->AddCut(VarManager::kTPCnSigmaEl, -3.0, 3.0); + cut->AddCut(VarManager::kTPCnSigmaPr, 3.0, 3000.0); + cut->AddCut(VarManager::kTPCnSigmaPi, 3.0, 3000.0); + return cut; + } + + if (!nameStr.compare("electronPIDnsigmaRandomized")) { + cut->AddCut(VarManager::kTPCnSigmaElRandomized, -3.0, 3.0); + cut->AddCut(VarManager::kTPCnSigmaPrRandomized, 3.0, 3000.0); + cut->AddCut(VarManager::kTPCnSigmaPiRandomized, 3.0, 3000.0); + return cut; + } + + if (!nameStr.compare("electronPIDworseRes")) { + cut->AddCut(VarManager::kTPCnSigmaEl, -3.0, 3.0); + cut->AddCut(VarManager::kTPCnSigmaPr, 3.0 * 0.8, 3000.0); // emulates a 20% degradation in PID resolution + cut->AddCut(VarManager::kTPCnSigmaPi, 3.0 * 0.8, 3000.0); // proton and pion rejections are effectively relaxed by 20% + return cut; + } + + if (!nameStr.compare("electronPIDshift")) { + cut->AddCut(VarManager::kTPCnSigmaEl, -3.0, 3.0); + cut->AddCut(VarManager::kTPCnSigmaPr, 3.0 - 0.2, 3000.0); + cut->AddCut(VarManager::kTPCnSigmaPi, 3.0 - 0.2, 3000.0); + return cut; + } + if (!nameStr.compare("tpc_pion_rejection")) { TF1* f1maxPi = new TF1("f1maxPi", "[0]+[1]*x", 0, 10); f1maxPi->SetParameters(85, -50); diff --git a/Analysis/PWGDQ/include/PWGDQCore/HistogramsLibrary.h b/Analysis/PWGDQ/include/PWGDQCore/HistogramsLibrary.h index a68e40b88b12d..8809ca25a0a75 100644 --- a/Analysis/PWGDQ/include/PWGDQCore/HistogramsLibrary.h +++ b/Analysis/PWGDQ/include/PWGDQCore/HistogramsLibrary.h @@ -41,10 +41,22 @@ void o2::aod::dqhistograms::DefineHistograms(HistogramManager* hm, const char* h if (subGroupStr.Contains("trigger")) { hm->AddHistogram(histClass, "IsINT7", "Is INT7", false, 2, -0.5, 1.5, VarManager::kIsINT7); - hm->AddHistogram(histClass, "IsINT7inMUON", "INT7inMUON", false, 2, -0.5, 1.5, VarManager::kIsINT7inMUON); - hm->AddHistogram(histClass, "IsMuonSingleLowPt7", "Is MuonSingleLowPt7", false, 2, -0.5, 1.5, VarManager::kIsMuonSingleLowPt7); - hm->AddHistogram(histClass, "IsMuonUnlikeLowPt7", "Is MuonUnlikeLowPt7", false, 2, -0.5, 1.5, VarManager::kIsMuonUnlikeLowPt7); - hm->AddHistogram(histClass, "IsMuonLikeLowPt7", "Is MuonLikeLowPt7", false, 2, -0.5, 1.5, VarManager::kIsMuonLikeLowPt7); + if (subGroupStr.Contains("muon") || subGroupStr.Contains("all")) { + hm->AddHistogram(histClass, "IsINT7inMUON", "INT7inMUON", false, 2, -0.5, 1.5, VarManager::kIsINT7inMUON); + hm->AddHistogram(histClass, "IsMuonSingleLowPt7", "Is MuonSingleLowPt7", false, 2, -0.5, 1.5, VarManager::kIsMuonSingleLowPt7); + hm->AddHistogram(histClass, "IsMuonSingleHighPt7", "Is MuonSingleHighPt7", false, 2, -0.5, 1.5, VarManager::kIsMuonSingleHighPt7); + hm->AddHistogram(histClass, "IsMuonUnlikeLowPt7", "Is MuonUnlikeLowPt7", false, 2, -0.5, 1.5, VarManager::kIsMuonUnlikeLowPt7); + hm->AddHistogram(histClass, "IsMuonLikeLowPt7", "Is MuonLikeLowPt7", false, 2, -0.5, 1.5, VarManager::kIsMuonLikeLowPt7); + } + if (subGroupStr.Contains("up") || subGroupStr.Contains("all")) { + hm->AddHistogram(histClass, "IsCUP8", "CUP8", false, 2, -0.5, 1.5, VarManager::kIsCUP8); + hm->AddHistogram(histClass, "IsCUP9", "CUP9", false, 2, -0.5, 1.5, VarManager::kIsCUP9); + hm->AddHistogram(histClass, "IsMUP10", "MUP10", false, 2, -0.5, 1.5, VarManager::kIsMUP10); + hm->AddHistogram(histClass, "IsMUP11", "MUP11", false, 2, -0.5, 1.5, VarManager::kIsMUP11); + } + if (subGroupStr.Contains("emc") || subGroupStr.Contains("all")) { + hm->AddHistogram(histClass, "IsEMC7", "EMC7", false, 2, -0.5, 1.5, VarManager::kIsEMC7); + } } if (subGroupStr.Contains("vtx")) { hm->AddHistogram(histClass, "VtxX", "Vtx X", false, 100, -0.5, 0.5, VarManager::kVtxX); @@ -88,13 +100,25 @@ void o2::aod::dqhistograms::DefineHistograms(HistogramManager* hm, const char* h 10, -0.5, 159.5, VarManager::kTPCncls, 10, 0., 1., VarManager::kNothing, VarManager::GetRunStr().Data()); hm->AddHistogram(histClass, "TPCnclsCR", "Number of crossed rows in TPC", false, 160, -0.5, 159.5, VarManager::kTPCnclsCR); hm->AddHistogram(histClass, "IsTPCrefit", "", false, 2, -0.5, 1.5, VarManager::kIsTPCrefit); + hm->AddHistogram(histClass, "IsGoldenChi2", "", false, 2, -0.5, 1.5, VarManager::kIsGoldenChi2); hm->AddHistogram(histClass, "TPCchi2", "TPC chi2", false, 100, 0.0, 10.0, VarManager::kTPCchi2); } if (subGroupStr.Contains("tpcpid")) { - hm->AddHistogram(histClass, "TPCdedx_pIN", "TPC dE/dx vs pIN", false, 200, 0.0, 20.0, VarManager::kPin, 200, 0.0, 200., VarManager::kTPCsignal); + hm->AddHistogram(histClass, "TPCdedx_pIN", "TPC dE/dx vs pIN", false, 200, 0.0, 10.0, VarManager::kPin, 200, 0.0, 200., VarManager::kTPCsignal); + hm->AddHistogram(histClass, "TPCdedxRandomized_pIN", "TPC dE/dx (randomized) vs pIN", false, 200, 0.0, 10.0, VarManager::kPin, 200, 0.0, 200., VarManager::kTPCsignalRandomized); + hm->AddHistogram(histClass, "TPCdedxRandomizedDelta_pIN", "TPC dE/dx (randomized - delta) vs pIN", false, 200, 0.0, 10.0, VarManager::kPin, 100, 0.0, 10., VarManager::kTPCsignalRandomizedDelta); + hm->AddHistogram(histClass, "TPCnSigEle_pIN", "TPC n-#sigma(e) vs pIN", false, 200, 0.0, 10.0, VarManager::kPin, 100, -5.0, 5.0, VarManager::kTPCnSigmaEl); + hm->AddHistogram(histClass, "TPCnSigEleRandomized_pIN", "TPC n-#sigma(e) - randomized - vs pIN", false, 200, 0.0, 10.0, VarManager::kPin, 100, -5.0, 5.0, VarManager::kTPCnSigmaElRandomized); + hm->AddHistogram(histClass, "TPCnSigEleRandomizedDelta_pIN", "TPC n-#sigma(e) - randomized delta - vs pIN", false, 20, 0.0, 10.0, VarManager::kPin, 200, -0.5, 0.5, VarManager::kTPCnSigmaElRandomizedDelta); + hm->AddHistogram(histClass, "TPCnSigEleRandomized_TPCnSigEle", "TPC n-#sigma(e) - randomized - vs TPC n-#sigma(e)", false, 100, -5.0, 5.0, VarManager::kTPCnSigmaEl, 100, -5.0, 5.0, VarManager::kTPCnSigmaElRandomized); + hm->AddHistogram(histClass, "TPCnSigPiRandomized_TPCnSigPi", "TPC n-#sigma(#pi) - randomized - vs TPC n-#sigma(#pi)", false, 100, -5.0, 5.0, VarManager::kTPCnSigmaPi, 100, -5.0, 5.0, VarManager::kTPCnSigmaPiRandomized); + hm->AddHistogram(histClass, "TPCnSigPrRandomized_TPCnSigPr", "TPC n-#sigma(p) - randomized - vs TPC n-#sigma(p)", false, 100, -5.0, 5.0, VarManager::kTPCnSigmaPr, 100, -5.0, 5.0, VarManager::kTPCnSigmaPrRandomized); + hm->AddHistogram(histClass, "TPCnSigPiRandomized_pIN", "TPC n-#sigma(#pi) - randomized - vs pIN", false, 200, 0.0, 10.0, VarManager::kPin, 100, -5.0, 5.0, VarManager::kTPCnSigmaPiRandomized); + hm->AddHistogram(histClass, "TPCnSigPrRandomized_pIN", "TPC n-#sigma(p) - randomized - vs pIN", false, 200, 0.0, 10.0, VarManager::kPin, 100, -5.0, 5.0, VarManager::kTPCnSigmaPrRandomized); } if (subGroupStr.Contains("tofpid")) { hm->AddHistogram(histClass, "TOFbeta_pIN", "TOF #beta vs pIN", false, 200, 0.0, 20.0, VarManager::kPin, 120, 0.0, 1.2, VarManager::kTOFbeta); + hm->AddHistogram(histClass, "TOFnSigEle_pIN", "TOF n-#sigma(e) vs pIN", false, 200, 0.0, 10.0, VarManager::kPin, 100, -5.0, 5.0, VarManager::kTOFnSigmaEl); } if (subGroupStr.Contains("dca")) { hm->AddHistogram(histClass, "DCAxy", "DCAxy", false, 100, -3.0, 3.0, VarManager::kTrackDCAxy); @@ -111,6 +135,20 @@ void o2::aod::dqhistograms::DefineHistograms(HistogramManager* hm, const char* h hm->AddHistogram(histClass, "Chi2MatchTrigger", "", false, 100, 0.0, 20.0, VarManager::kMuonChi2MatchTrigger); hm->AddHistogram(histClass, "RAtAbsorberEnd", "", false, 100, 10, 2000, VarManager::kMuonRAtAbsorberEnd); hm->AddHistogram(histClass, "pdca", "", false, 100, 0.0, 1000, VarManager::kMuonPDca); + + /*hm->AddHistogram(histClass, "MuonNClusters", "", false, 100, 0.0, 10.0, VarManager::kMuonNClusters); + hm->AddHistogram(histClass, "pdca", "", false, 100, 0.0, 1000., VarManager::kMuonPDca); + hm->AddHistogram(histClass, "RAtAbsorberEnd", "", false, 100, 10, 2000, VarManager::kMuonRAtAbsorberEnd); + hm->AddHistogram(histClass, "Chi2", "", false, 100, 0.0, 200.0, VarManager::kMuonChi2); + hm->AddHistogram(histClass, "Chi2MCHMID", "", false, 100, 0.0, 200.0, VarManager::kMuonChi2MatchMCHMID); + hm->AddHistogram(histClass, "Chi2MCHMFT", "", false, 100, 0.0, 200.0, VarManager::kMuonChi2MatchMCHMFT); + hm->AddHistogram(histClass, "Chi2MatchScoreMCHMFT", "", false, 100, 0.0, 200.0, VarManager::kMuonMatchScoreMCHMFT); + hm->AddHistogram(histClass, "MatchMFTTrackID", "", false, 100, 0.0, 200.0, VarManager::kMuonMatchMFTTrackID); + hm->AddHistogram(histClass, "MuonCXX", "", false, 100, -1.0, 1.0, VarManager::kMuonCXX); + hm->AddHistogram(histClass, "MuonCYY", "", false, 100, -1.0, 1.0, VarManager::kMuonCYY); + hm->AddHistogram(histClass, "MuonCPhiPhi", "", false, 100, -1.0, 1.0, VarManager::kMuonCPhiPhi); + hm->AddHistogram(histClass, "MuonCTglTgl", "", false, 100, -1.0, 1.0, VarManager::kMuonCTglTgl); + hm->AddHistogram(histClass, "MuonC1Pt21Pt2", "", false, 100, -1.0, 1.0, VarManager::kMuonC1Pt21Pt2);*/ } } diff --git a/Analysis/PWGDQ/include/PWGDQCore/VarManager.h b/Analysis/PWGDQ/include/PWGDQCore/VarManager.h index 40e5175de6e7f..f63bee9b89657 100644 --- a/Analysis/PWGDQ/include/PWGDQCore/VarManager.h +++ b/Analysis/PWGDQ/include/PWGDQCore/VarManager.h @@ -19,7 +19,7 @@ #include #include #include -#include +#include #include #include @@ -38,25 +38,31 @@ class VarManager : public TObject public: // map the information contained in the objects passed to the Fill functions enum ObjTypes { + // NOTE: Elements containing "Reduced" in their name refer to skimmed data tables + // and the ones that don't refer to tables from the Framework data model BC = BIT(0), Collision = BIT(1), CollisionCent = BIT(2), - ReducedEvent = BIT(3), - ReducedEventExtended = BIT(4), - ReducedEventVtxCov = BIT(5), + CollisionTimestamp = BIT(3), + ReducedEvent = BIT(4), + ReducedEventExtended = BIT(5), + ReducedEventVtxCov = BIT(6), Track = BIT(0), TrackCov = BIT(1), TrackExtra = BIT(2), TrackPID = BIT(3), TrackDCA = BIT(4), TrackSelection = BIT(5), - // TODO: Central model MUON variables to be added ReducedTrack = BIT(6), ReducedTrackBarrel = BIT(7), ReducedTrackBarrelCov = BIT(8), ReducedTrackBarrelPID = BIT(9), - ReducedTrackMuon = BIT(10), - Pair = BIT(11) + Muon = BIT(10), + MuonCov = BIT(11), + ReducedMuon = BIT(12), + ReducedMuonExtra = BIT(13), + ReducedMuonCov = BIT(14), + Pair = BIT(15) }; enum PairCandidateType { @@ -73,16 +79,21 @@ class VarManager : public TObject kRunId, kNRunWiseVariables, - // Event wise variables // Daria: imedjat ai ziua mja - kCollisionTime, + // Event wise variables + kTimestamp, kBC, kIsPhysicsSelection, kIsINT7, kIsEMC7, kIsINT7inMUON, kIsMuonSingleLowPt7, + kIsMuonSingleHighPt7, kIsMuonUnlikeLowPt7, kIsMuonLikeLowPt7, + kIsCUP8, + kIsCUP9, + kIsMUP10, + kIsMUP11, kVtxX, kVtxY, kVtxZ, @@ -97,7 +108,7 @@ class VarManager : public TObject kCentVZERO, kNEventWiseVariables, - // Basic track(pair) wise variables + // Basic track/muon/pair wise variables kPt, kEta, kPhi, @@ -126,22 +137,31 @@ class VarManager : public TObject kTPCnclsCR, kTPCchi2, kTPCsignal, + kTPCsignalRandomized, + kTPCsignalRandomizedDelta, kTRDsignal, - kTOFsignal, + kTRDPattern, kTOFbeta, kTrackLength, kTrackDCAxy, kTrackDCAz, + kIsGoldenChi2, kTrackCYY, kTrackCZZ, kTrackCSnpSnp, kTrackCTglTgl, kTrackC1Pt21Pt2, kTPCnSigmaEl, + kTPCnSigmaElRandomized, + kTPCnSigmaElRandomizedDelta, kTPCnSigmaMu, kTPCnSigmaPi, + kTPCnSigmaPiRandomized, + kTPCnSigmaPiRandomizedDelta, kTPCnSigmaKa, kTPCnSigmaPr, + kTPCnSigmaPrRandomized, + kTPCnSigmaPrRandomizedDelta, kTOFnSigmaEl, kTOFnSigmaMu, kTOFnSigmaPi, @@ -160,6 +180,20 @@ class VarManager : public TObject kMuonPDca, kMuonChi2, kMuonChi2MatchTrigger, + /* kMuonNClusters, + kMuonPDca, + kMuonRAtAbsorberEnd, + kMuonChi2, + kMuonChi2MatchMCHMID, + kMuonChi2MatchMCHMFT, + kMuonMatchScoreMCHMFT, + kMuonMatchMFTTrackID, + kMuonMatchMCHTrackID, + kMuonCXX, + kMuonCYY, + kMuonCPhiPhi, + kMuonCTglTgl, + kMuonC1Pt21Pt2,*/ kNMuonTrackVariables, // Pair variables @@ -270,6 +304,10 @@ void VarManager::FillEvent(T const& event, float* values) values[kBC] = event.bc().globalBC(); } + if constexpr ((fillMap & CollisionTimestamp) > 0) { + values[kTimestamp] = event.timestamp(); + } + if constexpr ((fillMap & Collision) > 0) { if (fgUsedVars[kIsINT7]) { values[kIsINT7] = (event.alias()[kINT7] > 0); @@ -283,17 +321,31 @@ void VarManager::FillEvent(T const& event, float* values) if (fgUsedVars[kIsMuonSingleLowPt7]) { values[kIsMuonSingleLowPt7] = (event.alias()[kMuonSingleLowPt7] > 0); } + if (fgUsedVars[kIsMuonSingleHighPt7]) { + values[kIsMuonSingleHighPt7] = (event.alias()[kMuonSingleHighPt7] > 0); + } if (fgUsedVars[kIsMuonUnlikeLowPt7]) { values[kIsMuonUnlikeLowPt7] = (event.alias()[kMuonUnlikeLowPt7] > 0); } if (fgUsedVars[kIsMuonLikeLowPt7]) { values[kIsMuonLikeLowPt7] = (event.alias()[kMuonLikeLowPt7] > 0); } + if (fgUsedVars[kIsCUP8]) { + values[kIsCUP8] = (event.alias()[kCUP8] > 0); + } + if (fgUsedVars[kIsCUP9]) { + values[kIsCUP9] = (event.alias()[kCUP9] > 0); + } + if (fgUsedVars[kIsMUP10]) { + values[kIsMUP10] = (event.alias()[kMUP10] > 0); + } + if (fgUsedVars[kIsMUP11]) { + values[kIsMUP11] = (event.alias()[kMUP11] > 0); + } values[kVtxX] = event.posX(); values[kVtxY] = event.posY(); values[kVtxZ] = event.posZ(); values[kVtxNcontrib] = event.numContrib(); - values[kCollisionTime] = event.collisionTime(); values[kVtxCovXX] = event.covXX(); values[kVtxCovXY] = event.covXY(); values[kVtxCovXZ] = event.covXZ(); @@ -319,6 +371,7 @@ void VarManager::FillEvent(T const& event, float* values) if constexpr ((fillMap & ReducedEventExtended) > 0) { values[kBC] = event.globalBC(); + values[kTimestamp] = event.timestamp(); values[kCentVZERO] = event.centV0M(); if (fgUsedVars[kIsINT7]) { values[kIsINT7] = (event.triggerAlias() & (uint32_t(1) << kINT7)) > 0; @@ -332,12 +385,27 @@ void VarManager::FillEvent(T const& event, float* values) if (fgUsedVars[kIsMuonSingleLowPt7]) { values[kIsMuonSingleLowPt7] = (event.triggerAlias() & (uint32_t(1) << kMuonSingleLowPt7)) > 0; } + if (fgUsedVars[kIsMuonSingleHighPt7]) { + values[kIsMuonSingleHighPt7] = (event.triggerAlias() & (uint32_t(1) << kMuonSingleHighPt7)) > 0; + } if (fgUsedVars[kIsMuonUnlikeLowPt7]) { values[kIsMuonUnlikeLowPt7] = (event.triggerAlias() & (uint32_t(1) << kMuonUnlikeLowPt7)) > 0; } if (fgUsedVars[kIsMuonLikeLowPt7]) { values[kIsMuonLikeLowPt7] = (event.triggerAlias() & (uint32_t(1) << kMuonLikeLowPt7)) > 0; } + if (fgUsedVars[kIsCUP8]) { + values[kIsCUP8] = (event.triggerAlias() & (uint32_t(1) << kCUP8)) > 0; + } + if (fgUsedVars[kIsCUP9]) { + values[kIsCUP9] = (event.triggerAlias() & (uint32_t(1) << kCUP9)) > 0; + } + if (fgUsedVars[kIsMUP10]) { + values[kIsMUP10] = (event.triggerAlias() & (uint32_t(1) << kMUP10)) > 0; + } + if (fgUsedVars[kIsMUP11]) { + values[kIsMUP11] = (event.triggerAlias() & (uint32_t(1) << kMUP11)) > 0; + } } if constexpr ((fillMap & ReducedEventVtxCov) > 0) { @@ -360,7 +428,7 @@ void VarManager::FillTrack(T const& track, float* values) values = fgValues; } - if constexpr ((fillMap & Track) > 0 || (fillMap & ReducedTrack) > 0) { + if constexpr ((fillMap & Track) > 0 || (fillMap & Muon) > 0 || (fillMap & ReducedTrack) > 0 || (fillMap & ReducedMuon) > 0) { values[kPt] = track.pt(); if (fgUsedVars[kPx]) { values[kPx] = track.px(); @@ -379,10 +447,13 @@ void VarManager::FillTrack(T const& track, float* values) if constexpr ((fillMap & TrackExtra) > 0 || (fillMap & ReducedTrackBarrel) > 0) { values[kPin] = track.tpcInnerParam(); if (fgUsedVars[kIsITSrefit]) { - values[kIsITSrefit] = (track.flags() & (uint32_t(1) << 0)) > 0; + values[kIsITSrefit] = (track.flags() & o2::aod::track::ITSrefit) > 0; } if (fgUsedVars[kIsTPCrefit]) { - values[kIsTPCrefit] = (track.flags() & (uint32_t(1) << 1)) > 0; + values[kIsTPCrefit] = (track.flags() & o2::aod::track::TPCrefit) > 0; + } + if (fgUsedVars[kIsGoldenChi2]) { + values[kIsGoldenChi2] = (track.flags() & o2::aod::track::GoldenChi2) > 0; } if (fgUsedVars[kIsSPDfirst]) { values[kIsSPDfirst] = (track.itsClusterMap() & uint8_t(1)) > 0; @@ -398,6 +469,7 @@ void VarManager::FillTrack(T const& track, float* values) values[kTPCchi2] = track.tpcChi2NCl(); values[kTrackLength] = track.length(); values[kTPCnclsCR] = track.tpcNClsCrossedRows(); + values[kTRDPattern] = track.trdPattern(); if constexpr ((fillMap & TrackExtra) > 0) { if (fgUsedVars[kITSncls]) { @@ -447,11 +519,25 @@ void VarManager::FillTrack(T const& track, float* values) values[kTOFnSigmaPr] = track.tofNSigmaPr(); values[kTPCsignal] = track.tpcSignal(); values[kTRDsignal] = track.trdSignal(); - values[kTOFsignal] = track.tofSignal(); values[kTOFbeta] = track.beta(); + if (fgUsedVars[kTPCsignalRandomized] || fgUsedVars[kTPCnSigmaElRandomized] || fgUsedVars[kTPCnSigmaPiRandomized] || fgUsedVars[kTPCnSigmaPrRandomized]) { + // NOTE: this is needed temporarilly for the study of the impact of TPC pid degradation on the quarkonium triggers in high lumi pp + // This study involves a degradation from a dE/dx resolution of 5% to one of 6% (20% worsening) + // For this we smear the dE/dx and n-sigmas using a gaus distribution with a width of 3.3% + // which is approx the needed amount to get dE/dx to a resolution of 6% + double randomX = gRandom->Gaus(0.0, 0.033); + values[kTPCsignalRandomized] = values[kTPCsignal] * (1.0 + randomX); + values[kTPCsignalRandomizedDelta] = values[kTPCsignal] * randomX; + values[kTPCnSigmaElRandomized] = values[kTPCnSigmaEl] * (1.0 + randomX); + values[kTPCnSigmaElRandomizedDelta] = values[kTPCnSigmaEl] * randomX; + values[kTPCnSigmaPiRandomized] = values[kTPCnSigmaPi] * (1.0 + randomX); + values[kTPCnSigmaPiRandomizedDelta] = values[kTPCnSigmaPi] * randomX; + values[kTPCnSigmaPrRandomized] = values[kTPCnSigmaPr] * (1.0 + randomX); + values[kTPCnSigmaPrRandomizedDelta] = values[kTPCnSigmaPr] * randomX; + } } - if constexpr ((fillMap & ReducedTrackMuon) > 0) { + if constexpr ((fillMap & ReducedMuonExtra) > 0) { values[kMuonInvBendingMomentum] = track.inverseBendingMomentum(); values[kMuonThetaX] = track.thetaX(); values[kMuonThetaY] = track.thetaY(); @@ -464,6 +550,26 @@ void VarManager::FillTrack(T const& track, float* values) values[kMuonChi2MatchTrigger] = track.chi2MatchTrigger(); } + // TODO: Uncomment when AO2Ds with the new data model are produced + /*if constexpr ((fillMap & ReducedMuonExtra) > 0 || (fillMap & Muon) > 0) { + values[kMuonNClusters] = track.nClusters(); + values[kMuonPDca] = track.pDca(); + values[kMuonRAtAbsorberEnd] = track.rAtAbsorberEnd(); + values[kMuonChi2] = track.chi2(); + values[kMuonChi2MatchMCHMID] = track.chi2MatchMCHMID(); + values[kMuonChi2MatchMCHMFT] = track.chi2MatchMCHMFT(); + values[kMuonMatchScoreMCHMFT] = track.matchScoreMCHMFT(); + values[kMuonMatchMFTTrackID] = track.matchMFTTrackID(); + values[kMuonMatchMCHTrackID] = track.matchMCHTrackID(); + }*/ + /*if constexpr ((fillMap & ReducedMuonCov) > 0 || (fillMap & MuonCov) > 0) { + values[kMuonCXX] = track.cXX(); + values[kMuonCYY] = track.cYY(); + values[kMuonCPhiPhi] = track.cPhiPhi(); + values[kMuonCTglTgl] = track.cTglTgl(); + values[kMuonC1Pt21Pt2] = track.c1Pt21Pt2(); + }*/ + if constexpr ((fillMap & Pair) > 0) { values[kMass] = track.mass(); } @@ -522,7 +628,7 @@ void VarManager::FillDileptonHadron(T1 const& dilepton, T2 const& hadron, float* values[kDeltaPhi] = delta; } if (fgUsedVars[kDeltaPhiSym]) { - double delta = TMath::Abs(dilepton.phi() - hadron.phi()); + double delta = std::abs(dilepton.phi() - hadron.phi()); if (delta > M_PI) { delta = 2 * M_PI - delta; } diff --git a/Analysis/PWGDQ/src/VarManager.cxx b/Analysis/PWGDQ/src/VarManager.cxx index ee1584ca3a6cc..a1b70905c61c5 100644 --- a/Analysis/PWGDQ/src/VarManager.cxx +++ b/Analysis/PWGDQ/src/VarManager.cxx @@ -10,7 +10,7 @@ #include "PWGDQCore/VarManager.h" -#include +#include ClassImp(VarManager); @@ -101,7 +101,7 @@ void VarManager::FillTrackDerived(float* values) // Fill track-wise derived quantities (these are all quantities which can be computed just based on the values already filled in the FillTrack() function) // if (fgUsedVars[kP]) { - values[kP] = values[kPt] * TMath::CosH(values[kEta]); + values[kP] = values[kPt] * std::cosh(values[kEta]); } } @@ -120,8 +120,6 @@ void VarManager::SetDefaultVarNames() fgVariableUnits[kRunNo] = ""; fgVariableNames[kRunId] = "Run number"; fgVariableUnits[kRunId] = ""; - fgVariableNames[kCollisionTime] = "collision time"; - fgVariableUnits[kCollisionTime] = ""; fgVariableNames[kBC] = "Bunch crossing"; fgVariableUnits[kBC] = ""; fgVariableNames[kIsPhysicsSelection] = "Physics selection"; @@ -188,8 +186,6 @@ void VarManager::SetDefaultVarNames() fgVariableUnits[kTPCsignal] = ""; fgVariableNames[kTRDsignal] = "TRD dE/dx"; fgVariableUnits[kTRDsignal] = ""; - fgVariableNames[kTOFsignal] = "TOF signal"; - fgVariableUnits[kTOFsignal] = ""; fgVariableNames[kTOFbeta] = "TOF #beta"; fgVariableUnits[kTOFbeta] = ""; fgVariableNames[kTrackLength] = "track length"; diff --git a/Analysis/Tasks/PWGDQ/dileptonEE.cxx b/Analysis/Tasks/PWGDQ/dileptonEE.cxx index b114c711bd855..63fc5a52b34ed 100644 --- a/Analysis/Tasks/PWGDQ/dileptonEE.cxx +++ b/Analysis/Tasks/PWGDQ/dileptonEE.cxx @@ -76,7 +76,7 @@ void DefineHistograms(HistogramManager* histMan, TString histClasses); constexpr static uint32_t gkEventFillMap = VarManager::ObjTypes::ReducedEvent | VarManager::ObjTypes::ReducedEventExtended; constexpr static uint32_t gkTrackFillMap = VarManager::ObjTypes::ReducedTrack | VarManager::ObjTypes::ReducedTrackBarrel | VarManager::ObjTypes::ReducedTrackBarrelCov | VarManager::ObjTypes::ReducedTrackBarrelPID; -struct EventSelection { +struct DQEventSelection { Produces eventSel; Produces hash; OutputObj fOutputList{"output"}; @@ -146,7 +146,7 @@ struct EventSelection { } }; -struct BarrelTrackSelection { +struct DQBarrelTrackSelection { Produces trackSel; OutputObj fOutputList{"output"}; HistogramManager* fHistMan; @@ -344,7 +344,7 @@ struct DileptonEE { } }; -struct EventMixing { +struct DQEventMixing { OutputObj fOutputList{"output"}; HistogramManager* fHistMan; float* fValues; @@ -446,10 +446,10 @@ struct EventMixing { WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { return WorkflowSpec{ - adaptAnalysisTask(cfgc), - adaptAnalysisTask(cfgc), + adaptAnalysisTask(cfgc), + adaptAnalysisTask(cfgc), adaptAnalysisTask(cfgc), - adaptAnalysisTask(cfgc), + adaptAnalysisTask(cfgc), }; } diff --git a/Analysis/Tasks/PWGDQ/dileptonMuMu.cxx b/Analysis/Tasks/PWGDQ/dileptonMuMu.cxx index 13140327863ec..7e5e85f13b9ea 100644 --- a/Analysis/Tasks/PWGDQ/dileptonMuMu.cxx +++ b/Analysis/Tasks/PWGDQ/dileptonMuMu.cxx @@ -20,7 +20,6 @@ #include "PWGDQCore/AnalysisCut.h" #include "PWGDQCore/AnalysisCompositeCut.h" #include -#include #include #include #include @@ -58,8 +57,8 @@ using MyEvents = soa::Join; using MyEventsSelected = soa::Join; using MyEventsVtxCov = soa::Join; using MyEventsVtxCovSelected = soa::Join; -using MyMuonTracks = soa::Join; -using MyMuonTracksSelected = soa::Join; +using MyMuonTracks = soa::Join; +using MyMuonTracksSelected = soa::Join; void DefineHistograms(HistogramManager* histMan, TString histClasses); @@ -71,9 +70,9 @@ void DefineHistograms(HistogramManager* histMan, TString histClasses); // This is a temporary fix until the arrow/ROOT issues are solved, at which point it will be possible // to automatically detect the object types transmitted to the VarManager constexpr static uint32_t gkEventFillMap = VarManager::ObjTypes::ReducedEvent | VarManager::ObjTypes::ReducedEventExtended; -constexpr static uint32_t gkMuonFillMap = VarManager::ObjTypes::ReducedTrack | VarManager::ObjTypes::ReducedTrackMuon; +constexpr static uint32_t gkMuonFillMap = VarManager::ObjTypes::ReducedTrack | VarManager::ObjTypes::ReducedMuon; -struct EventSelection { +struct DQEventSelection { Produces eventSel; OutputObj fOutputList{"output"}; HistogramManager* fHistMan; @@ -126,7 +125,7 @@ struct EventSelection { } }; -struct MuonTrackSelection { +struct DQMuonTrackSelection { Produces trackSel; OutputObj fOutputList{"output"}; HistogramManager* fHistMan; @@ -346,14 +345,14 @@ void DefineHistograms(HistogramManager* histMan, TString histClasses) histMan->AddHistogram(classStr.Data(), "Pz", "p_{z} distribution", false, 400, -20.0, 20.0, VarManager::kPz); if (classStr.Contains("Muon")) { - histMan->AddHistogram(classStr.Data(), "InvBendingMom", "", false, 100, 0.0, 1.0, VarManager::kMuonInvBendingMomentum); + /*histMan->AddHistogram(classStr.Data(), "InvBendingMom", "", false, 100, 0.0, 1.0, VarManager::kMuonInvBendingMomentum); histMan->AddHistogram(classStr.Data(), "ThetaX", "", false, 100, -1.0, 1.0, VarManager::kMuonThetaX); histMan->AddHistogram(classStr.Data(), "ThetaY", "", false, 100, -2.0, 2.0, VarManager::kMuonThetaY); histMan->AddHistogram(classStr.Data(), "ZMu", "", false, 100, -30.0, 30.0, VarManager::kMuonZMu); histMan->AddHistogram(classStr.Data(), "BendingCoor", "", false, 100, 0.32, 0.35, VarManager::kMuonBendingCoor); histMan->AddHistogram(classStr.Data(), "NonBendingCoor", "", false, 100, 0.065, 0.07, VarManager::kMuonNonBendingCoor); histMan->AddHistogram(classStr.Data(), "Chi2", "", false, 100, 0.0, 200.0, VarManager::kMuonChi2); - histMan->AddHistogram(classStr.Data(), "Chi2MatchTrigger", "", false, 100, 0.0, 20.0, VarManager::kMuonChi2MatchTrigger); + histMan->AddHistogram(classStr.Data(), "Chi2MatchTrigger", "", false, 100, 0.0, 20.0, VarManager::kMuonChi2MatchTrigger);*/ histMan->AddHistogram(classStr.Data(), "RAtAbsorberEnd", "", false, 140, 10, 150, VarManager::kMuonRAtAbsorberEnd); histMan->AddHistogram(classStr.Data(), "p x dca", "", false, 700, 0.0, 700, VarManager::kMuonRAtAbsorberEnd); } @@ -373,7 +372,7 @@ void DefineHistograms(HistogramManager* histMan, TString histClasses) WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { return WorkflowSpec{ - adaptAnalysisTask(cfgc, TaskName{"my-event-selection"}), - adaptAnalysisTask(cfgc, TaskName{"muon-track-selection"}), - adaptAnalysisTask(cfgc, TaskName{"dilepton-mumu"})}; + adaptAnalysisTask(cfgc), + adaptAnalysisTask(cfgc), + adaptAnalysisTask(cfgc)}; } diff --git a/Analysis/Tasks/PWGDQ/filterPP.cxx b/Analysis/Tasks/PWGDQ/filterPP.cxx index 8dda66436c82f..30121475c50a0 100644 --- a/Analysis/Tasks/PWGDQ/filterPP.cxx +++ b/Analysis/Tasks/PWGDQ/filterPP.cxx @@ -29,7 +29,6 @@ #include "AnalysisDataModel/TrackSelectionTables.h" #include #include -#include #include #include #include @@ -68,7 +67,7 @@ constexpr static uint32_t gkTrackFillMap = VarManager::ObjTypes::Track | VarMana void DefineHistograms(HistogramManager* histMan, TString histClasses); -struct EventSelectionTask { +struct DQEventSelectionTask { Produces eventSel; OutputObj fOutputList{"output"}; HistogramManager* fHistMan; @@ -125,7 +124,7 @@ struct EventSelectionTask { } }; -struct BarrelTrackSelectionTask { +struct DQBarrelTrackSelectionTask { Produces trackSel; OutputObj fOutputList{"output"}; HistogramManager* fHistMan; @@ -197,7 +196,7 @@ struct BarrelTrackSelectionTask { } }; -struct FilterPPTask { +struct DQFilterPPTask { Produces eventFilter; OutputObj fOutputList{"output"}; OutputObj fStats{"stats"}; @@ -321,9 +320,9 @@ struct FilterPPTask { WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { return WorkflowSpec{ - adaptAnalysisTask(cfgc, TaskName{"dq-event-selection"}), - adaptAnalysisTask(cfgc, TaskName{"dq-barrel-track-selection"}), - adaptAnalysisTask(cfgc, TaskName{"dq-ppFilter"})}; + adaptAnalysisTask(cfgc), + adaptAnalysisTask(cfgc), + adaptAnalysisTask(cfgc)}; } void DefineHistograms(HistogramManager* histMan, TString histClasses) diff --git a/Analysis/Tasks/PWGDQ/tableMaker.cxx b/Analysis/Tasks/PWGDQ/tableMaker.cxx index 75ecfe57588dd..076041cc47aeb 100644 --- a/Analysis/Tasks/PWGDQ/tableMaker.cxx +++ b/Analysis/Tasks/PWGDQ/tableMaker.cxx @@ -48,6 +48,9 @@ void customize(std::vector& workflowOptions) using MyBarrelTracks = soa::Join; using MyEvents = soa::Join; using MyEventsNoCent = soa::Join; +using MyMuons = aod::Muons; +//using MyMuons = soa::Join; +//using MyMuons = aod::FullFwdTracks; // HACK: In order to be able to deduce which kind of aod object is transmitted to the templated VarManager::Fill functions // a constexpr static bit map must be defined and sent as template argument @@ -59,7 +62,8 @@ using MyEventsNoCent = soa::Join; constexpr static uint32_t gkEventFillMap = VarManager::ObjTypes::BC | VarManager::ObjTypes::Collision | VarManager::ObjTypes::CollisionCent; constexpr static uint32_t gkEventFillMapNoCent = VarManager::ObjTypes::BC | VarManager::ObjTypes::Collision; constexpr static uint32_t gkTrackFillMap = VarManager::ObjTypes::Track | VarManager::ObjTypes::TrackExtra | VarManager::ObjTypes::TrackDCA | VarManager::ObjTypes::TrackSelection | VarManager::ObjTypes::TrackCov | VarManager::ObjTypes::TrackPID; -constexpr static uint32_t gkMuonFillMap = VarManager::ObjTypes::Track | VarManager::ObjTypes::ReducedTrackMuon; +//constexpr static uint32_t gkMuonFillMap = VarManager::ObjTypes::Muon | VarManager::ObjTypes::MuonCov; +constexpr static uint32_t gkMuonFillMap = VarManager::ObjTypes::Muon; template struct TableMaker { @@ -74,11 +78,13 @@ struct TableMaker { Produces trackBarrelCov; Produces trackBarrelPID; Produces muonBasic; - Produces muonExtended; + Produces muonExtra; + //Produces muonCov; // TODO: use with fwdtracks float* fValues; OutputObj fOutputList{"output"}; + OutputObj etaH{TH1F("eta", "eta", 102, -2.01, 2.01)}; HistogramManager* fHistMan; Configurable fConfigEventCuts{"cfgEventCuts", "eventStandard", "Event selection"}; @@ -93,12 +99,18 @@ struct TableMaker { AnalysisCompositeCut* fMuonCut; // TODO: filter on TPC dedx used temporarily until electron PID will be improved - Filter barrelSelectedTracks = o2::aod::track::pt >= fConfigBarrelTrackPtLow && nabs(o2::aod::track::eta) <= 0.9f && o2::aod::track::tpcSignal >= 70.0f && o2::aod::track::tpcSignal <= 100.0f && o2::aod::track::tpcChi2NCl < 4.0f && o2::aod::track::itsChi2NCl < 36.0f; + Filter barrelSelectedTracks = aod::track::trackType == uint8_t(aod::track::Run2Track) && o2::aod::track::pt >= fConfigBarrelTrackPtLow && nabs(o2::aod::track::eta) <= 0.9f && o2::aod::track::tpcSignal >= 70.0f && o2::aod::track::tpcSignal <= 100.0f && o2::aod::track::tpcChi2NCl < 4.0f && o2::aod::track::itsChi2NCl < 36.0f; + //Filter barrelSelectedTracks = aod::track::trackType == uint8_t(aod::track::Run2GlobalTrack); + + //Filter barrelSelectedTracks = o2::aod::track::pt >= fConfigBarrelTrackPtLow && nabs(o2::aod::track::eta) <= 0.9f; + //Filter trackFilter = aod::track::trackType == aod::track::Run2GlobalTrack; // TODO: some of the muon variables which could be used in the filter expression are currently DYNAMIC columns (e.g. eta) // Add more basic muon cuts // TODO: Use Partition to avoid the cross-talk between filters which use variables with the same name (e.g. pt for both barrel and muon tracks) + // Replace by Filter when the bug is fixed - Partition selectedMuons = o2::aod::muon::pt >= fConfigMuonPtLow; + Partition selectedMuons = o2::aod::muon::pt >= fConfigMuonPtLow; + //Partition selectedMuons = o2::aod::fwdtrack::pt >= fConfigMuonPtLow; void init(o2::framework::InitContext&) { @@ -131,15 +143,16 @@ struct TableMaker { VarManager::SetUseVars(AnalysisCut::fgUsedVars); // provide the list of required variables so that VarManager knows what to fill } - void process(MyEvent const& collision, aod::Muons const& tracksMuon, aod::BCs const& bcs, soa::Filtered const& tracksBarrel) + void process(MyEvent const& collision, MyMuons const& tracksMuon, aod::BCs const& bcs, soa::Filtered const& tracksBarrel) { - uint64_t tag = 0; uint32_t triggerAliases = 0; for (int i = 0; i < kNaliases; i++) { if (collision.alias()[i] > 0) { triggerAliases |= (uint32_t(1) << i); } } + uint64_t tag = 0; + //uint64_t tag = collision.run2bcinfo().eventCuts(); // TODO: get the event cuts VarManager::ResetValues(0, VarManager::kNEventWiseVariables, fValues); VarManager::FillEvent(collision, fValues); // extract event information and place it in the fgValues array @@ -152,7 +165,7 @@ struct TableMaker { fHistMan->FillHistClass("Event_AfterCuts", fValues); event(tag, collision.bc().runNumber(), collision.posX(), collision.posY(), collision.posZ(), collision.numContrib()); - eventExtended(collision.bc().globalBC(), collision.bc().triggerMask(), triggerAliases, fValues[VarManager::kCentVZERO]); + eventExtended(collision.bc().globalBC(), collision.bc().triggerMask(), 0, triggerAliases, fValues[VarManager::kCentVZERO]); eventVtxCov(collision.covXX(), collision.covXY(), collision.covXZ(), collision.covYY(), collision.covYZ(), collision.covZZ(), collision.chi2()); uint64_t trackFilteringTag = 0; @@ -169,6 +182,7 @@ struct TableMaker { } fHistMan->FillHistClass("TrackBarrel_AfterCuts", fValues); + etaH->Fill(track.eta()); if (track.isGlobalTrack()) { trackFilteringTag |= (uint64_t(1) << 0); } @@ -179,39 +193,52 @@ struct TableMaker { trackBarrel(track.tpcInnerParam(), track.flags(), track.itsClusterMap(), track.itsChi2NCl(), track.tpcNClsFindable(), track.tpcNClsFindableMinusFound(), track.tpcNClsFindableMinusCrossedRows(), track.tpcNClsShared(), track.tpcChi2NCl(), - track.trdChi2(), track.tofChi2(), + track.trdChi2(), track.trdPattern(), track.tofChi2(), track.length(), track.dcaXY(), track.dcaZ()); trackBarrelCov(track.cYY(), track.cZZ(), track.cSnpSnp(), track.cTglTgl(), track.c1Pt21Pt2()); trackBarrelPID(track.tpcSignal(), track.tpcNSigmaEl(), track.tpcNSigmaMu(), track.tpcNSigmaPi(), track.tpcNSigmaKa(), track.tpcNSigmaPr(), - track.tpcNSigmaDe(), track.tpcNSigmaTr(), track.tpcNSigmaHe(), track.tpcNSigmaAl(), - track.tofSignal(), track.beta(), + track.beta(), track.tofNSigmaEl(), track.tofNSigmaMu(), track.tofNSigmaPi(), track.tofNSigmaKa(), track.tofNSigmaPr(), - track.tofNSigmaDe(), track.tofNSigmaTr(), track.tofNSigmaHe(), track.tofNSigmaAl(), track.trdSignal()); } muonBasic.reserve(selectedMuons.size()); - muonExtended.reserve(selectedMuons.size()); + muonExtra.reserve(selectedMuons.size()); for (auto& muon : selectedMuons) { - // TODO: add proper information for muon tracks if (muon.bcId() != collision.bcId()) { continue; } VarManager::FillTrack(muon, fValues); fHistMan->FillHistClass("Muons_BeforeCuts", fValues); - // TODO: the trackFilteringTag will not be needed to encode whether the track is a muon since there is a dedicated table for muons - trackFilteringTag |= (uint64_t(1) << 0); // this is a MUON arm track TODO: to be taken out if (!fMuonCut->IsSelected(fValues)) { continue; } fHistMan->FillHistClass("Muons_AfterCuts", fValues); - muonBasic(event.lastIndex(), trackFilteringTag, muon.pt(), muon.eta(), muon.phi(), muon.sign()); - muonExtended(muon.inverseBendingMomentum(), muon.thetaX(), muon.thetaY(), muon.zMu(), muon.bendingCoor(), muon.nonBendingCoor(), muon.chi2(), muon.chi2MatchTrigger()); + muonExtra(muon.inverseBendingMomentum(), muon.thetaX(), muon.thetaY(), muon.zMu(), muon.bendingCoor(), muon.nonBendingCoor(), muon.chi2(), muon.chi2MatchTrigger()); } + + // TODO: to be used with the fwdtrack tables + /*muonBasic.reserve(tracksMuon.size()); + muonExtra.reserve(tracksMuon.size()); + //muonCov.reserve(tracksMuon.size()); + for (auto& muon : tracksMuon) { + VarManager::FillTrack(muon, fValues); + fHistMan->FillHistClass("Muons_BeforeCuts", fValues); + if (!fMuonCut->IsSelected(fValues)) { + continue; + } + fHistMan->FillHistClass("Muons_AfterCuts", fValues); + + muonBasic(event.lastIndex(), trackFilteringTag, muon.pt(), muon.eta(), muon.phi(), muon.sign()); + muonExtra(muon.nClusters(), muon.pDca(), muon.rAtAbsorberEnd(), + muon.chi2(), muon.chi2MatchMCHMID(), muon.chi2MatchMCHMFT(), + muon.matchScoreMCHMFT(), muon.matchMFTTrackID(), muon.matchMCHTrackID()); + //muonCov(muon.cXX(), muon.cYY(), muon.cPhiPhi(), muon.cTglTgl(), muon.c1Pt21Pt2()); + }*/ } void DefineHistograms(TString histClasses) @@ -223,11 +250,11 @@ struct TableMaker { // NOTE: The level of detail for histogramming can be controlled via configurables if (classStr.Contains("Event")) { - dqhistograms::DefineHistograms(fHistMan, objArray->At(iclass)->GetName(), "event", "trigger,cent"); + dqhistograms::DefineHistograms(fHistMan, objArray->At(iclass)->GetName(), "event", "triggerall,cent"); } if (classStr.Contains("Track")) { - dqhistograms::DefineHistograms(fHistMan, objArray->At(iclass)->GetName(), "track", "tpcpid"); + dqhistograms::DefineHistograms(fHistMan, objArray->At(iclass)->GetName(), "track", "dca,its,tpcpid"); } if (classStr.Contains("Muons")) { dqhistograms::DefineHistograms(fHistMan, objArray->At(iclass)->GetName(), "track", "muon"); @@ -241,9 +268,9 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) WorkflowSpec workflow; const bool isPbPb = cfgc.options().get("isPbPb"); if (isPbPb) { - workflow.push_back(adaptAnalysisTask>(cfgc, TaskName{"table-maker"})); + workflow.push_back(adaptAnalysisTask>(cfgc, TaskName{"dq-table-maker-pbpb"})); } else { - workflow.push_back(adaptAnalysisTask>(cfgc, TaskName{"table-maker"})); + workflow.push_back(adaptAnalysisTask>(cfgc, TaskName{"dq-table-maker-pp"})); } return workflow; diff --git a/Analysis/Tasks/PWGDQ/tableMakerMuon_pp.cxx b/Analysis/Tasks/PWGDQ/tableMakerMuon_pp.cxx index b6c39fd78411b..c002370d27c24 100644 --- a/Analysis/Tasks/PWGDQ/tableMakerMuon_pp.cxx +++ b/Analysis/Tasks/PWGDQ/tableMakerMuon_pp.cxx @@ -35,7 +35,9 @@ using namespace o2::framework; //using namespace o2::framework::expressions; using namespace o2::aod; -using MyEvents = soa::Join; +using MyEvents = soa::Join; +//using MyMuons = soa::Join; +using MyMuons = aod::Muons; // HACK: In order to be able to deduce which kind of aod object is transmitted to the templated VarManager::Fill functions // a constexpr static bit map must be defined and sent as template argument @@ -53,7 +55,8 @@ struct TableMakerMuon_pp { Produces eventVtxCov; Produces trackBasic; Produces muonBasic; - Produces muonExtended; + Produces muonExtended; + //Produces muonCov; // TODO: use with fwdtracks float* fValues; @@ -67,7 +70,7 @@ struct TableMakerMuon_pp { // TODO a few of the important muon variables in the central data model are dynamic columns so not usable in expressions (e.g. eta, phi) // Update the data model to have them as expression columns - Partition muonSelectedTracks = o2::aod::muon::pt >= 0.5f; // For pp collisions a 0.5 GeV/c pp cuts is defined + Partition muonSelectedTracks = o2::aod::muon::pt >= 0.5f; // For pp collisions a 0.5 GeV/c pp cuts is defined void init(o2::framework::InitContext&) { @@ -94,7 +97,7 @@ struct TableMakerMuon_pp { VarManager::SetUseVars(AnalysisCut::fgUsedVars); // provide the list of required variables so that VarManager knows what to fill } - void process(MyEvents::iterator const& collision, aod::MuonClusters const& clustersMuon, aod::Muons const& tracksMuon, aod::BCs const& bcs) + void process(MyEvents::iterator const& collision, MyMuons const& muonTracks, aod::BCs const& bcs) { uint64_t tag = 0; uint32_t triggerAliases = 0; @@ -115,7 +118,7 @@ struct TableMakerMuon_pp { fHistMan->FillHistClass("Event_AfterCuts", fValues); event(tag, collision.bc().runNumber(), collision.posX(), collision.posY(), collision.posZ(), collision.numContrib()); - eventExtended(collision.bc().globalBC(), collision.bc().triggerMask(), triggerAliases, 0.0f); + eventExtended(collision.bc().globalBC(), collision.bc().triggerMask(), collision.timestamp(), triggerAliases, 0.0f); eventVtxCov(collision.covXX(), collision.covXY(), collision.covXZ(), collision.covYY(), collision.covYZ(), collision.covZZ(), collision.chi2()); uint64_t trackFilteringTag = 0; @@ -132,6 +135,17 @@ struct TableMakerMuon_pp { muonBasic(event.lastIndex(), trackFilteringTag, muon.pt(), muon.eta(), muon.phi(), muon.sign()); muonExtended(muon.inverseBendingMomentum(), muon.thetaX(), muon.thetaY(), muon.zMu(), muon.bendingCoor(), muon.nonBendingCoor(), muon.chi2(), muon.chi2MatchTrigger()); } + // TODO: to be used with the fwdtrack tables + /*muonBasic.reserve(muonSelectedTracks.size()); + muonExtended.reserve(muonSelectedTracks.size()); + muonCov.reserve(muonSelectedTracks.size()); + for (auto& muon : muonSelectedTracks) { + muonBasic(event.lastIndex(), trackFilteringTag, muon.pt(), muon.eta(), muon.phi(), muon.sign()); + muonExtended(muon.nClusters(), muon.pDca(), muon.rAtAbsorberEnd(), + muon.chi2(), muon.chi2MatchMCHMID(), muon.chi2MatchMCHMFT(), + muon.matchScoreMCHMFT(), muon.matchMFTTrackID(), muon.matchMCHTrackID()); + muonCov(muon.cXX(), muon.cYY(), muon.cPhiPhi(), muon.cTglTgl(), muon.c1Pt21Pt2()); + }*/ } void DefineHistograms(TString histClasses) diff --git a/Analysis/Tasks/PWGDQ/tableReader.cxx b/Analysis/Tasks/PWGDQ/tableReader.cxx index 312314dd7c834..6530aa9822daf 100644 --- a/Analysis/Tasks/PWGDQ/tableReader.cxx +++ b/Analysis/Tasks/PWGDQ/tableReader.cxx @@ -22,7 +22,6 @@ #include "PWGDQCore/HistogramsLibrary.h" #include "PWGDQCore/CutsLibrary.h" #include -#include #include #include #include @@ -68,8 +67,8 @@ using MyEventsVtxCovSelected = soa::Join; using MyBarrelTracksSelected = soa::Join; -using MyMuonTracks = soa::Join; -using MyMuonTracksSelected = soa::Join; +using MyMuonTracks = soa::Join; +using MyMuonTracksSelected = soa::Join; void DefineHistograms(HistogramManager* histMan, TString histClasses); @@ -82,13 +81,13 @@ void DefineHistograms(HistogramManager* histMan, TString histClasses); // to automatically detect the object types transmitted to the VarManager constexpr static uint32_t gkEventFillMap = VarManager::ObjTypes::ReducedEvent | VarManager::ObjTypes::ReducedEventExtended; constexpr static uint32_t gkTrackFillMap = VarManager::ObjTypes::ReducedTrack | VarManager::ObjTypes::ReducedTrackBarrel | VarManager::ObjTypes::ReducedTrackBarrelCov | VarManager::ObjTypes::ReducedTrackBarrelPID; -constexpr static uint32_t gkMuonFillMap = VarManager::ObjTypes::ReducedTrack | VarManager::ObjTypes::ReducedTrackMuon; +constexpr static uint32_t gkMuonFillMap = VarManager::ObjTypes::ReducedTrack | VarManager::ObjTypes::ReducedMuon; // NOTE: hardcoded number of parallel electron cuts for the barrel analysis // TODO: make it configurable constexpr int gNTrackCuts = 2; -struct EventSelection { +struct DQEventSelection { Produces eventSel; Produces hash; OutputObj fOutputList{"output"}; @@ -153,7 +152,7 @@ struct EventSelection { } }; -struct BarrelTrackSelection { +struct DQBarrelTrackSelection { Produces trackSel; OutputObj fOutputList{"output"}; HistogramManager* fHistMan; @@ -232,7 +231,7 @@ struct BarrelTrackSelection { } }; -struct MuonTrackSelection { +struct DQMuonTrackSelection { Produces trackSel; OutputObj fOutputList{"output"}; HistogramManager* fHistMan; @@ -287,7 +286,7 @@ struct MuonTrackSelection { } }; -struct EventMixing { +struct DQEventMixing { OutputObj fOutputList{"output"}; HistogramManager* fHistMan; float* fValues; @@ -432,7 +431,7 @@ struct EventMixing { } // end process() }; -struct TableReader { +struct DQTableReader { Produces dileptonList; OutputObj fOutputList{"output"}; HistogramManager* fHistMan; @@ -536,7 +535,7 @@ struct TableReader { } }; -struct DileptonHadronAnalysis { +struct DQDileptonHadronAnalysis { // // This task combines dilepton candidates with a track and could be used for example // in analyses with the dilepton as one of the decay products of a higher mass resonance (e.g. B0 -> Jpsi + K) @@ -619,14 +618,12 @@ struct DileptonHadronAnalysis { WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { return WorkflowSpec{ - adaptAnalysisTask(cfgc, TaskName{"my-event-selection"}), - adaptAnalysisTask(cfgc, TaskName{"barrel-track-selection"}), - adaptAnalysisTask(cfgc, TaskName{"event-mixing"}), - adaptAnalysisTask(cfgc, TaskName{"muon-track-selection"}), - adaptAnalysisTask(cfgc, TaskName{"table-reader"}), - adaptAnalysisTask(cfgc, TaskName{"dilepton-hadron"}) - - }; + adaptAnalysisTask(cfgc), + adaptAnalysisTask(cfgc), + adaptAnalysisTask(cfgc), + adaptAnalysisTask(cfgc), + adaptAnalysisTask(cfgc), + adaptAnalysisTask(cfgc)}; } void DefineHistograms(HistogramManager* histMan, TString histClasses) From dd636f08c6cc81f768054030e0626d544e4a1d3b Mon Sep 17 00:00:00 2001 From: shahoian Date: Mon, 12 Apr 2021 20:56:22 +0200 Subject: [PATCH 108/770] Define DetID::mask_t as bitset<32> regardless on nDetectors --- .../Common/include/DetectorsCommonDataFormats/CTFHeader.h | 2 +- .../Common/include/DetectorsCommonDataFormats/DetID.h | 4 ++-- DataFormats/Detectors/Common/src/DetID.cxx | 2 +- .../Parameters/include/DataFormatsParameters/GRPObject.h | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/CTFHeader.h b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/CTFHeader.h index a9aed41b83596..dfb8d4e123ab9 100644 --- a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/CTFHeader.h +++ b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/CTFHeader.h @@ -32,7 +32,7 @@ struct CTFHeader { std::string describe() const; void print() const; - ClassDefNV(CTFHeader, 1) + ClassDefNV(CTFHeader, 2) }; std::ostream& operator<<(std::ostream& stream, const CTFHeader& c); diff --git a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h index d0152ee515eb8..277f9b6e10c63 100644 --- a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h +++ b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h @@ -84,7 +84,7 @@ class DetID static constexpr std::string_view NONE{"none"}; ///< keywork for no-detector static constexpr std::string_view ALL{"all"}; ///< keywork for all detectors - typedef std::bitset mask_t; + typedef std::bitset<32> mask_t; DetID(ID id) : mID(id) {} DetID(const char* name); @@ -164,7 +164,7 @@ class DetID #endif }; - ClassDefNV(DetID, 1); + ClassDefNV(DetID, 2); }; } // namespace detectors diff --git a/DataFormats/Detectors/Common/src/DetID.cxx b/DataFormats/Detectors/Common/src/DetID.cxx index f54cbee911410..a9834373c619f 100644 --- a/DataFormats/Detectors/Common/src/DetID.cxx +++ b/DataFormats/Detectors/Common/src/DetID.cxx @@ -45,7 +45,7 @@ DetID::mask_t DetID::getMask(const std::string_view detList) return mask; } if (ss.find(ALL) != std::string::npos) { - mask.set(); + mask = (0x1u << nDetectors) - 1; return mask; } std::replace(ss.begin(), ss.end(), ' ', ','); diff --git a/DataFormats/Parameters/include/DataFormatsParameters/GRPObject.h b/DataFormats/Parameters/include/DataFormatsParameters/GRPObject.h index 6e001febe44ae..a8e7e2142590b 100644 --- a/DataFormats/Parameters/include/DataFormatsParameters/GRPObject.h +++ b/DataFormats/Parameters/include/DataFormatsParameters/GRPObject.h @@ -164,7 +164,7 @@ class GRPObject std::string mDataPeriod = ""; ///< name of the period std::string mLHCState = ""; ///< machine state - ClassDefNV(GRPObject, 3); + ClassDefNV(GRPObject, 4); }; //______________________________________________ From 728bd899b4f7affbc1a48c21bd5912fd9d3ac80a Mon Sep 17 00:00:00 2001 From: shahoian Date: Tue, 13 Apr 2021 11:03:55 +0200 Subject: [PATCH 109/770] Update doc/DetectorSimulation.md by details of HBFUtils usage --- doc/DetectorSimulation.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/doc/DetectorSimulation.md b/doc/DetectorSimulation.md index ce934266a40f9..e75cbe9bf7507 100644 --- a/doc/DetectorSimulation.md +++ b/doc/DetectorSimulation.md @@ -361,13 +361,37 @@ Digitization - the transformation of hits produced in the transport simulation t | --sims | Comma separated list of simulation prefixes that should be overlaid/embedded. Example `--sims background,signal` where `background` and `signal` refer to transport simulation productions. Final collisions will be composed from both of them (in a round robin fashion). See separate section about [Embedding](#Embedding) for more details. If just one prefix is given, normal digitization without overlay will be done. | | --tpc-lanes | Number of parallel digitizers for TPC, which has a special attention due an increased data rate compared to other detectors. | | | --interactionRate | Total hadronic interaction rate (Hz). | -| --bcPatternFile | Interacting BC pattern file chaning the default bunch crossing pattern. | +| --bcPatternFile | Interacting BC pattern file chaning the default bunch crossing pattern, see `macro/CreateBCPattern.C` for details. | | --onlyDet | Comma separated list of detectors to digitize. (Default is all) | | --skipDet | Comma separed list of detectors to exclude. | | --incontext | Name of context file. Useful for reusing a context from a previous run when we split the processing detectorwise. | | --outcontext | Specify name of contextfile to produce. | | --simFileQED | Optional special QED hit file to include effect from QED effects into digitization. | +## Interaction sampling + +The files produced by the `o2-sim` contain only a set of separate events, w/o any time stamp. The digitization will sample the vector of non-decreasing `{BC/orbit}` pairs according to bunch filling schema and requested interaction rate and provide it to digitizers. +The interaction sampling is steered by the `HBFUtils` configurable parameters, e.g. + +```o2-sim-digitizer-workflow --configKeyValues "HBFUtils.nHBFPerTF=128;HBFUtils.orbitFirst=123;HBFUtils.orbitFirstSampled=300"``` + +The most important here is `HBFUtils.orbitFirstSampled` which tells to `InteractionSampler` the orbit from which the sampling should start. +Other parameters, `nHBFPerTF` and `orbitFirst` do not directly affect the digitization but they are stored in the `grp` object (`o2sim_grp.root` file) and the number of orbits per TF and the 1st orbit of the run. +The full content of the `HBFUtils` is stored in the `o2simdigitizerworkflow_configuration.ini` and can be used in reconstruction and MC->raw-data creation processes. +Particularly, when creating the raw data (see `...-digi2raw` group of commands in `O2/prodtests/full_system_test.sh`) the content of the `HBFUtils` settings will be loaded from this ini file +(the name can be changed via `--hbfutils-config ` option) and `HBFUtils.orbitFirst` will be used to define the start-of-the-run (`SOX flag in the RDH`) and `HBFUtils.nHBFPerTF` will be used to chop the digitized data to TFs. +Note that for the detectors in continuous readout mode all empty HBFs will be created for all orbits w/o detector data between the `SOX` and the last orbit of the TF for which data was received. +In case you want to create raw data starting from the 1st sampled TF, you should override the `HBFUtils.orbitFirst` by the wanted orbit, i.e. for the digitization done as in the example above +one can request + +```o2-ft0-digi2raw --configKeyValues "HBFUtils.orbitFirst=251" ...``` + +to start the raw data not from the orbit 123 indicated during digitization but from the orbit 251 (i.e. the 2nd TF of the run). Additional setting `HBFUtils.maxNOrbits` can be provided +to limit the number of orbits stored (counted from the `SOX`) in the raw data (i.e. all data with `orbit > HBFUtils.orbitFirst + HBFUtils.maxNOrbits` will be ignored when creating the raw data. + +Similarly, when running the reconstruction workflow using the output of the digitization, the `HBFUtils` settings used by `o2-sim-digitizer-workflow` will be loaded (again, they can be overridden +by either providing `--hbfutils-config ` option or by explicit `--configKeyValues "HBFUtils...` setting) and the DPL will make sure that the content of the `DataHeader.firstTForbit` correspond +to the 1st orbit of the TF containing `HBFUtils.orbitFirstSampled` (then incremented by `HBFUtils.nHBFPerTF` for the following TFs if the digits files contain multiple TF entries). ## Embedding From a71c7cbd5d954a88c89e36c869bde20667d10773 Mon Sep 17 00:00:00 2001 From: Laurent Aphecetche Date: Mon, 22 Mar 2021 18:13:31 +0100 Subject: [PATCH 110/770] [MCH] [MRRTF-110] Convert bad channel Root file to CSV To be used by the DCS central service which reads the CCDB and feeds the Oracle DB. --- DataFormats/Detectors/MUON/MCH/CMakeLists.txt | 5 ++ .../MUON/MCH/src/convert-bad-channels.cxx | 84 +++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 DataFormats/Detectors/MUON/MCH/src/convert-bad-channels.cxx diff --git a/DataFormats/Detectors/MUON/MCH/CMakeLists.txt b/DataFormats/Detectors/MUON/MCH/CMakeLists.txt index c8eca994138e6..094a815c5cad5 100644 --- a/DataFormats/Detectors/MUON/MCH/CMakeLists.txt +++ b/DataFormats/Detectors/MUON/MCH/CMakeLists.txt @@ -17,3 +17,8 @@ o2_target_root_dictionary(DataFormatsMCH include/DataFormatsMCH/DsChannelGroup.h include/DataFormatsMCH/ROFRecord.h include/DataFormatsMCH/TrackMCH.h) + +o2_add_executable(convert-bad-channels + SOURCES src/convert-bad-channels.cxx + COMPONENT_NAME mch + PUBLIC_LINK_LIBRARIES O2::DataFormatsMCH Boost::program_options) diff --git a/DataFormats/Detectors/MUON/MCH/src/convert-bad-channels.cxx b/DataFormats/Detectors/MUON/MCH/src/convert-bad-channels.cxx new file mode 100644 index 0000000000000..a66c437ad7efe --- /dev/null +++ b/DataFormats/Detectors/MUON/MCH/src/convert-bad-channels.cxx @@ -0,0 +1,84 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include +#include +#include +#include +#include +#include +#include "DataFormatsMCH/DsChannelGroup.h" + +namespace po = boost::program_options; + +int convertRootToCSV(const std::string rootFileName) +{ + TFile* f = TFile::Open(rootFileName.c_str()); + if (f->IsZombie()) { + throw std::runtime_error("can not open " + rootFileName); + } + auto dsChannelGroup = reinterpret_cast(f->Get("ccdb_object")); + auto channels = dsChannelGroup->getChannels(); + + std::cout << fmt::format("solarid,dsid,ch\n"); + + for (auto c : channels) { + std::cout << fmt::format("{},{},{}\n", + c.getSolarId(), c.getDsId(), c.getChannel()); + } + + delete f; + return 0; +} + +int main(int argc, char** argv) +{ + po::variables_map vm; + po::options_description options; + + // clang-format off + options.add_options() + ("help,h","help") + ("input",po::value()->required(),"path to input root file to be converted to csv"); + // clang-format on + + po::options_description cmdline; + cmdline.add(options); + + po::store(po::command_line_parser(argc, argv).options(cmdline).run(), vm); + + if (vm.count("help")) { + std::cout << R"( +This program converts a Root file containing bad channels information into the +same information in CSV format. + +The output file format is : + +solarid, dsid, ch + +where solarid, dsid and ch are integers. + +)"; + std::cout + << options << "\n"; + std::cout << "\n"; + return 2; + } + + try { + po::notify(vm); + } catch (boost::program_options::error& e) { + std::cout << "Error: " << e.what() << "\n"; + std::cout << options << "\n"; + exit(1); + } + + return convertRootToCSV(vm["input"].as()); +} From 25adee11d1834c882eb8c435ea5dbb8d58103608 Mon Sep 17 00:00:00 2001 From: Laurent Aphecetche Date: Fri, 2 Apr 2021 16:09:37 +0200 Subject: [PATCH 111/770] [MRRTF-114] [MCH] Add MCHDigitIO debug library. --- .../MUON/MCH/include/DataFormatsMCH/Digit.h | 2 +- DataFormats/Detectors/MUON/MCH/src/Digit.cxx | 7 +- Detectors/MUON/MCH/CMakeLists.txt | 1 + Detectors/MUON/MCH/DevIO/CMakeLists.txt | 11 + .../MUON/MCH/DevIO/Digits/CMakeLists.txt | 54 ++++ Detectors/MUON/MCH/DevIO/Digits/DigitD0.h | 32 ++ .../MUON/MCH/DevIO/Digits/DigitFileFormat.cxx | 74 +++++ .../MUON/MCH/DevIO/Digits/DigitFileFormat.h | 50 +++ Detectors/MUON/MCH/DevIO/Digits/DigitIO.h | 14 + .../MUON/MCH/DevIO/Digits/DigitIOBaseTask.cxx | 87 ++++++ .../MUON/MCH/DevIO/Digits/DigitIOBaseTask.h | 90 ++++++ Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.cxx | 95 ++++++ Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.h | 58 ++++ Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.cxx | 100 ++++++ Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.h | 42 +++ .../MUON/MCH/DevIO/Digits/DigitReader.cxx | 72 +++++ Detectors/MUON/MCH/DevIO/Digits/DigitReader.h | 82 +++++ .../MUON/MCH/DevIO/Digits/DigitReaderImpl.cxx | 64 ++++ .../MUON/MCH/DevIO/Digits/DigitReaderImpl.h | 63 ++++ .../MUON/MCH/DevIO/Digits/DigitWriter.cxx | 91 ++++++ Detectors/MUON/MCH/DevIO/Digits/DigitWriter.h | 66 ++++ .../MUON/MCH/DevIO/Digits/DigitWriterImpl.cxx | 32 ++ .../MUON/MCH/DevIO/Digits/DigitWriterImpl.h | 53 ++++ Detectors/MUON/MCH/DevIO/Digits/ProgOptions.h | 27 ++ Detectors/MUON/MCH/DevIO/Digits/README.md | 87 ++++++ .../MUON/MCH/DevIO/Digits/TestFileV0.cxx | 94 ++++++ Detectors/MUON/MCH/DevIO/Digits/TestFileV0.h | 14 + .../MCH/DevIO/Digits/digits-file-dumper.cxx | 107 +++++++ .../Digits/digits-file-reader-workflow.cxx | 159 ++++++++++ .../MCH/DevIO/Digits/digits-r23-workflow.cxx | 83 +++++ .../DevIO/Digits/digits-writer-workflow.cxx | 176 +++++++++++ .../MUON/MCH/DevIO/Digits/testDigitIO.cxx | 286 ++++++++++++++++++ .../MUON/MCH/DevIO/Digits/testDigitIOV0.cxx | 151 +++++++++ Detectors/MUON/MCH/DevIO/README.md | 9 + Detectors/MUON/MCH/README.md | 1 + 35 files changed, 2430 insertions(+), 4 deletions(-) create mode 100644 Detectors/MUON/MCH/DevIO/CMakeLists.txt create mode 100644 Detectors/MUON/MCH/DevIO/Digits/CMakeLists.txt create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitD0.h create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitFileFormat.cxx create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitFileFormat.h create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitIO.h create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitIOBaseTask.cxx create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitIOBaseTask.h create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.cxx create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.h create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.cxx create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.h create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitReader.cxx create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitReader.h create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.cxx create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.h create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitWriter.cxx create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitWriter.h create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitWriterImpl.cxx create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitWriterImpl.h create mode 100644 Detectors/MUON/MCH/DevIO/Digits/ProgOptions.h create mode 100644 Detectors/MUON/MCH/DevIO/Digits/README.md create mode 100644 Detectors/MUON/MCH/DevIO/Digits/TestFileV0.cxx create mode 100644 Detectors/MUON/MCH/DevIO/Digits/TestFileV0.h create mode 100644 Detectors/MUON/MCH/DevIO/Digits/digits-file-dumper.cxx create mode 100644 Detectors/MUON/MCH/DevIO/Digits/digits-file-reader-workflow.cxx create mode 100644 Detectors/MUON/MCH/DevIO/Digits/digits-r23-workflow.cxx create mode 100644 Detectors/MUON/MCH/DevIO/Digits/digits-writer-workflow.cxx create mode 100644 Detectors/MUON/MCH/DevIO/Digits/testDigitIO.cxx create mode 100644 Detectors/MUON/MCH/DevIO/Digits/testDigitIOV0.cxx create mode 100644 Detectors/MUON/MCH/DevIO/README.md diff --git a/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/Digit.h b/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/Digit.h index 2454fffd29930..0be8764a664d7 100644 --- a/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/Digit.h +++ b/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/Digit.h @@ -30,7 +30,7 @@ class Digit public: Digit() = default; - Digit(int detid, int pad, uint32_t adc, int32_t time, uint16_t nSamples = 1); + Digit(int detid, int pad, uint32_t adc, int32_t time, uint16_t nSamples = 1, bool saturated = false); ~Digit() = default; bool operator==(const Digit&) const; diff --git a/DataFormats/Detectors/MUON/MCH/src/Digit.cxx b/DataFormats/Detectors/MUON/MCH/src/Digit.cxx index 57144e005fbec..c0e5106cc6f04 100644 --- a/DataFormats/Detectors/MUON/MCH/src/Digit.cxx +++ b/DataFormats/Detectors/MUON/MCH/src/Digit.cxx @@ -19,10 +19,11 @@ bool closeEnough(double x, double y, double eps = 1E-6) return std::fabs(x - y) <= eps * std::max(1.0, std::max(std::fabs(x), std::fabs(y))); } -Digit::Digit(int detid, int pad, uint32_t adc, int32_t time, uint16_t nSamples) - : mTFtime(time), mNofSamples(nSamples), mDetID(detid), mPadID(pad), mADC(adc) +Digit::Digit(int detid, int pad, uint32_t adc, int32_t time, uint16_t nSamples, bool saturated) + : mTFtime(time), mDetID(detid), mPadID(pad), mADC(adc) { - setSaturated(false); + setNofSamples(nSamples); + setSaturated(saturated); } void Digit::setNofSamples(uint16_t n) diff --git a/Detectors/MUON/MCH/CMakeLists.txt b/Detectors/MUON/MCH/CMakeLists.txt index 53defca113a8c..f7ed4c12ed1a7 100644 --- a/Detectors/MUON/MCH/CMakeLists.txt +++ b/Detectors/MUON/MCH/CMakeLists.txt @@ -20,3 +20,4 @@ add_subdirectory(Raw) add_subdirectory(Workflow) add_subdirectory(Conditions) add_subdirectory(Calibration) +add_subdirectory(DevIO) diff --git a/Detectors/MUON/MCH/DevIO/CMakeLists.txt b/Detectors/MUON/MCH/DevIO/CMakeLists.txt new file mode 100644 index 0000000000000..13685eb8e0cb3 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/CMakeLists.txt @@ -0,0 +1,11 @@ +# Copyright CERN and copyright holders of ALICE O2. This software is distributed +# under the terms of the GNU General Public License v3 (GPL Version 3), copied +# verbatim in the file "COPYING". +# +# See http://alice-o2.web.cern.ch/license for full licensing information. +# +# In applying this license CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization or +# submit itself to any jurisdiction. + +add_subdirectory(Digits) diff --git a/Detectors/MUON/MCH/DevIO/Digits/CMakeLists.txt b/Detectors/MUON/MCH/DevIO/Digits/CMakeLists.txt new file mode 100644 index 0000000000000..8bee62acd48b2 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/CMakeLists.txt @@ -0,0 +1,54 @@ +# Copyright CERN and copyright holders of ALICE O2. This software is distributed +# under the terms of the GNU General Public License v3 (GPL Version 3), copied +# verbatim in the file "COPYING". +# +# See http://alice-o2.web.cern.ch/license for full licensing information. +# +# In applying this license CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization or +# submit itself to any jurisdiction. + +o2_add_library(MCHDigitIO + SOURCES DigitWriter.cxx DigitReader.cxx DigitFileFormat.cxx + DigitReaderImpl.cxx DigitWriterImpl.cxx + DigitIOV0.cxx DigitIOV1.cxx + PUBLIC_LINK_LIBRARIES ms_gsl::ms_gsl fmt::fmt O2::DataFormatsMCH) + +o2_add_test(digits-io + SOURCES testDigitIO.cxx + COMPONENT_NAME mch + LABELS muon;mch + PUBLIC_LINK_LIBRARIES O2::MCHDigitIO) + +o2_add_test(digits-io-v0 + SOURCES testDigitIOV0.cxx TestFileV0.cxx + COMPONENT_NAME mch + LABELS muon;mch + PUBLIC_LINK_LIBRARIES O2::MCHDigitIO) + +o2_add_executable(digits-r23-workflow + SOURCES digits-r23-workflow.cxx + COMPONENT_NAME mch + PUBLIC_LINK_LIBRARIES O2::Framework O2::DataFormatsMCH + O2::MCHBase O2::MCHMappingImpl3) + +o2_add_executable( + digits-writer-workflow + SOURCES digits-writer-workflow.cxx DigitIOBaseTask.cxx + COMPONENT_NAME mch + PUBLIC_LINK_LIBRARIES O2::Framework O2::DPLUtils Boost::program_options + O2::MCHBase O2::MCHRawDecoder O2::DataFormatsMCH + O2::MCHDigitIO) + +o2_add_executable( + digits-file-reader-workflow + SOURCES digits-file-reader-workflow.cxx DigitIOBaseTask.cxx + COMPONENT_NAME mch + PUBLIC_LINK_LIBRARIES O2::Framework O2::DataFormatsMCH O2::MCHBase O2::MCHDigitIO) + +o2_add_executable( + digits-file-dumper + SOURCES digits-file-dumper.cxx + COMPONENT_NAME mch + PUBLIC_LINK_LIBRARIES O2::MCHDigitIO O2::MCHMappingImpl3 Boost::program_options) + diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitD0.h b/Detectors/MUON/MCH/DevIO/Digits/DigitD0.h new file mode 100644 index 0000000000000..6986b16ba016c --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitD0.h @@ -0,0 +1,32 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#pragma once + +#include +#include + +namespace o2::mch::io::impl +{ +struct DigitD0 { + int32_t tfTime; /// time since the beginning of the time frame, in bunch crossing units + uint16_t nofSamples; /// number of samples in the signal + saturated bit + int detID; /// ID of the Detection Element to which the digit corresponds to + int padID; /// PadIndex to which the digit corresponds to + uint32_t adc; /// Amplitude of signal + + void setNofSamples(uint16_t n) { nofSamples = (nofSamples & 0x8000) + (n & 0x7FFF); } + uint16_t getNofSamples() const { return (nofSamples & 0x7FFF); } + + void setSaturated(bool sat) { nofSamples = sat ? nofSamples | 0x8000 : nofSamples & 0x7FFF; } + bool isSaturated() const { return ((nofSamples & 0x8000) > 0); } +}; + +} // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitFileFormat.cxx b/Detectors/MUON/MCH/DevIO/Digits/DigitFileFormat.cxx new file mode 100644 index 0000000000000..4ad0ff8463f94 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitFileFormat.cxx @@ -0,0 +1,74 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "DigitFileFormat.h" +#include +#include +#include +#include + +namespace o2::mch::io +{ + +std::array digitFileFormats = { + DigitFileFormat{2305844383603244847}, + DigitFileFormat{1224998065220435759}}; + +std::ostream& operator<<(std::ostream& os, const DigitFileFormat& dff) +{ + os << fmt::format( + "[ file version {} digit version {} size {} " + "rof version {} size {} hasRof {} run2ids {} ] formatWord {}", + dff.fileVersion, + dff.digitVersion, + dff.digitSize, + dff.rofVersion, + dff.rofSize, + static_cast(dff.hasRof), + static_cast(dff.run2ids), + dff.format); + return os; +} + +bool operator==(const DigitFileFormat& dff1, const DigitFileFormat& dff2) +{ + return dff1.format == dff2.format; +} + +bool operator!=(const DigitFileFormat& dff1, const DigitFileFormat& dff2) +{ + return !(dff1 == dff2); +} + +/* Read the file format from the stream. +* +* Every digit file should start with 8 bytes of format identifier. +*/ +DigitFileFormat readDigitFileFormat(std::istream& in) +{ + uint64_t fileFormat{0}; + in.read(reinterpret_cast(&fileFormat), sizeof(uint64_t)); + if (in.gcount() < sizeof(DigitFileFormat)) { + throw std::ios_base::failure("could not get a valid digit file format in this stream (too short)"); + } + DigitFileFormat df{fileFormat}; + if (!isValid(df)) { + throw std::ios_base::failure("could not get a valid digit file format in this stream"); + } + return df; +} + +bool isValid(DigitFileFormat dff) +{ + auto exists = std::find(digitFileFormats.begin(), + digitFileFormats.end(), dff); + return exists != digitFileFormats.end(); +} +} // namespace o2::mch::io diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitFileFormat.h b/Detectors/MUON/MCH/DevIO/Digits/DigitFileFormat.h new file mode 100644 index 0000000000000..7663e7a34ab77 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitFileFormat.h @@ -0,0 +1,50 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#pragma once + +#include +#include +#include + +namespace o2::mch::io +{ + +constexpr uint64_t TAG_DIGITS = 0x3F2F; // = 016175 = 0.1.6.1.7.5 = D.I.G.I.T.S + +struct DigitFileFormat { + union { + uint64_t format = TAG_DIGITS; + struct { + uint64_t tag : 16; + uint64_t fileVersion : 8; + uint64_t reserved : 4; + uint64_t digitVersion : 8; + uint64_t digitSize : 8; + uint64_t rofVersion : 8; + uint64_t rofSize : 8; + uint64_t hasRof : 1; + uint64_t run2ids : 1; + }; + }; +}; + +extern std::array digitFileFormats; + +std::ostream& operator<<(std::ostream&, const DigitFileFormat&); + +bool operator==(const DigitFileFormat& dff1, const DigitFileFormat& dff2); +bool operator!=(const DigitFileFormat& dff1, const DigitFileFormat& dff2); + +DigitFileFormat readDigitFileFormat(std::istream& in); + +bool isValid(DigitFileFormat dff); + +} // namespace o2::mch::io diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitIO.h b/Detectors/MUON/MCH/DevIO/Digits/DigitIO.h new file mode 100644 index 0000000000000..cefe1832a8502 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitIO.h @@ -0,0 +1,14 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#pragma once + +#include "DigitReader.h" +#include "DigitWriter.h" diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitIOBaseTask.cxx b/Detectors/MUON/MCH/DevIO/Digits/DigitIOBaseTask.cxx new file mode 100644 index 0000000000000..f8324878fb0a2 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitIOBaseTask.cxx @@ -0,0 +1,87 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "DataFormatsMCH/Digit.h" +#include "DataFormatsMCH/ROFRecord.h" +#include "DigitIOBaseTask.h" +#include "DigitWriter.h" +#include +#include "Framework/ConfigParamRegistry.h" +#include "Framework/InitContext.h" +#include "Framework/Logger.h" +#include "Framework/Variant.h" +#include "ProgOptions.h" +#include +#include +#include + +using namespace o2::framework; + +namespace o2::mch::io +{ +void DigitIOBaseTask::init(InitContext& ic) +{ + mMaxNofTimeFrames = ic.options().get(OPTNAME_MAX_NOF_TFS); + mFirstTF = ic.options().get(OPTNAME_FIRST_TF); + mNofProcessedTFs = 0; + mPrintDigits = ic.options().get(OPTNAME_PRINT_DIGITS); + mPrintTFs = ic.options().get(OPTNAME_PRINT_TFS); + if (mPrintDigits || mPrintTFs) { + fair::Logger::SetConsoleColor(true); + } +} + +void DigitIOBaseTask::printFull(gsl::span digits, + gsl::span rofs) const +{ + if (mPrintDigits) { + std::stringstream str; + o2::mch::io::DigitWriter dw(str); + dw.write(digits, rofs); + for (std::string line; std::getline(str, line);) { + LOG(INFO) << line; + } + } +} + +void DigitIOBaseTask::printSummary(gsl::span digits, + gsl::span rofs, + const char* suffix) const +{ + if (mPrintTFs) { + LOGP(INFO, "TF {:5d} {:4d} rofs - {:6d} digits - {}", mTFid, rofs.size(), digits.size(), suffix); + } +} + +bool DigitIOBaseTask::shouldProcess() const +{ + return (mTFid >= mFirstTF && mNofProcessedTFs < mMaxNofTimeFrames); +} + +void DigitIOBaseTask::incNofProcessedTFs() +{ + ++mNofProcessedTFs; +} + +void DigitIOBaseTask::incTFid() +{ + ++mTFid; +} + +std::vector getCommonOptions() +{ + return { + {OPTNAME_MAX_NOF_TFS, VariantType::Int, std::numeric_limits::max(), {OPTHELP_MAX_NOF_TFS}}, + {OPTNAME_FIRST_TF, VariantType::Int, 0, {OPTHELP_FIRST_TF}}, + {OPTNAME_PRINT_DIGITS, VariantType::Bool, false, {OPTHELP_PRINT_DIGITS}}, + {OPTNAME_PRINT_TFS, VariantType::Bool, false, {OPTHELP_PRINT_TFS}}}; +} + +} // namespace o2::mch::io diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitIOBaseTask.h b/Detectors/MUON/MCH/DevIO/Digits/DigitIOBaseTask.h new file mode 100644 index 0000000000000..3c553c9147c1e --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitIOBaseTask.h @@ -0,0 +1,90 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#pragma once + +#include "Framework/ConfigParamSpec.h" +#include +#include +#include +#include + +namespace o2::framework +{ +class InitContext; +} // namespace o2::framework + +namespace o2::mch +{ +class Digit; +class ROFRecord; +}; // namespace o2::mch + +namespace o2::mch::io +{ + +/** + * DigitIOBaseTask implements the commonalities between reader and writer + * tasks, like the handling of the common options. + */ + +class DigitIOBaseTask +{ + protected: + size_t mMaxNofTimeFrames{std::numeric_limits::max()}; // max number of timeframes to process + size_t mNofProcessedTFs{0}; // actual number of timeframes processed so far + size_t mFirstTF{0}; // first timeframe to process + size_t mTFid{0}; // current timeframe index + bool mPrintDigits = false; // print digits + bool mPrintTFs = false; // print number of rofs and digits per tf + + public: + /** + * Init data members from options + */ + void init(o2::framework::InitContext& ic); + + /** + * Make a full screen dump of the digits and rofs arrays. + */ + void printFull(gsl::span digits, + gsl::span rofs) const; + + /** + * Make a brief screen dump of the digits and rofs arrays (just showing + * number of items in each) + */ + void printSummary(gsl::span digits, + gsl::span rofs, + const char* suffix = "") const; + + /** + * Decide, depending on the current TFid being processed, if it should + * be processed or not. + */ + bool shouldProcess() const; + + /** + * Increment the number of timeframes that have been processed so far. + */ + void incNofProcessedTFs(); + + /** + * Increment the timeframe id (last one that has been processed). + */ + void incTFid(); +}; + +/** + * Define commonly used options, like max number of tfs, first tf, etc... + */ +std::vector getCommonOptions(); + +} // namespace o2::mch::io diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.cxx b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.cxx new file mode 100644 index 0000000000000..60ad76e758130 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.cxx @@ -0,0 +1,95 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "DigitIOV0.h" +#include "DigitD0.h" +#include +#include +#include "DataFormatsMCH/Digit.h" +#include "DataFormatsMCH/ROFRecord.h" +#include +#include +#include "DigitFileFormat.h" +#include "CommonDataFormat/InteractionRecord.h" + +// +// V0 was prior to the introduction of rofs, so the file format is +// simply a set of consecutive [nofDigits|list of digits] blocks +// + +namespace o2::mch::io::impl +{ +void DigitReaderV0::count(std::istream& in, size_t& ntfs, size_t& nrofs, size_t& ndigits) +{ + rewind(in); + ndigits = 0; + nrofs = 0; + ntfs = 0; + int ndig{0}; + auto dff = digitFileFormats[0]; + + while ((ndig = advance(in, dff.digitSize, "digits")) >= 0) { + ndigits += ndig; + ++nrofs; + ++ntfs; + } + rewind(in); +} + +bool DigitReaderV0::read(std::istream& in, + std::vector& digits, + std::vector& rofs) +{ + // note the input vectors are not cleared as this is the responsability + // of the calling class, if need be. + std::vector digitsd0; + bool ok = readBinary(in, digitsd0, "digits"); + if (!ok) { + return false; + } + + for (auto d0 : digitsd0) { + Digit d(d0.detID, d0.padID, d0.adc, d0.tfTime, d0.getNofSamples(), d0.isSaturated()); + digits.push_back(d); + } + + rofs.emplace_back(o2::InteractionRecord(0, mCurrentROF), 0, digits.size()); + ++mCurrentROF; + return true; +} + +void DigitReaderV0::rewind(std::istream& in) +{ + DigitReaderImpl::rewind(in); + mCurrentROF = 0; +} + +bool DigitWriterV0::write(std::ostream& out, + gsl::span digits, + gsl::span rofs) +{ + // V0 format had no notion of rofs, so we strip them + for (auto r : rofs) { + std::vector digitsd0; + for (int i = r.getFirstIdx(); i <= r.getLastIdx(); i++) { + const Digit& d = digits[i]; + digitsd0.push_back(DigitD0{d.getTime(), d.nofSamples(), d.getDetID(), d.getPadID(), d.getADC()}); + digitsd0.back().setSaturated(d.isSaturated()); + } + gsl::span d0(digitsd0); + bool ok = binary(out, d0); + if (!ok) { + return false; + } + } + return true; +} + +} // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.h b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.h new file mode 100644 index 0000000000000..25f1bed42a0b9 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.h @@ -0,0 +1,58 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#pragma once + +#include "DigitReaderImpl.h" +#include "DigitWriterImpl.h" +#include +#include + +/* + * Digit file format 0 is storing Digits version D0 + * with no ROF (i.e. just a set of nDigits|DigitsD0|...) + */ + +namespace o2::mch::io::impl +{ +/** + * Reader for digit file format 0 + */ +class DigitReaderV0 : public DigitReaderImpl +{ + public: + void count(std::istream& in, size_t& ntfs, size_t& nrofs, size_t& ndigits) override; + bool read(std::istream& in, + std::vector& digits, + std::vector& rofs) override; + void rewind(std::istream& in); + + private: + int mCurrentROF{0}; +}; + +/** + * Writer for digit file format 0 + */ +struct DigitWriterV0 : public DigitWriterImpl { + + /** write rofs, digits at the current position in the output stream + * @param digits vector of Digits, must not be empty + * @param rofs vector of ROFRecord, might be empty + * @returns true if writing was successull, false otherwise + */ + bool write(std::ostream& out, + gsl::span digits, + gsl::span rofs) override; + + bool mBinary; +}; + +} // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.cxx b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.cxx new file mode 100644 index 0000000000000..b6f2942e5c742 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.cxx @@ -0,0 +1,100 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "DigitIOV1.h" +#include "DigitD0.h" +#include "DataFormatsMCH/Digit.h" +#include "DataFormatsMCH/ROFRecord.h" +#include "DigitFileFormat.h" +#include "DigitReader.h" +#include + +namespace +{ +std::pair advanceOneEvent(std::istream& in) +{ + int nrofs = o2::mch::io::impl::advance(in, sizeof(o2::mch::ROFRecord), "rofs"); + if (nrofs < 0) { + return std::make_pair(-1, -1); + } + int ndigits = o2::mch::io::impl::advance(in, sizeof(o2::mch::io::impl::DigitD0), "digits"); + return std::make_pair(nrofs, ndigits); +} +} // namespace + +namespace o2::mch::io::impl +{ +void DigitReaderV1::count(std::istream& in, size_t& ntfs, size_t& nrofs, size_t& ndigits) +{ + rewind(in); + ndigits = 0; + nrofs = 0; + ntfs = 0; + std::pair pairs; + std::pair invalid{-1, -1}; + + while ((pairs = advanceOneEvent(in)) != invalid) { + ndigits += pairs.second; + nrofs += pairs.first; + ++ntfs; + } + rewind(in); +} + +bool DigitReaderV1::read(std::istream& in, + std::vector& digits, + std::vector& rofs) +{ + // note the input vectors are not cleared as this is the responsability + // of the calling class, if need be. + + bool ok = readBinary(in, rofs, "rofs"); + if (!ok) { + return false; + } + std::vector digitsd0; + + ok = readBinary(in, digitsd0, "digits"); + if (!ok) { + return false; + } + + for (auto d0 : digitsd0) { + Digit d(d0.detID, d0.padID, d0.adc, d0.tfTime, d0.getNofSamples(), d0.isSaturated()); + digits.push_back(d); + } + return true; +} + +void DigitReaderV1::rewind(std::istream& in) +{ + DigitReaderImpl::rewind(in); +} + +bool DigitWriterV1::write(std::ostream& out, + gsl::span digits, + gsl::span rofs) +{ + if (rofs.empty()) { + return false; + } + bool ok = impl::binary(out, rofs); + + std::vector digitsd0; + for (const auto& d : digits) { + digitsd0.push_back(DigitD0{d.getTime(), d.nofSamples(), d.getDetID(), d.getPadID(), d.getADC()}); + digitsd0.back().setSaturated(d.isSaturated()); + } + gsl::span d0(digitsd0); + ok &= impl::binary(out, d0); + return ok; +} + +} // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.h b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.h new file mode 100644 index 0000000000000..cadb17a201159 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.h @@ -0,0 +1,42 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#pragma once + +#include "DigitReaderImpl.h" +#include +#include "DataFormatsMCH/ROFRecord.h" +#include +#include "DigitWriterImpl.h" + +namespace o2::mch::io::impl +{ +class DigitReaderV1 : public DigitReaderImpl +{ + public: + void count(std::istream& in, size_t& ntfs, size_t& nrofs, size_t& ndigits) override; + bool read(std::istream& in, + std::vector& digits, + std::vector& rofs) override; + void rewind(std::istream& in); +}; + +struct DigitWriterV1 : public DigitWriterImpl { + /** write rofs, digits at the current position in the output stream + * @param digits vector of Digits, must not be empty + * @param rofs vector of ROFRecord, might be empty + * @returns true if writing was successull, false otherwise + */ + bool write(std::ostream& out, + gsl::span digits, + gsl::span rofs) override; +}; + +} // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitReader.cxx b/Detectors/MUON/MCH/DevIO/Digits/DigitReader.cxx new file mode 100644 index 0000000000000..0b1da7c7a3bff --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitReader.cxx @@ -0,0 +1,72 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "DigitReader.h" +#include +#include "DigitFileFormat.h" +#include +#include "DataFormatsMCH/Digit.h" +#include "DataFormatsMCH/ROFRecord.h" +#include +#include "DigitReaderImpl.h" + +namespace o2::mch::io +{ + +DigitReader::DigitReader(std::istream& in) : mInput{in} +{ + mFileFormat = readDigitFileFormat(mInput); + mImpl = impl::createDigitReaderImpl(mFileFormat.fileVersion); +} + +DigitReader::~DigitReader() = default; + +bool DigitReader::read(std::vector& digits, + std::vector& rofs) +{ + digits.clear(); + rofs.clear(); + bool ok = mImpl->read(mInput, digits, rofs); + return ok; +} + +void DigitReader::rewind() +{ + mImpl->rewind(mInput); +} + +void DigitReader::count() const +{ + if (mCountDone) { + return; + } + mImpl->count(mInput, mNofTimeFrames, mNofROFs, mNofDigits); + mCountDone = true; +} + +size_t DigitReader::nofTimeFrames() const +{ + count(); + return mNofTimeFrames; +} + +size_t DigitReader::nofROFs() const +{ + count(); + return mNofROFs; +} + +size_t DigitReader::nofDigits() const +{ + count(); + return mNofDigits; +} + +} // namespace o2::mch::io diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitReader.h b/Detectors/MUON/MCH/DevIO/Digits/DigitReader.h new file mode 100644 index 0000000000000..c734291b8aa21 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitReader.h @@ -0,0 +1,82 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#pragma once + +#include +#include "DigitFileFormat.h" +#include +#include + +namespace o2::mch +{ +class Digit; +class ROFRecord; +} // namespace o2::mch + +namespace o2::mch::io +{ +namespace impl +{ +class DigitReaderImpl; +} +class DigitReader +{ + public: + DigitReader(std::istream& in); + + /* defined in the implementation file, where mImpl is a complete type */ + ~DigitReader(); + + /** Which file format has been detected */ + DigitFileFormat fileFormat() const { return mFileFormat; } + + /** read rofs, digits at the current position in the input stream. + * i.e. reads one full time frame. + * + * @param digits vector of Digits + * @param rofs vector of ROFRecord + * @returns true if reading was successull, false otherwise + */ + bool read(std::vector& digits, + std::vector& rofs); + + /** Count the number of timeframes in the input stream. + * WARNING : depending on the size of the input this might be a + * costly operation */ + size_t nofTimeFrames() const; + + /** Count the number of ROFRecords in the input stream + * WARNING : depending on the size of the input this might be a + * costly operation */ + size_t nofROFs() const; + + /** Count the number of digits in the input stream + * WARNING : depending on the size of the input this might be a + * costly operation */ + size_t nofDigits() const; + + /** Rewind, aka restart reading from the beginning of the stream */ + void rewind(); + + private: + void count() const; + + private: + std::istream& mInput; + DigitFileFormat mFileFormat; + std::unique_ptr mImpl; + mutable size_t mNofTimeFrames{0}; + mutable size_t mNofROFs{0}; + mutable size_t mNofDigits{0}; + mutable bool mCountDone{false}; +}; + +} // namespace o2::mch::io diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.cxx b/Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.cxx new file mode 100644 index 0000000000000..f4a69450cc5e1 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.cxx @@ -0,0 +1,64 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "DigitReaderImpl.h" +#include +#include "DigitFileFormat.h" +#include +#include "DigitIOV0.h" +#include "DigitIOV1.h" +#include + +namespace o2::mch::io::impl +{ + +std::unique_ptr createDigitReaderImpl(int version) +{ + switch (version) { + case 0: + return std::make_unique(); + case 1: + return std::make_unique(); + default: + break; + }; + return nullptr; +} + +void DigitReaderImpl::rewind(std::istream& in) +{ + in.clear(); + in.seekg(sizeof(DigitFileFormat)); +} + +int readNofItems(std::istream& in, const char* itemName) +{ + int nitems(-1); + in.read(reinterpret_cast(&nitems), sizeof(int)); + if (in.fail() || nitems < 0) { + throw std::length_error(fmt::format("invalid input : cannot get number of {}", itemName)); + } + return nitems; +} + +int advance(std::istream& in, size_t itemByteSize, const char* itemName) +{ + if (in.peek() == EOF) { + return -1; + } + // get the number of items + int nitems = readNofItems(in, itemName); + // move forward of n items + auto current = in.tellg(); + in.seekg(current + static_cast(nitems * itemByteSize)); + return nitems; +} + +} // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.h b/Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.h new file mode 100644 index 0000000000000..ef6d896b760b5 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.h @@ -0,0 +1,63 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#pragma once + +#include +#include "DigitFileFormat.h" +#include +#include + +namespace o2::mch +{ +class Digit; +class ROFRecord; +} // namespace o2::mch + +namespace o2::mch::io::impl +{ + +struct DigitReaderImpl { + virtual ~DigitReaderImpl() = default; + virtual void count(std::istream& in, size_t& ntfs, size_t& nrofs, size_t& ndigits) = 0; + virtual bool read(std::istream& in, + std::vector& digits, + std::vector& rofs) = 0; + + void rewind(std::istream& in); +}; + +int readNofItems(std::istream& in, const char* itemName); + +int advance(std::istream& in, size_t itemByteSize, const char* itemName); + +template +bool readBinary(std::istream& in, std::vector& items, const char* itemName) +{ + if (in.peek() == EOF) { + return false; + } + // get the number of items + int nitems = readNofItems(in, itemName); + // get the items if any + if (nitems > 0) { + auto offset = items.size(); + items.resize(offset + nitems); + in.read(reinterpret_cast(&items[offset]), nitems * sizeof(T)); + if (in.fail()) { + throw std::length_error(fmt::format("invalid input : cannot read {} {}", nitems, itemName)); + } + } + return true; +} + +std::unique_ptr createDigitReaderImpl(int version); + +} // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitWriter.cxx b/Detectors/MUON/MCH/DevIO/Digits/DigitWriter.cxx new file mode 100644 index 0000000000000..2b81b09af0cb8 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitWriter.cxx @@ -0,0 +1,91 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "DataFormatsMCH/ROFRecord.h" +#include "DataFormatsMCH/Digit.h" +#include +#include +#include "DigitWriter.h" +#include +#include "DigitWriterImpl.h" + +namespace +{ +template +std::string asString(T t); + +template <> +std::string asString(o2::mch::ROFRecord rof) +{ + return fmt::format("{} FirstIdx: {:5d} LastIdx: {:5d}", + rof.getBCData().asString(), rof.getFirstIdx(), rof.getLastIdx()); +} +template <> +std::string asString(o2::mch::Digit d) +{ + return fmt::format("DetID {:4d} PadId {:10d} ADC {:10d} TFtime {:10d} NofSamples {:5d} {}", + d.getDetID(), d.getPadID(), d.getADC(), d.getTime(), d.nofSamples(), + d.isSaturated() ? "(S)" : ""); +} +template +void text(std::ostream& os, + const char* headline, + gsl::span items) +{ + os << fmt::format("{:=^70}\n", fmt::format("{} {}", items.size(), headline)); + size_t i{0}; + for (const auto item : items) { + os << fmt::format("[{:6d}] {}\n", i, asString(item)); + ++i; + } +} + +} // namespace + +namespace o2::mch::io +{ + +DigitWriter::DigitWriter(std::ostream& os, DigitFileFormat format, size_t maxSize) : mOutput(os), mBinary(true), mFileFormat(format), mMaxSize(maxSize) +{ + // write the tag to identify the file + os.write(reinterpret_cast(&mFileFormat), sizeof(DigitFileFormat)); + mImpl = impl::createDigitWriterImpl(mFileFormat.fileVersion); +} + +DigitWriter::DigitWriter(std::ostream& os) : mOutput(os), mBinary(false), mImpl{} +{ +} + +DigitWriter::~DigitWriter() = default; + +bool DigitWriter::write(gsl::span digits, + gsl::span rofs) +{ + if (digits.empty()) { + return false; + } + + bool ok{true}; + + if (mBinary) { + auto pos = static_cast(mOutput.tellp()); + auto newSize = (pos + digits.size_bytes() + rofs.size_bytes()) / 1024; + if (newSize >= mMaxSize) { + return false; + } + ok = mImpl->write(mOutput, digits, rofs); + } else { + text(mOutput, "rofs", rofs); + text(mOutput, "digits", digits); + } + return ok; +} + +} // namespace o2::mch::io diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitWriter.h b/Detectors/MUON/MCH/DevIO/Digits/DigitWriter.h new file mode 100644 index 0000000000000..a86f510163d56 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitWriter.h @@ -0,0 +1,66 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#pragma once + +#include +#include +#include "DigitFileFormat.h" +#include +#include + +namespace o2::mch +{ +class ROFRecord; +class Digit; + +namespace io +{ +namespace impl +{ +class DigitWriterImpl; +} +class DigitWriter +{ + public: + /** Create a text digit writer + * @param os output stream to write to + */ + DigitWriter(std::ostream& os); + + /** Create a binary digit writer + * @param os output stream to write to + * @param dff the digit file format to be used + * @param maxSize if not zero indicate that writing should stop past + * this size, expressed in KB. + */ + DigitWriter(std::ostream& os, DigitFileFormat format, + size_t maxSize = std::numeric_limits::max()); + + /* defined in the implementation file, where mImpl is a complete type */ + ~DigitWriter(); + + /** write rofs, digits at the current position in the output stream + * @param digits vector of Digits, must not be empty + * @param rofs vector of ROFRecord, might be empty + * @returns true if writing was successull, false otherwise + */ + bool write(gsl::span digits, + gsl::span rofs = {}); + + private: + std::ostream& mOutput; // underlying stream used for output + bool mBinary; // whether to output in binary mode or text mode + DigitFileFormat mFileFormat{}; // version information for the binary case + std::unique_ptr mImpl; // actual implementation of the writer + size_t mMaxSize; // max size written to output +}; +} // namespace io +} // namespace o2::mch diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitWriterImpl.cxx b/Detectors/MUON/MCH/DevIO/Digits/DigitWriterImpl.cxx new file mode 100644 index 0000000000000..c6717933a976f --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitWriterImpl.cxx @@ -0,0 +1,32 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "DigitWriterImpl.h" +#include "DigitIOV0.h" +#include "DigitIOV1.h" +#include + +namespace o2::mch::io::impl +{ +std::unique_ptr createDigitWriterImpl(int version) +{ + switch (version) { + case 0: + return std::make_unique(); + case 1: + return std::make_unique(); + default: + break; + }; + throw std::invalid_argument(fmt::format("DigitFileFormat version {} not implemented yet", + version)); + return nullptr; +} +} // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitWriterImpl.h b/Detectors/MUON/MCH/DevIO/Digits/DigitWriterImpl.h new file mode 100644 index 0000000000000..9cc6ab3f3d4f5 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitWriterImpl.h @@ -0,0 +1,53 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#pragma once + +#include +#include +#include + +namespace o2::mch +{ +class Digit; +class ROFRecord; +} // namespace o2::mch + +namespace o2::mch::io::impl +{ + +struct DigitWriterImpl { + virtual ~DigitWriterImpl() = default; + + /** write rofs, digits at the current position in the output stream + * @param digits vector of Digits, must not be empty + * @param rofs vector of ROFRecord, might be empty + * @returns true if writing was successull, false otherwise + */ + virtual bool write(std::ostream& out, + gsl::span digits, + gsl::span rofs) = 0; +}; + +template +bool binary(std::ostream& os, + gsl::span items) +{ + int nofItems = items.size(); + if (!nofItems) { + return !os.bad(); + } + os.write(reinterpret_cast(&nofItems), sizeof(int)); + os.write(reinterpret_cast(items.data()), items.size_bytes()); + return !os.bad(); +} + +std::unique_ptr createDigitWriterImpl(int version); +} // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/ProgOptions.h b/Detectors/MUON/MCH/DevIO/Digits/ProgOptions.h new file mode 100644 index 0000000000000..7a5be04b057b0 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/ProgOptions.h @@ -0,0 +1,27 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#pragma once + +/* Command line option names that are used by at least two + * executables (workflow or not). + */ + +constexpr const char* OPTNAME_MAX_NOF_TFS = "max-nof-tfs"; +constexpr const char* OPTHELP_MAX_NOF_TFS = "max number of timeframes to process"; + +constexpr const char* OPTNAME_FIRST_TF = "first-tf"; +constexpr const char* OPTHELP_FIRST_TF = "first timeframe to process"; + +constexpr const char* OPTNAME_PRINT_DIGITS = "print-digits"; +constexpr const char* OPTHELP_PRINT_DIGITS = "print digits"; + +constexpr const char* OPTNAME_PRINT_TFS = "print-tfs"; +constexpr const char* OPTHELP_PRINT_TFS = "print number of digits and rofs per tf"; diff --git a/Detectors/MUON/MCH/DevIO/Digits/README.md b/Detectors/MUON/MCH/DevIO/Digits/README.md new file mode 100644 index 0000000000000..a82b81b5a7f81 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/README.md @@ -0,0 +1,87 @@ + + +# Utilities to read and write MCH Digits in non-CTF formats (mostly for debug) + +The MCH digits can be stored in binary format for debug purpose. + +The file they are stored in can currently be of two different formats : with or +without associated ROFRecord. In both cases the digits themselves (currently) +have the same version (named D0). The file version number changes whenever the + file structure changes or the format of the objects it contain changes. + +| File version | Digit version | contains ROF | ROF version | support | +|:------------:|:-------------:|:------------:|:-----------:|:---------:| +| 0 | 0 | no | 0 | yes | +| 1 | 0 | yes | 0 | yes | +| 2 | 1 | yes | 0 | planned | + +## Standalone programs (i.e. not DPL devices) + +### Digit file dumper + +```shell +options: + -h [ --help ] produce help message + -i [ --infile ] arg input file name + -c [ --count ] count items (rofs, tfs, etc...) + -d [ --describe ] describe file format + -p [ --print-digits ] print digits + -t [ --print-tfs ] print number of digits and rofs per tf + --max-nof-tfs arg max number of timeframes to process + --first-tf arg first timeframe to process +``` + +## DPL devices + +Those are (partial) DPL workflows to be used to form bigger workflows + using pipes. + +### Digit file reader (aka sampler) device + +Reads a binary file containing digits. The binary format should be embedded +in the file directly. If the reader cannot identify the format it will assume +it is the V0 version, which might or not might be the case... + +``` +o2-mch-digits-file-reader-workflow + --infile arg input file name + [--verbose] print some basic information while processing + [--max-nof-tfs] max number of timeframes to process + [--first-tf] first timeframe to process + [--max-nof-rofs] max number of ROFs to process + [--repack-rofs] number of rofs to repack into a timeframe + (aka min number of rofs per timeframe) + [--print-digits] print digits + [--print-tfs] print number of digits and rofs per tf +``` + +### Digit writer (aka sink) device + +``` +o2-mch-digits-file-writer-workflow + [--outfile] arg (=digits.out) output file name + [--max-nof-tfs] arg (=2147483647) max number of timeframes to process + [--first-tf] arg (=0) first timeframe to process + [--no-file] no output to file + [--binary-file-format] arg (=v1) digit binary format to use + [--print-digits] print digits + [--print-tfs] print number of digits and rofs per tf + [--txt] output digits in text format + [--max-size] arg (=2147483647) max output size (in KB) +``` + +Take as input a list of digits in timeframes (and optionally their associated +Orbits) and dump them into a file (binary or text if `--txt` +option is used) or to screen (if `--no-file` option is used) + +### Digit ID converter (from Run2 to Run3) + +``` +o2-mch-digits-r23-workflow +``` + +A device that reads digits with ids in Run2 convention and outputs digits with + ids in Run3 convention. Note that expected input spec is `MCH/DIGITSRUN2` and + the output one is `MCH/DIGITS` diff --git a/Detectors/MUON/MCH/DevIO/Digits/TestFileV0.cxx b/Detectors/MUON/MCH/DevIO/Digits/TestFileV0.cxx new file mode 100644 index 0000000000000..67bef0b5069af --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/TestFileV0.cxx @@ -0,0 +1,94 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include + +std::array v0_buffer = { + 0x2F, 0x3F, 0x00, 0x00, 0x40, 0x01, 0x00, 0x20, + 0x1D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x67, 0x00, 0x00, 0x00, + 0x67, 0x30, 0x09, 0x54, 0xB7, 0x79, 0x31, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x67, 0x00, 0x00, 0x00, 0x67, 0x60, 0x47, 0x0A, 0xD2, 0x18, 0xF0, 0x3E, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x67, 0x00, 0x00, 0x00, 0x67, 0x20, 0x01, 0x5D, 0x64, 0xC0, 0x2C, 0x3F, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x00, 0x00, 0x00, 0x66, 0x20, 0x49, 0x6F, + 0x24, 0x41, 0x5E, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC8, 0x00, 0x00, 0x00, + 0xC8, 0xB0, 0x0E, 0x18, 0x9F, 0x55, 0x32, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xCB, 0x00, 0x00, 0x00, 0xCB, 0xF0, 0x47, 0x13, 0x19, 0xB1, 0x1B, 0x3F, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xC9, 0x00, 0x00, 0x00, 0xC9, 0x20, 0x07, 0x41, 0x19, 0xF6, 0x06, 0x3F, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2D, 0x01, 0x00, 0x00, 0x2D, 0x81, 0x43, 0x3C, + 0x6F, 0xDE, 0x2C, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x92, 0x01, 0x00, 0x00, + 0x92, 0xF1, 0x0A, 0x11, 0xD1, 0x65, 0x6E, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x92, 0x01, 0x00, 0x00, 0x92, 0xF1, 0x0A, 0x14, 0x24, 0xFC, 0x35, 0x40, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x92, 0x01, 0x00, 0x00, 0x92, 0xF1, 0x0A, 0x3F, 0xE5, 0xE5, 0x37, 0x3F, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x92, 0x01, 0x00, 0x00, 0x92, 0xF1, 0x4A, 0x61, + 0xA4, 0x2A, 0x51, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x92, 0x01, 0x00, 0x00, + 0x92, 0xF1, 0x4A, 0x62, 0xC5, 0x0E, 0xCD, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x92, 0x01, 0x00, 0x00, 0x92, 0xF1, 0x4A, 0x4F, 0xCF, 0xCD, 0x71, 0x40, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x92, 0x01, 0x00, 0x00, 0x92, 0x41, 0x42, 0x65, 0xCE, 0x29, 0x31, 0x3F, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x92, 0x01, 0x00, 0x00, 0x92, 0x21, 0x04, 0x13, + 0x3D, 0x50, 0x21, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x01, 0x00, 0x00, + 0xFF, 0x71, 0x46, 0x0E, 0xEE, 0x75, 0x05, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xFF, 0x01, 0x00, 0x00, 0xFF, 0x81, 0x06, 0x61, 0xB7, 0xAA, 0xEF, 0x3F, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x03, 0x02, 0x00, 0x00, 0x03, 0x22, 0x07, 0x40, 0x8B, 0xC8, 0x25, 0x40, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x67, 0x02, 0x00, 0x00, 0x67, 0xF2, 0x00, 0x56, + 0x24, 0x25, 0x8F, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC8, 0x02, 0x00, 0x00, + 0xC8, 0xC2, 0x06, 0x63, 0x22, 0xFC, 0x65, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x28, 0x03, 0x00, 0x00, 0x28, 0xE3, 0x46, 0x5C, 0x8F, 0xE5, 0x83, 0x3F, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x38, 0x03, 0x00, 0x00, 0x38, 0x13, 0x0D, 0x14, 0x7C, 0xCE, 0x47, 0x3F, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x39, 0x03, 0x00, 0x00, 0x39, 0x93, 0x01, 0x51, + 0x14, 0xDD, 0xB6, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x37, 0x03, 0x00, 0x00, + 0x37, 0x23, 0x07, 0x62, 0x7B, 0x42, 0x3A, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x21, 0x03, 0x00, 0x00, 0x21, 0x43, 0x53, 0x6A, 0x1E, 0x27, 0x6C, 0x3F, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x9D, 0x03, 0x00, 0x00, 0x9D, 0x83, 0x46, 0x3D, 0x89, 0x84, 0x2C, 0x40, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x03, 0x00, 0x00, 0xF8, 0xF3, 0x40, 0x7E, + 0xE2, 0x7A, 0x23, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFD, 0x03, 0x00, 0x00, + 0xFD, 0xE3, 0x46, 0x07, 0xB6, 0x1C, 0xAB, 0x3F, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x67, 0x00, 0x00, 0x00, 0x67, 0xF0, 0x01, 0x46, 0xB0, 0x31, 0x40, 0x3F, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x65, 0x60, 0x03, 0x7A, + 0xC0, 0x50, 0x02, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC8, 0x00, 0x00, 0x00, + 0xC8, 0xD0, 0x0E, 0x3D, 0xF5, 0xB4, 0x1C, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xC8, 0x00, 0x00, 0x00, 0xC8, 0xD0, 0x0A, 0x2B, 0x9C, 0xB2, 0x1E, 0x3F, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xCA, 0x00, 0x00, 0x00, 0xCA, 0xB0, 0x00, 0x31, 0xDE, 0x04, 0x1D, 0x3F, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xCA, 0x00, 0x00, 0x00, 0xCA, 0x70, 0x04, 0x22, + 0xB5, 0xD6, 0x1D, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2D, 0x01, 0x00, 0x00, + 0x2D, 0x51, 0x4F, 0x02, 0xB5, 0x90, 0x1D, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x93, 0x01, 0x00, 0x00, 0x93, 0xA1, 0x0B, 0x58, 0xB0, 0x30, 0x2B, 0x3F, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x5A, 0x02, 0x00, 0x00, 0x5A, 0xC2, 0x0D, 0x2A, 0x55, 0x47, 0x43, 0x3F, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x02, 0x00, 0x00, 0x64, 0x72, 0x06, 0x04, + 0x5D, 0xEE, 0x64, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x02, 0x00, 0x00, + 0x03, 0x22, 0x07, 0x40, 0x9A, 0x7C, 0xFD, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x02, 0x00, 0x00, 0x05, 0xE2, 0x0C, 0x6A, 0x11, 0x96, 0x87, 0x3F, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xC7, 0x02, 0x00, 0x00, 0xC7, 0x82, 0x00, 0x76, 0x08, 0x1A, 0x73, 0x3F, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC8, 0x02, 0x00, 0x00, 0xC8, 0xC2, 0x00, 0x6A, + 0x3F, 0xDD, 0x50, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x03, 0x00, 0x00, + 0x28, 0xC3, 0x06, 0x2D, 0x9B, 0x19, 0xA5, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x31, 0x03, 0x00, 0x00, 0x31, 0x23, 0x13, 0x58, 0x23, 0x12, 0x4A, 0x3F, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x95, 0x03, 0x00, 0x00, 0x95, 0x53, 0x00, 0x4C, 0x42, 0xDE, 0x7F, 0x3F, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x91, 0x03, 0x00, 0x00, 0x91, 0x43, 0x00, 0x70, + 0x01, 0xA3, 0x7A, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x93, 0x03, 0x00, 0x00, + 0x93, 0x33, 0x00, 0x78, 0xE3, 0x33, 0x4B, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x85, 0x03, 0x00, 0x00, 0x85, 0xB3, 0x14, 0x22, 0xDB, 0x13, 0x0B, 0x42, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x85, 0x03, 0x00, 0x00, 0x85, 0xB3, 0x14, 0x23, 0x22, 0x08, 0x4E, 0x42, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x03, 0x00, 0x00, 0x85, 0xB3, 0x14, 0x24, + 0xF8, 0xB4, 0x4E, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x03, 0x00, 0x00, + 0x85, 0xE3, 0x54, 0x71, 0x27, 0xFC, 0x55, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x85, 0x03, 0x00, 0x00, 0x85, 0xE3, 0x54, 0x76, 0x95, 0x8A, 0xB3, 0x41, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x88, 0x03, 0x00, 0x00, 0x88, 0xB3, 0x00, 0x16, 0x93, 0x95, 0x83, 0x3F, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x98, 0x03, 0x00, 0x00, 0x98, 0x83, 0x46, 0x51, + 0x4C, 0x85, 0xB4, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x98, 0x03, 0x00, 0x00, + 0x98, 0x83, 0x46, 0x59, 0xFC, 0xFD, 0xA2, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xF7, 0x03, 0x00, 0x00, 0xF7, 0x13, 0x42, 0x12, 0x10, 0x65, 0x36, 0x3F, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xF7, 0x03, 0x00, 0x00, 0xF7, 0x23, 0x07, 0x73, 0xB0, 0x19, 0x32, 0x3F, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF4, 0x03, 0x00, 0x00, 0xF4, 0x63, 0x06, 0x78, + 0xD9, 0xBB, 0xA3, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF4, 0x03, 0x00, 0x00, + 0xF4, 0x73, 0x06, 0x6E, 0xA7, 0x88, 0xA4, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x04, 0x00, 0x00, 0x00, 0x24, 0x00, 0x10, 0xFB, 0xB6, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x64, 0x14, 0x29, 0x11, 0xD9, 0x35, 0x3F, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEA, 0x03, 0x00, 0x00, 0xEA, 0xF3, 0x52, 0x7D, + 0x44, 0x19, 0x09, 0x40}; diff --git a/Detectors/MUON/MCH/DevIO/Digits/TestFileV0.h b/Detectors/MUON/MCH/DevIO/Digits/TestFileV0.h new file mode 100644 index 0000000000000..79483ec0e8d6d --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/TestFileV0.h @@ -0,0 +1,14 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#pragma once +#include + +extern std::array v0_buffer; diff --git a/Detectors/MUON/MCH/DevIO/Digits/digits-file-dumper.cxx b/Detectors/MUON/MCH/DevIO/Digits/digits-file-dumper.cxx new file mode 100644 index 0000000000000..b4f8f8f1f80e1 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/digits-file-dumper.cxx @@ -0,0 +1,107 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "boost/program_options.hpp" +#include +#include +#include "DigitReader.h" +#include "DigitWriter.h" +#include "DataFormatsMCH/Digit.h" +#include "DataFormatsMCH/ROFRecord.h" +#include +#include "ProgOptions.h" + +namespace po = boost::program_options; + +/** + * o2-mch-digits-file-dumper is a small helper program to inspect + * MCH digit binary files (the ones that are not in CTF format) + */ + +int main(int argc, char* argv[]) +{ + std::string inputFile; + po::variables_map vm; + po::options_description options("options"); + bool count{false}; + bool describe{false}; + bool printDigits{false}; + bool printTFs{false}; + int maxNofTimeFrames{std::numeric_limits::max()}; + int firstTimeFrame{0}; + + // clang-format off + // clang-format off + options.add_options() + ("help,h", "produce help message") + ("infile,i", po::value(&inputFile)->required(), "input file name") + ("count,c",po::bool_switch(&count),"count items (rofs, tfs, etc...)") + ("describe,d",po::bool_switch(&describe),"describe file format") + (OPTNAME_PRINT_DIGITS,po::bool_switch(&printDigits),OPTHELP_PRINT_DIGITS) + (OPTNAME_PRINT_TFS,po::bool_switch(&printTFs),OPTHELP_PRINT_TFS) + (OPTNAME_MAX_NOF_TFS,po::value(&maxNofTimeFrames),OPTHELP_MAX_NOF_TFS) + (OPTNAME_FIRST_TF,po::value(&firstTimeFrame),OPTHELP_FIRST_TF) + ; + // clang-format on + + po::options_description cmdline; + cmdline.add(options); + + po::store(po::command_line_parser(argc, argv).options(cmdline).run(), vm); + + if (vm.count("help")) { + std::cout << options << "\n"; + return 2; + } + + try { + po::notify(vm); + } catch (boost::program_options::error& e) { + std::cout << "Error: " << e.what() << "\n"; + exit(1); + } + + std::ifstream in(inputFile.c_str()); + if (!in.is_open()) { + std::cerr << "cannot open input file " << inputFile << "\n"; + return 3; + } + o2::mch::io::DigitReader dr(in); + + if (describe) { + std::cout << dr.fileFormat() << "\n"; + } + if (count) { + std::cout << fmt::format("nTFs {} nROFs {} nDigits {}\n", + dr.nofTimeFrames(), dr.nofROFs(), dr.nofDigits()); + } + + if (printTFs || printDigits) { + int tfid{0}; + int tfcount{0}; + o2::mch::io::DigitWriter dump(std::cout); + std::vector digits; + std::vector rofs; + while (dr.read(digits, rofs)) { + if (tfid >= firstTimeFrame && tfcount < maxNofTimeFrames) { + if (printTFs) { + std::cout << fmt::format("TF {:5d} {:4d} rofs {:5d} digits\n", + tfid, rofs.size(), digits.size()); + } + if (printDigits) { + dump.write(digits, rofs); + } + ++tfcount; + } + ++tfid; + } + } + return 0; +} diff --git a/Detectors/MUON/MCH/DevIO/Digits/digits-file-reader-workflow.cxx b/Detectors/MUON/MCH/DevIO/Digits/digits-file-reader-workflow.cxx new file mode 100644 index 0000000000000..0401d37ca8cee --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/digits-file-reader-workflow.cxx @@ -0,0 +1,159 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "DataFormatsMCH/Digit.h" +#include "DataFormatsMCH/ROFRecord.h" +#include "DigitIOBaseTask.h" +#include "DigitReader.h" +#include "Framework/ConfigParamRegistry.h" +#include "Framework/ConfigParamSpec.h" +#include "Framework/ControlService.h" +#include "Framework/DataProcessorSpec.h" +#include "Framework/Task.h" +#include "Framework/Variant.h" +#include "Framework/WorkflowSpec.h" +#include "ProgOptions.h" +#include +#include +#include +#include +#include +#include + +using namespace o2::framework; + +constexpr const char* OPTNAME_INFILE = "infile"; +constexpr const char* OPTNAME_MAX_NOF_ROFS = "max-nof-rofs"; +constexpr const char* OPTNAME_REPACK_ROFS = "repack-rofs"; +constexpr const char* OPTNAME_RUN2 = "run2"; + +using namespace o2::mch; + +class DigitSamplerTask : public io::DigitIOBaseTask +{ + private: + std::unique_ptr mDigitReader; + std::ifstream mInput; + bool mReadIsOk = true; + size_t mMaxNofROFs; + size_t mNofProcessedROFs{0}; + size_t mMinNumberOfROFsPerTF{1}; + std::vector mROFs; + std::vector mDigits; + + public: + void init(InitContext& ic) + { + io::DigitIOBaseTask::init(ic); // init common options + auto inputFileName = ic.options().get(OPTNAME_INFILE); + mInput.open(inputFileName); + mDigitReader = std::make_unique(mInput); + mNofProcessedTFs = 0; + mMaxNofROFs = ic.options().get(OPTNAME_MAX_NOF_ROFS); + mMinNumberOfROFsPerTF = ic.options().get(OPTNAME_REPACK_ROFS); + } + + void outputAndClear(DataAllocator& out) + { + printSummary(mDigits, mROFs, "-> to output"); + out.snapshot(OutputRef{"rofs"}, mROFs); + out.snapshot(OutputRef{"digits"}, mDigits); + mDigits.clear(); + mROFs.clear(); + } + + bool shouldEnd() const + { + bool maxTFreached = mNofProcessedTFs >= mMaxNofTimeFrames; + bool maxROFreached = mNofProcessedROFs >= mMaxNofROFs; + return !mReadIsOk || maxTFreached || maxROFreached; + } + + void run(ProcessingContext& pc) + { + if (shouldEnd()) { + // output remaining data if any + if (mROFs.size() > 0) { + --mTFid; + outputAndClear(pc.outputs()); + } + pc.services().get().endOfStream(); + return; + } + + std::vector rofs; + std::vector digits; + mReadIsOk = mDigitReader->read(digits, rofs); + if (!mReadIsOk) { + return; + } + + if (shouldProcess()) { + incNofProcessedTFs(); + mNofProcessedROFs += rofs.size(); + // append rofs to mROFs, but shift the indices by the amount of digits + // we have read so far. + auto offset = mDigits.size(); + std::transform(rofs.begin(), rofs.end(), std::back_inserter(mROFs), + [offset](ROFRecord r) { + r.setDataRef(r.getFirstIdx() + offset, r.getNEntries()); + return r; + }); + mDigits.insert(mDigits.end(), digits.begin(), digits.end()); + printSummary(mDigits, mROFs); + printFull(mDigits, mROFs); + } + + // output if we've accumulated enough ROFs + if (mROFs.size() >= mMinNumberOfROFsPerTF) { + outputAndClear(pc.outputs()); + } + + incTFid(); + } +}; + +o2::framework::DataProcessorSpec getDataProcessorSpec(bool run2) +{ + std::string spec = fmt::format("digits:MCH/DIGITS{}/0", run2 ? "R2" : ""); + InputSpec itmp = o2::framework::select(spec.c_str())[0]; + + auto commonOptions = o2::mch::io::getCommonOptions(); + auto options = Options{ + {OPTNAME_INFILE, VariantType::String, "", {"input file name"}}, + {OPTNAME_MAX_NOF_ROFS, VariantType::Int, std::numeric_limits::max(), {"max number of ROFs to process"}}, + {OPTNAME_REPACK_ROFS, VariantType::Int, 1, {"number of rofs to repack into a timeframe (aka min number of rofs per timeframe"}}}; + options.insert(options.end(), commonOptions.begin(), commonOptions.end()); + + return DataProcessorSpec{ + "mch-digits-file-reader", + Inputs{}, + Outputs{{DataSpecUtils::asOutputSpec(itmp)}, + OutputSpec{{"rofs"}, "MCH", "DIGITROFS", 0, Lifetime::Timeframe}}, + AlgorithmSpec{adaptFromTask()}, + options}; +} + +/** add workflow options. Note that customization needs to be declared +* before including Framework/runDataProcessing +*/ +void customize(std::vector& workflowOptions) +{ + workflowOptions.emplace_back(OPTNAME_RUN2, VariantType::Bool, false, + ConfigParamSpec::HelpString{"input digits use Run2 padIds"}); +} + +#include "Framework/runDataProcessing.h" + +//_________________________________________________________________________________________________ +WorkflowSpec defineDataProcessing(const ConfigContext& cc) +{ + return WorkflowSpec{getDataProcessorSpec(cc.options().get(OPTNAME_RUN2))}; +} diff --git a/Detectors/MUON/MCH/DevIO/Digits/digits-r23-workflow.cxx b/Detectors/MUON/MCH/DevIO/Digits/digits-r23-workflow.cxx new file mode 100644 index 0000000000000..06d8f95b18611 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/digits-r23-workflow.cxx @@ -0,0 +1,83 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/** Convert Digit's padID from Run2 to Run3. +*/ + +#include "Framework/CallbackService.h" +#include "Framework/ConfigParamRegistry.h" +#include "Framework/ControlService.h" +#include "Framework/DataProcessorSpec.h" +#include "Framework/DataProcessorSpec.h" +#include "Framework/Lifetime.h" +#include "Framework/Output.h" +#include "Framework/Task.h" +#include "Framework/WorkflowSpec.h" +#include "Framework/DataProcessorSpec.h" +#include "DataFormatsMCH/Digit.h" +#include "MCHMappingInterface/Segmentation.h" +#include +#include "Framework/Logger.h" + +using namespace o2::framework; + +#include "Framework/runDataProcessing.h" + +struct DigitConverter { + bool mVerbose{false}; + + void init(InitContext& ic) + { + mVerbose = ic.options().get("verbose"); + fair::Logger::SetConsoleColor(true); + } + + void run(ProcessingContext& pc) + { + auto digitsR2 = pc.inputs().get>("digits"); + auto& digitsR3 = pc.outputs().make>(OutputRef{"digits"}); + for (const auto d2 : digitsR2) { + auto digit = d2; + int deID = digit.getDetID(); + int digitID = digit.getPadID(); + int manuID = (digitID & 0xFFF000) >> 12; + int manuCh = (digitID & 0x3F000000) >> 24; + + int padID = o2::mch::mapping::segmentation(deID).findPadByFEE(manuID, manuCh); + if (mVerbose) { + LOGP(warn, "DEID {:4d} DIGITID {:10d} MANUID {:4d} CH {:2} PADID {:10d}", + deID, digitID, manuID, manuCh, padID); + } + if (padID < 0) { + throw std::runtime_error(fmt::format("digitID {} does not exist in the mapping", digitID)); + } + digit.setPadID(padID); + digitsR3.push_back(digit); + } + } +}; + +WorkflowSpec defineDataProcessing(const ConfigContext& cc) +{ + WorkflowSpec specs; + + std::string inputConfig = fmt::format("digits:MCH/DIGITSR2/0"); + inputConfig += ";rofs:MCH/DIGITROFS/0"; + + DataProcessorSpec padIdConverter{ + "mch-digits-r23", + Inputs{o2::framework::select(inputConfig.c_str())}, + Outputs{OutputSpec{{"digits"}, "MCH", "DIGITS", 0, Lifetime::Timeframe}}, + AlgorithmSpec{adaptFromTask()}, + Options{ + {"verbose", VariantType::Bool, false, {"print ids being converted"}}}}; + specs.push_back(padIdConverter); + return specs; +} diff --git a/Detectors/MUON/MCH/DevIO/Digits/digits-writer-workflow.cxx b/Detectors/MUON/MCH/DevIO/Digits/digits-writer-workflow.cxx new file mode 100644 index 0000000000000..45b56c910e55d --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/digits-writer-workflow.cxx @@ -0,0 +1,176 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/** + * o2-mch-digits-writer-workflow dumps to a file on disk the digits received + * via DPL, mainly in binary format (but txt is possible as well). + */ + +#include "DPLUtils/DPLRawParser.h" +#include "DataFormatsMCH/Digit.h" +#include "DataFormatsMCH/ROFRecord.h" +#include "DigitFileFormat.h" +#include "DigitIOBaseTask.h" +#include "DigitWriter.h" +#include "Framework/CallbackService.h" +#include "Framework/ConfigParamRegistry.h" +#include "Framework/ControlService.h" +#include "Framework/DataProcessorSpec.h" +#include "Framework/Lifetime.h" +#include "Framework/Output.h" +#include "Framework/Task.h" +#include "Framework/WorkflowSpec.h" +#include "MCHRawDecoder/OrbitInfo.h" +#include +#include +#include +#include +#include +#include +#include + +using namespace o2::framework; +using namespace o2::mch; + +constexpr const char* OPTNAME_OUTFILE = "outfile"; +constexpr const char* OPTNAME_TXT = "txt"; +constexpr const char* OPTNAME_NO_FILE = "no-file"; +constexpr const char* OPTNAME_BINARY_FORMAT = "binary-file-format"; +constexpr const char* OPTNAME_WITHOUT_ORBITS = "without-orbits"; +constexpr const char* OPTNAME_MAX_SIZE = "max-size"; + +class DigitsSinkTask : public io::DigitIOBaseTask +{ + public: + DigitsSinkTask(bool withOrbits) : mWithOrbits{withOrbits} {} + + //_________________________________________________________________________________________________ + void init(InitContext& ic) + { + /** + * init e.g. the options that are common to reading and writing + * like max number of timeframes to process, first time frame to process, etc... + */ + DigitIOBaseTask::init(ic); + + mNoFile = ic.options().get(OPTNAME_NO_FILE); + mBinary = not ic.options().get(OPTNAME_TXT); + + if (!mNoFile) { + auto outputFileName = ic.options().get(OPTNAME_OUTFILE); + mStream = std::make_unique(outputFileName, mBinary ? std::ios::out | std::ios::binary : std::ios::out); + if (mBinary) { + auto binaryFileFormat = ic.options().get(OPTNAME_BINARY_FORMAT); + if (binaryFileFormat >= o2::mch::io::digitFileFormats.size()) { + throw std::invalid_argument(fmt::format("file version {} is unknown", binaryFileFormat)); + } + auto maxsize = ic.options().get(OPTNAME_MAX_SIZE); + LOGP(warn, + "Will dump binary information (version {}) up to a maximum size of {} KB", + binaryFileFormat, maxsize); + mWriter = std::make_unique(*mStream, + io::digitFileFormats[binaryFileFormat], + static_cast(maxsize)); + } else { + LOGP(warn, "Will dump textual information"); + mWriter = std::make_unique(*mStream); + } + } + } + + void writeOrbits(gsl::span orbits) + { + if (orbits.size() && !mBinary) { + std::set orderedOrbits(orbits.begin(), orbits.end()); + for (auto o : orderedOrbits) { + (*mStream) << " FEEID " << o.getFeeID() << " LINK " << (int)o.getLinkID() << " ORBIT " << o.getOrbit() << std::endl; + } + } + } + + void write(gsl::span digits, + gsl::span rofs, + gsl::span orbits) + { + if (mNoFile) { + return; + } + writeOrbits(orbits); + mWriter->write(digits, rofs); + } + + void run(ProcessingContext& pc) + { + gsl::span voidOrbitInfos; + + auto digits = pc.inputs().get>("digits"); + auto rofs = pc.inputs().get>("rofs"); + auto orbits = mWithOrbits ? pc.inputs().get>("orbits") : voidOrbitInfos; + + if (shouldProcess()) { + incNofProcessedTFs(); + printSummary(digits, rofs, fmt::format("{:4d} orbits", orbits.size()).c_str()); + printFull(digits, rofs); + write(digits, rofs, orbits); + } + incTFid(); + } + + private: + std::unique_ptr mWriter = nullptr; // actual digit writer + std::unique_ptr mStream = nullptr; // output stream + bool mNoFile = false; // disable output to file + bool mWithOrbits = false; // expect ORBITs as input (in addition to just digits) + bool mBinary = true; // output is a binary file +}; + +/** + * Add workflow options. Note that customization needs to be declared + * before including Framework/runDataProcessing. + */ +void customize(std::vector& workflowOptions) +{ + workflowOptions.emplace_back(OPTNAME_WITHOUT_ORBITS, VariantType::Bool, true, + ConfigParamSpec::HelpString{"do not expect, in addition to digits and rofs, to get Orbits at the input"}); +} + +#include "Framework/runDataProcessing.h" + +WorkflowSpec defineDataProcessing(const ConfigContext& cc) +{ + WorkflowSpec specs; + + bool withOrbits = not cc.options().get(OPTNAME_WITHOUT_ORBITS); + + std::string inputConfig = fmt::format("digits:MCH/DIGITS/0"); + inputConfig += ";rofs:MCH/DIGITROFS/0"; + if (withOrbits) { + inputConfig += ";orbits:MCH/ORBITS/0"; + } + + auto commonOptions = o2::mch::io::getCommonOptions(); + auto options = Options{ + {OPTNAME_OUTFILE, VariantType::String, "digits.out", {"output file name"}}, + {OPTNAME_NO_FILE, VariantType::Bool, false, {"no output to file"}}, + {OPTNAME_BINARY_FORMAT, VariantType::Int, 0, {"digit binary format to use"}}, + {OPTNAME_TXT, VariantType::Bool, false, {"output digits in text format"}}, + {OPTNAME_MAX_SIZE, VariantType::Int, std::numeric_limits::max(), {"max output size (in KB)"}}}; + options.insert(options.end(), commonOptions.begin(), commonOptions.end()); + + DataProcessorSpec producer{ + "mch-digits-writer", + Inputs{o2::framework::select(inputConfig.c_str())}, + Outputs{}, + AlgorithmSpec{adaptFromTask(withOrbits)}, + options}; + specs.push_back(producer); + + return specs; +} diff --git a/Detectors/MUON/MCH/DevIO/Digits/testDigitIO.cxx b/Detectors/MUON/MCH/DevIO/Digits/testDigitIO.cxx new file mode 100644 index 0000000000000..0c27d1e1de527 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/testDigitIO.cxx @@ -0,0 +1,286 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include +#include +#include "DigitFileFormat.h" +#define BOOST_TEST_MODULE Test MCHWorkflow DigitsIO +#define BOOST_TEST_MAIN +#define BOOST_TEST_DYN_LINK + +#include +#include +#include "DigitIO.h" +#include +#include +#include +#include "DataFormatsMCH/Digit.h" +#include "DataFormatsMCH/ROFRecord.h" +#include +#include +#include +#include "DigitReaderImpl.h" + +using namespace o2::mch; +using namespace o2::mch::io; + +DigitFileFormat createFormat(uint8_t fileVersion, + uint8_t digitVersion, + uint8_t digitSize, + uint8_t rofVersion, + uint8_t rofSize, + bool run2ids, + bool hasRof) +{ + DigitFileFormat df; + df.fileVersion = fileVersion; + df.digitVersion = digitVersion; + df.digitSize = digitSize; + df.rofVersion = rofVersion; + df.rofSize = rofSize; + df.run2ids = run2ids; + df.hasRof = hasRof; + return df; +} + +BOOST_AUTO_TEST_CASE(DigitFileFormatV0Value) +{ + DigitFileFormat v0 = createFormat(0, 0, 20, 0, 0, true, false); + BOOST_CHECK_EQUAL(isValid(v0), true); +} + +BOOST_AUTO_TEST_CASE(DigitFileFormatV1Value) +{ + DigitFileFormat v1 = createFormat(1, 0, 20, 1, 16, false, true); + BOOST_CHECK_EQUAL(isValid(v1), true); + BOOST_CHECK_EQUAL(sizeof(o2::mch::ROFRecord), v1.rofSize); +} + +BOOST_DATA_TEST_CASE(WriteMustReturnFalseIfDigitVectorIsEmpty, digitFileFormats, digitFileFormat) +{ + std::ostringstream str; + std::vector rofs; + std::vector digits; + + rofs.push_back({}); + + DigitWriter dwText(str); + bool ok = dwText.write(digits, rofs); + + BOOST_CHECK_EQUAL(ok, false); + + DigitWriter dwBinary(str, digitFileFormat); + ok = dwBinary.write(digits, rofs); + + BOOST_CHECK_EQUAL(ok, false); +} + +BOOST_DATA_TEST_CASE(BinaryWriteMustReturnFalseIfRofVectorIsEmpty, digitFileFormats, digitFileFormat) +{ + if (digitFileFormat.fileVersion == 0) { + return; //V0 is the exception as it predates ROFs + } + std::ostringstream str; + std::vector rofs; + std::vector digits; + + digits.push_back({}); + + DigitWriter dwBinary(str, digitFileFormat); + bool ok = dwBinary.write(digits, rofs); + + BOOST_CHECK_EQUAL(ok, false); +} + +BOOST_AUTO_TEST_CASE(DefaultFormatIsTheTag) +{ + o2::mch::io::DigitFileFormat dff; + BOOST_CHECK_EQUAL(dff.format, o2::mch::io::TAG_DIGITS); +} + +BOOST_DATA_TEST_CASE(ReaderMustIdentifyFileFormat, digitFileFormats, digitFileFormat) +{ + std::stringstream buffer; + buffer.write(reinterpret_cast(&digitFileFormat), sizeof(uint64_t)); + buffer.clear(); + buffer.seekg(0); + DigitReader dr(buffer); + BOOST_CHECK_EQUAL(dr.fileFormat(), digitFileFormat); +} + +BOOST_DATA_TEST_CASE(BinaryWriterMustTagCorrectly, digitFileFormats, digitFileFormat) +{ + std::stringstream buffer; + DigitWriter dw(buffer, digitFileFormat); + DigitReader dr(buffer); + BOOST_CHECK_EQUAL(dr.fileFormat(), digitFileFormat); +} + +std::vector createDummyFixedDigits(int n) +{ + assert(n < 100); + std::vector digits; + int dummyADC{40}; + int32_t dummyTime{1000}; + uint16_t dummySamples{10}; + for (int i = 0; i < n; i++) { + digits.emplace_back(100, i, dummyADC + i, dummyTime + i * 100, dummySamples + i * 10); + } + return digits; +} + +struct TF { + std::vector digits; + std::vector rofs; +}; + +TF createDummyData(int ndigits, int nrofs, uint32_t firstOrbit) +{ + if (nrofs >= ndigits) { + throw std::invalid_argument("cannot have more rofs than digits!"); + } + TF tf; + tf.digits = createDummyFixedDigits(ndigits); + int step = ndigits / nrofs; + for (int i = 0; i < nrofs; i++) { + o2::InteractionRecord ir(0, firstOrbit + i); + tf.rofs.emplace_back(ir, step * i, i == nrofs - 1 ? ndigits - step * i : step); + }; + return tf; +} + +/** The test data is used to check the internal consistency + * of the reader and writer (i.e. data written by the writer must be readable + * by the reader). + * A complete test requires, in addition, the usage of externally created data + * (see for instance V0File in testDigitIOV0) + */ +constexpr int NROF_1 = 1; +constexpr int NROF_2 = 1; +constexpr int NROF_3 = 1; +constexpr int NROF_4 = 3; +constexpr int NROFS = NROF_1 + NROF_2 + NROF_3 + NROF_4; + +std::vector testData{ + createDummyData(3, NROF_1, 0), + createDummyData(5, NROF_2, 10), + createDummyData(13, NROF_3, 20), + createDummyData(26, NROF_4, 20), +}; + +void writeTestData(std::ostream& out, DigitFileFormat dff) +{ + auto tfs = testData; + DigitWriter dw(out, dff); + for (auto tf : tfs) { + dw.write(tf.digits, tf.rofs); + } +} + +BOOST_TEST_DECORATOR(*boost::unit_test::disabled()) +BOOST_DATA_TEST_CASE(TestDataDump, digitFileFormats, digitFileFormat) +{ + auto tfs = testData; + DigitWriter dw(std::cout); + for (auto tf : tfs) { + dw.write(tf.digits, tf.rofs); + } + BOOST_CHECK_EQUAL(tfs.size(), testData.size()); +} + +BOOST_DATA_TEST_CASE(TestDataIsOfExpectedFormat, digitFileFormats, digitFileFormat) +{ + std::stringstream buffer; + writeTestData(buffer, digitFileFormat); + DigitReader dr(buffer); + + BOOST_CHECK_EQUAL(dr.fileFormat(), digitFileFormat); +} + +BOOST_DATA_TEST_CASE(TestDataHasExpectedNofROFs, digitFileFormats, digitFileFormat) +{ + std::stringstream buffer; + writeTestData(buffer, digitFileFormat); + DigitReader dr(buffer); + + BOOST_CHECK_EQUAL(dr.nofROFs(), NROFS); +} + +BOOST_DATA_TEST_CASE(TestDataHasExpectedNofTFs, digitFileFormats, digitFileFormat) +{ + std::stringstream buffer; + writeTestData(buffer, digitFileFormat); + DigitReader dr(buffer); + + if (digitFileFormat.fileVersion == 0) { + BOOST_CHECK_EQUAL(dr.nofTimeFrames(), NROFS); + } else { + BOOST_CHECK_EQUAL(dr.nofTimeFrames(), testData.size()); + } +} + +BOOST_DATA_TEST_CASE(TestDataHasExpectedNumberOfDigitsWhenReading, digitFileFormats, digitFileFormat) +{ + std::stringstream buffer; + writeTestData(buffer, digitFileFormat); + DigitReader dr(buffer); + + std::vector digits; + std::vector rofs; + int ndigits{0}; + while (dr.read(digits, rofs)) { + ndigits += digits.size(); + } + BOOST_CHECK_EQUAL(ndigits, 47); +} + +BOOST_DATA_TEST_CASE(TestDataHasExpectedNumberOfDigitsWhenCounting, digitFileFormats, digitFileFormat) +{ + std::stringstream buffer; + writeTestData(buffer, digitFileFormat); + DigitReader dr(buffer); + + BOOST_CHECK_EQUAL(dr.nofDigits(), 47); +} + +BOOST_DATA_TEST_CASE(CheckReader, digitFileFormats, digitFileFormat) +{ + std::stringstream buffer; + writeTestData(buffer, digitFileFormat); + DigitReader dr(buffer); + + std::vector digits; + std::vector rofs; + + std::array digits_per_tf = {3, 5, 13}; + for (int itf = 0; itf < 3; ++itf) { + dr.read(digits, rofs); + BOOST_CHECK_EQUAL(digits.size(), digits_per_tf[itf]); + BOOST_CHECK_EQUAL(rofs.size(), 1); + BOOST_CHECK_EQUAL(rofs[0].getFirstIdx(), 0); + BOOST_CHECK_EQUAL(rofs[0].getLastIdx(), digits_per_tf[itf] - 1); + } + dr.read(digits, rofs); + int ndigits_4th_tf = digitFileFormat.fileVersion == 0 ? 8 : 26; + BOOST_CHECK_EQUAL(digits.size(), ndigits_4th_tf); + if (digitFileFormat.fileVersion == 0) { + BOOST_CHECK_EQUAL(rofs.size(), 1); + BOOST_CHECK_EQUAL(rofs[0].getFirstIdx(), 0); + BOOST_CHECK_EQUAL(rofs[0].getLastIdx(), 7); + } else { + BOOST_CHECK_EQUAL(rofs.size(), 3); + BOOST_CHECK_EQUAL(rofs[0].getFirstIdx(), 0); + BOOST_CHECK_EQUAL(rofs[0].getLastIdx(), 7); + BOOST_CHECK_EQUAL(rofs[1].getFirstIdx(), 8); + BOOST_CHECK_EQUAL(rofs[1].getLastIdx(), 15); + BOOST_CHECK_EQUAL(rofs[2].getFirstIdx(), 16); + BOOST_CHECK_EQUAL(rofs[2].getLastIdx(), 25); + } +} diff --git a/Detectors/MUON/MCH/DevIO/Digits/testDigitIOV0.cxx b/Detectors/MUON/MCH/DevIO/Digits/testDigitIOV0.cxx new file mode 100644 index 0000000000000..8e4d7a0eb83b4 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/testDigitIOV0.cxx @@ -0,0 +1,151 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include +#include +#include "DigitFileFormat.h" +#define BOOST_TEST_MODULE Test MCHWorkflow DigitsIO - V0 +#define BOOST_TEST_MAIN +#define BOOST_TEST_DYN_LINK + +#include +#include +#include "DigitIO.h" +#include +#include +#include +#include "DataFormatsMCH/Digit.h" +#include "DataFormatsMCH/ROFRecord.h" +#include +#include +#include +#include "DigitReaderImpl.h" +#include "TestFileV0.h" +#include "DigitD0.h" +using namespace o2::mch; +using namespace o2::mch::io; + +void bin2cpp(const char* filename = "digits.v3.in") +{ + // filename must point to a V0 format + std::ifstream in(filename); + int ndig; + int pos{8}; + int event{0}; + in.seekg(8); + while ((ndig = o2::mch::io::impl::advance(in, digitFileFormats[0].digitSize, "digits")) >= 0) { + int next = in.tellg(); + if (ndig < 40 || ndig == 96) { + std::cout << fmt::format("Event {:4d} {} ndigits between {} and {}\n", event, ndig, pos, next); + } + pos = next; + event++; + } + struct a { + int start, end; + }; + std::array positions = {a{17707576, 17708160}, a{38707380, 38708064}}; + std::vector bytes; + int i{1}; + for (auto p : positions) { + in.seekg(p.start); + int n = p.end - p.start; + bytes.resize(n); + in.read(reinterpret_cast(&bytes[0]), n); + if (in.tellg() != p.end) { + std::cout << "lost in file!\n"; + exit(1); + } + for (auto b : bytes) { + std::cout << fmt::format("0x{:02X},", b); + if (i % 16 == 0) { + std::cout << "\n"; + } + i++; + } + } + std::cout << "i=" << i << "\n"; +} + +BOOST_TEST_DECORATOR(*boost::unit_test::disabled()) +BOOST_AUTO_TEST_CASE(Bin2Cpp) +{ + bin2cpp(); +} +struct V0File { + V0File() + { + std::ostringstream buffer; + for (auto b : v0_buffer) { + buffer << b; + } + std::istringstream in(buffer.str()); + DigitReader r(in); + r.read(digits[0], rofs[0]); + r.read(digits[1], rofs[1]); + } + std::array, 2> digits; + std::array, 2> rofs; +}; + +BOOST_AUTO_TEST_CASE(CheckStructOffsets) +{ + BOOST_CHECK_EQUAL(offsetof(o2::mch::io::impl::DigitD0, tfTime), 0); + BOOST_CHECK_EQUAL(offsetof(o2::mch::io::impl::DigitD0, nofSamples), 4); + BOOST_CHECK_EQUAL(offsetof(o2::mch::io::impl::DigitD0, detID), 8); + BOOST_CHECK_EQUAL(offsetof(o2::mch::io::impl::DigitD0, padID), 12); + BOOST_CHECK_EQUAL(offsetof(o2::mch::io::impl::DigitD0, adc), 16); + BOOST_CHECK_EQUAL(sizeof(o2::mch::io::impl::DigitD0), 20); +} + +BOOST_FIXTURE_TEST_SUITE(SpotCheckV0, V0File) + +BOOST_AUTO_TEST_CASE(SpotCheckSizesV0) +{ + BOOST_CHECK_EQUAL(digits[0].size(), 29); + BOOST_CHECK_EQUAL(digits[1].size(), 34); + + BOOST_CHECK_EQUAL(rofs[0].size(), 1); + BOOST_CHECK_EQUAL(rofs[1].size(), 1); + + BOOST_CHECK_EQUAL(digits[0][20].getDetID(), 712); + BOOST_CHECK_EQUAL(digits[1][31].getDetID(), 1024); +} + +BOOST_TEST_DECORATOR(*boost::unit_test::disabled()) +BOOST_AUTO_TEST_CASE(SpotCheckDumpV0) +{ + DigitWriter w(std::cout); + w.write(digits[0], rofs[0]); + w.write(digits[1], rofs[1]); +} + +BOOST_TEST_DECORATOR(*boost::unit_test::disabled()) +BOOST_AUTO_TEST_CASE(SpotCheckDetIDV0) +{ + BOOST_CHECK_EQUAL(digits[0][20].getDetID(), 712); + BOOST_CHECK_EQUAL(digits[1][31].getDetID(), 1024); +} + +BOOST_TEST_DECORATOR(*boost::unit_test::disabled()) +BOOST_AUTO_TEST_CASE(SpotCheckPadIDV0) +{ + BOOST_CHECK_EQUAL(digits[0][20].getPadID(), 1661387464); + BOOST_CHECK_EQUAL(digits[1][31].getPadID(), 268444672); +} + +BOOST_TEST_DECORATOR(*boost::unit_test::disabled()) +BOOST_AUTO_TEST_CASE(SpotCheckADCV0) +{ + BOOST_CHECK_EQUAL(digits[0][20].getADC(), 1063648290); + BOOST_CHECK_EQUAL(digits[1][31].getADC(), 1065400059); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/Detectors/MUON/MCH/DevIO/README.md b/Detectors/MUON/MCH/DevIO/README.md new file mode 100644 index 0000000000000..6c140a792ccfd --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/README.md @@ -0,0 +1,9 @@ + + +I/O tools for reading and writing MCH data in custom debug formats + + diff --git a/Detectors/MUON/MCH/README.md b/Detectors/MUON/MCH/README.md index 534e4b8973de8..00db266f4d298 100644 --- a/Detectors/MUON/MCH/README.md +++ b/Detectors/MUON/MCH/README.md @@ -15,4 +15,5 @@ This is a top page for the MCH detector documentation. \subpage refDetectorsMUONMCHWorkflow \subpage refDetectorsMUONMCHGeometry \subpage refDetectorsMUONMCHConditions +\subpage refDetectorsMUONMCHDevIO /doxy --> From 5c2636dc9dd56b76e7c1f358d70f7fb7d5c3aa9d Mon Sep 17 00:00:00 2001 From: Ole Schmidt Date: Tue, 13 Apr 2021 11:38:52 +0200 Subject: [PATCH 112/770] TRD calibration subdirectory added (#5894) * TRD calibration subdirectory added - template for vDrift calibration - after global tracking angular differences between TRD-only tracks and tracklets are collected - small correction to always update to the correct pad plane during track following, since the pad row size depends also on the stack, not only on the layer * Remove copy-paste artifact (wrong comment) --- .../TRD/include/DataFormatsTRD/Constants.h | 1 + Detectors/TRD/CMakeLists.txt | 1 + Detectors/TRD/calibration/CMakeLists.txt | 17 ++ .../include/TRDCalibration/CalibVDrift.h | 68 ++++++++ Detectors/TRD/calibration/src/CalibVDrift.cxx | 50 ++++++ .../calibration/src/TRDCalibrationLinkDef.h | 19 +++ Detectors/TRD/workflow/CMakeLists.txt | 4 +- .../TRDWorkflow/TRDGlobalTrackingSpec.h | 2 + .../workflow/src/TRDGlobalTrackingSpec.cxx | 11 +- .../TRDTracking/GPUTRDInterfaces.h | 2 +- GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx | 152 +++++++++++++++++- GPU/GPUTracking/TRDTracking/GPUTRDTracker.h | 11 ++ 12 files changed, 326 insertions(+), 12 deletions(-) create mode 100644 Detectors/TRD/calibration/CMakeLists.txt create mode 100644 Detectors/TRD/calibration/include/TRDCalibration/CalibVDrift.h create mode 100644 Detectors/TRD/calibration/src/CalibVDrift.cxx create mode 100644 Detectors/TRD/calibration/src/TRDCalibrationLinkDef.h diff --git a/DataFormats/Detectors/TRD/include/DataFormatsTRD/Constants.h b/DataFormats/Detectors/TRD/include/DataFormatsTRD/Constants.h index 1a4cd01626406..79d6afad0f423 100644 --- a/DataFormats/Detectors/TRD/include/DataFormatsTRD/Constants.h +++ b/DataFormats/Detectors/TRD/include/DataFormatsTRD/Constants.h @@ -56,6 +56,7 @@ constexpr float GRANULARITYTRKLSLOPE = 1.f / PADGRANULARITYTRKLSLOPE; // granula // OS: Should this not be flexible for example in case of Kr calib? constexpr int TIMEBINS = 30; // the number of time bins +constexpr int NBINSANGLEDIFF = 26; // the number of bins for the track angle used for the vDrift and ExB calibration based on the tracking (last bin is for under-/overflow entries) // Trigger parameters constexpr double READOUT_TIME = 3000; // the time the readout takes, as 30 TB = 3 micro-s. diff --git a/Detectors/TRD/CMakeLists.txt b/Detectors/TRD/CMakeLists.txt index 97f3ae0f4f3f7..6adbc1c43d277 100644 --- a/Detectors/TRD/CMakeLists.txt +++ b/Detectors/TRD/CMakeLists.txt @@ -9,6 +9,7 @@ # submit itself to any jurisdiction. add_subdirectory(base) +add_subdirectory(calibration) add_subdirectory(simulation) add_subdirectory(reconstruction) add_subdirectory(macros) diff --git a/Detectors/TRD/calibration/CMakeLists.txt b/Detectors/TRD/calibration/CMakeLists.txt new file mode 100644 index 0000000000000..ba46a857e7c48 --- /dev/null +++ b/Detectors/TRD/calibration/CMakeLists.txt @@ -0,0 +1,17 @@ +#Copyright CERN and copyright holders of ALICE O2.This software is distributed +#under the terms of the GNU General Public License v3(GPL Version 3), copied +#verbatim in the file "COPYING". +# +#See http: //alice-o2.web.cern.ch/license for full licensing information. +# +#In applying this license CERN does not waive the privileges and immunities +#granted to it by virtue of its status as an Intergovernmental Organization or +#submit itself to any jurisdiction. + +o2_add_library(TRDCalibration + SOURCES src/CalibVDrift.cxx + PUBLIC_LINK_LIBRARIES O2::TRDBase + O2::DataFormatsTRD) + + o2_target_root_dictionary(TRDCalibration + HEADERS include/TRDCalibration/CalibVDrift.h) diff --git a/Detectors/TRD/calibration/include/TRDCalibration/CalibVDrift.h b/Detectors/TRD/calibration/include/TRDCalibration/CalibVDrift.h new file mode 100644 index 0000000000000..7e24a72b798b8 --- /dev/null +++ b/Detectors/TRD/calibration/include/TRDCalibration/CalibVDrift.h @@ -0,0 +1,68 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef ALICEO2_TRD_CALIBVDRIFT_H_ +#define ALICEO2_TRD_CALIBVDRIFT_H_ + +/// \file CalibVDrift.h +/// \author Ole Schmidt, ole.schmidt@cern.ch + +#include "DataFormatsTRD/Constants.h" +#include + +namespace o2 +{ +namespace trd +{ + +/// \brief VDrift calibration class +/// +/// This class is used to determine chamber-wise vDrift values +/// +/// origin: TRD +/// \author Ole Schmidt, ole.schmidt@cern.ch + +class CalibVDrift +{ + public: + /// default constructor + CalibVDrift() = default; + + /// default destructor + ~CalibVDrift() = default; + + /// set input angular difference sums + void setAngleDiffSums(float* input) + { + for (int i = 0; i < constants::MAXCHAMBER * constants::NBINSANGLEDIFF; ++i) { + mAngleDiffSums[i] = input[i]; + } + } + + /// set input angular difference bin counters + void setAngleDiffCounters(short* input) + { + for (int i = 0; i < constants::MAXCHAMBER * constants::NBINSANGLEDIFF; ++i) { + mAngleDiffCounters[i] = input[i]; + } + } + + /// main processing function + void process(); + + private: + std::array mAngleDiffSums{}; ///< input TRD track to tracklet angular difference sums per bin + std::array mAngleDiffCounters{}; ///< input bin counters +}; + +} // namespace trd + +} // namespace o2 +#endif diff --git a/Detectors/TRD/calibration/src/CalibVDrift.cxx b/Detectors/TRD/calibration/src/CalibVDrift.cxx new file mode 100644 index 0000000000000..65076f82d21df --- /dev/null +++ b/Detectors/TRD/calibration/src/CalibVDrift.cxx @@ -0,0 +1,50 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file CalibVDrift.cxx +/// \author Ole Schmidt, ole.schmidt@cern.ch + +#include "TFile.h" +#include "TH2F.h" + +#include + +#include "TRDCalibration/CalibVDrift.h" + +using namespace o2::trd; +using namespace o2::trd::constants; + +void CalibVDrift::process() +{ + LOG(info) << "Started processing for vDrift calibration"; + + for (int iDet = 0; iDet < constants::MAXCHAMBER; ++iDet) { + for (int iBin = 0; iBin < constants::NBINSANGLEDIFF; ++iBin) { // note: iBin = constants::NBINSANGLEDIFF - 1 is under-/overflow bin + short nEntries = mAngleDiffCounters[iDet * constants::NBINSANGLEDIFF + iBin]; + float angleDiffSum = mAngleDiffSums[iDet * constants::NBINSANGLEDIFF + iBin]; + if (nEntries > 0) { + LOGF(INFO, "Found %i entrie(s) in chamber %i, bin %i. Average angular deviation: %f", nEntries, iDet, iBin, angleDiffSum / nEntries); + } + } + } + + /* + // as an example I loop over the input, create a histogram and write it to a file + auto fOut = TFile::Open("trdcalibdummy.root", "recreate"); + auto hXY = std::make_unique("histDummy", "foo", 100, -60, 60, 100, 250, 400); // xy distribution of TRD space points + for (int i = 0; i < mAngulerDeviationProf.size(); ++i) { + hXY->Fill(mAngulerDeviationProf[i].mX[0], mAngulerDeviationProf[i].mR); + } + fOut->cd(); + hXY->Write(); + hXY.reset(); // delete the histogram before closing the output file + fOut->Close(); + */ +} diff --git a/Detectors/TRD/calibration/src/TRDCalibrationLinkDef.h b/Detectors/TRD/calibration/src/TRDCalibrationLinkDef.h new file mode 100644 index 0000000000000..6f10a82a50b64 --- /dev/null +++ b/Detectors/TRD/calibration/src/TRDCalibrationLinkDef.h @@ -0,0 +1,19 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifdef __CLING__ + +#pragma link off all globals; +#pragma link off all classes; +#pragma link off all functions; + +#pragma link C++ class o2::trd::CalibVDrift + ; + +#endif diff --git a/Detectors/TRD/workflow/CMakeLists.txt b/Detectors/TRD/workflow/CMakeLists.txt index 589932309585b..402102d857b2e 100644 --- a/Detectors/TRD/workflow/CMakeLists.txt +++ b/Detectors/TRD/workflow/CMakeLists.txt @@ -25,8 +25,8 @@ o2_add_library(TRDWorkflow src/TRDTrackWriterSpec.cxx src/TRDTrackingWorkflow.cxx src/EntropyDecoderSpec.cxx - src/EntropyEncoderSpec.cxx - PUBLIC_LINK_LIBRARIES O2::Framework O2::DPLUtils O2::Steer O2::Algorithm O2::DataFormatsTRD O2::TRDSimulation O2::TRDReconstruction O2::DetectorsBase O2::SimulationDataFormat O2::TRDBase O2::GPUTracking O2::GlobalTrackingWorkflow) + src/EntropyEncoderSpec.cxx + PUBLIC_LINK_LIBRARIES O2::Framework O2::DPLUtils O2::Steer O2::Algorithm O2::DataFormatsTRD O2::TRDSimulation O2::TRDReconstruction O2::DetectorsBase O2::SimulationDataFormat O2::TRDBase O2::TRDCalibration O2::GPUTracking O2::GlobalTrackingWorkflow) #o2_target_root_dictionary(TRDWorkflow # HEADERS include/TRDWorkflow/TRDTrapSimulatorSpec.h) diff --git a/Detectors/TRD/workflow/include/TRDWorkflow/TRDGlobalTrackingSpec.h b/Detectors/TRD/workflow/include/TRDWorkflow/TRDGlobalTrackingSpec.h index 3613cf620ca15..ec7bb972b8bec 100644 --- a/Detectors/TRD/workflow/include/TRDWorkflow/TRDGlobalTrackingSpec.h +++ b/Detectors/TRD/workflow/include/TRDWorkflow/TRDGlobalTrackingSpec.h @@ -17,6 +17,7 @@ #include "Framework/Task.h" #include "TStopwatch.h" #include "TRDBase/GeometryFlat.h" +#include "TRDCalibration/CalibVDrift.h" #include "GPUO2Interface.h" #include "GPUTRDTracker.h" @@ -41,6 +42,7 @@ class TRDGlobalTracking : public o2::framework::Task std::unique_ptr mFlatGeo{nullptr}; ///< flat TRD geometry bool mUseMC{false}; ///< MC flag bool mUseTrackletTransform{false}; ///< if true, output from TrackletTransformer is used instead of uncalibrated Tracklet64 directly + CalibVDrift mCalibVDrift{}; ///< steers the vDrift calibration TStopwatch mTimer; }; diff --git a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx index 57a79011f8bb8..c7a3596fcece8 100644 --- a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx @@ -22,6 +22,7 @@ #include "DataFormatsTRD/Tracklet64.h" #include "DataFormatsTRD/CalibratedTracklet.h" #include "DataFormatsTRD/TriggerRecord.h" +#include "DataFormatsTRD/Constants.h" // GPU header #include "GPUReconstruction.h" @@ -68,6 +69,7 @@ void TRDGlobalTracking::init(InitContext& ic) mTracker->SetProcessPerTimeFrame(); mTracker->SetNMaxCollisions(mRec->GetProcessingSettings().trdNMaxCollisions); mTracker->SetTrkltTransformNeeded(!mUseTrackletTransform); + //mTracker->SetDoImpactAngleHistograms(true); mRec->RegisterGPUProcessor(mTracker, false); mChainTracking->SetTRDGeometry(std::move(mFlatGeo)); @@ -99,7 +101,7 @@ void TRDGlobalTracking::run(ProcessingContext& pc) int nTrackletsCal = 0; if (mUseTrackletTransform) { - cTrklts.emplace(pc.inputs().get>("trdctracklets")); // MC labels associated to the input digits + cTrklts.emplace(pc.inputs().get>("trdctracklets")); cTrkltsPtr = &cTrklts.value(); nTrackletsCal = cTrkltsPtr->size(); LOGF(INFO, "Got %i calibrated tracklets as input", nTrackletsCal); @@ -171,11 +173,18 @@ void TRDGlobalTracking::run(ProcessingContext& pc) mTracker->SetTriggerRecordIndices(&(trdTriggerIndices[0])); mTracker->SetNCollisions(nCollisions); //mTracker->DumpTracks(); + mTracker->ResetImpactAngleHistograms(); mTracker->DoTracking(mChainTracking); //mTracker->DumpTracks(); std::vector tracksOut(mTracker->NTracks()); std::copy(mTracker->Tracks(), mTracker->Tracks() + mTracker->NTracks(), tracksOut.begin()); + + // Temporary until it is transferred to its own DPL device for calibrations + mCalibVDrift.setAngleDiffSums(mTracker->AngleDiffSums()); + mCalibVDrift.setAngleDiffCounters(mTracker->AngleDiffCounters()); + mCalibVDrift.process(); + pc.outputs().snapshot(Output{o2::header::gDataOriginTRD, "MATCHTRD", 0, Lifetime::Timeframe}, tracksOut); mTimer.Stop(); diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h index f6d71d93c60f6..e5a234d6b6eca 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h @@ -301,7 +301,7 @@ class trackInterface : public GPUTPCGMTrackParam GPUd() const float* getPar() const { return GetPar(); } GPUd() const float* getCov() const { return GetCov(); } GPUd() float getTime() const { return -1.f; } - + GPUd() void resetCovariance(float s) { ResetCovariance(); } GPUd() void setAlpha(float alpha) { mAlpha = alpha; } GPUd() void set(float x, float alpha, const float param[5], const float cov[15]) { diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx index 838fec471e870..fec9f3f3ff921 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx @@ -75,6 +75,8 @@ void* GPUTRDTracker_t::SetPointersBase(void* base) computePointerWithAlignment(base, mTrackletIndexArray, (kNChambers + 1) * mNMaxCollisions); computePointerWithAlignment(base, mHypothesis, mNCandidates * mMaxThreads); computePointerWithAlignment(base, mCandidates, mNCandidates * 2 * mMaxThreads); + computePointerWithAlignment(base, mAngleDiffSums, kNChambers * (mNAngleHistogramBins + 1)); + computePointerWithAlignment(base, mAngleDiffCounters, kNChambers * (mNAngleHistogramBins + 1)); return base; } @@ -103,7 +105,7 @@ void* GPUTRDTracker_t::SetPointersTracks(void* base) } template -GPUTRDTracker_t::GPUTRDTracker_t() : mR(nullptr), mIsInitialized(false), mTrkltTransfNeeded(true), mProcessPerTimeFrame(false), mMemoryPermanent(-1), mMemoryTracklets(-1), mMemoryTracks(-1), mNMaxCollisions(1), mNMaxTracks(0), mNMaxSpacePoints(0), mTracks(nullptr), mNCandidates(1), mNCollisions(1), mNTracks(0), mNEvents(0), mTriggerRecordIndices(nullptr), mTriggerRecordTimes(nullptr), mTracklets(nullptr), mTrackletIndices(nullptr), mMaxThreads(100), mNTracklets(0), mTrackletIndexArray(nullptr), mHypothesis(nullptr), mCandidates(nullptr), mSpacePoints(nullptr), mTrackletLabels(nullptr), mGeo(nullptr), mRPhiA2(0), mRPhiB(0), mRPhiC2(0), mDyA2(0), mDyB(0), mDyC2(0), mAngleToDyA(0), mAngleToDyB(0), mAngleToDyC(0), mDebugOutput(false), mTimeWindow(.1f), mRadialOffset(-0.1), mMaxEta(0.84f), mExtraRoadY(2.f), mRoadZ(18.f), mZCorrCoefNRC(1.4f), mMCEvent(nullptr), mDebug(new GPUTRDTrackerDebug()) +GPUTRDTracker_t::GPUTRDTracker_t() : mR(nullptr), mIsInitialized(false), mTrkltTransfNeeded(true), mDoImpactAngleHistograms(false), mProcessPerTimeFrame(false), mMemoryPermanent(-1), mMemoryTracklets(-1), mMemoryTracks(-1), mNMaxCollisions(1), mNMaxTracks(0), mNMaxSpacePoints(0), mTracks(nullptr), mNCandidates(1), mNCollisions(1), mNTracks(0), mNEvents(0), mTriggerRecordIndices(nullptr), mTriggerRecordTimes(nullptr), mTracklets(nullptr), mTrackletIndices(nullptr), mMaxThreads(100), mNTracklets(0), mTrackletIndexArray(nullptr), mHypothesis(nullptr), mNAngleHistogramBins(25), mAngleHistogramRange(50), mCandidates(nullptr), mSpacePoints(nullptr), mAngleDiffSums(nullptr), mAngleDiffCounters(nullptr), mTrackletLabels(nullptr), mGeo(nullptr), mRPhiA2(0), mRPhiB(0), mRPhiC2(0), mDyA2(0), mDyB(0), mDyC2(0), mAngleToDyA(0), mAngleToDyB(0), mAngleToDyC(0), mDebugOutput(false), mTimeWindow(.1f), mRadialOffset(-0.1), mMaxEta(0.84f), mExtraRoadY(2.f), mRoadZ(18.f), mZCorrCoefNRC(1.4f), mMCEvent(nullptr), mDebug(new GPUTRDTrackerDebug()) { //-------------------------------------------------------------------- // Default constructor @@ -272,6 +274,18 @@ void GPUTRDTracker_t::DoTracking(GPUChainTracking* chainTracking) #endif } + if (mDoImpactAngleHistograms) { + GPUInfo("Start calculating angular differences"); + for (int iTrk = 0; iTrk < mNTracks; ++iTrk) { + if (mTracks[iTrk].GetNtracklets() > 3) { + auto trkCopy = mTracks[iTrk]; + PROP prop(&Param().polynomialField); + prop.setFitInProjections(true); + prop.setTrack(&trkCopy); + FillImpactAngleHistograms(&prop, &trkCopy); + } + } + } auto duration = std::chrono::high_resolution_clock::now() - timeStart; (void)duration; // suppress warning about unused variable /* @@ -605,6 +619,125 @@ GPUd() bool GPUTRDTracker_t::CalculateSpacePoints(int iCollision) } return result; } +template +GPUd() void GPUTRDTracker_t::ResetImpactAngleHistograms() +{ + GPUInfo("Resetting angle histograms"); + for (int i = 0; i < kNChambers * (mNAngleHistogramBins + 1); i++) { + mAngleDiffSums[i] = 0; + mAngleDiffCounters[i] = 0; + } +} + +template +GPUd() int GPUTRDTracker_t::FillImpactAngleHistograms(PROP* prop, TRDTRK* t) +{ + //-------------------------------------------------------------------- + // To calibrate vDrift and ExB based on the online tracklets this function + // collects the differences between TRD-only tracks and their associated + // tracklets + // returns 0 in case of success + //-------------------------------------------------------------------- + float invBinWidth = mNAngleHistogramBins / mAngleHistogramRange; + t->SetChi2(0.f); + t->resetCovariance(100); + + // first inward propagation (TRD track fit) + for (int iLayer = kNLayers - 1; iLayer >= 0; --iLayer) { + if (t->GetTracklet(iLayer) == -1) { + continue; + } + if (PropagateToLayerAndUpdate(prop, t, iLayer)) { + return 1; + } + } + + // outward propagation (smoothing) + for (int iLayer = 1; iLayer < kNLayers; ++iLayer) { + if (t->GetTracklet(iLayer) == -1) { + continue; + } + if (PropagateToLayerAndUpdate(prop, t, iLayer)) { + return 2; + } + } + + // second inward propagation (collect angular differences between tracklets + TRD track) + for (int iLayer = kNLayers - 1; iLayer >= 0; --iLayer) { + if (t->GetTracklet(iLayer) == -1) { + continue; + } + if (PropagateToLayerAndUpdate(prop, t, iLayer, false)) { + return 3; + } + float radToDeg = 180.f / CAMath::Pi(); + float trkAngle = CAMath::ASin(t->getSnp()) * radToDeg; + float trkltAngle = CAMath::ATan(mSpacePoints[t->GetTracklet(iLayer)].mDy / 3.) * radToDeg; + + int idxOffsetDet = mTracklets[t->GetTracklet(iLayer)].GetDetector() * (mNAngleHistogramBins + 1); + int idxOffsetAngle = (trkAngle + .5 * mAngleHistogramRange) * invBinWidth; + + if (CAMath::Abs(idxOffsetAngle) >= .5 * mAngleHistogramRange) { + idxOffsetAngle = mNAngleHistogramBins; + } + + mAngleDiffSums[idxOffsetDet + idxOffsetAngle] += trkltAngle - trkAngle; + mAngleDiffCounters[idxOffsetDet + idxOffsetAngle]++; + + //GPUInfo("trkAngle(%f), idxOffsetAngle(%i), angleDifference(%f)", trkAngle, idxOffsetAngle, trkltAngle - trkAngle); + } + return 0; +} + +template +GPUd() int GPUTRDTracker_t::PropagateToLayerAndUpdate(PROP* prop, TRDTRK* trkWork, int iLayer, bool doUpdate) +{ + //-------------------------------------------------------------------- + // Propagates the track to TRD layer iLayer and updates the track + // parameters (if requested) + // returns 0 in case of success + //-------------------------------------------------------------------- + int trackletID = trkWork->GetTracklet(iLayer); + int trackletDet = mTracklets[trackletID].GetDetector(); + int trackletSector = trackletDet / (kNLayers * kNStacks); + int trackletStack = (trackletDet % (kNLayers * kNStacks)) / kNLayers; + + if (trackletSector != GetSector(prop->getAlpha())) { + if (!prop->rotate(GetAlphaOfSector(trackletSector))) { + GPUInfo("Track could not be rotated in tracklet coordinate system"); + return 1; + } + } + + if (!prop->propagateToX(mSpacePoints[trackletID].mR, .8f, 2.f)) { + GPUInfo("Track propagation failed in layer %i (pt=%f, xTrk=%f, xToGo=%f)", iLayer, trkWork->getPt(), trkWork->getX(), mSpacePoints[trackletID].mR); + return 2; + } + + if (!doUpdate) { + // nothing more to be done + return 0; + } + + const GPUTRDpadPlane* pad = mGeo->GetPadPlane(iLayer, trackletStack); + float tilt = CAMath::Tan(CAMath::Pi() / 180.f * pad->GetTiltingAngle()); // tilt is signed! + float tiltCorrUp = tilt * (mSpacePoints[trackletID].mX[1] - trkWork->getZ()); + float zPosCorrUp = mSpacePoints[trackletID].mX[1] + mZCorrCoefNRC * trkWork->getTgl(); + float padLength = pad->GetRowSize(mTracklets[trackletID].GetZbin()); + if (!((trkWork->getSigmaZ2() < (padLength * padLength / 12.f)) && (CAMath::Abs(mSpacePoints[trackletID].mX[1] - trkWork->getZ()) < padLength))) { + tiltCorrUp = 0.f; + } + + My_Float trkltPosUp[2] = {mSpacePoints[trackletID].mX[0] - tiltCorrUp, zPosCorrUp}; + My_Float trkltCovUp[3] = {0.f}; + RecalcTrkltCov(tilt, trkWork->getSnp(), pad->GetRowSize(mTracklets[trackletID].GetZbin()), trkltCovUp); + + if (!prop->update(trkltPosUp, trkltCovUp)) { + GPUWarning("Failed to update track with space point in layer %i", iLayer); + return 3; + } + return 0; +} template GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK* t, int threadId, int collisionId) @@ -733,6 +866,7 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK if (currDet == -1) { continue; } + pad = mGeo->GetPadPlane(currDet); int currSec = mGeo->GetSector(currDet); if (currSec != GetSector(prop->getAlpha())) { if (!prop->rotate(GetAlphaOfSector(currSec))) { @@ -762,10 +896,10 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK } float projY, projZ; prop->getPropagatedYZ(mSpacePoints[trkltIdxGlb].mR, projY, projZ); - // correction for tilted pads (only applied if deltaZ < l_pad && track z err << l_pad) + // correction for tilted pads (only applied if deltaZ < lPad && track z err << lPad) float tiltCorr = tilt * (mSpacePoints[trkltIdxGlb].mX[1] - projZ); - float l_pad = pad->GetRowSize(mTracklets[trkltIdxGlb].GetZbin()); - if (!((CAMath::Abs(mSpacePoints[trkltIdxGlb].mX[1] - projZ) < l_pad) && (trkWork->getSigmaZ2() < (l_pad * l_pad / 12.f)))) { + float lPad = pad->GetRowSize(mTracklets[trkltIdxGlb].GetZbin()); + if (!((CAMath::Abs(mSpacePoints[trkltIdxGlb].mX[1] - projZ) < lPad) && (trkWork->getSigmaZ2() < (lPad * lPad / 12.f)))) { tiltCorr = 0.f; } // correction for mean z position of tracklet (is not the center of the pad if track eta != 0) @@ -800,6 +934,7 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK mDebug->SetNmatchAvail(matchAvailableAll[iLayer].size(), iLayer); int realTrkltId = matchAvailableAll[iLayer].at(0); int realTrkltDet = mTracklets[realTrkltId].GetDetector(); + pad = mGeo->GetPadPlane(realTrkltDet); prop->rotate(GetAlphaOfSector(mGeo->GetSector(realTrkltDet))); if (!prop->propagateToX(mSpacePoints[realTrkltId].mR, .8f, 2.f) || GetSector(prop->getAlpha()) != mGeo->GetSector(realTrkltDet)) { if (ENABLE_WARNING) { @@ -811,8 +946,8 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK float zPosCorrReal = mSpacePoints[realTrkltId].mX[1] + mZCorrCoefNRC * trkWork->getTgl(); float deltaZReal = zPosCorrReal - trkWork->getZ(); float tiltCorrReal = tilt * (mSpacePoints[realTrkltId].mX[1] - trkWork->getZ()); - float l_padReal = pad->GetRowSize(mTracklets[realTrkltId].GetZbin()); - if ((trkWork->getSigmaZ2() >= (l_padReal * l_padReal / 12.f)) || (CAMath::Abs(mSpacePoints[realTrkltId].mX[1] - trkWork->getZ()) >= l_padReal)) { + float lPadReal = pad->GetRowSize(mTracklets[realTrkltId].GetZbin()); + if ((trkWork->getSigmaZ2() >= (lPadReal * lPadReal / 12.f)) || (CAMath::Abs(mSpacePoints[realTrkltId].mX[1] - trkWork->getZ()) >= lPadReal)) { tiltCorrReal = 0; } My_Float yzPosReal[2] = {mSpacePoints[realTrkltId].mX[0] - tiltCorrReal, zPosCorrReal}; @@ -890,10 +1025,11 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK continue; } + pad = mGeo->GetPadPlane(mTracklets[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].GetDetector()); float tiltCorrUp = tilt * (mSpacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].mX[1] - trkWork->getZ()); float zPosCorrUp = mSpacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].mX[1] + mZCorrCoefNRC * trkWork->getTgl(); - float l_padTrklt = pad->GetRowSize(mTracklets[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].GetZbin()); - if (!((trkWork->getSigmaZ2() < (l_padTrklt * l_padTrklt / 12.f)) && (CAMath::Abs(mSpacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].mX[1] - trkWork->getZ()) < l_padTrklt))) { + float padLength = pad->GetRowSize(mTracklets[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].GetZbin()); + if (!((trkWork->getSigmaZ2() < (padLength * padLength / 12.f)) && (CAMath::Abs(mSpacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].mX[1] - trkWork->getZ()) < padLength))) { tiltCorrUp = 0.f; } My_Float trkltPosUp[2] = {mSpacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].mX[0] - tiltCorrUp, zPosCorrUp}; diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h index ea3bbbc9cd060..da91005d9370d 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h @@ -122,6 +122,9 @@ class GPUTRDTracker_t : public GPUProcessor GPUd() void DoTrackingThread(int iTrk, int threadId = 0); GPUd() bool CalculateSpacePoints(int iCollision = 0); GPUd() bool FollowProlongation(PROP* prop, TRDTRK* t, int threadId, int collisionId); + GPUd() int FillImpactAngleHistograms(PROP* prop, TRDTRK* t); + GPUd() void ResetImpactAngleHistograms(); + GPUd() int PropagateToLayerAndUpdate(PROP* prop, TRDTRK* trkWork, int iLayer, bool doUpdate = true); GPUd() int GetDetectorNumber(const float zPos, const float alpha, const int layer) const; GPUd() bool AdjustSector(PROP* prop, TRDTRK* t) const; GPUd() int GetSector(float alpha) const; @@ -146,6 +149,7 @@ class GPUTRDTracker_t : public GPUProcessor // settings GPUd() void SetTrkltTransformNeeded(bool flag) { mTrkltTransfNeeded = flag; } GPUd() void SetProcessPerTimeFrame() { mProcessPerTimeFrame = true; } + GPUd() void SetDoImpactAngleHistograms(bool flag) { mDoImpactAngleHistograms = flag; } GPUd() void SetMCEvent(AliMCEvent* mc) { mMCEvent = mc; } GPUd() void EnableDebugOutput() { mDebugOutput = true; } GPUd() void SetMaxEta(float maxEta) { mMaxEta = maxEta; } @@ -164,6 +168,8 @@ class GPUTRDTracker_t : public GPUProcessor GPUd() TRDTRK* Tracks() const { return mTracks; } GPUd() int NTracklets() const { return mNTracklets; } GPUd() GPUTRDSpacePointInternal* SpacePoints() const { return mSpacePoints; } + GPUd() float* AngleDiffSums() const { return mAngleDiffSums; } + GPUd() short* AngleDiffCounters() const { return mAngleDiffCounters; } GPUd() GPUTRDTrackletWord* Tracklets() const { return mTracklets; } GPUd() void DumpTracks(); @@ -172,6 +178,9 @@ class GPUTRDTracker_t : public GPUProcessor bool mIsInitialized; // flag is set upon initialization bool mTrkltTransfNeeded; // if the output of the TRDTrackletTransformer is used we don't need to do the coordinate transformation for the tracklets bool mProcessPerTimeFrame; // if true, tracking is done per time frame instead of on a single events basis + bool mDoImpactAngleHistograms; // if true, impact angle vs angle difference histograms are filled + short mNAngleHistogramBins; // number of bins per chamber for the angular difference histograms + float mAngleHistogramRange; // range of impact angles covered by each histogram short mMemoryPermanent; // size of permanent memory for the tracker short mMemoryTracklets; // size of memory for TRD tracklets short mMemoryTracks; // size of memory for tracks (used for i/o) @@ -196,6 +205,8 @@ class GPUTRDTracker_t : public GPUProcessor Hypothesis* mHypothesis; // array with multiple track hypothesis TRDTRK* mCandidates; // array of tracks for multiple hypothesis tracking GPUTRDSpacePointInternal* mSpacePoints; // array with tracklet coordinates in global tracking frame + float* mAngleDiffSums; // array with sum of angular differences for a given bin + short* mAngleDiffCounters; // array with number of entries for a given bin int* mTrackletLabels; // array with MC tracklet labels TRD_GEOMETRY_CONST GPUTRDGeometry* mGeo; // TRD geometry /// ---- error parametrization depending on magnetic field ---- From c7ec842ce41a387b0910d3cad604c23bfb5e6522 Mon Sep 17 00:00:00 2001 From: ddobrigk Date: Tue, 13 Apr 2021 08:47:01 -0300 Subject: [PATCH 113/770] Add Armenteros-podolanski vars to str tables (#5892) * Add Armenteros-podolanski vars to str tables * Follow clang format rules * Update StrangenessTables.h --- .../AnalysisDataModel/StrangenessTables.h | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/Analysis/DataModel/include/AnalysisDataModel/StrangenessTables.h b/Analysis/DataModel/include/AnalysisDataModel/StrangenessTables.h index 87115f6c5d518..a41852bbc7589 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/StrangenessTables.h +++ b/Analysis/DataModel/include/AnalysisDataModel/StrangenessTables.h @@ -52,14 +52,30 @@ DECLARE_SOA_DYNAMIC_COLUMN(V0Radius, v0radius, [](float x, float y) { return Rec DECLARE_SOA_DYNAMIC_COLUMN(V0CosPA, v0cosPA, [](float X, float Y, float Z, float Px, float Py, float Pz, float pvX, float pvY, float pvZ) { return RecoDecay::CPA(array{pvX, pvY, pvZ}, array{X, Y, Z}, array{Px, Py, Pz}); }); DECLARE_SOA_DYNAMIC_COLUMN(DCAV0ToPV, dcav0topv, [](float X, float Y, float Z, float Px, float Py, float Pz, float pvX, float pvY, float pvZ) { return std::sqrt((std::pow((pvY - Y) * Pz - (pvZ - Z) * Py, 2) + std::pow((pvX - X) * Pz - (pvZ - Z) * Px, 2) + std::pow((pvX - X) * Py - (pvY - Y) * Px, 2)) / (Px * Px + Py * Py + Pz * Pz)); }); +//Armenteros-Podolanski variables +DECLARE_SOA_DYNAMIC_COLUMN(Alpha, alpha, [](float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) { + float momTot = RecoDecay::P(pxpos + pxneg, pypos + pyneg, pzpos + pzneg); + float lQlNeg = RecoDecay::dotProd(array{pxneg, pyneg, pzneg}, array{pxpos + pxneg, pypos + pyneg, pzpos + pzneg}) / momTot; + float lQlPos = RecoDecay::dotProd(array{pxpos, pypos, pzpos}, array{pxpos + pxneg, pypos + pyneg, pzpos + pzneg}) / momTot; + return (lQlPos - lQlNeg) / (lQlPos + lQlNeg); //alphav0 +}); + +DECLARE_SOA_DYNAMIC_COLUMN(QtArm, qtarm, [](float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) { + float momTot = RecoDecay::P2(pxpos + pxneg, pypos + pyneg, pzpos + pzneg); + float dp = RecoDecay::dotProd(array{pxneg, pyneg, pzneg}, array{pxpos + pxneg, pypos + pyneg, pzpos + pzneg}); + return std::sqrt(RecoDecay::P2(pxneg, pyneg, pzneg) - dp * dp / momTot); //qtarm +}); + //Calculated on the fly with mass assumption + dynamic tables DECLARE_SOA_DYNAMIC_COLUMN(MLambda, mLambda, [](float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) { return RecoDecay::M(array{array{pxpos, pypos, pzpos}, array{pxneg, pyneg, pzneg}}, array{RecoDecay::getMassPDG(kProton), RecoDecay::getMassPDG(kPiPlus)}); }); DECLARE_SOA_DYNAMIC_COLUMN(MAntiLambda, mAntiLambda, [](float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) { return RecoDecay::M(array{array{pxpos, pypos, pzpos}, array{pxneg, pyneg, pzneg}}, array{RecoDecay::getMassPDG(kPiPlus), RecoDecay::getMassPDG(kProton)}); }); DECLARE_SOA_DYNAMIC_COLUMN(MK0Short, mK0Short, [](float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) { return RecoDecay::M(array{array{pxpos, pypos, pzpos}, array{pxneg, pyneg, pzneg}}, array{RecoDecay::getMassPDG(kPiPlus), RecoDecay::getMassPDG(kPiPlus)}); }); +DECLARE_SOA_DYNAMIC_COLUMN(MGamma, mGamma, [](float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) { return RecoDecay::M(array{array{pxpos, pypos, pzpos}, array{pxneg, pyneg, pzneg}}, array{RecoDecay::getMassPDG(kElectron), RecoDecay::getMassPDG(kElectron)}); }); DECLARE_SOA_DYNAMIC_COLUMN(YK0Short, yK0Short, [](float Px, float Py, float Pz) { return RecoDecay::Y(array{Px, Py, Pz}, RecoDecay::getMassPDG(kK0)); }); DECLARE_SOA_DYNAMIC_COLUMN(YLambda, yLambda, [](float Px, float Py, float Pz) { return RecoDecay::Y(array{Px, Py, Pz}, RecoDecay::getMassPDG(kLambda0)); }); DECLARE_SOA_DYNAMIC_COLUMN(Eta, eta, [](float Px, float Py, float Pz) { return RecoDecay::Eta(array{Px, Py, Pz}); }); +DECLARE_SOA_DYNAMIC_COLUMN(Phi, phi, [](float Px, float Py) { return RecoDecay::Phi(Px, Py); }); DECLARE_SOA_EXPRESSION_COLUMN(Px, px, float, 1.f * aod::v0data::pxpos + 1.f * aod::v0data::pxneg); DECLARE_SOA_EXPRESSION_COLUMN(Py, py, float, 1.f * aod::v0data::pypos + 1.f * aod::v0data::pyneg); @@ -79,16 +95,20 @@ DECLARE_SOA_TABLE_FULL(StoredV0Datas, "V0Datas", "AOD", "V0DATA", v0data::V0Radius, v0data::V0CosPA, v0data::DCAV0ToPV, + v0data::Alpha, + v0data::QtArm, //Invariant masses v0data::MLambda, v0data::MAntiLambda, v0data::MK0Short, + v0data::MGamma, //Longitudinal v0data::YK0Short, v0data::YLambda, - v0data::Eta); + v0data::Eta, + v0data::Phi); // extended table with expression columns that can be used as arguments of dynamic columns DECLARE_SOA_EXTENDED_TABLE_USER(V0Datas, StoredV0Datas, "V0DATAEXT", From af4ab538c7d9f322c13bf837073e034fa1ee3124 Mon Sep 17 00:00:00 2001 From: Gian Michele Innocenti Date: Tue, 13 Apr 2021 22:06:03 +0200 Subject: [PATCH 114/770] Add PWGHF code owner (#5891) --- CODEOWNERS | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CODEOWNERS b/CODEOWNERS index aa0fb29d2fb26..927cbf9896cf0 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -13,8 +13,8 @@ /Algorithm @matthiasrichter /Analysis @jgrosseo @iarsene -/Analysis/Tasks/ALICE3 @ginnocen -/Analysis/Tasks/PWGHF @ginnocen +/Analysis/Tasks/ALICE3 @ginnocen @vkucera +/Analysis/Tasks/PWGHF @ginnocen @vkucera /CCDB @costing @Barthelemy @sawenzel @AliceO2Group/framework-admins From e91375b50835de9ea544b49e2a703f73f551d19e Mon Sep 17 00:00:00 2001 From: Matteo Concas Date: Wed, 7 Apr 2021 09:34:37 +0200 Subject: [PATCH 115/770] Use base::Propagator instead manual prop --- .../tracking/include/ITStracking/Tracker.h | 8 ++- Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx | 60 +++++++++++-------- 2 files changed, 42 insertions(+), 26 deletions(-) diff --git a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Tracker.h b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Tracker.h index 76c5acd946066..e756f63153495 100644 --- a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Tracker.h +++ b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Tracker.h @@ -44,6 +44,12 @@ namespace o2 { +namespace base +{ +template +class PropagatorImpl; +} + namespace gpu { class GPUChainITS; @@ -89,7 +95,7 @@ class Tracker void findCellsNeighbours(int& iteration); void findRoads(int& iteration); void findTracks(const ROframe& ev); - bool fitTrack(const ROframe& event, TrackITSExt& track, int start, int end, int step, + bool fitTrack(const ROframe& event, TrackITSExt& track, int start, int end, int step, o2::base::PropagatorImpl* propPtr, const float chi2cut = o2::constants::math::VeryBig); void traverseCellsTree(const int, const int); void computeRoadsMClabels(const ROframe&); diff --git a/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx b/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx index bea9fe7a23525..f80404c240cc7 100644 --- a/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx +++ b/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx @@ -17,6 +17,7 @@ #include "ITStracking/Cell.h" #include "ITStracking/Constants.h" #include "ITStracking/IndexTableUtils.h" +#include "DetectorsBase/Propagator.h" #include "ITStracking/Tracklet.h" #include "ITStracking/TrackerTraits.h" #include "ITStracking/TrackerTraitsCPU.h" @@ -233,6 +234,9 @@ void Tracker::findTracks(const ROframe& event) mTracks.reserve(mTracks.capacity() + mPrimaryVertexContext->getRoads().size()); std::vector tracks; tracks.reserve(mPrimaryVertexContext->getRoads().size()); + + auto propagator = o2::base::Propagator::Instance(); + #ifdef CA_DEBUG std::vector roadCounters(mTrkParams[0].NLayers - 3, 0); std::vector fitCounters(mTrkParams[0].NLayers - 3, 0); @@ -275,6 +279,7 @@ void Tracker::findTracks(const ROframe& event) clusters[iC] = mPrimaryVertexContext->getClusters()[iC][clusters[iC]].clusterId; } } + /// Track seed preparation. Clusters are numbered progressively from the outermost to the innermost. const auto& cluster1_glo = event.getClustersOnLayer(lastCellLevel + 2).at(clusters[lastCellLevel + 2]); const auto& cluster2_glo = event.getClustersOnLayer(lastCellLevel + 1).at(clusters[lastCellLevel + 1]); @@ -287,20 +292,20 @@ void Tracker::findTracks(const ROframe& event) for (size_t iC = 0; iC < clusters.size(); ++iC) { temporaryTrack.setExternalClusterIndex(iC, clusters[iC], clusters[iC] != constants::its::UnusedIndex); } - bool fitSuccess = fitTrack(event, temporaryTrack, mTrkParams[0].NLayers - 4, -1, -1); + bool fitSuccess = fitTrack(event, temporaryTrack, mTrkParams[0].NLayers - 4, -1, -1, propagator); if (!fitSuccess) { continue; } CA_DEBUGGER(fitCounters[nClusters - 4]++); temporaryTrack.resetCovariance(); - fitSuccess = fitTrack(event, temporaryTrack, 0, mTrkParams[0].NLayers, 1, mTrkParams[0].FitIterationMaxChi2[0]); + fitSuccess = fitTrack(event, temporaryTrack, 0, mTrkParams[0].NLayers, 1, propagator, mTrkParams[0].FitIterationMaxChi2[0]); if (!fitSuccess) { continue; } CA_DEBUGGER(backpropagatedCounters[nClusters - 4]++); temporaryTrack.getParamOut() = temporaryTrack; temporaryTrack.resetCovariance(); - fitSuccess = fitTrack(event, temporaryTrack, mTrkParams[0].NLayers - 1, -1, -1, mTrkParams[0].FitIterationMaxChi2[1]); + fitSuccess = fitTrack(event, temporaryTrack, mTrkParams[0].NLayers - 1, -1, -1, propagator, mTrkParams[0].FitIterationMaxChi2[1]); #ifdef CA_DEBUG mDebugger->dumpTrackToBranchWithInfo("testBranch", temporaryTrack, event, mPrimaryVertexContext, true); #endif @@ -407,7 +412,7 @@ void Tracker::findTracks(const ROframe& event) #endif } -bool Tracker::fitTrack(const ROframe& event, TrackITSExt& track, int start, int end, int step, const float chi2cut) +bool Tracker::fitTrack(const ROframe& event, TrackITSExt& track, int start, int end, int step, o2::base::PropagatorImpl* propPtr, const float chi2cut) { track.setChi2(0); for (int iLayer{start}; iLayer != end; iLayer += step) { @@ -420,9 +425,14 @@ bool Tracker::fitTrack(const ROframe& event, TrackITSExt& track, int start, int return false; } - if (!track.propagateTo(trackingHit.xTrackingFrame, getBz())) { + // if (!track.propagateTo(trackingHit.xTrackingFrame, getBz())) { + // return false; + // } + + if (!propPtr->PropagateToXBxByBz(track, trackingHit.xTrackingFrame)) { return false; } + auto predChi2{track.getPredictedChi2(trackingHit.positionTrackingFrame, trackingHit.covarianceTrackingFrame)}; if (predChi2 > chi2cut) { return false; @@ -432,28 +442,28 @@ bool Tracker::fitTrack(const ROframe& event, TrackITSExt& track, int start, int return false; } - float xx0 = ((iLayer > 2) ? 0.008f : 0.003f); // Rough layer thickness - float radiationLength = 9.36f; // Radiation length of Si [cm] - float density = 2.33f; // Density of Si [g/cm^3] - float distance = xx0; // Default thickness - - if (mMatLayerCylSet) { - if ((iLayer + step) != end) { - const auto cl_0 = mPrimaryVertexContext->getClusters()[iLayer][track.getClusterIndex(iLayer)]; - const auto cl_1 = mPrimaryVertexContext->getClusters()[iLayer + step][track.getClusterIndex(iLayer + step)]; - - auto matbud = mMatLayerCylSet->getMatBudget(cl_0.xCoordinate, cl_0.yCoordinate, cl_0.zCoordinate, cl_1.xCoordinate, cl_1.yCoordinate, cl_1.zCoordinate); - xx0 = matbud.meanX2X0; - density = matbud.meanRho; - distance = matbud.length; - } - } + // float xx0 = ((iLayer > 2) ? 0.008f : 0.003f); // Rough layer thickness + // float radiationLength = 9.36f; // Radiation length of Si [cm] + // float density = 2.33f; // Density of Si [g/cm^3] + // float distance = xx0; // Default thickness + // + // if (mMatLayerCylSet) { + // if ((iLayer + step) != end) { + // const auto cl_0 = mPrimaryVertexContext->getClusters()[iLayer][track.getClusterIndex(iLayer)]; + // const auto cl_1 = mPrimaryVertexContext->getClusters()[iLayer + step][track.getClusterIndex(iLayer + step)]; + // + // auto matbud = mMatLayerCylSet->getMatBudget(cl_0.xCoordinate, cl_0.yCoordinate, cl_0.zCoordinate, cl_1.xCoordinate, cl_1.yCoordinate, cl_1.zCoordinate); + // xx0 = matbud.meanX2X0; + // density = matbud.meanRho; + // distance = matbud.length; + // } + // } // The correctForMaterial should be called with anglecorr==true if the material budget is the "mean budget in vertical direction" and with false if the the estimated budget already accounts for the track inclination. // Here using !mMatLayerCylSet as its presence triggers update of parameters - - if (!track.correctForMaterial(xx0, ((start < end) ? -1. : 1.) * distance * density, !mMatLayerCylSet)) { // ~0.14 GeV: mass of charged pion is used by default - return false; - } + // + // if (!track.correctForMaterial(xx0, ((start < end) ? -1. : 1.) * distance * density, !mMatLayerCylSet)) { // ~0.14 GeV: mass of charged pion is used by default + // return false; + // } } return true; } From c118fe6e05118ff3ff783826c3f3028b83e11cf1 Mon Sep 17 00:00:00 2001 From: Matteo Concas Date: Wed, 7 Apr 2021 11:44:04 +0200 Subject: [PATCH 116/770] Get LUT for material budget by default --- .../tracking/include/ITStracking/Tracker.h | 13 ---- .../include/ITStracking/TrackingConfigParam.h | 3 - Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx | 33 +--------- .../ITSMFT/ITS/workflow/src/TrackerSpec.cxx | 1 - macro/run_trac_ca_its.C | 60 +++++++++++++++++-- 5 files changed, 56 insertions(+), 54 deletions(-) diff --git a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Tracker.h b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Tracker.h index e756f63153495..94c6dffafacdd 100644 --- a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Tracker.h +++ b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Tracker.h @@ -75,14 +75,12 @@ class Tracker std::vector& getTracks(); auto& getTrackLabels() { return mTrackLabels; } - bool isMatLUT(); void clustersToTracks(const ROframe&, std::ostream& = std::cout); void setROFrame(std::uint32_t f) { mROFrame = f; } std::uint32_t getROFrame() const { return mROFrame; } void setParameters(const std::vector&, const std::vector&); - void initMatBudLUTFromFile(); void getGlobalConfiguration(); private: @@ -116,7 +114,6 @@ class Tracker std::uint32_t mROFrame = 0; std::vector mTracks; std::vector mTrackLabels; - o2::base::MatLayerCylSet* mMatLayerCylSet = nullptr; o2::gpu::GPUChainITS* mRecoChain = nullptr; #ifdef CA_DEBUG @@ -140,16 +137,6 @@ inline void Tracker::setBz(float bz) mBz = bz; } -inline void Tracker::initMatBudLUTFromFile() -{ - mMatLayerCylSet = o2::base::MatLayerCylSet::loadFromFile(); -} - -inline bool Tracker::isMatLUT() -{ - return mMatLayerCylSet; -} - template void Tracker::initialisePrimaryVertexContext(T&&... args) { diff --git a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/TrackingConfigParam.h b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/TrackingConfigParam.h index deed8732f6ebd..9de802b9b8877 100644 --- a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/TrackingConfigParam.h +++ b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/TrackingConfigParam.h @@ -37,9 +37,6 @@ struct VertexerParamConfig : public o2::conf::ConfigurableParamHelper { - // Use lookup table for mat. budget - bool useMatBudLUT = false; - O2ParamDef(TrackerParamConfig, "ITSCATrackerParam"); }; diff --git a/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx b/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx index f80404c240cc7..cae586cdd0a1c 100644 --- a/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx +++ b/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx @@ -425,11 +425,7 @@ bool Tracker::fitTrack(const ROframe& event, TrackITSExt& track, int start, int return false; } - // if (!track.propagateTo(trackingHit.xTrackingFrame, getBz())) { - // return false; - // } - - if (!propPtr->PropagateToXBxByBz(track, trackingHit.xTrackingFrame)) { + if (!propPtr->propagateToX(track, trackingHit.xTrackingFrame, getBz())) { return false; } @@ -441,29 +437,6 @@ bool Tracker::fitTrack(const ROframe& event, TrackITSExt& track, int start, int if (!track.o2::track::TrackParCov::update(trackingHit.positionTrackingFrame, trackingHit.covarianceTrackingFrame)) { return false; } - - // float xx0 = ((iLayer > 2) ? 0.008f : 0.003f); // Rough layer thickness - // float radiationLength = 9.36f; // Radiation length of Si [cm] - // float density = 2.33f; // Density of Si [g/cm^3] - // float distance = xx0; // Default thickness - // - // if (mMatLayerCylSet) { - // if ((iLayer + step) != end) { - // const auto cl_0 = mPrimaryVertexContext->getClusters()[iLayer][track.getClusterIndex(iLayer)]; - // const auto cl_1 = mPrimaryVertexContext->getClusters()[iLayer + step][track.getClusterIndex(iLayer + step)]; - // - // auto matbud = mMatLayerCylSet->getMatBudget(cl_0.xCoordinate, cl_0.yCoordinate, cl_0.zCoordinate, cl_1.xCoordinate, cl_1.yCoordinate, cl_1.zCoordinate); - // xx0 = matbud.meanX2X0; - // density = matbud.meanRho; - // distance = matbud.length; - // } - // } - // The correctForMaterial should be called with anglecorr==true if the material budget is the "mean budget in vertical direction" and with false if the the estimated budget already accounts for the track inclination. - // Here using !mMatLayerCylSet as its presence triggers update of parameters - // - // if (!track.correctForMaterial(xx0, ((start < end) ? -1. : 1.) * distance * density, !mMatLayerCylSet)) { // ~0.14 GeV: mass of charged pion is used by default - // return false; - // } } return true; } @@ -676,10 +649,6 @@ track::TrackParCov Tracker::buildTrackSeed(const Cluster& cluster1, const Cluste void Tracker::getGlobalConfiguration() { auto& tc = o2::its::TrackerParamConfig::Instance(); - - if (tc.useMatBudLUT) { - initMatBudLUTFromFile(); - } } } // namespace its diff --git a/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx b/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx index 0a4d1ca11efdb..b5b8e46419f76 100644 --- a/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx +++ b/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx @@ -116,7 +116,6 @@ void TrackerDPL::init(InitContext& ic) mVertexer->getGlobalConfiguration(); mTracker->getGlobalConfiguration(); - LOG(INFO) << Form("%ssing lookup table for material budget approximation", (mTracker->isMatLUT() ? "U" : "Not u")); double origD[3] = {0., 0., 0.}; mTracker->setBz(field->getBz(origD)); diff --git a/macro/run_trac_ca_its.C b/macro/run_trac_ca_its.C index 1f1d8ccb94340..13cc2bbf07a1f 100644 --- a/macro/run_trac_ca_its.C +++ b/macro/run_trac_ca_its.C @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -179,6 +180,11 @@ void run_trac_ca_its(bool cosmics = false, o2::its::VertexerTraits* traits = o2::its::createVertexerTraits(); o2::its::Vertexer vertexer(traits); + o2::its::VertexingParameters parameters; + parameters.phiCut = 0.005f; + parameters.tanLambdaCut = 0.002f; + vertexer.setParameters(parameters); + int roFrameCounter{0}; std::vector ncls; @@ -200,12 +206,53 @@ void run_trac_ca_its(bool cosmics = false, memParams[0].CellsMemoryCoefficients[iLayer] = 0.001f; } } else { + // Comment for pp + // ---- trackParams.resize(3); memParams.resize(3); - trackParams[0].TrackletMaxDeltaPhi = 0.05f; - trackParams[1].TrackletMaxDeltaPhi = 0.1f; + for (int iParam{0}; iParam < 3; ++iParam) { + for (int iLayer = 0; iLayer < o2::its::constants::its2::TrackletsPerRoad; iLayer++) { + memParams[iParam].TrackletsMemoryCoefficients[iLayer] = 5.f; + memParams[iParam].CellsMemoryCoefficients[iLayer] = 0.1f; + } + } + for (auto i{0}; i < 3; ++i) { + trackParams[i].TrackletMaxDeltaPhi = 3.f; + trackParams[i].CellMaxDeltaPhi = 3.f; + trackParams[i].CellMaxDeltaTanLambda = 1.f; + for (auto j{0}; j < 6; ++j) { + trackParams[i].TrackletMaxDeltaZ[j] = 10.f; + } + for (auto j{0}; j < 5; ++j) { + trackParams[i].CellMaxDeltaZ[j] = 10.f; + } + } trackParams[2].MinTrackLength = 4; - trackParams[2].TrackletMaxDeltaPhi = 0.3; + // --- + // Uncomment for pp + // trackParams.resize(2); + // std::array kmaxDCAxy1 = {1.f * 2.0, 0.4f * 2.0, 0.4f * 2.0, 2.0f * 2.0, 3.f * 2.0}; + // std::array kmaxDCAz1 = {1.f * 2.0, 0.4f * 2.0, 0.4f * 2.0, 2.0f * 2.0, 3.f * 2.0}; + // std::array kmaxDN1 = {0.005f * 2.0, 0.0035f * 2.0, 0.009f * 2.0, 0.03f * 2.0}; + // std::array kmaxDP1 = {0.02f * 2.0, 0.005f * 2.0, 0.006f * 2.0, 0.007f * 2.0}; + // std::array kmaxDZ1 = {1.f * 2.0, 1.f * 2.0, 2.0f * 2.0, 2.0f * 2.0, 2.0f * 2.0, 2.0f * 2.0}; + // const float kDoublTanL1 = 0.05f * 5.; + // const float kDoublPhi1 = 0.2f * 5.; + // trackParams[1].MinTrackLength = 7; + // trackParams[1].TrackletMaxDeltaPhi = 0.3; + // trackParams[1].CellMaxDeltaPhi = 0.2 * 2; + // trackParams[1].CellMaxDeltaTanLambda = 0.05 * 2; + // std::copy(kmaxDZ1.begin(), kmaxDZ1.end(), trackParams[1].TrackletMaxDeltaZ.begin()); + // std::copy(kmaxDCAxy1.begin(), kmaxDCAxy1.end(), trackParams[1].CellMaxDCA.begin()); + // std::copy(kmaxDCAz1.begin(), kmaxDCAz1.end(), trackParams[1].CellMaxDeltaZ.begin()); + // std::copy(kmaxDP1.begin(), kmaxDP1.end(), trackParams[1].NeighbourMaxDeltaCurvature.begin()); + // std::copy(kmaxDN1.begin(), kmaxDN1.end(), trackParams[1].NeighbourMaxDeltaN.begin()); + // memParams.resize(2); + // for (auto& coef : memParams[1].CellsMemoryCoefficients) + // coef *= 40; + // for (auto& coef : memParams[1].TrackletsMemoryCoefficients) + // coef *= 40; + // --- } tracker.setParameters(memParams, trackParams); @@ -236,7 +283,7 @@ void run_trac_ca_its(bool cosmics = false, if (!vertITS.empty()) { // Using only the first vertex in the list - std::cout << " - Reconstructed vertexer: x = " << vertITS[0].getX() << " y = " << vertITS[0].getY() << " x = " << vertITS[0].getZ() << std::endl; + std::cout << " - Reconstructed vertex: x = " << vertITS[0].getX() << " y = " << vertITS[0].getY() << " x = " << vertITS[0].getZ() << std::endl; event.addPrimaryVertex(vertITS[0].getX(), vertITS[0].getY(), vertITS[0].getZ()); } else { std::cout << " - Vertex not reconstructed, tracking skipped" << std::endl; @@ -252,6 +299,9 @@ void run_trac_ca_its(bool cosmics = false, time.push_back(diff_t.count()); tracks.swap(tracker.getTracks()); + if (tracks.size()) { + std::cout << "\t\tFound " << tracks.size() << " tracks" << std::endl; + } for (auto& trc : tracks) { trc.setFirstClusterEntry(trackClIdx.size()); // before adding tracks, create final cluster indices int ncl = trc.getNumberOfClusters(); @@ -275,4 +325,4 @@ void run_trac_ca_its(bool cosmics = false, graph->Draw("AP"); } -#endif +#endif \ No newline at end of file From 0eb0d4d5a4f2d6746240c30d7e69ef91d9c8d1dd Mon Sep 17 00:00:00 2001 From: Matteo Concas Date: Wed, 7 Apr 2021 14:48:00 +0200 Subject: [PATCH 117/770] Add option for mat. corr. based on TGeometry --- .../ITSMFT/ITS/tracking/include/ITStracking/Tracker.h | 9 ++++----- .../tracking/include/ITStracking/TrackingConfigParam.h | 3 +++ Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx | 6 ++++-- Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx | 1 + macro/run_trac_ca_its.C | 2 ++ 5 files changed, 14 insertions(+), 7 deletions(-) diff --git a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Tracker.h b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Tracker.h index 94c6dffafacdd..416be0bd9df9b 100644 --- a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Tracker.h +++ b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Tracker.h @@ -31,6 +31,7 @@ #include "ITStracking/ROframe.h" #include "ITStracking/MathUtils.h" #include "ITStracking/PrimaryVertexContext.h" +#include "DetectorsBase/Propagator.h" #include "ITStracking/Road.h" #include "DataFormatsITS/TrackITS.h" @@ -44,11 +45,6 @@ namespace o2 { -namespace base -{ -template -class PropagatorImpl; -} namespace gpu { @@ -80,8 +76,10 @@ class Tracker void setROFrame(std::uint32_t f) { mROFrame = f; } std::uint32_t getROFrame() const { return mROFrame; } + void setCorrType(const o2::base::PropagatorImpl::MatCorrType& type) { mCorrType = type; } void setParameters(const std::vector&, const std::vector&); void getGlobalConfiguration(); + bool isMatLUT() const { return mCorrType == o2::base::PropagatorImpl::MatCorrType::USEMatCorrLUT; } private: track::TrackParCov buildTrackSeed(const Cluster& cluster1, const Cluster& cluster2, const Cluster& cluster3, @@ -110,6 +108,7 @@ class Tracker std::vector mTrkParams; bool mCUDA = false; + o2::base::PropagatorImpl::MatCorrType mCorrType = o2::base::PropagatorImpl::MatCorrType::USEMatCorrLUT; float mBz = 5.f; std::uint32_t mROFrame = 0; std::vector mTracks; diff --git a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/TrackingConfigParam.h b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/TrackingConfigParam.h index 9de802b9b8877..82fc7baa41238 100644 --- a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/TrackingConfigParam.h +++ b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/TrackingConfigParam.h @@ -37,6 +37,9 @@ struct VertexerParamConfig : public o2::conf::ConfigurableParamHelper { + // Use TGeo for mat. budget + bool useMatCorrTGeo = false; + O2ParamDef(TrackerParamConfig, "ITSCATrackerParam"); }; diff --git a/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx b/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx index cae586cdd0a1c..b87fd04c0d8e5 100644 --- a/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx +++ b/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx @@ -17,7 +17,6 @@ #include "ITStracking/Cell.h" #include "ITStracking/Constants.h" #include "ITStracking/IndexTableUtils.h" -#include "DetectorsBase/Propagator.h" #include "ITStracking/Tracklet.h" #include "ITStracking/TrackerTraits.h" #include "ITStracking/TrackerTraitsCPU.h" @@ -425,7 +424,7 @@ bool Tracker::fitTrack(const ROframe& event, TrackITSExt& track, int start, int return false; } - if (!propPtr->propagateToX(track, trackingHit.xTrackingFrame, getBz())) { + if (!propPtr->propagateToX(track, trackingHit.xTrackingFrame, getBz(), o2::base::PropagatorImpl::MAX_SIN_PHI, o2::base::PropagatorImpl::MAX_STEP, mCorrType)) { return false; } @@ -649,6 +648,9 @@ track::TrackParCov Tracker::buildTrackSeed(const Cluster& cluster1, const Cluste void Tracker::getGlobalConfiguration() { auto& tc = o2::its::TrackerParamConfig::Instance(); + if (tc.useMatCorrTGeo) { + setCorrType(o2::base::PropagatorImpl::MatCorrType::USEMatCorrTGeo); + } } } // namespace its diff --git a/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx b/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx index b5b8e46419f76..4840eb9dcc74e 100644 --- a/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx +++ b/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx @@ -116,6 +116,7 @@ void TrackerDPL::init(InitContext& ic) mVertexer->getGlobalConfiguration(); mTracker->getGlobalConfiguration(); + LOG(INFO) << Form("Using %s for material budget approximation", (mTracker->isMatLUT() ? "lookup table" : "TGeometry")); double origD[3] = {0., 0., 0.}; mTracker->setBz(field->getBz(origD)); diff --git a/macro/run_trac_ca_its.C b/macro/run_trac_ca_its.C index 13cc2bbf07a1f..8b52cac803d32 100644 --- a/macro/run_trac_ca_its.C +++ b/macro/run_trac_ca_its.C @@ -35,6 +35,7 @@ #include "ITStracking/Vertexer.h" #include "MathUtils/Utils.h" +#include "DetectorsBase/Propagator.h" #include "SimulationDataFormat/MCCompLabel.h" #include "SimulationDataFormat/MCTruthContainer.h" @@ -90,6 +91,7 @@ void run_trac_ca_its(bool cosmics = false, } double origD[3] = {0., 0., 0.}; tracker.setBz(field->getBz(origD)); + // tracker.setCorrType(o2::base::PropagatorImpl::MatCorrType::USEMatCorrTGeo); bool isITS = grp->isDetReadOut(o2::detectors::DetID::ITS); if (!isITS) { From f22d2510be611391b1fd7540d7791365ec46f8e3 Mon Sep 17 00:00:00 2001 From: Matteo Concas Date: Thu, 8 Apr 2021 11:34:00 +0200 Subject: [PATCH 118/770] Add default query to TGeom for ALICE3 --- macro/run_trac_alice3.C | 1 + 1 file changed, 1 insertion(+) diff --git a/macro/run_trac_alice3.C b/macro/run_trac_alice3.C index ca5fea1be42bb..8fe3f7af9da37 100644 --- a/macro/run_trac_alice3.C +++ b/macro/run_trac_alice3.C @@ -69,6 +69,7 @@ void run_trac_alice3(const string hitsFileName = "o2sim_HitsTRK.root") o2::its::Tracker tracker(new o2::its::TrackerTraitsCPU()); tracker.setBz(5.f); + tracker.setCorrType(o2::base::PropagatorImpl::MatCorrType::USEMatCorrTGeo); std::uint32_t roFrame; std::vector* hits = nullptr; From a57ce39f41bd505ff3a9e7365a2a9d05cabde700 Mon Sep 17 00:00:00 2001 From: Matteo Concas Date: Fri, 9 Apr 2021 16:13:22 +0200 Subject: [PATCH 119/770] Fix actual mut budget LUT usage --- .../tracking/include/ITStracking/Tracker.h | 5 ++--- Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx | 13 ++++++------ .../ITSMFT/ITS/workflow/src/TrackerSpec.cxx | 13 +++++++++++- macro/run_trac_ca_its.C | 21 +++++++++++++++++-- 4 files changed, 39 insertions(+), 13 deletions(-) diff --git a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Tracker.h b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Tracker.h index 416be0bd9df9b..956856b601588 100644 --- a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Tracker.h +++ b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Tracker.h @@ -79,7 +79,7 @@ class Tracker void setCorrType(const o2::base::PropagatorImpl::MatCorrType& type) { mCorrType = type; } void setParameters(const std::vector&, const std::vector&); void getGlobalConfiguration(); - bool isMatLUT() const { return mCorrType == o2::base::PropagatorImpl::MatCorrType::USEMatCorrLUT; } + bool isMatLUT() const { return o2::base::Propagator::Instance()->getMatLUT() && (mCorrType == o2::base::PropagatorImpl::MatCorrType::USEMatCorrLUT); } private: track::TrackParCov buildTrackSeed(const Cluster& cluster1, const Cluster& cluster2, const Cluster& cluster3, @@ -91,8 +91,7 @@ class Tracker void findCellsNeighbours(int& iteration); void findRoads(int& iteration); void findTracks(const ROframe& ev); - bool fitTrack(const ROframe& event, TrackITSExt& track, int start, int end, int step, o2::base::PropagatorImpl* propPtr, - const float chi2cut = o2::constants::math::VeryBig); + bool fitTrack(const ROframe& event, TrackITSExt& track, int start, int end, int step, const float chi2cut = o2::constants::math::VeryBig); void traverseCellsTree(const int, const int); void computeRoadsMClabels(const ROframe&); void computeTracksMClabels(const ROframe&); diff --git a/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx b/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx index b87fd04c0d8e5..367e2163472be 100644 --- a/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx +++ b/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx @@ -234,8 +234,6 @@ void Tracker::findTracks(const ROframe& event) std::vector tracks; tracks.reserve(mPrimaryVertexContext->getRoads().size()); - auto propagator = o2::base::Propagator::Instance(); - #ifdef CA_DEBUG std::vector roadCounters(mTrkParams[0].NLayers - 3, 0); std::vector fitCounters(mTrkParams[0].NLayers - 3, 0); @@ -291,20 +289,20 @@ void Tracker::findTracks(const ROframe& event) for (size_t iC = 0; iC < clusters.size(); ++iC) { temporaryTrack.setExternalClusterIndex(iC, clusters[iC], clusters[iC] != constants::its::UnusedIndex); } - bool fitSuccess = fitTrack(event, temporaryTrack, mTrkParams[0].NLayers - 4, -1, -1, propagator); + bool fitSuccess = fitTrack(event, temporaryTrack, mTrkParams[0].NLayers - 4, -1, -1); if (!fitSuccess) { continue; } CA_DEBUGGER(fitCounters[nClusters - 4]++); temporaryTrack.resetCovariance(); - fitSuccess = fitTrack(event, temporaryTrack, 0, mTrkParams[0].NLayers, 1, propagator, mTrkParams[0].FitIterationMaxChi2[0]); + fitSuccess = fitTrack(event, temporaryTrack, 0, mTrkParams[0].NLayers, 1, mTrkParams[0].FitIterationMaxChi2[0]); if (!fitSuccess) { continue; } CA_DEBUGGER(backpropagatedCounters[nClusters - 4]++); temporaryTrack.getParamOut() = temporaryTrack; temporaryTrack.resetCovariance(); - fitSuccess = fitTrack(event, temporaryTrack, mTrkParams[0].NLayers - 1, -1, -1, propagator, mTrkParams[0].FitIterationMaxChi2[1]); + fitSuccess = fitTrack(event, temporaryTrack, mTrkParams[0].NLayers - 1, -1, -1, mTrkParams[0].FitIterationMaxChi2[1]); #ifdef CA_DEBUG mDebugger->dumpTrackToBranchWithInfo("testBranch", temporaryTrack, event, mPrimaryVertexContext, true); #endif @@ -411,8 +409,9 @@ void Tracker::findTracks(const ROframe& event) #endif } -bool Tracker::fitTrack(const ROframe& event, TrackITSExt& track, int start, int end, int step, o2::base::PropagatorImpl* propPtr, const float chi2cut) +bool Tracker::fitTrack(const ROframe& event, TrackITSExt& track, int start, int end, int step, const float chi2cut) { + auto propInstance = o2::base::Propagator::Instance(); track.setChi2(0); for (int iLayer{start}; iLayer != end; iLayer += step) { if (track.getClusterIndex(iLayer) == constants::its::UnusedIndex) { @@ -424,7 +423,7 @@ bool Tracker::fitTrack(const ROframe& event, TrackITSExt& track, int start, int return false; } - if (!propPtr->propagateToX(track, trackingHit.xTrackingFrame, getBz(), o2::base::PropagatorImpl::MAX_SIN_PHI, o2::base::PropagatorImpl::MAX_STEP, mCorrType)) { + if (!propInstance->propagateToX(track, trackingHit.xTrackingFrame, getBz(), o2::base::PropagatorImpl::MAX_SIN_PHI, o2::base::PropagatorImpl::MAX_STEP, mCorrType)) { return false; } diff --git a/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx b/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx index 4840eb9dcc74e..7e05671323620 100644 --- a/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx +++ b/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx @@ -65,6 +65,16 @@ void TrackerDPL::init(InitContext& ic) geom->fillMatrixCache(o2::math_utils::bit2Mask(o2::math_utils::TransformType::T2L, o2::math_utils::TransformType::T2GRot, o2::math_utils::TransformType::T2G)); + std::string matLUTPath = ic.options().get("material-lut-path"); + std::string matLUTFile = o2::base::NameConf::getMatLUTFileName(matLUTPath); + if (o2::base::NameConf::pathExists(matLUTFile)) { + auto* lut = o2::base::MatLayerCylSet::loadFromFile(matLUTFile); + o2::base::Propagator::Instance()->setMatLUT(lut); + LOG(INFO) << "Loaded material LUT from " << matLUTFile; + } else { + LOG(INFO) << "Material LUT " << matLUTFile << " file is absent, only TGeo can be used"; + } + auto* chainITS = mRecChain->AddChain(); mRecChain->Init(); mVertexer = std::make_unique(chainITS->GetITSVertexerTraits()); @@ -323,7 +333,8 @@ DataProcessorSpec getTrackerSpec(bool useMC, const std::string& trModeS, o2::gpu AlgorithmSpec{adaptFromTask(useMC, trModeS, dType)}, Options{ {"grp-file", VariantType::String, "o2sim_grp.root", {"Name of the grp file"}}, - {"its-dictionary-path", VariantType::String, "", {"Path of the cluster-topology dictionary file"}}}}; + {"its-dictionary-path", VariantType::String, "", {"Path of the cluster-topology dictionary file"}}, + {"material-lut-path", VariantType::String, "", {"Path of the material LUT file"}}}}; } } // namespace its diff --git a/macro/run_trac_ca_its.C b/macro/run_trac_ca_its.C index 8b52cac803d32..5595362209949 100644 --- a/macro/run_trac_ca_its.C +++ b/macro/run_trac_ca_its.C @@ -56,10 +56,12 @@ using Vertex = o2::dataformats::Vertex>; using MCLabCont = o2::dataformats::MCTruthContainer; void run_trac_ca_its(bool cosmics = false, + bool useLUT = true, std::string path = "./", std::string outputfile = "o2trac_its.root", std::string inputClustersITS = "o2clus_its.root", std::string dictfile = "", + std::string matLUTFile = "matbud.root", std::string inputGRP = "o2sim_grp.root") { @@ -91,11 +93,26 @@ void run_trac_ca_its(bool cosmics = false, } double origD[3] = {0., 0., 0.}; tracker.setBz(field->getBz(origD)); - // tracker.setCorrType(o2::base::PropagatorImpl::MatCorrType::USEMatCorrTGeo); + + //-------- init lookuptable --------// + if (useLUT) { + auto* lut = o2::base::MatLayerCylSet::loadFromFile(matLUTFile); + o2::base::Propagator::Instance()->setMatLUT(lut); + } else { + tracker.setCorrType(o2::base::PropagatorImpl::MatCorrType::USEMatCorrTGeo); + } + + if (tracker.isMatLUT()) { + LOG(INFO) << "Loaded material LUT from " << matLUTFile; + } else { + LOG(INFO) << "Material LUT " << matLUTFile << " file is absent, only TGeo can be used"; + } + + // bool isITS = grp->isDetReadOut(o2::detectors::DetID::ITS); if (!isITS) { - LOG(WARNING) << "ITS is not in the readoute"; + LOG(WARNING) << "ITS is not in the readout"; return; } bool isContITS = grp->isDetContinuousReadOut(o2::detectors::DetID::ITS); From b2da32ff3ea995fa2f2e02dc6ec905f26a122a94 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Tue, 13 Apr 2021 22:55:32 +0200 Subject: [PATCH 120/770] DPL: resume old behavior for timer (#5921) --- Framework/Core/src/ArrowSupport.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Framework/Core/src/ArrowSupport.cxx b/Framework/Core/src/ArrowSupport.cxx index 9154c0b3af3dc..c68ddb93c5bcf 100644 --- a/Framework/Core/src/ArrowSupport.cxx +++ b/Framework/Core/src/ArrowSupport.cxx @@ -160,8 +160,6 @@ o2::framework::ServiceSpec ArrowSupport::arrowBackendSpec() size_t lastTimestamp = 0; size_t firstTimestamp = -1; size_t lastDecision = 0; - static uint64_t now = 0; - now = uv_hrtime(); static std::vector allIndices = createDefaultIndices(allDeviceMetrics); for (size_t mi = 0; mi < allDeviceMetrics.size(); ++mi) { auto& deviceMetrics = allDeviceMetrics[mi]; @@ -217,7 +215,9 @@ o2::framework::ServiceSpec ArrowSupport::arrowBackendSpec() static int stateTransitions = 0; static int signalsCount = 0; static int skippedCount = 0; + static uint64_t now = 0; static uint64_t lastSignal = 0; + now = uv_hrtime(); while (!done) { stateMetric(driverMetrics, (uint64_t)(currentState), stateTransitions++); switch (currentState) { From 046875cd57cbba36a547bdb9c944591d8cec286d Mon Sep 17 00:00:00 2001 From: afurs Date: Mon, 12 Apr 2021 13:46:32 +0200 Subject: [PATCH 121/770] FDD: Singleton for LookupTable FDD: clang applied FDD: LUT fixed --- .../FIT/FDD/include/DataFormatsFDD/LookUpTable.h | 15 +++++++++++++++ .../FIT/FDD/raw/include/FDDRaw/DigitBlockFDD.h | 3 +-- Detectors/FIT/FDD/raw/src/DigitBlockFDD.cxx | 1 - 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/DataFormats/Detectors/FIT/FDD/include/DataFormatsFDD/LookUpTable.h b/DataFormats/Detectors/FIT/FDD/include/DataFormatsFDD/LookUpTable.h index ced5f8ed51469..69fb9de7da346 100644 --- a/DataFormats/Detectors/FIT/FDD/include/DataFormatsFDD/LookUpTable.h +++ b/DataFormats/Detectors/FIT/FDD/include/DataFormatsFDD/LookUpTable.h @@ -115,6 +115,21 @@ class LookUpTable ClassDefNV(LookUpTable, 1); }; +//Singleton for LookUpTable +class SingleLUT : public LookUpTable +{ + private: + SingleLUT() : LookUpTable(LookUpTable::linear()) {} + SingleLUT(const SingleLUT&) = delete; + SingleLUT& operator=(SingleLUT&) = delete; + + public: + static SingleLUT& Instance() + { + static SingleLUT instanceLUT; + return instanceLUT; + } +}; } // namespace fdd } // namespace o2 #endif diff --git a/Detectors/FIT/FDD/raw/include/FDDRaw/DigitBlockFDD.h b/Detectors/FIT/FDD/raw/include/FDDRaw/DigitBlockFDD.h index 34c57260d15ed..664a302d00c03 100644 --- a/Detectors/FIT/FDD/raw/include/FDDRaw/DigitBlockFDD.h +++ b/Detectors/FIT/FDD/raw/include/FDDRaw/DigitBlockFDD.h @@ -53,7 +53,6 @@ class DigitBlockFDD : public DigitBlockBase void setIntRec(o2::InteractionRecord intRec) { mDigit.mIntRecord = intRec; } Digit mDigit; std::vector mVecChannelData; - static o2::fdd::LookUpTable sLookupTable; static int sEventID; template @@ -61,7 +60,7 @@ class DigitBlockFDD : public DigitBlockBase { if constexpr (std::is_same::value) { //Filling data from PM for (int iEventData = 0; iEventData < dataBlock.DataBlockWrapper::mNelements; iEventData++) { - mVecChannelData.emplace_back(int(sLookupTable.getChannel(linkID, dataBlock.DataBlockWrapper::mData[iEventData].channelID)), + mVecChannelData.emplace_back(int(o2::fdd::SingleLUT::Instance().getChannel(linkID, dataBlock.DataBlockWrapper::mData[iEventData].channelID)), int(dataBlock.DataBlockWrapper::mData[iEventData].time), int(dataBlock.DataBlockWrapper::mData[iEventData].charge), dataBlock.DataBlockWrapper::mData[iEventData].getFlagWord()); diff --git a/Detectors/FIT/FDD/raw/src/DigitBlockFDD.cxx b/Detectors/FIT/FDD/raw/src/DigitBlockFDD.cxx index db0a70f93e37e..d19f5a39c6537 100644 --- a/Detectors/FIT/FDD/raw/src/DigitBlockFDD.cxx +++ b/Detectors/FIT/FDD/raw/src/DigitBlockFDD.cxx @@ -12,4 +12,3 @@ using namespace o2::fdd; int DigitBlockFDD::sEventID = 0; -o2::fdd::LookUpTable DigitBlockFDD::sLookupTable = o2::fdd::LookUpTable::linear(); From 6db4b80e6c3dd2287af807c0b9d370689281b547 Mon Sep 17 00:00:00 2001 From: afurs Date: Mon, 12 Apr 2021 14:23:46 +0200 Subject: [PATCH 122/770] FDD: Printing LookupTable in init() within DPL workflow raw2digit --- .../FIT/FDD/workflow/include/FDDWorkflow/RawDataReaderSpec.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Detectors/FIT/FDD/workflow/include/FDDWorkflow/RawDataReaderSpec.h b/Detectors/FIT/FDD/workflow/include/FDDWorkflow/RawDataReaderSpec.h index 0cb7bb95a6f2d..234fb9d2afa26 100644 --- a/Detectors/FIT/FDD/workflow/include/FDDWorkflow/RawDataReaderSpec.h +++ b/Detectors/FIT/FDD/workflow/include/FDDWorkflow/RawDataReaderSpec.h @@ -13,6 +13,7 @@ #ifndef O2_FDD_RAWDATAREADERSPEC_H #define O2_FDD_RAWDATAREADERSPEC_H +#include "DataFormatsFDD/LookUpTable.h" #include "Framework/DataProcessorSpec.h" #include "Framework/Task.h" #include "Framework/CallbackService.h" @@ -40,7 +41,7 @@ class RawDataReaderSpec : public Task RawDataReaderSpec(const RawReader& rawReader) : mRawReader(rawReader) {} RawDataReaderSpec() = default; ~RawDataReaderSpec() override = default; - void init(InitContext& ic) final {} + void init(InitContext& ic) final { o2::fdd::SingleLUT::Instance().printFullMap(); } void run(ProcessingContext& pc) final { DPLRawParser parser(pc.inputs()); From 0274d667cff50f06ae41f88a21d2d62155e510b5 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Wed, 27 Jan 2021 14:43:30 +0100 Subject: [PATCH 123/770] [TrackPar] cleanup TrackPar and TrackParCov * cleanup typenames in interfaces * use math_utils instead of GPU math --- .../TrackParametrization.h | 51 ++++--- .../TrackParametrizationWithError.h | 40 ++--- .../src/TrackParametrization.cxx | 144 +++++++++--------- .../src/TrackParametrizationWithError.cxx | 8 +- 4 files changed, 122 insertions(+), 121 deletions(-) diff --git a/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrization.h b/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrization.h index ea7b8d323fff7..5456556e7b538 100644 --- a/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrization.h +++ b/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrization.h @@ -37,6 +37,7 @@ #include #include #include +#include #endif #ifndef GPUCA_ALIGPUCODE //Used only by functions that are hidden on the GPU @@ -261,70 +262,70 @@ GPUdi() void TrackParametrization::set(value_t x, value_t alpha, const //____________________________________________________________ template -GPUdi() const typename TrackParametrization::value_t* TrackParametrization::getParams() const +GPUdi() auto TrackParametrization::getParams() const -> const value_t* { return mP; } //____________________________________________________________ template -GPUdi() typename TrackParametrization::value_t TrackParametrization::getParam(int i) const +GPUdi() auto TrackParametrization::getParam(int i) const -> value_t { return mP[i]; } //____________________________________________________________ template -GPUdi() typename TrackParametrization::value_t TrackParametrization::getX() const +GPUdi() auto TrackParametrization::getX() const -> value_t { return mX; } //____________________________________________________________ template -GPUdi() typename TrackParametrization::value_t TrackParametrization::getAlpha() const +GPUdi() auto TrackParametrization::getAlpha() const -> value_t { return mAlpha; } //____________________________________________________________ template -GPUdi() typename TrackParametrization::value_t TrackParametrization::getY() const +GPUdi() auto TrackParametrization::getY() const -> value_t { return mP[kY]; } //____________________________________________________________ template -GPUdi() typename TrackParametrization::value_t TrackParametrization::getZ() const +GPUdi() auto TrackParametrization::getZ() const -> value_t { return mP[kZ]; } //____________________________________________________________ template -GPUdi() typename TrackParametrization::value_t TrackParametrization::getSnp() const +GPUdi() auto TrackParametrization::getSnp() const -> value_t { return mP[kSnp]; } //____________________________________________________________ template -GPUdi() typename TrackParametrization::value_t TrackParametrization::getTgl() const +GPUdi() auto TrackParametrization::getTgl() const -> value_t { return mP[kTgl]; } //____________________________________________________________ template -GPUdi() typename TrackParametrization::value_t TrackParametrization::getQ2Pt() const +GPUdi() auto TrackParametrization::getQ2Pt() const -> value_t { return mP[kQ2Pt]; } //____________________________________________________________ template -GPUdi() typename TrackParametrization::value_t TrackParametrization::getCharge2Pt() const +GPUdi() auto TrackParametrization::getCharge2Pt() const -> value_t { return mAbsCharge ? mP[kQ2Pt] : 0.f; } @@ -353,7 +354,7 @@ GPUdi() void TrackParametrization::setPID(const PID pid) //____________________________________________________________ template -GPUdi() typename TrackParametrization::value_t TrackParametrization::getCsp2() const +GPUdi() auto TrackParametrization::getCsp2() const -> value_t { const value_t csp2 = (1.f - mP[kSnp]) * (1.f + mP[kSnp]); return csp2 > o2::constants::math::Almost0 ? csp2 : o2::constants::math::Almost0; @@ -361,7 +362,7 @@ GPUdi() typename TrackParametrization::value_t TrackParametrization -GPUdi() typename TrackParametrization::value_t TrackParametrization::getCsp() const +GPUdi() auto TrackParametrization::getCsp() const -> value_t { return gpu::CAMath::Sqrt(getCsp2()); } @@ -474,7 +475,7 @@ GPUdi() void TrackParametrization::getLineParams(o2::math_utils::Interv //____________________________________________________________ template -GPUdi() typename TrackParametrization::value_t TrackParametrization::getCurvature(value_t b) const +GPUdi() auto TrackParametrization::getCurvature(value_t b) const -> value_t { return mAbsCharge ? mP[kQ2Pt] * b * o2::constants::math::B2C : 0.; } @@ -495,7 +496,7 @@ GPUdi() int TrackParametrization::getSign() const //_______________________________________________________ template -GPUdi() typename TrackParametrization::value_t TrackParametrization::getPhi() const +GPUdi() auto TrackParametrization::getPhi() const -> value_t { // track pt direction phi (in 0:2pi range) value_t phi = gpu::CAMath::ASin(getSnp()) + getAlpha(); @@ -505,7 +506,7 @@ GPUdi() typename TrackParametrization::value_t TrackParametrization -GPUdi() typename TrackParametrization::value_t TrackParametrization::getPhiPos() const +GPUdi() auto TrackParametrization::getPhiPos() const -> value_t { // angle of track position (in -pi:pi range) value_t phi = gpu::CAMath::ATan2(getY(), getX()) + getAlpha(); @@ -515,7 +516,7 @@ GPUdi() typename TrackParametrization::value_t TrackParametrization -GPUdi() typename TrackParametrization::value_t TrackParametrization::getPtInv() const +GPUdi() auto TrackParametrization::getPtInv() const -> value_t { // return the inverted track pT const value_t ptInv = gpu::CAMath::Abs(mP[kQ2Pt]); @@ -524,7 +525,7 @@ GPUdi() typename TrackParametrization::value_t TrackParametrization -GPUdi() typename TrackParametrization::value_t TrackParametrization::getP2Inv() const +GPUdi() auto TrackParametrization::getP2Inv() const -> value_t { // return the inverted track momentum^2 const value_t p2 = mP[kQ2Pt] * mP[kQ2Pt] / (1.f + getTgl() * getTgl()); @@ -533,7 +534,7 @@ GPUdi() typename TrackParametrization::value_t TrackParametrization -GPUdi() typename TrackParametrization::value_t TrackParametrization::getP2() const +GPUdi() auto TrackParametrization::getP2() const -> value_t { // return the track momentum^2 const value_t p2inv = getP2Inv(); @@ -542,7 +543,7 @@ GPUdi() typename TrackParametrization::value_t TrackParametrization -GPUdi() typename TrackParametrization::value_t TrackParametrization::getPInv() const +GPUdi() auto TrackParametrization::getPInv() const -> value_t { // return the inverted track momentum^2 const value_t pInv = gpu::CAMath::Abs(mP[kQ2Pt]) / gpu::CAMath::Sqrt(1.f + getTgl() * getTgl()); @@ -551,7 +552,7 @@ GPUdi() typename TrackParametrization::value_t TrackParametrization -GPUdi() typename TrackParametrization::value_t TrackParametrization::getP() const +GPUdi() auto TrackParametrization::getP() const -> value_t { // return the track momentum const value_t pInv = getPInv(); @@ -560,7 +561,7 @@ GPUdi() typename TrackParametrization::value_t TrackParametrization -GPUdi() typename TrackParametrization::value_t TrackParametrization::getPt() const +GPUdi() auto TrackParametrization::getPt() const -> value_t { // return the track transverse momentum value_t ptI = gpu::CAMath::Abs(mP[kQ2Pt]); @@ -572,21 +573,21 @@ GPUdi() typename TrackParametrization::value_t TrackParametrization -GPUdi() typename TrackParametrization::value_t TrackParametrization::getTheta() const +GPUdi() auto TrackParametrization::getTheta() const -> value_t { return constants::math::PIHalf - gpu::CAMath::ATan(mP[3]); } //____________________________________________________________ template -GPUdi() typename TrackParametrization::value_t TrackParametrization::getEta() const +GPUdi() auto TrackParametrization::getEta() const -> value_t { return -gpu::CAMath::Log(gpu::CAMath::Tan(0.5f * getTheta())); } //_______________________________________________________ template -GPUdi() math_utils::Point3D::value_t> TrackParametrization::getXYZGlo() const +GPUdi() auto TrackParametrization::getXYZGlo() const -> math_utils::Point3D { #ifndef GPUCA_ALIGPUCODE return math_utils::Rotation2D(getAlpha())(math_utils::Point3D(getX(), getY(), getZ())); @@ -610,7 +611,7 @@ GPUdi() void TrackParametrization::getXYZGlo(dim3_t& xyz) const //_______________________________________________________ template -GPUdi() math_utils::Point3D::value_t> TrackParametrization::getXYZGloAt(value_t xk, value_t b, bool& ok) const +GPUdi() auto TrackParametrization::getXYZGloAt(value_t xk, value_t b, bool& ok) const -> math_utils::Point3D { //---------------------------------------------------------------- // estimate global X,Y,Z in global frame at given X diff --git a/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrizationWithError.h b/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrizationWithError.h index 0826b1610a6e0..4766635061446 100644 --- a/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrizationWithError.h +++ b/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrizationWithError.h @@ -26,6 +26,7 @@ namespace track template class TrackParametrizationWithError : public TrackParametrization { // track+error parameterization + public: using typename TrackParametrization::value_t; using typename TrackParametrization::dim3_t; @@ -36,7 +37,6 @@ class TrackParametrizationWithError : public TrackParametrization static_assert(std::is_floating_point_v); #endif - public: using covMat_t = gpu::gpustd::array; using MatrixDSym5 = ROOT::Math::SMatrix>; using MatrixD5 = ROOT::Math::SMatrix>; @@ -149,126 +149,126 @@ GPUdi() void TrackParametrizationWithError::set(value_t x, value_t alph //__________________________________________________________________________ template -GPUdi() const typename TrackParametrizationWithError::value_t* TrackParametrizationWithError::getCov() const +GPUdi() auto TrackParametrizationWithError::getCov() const -> const value_t* { return mC; } //__________________________________________________________________________ template -GPUdi() typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getSigmaY2() const +GPUdi() auto TrackParametrizationWithError::getSigmaY2() const -> value_t { return mC[kSigY2]; } //__________________________________________________________________________ template -GPUdi() typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getSigmaZY() const +GPUdi() auto TrackParametrizationWithError::getSigmaZY() const -> value_t { return mC[kSigZY]; } //__________________________________________________________________________ template -GPUdi() typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getSigmaZ2() const +GPUdi() auto TrackParametrizationWithError::getSigmaZ2() const -> value_t { return mC[kSigZ2]; } //__________________________________________________________________________ template -GPUdi() typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getSigmaSnpY() const +GPUdi() auto TrackParametrizationWithError::getSigmaSnpY() const -> value_t { return mC[kSigSnpY]; } //__________________________________________________________________________ template -GPUdi() typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getSigmaSnpZ() const +GPUdi() auto TrackParametrizationWithError::getSigmaSnpZ() const -> value_t { return mC[kSigSnpZ]; } //__________________________________________________________________________ template -GPUdi() typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getSigmaSnp2() const +GPUdi() auto TrackParametrizationWithError::getSigmaSnp2() const -> value_t { return mC[kSigSnp2]; } //__________________________________________________________________________ template -GPUdi() typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getSigmaTglY() const +GPUdi() auto TrackParametrizationWithError::getSigmaTglY() const -> value_t { return mC[kSigTglY]; } //__________________________________________________________________________ template -GPUdi() typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getSigmaTglZ() const +GPUdi() auto TrackParametrizationWithError::getSigmaTglZ() const -> value_t { return mC[kSigTglZ]; } //__________________________________________________________________________ template -GPUdi() typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getSigmaTglSnp() const +GPUdi() auto TrackParametrizationWithError::getSigmaTglSnp() const -> value_t { return mC[kSigTglSnp]; } //__________________________________________________________________________ template -GPUdi() typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getSigmaTgl2() const +GPUdi() auto TrackParametrizationWithError::getSigmaTgl2() const -> value_t { return mC[kSigTgl2]; } //__________________________________________________________________________ template -GPUdi() typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getSigma1PtY() const +GPUdi() auto TrackParametrizationWithError::getSigma1PtY() const -> value_t { return mC[kSigQ2PtY]; } //__________________________________________________________________________ template -GPUdi() typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getSigma1PtZ() const +GPUdi() auto TrackParametrizationWithError::getSigma1PtZ() const -> value_t { return mC[kSigQ2PtZ]; } //__________________________________________________________________________ template -GPUdi() typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getSigma1PtSnp() const +GPUdi() auto TrackParametrizationWithError::getSigma1PtSnp() const -> value_t { return mC[kSigQ2PtSnp]; } //__________________________________________________________________________ template -GPUdi() typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getSigma1PtTgl() const +GPUdi() auto TrackParametrizationWithError::getSigma1PtTgl() const -> value_t { return mC[kSigQ2PtTgl]; } //__________________________________________________________________________ template -GPUdi() typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getSigma1Pt2() const +GPUdi() auto TrackParametrizationWithError::getSigma1Pt2() const -> value_t { return mC[kSigQ2Pt2]; } //__________________________________________________________________________ template -GPUdi() typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getCovarElem(int i, int j) const +GPUdi() auto TrackParametrizationWithError::getCovarElem(int i, int j) const -> value_t { return mC[CovarMap[i][j]]; } //__________________________________________________________________________ template -GPUdi() typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getDiagError2(int i) const +GPUdi() auto TrackParametrizationWithError::getDiagError2(int i) const -> value_t { return mC[DiagMap[i]]; } @@ -276,7 +276,7 @@ GPUdi() typename TrackParametrizationWithError::value_t TrackParametriz //__________________________________________________________________________ template template -GPUdi() typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getPredictedChi2(const BaseCluster& p) const +GPUdi() auto TrackParametrizationWithError::getPredictedChi2(const BaseCluster& p) const -> value_t { const dim2_t pyz = {p.getY(), p.getZ()}; const dim3_t cov = {p.getSigmaY2(), p.getSigmaYZ(), p.getSigmaZ2()}; diff --git a/DataFormats/Reconstruction/src/TrackParametrization.cxx b/DataFormats/Reconstruction/src/TrackParametrization.cxx index ea33e6b60b285..cb8d49d63c578 100644 --- a/DataFormats/Reconstruction/src/TrackParametrization.cxx +++ b/DataFormats/Reconstruction/src/TrackParametrization.cxx @@ -57,9 +57,9 @@ GPUd() TrackParametrization::TrackParametrization(const dim3_t& xyz, co value_t radPos2 = xyz[0] * xyz[0] + xyz[1] * xyz[1]; value_t alp = 0; if (sectorAlpha || radPos2 < 1) { - alp = gpu::CAMath::ATan2(pxpypz[1], pxpypz[0]); + alp = math_utils::detail::atan2(pxpypz[1], pxpypz[0]); } else { - alp = gpu::CAMath::ATan2(xyz[1], xyz[0]); + alp = math_utils::detail::atan2(xyz[1], xyz[0]); } if (sectorAlpha) { alp = math_utils::detail::angle2Alpha(alp); @@ -70,7 +70,7 @@ GPUd() TrackParametrization::TrackParametrization(const dim3_t& xyz, co // protection against cosp<0 if (cs * pxpypz[0] + sn * pxpypz[1] < 0) { LOG(WARNING) << "alpha from phiPos() will invalidate this track parameters, overriding to alpha from phi()"; - alp = gpu::CAMath::ATan2(pxpypz[1], pxpypz[0]); + alp = math_utils::detail::atan2(pxpypz[1], pxpypz[0]); if (sectorAlpha) { alp = math_utils::detail::angle2Alpha(alp); } @@ -78,14 +78,14 @@ GPUd() TrackParametrization::TrackParametrization(const dim3_t& xyz, co } // protection: avoid alpha being too close to 0 or +-pi/2 - if (gpu::CAMath::Abs(sn) < 2 * kSafe) { + if (math_utils::detail::abs(sn) < 2 * kSafe) { if (alp > 0) { alp += alp < constants::math::PIHalf ? 2 * kSafe : -2 * kSafe; } else { alp += alp > -constants::math::PIHalf ? -2 * kSafe : 2 * kSafe; } math_utils::detail::sincos(alp, sn, cs); - } else if (gpu::CAMath::Abs(cs) < 2 * kSafe) { + } else if (math_utils::detail::abs(cs) < 2 * kSafe) { if (alp > 0) { alp += alp > constants::math::PIHalf ? 2 * kSafe : -2 * kSafe; } else { @@ -108,13 +108,13 @@ GPUd() TrackParametrization::TrackParametrization(const dim3_t& xyz, co mP[kZ] = ver[2]; mP[kSnp] = mom[1] * ptI; mP[kTgl] = mom[2] * ptI; - mAbsCharge = gpu::CAMath::Abs(charge); + mAbsCharge = math_utils::detail::abs(charge); mP[kQ2Pt] = charge ? ptI * charge : ptI; mPID = pid; // - if (gpu::CAMath::Abs(1 - getSnp()) < kSafe) { + if (math_utils::detail::abs(1 - getSnp()) < kSafe) { mP[kSnp] = 1.f - kSafe; // Protection - } else if (gpu::CAMath::Abs(-1 - getSnp()) < kSafe) { + } else if (math_utils::detail::abs(-1 - getSnp()) < kSafe) { mP[kSnp] = -1.f + kSafe; // Protection } // @@ -125,11 +125,11 @@ template GPUd() bool TrackParametrization::getPxPyPzGlo(dim3_t& pxyz) const { // track momentum - if (gpu::CAMath::Abs(getQ2Pt()) < constants::math::Almost0 || gpu::CAMath::Abs(getSnp()) > constants::math::Almost1) { + if (math_utils::detail::abs(getQ2Pt()) < constants::math::Almost0 || math_utils::detail::abs(getSnp()) > constants::math::Almost1) { return false; } value_t cs, sn, pt = getPt(); - value_t r = gpu::CAMath::Sqrt((1.f - getSnp()) * (1.f + getSnp())); + value_t r = math_utils::detail::sqrt((1.f - getSnp()) * (1.f + getSnp())); math_utils::detail::sincos(getAlpha(), sn, cs); pxyz[0] = pt * (r * cs - getSnp() * sn); pxyz[1] = pt * (getSnp() * cs + r * sn); @@ -142,14 +142,14 @@ template GPUd() bool TrackParametrization::getPosDirGlo(gpu::gpustd::array& posdirp) const { // fill vector with lab x,y,z,px/p,py/p,pz/p,p,sinAlpha,cosAlpha - value_t ptI = gpu::CAMath::Abs(getQ2Pt()); + value_t ptI = math_utils::detail::abs(getQ2Pt()); value_t snp = getSnp(); - if (ptI < constants::math::Almost0 || gpu::CAMath::Abs(snp) > constants::math::Almost1) { + if (ptI < constants::math::Almost0 || math_utils::detail::abs(snp) > constants::math::Almost1) { return false; } value_t &sn = posdirp[7], &cs = posdirp[8]; - value_t csp = gpu::CAMath::Sqrt((1.f - snp) * (1.f + snp)); - value_t cstht = gpu::CAMath::Sqrt(1.f + getTgl() * getTgl()); + value_t csp = math_utils::detail::sqrt((1.f - snp) * (1.f + snp)); + value_t cstht = math_utils::detail::sqrt(1.f + getTgl() * getTgl()); value_t csthti = 1.f / cstht; math_utils::detail::sincos(getAlpha(), sn, cs); posdirp[0] = getX() * cs - getY() * sn; @@ -167,7 +167,7 @@ template GPUd() bool TrackParametrization::rotateParam(value_t alpha) { // rotate to alpha frame - if (gpu::CAMath::Abs(getSnp()) > constants::math::Almost1) { + if (math_utils::detail::abs(getSnp()) > constants::math::Almost1) { LOGP(WARNING, "Precondition is not satisfied: |sin(phi)|>1 ! {:f}", getSnp()); return false; } @@ -176,7 +176,7 @@ GPUd() bool TrackParametrization::rotateParam(value_t alpha) // value_t ca = 0, sa = 0; math_utils::detail::sincos(alpha - getAlpha(), sa, ca); - value_t snp = getSnp(), csp = gpu::CAMath::Sqrt((1.f - snp) * (1.f + snp)); // Improve precision + value_t snp = getSnp(), csp = math_utils::detail::sqrt((1.f - snp) * (1.f + snp)); // Improve precision // RS: check if rotation does no invalidate track model (cos(local_phi)>=0, i.e. particle // direction in local frame is along the X axis if ((csp * ca + snp * sa) < 0) { @@ -185,7 +185,7 @@ GPUd() bool TrackParametrization::rotateParam(value_t alpha) } // value_t tmp = snp * ca - csp * sa; - if (gpu::CAMath::Abs(tmp) > constants::math::Almost1) { + if (math_utils::detail::abs(tmp) > constants::math::Almost1) { LOGP(WARNING, "Rotation failed: new snp {:.2f}", tmp); return false; } @@ -209,11 +209,11 @@ GPUd() bool TrackParametrization::propagateParamTo(value_t xk, const di //---------------------------------------------------------------- value_t dx = xk - getX(); - if (gpu::CAMath::Abs(dx) < constants::math::Almost0) { + if (math_utils::detail::abs(dx) < constants::math::Almost0) { return true; } // Do not propagate tracks outside the ALICE detector - if (gpu::CAMath::Abs(dx) > 1e5 || gpu::CAMath::Abs(getY()) > 1e5 || gpu::CAMath::Abs(getZ()) > 1e5) { + if (math_utils::detail::abs(dx) > 1e5 || math_utils::detail::abs(getY()) > 1e5 || math_utils::detail::abs(getZ()) > 1e5) { LOGP(WARNING, "Anomalous track, target X:{:f}", xk); // print(); return false; @@ -221,21 +221,21 @@ GPUd() bool TrackParametrization::propagateParamTo(value_t xk, const di value_t crv = getCurvature(b[2]); value_t x2r = crv * dx; value_t f1 = getSnp(), f2 = f1 + x2r; - if (gpu::CAMath::Abs(f1) > constants::math::Almost1 || gpu::CAMath::Abs(f2) > constants::math::Almost1) { + if (math_utils::detail::abs(f1) > constants::math::Almost1 || math_utils::detail::abs(f2) > constants::math::Almost1) { return false; } - value_t r1 = gpu::CAMath::Sqrt((1.f - f1) * (1.f + f1)); - if (gpu::CAMath::Abs(r1) < constants::math::Almost0) { + value_t r1 = math_utils::detail::sqrt((1.f - f1) * (1.f + f1)); + if (math_utils::detail::abs(r1) < constants::math::Almost0) { return false; } - value_t r2 = gpu::CAMath::Sqrt((1.f - f2) * (1.f + f2)); - if (gpu::CAMath::Abs(r2) < constants::math::Almost0) { + value_t r2 = math_utils::detail::sqrt((1.f - f2) * (1.f + f2)); + if (math_utils::detail::abs(r2) < constants::math::Almost0) { return false; } value_t dy2dx = (f1 + f2) / (r1 + r2); - value_t step = (gpu::CAMath::Abs(x2r) < 0.05f) ? dx * gpu::CAMath::Abs(r2 + f2 * dy2dx) // chord - : 2.f * CAMath::ASin(0.5f * dx * gpu::CAMath::Sqrt(1.f + dy2dx * dy2dx) * crv) / crv; // arc - step *= gpu::CAMath::Sqrt(1.f + getTgl() * getTgl()); + value_t step = (math_utils::detail::abs(x2r) < 0.05f) ? dx * math_utils::detail::abs(r2 + f2 * dy2dx) // chord + : 2.f * CAMath::ASin(0.5f * dx * math_utils::detail::sqrt(1.f + dy2dx * dy2dx) * crv) / crv; // arc + step *= math_utils::detail::sqrt(1.f + getTgl() * getTgl()); // // get the track x,y,z,px/p,py/p,pz/p,p,sinAlpha,cosAlpha in the Global System gpu::gpustd::array vecLab{0.f}; @@ -245,13 +245,13 @@ GPUd() bool TrackParametrization::propagateParamTo(value_t xk, const di // rotate to the system where Bx=By=0. value_t bxy2 = b[0] * b[0] + b[1] * b[1]; - value_t bt = gpu::CAMath::Sqrt(bxy2); + value_t bt = math_utils::detail::sqrt(bxy2); value_t cosphi = 1.f, sinphi = 0.f; if (bt > constants::math::Almost0) { cosphi = b[0] / bt; sinphi = b[1] / bt; } - value_t bb = gpu::CAMath::Sqrt(bxy2 + b[2] * b[2]); + value_t bb = math_utils::detail::sqrt(bxy2 + b[2] * b[2]); value_t costet = 1.f, sintet = 0.f; if (bb > constants::math::Almost0) { costet = b[2] / bb; @@ -289,8 +289,8 @@ GPUd() bool TrackParametrization::propagateParamTo(value_t xk, const di // Do the final correcting step to the target plane (linear approximation) value_t x = vecLab[0], y = vecLab[1], z = vecLab[2]; - if (gpu::CAMath::Abs(dx) > constants::math::Almost0) { - if (gpu::CAMath::Abs(vecLab[3]) < constants::math::Almost0) { + if (math_utils::detail::abs(dx) > constants::math::Almost0) { + if (math_utils::detail::abs(vecLab[3]) < constants::math::Almost0) { return false; } dx = xk - vecLab[0]; @@ -300,7 +300,7 @@ GPUd() bool TrackParametrization::propagateParamTo(value_t xk, const di } // Calculate the track parameters - t = 1.f / gpu::CAMath::Sqrt(vecLab[3] * vecLab[3] + vecLab[4] * vecLab[4]); + t = 1.f / math_utils::detail::sqrt(vecLab[3] * vecLab[3] + vecLab[4] * vecLab[4]); mX = xk; mP[kY] = y; mP[kZ] = z; @@ -321,28 +321,28 @@ GPUd() bool TrackParametrization::propagateParamTo(value_t xk, value_t // distances only ((dx) < constants::math::Almost0) { return true; } - value_t crv = (gpu::CAMath::Abs(b) < constants::math::Almost0) ? 0.f : getCurvature(b); + value_t crv = (math_utils::detail::abs(b) < constants::math::Almost0) ? 0.f : getCurvature(b); value_t x2r = crv * dx; value_t f1 = getSnp(), f2 = f1 + x2r; - if ((gpu::CAMath::Abs(f1) > constants::math::Almost1) || (gpu::CAMath::Abs(f2) > constants::math::Almost1)) { + if ((math_utils::detail::abs(f1) > constants::math::Almost1) || (math_utils::detail::abs(f2) > constants::math::Almost1)) { return false; } - value_t r1 = gpu::CAMath::Sqrt((1.f - f1) * (1.f + f1)); - if (gpu::CAMath::Abs(r1) < constants::math::Almost0) { + value_t r1 = math_utils::detail::sqrt((1.f - f1) * (1.f + f1)); + if (math_utils::detail::abs(r1) < constants::math::Almost0) { return false; } - value_t r2 = gpu::CAMath::Sqrt((1.f - f2) * (1.f + f2)); - if (gpu::CAMath::Abs(r2) < constants::math::Almost0) { + value_t r2 = math_utils::detail::sqrt((1.f - f2) * (1.f + f2)); + if (math_utils::detail::abs(r2) < constants::math::Almost0) { return false; } mX = xk; double dy2dx = (f1 + f2) / (r1 + r2); mP[kY] += dx * dy2dx; mP[kSnp] += x2r; - if (gpu::CAMath::Abs(x2r) < 0.05f) { + if (math_utils::detail::abs(x2r) < 0.05f) { mP[kZ] += dx * (r2 + f2 * dy2dx) * getTgl(); } else { // for small dx/R the linear apporximation of the arc by the segment is OK, @@ -373,27 +373,27 @@ GPUd() bool TrackParametrization::propagateParamToDCA(const math_utils: // propagate track to DCA to the vertex value_t sn, cs, alp = getAlpha(); math_utils::detail::sincos(alp, sn, cs); - value_t x = getX(), y = getY(), snp = getSnp(), csp = gpu::CAMath::Sqrt((1.f - snp) * (1.f + snp)); + value_t x = getX(), y = getY(), snp = getSnp(), csp = math_utils::detail::sqrt((1.f - snp) * (1.f + snp)); value_t xv = vtx.X() * cs + vtx.Y() * sn, yv = -vtx.X() * sn + vtx.Y() * cs, zv = vtx.Z(); x -= xv; y -= yv; //Estimate the impact parameter neglecting the track curvature - value_t d = gpu::CAMath::Abs(x * snp - y * csp); + value_t d = math_utils::detail::abs(x * snp - y * csp); if (d > maxD) { return false; } value_t crv = getCurvature(b); value_t tgfv = -(crv * x - snp) / (crv * y + csp); - sn = tgfv / gpu::CAMath::Sqrt(1.f + tgfv * tgfv); - cs = gpu::CAMath::Sqrt((1.f - sn) * (1.f + sn)); - cs = (gpu::CAMath::Abs(tgfv) > constants::math::Almost0) ? sn / tgfv : constants::math::Almost1; + sn = tgfv / math_utils::detail::sqrt(1.f + tgfv * tgfv); + cs = math_utils::detail::sqrt((1.f - sn) * (1.f + sn)); + cs = (math_utils::detail::abs(tgfv) > constants::math::Almost0) ? sn / tgfv : constants::math::Almost1; x = xv * cs + yv * sn; yv = -xv * sn + yv * cs; xv = x; auto tmpT(*this); // operate on the copy to recover after the failure - alp += gpu::CAMath::ASin(sn); + alp += math_utils::detail::asin(sn); if (!tmpT.rotateParam(alp) || !tmpT.propagateParamTo(xv, b)) { LOG(WARNING) << "failed to propagate to alpha=" << alp << " X=" << xv << " for vertex " << vtx.X() << ' ' << vtx.Y() << ' ' << vtx.Z() << " | Track is: "; @@ -418,26 +418,26 @@ GPUd() bool TrackParametrization::getYZAt(value_t xk, value_t b, value_ value_t dx = xk - getX(); y = mP[kY]; z = mP[kZ]; - if (gpu::CAMath::Abs(dx) < constants::math::Almost0) { + if (math_utils::detail::abs(dx) < constants::math::Almost0) { return true; } value_t crv = getCurvature(b); value_t x2r = crv * dx; value_t f1 = getSnp(), f2 = f1 + x2r; - if ((gpu::CAMath::Abs(f1) > constants::math::Almost1) || (gpu::CAMath::Abs(f2) > constants::math::Almost1)) { + if ((math_utils::detail::abs(f1) > constants::math::Almost1) || (math_utils::detail::abs(f2) > constants::math::Almost1)) { return false; } - value_t r1 = gpu::CAMath::Sqrt((1.f - f1) * (1.f + f1)); - if (gpu::CAMath::Abs(r1) < constants::math::Almost0) { + value_t r1 = math_utils::detail::sqrt((1.f - f1) * (1.f + f1)); + if (math_utils::detail::abs(r1) < constants::math::Almost0) { return false; } - value_t r2 = gpu::CAMath::Sqrt((1.f - f2) * (1.f + f2)); - if (gpu::CAMath::Abs(r2) < constants::math::Almost0) { + value_t r2 = math_utils::detail::sqrt((1.f - f2) * (1.f + f2)); + if (math_utils::detail::abs(r2) < constants::math::Almost0) { return false; } double dy2dx = (f1 + f2) / (r1 + r2); y += dx * dy2dx; - if (gpu::CAMath::Abs(x2r) < 0.05f) { + if (math_utils::detail::abs(x2r) < 0.05f) { z += dx * (r2 + f2 * dy2dx) * getTgl(); } else { // for small dx/R the linear apporximation of the arc by the segment is OK, @@ -531,16 +531,16 @@ GPUd() bool TrackParametrization::getXatLabR(value_t r, value_t& x, val const value_t kEps = 1.e-6; // auto crv = getCurvature(bz); - if (gpu::CAMath::Abs(crv) > constants::math::Almost0) { // helix + if (math_utils::detail::abs(crv) > constants::math::Almost0) { // helix // get center of the track circle math_utils::CircleXY circle; getCircleParamsLoc(bz, circle); - value_t r0 = gpu::CAMath::Sqrt(circle.getCenterD2()); + value_t r0 = math_utils::detail::sqrt(circle.getCenterD2()); if (r0 <= constants::math::Almost0) { return false; // the track is concentric to circle } value_t tR2r0 = 1.f, g = 0.f, tmp = 0.f; - if (gpu::CAMath::Abs(circle.rC - r0) > kEps) { + if (math_utils::detail::abs(circle.rC - r0) > kEps) { tR2r0 = circle.rC / r0; g = 0.5f * (r * r / (r0 * circle.rC) - tR2r0 - 1.f / tR2r0); tmp = 1.f + g * tR2r0; @@ -553,7 +553,7 @@ GPUd() bool TrackParametrization::getXatLabR(value_t r, value_t& x, val if (det < 0.f) { return false; // does not reach raduis r } - det = gpu::CAMath::Sqrt(det); + det = math_utils::detail::sqrt(det); // // the intersection happens in 2 points: {circle.xC+tR*C,circle.yC+tR*S} // with C=f*c0+-|s0|*det and S=f*s0-+c0 sign(s0)*det @@ -561,8 +561,8 @@ GPUd() bool TrackParametrization::getXatLabR(value_t r, value_t& x, val // x = circle.xC * tmp; value_t y = circle.yC * tmp; - if (gpu::CAMath::Abs(circle.yC) > constants::math::Almost0) { // when circle.yC==0 the x,y is unique - value_t dfx = tR2r0 * gpu::CAMath::Abs(circle.yC) * det; + if (math_utils::detail::abs(circle.yC) > constants::math::Almost0) { // when circle.yC==0 the x,y is unique + value_t dfx = tR2r0 * math_utils::detail::abs(circle.yC) * det; value_t dfy = tR2r0 * circle.xC * (circle.yC > 0.f ? det : -det); if (dir == DirAuto) { // chose the one which corresponds to smallest step value_t delta = (x - mX) * dfx - (y - fy) * dfy; // the choice of + in C will lead to smaller step if delta<0 @@ -573,7 +573,7 @@ GPUd() bool TrackParametrization::getXatLabR(value_t r, value_t& x, val if (dfeps < -kEps) { return true; } - if (gpu::CAMath::Abs(dfeps) < kEps && gpu::CAMath::Abs(mX * mX + fy * fy - r * r) < kEps) { // are we already in right r? + if (math_utils::detail::abs(dfeps) < kEps && math_utils::detail::abs(mX * mX + fy * fy - r * r) < kEps) { // are we already in right r? return mX; } x += dfx + dfx; @@ -590,7 +590,7 @@ GPUd() bool TrackParametrization::getXatLabR(value_t r, value_t& x, val if (dfeps < -kEps) { return true; } - if (gpu::CAMath::Abs(dfeps) < kEps && gpu::CAMath::Abs(mX * mX + fy * fy - r * r) < kEps) { // are we already in right r? + if (math_utils::detail::abs(dfeps) < kEps && math_utils::detail::abs(mX * mX + fy * fy - r * r) < kEps) { // are we already in right r? return mX; } x -= dfx + dfx; @@ -608,8 +608,8 @@ GPUd() bool TrackParametrization::getXatLabR(value_t r, value_t& x, val return false; } } - } else { // this is a straight track - if (gpu::CAMath::Abs(sn) >= constants::math::Almost1) { // || to Y axis + } else { // this is a straight track + if (math_utils::detail::abs(sn) >= constants::math::Almost1) { // || to Y axis value_t det = (r - mX) * (r + mX); if (det < 0.f) { return false; // does not reach raduis r @@ -618,7 +618,7 @@ GPUd() bool TrackParametrization::getXatLabR(value_t r, value_t& x, val if (dir == DirAuto) { return true; } - det = gpu::CAMath::Sqrt(det); + det = math_utils::detail::sqrt(det); if (dir == DirOutward) { // along the track direction if (sn > 0.f) { if (fy > det) { @@ -638,12 +638,12 @@ GPUd() bool TrackParametrization::getXatLabR(value_t r, value_t& x, val return false; // track is against Y axis } } - } else if (gpu::CAMath::Abs(sn) <= constants::math::Almost0) { // || to X axis + } else if (math_utils::detail::abs(sn) <= constants::math::Almost0) { // || to X axis value_t det = (r - fy) * (r + fy); if (det < 0.f) { return false; // does not reach raduis r } - det = gpu::CAMath::Sqrt(det); + det = math_utils::detail::sqrt(det); if (dir == DirAuto) { x = mX > 0.f ? det : -det; // choose the solution requiring the smalest step return true; @@ -661,13 +661,13 @@ GPUd() bool TrackParametrization::getXatLabR(value_t r, value_t& x, val } } } else { // general case of straight line - value_t cs = gpu::CAMath::Sqrt((1.f - sn) * (1.f + sn)); + value_t cs = math_utils::detail::sqrt((1.f - sn) * (1.f + sn)); value_t xsyc = mX * sn - fy * cs; value_t det = (r - xsyc) * (r + xsyc); if (det < 0.f) { return false; // does not reach raduis r } - det = gpu::CAMath::Sqrt(det); + det = math_utils::detail::sqrt(det); value_t xcys = mX * cs + fy * sn; value_t t = -xcys; if (dir == DirAuto) { @@ -711,7 +711,7 @@ GPUd() bool TrackParametrization::correctForELoss(value_t xrho, bool an if (anglecorr) { value_t csp2 = (1.f - getSnp()) * (1.f + getSnp()); // cos(phi)^2 value_t cst2I = (1.f + getTgl() * getTgl()); // 1/cos(lambda)^2 - value_t angle = gpu::CAMath::Sqrt(cst2I / (csp2)); + value_t angle = math_utils::detail::sqrt(cst2I / (csp2)); xrho *= angle; } value_t p = getP(); @@ -729,8 +729,8 @@ GPUd() bool TrackParametrization::correctForELoss(value_t xrho, bool an } value_t dE = dedx * xrho; - value_t e = gpu::CAMath::Sqrt(e2); - if (gpu::CAMath::Abs(dE) > kMaxELossFrac * e) { + value_t e = math_utils::detail::sqrt(e2); + if (math_utils::detail::abs(dE) > kMaxELossFrac * e) { return false; // 30% energy loss is too much! } value_t eupd = e + dE; @@ -738,7 +738,7 @@ GPUd() bool TrackParametrization::correctForELoss(value_t xrho, bool an if (pupd2 < kMinP * kMinP) { return false; } - setQ2Pt(getQ2Pt() * p / gpu::CAMath::Sqrt(pupd2)); + setQ2Pt(getQ2Pt() * p / math_utils::detail::sqrt(pupd2)); } return true; diff --git a/DataFormats/Reconstruction/src/TrackParametrizationWithError.cxx b/DataFormats/Reconstruction/src/TrackParametrizationWithError.cxx index 07bd6ab1ed0f8..692b9cf1b8d0e 100644 --- a/DataFormats/Reconstruction/src/TrackParametrizationWithError.cxx +++ b/DataFormats/Reconstruction/src/TrackParametrizationWithError.cxx @@ -99,7 +99,7 @@ GPUd() bool TrackParametrizationWithError::propagateTo(value_t xk, valu // mP1 += rot/crv*mP3; // value_t rot = gpu::CAMath::ASin(r1 * f2 - r2 * f1); // more economic version from Yura. - if (f1 * f1 + f2 * f2 > 1.f && f1 * f2 < 0.f) { // special cases of large rotations or large abs angles + if (f1 * f1 + f2 * f2 > 1.f && f1 * f2 < 0.f) { // special cases of large rotations or large abs angles if (f2 > 0.f) { rot = constants::math::PI - rot; // } else { @@ -691,7 +691,7 @@ GPUd() void TrackParametrizationWithError::resetCovariance(value_t s2) //______________________________________________ template -GPUd() typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getPredictedChi2(const dim2_t& p, const dim3_t& cov) const +GPUd() auto TrackParametrizationWithError::getPredictedChi2(const dim2_t& p, const dim3_t& cov) const -> value_t { // Estimate the chi2 of the space point "p" with the cov. matrix "cov" auto sdd = static_cast(getSigmaY2()) + static_cast(cov[0]); @@ -735,7 +735,7 @@ void TrackParametrizationWithError::buildCombinedCovMatrix(const TrackP //______________________________________________ template -typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getPredictedChi2(const TrackParametrizationWithError& rhs) const +auto TrackParametrizationWithError::getPredictedChi2(const TrackParametrizationWithError& rhs) const -> value_t { MatrixDSym5 cov; // perform matrix operations in double! return getPredictedChi2(rhs, cov); @@ -743,7 +743,7 @@ typename TrackParametrizationWithError::value_t TrackParametrizationWit //______________________________________________ template -typename TrackParametrizationWithError::value_t TrackParametrizationWithError::getPredictedChi2(const TrackParametrizationWithError& rhs, MatrixDSym5& covToSet) const +auto TrackParametrizationWithError::getPredictedChi2(const TrackParametrizationWithError& rhs, MatrixDSym5& covToSet) const -> value_t { // get chi2 wrt other track, which must be defined at the same parameters X,alpha // Supplied non-initialized covToSet matrix is filled by inverse combined matrix for further use From 7b33da0bd3f22fe2d6ae27aaa30a00931c126985 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Tue, 2 Feb 2021 10:57:19 +0100 Subject: [PATCH 124/770] [TrackPar] use std::array instead of C arrays * Use std::array instead of C arrays * Change interfaces of member functions to std::array refs from ptrs * Fallback to member functions using pointers to ensure compatibility with alignment framework for now, will be deprecated in the future. --- .../TrackParametrization.h | 21 +++++- .../TrackParametrizationWithError.h | 65 ++++++++++++++++--- .../src/TrackParametrizationWithError.cxx | 10 +-- GPU/Common/GPUCommonArray.h | 6 +- 4 files changed, 83 insertions(+), 19 deletions(-) diff --git a/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrization.h b/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrization.h index 5456556e7b538..abda84a2b1b73 100644 --- a/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrization.h +++ b/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrization.h @@ -139,6 +139,7 @@ class TrackParametrization GPUdDefault() ~TrackParametrization() = default; GPUd() void set(value_t x, value_t alpha, const params_t& par, int charge = 1, const PID pid = PID::Pion); + GPUd() void set(value_t x, value_t alpha, const value_t* par, int charge = 1, const PID pid = PID::Pion); GPUd() const value_t* getParams() const; GPUd() value_t getParam(int i) const; GPUd() value_t getX() const; @@ -219,9 +220,9 @@ class TrackParametrization std::string asString() const; #endif - protected: GPUd() void updateParam(value_t delta, int i); - GPUd() void updateParams(const value_t delta[kNParams]); + GPUd() void updateParams(const params_t& delta); + GPUd() void updateParams(const value_t* delta); private: // @@ -250,6 +251,13 @@ GPUdi() TrackParametrization::TrackParametrization(value_t x, value_t a //____________________________________________________________ template GPUdi() void TrackParametrization::set(value_t x, value_t alpha, const params_t& par, int charge, const PID pid) +{ + set(x, alpha, par.data(), charge, pid); +} + +//____________________________________________________________ +template +GPUdi() void TrackParametrization::set(value_t x, value_t alpha, const value_t* par, int charge, const PID pid) { mX = x; mAlpha = alpha; @@ -666,7 +674,14 @@ GPUdi() void TrackParametrization::updateParam(value_t delta, int i) //____________________________________________________________ template -GPUdi() void TrackParametrization::updateParams(const value_t delta[kNParams]) +GPUdi() void TrackParametrization::updateParams(const params_t& delta) +{ + updateParams(delta.data()); +} + +//____________________________________________________________ +template +GPUdi() void TrackParametrization::updateParams(const value_t* delta) { for (int i = kNParams; i--;) { mP[i] += delta[i]; diff --git a/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrizationWithError.h b/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrizationWithError.h index 4766635061446..9aa49c3bc336e 100644 --- a/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrizationWithError.h +++ b/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrizationWithError.h @@ -27,7 +27,6 @@ template class TrackParametrizationWithError : public TrackParametrization { // track+error parameterization public: - using typename TrackParametrization::value_t; using typename TrackParametrization::dim3_t; using typename TrackParametrization::dim2_t; @@ -53,9 +52,11 @@ class TrackParametrizationWithError : public TrackParametrization GPUdDefault() ~TrackParametrizationWithError() = default; using TrackParametrization::TrackParametrization; + using TrackParametrization::set; GPUd() void set(value_t x, value_t alpha, const params_t& par, const covMat_t& cov, int charge = 1, const PID pid = PID::Pion); + GPUd() void set(value_t x, value_t alpha, const value_t* par, const value_t* cov, int charge = 1, const PID pid = PID::Pion); GPUd() void set(const dim3_t& xyz, const dim3_t& pxpypz, const gpu::gpustd::array& cv, int sign, bool sectorAlpha = true, const PID pid = PID::Pion); - GPUd() const value_t* getCov() const; + GPUd() const covMat_t& getCov() const; GPUd() value_t getSigmaY2() const; GPUd() value_t getSigmaZY() const; GPUd() value_t getSigmaZ2() const; @@ -89,6 +90,7 @@ class TrackParametrizationWithError : public TrackParametrization GPUd() void invert(); GPUd() value_t getPredictedChi2(const dim2_t& p, const dim3_t& cov) const; + GPUd() value_t getPredictedChi2(const value_t* p, const value_t* cov) const; template GPUd() value_t getPredictedChi2(const BaseCluster& p) const; @@ -100,6 +102,7 @@ class TrackParametrizationWithError : public TrackParametrization bool update(const TrackParametrizationWithError& rhs); GPUd() bool update(const dim2_t& p, const dim3_t& cov); + GPUd() bool update(const value_t* p, const value_t* cov); template GPUd() bool update(const BaseCluster& p); @@ -108,13 +111,16 @@ class TrackParametrizationWithError : public TrackParametrization GPUd() void resetCovariance(value_t s2 = 0); GPUd() void checkCovariance(); + GPUd() void setCov(value_t v, size_t i, size_t j); GPUd() void setCov(value_t v, int i); + GPUd() void setCov(const covMat_t& mat); - GPUd() void updateCov(const value_t delta[kCovMatSize]); - GPUd() void updateCov(value_t delta, int i); + GPUd() void updateCov(const covMat_t& delta); + GPUd() void updateCov(value_t delta, size_t i, size_t j); + GPUd() void updateCov(value_t delta, size_t i); protected: - value_t mC[kCovMatSize] = {0.f}; // 15 covariance matrix elements + covMat_t mC{0.f}; // 15 covariance matrix elements ClassDefNV(TrackParametrizationWithError, 2); }; @@ -140,6 +146,13 @@ GPUdi() TrackParametrizationWithError::TrackParametrizationWithError(va //__________________________________________________________________________ template GPUdi() void TrackParametrizationWithError::set(value_t x, value_t alpha, const params_t& par, const covMat_t& cov, int charge, const PID pid) +{ + set(x, alpha, par.data(), cov.data(), charge, pid); +} + +//__________________________________________________________________________ +template +GPUdi() void TrackParametrizationWithError::set(value_t x, value_t alpha, const value_t* par, const value_t* cov, int charge, const PID pid) { TrackParametrization::set(x, alpha, par, charge, pid); for (int i = 0; i < kCovMatSize; i++) { @@ -149,7 +162,7 @@ GPUdi() void TrackParametrizationWithError::set(value_t x, value_t alph //__________________________________________________________________________ template -GPUdi() auto TrackParametrizationWithError::getCov() const -> const value_t* +GPUdi() auto TrackParametrizationWithError::getCov() const -> const covMat_t& { return mC; } @@ -283,6 +296,20 @@ GPUdi() auto TrackParametrizationWithError::getPredictedChi2(const Base return getPredictedChi2(pyz, cov); } +//______________________________________________ +template +GPUdi() auto TrackParametrizationWithError::getPredictedChi2(const dim2_t& p, const dim3_t& cov) const -> value_t +{ + return getPredictedChi2(p.data(), cov.data()); +} + +//______________________________________________ +template +GPUdi() bool TrackParametrizationWithError::update(const dim2_t& p, const dim3_t& cov) +{ + return update(p.data(), cov.data()); +} + //__________________________________________________________________________ template template @@ -302,16 +329,36 @@ GPUdi() void TrackParametrizationWithError::setCov(value_t v, int i) //__________________________________________________________________________ template -GPUdi() void TrackParametrizationWithError::updateCov(value_t delta, int i) +GPUdi() void TrackParametrizationWithError::setCov(value_t v, size_t i, size_t j) +{ + mC[CovarMap[i][j]] = v; +} + +template +GPUdi() void TrackParametrizationWithError::setCov(const covMat_t& cov) +{ + mC = cov; +} + +//__________________________________________________________________________ +template +GPUdi() void TrackParametrizationWithError::updateCov(value_t delta, size_t i, size_t j) +{ + mC[CovarMap[i][j]] += delta; +} + +//__________________________________________________________________________ +template +GPUdi() void TrackParametrizationWithError::updateCov(value_t delta, size_t i) { mC[i] += delta; } //__________________________________________________________________________ template -GPUdi() void TrackParametrizationWithError::updateCov(const value_t delta[kCovMatSize]) +GPUdi() void TrackParametrizationWithError::updateCov(const covMat_t& delta) { - for (int i = kCovMatSize; i--;) { + for (size_t i = 0; i < kCovMatSize; ++i) { mC[i] += delta[i]; } } diff --git a/DataFormats/Reconstruction/src/TrackParametrizationWithError.cxx b/DataFormats/Reconstruction/src/TrackParametrizationWithError.cxx index 692b9cf1b8d0e..db7ea9a7636c8 100644 --- a/DataFormats/Reconstruction/src/TrackParametrizationWithError.cxx +++ b/DataFormats/Reconstruction/src/TrackParametrizationWithError.cxx @@ -84,7 +84,7 @@ GPUd() bool TrackParametrizationWithError::propagateTo(value_t xk, valu } this->setX(xk); double dy2dx = (f1 + f2) / (r1 + r2); - value_t dP[kNParams] = {0.f}; + params_t dP{0.f}; dP[kY] = dx * dy2dx; dP[kSnp] = x2r; if (gpu::CAMath::Abs(x2r) < 0.05f) { @@ -691,7 +691,7 @@ GPUd() void TrackParametrizationWithError::resetCovariance(value_t s2) //______________________________________________ template -GPUd() auto TrackParametrizationWithError::getPredictedChi2(const dim2_t& p, const dim3_t& cov) const -> value_t +GPUd() auto TrackParametrizationWithError::getPredictedChi2(const value_t* p, const value_t* cov) const -> value_t { // Estimate the chi2 of the space point "p" with the cov. matrix "cov" auto sdd = static_cast(getSigmaY2()) + static_cast(cov[0]); @@ -860,7 +860,7 @@ bool TrackParametrizationWithError::update(const TrackParametrizationWi //______________________________________________ template -GPUd() bool TrackParametrizationWithError::update(const dim2_t& p, const dim3_t& cov) +GPUd() bool TrackParametrizationWithError::update(const value_t* p, const value_t* cov) { // Update the track parameters with the space point "p" having // the covariance matrix "cov" @@ -897,8 +897,8 @@ GPUd() bool TrackParametrizationWithError::update(const dim2_t& p, cons return false; } - value_t dP[kNParams] = {value_t(k00 * dy + k01 * dz), value_t(k10 * dy + k11 * dz), dsnp, value_t(k30 * dy + k31 * dz), - value_t(k40 * dy + k41 * dz)}; + const params_t dP{value_t(k00 * dy + k01 * dz), value_t(k10 * dy + k11 * dz), dsnp, value_t(k30 * dy + k31 * dz), + value_t(k40 * dy + k41 * dz)}; this->updateParams(dP); double c01 = cm10, c02 = cm20, c03 = cm30, c04 = cm40; diff --git a/GPU/Common/GPUCommonArray.h b/GPU/Common/GPUCommonArray.h index 2ef5bb11f9da8..c93e1be99510b 100644 --- a/GPU/Common/GPUCommonArray.h +++ b/GPU/Common/GPUCommonArray.h @@ -24,8 +24,10 @@ namespace o2::gpu::gpustd #ifdef GPUCA_GPUCODE_DEVICE template struct array { - GPUd() T& operator[](size_t i) { return m_internal_V__[i]; } - GPUd() const T& operator[](size_t i) const { return m_internal_V__[i]; } + GPUd() T& operator[](size_t i) { return m_internal_V__[i]; }; + GPUd() const T& operator[](size_t i) const { return m_internal_V__[i]; }; + GPUd() T* data() { return m_internal_V__; }; + GPUd() const T* data() const { return m_internal_V__; }; T m_internal_V__[N]; }; template From 4c99bea470348930a2e089e33e3080a7b77a4533 Mon Sep 17 00:00:00 2001 From: shahoian Date: Tue, 23 Mar 2021 20:42:21 +0100 Subject: [PATCH 125/770] [TrackLTIntegral] optionally update only L and mat.budget integral --- .../ReconstructionDataFormats/TrackLTIntegral.h | 12 +++++++++++- DataFormats/Reconstruction/src/TrackLTIntegral.cxx | 13 ++++++++++--- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackLTIntegral.h b/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackLTIntegral.h index e729ecaed8039..e0cf44df2bbde 100644 --- a/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackLTIntegral.h +++ b/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackLTIntegral.h @@ -27,6 +27,8 @@ namespace track class TrackLTIntegral { public: + static constexpr float NeglectTime = -1.; // if 1st mT slot contains this, don't fill time + GPUdDefault() TrackLTIntegral() = default; GPUdDefault() TrackLTIntegral(const TrackLTIntegral& stc) = default; GPUdDefault() ~TrackLTIntegral() = default; @@ -35,12 +37,14 @@ class TrackLTIntegral GPUd() float getL() const { return mL; } GPUd() float getX2X0() const { return mX2X0; } + GPUd() float getXRho() const { return mXRho; } GPUd() float getTOF(int id) const { return mT[id]; } GPUd() void clear() { mL = 0.f; mX2X0 = 0.f; + mXRho = 0.f; for (int i = getNTOFs(); i--;) { mT[i] = 0.f; } @@ -48,19 +52,25 @@ class TrackLTIntegral GPUd() void addStep(float dL, float p2Inv); GPUd() void addX2X0(float d) { mX2X0 += d; } + GPUd() void addXRho(float d) { mXRho += d; } GPUd() void setL(float l) { mL = l; } GPUd() void setX2X0(float x) { mX2X0 = x; } + GPUd() void setXRho(float x) { mXRho = x; } GPUd() void setTOF(float t, int id) { mT[id] = t; } + GPUd() void setTimeNotNeeded() { mT[0] = NeglectTime; } + GPUd() bool isTimeNotNeeded() const { return mT[0] == NeglectTime; } + GPUd() void print() const; private: float mL = 0.; // length in cm float mX2X0 = 0.; // integrated X/X0 + float mXRho = 0.; // average X*rho float mT[o2::track::PID::NIDs] = {0.}; // TOF in ps - ClassDefNV(TrackLTIntegral, 1); + ClassDefNV(TrackLTIntegral, 2); }; }; // namespace track }; // namespace o2 diff --git a/DataFormats/Reconstruction/src/TrackLTIntegral.cxx b/DataFormats/Reconstruction/src/TrackLTIntegral.cxx index 07a36397f3dd5..585e5a64a7d89 100644 --- a/DataFormats/Reconstruction/src/TrackLTIntegral.cxx +++ b/DataFormats/Reconstruction/src/TrackLTIntegral.cxx @@ -21,9 +21,13 @@ namespace track GPUd() void TrackLTIntegral::print() const { #ifndef GPUCA_GPUCODE_DEVICE - printf("L(cm): %6.2f, X2X0: %5.3f TOF(ps): ", getL(), getX2X0()); - for (int i = 0; i < getNTOFs(); i++) { - printf(" %7.1f |", getTOF(i)); + printf("L(cm): %6.2f, X2X0: %e XRho: %e TOF(ps): ", getL(), getX2X0(), getXRho()); + if (isTimeNotNeeded()) { + printf(" Times not filled"); + } else { + for (int i = 0; i < getNTOFs(); i++) { + printf(" %7.1f |", getTOF(i)); + } } printf("\n"); #endif @@ -34,6 +38,9 @@ GPUd() void TrackLTIntegral::addStep(float dL, float p2Inv) { ///< add step in cm to integrals mL += dL; + if (isTimeNotNeeded()) { + return; + } const float dTns = dL * 1000.f / o2::constants::physics::LightSpeedCm2NS; // time change in ps for beta = 1 particle for (int id = 0; id < getNTOFs(); id++) { const float m2z = track::PID::getMass2Z(id); From 3cf7a60b1314edcc4d419b5ab632f89c32e0a26d Mon Sep 17 00:00:00 2001 From: shahoian Date: Tue, 23 Mar 2021 20:43:19 +0100 Subject: [PATCH 126/770] [Propagator] unified interface for propagations --- Detectors/Base/include/DetectorsBase/Propagator.h | 7 +++++++ Detectors/Base/src/Propagator.cxx | 1 + 2 files changed, 8 insertions(+) diff --git a/Detectors/Base/include/DetectorsBase/Propagator.h b/Detectors/Base/include/DetectorsBase/Propagator.h index e904bf4ee08dc..206990a9e94b0 100644 --- a/Detectors/Base/include/DetectorsBase/Propagator.h +++ b/Detectors/Base/include/DetectorsBase/Propagator.h @@ -85,6 +85,13 @@ class PropagatorImpl value_type maxSnp = MAX_SIN_PHI, value_type maxStep = MAX_STEP, MatCorrType matCorr = MatCorrType::USEMatCorrLUT, track::TrackLTIntegral* tofInfo = nullptr, int signCorr = 0) const; + template + GPUd() bool propagateTo(track_T& track, value_type x, bool bzOnly = false, value_type maxSnp = MAX_SIN_PHI, value_type maxStep = MAX_STEP, + MatCorrType matCorr = MatCorrType::USEMatCorrLUT, track::TrackLTIntegral* tofInfo = nullptr, int signCorr = 0) const + { + return bzOnly ? propagateToX(track, x, getNominalBz(), maxSnp, maxStep, matCorr, tofInfo, signCorr) : PropagateToXBxByBz(track, x, maxSnp, maxStep, matCorr, tofInfo, signCorr); + } + GPUd() bool propagateToDCA(const o2::dataformats::VertexBase& vtx, o2::track::TrackParametrizationWithError& track, value_type bZ, value_type maxStep = MAX_STEP, MatCorrType matCorr = MatCorrType::USEMatCorrLUT, o2::dataformats::DCA* dcaInfo = nullptr, track::TrackLTIntegral* tofInfo = nullptr, diff --git a/Detectors/Base/src/Propagator.cxx b/Detectors/Base/src/Propagator.cxx index 9c8dc73085d14..ecd23f8ec943a 100644 --- a/Detectors/Base/src/Propagator.cxx +++ b/Detectors/Base/src/Propagator.cxx @@ -160,6 +160,7 @@ GPUd() bool PropagatorImpl::PropagateToXBxByBz(TrackParCov_t& track, va if (tofInfo) { tofInfo->addStep(mb.length, track.getP2Inv()); // fill L,ToF info using already calculated step length tofInfo->addX2X0(mb.meanX2X0); + tofInfo->addXRho(mb.getXRho(signCorr)); } } else if (tofInfo) { // if tofInfo filling was requested w/o material correction, we need to calculate the step lenght auto xyz1 = track.getXYZGlo(); From 8ccbcb53a3f1e30557170e6d5834c17a91448686 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Wed, 14 Apr 2021 07:50:32 +0200 Subject: [PATCH 127/770] DPL: handle 100% CPU usage on exit (#5922) This should finally fix the 100% CPU usage on exit. * Do not create new timeslices when we are entering end of stream. * Do not run any processing if we are in Idle. --- Framework/Core/include/Framework/DataRelayer.h | 3 ++- Framework/Core/src/DataProcessingDevice.cxx | 8 ++++++-- Framework/Core/src/DataRelayer.cxx | 8 +++++--- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/Framework/Core/include/Framework/DataRelayer.h b/Framework/Core/include/Framework/DataRelayer.h index 54fe5f92f2f8f..d482a8ea7aaa9 100644 --- a/Framework/Core/include/Framework/DataRelayer.h +++ b/Framework/Core/include/Framework/DataRelayer.h @@ -78,9 +78,10 @@ class DataRelayer /// This invokes the appropriate `InputRoute::danglingChecker` on every /// entry in the cache and if it returns true, it creates a new /// cache entry by invoking the associated `InputRoute::expirationHandler`. + /// @a createNew true if the dangling inputs are allowed to create new slots. /// @return true if there were expirations, false if not. ActivityStats processDanglingInputs(std::vector const&, - ServiceRegistry& context); + ServiceRegistry& context, bool createNew); /// This is used to ask for relaying a given (header,payload) pair. /// Notice that we expect that the header is an O2 Header Stack diff --git a/Framework/Core/src/DataProcessingDevice.cxx b/Framework/Core/src/DataProcessingDevice.cxx index 9eac7270756b5..8a380fda37fc9 100644 --- a/Framework/Core/src/DataProcessingDevice.cxx +++ b/Framework/Core/src/DataProcessingDevice.cxx @@ -569,6 +569,10 @@ void DataProcessingDevice::doRun(DataProcessorContext& context) registry->get().notifyStreamingState(state->streaming); }; + if (context.state->streaming == StreamingState::Idle) { + return; + } + context.completed->clear(); context.completed->reserve(16); *context.wasActive |= DataProcessingDevice::tryDispatchComputation(context, *context.completed); @@ -578,7 +582,7 @@ void DataProcessingDevice::doRun(DataProcessorContext& context) if (*context.wasActive == false) { context.registry->get()(CallbackService::Id::Idle); } - auto activity = context.relayer->processDanglingInputs(*context.expirationHandlers, *context.registry); + auto activity = context.relayer->processDanglingInputs(*context.expirationHandlers, *context.registry, true); *context.wasActive |= activity.expiredSlots > 0; context.completed->clear(); @@ -600,7 +604,7 @@ void DataProcessingDevice::doRun(DataProcessorContext& context) // FIXME: not sure this is the correct way to drain the queues, but // I guess we will see. while (DataProcessingDevice::tryDispatchComputation(context, *context.completed)) { - context.relayer->processDanglingInputs(*context.expirationHandlers, *context.registry); + context.relayer->processDanglingInputs(*context.expirationHandlers, *context.registry, false); } EndOfStreamContext eosContext{*context.registry, *context.allocator}; diff --git a/Framework/Core/src/DataRelayer.cxx b/Framework/Core/src/DataRelayer.cxx index 134168347584f..c490c66841f96 100644 --- a/Framework/Core/src/DataRelayer.cxx +++ b/Framework/Core/src/DataRelayer.cxx @@ -82,7 +82,7 @@ TimesliceId DataRelayer::getTimesliceForSlot(TimesliceSlot slot) } DataRelayer::ActivityStats DataRelayer::processDanglingInputs(std::vector const& expirationHandlers, - ServiceRegistry& services) + ServiceRegistry& services, bool createNew) { std::scoped_lock lock(mMutex); @@ -93,8 +93,10 @@ DataRelayer::ActivityStats DataRelayer::processDanglingInputs(std::vector slotsCreatedByHandlers; - for (auto& handler : expirationHandlers) { - slotsCreatedByHandlers.push_back(handler.creator(mTimesliceIndex)); + if (createNew) { + for (auto& handler : expirationHandlers) { + slotsCreatedByHandlers.push_back(handler.creator(mTimesliceIndex)); + } } if (slotsCreatedByHandlers.empty() == false) { activity.newSlots++; From e4b4155eb129947b912498001fe1761c36974f5b Mon Sep 17 00:00:00 2001 From: shahoian Date: Tue, 13 Apr 2021 22:50:21 +0200 Subject: [PATCH 128/770] Option to write/read CTF and CTF_dict to/from arbitrary directories --- .../DetectorsCommonDataFormats/NameConf.h | 6 ++++ DataFormats/Detectors/Common/src/NameConf.cxx | 21 +++++++++++++- .../CPV/workflow/src/EntropyDecoderSpec.cxx | 4 +-- .../CPV/workflow/src/EntropyEncoderSpec.cxx | 4 +-- Detectors/CTF/workflow/src/CTFReaderSpec.cxx | 6 ++-- Detectors/CTF/workflow/src/CTFWriterSpec.cxx | 14 +++++++--- .../CTF/workflow/src/ctf-reader-workflow.cxx | 28 ++++++++++--------- .../CTF/workflow/src/ctf-writer-workflow.cxx | 6 ++-- .../EMCAL/workflow/src/EntropyDecoderSpec.cxx | 4 +-- .../EMCAL/workflow/src/EntropyEncoderSpec.cxx | 4 +-- .../FDD/workflow/src/EntropyDecoderSpec.cxx | 4 +-- .../FDD/workflow/src/EntropyEncoderSpec.cxx | 4 +-- .../FT0/workflow/src/EntropyDecoderSpec.cxx | 4 +-- .../FT0/workflow/src/EntropyEncoderSpec.cxx | 4 +-- .../FV0/workflow/src/EntropyDecoderSpec.cxx | 4 +-- .../FV0/workflow/src/EntropyEncoderSpec.cxx | 4 +-- .../HMPID/workflow/src/EntropyDecoderSpec.cxx | 4 +-- .../HMPID/workflow/src/EntropyEncoderSpec.cxx | 4 +-- .../workflow/src/EntropyDecoderSpec.cxx | 6 ++-- .../workflow/src/EntropyEncoderSpec.cxx | 6 ++-- .../MID/Workflow/src/EntropyDecoderSpec.cxx | 4 +-- .../MID/Workflow/src/EntropyEncoderSpec.cxx | 4 +-- .../PHOS/workflow/src/EntropyDecoderSpec.cxx | 4 +-- .../PHOS/workflow/src/EntropyEncoderSpec.cxx | 4 +-- .../TOF/workflow/src/EntropyDecoderSpec.cxx | 4 +-- .../TOF/workflow/src/EntropyEncoderSpec.cxx | 4 +-- .../TPC/workflow/src/EntropyDecoderSpec.cxx | 4 +-- .../TPC/workflow/src/EntropyEncoderSpec.cxx | 4 +-- .../TRD/workflow/src/EntropyDecoderSpec.cxx | 4 +-- .../TRD/workflow/src/EntropyEncoderSpec.cxx | 4 +-- .../ZDC/workflow/src/EntropyDecoderSpec.cxx | 4 +-- .../ZDC/workflow/src/EntropyEncoderSpec.cxx | 4 +-- prodtests/full-system-test/dpl-workflow.sh | 21 +++++++++++--- prodtests/full_system_test.sh | 1 - 34 files changed, 128 insertions(+), 83 deletions(-) diff --git a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h index 5565271ae133a..852807451f5e8 100644 --- a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h +++ b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h @@ -37,6 +37,9 @@ class NameConf // Expand to full path static std::string getFullPath(const std::string_view p); + // Rectify directory allowing empty one and adding '/' if it is not empty + static void rectifyDirectory(std::string& dir); + // The Hits file name are generated by hardcoded schema, only prefix is mutable to allow the embedding static std::string getHitsFileName(o2::detectors::DetID d, const std::string_view prefix = STANDARDSIMPREFIX) { @@ -103,6 +106,9 @@ class NameConf // CTF Filename static std::string getCTFFileName(uint32_t run, uint32_t orb, uint32_t id, const std::string_view prefix = "o2_ctf"); + // CTF Dictionary + static std::string getCTFDictFileName(); + private: // unmodifiable constants used to construct filenames etc static constexpr std::string_view STANDARDSIMPREFIX = "o2sim"; diff --git a/DataFormats/Detectors/Common/src/NameConf.cxx b/DataFormats/Detectors/Common/src/NameConf.cxx index ae8b2d6ee9bf6..d4ac350dba7f6 100644 --- a/DataFormats/Detectors/Common/src/NameConf.cxx +++ b/DataFormats/Detectors/Common/src/NameConf.cxx @@ -37,6 +37,20 @@ std::string NameConf::getFullPath(const std::string_view p) return std::string(real_path.get()); } +void NameConf::rectifyDirectory(std::string& dir) +{ + if (dir.empty() || dir == "none") { + dir = ""; + } else { + dir = o2::base::NameConf::getFullPath(dir); + if (!o2::base::NameConf::pathIsDirectory(dir)) { + throw std::runtime_error(fmt::format("{:s} is not an accessible directory", dir)); + } else { + dir += '/'; + } + } +} + // Filename to store geometry file std::string NameConf::getGeomFileName(const std::string_view prefix) { @@ -87,5 +101,10 @@ std::string NameConf::getMatLUTFileName(const std::string_view prefix) std::string NameConf::getCTFFileName(uint32_t run, uint32_t orb, uint32_t id, const std::string_view prefix) { - return o2::utils::concat_string(prefix, "_", fmt::format("run{:08d}_orbit{:010d}_tf{:010d}", run, orb, id), ".root"); + return o2::utils::concat_string(prefix, '_', fmt::format("run{:08d}_orbit{:010d}_tf{:010d}", run, orb, id), ".root"); +} + +std::string NameConf::getCTFDictFileName() +{ + return o2::utils::concat_string(CTFDICT, ".root"); } diff --git a/Detectors/CPV/workflow/src/EntropyDecoderSpec.cxx b/Detectors/CPV/workflow/src/EntropyDecoderSpec.cxx index 1b696185f7dbd..655e2a9be7701 100644 --- a/Detectors/CPV/workflow/src/EntropyDecoderSpec.cxx +++ b/Detectors/CPV/workflow/src/EntropyDecoderSpec.cxx @@ -31,7 +31,7 @@ EntropyDecoderSpec::EntropyDecoderSpec() void EntropyDecoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("cpv-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Decoder); } @@ -72,7 +72,7 @@ DataProcessorSpec getEntropyDecoderSpec() Inputs{InputSpec{"ctf", "CPV", "CTFDATA", 0, Lifetime::Timeframe}}, outputs, AlgorithmSpec{adaptFromTask()}, - Options{{"cpv-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF decoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF decoding dictionary"}}}}; } } // namespace cpv diff --git a/Detectors/CPV/workflow/src/EntropyEncoderSpec.cxx b/Detectors/CPV/workflow/src/EntropyEncoderSpec.cxx index 95588b1f45e77..76f5974eeb594 100644 --- a/Detectors/CPV/workflow/src/EntropyEncoderSpec.cxx +++ b/Detectors/CPV/workflow/src/EntropyEncoderSpec.cxx @@ -32,7 +32,7 @@ EntropyEncoderSpec::EntropyEncoderSpec() void EntropyEncoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("cpv-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Encoder); } @@ -72,7 +72,7 @@ DataProcessorSpec getEntropyEncoderSpec() inputs, Outputs{{"CPV", "CTFDATA", 0, Lifetime::Timeframe}}, AlgorithmSpec{adaptFromTask()}, - Options{{"cpv-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF encoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF encoding dictionary"}}}}; } } // namespace cpv diff --git a/Detectors/CTF/workflow/src/CTFReaderSpec.cxx b/Detectors/CTF/workflow/src/CTFReaderSpec.cxx index 6e1d62e3a3c4c..e3f9eb95df5fa 100644 --- a/Detectors/CTF/workflow/src/CTFReaderSpec.cxx +++ b/Detectors/CTF/workflow/src/CTFReaderSpec.cxx @@ -75,6 +75,7 @@ class CTFReaderSpec : public o2::framework::Task std::vector mInput; // input files uint32_t mTFCounter = 0; size_t mNextToProcess = 0; + std::string mCTFDir = "./"; TStopwatch mTimer; }; @@ -89,6 +90,7 @@ CTFReaderSpec::CTFReaderSpec(DetID::mask_t dm, const std::string& inp) : mDets(d ///_______________________________________ void CTFReaderSpec::init(InitContext& ic) { + o2::base::NameConf::rectifyDirectory((mCTFDir = ic.options().get("ctf-input-dir"))); } ///_______________________________________ @@ -100,7 +102,7 @@ void CTFReaderSpec::run(ProcessingContext& pc) auto cput = mTimer.CpuTime(); mTimer.Start(false); - const auto& inputFile = mInput[mNextToProcess]; + std::string inputFile = o2::utils::concat_string(mCTFDir, mInput[mNextToProcess]); LOG(INFO) << "Reading CTF input " << mNextToProcess << ' ' << inputFile; TFile flIn(inputFile.c_str()); @@ -261,7 +263,7 @@ DataProcessorSpec getCTFReaderSpec(DetID::mask_t dets, const std::string& inp) Inputs{}, outputs, AlgorithmSpec{adaptFromTask(dets, inp)}, - Options{}}; + Options{{"ctf-input-dir", VariantType::String, "./", {"CTF input directory"}}}}; } } // namespace ctf diff --git a/Detectors/CTF/workflow/src/CTFWriterSpec.cxx b/Detectors/CTF/workflow/src/CTFWriterSpec.cxx index 7d409b29c3559..5212494f5e7a7 100644 --- a/Detectors/CTF/workflow/src/CTFWriterSpec.cxx +++ b/Detectors/CTF/workflow/src/CTFWriterSpec.cxx @@ -95,6 +95,8 @@ class CTFWriterSpec : public o2::framework::Task size_t mNTF = 0; int mSaveDictAfter = -1; // if positive and mWriteCTF==true, save dictionary after each mSaveDictAfter TFs processed uint64_t mRun = 0; + std::string mDictDir = "./"; + std::string mCTFDir = "./"; std::unique_ptr mDictFileOut; // file to store dictionary std::unique_ptr mDictTreeOut; // tree to store dictionary @@ -195,6 +197,8 @@ CTFWriterSpec::CTFWriterSpec(DetID::mask_t dm, uint64_t r, bool doCTF, bool doDi void CTFWriterSpec::init(InitContext& ic) { mSaveDictAfter = ic.options().get("save-dict-after"); + o2::base::NameConf::rectifyDirectory((mDictDir = ic.options().get("ctf-dict-dir"))); + o2::base::NameConf::rectifyDirectory((mCTFDir = ic.options().get("ctf-output-dir"))); } void CTFWriterSpec::run(ProcessingContext& pc) @@ -206,7 +210,7 @@ void CTFWriterSpec::run(ProcessingContext& pc) std::unique_ptr fileOut; std::unique_ptr treeOut; if (mWriteCTF) { - fileOut.reset(TFile::Open(o2::base::NameConf::getCTFFileName(dh->runNumber, dh->firstTForbit, dh->tfCounter).c_str(), "recreate")); + fileOut.reset(TFile::Open(o2::utils::concat_string(mCTFDir, o2::base::NameConf::getCTFFileName(dh->runNumber, dh->firstTForbit, dh->tfCounter)).c_str(), "recreate")); treeOut = std::make_unique(std::string(o2::base::NameConf::CTFTREENAME).c_str(), "O2 CTF tree"); } @@ -279,9 +283,9 @@ std::string CTFWriterSpec::dictionaryFileName(const std::string& detName) if (detName.empty()) { throw std::runtime_error("Per-detector dictionary files are requested but detector name is not provided"); } - return o2::utils::concat_string(detName, "_", o2::base::NameConf::CTFDICT, ".root"); + return o2::utils::concat_string(mDictDir, detName, '_', o2::base::NameConf::CTFDICT, ".root"); } else { - return o2::utils::concat_string(o2::base::NameConf::CTFDICT, ".root"); + return o2::utils::concat_string(mDictDir, o2::base::NameConf::CTFDICT, ".root"); } } @@ -336,7 +340,9 @@ DataProcessorSpec getCTFWriterSpec(DetID::mask_t dets, uint64_t run, bool doCTF, inputs, Outputs{}, AlgorithmSpec{adaptFromTask(dets, run, doCTF, doDict, dictPerDet)}, - Options{{"save-dict-after", VariantType::Int, -1, {"In dictionary generation mode save it dictionary after certain number of TFs processed"}}}}; + Options{{"save-dict-after", VariantType::Int, -1, {"In dictionary generation mode save it dictionary after certain number of TFs processed"}}, + {"ctf-dict-dir", VariantType::String, "./", {"CTF dictionary directory"}}, + {"ctf-output-dir", VariantType::String, "./", {"CTF output directory"}}}}; } } // namespace ctf diff --git a/Detectors/CTF/workflow/src/ctf-reader-workflow.cxx b/Detectors/CTF/workflow/src/ctf-reader-workflow.cxx index ae88bd74b817a..ee30a1165764c 100644 --- a/Detectors/CTF/workflow/src/ctf-reader-workflow.cxx +++ b/Detectors/CTF/workflow/src/ctf-reader-workflow.cxx @@ -44,7 +44,7 @@ void customize(std::vector& workflowOptions) std::vector options; options.push_back(ConfigParamSpec{"onlyDet", VariantType::String, std::string{DetID::NONE}, {"comma-separated list of detectors to accept. Overrides skipDet"}}); options.push_back(ConfigParamSpec{"skipDet", VariantType::String, std::string{DetID::NONE}, {"comma-separate list of detectors to skip"}}); - options.push_back(ConfigParamSpec{"ctf-input", VariantType::String, "", {"comma-separated list CTF input files"}}); + options.push_back(ConfigParamSpec{"ctf-input", VariantType::String, "none", {"comma-separated list CTF input files"}}); std::swap(workflowOptions, options); } @@ -55,24 +55,26 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { DetID::mask_t dets; + dets.set(); // by default read all WorkflowSpec specs; - std::string inpNames; - if (!configcontext.helpOnCommandLine()) { - dets.set(); // by default read all - auto mskOnly = DetID::getMask(configcontext.options().get("onlyDet")); - auto mskSkip = DetID::getMask(configcontext.options().get("skipDet")); - if (mskOnly.any()) { - dets &= mskOnly; - } else { - dets ^= mskSkip; - } - if ((inpNames = configcontext.options().get("ctf-input")).empty()) { + auto mskOnly = DetID::getMask(configcontext.options().get("onlyDet")); + auto mskSkip = DetID::getMask(configcontext.options().get("skipDet")); + if (mskOnly.any()) { + dets &= mskOnly; + } else { + dets ^= mskSkip; + } + + std::string inpNames = configcontext.options().get("ctf-input"); + if (inpNames.empty() || inpNames == "none") { + if (!configcontext.helpOnCommandLine()) { throw std::runtime_error("--ctf-input is not provided"); } + inpNames = ""; } - specs.push_back(o2::ctf::getCTFReaderSpec(dets, inpNames)); + // add decodors for all allowed detectors. if (dets[DetID::ITS]) { specs.push_back(o2::itsmft::getEntropyDecoderSpec(DetID::getDataOrigin(DetID::ITS))); diff --git a/Detectors/CTF/workflow/src/ctf-writer-workflow.cxx b/Detectors/CTF/workflow/src/ctf-writer-workflow.cxx index 1ff74331c51a2..660591236d543 100644 --- a/Detectors/CTF/workflow/src/ctf-writer-workflow.cxx +++ b/Detectors/CTF/workflow/src/ctf-writer-workflow.cxx @@ -29,6 +29,7 @@ void customize(std::vector& workflowOptions) std::vector options; options.push_back(ConfigParamSpec{"onlyDet", VariantType::String, std::string{DetID::NONE}, {"comma separated list of detectors to accept. Overrides skipDet"}}); options.push_back(ConfigParamSpec{"skipDet", VariantType::String, std::string{DetID::NONE}, {"comma separate list of detectors to skip"}}); + options.push_back(ConfigParamSpec{"dict-per-det", VariantType::Bool, false, {"create dictionary file per detector"}}); options.push_back(ConfigParamSpec{"grpfile", VariantType::String, o2::base::NameConf::getGRPFileName(), {"name of the grp file"}}); options.push_back(ConfigParamSpec{"output-type", VariantType::String, "ctf", {"output types: ctf (per TF) or dict (create dictionaries) or both or none"}}); std::swap(workflowOptions, options); @@ -41,11 +42,12 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { DetID::mask_t dets; long run = 0; - bool doCTF = true, doDict = false; + bool doCTF = true, doDict = false, dictPerDet = false; if (!configcontext.helpOnCommandLine()) { std::unique_ptr grp(o2::parameters::GRPObject::loadFrom(configcontext.options().get("grpfile"))); dets = grp->getDetsReadOut(configcontext.options().get("onlyDet"), configcontext.options().get("skipDet")); auto outmode = configcontext.options().get("output-type"); + dictPerDet = configcontext.options().get("dict-per-det"); if (outmode == "ctf") { doCTF = true; doDict = false; @@ -63,6 +65,6 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) } run = grp->getRun(); } - WorkflowSpec specs{o2::ctf::getCTFWriterSpec(dets, run, doCTF, doDict)}; + WorkflowSpec specs{o2::ctf::getCTFWriterSpec(dets, run, doCTF, doDict, dictPerDet)}; return std::move(specs); } diff --git a/Detectors/EMCAL/workflow/src/EntropyDecoderSpec.cxx b/Detectors/EMCAL/workflow/src/EntropyDecoderSpec.cxx index dec7ed2f81cdd..86db412773721 100644 --- a/Detectors/EMCAL/workflow/src/EntropyDecoderSpec.cxx +++ b/Detectors/EMCAL/workflow/src/EntropyDecoderSpec.cxx @@ -31,7 +31,7 @@ EntropyDecoderSpec::EntropyDecoderSpec() void EntropyDecoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("emcal-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Decoder); } @@ -72,7 +72,7 @@ DataProcessorSpec getEntropyDecoderSpec() Inputs{InputSpec{"ctf", "EMC", "CTFDATA", 0, Lifetime::Timeframe}}, outputs, AlgorithmSpec{adaptFromTask()}, - Options{{"emcal-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF decoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF decoding dictionary"}}}}; } } // namespace emcal diff --git a/Detectors/EMCAL/workflow/src/EntropyEncoderSpec.cxx b/Detectors/EMCAL/workflow/src/EntropyEncoderSpec.cxx index b4372ed4d8186..1a83e73d1093a 100644 --- a/Detectors/EMCAL/workflow/src/EntropyEncoderSpec.cxx +++ b/Detectors/EMCAL/workflow/src/EntropyEncoderSpec.cxx @@ -32,7 +32,7 @@ EntropyEncoderSpec::EntropyEncoderSpec() void EntropyEncoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("emcal-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Encoder); } @@ -72,7 +72,7 @@ DataProcessorSpec getEntropyEncoderSpec() inputs, Outputs{{"EMC", "CTFDATA", 0, Lifetime::Timeframe}}, AlgorithmSpec{adaptFromTask()}, - Options{{"emcal-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF encoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF encoding dictionary"}}}}; } } // namespace emcal diff --git a/Detectors/FIT/FDD/workflow/src/EntropyDecoderSpec.cxx b/Detectors/FIT/FDD/workflow/src/EntropyDecoderSpec.cxx index b4555f711b98c..39a0146c12754 100644 --- a/Detectors/FIT/FDD/workflow/src/EntropyDecoderSpec.cxx +++ b/Detectors/FIT/FDD/workflow/src/EntropyDecoderSpec.cxx @@ -31,7 +31,7 @@ EntropyDecoderSpec::EntropyDecoderSpec() void EntropyDecoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("fdd-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Decoder); } @@ -72,7 +72,7 @@ DataProcessorSpec getEntropyDecoderSpec() Inputs{InputSpec{"ctf", "FDD", "CTFDATA", 0, Lifetime::Timeframe}}, outputs, AlgorithmSpec{adaptFromTask()}, - Options{{"fdd-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF decoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF decoding dictionary"}}}}; } } // namespace fdd diff --git a/Detectors/FIT/FDD/workflow/src/EntropyEncoderSpec.cxx b/Detectors/FIT/FDD/workflow/src/EntropyEncoderSpec.cxx index 6d6e57ba042fc..659d8af844c1b 100644 --- a/Detectors/FIT/FDD/workflow/src/EntropyEncoderSpec.cxx +++ b/Detectors/FIT/FDD/workflow/src/EntropyEncoderSpec.cxx @@ -32,7 +32,7 @@ EntropyEncoderSpec::EntropyEncoderSpec() void EntropyEncoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("fdd-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Encoder); } @@ -71,7 +71,7 @@ DataProcessorSpec getEntropyEncoderSpec() inputs, Outputs{{"FDD", "CTFDATA", 0, Lifetime::Timeframe}}, AlgorithmSpec{adaptFromTask()}, - Options{{"fdd-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF encoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF encoding dictionary"}}}}; } } // namespace fdd diff --git a/Detectors/FIT/FT0/workflow/src/EntropyDecoderSpec.cxx b/Detectors/FIT/FT0/workflow/src/EntropyDecoderSpec.cxx index d69e174deb922..c1757e73e387b 100644 --- a/Detectors/FIT/FT0/workflow/src/EntropyDecoderSpec.cxx +++ b/Detectors/FIT/FT0/workflow/src/EntropyDecoderSpec.cxx @@ -31,7 +31,7 @@ EntropyDecoderSpec::EntropyDecoderSpec() void EntropyDecoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("ft0-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Decoder); } @@ -72,7 +72,7 @@ DataProcessorSpec getEntropyDecoderSpec() Inputs{InputSpec{"ctf", "FT0", "CTFDATA", 0, Lifetime::Timeframe}}, outputs, AlgorithmSpec{adaptFromTask()}, - Options{{"ft0-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF decoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF decoding dictionary"}}}}; } } // namespace ft0 diff --git a/Detectors/FIT/FT0/workflow/src/EntropyEncoderSpec.cxx b/Detectors/FIT/FT0/workflow/src/EntropyEncoderSpec.cxx index 93e1d013ba95d..f7f41ad0d11c1 100644 --- a/Detectors/FIT/FT0/workflow/src/EntropyEncoderSpec.cxx +++ b/Detectors/FIT/FT0/workflow/src/EntropyEncoderSpec.cxx @@ -32,7 +32,7 @@ EntropyEncoderSpec::EntropyEncoderSpec() void EntropyEncoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("ft0-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Encoder); } @@ -72,7 +72,7 @@ DataProcessorSpec getEntropyEncoderSpec() inputs, Outputs{{"FT0", "CTFDATA", 0, Lifetime::Timeframe}}, AlgorithmSpec{adaptFromTask()}, - Options{{"ft0-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF encoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF encoding dictionary"}}}}; } } // namespace ft0 diff --git a/Detectors/FIT/FV0/workflow/src/EntropyDecoderSpec.cxx b/Detectors/FIT/FV0/workflow/src/EntropyDecoderSpec.cxx index 6f5cb5b0b3a06..51f92bfcf1405 100644 --- a/Detectors/FIT/FV0/workflow/src/EntropyDecoderSpec.cxx +++ b/Detectors/FIT/FV0/workflow/src/EntropyDecoderSpec.cxx @@ -31,7 +31,7 @@ EntropyDecoderSpec::EntropyDecoderSpec() void EntropyDecoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("fv0-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Decoder); } @@ -72,7 +72,7 @@ DataProcessorSpec getEntropyDecoderSpec() Inputs{InputSpec{"ctf", "FV0", "CTFDATA", 0, Lifetime::Timeframe}}, outputs, AlgorithmSpec{adaptFromTask()}, - Options{{"fv0-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF decoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF decoding dictionary"}}}}; } } // namespace fv0 diff --git a/Detectors/FIT/FV0/workflow/src/EntropyEncoderSpec.cxx b/Detectors/FIT/FV0/workflow/src/EntropyEncoderSpec.cxx index ff8f7bd5f6c5a..7d786f88ffef1 100644 --- a/Detectors/FIT/FV0/workflow/src/EntropyEncoderSpec.cxx +++ b/Detectors/FIT/FV0/workflow/src/EntropyEncoderSpec.cxx @@ -32,7 +32,7 @@ EntropyEncoderSpec::EntropyEncoderSpec() void EntropyEncoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("fv0-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Encoder); } @@ -71,7 +71,7 @@ DataProcessorSpec getEntropyEncoderSpec() inputs, Outputs{{"FV0", "CTFDATA", 0, Lifetime::Timeframe}}, AlgorithmSpec{adaptFromTask()}, - Options{{"fv0-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF encoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF encoding dictionary"}}}}; } } // namespace fv0 diff --git a/Detectors/HMPID/workflow/src/EntropyDecoderSpec.cxx b/Detectors/HMPID/workflow/src/EntropyDecoderSpec.cxx index a5264b3ee4e8d..56ec0a414f09e 100644 --- a/Detectors/HMPID/workflow/src/EntropyDecoderSpec.cxx +++ b/Detectors/HMPID/workflow/src/EntropyDecoderSpec.cxx @@ -47,7 +47,7 @@ EntropyDecoderSpec::EntropyDecoderSpec() void EntropyDecoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("hmpid-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Decoder); } @@ -88,7 +88,7 @@ DataProcessorSpec getEntropyDecoderSpec() Inputs{InputSpec{"ctf", "HMP", "CTFDATA", 0, Lifetime::Timeframe}}, outputs, AlgorithmSpec{adaptFromTask()}, - Options{{"hmpid-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF decoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF decoding dictionary"}}}}; } } // namespace hmpid diff --git a/Detectors/HMPID/workflow/src/EntropyEncoderSpec.cxx b/Detectors/HMPID/workflow/src/EntropyEncoderSpec.cxx index fb5472a013496..94e9ad05bafb5 100644 --- a/Detectors/HMPID/workflow/src/EntropyEncoderSpec.cxx +++ b/Detectors/HMPID/workflow/src/EntropyEncoderSpec.cxx @@ -48,7 +48,7 @@ EntropyEncoderSpec::EntropyEncoderSpec() void EntropyEncoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("hmpid-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Encoder); } @@ -88,7 +88,7 @@ DataProcessorSpec getEntropyEncoderSpec() inputs, Outputs{{"HMP", "CTFDATA", 0, Lifetime::Timeframe}}, AlgorithmSpec{adaptFromTask()}, - Options{{"hmpid-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF encoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF encoding dictionary"}}}}; } } // namespace hmpid diff --git a/Detectors/ITSMFT/common/workflow/src/EntropyDecoderSpec.cxx b/Detectors/ITSMFT/common/workflow/src/EntropyDecoderSpec.cxx index ffd61641dfd4b..b50e3f7e9ebd9 100644 --- a/Detectors/ITSMFT/common/workflow/src/EntropyDecoderSpec.cxx +++ b/Detectors/ITSMFT/common/workflow/src/EntropyDecoderSpec.cxx @@ -34,7 +34,7 @@ EntropyDecoderSpec::EntropyDecoderSpec(o2::header::DataOrigin orig) void EntropyDecoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get((mOrigin == o2::header::gDataOriginITS) ? "its-ctf-dictionary" : "mft-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Decoder); } @@ -72,14 +72,12 @@ DataProcessorSpec getEntropyDecoderSpec(o2::header::DataOrigin orig) OutputSpec{{"patterns"}, orig, "PATTERNS", 0, Lifetime::Timeframe}, OutputSpec{{"ROframes"}, orig, "CLUSTERSROF", 0, Lifetime::Timeframe}}; - std::string dictOptName = (orig == o2::header::gDataOriginITS) ? "its-ctf-dictionary" : "mft-ctf-dictionary"; - return DataProcessorSpec{ orig == o2::header::gDataOriginITS ? "its-entropy-decoder" : "mft-entropy-decoder", Inputs{InputSpec{"ctf", orig, "CTFDATA", 0, Lifetime::Timeframe}}, outputs, AlgorithmSpec{adaptFromTask(orig)}, - Options{{dictOptName, VariantType::String, "ctf_dictionary.root", {"File of CTF decoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF decoding dictionary"}}}}; } } // namespace itsmft diff --git a/Detectors/ITSMFT/common/workflow/src/EntropyEncoderSpec.cxx b/Detectors/ITSMFT/common/workflow/src/EntropyEncoderSpec.cxx index cb9af0129f9ab..17d36b9eead8a 100644 --- a/Detectors/ITSMFT/common/workflow/src/EntropyEncoderSpec.cxx +++ b/Detectors/ITSMFT/common/workflow/src/EntropyEncoderSpec.cxx @@ -35,7 +35,7 @@ EntropyEncoderSpec::EntropyEncoderSpec(o2::header::DataOrigin orig) void EntropyEncoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get((mOrigin == o2::header::gDataOriginITS) ? "its-ctf-dictionary" : "mft-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Encoder); } @@ -72,14 +72,12 @@ DataProcessorSpec getEntropyEncoderSpec(o2::header::DataOrigin orig) inputs.emplace_back("patterns", orig, "PATTERNS", 0, Lifetime::Timeframe); inputs.emplace_back("ROframes", orig, "CLUSTERSROF", 0, Lifetime::Timeframe); - std::string dictOptName = (orig == o2::header::gDataOriginITS) ? "its-ctf-dictionary" : "mft-ctf-dictionary"; - return DataProcessorSpec{ orig == o2::header::gDataOriginITS ? "its-entropy-encoder" : "mft-entropy-encoder", inputs, Outputs{{orig, "CTFDATA", 0, Lifetime::Timeframe}}, AlgorithmSpec{adaptFromTask(orig)}, - Options{{dictOptName, VariantType::String, "ctf_dictionary.root", {"File of CTF encoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF encoding dictionary"}}}}; } } // namespace itsmft diff --git a/Detectors/MUON/MID/Workflow/src/EntropyDecoderSpec.cxx b/Detectors/MUON/MID/Workflow/src/EntropyDecoderSpec.cxx index ac4f7364faa95..d322d735f0c67 100644 --- a/Detectors/MUON/MID/Workflow/src/EntropyDecoderSpec.cxx +++ b/Detectors/MUON/MID/Workflow/src/EntropyDecoderSpec.cxx @@ -31,7 +31,7 @@ EntropyDecoderSpec::EntropyDecoderSpec() void EntropyDecoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("mid-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Decoder); } @@ -72,7 +72,7 @@ DataProcessorSpec getEntropyDecoderSpec() Inputs{InputSpec{"ctf", "MID", "CTFDATA", 0, Lifetime::Timeframe}}, outputs, AlgorithmSpec{adaptFromTask()}, - Options{{"mid-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF decoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF decoding dictionary"}}}}; } } // namespace mid diff --git a/Detectors/MUON/MID/Workflow/src/EntropyEncoderSpec.cxx b/Detectors/MUON/MID/Workflow/src/EntropyEncoderSpec.cxx index e3aca8c542833..0e240ff4ffdd6 100644 --- a/Detectors/MUON/MID/Workflow/src/EntropyEncoderSpec.cxx +++ b/Detectors/MUON/MID/Workflow/src/EntropyEncoderSpec.cxx @@ -34,7 +34,7 @@ EntropyEncoderSpec::EntropyEncoderSpec() void EntropyEncoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("mid-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Encoder); } @@ -74,7 +74,7 @@ DataProcessorSpec getEntropyEncoderSpec() inputs, Outputs{{"MID", "CTFDATA", 0, Lifetime::Timeframe}}, AlgorithmSpec{adaptFromTask()}, - Options{{"mid-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF encoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF encoding dictionary"}}}}; } } // namespace mid diff --git a/Detectors/PHOS/workflow/src/EntropyDecoderSpec.cxx b/Detectors/PHOS/workflow/src/EntropyDecoderSpec.cxx index 0726b61363ab7..c61eae2a6ff02 100644 --- a/Detectors/PHOS/workflow/src/EntropyDecoderSpec.cxx +++ b/Detectors/PHOS/workflow/src/EntropyDecoderSpec.cxx @@ -31,7 +31,7 @@ EntropyDecoderSpec::EntropyDecoderSpec() void EntropyDecoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("phos-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Decoder); } @@ -72,7 +72,7 @@ DataProcessorSpec getEntropyDecoderSpec() Inputs{InputSpec{"ctf", "PHS", "CTFDATA", 0, Lifetime::Timeframe}}, outputs, AlgorithmSpec{adaptFromTask()}, - Options{{"phos-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF decoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF decoding dictionary"}}}}; } } // namespace phos diff --git a/Detectors/PHOS/workflow/src/EntropyEncoderSpec.cxx b/Detectors/PHOS/workflow/src/EntropyEncoderSpec.cxx index 0c5a4b8d6119c..799bc68c75f3c 100644 --- a/Detectors/PHOS/workflow/src/EntropyEncoderSpec.cxx +++ b/Detectors/PHOS/workflow/src/EntropyEncoderSpec.cxx @@ -32,7 +32,7 @@ EntropyEncoderSpec::EntropyEncoderSpec() void EntropyEncoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("phos-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Encoder); } @@ -72,7 +72,7 @@ DataProcessorSpec getEntropyEncoderSpec() inputs, Outputs{{"PHS", "CTFDATA", 0, Lifetime::Timeframe}}, AlgorithmSpec{adaptFromTask()}, - Options{{"phos-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF encoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF encoding dictionary"}}}}; } } // namespace phos diff --git a/Detectors/TOF/workflow/src/EntropyDecoderSpec.cxx b/Detectors/TOF/workflow/src/EntropyDecoderSpec.cxx index ca1fa309a8831..8542029b9c1a1 100644 --- a/Detectors/TOF/workflow/src/EntropyDecoderSpec.cxx +++ b/Detectors/TOF/workflow/src/EntropyDecoderSpec.cxx @@ -31,7 +31,7 @@ EntropyDecoderSpec::EntropyDecoderSpec() void EntropyDecoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("tof-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Decoder); } @@ -76,7 +76,7 @@ DataProcessorSpec getEntropyDecoderSpec() Inputs{InputSpec{"ctf", o2::header::gDataOriginTOF, "CTFDATA", 0, Lifetime::Timeframe}}, outputs, AlgorithmSpec{adaptFromTask()}, - Options{{"tof-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF decoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF decoding dictionary"}}}}; } } // namespace tof diff --git a/Detectors/TOF/workflow/src/EntropyEncoderSpec.cxx b/Detectors/TOF/workflow/src/EntropyEncoderSpec.cxx index 8d5ff90003cfe..4b28755cbbd6e 100644 --- a/Detectors/TOF/workflow/src/EntropyEncoderSpec.cxx +++ b/Detectors/TOF/workflow/src/EntropyEncoderSpec.cxx @@ -32,7 +32,7 @@ EntropyEncoderSpec::EntropyEncoderSpec() void EntropyEncoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("tof-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Encoder); } @@ -74,7 +74,7 @@ DataProcessorSpec getEntropyEncoderSpec() inputs, Outputs{{o2::header::gDataOriginTOF, "CTFDATA", 0, Lifetime::Timeframe}}, AlgorithmSpec{adaptFromTask()}, - Options{{"tof-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF encoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF encoding dictionary"}}}}; } } // namespace tof diff --git a/Detectors/TPC/workflow/src/EntropyDecoderSpec.cxx b/Detectors/TPC/workflow/src/EntropyDecoderSpec.cxx index b5d97bb2931ff..1a35e5ea5c1e3 100644 --- a/Detectors/TPC/workflow/src/EntropyDecoderSpec.cxx +++ b/Detectors/TPC/workflow/src/EntropyDecoderSpec.cxx @@ -26,7 +26,7 @@ namespace tpc void EntropyDecoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("tpc-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Decoder); } @@ -61,7 +61,7 @@ DataProcessorSpec getEntropyDecoderSpec() Inputs{InputSpec{"ctf", "TPC", "CTFDATA", 0, Lifetime::Timeframe}}, Outputs{OutputSpec{{"output"}, "TPC", "COMPCLUSTERSFLAT", 0, Lifetime::Timeframe}}, AlgorithmSpec{adaptFromTask()}, - Options{{"tpc-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF decoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF decoding dictionary"}}}}; } } // namespace tpc diff --git a/Detectors/TPC/workflow/src/EntropyEncoderSpec.cxx b/Detectors/TPC/workflow/src/EntropyEncoderSpec.cxx index e89992a9cf963..575a250dd263e 100644 --- a/Detectors/TPC/workflow/src/EntropyEncoderSpec.cxx +++ b/Detectors/TPC/workflow/src/EntropyEncoderSpec.cxx @@ -29,7 +29,7 @@ namespace tpc void EntropyEncoderSpec::init(o2::framework::InitContext& ic) { mCTFCoder.setCombineColumns(!ic.options().get("no-ctf-columns-combining")); - std::string dictPath = ic.options().get("tpc-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Encoder); } @@ -82,7 +82,7 @@ DataProcessorSpec getEntropyEncoderSpec(bool inputFromFile) Inputs{{"input", "TPC", inputType, 0, Lifetime::Timeframe}}, Outputs{{"TPC", "CTFDATA", 0, Lifetime::Timeframe}}, AlgorithmSpec{adaptFromTask(inputFromFile)}, - Options{{"tpc-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF encoding dictionary"}}, + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF encoding dictionary"}}, {"no-ctf-columns-combining", VariantType::Bool, false, {"Do not combine correlated columns in CTF"}}}}; } diff --git a/Detectors/TRD/workflow/src/EntropyDecoderSpec.cxx b/Detectors/TRD/workflow/src/EntropyDecoderSpec.cxx index e8b3e23fda965..9fb6edad53d7b 100644 --- a/Detectors/TRD/workflow/src/EntropyDecoderSpec.cxx +++ b/Detectors/TRD/workflow/src/EntropyDecoderSpec.cxx @@ -47,7 +47,7 @@ EntropyDecoderSpec::EntropyDecoderSpec() void EntropyDecoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("trd-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Decoder); } @@ -90,7 +90,7 @@ DataProcessorSpec getEntropyDecoderSpec() Inputs{InputSpec{"ctf", "TRD", "CTFDATA", 0, Lifetime::Timeframe}}, outputs, AlgorithmSpec{adaptFromTask()}, - Options{{"trd-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF decoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF decoding dictionary"}}}}; } } // namespace trd diff --git a/Detectors/TRD/workflow/src/EntropyEncoderSpec.cxx b/Detectors/TRD/workflow/src/EntropyEncoderSpec.cxx index 2c66115edbaba..495b75801c2e1 100644 --- a/Detectors/TRD/workflow/src/EntropyEncoderSpec.cxx +++ b/Detectors/TRD/workflow/src/EntropyEncoderSpec.cxx @@ -48,7 +48,7 @@ EntropyEncoderSpec::EntropyEncoderSpec() void EntropyEncoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("trd-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Encoder); } @@ -90,7 +90,7 @@ DataProcessorSpec getEntropyEncoderSpec() inputs, Outputs{{"TRD", "CTFDATA", 0, Lifetime::Timeframe}}, AlgorithmSpec{adaptFromTask()}, - Options{{"trd-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF encoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF encoding dictionary"}}}}; } } // namespace trd diff --git a/Detectors/ZDC/workflow/src/EntropyDecoderSpec.cxx b/Detectors/ZDC/workflow/src/EntropyDecoderSpec.cxx index 2e38aad38b2e6..b35fc4fc205ca 100644 --- a/Detectors/ZDC/workflow/src/EntropyDecoderSpec.cxx +++ b/Detectors/ZDC/workflow/src/EntropyDecoderSpec.cxx @@ -31,7 +31,7 @@ EntropyDecoderSpec::EntropyDecoderSpec() void EntropyDecoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("zdc-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Decoder); } @@ -74,7 +74,7 @@ DataProcessorSpec getEntropyDecoderSpec() Inputs{InputSpec{"ctf", "ZDC", "CTFDATA", 0, Lifetime::Timeframe}}, outputs, AlgorithmSpec{adaptFromTask()}, - Options{{"zdc-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF decoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF decoding dictionary"}}}}; } } // namespace zdc diff --git a/Detectors/ZDC/workflow/src/EntropyEncoderSpec.cxx b/Detectors/ZDC/workflow/src/EntropyEncoderSpec.cxx index f30f2b02c5d47..fe659a440f545 100644 --- a/Detectors/ZDC/workflow/src/EntropyEncoderSpec.cxx +++ b/Detectors/ZDC/workflow/src/EntropyEncoderSpec.cxx @@ -34,7 +34,7 @@ EntropyEncoderSpec::EntropyEncoderSpec() void EntropyEncoderSpec::init(o2::framework::InitContext& ic) { - std::string dictPath = ic.options().get("zdc-ctf-dictionary"); + std::string dictPath = ic.options().get("ctf-dict"); if (!dictPath.empty() && dictPath != "none") { mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Encoder); } @@ -76,7 +76,7 @@ DataProcessorSpec getEntropyEncoderSpec() inputs, Outputs{{"ZDC", "CTFDATA", 0, Lifetime::Timeframe}}, AlgorithmSpec{adaptFromTask()}, - Options{{"zdc-ctf-dictionary", VariantType::String, "ctf_dictionary.root", {"File of CTF encoding dictionary"}}}}; + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF encoding dictionary"}}}}; } } // namespace zdc diff --git a/prodtests/full-system-test/dpl-workflow.sh b/prodtests/full-system-test/dpl-workflow.sh index fc4851f0ec005..0e3bfcf5c7edb 100755 --- a/prodtests/full-system-test/dpl-workflow.sh +++ b/prodtests/full-system-test/dpl-workflow.sh @@ -22,6 +22,8 @@ fi # Set some individual workflow arguments depending on configuration CTF_DETECTORS=ITS,MFT,TPC,TOF,FT0,MID,EMC,PHS,CPV,ZDC,FDD +CTF_DIR= +CTF_DICT_DIR= TPC_INPUT=zsraw TPC_OUTPUT=tracks,clusters,disable-writer TPC_CONFIG= @@ -85,7 +87,9 @@ if [ $CTFINPUT == 1 ]; then TPC_INPUT=compressed-clusters-ctf TOF_INPUT=digits CTFName=`ls -t o2_ctf_*.root | head -n1` - WORKFLOW="o2-ctf-reader-workflow --ctf-input ${CTFName} --onlyDet $CTF_DETECTORS $ARGS_ALL | " + CTF_DICT= + if [ ! -z $CTF_DICT_DIR ] ; then CTF_DICT=" --ctf-dict ${CTF_DICT_DIR}/ctf_dictionary.root"; fi + WORKFLOW="o2-ctf-reader-workflow --ctf-input ${CTFName} ${CTF_DICT} --onlyDet $CTF_DETECTORS $ARGS_ALL | " elif [ $EXTINPUT == 1 ]; then WORKFLOW="o2-dpl-raw-proxy $ARGS_ALL --dataspec \"FLP:FLP/DISTSUBTIMEFRAME/0;B:TPC/RAWDATA;C:ITS/RAWDATA;D:TOF/RAWDATA;D:MFT/RAWDATA;E:FT0/RAWDATA;F:MID/RAWDATA;G:EMC/RAWDATA;H:PHS/RAWDATA;I:CPV/RAWDATA;J:ZDC/RAWDATA;K:HMP/RAWDATA;L:FDD/RAWDATA\" --channel-config \"name=readout-proxy,type=pull,method=connect,address=ipc://@stfb-to-dpl,transport=shmem,rateLogging=0\" | " else @@ -139,14 +143,23 @@ if [ $CTFINPUT == 0 ]; then WORKFLOW+="o2-tpc-scdcalib-interpolation-workflow $ARGS_ALL --disable-root-output --disable-root-input | " # Output workflow + if [ ! -z $CTF_DIR ] ; then mkdir -p $CTF_DIR; fi + if [ $CREATECTFDICT == 1 ] ; then + _DICT_="ctf_dictionary.root" + if [ ! -z $CTF_DICT_DIR ] ; then + mkdir -p $CTF_DICT_DIR; + _DICT_="$CTF_DICT_DIR/$_DICT_" + fi + if [ -e $_DICT_ ] ; then rm -f $_DICT_; fi + fi CTF_OUTPUT_TYPE="none" if [ $CREATECTFDICT == 1 ] && [ $SAVECTF == 1 ]; then CTF_OUTPUT_TYPE="both"; fi if [ $CREATECTFDICT == 1 ] && [ $SAVECTF == 0 ]; then CTF_OUTPUT_TYPE="dict"; fi if [ $CREATECTFDICT == 0 ] && [ $SAVECTF == 1 ]; then CTF_OUTPUT_TYPE="ctf"; fi CMD_CTF="o2-ctf-writer-workflow $ARGS_ALL --output-type $CTF_OUTPUT_TYPE --onlyDet $CTF_DETECTORS" - if [ $CREATECTFDICT == 1 ] && [ $EXTINPUT == 1 ]; then - CMD_CTF+=" --save-dict-after $NTIMEFRAMES" - fi + if [ $CREATECTFDICT == 1 ] && [ $EXTINPUT == 1 ]; then CMD_CTF+=" --save-dict-after $NTIMEFRAMES"; fi + if [ ! -z $CTF_DICT_DIR ]; then CMD_CTF+=" --ctf-dict-dir $CTF_DICT_DIR"; fi + if [ ! -z $CTF_DIR ]; then CMD_CTF+=" --ctf-output-dir $CTF_DIR"; fi WORKFLOW+="$CMD_CTF | " fi diff --git a/prodtests/full_system_test.sh b/prodtests/full_system_test.sh index 2262f1c2c8302..0e39047ec543b 100755 --- a/prodtests/full_system_test.sh +++ b/prodtests/full_system_test.sh @@ -141,7 +141,6 @@ for STAGE in $STAGES; do export HOSTMEMSIZE=$TPCTRACKERSCRATCHMEMORY export CTFINPUT=0 export SAVECTF=1 - JOBUTILS_JOB_SKIPCREATEDONE=1 taskwrapper ${logfile} "rm -f ctf_dictionary.root" unset JOBUTILS_JOB_SKIPCREATEDONE fi export SHMSIZE From 11dccf982d2e61766f7f280b436d798ecb0149e5 Mon Sep 17 00:00:00 2001 From: Fabrizio Date: Wed, 14 Apr 2021 09:49:06 +0200 Subject: [PATCH 129/770] PWGHF: Adapt track index skim creator with 2D configurables (#5832) --- .../include/AnalysisCore/HFSelectorCuts.h | 32 ++++++++++ .../Tasks/PWGHF/HFTrackIndexSkimsCreator.cxx | 59 +++++++++++++++---- 2 files changed, 79 insertions(+), 12 deletions(-) diff --git a/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h b/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h index 4bc1ded308ffc..054ba659d51f5 100644 --- a/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h +++ b/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h @@ -41,6 +41,38 @@ int findBin(o2::framework::Configurable> const& bins, T2 value) } // namespace per channel +namespace hf_cuts_single_track +{ +static constexpr int npTBinsTrack = 6; +static constexpr int nCutVarsTrack = 2; +// default values for the pT bin edges (can be used to configure histogram axis) +// common for any candidate type (2-prong, 3-prong) +// offset by 1 from the bin numbers in cuts array +constexpr double pTBinsTrack[npTBinsTrack + 1] = { + 0, + 0.5, + 1.0, + 1.5, + 2.0, + 3.0, + 1000.0}; +auto pTBinsTrack_v = std::vector{pTBinsTrack, pTBinsTrack + npTBinsTrack + 1}; + +// default values for the cuts +constexpr double cutsTrack[npTBinsTrack][nCutVarsTrack] = {{0., 10.}, /* pt<0.5*/ + {0., 10.}, /* 0.53*/ + +// row labels +static const std::vector pTBinLabelsTrack{}; + +// column labels +static const std::vector cutVarLabelsTrack = {"min_dcaxytoprimary", "max_dcaxytoprimary"}; +} // namespace hf_cuts_single_track + namespace hf_cuts_d0_topik { static constexpr int npTBins = 25; diff --git a/Analysis/Tasks/PWGHF/HFTrackIndexSkimsCreator.cxx b/Analysis/Tasks/PWGHF/HFTrackIndexSkimsCreator.cxx index dc12a6880a19b..01d2d4fadbd6b 100644 --- a/Analysis/Tasks/PWGHF/HFTrackIndexSkimsCreator.cxx +++ b/Analysis/Tasks/PWGHF/HFTrackIndexSkimsCreator.cxx @@ -21,6 +21,7 @@ #include "AnalysisDataModel/HFSecondaryVertex.h" #include "AnalysisCore/trackUtilities.h" #include "AnalysisCore/HFConfigurables.h" +#include "AnalysisCore/HFSelectorCuts.h" //#include "AnalysisDataModel/Centrality.h" #include "Framework/HistogramRegistry.h" #include @@ -30,9 +31,18 @@ using namespace o2::framework; using namespace o2::framework::expressions; using namespace o2::aod::hf_cand_prong2; using namespace o2::aod::hf_cand_prong3; +using namespace o2::analysis; +using namespace o2::analysis::hf_cuts_single_track; /// Track selection struct SelectTracks { + + // enum for candidate type + enum CandidateType { + Cand2Prong = 0, + Cand3Prong + }; + Produces rowSelectedTrack; Configurable b_dovalplots{"b_dovalplots", true, "fill histograms"}; @@ -40,17 +50,15 @@ struct SelectTracks { // quality cut Configurable doCutQuality{"doCutQuality", true, "apply quality cuts"}; Configurable d_tpcnclsfound{"d_tpcnclsfound", 70, ">= min. number of TPC clusters needed"}; + // pT bins for single-track cuts + Configurable> pTBinsTrack{"ptbins_singletrack", std::vector{hf_cuts_single_track::pTBinsTrack_v}, "track pT bin limits for 2-prong DCAXY pT-depentend cut"}; // 2-prong cuts Configurable ptmintrack_2prong{"ptmintrack_2prong", -1., "min. track pT for 2 prong candidate"}; - Configurable dcatoprimxy_2prong_maxpt{"dcatoprimxy_2prong_maxpt", 2., "max pt cut for min. DCAXY to prim. vtx. for 2 prong candidate"}; - Configurable dcatoprimxymin_2prong{"dcatoprimxymin_2prong", 0., "min. DCAXY to prim. vtx. for 2 prong candidate"}; - Configurable dcatoprimxymax_2prong{"dcatoprimxymax_2prong", 1.0, "max. DCAXY to prim. vtx. for 2 prong candidate"}; + Configurable> cutsTrack2Prong{"cuts_singletrack_2prong", {hf_cuts_single_track::cutsTrack[0], npTBinsTrack, nCutVarsTrack, pTBinLabelsTrack, cutVarLabelsTrack}, "Single-track selections per pT bin for 2-prong candidates"}; Configurable etamax_2prong{"etamax_2prong", 4., "max. pseudorapidity for 2 prong candidate"}; // 3-prong cuts Configurable ptmintrack_3prong{"ptmintrack_3prong", -1., "min. track pT for 3 prong candidate"}; - Configurable dcatoprimxy_3prong_maxpt{"dcatoprimxy_3prong_maxpt", 2., "max pt cut for min. DCAXY to prim. vtx. for 3 prong candidate"}; - Configurable dcatoprimxymin_3prong{"dcatoprimxymin_3prong", 0., "min. DCAXY to prim. vtx. for 3 prong candidate"}; - Configurable dcatoprimxymax_3prong{"dcatoprimxymax_3prong", 1.0, "max. DCAXY to prim. vtx. for 3 prong candidate"}; + Configurable> cutsTrack3Prong{"cuts_singletrack_3prong", {hf_cuts_single_track::cutsTrack[0], npTBinsTrack, nCutVarsTrack, pTBinLabelsTrack, cutVarLabelsTrack}, "Single-track selections per pT bin for 3-prong candidates"}; Configurable etamax_3prong{"etamax_3prong", 4., "max. pseudorapidity for 3 prong candidate"}; HistogramRegistry registry{ @@ -58,13 +66,42 @@ struct SelectTracks { {{"hpt_nocuts", "all tracks;#it{p}_{T}^{track} (GeV/#it{c});entries", {HistType::kTH1F, {{100, 0., 10.}}}}, // 2-prong histograms {"hpt_cuts_2prong", "tracks selected for 2-prong vertexing;#it{p}_{T}^{track} (GeV/#it{c});entries", {HistType::kTH1F, {{100, 0., 10.}}}}, - {"hdcatoprimxy_cuts_2prong", "tracks selected for 2-prong vertexing;DCAxy to prim. vtx. (cm);entries", {HistType::kTH1F, {{static_cast(1.2 * dcatoprimxymax_2prong * 100), -1.2 * dcatoprimxymax_2prong, 1.2 * dcatoprimxymax_2prong}}}}, + {"hdcatoprimxy_cuts_2prong", "tracks selected for 2-prong vertexing;DCAxy to prim. vtx. (cm);entries", {HistType::kTH1F, {{400, -2., 2.}}}}, {"heta_cuts_2prong", "tracks selected for 2-prong vertexing;#it{#eta};entries", {HistType::kTH1F, {{static_cast(1.2 * etamax_2prong * 100), -1.2 * etamax_2prong, 1.2 * etamax_2prong}}}}, // 3-prong histograms {"hpt_cuts_3prong", "tracks selected for 3-prong vertexing;#it{p}_{T}^{track} (GeV/#it{c});entries", {HistType::kTH1F, {{100, 0., 10.}}}}, - {"hdcatoprimxy_cuts_3prong", "tracks selected for 3-prong vertexing;DCAxy to prim. vtx. (cm);entries", {HistType::kTH1F, {{static_cast(1.2 * dcatoprimxymax_3prong) * 100, -1.2 * dcatoprimxymax_3prong, 1.2 * dcatoprimxymax_3prong}}}}, + {"hdcatoprimxy_cuts_3prong", "tracks selected for 3-prong vertexing;DCAxy to prim. vtx. (cm);entries", {HistType::kTH1F, {{400, -2., 2.}}}}, {"heta_cuts_3prong", "tracks selected for 3-prong vertexing;#it{#eta};entries", {HistType::kTH1F, {{static_cast(1.2 * etamax_3prong * 100), -1.2 * etamax_3prong, 1.2 * etamax_3prong}}}}}}; + // array of 2-prong and 3-prong single-track cuts + std::array, 2> cutsSingleTrack; + + void init(InitContext const&) + { + cutsSingleTrack = {cutsTrack2Prong, cutsTrack3Prong}; + } + + /// Single-track cuts for 2-prongs or 3-prongs + /// \param hfTrack is a track + /// \param dca is a 2-element array with dca in transverse and longitudinal directions + /// \return true if track passes all cuts + template + bool isSelectedTrack(const T& hfTrack, const array& dca, const int candType) + { + auto pTBinTrack = findBin(pTBinsTrack, hfTrack.pt()); + if (pTBinTrack == -1) { + return false; + } + + if (abs(dca[0]) < cutsSingleTrack[candType].get(pTBinTrack, "min_dcaxytoprimary")) { + return false; //minimum DCAxy + } + if (abs(dca[0]) > cutsSingleTrack[candType].get(pTBinTrack, "max_dcaxytoprimary")) { + return false; //maximum DCAxy + } + return true; + } + void process(aod::Collision const& collision, soa::Join const& tracks) { @@ -108,16 +145,14 @@ struct SelectTracks { // DCA cut array dca; if (status_prong > 0) { - double dcatoprimxymin_2prong_ptdep = dcatoprimxymin_2prong * TMath::Max(0., (1 - TMath::Floor(trackPt / dcatoprimxy_2prong_maxpt))); - double dcatoprimxymin_3prong_ptdep = dcatoprimxymin_3prong * TMath::Max(0., (1 - TMath::Floor(trackPt / dcatoprimxy_3prong_maxpt))); auto trackparvar0 = getTrackParCov(track); if (!trackparvar0.propagateParamToDCA(vtxXYZ, d_bz, &dca, 100.)) { // get impact parameters status_prong = 0; } - if ((status_prong & (1 << 0)) && (abs(dca[0]) < dcatoprimxymin_2prong_ptdep || abs(dca[0]) > dcatoprimxymax_2prong)) { + if ((status_prong & (1 << 0)) && !isSelectedTrack(track, dca, Cand2Prong)) { status_prong = status_prong & ~(1 << 0); } - if ((status_prong & (1 << 1)) && (abs(dca[0]) < dcatoprimxymin_3prong_ptdep || abs(dca[0]) > dcatoprimxymax_3prong)) { + if ((status_prong & (1 << 1)) && !isSelectedTrack(track, dca, Cand3Prong)) { status_prong = status_prong & ~(1 << 1); } } From 6c1a19ba6b5ac898eff86e4e3c97606e1350287a Mon Sep 17 00:00:00 2001 From: shahoian Date: Wed, 14 Apr 2021 09:48:53 +0200 Subject: [PATCH 130/770] CTP: digitizer should always send output, even if empty --- Steer/DigitizerWorkflow/src/CTPDigitizerSpec.cxx | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Steer/DigitizerWorkflow/src/CTPDigitizerSpec.cxx b/Steer/DigitizerWorkflow/src/CTPDigitizerSpec.cxx index 198e7cc074810..38e36e91a35ee 100644 --- a/Steer/DigitizerWorkflow/src/CTPDigitizerSpec.cxx +++ b/Steer/DigitizerWorkflow/src/CTPDigitizerSpec.cxx @@ -50,10 +50,6 @@ class CTPDPLDigitizerTask : public o2::base::BaseDPLDigitizer auto ft0inputs = pc.inputs().get>("ft0"); auto fv0inputs = pc.inputs().get>("fv0"); - // if there is nothing to do ... return - if ((ft0inputs.size() == 0) && (fv0inputs.size() == 0)) { - return; - } std::vector finputs; TStopwatch timer; timer.Start(); From bba047fcdef544a2bbf8ff6314d8bc041bbf3424 Mon Sep 17 00:00:00 2001 From: ddobrigk Date: Wed, 14 Apr 2021 09:27:34 -0300 Subject: [PATCH 131/770] Update trackextension.cxx (#5928) This adds a boolean configurable to use the MC PV instead of the reco-ed PV. Useful for PV resolution studies. Change has already been discussed with Mario Kruger (thanks a lot!) --- Analysis/Tasks/trackextension.cxx | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Analysis/Tasks/trackextension.cxx b/Analysis/Tasks/trackextension.cxx index 3cb5e87cf6bc4..554764f7e75bf 100644 --- a/Analysis/Tasks/trackextension.cxx +++ b/Analysis/Tasks/trackextension.cxx @@ -31,10 +31,13 @@ using namespace o2::framework::expressions; */ //**************************************************************************************** struct TrackExtensionTask { + Configurable pvMC{"pvMC", false, "option to use mc pv"}; Produces extendedTrackQuantities; - void process(aod::Collision const& collision, aod::FullTracks const& tracks) + //aod::McCollision const& mcCollision + + void process(soa::Join::iterator const& collision, aod::McCollisions const& mcCollisions, aod::FullTracks const& tracks) { for (auto& track : tracks) { @@ -43,7 +46,11 @@ struct TrackExtensionTask { if (track.trackType() == o2::aod::track::TrackTypeEnum::Run2Track && track.itsChi2NCl() != 0.f && track.tpcChi2NCl() != 0.f && std::abs(track.x()) < 10.f) { float magField = 5.0; // in kG (FIXME: get this from CCDB) auto trackPar = getTrackPar(track); - trackPar.propagateParamToDCA({collision.posX(), collision.posY(), collision.posZ()}, magField, &dca); + if (!pvMC) { + trackPar.propagateParamToDCA({collision.posX(), collision.posY(), collision.posZ()}, magField, &dca); + } else { + trackPar.propagateParamToDCA({collision.mcCollision().posX(), collision.mcCollision().posY(), collision.mcCollision().posZ()}, magField, &dca); + } } extendedTrackQuantities(dca[0], dca[1]); From 857bbbc170e595e65a23a09addf9f5394f6d19a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B2=20Jacazio?= Date: Wed, 14 Apr 2021 21:17:00 +0200 Subject: [PATCH 132/770] PID: Move from large tables to split tables (#5915) - Improve handler of TOF parametrization - Add dedicated PID directory for PID tasks - Add TOF beta task with dedicated QA - Move from TOF full table to TOF split tables - Move from TPC full table to TPC split tables - Add QA tasks for split PID tables - The PID split task is the PID default task - Add separate task for the TOF beta --- .../AnalysisDataModel/HFSecondaryVertex.h | 4 +- .../AnalysisDataModel/PID/PIDResponse.h | 42 --- Analysis/DataModel/src/aodDataModelGraph.cxx | 8 +- Analysis/DataModel/src/handleParamTOFReso.cxx | 23 +- Analysis/Tasks/CMakeLists.txt | 36 +-- Analysis/Tasks/PID/CMakeLists.txt | 34 +++ Analysis/Tasks/{ => PID}/pidTOF.cxx | 133 ++++----- Analysis/Tasks/PID/pidTOF_tiny.cxx | 271 ++++++++++++++++++ Analysis/Tasks/PID/pidTOFbeta.cxx | 149 ++++++++++ Analysis/Tasks/{ => PID}/pidTOFqa.cxx | 28 +- Analysis/Tasks/{ => PID}/pidTPC.cxx | 88 ++++-- Analysis/Tasks/{ => PID}/pidTPC_tiny.cxx | 121 +++++++- Analysis/Tasks/PWGDQ/filterPP.cxx | 18 +- Analysis/Tasks/PWGDQ/tableMaker.cxx | 11 +- Analysis/Tasks/PWGLF/NucleiSpectraTask.cxx | 2 +- Analysis/Tasks/PWGLF/spectraTOF.cxx | 6 +- Analysis/Tasks/PWGLF/spectraTPC.cxx | 15 +- .../spectraNucleiProvider.cxx | 5 +- .../spectraNucleiReference.cxx | 2 +- .../SkimmingTutorials/spectraTPCProvider.cxx | 6 +- .../SkimmingTutorials/spectraTPCReference.cxx | 6 +- Analysis/Tasks/pidTOF_split.cxx | 126 -------- Analysis/Tasks/pidTOF_tiny.cxx | 134 --------- Analysis/Tasks/pidTPC_split.cxx | 127 -------- 24 files changed, 811 insertions(+), 584 deletions(-) create mode 100644 Analysis/Tasks/PID/CMakeLists.txt rename Analysis/Tasks/{ => PID}/pidTOF.cxx (66%) create mode 100644 Analysis/Tasks/PID/pidTOF_tiny.cxx create mode 100644 Analysis/Tasks/PID/pidTOFbeta.cxx rename Analysis/Tasks/{ => PID}/pidTOFqa.cxx (85%) rename Analysis/Tasks/{ => PID}/pidTPC.cxx (70%) rename Analysis/Tasks/{ => PID}/pidTPC_tiny.cxx (56%) delete mode 100644 Analysis/Tasks/pidTOF_split.cxx delete mode 100644 Analysis/Tasks/pidTOF_tiny.cxx delete mode 100644 Analysis/Tasks/pidTPC_split.cxx diff --git a/Analysis/DataModel/include/AnalysisDataModel/HFSecondaryVertex.h b/Analysis/DataModel/include/AnalysisDataModel/HFSecondaryVertex.h index b897517fc465a..8c62fd41b43ba 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/HFSecondaryVertex.h +++ b/Analysis/DataModel/include/AnalysisDataModel/HFSecondaryVertex.h @@ -37,7 +37,9 @@ DECLARE_SOA_TABLE(HFSelTrack, "AOD", "HFSELTRACK", using BigTracks = soa::Join; using BigTracksMC = soa::Join; -using BigTracksPID = soa::Join; +using BigTracksPID = soa::Join; // FIXME: this is a workaround until we get the index columns to work with joins. diff --git a/Analysis/DataModel/include/AnalysisDataModel/PID/PIDResponse.h b/Analysis/DataModel/include/AnalysisDataModel/PID/PIDResponse.h index f38900bf98176..bc62d12557790 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/PID/PIDResponse.h +++ b/Analysis/DataModel/include/AnalysisDataModel/PID/PIDResponse.h @@ -114,27 +114,6 @@ DECLARE_SOA_TABLE(pidRespTOFbeta, "AOD", "pidRespTOFbeta", pidtofbeta::SeparationBetaEl, pidtofbeta::DiffBetaEl); -// Table with the full information for all particles -DECLARE_SOA_TABLE(pidRespTOF, "AOD", "pidRespTOF", - // Expected signals - pidtof::TOFExpSignalDiffEl, - pidtof::TOFExpSignalDiffMu, - pidtof::TOFExpSignalDiffPi, - pidtof::TOFExpSignalDiffKa, - pidtof::TOFExpSignalDiffPr, - pidtof::TOFExpSignalDiffDe, - pidtof::TOFExpSignalDiffTr, - pidtof::TOFExpSignalDiffHe, - pidtof::TOFExpSignalDiffAl, - // Expected sigma - pidtof::TOFExpSigmaEl, pidtof::TOFExpSigmaMu, pidtof::TOFExpSigmaPi, - pidtof::TOFExpSigmaKa, pidtof::TOFExpSigmaPr, pidtof::TOFExpSigmaDe, - pidtof::TOFExpSigmaTr, pidtof::TOFExpSigmaHe, pidtof::TOFExpSigmaAl, - // NSigma - pidtof::TOFNSigmaEl, pidtof::TOFNSigmaMu, pidtof::TOFNSigmaPi, - pidtof::TOFNSigmaKa, pidtof::TOFNSigmaPr, pidtof::TOFNSigmaDe, - pidtof::TOFNSigmaTr, pidtof::TOFNSigmaHe, pidtof::TOFNSigmaAl); - // Per particle tables DECLARE_SOA_TABLE(pidRespTOFEl, "AOD", "pidRespTOFEl", pidtof::TOFExpSignalDiffEl, pidtof::TOFExpSigmaEl, pidtof::TOFNSigmaEl); DECLARE_SOA_TABLE(pidRespTOFMu, "AOD", "pidRespTOFMu", pidtof::TOFExpSignalDiffMu, pidtof::TOFExpSigmaMu, pidtof::TOFNSigmaMu); @@ -223,27 +202,6 @@ DEFINE_UNWRAP_NSIGMA_COLUMN(TPCNSigmaAl, tpcNSigmaAl); } // namespace pidtpc_tiny -// Table with the full information for all particles -DECLARE_SOA_TABLE(pidRespTPC, "AOD", "pidRespTPC", - // Expected signals - pidtpc::TPCExpSignalDiffEl, - pidtpc::TPCExpSignalDiffMu, - pidtpc::TPCExpSignalDiffPi, - pidtpc::TPCExpSignalDiffKa, - pidtpc::TPCExpSignalDiffPr, - pidtpc::TPCExpSignalDiffDe, - pidtpc::TPCExpSignalDiffTr, - pidtpc::TPCExpSignalDiffHe, - pidtpc::TPCExpSignalDiffAl, - // Expected sigma - pidtpc::TPCExpSigmaEl, pidtpc::TPCExpSigmaMu, pidtpc::TPCExpSigmaPi, - pidtpc::TPCExpSigmaKa, pidtpc::TPCExpSigmaPr, pidtpc::TPCExpSigmaDe, - pidtpc::TPCExpSigmaTr, pidtpc::TPCExpSigmaHe, pidtpc::TPCExpSigmaAl, - // NSigma - pidtpc::TPCNSigmaEl, pidtpc::TPCNSigmaMu, pidtpc::TPCNSigmaPi, - pidtpc::TPCNSigmaKa, pidtpc::TPCNSigmaPr, pidtpc::TPCNSigmaDe, - pidtpc::TPCNSigmaTr, pidtpc::TPCNSigmaHe, pidtpc::TPCNSigmaAl); - // Per particle tables DECLARE_SOA_TABLE(pidRespTPCEl, "AOD", "pidRespTPCEl", pidtpc::TPCExpSignalDiffEl, pidtpc::TPCExpSigmaEl, pidtpc::TPCNSigmaEl); DECLARE_SOA_TABLE(pidRespTPCMu, "AOD", "pidRespTPCMu", pidtpc::TPCExpSignalDiffMu, pidtpc::TPCExpSigmaMu, pidtpc::TPCNSigmaMu); diff --git a/Analysis/DataModel/src/aodDataModelGraph.cxx b/Analysis/DataModel/src/aodDataModelGraph.cxx index e6c94e7afa1a0..d61a2bc38c5ac 100644 --- a/Analysis/DataModel/src/aodDataModelGraph.cxx +++ b/Analysis/DataModel/src/aodDataModelGraph.cxx @@ -258,7 +258,13 @@ int main(int, char**) displayEntity(); displayEntity(); - displayEntities(); + displayEntities(); displayEntity(); displayEntity(); diff --git a/Analysis/DataModel/src/handleParamTOFReso.cxx b/Analysis/DataModel/src/handleParamTOFReso.cxx index 2d6c62f72f3f8..75441a1ec662a 100644 --- a/Analysis/DataModel/src/handleParamTOFReso.cxx +++ b/Analysis/DataModel/src/handleParamTOFReso.cxx @@ -32,7 +32,12 @@ bool initOptionsAndParse(bpo::options_description& options, int argc, char* argv "stop,S", bpo::value()->default_value(4108971600000), "Stop timestamp of object validity")( "delete_previous,d", bpo::value()->default_value(0), "Flag to delete previous versions of converter objects in the CCDB before uploading the new one so as to avoid proliferation on CCDB")( "file,f", bpo::value()->default_value(""), "Option to save parametrization to file instead of uploading to ccdb")( - "mode,m", bpo::value()->default_value(0), "Working mode: 0 push 1 pull and test")( + "mode,m", bpo::value()->default_value(1), "Working mode: 0 push 1 pull and test")( + "p0", bpo::value()->default_value(0.008f), "Parameter 0 of the TOF resolution")( + "p1", bpo::value()->default_value(0.008f), "Parameter 1 of the TOF resolution")( + "p2", bpo::value()->default_value(0.002f), "Parameter 2 of the TOF resolution")( + "p3", bpo::value()->default_value(40.0f), "Parameter 3 of the TOF resolution")( + "p4", bpo::value()->default_value(60.0f), "Parameter 4 of the TOF resolution: average TOF resolution")( "verbose,v", bpo::value()->default_value(0), "Verbose level 0, 1")( "help,h", "Produce help message."); try { @@ -74,16 +79,24 @@ int main(int argc, char* argv[]) return 1; } if (mode == 0) { // Push mode - const std::vector resoparams = {0.008, 0.008, 0.002, 40.0, 60.f}; + LOG(INFO) << "Handling TOF resolution parametrization in create mode"; + const std::vector resoparams = {vm["p0"].as(), vm["p1"].as(), vm["p2"].as(), vm["p3"].as(), vm["p4"].as()}; TOFReso reso; reso.SetParameters(resoparams); + reso.PrintParametrization(); + const float x[4] = {1, 1, 1, 1}; // mom, time, ev. reso, mass + LOG(INFO) << "TOF expected resolution at p=" << x[0] << " GeV/c " + << " and mass " << x[3] << ":" << reso(x); + const std::string fname = vm["file"].as(); if (!fname.empty()) { // Saving it to file + LOG(INFO) << "Saving parametrization to file " << fname; TFile f(fname.data(), "RECREATE"); reso.Write(); f.ls(); f.Close(); } else { // Saving it to CCDB + LOG(INFO) << "Saving parametrization to CCDB " << path; long start = vm["start"].as(); long stop = vm["stop"].as(); @@ -94,10 +107,12 @@ int main(int argc, char* argv[]) api.storeAsTFileAny(&reso, path + "/TOFReso", metadata, start, stop); } } else { // Pull and test mode - const float x[2] = {1, 1}; + LOG(INFO) << "Handling TOF resolution parametrization in test mode"; + const float x[4] = {1, 1, 1, 1}; // mom, time, ev. reso, mass TOFReso* reso = api.retrieveFromTFileAny(path + "/TOFReso", metadata, -1, headers); reso->PrintParametrization(); - LOG(INFO) << "TOFReso " << reso->operator()(x); + LOG(INFO) << "TOF expected resolution at p=" << x[0] << " GeV/c " + << " and mass " << x[3] << ":" << reso->operator()(x); } return 0; diff --git a/Analysis/Tasks/CMakeLists.txt b/Analysis/Tasks/CMakeLists.txt index 0e7c630d6e52a..970e02bdb2dd0 100644 --- a/Analysis/Tasks/CMakeLists.txt +++ b/Analysis/Tasks/CMakeLists.txt @@ -15,6 +15,7 @@ add_subdirectory(PWGJE) add_subdirectory(PWGLF) add_subdirectory(PWGUD) add_subdirectory(SkimmingTutorials) +add_subdirectory(PID) o2_add_dpl_workflow(trackextension @@ -32,41 +33,6 @@ o2_add_dpl_workflow(trackqa PUBLIC_LINK_LIBRARIES O2::Framework O2::AnalysisDataModel O2::AnalysisCore COMPONENT_NAME Analysis) -o2_add_dpl_workflow(pid-tof - SOURCES pidTOF.cxx - PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore - COMPONENT_NAME Analysis) - -o2_add_dpl_workflow(pid-tof-qa - SOURCES pidTOFqa.cxx - PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore - COMPONENT_NAME Analysis) - -o2_add_dpl_workflow(pid-tof-split - SOURCES pidTOF_split.cxx - PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore - COMPONENT_NAME Analysis) - -o2_add_dpl_workflow(pid-tof-tiny - SOURCES pidTOF_tiny.cxx - PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore - COMPONENT_NAME Analysis) - -o2_add_dpl_workflow(pid-tpc - SOURCES pidTPC.cxx - PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore - COMPONENT_NAME Analysis) - -o2_add_dpl_workflow(pid-tpc-split - SOURCES pidTPC_split.cxx - PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore - COMPONENT_NAME Analysis) - -o2_add_dpl_workflow(pid-tpc-tiny - SOURCES pidTPC_tiny.cxx - PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore - COMPONENT_NAME Analysis) - o2_add_dpl_workflow(validation SOURCES validation.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase diff --git a/Analysis/Tasks/PID/CMakeLists.txt b/Analysis/Tasks/PID/CMakeLists.txt new file mode 100644 index 0000000000000..86725c40682d9 --- /dev/null +++ b/Analysis/Tasks/PID/CMakeLists.txt @@ -0,0 +1,34 @@ +# Copyright CERN and copyright holders of ALICE O2. This software is distributed +# under the terms of the GNU General Public License v3 (GPL Version 3), copied +# verbatim in the file "COPYING". +# +# See http://alice-o2.web.cern.ch/license for full licensing information. +# +# In applying this license CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization or +# submit itself to any jurisdiction. + +o2_add_dpl_workflow(pid-tof + SOURCES pidTOF.cxx + PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore + COMPONENT_NAME Analysis) + +o2_add_dpl_workflow(pid-tof-beta + SOURCES pidTOFbeta.cxx + PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore + COMPONENT_NAME Analysis) + +o2_add_dpl_workflow(pid-tof-tiny + SOURCES pidTOF_tiny.cxx + PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore + COMPONENT_NAME Analysis) + +o2_add_dpl_workflow(pid-tpc + SOURCES pidTPC.cxx + PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore + COMPONENT_NAME Analysis) + +o2_add_dpl_workflow(pid-tpc-tiny + SOURCES pidTPC_tiny.cxx + PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore + COMPONENT_NAME Analysis) diff --git a/Analysis/Tasks/pidTOF.cxx b/Analysis/Tasks/PID/pidTOF.cxx similarity index 66% rename from Analysis/Tasks/pidTOF.cxx rename to Analysis/Tasks/PID/pidTOF.cxx index e461003cc94ad..2246921408457 100644 --- a/Analysis/Tasks/pidTOF.cxx +++ b/Analysis/Tasks/PID/pidTOF.cxx @@ -8,15 +8,21 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +/// +/// \file pidTOF_split.cxx +/// \author Nicolo' Jacazio +/// \brief Task to produce PID tables for TOF split for each particle. +/// Only the tables for the mass hypotheses requested are filled, the others are sent empty. +/// + // O2 includes #include "Framework/AnalysisTask.h" -#include "Framework/AnalysisDataModel.h" -#include "Framework/ASoAHelpers.h" #include "Framework/HistogramRegistry.h" #include "ReconstructionDataFormats/Track.h" #include #include "AnalysisDataModel/PID/PIDResponse.h" #include "AnalysisDataModel/PID/PIDTOF.h" +#include "AnalysisDataModel/TrackSelectionTables.h" using namespace o2; using namespace o2::framework; @@ -26,24 +32,42 @@ using namespace o2::track; void customize(std::vector& workflowOptions) { - std::vector options{ - {"add-qa", VariantType::Int, 0, {"Produce TOF PID QA histograms"}}, - {"add-beta", VariantType::Int, 1, {"Produce TOF Beta table"}}}; + std::vector options{{"add-qa", VariantType::Int, 0, {"Produce TOF PID QA histograms"}}}; std::swap(workflowOptions, options); } #include "Framework/runDataProcessing.h" -struct pidTOFTask { - using Trks = soa::Join; +struct pidTOFTaskSplit { + using Trks = soa::Join; using Coll = aod::Collisions; - Produces tablePID; + // Tables to produce + Produces tablePIDEl; + Produces tablePIDMu; + Produces tablePIDPi; + Produces tablePIDKa; + Produces tablePIDPr; + Produces tablePIDDe; + Produces tablePIDTr; + Produces tablePIDHe; + Produces tablePIDAl; + // Detector response and input parameters DetectorResponse response; Service ccdb; Configurable paramfile{"param-file", "", "Path to the parametrization object, if emtpy the parametrization is not taken from file"}; Configurable sigmaname{"param-sigma", "TOFReso", "Name of the parametrization for the expected sigma, used in both file and CCDB mode"}; Configurable url{"ccdb-url", "http://ccdb-test.cern.ch:8080", "url of the ccdb repository"}; Configurable timestamp{"ccdb-timestamp", -1, "timestamp of the object"}; + // Configuration flags to include and exclude particle hypotheses + Configurable pidEl{"pid-el", 0, {"Produce PID information for the Electron mass hypothesis"}}; + Configurable pidMu{"pid-mu", 0, {"Produce PID information for the Muon mass hypothesis"}}; + Configurable pidPi{"pid-pi", 0, {"Produce PID information for the Pion mass hypothesis"}}; + Configurable pidKa{"pid-ka", 0, {"Produce PID information for the Kaon mass hypothesis"}}; + Configurable pidPr{"pid-pr", 0, {"Produce PID information for the Proton mass hypothesis"}}; + Configurable pidDe{"pid-de", 0, {"Produce PID information for the Deuterons mass hypothesis"}}; + Configurable pidTr{"pid-tr", 0, {"Produce PID information for the Triton mass hypothesis"}}; + Configurable pidHe{"pid-he", 0, {"Produce PID information for the Helium3 mass hypothesis"}}; + Configurable pidAl{"pid-al", 0, {"Produce PID information for the Alpha mass hypothesis"}}; void init(o2::framework::InitContext&) { @@ -79,52 +103,26 @@ struct pidTOFTask { constexpr auto responseHe = ResponseImplementation(); constexpr auto responseAl = ResponseImplementation(); - tablePID.reserve(tracks.size()); - for (auto const& trk : tracks) { - tablePID(responseEl.GetExpectedSigma(response, trk.collision(), trk), - responseMu.GetExpectedSigma(response, trk.collision(), trk), - responsePi.GetExpectedSigma(response, trk.collision(), trk), - responseKa.GetExpectedSigma(response, trk.collision(), trk), - responsePr.GetExpectedSigma(response, trk.collision(), trk), - responseDe.GetExpectedSigma(response, trk.collision(), trk), - responseTr.GetExpectedSigma(response, trk.collision(), trk), - responseHe.GetExpectedSigma(response, trk.collision(), trk), - responseAl.GetExpectedSigma(response, trk.collision(), trk), - responseEl.GetSeparation(response, trk.collision(), trk), - responseMu.GetSeparation(response, trk.collision(), trk), - responsePi.GetSeparation(response, trk.collision(), trk), - responseKa.GetSeparation(response, trk.collision(), trk), - responsePr.GetSeparation(response, trk.collision(), trk), - responseDe.GetSeparation(response, trk.collision(), trk), - responseTr.GetSeparation(response, trk.collision(), trk), - responseHe.GetSeparation(response, trk.collision(), trk), - responseAl.GetSeparation(response, trk.collision(), trk)); - } - } -}; - -struct pidTOFTaskBeta { - using Trks = soa::Join; - using Coll = aod::Collision; - Produces tablePIDBeta; - tof::Beta responseElectron; - Configurable expreso{"tof-expreso", 80, "Expected resolution for the computation of the expected beta"}; - - void init(o2::framework::InitContext&) - { - responseElectron.mExpectedResolution = expreso.value; - } - - void process(Coll const& collision, Trks const& tracks) - { - tablePIDBeta.reserve(tracks.size()); - for (auto const& trk : tracks) { - tablePIDBeta(responseElectron.GetBeta(collision, trk), - responseElectron.GetExpectedSigma(collision, trk), - responseElectron.GetExpectedSignal(collision, trk), - responseElectron.GetExpectedSigma(collision, trk), - responseElectron.GetSeparation(collision, trk)); - } + // Check and fill enabled tables + auto makeTable = [&tracks](const Configurable& flag, auto& table, const DetectorResponse& response, const auto& responsePID) { + if (flag.value) { + // Prepare memory for enabled tables + table.reserve(tracks.size()); + for (auto const& trk : tracks) { // Loop on Tracks + table(responsePID.GetExpectedSigma(response, trk.collision(), trk), + responsePID.GetSeparation(response, trk.collision(), trk)); + } + } + }; + makeTable(pidEl, tablePIDEl, response, responseEl); + makeTable(pidMu, tablePIDMu, response, responseMu); + makeTable(pidPi, tablePIDPi, response, responsePi); + makeTable(pidKa, tablePIDKa, response, responseKa); + makeTable(pidPr, tablePIDPr, response, responsePr); + makeTable(pidDe, tablePIDDe, response, responseDe); + makeTable(pidTr, tablePIDTr, response, responseTr); + makeTable(pidHe, tablePIDHe, response, responseHe); + makeTable(pidAl, tablePIDAl, response, responseAl); } }; @@ -189,8 +187,11 @@ struct pidTOFTaskQA { histos.add("event/colltime", ";Collision time (ps);Entries", HistType::kTH1F, {{100, -2000, 2000}}); histos.add("event/tofsignal", ";#it{p} (GeV/#it{c});TOF Signal", HistType::kTH2F, {{nBinsP, MinP, MaxP}, {10000, 0, 2e6}}); makelogaxis(histos.get(HIST("event/tofsignal"))); - histos.add("event/tofbeta", ";#it{p} (GeV/#it{c});TOF #beta", HistType::kTH2F, {{nBinsP, MinP, MaxP}, {1000, 0, 2}}); - makelogaxis(histos.get(HIST("event/tofbeta"))); + histos.add("event/eta", ";#it{#eta};Entries", HistType::kTH1F, {{100, -2, 2}}); + histos.add("event/length", ";Track length (cm);Entries", HistType::kTH1F, {{100, 0, 500}}); + histos.add("event/pt", ";#it{p}_{T} (GeV/#it{c});Entries", HistType::kTH1F, {{nBinsP, MinP, MaxP}}); + histos.add("event/p", ";#it{p} (GeV/#it{c});Entries", HistType::kTH1F, {{nBinsP, MinP, MaxP}}); + histos.add("event/ptreso", ";#it{p} (GeV/#it{c});Entries", HistType::kTH2F, {{nBinsP, MinP, MaxP}, {100, 0, 0.1}}); addParticleHistos<0>(); addParticleHistos<1>(); @@ -211,7 +212,11 @@ struct pidTOFTaskQA { histos.fill(HIST(hnsigma[i]), t.p(), nsigma); } - void process(aod::Collision const& collision, soa::Join const& tracks) + void process(aod::Collision const& collision, soa::Join const& tracks) { const float collisionTime_ps = collision.collisionTime() * 1000.f; histos.fill(HIST("event/vertexz"), collision.posZ()); @@ -227,7 +232,10 @@ struct pidTOFTaskQA { // histos.fill(HIST("event/tofsignal"), t.p(), t.tofSignal()); - histos.fill(HIST("event/tofbeta"), t.p(), t.beta()); + histos.fill(HIST("event/eta"), t.eta()); + histos.fill(HIST("event/length"), t.length()); + histos.fill(HIST("event/pt"), t.pt()); + histos.fill(HIST("event/ptreso"), t.p(), t.sigma1Pt() * t.pt() * t.pt()); // fillParticleHistos<0>(t, tof, t.tofExpSignalDiffEl(), t.tofNSigmaEl()); fillParticleHistos<1>(t, tof, t.tofExpSignalDiffMu(), t.tofNSigmaMu()); @@ -244,13 +252,8 @@ struct pidTOFTaskQA { WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { - auto workflow = WorkflowSpec{adaptAnalysisTask(cfgc, TaskName{"pidTOF-task"})}; - const int add_beta = cfgc.options().get("add-beta"); - const int add_qa = cfgc.options().get("add-qa"); - if (add_beta || add_qa) { - workflow.push_back(adaptAnalysisTask(cfgc, TaskName{"pidTOFBeta-task"})); - } - if (add_qa) { + auto workflow = WorkflowSpec{adaptAnalysisTask(cfgc, TaskName{"pidTOF-split-task"})}; + if (cfgc.options().get("add-qa")) { workflow.push_back(adaptAnalysisTask(cfgc, TaskName{"pidTOFQA-task"})); } return workflow; diff --git a/Analysis/Tasks/PID/pidTOF_tiny.cxx b/Analysis/Tasks/PID/pidTOF_tiny.cxx new file mode 100644 index 0000000000000..c7759445f609e --- /dev/null +++ b/Analysis/Tasks/PID/pidTOF_tiny.cxx @@ -0,0 +1,271 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// +/// \file pidTOF_tiny.cxx +/// \author Nicolo' Jacazio +/// \brief Task to produce PID tables for TOF split for each particle with only the Nsigma information. +/// Only the tables for the mass hypotheses requested are filled, the others are sent empty. +/// + +// O2 includes +#include "Framework/AnalysisTask.h" +#include "Framework/HistogramRegistry.h" +#include "ReconstructionDataFormats/Track.h" +#include +#include "AnalysisDataModel/PID/PIDResponse.h" +#include "AnalysisDataModel/PID/PIDTOF.h" +#include "AnalysisDataModel/TrackSelectionTables.h" + +using namespace o2; +using namespace o2::framework; +using namespace o2::pid; +using namespace o2::framework::expressions; +using namespace o2::track; + +void customize(std::vector& workflowOptions) +{ + std::vector options{{"add-qa", VariantType::Int, 0, {"Produce TOF PID QA histograms"}}}; + std::swap(workflowOptions, options); +} + +#include "Framework/runDataProcessing.h" + +struct pidTOFTaskTiny { + using Trks = soa::Join; + using Coll = aod::Collisions; + // Tables to produce + Produces tablePIDEl; + Produces tablePIDMu; + Produces tablePIDPi; + Produces tablePIDKa; + Produces tablePIDPr; + Produces tablePIDDe; + Produces tablePIDTr; + Produces tablePIDHe; + Produces tablePIDAl; + // Detector response and input parameters + DetectorResponse response; + Service ccdb; + Configurable paramfile{"param-file", "", "Path to the parametrization object, if emtpy the parametrization is not taken from file"}; + Configurable sigmaname{"param-sigma", "TOFReso", "Name of the parametrization for the expected sigma, used in both file and CCDB mode"}; + Configurable url{"ccdb-url", "http://ccdb-test.cern.ch:8080", "url of the ccdb repository"}; + Configurable timestamp{"ccdb-timestamp", -1, "timestamp of the object"}; + // Configuration flags to include and exclude particle hypotheses + Configurable pidEl{"pid-el", 0, {"Produce PID information for the Electron mass hypothesis"}}; + Configurable pidMu{"pid-mu", 0, {"Produce PID information for the Muon mass hypothesis"}}; + Configurable pidPi{"pid-pi", 0, {"Produce PID information for the Pion mass hypothesis"}}; + Configurable pidKa{"pid-ka", 0, {"Produce PID information for the Kaon mass hypothesis"}}; + Configurable pidPr{"pid-pr", 0, {"Produce PID information for the Proton mass hypothesis"}}; + Configurable pidDe{"pid-de", 0, {"Produce PID information for the Deuterons mass hypothesis"}}; + Configurable pidTr{"pid-tr", 0, {"Produce PID information for the Triton mass hypothesis"}}; + Configurable pidHe{"pid-he", 0, {"Produce PID information for the Helium3 mass hypothesis"}}; + Configurable pidAl{"pid-al", 0, {"Produce PID information for the Alpha mass hypothesis"}}; + + void init(o2::framework::InitContext&) + { + ccdb->setURL(url.value); + ccdb->setTimestamp(timestamp.value); + ccdb->setCaching(true); + ccdb->setLocalObjectValidityChecking(); + // Not later than now objects + ccdb->setCreatedNotAfter(std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count()); + // + const std::vector p = {0.008, 0.008, 0.002, 40.0}; + response.SetParameters(DetectorResponse::kSigma, p); + const std::string fname = paramfile.value; + if (!fname.empty()) { // Loading the parametrization from file + response.LoadParamFromFile(fname.data(), sigmaname.value, DetectorResponse::kSigma); + } else { // Loading it from CCDB + const std::string path = "Analysis/PID/TOF"; + response.LoadParam(DetectorResponse::kSigma, ccdb->getForTimeStamp(path + "/" + sigmaname.value, timestamp.value)); + } + } + + template + using ResponseImplementation = tof::ExpTimes; + void process(Coll const& collisions, Trks const& tracks) + { + constexpr auto responseEl = ResponseImplementation(); + constexpr auto responseMu = ResponseImplementation(); + constexpr auto responsePi = ResponseImplementation(); + constexpr auto responseKa = ResponseImplementation(); + constexpr auto responsePr = ResponseImplementation(); + constexpr auto responseDe = ResponseImplementation(); + constexpr auto responseTr = ResponseImplementation(); + constexpr auto responseHe = ResponseImplementation(); + constexpr auto responseAl = ResponseImplementation(); + + // Check and fill enabled tables + auto makeTable = [&tracks](const Configurable& flag, auto& table, const DetectorResponse& response, const auto& responsePID) { + if (flag.value) { + // Prepare memory for enabled tables + table.reserve(tracks.size()); + for (auto const& trk : tracks) { // Loop on Tracks + const float separation = responsePID.GetSeparation(response, trk.collision(), trk); + if (separation <= o2::aod::pidtof_tiny::binned_min) { + table(o2::aod::pidtof_tiny::lower_bin); + } else if (separation >= o2::aod::pidtof_tiny::binned_max) { + table(o2::aod::pidtof_tiny::upper_bin); + } else if (separation >= 0) { + table(separation / o2::aod::pidtof_tiny::bin_width + 0.5f); + } else { + table(separation / o2::aod::pidtof_tiny::bin_width - 0.5f); + } + } + } + }; + makeTable(pidEl, tablePIDEl, response, responseEl); + makeTable(pidMu, tablePIDMu, response, responseMu); + makeTable(pidPi, tablePIDPi, response, responsePi); + makeTable(pidKa, tablePIDKa, response, responseKa); + makeTable(pidPr, tablePIDPr, response, responsePr); + makeTable(pidDe, tablePIDDe, response, responseDe); + makeTable(pidTr, tablePIDTr, response, responseTr); + makeTable(pidHe, tablePIDHe, response, responseHe); + makeTable(pidAl, tablePIDAl, response, responseAl); + } +}; + +struct pidTOFTaskQA { + + static constexpr int Np = 9; + static constexpr const char* pT[Np] = {"e", "#mu", "#pi", "K", "p", "d", "t", "^{3}He", "#alpha"}; + static constexpr std::string_view hexpected[Np] = {"expected/El", "expected/Mu", "expected/Pi", + "expected/Ka", "expected/Pr", "expected/De", + "expected/Tr", "expected/He", "expected/Al"}; + static constexpr std::string_view hexpected_diff[Np] = {"expected_diff/El", "expected_diff/Mu", "expected_diff/Pi", + "expected_diff/Ka", "expected_diff/Pr", "expected_diff/De", + "expected_diff/Tr", "expected_diff/He", "expected_diff/Al"}; + static constexpr std::string_view hnsigma[Np] = {"nsigma/El", "nsigma/Mu", "nsigma/Pi", + "nsigma/Ka", "nsigma/Pr", "nsigma/De", + "nsigma/Tr", "nsigma/He", "nsigma/Al"}; + HistogramRegistry histos{"Histos", {}, OutputObjHandlingPolicy::QAObject}; + + Configurable logAxis{"logAxis", 1, "Flag to use a log momentum axis"}; + Configurable nBinsP{"nBinsP", 400, "Number of bins for the momentum"}; + Configurable MinP{"MinP", 0.1f, "Minimum momentum in range"}; + Configurable MaxP{"MaxP", 5.f, "Maximum momentum in range"}; + Configurable nBinsDelta{"nBinsDelta", 200, "Number of bins for the Delta"}; + Configurable MinDelta{"MinDelta", -1000.f, "Minimum Delta in range"}; + Configurable MaxDelta{"MaxDelta", 1000.f, "Maximum Delta in range"}; + Configurable nBinsNSigma{"nBinsNSigma", 200, "Number of bins for the NSigma"}; + Configurable MinNSigma{"MinNSigma", -10.f, "Minimum NSigma in range"}; + Configurable MaxNSigma{"MaxNSigma", 10.f, "Maximum NSigma in range"}; + + template + void makelogaxis(T h) + { + if (logAxis == 0) { + return; + } + const int nbins = h->GetNbinsX(); + double binp[nbins + 1]; + double max = h->GetXaxis()->GetBinUpEdge(nbins); + double min = h->GetXaxis()->GetBinLowEdge(1); + if (min <= 0) { + min = 0.00001; + } + double lmin = TMath::Log10(min); + double ldelta = (TMath::Log10(max) - lmin) / ((double)nbins); + for (int i = 0; i < nbins; i++) { + binp[i] = TMath::Exp(TMath::Log(10) * (lmin + i * ldelta)); + } + binp[nbins] = max + 1; + h->GetXaxis()->Set(nbins, binp); + } + + template + void addParticleHistos() + { + // NSigma + histos.add(hnsigma[i].data(), Form(";#it{p} (GeV/#it{c});N_{#sigma}^{TOF}(%s)", pT[i]), HistType::kTH2F, {{nBinsP, MinP, MaxP}, {nBinsNSigma, MinNSigma, MaxNSigma}}); + makelogaxis(histos.get(HIST(hnsigma[i]))); + } + + void init(o2::framework::InitContext&) + { + // Event properties + histos.add("event/vertexz", ";Vtx_{z} (cm);Entries", HistType::kTH1F, {{100, -20, 20}}); + histos.add("event/colltime", ";Collision time (ps);Entries", HistType::kTH1F, {{100, -2000, 2000}}); + histos.add("event/tofsignal", ";#it{p} (GeV/#it{c});TOF Signal", HistType::kTH2F, {{nBinsP, MinP, MaxP}, {10000, 0, 2e6}}); + makelogaxis(histos.get(HIST("event/tofsignal"))); + histos.add("event/eta", ";#it{#eta};Entries", HistType::kTH1F, {{100, -2, 2}}); + histos.add("event/length", ";Track length (cm);Entries", HistType::kTH1F, {{100, 0, 500}}); + histos.add("event/pt", ";#it{p}_{T} (GeV/#it{c});Entries", HistType::kTH1F, {{nBinsP, MinP, MaxP}}); + histos.add("event/p", ";#it{p} (GeV/#it{c});Entries", HistType::kTH1F, {{nBinsP, MinP, MaxP}}); + histos.add("event/ptreso", ";#it{p} (GeV/#it{c});Entries", HistType::kTH2F, {{nBinsP, MinP, MaxP}, {100, 0, 0.1}}); + + addParticleHistos<0>(); + addParticleHistos<1>(); + addParticleHistos<2>(); + addParticleHistos<3>(); + addParticleHistos<4>(); + addParticleHistos<5>(); + addParticleHistos<6>(); + addParticleHistos<7>(); + addParticleHistos<8>(); + } + + template + void fillParticleHistos(const T& t, const float nsigma) + { + histos.fill(HIST(hnsigma[i]), t.p(), nsigma); + } + + void process(aod::Collision const& collision, soa::Join const& tracks) + { + const float collisionTime_ps = collision.collisionTime() * 1000.f; + histos.fill(HIST("event/vertexz"), collision.posZ()); + histos.fill(HIST("event/colltime"), collisionTime_ps); + + for (auto t : tracks) { + // + if (t.tofSignal() < 0) { // Skipping tracks without TOF + continue; + } + if (!t.isGlobalTrack()) { + continue; + } + + const float tof = t.tofSignal() - collisionTime_ps; + + // + histos.fill(HIST("event/tofsignal"), t.p(), t.tofSignal()); + histos.fill(HIST("event/eta"), t.eta()); + histos.fill(HIST("event/length"), t.length()); + histos.fill(HIST("event/pt"), t.pt()); + histos.fill(HIST("event/ptreso"), t.p(), t.sigma1Pt() * t.pt() * t.pt()); + // + fillParticleHistos<0>(t, t.tofNSigmaEl()); + fillParticleHistos<1>(t, t.tofNSigmaMu()); + fillParticleHistos<2>(t, t.tofNSigmaPi()); + fillParticleHistos<3>(t, t.tofNSigmaKa()); + fillParticleHistos<4>(t, t.tofNSigmaPr()); + fillParticleHistos<5>(t, t.tofNSigmaDe()); + fillParticleHistos<6>(t, t.tofNSigmaTr()); + fillParticleHistos<7>(t, t.tofNSigmaHe()); + fillParticleHistos<8>(t, t.tofNSigmaAl()); + } + } +}; + +WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) +{ + auto workflow = WorkflowSpec{adaptAnalysisTask(cfgc, TaskName{"pidTOF-tiny-task"})}; + if (cfgc.options().get("add-qa")) { + workflow.push_back(adaptAnalysisTask(cfgc, TaskName{"pidTOFQA-task"})); + } + return workflow; +} \ No newline at end of file diff --git a/Analysis/Tasks/PID/pidTOFbeta.cxx b/Analysis/Tasks/PID/pidTOFbeta.cxx new file mode 100644 index 0000000000000..6e84f4ab1b074 --- /dev/null +++ b/Analysis/Tasks/PID/pidTOFbeta.cxx @@ -0,0 +1,149 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +// O2 includes +#include "Framework/AnalysisTask.h" +#include "Framework/HistogramRegistry.h" +#include "AnalysisDataModel/TrackSelectionTables.h" +#include "AnalysisDataModel/PID/PIDResponse.h" +#include "AnalysisDataModel/PID/PIDTOF.h" + +using namespace o2; +using namespace o2::pid; +using namespace o2::track; +using namespace o2::framework; +using namespace o2::framework::expressions; + +void customize(std::vector& workflowOptions) +{ + std::vector options{{"add-qa", VariantType::Int, 0, {"Produce TOF PID QA histograms"}}}; + std::swap(workflowOptions, options); +} + +#include "Framework/runDataProcessing.h" + +struct pidTOFTaskBeta { + using Trks = soa::Join; + using Coll = aod::Collision; + Produces tablePIDBeta; + tof::Beta responseElectron; + Configurable expreso{"tof-expreso", 80, "Expected resolution for the computation of the expected beta"}; + + void init(o2::framework::InitContext&) + { + responseElectron.mExpectedResolution = expreso.value; + } + + void process(Coll const& collision, Trks const& tracks) + { + tablePIDBeta.reserve(tracks.size()); + for (auto const& trk : tracks) { + tablePIDBeta(responseElectron.GetBeta(collision, trk), + responseElectron.GetExpectedSigma(collision, trk), + responseElectron.GetExpectedSignal(collision, trk), + responseElectron.GetExpectedSigma(collision, trk), + responseElectron.GetSeparation(collision, trk)); + } + } +}; + +struct pidTOFTaskQABeta { + + static constexpr int Np = 9; + static constexpr const char* pT[Np] = {"e", "#mu", "#pi", "K", "p", "d", "t", "^{3}He", "#alpha"}; + static constexpr std::string_view hexpected[Np] = {"expected/El", "expected/Mu", "expected/Pi", + "expected/Ka", "expected/Pr", "expected/De", + "expected/Tr", "expected/He", "expected/Al"}; + static constexpr std::string_view hexpected_diff[Np] = {"expected_diff/El", "expected_diff/Mu", "expected_diff/Pi", + "expected_diff/Ka", "expected_diff/Pr", "expected_diff/De", + "expected_diff/Tr", "expected_diff/He", "expected_diff/Al"}; + static constexpr std::string_view hnsigma[Np] = {"nsigma/El", "nsigma/Mu", "nsigma/Pi", + "nsigma/Ka", "nsigma/Pr", "nsigma/De", + "nsigma/Tr", "nsigma/He", "nsigma/Al"}; + HistogramRegistry histos{"Histos", {}, OutputObjHandlingPolicy::QAObject}; + + Configurable logAxis{"logAxis", 1, "Flag to use a log momentum axis"}; + Configurable nBinsP{"nBinsP", 400, "Number of bins for the momentum"}; + Configurable MinP{"MinP", 0.1f, "Minimum momentum in range"}; + Configurable MaxP{"MaxP", 5.f, "Maximum momentum in range"}; + Configurable nBinsDelta{"nBinsDelta", 200, "Number of bins for the Delta"}; + Configurable MinDelta{"MinDelta", -1000.f, "Minimum Delta in range"}; + Configurable MaxDelta{"MaxDelta", 1000.f, "Maximum Delta in range"}; + Configurable nBinsNSigma{"nBinsNSigma", 200, "Number of bins for the NSigma"}; + Configurable MinNSigma{"MinNSigma", -10.f, "Minimum NSigma in range"}; + Configurable MaxNSigma{"MaxNSigma", 10.f, "Maximum NSigma in range"}; + + template + void makelogaxis(T h) + { + if (logAxis == 0) { + return; + } + const int nbins = h->GetNbinsX(); + double binp[nbins + 1]; + double max = h->GetXaxis()->GetBinUpEdge(nbins); + double min = h->GetXaxis()->GetBinLowEdge(1); + if (min <= 0) { + min = 0.00001; + } + double lmin = TMath::Log10(min); + double ldelta = (TMath::Log10(max) - lmin) / ((double)nbins); + for (int i = 0; i < nbins; i++) { + binp[i] = TMath::Exp(TMath::Log(10) * (lmin + i * ldelta)); + } + binp[nbins] = max + 1; + h->GetXaxis()->Set(nbins, binp); + } + + void init(o2::framework::InitContext&) + { + // Event properties + histos.add("event/vertexz", ";Vtx_{z} (cm);Entries", HistType::kTH1F, {{100, -20, 20}}); + histos.add("event/colltime", ";Collision time (ps);Entries", HistType::kTH1F, {{100, -2000, 2000}}); + histos.add("event/tofsignal", ";#it{p} (GeV/#it{c});TOF Signal", HistType::kTH2F, {{nBinsP, MinP, MaxP}, {10000, 0, 2e6}}); + makelogaxis(histos.get(HIST("event/tofsignal"))); + histos.add("event/tofbeta", ";#it{p} (GeV/#it{c});TOF #beta", HistType::kTH2F, {{nBinsP, MinP, MaxP}, {1000, 0, 2}}); + makelogaxis(histos.get(HIST("event/tofbeta"))); + histos.add("event/eta", ";#it{#eta};Entries", HistType::kTH1F, {{100, -2, 2}}); + histos.add("event/length", ";Track length (cm);Entries", HistType::kTH1F, {{100, 0, 500}}); + histos.add("event/pt", ";#it{p}_{T} (GeV/#it{c});Entries", HistType::kTH1F, {{nBinsP, MinP, MaxP}}); + histos.add("event/p", ";#it{p} (GeV/#it{c});Entries", HistType::kTH1F, {{nBinsP, MinP, MaxP}}); + histos.add("event/ptreso", ";#it{p} (GeV/#it{c});Entries", HistType::kTH2F, {{nBinsP, MinP, MaxP}, {100, 0, 0.1}}); + } + + template + void fillParticleHistos(const T& t, const float tof, const float exp_diff, const float nsigma) + { + histos.fill(HIST(hexpected[i]), t.p(), tof - exp_diff); + histos.fill(HIST(hexpected_diff[i]), t.p(), exp_diff); + histos.fill(HIST(hnsigma[i]), t.p(), nsigma); + } + + void process(soa::Join::iterator const& track) + { + // + if (track.tofSignal() < 0) { // Skipping tracks without TOF + return; + } + if (!track.isGlobalTrack()) { + return; + } + histos.fill(HIST("event/tofbeta"), track.p(), track.beta()); + } +}; + +WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) +{ + auto workflow = WorkflowSpec{adaptAnalysisTask(cfgc)}; + if (cfgc.options().get("add-qa")) { + workflow.push_back(adaptAnalysisTask(cfgc, TaskName{"pidTOFQA-task"})); + } + return workflow; +} diff --git a/Analysis/Tasks/pidTOFqa.cxx b/Analysis/Tasks/PID/pidTOFqa.cxx similarity index 85% rename from Analysis/Tasks/pidTOFqa.cxx rename to Analysis/Tasks/PID/pidTOFqa.cxx index 570fffe4f2389..b0335451b47c9 100644 --- a/Analysis/Tasks/pidTOFqa.cxx +++ b/Analysis/Tasks/PID/pidTOFqa.cxx @@ -28,8 +28,8 @@ using namespace o2::track; void customize(std::vector& workflowOptions) { std::vector options{ - {"pid-el", VariantType::Int, 1, {"Produce PID information for the electron mass hypothesis"}}, - {"pid-mu", VariantType::Int, 1, {"Produce PID information for the muon mass hypothesis"}}, + {"pid-el", VariantType::Int, 0, {"Produce PID information for the electron mass hypothesis"}}, + {"pid-mu", VariantType::Int, 0, {"Produce PID information for the muon mass hypothesis"}}, {"pid-pikapr", VariantType::Int, 1, {"Produce PID information for the Pion, Kaon, Proton mass hypothesis"}}, {"pid-nuclei", VariantType::Int, 0, {"Produce PID information for the Deuteron, Triton, Alpha mass hypothesis"}}}; std::swap(workflowOptions, options); @@ -66,6 +66,8 @@ struct pidTOFTaskQA { Configurable nBinsP{"nBinsP", 400, "Number of bins for the momentum"}; Configurable MinP{"MinP", 0.1, "Minimum momentum in range"}; Configurable MaxP{"MaxP", 5, "Maximum momentum in range"}; + Configurable MinEta{"MinEta", -0.8, "Minimum eta in range"}; + Configurable MaxEta{"MaxEta", 0.8, "Maximum eta in range"}; template void makelogaxis(T h) @@ -100,6 +102,7 @@ struct pidTOFTaskQA { void init(o2::framework::InitContext&) { + histos.add("event/T0", ";Tracks with TOF;T0 (ps);Counts", HistType::kTH2F, {{1000, 0, 100}, {1000, -600, 600}}); histos.add(hnsigma[pid_type].data(), Form(";#it{p}_{T} (GeV/#it{c});N_{#sigma}^{TOF}(%s)", pT[pid_type]), HistType::kTH2F, {{nBinsP, MinP, MaxP}, {2000, -30, 30}}); makelogaxis(histos.get(HIST(hnsigma[pid_type]))); histos.add(hnsigmaprm[pid_type].data(), Form("Primary;#it{p}_{T} (GeV/#it{c});N_{#sigma}^{TOF}(%s)", pT[pid_type]), HistType::kTH2F, {{nBinsP, MinP, MaxP}, {2000, -30, 30}}); @@ -115,6 +118,12 @@ struct pidTOFTaskQA { addParticleHistos<6>(); addParticleHistos<7>(); addParticleHistos<8>(); + histos.add("event/tofbeta", ";#it{p}_{T} (GeV/#it{c});TOF #beta", HistType::kTH2F, {{nBinsP, MinP, MaxP}, {1000, 0, 1.2}}); + makelogaxis(histos.get(HIST("event/tofbeta"))); + histos.add("event/tofbetaPrm", ";#it{p}_{T} (GeV/#it{c});TOF #beta", HistType::kTH2F, {{nBinsP, MinP, MaxP}, {1000, 0, 1.2}}); + makelogaxis(histos.get(HIST("event/tofbetaPrm"))); + histos.add("event/tofbetaSec", ";#it{p}_{T} (GeV/#it{c});TOF #beta", HistType::kTH2F, {{nBinsP, MinP, MaxP}, {1000, 0, 1.2}}); + makelogaxis(histos.get(HIST("event/tofbetaSec"))); } template @@ -132,15 +141,24 @@ struct pidTOFTaskQA { } void process(aod::Collision const& collision, - soa::Join const& tracks, + soa::Join const& tracks, aod::McParticles& mcParticles) { const float collisionTime_ps = collision.collisionTime() * 1000.f; + unsigned int nTracksWithTOF = 0; for (auto t : tracks) { // if (t.tofSignal() < 0) { // Skipping tracks without TOF continue; } + if (t.eta() < MinEta || t.eta() > MaxEta) { + continue; + } + nTracksWithTOF++; float nsigma = -999.f; if constexpr (pid_type == 0) { nsigma = t.tofNSigmaEl(); @@ -164,10 +182,13 @@ struct pidTOFTaskQA { // Fill for all histos.fill(HIST(hnsigma[pid_type]), t.pt(), nsigma); + histos.fill(HIST("event/tofbeta"), t.p(), t.beta()); if (MC::isPhysicalPrimary(mcParticles, t.mcParticle())) { // Selecting primaries histos.fill(HIST(hnsigmaprm[pid_type]), t.pt(), nsigma); + histos.fill(HIST("event/tofbetaPrm"), t.p(), t.beta()); } else { histos.fill(HIST(hnsigmasec[pid_type]), t.pt(), nsigma); + histos.fill(HIST("event/tofbetaSec"), t.p(), t.beta()); } // Fill with PDG codes fillNsigma<0>(t, mcParticles, nsigma); @@ -180,6 +201,7 @@ struct pidTOFTaskQA { fillNsigma<7>(t, mcParticles, nsigma); fillNsigma<8>(t, mcParticles, nsigma); } + histos.fill(HIST("event/T0"), nTracksWithTOF, collisionTime_ps); } }; diff --git a/Analysis/Tasks/pidTPC.cxx b/Analysis/Tasks/PID/pidTPC.cxx similarity index 70% rename from Analysis/Tasks/pidTPC.cxx rename to Analysis/Tasks/PID/pidTPC.cxx index 964c5fd3ca2db..cb4bcc57bb113 100644 --- a/Analysis/Tasks/pidTPC.cxx +++ b/Analysis/Tasks/PID/pidTPC.cxx @@ -8,15 +8,21 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +/// +/// \file pidTPC_split.cxx +/// \author Nicolo' Jacazio +/// \brief Task to produce PID tables for TPC split for each particle. +/// Only the tables for the mass hypotheses requested are filled, the others are sent empty. +/// + // O2 includes #include "Framework/AnalysisTask.h" -#include "Framework/AnalysisDataModel.h" -#include "Framework/ASoAHelpers.h" #include "Framework/HistogramRegistry.h" #include "ReconstructionDataFormats/Track.h" #include #include "AnalysisDataModel/PID/PIDResponse.h" #include "AnalysisDataModel/PID/PIDTPC.h" +#include "AnalysisDataModel/TrackSelectionTables.h" using namespace o2; using namespace o2::framework; @@ -26,17 +32,26 @@ using namespace o2::track; void customize(std::vector& workflowOptions) { - std::vector options{ - {"add-qa", VariantType::Int, 0, {"Produce TPC PID QA histograms"}}}; + std::vector options{{"add-qa", VariantType::Int, 0, {"Produce TPC PID QA histograms"}}}; std::swap(workflowOptions, options); } #include "Framework/runDataProcessing.h" -struct pidTPCTask { +struct pidTPCTaskSplit { using Trks = soa::Join; using Coll = aod::Collisions; - Produces tablePID; + // Tables to produce + Produces tablePIDEl; + Produces tablePIDMu; + Produces tablePIDPi; + Produces tablePIDKa; + Produces tablePIDPr; + Produces tablePIDDe; + Produces tablePIDTr; + Produces tablePIDHe; + Produces tablePIDAl; + // Detector response and input parameters DetectorResponse response; Service ccdb; Configurable paramfile{"param-file", "", "Path to the parametrization object, if emtpy the parametrization is not taken from file"}; @@ -44,6 +59,16 @@ struct pidTPCTask { Configurable sigmaname{"param-sigma", "TPCReso", "Name of the parametrization for the expected sigma, used in both file and CCDB mode"}; Configurable url{"ccdb-url", "http://ccdb-test.cern.ch:8080", "url of the ccdb repository"}; Configurable timestamp{"ccdb-timestamp", -1, "timestamp of the object"}; + // Configuration flags to include and exclude particle hypotheses + Configurable pidEl{"pid-el", 0, {"Produce PID information for the Electron mass hypothesis"}}; + Configurable pidMu{"pid-mu", 0, {"Produce PID information for the Muon mass hypothesis"}}; + Configurable pidPi{"pid-pi", 0, {"Produce PID information for the Pion mass hypothesis"}}; + Configurable pidKa{"pid-ka", 0, {"Produce PID information for the Kaon mass hypothesis"}}; + Configurable pidPr{"pid-pr", 0, {"Produce PID information for the Proton mass hypothesis"}}; + Configurable pidDe{"pid-de", 0, {"Produce PID information for the Deuterons mass hypothesis"}}; + Configurable pidTr{"pid-tr", 0, {"Produce PID information for the Triton mass hypothesis"}}; + Configurable pidHe{"pid-he", 0, {"Produce PID information for the Helium3 mass hypothesis"}}; + Configurable pidAl{"pid-al", 0, {"Produce PID information for the Alpha mass hypothesis"}}; void init(o2::framework::InitContext&) { @@ -79,27 +104,26 @@ struct pidTPCTask { constexpr auto responseHe = ResponseImplementation(); constexpr auto responseAl = ResponseImplementation(); - tablePID.reserve(tracks.size()); - for (auto const& trk : tracks) { - tablePID(responseEl.GetExpectedSigma(response, trk.collision(), trk), - responseMu.GetExpectedSigma(response, trk.collision(), trk), - responsePi.GetExpectedSigma(response, trk.collision(), trk), - responseKa.GetExpectedSigma(response, trk.collision(), trk), - responsePr.GetExpectedSigma(response, trk.collision(), trk), - responseDe.GetExpectedSigma(response, trk.collision(), trk), - responseTr.GetExpectedSigma(response, trk.collision(), trk), - responseHe.GetExpectedSigma(response, trk.collision(), trk), - responseAl.GetExpectedSigma(response, trk.collision(), trk), - responseEl.GetSeparation(response, trk.collision(), trk), - responseMu.GetSeparation(response, trk.collision(), trk), - responsePi.GetSeparation(response, trk.collision(), trk), - responseKa.GetSeparation(response, trk.collision(), trk), - responsePr.GetSeparation(response, trk.collision(), trk), - responseDe.GetSeparation(response, trk.collision(), trk), - responseTr.GetSeparation(response, trk.collision(), trk), - responseHe.GetSeparation(response, trk.collision(), trk), - responseAl.GetSeparation(response, trk.collision(), trk)); - } + // Check and fill enabled tables + auto makeTable = [&tracks](const Configurable& flag, auto& table, const DetectorResponse& response, const auto& responsePID) { + if (flag.value) { + // Prepare memory for enabled tables + table.reserve(tracks.size()); + for (auto const& trk : tracks) { // Loop on Tracks + table(responsePID.GetExpectedSigma(response, trk.collision(), trk), + responsePID.GetSeparation(response, trk.collision(), trk)); + } + } + }; + makeTable(pidEl, tablePIDEl, response, responseEl); + makeTable(pidMu, tablePIDMu, response, responseMu); + makeTable(pidPi, tablePIDPi, response, responsePi); + makeTable(pidKa, tablePIDKa, response, responseKa); + makeTable(pidPr, tablePIDPr, response, responsePr); + makeTable(pidDe, tablePIDDe, response, responseDe); + makeTable(pidTr, tablePIDTr, response, responseTr); + makeTable(pidHe, tablePIDHe, response, responseHe); + makeTable(pidAl, tablePIDAl, response, responseAl); } }; @@ -182,7 +206,11 @@ struct pidTPCTaskQA { histos.fill(HIST(hnsigma[i]), t.p(), nsigma); } - void process(aod::Collision const& collision, soa::Join const& tracks) + void process(aod::Collision const& collision, soa::Join const& tracks) { histos.fill(HIST("event/vertexz"), collision.posZ()); @@ -206,9 +234,9 @@ struct pidTPCTaskQA { WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { - auto workflow = WorkflowSpec{adaptAnalysisTask(cfgc, TaskName{"pidTPC-task"})}; + auto workflow = WorkflowSpec{adaptAnalysisTask(cfgc, TaskName{"pidTPC-split-task"})}; if (cfgc.options().get("add-qa")) { - workflow.push_back(adaptAnalysisTask(cfgc, TaskName{"pidTPCQA-task"})); + workflow.push_back(adaptAnalysisTask(cfgc, TaskName{"pidTOFQA-task"})); } return workflow; } diff --git a/Analysis/Tasks/pidTPC_tiny.cxx b/Analysis/Tasks/PID/pidTPC_tiny.cxx similarity index 56% rename from Analysis/Tasks/pidTPC_tiny.cxx rename to Analysis/Tasks/PID/pidTPC_tiny.cxx index 09328f89f7dfa..0d918702774d2 100644 --- a/Analysis/Tasks/pidTPC_tiny.cxx +++ b/Analysis/Tasks/PID/pidTPC_tiny.cxx @@ -17,14 +17,12 @@ // O2 includes #include "Framework/AnalysisTask.h" -#include "Framework/AnalysisDataModel.h" -#include "Framework/ASoAHelpers.h" #include "Framework/HistogramRegistry.h" -#include "Framework/runDataProcessing.h" #include "ReconstructionDataFormats/Track.h" #include #include "AnalysisDataModel/PID/PIDResponse.h" #include "AnalysisDataModel/PID/PIDTPC.h" +#include "AnalysisDataModel/TrackSelectionTables.h" using namespace o2; using namespace o2::framework; @@ -32,6 +30,14 @@ using namespace o2::pid; using namespace o2::framework::expressions; using namespace o2::track; +void customize(std::vector& workflowOptions) +{ + std::vector options{{"add-qa", VariantType::Int, 0, {"Produce TPC PID QA histograms"}}}; + std::swap(workflowOptions, options); +} + +#include "Framework/runDataProcessing.h" + struct pidTPCTaskTiny { using Trks = soa::Join; using Coll = aod::Collisions; @@ -129,7 +135,114 @@ struct pidTPCTaskTiny { } }; +struct pidTPCTaskQA { + static constexpr int Np = 9; + static constexpr const char* pT[Np] = {"e", "#mu", "#pi", "K", "p", "d", "t", "^{3}He", "#alpha"}; + static constexpr std::string_view hexpected[Np] = {"expected/El", "expected/Mu", "expected/Pi", + "expected/Ka", "expected/Pr", "expected/De", + "expected/Tr", "expected/He", "expected/Al"}; + static constexpr std::string_view hexpected_diff[Np] = {"expected_diff/El", "expected_diff/Mu", "expected_diff/Pi", + "expected_diff/Ka", "expected_diff/Pr", "expected_diff/De", + "expected_diff/Tr", "expected_diff/He", "expected_diff/Al"}; + static constexpr std::string_view hnsigma[Np] = {"nsigma/El", "nsigma/Mu", "nsigma/Pi", + "nsigma/Ka", "nsigma/Pr", "nsigma/De", + "nsigma/Tr", "nsigma/He", "nsigma/Al"}; + HistogramRegistry histos{"Histos", {}, OutputObjHandlingPolicy::QAObject}; + + Configurable nBinsP{"nBinsP", 400, "Number of bins for the momentum"}; + Configurable MinP{"MinP", 0, "Minimum momentum in range"}; + Configurable MaxP{"MaxP", 20, "Maximum momentum in range"}; + + template + void makelogaxis(T h) + { + const int nbins = h->GetNbinsX(); + double binp[nbins + 1]; + double max = h->GetXaxis()->GetBinUpEdge(nbins); + double min = h->GetXaxis()->GetBinLowEdge(1); + if (min <= 0) { + min = 0.00001; + } + double lmin = TMath::Log10(min); + double ldelta = (TMath::Log10(max) - lmin) / ((double)nbins); + for (int i = 0; i < nbins; i++) { + binp[i] = TMath::Exp(TMath::Log(10) * (lmin + i * ldelta)); + } + binp[nbins] = max + 1; + h->GetXaxis()->Set(nbins, binp); + } + + template + void addParticleHistos() + { + // Exp signal + histos.add(hexpected[i].data(), Form(";#it{p} (GeV/#it{c});d#it{E}/d#it{x}_(%s)", pT[i]), kTH2F, {{nBinsP, MinP, MaxP}, {1000, 0, 1000}}); + makelogaxis(histos.get(HIST(hexpected[i]))); + + // Signal - Expected signal + histos.add(hexpected_diff[i].data(), Form(";#it{p} (GeV/#it{c});;d#it{E}/d#it{x} - d#it{E}/d#it{x}(%s)", pT[i]), kTH2F, {{nBinsP, MinP, MaxP}, {1000, -500, 500}}); + makelogaxis(histos.get(HIST(hexpected_diff[i]))); + + // NSigma + histos.add(hnsigma[i].data(), Form(";#it{p} (GeV/#it{c});N_{#sigma}^{TPC}(%s)", pT[i]), kTH2F, {{nBinsP, MinP, MaxP}, {200, -10, 10}}); + makelogaxis(histos.get(HIST(hnsigma[i]))); + } + + void init(o2::framework::InitContext&) + { + // Event properties + histos.add("event/vertexz", ";Vtx_{z} (cm);Entries", kTH1F, {{100, -20, 20}}); + histos.add("event/tpcsignal", ";#it{p} (GeV/#it{c});TPC Signal", kTH2F, {{nBinsP, MinP, MaxP}, {1000, 0, 1000}}); + makelogaxis(histos.get(HIST("event/tpcsignal"))); + + addParticleHistos<0>(); + addParticleHistos<1>(); + addParticleHistos<2>(); + addParticleHistos<3>(); + addParticleHistos<4>(); + addParticleHistos<5>(); + addParticleHistos<6>(); + addParticleHistos<7>(); + addParticleHistos<8>(); + } + + template + void fillParticleHistos(const T& t, const float nsigma) + { + histos.fill(HIST(hnsigma[i]), t.p(), nsigma); + } + + void process(aod::Collision const& collision, soa::Join const& tracks) + { + histos.fill(HIST("event/vertexz"), collision.posZ()); + + for (auto t : tracks) { + // const float mom = t.p(); + const float mom = t.tpcInnerParam(); + histos.fill(HIST("event/tpcsignal"), mom, t.tpcSignal()); + // + fillParticleHistos<0>(t, t.tpcNSigmaEl()); + fillParticleHistos<1>(t, t.tpcNSigmaMu()); + fillParticleHistos<2>(t, t.tpcNSigmaPi()); + fillParticleHistos<3>(t, t.tpcNSigmaKa()); + fillParticleHistos<4>(t, t.tpcNSigmaPr()); + fillParticleHistos<5>(t, t.tpcNSigmaDe()); + fillParticleHistos<6>(t, t.tpcNSigmaTr()); + fillParticleHistos<7>(t, t.tpcNSigmaHe()); + fillParticleHistos<8>(t, t.tpcNSigmaAl()); + } + } +}; + WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { - return WorkflowSpec{adaptAnalysisTask(cfgc, TaskName{"pidTPC-tiny-task"})}; + auto workflow = WorkflowSpec{adaptAnalysisTask(cfgc, TaskName{"pidTPC-tiny-task"})}; + if (cfgc.options().get("add-qa")) { + workflow.push_back(adaptAnalysisTask(cfgc, TaskName{"pidTOFQA-task"})); + } + return workflow; } diff --git a/Analysis/Tasks/PWGDQ/filterPP.cxx b/Analysis/Tasks/PWGDQ/filterPP.cxx index 30121475c50a0..562279300e12e 100644 --- a/Analysis/Tasks/PWGDQ/filterPP.cxx +++ b/Analysis/Tasks/PWGDQ/filterPP.cxx @@ -59,8 +59,22 @@ DECLARE_SOA_TABLE(DQBarrelTrackCuts, "AOD", "DQBARRELCUTS", dqppfilter::IsBarrel using MyEvents = soa::Join; using MyEventsSelected = soa::Join; -using MyBarrelTracks = soa::Join; -using MyBarrelTracksSelected = soa::Join; +using MyBarrelTracks = soa::Join; +using MyBarrelTracksSelected = soa::Join; constexpr static uint32_t gkEventFillMap = VarManager::ObjTypes::BC | VarManager::ObjTypes::Collision; constexpr static uint32_t gkTrackFillMap = VarManager::ObjTypes::Track | VarManager::ObjTypes::TrackExtra | VarManager::ObjTypes::TrackDCA | VarManager::ObjTypes::TrackSelection | VarManager::ObjTypes::TrackCov | VarManager::ObjTypes::TrackPID; diff --git a/Analysis/Tasks/PWGDQ/tableMaker.cxx b/Analysis/Tasks/PWGDQ/tableMaker.cxx index 076041cc47aeb..d429d676f63bc 100644 --- a/Analysis/Tasks/PWGDQ/tableMaker.cxx +++ b/Analysis/Tasks/PWGDQ/tableMaker.cxx @@ -45,7 +45,14 @@ void customize(std::vector& workflowOptions) #include "Framework/runDataProcessing.h" -using MyBarrelTracks = soa::Join; +using MyBarrelTracks = soa::Join; using MyEvents = soa::Join; using MyEventsNoCent = soa::Join; using MyMuons = aod::Muons; @@ -121,7 +128,7 @@ struct TableMaker { fHistMan->SetDefaultVarNames(VarManager::fgVariableNames, VarManager::fgVariableUnits); DefineHistograms("Event_BeforeCuts;Event_AfterCuts;TrackBarrel_BeforeCuts;TrackBarrel_AfterCuts;Muons_BeforeCuts;Muons_AfterCuts;"); // define all histograms - VarManager::SetUseVars(fHistMan->GetUsedVars()); // provide the list of required variables so that VarManager knows what to fill + VarManager::SetUseVars(fHistMan->GetUsedVars()); // provide the list of required variables so that VarManager knows what to fill fOutputList.setObject(fHistMan->GetMainHistogramList()); DefineCuts(); } diff --git a/Analysis/Tasks/PWGLF/NucleiSpectraTask.cxx b/Analysis/Tasks/PWGLF/NucleiSpectraTask.cxx index b64f3728e3593..eac811b6860e9 100644 --- a/Analysis/Tasks/PWGLF/NucleiSpectraTask.cxx +++ b/Analysis/Tasks/PWGLF/NucleiSpectraTask.cxx @@ -61,7 +61,7 @@ struct NucleiSpecraTask { Filter collisionFilter = nabs(aod::collision::posZ) < cfgCutVertex; Filter trackFilter = (nabs(aod::track::eta) < cfgCutEta) && (aod::track::isGlobalTrack == (uint8_t) true); - using TrackCandidates = soa::Filtered>; + using TrackCandidates = soa::Filtered>; void process(soa::Filtered>::iterator const& collision, aod::BCsWithTimestamps const&, TrackCandidates const& tracks) { diff --git a/Analysis/Tasks/PWGLF/spectraTOF.cxx b/Analysis/Tasks/PWGLF/spectraTOF.cxx index b80d0b3f2a1c0..87f0cecb4f666 100644 --- a/Analysis/Tasks/PWGLF/spectraTOF.cxx +++ b/Analysis/Tasks/PWGLF/spectraTOF.cxx @@ -60,7 +60,11 @@ struct TOFSpectraTask { Filter collisionFilter = nabs(aod::collision::posZ) < cfgCutVertex; Filter trackFilter = (nabs(aod::track::eta) < cfgCutEta) && (aod::track::isGlobalTrack == (uint8_t) true) && (aod::track::tofSignal > 0.f); - using TrackCandidates = soa::Filtered>; + using TrackCandidates = soa::Filtered>; void process(TrackCandidates::iterator const& track) { histos.fill(HIST("p/Unselected"), track.p()); diff --git a/Analysis/Tasks/PWGLF/spectraTPC.cxx b/Analysis/Tasks/PWGLF/spectraTPC.cxx index 36d7895ecec52..aaeec55ed0a62 100644 --- a/Analysis/Tasks/PWGLF/spectraTPC.cxx +++ b/Analysis/Tasks/PWGLF/spectraTPC.cxx @@ -87,7 +87,11 @@ struct TPCSpectraTask { histos.fill(HIST(hpt[i]), track.pt()); } - using TrackCandidates = soa::Filtered>; + using TrackCandidates = soa::Filtered>; void process(TrackCandidates::iterator const& track) { histos.fill(HIST("p/Unselected"), track.p()); @@ -136,7 +140,14 @@ struct TPCPIDQASignalwTOFTask { CANDIDATE_SELECTION Filter trackFilterTOF = (aod::track::tofSignal > 0.f); // Skip tracks without TOF - using TrackCandidates = soa::Filtered>; + using TrackCandidates = soa::Filtered>; void process(TrackCandidates::iterator const& track) { // const float mom = track.p(); diff --git a/Analysis/Tasks/SkimmingTutorials/spectraNucleiProvider.cxx b/Analysis/Tasks/SkimmingTutorials/spectraNucleiProvider.cxx index cbc952d6a2ae5..110540c6c9ca9 100644 --- a/Analysis/Tasks/SkimmingTutorials/spectraNucleiProvider.cxx +++ b/Analysis/Tasks/SkimmingTutorials/spectraNucleiProvider.cxx @@ -49,7 +49,10 @@ struct NucleiSpectraProviderTask { Filter collisionFilter = nabs(aod::collision::posZ) < vertexZCut; Filter trackFilter = (nabs(aod::track::eta) < trackEtaCut) && (aod::track::isGlobalTrack == (uint8_t) true) && (aod::track::pt > trackPtCut); - using TrackCandidates = soa::Filtered>; + using TrackCandidates = soa::Filtered>; void process(soa::Filtered>::iterator const& collision, TrackCandidates const& tracks) { bool keepEvent = false; diff --git a/Analysis/Tasks/SkimmingTutorials/spectraNucleiReference.cxx b/Analysis/Tasks/SkimmingTutorials/spectraNucleiReference.cxx index d9468ad435fe8..91aecb68b6c9b 100644 --- a/Analysis/Tasks/SkimmingTutorials/spectraNucleiReference.cxx +++ b/Analysis/Tasks/SkimmingTutorials/spectraNucleiReference.cxx @@ -61,7 +61,7 @@ struct NucleiSpectraReferenceTask { Filter collisionFilter = nabs(aod::collision::posZ) < cfgCutVertex; Filter trackFilter = (nabs(aod::track::eta) < cfgCutEta) && (aod::track::isGlobalTrack == (uint8_t) true); - using TrackCandidates = soa::Filtered>; + using TrackCandidates = soa::Filtered>; void process(soa::Filtered>::iterator const& collision, aod::BCsWithTimestamps const&, TrackCandidates const& tracks) { diff --git a/Analysis/Tasks/SkimmingTutorials/spectraTPCProvider.cxx b/Analysis/Tasks/SkimmingTutorials/spectraTPCProvider.cxx index e36a025998165..c5dd84cd27f48 100644 --- a/Analysis/Tasks/SkimmingTutorials/spectraTPCProvider.cxx +++ b/Analysis/Tasks/SkimmingTutorials/spectraTPCProvider.cxx @@ -88,7 +88,11 @@ struct TPCSpectraProviderTask { Filter collisionFilter = nabs(aod::collision::posZ) < vertexZCut; Filter trackFilter = (nabs(aod::track::eta) < trackEtaCut) && (aod::track::pt > trackPtCut) && (aod::track::isGlobalTrack == (uint8_t) true); - using TrackCandidates = soa::Filtered>; + using TrackCandidates = soa::Filtered>; void process(soa::Filtered>::iterator const& collision, TrackCandidates const& tracks) { if (!collision.alias()[kINT7]) { diff --git a/Analysis/Tasks/SkimmingTutorials/spectraTPCReference.cxx b/Analysis/Tasks/SkimmingTutorials/spectraTPCReference.cxx index 31b30127befe0..eea0f635f8180 100644 --- a/Analysis/Tasks/SkimmingTutorials/spectraTPCReference.cxx +++ b/Analysis/Tasks/SkimmingTutorials/spectraTPCReference.cxx @@ -85,7 +85,11 @@ struct TPCSpectraReferenceTask { histos.fill(HIST(hpt[i]), track.pt()); } - using TrackCandidates = soa::Filtered>; + using TrackCandidates = soa::Filtered>; void process(soa::Filtered::iterator const& collision, TrackCandidates const& tracks) { for (auto track : tracks) { diff --git a/Analysis/Tasks/pidTOF_split.cxx b/Analysis/Tasks/pidTOF_split.cxx deleted file mode 100644 index ed8bdcf10eae4..0000000000000 --- a/Analysis/Tasks/pidTOF_split.cxx +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// -/// \file pidTOF_split.cxx -/// \author Nicolo' Jacazio -/// \brief Task to produce PID tables for TOF split for each particle. -/// Only the tables for the mass hypotheses requested are filled, the others are sent empty. -/// - -// O2 includes -#include "Framework/AnalysisTask.h" -#include "Framework/AnalysisDataModel.h" -#include "Framework/ASoAHelpers.h" -#include "Framework/HistogramRegistry.h" -#include "Framework/runDataProcessing.h" -#include "ReconstructionDataFormats/Track.h" -#include -#include "AnalysisDataModel/PID/PIDResponse.h" -#include "AnalysisDataModel/PID/PIDTOF.h" - -using namespace o2; -using namespace o2::framework; -using namespace o2::pid; -using namespace o2::framework::expressions; -using namespace o2::track; - -struct pidTOFTaskSplit { - using Trks = soa::Join; - using Coll = aod::Collisions; - // Tables to produce - Produces tablePIDEl; - Produces tablePIDMu; - Produces tablePIDPi; - Produces tablePIDKa; - Produces tablePIDPr; - Produces tablePIDDe; - Produces tablePIDTr; - Produces tablePIDHe; - Produces tablePIDAl; - // Detector response and input parameters - DetectorResponse response; - Service ccdb; - Configurable paramfile{"param-file", "", "Path to the parametrization object, if emtpy the parametrization is not taken from file"}; - Configurable sigmaname{"param-sigma", "TOFReso", "Name of the parametrization for the expected sigma, used in both file and CCDB mode"}; - Configurable url{"ccdb-url", "http://ccdb-test.cern.ch:8080", "url of the ccdb repository"}; - Configurable timestamp{"ccdb-timestamp", -1, "timestamp of the object"}; - // Configuration flags to include and exclude particle hypotheses - Configurable pidEl{"pid-el", 0, {"Produce PID information for the Electron mass hypothesis"}}; - Configurable pidMu{"pid-mu", 0, {"Produce PID information for the Muon mass hypothesis"}}; - Configurable pidPi{"pid-pi", 0, {"Produce PID information for the Pion mass hypothesis"}}; - Configurable pidKa{"pid-ka", 0, {"Produce PID information for the Kaon mass hypothesis"}}; - Configurable pidPr{"pid-pr", 0, {"Produce PID information for the Proton mass hypothesis"}}; - Configurable pidDe{"pid-de", 0, {"Produce PID information for the Deuterons mass hypothesis"}}; - Configurable pidTr{"pid-tr", 0, {"Produce PID information for the Triton mass hypothesis"}}; - Configurable pidHe{"pid-he", 0, {"Produce PID information for the Helium3 mass hypothesis"}}; - Configurable pidAl{"pid-al", 0, {"Produce PID information for the Alpha mass hypothesis"}}; - - void init(o2::framework::InitContext&) - { - ccdb->setURL(url.value); - ccdb->setTimestamp(timestamp.value); - ccdb->setCaching(true); - ccdb->setLocalObjectValidityChecking(); - // Not later than now objects - ccdb->setCreatedNotAfter(std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count()); - // - const std::vector p = {0.008, 0.008, 0.002, 40.0}; - response.SetParameters(DetectorResponse::kSigma, p); - const std::string fname = paramfile.value; - if (!fname.empty()) { // Loading the parametrization from file - response.LoadParamFromFile(fname.data(), sigmaname.value, DetectorResponse::kSigma); - } else { // Loading it from CCDB - const std::string path = "Analysis/PID/TOF"; - response.LoadParam(DetectorResponse::kSigma, ccdb->getForTimeStamp(path + "/" + sigmaname.value, timestamp.value)); - } - } - - template - using ResponseImplementation = tof::ExpTimes; - void process(Coll const& collisions, Trks const& tracks) - { - constexpr auto responseEl = ResponseImplementation(); - constexpr auto responseMu = ResponseImplementation(); - constexpr auto responsePi = ResponseImplementation(); - constexpr auto responseKa = ResponseImplementation(); - constexpr auto responsePr = ResponseImplementation(); - constexpr auto responseDe = ResponseImplementation(); - constexpr auto responseTr = ResponseImplementation(); - constexpr auto responseHe = ResponseImplementation(); - constexpr auto responseAl = ResponseImplementation(); - - // Check and fill enabled tables - auto makeTable = [&tracks](const Configurable& flag, auto& table, const DetectorResponse& response, const auto& responsePID) { - if (flag.value) { - // Prepare memory for enabled tables - table.reserve(tracks.size()); - for (auto const& trk : tracks) { // Loop on Tracks - table(responsePID.GetExpectedSigma(response, trk.collision(), trk), - responsePID.GetSeparation(response, trk.collision(), trk)); - } - } - }; - makeTable(pidEl, tablePIDEl, response, responseEl); - makeTable(pidMu, tablePIDMu, response, responseMu); - makeTable(pidPi, tablePIDPi, response, responsePi); - makeTable(pidKa, tablePIDKa, response, responseKa); - makeTable(pidPr, tablePIDPr, response, responsePr); - makeTable(pidDe, tablePIDDe, response, responseDe); - makeTable(pidTr, tablePIDTr, response, responseTr); - makeTable(pidHe, tablePIDHe, response, responseHe); - makeTable(pidAl, tablePIDAl, response, responseAl); - } -}; - -WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) -{ - return WorkflowSpec{adaptAnalysisTask(cfgc, TaskName{"pidTOF-split-task"})}; -} diff --git a/Analysis/Tasks/pidTOF_tiny.cxx b/Analysis/Tasks/pidTOF_tiny.cxx deleted file mode 100644 index e3b5681b65553..0000000000000 --- a/Analysis/Tasks/pidTOF_tiny.cxx +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// -/// \file pidTOF_tiny.cxx -/// \author Nicolo' Jacazio -/// \brief Task to produce PID tables for TOF split for each particle with only the Nsigma information. -/// Only the tables for the mass hypotheses requested are filled, the others are sent empty. -/// - -// O2 includes -#include "Framework/AnalysisTask.h" -#include "Framework/AnalysisDataModel.h" -#include "Framework/ASoAHelpers.h" -#include "Framework/HistogramRegistry.h" -#include "Framework/runDataProcessing.h" -#include "ReconstructionDataFormats/Track.h" -#include -#include "AnalysisDataModel/PID/PIDResponse.h" -#include "AnalysisDataModel/PID/PIDTOF.h" - -using namespace o2; -using namespace o2::framework; -using namespace o2::pid; -using namespace o2::framework::expressions; -using namespace o2::track; - -struct pidTOFTaskTiny { - using Trks = soa::Join; - using Coll = aod::Collisions; - // Tables to produce - Produces tablePIDEl; - Produces tablePIDMu; - Produces tablePIDPi; - Produces tablePIDKa; - Produces tablePIDPr; - Produces tablePIDDe; - Produces tablePIDTr; - Produces tablePIDHe; - Produces tablePIDAl; - // Detector response and input parameters - DetectorResponse response; - Service ccdb; - Configurable paramfile{"param-file", "", "Path to the parametrization object, if emtpy the parametrization is not taken from file"}; - Configurable sigmaname{"param-sigma", "TOFReso", "Name of the parametrization for the expected sigma, used in both file and CCDB mode"}; - Configurable url{"ccdb-url", "http://ccdb-test.cern.ch:8080", "url of the ccdb repository"}; - Configurable timestamp{"ccdb-timestamp", -1, "timestamp of the object"}; - // Configuration flags to include and exclude particle hypotheses - Configurable pidEl{"pid-el", 0, {"Produce PID information for the Electron mass hypothesis"}}; - Configurable pidMu{"pid-mu", 0, {"Produce PID information for the Muon mass hypothesis"}}; - Configurable pidPi{"pid-pi", 0, {"Produce PID information for the Pion mass hypothesis"}}; - Configurable pidKa{"pid-ka", 0, {"Produce PID information for the Kaon mass hypothesis"}}; - Configurable pidPr{"pid-pr", 0, {"Produce PID information for the Proton mass hypothesis"}}; - Configurable pidDe{"pid-de", 0, {"Produce PID information for the Deuterons mass hypothesis"}}; - Configurable pidTr{"pid-tr", 0, {"Produce PID information for the Triton mass hypothesis"}}; - Configurable pidHe{"pid-he", 0, {"Produce PID information for the Helium3 mass hypothesis"}}; - Configurable pidAl{"pid-al", 0, {"Produce PID information for the Alpha mass hypothesis"}}; - - void init(o2::framework::InitContext&) - { - ccdb->setURL(url.value); - ccdb->setTimestamp(timestamp.value); - ccdb->setCaching(true); - ccdb->setLocalObjectValidityChecking(); - // Not later than now objects - ccdb->setCreatedNotAfter(std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count()); - // - const std::vector p = {0.008, 0.008, 0.002, 40.0}; - response.SetParameters(DetectorResponse::kSigma, p); - const std::string fname = paramfile.value; - if (!fname.empty()) { // Loading the parametrization from file - response.LoadParamFromFile(fname.data(), sigmaname.value, DetectorResponse::kSigma); - } else { // Loading it from CCDB - const std::string path = "Analysis/PID/TOF"; - response.LoadParam(DetectorResponse::kSigma, ccdb->getForTimeStamp(path + "/" + sigmaname.value, timestamp.value)); - } - } - - template - using ResponseImplementation = tof::ExpTimes; - void process(Coll const& collisions, Trks const& tracks) - { - constexpr auto responseEl = ResponseImplementation(); - constexpr auto responseMu = ResponseImplementation(); - constexpr auto responsePi = ResponseImplementation(); - constexpr auto responseKa = ResponseImplementation(); - constexpr auto responsePr = ResponseImplementation(); - constexpr auto responseDe = ResponseImplementation(); - constexpr auto responseTr = ResponseImplementation(); - constexpr auto responseHe = ResponseImplementation(); - constexpr auto responseAl = ResponseImplementation(); - - // Check and fill enabled tables - auto makeTable = [&tracks](const Configurable& flag, auto& table, const DetectorResponse& response, const auto& responsePID) { - if (flag.value) { - // Prepare memory for enabled tables - table.reserve(tracks.size()); - for (auto const& trk : tracks) { // Loop on Tracks - const float separation = responsePID.GetSeparation(response, trk.collision(), trk); - if (separation <= o2::aod::pidtof_tiny::binned_min) { - table(o2::aod::pidtof_tiny::lower_bin); - } else if (separation >= o2::aod::pidtof_tiny::binned_max) { - table(o2::aod::pidtof_tiny::upper_bin); - } else if (separation >= 0) { - table(separation / o2::aod::pidtof_tiny::bin_width + 0.5f); - } else { - table(separation / o2::aod::pidtof_tiny::bin_width - 0.5f); - } - } - } - }; - makeTable(pidEl, tablePIDEl, response, responseEl); - makeTable(pidMu, tablePIDMu, response, responseMu); - makeTable(pidPi, tablePIDPi, response, responsePi); - makeTable(pidKa, tablePIDKa, response, responseKa); - makeTable(pidPr, tablePIDPr, response, responsePr); - makeTable(pidDe, tablePIDDe, response, responseDe); - makeTable(pidTr, tablePIDTr, response, responseTr); - makeTable(pidHe, tablePIDHe, response, responseHe); - makeTable(pidAl, tablePIDAl, response, responseAl); - } -}; - -WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) -{ - return WorkflowSpec{adaptAnalysisTask(cfgc, TaskName{"pidTOF-tiny-task"})}; -} diff --git a/Analysis/Tasks/pidTPC_split.cxx b/Analysis/Tasks/pidTPC_split.cxx deleted file mode 100644 index 677ae36fd726c..0000000000000 --- a/Analysis/Tasks/pidTPC_split.cxx +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// -/// \file pidTPC_split.cxx -/// \author Nicolo' Jacazio -/// \brief Task to produce PID tables for TPC split for each particle. -/// Only the tables for the mass hypotheses requested are filled, the others are sent empty. -/// - -// O2 includes -#include "Framework/AnalysisTask.h" -#include "Framework/AnalysisDataModel.h" -#include "Framework/ASoAHelpers.h" -#include "Framework/HistogramRegistry.h" -#include "Framework/runDataProcessing.h" -#include "ReconstructionDataFormats/Track.h" -#include -#include "AnalysisDataModel/PID/PIDResponse.h" -#include "AnalysisDataModel/PID/PIDTPC.h" - -using namespace o2; -using namespace o2::framework; -using namespace o2::pid; -using namespace o2::framework::expressions; -using namespace o2::track; - -struct pidTPCTaskSplit { - using Trks = soa::Join; - using Coll = aod::Collisions; - // Tables to produce - Produces tablePIDEl; - Produces tablePIDMu; - Produces tablePIDPi; - Produces tablePIDKa; - Produces tablePIDPr; - Produces tablePIDDe; - Produces tablePIDTr; - Produces tablePIDHe; - Produces tablePIDAl; - // Detector response and input parameters - DetectorResponse response; - Service ccdb; - Configurable paramfile{"param-file", "", "Path to the parametrization object, if emtpy the parametrization is not taken from file"}; - Configurable signalname{"param-signal", "BetheBloch", "Name of the parametrization for the expected signal, used in both file and CCDB mode"}; - Configurable sigmaname{"param-sigma", "TPCReso", "Name of the parametrization for the expected sigma, used in both file and CCDB mode"}; - Configurable url{"ccdb-url", "http://ccdb-test.cern.ch:8080", "url of the ccdb repository"}; - Configurable timestamp{"ccdb-timestamp", -1, "timestamp of the object"}; - // Configuration flags to include and exclude particle hypotheses - Configurable pidEl{"pid-el", 0, {"Produce PID information for the Electron mass hypothesis"}}; - Configurable pidMu{"pid-mu", 0, {"Produce PID information for the Muon mass hypothesis"}}; - Configurable pidPi{"pid-pi", 0, {"Produce PID information for the Pion mass hypothesis"}}; - Configurable pidKa{"pid-ka", 0, {"Produce PID information for the Kaon mass hypothesis"}}; - Configurable pidPr{"pid-pr", 0, {"Produce PID information for the Proton mass hypothesis"}}; - Configurable pidDe{"pid-de", 0, {"Produce PID information for the Deuterons mass hypothesis"}}; - Configurable pidTr{"pid-tr", 0, {"Produce PID information for the Triton mass hypothesis"}}; - Configurable pidHe{"pid-he", 0, {"Produce PID information for the Helium3 mass hypothesis"}}; - Configurable pidAl{"pid-al", 0, {"Produce PID information for the Alpha mass hypothesis"}}; - - void init(o2::framework::InitContext&) - { - ccdb->setURL(url.value); - ccdb->setTimestamp(timestamp.value); - ccdb->setCaching(true); - ccdb->setLocalObjectValidityChecking(); - // Not later than now objects - ccdb->setCreatedNotAfter(std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count()); - // - const std::string fname = paramfile.value; - if (!fname.empty()) { // Loading the parametrization from file - response.LoadParamFromFile(fname.data(), signalname.value, DetectorResponse::kSignal); - response.LoadParamFromFile(fname.data(), sigmaname.value, DetectorResponse::kSigma); - } else { // Loading it from CCDB - const std::string path = "Analysis/PID/TPC"; - response.LoadParam(DetectorResponse::kSignal, ccdb->getForTimeStamp(path + "/" + signalname.value, timestamp.value)); - response.LoadParam(DetectorResponse::kSigma, ccdb->getForTimeStamp(path + "/" + sigmaname.value, timestamp.value)); - } - } - - template - using ResponseImplementation = tpc::ELoss; - void process(Coll const& collisions, Trks const& tracks) - { - constexpr auto responseEl = ResponseImplementation(); - constexpr auto responseMu = ResponseImplementation(); - constexpr auto responsePi = ResponseImplementation(); - constexpr auto responseKa = ResponseImplementation(); - constexpr auto responsePr = ResponseImplementation(); - constexpr auto responseDe = ResponseImplementation(); - constexpr auto responseTr = ResponseImplementation(); - constexpr auto responseHe = ResponseImplementation(); - constexpr auto responseAl = ResponseImplementation(); - - // Check and fill enabled tables - auto makeTable = [&tracks](const Configurable& flag, auto& table, const DetectorResponse& response, const auto& responsePID) { - if (flag.value) { - // Prepare memory for enabled tables - table.reserve(tracks.size()); - for (auto const& trk : tracks) { // Loop on Tracks - table(responsePID.GetExpectedSigma(response, trk.collision(), trk), - responsePID.GetSeparation(response, trk.collision(), trk)); - } - } - }; - makeTable(pidEl, tablePIDEl, response, responseEl); - makeTable(pidMu, tablePIDMu, response, responseMu); - makeTable(pidPi, tablePIDPi, response, responsePi); - makeTable(pidKa, tablePIDKa, response, responseKa); - makeTable(pidPr, tablePIDPr, response, responsePr); - makeTable(pidDe, tablePIDDe, response, responseDe); - makeTable(pidTr, tablePIDTr, response, responseTr); - makeTable(pidHe, tablePIDHe, response, responseHe); - makeTable(pidAl, tablePIDAl, response, responseAl); - } -}; - -WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) -{ - return WorkflowSpec{adaptAnalysisTask(cfgc, TaskName{"pidTPC-split-task"})}; -} From 4c5cb12730586cf9f0fe782f55242332e1266af2 Mon Sep 17 00:00:00 2001 From: Amrit Gautam <40325188+aga01935@users.noreply.github.com> Date: Wed, 14 Apr 2021 14:28:31 -0500 Subject: [PATCH 133/770] updated the O2 build and ran clang-format (#5929) Co-authored-by: amrit gautam --- Analysis/Tasks/PWGUD/upcForward.cxx | 78 ++++++++++++++++------------- 1 file changed, 44 insertions(+), 34 deletions(-) diff --git a/Analysis/Tasks/PWGUD/upcForward.cxx b/Analysis/Tasks/PWGUD/upcForward.cxx index cbb91e3a92c09..4c378f63477d3 100644 --- a/Analysis/Tasks/PWGUD/upcForward.cxx +++ b/Analysis/Tasks/PWGUD/upcForward.cxx @@ -7,19 +7,15 @@ // In applying this license CERN does not waive the privileges and immunities // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. - /* I ran this code using following: -o2-analysis-timestamp| o2-analysis-upc-forward --aod-file [--isPbPb] --aod-memory-rate-limit 10000000000 --shm-segment-size 16000000000 -b +o2-analysis-timestamp| o2-analysis-upc-forward | o2-analysis-event-selection --aod-file [--isPbPb] -b for now AO2D.root I am using is -/alice/data/2015/LHC15o/000246392/pass5_lowIR/PWGZZ/Run3_Conversion/138_20210129-0800_child_1/0001/AO2D.root -it can be copied using -alien_cp alien:/alice/data/2015/LHC15o/000246392/pass5_lowIR/PWGZZ/Run3_Conversion/138_20210129-0800_child_1/0001/AO2D.root file:./ +alien:///alice/data/2015/LHC15o/000246392/pass5_lowIR/PWGZZ/Run3_Conversion/148_20210304-0829_child_1/AOD/001/AO2D.root */ #include "Framework/runDataProcessing.h" #include "Framework/AnalysisTask.h" #include "Framework/AnalysisDataModel.h" -#include "AnalysisDataModel/TrackSelectionTables.h" #include "AnalysisDataModel/EventSelection.h" #include #include @@ -32,7 +28,7 @@ using namespace o2::framework; using namespace o2::framework::expressions; #define mmuon 0.1057 //mass of muon struct UPCForward { - //defining histograms + //defining histograms using histogram registry HistogramRegistry registry{ "registry", {{"hMass", ";#it{m_{#mu#mu}}, GeV/c^{2};", {HistType::kTH1D, {{500, 0, 10}}}}, @@ -49,14 +45,15 @@ struct UPCForward { void init(o2::framework::InitContext&) { - TString SelectionCuts[6] = {"NoSelection", "CMup11and10Trigger", "twotracks", "oppositecharge", "-2.5::iterator const& bc, aod::Muons const& tracksMuon) + //new + void process(soa::Join::iterator const& bc, aod::Muons const& tracksMuon) { registry.fill(HIST("hSelectionCounter"), 0); @@ -64,30 +61,42 @@ struct UPCForward { TLorentzVector p1, p2, p; bool ispositive = kFALSE; bool isnegative = kFALSE; - /*this code below is suggested by evgeny. - this code is now hardcoded for runs 246391, 246392 for CMUP11 - and 244980, 244982, 244983, 245064, 245066, 245068 for CMUP10*/ - uint64_t classIndexMUP = -1; - Int_t iRunNumber = bc.runNumber(); - if (iRunNumber == 246391 || iRunNumber == 246392) { - classIndexMUP = 51; //CMUP11 - } else if (iRunNumber == 246980 || iRunNumber == 246982 || iRunNumber == 246983) { - classIndexMUP = 88; //CMUP10 - } else if (iRunNumber == 245064 || iRunNumber == 245066 || iRunNumber == 245068) { - classIndexMUP = 62; //CMUP10 - } - if (classIndexMUP == -1) { + // V0 and FD information + bool isBeamBeamV0A = bc.bbV0A(); + bool isBeamGasV0A = bc.bgV0A(); + bool isBeamBeamV0C = bc.bbV0C(); + bool isBeamGasV0C = bc.bgV0C(); + + bool isBeamBeamFDA = bc.bbFDA(); + bool isBeamGasFDA = bc.bgFDA(); + bool isBeamBeamFDC = bc.bbFDC(); + bool isBeamGasFDC = bc.bgFDC(); + + //offline V0 and FD selection + bool isV0Selection = isBeamBeamV0A || isBeamGasV0A || isBeamGasV0C; + bool isFDSelection = isBeamBeamFDA || isBeamGasFDA || isBeamBeamFDC || isBeamGasFDC; + + //CCUP10 and CCUP11 information + bool iskMUP11fired = bc.alias()[kMUP11]; + bool iskMUP10fired = bc.alias()[kMUP10]; + + // selecting kMUP10 and 11 triggers + if (!iskMUP11fired && !iskMUP10fired) { return; } - //selecting CMUP10 and CMUP11 events selection + registry.fill(HIST("hSelectionCounter"), 1); - bool isMUP11fired = bc.triggerMaskNext50() & (1ull << (classIndexMUP - 50)); + if (isV0Selection) { + return; + } + registry.fill(HIST("hSelectionCounter"), 2); - if (!isMUP11fired) { + if (isFDSelection) { return; } - registry.fill(HIST("hSelectionCounter"), 1); + registry.fill(HIST("hSelectionCounter"), 3); + for (auto& muon : tracksMuon) { registry.fill(HIST("hCharge"), muon.sign()); iMuonTracknumber++; @@ -103,21 +112,22 @@ struct UPCForward { if (iMuonTracknumber != 2) { return; } - registry.fill(HIST("hSelectionCounter"), 2); + registry.fill(HIST("hSelectionCounter"), 4); if (!ispositive || !isnegative) { return; } - registry.fill(HIST("hSelectionCounter"), 3); + registry.fill(HIST("hSelectionCounter"), 5); if (-4 < p1.Eta() < -2.5 || -4 < p2.Eta() < -2.5) { + return; } - registry.fill(HIST("hSelectionCounter"), 4); + registry.fill(HIST("hSelectionCounter"), 6); p = p1 + p2; if (p.Pt() > 1) { return; } - registry.fill(HIST("hSelectionCounter"), 5); + registry.fill(HIST("hSelectionCounter"), 7); registry.fill(HIST("hPt"), p.Pt()); registry.fill(HIST("hPx"), p.Px()); registry.fill(HIST("hPy"), p.Py()); @@ -127,13 +137,13 @@ struct UPCForward { registry.fill(HIST("hPhi"), p.Phi()); registry.fill(HIST("hEta"), p1.Eta()); registry.fill(HIST("hEta"), p2.Eta()); - registry.fill(HIST("hPtsingle"), p1.Pt()); - registry.fill(HIST("hPtsingle"), p2.Pt()); + registry.fill(HIST("hPtsingle_muons"), p1.Pt()); + registry.fill(HIST("hPtsingle_muons"), p2.Pt()); } //end of process }; WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { return WorkflowSpec{ - adaptAnalysisTask(cfgc, TaskName{"upc-forward"})}; + adaptAnalysisTask(cfgc)}; } From f480fa87857a44ff06ace8f11836e87d991338f4 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Thu, 15 Apr 2021 21:52:28 +0200 Subject: [PATCH 134/770] DPL: add support for exporting merged workflows to DDS (#5936) --- Framework/Core/src/DDSConfigHelpers.cxx | 27 ++++++++++--------- Framework/Core/src/DDSConfigHelpers.h | 18 ++++++------- Framework/Core/src/runDataProcessing.cxx | 4 +-- .../Core/test/test_FrameworkDataFlowToDDS.cxx | 11 ++++---- 4 files changed, 32 insertions(+), 28 deletions(-) diff --git a/Framework/Core/src/DDSConfigHelpers.cxx b/Framework/Core/src/DDSConfigHelpers.cxx index aed34946ec269..d2fbd18c3d8fd 100644 --- a/Framework/Core/src/DDSConfigHelpers.cxx +++ b/Framework/Core/src/DDSConfigHelpers.cxx @@ -17,9 +17,22 @@ namespace o2::framework { +std::string replaceFirstOccurrence( + std::string s, + const std::string& toReplace, + const std::string& replaceWith) +{ + std::size_t pos = s.find(toReplace); + if (pos == std::string::npos) { + return s; + } + return s.replace(pos, toReplace.length(), replaceWith); +} + void dumpDeviceSpec2DDS(std::ostream& out, const std::vector& specs, - const std::vector& executions) + const std::vector& executions, + const CommandInfo& commandInfo) { out << R"()" "\n"; @@ -35,6 +48,7 @@ void dumpDeviceSpec2DDS(std::ostream& out, << fmt::format("\n", spec.name); out << " " << R"()"; + out << replaceFirstOccurrence(commandInfo.command, "--dds", "--dump") << " | "; std::string accumulatedChannelPrefix; char* s = strdup(execution.args[0]); out << basename(s) << " "; @@ -53,17 +67,6 @@ void dumpDeviceSpec2DDS(std::ostream& out, ai++; continue; } - if (strcmp(arg, "--channel-config") == 0) { - if ((ai + 1) < execution.args.size()) { - if (accumulatedChannelPrefix.empty() == false) { - accumulatedChannelPrefix += ";"; - } - accumulatedChannelPrefix += execution.args[ai + 1]; - } - ai++; - continue; - } - // If channel-prefix is empty do not print it out if (strcmp(arg, "--channel-prefix") == 0 && ai + 1 < execution.args.size() && *execution.args[ai + 1] == 0) { diff --git a/Framework/Core/src/DDSConfigHelpers.h b/Framework/Core/src/DDSConfigHelpers.h index f65e06c8eb591..af804f79f6526 100644 --- a/Framework/Core/src/DDSConfigHelpers.h +++ b/Framework/Core/src/DDSConfigHelpers.h @@ -7,17 +7,16 @@ // In applying this license CERN does not waive the privileges and immunities // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef FRAMEWORK_DDSCONFIGHELPERS_H -#define FRAMEWORK_DDSCONFIGHELPERS_H +#ifndef O2_FRAMEWORK_DDSCONFIGHELPERS_H_ +#define O2_FRAMEWORK_DDSCONFIGHELPERS_H_ #include "Framework/DeviceSpec.h" #include "Framework/DeviceExecution.h" +#include "Framework/CommandInfo.h" #include #include -namespace o2 -{ -namespace framework +namespace o2::framework { /// Helper to dump DDS configuration to run in a deployed @@ -27,10 +26,11 @@ namespace framework /// which we want to dump. /// @a executions is the transient parameters for the afore mentioned /// specifications +/// @a the full command being used void dumpDeviceSpec2DDS(std::ostream& out, std::vector const& specs, - std::vector const& executions); + std::vector const& executions, + CommandInfo const& commandInfo); -} // namespace framework -} // namespace o2 -#endif // FRAMEWORK_DDSCONFIGHELPERS_H +} // namespace o2::framework +#endif // O2_FRAMEWORK_DDSCONFIGHELPERS_H_ diff --git a/Framework/Core/src/runDataProcessing.cxx b/Framework/Core/src/runDataProcessing.cxx index 7d1d7ede58087..77b25c4827ec5 100644 --- a/Framework/Core/src/runDataProcessing.cxx +++ b/Framework/Core/src/runDataProcessing.cxx @@ -1880,8 +1880,8 @@ void initialiseDriverControl(bpo::variables_map const& varmap, DeviceSpecs const& specs, DeviceExecutions const& executions, DataProcessorInfos&, - CommandInfo const&) { - dumpDeviceSpec2DDS(std::cout, specs, executions); + CommandInfo const& commandInfo) { + dumpDeviceSpec2DDS(std::cout, specs, executions, commandInfo); }}; control.forcedTransitions = { DriverState::EXIT, // diff --git a/Framework/Core/test/test_FrameworkDataFlowToDDS.cxx b/Framework/Core/test/test_FrameworkDataFlowToDDS.cxx index f8788658260ec..55ed270d808ec 100644 --- a/Framework/Core/test/test_FrameworkDataFlowToDDS.cxx +++ b/Framework/Core/test/test_FrameworkDataFlowToDDS.cxx @@ -110,19 +110,20 @@ BOOST_AUTO_TEST_CASE(TestDDS) dataProcessorInfos, devices, executions, controls, "workflow-id"); - dumpDeviceSpec2DDS(ss, devices, executions); + CommandInfo command{"foo"}; + dumpDeviceSpec2DDS(ss, devices, executions, command); auto expected = R"EXPECTED( - foo --id A --shm-monitor false --log-color false --color false --jobs 4 --severity info --shm-mlock-segment false --shm-segment-id 0 --shm-throw-bad-alloc true --shm-zero-segment false --stacktrace-on-signal all --session dpl_workflow-id --plugin dds --channel-config "name=from_A_to_B,type=push,method=bind,address=ipc://@localhostworkflow-id_22000,transport=shmem,rateLogging=0,rcvBufSize=1,sndBufSize=1;name=from_A_to_C,type=push,method=bind,address=ipc://@localhostworkflow-id_22001,transport=shmem,rateLogging=0,rcvBufSize=1,sndBufSize=1" + foo | foo --id A --shm-monitor false --log-color false --color false --jobs 4 --severity info --shm-mlock-segment false --shm-segment-id 0 --shm-throw-bad-alloc true --shm-zero-segment false --stacktrace-on-signal all --channel-config "name=from_A_to_B,type=push,method=bind,address=ipc://@localhostworkflow-id_22000,transport=shmem,rateLogging=0,rcvBufSize=1,sndBufSize=1" --channel-config "name=from_A_to_C,type=push,method=bind,address=ipc://@localhostworkflow-id_22001,transport=shmem,rateLogging=0,rcvBufSize=1,sndBufSize=1" --session dpl_workflow-id --plugin dds - foo --id B --shm-monitor false --log-color false --color false --jobs 4 --severity info --shm-mlock-segment false --shm-segment-id 0 --shm-throw-bad-alloc true --shm-zero-segment false --stacktrace-on-signal all --session dpl_workflow-id --plugin dds --channel-config "name=from_B_to_D,type=push,method=bind,address=ipc://@localhostworkflow-id_22002,transport=shmem,rateLogging=0,rcvBufSize=1,sndBufSize=1;name=from_A_to_B,type=pull,method=connect,address=ipc://@localhostworkflow-id_22000,transport=shmem,rateLogging=0,rcvBufSize=1,sndBufSize=1" + foo | foo --id B --shm-monitor false --log-color false --color false --jobs 4 --severity info --shm-mlock-segment false --shm-segment-id 0 --shm-throw-bad-alloc true --shm-zero-segment false --stacktrace-on-signal all --channel-config "name=from_B_to_D,type=push,method=bind,address=ipc://@localhostworkflow-id_22002,transport=shmem,rateLogging=0,rcvBufSize=1,sndBufSize=1" --channel-config "name=from_A_to_B,type=pull,method=connect,address=ipc://@localhostworkflow-id_22000,transport=shmem,rateLogging=0,rcvBufSize=1,sndBufSize=1" --session dpl_workflow-id --plugin dds - foo --id C --shm-monitor false --log-color false --color false --jobs 4 --severity info --shm-mlock-segment false --shm-segment-id 0 --shm-throw-bad-alloc true --shm-zero-segment false --stacktrace-on-signal all --session dpl_workflow-id --plugin dds --channel-config "name=from_C_to_D,type=push,method=bind,address=ipc://@localhostworkflow-id_22003,transport=shmem,rateLogging=0,rcvBufSize=1,sndBufSize=1;name=from_A_to_C,type=pull,method=connect,address=ipc://@localhostworkflow-id_22001,transport=shmem,rateLogging=0,rcvBufSize=1,sndBufSize=1" + foo | foo --id C --shm-monitor false --log-color false --color false --jobs 4 --severity info --shm-mlock-segment false --shm-segment-id 0 --shm-throw-bad-alloc true --shm-zero-segment false --stacktrace-on-signal all --channel-config "name=from_C_to_D,type=push,method=bind,address=ipc://@localhostworkflow-id_22003,transport=shmem,rateLogging=0,rcvBufSize=1,sndBufSize=1" --channel-config "name=from_A_to_C,type=pull,method=connect,address=ipc://@localhostworkflow-id_22001,transport=shmem,rateLogging=0,rcvBufSize=1,sndBufSize=1" --session dpl_workflow-id --plugin dds - foo --id D --shm-monitor false --log-color false --color false --jobs 4 --severity info --shm-mlock-segment false --shm-segment-id 0 --shm-throw-bad-alloc true --shm-zero-segment false --stacktrace-on-signal all --a-param 1 --b-param "" --c-param "foo;bar" --session dpl_workflow-id --plugin dds --channel-config "name=from_B_to_D,type=pull,method=connect,address=ipc://@localhostworkflow-id_22002,transport=shmem,rateLogging=0,rcvBufSize=1,sndBufSize=1;name=from_C_to_D,type=pull,method=connect,address=ipc://@localhostworkflow-id_22003,transport=shmem,rateLogging=0,rcvBufSize=1,sndBufSize=1" + foo | foo --id D --shm-monitor false --log-color false --color false --jobs 4 --severity info --shm-mlock-segment false --shm-segment-id 0 --shm-throw-bad-alloc true --shm-zero-segment false --stacktrace-on-signal all --a-param 1 --b-param "" --c-param "foo;bar" --channel-config "name=from_B_to_D,type=pull,method=connect,address=ipc://@localhostworkflow-id_22002,transport=shmem,rateLogging=0,rcvBufSize=1,sndBufSize=1" --channel-config "name=from_C_to_D,type=pull,method=connect,address=ipc://@localhostworkflow-id_22003,transport=shmem,rateLogging=0,rcvBufSize=1,sndBufSize=1" --session dpl_workflow-id --plugin dds From 1274d9d64374b2e6a3a655b0227bf0eac5a68d0d Mon Sep 17 00:00:00 2001 From: shahoian Date: Thu, 15 Apr 2021 11:51:01 +0200 Subject: [PATCH 135/770] Fix in cosmic track time assignment --- .../include/ReconstructionDataFormats/TrackCosmics.h | 4 ++-- Detectors/GlobalTracking/src/MatchCosmics.cxx | 9 ++++----- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackCosmics.h b/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackCosmics.h index 6a8790fe2cc94..6639d9c3e44bc 100644 --- a/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackCosmics.h +++ b/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackCosmics.h @@ -32,8 +32,8 @@ class TrackCosmics : public o2::track::TrackParCov TrackCosmics() = default; ~TrackCosmics() = default; TrackCosmics(const TrackCosmics& src) = default; - TrackCosmics(GlobalTrackID btm, GlobalTrackID top, const o2::track::TrackParCov& srcCent, const o2::track::TrackParCov& srcOut, float chi2Ref, float chi2Match, int ncl) - : o2::track::TrackParCov(srcCent), mParamOut(srcOut), mRefBottom(btm), mRefTop(top), mChi2Refit(chi2Ref), mChi2Match(chi2Match), mNClusters(ncl) {} + TrackCosmics(GlobalTrackID btm, GlobalTrackID top, const o2::track::TrackParCov& srcCent, const o2::track::TrackParCov& srcOut, float chi2Ref, float chi2Match, int ncl, float t, float tErr) + : o2::track::TrackParCov(srcCent), mParamOut(srcOut), mRefBottom(btm), mRefTop(top), mChi2Refit(chi2Ref), mChi2Match(chi2Match), mNClusters(ncl), mTimeMUS{t, tErr} {} GlobalTrackID getRefBottom() const { return mRefBottom; } GlobalTrackID getRefTop() const { return mRefTop; } diff --git a/Detectors/GlobalTracking/src/MatchCosmics.cxx b/Detectors/GlobalTracking/src/MatchCosmics.cxx index f4884de2e0aa7..c8fc68fc918c3 100644 --- a/Detectors/GlobalTracking/src/MatchCosmics.cxx +++ b/Detectors/GlobalTracking/src/MatchCosmics.cxx @@ -141,9 +141,8 @@ void MatchCosmics::refitWinners(const o2::globaltracking::RecoContainer& data) const auto& rec = mRecords[winRID]; int poolEntryID[2] = {rec.id0, rec.id1}; const o2::track::TrackParCov outerLegs[2] = {data.getTrackParamOut(mSeeds[rec.id0].origID), data.getTrackParamOut(mSeeds[rec.id1].origID)}; - auto tmin = std::max(mSeeds[rec.id0].tBracket.getMin(), mSeeds[rec.id1].tBracket.getMin()); - auto tmax = std::min(mSeeds[rec.id0].tBracket.getMax(), mSeeds[rec.id1].tBracket.getMax()); - auto t0 = 0.5 * (tmin + tmax); + auto tOverlap = mSeeds[rec.id0].tBracket.getOverlap(mSeeds[rec.id1].tBracket); + float t0 = tOverlap.mean(), dt = tOverlap.delta() * 0.5; auto pnt0 = outerLegs[0].getXYZGlo(), pnt1 = outerLegs[1].getXYZGlo(); int btm = 0, top = 1; // we fit topward from bottom @@ -154,7 +153,7 @@ void MatchCosmics::refitWinners(const o2::globaltracking::RecoContainer& data) LOG(DEBUG) << "Winner " << count++ << " Record " << winRID << " Partners:" << " B: " << mSeeds[poolEntryID[btm]].origID << "/" << mSeeds[poolEntryID[btm]].origID.getSourceName() << " U: " << mSeeds[poolEntryID[top]].origID << "/" << mSeeds[poolEntryID[top]].origID.getSourceName() - << " | T[" << tmin << ":" << tmax << "]"; + << " | T:" << tOverlap.asString(); float chi2 = 0; int nclTot = 0; @@ -258,7 +257,7 @@ void MatchCosmics::refitWinners(const o2::globaltracking::RecoContainer& data) continue; } // create final track - mCosmicTracks.emplace_back(mSeeds[poolEntryID[btm]].origID, mSeeds[poolEntryID[top]].origID, trCosmBtm, trCosmTop, chi2, chi2Match, nclTot); + mCosmicTracks.emplace_back(mSeeds[poolEntryID[btm]].origID, mSeeds[poolEntryID[top]].origID, trCosmBtm, trCosmTop, chi2, chi2Match, nclTot, t0, dt); if (mUseMC) { o2::MCCompLabel lbl[2] = {data.getTrackMCLabel(mSeeds[poolEntryID[btm]].origID), data.getTrackMCLabel(mSeeds[poolEntryID[top]].origID)}; auto& tlb = mCosmicTracksLbl.emplace_back((nclBtm > nclTot - nclBtm ? lbl[0] : lbl[1])); From 4b55fa2629160a73e13ce89a630c4c61f103d6f9 Mon Sep 17 00:00:00 2001 From: shahoian Date: Thu, 15 Apr 2021 17:09:37 +0200 Subject: [PATCH 136/770] Fix in cosmic track refit --- Detectors/GlobalTracking/src/MatchCosmics.cxx | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/Detectors/GlobalTracking/src/MatchCosmics.cxx b/Detectors/GlobalTracking/src/MatchCosmics.cxx index c8fc68fc918c3..6f85b29239b0e 100644 --- a/Detectors/GlobalTracking/src/MatchCosmics.cxx +++ b/Detectors/GlobalTracking/src/MatchCosmics.cxx @@ -174,7 +174,7 @@ void MatchCosmics::refitWinners(const o2::globaltracking::RecoContainer& data) } else { // just collect NClusters and chi2 auto gidxListBtm = data.getSingleDetectorRefs(mSeeds[poolEntryID[btm]].origID); if (gidxListBtm[GTrackID::TPC].isIndexSet()) { - const auto& tpcTrOrig = data.getTPCTrack(gidxListBtm[GTrackID::TPC]); + const auto& tpcTrOrig = data.getTPCTrack(gidxListBtm[GTrackID::TPC]); nclTot += tpcTrOrig.getNClusters(); chi2 += tpcTrOrig.getChi2(); } @@ -208,11 +208,14 @@ void MatchCosmics::refitWinners(const o2::globaltracking::RecoContainer& data) } // ITS refit // if (gidxListTop[GTrackID::TPC].isIndexSet()) { // outward refit in TPC - float xtogo = 0; - if (!trCosm.getXatLabR(o2::constants::geom::XTPCInnerRef, xtogo, mBz, o2::track::DirOutward) || - !o2::base::Propagator::Instance()->PropagateToXBxByBz(trCosm, xtogo, mMatchParams->maxSnp, mMatchParams->maxStep, mMatchParams->matCorr)) { - LOG(DEBUG) << "Propagation to inner TPC boundary X=" << xtogo << " failed"; - continue; + // go to TPC boundary, if needed + if (trCosm.getX() * trCosm.getX() + trCosm.getY() * trCosm.getY() <= o2::constants::geom::XTPCInnerRef * o2::constants::geom::XTPCInnerRef) { + float xtogo = 0; + if (!trCosm.getXatLabR(o2::constants::geom::XTPCInnerRef, xtogo, mBz, o2::track::DirOutward) || + !o2::base::Propagator::Instance()->PropagateToXBxByBz(trCosm, xtogo, mMatchParams->maxSnp, mMatchParams->maxStep, mMatchParams->matCorr)) { + LOG(DEBUG) << "Propagation to inner TPC boundary X=" << xtogo << " failed"; + continue; + } } const auto& tpcTrOrig = data.getTPCTrack(gidxListTop[GTrackID::TPC]); int retVal = tpcRefitter->RefitTrackAsTrackParCov(trCosm, tpcTrOrig.getClusterRef(), t0 * tpcTBinMUSInv, &chi2, true, false); // outward refit, no reset From 1e74aeb87b9eff50a21898b406245642178ce1f9 Mon Sep 17 00:00:00 2001 From: Ole Schmidt Date: Thu, 15 Apr 2021 13:44:17 +0200 Subject: [PATCH 137/770] TRD FeeParam singleton thread-safe for OMP - as FeeParam is a singleton the members don't need to be static - CommonParam which is also a singleton is simplified - for both singletons the copy and assignment operators are deleted - FeeParam still has hard-coded some values which could in principle also be taken from o2::trd::Geometry or o2::trd::PadPlane - The dy range calculation in FeeParam is still based on the Run 1-2 tracklet data format --- .../TRD/base/include/TRDBase/CommonParam.h | 67 ++--- Detectors/TRD/base/include/TRDBase/FeeParam.h | 110 +++++---- Detectors/TRD/base/src/CommonParam.cxx | 140 +++-------- .../base/src/DiffAndTimeStructEstimator.cxx | 6 +- Detectors/TRD/base/src/FeeParam.cxx | 232 +++++------------- Detectors/TRD/base/src/SimParam.cxx | 12 +- .../base/test/testTRDDiffusionCoefficient.cxx | 24 +- Detectors/TRD/simulation/src/Detector.cxx | 16 +- Detectors/TRD/simulation/src/Digitizer.cxx | 12 +- .../TRD/simulation/src/TrapConfigHandler.cxx | 1 + 10 files changed, 224 insertions(+), 396 deletions(-) diff --git a/Detectors/TRD/base/include/TRDBase/CommonParam.h b/Detectors/TRD/base/include/TRDBase/CommonParam.h index 5c1f6e079a9ef..5bd46b9966d07 100644 --- a/Detectors/TRD/base/include/TRDBase/CommonParam.h +++ b/Detectors/TRD/base/include/TRDBase/CommonParam.h @@ -12,6 +12,7 @@ #define O2_TRD_COMMONPARAM_H #include "GPUCommonRtypes.h" +#include namespace o2 { @@ -26,58 +27,58 @@ class CommonParam enum { kXenon = 0, kArgon = 1 }; - CommonParam(const CommonParam& p); - CommonParam& operator=(const CommonParam& p); - ~CommonParam(); + CommonParam(const CommonParam&) = delete; + CommonParam& operator=(const CommonParam&) = delete; + ~CommonParam() = default; - static CommonParam* Instance(); - static void Terminate(); + static CommonParam* instance(); - void SetExB(int exbOn = 1) { mExBOn = exbOn; } - void SetSamplingFrequency(float freq) { mSamplingFrequency = freq; } - void SetXenon(); - void SetArgon(); + void setExB(bool flag = true) { mExBOn = flag; } + void setSamplingFrequency(float freq) { mSamplingFrequency = freq; } + void setXenon(); + void setArgon(); - bool ExBOn() const { return mExBOn; } - bool IsXenon() const { return (mGasMixture == kXenon); } - bool IsArgon() const { return (mGasMixture == kArgon); } - int GetGasMixture() const { return mGasMixture; } - float GetSamplingFrequency() const { return mSamplingFrequency; } - float GetCachedField() const { return mField; } + bool isExBOn() const { return mExBOn; } + bool isXenon() const { return (mGasMixture == kXenon); } + bool isArgon() const { return (mGasMixture == kArgon); } + int getGasMixture() const { return mGasMixture; } + float getSamplingFrequency() const { return mSamplingFrequency; } + float getCachedField() const { return mField; } // Cached magnetic field, to be called by the user before using GetDiffCoeff or GetOmegaTau bool cacheMagField(); - float GetOmegaTau(float vdrift); - bool GetDiffCoeff(float& dl, float& dt, float vdrift); + float getOmegaTau(float vdrift); + bool getDiffCoeff(float& dl, float& dt, float vdrift); - double TimeStruct(float vdrift, double xd, double z); + double timeStruct(float vdrift, double xd, double z); protected: - void SampleTimeStruct(float vdrift); + void sampleTimeStruct(float vdrift); #ifndef GPUCA_GPUCODE_DEVICE static CommonParam* fgInstance; // Instance of this class (singleton implementation) - static bool fgTerminated; // Defines if this class has already been terminated #endif - int mExBOn; // Switch for the ExB effects - double mField; // cached magnetic field - float mDiffusionT; // Transverse drift coefficient - float mDiffusionL; // Longitudinal drift coefficient - float mDiffLastVdrift; // The structures are valid for fLastVdrift (caching) + static constexpr int TIMEBIN = 38; + static constexpr int ZBIN = 11; + bool mExBOn{true}; // Switch for the ExB effects + double mField{-0.5}; // cached magnetic field + float mDiffusionT{0.}; // Transverse drift coefficient + float mDiffusionL{0.}; // Longitudinal drift coefficient + float mDiffLastVdrift{-1.}; // The structures are valid for fLastVdrift (caching) - float* mTimeStruct1; //! Time Structure of Drift Cells - float* mTimeStruct2; //! Time Structure of Drift Cells - float mVDlo; // Lower drift velocity, for interpolation - float mVDhi; // Higher drift velocity, for interpolation - float mTimeLastVdrift; // The structures are valid for fLastVdrift (caching) + std::array mTimeStruct1{}; // Time Structure of Drift Cells + std::array mTimeStruct2{}; // Time Structure of Drift Cells + float mVDlo{0.}; // Lower drift velocity, for interpolation + float mVDhi{0.}; // Higher drift velocity, for interpolation + float mTimeLastVdrift{-1.}; // The structures are valid for fLastVdrift (caching) - float mSamplingFrequency; // Sampling Frequency in MHz + float mSamplingFrequency{10.}; // Sampling Frequency in MHz - int mGasMixture; // Gas mixture: 0-Xe/C02 1-Ar/CO2. + int mGasMixture{kXenon}; // Gas mixture: 0-Xe/C02 1-Ar/CO2. private: // This is a singleton, constructor is private! - CommonParam(); + CommonParam() = default; ClassDef(CommonParam, 1); // The constant parameters common to simulation and reconstruction }; diff --git a/Detectors/TRD/base/include/TRDBase/FeeParam.h b/Detectors/TRD/base/include/TRDBase/FeeParam.h index 3d9ce1e77f078..a139a4fe3cb23 100644 --- a/Detectors/TRD/base/include/TRDBase/FeeParam.h +++ b/Detectors/TRD/base/include/TRDBase/FeeParam.h @@ -27,6 +27,7 @@ //////////////////////////////////////////////////////////////////////////// #include "DataFormatsTRD/Constants.h" +#include "TRDBase/CommonParam.h" #include #include @@ -44,13 +45,11 @@ class FeeParam { public: - FeeParam(const FeeParam& p); - virtual ~FeeParam(); - FeeParam& operator=(const FeeParam& p); - virtual void Copy(FeeParam& p) const; + ~FeeParam() = default; + FeeParam(const FeeParam&) = delete; + FeeParam& operator=(const FeeParam&) = delete; static FeeParam* instance(); // Singleton - static void terminate(); // Translation from MCM to Pad and vice versa static int getPadRowFromMCM(int irob, int imcm); @@ -72,25 +71,25 @@ class FeeParam // wiring static int getORI(int detector, int readoutboard); static int getORIinSM(int detector, int readoutboard); - // static void createORILookUpTable(); + // void createORILookUpTable(); static int getORIfromHCID(int hcid); static int getHCIDfromORI(int ori, int readoutboard); // TODO we need more info than just ori, for now readoutboard is there ... might change // tracklet simulation - bool getTracklet() const { return mgTracklet; } - static void setTracklet(bool trackletSim = true) { mgTracklet = trackletSim; } - bool getRejectMultipleTracklets() const { return mgRejectMultipleTracklets; } - static void setRejectMultipleTracklets(bool rej = true) { mgRejectMultipleTracklets = rej; } - bool getUseMisalignCorr() const { return mgUseMisalignCorr; } - static void setUseMisalignCorr(bool misalign = true) { mgUseMisalignCorr = misalign; } - bool getUseTimeOffset() const { return mgUseTimeOffset; } - static void setUseTimeOffset(bool timeOffset = true) { mgUseTimeOffset = timeOffset; } + bool getTracklet() const { return mTracklet; } + void setTracklet(bool trackletSim = true) { mTracklet = trackletSim; } + bool getRejectMultipleTracklets() const { return mRejectMultipleTracklets; } + void setRejectMultipleTracklets(bool rej = true) { mRejectMultipleTracklets = rej; } + bool getUseMisalignCorr() const { return mUseMisalignCorr; } + void setUseMisalignCorr(bool misalign = true) { mUseMisalignCorr = misalign; } + bool getUseTimeOffset() const { return mUseTimeOffset; } + void setUseTimeOffset(bool timeOffset = true) { mUseTimeOffset = timeOffset; } // Concerning raw data format int getRAWversion() const { return mRAWversion; } void setRAWversion(int rawver); - inline short padMcmLUT(int index) { return mgLUTPadNumbering[index]; } + short padMcmLUT(int index) { return mLUTPadNumbering[index]; } // configuration settings // called with special SCSN commands @@ -138,56 +137,61 @@ class FeeParam protected: static FeeParam* mgInstance; // Singleton instance - static bool mgTerminated; // Defines if this class has already been terminated - CommonParam* mCP = nullptr; // TRD common parameters class + CommonParam* mCP{CommonParam::instance()}; // TRD common parameters class - static std::vector mgLUTPadNumbering; // Lookup table mapping Pad to MCM - static bool mgLUTPadNumberingFilled; // Lookup table mapping Pad to MCM + std::array mLUTPadNumbering; // Lookup table mapping Pad to MCM - void createPad2MCMLookUpTable(); + void fillPad2MCMLookUpTable(); // Tracklet processing on/off - static bool mgTracklet; // tracklet processing - static bool mgRejectMultipleTracklets; // only accept best tracklet if found more than once - static bool mgUseMisalignCorr; // add correction for mis-alignment in y - static bool mgUseTimeOffset; // add time offset in calculation of fit sums + bool mTracklet{true}; // tracklet processing + bool mRejectMultipleTracklets{false}; // only accept best tracklet if found more than once + bool mUseMisalignCorr{false}; // add correction for mis-alignment in y + bool mUseTimeOffset{false}; // add time offset in calculation of fit sums // For raw production int mRAWversion{3}; // Raw data production version - static const int mgkMaxRAWversion = 3; // Maximum raw version number supported + const int mkMaxRAWversion = 3; // Maximum raw version number supported // geometry constants - static std::array mgZrow; // z-position of pad row edge 6x5 - static std::array mgX; // x-position for all layers - static std::array mgInvX; // inverse x-position for all layers (to remove divisions) - static std::array mgTiltingAngle; // tilting angle for every layer - static std::array mgTiltingAngleTan; // tan of tilting angle for every layer (look up table to avoid tan calculations) - static std::array mgWidthPad; // pad width for all layers - static std::array mgInvWidthPad; // inverse pad width for all layers (to remove divisions) - static float mgLengthInnerPadC0; // inner pad length C0 chamber - static float mgLengthOuterPadC0; // outer pad length C0 chamber - static std::array mgLengthInnerPadC1; // inner pad length C1 chambers - static std::array mgLengthOuterPadC1; // outer pad length C1 chambers - static float mgScalePad; // scaling factor for pad width - static float mgDriftLength; // length of the parse gaintbl Krypton_2009-01 drift region - static float mgBinDy; // bin in dy (140 um) - static int mgDyMax; // max dy for a tracklet (hard limit) - static int mgDyMin; // min dy for a tracklet (hard limit) - //std::array mgAsideLUT; // A side LUT to map ORI to stack/layer/side - //std::array mgCsideLUT; // C side LUT to map ORI to stack/layer/side + std::array mZrow{// z-position of pad row edge 6x5 + 301, 177, 53, -57, -181, + 301, 177, 53, -57, -181, + 315, 184, 53, -57, -188, + 329, 191, 53, -57, -195, + 343, 198, 53, -57, -202, + 347, 200, 53, -57, -204}; + std::array mX{300.65, 313.25, 325.85, 338.45, 351.05, 363.65}; // x-position for all layers + std::array mInvX; // inverse x-position for all layers (to remove divisions) + std::array mTiltingAngle{-2., 2., -2., 2., -2., 2.}; // tilting angle for every layer + std::array mTiltingAngleTan; // tan of tilting angle for every layer (look up table to avoid tan calculations) + std::array mWidthPad{0.635, 0.665, 0.695, 0.725, 0.755, 0.785}; // pad width for all layers + std::array mInvWidthPad; // inverse pad width for all layers (to remove divisions) + float mLengthInnerPadC0{9.f}; // inner pad length C0 chamber + float mLengthOuterPadC0{8.f}; // outer pad length C0 chamber + std::array mLengthInnerPadC1{7.5, 7.5, 8.0, 8.5, 9.0, 9.0}; // inner pad length C1 chambers + std::array mLengthOuterPadC1{7.5, 7.5, 7.5, 7.5, 7.5, 8.5}; // outer pad length C1 chambers + float mScalePad{256. * 32.}; // scaling factor for pad width + float mDriftLength{3.}; // length of the parse gaintbl Krypton_2009-01 drift region + // WARNING: This values for dY are valid for Run 1+2 format only + float mBinDy{140e-4}; // bin in dy (140 um) + int mDyMax{63}; // max dy for a tracklet (hard limit) + int mDyMin{-64}; // min dy for a tracklet (hard limit) + //std::array mAsideLUT; // A side LUT to map ORI to stack/layer/side + //std::array mCsideLUT; // C side LUT to map ORI to stack/layer/side // settings - float mMagField; // magnetic field - float mOmegaTau; // omega tau, i.e. tan(Lorentz angle) - float mPtMin; // min. pt for deflection cut - float mInvPtMin; // min. pt for deflection cut (Inverted to remove division) - int mNtimebins; // drift time in units of timebins << 5n - unsigned int mScaleQ0; // scale factor for accumulated charge Q0 - unsigned int mScaleQ1; // scale factor for accumulated charge Q1 - bool mPidTracklengthCorr; // enable tracklet length correction - bool mTiltCorr; // enable tilt correction - bool mPidGainCorr; // enable MCM gain correction factor for PID + float mMagField{0.f}; // magnetic field + float mOmegaTau{0.f}; // omega tau, i.e. tan(Lorentz angle) + float mPtMin{.1f}; // min. pt for deflection cut + float mInvPtMin{1.f / mPtMin}; // min. pt for deflection cut (Inverted to remove division) + int mNtimebins{20 << 5}; // drift time in units of timebins << 5n + unsigned int mScaleQ0{0}; // scale factor for accumulated charge Q0 + unsigned int mScaleQ1{0}; // scale factor for accumulated charge Q1 + bool mPidTracklengthCorr{false}; // enable tracklet length correction + bool mTiltCorr{false}; // enable tilt correction + bool mPidGainCorr{false}; // enable MCM gain correction factor for PID private: FeeParam(); diff --git a/Detectors/TRD/base/src/CommonParam.cxx b/Detectors/TRD/base/src/CommonParam.cxx index c8fe591d0536d..aa3888300ad62 100644 --- a/Detectors/TRD/base/src/CommonParam.cxx +++ b/Detectors/TRD/base/src/CommonParam.cxx @@ -12,7 +12,7 @@ // // // Class containing parameters common to simulation and reconstruction // // // -// Request an instance with AliTRDCommonParam::Instance() // +// Request an instance with CommonParam::instance() // // Then request the needed values // // // /////////////////////////////////////////////////////////////////////////////// @@ -31,20 +31,15 @@ using namespace o2::trd; ClassImp(CommonParam); CommonParam* CommonParam::fgInstance = nullptr; -bool CommonParam::fgTerminated = false; //_ singleton implementation __________________________________________________ -CommonParam* CommonParam::Instance() +CommonParam* CommonParam::instance() { // // Singleton implementation // Returns an instance of this class, it is created if neccessary // - if (fgTerminated != false) { - return nullptr; - } - if (fgInstance == nullptr) { fgInstance = new CommonParam(); } @@ -52,59 +47,6 @@ CommonParam* CommonParam::Instance() return fgInstance; } -//_____________________________________________________________________________ -void CommonParam::Terminate() -{ - // - // Singleton implementation - // Deletes the instance of this class and sets the terminated flag, - // instances cannot be requested anymore - // This function can be called several times. - // - - fgTerminated = true; - - if (fgInstance != nullptr) { - delete fgInstance; - fgInstance = nullptr; - } -} - -//_____________________________________________________________________________ -CommonParam::CommonParam() - : mExBOn(true), - mDiffusionT(0.0), - mDiffusionL(0.0), - mDiffLastVdrift(-1.0), - mTimeStruct1(nullptr), - mTimeStruct2(nullptr), - mVDlo(0.0), - mVDhi(0.0), - mTimeLastVdrift(-1.0), - mSamplingFrequency(10.0), - mGasMixture(kXenon), - mField(-0.5) -{ - // - // Default constructor - // -} - -//_____________________________________________________________________________ -CommonParam::~CommonParam() -{ - // - // Destructor - // - if (mTimeStruct1) { - delete[] mTimeStruct1; - mTimeStruct1 = nullptr; - } - if (mTimeStruct2) { - delete[] mTimeStruct2; - mTimeStruct2 = nullptr; - } -} //_____________________________________________________________________________ bool CommonParam::cacheMagField() @@ -120,7 +62,7 @@ bool CommonParam::cacheMagField() } //_____________________________________________________________________________ -float CommonParam::GetOmegaTau(float vdrift) +float CommonParam::getOmegaTau(float vdrift) { /* // @@ -176,7 +118,7 @@ float CommonParam::GetOmegaTau(float vdrift) } //_____________________________________________________________________________ -bool CommonParam::GetDiffCoeff(float& dl, float& dt, float vdrift) +bool CommonParam::getDiffCoeff(float& dl, float& dt, float vdrift) { // // Calculates the diffusion coefficients in longitudinal
and @@ -191,7 +133,7 @@ bool CommonParam::GetDiffCoeff(float& dl, float& dt, float vdrift) } mDiffLastVdrift = vdrift; - if (IsXenon()) { + if (isXenon()) { // // Vd and B-field dependent diffusion and Lorentz angle // @@ -224,7 +166,7 @@ bool CommonParam::GetDiffCoeff(float& dl, float& dt, float vdrift) dl = mDiffusionL; dt = mDiffusionT; return true; - } else if (IsArgon()) { + } else if (isArgon()) { // // Diffusion constants and Lorentz angle only for B = 0.5T // @@ -239,7 +181,7 @@ bool CommonParam::GetDiffCoeff(float& dl, float& dt, float vdrift) } //_____________________________________________________________________________ -double CommonParam::TimeStruct(float vdrift, double dist, double z) +double CommonParam::timeStruct(float vdrift, double dist, double z) { // // Applies the time structure of the drift cells (by C.Lippmann). @@ -259,7 +201,7 @@ double CommonParam::TimeStruct(float vdrift, double dist, double z) // and fTimeStruct2, calculated for the two mentioned drift velocities. // - SampleTimeStruct(vdrift); + sampleTimeStruct(vdrift); // Indices: int r1 = (int)(10 * dist); @@ -318,7 +260,7 @@ double CommonParam::TimeStruct(float vdrift, double dist, double z) } //_____________________________________________________________________________ -void CommonParam::SampleTimeStruct(float vdrift) +void CommonParam::sampleTimeStruct(float vdrift) { // // Samples the timing structure of a drift cell @@ -350,11 +292,8 @@ void CommonParam::SampleTimeStruct(float vdrift) vdrift = fVDsmp[7]; } - const int ktimebin = 38; - const int kZbin = 11; - // Garfield simulation at UD = -1500V; vd = 1.032cm/microsec, = 525V/cm - float time1500[ktimebin][kZbin] = { + float time1500[TIMEBIN][ZBIN] = { {0.09170, 0.09205, 0.09306, 0.09475, 0.09716, 0.10035, 0.10445, 0.10993, 0.11838, 0.13986, 0.37858}, {0.06588, 0.06626, 0.06739, 0.06926, 0.07186, 0.07524, 0.07951, 0.08515, 0.09381, 0.11601, 0.35673}, {0.03946, 0.04003, 0.04171, 0.04435, 0.04780, 0.05193, 0.05680, 0.06306, 0.07290, 0.09873, 0.34748}, @@ -395,7 +334,7 @@ void CommonParam::SampleTimeStruct(float vdrift) {2.94239, 2.94469, 2.95221, 2.96625, 2.99345, 3.07747, 3.04266, 3.02545, 3.03051, 3.07118, 3.33555}}; // Garfield simulation at UD = -1600V; vd = 1.158cm/microsec, = 558V/cm - float time1600[ktimebin][kZbin] = { + float time1600[TIMEBIN][ZBIN] = { {0.09169, 0.09203, 0.09305, 0.09473, 0.09714, 0.10032, 0.10441, 0.10990, 0.11835, 0.13986, 0.37845}, {0.06589, 0.06626, 0.06738, 0.06924, 0.07184, 0.07521, 0.07947, 0.08512, 0.09379, 0.11603, 0.35648}, {0.03947, 0.04003, 0.04171, 0.04434, 0.04778, 0.05190, 0.05678, 0.06304, 0.07292, 0.09876, 0.34759}, @@ -436,7 +375,7 @@ void CommonParam::SampleTimeStruct(float vdrift) {2.63456, 2.63660, 2.64304, 2.65555, 2.67938, 2.75739, 2.72629, 2.71064, 2.71688, 2.75671, 3.01886}}; // Garfield simulation at UD = -1700V; vd = 1.299cm/microsec, = 590V/cm - float time1700[ktimebin][kZbin] = { + float time1700[TIMEBIN][ZBIN] = { {0.09167, 0.09201, 0.09302, 0.09471, 0.09712, 0.10029, 0.10438, 0.10986, 0.11832, 0.13986, 0.37824}, {0.06591, 0.06626, 0.06736, 0.06923, 0.07183, 0.07519, 0.07944, 0.08511, 0.09378, 0.11603, 0.35625}, {0.03946, 0.04003, 0.04170, 0.04433, 0.04777, 0.05189, 0.05676, 0.06301, 0.07291, 0.09880, 0.34724}, @@ -477,7 +416,7 @@ void CommonParam::SampleTimeStruct(float vdrift) {2.36153, 2.36806, 2.36889, 2.37985, 2.40092, 2.47828, 2.44381, 2.43099, 2.43819, 2.47750, 2.73779}}; // Garfield simulation at UD = -1800V; vd = 1.450cm/microsec, = 623V/cm - float time1800[ktimebin][kZbin] = { + float time1800[TIMEBIN][ZBIN] = { {0.09166, 0.09199, 0.09300, 0.09470, 0.09709, 0.10026, 0.10434, 0.10983, 0.11831, 0.13987, 0.37802}, {0.06585, 0.06623, 0.06735, 0.06921, 0.07180, 0.07520, 0.07941, 0.08507, 0.09376, 0.11604, 0.35624}, {0.03945, 0.04004, 0.04169, 0.04432, 0.04776, 0.05187, 0.05674, 0.06300, 0.07290, 0.09884, 0.34704}, @@ -518,7 +457,7 @@ void CommonParam::SampleTimeStruct(float vdrift) {2.12726, 2.12869, 2.13360, 2.14425, 2.16160, 2.22872, 2.20118, 2.19078, 2.19876, 2.23416, 2.50007}}; // Garfield simulation at UD = -1900V; vd = 1.610cm/microsec, = 655V/cm - float time1900[ktimebin][kZbin] = { + float time1900[TIMEBIN][ZBIN] = { {0.09166, 0.09198, 0.09298, 0.09467, 0.09707, 0.10023, 0.10431, 0.10980, 0.11828, 0.13988, 0.37789}, {0.06584, 0.06622, 0.06735, 0.06920, 0.07179, 0.07514, 0.07938, 0.08505, 0.09374, 0.11606, 0.35599}, {0.03945, 0.04002, 0.04169, 0.04432, 0.04775, 0.05185, 0.05672, 0.06298, 0.07290, 0.09888, 0.34695}, @@ -559,7 +498,7 @@ void CommonParam::SampleTimeStruct(float vdrift) {1.92700, 1.92783, 1.93197, 1.95049, 1.95649, 2.01668, 1.99217, 1.98486, 1.99352, 2.03143, 2.29358}}; // Garfield simulation at UD = -2000V; vd = 1.783cm/microsec, = 688V/cm - float time2000[ktimebin][kZbin] = { + float time2000[TIMEBIN][ZBIN] = { {0.09176, 0.09196, 0.09296, 0.09465, 0.09704, 0.10020, 0.10427, 0.10977, 0.11825, 0.13988, 0.37774}, {0.06583, 0.06620, 0.06735, 0.06918, 0.07177, 0.07513, 0.07936, 0.08503, 0.09372, 0.11606, 0.35586}, {0.03944, 0.04001, 0.04170, 0.04431, 0.04774, 0.05184, 0.05670, 0.06296, 0.07291, 0.09893, 0.34680}, @@ -600,7 +539,7 @@ void CommonParam::SampleTimeStruct(float vdrift) {1.75054, 1.75221, 1.75527, 1.76306, 1.77662, 1.83428, 1.81006, 1.81173, 1.81345, 1.85076, 2.10289}}; // Garfield simulation at UD = -2100V; vd = 1.959cm/microsec, = 720V/cm - float time2100[ktimebin][kZbin] = { + float time2100[TIMEBIN][ZBIN] = { {0.09160, 0.09194, 0.09294, 0.09462, 0.09701, 0.10017, 0.10424, 0.10974, 0.11823, 0.13988, 0.37762}, {0.06585, 0.06619, 0.06731, 0.06916, 0.07174, 0.07509, 0.07933, 0.08500, 0.09370, 0.11609, 0.35565}, {0.03960, 0.04001, 0.04171, 0.04430, 0.04774, 0.05182, 0.05668, 0.06294, 0.07291, 0.09896, 0.34676}, @@ -641,7 +580,7 @@ void CommonParam::SampleTimeStruct(float vdrift) {1.60368, 1.60469, 1.60779, 1.61373, 1.62596, 1.67738, 1.65651, 1.65249, 1.66290, 1.69936, 1.95959}}; // Garfield simulation at UD = -2200V; vd = 2.134cm/microsec, = 753V/cm - float time2200[ktimebin][kZbin] = { + float time2200[TIMEBIN][ZBIN] = { {0.09162, 0.09194, 0.09292, 0.09460, 0.09702, 0.10014, 0.10421, 0.10971, 0.11820, 0.13990, 0.37745}, {0.06581, 0.06618, 0.06730, 0.06915, 0.07173, 0.07507, 0.07931, 0.08497, 0.09368, 0.11609, 0.35560}, {0.03947, 0.04001, 0.04167, 0.04429, 0.04772, 0.05183, 0.05667, 0.06293, 0.07292, 0.09900, 0.34673}, @@ -681,50 +620,41 @@ void CommonParam::SampleTimeStruct(float vdrift) {1.43524, 1.43533, 1.43796, 1.44310, 1.45371, 1.49305, 1.48224, 1.47941, 1.49034, 1.52601, 1.78552}, {1.48122, 1.48219, 1.48482, 1.48991, 1.50030, 1.53991, 1.52898, 1.52653, 1.53653, 1.57282, 1.82386}}; - if (!mTimeStruct1) { - mTimeStruct1 = new float[ktimebin * kZbin]; - } - if (!mTimeStruct2) { - mTimeStruct2 = new float[ktimebin * kZbin]; - } - memset(mTimeStruct1, 0, ktimebin * kZbin * sizeof(float)); - memset(mTimeStruct2, 0, ktimebin * kZbin * sizeof(float)); - - for (int ctrt = 0; ctrt < ktimebin; ctrt++) { - for (int ctrz = 0; ctrz < kZbin; ctrz++) { + for (int ctrt = 0; ctrt < TIMEBIN; ctrt++) { + for (int ctrz = 0; ctrz < ZBIN; ctrz++) { if (vdrift > fVDsmp[6]) { - mTimeStruct1[ctrt + ctrz * ktimebin] = time2100[ctrt][ctrz]; - mTimeStruct2[ctrt + ctrz * ktimebin] = time2200[ctrt][ctrz]; + mTimeStruct1[ctrt + ctrz * TIMEBIN] = time2100[ctrt][ctrz]; + mTimeStruct2[ctrt + ctrz * TIMEBIN] = time2200[ctrt][ctrz]; mVDlo = fVDsmp[6]; mVDhi = fVDsmp[7]; } else if (vdrift > fVDsmp[5]) { - mTimeStruct1[ctrt + ctrz * ktimebin] = time2000[ctrt][ctrz]; - mTimeStruct2[ctrt + ctrz * ktimebin] = time2100[ctrt][ctrz]; + mTimeStruct1[ctrt + ctrz * TIMEBIN] = time2000[ctrt][ctrz]; + mTimeStruct2[ctrt + ctrz * TIMEBIN] = time2100[ctrt][ctrz]; mVDlo = fVDsmp[5]; mVDhi = fVDsmp[6]; } else if (vdrift > fVDsmp[4]) { - mTimeStruct1[ctrt + ctrz * ktimebin] = time1900[ctrt][ctrz]; - mTimeStruct2[ctrt + ctrz * ktimebin] = time2000[ctrt][ctrz]; + mTimeStruct1[ctrt + ctrz * TIMEBIN] = time1900[ctrt][ctrz]; + mTimeStruct2[ctrt + ctrz * TIMEBIN] = time2000[ctrt][ctrz]; mVDlo = fVDsmp[4]; mVDhi = fVDsmp[5]; } else if (vdrift > fVDsmp[3]) { - mTimeStruct1[ctrt + ctrz * ktimebin] = time1800[ctrt][ctrz]; - mTimeStruct2[ctrt + ctrz * ktimebin] = time1900[ctrt][ctrz]; + mTimeStruct1[ctrt + ctrz * TIMEBIN] = time1800[ctrt][ctrz]; + mTimeStruct2[ctrt + ctrz * TIMEBIN] = time1900[ctrt][ctrz]; mVDlo = fVDsmp[3]; mVDhi = fVDsmp[4]; } else if (vdrift > fVDsmp[2]) { - mTimeStruct1[ctrt + ctrz * ktimebin] = time1700[ctrt][ctrz]; - mTimeStruct2[ctrt + ctrz * ktimebin] = time1800[ctrt][ctrz]; + mTimeStruct1[ctrt + ctrz * TIMEBIN] = time1700[ctrt][ctrz]; + mTimeStruct2[ctrt + ctrz * TIMEBIN] = time1800[ctrt][ctrz]; mVDlo = fVDsmp[2]; mVDhi = fVDsmp[3]; } else if (vdrift > fVDsmp[1]) { - mTimeStruct1[ctrt + ctrz * ktimebin] = time1600[ctrt][ctrz]; - mTimeStruct2[ctrt + ctrz * ktimebin] = time1700[ctrt][ctrz]; + mTimeStruct1[ctrt + ctrz * TIMEBIN] = time1600[ctrt][ctrz]; + mTimeStruct2[ctrt + ctrz * TIMEBIN] = time1700[ctrt][ctrz]; mVDlo = fVDsmp[1]; mVDhi = fVDsmp[2]; } else if (vdrift > (fVDsmp[0] - 1.0e-5)) { - mTimeStruct1[ctrt + ctrz * ktimebin] = time1500[ctrt][ctrz]; - mTimeStruct2[ctrt + ctrz * ktimebin] = time1600[ctrt][ctrz]; + mTimeStruct1[ctrt + ctrz * TIMEBIN] = time1500[ctrt][ctrz]; + mTimeStruct2[ctrt + ctrz * TIMEBIN] = time1600[ctrt][ctrz]; mVDlo = fVDsmp[0]; mVDhi = fVDsmp[1]; } @@ -732,13 +662,13 @@ void CommonParam::SampleTimeStruct(float vdrift) } } -void CommonParam::SetXenon() +void CommonParam::setXenon() { mGasMixture = kXenon; SimParam::Instance()->ReInit(); } -void CommonParam::SetArgon() +void CommonParam::setArgon() { mGasMixture = kArgon; SimParam::Instance()->ReInit(); diff --git a/Detectors/TRD/base/src/DiffAndTimeStructEstimator.cxx b/Detectors/TRD/base/src/DiffAndTimeStructEstimator.cxx index 5c9a131050a22..4ed62572f8470 100644 --- a/Detectors/TRD/base/src/DiffAndTimeStructEstimator.cxx +++ b/Detectors/TRD/base/src/DiffAndTimeStructEstimator.cxx @@ -531,7 +531,7 @@ bool DiffusionAndTimeStructEstimator::GetDiffCoeff(float& dl, float& dt, float v } mDiffLastVdrift = vdrift; - if (CommonParam::Instance()->IsXenon()) { + if (CommonParam::instance()->isXenon()) { // // Vd and B-field dependent diffusion and Lorentz angle // @@ -541,7 +541,7 @@ bool DiffusionAndTimeStructEstimator::GetDiffCoeff(float& dl, float& dt, float v // If looking at compatibility with AliRoot: // ibL and ibT are calculated the same way so, just define ib = ibL = ibT - int ib = ((int)(10 * (CommonParam::Instance()->GetCachedField() - 0.15))); + int ib = ((int)(10 * (CommonParam::instance()->getCachedField() - 0.15))); ib = std::max(0, ib); ib = std::min(kNb - 1, ib); @@ -564,7 +564,7 @@ bool DiffusionAndTimeStructEstimator::GetDiffCoeff(float& dl, float& dt, float v dl = mDiffusionL; dt = mDiffusionT; return true; - } else if (CommonParam::Instance()->IsArgon()) { + } else if (CommonParam::instance()->isArgon()) { // // Diffusion constants and Lorentz angle only for B = 0.5T // diff --git a/Detectors/TRD/base/src/FeeParam.cxx b/Detectors/TRD/base/src/FeeParam.cxx index b3fb584956711..9369ee8931168 100644 --- a/Detectors/TRD/base/src/FeeParam.cxx +++ b/Detectors/TRD/base/src/FeeParam.cxx @@ -39,8 +39,10 @@ #include "TRDBase/Geometry.h" #include "TRDBase/PadPlane.h" #include "TRDBase/FeeParam.h" -#include "TRDBase/CommonParam.h" -//#include "DataFormatsTRD/Constants.h" + +#ifdef WITH_OPENMP +#include +#endif using namespace std; using namespace o2::trd; @@ -49,38 +51,6 @@ using namespace o2::trd::constants; //_____________________________________________________________________________ FeeParam* FeeParam::mgInstance = nullptr; -bool FeeParam::mgTerminated = false; -bool FeeParam::mgTracklet = true; -bool FeeParam::mgRejectMultipleTracklets = false; -bool FeeParam::mgUseMisalignCorr = false; -bool FeeParam::mgUseTimeOffset = false; -bool FeeParam::mgLUTPadNumberingFilled = false; -std::vector FeeParam::mgLUTPadNumbering; - -// definition of geometry constants -std::array FeeParam::mgZrow = { - 301, 177, 53, -57, -181, - 301, 177, 53, -57, -181, - 315, 184, 53, -57, -188, - 329, 191, 53, -57, -195, - 343, 198, 53, -57, -202, - 347, 200, 53, -57, -204}; -std::array FeeParam::mgX = {300.65, 313.25, 325.85, 338.45, 351.05, 363.65}; -std::array FeeParam::mgTiltingAngle = {-2., 2., -2., 2., -2., 2.}; -int FeeParam::mgDyMax = 63; -int FeeParam::mgDyMin = -64; -float FeeParam::mgBinDy = 140e-4; -std::array FeeParam::mgWidthPad = {0.635, 0.665, 0.695, 0.725, 0.755, 0.785}; -std::array FeeParam::mgLengthInnerPadC1 = {7.5, 7.5, 8.0, 8.5, 9.0, 9.0}; -std::array FeeParam::mgLengthOuterPadC1 = {7.5, 7.5, 7.5, 7.5, 7.5, 8.5}; -std::array FeeParam::mgInvX; -std::array FeeParam::mgTiltingAngleTan; -std::array FeeParam::mgInvWidthPad; - -float FeeParam::mgLengthInnerPadC0 = 9.0; -float FeeParam::mgLengthOuterPadC0 = 8.0; -float FeeParam::mgScalePad = 256. * 32.; -float FeeParam::mgDriftLength = 3.; //_____________________________________________________________________________ FeeParam* FeeParam::instance() @@ -88,111 +58,39 @@ FeeParam* FeeParam::instance() // // Instance constructor // - if (mgTerminated != false) { - return nullptr; - } +#ifdef WITH_OPENMP +#pragma omp critical +#endif + { // start omp critical block + if (mgInstance == nullptr) { + mgInstance = new FeeParam(); + } - if (mgInstance == nullptr) { - mgInstance = new FeeParam(); - } - // this is moved here to remove recursive calls induced by the line 2 above this one. - if (!mgLUTPadNumberingFilled) { - mgInstance->createPad2MCMLookUpTable(); - } - return mgInstance; + return mgInstance; + } // end omp critical block } -//_____________________________________________________________________________ -void FeeParam::terminate() -{ - // - // Terminate the class and release memory - // - - mgTerminated = true; - - if (mgInstance != nullptr) { - delete mgInstance; - mgInstance = nullptr; - } -} //_____________________________________________________________________________ -FeeParam::FeeParam() : mMagField(0.), - mOmegaTau(0.), - mPtMin(0.1), - mNtimebins(20 << 5), - mScaleQ0(0), - mScaleQ1(0), - mPidTracklengthCorr(false), - mTiltCorr(false), - mPidGainCorr(false) +FeeParam::FeeParam() { // // Default constructor // - mCP = CommonParam::Instance(); // These variables are used internally in the class to elliminate divisions. // putting them at the top was messy. int j = 0; - std::for_each(mgInvX.begin(), mgInvX.end(), [&j](float& x) { x = 1. / mgX[j]; }); + std::for_each(mInvX.begin(), mInvX.end(), [&](float& x) { x = 1. / mX[j]; }); j = 0; - std::for_each(mgInvWidthPad.begin(), mgInvWidthPad.end(), [&j](float& x) { x = 1. / mgWidthPad[j]; }); + std::for_each(mInvWidthPad.begin(), mInvWidthPad.end(), [&](float& x) { x = 1. / mWidthPad[j]; }); j = 0; - std::for_each(mgTiltingAngleTan.begin(), mgTiltingAngleTan.end(), [&j](float& x) { x = std::tan(mgTiltingAngle[j] * M_PI / 180.0); }); + std::for_each(mTiltingAngleTan.begin(), mTiltingAngleTan.end(), [&](float& x) { x = std::tan(mTiltingAngle[j] * M_PI / 180.0); }); - mInvPtMin = 1 / mPtMin; + fillPad2MCMLookUpTable(); } -//_____________________________________________________________________________ -//FeeParam::FeeParam(TRootIoCtor*) -//{ -// -// IO constructor -// -//} -//_____________________________________________________________________________ -FeeParam::FeeParam(const FeeParam& p) -{ - // - // FeeParam copy constructor - // - mRAWversion = p.mRAWversion; - mCP = p.mCP; - if (!mgLUTPadNumberingFilled) { - mgInstance->createPad2MCMLookUpTable(); - } -} - -//_____________________________________________________________________________ -FeeParam::~FeeParam() = default; - -//_____________________________________________________________________________ -FeeParam& FeeParam::operator=(const FeeParam& p) -{ - // - // Assignment operator - // - - if (this != &p) { - ((FeeParam&)p).Copy(*this); - } - - return *this; -} - -//_____________________________________________________________________________ -void FeeParam::Copy(FeeParam& p) const -{ - // - // Copy function - // - - p.mCP = mCP; - p.mRAWversion = mRAWversion; -} //_____________________________________________________________________________ int FeeParam::getPadRowFromMCM(int irob, int imcm) @@ -367,7 +265,7 @@ int FeeParam::extAliToAli(unsigned int dest, unsigned short linkpair, unsigned s unsigned int cmA = 0, cmB = 0; // Chipmask for each A and B side // Default chipmask for 4 linkpairs (each bit correponds each alice-mcm) - static const unsigned int gkChipmaskDefLp[4] = {0x1FFFF, 0x1FFFF, 0x3FFFF, 0x1FFFF}; + const unsigned int gkChipmaskDefLp[4] = {0x1FFFF, 0x1FFFF, 0x3FFFF, 0x1FFFF}; rob = dest >> 7; // Extract ROB pattern from dest. mcm = dest & 0x07F; // Extract MCM pattern from dest. @@ -471,7 +369,7 @@ short FeeParam::getRobAB(unsigned short robsel, unsigned short linkpair) return 0; } -/* +/* void FeeParam::createORILookUpTable() { int ori; @@ -482,10 +380,10 @@ void FeeParam::createORILookUpTable() for(int trdlayer=5;trdlayer>=0;trdlayer++) { - ori=trdstack*12 + (5-trdlayer + side*6) +trdlayer/6 + side; - mgAsideLUT[ori]= (trdstack<<8) + (trdlayer<<4) + side; // A side LUT to map ORI to stack/layer/side + ori=trdstack*12 + (5-trdlayer + side*6) +trdlayer/6 + side; + mAsideLUT[ori]= (trdstack<<8) + (trdlayer<<4) + side; // A side LUT to map ORI to stack/layer/side if(ori==29) break; - + } if(ori==29) break; } @@ -501,7 +399,7 @@ void FeeParam::createORILookUpTable() ori = (4-trdstack)*12 + (5-trdlayer + side*5) +trdlayer/6 + side; int newside; if(ori >=24) newside=1; else newside=side; // a hack as I am not typing this all out. - mgCsideLUT[ori]= (trdstack<<8) + (trdlayer<<4) + newside; // A side LUT to map ORI to stack/layer/side + mCsideLUT[ori]= (trdstack<<8) + (trdlayer<<4) + newside; // A side LUT to map ORI to stack/layer/side if(ori==29) break; } if(ori==29) break; @@ -591,10 +489,10 @@ void FeeParam::setRAWversion(int rawver) { // // Set raw data version (major number only) - // Maximum available number is preset in mgkMaxRAWversion + // Maximum available number is preset in mkMaxRAWversion // - if (rawver >= 0 && rawver <= mgkMaxRAWversion) { + if (rawver >= 0 && rawver <= mkMaxRAWversion) { mRAWversion = rawver; } else { LOG(error) << "Raw version is out of range: " << rawver; @@ -605,24 +503,18 @@ void FeeParam::setRAWversion(int rawver) * This was originally moved here from arrayADC, signalADC etc. We now longer use those classes * so removing this for now as its crashing. */ -void FeeParam::createPad2MCMLookUpTable() +void FeeParam::fillPad2MCMLookUpTable() { // // Initializes the Look Up Table to relate // pad numbering and mcm channel numbering // - if (!mgLUTPadNumberingFilled) { - - LOG(debug) << " resizing lookup array to : " << NCOLUMN << " elements previously : " << mgLUTPadNumbering.size(); - mgLUTPadNumbering.resize(NCOLUMN); - memset(&mgLUTPadNumbering[0], 0, sizeof(mgLUTPadNumbering[0]) * NCOLUMN); - for (int mcm = 0; mcm < 8; mcm++) { - int lowerlimit = 0 + mcm * 18; - int upperlimit = 18 + mcm * 18; - int shiftposition = 1 + 3 * mcm; - for (int index = lowerlimit; index < upperlimit; index++) { - mgLUTPadNumbering[index] = index + shiftposition; - } + for (int mcm = 0; mcm < NMCMROBINCOL * 2; mcm++) { + int lowerlimit = mcm * NCOLMCM; + int upperlimit = NCOLMCM + mcm * NCOLMCM; + int shiftposition = 1 + 3 * mcm; + for (int index = lowerlimit; index < upperlimit; index++) { + mLUTPadNumbering[index] = index + shiftposition; } } } @@ -634,17 +526,17 @@ int FeeParam::getDyCorrection(int det, int rob, int mcm) const int layer = det % NLAYER; - float dyTilt = (mgDriftLength * std::tan(mgTiltingAngle[layer] * M_PI / 180.) * - getLocalZ(det, rob, mcm) * mgInvX[layer]); + float dyTilt = (mDriftLength * std::tan(mTiltingAngle[layer] * M_PI / 180.) * + getLocalZ(det, rob, mcm) * mInvX[layer]); // calculate Lorentz correction - float dyCorr = -mOmegaTau * mgDriftLength; + float dyCorr = -mOmegaTau * mDriftLength; if (mTiltCorr) { dyCorr += dyTilt; // add tilt correction } - return (int)TMath::Nint(dyCorr * mgScalePad * mgInvWidthPad[layer]); + return (int)TMath::Nint(dyCorr * mScalePad * mInvWidthPad[layer]); } void FeeParam::getDyRange(int det, int rob, int mcm, int ch, @@ -652,8 +544,8 @@ void FeeParam::getDyRange(int det, int rob, int mcm, int ch, { // calculate the deflection range in which tracklets are accepted - dyMinInt = mgDyMin; - dyMaxInt = mgDyMax; + dyMinInt = mDyMin; + dyMaxInt = mDyMax; // deflection cut is considered for |B| > 0.1 T only if (std::abs(mMagField) < 0.1) { @@ -669,26 +561,26 @@ void FeeParam::getDyRange(int det, int rob, int mcm, int ch, if (maxDeflTemp < std::cos(phi)) { float maxDeflAngle = std::asin(maxDeflTemp); - float dyMin = (mgDriftLength * + float dyMin = (mDriftLength * std::tan(phi - maxDeflAngle)); - dyMinInt = int(dyMin / mgBinDy); + dyMinInt = int(dyMin / mBinDy); // clipping to allowed range - if (dyMinInt < mgDyMin) { - dyMinInt = mgDyMin; - } else if (dyMinInt > mgDyMax) { - dyMinInt = mgDyMax; + if (dyMinInt < mDyMin) { + dyMinInt = mDyMin; + } else if (dyMinInt > mDyMax) { + dyMinInt = mDyMax; } - float dyMax = (mgDriftLength * + float dyMax = (mDriftLength * std::tan(phi + maxDeflAngle)); - dyMaxInt = int(dyMax / mgBinDy); + dyMaxInt = int(dyMax / mBinDy); // clipping to allowed range - if (dyMaxInt > mgDyMax) { - dyMaxInt = mgDyMax; - } else if (dyMaxInt < mgDyMin) { - dyMaxInt = mgDyMin; + if (dyMaxInt > mDyMax) { + dyMaxInt = mDyMax; + } else if (dyMaxInt < mDyMin) { + dyMaxInt = mDyMin; } } else if (maxDeflTemp < 0.) { // this must not happen @@ -700,8 +592,8 @@ void FeeParam::getDyRange(int det, int rob, int mcm, int ch, if ((dyMaxInt - dyMinInt) <= 0) { LOG(debug) << "strange dy range: [" << dyMinInt << "," << dyMaxInt << "], using max range now"; - dyMaxInt = mgDyMax; - dyMinInt = mgDyMin; + dyMaxInt = mDyMax; + dyMinInt = mDyMin; } } @@ -712,7 +604,7 @@ float FeeParam::getElongation(int det, int rob, int mcm, int ch) const int layer = det % NLAYER; - float elongation = std::abs(getDist(det, rob, mcm, ch) * mgInvX[layer]); + float elongation = std::abs(getDist(det, rob, mcm, ch) * mInvX[layer]); // sanity check if (elongation < 0.001) { @@ -752,7 +644,7 @@ float FeeParam::getX(int det, int /* rob */, int /* mcm */) const // return the distance to the beam axis in x-direction int layer = det % NLAYER; - return mgX[layer]; + return mX[layer]; } float FeeParam::getLocalY(int det, int rob, int mcm, int ch) const @@ -762,7 +654,7 @@ float FeeParam::getLocalY(int det, int rob, int mcm, int ch) const int layer = det % NLAYER; // calculate the pad position as in the TRAP float ypos = (-4 + 1 + (rob & 0x1) * 4 + (mcm & 0x3)) * 18 - ch - 0.5; // y position in bins of pad widths - return ypos * mgWidthPad[layer]; + return ypos * mWidthPad[layer]; } float FeeParam::getLocalZ(int det, int rob, int mcm) const @@ -775,19 +667,19 @@ float FeeParam::getLocalZ(int det, int rob, int mcm) const if (stack == 2) { if (row == 0) { - return (mgZrow[layer * NLAYER + stack] - 0.5 * mgLengthOuterPadC0); + return (mZrow[layer * NLAYER + stack] - 0.5 * mLengthOuterPadC0); } else if (row == 11) { - return (mgZrow[layer * NLAYER + stack] - 1.5 * mgLengthOuterPadC0 - (row - 1) * mgLengthInnerPadC0); + return (mZrow[layer * NLAYER + stack] - 1.5 * mLengthOuterPadC0 - (row - 1) * mLengthInnerPadC0); } else { - return (mgZrow[layer * NLAYER + stack] - mgLengthOuterPadC0 - (row - 0.5) * mgLengthInnerPadC0); + return (mZrow[layer * NLAYER + stack] - mLengthOuterPadC0 - (row - 0.5) * mLengthInnerPadC0); } } else { if (row == 0) { - return (mgZrow[layer * NLAYER + stack] - 0.5 * mgLengthOuterPadC1[layer]); + return (mZrow[layer * NLAYER + stack] - 0.5 * mLengthOuterPadC1[layer]); } else if (row == 15) { - return (mgZrow[layer * NLAYER + stack] - 1.5 * mgLengthOuterPadC1[layer] - (row - 1) * mgLengthInnerPadC1[layer]); + return (mZrow[layer * NLAYER + stack] - 1.5 * mLengthOuterPadC1[layer] - (row - 1) * mLengthInnerPadC1[layer]); } else { - return (mgZrow[layer * NLAYER + stack] - mgLengthOuterPadC1[layer] - (row - 0.5) * mgLengthInnerPadC1[layer]); + return (mZrow[layer * NLAYER + stack] - mLengthOuterPadC1[layer] - (row - 0.5) * mLengthInnerPadC1[layer]); } } } diff --git a/Detectors/TRD/base/src/SimParam.cxx b/Detectors/TRD/base/src/SimParam.cxx index 83223d8af1b23..1f62efea8076a 100644 --- a/Detectors/TRD/base/src/SimParam.cxx +++ b/Detectors/TRD/base/src/SimParam.cxx @@ -171,7 +171,7 @@ void SimParam::ReInit() // Reinitializes the parameter class after a change // - if (CommonParam::Instance()->IsXenon()) { + if (CommonParam::instance()->isXenon()) { // The range and the binwidth for the sampled TRF mTRFbin = 200; // Start 0.2 mus before the signal @@ -180,7 +180,7 @@ void SimParam::ReInit() mTRFhi = 3.58; // Standard gas gain mGasGain = 4000.0; - } else if (CommonParam::Instance()->IsArgon()) { + } else if (CommonParam::instance()->isArgon()) { // The range and the binwidth for the sampled TRF mTRFbin = 50; // Start 0.2 mus before the signal @@ -273,21 +273,21 @@ void SimParam::SampleTRF() } mCTsmp = new float[mTRFbin]; - if (CommonParam::Instance()->IsXenon()) { + if (CommonParam::instance()->isXenon()) { if (mTRFbin != kNpasa) { LOG(ERROR) << "Array mismatch (xenon)\n\n"; } - } else if (CommonParam::Instance()->IsArgon()) { + } else if (CommonParam::instance()->isArgon()) { if (mTRFbin != kNpasaAr) { LOG(ERROR) << "Array mismatch (argon)\n\n"; } } for (int iBin = 0; iBin < mTRFbin; iBin++) { - if (CommonParam::Instance()->IsXenon()) { + if (CommonParam::instance()->isXenon()) { mTRFsmp[iBin] = signal[iBin]; mCTsmp[iBin] = xtalk[iBin]; - } else if (CommonParam::Instance()->IsArgon()) { + } else if (CommonParam::instance()->isArgon()) { mTRFsmp[iBin] = signalAr[iBin]; mCTsmp[iBin] = xtalkAr[iBin]; } diff --git a/Detectors/TRD/base/test/testTRDDiffusionCoefficient.cxx b/Detectors/TRD/base/test/testTRDDiffusionCoefficient.cxx index 55355fc7ef386..8b18ada89fb61 100644 --- a/Detectors/TRD/base/test/testTRDDiffusionCoefficient.cxx +++ b/Detectors/TRD/base/test/testTRDDiffusionCoefficient.cxx @@ -34,11 +34,11 @@ BOOST_AUTO_TEST_CASE(TRDDiffusionCoefficient_test1) TGeoGlobalMagField::Instance()->SetField(fld); TGeoGlobalMagField::Instance()->Lock(); - auto commonParam = CommonParam::Instance(); + auto commonParam = CommonParam::instance(); float dl = 0; float dt = 0; float vd = 1.48; - commonParam->GetDiffCoeff(dl, dt, vd); + commonParam->getDiffCoeff(dl, dt, vd); // check whether the values match the expected AliRoot known output BOOST_CHECK_CLOSE(dl, 0.0255211, 0.1); BOOST_CHECK_CLOSE(dt, 0.0179734, 0.1); @@ -47,40 +47,40 @@ BOOST_AUTO_TEST_CASE(TRDDiffusionCoefficient_test1) /// \brief Test time structure BOOST_AUTO_TEST_CASE(TRDTimeStructure_test) { - auto commonParam = CommonParam::Instance(); + auto commonParam = CommonParam::instance(); DiffusionAndTimeStructEstimator estimator; - BOOST_CHECK_CLOSE(estimator.TimeStruct(1.48, 1., 0.1), commonParam->TimeStruct(1.48, 1., 0.1), 0.001); - BOOST_CHECK_CLOSE(estimator.TimeStruct(1.1, 1., 0.1), commonParam->TimeStruct(1.1, 1., 0.1), 0.001); - BOOST_CHECK_CLOSE(estimator.TimeStruct(2, 1., 0.1), commonParam->TimeStruct(2, 1., 0.1), 0.001); - BOOST_CHECK_CLOSE(estimator.TimeStruct(4, 1., 0.1), commonParam->TimeStruct(4, 1., 0.1), 0.001); + BOOST_CHECK_CLOSE(estimator.TimeStruct(1.48, 1., 0.1), commonParam->timeStruct(1.48, 1., 0.1), 0.001); + BOOST_CHECK_CLOSE(estimator.TimeStruct(1.1, 1., 0.1), commonParam->timeStruct(1.1, 1., 0.1), 0.001); + BOOST_CHECK_CLOSE(estimator.TimeStruct(2, 1., 0.1), commonParam->timeStruct(2, 1., 0.1), 0.001); + BOOST_CHECK_CLOSE(estimator.TimeStruct(4, 1., 0.1), commonParam->timeStruct(4, 1., 0.1), 0.001); } /// \brief compare diffusion coeff BOOST_AUTO_TEST_CASE(TRDDiffusion_test) { - auto commonParam = CommonParam::Instance(); + auto commonParam = CommonParam::instance(); DiffusionAndTimeStructEstimator estimator; float dl1 = 0.; float dl2 = 0.; float dt1 = 0.; float dt2 = 0.; estimator.GetDiffCoeff(dl1, dt1, 1.48); - commonParam->GetDiffCoeff(dl2, dt2, 1.48); + commonParam->getDiffCoeff(dl2, dt2, 1.48); BOOST_CHECK_CLOSE(dl1, dl2, 0.001); BOOST_CHECK_CLOSE(dt1, dt2, 0.001); estimator.GetDiffCoeff(dl1, dt1, 1.1); - commonParam->GetDiffCoeff(dl2, dt2, 1.1); + commonParam->getDiffCoeff(dl2, dt2, 1.1); BOOST_CHECK_CLOSE(dl1, dl2, 0.001); BOOST_CHECK_CLOSE(dt1, dt2, 0.001); estimator.GetDiffCoeff(dl1, dt1, 2); - commonParam->GetDiffCoeff(dl2, dt2, 2); + commonParam->getDiffCoeff(dl2, dt2, 2); BOOST_CHECK_CLOSE(dl1, dl2, 0.001); BOOST_CHECK_CLOSE(dt1, dt2, 0.001); estimator.GetDiffCoeff(dl1, dt1, 4); - commonParam->GetDiffCoeff(dl2, dt2, 4); + commonParam->getDiffCoeff(dl2, dt2, 4); BOOST_CHECK_CLOSE(dl1, dl2, 0.001); BOOST_CHECK_CLOSE(dt1, dt2, 0.001); } diff --git a/Detectors/TRD/simulation/src/Detector.cxx b/Detectors/TRD/simulation/src/Detector.cxx index c62feaf6bbe72..731392d8c24e8 100644 --- a/Detectors/TRD/simulation/src/Detector.cxx +++ b/Detectors/TRD/simulation/src/Detector.cxx @@ -63,9 +63,9 @@ void Detector::InitializeO2Detector() void Detector::InitializeParams() { - if (CommonParam::Instance()->IsXenon()) { + if (CommonParam::instance()->isXenon()) { mWion = 23.53; // Ionization energy XeCO2 (85/15) - } else if (CommonParam::Instance()->IsArgon()) { + } else if (CommonParam::instance()->isArgon()) { mWion = 27.21; // Ionization energy ArCO2 (82/18) } else { LOG(FATAL) << "Wrong gas mixture"; @@ -232,9 +232,9 @@ void Detector::createTRhit(int det) // The absorbtion cross sections in the drift gas // Gas-mixture (Xe/CO2) double muNo = 0.0; - if (CommonParam::Instance()->IsXenon()) { + if (CommonParam::instance()->isXenon()) { muNo = mTR->getMuXe(energyMeV); - } else if (CommonParam::Instance()->IsArgon()) { + } else if (CommonParam::instance()->isArgon()) { muNo = mTR->getMuAr(energyMeV); } double muCO = mTR->getMuCO(energyMeV); @@ -359,9 +359,9 @@ void Detector::createMaterials() float fac = 0.82; float dar = 0.00166; // at 20C float dgmAr = fac * dar + (1.0 - fac) * dco; - if (CommonParam::Instance()->IsXenon()) { + if (CommonParam::instance()->isXenon()) { Mixture(53, "XeCO2", aXeCO2, zXeCO2, dgmXe, -3, wXeCO2); - } else if (CommonParam::Instance()->IsArgon()) { + } else if (CommonParam::instance()->isArgon()) { LOG(INFO) << "Gas mixture: Ar C02 (80/20)"; Mixture(53, "ArCO2", aArCO2, zArCO2, dgmAr, -3, wArCO2); } else { @@ -492,10 +492,10 @@ void Detector::createMaterials() // Save the density values for the TRD absorbtion float dmy = 1.39; mFoilDensity = dmy; - if (CommonParam::Instance()->IsXenon()) { + if (CommonParam::instance()->isXenon()) { mGasDensity = dgmXe; mGasNobleFraction = fxc; - } else if (CommonParam::Instance()->IsArgon()) { + } else if (CommonParam::instance()->isArgon()) { mGasDensity = dgmAr; mGasNobleFraction = fac; } diff --git a/Detectors/TRD/simulation/src/Digitizer.cxx b/Detectors/TRD/simulation/src/Digitizer.cxx index f94c6652cfb59..0f814463480aa 100644 --- a/Detectors/TRD/simulation/src/Digitizer.cxx +++ b/Detectors/TRD/simulation/src/Digitizer.cxx @@ -41,7 +41,7 @@ void Digitizer::init() mGeo->createClusterMatrixArray(); // Requiered for chamberInGeometry() mPRF = new PadResponse(); // Pad response function initialization mSimParam = SimParam::Instance(); // Instance for simulation parameters - mCommonParam = CommonParam::Instance(); // Instance for common parameters + mCommonParam = CommonParam::instance(); // Instance for common parameters if (!mSimParam) { } if (!mCommonParam) { @@ -80,11 +80,11 @@ void Digitizer::setSimulationParameters() { mNpad = mSimParam->getNumberOfPadsInPadResponse(); // Number of pads included in the pad response if (mSimParam->TRFOn()) { - mTimeBinTRFend = ((int)(mSimParam->GetTRFhi() * mCommonParam->GetSamplingFrequency())) - 1; + mTimeBinTRFend = ((int)(mSimParam->GetTRFhi() * mCommonParam->getSamplingFrequency())) - 1; } mMaxTimeBins = TIMEBINS; // for signals, usually set at 30 tb = 3 microseconds mMaxTimeBinsTRAP = TIMEBINS; // for adcs; should be read from the CCDB or the TRAP config - mSamplingRate = mCommonParam->GetSamplingFrequency(); + mSamplingRate = mCommonParam->getSamplingFrequency(); mElAttachProp = mSimParam->GetElAttachProp() / 100; } @@ -259,7 +259,7 @@ bool Digitizer::convertHits(const int det, const std::vector& hits, SignalC } double absDriftLength = std::fabs(driftLength); // Normalized drift length - if (mCommonParam->ExBOn()) { + if (mCommonParam->isExBOn()) { absDriftLength /= std::sqrt(1 / (1 + calExBDetValue * calExBDetValue)); } @@ -286,7 +286,7 @@ bool Digitizer::convertHits(const int det, const std::vector& hits, SignalC } // Apply E x B effects - if (mCommonParam->ExBOn()) { + if (mCommonParam->isExBOn()) { locCd = locCd + calExBDetValue * driftLength; } // The electron position after diffusion and ExB in pad coordinates. @@ -511,7 +511,7 @@ bool Digitizer::diffusion(float vdrift, float absdriftlength, float exbvalue, float sigmaT = driftSqrt * diffT; float sigmaL = driftSqrt * diffL; lRow = drawGaus(mGausRandomRings[thread], lRow0, sigmaT); - if (mCommonParam->ExBOn()) { + if (mCommonParam->isExBOn()) { const float exbfactor = 1.f / (1.f + exbvalue * exbvalue); lCol = drawGaus(mGausRandomRings[thread], lCol0, sigmaT * exbfactor); lTime = drawGaus(mGausRandomRings[thread], lTime0, sigmaL * exbfactor); diff --git a/Detectors/TRD/simulation/src/TrapConfigHandler.cxx b/Detectors/TRD/simulation/src/TrapConfigHandler.cxx index e0c144dd11ec3..2a76265490f19 100644 --- a/Detectors/TRD/simulation/src/TrapConfigHandler.cxx +++ b/Detectors/TRD/simulation/src/TrapConfigHandler.cxx @@ -478,6 +478,7 @@ void TrapConfigHandler::configureDRange(int det) // if pt_min < 0.1 GeV/c the maximal allowed range for the tracklet // deflection (-64..63) is used // + // TODO might need to be updated depending in the FEE configuration for Run 3 if (!mTrapConfig) { LOG(error) << "No TRAPconfig given"; From 24dca669fcd00b250fce0bc5650b848bc9f63264 Mon Sep 17 00:00:00 2001 From: Ole Schmidt Date: Thu, 15 Apr 2021 16:46:47 +0200 Subject: [PATCH 138/770] Remove unnecessary include of CommonParam in GeometryBase --- Detectors/TRD/base/include/TRDBase/CommonParam.h | 4 +--- Detectors/TRD/base/include/TRDBase/GeometryBase.h | 1 - 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/Detectors/TRD/base/include/TRDBase/CommonParam.h b/Detectors/TRD/base/include/TRDBase/CommonParam.h index 5bd46b9966d07..77d50e42a7b9a 100644 --- a/Detectors/TRD/base/include/TRDBase/CommonParam.h +++ b/Detectors/TRD/base/include/TRDBase/CommonParam.h @@ -11,8 +11,8 @@ #ifndef O2_TRD_COMMONPARAM_H #define O2_TRD_COMMONPARAM_H -#include "GPUCommonRtypes.h" #include +#include "Rtypes.h" // for ClassDef namespace o2 { @@ -55,9 +55,7 @@ class CommonParam protected: void sampleTimeStruct(float vdrift); -#ifndef GPUCA_GPUCODE_DEVICE static CommonParam* fgInstance; // Instance of this class (singleton implementation) -#endif static constexpr int TIMEBIN = 38; static constexpr int ZBIN = 11; bool mExBOn{true}; // Switch for the ExB effects diff --git a/Detectors/TRD/base/include/TRDBase/GeometryBase.h b/Detectors/TRD/base/include/TRDBase/GeometryBase.h index 7bb5fec24b65d..c40720c9df4b6 100644 --- a/Detectors/TRD/base/include/TRDBase/GeometryBase.h +++ b/Detectors/TRD/base/include/TRDBase/GeometryBase.h @@ -12,7 +12,6 @@ #define O2_TRD_GEOMETRYBASE_H #include "GPUCommonDef.h" -#include "TRDBase/CommonParam.h" #include "DataFormatsTRD/Constants.h" #include "TRDBase/PadPlane.h" From f86e9df7fb88e37cab1f5a8f894f4dbf7914285a Mon Sep 17 00:00:00 2001 From: Ole Schmidt Date: Thu, 15 Apr 2021 17:56:30 +0200 Subject: [PATCH 139/770] Adapt SimParam class to O2 naming convention --- .../TRD/base/include/TRDBase/CommonParam.h | 2 +- Detectors/TRD/base/include/TRDBase/SimParam.h | 156 ++++++++---------- Detectors/TRD/base/src/CommonParam.cxx | 12 +- Detectors/TRD/base/src/SimParam.cxx | 155 ++--------------- Detectors/TRD/simulation/src/Digitizer.cxx | 38 ++--- 5 files changed, 109 insertions(+), 254 deletions(-) diff --git a/Detectors/TRD/base/include/TRDBase/CommonParam.h b/Detectors/TRD/base/include/TRDBase/CommonParam.h index 77d50e42a7b9a..39f08fa67f63d 100644 --- a/Detectors/TRD/base/include/TRDBase/CommonParam.h +++ b/Detectors/TRD/base/include/TRDBase/CommonParam.h @@ -55,7 +55,7 @@ class CommonParam protected: void sampleTimeStruct(float vdrift); - static CommonParam* fgInstance; // Instance of this class (singleton implementation) + static CommonParam* mgInstance; // Instance of this class (singleton implementation) static constexpr int TIMEBIN = 38; static constexpr int ZBIN = 11; bool mExBOn{true}; // Switch for the ExB effects diff --git a/Detectors/TRD/base/include/TRDBase/SimParam.h b/Detectors/TRD/base/include/TRDBase/SimParam.h index e6de326bc8650..98db5f1d81fc7 100644 --- a/Detectors/TRD/base/include/TRDBase/SimParam.h +++ b/Detectors/TRD/base/include/TRDBase/SimParam.h @@ -11,8 +11,8 @@ #ifndef O2_TRD_SIMPARAM_H #define O2_TRD_SIMPARAM_H -//Forwards to standard header with protection for GPU compilation -#include "GPUCommonRtypes.h" // for ClassDef +#include +#include "Rtypes.h" // for ClassDef namespace o2 { @@ -30,108 +30,96 @@ class SimParam kNPadsInPadResponse = 3 // Number of pads included in the pad response }; - static SimParam* Instance(); - static void Terminate(); - - void SetGasGain(float gasgain) { mGasGain = gasgain; } - void SetNoise(float noise) { mNoise = noise; } - void SetChipGain(float chipgain) { mChipGain = chipgain; } - void SetADCoutRange(float range) { mADCoutRange = range; } - void SetADCinRange(float range) { mADCinRange = range; } - void SetADCbaseline(int basel) { mADCbaseline = basel; } - void SetDiffusion(int diffOn = 1) { mDiffusionOn = diffOn; } - void SetElAttach(int elOn = 1) { mElAttachOn = elOn; } - void SetElAttachProp(float prop) { mElAttachProp = prop; } - void SetTimeResponse(int trfOn = 1) - { - mTRFOn = trfOn; - ReInit(); - } - void SetCrossTalk(int ctOn = 1) - { - mCTOn = ctOn; - ReInit(); - } - void SetPadCoupling(float v) { mPadCoupling = v; } - void SetTimeCoupling(float v) { mTimeCoupling = v; } - void SetTimeStruct(bool tsOn = 1) { mTimeStructOn = tsOn; } - void SetPadResponse(int prfOn = 1) { mPRFOn = prfOn; } - void SetNTimeBins(int ntb) { mNTimeBins = ntb; } - void SetNTBoverwriteOCDB(bool over = true) { mNTBoverwriteOCDB = over; } - float GetGasGain() const { return mGasGain; } - float GetNoise() const { return mNoise; } - float GetChipGain() const { return mChipGain; } - float GetADCoutRange() const { return mADCoutRange; } - float GetADCinRange() const { return mADCinRange; } - int GetADCbaseline() const { return mADCbaseline; } - float GetTRFlo() const { return mTRFlo; } - float GetTRFhi() const { return mTRFhi; } - float GetPadCoupling() const { return mPadCoupling; } - float GetTimeCoupling() const { return mTimeCoupling; } - int GetNTimeBins() const { return mNTimeBins; } - bool GetNTBoverwriteOCDB() const { return mNTBoverwriteOCDB; } - bool DiffusionOn() const { return mDiffusionOn; } - bool ElAttachOn() const { return mElAttachOn; } - float GetElAttachProp() const { return mElAttachProp; } - bool TRFOn() const { return mTRFOn; } - bool CTOn() const { return mCTOn; } - bool TimeStructOn() const { return mTimeStructOn; } - bool PRFOn() const { return mPRFOn; } + SimParam(const SimParam&) = delete; + SimParam& operator=(const SimParam&) = delete; + static SimParam* instance(); + + void setGasGain(float gasgain) { mGasGain = gasgain; } + void setNoise(float noise) { mNoise = noise; } + void setChipGain(float chipgain) { mChipGain = chipgain; } + void setADCoutRange(float range) { mADCoutRange = range; } + void setADCinRange(float range) { mADCinRange = range; } + void setADCbaseline(int basel) { mADCbaseline = basel; } + void setDiffusion(bool flag = true) { mDiffusionOn = flag; } + void setElAttach(bool flag = true) { mElAttachOn = flag; } + void setElAttachProp(float prop) { mElAttachProp = prop; } + void setTimeResponse(bool flag = true) { mTRFOn = flag; } + void setCrossTalk(bool flag = true) { mCTOn = flag; } + void setPadCoupling(float v) { mPadCoupling = v; } + void setTimeCoupling(float v) { mTimeCoupling = v; } + void setTimeStruct(bool flag = true) { mTimeStructOn = flag; } + void setPadResponse(bool flag = true) { mPRFOn = flag; } + + float getGasGain() const { return mGasGain; } + float getNoise() const { return mNoise; } + float getChipGain() const { return mChipGain; } + float getADCoutRange() const { return mADCoutRange; } + float getADCinRange() const { return mADCinRange; } + int getADCbaseline() const { return mADCbaseline; } + float getTRFlo() const { return mTRFlo; } + float getTRFhi() const { return mTRFhi; } + float getPadCoupling() const { return mPadCoupling; } + float getTimeCoupling() const { return mTimeCoupling; } + bool diffusionOn() const { return mDiffusionOn; } + bool elAttachOn() const { return mElAttachOn; } + float getElAttachProp() const { return mElAttachProp; } + bool trfOn() const { return mTRFOn; } + bool ctOn() const { return mCTOn; } + bool timeStructOn() const { return mTimeStructOn; } + bool prfOn() const { return mPRFOn; } const int getNumberOfPadsInPadResponse() const { return kNPadsInPadResponse; } - inline double TimeResponse(double) const; - inline double CrossTalk(double) const; - void ReInit(); + inline double timeResponse(double) const; + inline double crossTalk(double) const; + void reInit(); protected: - static SimParam* fgInstance; // Instance of this class (singleton implementation) - static bool fgTerminated; // Defines if this class has already been terminated and - // therefore does not return instances in GetInstance anymore + static SimParam* mgInstance; // Instance of this class (singleton implementation) // Digitization parameter - float mGasGain; // Gas gain - float mNoise; // Electronics noise - float mChipGain; // Electronics gain - - float mADCoutRange; // ADC output range (number of channels) - float mADCinRange; // ADC input range (input charge) - int mADCbaseline; // ADC intrinsic baseline in ADC channel + float mGasGain{4000.f}; // Gas gain + float mNoise{1250.f}; // Electronics noise + float mChipGain{12.4f}; // Electronics gain - int mDiffusionOn; // Switch for the diffusion + float mADCoutRange{1023.f}; // ADC output range (number of channels); 10 bit ADC + float mADCinRange{2000.f}; // ADC input range (input charge); 2V input range + int mADCbaseline{10}; // ADC intrinsic baseline in ADC channel - int mElAttachOn; // Switch for the electron attachment - float mElAttachProp; // Propability for electron attachment (for 1m) + bool mDiffusionOn{true}; // Switch for the diffusion - int mTRFOn; // Switch for the time response - float* mTRFsmp; //! Integrated time response - int mTRFbin; // Number of bins for the TRF - float mTRFlo; // Lower boundary of the TRF - float mTRFhi; // Higher boundary of the TRF - float mInvTRFwid; // Inverse of the bin width of the integrated TRF + bool mElAttachOn{false}; // Switch for the electron attachment + float mElAttachProp{0.f}; // Propability for electron attachment (for 1m) - int mCTOn; // Switch for cross talk - float* mCTsmp; //! Integrated cross talk + static constexpr int mNBinsMax = 200; // maximum number of bins for integrated time response and cross talk + bool mTRFOn{true}; // Switch for the time response + std::array mTRFsmp{}; // Integrated time response + int mTRFbin{200}; // Number of bins for the TRF + float mTRFlo{-.4f}; // Lower boundary of the TRF + float mTRFhi{3.58f}; // Higher boundary of the TRF + float mInvTRFwid{static_cast(mTRFbin) / (mTRFhi - mTRFlo)}; // Inverse of the bin width of the integrated TRF - float mPadCoupling; // Pad coupling factor - float mTimeCoupling; // Time coupling factor (image charge of moving ions) - int mTimeStructOn; // Switch for cell time structure + bool mCTOn{true}; // Switch for cross talk + std::array mCTsmp{}; // Integrated cross talk - int mPRFOn; // Switch for the pad response + // The pad coupling factor + // Use 0.46, instead of the theroetical value 0.3, since it reproduces better + // the test beam data, even tough it is not understood why. + float mPadCoupling{.46f}; + float mTimeCoupling{.4f}; // Time coupling factor (image charge of moving ions); same number as for the TPC + bool mTimeStructOn{true}; // Switch for cell time structure - int mNTimeBins; // Number of time bins (only used it fNTBoverwriteOCDB = true) - bool mNTBoverwriteOCDB; // Switch to overwrite number of time bins from PCDB + bool mPRFOn{true}; // Switch for the pad response private: // This is a singleton, constructor is private! SimParam(); - ~SimParam(); + ~SimParam() = default; - void Init(); - void SampleTRF(); + void sampleTRF(); ClassDefNV(SimParam, 1); // The TRD simulation parameters }; -inline double SimParam::TimeResponse(double time) const +inline double SimParam::timeResponse(double time) const { // // Applies the preamp shaper time response @@ -148,7 +136,7 @@ inline double SimParam::TimeResponse(double time) const } } -inline double SimParam::CrossTalk(double time) const +inline double SimParam::crossTalk(double time) const { // // Applies the pad-pad capacitive cross talk diff --git a/Detectors/TRD/base/src/CommonParam.cxx b/Detectors/TRD/base/src/CommonParam.cxx index aa3888300ad62..0e8db565d2661 100644 --- a/Detectors/TRD/base/src/CommonParam.cxx +++ b/Detectors/TRD/base/src/CommonParam.cxx @@ -30,7 +30,7 @@ using namespace o2::trd; ClassImp(CommonParam); -CommonParam* CommonParam::fgInstance = nullptr; +CommonParam* CommonParam::mgInstance = nullptr; //_ singleton implementation __________________________________________________ CommonParam* CommonParam::instance() @@ -40,11 +40,11 @@ CommonParam* CommonParam::instance() // Returns an instance of this class, it is created if neccessary // - if (fgInstance == nullptr) { - fgInstance = new CommonParam(); + if (mgInstance == nullptr) { + mgInstance = new CommonParam(); } - return fgInstance; + return mgInstance; } @@ -665,11 +665,11 @@ void CommonParam::sampleTimeStruct(float vdrift) void CommonParam::setXenon() { mGasMixture = kXenon; - SimParam::Instance()->ReInit(); + SimParam::instance()->reInit(); } void CommonParam::setArgon() { mGasMixture = kArgon; - SimParam::Instance()->ReInit(); + SimParam::instance()->reInit(); } diff --git a/Detectors/TRD/base/src/SimParam.cxx b/Detectors/TRD/base/src/SimParam.cxx index 1f62efea8076a..4555b6788bced 100644 --- a/Detectors/TRD/base/src/SimParam.cxx +++ b/Detectors/TRD/base/src/SimParam.cxx @@ -18,157 +18,45 @@ //////////////////////////////////////////////////////////////////////////// #include "TRDBase/SimParam.h" -#include #include "TRDBase/CommonParam.h" #include using namespace o2::trd; ClassImp(SimParam); -SimParam* SimParam::fgInstance = nullptr; -bool SimParam::fgTerminated = false; +SimParam* SimParam::mgInstance = nullptr; //_ singleton implementation __________________________________________________ -SimParam* SimParam::Instance() +SimParam* SimParam::instance() { // // Singleton implementation // Returns an instance of this class, it is created if neccessary // - if (fgTerminated != false) { - return nullptr; + if (mgInstance == nullptr) { + mgInstance = new SimParam(); } - if (fgInstance == nullptr) { - fgInstance = new SimParam(); - } - - return fgInstance; -} - -//_ singleton implementation __________________________________________________ -void SimParam::Terminate() -{ - // - // Singleton implementation - // Deletes the instance of this class and sets the terminated flag, - // instances cannot be requested anymore - // This function can be called several times. - // - - fgTerminated = true; - - if (fgInstance != nullptr) { - delete fgInstance; - fgInstance = nullptr; - } + return mgInstance; } //_____________________________________________________________________________ SimParam::SimParam() - : mGasGain(0.0), - mNoise(0.0), - mChipGain(0.0), - mADCoutRange(0.0), - mADCinRange(0.0), - mADCbaseline(0), - mDiffusionOn(false), - mElAttachOn(false), - mElAttachProp(0.0), - mTRFOn(false), - mTRFsmp(nullptr), - mTRFbin(0), - mTRFlo(0.0), - mTRFhi(0.0), - mInvTRFwid(0.0), - mCTOn(false), - mCTsmp(nullptr), - mPadCoupling(0.0), - mTimeCoupling(0.0), - mTimeStructOn(false), - mPRFOn(false), - mNTimeBins(0), - mNTBoverwriteOCDB(false) { // // Default constructor // - - Init(); + sampleTRF(); } -//_____________________________________________________________________________ -void SimParam::Init() -{ - // - // Default initializiation - // - - // The default parameter for the digitization - mGasGain = 4000.0; - mChipGain = 12.4; - mNoise = 1250.0; - mADCoutRange = 1023.0; // 10-bit ADC - mADCinRange = 2000.0; // 2V input range - mADCbaseline = 10; - - // Diffusion on - mDiffusionOn = true; - - // Propability for electron attachment - mElAttachOn = false; - mElAttachProp = 0.0; - - // The time response function - mTRFOn = true; - - // The cross talk - mCTOn = true; - - // The pad coupling factor - // Use 0.46, instead of the theroetical value 0.3, since it reproduces better - // the test beam data, even tough it is not understood why. - mPadCoupling = 0.46; - - // The time coupling factor (same number as for the TPC) - mTimeCoupling = 0.4; - // Use drift time maps - mTimeStructOn = true; - - // The pad response function - mPRFOn = true; - - // The number of time bins - mNTimeBins = 22; - mNTBoverwriteOCDB = false; - - ReInit(); -} //_____________________________________________________________________________ -SimParam::~SimParam() +void SimParam::reInit() { // - // Destructor - // - if (mTRFsmp) { - delete[] mTRFsmp; - mTRFsmp = nullptr; - } - - if (mCTsmp) { - delete[] mCTsmp; - mCTsmp = nullptr; - } -} - -//_____________________________________________________________________________ -void SimParam::ReInit() -{ - // - // Reinitializes the parameter class after a change + // Reinitializes the parameter class after a change of the gas mixture // if (CommonParam::instance()->isXenon()) { @@ -195,11 +83,11 @@ void SimParam::ReInit() mInvTRFwid = ((float)mTRFbin) / (mTRFhi - mTRFlo); // Inverse of the bin width of the integrated TRF // Create the sampled TRF - SampleTRF(); + sampleTRF(); } //_____________________________________________________________________________ -void SimParam::SampleTRF() +void SimParam::sampleTRF() { // // Samples the new time response function. @@ -228,9 +116,7 @@ void SimParam::SampleTRF() 0.0138, 0.0135, 0.0133, 0.0131, 0.0128, 0.0126, 0.0124, 0.0121, 0.0119, 0.0120, 0.0115, 0.0113, 0.0111, 0.0109, 0.0107, 0.0105, 0.0103, 0.0101, 0.0100, 0.0098, 0.0096, 0.0094, 0.0092, 0.0091, 0.0089, 0.0088, 0.0086, 0.0084, 0.0083, 0.0081, 0.0080, 0.0078}; - signal[0] = 0.0; - signal[1] = 0.0; - signal[2] = 0.0; + // With undershoot, positive peak corresponds to ~3% of the main signal: for (ipasa = 3; ipasa < kNpasa; ipasa++) { xtalk[ipasa] = 0.2 * (signal[ipasa - 2] - signal[ipasa - 3]); @@ -263,25 +149,6 @@ void SimParam::SampleTRF() xtalkAr[1] = 0.0; xtalkAr[2] = 0.0; - if (mTRFsmp) { - delete[] mTRFsmp; - } - mTRFsmp = new float[mTRFbin]; - - if (mCTsmp) { - delete[] mCTsmp; - } - mCTsmp = new float[mTRFbin]; - - if (CommonParam::instance()->isXenon()) { - if (mTRFbin != kNpasa) { - LOG(ERROR) << "Array mismatch (xenon)\n\n"; - } - } else if (CommonParam::instance()->isArgon()) { - if (mTRFbin != kNpasaAr) { - LOG(ERROR) << "Array mismatch (argon)\n\n"; - } - } for (int iBin = 0; iBin < mTRFbin; iBin++) { if (CommonParam::instance()->isXenon()) { diff --git a/Detectors/TRD/simulation/src/Digitizer.cxx b/Detectors/TRD/simulation/src/Digitizer.cxx index 0f814463480aa..78990547d646f 100644 --- a/Detectors/TRD/simulation/src/Digitizer.cxx +++ b/Detectors/TRD/simulation/src/Digitizer.cxx @@ -40,7 +40,7 @@ void Digitizer::init() mGeo = Geometry::instance(); mGeo->createClusterMatrixArray(); // Requiered for chamberInGeometry() mPRF = new PadResponse(); // Pad response function initialization - mSimParam = SimParam::Instance(); // Instance for simulation parameters + mSimParam = SimParam::instance(); // Instance for simulation parameters mCommonParam = CommonParam::instance(); // Instance for common parameters if (!mSimParam) { } @@ -79,13 +79,13 @@ void Digitizer::init() void Digitizer::setSimulationParameters() { mNpad = mSimParam->getNumberOfPadsInPadResponse(); // Number of pads included in the pad response - if (mSimParam->TRFOn()) { - mTimeBinTRFend = ((int)(mSimParam->GetTRFhi() * mCommonParam->getSamplingFrequency())) - 1; + if (mSimParam->trfOn()) { + mTimeBinTRFend = ((int)(mSimParam->getTRFhi() * mCommonParam->getSamplingFrequency())) - 1; } mMaxTimeBins = TIMEBINS; // for signals, usually set at 30 tb = 3 microseconds mMaxTimeBinsTRAP = TIMEBINS; // for adcs; should be read from the CCDB or the TRAP config mSamplingRate = mCommonParam->getSamplingFrequency(); - mElAttachProp = mSimParam->GetElAttachProp() / 100; + mElAttachProp = mSimParam->getElAttachProp() / 100; } void Digitizer::flush(DigitContainer& digits, o2::dataformats::MCTruthContainer& labels) @@ -270,7 +270,7 @@ bool Digitizer::convertHits(const int det, const std::vector& hits, SignalC const int nElectrons = std::fabs(qTotal); for (int el = 0; el < nElectrons; ++el) { // Electron attachment - if (mSimParam->ElAttachOn()) { + if (mSimParam->elAttachOn()) { if (mFlatRandomRings[thread].getNextValue() < absDriftLength * mElAttachProp) { continue; } @@ -279,7 +279,7 @@ bool Digitizer::convertHits(const int det, const std::vector& hits, SignalC double locRd{locR}, locCd{locC}, locTd{locT}; // Apply diffusion smearing - if (mSimParam->DiffusionOn()) { + if (mSimParam->diffusionOn()) { if (!diffusion(driftVelocity, absDriftLength, calExBDetValue, locR, locC, locT, locRd, locCd, locTd, thread)) { continue; } @@ -308,7 +308,7 @@ bool Digitizer::convertHits(const int det, const std::vector& hits, SignalC // time structure of drift cells (non-isochronity, GARFIELD calculation). // Also add absolute time of hits to take pile-up events into account properly double driftTime; - if (mSimParam->TimeStructOn()) { + if (mSimParam->timeStructOn()) { // Get z-position with respect to anode wire double zz = row0 - locRd + padPlane->getAnodeWireOffset(); zz -= ((int)(2 * zz)) * 0.5; @@ -323,10 +323,10 @@ bool Digitizer::convertHits(const int det, const std::vector& hits, SignalC } // Apply the gas gain including fluctuations - const double signal = -(mSimParam->GetGasGain()) * mLogRandomRings[thread].getNextValue(); + const double signal = -(mSimParam->getGasGain()) * mLogRandomRings[thread].getNextValue(); // Apply the pad response - if (mSimParam->PRFOn()) { + if (mSimParam->prfOn()) { // The distance of the electron to the center of the pad in units of pad width double dist = (colOffset - 0.5 * padPlane->getColSize(colE)) / padPlane->getColSize(colE); // ******************************************************************************** @@ -378,14 +378,14 @@ bool Digitizer::convertHits(const int det, const std::vector& hits, SignalC if (colPos != colE) { for (int tb = firstTimeBin; tb < lastTimeBin; ++tb) { const double t = (tb - timeBinTruncated) / mSamplingRate + timeOffset; - const double timeResponse = mSimParam->TRFOn() ? mSimParam->TimeResponse(t) : 1; - const double crossTalk = mSimParam->CTOn() ? mSimParam->CrossTalk(t) : 0; + const double timeResponse = mSimParam->trfOn() ? mSimParam->timeResponse(t) : 1; + const double crossTalk = mSimParam->ctOn() ? mSimParam->crossTalk(t) : 0; currentSignal[tb] += padSignal[pad] * (timeResponse + crossTalk); } // end of loop time bins } else { for (int tb = firstTimeBin; tb < lastTimeBin; ++tb) { const double t = (tb - timeBinTruncated) / mSamplingRate + timeOffset; - const double timeResponse = mSimParam->TRFOn() ? mSimParam->TimeResponse(t) : 1; + const double timeResponse = mSimParam->trfOn() ? mSimParam->timeResponse(t) : 1; currentSignal[tb] += padSignal[pad] * timeResponse; } // end of loop time bins } @@ -418,10 +418,10 @@ bool Digitizer::convertSignalsToADC(SignalContainer& signalMapCont, DigitContain // constexpr double kEl2fC = 1.602e-19 * 1.0e15; // Converts number of electrons to fC - double coupling = mSimParam->GetPadCoupling() * mSimParam->GetTimeCoupling(); // Coupling factor - double convert = kEl2fC * mSimParam->GetChipGain(); // Electronics conversion factor - double adcConvert = mSimParam->GetADCoutRange() / mSimParam->GetADCinRange(); // ADC conversion factor - double baseline = mSimParam->GetADCbaseline() / adcConvert; // The electronics baseline in mV + double coupling = mSimParam->getPadCoupling() * mSimParam->getTimeCoupling(); // Coupling factor + double convert = kEl2fC * mSimParam->getChipGain(); // Electronics conversion factor + double adcConvert = mSimParam->getADCoutRange() / mSimParam->getADCinRange(); // ADC conversion factor + double baseline = mSimParam->getADCbaseline() / adcConvert; // The electronics baseline in mV double baselineEl = baseline / convert; // The electronics baseline in electrons for (auto& signalMapIter : signalMapCont) { @@ -460,14 +460,14 @@ bool Digitizer::convertSignalsToADC(SignalContainer& signalMapCont, DigitContain signalAmp *= coupling; // Pad and time coupling signalAmp *= padgain; // Gain factors // Add the noise, starting from minus ADC baseline in electrons - signalAmp = std::max((double)drawGaus(mGausRandomRings[thread], signalAmp, mSimParam->GetNoise()), -baselineEl); + signalAmp = std::max((double)drawGaus(mGausRandomRings[thread], signalAmp, mSimParam->getNoise()), -baselineEl); signalAmp *= convert; // Convert to mV signalAmp += baseline; // Add ADC baseline in mV // Convert to ADC counts // Set the overflow-bit fADCoutRange if the signal is larger than fADCinRange ADC_t adc = 0; - if (signalAmp >= mSimParam->GetADCinRange()) { - adc = ((ADC_t)mSimParam->GetADCoutRange()); + if (signalAmp >= mSimParam->getADCinRange()) { + adc = ((ADC_t)mSimParam->getADCoutRange()); } else { adc = std::lround(signalAmp * adcConvert); } From 28e9ba0ccae3ce974607b03f874237a70ac0dc83 Mon Sep 17 00:00:00 2001 From: Ole Schmidt Date: Thu, 15 Apr 2021 22:33:35 +0200 Subject: [PATCH 140/770] More code cleanup --- .../TRD/base/include/TRDBase/CommonParam.h | 32 ++++---- Detectors/TRD/base/include/TRDBase/SimParam.h | 82 ++++++++++--------- Detectors/TRD/macros/CheckDigits.C | 2 +- 3 files changed, 59 insertions(+), 57 deletions(-) diff --git a/Detectors/TRD/base/include/TRDBase/CommonParam.h b/Detectors/TRD/base/include/TRDBase/CommonParam.h index 39f08fa67f63d..e0bc8182ca422 100644 --- a/Detectors/TRD/base/include/TRDBase/CommonParam.h +++ b/Detectors/TRD/base/include/TRDBase/CommonParam.h @@ -55,27 +55,27 @@ class CommonParam protected: void sampleTimeStruct(float vdrift); - static CommonParam* mgInstance; // Instance of this class (singleton implementation) - static constexpr int TIMEBIN = 38; - static constexpr int ZBIN = 11; - bool mExBOn{true}; // Switch for the ExB effects - double mField{-0.5}; // cached magnetic field - float mDiffusionT{0.}; // Transverse drift coefficient - float mDiffusionL{0.}; // Longitudinal drift coefficient - float mDiffLastVdrift{-1.}; // The structures are valid for fLastVdrift (caching) + static CommonParam* mgInstance; ///< Instance of this class (singleton implementation) + static constexpr int TIMEBIN = 38; ///< Number of bins in time direction used for garfield simulation + static constexpr int ZBIN = 11; ///< Number of bins in z direction used for garfield simulation + bool mExBOn{true}; ///< Switch for the ExB effects + double mField{-0.5}; ///< Cached magnetic field + float mDiffusionT{0.}; ///< Transverse drift coefficient + float mDiffusionL{0.}; ///< Longitudinal drift coefficient + float mDiffLastVdrift{-1.}; ///< The structures are valid for fLastVdrift (caching) - std::array mTimeStruct1{}; // Time Structure of Drift Cells - std::array mTimeStruct2{}; // Time Structure of Drift Cells - float mVDlo{0.}; // Lower drift velocity, for interpolation - float mVDhi{0.}; // Higher drift velocity, for interpolation - float mTimeLastVdrift{-1.}; // The structures are valid for fLastVdrift (caching) + std::array mTimeStruct1{}; ///< Time Structure of Drift Cells + std::array mTimeStruct2{}; ///< Time Structure of Drift Cells + float mVDlo{0.}; ///< Lower drift velocity, for interpolation + float mVDhi{0.}; ///< Higher drift velocity, for interpolation + float mTimeLastVdrift{-1.}; ///< The structures are valid for fLastVdrift (caching) - float mSamplingFrequency{10.}; // Sampling Frequency in MHz + float mSamplingFrequency{10.}; ///< Sampling Frequency in MHz - int mGasMixture{kXenon}; // Gas mixture: 0-Xe/C02 1-Ar/CO2. + int mGasMixture{kXenon}; ///< Gas mixture: 0-Xe/C02 1-Ar/CO2. private: - // This is a singleton, constructor is private! + /// This is a singleton, constructor is private! CommonParam() = default; ClassDef(CommonParam, 1); // The constant parameters common to simulation and reconstruction diff --git a/Detectors/TRD/base/include/TRDBase/SimParam.h b/Detectors/TRD/base/include/TRDBase/SimParam.h index 98db5f1d81fc7..cddae38d7f1df 100644 --- a/Detectors/TRD/base/include/TRDBase/SimParam.h +++ b/Detectors/TRD/base/include/TRDBase/SimParam.h @@ -8,6 +8,8 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +/// \file SimParam.h + #ifndef O2_TRD_SIMPARAM_H #define O2_TRD_SIMPARAM_H @@ -18,22 +20,27 @@ namespace o2 { namespace trd { -//////////////////////////////////////////////////////////////////////////// -// // -// Class containing constant simulation parameters // -// // -//////////////////////////////////////////////////////////////////////////// + +/// \brief Constant parameters for the TRD simulation +/// class SimParam { public: enum { - kNPadsInPadResponse = 3 // Number of pads included in the pad response + kNPadsInPadResponse = 3 ///< Number of pads included in the pad response }; + /// For a singleton class copying and assigning is not allowed SimParam(const SimParam&) = delete; SimParam& operator=(const SimParam&) = delete; + + /// Returns an instance of this class. A SimParam object is created upon the first call of this function static SimParam* instance(); + /// After setting a new gas mixture the parameters need to be re-evaluated + void reInit(); + + // Setters void setGasGain(float gasgain) { mGasGain = gasgain; } void setNoise(float noise) { mNoise = noise; } void setChipGain(float chipgain) { mChipGain = chipgain; } @@ -50,6 +57,7 @@ class SimParam void setTimeStruct(bool flag = true) { mTimeStructOn = flag; } void setPadResponse(bool flag = true) { mPRFOn = flag; } + // Getters float getGasGain() const { return mGasGain; } float getNoise() const { return mNoise; } float getChipGain() const { return mChipGain; } @@ -70,50 +78,44 @@ class SimParam const int getNumberOfPadsInPadResponse() const { return kNPadsInPadResponse; } inline double timeResponse(double) const; inline double crossTalk(double) const; - void reInit(); protected: - static SimParam* mgInstance; // Instance of this class (singleton implementation) - - // Digitization parameter - float mGasGain{4000.f}; // Gas gain - float mNoise{1250.f}; // Electronics noise - float mChipGain{12.4f}; // Electronics gain + static SimParam* mgInstance; ///< Instance of this class (singleton implementation) + + float mNoise{1250.f}; ///< Electronics noise + float mChipGain{12.4f}; ///< Electronics gain + float mADCoutRange{1023.f}; ///< ADC output range (number of channels for the 10 bit ADC) + float mADCinRange{2000.f}; ///< ADC input range (2V) + int mADCbaseline{10}; ///< ADC intrinsic baseline in ADC channel + bool mDiffusionOn{true}; ///< Switch for the diffusion + bool mElAttachOn{false}; ///< Switch for the electron attachment + float mElAttachProp{0.f}; ///< Propability for electron attachment (for 1m) + bool mTRFOn{true}; ///< Switch for the time response + bool mCTOn{true}; ///< Switch for cross talk + bool mPRFOn{true}; ///< Switch for the pad response + static constexpr int mNBinsMax = 200; ///< Maximum number of bins for integrated time response and cross talk - float mADCoutRange{1023.f}; // ADC output range (number of channels); 10 bit ADC - float mADCinRange{2000.f}; // ADC input range (input charge); 2V input range - int mADCbaseline{10}; // ADC intrinsic baseline in ADC channel - - bool mDiffusionOn{true}; // Switch for the diffusion - - bool mElAttachOn{false}; // Switch for the electron attachment - float mElAttachProp{0.f}; // Propability for electron attachment (for 1m) - - static constexpr int mNBinsMax = 200; // maximum number of bins for integrated time response and cross talk - bool mTRFOn{true}; // Switch for the time response - std::array mTRFsmp{}; // Integrated time response - int mTRFbin{200}; // Number of bins for the TRF - float mTRFlo{-.4f}; // Lower boundary of the TRF - float mTRFhi{3.58f}; // Higher boundary of the TRF - float mInvTRFwid{static_cast(mTRFbin) / (mTRFhi - mTRFlo)}; // Inverse of the bin width of the integrated TRF - - bool mCTOn{true}; // Switch for cross talk - std::array mCTsmp{}; // Integrated cross talk - - // The pad coupling factor // Use 0.46, instead of the theroetical value 0.3, since it reproduces better // the test beam data, even tough it is not understood why. - float mPadCoupling{.46f}; - float mTimeCoupling{.4f}; // Time coupling factor (image charge of moving ions); same number as for the TPC - bool mTimeStructOn{true}; // Switch for cell time structure - - bool mPRFOn{true}; // Switch for the pad response + float mPadCoupling{.46f}; ///< The pad coupling factor + float mTimeCoupling{.4f}; ///< Time coupling factor (image charge of moving ions); same number as for the TPC + bool mTimeStructOn{true}; ///< Switch for cell time structure + + /// The parameters below depend on the gas mixture and are re-evaluated upon a change + std::array mTRFsmp{}; ///< Integrated time response + std::array mCTsmp{}; ///< Integrated cross talk + int mTRFbin{200}; ///< Number of bins for the TRF and x-talk + float mTRFlo{-.4f}; ///< Lower boundary of the TRF and x-talk + float mTRFhi{3.58f}; ///< Higher boundary of the TRF and x-talk + float mInvTRFwid{static_cast(mTRFbin) / (mTRFhi - mTRFlo)}; ///< Inverse of the bin width of the integrated TRF and x-talk + float mGasGain{4000.f}; ///< Gas gain private: - // This is a singleton, constructor is private! + /// This is a singleton, constructor is private! SimParam(); ~SimParam() = default; + /// Fill the arrays mTRDsmp and mCTsmp for the given gas mixture void sampleTRF(); ClassDefNV(SimParam, 1); // The TRD simulation parameters diff --git a/Detectors/TRD/macros/CheckDigits.C b/Detectors/TRD/macros/CheckDigits.C index f887fe44d6d3f..95a5bc9aaf4bb 100644 --- a/Detectors/TRD/macros/CheckDigits.C +++ b/Detectors/TRD/macros/CheckDigits.C @@ -77,7 +77,7 @@ void CheckDigits(std::string digifile = "trddigits.root", hPad->Fill(pad); for (int tb = 0; tb < o2::trd::constants::TIMEBINS; ++tb) { ADC_t adc = adcs[tb]; - if (adc == (ADC_t)SimParam::Instance()->GetADCoutRange()) { + if (adc == (ADC_t)SimParam::instance()->getADCoutRange()) { // LOG(INFO) << "Out of range ADC " << adc; continue; } From bfa19f8e149525eb6b89224c91f0572ce099faf5 Mon Sep 17 00:00:00 2001 From: shahoian Date: Thu, 15 Apr 2021 22:54:42 +0200 Subject: [PATCH 141/770] fix in NameConf::rectifyDir method --- .../Utils/include/CommonUtils/StringUtils.h | 40 +++++++++++++++++++ .../DetectorsCommonDataFormats/NameConf.h | 2 +- DataFormats/Detectors/Common/src/NameConf.cxx | 24 +++-------- 3 files changed, 46 insertions(+), 20 deletions(-) diff --git a/Common/Utils/include/CommonUtils/StringUtils.h b/Common/Utils/include/CommonUtils/StringUtils.h index 998f5029f77f1..4a7e0db29db0a 100644 --- a/Common/Utils/include/CommonUtils/StringUtils.h +++ b/Common/Utils/include/CommonUtils/StringUtils.h @@ -17,6 +17,9 @@ #define ALICEO2_STRINGUTILS_H #include +#include +#include +#include namespace o2 { @@ -89,6 +92,43 @@ std::string concat_string(Ts const&... ts) return s.str(); } +// Check if the path exists +static inline bool pathExists(const std::string_view p) +{ + struct stat buffer; + return (stat(p.data(), &buffer) == 0); +} + +// Check if the path is a directory +static inline bool pathIsDirectory(const std::string_view p) +{ + struct stat buffer; + return (stat(p.data(), &buffer) == 0) && S_ISDIR(buffer.st_mode); +} + +static inline std::string getFullPath(const std::string_view p) +{ + std::unique_ptr real_path(realpath(p.data(), nullptr)); + return std::string(real_path.get()); +} + +static inline std::string rectifyDirectory(const std::string& _dir) +{ + std::string dir = _dir; + if (dir.empty() || dir == "none") { + dir = ""; + } else { + dir = getFullPath(dir); + if (!pathIsDirectory(dir)) { + throw std::runtime_error(fmt::format("{:s} is not an accessible directory", dir)); + } else { + dir += '/'; + } + } + return dir; +} + + } // namespace utils } // namespace o2 diff --git a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h index 852807451f5e8..66cf2ddd4e6af 100644 --- a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h +++ b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h @@ -38,7 +38,7 @@ class NameConf static std::string getFullPath(const std::string_view p); // Rectify directory allowing empty one and adding '/' if it is not empty - static void rectifyDirectory(std::string& dir); + static std::string rectifyDirectory(const std::string& _dir); // The Hits file name are generated by hardcoded schema, only prefix is mutable to allow the embedding static std::string getHitsFileName(o2::detectors::DetID d, const std::string_view prefix = STANDARDSIMPREFIX) diff --git a/DataFormats/Detectors/Common/src/NameConf.cxx b/DataFormats/Detectors/Common/src/NameConf.cxx index d4ac350dba7f6..78c6af08ced06 100644 --- a/DataFormats/Detectors/Common/src/NameConf.cxx +++ b/DataFormats/Detectors/Common/src/NameConf.cxx @@ -9,8 +9,6 @@ // or submit itself to any jurisdiction. #include "DetectorsCommonDataFormats/NameConf.h" -#include -#include #include #include @@ -20,35 +18,23 @@ using DId = o2::detectors::DetID; // Check if the path exists bool NameConf::pathExists(const std::string_view p) { - struct stat buffer; - return (stat(p.data(), &buffer) == 0); + return o2::utils::pathExists(p); } // Check if the path is a directory bool NameConf::pathIsDirectory(const std::string_view p) { - struct stat buffer; - return (stat(p.data(), &buffer) == 0) && S_ISDIR(buffer.st_mode); + return o2::utils::pathIsDirectory(p); } std::string NameConf::getFullPath(const std::string_view p) { - std::unique_ptr real_path(realpath(p.data(), nullptr)); - return std::string(real_path.get()); + return o2::utils::getFullPath(p); } -void NameConf::rectifyDirectory(std::string& dir) +std::string NameConf::rectifyDirectory(const std::string& _dir) { - if (dir.empty() || dir == "none") { - dir = ""; - } else { - dir = o2::base::NameConf::getFullPath(dir); - if (!o2::base::NameConf::pathIsDirectory(dir)) { - throw std::runtime_error(fmt::format("{:s} is not an accessible directory", dir)); - } else { - dir += '/'; - } - } + return o2::utils::rectifyDirectory(_dir); } // Filename to store geometry file From b3fbdd418a8cf7a51052a0f3eaa968dcd5c3064f Mon Sep 17 00:00:00 2001 From: shahoian Date: Thu, 15 Apr 2021 22:50:38 +0200 Subject: [PATCH 142/770] MakeRootTreeWriterSpec get --output-dir option (def:=./) --- .../Utils/include/DPLUtils/MakeRootTreeWriterSpec.h | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Framework/Utils/include/DPLUtils/MakeRootTreeWriterSpec.h b/Framework/Utils/include/DPLUtils/MakeRootTreeWriterSpec.h index 27cfc338b3b92..ebf6258a2f7c3 100644 --- a/Framework/Utils/include/DPLUtils/MakeRootTreeWriterSpec.h +++ b/Framework/Utils/include/DPLUtils/MakeRootTreeWriterSpec.h @@ -62,6 +62,7 @@ namespace framework /// \par The processor spec is generated with the following options: /// /// --outfile +/// --output-dir /// --treename /// --nevents /// --autosave @@ -371,6 +372,7 @@ class MakeRootTreeWriterSpec auto filename = ic.options().get("outfile"); auto treename = ic.options().get("treename"); auto treetitle = ic.options().get("treetitle"); + auto outdir = ic.options().get("output-dir"); processAttributes->nEvents = ic.options().get("nevents"); if (processAttributes->nEvents > 0 && processAttributes->activeInputs.size() != processAttributes->nofBranches) { LOG(WARNING) << "the n inputs serve in total m branches with n != m, this means that there will be data for\n" @@ -394,12 +396,18 @@ class MakeRootTreeWriterSpec auto branchName = ic.options().get(branchNameOptions[branchIndex].first.c_str()); processAttributes->writer->setBranchName(branchIndex, branchName.c_str()); } + if (!outdir.empty() && outdir != "none") { + if (outdir.back() != '/') { + outdir += '/'; + } + filename = outdir + filename; + } processAttributes->writer->init(filename.c_str(), treename.c_str(), treetitle.c_str()); - // the callback to be set as hook at stop of processing for the framework auto finishWriting = [processAttributes]() { processAttributes->writer->close(); }; + ic.services().get().set(CallbackService::Id::Stop, finishWriting); auto processingFct = [processAttributes](ProcessingContext& pc) { @@ -477,6 +485,7 @@ class MakeRootTreeWriterSpec Options options{ // default options {"outfile", VariantType::String, mDefaultFileName.c_str(), {"Name of the output file"}}, + {"output-dir", VariantType::String, mDefaultDir.c_str(), {"Output directory"}}, {"treename", VariantType::String, mDefaultTreeName.c_str(), {"Name of tree"}}, {"treetitle", VariantType::String, mDefaultTreeTitle.c_str(), {"Title of tree"}}, {"nevents", VariantType::Int, mDefaultNofEvents, {"Number of events to execute"}}, @@ -635,6 +644,7 @@ class MakeRootTreeWriterSpec std::string mDefaultFileName; std::string mDefaultTreeName; std::string mDefaultTreeTitle; + std::string mDefaultDir = "./"; int mDefaultNofEvents = -1; int mDefaultAutoSave = -1; std::string mDefaultTerminationPolicy = "process"; From a23f6ee7fe1a93835cca7022e2642886c27c797e Mon Sep 17 00:00:00 2001 From: shahoian Date: Thu, 15 Apr 2021 22:52:01 +0200 Subject: [PATCH 143/770] change option name to output-dir for uniformity --- Detectors/CTF/workflow/src/CTFWriterSpec.cxx | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Detectors/CTF/workflow/src/CTFWriterSpec.cxx b/Detectors/CTF/workflow/src/CTFWriterSpec.cxx index 5212494f5e7a7..32193b3751eb0 100644 --- a/Detectors/CTF/workflow/src/CTFWriterSpec.cxx +++ b/Detectors/CTF/workflow/src/CTFWriterSpec.cxx @@ -95,8 +95,8 @@ class CTFWriterSpec : public o2::framework::Task size_t mNTF = 0; int mSaveDictAfter = -1; // if positive and mWriteCTF==true, save dictionary after each mSaveDictAfter TFs processed uint64_t mRun = 0; - std::string mDictDir = "./"; - std::string mCTFDir = "./"; + std::string mDictDir = ""; + std::string mCTFDir = ""; std::unique_ptr mDictFileOut; // file to store dictionary std::unique_ptr mDictTreeOut; // tree to store dictionary @@ -197,8 +197,8 @@ CTFWriterSpec::CTFWriterSpec(DetID::mask_t dm, uint64_t r, bool doCTF, bool doDi void CTFWriterSpec::init(InitContext& ic) { mSaveDictAfter = ic.options().get("save-dict-after"); - o2::base::NameConf::rectifyDirectory((mDictDir = ic.options().get("ctf-dict-dir"))); - o2::base::NameConf::rectifyDirectory((mCTFDir = ic.options().get("ctf-output-dir"))); + mDictDir = o2::base::NameConf::rectifyDirectory(ic.options().get("ctf-dict-dir")); + mCTFDir = o2::base::NameConf::rectifyDirectory(ic.options().get("output-dir")); } void CTFWriterSpec::run(ProcessingContext& pc) @@ -341,8 +341,8 @@ DataProcessorSpec getCTFWriterSpec(DetID::mask_t dets, uint64_t run, bool doCTF, Outputs{}, AlgorithmSpec{adaptFromTask(dets, run, doCTF, doDict, dictPerDet)}, Options{{"save-dict-after", VariantType::Int, -1, {"In dictionary generation mode save it dictionary after certain number of TFs processed"}}, - {"ctf-dict-dir", VariantType::String, "./", {"CTF dictionary directory"}}, - {"ctf-output-dir", VariantType::String, "./", {"CTF output directory"}}}}; + {"ctf-dict-dir", VariantType::String, "none", {"CTF dictionary directory"}}, + {"output-dir", VariantType::String, "none", {"CTF output directory"}}}}; } } // namespace ctf From 9fe7fbc5238d5725f0c9cb5e7ccdead816ee7160 Mon Sep 17 00:00:00 2001 From: shahoian Date: Thu, 15 Apr 2021 22:53:54 +0200 Subject: [PATCH 144/770] All root-file reader devices got --input-dir option --- Common/Utils/include/CommonUtils/StringUtils.h | 5 ++--- Detectors/CPV/workflow/src/ReaderSpec.cxx | 7 +++++-- Detectors/CTF/workflow/src/CTFReaderSpec.cxx | 6 +++--- Detectors/EMCAL/workflow/src/PublisherSpec.cxx | 5 ++++- Detectors/FIT/FDD/workflow/src/DigitReaderSpec.cxx | 7 +++++-- Detectors/FIT/FDD/workflow/src/RecPointReaderSpec.cxx | 7 +++++-- Detectors/FIT/FT0/workflow/src/DigitReaderSpec.cxx | 7 +++++-- Detectors/FIT/FT0/workflow/src/RecPointReaderSpec.cxx | 7 +++++-- Detectors/FIT/FV0/workflow/src/DigitReaderSpec.cxx | 7 +++++-- .../src/PrimaryVertexReaderSpec.cxx | 7 +++++-- .../src/SecondaryVertexReaderSpec.cxx | 7 +++++-- .../src/TrackCosmicsReaderSpec.cxx | 7 +++++-- .../GlobalTrackingWorkflow/src/TrackTPCITSReaderSpec.cxx | 7 +++++-- .../include/TOFWorkflow/CalibInfoReaderSpec.h | 3 ++- .../tofworkflow/src/CalibInfoReaderSpec.cxx | 8 +++++--- .../tofworkflow/src/TOFMatchedReaderSpec.cxx | 5 ++++- Detectors/ITSMFT/ITS/workflow/src/TrackReaderSpec.cxx | 7 +++++-- Detectors/ITSMFT/ITS/workflow/src/VertexReaderSpec.cxx | 7 +++++-- Detectors/ITSMFT/MFT/workflow/src/ClusterReaderSpec.cxx | 7 +++++-- .../ITSMFT/common/workflow/src/ClusterReaderSpec.cxx | 7 +++++-- Detectors/ITSMFT/common/workflow/src/DigitReaderSpec.cxx | 7 +++++-- Detectors/MUON/MID/Workflow/src/DigitReaderSpec.cxx | 7 +++++-- Detectors/PHOS/workflow/src/ReaderSpec.cxx | 9 +++++++-- Detectors/TOF/workflow/src/ClusterReaderSpec.cxx | 7 +++++-- Detectors/TOF/workflow/src/DigitReaderSpec.cxx | 7 +++++-- Detectors/TPC/workflow/src/PublisherSpec.cxx | 5 ++++- Detectors/TPC/workflow/src/TrackReaderSpec.cxx | 7 +++++-- Detectors/TRD/workflow/src/TRDTrackletReaderSpec.cxx | 8 ++++++-- Detectors/ZDC/workflow/src/DigitReaderSpec.cxx | 7 +++++-- .../Utils/include/DPLUtils/MakeRootTreeWriterSpec.h | 2 +- 30 files changed, 138 insertions(+), 58 deletions(-) diff --git a/Common/Utils/include/CommonUtils/StringUtils.h b/Common/Utils/include/CommonUtils/StringUtils.h index 4a7e0db29db0a..2b73082d13b3f 100644 --- a/Common/Utils/include/CommonUtils/StringUtils.h +++ b/Common/Utils/include/CommonUtils/StringUtils.h @@ -92,13 +92,13 @@ std::string concat_string(Ts const&... ts) return s.str(); } -// Check if the path exists +// Check if the path exists static inline bool pathExists(const std::string_view p) { struct stat buffer; return (stat(p.data(), &buffer) == 0); } - + // Check if the path is a directory static inline bool pathIsDirectory(const std::string_view p) { @@ -128,7 +128,6 @@ static inline std::string rectifyDirectory(const std::string& _dir) return dir; } - } // namespace utils } // namespace o2 diff --git a/Detectors/CPV/workflow/src/ReaderSpec.cxx b/Detectors/CPV/workflow/src/ReaderSpec.cxx index 166488752c2e8..75f81e0959da6 100644 --- a/Detectors/CPV/workflow/src/ReaderSpec.cxx +++ b/Detectors/CPV/workflow/src/ReaderSpec.cxx @@ -16,6 +16,7 @@ #include "DPLUtils/RootTreeReader.h" #include "DPLUtils/MakeRootTreeWriterSpec.h" #include "Framework/DataSpecUtils.h" +#include "DetectorsCommonDataFormats/NameConf.h" #include #include @@ -42,11 +43,11 @@ DataProcessorSpec getDigitsReaderSpec(bool propagateMC) auto initFunction = [propagateMC](InitContext& ic) { // get the option from the init context - auto filename = ic.options().get("infile"); + auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("infile")); auto treename = ic.options().get("treename"); auto nofEvents = ic.options().get("nevents"); auto publishingMode = nofEvents == -1 ? RootTreeReader::PublishingMode::Single : RootTreeReader::PublishingMode::Loop; - auto processAttributes = std::make_shared(); { processAttributes->terminateOnEod = ic.options().get("terminate-on-eod"); @@ -126,6 +127,7 @@ DataProcessorSpec getDigitsReaderSpec(bool propagateMC) AlgorithmSpec(initFunction), Options{ {"infile", VariantType::String, "cpvdigits.root", {"Name of the input file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}, {"treename", VariantType::String, "o2sim", {"Name of input tree"}}, {"nevents", VariantType::Int, -1, {"number of events to run, -1: inf loop"}}, {"terminate-on-eod", VariantType::Bool, true, {"terminate on end-of-data"}}, @@ -222,6 +224,7 @@ DataProcessorSpec getClustersReaderSpec(bool propagateMC) Options{ {"infile", VariantType::String, "cpvclusters.root", {"Name of the input file"}}, {"treename", VariantType::String, "o2sim", {"Name of input tree"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}, {"nevents", VariantType::Int, -1, {"number of events to run, -1: inf loop"}}, {"terminate-on-eod", VariantType::Bool, true, {"terminate on end-of-data"}}, }}; diff --git a/Detectors/CTF/workflow/src/CTFReaderSpec.cxx b/Detectors/CTF/workflow/src/CTFReaderSpec.cxx index e3f9eb95df5fa..14e7aea10fd91 100644 --- a/Detectors/CTF/workflow/src/CTFReaderSpec.cxx +++ b/Detectors/CTF/workflow/src/CTFReaderSpec.cxx @@ -75,7 +75,7 @@ class CTFReaderSpec : public o2::framework::Task std::vector mInput; // input files uint32_t mTFCounter = 0; size_t mNextToProcess = 0; - std::string mCTFDir = "./"; + std::string mCTFDir = ""; TStopwatch mTimer; }; @@ -90,7 +90,7 @@ CTFReaderSpec::CTFReaderSpec(DetID::mask_t dm, const std::string& inp) : mDets(d ///_______________________________________ void CTFReaderSpec::init(InitContext& ic) { - o2::base::NameConf::rectifyDirectory((mCTFDir = ic.options().get("ctf-input-dir"))); + mCTFDir = o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")); } ///_______________________________________ @@ -263,7 +263,7 @@ DataProcessorSpec getCTFReaderSpec(DetID::mask_t dets, const std::string& inp) Inputs{}, outputs, AlgorithmSpec{adaptFromTask(dets, inp)}, - Options{{"ctf-input-dir", VariantType::String, "./", {"CTF input directory"}}}}; + Options{{"input-dir", VariantType::String, "none", {"CTF input directory"}}}}; } } // namespace ctf diff --git a/Detectors/EMCAL/workflow/src/PublisherSpec.cxx b/Detectors/EMCAL/workflow/src/PublisherSpec.cxx index 13a0890405284..1281ce7a6dfb1 100644 --- a/Detectors/EMCAL/workflow/src/PublisherSpec.cxx +++ b/Detectors/EMCAL/workflow/src/PublisherSpec.cxx @@ -8,6 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +#include "DetectorsCommonDataFormats/NameConf.h" #include "DataFormatsEMCAL/EMCALBlockHeader.h" #include "EMCALWorkflow/PublisherSpec.h" #include "Framework/ConfigParamRegistry.h" @@ -33,7 +34,8 @@ o2::framework::DataProcessorSpec createPublisherSpec(PublisherConf const& config auto initFunction = [config, propagateMC, creator](o2::framework::InitContext& ic) { // get the option from the init context - auto filename = ic.options().get("infile"); + auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("infile")); auto treename = ic.options().get("treename"); auto dtbrName = ic.options().get(config.databranch.option.c_str()); // databranch name auto trgbrName = ic.options().get(config.triggerrecordbranch.option.c_str()); // triggerbranch name @@ -106,6 +108,7 @@ o2::framework::DataProcessorSpec createPublisherSpec(PublisherConf const& config o2::framework::AlgorithmSpec(initFunction), o2::framework::Options{ {"infile", o2::framework::VariantType::String, "", {"Name of the input file"}}, + {"input-dir", o2::framework::VariantType::String, "none", {"Input directory"}}, {"treename", o2::framework::VariantType::String, config.defaultTreeName.c_str(), {"Name of input tree"}}, {dtb.option.c_str(), o2::framework::VariantType::String, dtb.defval.c_str(), {dtb.help.c_str()}}, {trb.option.c_str(), o2::framework::VariantType::String, trb.defval.c_str(), {trb.help.c_str()}}, diff --git a/Detectors/FIT/FDD/workflow/src/DigitReaderSpec.cxx b/Detectors/FIT/FDD/workflow/src/DigitReaderSpec.cxx index 6f4c1c83517fc..740e0371137f3 100644 --- a/Detectors/FIT/FDD/workflow/src/DigitReaderSpec.cxx +++ b/Detectors/FIT/FDD/workflow/src/DigitReaderSpec.cxx @@ -20,6 +20,7 @@ #include "FDDWorkflow/DigitReaderSpec.h" #include "SimulationDataFormat/MCTruthContainer.h" #include "SimulationDataFormat/IOMCTruthContainerView.h" +#include "DetectorsCommonDataFormats/NameConf.h" #include using namespace o2::framework; @@ -37,7 +38,8 @@ DigitReader::DigitReader(bool useMC) void DigitReader::init(InitContext& ic) { - mInputFileName = ic.options().get("fdd-digits-infile"); + mInputFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("fdd-digits-infile")); } void DigitReader::run(ProcessingContext& pc) @@ -113,7 +115,8 @@ DataProcessorSpec getFDDDigitReaderSpec(bool useMC) outputSpec, AlgorithmSpec{adaptFromTask()}, Options{ - {"fdd-digits-infile", VariantType::String, "fdddigits.root", {"Name of the input file"}}}}; + {"fdd-digits-infile", VariantType::String, "fdddigits.root", {"Name of the input file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } } // namespace fdd diff --git a/Detectors/FIT/FDD/workflow/src/RecPointReaderSpec.cxx b/Detectors/FIT/FDD/workflow/src/RecPointReaderSpec.cxx index 2fd688e96c490..6576e6d59a87c 100644 --- a/Detectors/FIT/FDD/workflow/src/RecPointReaderSpec.cxx +++ b/Detectors/FIT/FDD/workflow/src/RecPointReaderSpec.cxx @@ -18,6 +18,7 @@ #include "Framework/ConfigParamRegistry.h" #include "Framework/Logger.h" #include "FDDWorkflow/RecPointReaderSpec.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; using namespace o2::fdd; @@ -37,7 +38,8 @@ RecPointReader::RecPointReader(bool useMC) void RecPointReader::init(InitContext& ic) { - mInputFileName = ic.options().get("fdd-recpoints-infile"); + mInputFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("fdd-recpoints-infile")); connectTree(mInputFileName); } @@ -87,7 +89,8 @@ DataProcessorSpec getFDDRecPointReaderSpec(bool useMC) outputSpec, AlgorithmSpec{adaptFromTask()}, Options{ - {"fdd-recpoints-infile", VariantType::String, "o2reco_fdd.root", {"Name of the input file"}}}}; + {"fdd-recpoints-infile", VariantType::String, "o2reco_fdd.root", {"Name of the input file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } } // namespace fdd diff --git a/Detectors/FIT/FT0/workflow/src/DigitReaderSpec.cxx b/Detectors/FIT/FT0/workflow/src/DigitReaderSpec.cxx index 3aa0afec0b96d..1752e84179cdb 100644 --- a/Detectors/FIT/FT0/workflow/src/DigitReaderSpec.cxx +++ b/Detectors/FIT/FT0/workflow/src/DigitReaderSpec.cxx @@ -22,6 +22,7 @@ #include "DataFormatsFT0/ChannelData.h" #include "DataFormatsFT0/MCLabel.h" #include "SimulationDataFormat/MCTruthContainer.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; @@ -32,7 +33,8 @@ namespace ft0 void DigitReader::init(InitContext& ic) { - auto filename = ic.options().get("ft0-digit-infile"); + auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("ft0-digit-infile")); mFile = std::make_unique(filename.c_str(), "OLD"); if (!mFile->IsOpen()) { LOG(ERROR) << "Cannot open the " << filename.c_str() << " file !"; @@ -95,7 +97,8 @@ DataProcessorSpec getDigitReaderSpec(bool useMC, bool useTrgInput) outputs, AlgorithmSpec{adaptFromTask(useMC, useTrgInput)}, Options{ - {"ft0-digit-infile", VariantType::String, "ft0digits.root", {"Name of the input file"}}}}; + {"ft0-digit-infile", VariantType::String, "ft0digits.root", {"Name of the input file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } } // namespace ft0 diff --git a/Detectors/FIT/FT0/workflow/src/RecPointReaderSpec.cxx b/Detectors/FIT/FT0/workflow/src/RecPointReaderSpec.cxx index ef9c03c8b6618..be46819c1fb78 100644 --- a/Detectors/FIT/FT0/workflow/src/RecPointReaderSpec.cxx +++ b/Detectors/FIT/FT0/workflow/src/RecPointReaderSpec.cxx @@ -18,6 +18,7 @@ #include "Framework/ControlService.h" #include "Framework/Logger.h" #include "FT0Workflow/RecPointReaderSpec.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; using namespace o2::ft0; @@ -37,7 +38,8 @@ RecPointReader::RecPointReader(bool useMC) void RecPointReader::init(InitContext& ic) { - mInputFileName = ic.options().get("ft0-recpoints-infile"); + mInputFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("ft0-recpoints-infile")); connectTree(mInputFileName); } @@ -87,7 +89,8 @@ DataProcessorSpec getRecPointReaderSpec(bool useMC) outputSpec, AlgorithmSpec{adaptFromTask()}, Options{ - {"ft0-recpoints-infile", VariantType::String, "o2reco_ft0.root", {"Name of the input file"}}}}; + {"ft0-recpoints-infile", VariantType::String, "o2reco_ft0.root", {"Name of the input file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } } // namespace ft0 diff --git a/Detectors/FIT/FV0/workflow/src/DigitReaderSpec.cxx b/Detectors/FIT/FV0/workflow/src/DigitReaderSpec.cxx index 781950909edc1..bd9d87597c7b0 100644 --- a/Detectors/FIT/FV0/workflow/src/DigitReaderSpec.cxx +++ b/Detectors/FIT/FV0/workflow/src/DigitReaderSpec.cxx @@ -22,6 +22,7 @@ #include "DataFormatsFV0/ChannelData.h" #include "DataFormatsFV0/MCLabel.h" #include "SimulationDataFormat/MCTruthContainer.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; @@ -32,7 +33,8 @@ namespace fv0 void DigitReader::init(InitContext& ic) { - auto filename = ic.options().get("fv0-digit-infile"); + auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("fv0-digit-infile")); mFile = std::make_unique(filename.c_str(), "OLD"); if (!mFile->IsOpen()) { LOG(ERROR) << "Cannot open the " << filename.c_str() << " file !"; @@ -85,7 +87,8 @@ DataProcessorSpec getDigitReaderSpec(bool useMC) outputs, AlgorithmSpec{adaptFromTask(useMC)}, Options{ - {"fv0-digit-infile", VariantType::String, "fv0digits.root", {"Name of the input file"}}}}; + {"fv0-digit-infile", VariantType::String, "fv0digits.root", {"Name of the input file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } } // namespace fv0 diff --git a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexReaderSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexReaderSpec.cxx index a5640d7503689..fbe0b6290f479 100644 --- a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexReaderSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexReaderSpec.cxx @@ -16,6 +16,7 @@ #include "Framework/ConfigParamRegistry.h" #include "Framework/Logger.h" #include "GlobalTrackingWorkflow/PrimaryVertexReaderSpec.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; @@ -26,7 +27,8 @@ namespace vertexing void PrimaryVertexReader::init(InitContext& ic) { - mFileName = ic.options().get("primary-vertex-infile"); + mFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("primary-vertex-infile")); connectTree(); } @@ -121,7 +123,8 @@ DataProcessorSpec getPrimaryVertexReaderSpec(bool useMC) AlgorithmSpec{adaptFromTask(useMC)}, Options{ {"primary-vertex-infile", VariantType::String, "o2_primary_vertex.root", {"Name of the input primary vertex file"}}, - {"vertex-track-matches-infile", VariantType::String, "o2_pvertex_track_matches.root", {"Name of the input file with primary vertex - tracks matches"}}}}; + {"vertex-track-matches-infile", VariantType::String, "o2_pvertex_track_matches.root", {"Name of the input file with primary vertex - tracks matches"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } } // namespace vertexing diff --git a/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexReaderSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexReaderSpec.cxx index 4ac021d3dad05..7618e6c56c66f 100644 --- a/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexReaderSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexReaderSpec.cxx @@ -16,6 +16,7 @@ #include "Framework/ConfigParamRegistry.h" #include "Framework/Logger.h" #include "GlobalTrackingWorkflow/SecondaryVertexReaderSpec.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; @@ -26,7 +27,8 @@ namespace vertexing void SecondaryVertexReader::init(InitContext& ic) { - mFileName = ic.options().get("secondary-vertex-infile"); + mFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("secondary-vertex-infile")); connectTree(); } @@ -82,7 +84,8 @@ DataProcessorSpec getSecondaryVertexReaderSpec() outputs, AlgorithmSpec{adaptFromTask()}, Options{ - {"secondary-vertex-infile", VariantType::String, "o2_secondary_vertex.root", {"Name of the input secondary vertex file"}}}}; + {"secondary-vertex-infile", VariantType::String, "o2_secondary_vertex.root", {"Name of the input secondary vertex file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } } // namespace vertexing diff --git a/Detectors/GlobalTrackingWorkflow/src/TrackCosmicsReaderSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/TrackCosmicsReaderSpec.cxx index 3e7e351171f9b..ba181c59a1052 100644 --- a/Detectors/GlobalTrackingWorkflow/src/TrackCosmicsReaderSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/TrackCosmicsReaderSpec.cxx @@ -17,6 +17,7 @@ #include "GlobalTrackingWorkflow/TrackCosmicsReaderSpec.h" #include "DataFormatsParameters/GRPObject.h" #include "Framework/SerializationMethods.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; using namespace o2::globaltracking; @@ -27,7 +28,8 @@ namespace globaltracking { void TrackCosmicsReader::init(InitContext& ic) { - mFileName = ic.options().get("cosmics-infile"); + mFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("cosmics-infile")); connectTree(mFileName); } @@ -77,7 +79,8 @@ DataProcessorSpec getTrackCosmicsReaderSpec(bool useMC) outputs, AlgorithmSpec{adaptFromTask(useMC)}, Options{ - {"cosmics-infile", VariantType::String, "cosmics.root", {"Name of the input file"}}}}; + {"cosmics-infile", VariantType::String, "cosmics.root", {"Name of the input file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } } // namespace globaltracking diff --git a/Detectors/GlobalTrackingWorkflow/src/TrackTPCITSReaderSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/TrackTPCITSReaderSpec.cxx index 6fc047ef0e035..340244fd0e3b9 100644 --- a/Detectors/GlobalTrackingWorkflow/src/TrackTPCITSReaderSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/TrackTPCITSReaderSpec.cxx @@ -17,6 +17,7 @@ #include "GlobalTrackingWorkflow/TrackTPCITSReaderSpec.h" #include "DataFormatsParameters/GRPObject.h" #include "Framework/SerializationMethods.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; using namespace o2::globaltracking; @@ -27,7 +28,8 @@ namespace globaltracking { void TrackTPCITSReader::init(InitContext& ic) { - mFileName = ic.options().get("itstpc-track-infile"); + mFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("itstpc-track-infile")); connectTree(mFileName); } @@ -77,7 +79,8 @@ DataProcessorSpec getTrackTPCITSReaderSpec(bool useMC) outputs, AlgorithmSpec{adaptFromTask(useMC)}, Options{ - {"itstpc-track-infile", VariantType::String, "o2match_itstpc.root", {"Name of the input file"}}}}; + {"itstpc-track-infile", VariantType::String, "o2match_itstpc.root", {"Name of the input file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } } // namespace globaltracking diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/include/TOFWorkflow/CalibInfoReaderSpec.h b/Detectors/GlobalTrackingWorkflow/tofworkflow/include/TOFWorkflow/CalibInfoReaderSpec.h index 2c46fa4e267f9..3e72aa4cab713 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/include/TOFWorkflow/CalibInfoReaderSpec.h +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/include/TOFWorkflow/CalibInfoReaderSpec.h @@ -18,6 +18,7 @@ #include "Framework/DataProcessorSpec.h" #include "Framework/Task.h" #include "DataFormatsTOF/CalibInfoTOF.h" +#include class TTree; @@ -40,7 +41,7 @@ class CalibInfoReader : public Task int mState = 0; int mInstance; int mNinstances; - const char* mFileName = nullptr; + std::string mFileName{}; FILE* mFile = nullptr; TTree* mTree = nullptr; bool mTOFTPC = false; diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/CalibInfoReaderSpec.cxx b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/CalibInfoReaderSpec.cxx index 7fa1261920bab..3423cd076b06e 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/CalibInfoReaderSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/CalibInfoReaderSpec.cxx @@ -20,6 +20,7 @@ #include "Framework/ConfigParamRegistry.h" #include "Framework/Logger.h" #include "TOFWorkflow/CalibInfoReaderSpec.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; using namespace o2::tof; @@ -34,9 +35,10 @@ constexpr o2::header::DataDescription ddCalib{"CALIBDATA"}, ddCalib_tpc{"CALIBDA void CalibInfoReader::init(InitContext& ic) { LOG(INFO) << "Init CalibInfo reader!"; - mFile = fopen(mFileName, "r"); + auto fname = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), mFileName); + mFile = fopen(fname.c_str(), "r"); if (!mFile) { - LOG(ERROR) << "Cannot open the " << mFileName << " file !"; + LOG(ERROR) << "Cannot open the " << fname << " file !"; mState = 0; return; } @@ -91,7 +93,7 @@ DataProcessorSpec getCalibInfoReaderSpec(int instance, int ninstances, const cha Inputs{}, outputs, AlgorithmSpec{adaptFromTask(instance, ninstances, filename)}, - Options{/* for the moment no options */}}; + Options{{"input-dir", VariantType::String, "none", {"Input directory"}}}}; } } // namespace tof } // namespace o2 diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/TOFMatchedReaderSpec.cxx b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/TOFMatchedReaderSpec.cxx index 2f8cd069deba2..61b8b424b8eda 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/TOFMatchedReaderSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/TOFMatchedReaderSpec.cxx @@ -23,6 +23,7 @@ #include "SimulationDataFormat/MCTruthContainer.h" #include "ReconstructionDataFormats/MatchInfoTOF.h" #include "CommonUtils/StringUtils.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; @@ -37,7 +38,8 @@ void TOFMatchedReader::init(InitContext& ic) { // get the option from the init context LOG(INFO) << "Init TOF matching info reader!"; - mInFileName = ic.options().get("tof-matched-infile"); + mInFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("tof-matched-infile")); mInTreeName = ic.options().get("treename"); connectTree(mInFileName); } @@ -102,6 +104,7 @@ DataProcessorSpec getTOFMatchedReaderSpec(bool useMC, bool tpcmatch, bool readTr AlgorithmSpec{adaptFromTask(useMC, tpcmatch, readTracks)}, Options{ {"tof-matched-infile", VariantType::String, tpcmatch ? "o2match_toftpc.root" : "o2match_tof.root", {"Name of the input file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}, {"treename", VariantType::String, "matchTOF", {"Name of top-level TTree"}}, }}; } diff --git a/Detectors/ITSMFT/ITS/workflow/src/TrackReaderSpec.cxx b/Detectors/ITSMFT/ITS/workflow/src/TrackReaderSpec.cxx index bd19dd45a0060..f0a1bac2dd354 100644 --- a/Detectors/ITSMFT/ITS/workflow/src/TrackReaderSpec.cxx +++ b/Detectors/ITSMFT/ITS/workflow/src/TrackReaderSpec.cxx @@ -15,6 +15,7 @@ #include "Framework/ControlService.h" #include "Framework/ConfigParamRegistry.h" #include "ITSWorkflow/TrackReaderSpec.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; using namespace o2::its; @@ -31,7 +32,8 @@ TrackReader::TrackReader(bool useMC) void TrackReader::init(InitContext& ic) { - mInputFileName = ic.options().get("its-tracks-infile"); + mInputFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("its-tracks-infile")); connectTree(mInputFileName); } @@ -107,7 +109,8 @@ DataProcessorSpec getITSTrackReaderSpec(bool useMC) outputSpec, AlgorithmSpec{adaptFromTask(useMC)}, Options{ - {"its-tracks-infile", VariantType::String, "o2trac_its.root", {"Name of the input track file"}}}}; + {"its-tracks-infile", VariantType::String, "o2trac_its.root", {"Name of the input track file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } } // namespace its diff --git a/Detectors/ITSMFT/ITS/workflow/src/VertexReaderSpec.cxx b/Detectors/ITSMFT/ITS/workflow/src/VertexReaderSpec.cxx index 31a3d29dacfed..1b07168e67416 100644 --- a/Detectors/ITSMFT/ITS/workflow/src/VertexReaderSpec.cxx +++ b/Detectors/ITSMFT/ITS/workflow/src/VertexReaderSpec.cxx @@ -16,6 +16,7 @@ #include "Framework/ConfigParamRegistry.h" #include "Framework/Logger.h" #include "ITSWorkflow/VertexReaderSpec.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; using namespace o2::its; @@ -27,7 +28,8 @@ namespace its void VertexReader::init(InitContext& ic) { - mFileName = ic.options().get("its-vertex-infile"); + mFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("its-vertex-infile")); connectTree(mFileName); } @@ -73,7 +75,8 @@ DataProcessorSpec getITSVertexReaderSpec() outputSpec, AlgorithmSpec{adaptFromTask()}, Options{ - {"its-vertex-infile", VariantType::String, "o2trac_its.root", {"Name of the input ITS vertex file"}}}}; + {"its-vertex-infile", VariantType::String, "o2trac_its.root", {"Name of the input ITS vertex file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } } // namespace its diff --git a/Detectors/ITSMFT/MFT/workflow/src/ClusterReaderSpec.cxx b/Detectors/ITSMFT/MFT/workflow/src/ClusterReaderSpec.cxx index 896aacf27d59b..7cce47c89e778 100644 --- a/Detectors/ITSMFT/MFT/workflow/src/ClusterReaderSpec.cxx +++ b/Detectors/ITSMFT/MFT/workflow/src/ClusterReaderSpec.cxx @@ -22,6 +22,7 @@ #include "DataFormatsITSMFT/ROFRecord.h" #include "SimulationDataFormat/MCCompLabel.h" #include "SimulationDataFormat/MCTruthContainer.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; using namespace o2::itsmft; @@ -33,7 +34,8 @@ namespace mft void ClusterReader::init(InitContext& ic) { - auto filename = ic.options().get("mft-cluster-infile"); + auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("mft-cluster-infile")); mFile = std::make_unique(filename.c_str(), "OLD"); if (!mFile->IsOpen()) { LOG(ERROR) << "Cannot open the " << filename.c_str() << " file !"; @@ -100,7 +102,8 @@ DataProcessorSpec getClusterReaderSpec(bool useMC) outputs, AlgorithmSpec{adaptFromTask(useMC)}, Options{ - {"mft-cluster-infile", VariantType::String, "mftclusters.root", {"Name of the input file"}}}}; + {"mft-cluster-infile", VariantType::String, "mftclusters.root", {"Name of the input file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } } // namespace mft diff --git a/Detectors/ITSMFT/common/workflow/src/ClusterReaderSpec.cxx b/Detectors/ITSMFT/common/workflow/src/ClusterReaderSpec.cxx index 5047a52807531..4d5e62fc2b4e8 100644 --- a/Detectors/ITSMFT/common/workflow/src/ClusterReaderSpec.cxx +++ b/Detectors/ITSMFT/common/workflow/src/ClusterReaderSpec.cxx @@ -19,6 +19,7 @@ #include "Framework/Logger.h" #include "ITSMFTWorkflow/ClusterReaderSpec.h" #include +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; using namespace o2::itsmft; @@ -39,7 +40,8 @@ ClusterReader::ClusterReader(o2::detectors::DetID id, bool useMC, bool usePatter void ClusterReader::init(InitContext& ic) { - mFileName = ic.options().get((mDetNameLC + "-cluster-infile").c_str()); + mFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get((mDetNameLC + "-cluster-infile").c_str())); connectTree(mFileName); } @@ -136,7 +138,8 @@ DataProcessorSpec getMFTClusterReaderSpec(bool useMC, bool usePatterns) outputSpec, AlgorithmSpec{adaptFromTask(useMC, usePatterns)}, Options{ - {"mft-cluster-infile", VariantType::String, "o2clus_mft.root", {"Name of the input cluster file"}}}}; + {"mft-cluster-infile", VariantType::String, "o2clus_mft.root", {"Name of the input cluster file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } } // namespace itsmft diff --git a/Detectors/ITSMFT/common/workflow/src/DigitReaderSpec.cxx b/Detectors/ITSMFT/common/workflow/src/DigitReaderSpec.cxx index a54e8a2608618..9f56dde5900bf 100644 --- a/Detectors/ITSMFT/common/workflow/src/DigitReaderSpec.cxx +++ b/Detectors/ITSMFT/common/workflow/src/DigitReaderSpec.cxx @@ -21,6 +21,7 @@ #include "SimulationDataFormat/MCCompLabel.h" #include "SimulationDataFormat/ConstMCTruthContainer.h" #include "SimulationDataFormat/IOMCTruthContainerView.h" +#include "DetectorsCommonDataFormats/NameConf.h" #include using namespace o2::framework; @@ -51,7 +52,8 @@ DigitReader::DigitReader(o2::detectors::DetID id, bool useMC, bool useCalib) void DigitReader::init(InitContext& ic) { - mFileName = ic.options().get((mDetNameLC + "-digit-infile").c_str()); + mFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get((mDetNameLC + "-digit-infile").c_str())); connectTree(mFileName); } @@ -155,7 +157,8 @@ DataProcessorSpec getMFTDigitReaderSpec(bool useMC, bool useCalib, std::string d outputSpec, AlgorithmSpec{adaptFromTask(useMC, useCalib)}, Options{ - {"mft-digit-infile", VariantType::String, defname, {"Name of the input digit file"}}}}; + {"mft-digit-infile", VariantType::String, defname, {"Name of the input digit file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } } // namespace itsmft diff --git a/Detectors/MUON/MID/Workflow/src/DigitReaderSpec.cxx b/Detectors/MUON/MID/Workflow/src/DigitReaderSpec.cxx index 1e87b11e22648..04b50383fa0e0 100644 --- a/Detectors/MUON/MID/Workflow/src/DigitReaderSpec.cxx +++ b/Detectors/MUON/MID/Workflow/src/DigitReaderSpec.cxx @@ -32,6 +32,7 @@ #include "DataFormatsMID/ROFRecord.h" #include "MIDSimulation/ColumnDataMC.h" #include "MIDSimulation/MCLabel.h" +#include "DetectorsCommonDataFormats/NameConf.h" namespace of = o2::framework; @@ -46,7 +47,8 @@ class DigitsReaderDeviceDPL DigitsReaderDeviceDPL(bool useMC, const std::vector& descriptions) : mUseMC(useMC), mDescriptions(descriptions) {} void init(o2::framework::InitContext& ic) { - auto filename = ic.options().get("mid-digit-infile"); + auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("mid-digit-infile")); mFile = std::make_unique(filename.c_str()); if (!mFile->IsOpen()) { LOG(ERROR) << "Cannot open the " << filename << " file !"; @@ -129,7 +131,8 @@ framework::DataProcessorSpec getDigitReaderSpec(bool useMC, const char* baseDesc of::Inputs{}, outputs, of::AlgorithmSpec{of::adaptFromTask(useMC, descriptions)}, - of::Options{{"mid-digit-infile", of::VariantType::String, "middigits.root", {"Name of the input file"}}}}; + of::Options{{"mid-digit-infile", of::VariantType::String, "middigits.root", {"Name of the input file"}}, + {"input-dir", of::VariantType::String, "none", {"Input directory"}}}}; } } // namespace mid } // namespace o2 diff --git a/Detectors/PHOS/workflow/src/ReaderSpec.cxx b/Detectors/PHOS/workflow/src/ReaderSpec.cxx index b2bb1f37bd2a2..a0afec314b5d6 100644 --- a/Detectors/PHOS/workflow/src/ReaderSpec.cxx +++ b/Detectors/PHOS/workflow/src/ReaderSpec.cxx @@ -16,6 +16,7 @@ #include "DPLUtils/RootTreeReader.h" #include "DPLUtils/MakeRootTreeWriterSpec.h" #include "Framework/DataSpecUtils.h" +#include "DetectorsCommonDataFormats/NameConf.h" #include #include @@ -42,7 +43,8 @@ DataProcessorSpec getDigitsReaderSpec(bool propagateMC) auto initFunction = [propagateMC](InitContext& ic) { // get the option from the init context - auto filename = ic.options().get("infile"); + auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("infile")); auto treename = ic.options().get("treename"); auto nofEvents = ic.options().get("nevents"); auto publishingMode = nofEvents == -1 ? RootTreeReader::PublishingMode::Single : RootTreeReader::PublishingMode::Loop; @@ -126,6 +128,7 @@ DataProcessorSpec getDigitsReaderSpec(bool propagateMC) AlgorithmSpec(initFunction), Options{ {"infile", VariantType::String, "phosdigits.root", {"Name of the input file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}, {"treename", VariantType::String, "o2sim", {"Name of input tree"}}, {"nevents", VariantType::Int, -1, {"number of events to run, -1: inf loop"}}, {"terminate-on-eod", VariantType::Bool, true, {"terminate on end-of-data"}}, @@ -139,7 +142,8 @@ DataProcessorSpec getCellReaderSpec(bool propagateMC) auto initFunction = [propagateMC](InitContext& ic) { // get the option from the init context - auto filename = ic.options().get("infile"); + auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("infile")); auto treename = ic.options().get("treename"); auto nofEvents = ic.options().get("nevents"); auto publishingMode = nofEvents == -1 ? RootTreeReader::PublishingMode::Single : RootTreeReader::PublishingMode::Loop; @@ -225,6 +229,7 @@ DataProcessorSpec getCellReaderSpec(bool propagateMC) AlgorithmSpec(initFunction), Options{ {"infile", VariantType::String, "phoscells.root", {"Name of the input file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}, {"treename", VariantType::String, "o2sim", {"Name of input tree"}}, {"nevents", VariantType::Int, -1, {"number of events to run, -1: inf loop"}}, {"terminate-on-eod", VariantType::Bool, true, {"terminate on end-of-data"}}, diff --git a/Detectors/TOF/workflow/src/ClusterReaderSpec.cxx b/Detectors/TOF/workflow/src/ClusterReaderSpec.cxx index f9c422307bab3..1a0a081c1174d 100644 --- a/Detectors/TOF/workflow/src/ClusterReaderSpec.cxx +++ b/Detectors/TOF/workflow/src/ClusterReaderSpec.cxx @@ -16,6 +16,7 @@ #include "Framework/ConfigParamRegistry.h" #include "TOFWorkflowUtils/ClusterReaderSpec.h" #include "DataFormatsParameters/GRPObject.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; using namespace o2::tof; @@ -28,7 +29,8 @@ namespace tof void ClusterReader::init(InitContext& ic) { LOG(INFO) << "Init Cluster reader!"; - mFileName = ic.options().get("tof-cluster-infile"); + mFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("tof-cluster-infile")); connectTree(mFileName); } @@ -78,7 +80,8 @@ DataProcessorSpec getClusterReaderSpec(bool useMC) outputs, AlgorithmSpec{adaptFromTask(useMC)}, Options{ - {"tof-cluster-infile", VariantType::String, "tofclusters.root", {"Name of the input file"}}}}; + {"tof-cluster-infile", VariantType::String, "tofclusters.root", {"Name of the input file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } } // namespace tof diff --git a/Detectors/TOF/workflow/src/DigitReaderSpec.cxx b/Detectors/TOF/workflow/src/DigitReaderSpec.cxx index a987aa493515c..d4034aea05ba7 100644 --- a/Detectors/TOF/workflow/src/DigitReaderSpec.cxx +++ b/Detectors/TOF/workflow/src/DigitReaderSpec.cxx @@ -19,6 +19,7 @@ #include "Framework/Logger.h" #include "TOFWorkflowUtils/DigitReaderSpec.h" #include "DataFormatsParameters/GRPObject.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; using namespace o2::tof; @@ -31,7 +32,8 @@ namespace tof void DigitReader::init(InitContext& ic) { LOG(INFO) << "Init Digit reader!"; - auto filename = ic.options().get("tof-digit-infile"); + auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("tof-digit-infile")); mFile = std::make_unique(filename.c_str(), "OLD"); if (!mFile->IsOpen()) { LOG(ERROR) << "Cannot open the " << filename.c_str() << " file !"; @@ -103,7 +105,8 @@ DataProcessorSpec getDigitReaderSpec(bool useMC) outputs, AlgorithmSpec{adaptFromTask(useMC)}, Options{ - {"tof-digit-infile", VariantType::String, "tofdigits.root", {"Name of the input file"}}}}; + {"tof-digit-infile", VariantType::String, "tofdigits.root", {"Name of the input file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } } // namespace tof diff --git a/Detectors/TPC/workflow/src/PublisherSpec.cxx b/Detectors/TPC/workflow/src/PublisherSpec.cxx index ddf833c2d7e12..203bb9facd588 100644 --- a/Detectors/TPC/workflow/src/PublisherSpec.cxx +++ b/Detectors/TPC/workflow/src/PublisherSpec.cxx @@ -18,6 +18,7 @@ #include "TPCWorkflow/PublisherSpec.h" #include "Headers/DataHeader.h" #include "TPCBase/Sector.h" +#include "DetectorsCommonDataFormats/NameConf.h" #include "DataFormatsTPC/TPCSectorHeader.h" #include // for make_shared, make_unique, unique_ptr #include @@ -63,7 +64,8 @@ DataProcessorSpec createPublisherSpec(PublisherConf const& config, bool propagat auto initFunction = [config, propagateMC, creator](InitContext& ic) { // get the option from the init context - auto filename = ic.options().get("infile"); + auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("infile")); auto treename = ic.options().get("treename"); auto clbrName = ic.options().get(config.databranch.option.c_str()); auto mcbrName = ic.options().get(config.mcbranch.option.c_str()); @@ -236,6 +238,7 @@ DataProcessorSpec createPublisherSpec(PublisherConf const& config, bool propagat AlgorithmSpec(initFunction), Options{ {"infile", VariantType::String, config.defaultFileName.c_str(), {"Name of the input file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}, {"treename", VariantType::String, config.defaultTreeName.c_str(), {"Name of input tree"}}, {dtb.option.c_str(), VariantType::String, dtb.defval.c_str(), {dtb.help.c_str()}}, {mcb.option.c_str(), VariantType::String, mcb.defval.c_str(), {mcb.help.c_str()}}, diff --git a/Detectors/TPC/workflow/src/TrackReaderSpec.cxx b/Detectors/TPC/workflow/src/TrackReaderSpec.cxx index da9a1c6ef7907..338b2ffa81266 100644 --- a/Detectors/TPC/workflow/src/TrackReaderSpec.cxx +++ b/Detectors/TPC/workflow/src/TrackReaderSpec.cxx @@ -14,6 +14,7 @@ #include "Framework/ControlService.h" #include "Framework/ConfigParamRegistry.h" #include "TPCWorkflow/TrackReaderSpec.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; @@ -29,7 +30,8 @@ TrackReader::TrackReader(bool useMC) void TrackReader::init(InitContext& ic) { - mInputFileName = ic.options().get("infile"); + mInputFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("infile")); connectTree(mInputFileName); } @@ -131,7 +133,8 @@ DataProcessorSpec getTPCTrackReaderSpec(bool useMC) outputSpec, AlgorithmSpec{adaptFromTask(useMC)}, Options{ - {"infile", VariantType::String, "tpctracks.root", {"Name of the input track file"}}}}; + {"infile", VariantType::String, "tpctracks.root", {"Name of the input track file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } } // namespace tpc diff --git a/Detectors/TRD/workflow/src/TRDTrackletReaderSpec.cxx b/Detectors/TRD/workflow/src/TRDTrackletReaderSpec.cxx index b9f5a5ec5a19d..ab53c8ec1efa9 100644 --- a/Detectors/TRD/workflow/src/TRDTrackletReaderSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDTrackletReaderSpec.cxx @@ -16,6 +16,7 @@ #include "Framework/ControlService.h" #include "Framework/ConfigParamRegistry.h" #include "fairlogger/Logger.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; @@ -28,8 +29,10 @@ void TRDTrackletReader::init(InitContext& ic) { // get the option from the init context LOG(INFO) << "Init TRD tracklet reader!"; - mInFileNameTrklt = ic.options().get("trd-tracklet-infile"); - mInTreeNameTrklt = ic.options().get("treename"); + mInFileNameTrklt = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("trd-tracklet-infile")); + mInTreeNameTrklt = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("treename")); connectTree(); if (mUseTrackletTransform) { connectTreeCTracklet(); @@ -107,6 +110,7 @@ DataProcessorSpec getTRDTrackletReaderSpec(bool useMC, bool useCalibratedTrackle AlgorithmSpec{adaptFromTask(useMC, useCalibratedTracklets)}, Options{ {"trd-tracklet-infile", VariantType::String, "trdtracklets.root", {"Name of the input file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}, {"treename", VariantType::String, "o2sim", {"Name of top-level TTree"}}, }}; } diff --git a/Detectors/ZDC/workflow/src/DigitReaderSpec.cxx b/Detectors/ZDC/workflow/src/DigitReaderSpec.cxx index 98e94b2b099e9..809660efb573c 100644 --- a/Detectors/ZDC/workflow/src/DigitReaderSpec.cxx +++ b/Detectors/ZDC/workflow/src/DigitReaderSpec.cxx @@ -23,6 +23,7 @@ #include "DataFormatsZDC/OrbitData.h" #include "DataFormatsZDC/MCLabel.h" #include "SimulationDataFormat/MCTruthContainer.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; @@ -33,7 +34,8 @@ namespace zdc void DigitReader::init(InitContext& ic) { - auto filename = ic.options().get("zdc-digit-infile"); + auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("zdc-digit-infile")); mFile = std::make_unique(filename.c_str()); if (!mFile->IsOpen()) { LOG(ERROR) << "Cannot open the " << filename.c_str() << " file !"; @@ -89,7 +91,8 @@ DataProcessorSpec getDigitReaderSpec(bool useMC) outputs, AlgorithmSpec{adaptFromTask(useMC)}, Options{ - {"zdc-digit-infile", VariantType::String, "zdcdigits.root", {"Name of the input file"}}}}; + {"zdc-digit-infile", VariantType::String, "zdcdigits.root", {"Name of the input file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } } // namespace zdc diff --git a/Framework/Utils/include/DPLUtils/MakeRootTreeWriterSpec.h b/Framework/Utils/include/DPLUtils/MakeRootTreeWriterSpec.h index ebf6258a2f7c3..01f3615dc7ca9 100644 --- a/Framework/Utils/include/DPLUtils/MakeRootTreeWriterSpec.h +++ b/Framework/Utils/include/DPLUtils/MakeRootTreeWriterSpec.h @@ -644,7 +644,7 @@ class MakeRootTreeWriterSpec std::string mDefaultFileName; std::string mDefaultTreeName; std::string mDefaultTreeTitle; - std::string mDefaultDir = "./"; + std::string mDefaultDir = "none"; int mDefaultNofEvents = -1; int mDefaultAutoSave = -1; std::string mDefaultTerminationPolicy = "process"; From 001c39df0d500f63bb3a5fa3806476214b06c8e4 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 16 Apr 2021 13:58:07 +0200 Subject: [PATCH 145/770] Full system test: Tuning 8 GPU EPN workflow settings (#5940) * Full system test: Tuning 8 GPU EPN workflow settings * Full system test: Use variable to define input raw channel name --- prodtests/full-system-test/datadistribution.sh | 3 ++- prodtests/full-system-test/dpl-workflow.sh | 10 +++++----- prodtests/full-system-test/raw-reader.sh | 2 +- prodtests/full-system-test/setenv.sh | 1 + prodtests/full-system-test/start_tmux.sh | 2 +- 5 files changed, 10 insertions(+), 8 deletions(-) diff --git a/prodtests/full-system-test/datadistribution.sh b/prodtests/full-system-test/datadistribution.sh index 0db3a37922fdc..241f5f3b5eb86 100755 --- a/prodtests/full-system-test/datadistribution.sh +++ b/prodtests/full-system-test/datadistribution.sh @@ -18,7 +18,7 @@ export TFRATE=$(awk "BEGIN {printf \"%.6f\",1/$TFDELAY}") ARGS_ALL="--session default --severity $SEVERITY --shm-segment-size $SHMSIZE --no-cleanup" StfBuilder --id stfb --transport shmem \ - --dpl-channel-name dpl-chan --channel-config "name=dpl-chan,type=push,method=bind,address=ipc://@stfb-to-dpl,transport=shmem,rateLogging=1" \ + --dpl-channel-name dpl-chan --channel-config "name=dpl-chan,type=push,method=bind,address=ipc://@$INRAWCHANNAME,transport=shmem,rateLogging=1" \ --data-source-dir ${TF_DIR} \ --data-source-rate=${TFRATE} \ --data-source-repeat \ @@ -26,5 +26,6 @@ StfBuilder --id stfb --transport shmem \ --data-source-headersize=1024 \ --data-source-enable \ --data-source-preread 5 \ + --shm-no-cleanup on \ --control=static \ ${ARGS_ALL} diff --git a/prodtests/full-system-test/dpl-workflow.sh b/prodtests/full-system-test/dpl-workflow.sh index 0e3bfcf5c7edb..b0c3dcea66c24 100755 --- a/prodtests/full-system-test/dpl-workflow.sh +++ b/prodtests/full-system-test/dpl-workflow.sh @@ -69,11 +69,11 @@ if [ $HOSTMEMSIZE != "0" ]; then fi if [ $EPNPIPELINES != 0 ]; then - N_TPCENT=$(($(expr 7 \* $EPNPIPELINES \* $NGPUS / 4) > 0 ? $(expr 7 \* $EPNPIPELINES \* $NGPUS / 4) : 1)) - N_TPCITS=$(($(expr 7 \* $EPNPIPELINES \* $NGPUS / 4) > 0 ? $(expr 7 \* $EPNPIPELINES \* $NGPUS / 4) : 1)) + N_TPCENT=$(($(expr 3 \* $EPNPIPELINES \* $NGPUS / 4) > 0 ? $(expr 3 \* $EPNPIPELINES \* $NGPUS / 4) : 1)) + N_TPCITS=$(($(expr 3 \* $EPNPIPELINES \* $NGPUS / 4) > 0 ? $(expr 3 \* $EPNPIPELINES \* $NGPUS / 4) : 1)) N_ITSDEC=$(($(expr 3 \* $EPNPIPELINES \* $NGPUS / 4) > 0 ? $(expr 3 \* $EPNPIPELINES \* $NGPUS / 4) : 1)) - N_EMC=$(($(expr 2 \* $EPNPIPELINES \* $NGPUS / 4) > 0 ? $(expr 2 \* $EPNPIPELINES \* $NGPUS / 4) : 1)) - N_CPV=$(($(expr 6 \* $EPNPIPELINES \* $NGPUS / 4) > 0 ? $(expr 6 \* $EPNPIPELINES \* $NGPUS / 4) : 1)) + N_EMC=$(($(expr 3 \* $EPNPIPELINES \* $NGPUS / 4) > 0 ? $(expr 3 \* $EPNPIPELINES \* $NGPUS / 4) : 1)) + N_CPV=$(($(expr 5 \* $EPNPIPELINES \* $NGPUS / 4) > 0 ? $(expr 5 \* $EPNPIPELINES \* $NGPUS / 4) : 1)) else N_TPCENT=1 N_TPCITS=1 @@ -91,7 +91,7 @@ if [ $CTFINPUT == 1 ]; then if [ ! -z $CTF_DICT_DIR ] ; then CTF_DICT=" --ctf-dict ${CTF_DICT_DIR}/ctf_dictionary.root"; fi WORKFLOW="o2-ctf-reader-workflow --ctf-input ${CTFName} ${CTF_DICT} --onlyDet $CTF_DETECTORS $ARGS_ALL | " elif [ $EXTINPUT == 1 ]; then - WORKFLOW="o2-dpl-raw-proxy $ARGS_ALL --dataspec \"FLP:FLP/DISTSUBTIMEFRAME/0;B:TPC/RAWDATA;C:ITS/RAWDATA;D:TOF/RAWDATA;D:MFT/RAWDATA;E:FT0/RAWDATA;F:MID/RAWDATA;G:EMC/RAWDATA;H:PHS/RAWDATA;I:CPV/RAWDATA;J:ZDC/RAWDATA;K:HMP/RAWDATA;L:FDD/RAWDATA\" --channel-config \"name=readout-proxy,type=pull,method=connect,address=ipc://@stfb-to-dpl,transport=shmem,rateLogging=0\" | " + WORKFLOW="o2-dpl-raw-proxy $ARGS_ALL --dataspec \"FLP:FLP/DISTSUBTIMEFRAME/0;B:TPC/RAWDATA;C:ITS/RAWDATA;D:TOF/RAWDATA;D:MFT/RAWDATA;E:FT0/RAWDATA;F:MID/RAWDATA;G:EMC/RAWDATA;H:PHS/RAWDATA;I:CPV/RAWDATA;J:ZDC/RAWDATA;K:HMP/RAWDATA;L:FDD/RAWDATA\" --channel-config \"name=readout-proxy,type=pull,method=connect,address=ipc://@$INRAWCHANNAME,transport=shmem,rateLogging=0\" | " else WORKFLOW="o2-raw-file-reader-workflow --detect-tf0 $ARGS_ALL --configKeyValues \"HBFUtils.nHBFPerTF=$NHBPERTF;\" --delay $TFDELAY --loop $NTIMEFRAMES --max-tf 0 --input-conf rawAll.cfg | " fi diff --git a/prodtests/full-system-test/raw-reader.sh b/prodtests/full-system-test/raw-reader.sh index 9a3d91935d584..bf62155c18391 100755 --- a/prodtests/full-system-test/raw-reader.sh +++ b/prodtests/full-system-test/raw-reader.sh @@ -19,4 +19,4 @@ if [ $NORATELOG == 1 ]; then ARGS_ALL+=" --fairmq-rate-logging 0" fi -o2-raw-file-reader-workflow $ARGS_ALL --loop $NTIMEFRAMES --delay $TFDELAY --input-conf rawAll.cfg --configKeyValues "HBFUtils.nHBFPerTF=$NHBPERTF;" --max-tf 0 --raw-channel-config "name=dpl-chan,type=push,method=bind,address=ipc://@stfb-to-dpl,transport=shmem,rateLogging=0" $GLOBALDPLOPT --run +o2-raw-file-reader-workflow $ARGS_ALL --loop $NTIMEFRAMES --delay $TFDELAY --input-conf rawAll.cfg --configKeyValues "HBFUtils.nHBFPerTF=$NHBPERTF;" --max-tf 0 --raw-channel-config "name=dpl-chan,type=push,method=bind,address=ipc://@$INRAWCHANNAME,transport=shmem,rateLogging=0" $GLOBALDPLOPT --run diff --git a/prodtests/full-system-test/setenv.sh b/prodtests/full-system-test/setenv.sh index f8be97a2b9d21..985f1d0633108 100755 --- a/prodtests/full-system-test/setenv.sh +++ b/prodtests/full-system-test/setenv.sh @@ -28,6 +28,7 @@ if [ -z "$EPNPIPELINES" ]; then export EPNPIPELINES=0; fi # Set def if [ -z "$SEVERITY" ]; then export SEVERITY="info"; fi # Log verbosity if [ -z "$SHMTHROW" ]; then export SHMTHROW=1; fi # Throw exception when running out of SHM if [ -z "$NORATELOG" ]; then export NORATELOG=1; fi # Disable FairMQ Rate Logging +if [ -z "$INRAWCHANNAME" ]; then export INRAWCHANNAME=stfb-to-dpl; fi # Raw channel name used to communicate with DataDistribution SEVERITY_TPC="info" # overrides severity for the tpc workflow DISABLE_MC="--disable-mc" diff --git a/prodtests/full-system-test/start_tmux.sh b/prodtests/full-system-test/start_tmux.sh index 70803e78ce353..3ca8c55419775 100755 --- a/prodtests/full-system-test/start_tmux.sh +++ b/prodtests/full-system-test/start_tmux.sh @@ -12,7 +12,7 @@ source $MYDIR/setenv.sh export NGPUS=4 export GPUTYPE=HIP export SHMSIZE=$(( 128 << 30 )) -export DDSHMSIZE=$(( 64 << 10 )) +export DDSHMSIZE=$(( 128 << 10 )) export GPUMEMSIZE=$(( 24 << 30 )) export NUMAGPUIDS=1 export EXTINPUT=1 From 2c9e913e9fadbf70c37bf6e3e95cbaf699323015 Mon Sep 17 00:00:00 2001 From: Paul Buehler Date: Fri, 16 Apr 2021 14:18:56 +0200 Subject: [PATCH 146/770] Reformatting of AnalysisDataModel.h (#5930) * Reformation of AnalysisDataModel.h Single line comments added to column and table declarations Using doxygen compatible syntax //! * clan-format * added comment tags //! to column and table declarations added type specifier (-> type) to all DYNAMIC_COLUMN declarations --- .../include/AnalysisDataModel/CFDerived.h | 19 +- .../include/AnalysisDataModel/Centrality.h | 4 +- .../include/AnalysisDataModel/EMCALClusters.h | 17 +- .../AnalysisDataModel/EventSelection.h | 38 +- .../HFCandidateSelectionTables.h | 31 +- .../AnalysisDataModel/HFSecondaryVertex.h | 263 +++-- .../DataModel/include/AnalysisDataModel/Jet.h | 60 +- .../include/AnalysisDataModel/Multiplicity.h | 26 +- .../AnalysisDataModel/PID/PIDResponse.h | 321 +++--- .../AnalysisDataModel/ReducedInfoTables.h | 110 ++- .../AnalysisDataModel/StrangenessTables.h | 224 +++-- .../AnalysisDataModel/TrackSelectionTables.h | 14 +- .../include/Framework/AnalysisDataModel.h | 929 ++++++++++-------- 13 files changed, 1163 insertions(+), 893 deletions(-) diff --git a/Analysis/DataModel/include/AnalysisDataModel/CFDerived.h b/Analysis/DataModel/include/AnalysisDataModel/CFDerived.h index 762e5ddc15361..1acf6243c1e27 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/CFDerived.h +++ b/Analysis/DataModel/include/AnalysisDataModel/CFDerived.h @@ -16,19 +16,22 @@ namespace o2::aod { -DECLARE_SOA_TABLE(CFCollisions, "AOD", "CFCOLLISION", o2::soa::Index<>, - bc::RunNumber, collision::PosZ, cent::CentV0M, timestamp::Timestamp); +DECLARE_SOA_TABLE(CFCollisions, "AOD", "CFCOLLISION", //! + o2::soa::Index<>, + bc::RunNumber, collision::PosZ, + cent::CentV0M, timestamp::Timestamp); using CFCollision = CFCollisions::iterator; namespace cftrack { -DECLARE_SOA_INDEX_COLUMN(CFCollision, cfCollision); -DECLARE_SOA_COLUMN(Pt, pt, float); -DECLARE_SOA_COLUMN(Eta, eta, float); -DECLARE_SOA_COLUMN(Phi, phi, float); -DECLARE_SOA_COLUMN(Sign, sign, int8_t); +DECLARE_SOA_INDEX_COLUMN(CFCollision, cfCollision); //! +DECLARE_SOA_COLUMN(Pt, pt, float); //! +DECLARE_SOA_COLUMN(Eta, eta, float); //! +DECLARE_SOA_COLUMN(Phi, phi, float); //! +DECLARE_SOA_COLUMN(Sign, sign, int8_t); //! } // namespace cftrack -DECLARE_SOA_TABLE(CFTracks, "AOD", "CFTRACK", o2::soa::Index<>, +DECLARE_SOA_TABLE(CFTracks, "AOD", "CFTRACK", //! + o2::soa::Index<>, cftrack::CFCollisionId, cftrack::Pt, cftrack::Eta, cftrack::Phi, cftrack::Sign, track::TrackType); diff --git a/Analysis/DataModel/include/AnalysisDataModel/Centrality.h b/Analysis/DataModel/include/AnalysisDataModel/Centrality.h index 2dff05cde076a..3bdb9aadf7726 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/Centrality.h +++ b/Analysis/DataModel/include/AnalysisDataModel/Centrality.h @@ -16,9 +16,9 @@ namespace o2::aod { namespace cent { -DECLARE_SOA_COLUMN(CentV0M, centV0M, float); +DECLARE_SOA_COLUMN(CentV0M, centV0M, float); //! } // namespace cent -DECLARE_SOA_TABLE(Cents, "AOD", "CENT", cent::CentV0M); +DECLARE_SOA_TABLE(Cents, "AOD", "CENT", cent::CentV0M); //! using Cent = Cents::iterator; } // namespace o2::aod diff --git a/Analysis/DataModel/include/AnalysisDataModel/EMCALClusters.h b/Analysis/DataModel/include/AnalysisDataModel/EMCALClusters.h index a75ad1f8ca00b..fa3c89470dc7f 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/EMCALClusters.h +++ b/Analysis/DataModel/include/AnalysisDataModel/EMCALClusters.h @@ -20,16 +20,17 @@ namespace o2::aod { namespace emcalcluster { -DECLARE_SOA_INDEX_COLUMN(Collision, collision); -DECLARE_SOA_COLUMN(Energy, energy, float); -DECLARE_SOA_COLUMN(Eta, eta, float); -DECLARE_SOA_COLUMN(Phi, phi, float); -DECLARE_SOA_COLUMN(M02, m02, float); +DECLARE_SOA_INDEX_COLUMN(Collision, collision); //! +DECLARE_SOA_COLUMN(Energy, energy, float); //! +DECLARE_SOA_COLUMN(Eta, eta, float); //! +DECLARE_SOA_COLUMN(Phi, phi, float); //! +DECLARE_SOA_COLUMN(M02, m02, float); //! } // namespace emcalcluster -DECLARE_SOA_TABLE(EMCALClusters, "AOD", "EMCALCLUSTERS", - o2::soa::Index<>, emcalcluster::CollisionId, emcalcluster::Energy, - emcalcluster::Eta, emcalcluster::Phi, emcalcluster::M02); +DECLARE_SOA_TABLE(EMCALClusters, "AOD", "EMCALCLUSTERS", //! + o2::soa::Index<>, emcalcluster::CollisionId, + emcalcluster::Energy, emcalcluster::Eta, emcalcluster::Phi, + emcalcluster::M02); using EMCALCluster = EMCALClusters::iterator; diff --git a/Analysis/DataModel/include/AnalysisDataModel/EventSelection.h b/Analysis/DataModel/include/AnalysisDataModel/EventSelection.h index 6b100004de17d..2ec114918a6e6 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/EventSelection.h +++ b/Analysis/DataModel/include/AnalysisDataModel/EventSelection.h @@ -19,24 +19,26 @@ namespace o2::aod namespace evsel { // TODO bool arrays are not supported? Storing in int32 for the moment -DECLARE_SOA_COLUMN(Alias, alias, int32_t[kNaliases]); -DECLARE_SOA_COLUMN(BBT0A, bbT0A, bool); // beam-beam time in T0A -DECLARE_SOA_COLUMN(BBT0C, bbT0C, bool); // beam-beam time in T0C -DECLARE_SOA_COLUMN(BBV0A, bbV0A, bool); // beam-beam time in V0A -DECLARE_SOA_COLUMN(BBV0C, bbV0C, bool); // beam-beam time in V0C -DECLARE_SOA_COLUMN(BGV0A, bgV0A, bool); // beam-gas time in V0A -DECLARE_SOA_COLUMN(BGV0C, bgV0C, bool); // beam-gas time in V0C -DECLARE_SOA_COLUMN(BBZNA, bbZNA, bool); // beam-beam time in ZNA -DECLARE_SOA_COLUMN(BBZNC, bbZNC, bool); // beam-beam time in ZNC -DECLARE_SOA_COLUMN(BBFDA, bbFDA, bool); // beam-beam time in FDA -DECLARE_SOA_COLUMN(BBFDC, bbFDC, bool); // beam-beam time in FDC -DECLARE_SOA_COLUMN(BGFDA, bgFDA, bool); // beam-gas time in FDA -DECLARE_SOA_COLUMN(BGFDC, bgFDC, bool); // beam-gas time in FDC -DECLARE_SOA_COLUMN(FoundFT0, foundFT0, int64_t); // the nearest FT0 signal -DECLARE_SOA_DYNAMIC_COLUMN(SEL7, sel7, [](bool bbV0A, bool bbV0C, bool bbZNA, bool bbZNC) -> bool { return bbV0A && bbV0C && bbZNA && bbZNC; }); -DECLARE_SOA_DYNAMIC_COLUMN(SEL8, sel8, [](bool bbT0A, bool bbT0C, bool bbZNA, bool bbZNC) -> bool { return bbT0A && bbT0C && bbZNA && bbZNC; }); +DECLARE_SOA_COLUMN(Alias, alias, int32_t[kNaliases]); //! +DECLARE_SOA_COLUMN(BBT0A, bbT0A, bool); //! beam-beam time in T0A +DECLARE_SOA_COLUMN(BBT0C, bbT0C, bool); //! beam-beam time in T0C +DECLARE_SOA_COLUMN(BBV0A, bbV0A, bool); //! beam-beam time in V0A +DECLARE_SOA_COLUMN(BBV0C, bbV0C, bool); //! beam-beam time in V0C +DECLARE_SOA_COLUMN(BGV0A, bgV0A, bool); //! beam-gas time in V0A +DECLARE_SOA_COLUMN(BGV0C, bgV0C, bool); //! beam-gas time in V0C +DECLARE_SOA_COLUMN(BBZNA, bbZNA, bool); //! beam-beam time in ZNA +DECLARE_SOA_COLUMN(BBZNC, bbZNC, bool); //! beam-beam time in ZNC +DECLARE_SOA_COLUMN(BBFDA, bbFDA, bool); //! beam-beam time in FDA +DECLARE_SOA_COLUMN(BBFDC, bbFDC, bool); //! beam-beam time in FDC +DECLARE_SOA_COLUMN(BGFDA, bgFDA, bool); //! beam-gas time in FDA +DECLARE_SOA_COLUMN(BGFDC, bgFDC, bool); //! beam-gas time in FDC +DECLARE_SOA_COLUMN(FoundFT0, foundFT0, int64_t); //! the nearest FT0 signal +DECLARE_SOA_DYNAMIC_COLUMN(SEL7, sel7, //! + [](bool bbV0A, bool bbV0C, bool bbZNA, bool bbZNC) -> bool { return bbV0A && bbV0C && bbZNA && bbZNC; }); +DECLARE_SOA_DYNAMIC_COLUMN(SEL8, sel8, //! + [](bool bbT0A, bool bbT0C, bool bbZNA, bool bbZNC) -> bool { return bbT0A && bbT0C && bbZNA && bbZNC; }); } // namespace evsel -DECLARE_SOA_TABLE(EvSels, "AOD", "EVSEL", +DECLARE_SOA_TABLE(EvSels, "AOD", "EVSEL", //! evsel::Alias, evsel::BBT0A, evsel::BBT0C, evsel::BBV0A, evsel::BBV0C, evsel::BGV0A, evsel::BGV0C, @@ -47,7 +49,7 @@ DECLARE_SOA_TABLE(EvSels, "AOD", "EVSEL", evsel::FoundFT0); using EvSel = EvSels::iterator; -DECLARE_SOA_TABLE(BcSels, "AOD", "BCSEL", +DECLARE_SOA_TABLE(BcSels, "AOD", "BCSEL", //! evsel::Alias, evsel::BBT0A, evsel::BBT0C, evsel::BBV0A, evsel::BBV0C, evsel::BGV0A, evsel::BGV0C, diff --git a/Analysis/DataModel/include/AnalysisDataModel/HFCandidateSelectionTables.h b/Analysis/DataModel/include/AnalysisDataModel/HFCandidateSelectionTables.h index 20b054d868171..8a664269bb901 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/HFCandidateSelectionTables.h +++ b/Analysis/DataModel/include/AnalysisDataModel/HFCandidateSelectionTables.h @@ -15,38 +15,43 @@ namespace o2::aod { namespace hf_selcandidate_d0 { -DECLARE_SOA_COLUMN(IsSelD0, isSelD0, int); -DECLARE_SOA_COLUMN(IsSelD0bar, isSelD0bar, int); +DECLARE_SOA_COLUMN(IsSelD0, isSelD0, int); //! +DECLARE_SOA_COLUMN(IsSelD0bar, isSelD0bar, int); //! } // namespace hf_selcandidate_d0 -DECLARE_SOA_TABLE(HFSelD0Candidate, "AOD", "HFSELD0CAND", hf_selcandidate_d0::IsSelD0, hf_selcandidate_d0::IsSelD0bar); +DECLARE_SOA_TABLE(HFSelD0Candidate, "AOD", "HFSELD0CAND", //! + hf_selcandidate_d0::IsSelD0, hf_selcandidate_d0::IsSelD0bar); namespace hf_selcandidate_dplus { -DECLARE_SOA_COLUMN(IsSelDplusToPiKPi, isSelDplusToPiKPi, int); +DECLARE_SOA_COLUMN(IsSelDplusToPiKPi, isSelDplusToPiKPi, int); //! } // namespace hf_selcandidate_dplus -DECLARE_SOA_TABLE(HFSelDplusToPiKPiCandidate, "AOD", "HFSELDPLUSCAND", hf_selcandidate_dplus::IsSelDplusToPiKPi); +DECLARE_SOA_TABLE(HFSelDplusToPiKPiCandidate, "AOD", "HFSELDPLUSCAND", //! + hf_selcandidate_dplus::IsSelDplusToPiKPi); namespace hf_selcandidate_lc { -DECLARE_SOA_COLUMN(IsSelLcpKpi, isSelLcpKpi, int); -DECLARE_SOA_COLUMN(IsSelLcpiKp, isSelLcpiKp, int); +DECLARE_SOA_COLUMN(IsSelLcpKpi, isSelLcpKpi, int); //! +DECLARE_SOA_COLUMN(IsSelLcpiKp, isSelLcpiKp, int); //! } // namespace hf_selcandidate_lc -DECLARE_SOA_TABLE(HFSelLcCandidate, "AOD", "HFSELLCCAND", hf_selcandidate_lc::IsSelLcpKpi, hf_selcandidate_lc::IsSelLcpiKp); +DECLARE_SOA_TABLE(HFSelLcCandidate, "AOD", "HFSELLCCAND", //! + hf_selcandidate_lc::IsSelLcpKpi, hf_selcandidate_lc::IsSelLcpiKp); namespace hf_selcandidate_jpsi { -DECLARE_SOA_COLUMN(IsSelJpsiToEE, isSelJpsiToEE, int); +DECLARE_SOA_COLUMN(IsSelJpsiToEE, isSelJpsiToEE, int); //! } // namespace hf_selcandidate_jpsi -DECLARE_SOA_TABLE(HFSelJpsiToEECandidate, "AOD", "HFSELJPSICAND", hf_selcandidate_jpsi::IsSelJpsiToEE); +DECLARE_SOA_TABLE(HFSelJpsiToEECandidate, "AOD", "HFSELJPSICAND", //! + hf_selcandidate_jpsi::IsSelJpsiToEE); } // namespace o2::aod namespace o2::aod { namespace hf_selcandidate_xic { -DECLARE_SOA_COLUMN(IsSelXicToPKPi, isSelXicToPKPi, int); -DECLARE_SOA_COLUMN(IsSelXicToPiKP, isSelXicToPiKP, int); +DECLARE_SOA_COLUMN(IsSelXicToPKPi, isSelXicToPKPi, int); //! +DECLARE_SOA_COLUMN(IsSelXicToPiKP, isSelXicToPiKP, int); //! } // namespace hf_selcandidate_xic -DECLARE_SOA_TABLE(HFSelXicToPKPiCandidate, "AOD", "HFSELXICCAND", hf_selcandidate_xic::IsSelXicToPKPi, hf_selcandidate_xic::IsSelXicToPiKP); +DECLARE_SOA_TABLE(HFSelXicToPKPiCandidate, "AOD", "HFSELXICCAND", //! + hf_selcandidate_xic::IsSelXicToPKPi, hf_selcandidate_xic::IsSelXicToPiKP); } // namespace o2::aod #endif // O2_ANALYSIS_HFCANDIDATESELECTIONTABLES_H_ diff --git a/Analysis/DataModel/include/AnalysisDataModel/HFSecondaryVertex.h b/Analysis/DataModel/include/AnalysisDataModel/HFSecondaryVertex.h index 8c62fd41b43ba..666d2ace1d8da 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/HFSecondaryVertex.h +++ b/Analysis/DataModel/include/AnalysisDataModel/HFSecondaryVertex.h @@ -25,12 +25,12 @@ namespace o2::aod { namespace hf_seltrack { -DECLARE_SOA_COLUMN(IsSelProng, isSelProng, int); -DECLARE_SOA_COLUMN(DCAPrim0, dcaPrim0, float); -DECLARE_SOA_COLUMN(DCAPrim1, dcaPrim1, float); +DECLARE_SOA_COLUMN(IsSelProng, isSelProng, int); //! +DECLARE_SOA_COLUMN(DCAPrim0, dcaPrim0, float); //! +DECLARE_SOA_COLUMN(DCAPrim1, dcaPrim1, float); //! } // namespace hf_seltrack -DECLARE_SOA_TABLE(HFSelTrack, "AOD", "HFSELTRACK", +DECLARE_SOA_TABLE(HFSelTrack, "AOD", "HFSELTRACK", //! hf_seltrack::IsSelProng, hf_seltrack::DCAPrim0, hf_seltrack::DCAPrim1); @@ -45,37 +45,37 @@ using BigTracksPID = soa::Join float { return RecoDecay::sqrtSumOfSquares(xVtxS, yVtxS); }); +DECLARE_SOA_COLUMN(Chi2PCA, chi2PCA, float); //! sum of (non-weighted) distances of the secondary vertex to its prongs // prong properties -DECLARE_SOA_COLUMN(PxProng0, pxProng0, float); -DECLARE_SOA_COLUMN(PyProng0, pyProng0, float); -DECLARE_SOA_COLUMN(PzProng0, pzProng0, float); -DECLARE_SOA_DYNAMIC_COLUMN(PtProng0, ptProng0, [](float px, float py) { return RecoDecay::Pt(px, py); }); -DECLARE_SOA_DYNAMIC_COLUMN(Pt2Prong0, pt2Prong0, [](float px, float py) { return RecoDecay::Pt2(px, py); }); -DECLARE_SOA_DYNAMIC_COLUMN(PVectorProng0, pVectorProng0, [](float px, float py, float pz) { return array{px, py, pz}; }); -DECLARE_SOA_COLUMN(ImpactParameter0, impactParameter0, float); -DECLARE_SOA_COLUMN(ErrorImpactParameter0, errorImpactParameter0, float); -DECLARE_SOA_DYNAMIC_COLUMN(ImpactParameterNormalised0, impactParameterNormalised0, [](float dca, float err) { return dca / err; }); -DECLARE_SOA_COLUMN(PxProng1, pxProng1, float); -DECLARE_SOA_COLUMN(PyProng1, pyProng1, float); -DECLARE_SOA_COLUMN(PzProng1, pzProng1, float); -DECLARE_SOA_DYNAMIC_COLUMN(PtProng1, ptProng1, [](float px, float py) { return RecoDecay::Pt(px, py); }); -DECLARE_SOA_DYNAMIC_COLUMN(Pt2Prong1, pt2Prong1, [](float px, float py) { return RecoDecay::Pt2(px, py); }); -DECLARE_SOA_DYNAMIC_COLUMN(PVectorProng1, pVectorProng1, [](float px, float py, float pz) { return array{px, py, pz}; }); -DECLARE_SOA_COLUMN(ImpactParameter1, impactParameter1, float); -DECLARE_SOA_COLUMN(ErrorImpactParameter1, errorImpactParameter1, float); -DECLARE_SOA_DYNAMIC_COLUMN(ImpactParameterNormalised1, impactParameterNormalised1, [](float dca, float err) { return dca / err; }); -DECLARE_SOA_COLUMN(PxProng2, pxProng2, float); -DECLARE_SOA_COLUMN(PyProng2, pyProng2, float); -DECLARE_SOA_COLUMN(PzProng2, pzProng2, float); -DECLARE_SOA_DYNAMIC_COLUMN(PtProng2, ptProng2, [](float px, float py) { return RecoDecay::Pt(px, py); }); -DECLARE_SOA_DYNAMIC_COLUMN(Pt2Prong2, pt2Prong2, [](float px, float py) { return RecoDecay::Pt2(px, py); }); -DECLARE_SOA_DYNAMIC_COLUMN(PVectorProng2, pVectorProng2, [](float px, float py, float pz) { return array{px, py, pz}; }); -DECLARE_SOA_COLUMN(ImpactParameter2, impactParameter2, float); -DECLARE_SOA_COLUMN(ErrorImpactParameter2, errorImpactParameter2, float); -DECLARE_SOA_DYNAMIC_COLUMN(ImpactParameterNormalised2, impactParameterNormalised2, [](float dca, float err) { return dca / err; }); +DECLARE_SOA_COLUMN(PxProng0, pxProng0, float); //! +DECLARE_SOA_COLUMN(PyProng0, pyProng0, float); //! +DECLARE_SOA_COLUMN(PzProng0, pzProng0, float); //! +DECLARE_SOA_DYNAMIC_COLUMN(PtProng0, ptProng0, //! + [](float px, float py) -> float { return RecoDecay::Pt(px, py); }); +DECLARE_SOA_DYNAMIC_COLUMN(Pt2Prong0, pt2Prong0, //! + [](float px, float py) -> float { return RecoDecay::Pt2(px, py); }); +DECLARE_SOA_DYNAMIC_COLUMN(PVectorProng0, pVectorProng0, //! + [](float px, float py, float pz) -> array { return array{px, py, pz}; }); +DECLARE_SOA_COLUMN(ImpactParameter0, impactParameter0, float); //! +DECLARE_SOA_COLUMN(ErrorImpactParameter0, errorImpactParameter0, float); //! +DECLARE_SOA_DYNAMIC_COLUMN(ImpactParameterNormalised0, impactParameterNormalised0, //! + [](float dca, float err) -> float { return dca / err; }); +DECLARE_SOA_COLUMN(PxProng1, pxProng1, float); //! +DECLARE_SOA_COLUMN(PyProng1, pyProng1, float); //! +DECLARE_SOA_COLUMN(PzProng1, pzProng1, float); //! +DECLARE_SOA_DYNAMIC_COLUMN(PtProng1, ptProng1, //! + [](float px, float py) -> float { return RecoDecay::Pt(px, py); }); +DECLARE_SOA_DYNAMIC_COLUMN(Pt2Prong1, pt2Prong1, //! + [](float px, float py) -> float { return RecoDecay::Pt2(px, py); }); +DECLARE_SOA_DYNAMIC_COLUMN(PVectorProng1, pVectorProng1, //! + [](float px, float py, float pz) -> array { return array{px, py, pz}; }); +DECLARE_SOA_COLUMN(ImpactParameter1, impactParameter1, float); //! +DECLARE_SOA_COLUMN(ErrorImpactParameter1, errorImpactParameter1, float); //! +DECLARE_SOA_DYNAMIC_COLUMN(ImpactParameterNormalised1, impactParameterNormalised1, //! + [](float dca, float err) -> float { return dca / err; }); +DECLARE_SOA_COLUMN(PxProng2, pxProng2, float); //! +DECLARE_SOA_COLUMN(PyProng2, pyProng2, float); //! +DECLARE_SOA_COLUMN(PzProng2, pzProng2, float); //! +DECLARE_SOA_DYNAMIC_COLUMN(PtProng2, ptProng2, //! + [](float px, float py) -> float { return RecoDecay::Pt(px, py); }); +DECLARE_SOA_DYNAMIC_COLUMN(Pt2Prong2, pt2Prong2, //! + [](float px, float py) -> float { return RecoDecay::Pt2(px, py); }); +DECLARE_SOA_DYNAMIC_COLUMN(PVectorProng2, pVectorProng2, //! + [](float px, float py, float pz) -> array { return array{px, py, pz}; }); +DECLARE_SOA_COLUMN(ImpactParameter2, impactParameter2, float); //! +DECLARE_SOA_COLUMN(ErrorImpactParameter2, errorImpactParameter2, float); //! +DECLARE_SOA_DYNAMIC_COLUMN(ImpactParameterNormalised2, impactParameterNormalised2, //! + [](float dca, float err) -> float { return dca / err; }); // candidate properties -DECLARE_SOA_DYNAMIC_COLUMN(Pt, pt, [](float px, float py) { return RecoDecay::Pt(px, py); }); -DECLARE_SOA_DYNAMIC_COLUMN(Pt2, pt2, [](float px, float py) { return RecoDecay::Pt2(px, py); }); -DECLARE_SOA_DYNAMIC_COLUMN(P, p, [](float px, float py, float pz) { return RecoDecay::P(px, py, pz); }); -DECLARE_SOA_DYNAMIC_COLUMN(P2, p2, [](float px, float py, float pz) { return RecoDecay::P2(px, py, pz); }); -DECLARE_SOA_DYNAMIC_COLUMN(PVector, pVector, [](float px, float py, float pz) { return array{px, py, pz}; }); -DECLARE_SOA_DYNAMIC_COLUMN(Eta, eta, [](float px, float py, float pz) { return RecoDecay::Eta(array{px, py, pz}); }); -DECLARE_SOA_DYNAMIC_COLUMN(Phi, phi, [](float px, float py) { return RecoDecay::Phi(px, py); }); -DECLARE_SOA_DYNAMIC_COLUMN(Y, y, [](float px, float py, float pz, double m) { return RecoDecay::Y(array{px, py, pz}, m); }); -DECLARE_SOA_DYNAMIC_COLUMN(E, e, [](float px, float py, float pz, double m) { return RecoDecay::E(px, py, pz, m); }); -DECLARE_SOA_DYNAMIC_COLUMN(E2, e2, [](float px, float py, float pz, double m) { return RecoDecay::E2(px, py, pz, m); }); -DECLARE_SOA_DYNAMIC_COLUMN(DecayLength, decayLength, [](float xVtxP, float yVtxP, float zVtxP, float xVtxS, float yVtxS, float zVtxS) { return RecoDecay::distance(array{xVtxP, yVtxP, zVtxP}, array{xVtxS, yVtxS, zVtxS}); }); -DECLARE_SOA_DYNAMIC_COLUMN(DecayLengthXY, decayLengthXY, [](float xVtxP, float yVtxP, float xVtxS, float yVtxS) { return RecoDecay::distanceXY(array{xVtxP, yVtxP}, array{xVtxS, yVtxS}); }); -DECLARE_SOA_DYNAMIC_COLUMN(DecayLengthNormalised, decayLengthNormalised, [](float xVtxP, float yVtxP, float zVtxP, float xVtxS, float yVtxS, float zVtxS, float err) { return RecoDecay::distance(array{xVtxP, yVtxP, zVtxP}, array{xVtxS, yVtxS, zVtxS}) / err; }); -DECLARE_SOA_DYNAMIC_COLUMN(DecayLengthXYNormalised, decayLengthXYNormalised, [](float xVtxP, float yVtxP, float xVtxS, float yVtxS, float err) { return RecoDecay::distanceXY(array{xVtxP, yVtxP}, array{xVtxS, yVtxS}) / err; }); -DECLARE_SOA_COLUMN(ErrorDecayLength, errorDecayLength, float); -DECLARE_SOA_COLUMN(ErrorDecayLengthXY, errorDecayLengthXY, float); -DECLARE_SOA_DYNAMIC_COLUMN(CPA, cpa, [](float xVtxP, float yVtxP, float zVtxP, float xVtxS, float yVtxS, float zVtxS, float px, float py, float pz) { return RecoDecay::CPA(array{xVtxP, yVtxP, zVtxP}, array{xVtxS, yVtxS, zVtxS}, array{px, py, pz}); }); -DECLARE_SOA_DYNAMIC_COLUMN(CPAXY, cpaXY, [](float xVtxP, float yVtxP, float xVtxS, float yVtxS, float px, float py) { return RecoDecay::CPAXY(array{xVtxP, yVtxP}, array{xVtxS, yVtxS}, array{px, py}); }); -DECLARE_SOA_DYNAMIC_COLUMN(Ct, ct, [](float xVtxP, float yVtxP, float zVtxP, float xVtxS, float yVtxS, float zVtxS, float px, float py, float pz, double m) { return RecoDecay::Ct(array{px, py, pz}, RecoDecay::distance(array{xVtxP, yVtxP, zVtxP}, array{xVtxS, yVtxS, zVtxS}), m); }); -DECLARE_SOA_DYNAMIC_COLUMN(ImpactParameterXY, impactParameterXY, [](float xVtxP, float yVtxP, float zVtxP, float xVtxS, float yVtxS, float zVtxS, float px, float py, float pz) { return RecoDecay::ImpParXY(array{xVtxP, yVtxP, zVtxP}, array{xVtxS, yVtxS, zVtxS}, array{px, py, pz}); }); +DECLARE_SOA_DYNAMIC_COLUMN(Pt, pt, //! + [](float px, float py) -> float { return RecoDecay::Pt(px, py); }); +DECLARE_SOA_DYNAMIC_COLUMN(Pt2, pt2, //! + [](float px, float py) -> float { return RecoDecay::Pt2(px, py); }); +DECLARE_SOA_DYNAMIC_COLUMN(P, p, //! + [](float px, float py, float pz) -> float { return RecoDecay::P(px, py, pz); }); +DECLARE_SOA_DYNAMIC_COLUMN(P2, p2, //! + [](float px, float py, float pz) -> float { return RecoDecay::P2(px, py, pz); }); +DECLARE_SOA_DYNAMIC_COLUMN(PVector, pVector, //! + [](float px, float py, float pz) -> array { return array{px, py, pz}; }); +DECLARE_SOA_DYNAMIC_COLUMN(Eta, eta, //! + [](float px, float py, float pz) -> float { return RecoDecay::Eta(array{px, py, pz}); }); +DECLARE_SOA_DYNAMIC_COLUMN(Phi, phi, //! + [](float px, float py) -> float { return RecoDecay::Phi(px, py); }); +DECLARE_SOA_DYNAMIC_COLUMN(Y, y, //! + [](float px, float py, float pz, double m) -> float { return RecoDecay::Y(array{px, py, pz}, m); }); +DECLARE_SOA_DYNAMIC_COLUMN(E, e, //! + [](float px, float py, float pz, double m) -> float { return RecoDecay::E(px, py, pz, m); }); +DECLARE_SOA_DYNAMIC_COLUMN(E2, e2, //! + [](float px, float py, float pz, double m) -> float { return RecoDecay::E2(px, py, pz, m); }); +DECLARE_SOA_DYNAMIC_COLUMN(DecayLength, decayLength, //! + [](float xVtxP, float yVtxP, float zVtxP, float xVtxS, float yVtxS, float zVtxS) -> float { return RecoDecay::distance(array{xVtxP, yVtxP, zVtxP}, array{xVtxS, yVtxS, zVtxS}); }); +DECLARE_SOA_DYNAMIC_COLUMN(DecayLengthXY, decayLengthXY, //! + [](float xVtxP, float yVtxP, float xVtxS, float yVtxS) -> float { return RecoDecay::distanceXY(array{xVtxP, yVtxP}, array{xVtxS, yVtxS}); }); +DECLARE_SOA_DYNAMIC_COLUMN(DecayLengthNormalised, decayLengthNormalised, //! + [](float xVtxP, float yVtxP, float zVtxP, float xVtxS, float yVtxS, float zVtxS, float err) -> float { return RecoDecay::distance(array{xVtxP, yVtxP, zVtxP}, array{xVtxS, yVtxS, zVtxS}) / err; }); +DECLARE_SOA_DYNAMIC_COLUMN(DecayLengthXYNormalised, decayLengthXYNormalised, //! + [](float xVtxP, float yVtxP, float xVtxS, float yVtxS, float err) -> float { return RecoDecay::distanceXY(array{xVtxP, yVtxP}, array{xVtxS, yVtxS}) / err; }); +DECLARE_SOA_COLUMN(ErrorDecayLength, errorDecayLength, float); //! +DECLARE_SOA_COLUMN(ErrorDecayLengthXY, errorDecayLengthXY, float); //! +DECLARE_SOA_DYNAMIC_COLUMN(CPA, cpa, //! + [](float xVtxP, float yVtxP, float zVtxP, float xVtxS, float yVtxS, float zVtxS, float px, float py, float pz) -> float { return RecoDecay::CPA(array{xVtxP, yVtxP, zVtxP}, array{xVtxS, yVtxS, zVtxS}, array{px, py, pz}); }); +DECLARE_SOA_DYNAMIC_COLUMN(CPAXY, cpaXY, //! + [](float xVtxP, float yVtxP, float xVtxS, float yVtxS, float px, float py) -> float { return RecoDecay::CPAXY(array{xVtxP, yVtxP}, array{xVtxS, yVtxS}, array{px, py}); }); +DECLARE_SOA_DYNAMIC_COLUMN(Ct, ct, //! + [](float xVtxP, float yVtxP, float zVtxP, float xVtxS, float yVtxS, float zVtxS, float px, float py, float pz, double m) -> float { return RecoDecay::Ct(array{px, py, pz}, RecoDecay::distance(array{xVtxP, yVtxP, zVtxP}, array{xVtxS, yVtxS, zVtxS}), m); }); +DECLARE_SOA_DYNAMIC_COLUMN(ImpactParameterXY, impactParameterXY, //! + [](float xVtxP, float yVtxP, float zVtxP, float xVtxS, float yVtxS, float zVtxS, float px, float py, float pz) -> float { return RecoDecay::ImpParXY(array{xVtxP, yVtxP, zVtxP}, array{xVtxS, yVtxS, zVtxS}, array{px, py, pz}); }); // mapping of origin type enum OriginType { Prompt = 1, @@ -150,20 +181,29 @@ enum OriginType { Prompt = 1, // specific 2-prong decay properties namespace hf_cand_prong2 { -DECLARE_SOA_EXPRESSION_COLUMN(Px, px, float, 1.f * aod::hf_cand::pxProng0 + 1.f * aod::hf_cand::pxProng1); -DECLARE_SOA_EXPRESSION_COLUMN(Py, py, float, 1.f * aod::hf_cand::pyProng0 + 1.f * aod::hf_cand::pyProng1); -DECLARE_SOA_EXPRESSION_COLUMN(Pz, pz, float, 1.f * aod::hf_cand::pzProng0 + 1.f * aod::hf_cand::pzProng1); -DECLARE_SOA_DYNAMIC_COLUMN(ImpactParameterProduct, impactParameterProduct, [](float dca1, float dca2) { return dca1 * dca2; }); -DECLARE_SOA_DYNAMIC_COLUMN(M, m, [](float px0, float py0, float pz0, float px1, float py1, float pz1, const array& m) { return RecoDecay::M(array{array{px0, py0, pz0}, array{px1, py1, pz1}}, m); }); -DECLARE_SOA_DYNAMIC_COLUMN(M2, m2, [](float px0, float py0, float pz0, float px1, float py1, float pz1, const array& m) { return RecoDecay::M2(array{array{px0, py0, pz0}, array{px1, py1, pz1}}, m); }); -DECLARE_SOA_DYNAMIC_COLUMN(CosThetaStar, cosThetaStar, [](float px0, float py0, float pz0, float px1, float py1, float pz1, const array& m, double mTot, int iProng) { return RecoDecay::CosThetaStar(array{array{px0, py0, pz0}, array{px1, py1, pz1}}, m, mTot, iProng); }); -DECLARE_SOA_DYNAMIC_COLUMN(ImpactParameterProngSqSum, impactParameterProngSqSum, [](float impParProng0, float impParProng1) { return RecoDecay::sumOfSquares(impParProng0, impParProng1); }); -DECLARE_SOA_DYNAMIC_COLUMN(MaxNormalisedDeltaIP, maxNormalisedDeltaIP, [](float xVtxP, float yVtxP, float xVtxS, float yVtxS, float errDlxy, float pxM, float pyM, float ip0, float errIp0, float ip1, float errIp1, float px0, float py0, float px1, float py1) { return RecoDecay::maxNormalisedDeltaIP(array{xVtxP, yVtxP}, array{xVtxS, yVtxS}, errDlxy, array{pxM, pyM}, array{ip0, ip1}, array{errIp0, errIp1}, array{array{px0, py0}, array{px1, py1}}); }); +DECLARE_SOA_EXPRESSION_COLUMN(Px, px, //! + float, 1.f * aod::hf_cand::pxProng0 + 1.f * aod::hf_cand::pxProng1); +DECLARE_SOA_EXPRESSION_COLUMN(Py, py, //! + float, 1.f * aod::hf_cand::pyProng0 + 1.f * aod::hf_cand::pyProng1); +DECLARE_SOA_EXPRESSION_COLUMN(Pz, pz, //! + float, 1.f * aod::hf_cand::pzProng0 + 1.f * aod::hf_cand::pzProng1); +DECLARE_SOA_DYNAMIC_COLUMN(ImpactParameterProduct, impactParameterProduct, //! + [](float dca1, float dca2) -> float { return dca1 * dca2; }); +DECLARE_SOA_DYNAMIC_COLUMN(M, m, //! + [](float px0, float py0, float pz0, float px1, float py1, float pz1, const array& m) -> float { return RecoDecay::M(array{array{px0, py0, pz0}, array{px1, py1, pz1}}, m); }); +DECLARE_SOA_DYNAMIC_COLUMN(M2, m2, //! + [](float px0, float py0, float pz0, float px1, float py1, float pz1, const array& m) -> float { return RecoDecay::M2(array{array{px0, py0, pz0}, array{px1, py1, pz1}}, m); }); +DECLARE_SOA_DYNAMIC_COLUMN(CosThetaStar, cosThetaStar, //! + [](float px0, float py0, float pz0, float px1, float py1, float pz1, const array& m, double mTot, int iProng) -> float { return RecoDecay::CosThetaStar(array{array{px0, py0, pz0}, array{px1, py1, pz1}}, m, mTot, iProng); }); +DECLARE_SOA_DYNAMIC_COLUMN(ImpactParameterProngSqSum, impactParameterProngSqSum, //! + [](float impParProng0, float impParProng1) -> float { return RecoDecay::sumOfSquares(impParProng0, impParProng1); }); +DECLARE_SOA_DYNAMIC_COLUMN(MaxNormalisedDeltaIP, maxNormalisedDeltaIP, //! + [](float xVtxP, float yVtxP, float xVtxS, float yVtxS, float errDlxy, float pxM, float pyM, float ip0, float errIp0, float ip1, float errIp1, float px0, float py0, float px1, float py1) -> float { return RecoDecay::maxNormalisedDeltaIP(array{xVtxP, yVtxP}, array{xVtxS, yVtxS}, errDlxy, array{pxM, pyM}, array{ip0, ip1}, array{errIp0, errIp1}, array{array{px0, py0}, array{px1, py1}}); }); // MC matching result: -DECLARE_SOA_COLUMN(FlagMCMatchRec, flagMCMatchRec, int8_t); // reconstruction level -DECLARE_SOA_COLUMN(FlagMCMatchGen, flagMCMatchGen, int8_t); // generator level -DECLARE_SOA_COLUMN(OriginMCRec, originMCRec, int8_t); // particle origin, reconstruction level -DECLARE_SOA_COLUMN(OriginMCGen, originMCGen, int8_t); // particle origin, generator level +DECLARE_SOA_COLUMN(FlagMCMatchRec, flagMCMatchRec, int8_t); //! reconstruction level +DECLARE_SOA_COLUMN(FlagMCMatchGen, flagMCMatchGen, int8_t); //! generator level +DECLARE_SOA_COLUMN(OriginMCRec, originMCRec, int8_t); //! particle origin, reconstruction level +DECLARE_SOA_COLUMN(OriginMCGen, originMCGen, int8_t); //! particle origin, generator level // mapping of decay types enum DecayType { D0ToPiK = 0, @@ -264,7 +304,7 @@ auto InvMassJpsiToEE(const T& candidate) hf_cand::PVectorProng1 // 2-prong decay candidate table -DECLARE_SOA_TABLE(HfCandProng2Base, "AOD", "HFCANDP2BASE", +DECLARE_SOA_TABLE(HfCandProng2Base, "AOD", "HFCANDP2BASE", //! // general columns HFCAND_COLUMNS, // 2-prong specific columns @@ -298,38 +338,45 @@ DECLARE_SOA_TABLE(HfCandProng2Base, "AOD", "HFCANDP2BASE", hf_cand::E2); // extended table with expression columns that can be used as arguments of dynamic columns -DECLARE_SOA_EXTENDED_TABLE_USER(HfCandProng2Ext, HfCandProng2Base, "HFCANDP2EXT", +DECLARE_SOA_EXTENDED_TABLE_USER(HfCandProng2Ext, HfCandProng2Base, "HFCANDP2EXT", //! hf_cand_prong2::Px, hf_cand_prong2::Py, hf_cand_prong2::Pz); using HfCandProng2 = HfCandProng2Ext; // table with results of reconstruction level MC matching -DECLARE_SOA_TABLE(HfCandProng2MCRec, "AOD", "HFCANDP2MCREC", +DECLARE_SOA_TABLE(HfCandProng2MCRec, "AOD", "HFCANDP2MCREC", //! hf_cand_prong2::FlagMCMatchRec, hf_cand_prong2::OriginMCRec); // table with results of generator level MC matching -DECLARE_SOA_TABLE(HfCandProng2MCGen, "AOD", "HFCANDP2MCGEN", +DECLARE_SOA_TABLE(HfCandProng2MCGen, "AOD", "HFCANDP2MCGEN", //! hf_cand_prong2::FlagMCMatchGen, hf_cand_prong2::OriginMCGen); // specific 3-prong decay properties namespace hf_cand_prong3 { -DECLARE_SOA_EXPRESSION_COLUMN(Px, px, float, 1.f * aod::hf_cand::pxProng0 + 1.f * aod::hf_cand::pxProng1 + 1.f * aod::hf_cand::pxProng2); -DECLARE_SOA_EXPRESSION_COLUMN(Py, py, float, 1.f * aod::hf_cand::pyProng0 + 1.f * aod::hf_cand::pyProng1 + 1.f * aod::hf_cand::pyProng2); -DECLARE_SOA_EXPRESSION_COLUMN(Pz, pz, float, 1.f * aod::hf_cand::pzProng0 + 1.f * aod::hf_cand::pzProng1 + 1.f * aod::hf_cand::pzProng2); -DECLARE_SOA_DYNAMIC_COLUMN(M, m, [](float px0, float py0, float pz0, float px1, float py1, float pz1, float px2, float py2, float pz2, const array& m) { return RecoDecay::M(array{array{px0, py0, pz0}, array{px1, py1, pz1}, array{px2, py2, pz2}}, m); }); -DECLARE_SOA_DYNAMIC_COLUMN(M2, m2, [](float px0, float py0, float pz0, float px1, float py1, float pz1, float px2, float py2, float pz2, const array& m) { return RecoDecay::M2(array{array{px0, py0, pz0}, array{px1, py1, pz1}, array{px2, py2, pz2}}, m); }); -DECLARE_SOA_DYNAMIC_COLUMN(ImpactParameterProngSqSum, impactParameterProngSqSum, [](float impParProng0, float impParProng1, float impParProng2) { return RecoDecay::sumOfSquares(impParProng0, impParProng1, impParProng2); }); -DECLARE_SOA_DYNAMIC_COLUMN(MaxNormalisedDeltaIP, maxNormalisedDeltaIP, [](float xVtxP, float yVtxP, float xVtxS, float yVtxS, float errDlxy, float pxM, float pyM, float ip0, float errIp0, float ip1, float errIp1, float ip2, float errIp2, float px0, float py0, float px1, float py1, float px2, float py2) { return RecoDecay::maxNormalisedDeltaIP(array{xVtxP, yVtxP}, array{xVtxS, yVtxS}, errDlxy, array{pxM, pyM}, array{ip0, ip1, ip2}, array{errIp0, errIp1, errIp2}, array{array{px0, py0}, array{px1, py1}, array{px2, py2}}); }); +DECLARE_SOA_EXPRESSION_COLUMN(Px, px, //! + float, 1.f * aod::hf_cand::pxProng0 + 1.f * aod::hf_cand::pxProng1 + 1.f * aod::hf_cand::pxProng2); +DECLARE_SOA_EXPRESSION_COLUMN(Py, py, //! + float, 1.f * aod::hf_cand::pyProng0 + 1.f * aod::hf_cand::pyProng1 + 1.f * aod::hf_cand::pyProng2); +DECLARE_SOA_EXPRESSION_COLUMN(Pz, pz, //! + float, 1.f * aod::hf_cand::pzProng0 + 1.f * aod::hf_cand::pzProng1 + 1.f * aod::hf_cand::pzProng2); +DECLARE_SOA_DYNAMIC_COLUMN(M, m, //! + [](float px0, float py0, float pz0, float px1, float py1, float pz1, float px2, float py2, float pz2, const array& m) -> float { return RecoDecay::M(array{array{px0, py0, pz0}, array{px1, py1, pz1}, array{px2, py2, pz2}}, m); }); +DECLARE_SOA_DYNAMIC_COLUMN(M2, m2, //! + [](float px0, float py0, float pz0, float px1, float py1, float pz1, float px2, float py2, float pz2, const array& m) -> float { return RecoDecay::M2(array{array{px0, py0, pz0}, array{px1, py1, pz1}, array{px2, py2, pz2}}, m); }); +DECLARE_SOA_DYNAMIC_COLUMN(ImpactParameterProngSqSum, impactParameterProngSqSum, //! + [](float impParProng0, float impParProng1, float impParProng2) -> float { return RecoDecay::sumOfSquares(impParProng0, impParProng1, impParProng2); }); +DECLARE_SOA_DYNAMIC_COLUMN(MaxNormalisedDeltaIP, maxNormalisedDeltaIP, //! + [](float xVtxP, float yVtxP, float xVtxS, float yVtxS, float errDlxy, float pxM, float pyM, float ip0, float errIp0, float ip1, float errIp1, float ip2, float errIp2, float px0, float py0, float px1, float py1, float px2, float py2) -> float { return RecoDecay::maxNormalisedDeltaIP(array{xVtxP, yVtxP}, array{xVtxS, yVtxS}, errDlxy, array{pxM, pyM}, array{ip0, ip1, ip2}, array{errIp0, errIp1, errIp2}, array{array{px0, py0}, array{px1, py1}, array{px2, py2}}); }); // MC matching result: -DECLARE_SOA_COLUMN(FlagMCMatchRec, flagMCMatchRec, int8_t); // reconstruction level -DECLARE_SOA_COLUMN(FlagMCMatchGen, flagMCMatchGen, int8_t); // generator level -DECLARE_SOA_COLUMN(OriginMCRec, originMCRec, int8_t); // particle origin, reconstruction level -DECLARE_SOA_COLUMN(OriginMCGen, originMCGen, int8_t); // particle origin, generator level -DECLARE_SOA_COLUMN(FlagMCDecayChanRec, flagMCDecayChanRec, int8_t); // resonant decay channel flag, reconstruction level -DECLARE_SOA_COLUMN(FlagMCDecayChanGen, flagMCDecayChanGen, int8_t); // resonant decay channel flag, generator level +DECLARE_SOA_COLUMN(FlagMCMatchRec, flagMCMatchRec, int8_t); //! reconstruction level +DECLARE_SOA_COLUMN(FlagMCMatchGen, flagMCMatchGen, int8_t); //! generator level +DECLARE_SOA_COLUMN(OriginMCRec, originMCRec, int8_t); //! particle origin, reconstruction level +DECLARE_SOA_COLUMN(OriginMCGen, originMCGen, int8_t); //! particle origin, generator level +DECLARE_SOA_COLUMN(FlagMCDecayChanRec, flagMCDecayChanRec, int8_t); //! resonant decay channel flag, reconstruction level +DECLARE_SOA_COLUMN(FlagMCDecayChanGen, flagMCDecayChanGen, int8_t); //! resonant decay channel flag, generator level // mapping of decay types enum DecayType { DPlusToPiKPi = 0, @@ -432,7 +479,7 @@ auto InvMassXicToPiKP(const T& candidate) } // namespace hf_cand_prong3 // 3-prong decay candidate table -DECLARE_SOA_TABLE(HfCandProng3Base, "AOD", "HFCANDP3BASE", +DECLARE_SOA_TABLE(HfCandProng3Base, "AOD", "HFCANDP3BASE", //! // general columns HFCAND_COLUMNS, // 3-prong specific columns @@ -470,19 +517,19 @@ DECLARE_SOA_TABLE(HfCandProng3Base, "AOD", "HFCANDP3BASE", hf_cand::E2); // extended table with expression columns that can be used as arguments of dynamic columns -DECLARE_SOA_EXTENDED_TABLE_USER(HfCandProng3Ext, HfCandProng3Base, "HFCANDP3EXT", +DECLARE_SOA_EXTENDED_TABLE_USER(HfCandProng3Ext, HfCandProng3Base, "HFCANDP3EXT", //! hf_cand_prong3::Px, hf_cand_prong3::Py, hf_cand_prong3::Pz); using HfCandProng3 = HfCandProng3Ext; // table with results of reconstruction level MC matching -DECLARE_SOA_TABLE(HfCandProng3MCRec, "AOD", "HFCANDP3MCREC", +DECLARE_SOA_TABLE(HfCandProng3MCRec, "AOD", "HFCANDP3MCREC", //! hf_cand_prong3::FlagMCMatchRec, hf_cand_prong3::OriginMCRec, hf_cand_prong3::FlagMCDecayChanRec); // table with results of generator level MC matching -DECLARE_SOA_TABLE(HfCandProng3MCGen, "AOD", "HFCANDP3MCGEN", +DECLARE_SOA_TABLE(HfCandProng3MCGen, "AOD", "HFCANDP3MCGEN", //! hf_cand_prong3::FlagMCMatchGen, hf_cand_prong3::OriginMCGen, hf_cand_prong3::FlagMCDecayChanGen); diff --git a/Analysis/DataModel/include/AnalysisDataModel/Jet.h b/Analysis/DataModel/include/AnalysisDataModel/Jet.h index 12b19798af5ed..a27351a27d5e6 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/Jet.h +++ b/Analysis/DataModel/include/AnalysisDataModel/Jet.h @@ -21,20 +21,24 @@ namespace o2::aod { namespace jet { -DECLARE_SOA_INDEX_COLUMN(Collision, collision); -DECLARE_SOA_COLUMN(Pt, pt, float); -DECLARE_SOA_COLUMN(Eta, eta, float); -DECLARE_SOA_COLUMN(Phi, phi, float); -DECLARE_SOA_COLUMN(Energy, energy, float); -DECLARE_SOA_COLUMN(Mass, mass, float); -DECLARE_SOA_COLUMN(Area, area, float); -DECLARE_SOA_DYNAMIC_COLUMN(Px, px, [](float pt, float phi) { return pt * std::cos(phi); }); -DECLARE_SOA_DYNAMIC_COLUMN(Py, py, [](float pt, float phi) { return pt * std::sin(phi); }); -DECLARE_SOA_DYNAMIC_COLUMN(Pz, pz, [](float pt, float eta) { return pt * std::sinh(eta); }); -DECLARE_SOA_DYNAMIC_COLUMN(P, p, [](float pt, float eta) { return pt * std::cosh(eta); }); //absolute p +DECLARE_SOA_INDEX_COLUMN(Collision, collision); //! +DECLARE_SOA_COLUMN(Pt, pt, float); //! +DECLARE_SOA_COLUMN(Eta, eta, float); //! +DECLARE_SOA_COLUMN(Phi, phi, float); //! +DECLARE_SOA_COLUMN(Energy, energy, float); //! +DECLARE_SOA_COLUMN(Mass, mass, float); //! +DECLARE_SOA_COLUMN(Area, area, float); //! +DECLARE_SOA_DYNAMIC_COLUMN(Px, px, //! + [](float pt, float phi) -> float { return pt * std::cos(phi); }); +DECLARE_SOA_DYNAMIC_COLUMN(Py, py, //! + [](float pt, float phi) -> float { return pt * std::sin(phi); }); +DECLARE_SOA_DYNAMIC_COLUMN(Pz, pz, //! + [](float pt, float eta) -> float { return pt * std::sinh(eta); }); +DECLARE_SOA_DYNAMIC_COLUMN(P, p, //! absolute p + [](float pt, float eta) -> float { return pt * std::cosh(eta); }); } // namespace jet -DECLARE_SOA_TABLE(Jets, "AOD", "JET", +DECLARE_SOA_TABLE(Jets, "AOD", "JET", //! o2::soa::Index<>, jet::CollisionId, jet::Pt, @@ -54,11 +58,11 @@ using Jet = Jets::iterator; // when list of references available namespace constituents { -DECLARE_SOA_INDEX_COLUMN(Jet, jet); -DECLARE_SOA_INDEX_COLUMN(Track, track); +DECLARE_SOA_INDEX_COLUMN(Jet, jet); //! +DECLARE_SOA_INDEX_COLUMN(Track, track); //! } // namespace constituents -DECLARE_SOA_TABLE(JetConstituents, "AOD", "CONSTITUENTS", +DECLARE_SOA_TABLE(JetConstituents, "AOD", "CONSTITUENTS", //! constituents::JetId, constituents::TrackId); @@ -66,18 +70,22 @@ using JetConstituent = JetConstituents::iterator; namespace constituentssub { -DECLARE_SOA_INDEX_COLUMN(Jet, jet); -DECLARE_SOA_COLUMN(Pt, pt, float); -DECLARE_SOA_COLUMN(Eta, eta, float); -DECLARE_SOA_COLUMN(Phi, phi, float); -DECLARE_SOA_COLUMN(Energy, energy, float); -DECLARE_SOA_COLUMN(Mass, mass, float); -DECLARE_SOA_DYNAMIC_COLUMN(Px, px, [](float pt, float phi) { return pt * std::cos(phi); }); -DECLARE_SOA_DYNAMIC_COLUMN(Py, py, [](float pt, float phi) { return pt * std::sin(phi); }); -DECLARE_SOA_DYNAMIC_COLUMN(Pz, pz, [](float pt, float eta) { return pt * std::sinh(eta); }); -DECLARE_SOA_DYNAMIC_COLUMN(P, p, [](float pt, float eta) { return pt * std::cosh(eta); }); //absolute p +DECLARE_SOA_INDEX_COLUMN(Jet, jet); //! +DECLARE_SOA_COLUMN(Pt, pt, float); //! +DECLARE_SOA_COLUMN(Eta, eta, float); //! +DECLARE_SOA_COLUMN(Phi, phi, float); //! +DECLARE_SOA_COLUMN(Energy, energy, float); //! +DECLARE_SOA_COLUMN(Mass, mass, float); //! +DECLARE_SOA_DYNAMIC_COLUMN(Px, px, //! + [](float pt, float phi) -> float { return pt * std::cos(phi); }); +DECLARE_SOA_DYNAMIC_COLUMN(Py, py, //! + [](float pt, float phi) -> float { return pt * std::sin(phi); }); +DECLARE_SOA_DYNAMIC_COLUMN(Pz, pz, //! + [](float pt, float eta) -> float { return pt * std::sinh(eta); }); +DECLARE_SOA_DYNAMIC_COLUMN(P, p, //! absolute p + [](float pt, float eta) -> float { return pt * std::cosh(eta); }); } //namespace constituentssub -DECLARE_SOA_TABLE(JetConstituentsSub, "AOD", "CONSTITUENTSSUB", +DECLARE_SOA_TABLE(JetConstituentsSub, "AOD", "CONSTITUENTSSUB", //! constituentssub::JetId, constituentssub::Pt, constituentssub::Eta, diff --git a/Analysis/DataModel/include/AnalysisDataModel/Multiplicity.h b/Analysis/DataModel/include/AnalysisDataModel/Multiplicity.h index bb4b4aadccf51..e9644cdbc5d7f 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/Multiplicity.h +++ b/Analysis/DataModel/include/AnalysisDataModel/Multiplicity.h @@ -16,18 +16,26 @@ namespace o2::aod { namespace mult { -DECLARE_SOA_COLUMN(MultV0A, multV0A, float); -DECLARE_SOA_COLUMN(MultV0C, multV0C, float); -DECLARE_SOA_COLUMN(MultT0A, multT0A, float); -DECLARE_SOA_COLUMN(MultT0C, multT0C, float); -DECLARE_SOA_COLUMN(MultZNA, multZNA, float); -DECLARE_SOA_COLUMN(MultZNC, multZNC, float); -DECLARE_SOA_DYNAMIC_COLUMN(MultV0M, multV0M, [](float multV0A, float multV0C) -> float { return multV0A + multV0C; }); -DECLARE_SOA_DYNAMIC_COLUMN(MultT0M, multT0M, [](float multT0A, float multT0C) -> float { return multT0A + multT0C; }); +DECLARE_SOA_COLUMN(MultV0A, multV0A, float); //! +DECLARE_SOA_COLUMN(MultV0C, multV0C, float); //! +DECLARE_SOA_COLUMN(MultT0A, multT0A, float); //! +DECLARE_SOA_COLUMN(MultT0C, multT0C, float); //! +DECLARE_SOA_COLUMN(MultZNA, multZNA, float); //! +DECLARE_SOA_COLUMN(MultZNC, multZNC, float); //! +DECLARE_SOA_DYNAMIC_COLUMN(MultV0M, multV0M, //! + [](float multV0A, float multV0C) -> float { return multV0A + multV0C; }); +DECLARE_SOA_DYNAMIC_COLUMN(MultT0M, multT0M, //! + [](float multT0A, float multT0C) -> float { return multT0A + multT0C; }); DECLARE_SOA_COLUMN(MultTracklets, multTracklets, int); } // namespace mult -DECLARE_SOA_TABLE(Mults, "AOD", "MULT", mult::MultV0A, mult::MultV0C, mult::MultT0A, mult::MultT0C, mult::MultZNA, mult::MultZNC, mult::MultV0M, mult::MultT0M, mult::MultTracklets); +DECLARE_SOA_TABLE(Mults, "AOD", "MULT", //! + mult::MultV0A, mult::MultV0C, + mult::MultT0A, mult::MultT0C, + mult::MultZNA, mult::MultZNC, + mult::MultV0M, + mult::MultT0M, + mult::MultTracklets); using Mult = Mults::iterator; } // namespace o2::aod diff --git a/Analysis/DataModel/include/AnalysisDataModel/PID/PIDResponse.h b/Analysis/DataModel/include/AnalysisDataModel/PID/PIDResponse.h index bc62d12557790..38bbb0928813f 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/PID/PIDResponse.h +++ b/Analysis/DataModel/include/AnalysisDataModel/PID/PIDResponse.h @@ -27,48 +27,58 @@ namespace o2::aod namespace pidtofbeta { -DECLARE_SOA_COLUMN(Beta, beta, float); -DECLARE_SOA_COLUMN(BetaError, betaerror, float); +DECLARE_SOA_COLUMN(Beta, beta, float); //! +DECLARE_SOA_COLUMN(BetaError, betaerror, float); //! // -DECLARE_SOA_COLUMN(ExpBetaEl, expbetael, float); -DECLARE_SOA_COLUMN(ExpBetaElError, expbetaelerror, float); +DECLARE_SOA_COLUMN(ExpBetaEl, expbetael, float); //! +DECLARE_SOA_COLUMN(ExpBetaElError, expbetaelerror, float); //! // -DECLARE_SOA_COLUMN(SeparationBetaEl, separationbetael, float); -DECLARE_SOA_DYNAMIC_COLUMN(DiffBetaEl, diffbetael, [](float beta, float expbetael) -> float { return beta - expbetael; }); +DECLARE_SOA_COLUMN(SeparationBetaEl, separationbetael, float); //! +DECLARE_SOA_DYNAMIC_COLUMN(DiffBetaEl, diffbetael, //! + [](float beta, float expbetael) -> float { return beta - expbetael; }); } // namespace pidtofbeta namespace pidtof { // Expected times -DECLARE_SOA_DYNAMIC_COLUMN(TOFExpSignalDiffEl, tofExpSignalDiffEl, [](float nsigma, float sigma) { return nsigma * sigma; }); -DECLARE_SOA_DYNAMIC_COLUMN(TOFExpSignalDiffMu, tofExpSignalDiffMu, [](float nsigma, float sigma) { return nsigma * sigma; }); -DECLARE_SOA_DYNAMIC_COLUMN(TOFExpSignalDiffPi, tofExpSignalDiffPi, [](float nsigma, float sigma) { return nsigma * sigma; }); -DECLARE_SOA_DYNAMIC_COLUMN(TOFExpSignalDiffKa, tofExpSignalDiffKa, [](float nsigma, float sigma) { return nsigma * sigma; }); -DECLARE_SOA_DYNAMIC_COLUMN(TOFExpSignalDiffPr, tofExpSignalDiffPr, [](float nsigma, float sigma) { return nsigma * sigma; }); -DECLARE_SOA_DYNAMIC_COLUMN(TOFExpSignalDiffDe, tofExpSignalDiffDe, [](float nsigma, float sigma) { return nsigma * sigma; }); -DECLARE_SOA_DYNAMIC_COLUMN(TOFExpSignalDiffTr, tofExpSignalDiffTr, [](float nsigma, float sigma) { return nsigma * sigma; }); -DECLARE_SOA_DYNAMIC_COLUMN(TOFExpSignalDiffHe, tofExpSignalDiffHe, [](float nsigma, float sigma) { return nsigma * sigma; }); -DECLARE_SOA_DYNAMIC_COLUMN(TOFExpSignalDiffAl, tofExpSignalDiffAl, [](float nsigma, float sigma) { return nsigma * sigma; }); +DECLARE_SOA_DYNAMIC_COLUMN(TOFExpSignalDiffEl, tofExpSignalDiffEl, //! + [](float nsigma, float sigma) -> float { return nsigma * sigma; }); +DECLARE_SOA_DYNAMIC_COLUMN(TOFExpSignalDiffMu, tofExpSignalDiffMu, //! + [](float nsigma, float sigma) -> float { return nsigma * sigma; }); +DECLARE_SOA_DYNAMIC_COLUMN(TOFExpSignalDiffPi, tofExpSignalDiffPi, //! + [](float nsigma, float sigma) -> float { return nsigma * sigma; }); +DECLARE_SOA_DYNAMIC_COLUMN(TOFExpSignalDiffKa, tofExpSignalDiffKa, //! + [](float nsigma, float sigma) -> float { return nsigma * sigma; }); +DECLARE_SOA_DYNAMIC_COLUMN(TOFExpSignalDiffPr, tofExpSignalDiffPr, //! + [](float nsigma, float sigma) -> float { return nsigma * sigma; }); +DECLARE_SOA_DYNAMIC_COLUMN(TOFExpSignalDiffDe, tofExpSignalDiffDe, //! + [](float nsigma, float sigma) -> float { return nsigma * sigma; }); +DECLARE_SOA_DYNAMIC_COLUMN(TOFExpSignalDiffTr, tofExpSignalDiffTr, //! + [](float nsigma, float sigma) -> float { return nsigma * sigma; }); +DECLARE_SOA_DYNAMIC_COLUMN(TOFExpSignalDiffHe, tofExpSignalDiffHe, //! + [](float nsigma, float sigma) -> float { return nsigma * sigma; }); +DECLARE_SOA_DYNAMIC_COLUMN(TOFExpSignalDiffAl, tofExpSignalDiffAl, //! + [](float nsigma, float sigma) -> float { return nsigma * sigma; }); // Expected sigma -DECLARE_SOA_COLUMN(TOFExpSigmaEl, tofExpSigmaEl, float); -DECLARE_SOA_COLUMN(TOFExpSigmaMu, tofExpSigmaMu, float); -DECLARE_SOA_COLUMN(TOFExpSigmaPi, tofExpSigmaPi, float); -DECLARE_SOA_COLUMN(TOFExpSigmaKa, tofExpSigmaKa, float); -DECLARE_SOA_COLUMN(TOFExpSigmaPr, tofExpSigmaPr, float); -DECLARE_SOA_COLUMN(TOFExpSigmaDe, tofExpSigmaDe, float); -DECLARE_SOA_COLUMN(TOFExpSigmaTr, tofExpSigmaTr, float); -DECLARE_SOA_COLUMN(TOFExpSigmaHe, tofExpSigmaHe, float); -DECLARE_SOA_COLUMN(TOFExpSigmaAl, tofExpSigmaAl, float); +DECLARE_SOA_COLUMN(TOFExpSigmaEl, tofExpSigmaEl, float); //! +DECLARE_SOA_COLUMN(TOFExpSigmaMu, tofExpSigmaMu, float); //! +DECLARE_SOA_COLUMN(TOFExpSigmaPi, tofExpSigmaPi, float); //! +DECLARE_SOA_COLUMN(TOFExpSigmaKa, tofExpSigmaKa, float); //! +DECLARE_SOA_COLUMN(TOFExpSigmaPr, tofExpSigmaPr, float); //! +DECLARE_SOA_COLUMN(TOFExpSigmaDe, tofExpSigmaDe, float); //! +DECLARE_SOA_COLUMN(TOFExpSigmaTr, tofExpSigmaTr, float); //! +DECLARE_SOA_COLUMN(TOFExpSigmaHe, tofExpSigmaHe, float); //! +DECLARE_SOA_COLUMN(TOFExpSigmaAl, tofExpSigmaAl, float); //! // NSigma -DECLARE_SOA_COLUMN(TOFNSigmaEl, tofNSigmaEl, float); -DECLARE_SOA_COLUMN(TOFNSigmaMu, tofNSigmaMu, float); -DECLARE_SOA_COLUMN(TOFNSigmaPi, tofNSigmaPi, float); -DECLARE_SOA_COLUMN(TOFNSigmaKa, tofNSigmaKa, float); -DECLARE_SOA_COLUMN(TOFNSigmaPr, tofNSigmaPr, float); -DECLARE_SOA_COLUMN(TOFNSigmaDe, tofNSigmaDe, float); -DECLARE_SOA_COLUMN(TOFNSigmaTr, tofNSigmaTr, float); -DECLARE_SOA_COLUMN(TOFNSigmaHe, tofNSigmaHe, float); -DECLARE_SOA_COLUMN(TOFNSigmaAl, tofNSigmaAl, float); +DECLARE_SOA_COLUMN(TOFNSigmaEl, tofNSigmaEl, float); //! +DECLARE_SOA_COLUMN(TOFNSigmaMu, tofNSigmaMu, float); //! +DECLARE_SOA_COLUMN(TOFNSigmaPi, tofNSigmaPi, float); //! +DECLARE_SOA_COLUMN(TOFNSigmaKa, tofNSigmaKa, float); //! +DECLARE_SOA_COLUMN(TOFNSigmaPr, tofNSigmaPr, float); //! +DECLARE_SOA_COLUMN(TOFNSigmaDe, tofNSigmaDe, float); //! +DECLARE_SOA_COLUMN(TOFNSigmaTr, tofNSigmaTr, float); //! +DECLARE_SOA_COLUMN(TOFNSigmaHe, tofNSigmaHe, float); //! +DECLARE_SOA_COLUMN(TOFNSigmaAl, tofNSigmaAl, float); //! } // namespace pidtof // Macro to convert the stored Nsigmas to floats @@ -86,88 +96,115 @@ constexpr float binned_max = 6.35; constexpr float binned_min = -6.35; constexpr float bin_width = (binned_max - binned_min) / nbins; // NSigma with reduced size 8 bit -DECLARE_SOA_COLUMN(TOFNSigmaStoreEl, tofNSigmaStoreEl, binned_nsigma_t); -DECLARE_SOA_COLUMN(TOFNSigmaStoreMu, tofNSigmaStoreMu, binned_nsigma_t); -DECLARE_SOA_COLUMN(TOFNSigmaStorePi, tofNSigmaStorePi, binned_nsigma_t); -DECLARE_SOA_COLUMN(TOFNSigmaStoreKa, tofNSigmaStoreKa, binned_nsigma_t); -DECLARE_SOA_COLUMN(TOFNSigmaStorePr, tofNSigmaStorePr, binned_nsigma_t); -DECLARE_SOA_COLUMN(TOFNSigmaStoreDe, tofNSigmaStoreDe, binned_nsigma_t); -DECLARE_SOA_COLUMN(TOFNSigmaStoreTr, tofNSigmaStoreTr, binned_nsigma_t); -DECLARE_SOA_COLUMN(TOFNSigmaStoreHe, tofNSigmaStoreHe, binned_nsigma_t); -DECLARE_SOA_COLUMN(TOFNSigmaStoreAl, tofNSigmaStoreAl, binned_nsigma_t); +DECLARE_SOA_COLUMN(TOFNSigmaStoreEl, tofNSigmaStoreEl, binned_nsigma_t); //! +DECLARE_SOA_COLUMN(TOFNSigmaStoreMu, tofNSigmaStoreMu, binned_nsigma_t); //! +DECLARE_SOA_COLUMN(TOFNSigmaStorePi, tofNSigmaStorePi, binned_nsigma_t); //! +DECLARE_SOA_COLUMN(TOFNSigmaStoreKa, tofNSigmaStoreKa, binned_nsigma_t); //! +DECLARE_SOA_COLUMN(TOFNSigmaStorePr, tofNSigmaStorePr, binned_nsigma_t); //! +DECLARE_SOA_COLUMN(TOFNSigmaStoreDe, tofNSigmaStoreDe, binned_nsigma_t); //! +DECLARE_SOA_COLUMN(TOFNSigmaStoreTr, tofNSigmaStoreTr, binned_nsigma_t); //! +DECLARE_SOA_COLUMN(TOFNSigmaStoreHe, tofNSigmaStoreHe, binned_nsigma_t); //! +DECLARE_SOA_COLUMN(TOFNSigmaStoreAl, tofNSigmaStoreAl, binned_nsigma_t); //! // NSigma with reduced size in [binned_min, binned_max] bin size bin_width -DEFINE_UNWRAP_NSIGMA_COLUMN(TOFNSigmaEl, tofNSigmaEl); -DEFINE_UNWRAP_NSIGMA_COLUMN(TOFNSigmaMu, tofNSigmaMu); -DEFINE_UNWRAP_NSIGMA_COLUMN(TOFNSigmaPi, tofNSigmaPi); -DEFINE_UNWRAP_NSIGMA_COLUMN(TOFNSigmaKa, tofNSigmaKa); -DEFINE_UNWRAP_NSIGMA_COLUMN(TOFNSigmaPr, tofNSigmaPr); -DEFINE_UNWRAP_NSIGMA_COLUMN(TOFNSigmaDe, tofNSigmaDe); -DEFINE_UNWRAP_NSIGMA_COLUMN(TOFNSigmaTr, tofNSigmaTr); -DEFINE_UNWRAP_NSIGMA_COLUMN(TOFNSigmaHe, tofNSigmaHe); -DEFINE_UNWRAP_NSIGMA_COLUMN(TOFNSigmaAl, tofNSigmaAl); +DEFINE_UNWRAP_NSIGMA_COLUMN(TOFNSigmaEl, tofNSigmaEl); //! +DEFINE_UNWRAP_NSIGMA_COLUMN(TOFNSigmaMu, tofNSigmaMu); //! +DEFINE_UNWRAP_NSIGMA_COLUMN(TOFNSigmaPi, tofNSigmaPi); //! +DEFINE_UNWRAP_NSIGMA_COLUMN(TOFNSigmaKa, tofNSigmaKa); //! +DEFINE_UNWRAP_NSIGMA_COLUMN(TOFNSigmaPr, tofNSigmaPr); //! +DEFINE_UNWRAP_NSIGMA_COLUMN(TOFNSigmaDe, tofNSigmaDe); //! +DEFINE_UNWRAP_NSIGMA_COLUMN(TOFNSigmaTr, tofNSigmaTr); //! +DEFINE_UNWRAP_NSIGMA_COLUMN(TOFNSigmaHe, tofNSigmaHe); //! +DEFINE_UNWRAP_NSIGMA_COLUMN(TOFNSigmaAl, tofNSigmaAl); //! } // namespace pidtof_tiny -DECLARE_SOA_TABLE(pidRespTOFbeta, "AOD", "pidRespTOFbeta", +DECLARE_SOA_TABLE(pidRespTOFbeta, "AOD", "pidRespTOFbeta", //! pidtofbeta::Beta, pidtofbeta::BetaError, pidtofbeta::ExpBetaEl, pidtofbeta::ExpBetaElError, pidtofbeta::SeparationBetaEl, pidtofbeta::DiffBetaEl); // Per particle tables -DECLARE_SOA_TABLE(pidRespTOFEl, "AOD", "pidRespTOFEl", pidtof::TOFExpSignalDiffEl, pidtof::TOFExpSigmaEl, pidtof::TOFNSigmaEl); -DECLARE_SOA_TABLE(pidRespTOFMu, "AOD", "pidRespTOFMu", pidtof::TOFExpSignalDiffMu, pidtof::TOFExpSigmaMu, pidtof::TOFNSigmaMu); -DECLARE_SOA_TABLE(pidRespTOFPi, "AOD", "pidRespTOFPi", pidtof::TOFExpSignalDiffPi, pidtof::TOFExpSigmaPi, pidtof::TOFNSigmaPi); -DECLARE_SOA_TABLE(pidRespTOFKa, "AOD", "pidRespTOFKa", pidtof::TOFExpSignalDiffKa, pidtof::TOFExpSigmaKa, pidtof::TOFNSigmaKa); -DECLARE_SOA_TABLE(pidRespTOFPr, "AOD", "pidRespTOFPr", pidtof::TOFExpSignalDiffPr, pidtof::TOFExpSigmaPr, pidtof::TOFNSigmaPr); -DECLARE_SOA_TABLE(pidRespTOFDe, "AOD", "pidRespTOFDe", pidtof::TOFExpSignalDiffDe, pidtof::TOFExpSigmaDe, pidtof::TOFNSigmaDe); -DECLARE_SOA_TABLE(pidRespTOFTr, "AOD", "pidRespTOFTr", pidtof::TOFExpSignalDiffTr, pidtof::TOFExpSigmaTr, pidtof::TOFNSigmaTr); -DECLARE_SOA_TABLE(pidRespTOFHe, "AOD", "pidRespTOFHe", pidtof::TOFExpSignalDiffHe, pidtof::TOFExpSigmaHe, pidtof::TOFNSigmaHe); -DECLARE_SOA_TABLE(pidRespTOFAl, "AOD", "pidRespTOFAl", pidtof::TOFExpSignalDiffAl, pidtof::TOFExpSigmaAl, pidtof::TOFNSigmaAl); +DECLARE_SOA_TABLE(pidRespTOFEl, "AOD", "pidRespTOFEl", //! + pidtof::TOFExpSignalDiffEl, pidtof::TOFExpSigmaEl, pidtof::TOFNSigmaEl); +DECLARE_SOA_TABLE(pidRespTOFMu, "AOD", "pidRespTOFMu", //! + pidtof::TOFExpSignalDiffMu, pidtof::TOFExpSigmaMu, pidtof::TOFNSigmaMu); +DECLARE_SOA_TABLE(pidRespTOFPi, "AOD", "pidRespTOFPi", //! + pidtof::TOFExpSignalDiffPi, pidtof::TOFExpSigmaPi, pidtof::TOFNSigmaPi); +DECLARE_SOA_TABLE(pidRespTOFKa, "AOD", "pidRespTOFKa", //! + pidtof::TOFExpSignalDiffKa, pidtof::TOFExpSigmaKa, pidtof::TOFNSigmaKa); +DECLARE_SOA_TABLE(pidRespTOFPr, "AOD", "pidRespTOFPr", //! + pidtof::TOFExpSignalDiffPr, pidtof::TOFExpSigmaPr, pidtof::TOFNSigmaPr); +DECLARE_SOA_TABLE(pidRespTOFDe, "AOD", "pidRespTOFDe", //! + pidtof::TOFExpSignalDiffDe, pidtof::TOFExpSigmaDe, pidtof::TOFNSigmaDe); +DECLARE_SOA_TABLE(pidRespTOFTr, "AOD", "pidRespTOFTr", //! + pidtof::TOFExpSignalDiffTr, pidtof::TOFExpSigmaTr, pidtof::TOFNSigmaTr); +DECLARE_SOA_TABLE(pidRespTOFHe, "AOD", "pidRespTOFHe", //! + pidtof::TOFExpSignalDiffHe, pidtof::TOFExpSigmaHe, pidtof::TOFNSigmaHe); +DECLARE_SOA_TABLE(pidRespTOFAl, "AOD", "pidRespTOFAl", //! + pidtof::TOFExpSignalDiffAl, pidtof::TOFExpSigmaAl, pidtof::TOFNSigmaAl); // Tiny size tables -DECLARE_SOA_TABLE(pidRespTOFTEl, "AOD", "pidRespTOFTEl", pidtof_tiny::TOFNSigmaStoreEl, pidtof_tiny::TOFNSigmaEl); -DECLARE_SOA_TABLE(pidRespTOFTMu, "AOD", "pidRespTOFTMu", pidtof_tiny::TOFNSigmaStoreMu, pidtof_tiny::TOFNSigmaMu); -DECLARE_SOA_TABLE(pidRespTOFTPi, "AOD", "pidRespTOFTPi", pidtof_tiny::TOFNSigmaStorePi, pidtof_tiny::TOFNSigmaPi); -DECLARE_SOA_TABLE(pidRespTOFTKa, "AOD", "pidRespTOFTKa", pidtof_tiny::TOFNSigmaStoreKa, pidtof_tiny::TOFNSigmaKa); -DECLARE_SOA_TABLE(pidRespTOFTPr, "AOD", "pidRespTOFTPr", pidtof_tiny::TOFNSigmaStorePr, pidtof_tiny::TOFNSigmaPr); -DECLARE_SOA_TABLE(pidRespTOFTDe, "AOD", "pidRespTOFTDe", pidtof_tiny::TOFNSigmaStoreDe, pidtof_tiny::TOFNSigmaDe); -DECLARE_SOA_TABLE(pidRespTOFTTr, "AOD", "pidRespTOFTTr", pidtof_tiny::TOFNSigmaStoreTr, pidtof_tiny::TOFNSigmaTr); -DECLARE_SOA_TABLE(pidRespTOFTHe, "AOD", "pidRespTOFTHe", pidtof_tiny::TOFNSigmaStoreHe, pidtof_tiny::TOFNSigmaHe); -DECLARE_SOA_TABLE(pidRespTOFTAl, "AOD", "pidRespTOFTAl", pidtof_tiny::TOFNSigmaStoreAl, pidtof_tiny::TOFNSigmaAl); +DECLARE_SOA_TABLE(pidRespTOFTEl, "AOD", "pidRespTOFTEl", //! + pidtof_tiny::TOFNSigmaStoreEl, pidtof_tiny::TOFNSigmaEl); +DECLARE_SOA_TABLE(pidRespTOFTMu, "AOD", "pidRespTOFTMu", //! + pidtof_tiny::TOFNSigmaStoreMu, pidtof_tiny::TOFNSigmaMu); +DECLARE_SOA_TABLE(pidRespTOFTPi, "AOD", "pidRespTOFTPi", //! + pidtof_tiny::TOFNSigmaStorePi, pidtof_tiny::TOFNSigmaPi); +DECLARE_SOA_TABLE(pidRespTOFTKa, "AOD", "pidRespTOFTKa", //! + pidtof_tiny::TOFNSigmaStoreKa, pidtof_tiny::TOFNSigmaKa); +DECLARE_SOA_TABLE(pidRespTOFTPr, "AOD", "pidRespTOFTPr", //! + pidtof_tiny::TOFNSigmaStorePr, pidtof_tiny::TOFNSigmaPr); +DECLARE_SOA_TABLE(pidRespTOFTDe, "AOD", "pidRespTOFTDe", //! + pidtof_tiny::TOFNSigmaStoreDe, pidtof_tiny::TOFNSigmaDe); +DECLARE_SOA_TABLE(pidRespTOFTTr, "AOD", "pidRespTOFTTr", //! + pidtof_tiny::TOFNSigmaStoreTr, pidtof_tiny::TOFNSigmaTr); +DECLARE_SOA_TABLE(pidRespTOFTHe, "AOD", "pidRespTOFTHe", //! + pidtof_tiny::TOFNSigmaStoreHe, pidtof_tiny::TOFNSigmaHe); +DECLARE_SOA_TABLE(pidRespTOFTAl, "AOD", "pidRespTOFTAl", //! + pidtof_tiny::TOFNSigmaStoreAl, pidtof_tiny::TOFNSigmaAl); namespace pidtpc { // Expected signals -DECLARE_SOA_DYNAMIC_COLUMN(TPCExpSignalDiffEl, tpcExpSignalDiffEl, [](float nsigma, float sigma) { return nsigma * sigma; }); -DECLARE_SOA_DYNAMIC_COLUMN(TPCExpSignalDiffMu, tpcExpSignalDiffMu, [](float nsigma, float sigma) { return nsigma * sigma; }); -DECLARE_SOA_DYNAMIC_COLUMN(TPCExpSignalDiffPi, tpcExpSignalDiffPi, [](float nsigma, float sigma) { return nsigma * sigma; }); -DECLARE_SOA_DYNAMIC_COLUMN(TPCExpSignalDiffKa, tpcExpSignalDiffKa, [](float nsigma, float sigma) { return nsigma * sigma; }); -DECLARE_SOA_DYNAMIC_COLUMN(TPCExpSignalDiffPr, tpcExpSignalDiffPr, [](float nsigma, float sigma) { return nsigma * sigma; }); -DECLARE_SOA_DYNAMIC_COLUMN(TPCExpSignalDiffDe, tpcExpSignalDiffDe, [](float nsigma, float sigma) { return nsigma * sigma; }); -DECLARE_SOA_DYNAMIC_COLUMN(TPCExpSignalDiffTr, tpcExpSignalDiffTr, [](float nsigma, float sigma) { return nsigma * sigma; }); -DECLARE_SOA_DYNAMIC_COLUMN(TPCExpSignalDiffHe, tpcExpSignalDiffHe, [](float nsigma, float sigma) { return nsigma * sigma; }); -DECLARE_SOA_DYNAMIC_COLUMN(TPCExpSignalDiffAl, tpcExpSignalDiffAl, [](float nsigma, float sigma) { return nsigma * sigma; }); +DECLARE_SOA_DYNAMIC_COLUMN(TPCExpSignalDiffEl, tpcExpSignalDiffEl, //! + [](float nsigma, float sigma) -> float { return nsigma * sigma; }); +DECLARE_SOA_DYNAMIC_COLUMN(TPCExpSignalDiffMu, tpcExpSignalDiffMu, //! + [](float nsigma, float sigma) -> float { return nsigma * sigma; }); +DECLARE_SOA_DYNAMIC_COLUMN(TPCExpSignalDiffPi, tpcExpSignalDiffPi, //! + [](float nsigma, float sigma) -> float { return nsigma * sigma; }); +DECLARE_SOA_DYNAMIC_COLUMN(TPCExpSignalDiffKa, tpcExpSignalDiffKa, //! + [](float nsigma, float sigma) -> float { return nsigma * sigma; }); +DECLARE_SOA_DYNAMIC_COLUMN(TPCExpSignalDiffPr, tpcExpSignalDiffPr, //! + [](float nsigma, float sigma) -> float { return nsigma * sigma; }); +DECLARE_SOA_DYNAMIC_COLUMN(TPCExpSignalDiffDe, tpcExpSignalDiffDe, //! + [](float nsigma, float sigma) -> float { return nsigma * sigma; }); +DECLARE_SOA_DYNAMIC_COLUMN(TPCExpSignalDiffTr, tpcExpSignalDiffTr, //! + [](float nsigma, float sigma) -> float { return nsigma * sigma; }); +DECLARE_SOA_DYNAMIC_COLUMN(TPCExpSignalDiffHe, tpcExpSignalDiffHe, //! + [](float nsigma, float sigma) -> float { return nsigma * sigma; }); +DECLARE_SOA_DYNAMIC_COLUMN(TPCExpSignalDiffAl, tpcExpSignalDiffAl, //! + [](float nsigma, float sigma) -> float { return nsigma * sigma; }); // Expected sigma -DECLARE_SOA_COLUMN(TPCExpSigmaEl, tpcExpSigmaEl, float); -DECLARE_SOA_COLUMN(TPCExpSigmaMu, tpcExpSigmaMu, float); -DECLARE_SOA_COLUMN(TPCExpSigmaPi, tpcExpSigmaPi, float); -DECLARE_SOA_COLUMN(TPCExpSigmaKa, tpcExpSigmaKa, float); -DECLARE_SOA_COLUMN(TPCExpSigmaPr, tpcExpSigmaPr, float); -DECLARE_SOA_COLUMN(TPCExpSigmaDe, tpcExpSigmaDe, float); -DECLARE_SOA_COLUMN(TPCExpSigmaTr, tpcExpSigmaTr, float); -DECLARE_SOA_COLUMN(TPCExpSigmaHe, tpcExpSigmaHe, float); -DECLARE_SOA_COLUMN(TPCExpSigmaAl, tpcExpSigmaAl, float); +DECLARE_SOA_COLUMN(TPCExpSigmaEl, tpcExpSigmaEl, float); //! +DECLARE_SOA_COLUMN(TPCExpSigmaMu, tpcExpSigmaMu, float); //! +DECLARE_SOA_COLUMN(TPCExpSigmaPi, tpcExpSigmaPi, float); //! +DECLARE_SOA_COLUMN(TPCExpSigmaKa, tpcExpSigmaKa, float); //! +DECLARE_SOA_COLUMN(TPCExpSigmaPr, tpcExpSigmaPr, float); //! +DECLARE_SOA_COLUMN(TPCExpSigmaDe, tpcExpSigmaDe, float); //! +DECLARE_SOA_COLUMN(TPCExpSigmaTr, tpcExpSigmaTr, float); //! +DECLARE_SOA_COLUMN(TPCExpSigmaHe, tpcExpSigmaHe, float); //! +DECLARE_SOA_COLUMN(TPCExpSigmaAl, tpcExpSigmaAl, float); //! // NSigma -DECLARE_SOA_COLUMN(TPCNSigmaEl, tpcNSigmaEl, float); -DECLARE_SOA_COLUMN(TPCNSigmaMu, tpcNSigmaMu, float); -DECLARE_SOA_COLUMN(TPCNSigmaPi, tpcNSigmaPi, float); -DECLARE_SOA_COLUMN(TPCNSigmaKa, tpcNSigmaKa, float); -DECLARE_SOA_COLUMN(TPCNSigmaPr, tpcNSigmaPr, float); -DECLARE_SOA_COLUMN(TPCNSigmaDe, tpcNSigmaDe, float); -DECLARE_SOA_COLUMN(TPCNSigmaTr, tpcNSigmaTr, float); -DECLARE_SOA_COLUMN(TPCNSigmaHe, tpcNSigmaHe, float); -DECLARE_SOA_COLUMN(TPCNSigmaAl, tpcNSigmaAl, float); +DECLARE_SOA_COLUMN(TPCNSigmaEl, tpcNSigmaEl, float); //! +DECLARE_SOA_COLUMN(TPCNSigmaMu, tpcNSigmaMu, float); //! +DECLARE_SOA_COLUMN(TPCNSigmaPi, tpcNSigmaPi, float); //! +DECLARE_SOA_COLUMN(TPCNSigmaKa, tpcNSigmaKa, float); //! +DECLARE_SOA_COLUMN(TPCNSigmaPr, tpcNSigmaPr, float); //! +DECLARE_SOA_COLUMN(TPCNSigmaDe, tpcNSigmaDe, float); //! +DECLARE_SOA_COLUMN(TPCNSigmaTr, tpcNSigmaTr, float); //! +DECLARE_SOA_COLUMN(TPCNSigmaHe, tpcNSigmaHe, float); //! +DECLARE_SOA_COLUMN(TPCNSigmaAl, tpcNSigmaAl, float); //! } // namespace pidtpc namespace pidtpc_tiny @@ -180,49 +217,67 @@ constexpr float binned_max = 6.35; constexpr float binned_min = -6.35; constexpr float bin_width = (binned_max - binned_min) / nbins; // NSigma with reduced size -DECLARE_SOA_COLUMN(TPCNSigmaStoreEl, tpcNSigmaStoreEl, binned_nsigma_t); -DECLARE_SOA_COLUMN(TPCNSigmaStoreMu, tpcNSigmaStoreMu, binned_nsigma_t); -DECLARE_SOA_COLUMN(TPCNSigmaStorePi, tpcNSigmaStorePi, binned_nsigma_t); -DECLARE_SOA_COLUMN(TPCNSigmaStoreKa, tpcNSigmaStoreKa, binned_nsigma_t); -DECLARE_SOA_COLUMN(TPCNSigmaStorePr, tpcNSigmaStorePr, binned_nsigma_t); -DECLARE_SOA_COLUMN(TPCNSigmaStoreDe, tpcNSigmaStoreDe, binned_nsigma_t); -DECLARE_SOA_COLUMN(TPCNSigmaStoreTr, tpcNSigmaStoreTr, binned_nsigma_t); -DECLARE_SOA_COLUMN(TPCNSigmaStoreHe, tpcNSigmaStoreHe, binned_nsigma_t); -DECLARE_SOA_COLUMN(TPCNSigmaStoreAl, tpcNSigmaStoreAl, binned_nsigma_t); +DECLARE_SOA_COLUMN(TPCNSigmaStoreEl, tpcNSigmaStoreEl, binned_nsigma_t); //! +DECLARE_SOA_COLUMN(TPCNSigmaStoreMu, tpcNSigmaStoreMu, binned_nsigma_t); //! +DECLARE_SOA_COLUMN(TPCNSigmaStorePi, tpcNSigmaStorePi, binned_nsigma_t); //! +DECLARE_SOA_COLUMN(TPCNSigmaStoreKa, tpcNSigmaStoreKa, binned_nsigma_t); //! +DECLARE_SOA_COLUMN(TPCNSigmaStorePr, tpcNSigmaStorePr, binned_nsigma_t); //! +DECLARE_SOA_COLUMN(TPCNSigmaStoreDe, tpcNSigmaStoreDe, binned_nsigma_t); //! +DECLARE_SOA_COLUMN(TPCNSigmaStoreTr, tpcNSigmaStoreTr, binned_nsigma_t); //! +DECLARE_SOA_COLUMN(TPCNSigmaStoreHe, tpcNSigmaStoreHe, binned_nsigma_t); //! +DECLARE_SOA_COLUMN(TPCNSigmaStoreAl, tpcNSigmaStoreAl, binned_nsigma_t); //! // NSigma with reduced size in [binned_min, binned_max] bin size bin_width -DEFINE_UNWRAP_NSIGMA_COLUMN(TPCNSigmaEl, tpcNSigmaEl); -DEFINE_UNWRAP_NSIGMA_COLUMN(TPCNSigmaMu, tpcNSigmaMu); -DEFINE_UNWRAP_NSIGMA_COLUMN(TPCNSigmaPi, tpcNSigmaPi); -DEFINE_UNWRAP_NSIGMA_COLUMN(TPCNSigmaKa, tpcNSigmaKa); -DEFINE_UNWRAP_NSIGMA_COLUMN(TPCNSigmaPr, tpcNSigmaPr); -DEFINE_UNWRAP_NSIGMA_COLUMN(TPCNSigmaDe, tpcNSigmaDe); -DEFINE_UNWRAP_NSIGMA_COLUMN(TPCNSigmaTr, tpcNSigmaTr); -DEFINE_UNWRAP_NSIGMA_COLUMN(TPCNSigmaHe, tpcNSigmaHe); -DEFINE_UNWRAP_NSIGMA_COLUMN(TPCNSigmaAl, tpcNSigmaAl); +DEFINE_UNWRAP_NSIGMA_COLUMN(TPCNSigmaEl, tpcNSigmaEl); //! +DEFINE_UNWRAP_NSIGMA_COLUMN(TPCNSigmaMu, tpcNSigmaMu); //! +DEFINE_UNWRAP_NSIGMA_COLUMN(TPCNSigmaPi, tpcNSigmaPi); //! +DEFINE_UNWRAP_NSIGMA_COLUMN(TPCNSigmaKa, tpcNSigmaKa); //! +DEFINE_UNWRAP_NSIGMA_COLUMN(TPCNSigmaPr, tpcNSigmaPr); //! +DEFINE_UNWRAP_NSIGMA_COLUMN(TPCNSigmaDe, tpcNSigmaDe); //! +DEFINE_UNWRAP_NSIGMA_COLUMN(TPCNSigmaTr, tpcNSigmaTr); //! +DEFINE_UNWRAP_NSIGMA_COLUMN(TPCNSigmaHe, tpcNSigmaHe); //! +DEFINE_UNWRAP_NSIGMA_COLUMN(TPCNSigmaAl, tpcNSigmaAl); //! } // namespace pidtpc_tiny // Per particle tables -DECLARE_SOA_TABLE(pidRespTPCEl, "AOD", "pidRespTPCEl", pidtpc::TPCExpSignalDiffEl, pidtpc::TPCExpSigmaEl, pidtpc::TPCNSigmaEl); -DECLARE_SOA_TABLE(pidRespTPCMu, "AOD", "pidRespTPCMu", pidtpc::TPCExpSignalDiffMu, pidtpc::TPCExpSigmaMu, pidtpc::TPCNSigmaMu); -DECLARE_SOA_TABLE(pidRespTPCPi, "AOD", "pidRespTPCPi", pidtpc::TPCExpSignalDiffPi, pidtpc::TPCExpSigmaPi, pidtpc::TPCNSigmaPi); -DECLARE_SOA_TABLE(pidRespTPCKa, "AOD", "pidRespTPCKa", pidtpc::TPCExpSignalDiffKa, pidtpc::TPCExpSigmaKa, pidtpc::TPCNSigmaKa); -DECLARE_SOA_TABLE(pidRespTPCPr, "AOD", "pidRespTPCPr", pidtpc::TPCExpSignalDiffPr, pidtpc::TPCExpSigmaPr, pidtpc::TPCNSigmaPr); -DECLARE_SOA_TABLE(pidRespTPCDe, "AOD", "pidRespTPCDe", pidtpc::TPCExpSignalDiffDe, pidtpc::TPCExpSigmaDe, pidtpc::TPCNSigmaDe); -DECLARE_SOA_TABLE(pidRespTPCTr, "AOD", "pidRespTPCTr", pidtpc::TPCExpSignalDiffTr, pidtpc::TPCExpSigmaTr, pidtpc::TPCNSigmaTr); -DECLARE_SOA_TABLE(pidRespTPCHe, "AOD", "pidRespTPCHe", pidtpc::TPCExpSignalDiffHe, pidtpc::TPCExpSigmaHe, pidtpc::TPCNSigmaHe); -DECLARE_SOA_TABLE(pidRespTPCAl, "AOD", "pidRespTPCAl", pidtpc::TPCExpSignalDiffAl, pidtpc::TPCExpSigmaAl, pidtpc::TPCNSigmaAl); +DECLARE_SOA_TABLE(pidRespTPCEl, "AOD", "pidRespTPCEl", //! + pidtpc::TPCExpSignalDiffEl, pidtpc::TPCExpSigmaEl, pidtpc::TPCNSigmaEl); +DECLARE_SOA_TABLE(pidRespTPCMu, "AOD", "pidRespTPCMu", //! + pidtpc::TPCExpSignalDiffMu, pidtpc::TPCExpSigmaMu, pidtpc::TPCNSigmaMu); +DECLARE_SOA_TABLE(pidRespTPCPi, "AOD", "pidRespTPCPi", //! + pidtpc::TPCExpSignalDiffPi, pidtpc::TPCExpSigmaPi, pidtpc::TPCNSigmaPi); +DECLARE_SOA_TABLE(pidRespTPCKa, "AOD", "pidRespTPCKa", //! + pidtpc::TPCExpSignalDiffKa, pidtpc::TPCExpSigmaKa, pidtpc::TPCNSigmaKa); +DECLARE_SOA_TABLE(pidRespTPCPr, "AOD", "pidRespTPCPr", //! + pidtpc::TPCExpSignalDiffPr, pidtpc::TPCExpSigmaPr, pidtpc::TPCNSigmaPr); +DECLARE_SOA_TABLE(pidRespTPCDe, "AOD", "pidRespTPCDe", //! + pidtpc::TPCExpSignalDiffDe, pidtpc::TPCExpSigmaDe, pidtpc::TPCNSigmaDe); +DECLARE_SOA_TABLE(pidRespTPCTr, "AOD", "pidRespTPCTr", //! + pidtpc::TPCExpSignalDiffTr, pidtpc::TPCExpSigmaTr, pidtpc::TPCNSigmaTr); +DECLARE_SOA_TABLE(pidRespTPCHe, "AOD", "pidRespTPCHe", //! + pidtpc::TPCExpSignalDiffHe, pidtpc::TPCExpSigmaHe, pidtpc::TPCNSigmaHe); +DECLARE_SOA_TABLE(pidRespTPCAl, "AOD", "pidRespTPCAl", //! + pidtpc::TPCExpSignalDiffAl, pidtpc::TPCExpSigmaAl, pidtpc::TPCNSigmaAl); // Tiny size tables -DECLARE_SOA_TABLE(pidRespTPCTEl, "AOD", "pidRespTPCTEl", pidtpc_tiny::TPCNSigmaStoreEl, pidtpc_tiny::TPCNSigmaEl); -DECLARE_SOA_TABLE(pidRespTPCTMu, "AOD", "pidRespTPCTMu", pidtpc_tiny::TPCNSigmaStoreMu, pidtpc_tiny::TPCNSigmaMu); -DECLARE_SOA_TABLE(pidRespTPCTPi, "AOD", "pidRespTPCTPi", pidtpc_tiny::TPCNSigmaStorePi, pidtpc_tiny::TPCNSigmaPi); -DECLARE_SOA_TABLE(pidRespTPCTKa, "AOD", "pidRespTPCTKa", pidtpc_tiny::TPCNSigmaStoreKa, pidtpc_tiny::TPCNSigmaKa); -DECLARE_SOA_TABLE(pidRespTPCTPr, "AOD", "pidRespTPCTPr", pidtpc_tiny::TPCNSigmaStorePr, pidtpc_tiny::TPCNSigmaPr); -DECLARE_SOA_TABLE(pidRespTPCTDe, "AOD", "pidRespTPCTDe", pidtpc_tiny::TPCNSigmaStoreDe, pidtpc_tiny::TPCNSigmaDe); -DECLARE_SOA_TABLE(pidRespTPCTTr, "AOD", "pidRespTPCTTr", pidtpc_tiny::TPCNSigmaStoreTr, pidtpc_tiny::TPCNSigmaTr); -DECLARE_SOA_TABLE(pidRespTPCTHe, "AOD", "pidRespTPCTHe", pidtpc_tiny::TPCNSigmaStoreHe, pidtpc_tiny::TPCNSigmaHe); -DECLARE_SOA_TABLE(pidRespTPCTAl, "AOD", "pidRespTPCTAl", pidtpc_tiny::TPCNSigmaStoreAl, pidtpc_tiny::TPCNSigmaAl); +DECLARE_SOA_TABLE(pidRespTPCTEl, "AOD", "pidRespTPCTEl", //! + pidtpc_tiny::TPCNSigmaStoreEl, pidtpc_tiny::TPCNSigmaEl); +DECLARE_SOA_TABLE(pidRespTPCTMu, "AOD", "pidRespTPCTMu", //! + pidtpc_tiny::TPCNSigmaStoreMu, pidtpc_tiny::TPCNSigmaMu); +DECLARE_SOA_TABLE(pidRespTPCTPi, "AOD", "pidRespTPCTPi", //! + pidtpc_tiny::TPCNSigmaStorePi, pidtpc_tiny::TPCNSigmaPi); +DECLARE_SOA_TABLE(pidRespTPCTKa, "AOD", "pidRespTPCTKa", //! + pidtpc_tiny::TPCNSigmaStoreKa, pidtpc_tiny::TPCNSigmaKa); +DECLARE_SOA_TABLE(pidRespTPCTPr, "AOD", "pidRespTPCTPr", //! + pidtpc_tiny::TPCNSigmaStorePr, pidtpc_tiny::TPCNSigmaPr); +DECLARE_SOA_TABLE(pidRespTPCTDe, "AOD", "pidRespTPCTDe", //! + pidtpc_tiny::TPCNSigmaStoreDe, pidtpc_tiny::TPCNSigmaDe); +DECLARE_SOA_TABLE(pidRespTPCTTr, "AOD", "pidRespTPCTTr", //! + pidtpc_tiny::TPCNSigmaStoreTr, pidtpc_tiny::TPCNSigmaTr); +DECLARE_SOA_TABLE(pidRespTPCTHe, "AOD", "pidRespTPCTHe", //! + pidtpc_tiny::TPCNSigmaStoreHe, pidtpc_tiny::TPCNSigmaHe); +DECLARE_SOA_TABLE(pidRespTPCTAl, "AOD", "pidRespTPCTAl", //! + pidtpc_tiny::TPCNSigmaStoreAl, pidtpc_tiny::TPCNSigmaAl); #undef DEFINE_UNWRAP_NSIGMA_COLUMN diff --git a/Analysis/DataModel/include/AnalysisDataModel/ReducedInfoTables.h b/Analysis/DataModel/include/AnalysisDataModel/ReducedInfoTables.h index 1ce0c10c9a860..9494add28d682 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/ReducedInfoTables.h +++ b/Analysis/DataModel/include/AnalysisDataModel/ReducedInfoTables.h @@ -30,7 +30,8 @@ namespace dqppfilter DECLARE_SOA_COLUMN(EventFilter, eventFilter, uint64_t); } // Table to be used for storing event-level decisions (DQ high level triggers) -DECLARE_SOA_TABLE(DQEventFilter, "AOD", "EVENTFILTER", dqppfilter::EventFilter); +DECLARE_SOA_TABLE(DQEventFilter, "AOD", "EVENTFILTER", //! + dqppfilter::EventFilter); namespace reducedevent { @@ -41,14 +42,15 @@ DECLARE_SOA_COLUMN(TriggerAlias, triggerAlias, uint32_t); } // namespace reducedevent -DECLARE_SOA_TABLE(ReducedEvents, "AOD", "REDUCEDEVENT", o2::soa::Index<>, +DECLARE_SOA_TABLE(ReducedEvents, "AOD", "REDUCEDEVENT", //! + o2::soa::Index<>, reducedevent::Tag, bc::RunNumber, collision::PosX, collision::PosY, collision::PosZ, collision::NumContrib); -DECLARE_SOA_TABLE(ReducedEventsExtended, "AOD", "REEXTENDED", +DECLARE_SOA_TABLE(ReducedEventsExtended, "AOD", "REEXTENDED", //! bc::GlobalBC, bc::TriggerMask, timestamp::Timestamp, reducedevent::TriggerAlias, cent::CentV0M); -DECLARE_SOA_TABLE(ReducedEventsVtxCov, "AOD", "REVTXCOV", +DECLARE_SOA_TABLE(ReducedEventsVtxCov, "AOD", "REVTXCOV", //! collision::CovXX, collision::CovXY, collision::CovXZ, collision::CovYY, collision::CovYZ, collision::CovZZ, collision::Chi2); @@ -59,26 +61,30 @@ using ReducedEventVtxCov = ReducedEventsVtxCov::iterator; namespace reducedtrack { // basic track information -DECLARE_SOA_INDEX_COLUMN(ReducedEvent, reducedevent); -DECLARE_SOA_COLUMN(Idx, idx, uint16_t); +DECLARE_SOA_INDEX_COLUMN(ReducedEvent, reducedevent); //! +DECLARE_SOA_COLUMN(Idx, idx, uint16_t); //! // ---- flags reserved for storing various information during filtering -DECLARE_SOA_COLUMN(FilteringFlags, filteringFlags, uint64_t); +DECLARE_SOA_COLUMN(FilteringFlags, filteringFlags, uint64_t); //! // ----------------------------------------------------- -DECLARE_SOA_COLUMN(Pt, pt, float); -DECLARE_SOA_COLUMN(Eta, eta, float); -DECLARE_SOA_COLUMN(Phi, phi, float); -DECLARE_SOA_COLUMN(Sign, sign, int); -DECLARE_SOA_COLUMN(DcaXY, dcaXY, float); -DECLARE_SOA_COLUMN(DcaZ, dcaZ, float); -DECLARE_SOA_DYNAMIC_COLUMN(Px, px, [](float pt, float phi) -> float { return pt * std::cos(phi); }); -DECLARE_SOA_DYNAMIC_COLUMN(Py, py, [](float pt, float phi) -> float { return pt * std::sin(phi); }); -DECLARE_SOA_DYNAMIC_COLUMN(Pz, pz, [](float pt, float eta) -> float { return pt * std::sinh(eta); }); -DECLARE_SOA_DYNAMIC_COLUMN(Pmom, pmom, [](float pt, float eta) -> float { return pt * std::cosh(eta); }); +DECLARE_SOA_COLUMN(Pt, pt, float); //! +DECLARE_SOA_COLUMN(Eta, eta, float); //! +DECLARE_SOA_COLUMN(Phi, phi, float); //! +DECLARE_SOA_COLUMN(Sign, sign, int); //! +DECLARE_SOA_COLUMN(DcaXY, dcaXY, float); //! +DECLARE_SOA_COLUMN(DcaZ, dcaZ, float); //! +DECLARE_SOA_DYNAMIC_COLUMN(Px, px, //! + [](float pt, float phi) -> float { return pt * std::cos(phi); }); +DECLARE_SOA_DYNAMIC_COLUMN(Py, py, //! + [](float pt, float phi) -> float { return pt * std::sin(phi); }); +DECLARE_SOA_DYNAMIC_COLUMN(Pz, pz, //! + [](float pt, float eta) -> float { return pt * std::sinh(eta); }); +DECLARE_SOA_DYNAMIC_COLUMN(Pmom, pmom, //! + [](float pt, float eta) -> float { return pt * std::cosh(eta); }); } //namespace reducedtrack // basic track information -DECLARE_SOA_TABLE(ReducedTracks, "AOD", "REDUCEDTRACK", +DECLARE_SOA_TABLE(ReducedTracks, "AOD", "REDUCEDTRACK", //! o2::soa::Index<>, reducedtrack::ReducedEventId, reducedtrack::Idx, reducedtrack::FilteringFlags, reducedtrack::Pt, reducedtrack::Eta, reducedtrack::Phi, reducedtrack::Sign, reducedtrack::Px, @@ -87,8 +93,8 @@ DECLARE_SOA_TABLE(ReducedTracks, "AOD", "REDUCEDTRACK", reducedtrack::Pmom); // barrel track information -DECLARE_SOA_TABLE(ReducedTracksBarrel, "AOD", "RTBARREL", - track::TPCInnerParam, track::Flags, // tracking status flags +DECLARE_SOA_TABLE(ReducedTracksBarrel, "AOD", "RTBARREL", //! + track::TPCInnerParam, track::Flags, // tracking status flags track::ITSClusterMap, track::ITSChi2NCl, track::TPCNClsFindable, track::TPCNClsFindableMinusFound, track::TPCNClsFindableMinusCrossedRows, track::TPCNClsShared, track::TPCChi2NCl, @@ -97,12 +103,12 @@ DECLARE_SOA_TABLE(ReducedTracksBarrel, "AOD", "RTBARREL", track::TPCNClsCrossedRows); // barrel covariance matrix TODO: add all the elements required for secondary vertexing -DECLARE_SOA_TABLE(ReducedTracksBarrelCov, "AOD", "RTBARRELCOV", +DECLARE_SOA_TABLE(ReducedTracksBarrelCov, "AOD", "RTBARRELCOV", //! track::CYY, track::CZZ, track::CSnpSnp, track::CTglTgl, track::C1Pt21Pt2); // barrel PID information -DECLARE_SOA_TABLE(ReducedTracksBarrelPID, "AOD", "RTBARRELPID", +DECLARE_SOA_TABLE(ReducedTracksBarrelPID, "AOD", "RTBARRELPID", //! track::TPCSignal, pidtpc::TPCNSigmaEl, pidtpc::TPCNSigmaMu, pidtpc::TPCNSigmaPi, pidtpc::TPCNSigmaKa, pidtpc::TPCNSigmaPr, @@ -114,21 +120,25 @@ DECLARE_SOA_TABLE(ReducedTracksBarrelPID, "AOD", "RTBARRELPID", // muon quantities namespace reducedmuon { -DECLARE_SOA_INDEX_COLUMN(ReducedEvent, reducedevent); -DECLARE_SOA_COLUMN(FilteringFlags, filteringFlags, uint8_t); -// the (pt,eta,phi,sign) will be computed in the skimming task -DECLARE_SOA_COLUMN(Pt, pt, float); -DECLARE_SOA_COLUMN(Eta, eta, float); -DECLARE_SOA_COLUMN(Phi, phi, float); -DECLARE_SOA_COLUMN(Sign, sign, int); -DECLARE_SOA_DYNAMIC_COLUMN(Px, px, [](float pt, float phi) -> float { return pt * std::cos(phi); }); -DECLARE_SOA_DYNAMIC_COLUMN(Py, py, [](float pt, float phi) -> float { return pt * std::sin(phi); }); -DECLARE_SOA_DYNAMIC_COLUMN(Pz, pz, [](float pt, float eta) -> float { return pt * std::sinh(eta); }); -DECLARE_SOA_DYNAMIC_COLUMN(Pmom, pmom, [](float pt, float eta) -> float { return pt * std::cosh(eta); }); +DECLARE_SOA_INDEX_COLUMN(ReducedEvent, reducedevent); //! +DECLARE_SOA_COLUMN(FilteringFlags, filteringFlags, uint8_t); //! +// the (pt,eta,phi,sign) will be computed in the skimming task //! +DECLARE_SOA_COLUMN(Pt, pt, float); //! +DECLARE_SOA_COLUMN(Eta, eta, float); //! +DECLARE_SOA_COLUMN(Phi, phi, float); //! +DECLARE_SOA_COLUMN(Sign, sign, int); //! +DECLARE_SOA_DYNAMIC_COLUMN(Px, px, //! + [](float pt, float phi) -> float { return pt * std::cos(phi); }); +DECLARE_SOA_DYNAMIC_COLUMN(Py, py, //! + [](float pt, float phi) -> float { return pt * std::sin(phi); }); +DECLARE_SOA_DYNAMIC_COLUMN(Pz, pz, //! + [](float pt, float eta) -> float { return pt * std::sinh(eta); }); +DECLARE_SOA_DYNAMIC_COLUMN(Pmom, pmom, //! + [](float pt, float eta) -> float { return pt * std::cosh(eta); }); } // namespace reducedmuon // Muon track kinematics -DECLARE_SOA_TABLE(ReducedMuons, "AOD", "RTMUON", +DECLARE_SOA_TABLE(ReducedMuons, "AOD", "RTMUON", //! o2::soa::Index<>, reducedmuon::ReducedEventId, reducedmuon::FilteringFlags, reducedmuon::Pt, reducedmuon::Eta, reducedmuon::Phi, reducedmuon::Sign, reducedmuon::Px, @@ -137,12 +147,12 @@ DECLARE_SOA_TABLE(ReducedMuons, "AOD", "RTMUON", reducedmuon::Pmom); // Muon track quality details -DECLARE_SOA_TABLE(ReducedMuonsExtra, "AOD", "RTMUONEXTRA", +DECLARE_SOA_TABLE(ReducedMuonsExtra, "AOD", "RTMUONEXTRA", //! muon::InverseBendingMomentum, muon::ThetaX, muon::ThetaY, muon::ZMu, muon::BendingCoor, muon::NonBendingCoor, muon::Chi2, muon::Chi2MatchTrigger); // TODO: tables to be used once new AO2Ds are created -/*DECLARE_SOA_TABLE(ReducedMuonsExtra, "AOD", "RTMUONEXTRA", +/*DECLARE_SOA_TABLE(ReducedMuonsExtra, "AOD", "RTMUONEXTRA", //! fwdtrack::NClusters, fwdtrack::PDca, fwdtrack::RAtAbsorberEnd, fwdtrack::Chi2, fwdtrack::Chi2MatchMCHMID, fwdtrack::Chi2MatchMCHMFT, fwdtrack::MatchScoreMCHMFT, fwdtrack::MatchMFTTrackID, fwdtrack::MatchMCHTrackID); @@ -155,20 +165,24 @@ DECLARE_SOA_TABLE(ReducedMuonsCov, "AOD", "RTMUONCOV", // pair information namespace reducedpair { -DECLARE_SOA_INDEX_COLUMN(ReducedEvent, reducedevent); -DECLARE_SOA_COLUMN(Mass, mass, float); -DECLARE_SOA_COLUMN(Pt, pt, float); -DECLARE_SOA_COLUMN(Eta, eta, float); -DECLARE_SOA_COLUMN(Phi, phi, float); -DECLARE_SOA_COLUMN(Sign, sign, int); -DECLARE_SOA_COLUMN(FilterMap, filterMap, uint16_t); -DECLARE_SOA_DYNAMIC_COLUMN(Px, px, [](float pt, float phi) -> float { return pt * std::cos(phi); }); -DECLARE_SOA_DYNAMIC_COLUMN(Py, py, [](float pt, float phi) -> float { return pt * std::sin(phi); }); -DECLARE_SOA_DYNAMIC_COLUMN(Pz, pz, [](float pt, float eta) -> float { return pt * std::sinh(eta); }); -DECLARE_SOA_DYNAMIC_COLUMN(Pmom, pmom, [](float pt, float eta) -> float { return pt * std::cosh(eta); }); +DECLARE_SOA_INDEX_COLUMN(ReducedEvent, reducedevent); //! +DECLARE_SOA_COLUMN(Mass, mass, float); //! +DECLARE_SOA_COLUMN(Pt, pt, float); //! +DECLARE_SOA_COLUMN(Eta, eta, float); //! +DECLARE_SOA_COLUMN(Phi, phi, float); //! +DECLARE_SOA_COLUMN(Sign, sign, int); //! +DECLARE_SOA_COLUMN(FilterMap, filterMap, uint16_t); //! +DECLARE_SOA_DYNAMIC_COLUMN(Px, px, //! + [](float pt, float phi) -> float { return pt * std::cos(phi); }); +DECLARE_SOA_DYNAMIC_COLUMN(Py, py, //! + [](float pt, float phi) -> float { return pt * std::sin(phi); }); +DECLARE_SOA_DYNAMIC_COLUMN(Pz, pz, //! + [](float pt, float eta) -> float { return pt * std::sinh(eta); }); +DECLARE_SOA_DYNAMIC_COLUMN(Pmom, pmom, //! + [](float pt, float eta) -> float { return pt * std::cosh(eta); }); } // namespace reducedpair -DECLARE_SOA_TABLE(Dileptons, "AOD", "RTDILEPTON", +DECLARE_SOA_TABLE(Dileptons, "AOD", "RTDILEPTON", //! reducedpair::ReducedEventId, reducedpair::Mass, reducedpair::Pt, reducedpair::Eta, reducedpair::Phi, reducedpair::Sign, reducedpair::FilterMap, diff --git a/Analysis/DataModel/include/AnalysisDataModel/StrangenessTables.h b/Analysis/DataModel/include/AnalysisDataModel/StrangenessTables.h index a41852bbc7589..d71b1c3e33256 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/StrangenessTables.h +++ b/Analysis/DataModel/include/AnalysisDataModel/StrangenessTables.h @@ -19,70 +19,87 @@ namespace o2::aod namespace v0data { //Needed to have shorter table that does not rely on existing one (filtering!) -DECLARE_SOA_INDEX_COLUMN_FULL(PosTrack, posTrack, int, Tracks, "_Pos"); -DECLARE_SOA_INDEX_COLUMN_FULL(NegTrack, negTrack, int, Tracks, "_Neg"); -DECLARE_SOA_INDEX_COLUMN(Collision, collision); +DECLARE_SOA_INDEX_COLUMN_FULL(PosTrack, posTrack, int, Tracks, "_Pos"); //! +DECLARE_SOA_INDEX_COLUMN_FULL(NegTrack, negTrack, int, Tracks, "_Neg"); //! +DECLARE_SOA_INDEX_COLUMN(Collision, collision); //! //General V0 properties: position, momentum -DECLARE_SOA_COLUMN(PosX, posX, float); -DECLARE_SOA_COLUMN(NegX, negX, float); -DECLARE_SOA_COLUMN(PxPos, pxpos, float); -DECLARE_SOA_COLUMN(PyPos, pypos, float); -DECLARE_SOA_COLUMN(PzPos, pzpos, float); -DECLARE_SOA_COLUMN(PxNeg, pxneg, float); -DECLARE_SOA_COLUMN(PyNeg, pyneg, float); -DECLARE_SOA_COLUMN(PzNeg, pzneg, float); -DECLARE_SOA_COLUMN(X, x, float); -DECLARE_SOA_COLUMN(Y, y, float); -DECLARE_SOA_COLUMN(Z, z, float); +DECLARE_SOA_COLUMN(PosX, posX, float); //! +DECLARE_SOA_COLUMN(NegX, negX, float); //! +DECLARE_SOA_COLUMN(PxPos, pxpos, float); //! +DECLARE_SOA_COLUMN(PyPos, pypos, float); //! +DECLARE_SOA_COLUMN(PzPos, pzpos, float); //! +DECLARE_SOA_COLUMN(PxNeg, pxneg, float); //! +DECLARE_SOA_COLUMN(PyNeg, pyneg, float); //! +DECLARE_SOA_COLUMN(PzNeg, pzneg, float); //! +DECLARE_SOA_COLUMN(X, x, float); //! +DECLARE_SOA_COLUMN(Y, y, float); //! +DECLARE_SOA_COLUMN(Z, z, float); //! //Saved from finding: DCAs -DECLARE_SOA_COLUMN(DCAV0Daughters, dcaV0daughters, float); -DECLARE_SOA_COLUMN(DCAPosToPV, dcapostopv, float); -DECLARE_SOA_COLUMN(DCANegToPV, dcanegtopv, float); +DECLARE_SOA_COLUMN(DCAV0Daughters, dcaV0daughters, float); //! +DECLARE_SOA_COLUMN(DCAPosToPV, dcapostopv, float); //! +DECLARE_SOA_COLUMN(DCANegToPV, dcanegtopv, float); //! //Derived expressions //Momenta -DECLARE_SOA_DYNAMIC_COLUMN(Pt, pt, [](float pxpos, float pypos, float pxneg, float pyneg) { return RecoDecay::sqrtSumOfSquares(pxpos + pxneg, pypos + pyneg); }); +DECLARE_SOA_DYNAMIC_COLUMN(Pt, pt, //! + [](float pxpos, float pypos, float pxneg, float pyneg) -> float { return RecoDecay::sqrtSumOfSquares(pxpos + pxneg, pypos + pyneg); }); //Length quantities -DECLARE_SOA_DYNAMIC_COLUMN(V0Radius, v0radius, [](float x, float y) { return RecoDecay::sqrtSumOfSquares(x, y); }); +DECLARE_SOA_DYNAMIC_COLUMN(V0Radius, v0radius, //! + [](float x, float y) -> float { return RecoDecay::sqrtSumOfSquares(x, y); }); //CosPA -DECLARE_SOA_DYNAMIC_COLUMN(V0CosPA, v0cosPA, [](float X, float Y, float Z, float Px, float Py, float Pz, float pvX, float pvY, float pvZ) { return RecoDecay::CPA(array{pvX, pvY, pvZ}, array{X, Y, Z}, array{Px, Py, Pz}); }); -DECLARE_SOA_DYNAMIC_COLUMN(DCAV0ToPV, dcav0topv, [](float X, float Y, float Z, float Px, float Py, float Pz, float pvX, float pvY, float pvZ) { return std::sqrt((std::pow((pvY - Y) * Pz - (pvZ - Z) * Py, 2) + std::pow((pvX - X) * Pz - (pvZ - Z) * Px, 2) + std::pow((pvX - X) * Py - (pvY - Y) * Px, 2)) / (Px * Px + Py * Py + Pz * Pz)); }); +DECLARE_SOA_DYNAMIC_COLUMN(V0CosPA, v0cosPA, //! + [](float X, float Y, float Z, float Px, float Py, float Pz, float pvX, float pvY, float pvZ) -> float { return RecoDecay::CPA(array{pvX, pvY, pvZ}, array{X, Y, Z}, array{Px, Py, Pz}); }); +DECLARE_SOA_DYNAMIC_COLUMN(DCAV0ToPV, dcav0topv, //! + [](float X, float Y, float Z, float Px, float Py, float Pz, float pvX, float pvY, float pvZ) -> float { return std::sqrt((std::pow((pvY - Y) * Pz - (pvZ - Z) * Py, 2) + std::pow((pvX - X) * Pz - (pvZ - Z) * Px, 2) + std::pow((pvX - X) * Py - (pvY - Y) * Px, 2)) / (Px * Px + Py * Py + Pz * Pz)); }); //Armenteros-Podolanski variables -DECLARE_SOA_DYNAMIC_COLUMN(Alpha, alpha, [](float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) { - float momTot = RecoDecay::P(pxpos + pxneg, pypos + pyneg, pzpos + pzneg); - float lQlNeg = RecoDecay::dotProd(array{pxneg, pyneg, pzneg}, array{pxpos + pxneg, pypos + pyneg, pzpos + pzneg}) / momTot; - float lQlPos = RecoDecay::dotProd(array{pxpos, pypos, pzpos}, array{pxpos + pxneg, pypos + pyneg, pzpos + pzneg}) / momTot; - return (lQlPos - lQlNeg) / (lQlPos + lQlNeg); //alphav0 -}); - -DECLARE_SOA_DYNAMIC_COLUMN(QtArm, qtarm, [](float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) { - float momTot = RecoDecay::P2(pxpos + pxneg, pypos + pyneg, pzpos + pzneg); - float dp = RecoDecay::dotProd(array{pxneg, pyneg, pzneg}, array{pxpos + pxneg, pypos + pyneg, pzpos + pzneg}); - return std::sqrt(RecoDecay::P2(pxneg, pyneg, pzneg) - dp * dp / momTot); //qtarm -}); +DECLARE_SOA_DYNAMIC_COLUMN(Alpha, alpha, //! + [](float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) { + float momTot = RecoDecay::P(pxpos + pxneg, pypos + pyneg, pzpos + pzneg); + float lQlNeg = RecoDecay::dotProd(array{pxneg, pyneg, pzneg}, array{pxpos + pxneg, pypos + pyneg, pzpos + pzneg}) / momTot; + float lQlPos = RecoDecay::dotProd(array{pxpos, pypos, pzpos}, array{pxpos + pxneg, pypos + pyneg, pzpos + pzneg}) / momTot; + return (lQlPos - lQlNeg) / (lQlPos + lQlNeg); //alphav0 + }); + +DECLARE_SOA_DYNAMIC_COLUMN(QtArm, qtarm, //! + [](float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) { + float momTot = RecoDecay::P2(pxpos + pxneg, pypos + pyneg, pzpos + pzneg); + float dp = RecoDecay::dotProd(array{pxneg, pyneg, pzneg}, array{pxpos + pxneg, pypos + pyneg, pzpos + pzneg}); + return std::sqrt(RecoDecay::P2(pxneg, pyneg, pzneg) - dp * dp / momTot); //qtarm + }); //Calculated on the fly with mass assumption + dynamic tables -DECLARE_SOA_DYNAMIC_COLUMN(MLambda, mLambda, [](float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) { return RecoDecay::M(array{array{pxpos, pypos, pzpos}, array{pxneg, pyneg, pzneg}}, array{RecoDecay::getMassPDG(kProton), RecoDecay::getMassPDG(kPiPlus)}); }); -DECLARE_SOA_DYNAMIC_COLUMN(MAntiLambda, mAntiLambda, [](float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) { return RecoDecay::M(array{array{pxpos, pypos, pzpos}, array{pxneg, pyneg, pzneg}}, array{RecoDecay::getMassPDG(kPiPlus), RecoDecay::getMassPDG(kProton)}); }); -DECLARE_SOA_DYNAMIC_COLUMN(MK0Short, mK0Short, [](float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) { return RecoDecay::M(array{array{pxpos, pypos, pzpos}, array{pxneg, pyneg, pzneg}}, array{RecoDecay::getMassPDG(kPiPlus), RecoDecay::getMassPDG(kPiPlus)}); }); -DECLARE_SOA_DYNAMIC_COLUMN(MGamma, mGamma, [](float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) { return RecoDecay::M(array{array{pxpos, pypos, pzpos}, array{pxneg, pyneg, pzneg}}, array{RecoDecay::getMassPDG(kElectron), RecoDecay::getMassPDG(kElectron)}); }); - -DECLARE_SOA_DYNAMIC_COLUMN(YK0Short, yK0Short, [](float Px, float Py, float Pz) { return RecoDecay::Y(array{Px, Py, Pz}, RecoDecay::getMassPDG(kK0)); }); -DECLARE_SOA_DYNAMIC_COLUMN(YLambda, yLambda, [](float Px, float Py, float Pz) { return RecoDecay::Y(array{Px, Py, Pz}, RecoDecay::getMassPDG(kLambda0)); }); -DECLARE_SOA_DYNAMIC_COLUMN(Eta, eta, [](float Px, float Py, float Pz) { return RecoDecay::Eta(array{Px, Py, Pz}); }); -DECLARE_SOA_DYNAMIC_COLUMN(Phi, phi, [](float Px, float Py) { return RecoDecay::Phi(Px, Py); }); - -DECLARE_SOA_EXPRESSION_COLUMN(Px, px, float, 1.f * aod::v0data::pxpos + 1.f * aod::v0data::pxneg); -DECLARE_SOA_EXPRESSION_COLUMN(Py, py, float, 1.f * aod::v0data::pypos + 1.f * aod::v0data::pyneg); -DECLARE_SOA_EXPRESSION_COLUMN(Pz, pz, float, 1.f * aod::v0data::pzpos + 1.f * aod::v0data::pzneg); +DECLARE_SOA_DYNAMIC_COLUMN(MLambda, mLambda, //! + [](float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) -> float { return RecoDecay::M(array{array{pxpos, pypos, pzpos}, array{pxneg, pyneg, pzneg}}, array{RecoDecay::getMassPDG(kProton), RecoDecay::getMassPDG(kPiPlus)}); }); +DECLARE_SOA_DYNAMIC_COLUMN(MAntiLambda, mAntiLambda, //! + [](float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) -> float { return RecoDecay::M(array{array{pxpos, pypos, pzpos}, array{pxneg, pyneg, pzneg}}, array{RecoDecay::getMassPDG(kPiPlus), RecoDecay::getMassPDG(kProton)}); }); +DECLARE_SOA_DYNAMIC_COLUMN(MK0Short, mK0Short, //! + [](float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) -> float { return RecoDecay::M(array{array{pxpos, pypos, pzpos}, array{pxneg, pyneg, pzneg}}, array{RecoDecay::getMassPDG(kPiPlus), RecoDecay::getMassPDG(kPiPlus)}); }); +DECLARE_SOA_DYNAMIC_COLUMN(MGamma, mGamma, //! + [](float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) -> float { return RecoDecay::M(array{array{pxpos, pypos, pzpos}, array{pxneg, pyneg, pzneg}}, array{RecoDecay::getMassPDG(kElectron), RecoDecay::getMassPDG(kElectron)}); }); + +DECLARE_SOA_DYNAMIC_COLUMN(YK0Short, yK0Short, //! + [](float Px, float Py, float Pz) -> float { return RecoDecay::Y(array{Px, Py, Pz}, RecoDecay::getMassPDG(kK0)); }); +DECLARE_SOA_DYNAMIC_COLUMN(YLambda, yLambda, //! + [](float Px, float Py, float Pz) -> float { return RecoDecay::Y(array{Px, Py, Pz}, RecoDecay::getMassPDG(kLambda0)); }); +DECLARE_SOA_DYNAMIC_COLUMN(Eta, eta, //! + [](float Px, float Py, float Pz) -> float { return RecoDecay::Eta(array{Px, Py, Pz}); }); +DECLARE_SOA_DYNAMIC_COLUMN(Phi, phi, //! + [](float Px, float Py) -> float { return RecoDecay::Phi(Px, Py); }); + +DECLARE_SOA_EXPRESSION_COLUMN(Px, px, //! + float, 1.f * aod::v0data::pxpos + 1.f * aod::v0data::pxneg); +DECLARE_SOA_EXPRESSION_COLUMN(Py, py, //! + float, 1.f * aod::v0data::pypos + 1.f * aod::v0data::pyneg); +DECLARE_SOA_EXPRESSION_COLUMN(Pz, pz, //! + float, 1.f * aod::v0data::pzpos + 1.f * aod::v0data::pzneg); } // namespace v0data -DECLARE_SOA_TABLE_FULL(StoredV0Datas, "V0Datas", "AOD", "V0DATA", +DECLARE_SOA_TABLE_FULL(StoredV0Datas, "V0Datas", "AOD", "V0DATA", //! o2::soa::Index<>, v0data::PosTrackId, v0data::NegTrackId, v0data::CollisionId, v0data::PosX, v0data::NegX, v0data::X, v0data::Y, v0data::Z, @@ -111,78 +128,97 @@ DECLARE_SOA_TABLE_FULL(StoredV0Datas, "V0Datas", "AOD", "V0DATA", v0data::Phi); // extended table with expression columns that can be used as arguments of dynamic columns -DECLARE_SOA_EXTENDED_TABLE_USER(V0Datas, StoredV0Datas, "V0DATAEXT", +DECLARE_SOA_EXTENDED_TABLE_USER(V0Datas, StoredV0Datas, "V0DATAEXT", //! v0data::Px, v0data::Py, v0data::Pz); // the table name has here to be the one with EXT which is not nice and under study using V0Data = V0Datas::iterator; namespace cascdata { //Necessary for full filtering functionality -DECLARE_SOA_INDEX_COLUMN(V0Data, v0Data); -DECLARE_SOA_INDEX_COLUMN_FULL(Bachelor, bachelor, int, Tracks, ""); -DECLARE_SOA_INDEX_COLUMN(Collision, collision); +DECLARE_SOA_INDEX_COLUMN(V0Data, v0Data); //! +DECLARE_SOA_INDEX_COLUMN_FULL(Bachelor, bachelor, int, Tracks, ""); //! +DECLARE_SOA_INDEX_COLUMN(Collision, collision); //! //General V0 properties: position, momentum -DECLARE_SOA_COLUMN(Sign, sign, int); -DECLARE_SOA_COLUMN(PxPos, pxpos, float); -DECLARE_SOA_COLUMN(PyPos, pypos, float); -DECLARE_SOA_COLUMN(PzPos, pzpos, float); -DECLARE_SOA_COLUMN(PxNeg, pxneg, float); -DECLARE_SOA_COLUMN(PyNeg, pyneg, float); -DECLARE_SOA_COLUMN(PzNeg, pzneg, float); -DECLARE_SOA_COLUMN(PxBach, pxbach, float); -DECLARE_SOA_COLUMN(PyBach, pybach, float); -DECLARE_SOA_COLUMN(PzBach, pzbach, float); -DECLARE_SOA_COLUMN(X, x, float); -DECLARE_SOA_COLUMN(Y, y, float); -DECLARE_SOA_COLUMN(Z, z, float); -DECLARE_SOA_COLUMN(Xlambda, xlambda, float); -DECLARE_SOA_COLUMN(Ylambda, ylambda, float); -DECLARE_SOA_COLUMN(Zlambda, zlambda, float); +DECLARE_SOA_COLUMN(Sign, sign, int); //! +DECLARE_SOA_COLUMN(PxPos, pxpos, float); //! +DECLARE_SOA_COLUMN(PyPos, pypos, float); //! +DECLARE_SOA_COLUMN(PzPos, pzpos, float); //! +DECLARE_SOA_COLUMN(PxNeg, pxneg, float); //! +DECLARE_SOA_COLUMN(PyNeg, pyneg, float); //! +DECLARE_SOA_COLUMN(PzNeg, pzneg, float); //! +DECLARE_SOA_COLUMN(PxBach, pxbach, float); //! +DECLARE_SOA_COLUMN(PyBach, pybach, float); //! +DECLARE_SOA_COLUMN(PzBach, pzbach, float); //! +DECLARE_SOA_COLUMN(X, x, float); //! +DECLARE_SOA_COLUMN(Y, y, float); //! +DECLARE_SOA_COLUMN(Z, z, float); //! +DECLARE_SOA_COLUMN(Xlambda, xlambda, float); //! +DECLARE_SOA_COLUMN(Ylambda, ylambda, float); //! +DECLARE_SOA_COLUMN(Zlambda, zlambda, float); //! //Saved from finding: DCAs -DECLARE_SOA_COLUMN(DCAV0Daughters, dcaV0daughters, float); -DECLARE_SOA_COLUMN(DCACascDaughters, dcacascdaughters, float); -DECLARE_SOA_COLUMN(DCAPosToPV, dcapostopv, float); -DECLARE_SOA_COLUMN(DCANegToPV, dcanegtopv, float); -DECLARE_SOA_COLUMN(DCABachToPV, dcabachtopv, float); +DECLARE_SOA_COLUMN(DCAV0Daughters, dcaV0daughters, float); //! +DECLARE_SOA_COLUMN(DCACascDaughters, dcacascdaughters, float); //! +DECLARE_SOA_COLUMN(DCAPosToPV, dcapostopv, float); //! +DECLARE_SOA_COLUMN(DCANegToPV, dcanegtopv, float); //! +DECLARE_SOA_COLUMN(DCABachToPV, dcabachtopv, float); //! //Derived expressions //Momenta -DECLARE_SOA_DYNAMIC_COLUMN(Pt, pt, [](float Px, float Py) { return RecoDecay::sqrtSumOfSquares(Px, Py); }); +DECLARE_SOA_DYNAMIC_COLUMN(Pt, pt, //! + [](float Px, float Py) -> float { return RecoDecay::sqrtSumOfSquares(Px, Py); }); //Length quantities -DECLARE_SOA_DYNAMIC_COLUMN(V0Radius, v0radius, [](float xlambda, float ylambda) { return RecoDecay::sqrtSumOfSquares(xlambda, ylambda); }); -DECLARE_SOA_DYNAMIC_COLUMN(CascRadius, cascradius, [](float x, float y) { return RecoDecay::sqrtSumOfSquares(x, y); }); +DECLARE_SOA_DYNAMIC_COLUMN(V0Radius, v0radius, //! + [](float xlambda, float ylambda) -> float { return RecoDecay::sqrtSumOfSquares(xlambda, ylambda); }); +DECLARE_SOA_DYNAMIC_COLUMN(CascRadius, cascradius, //! + [](float x, float y) -> float { return RecoDecay::sqrtSumOfSquares(x, y); }); //CosPAs -DECLARE_SOA_DYNAMIC_COLUMN(V0CosPA, v0cosPA, [](float Xlambda, float Ylambda, float Zlambda, float PxLambda, float PyLambda, float PzLambda, float pvX, float pvY, float pvZ) { return RecoDecay::CPA(array{pvX, pvY, pvZ}, array{Xlambda, Ylambda, Zlambda}, array{PxLambda, PyLambda, PzLambda}); }); -DECLARE_SOA_DYNAMIC_COLUMN(CascCosPA, casccosPA, [](float X, float Y, float Z, float Px, float Py, float Pz, float pvX, float pvY, float pvZ) { return RecoDecay::CPA(array{pvX, pvY, pvZ}, array{X, Y, Z}, array{Px, Py, Pz}); }); -DECLARE_SOA_DYNAMIC_COLUMN(DCAV0ToPV, dcav0topv, [](float X, float Y, float Z, float Px, float Py, float Pz, float pvX, float pvY, float pvZ) { return std::sqrt((std::pow((pvY - Y) * Pz - (pvZ - Z) * Py, 2) + std::pow((pvX - X) * Pz - (pvZ - Z) * Px, 2) + std::pow((pvX - X) * Py - (pvY - Y) * Px, 2)) / (Px * Px + Py * Py + Pz * Pz)); }); -DECLARE_SOA_DYNAMIC_COLUMN(DCACascToPV, dcacasctopv, [](float X, float Y, float Z, float Px, float Py, float Pz, float pvX, float pvY, float pvZ) { return std::sqrt((std::pow((pvY - Y) * Pz - (pvZ - Z) * Py, 2) + std::pow((pvX - X) * Pz - (pvZ - Z) * Px, 2) + std::pow((pvX - X) * Py - (pvY - Y) * Px, 2)) / (Px * Px + Py * Py + Pz * Pz)); }); +DECLARE_SOA_DYNAMIC_COLUMN(V0CosPA, v0cosPA, //! + [](float Xlambda, float Ylambda, float Zlambda, float PxLambda, float PyLambda, float PzLambda, float pvX, float pvY, float pvZ) -> float { return RecoDecay::CPA(array{pvX, pvY, pvZ}, array{Xlambda, Ylambda, Zlambda}, array{PxLambda, PyLambda, PzLambda}); }); +DECLARE_SOA_DYNAMIC_COLUMN(CascCosPA, casccosPA, //! + [](float X, float Y, float Z, float Px, float Py, float Pz, float pvX, float pvY, float pvZ) -> float { return RecoDecay::CPA(array{pvX, pvY, pvZ}, array{X, Y, Z}, array{Px, Py, Pz}); }); +DECLARE_SOA_DYNAMIC_COLUMN(DCAV0ToPV, dcav0topv, //! + [](float X, float Y, float Z, float Px, float Py, float Pz, float pvX, float pvY, float pvZ) -> float { return std::sqrt((std::pow((pvY - Y) * Pz - (pvZ - Z) * Py, 2) + std::pow((pvX - X) * Pz - (pvZ - Z) * Px, 2) + std::pow((pvX - X) * Py - (pvY - Y) * Px, 2)) / (Px * Px + Py * Py + Pz * Pz)); }); +DECLARE_SOA_DYNAMIC_COLUMN(DCACascToPV, dcacasctopv, //! + [](float X, float Y, float Z, float Px, float Py, float Pz, float pvX, float pvY, float pvZ) -> float { return std::sqrt((std::pow((pvY - Y) * Pz - (pvZ - Z) * Py, 2) + std::pow((pvX - X) * Pz - (pvZ - Z) * Px, 2) + std::pow((pvX - X) * Py - (pvY - Y) * Px, 2)) / (Px * Px + Py * Py + Pz * Pz)); }); //Calculated on the fly with mass assumption + dynamic tables -DECLARE_SOA_DYNAMIC_COLUMN(MLambda, mLambda, [](int charge, float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) { return RecoDecay::M(array{array{pxpos, pypos, pzpos}, array{pxneg, pyneg, pzneg}}, charge < 0 ? array{RecoDecay::getMassPDG(kProton), RecoDecay::getMassPDG(kPiPlus)} : array{RecoDecay::getMassPDG(kPiPlus), RecoDecay::getMassPDG(kProton)}); }); +DECLARE_SOA_DYNAMIC_COLUMN(MLambda, mLambda, //! + [](int charge, float pxpos, float pypos, float pzpos, float pxneg, float pyneg, float pzneg) -> float { return RecoDecay::M(array{array{pxpos, pypos, pzpos}, array{pxneg, pyneg, pzneg}}, charge < 0 ? array{RecoDecay::getMassPDG(kProton), RecoDecay::getMassPDG(kPiPlus)} : array{RecoDecay::getMassPDG(kPiPlus), RecoDecay::getMassPDG(kProton)}); }); //Calculated on the fly with mass assumption + dynamic tables -DECLARE_SOA_DYNAMIC_COLUMN(MXi, mXi, [](float pxbach, float pybach, float pzbach, float PxLambda, float PyLambda, float PzLambda) { return RecoDecay::M(array{array{pxbach, pybach, pzbach}, array{PxLambda, PyLambda, PzLambda}}, array{RecoDecay::getMassPDG(kPiPlus), RecoDecay::getMassPDG(kLambda0)}); }); -DECLARE_SOA_DYNAMIC_COLUMN(MOmega, mOmega, [](float pxbach, float pybach, float pzbach, float PxLambda, float PyLambda, float PzLambda) { return RecoDecay::M(array{array{pxbach, pybach, pzbach}, array{PxLambda, PyLambda, PzLambda}}, array{RecoDecay::getMassPDG(kKPlus), RecoDecay::getMassPDG(kLambda0)}); }); - -DECLARE_SOA_DYNAMIC_COLUMN(YXi, yXi, [](float Px, float Py, float Pz) { return RecoDecay::Y(array{Px, Py, Pz}, 1.32171); }); -DECLARE_SOA_DYNAMIC_COLUMN(YOmega, yOmega, [](float Px, float Py, float Pz) { return RecoDecay::Y(array{Px, Py, Pz}, 1.67245); }); -DECLARE_SOA_DYNAMIC_COLUMN(Eta, eta, [](float Px, float Py, float Pz) { return RecoDecay::Eta(array{Px, Py, Pz}); }); +DECLARE_SOA_DYNAMIC_COLUMN(MXi, mXi, //! + [](float pxbach, float pybach, float pzbach, float PxLambda, float PyLambda, float PzLambda) -> float { return RecoDecay::M(array{array{pxbach, pybach, pzbach}, array{PxLambda, PyLambda, PzLambda}}, array{RecoDecay::getMassPDG(kPiPlus), RecoDecay::getMassPDG(kLambda0)}); }); +DECLARE_SOA_DYNAMIC_COLUMN(MOmega, mOmega, //! + [](float pxbach, float pybach, float pzbach, float PxLambda, float PyLambda, float PzLambda) -> float { return RecoDecay::M(array{array{pxbach, pybach, pzbach}, array{PxLambda, PyLambda, PzLambda}}, array{RecoDecay::getMassPDG(kKPlus), RecoDecay::getMassPDG(kLambda0)}); }); + +DECLARE_SOA_DYNAMIC_COLUMN(YXi, yXi, //! + [](float Px, float Py, float Pz) -> float { return RecoDecay::Y(array{Px, Py, Pz}, 1.32171); }); +DECLARE_SOA_DYNAMIC_COLUMN(YOmega, yOmega, //! + [](float Px, float Py, float Pz) -> float { return RecoDecay::Y(array{Px, Py, Pz}, 1.67245); }); +DECLARE_SOA_DYNAMIC_COLUMN(Eta, eta, //! + [](float Px, float Py, float Pz) -> float { return RecoDecay::Eta(array{Px, Py, Pz}); }); } // namespace cascdata namespace cascdataext { -DECLARE_SOA_EXPRESSION_COLUMN(PxLambda, pxlambda, float, 1.f * aod::cascdata::pxpos + 1.f * aod::cascdata::pxneg); -DECLARE_SOA_EXPRESSION_COLUMN(PyLambda, pylambda, float, 1.f * aod::cascdata::pypos + 1.f * aod::cascdata::pyneg); -DECLARE_SOA_EXPRESSION_COLUMN(PzLambda, pzlambda, float, 1.f * aod::cascdata::pzpos + 1.f * aod::cascdata::pzneg); -DECLARE_SOA_EXPRESSION_COLUMN(Px, px, float, 1.f * aod::cascdata::pxpos + 1.f * aod::cascdata::pxneg + 1.f * aod::cascdata::pxbach); -DECLARE_SOA_EXPRESSION_COLUMN(Py, py, float, 1.f * aod::cascdata::pypos + 1.f * aod::cascdata::pyneg + 1.f * aod::cascdata::pybach); -DECLARE_SOA_EXPRESSION_COLUMN(Pz, pz, float, 1.f * aod::cascdata::pzpos + 1.f * aod::cascdata::pzneg + 1.f * aod::cascdata::pzbach); +DECLARE_SOA_EXPRESSION_COLUMN(PxLambda, pxlambda, //! + float, 1.f * aod::cascdata::pxpos + 1.f * aod::cascdata::pxneg); +DECLARE_SOA_EXPRESSION_COLUMN(PyLambda, pylambda, //! + float, 1.f * aod::cascdata::pypos + 1.f * aod::cascdata::pyneg); +DECLARE_SOA_EXPRESSION_COLUMN(PzLambda, pzlambda, //! + float, 1.f * aod::cascdata::pzpos + 1.f * aod::cascdata::pzneg); +DECLARE_SOA_EXPRESSION_COLUMN(Px, px, //! + float, 1.f * aod::cascdata::pxpos + 1.f * aod::cascdata::pxneg + 1.f * aod::cascdata::pxbach); +DECLARE_SOA_EXPRESSION_COLUMN(Py, py, //! + float, 1.f * aod::cascdata::pypos + 1.f * aod::cascdata::pyneg + 1.f * aod::cascdata::pybach); +DECLARE_SOA_EXPRESSION_COLUMN(Pz, pz, //! + float, 1.f * aod::cascdata::pzpos + 1.f * aod::cascdata::pzneg + 1.f * aod::cascdata::pzbach); } // namespace cascdataext -DECLARE_SOA_TABLE(CascData, "AOD", "CASCDATA", +DECLARE_SOA_TABLE(CascData, "AOD", "CASCDATA", //! o2::soa::Index<>, cascdata::V0DataId, cascdata::BachelorId, cascdata::CollisionId, cascdata::Sign, @@ -215,7 +251,7 @@ DECLARE_SOA_TABLE(CascData, "AOD", "CASCDATA", using CascDataOrigin = CascData; // extended table with expression columns that can be used as arguments of dynamic columns -DECLARE_SOA_EXTENDED_TABLE_USER(CascDataExt, CascDataOrigin, "CascDATAEXT", +DECLARE_SOA_EXTENDED_TABLE_USER(CascDataExt, CascDataOrigin, "CascDATAEXT", //! cascdataext::PxLambda, cascdataext::PyLambda, cascdataext::PzLambda, cascdataext::Px, cascdataext::Py, cascdataext::Pz); diff --git a/Analysis/DataModel/include/AnalysisDataModel/TrackSelectionTables.h b/Analysis/DataModel/include/AnalysisDataModel/TrackSelectionTables.h index 52e114013a87a..fb8362b575353 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/TrackSelectionTables.h +++ b/Analysis/DataModel/include/AnalysisDataModel/TrackSelectionTables.h @@ -18,18 +18,20 @@ namespace o2::aod namespace track { // Columns to store the DCA to the primary vertex -DECLARE_SOA_COLUMN(DcaXY, dcaXY, float); -DECLARE_SOA_COLUMN(DcaZ, dcaZ, float); +DECLARE_SOA_COLUMN(DcaXY, dcaXY, float); //! +DECLARE_SOA_COLUMN(DcaZ, dcaZ, float); //! // Columns to store track filter decisions -DECLARE_SOA_COLUMN(IsGlobalTrack, isGlobalTrack, uint8_t); -DECLARE_SOA_COLUMN(IsGlobalTrackSDD, isGlobalTrackSDD, uint8_t); +DECLARE_SOA_COLUMN(IsGlobalTrack, isGlobalTrack, uint8_t); //! +DECLARE_SOA_COLUMN(IsGlobalTrackSDD, isGlobalTrackSDD, uint8_t); //! } // namespace track -DECLARE_SOA_TABLE(TracksExtended, "AOD", "TRACKEXTENDED", track::DcaXY, +DECLARE_SOA_TABLE(TracksExtended, "AOD", "TRACKEXTENDED", //! + track::DcaXY, track::DcaZ); -DECLARE_SOA_TABLE(TrackSelection, "AOD", "TRACKSELECTION", track::IsGlobalTrack, +DECLARE_SOA_TABLE(TrackSelection, "AOD", "TRACKSELECTION", //! + track::IsGlobalTrack, track::IsGlobalTrackSDD); } // namespace o2::aod diff --git a/Framework/Core/include/Framework/AnalysisDataModel.h b/Framework/Core/include/Framework/AnalysisDataModel.h index 62d315d053d04..c6715697ab8a1 100644 --- a/Framework/Core/include/Framework/AnalysisDataModel.h +++ b/Framework/Core/include/Framework/AnalysisDataModel.h @@ -25,46 +25,52 @@ DECLARE_SOA_STORE(); namespace bc { -DECLARE_SOA_COLUMN(RunNumber, runNumber, int); -DECLARE_SOA_COLUMN(GlobalBC, globalBC, uint64_t); -DECLARE_SOA_COLUMN(TriggerMask, triggerMask, uint64_t); +DECLARE_SOA_COLUMN(RunNumber, runNumber, int); //! +DECLARE_SOA_COLUMN(GlobalBC, globalBC, uint64_t); //! Bunch crossing number +DECLARE_SOA_COLUMN(TriggerMask, triggerMask, uint64_t); //! } // namespace bc -DECLARE_SOA_TABLE(BCs, "AOD", "BC", o2::soa::Index<>, +DECLARE_SOA_TABLE(BCs, "AOD", "BC", o2::soa::Index<>, //! bc::RunNumber, bc::GlobalBC, bc::TriggerMask); using BC = BCs::iterator; namespace timestamp { -DECLARE_SOA_COLUMN(Timestamp, timestamp, uint64_t); +DECLARE_SOA_COLUMN(Timestamp, timestamp, uint64_t); //! } // namespace timestamp -DECLARE_SOA_TABLE(Timestamps, "AOD", "TIMESTAMPS", timestamp::Timestamp); +DECLARE_SOA_TABLE(Timestamps, "AOD", "TIMESTAMPS", //! + timestamp::Timestamp); using BCsWithTimestamps = soa::Join; namespace collision { -DECLARE_SOA_INDEX_COLUMN(BC, bc); -DECLARE_SOA_COLUMN(PosX, posX, float); -DECLARE_SOA_COLUMN(PosY, posY, float); -DECLARE_SOA_COLUMN(PosZ, posZ, float); -DECLARE_SOA_COLUMN(CovXX, covXX, float); -DECLARE_SOA_COLUMN(CovXY, covXY, float); -DECLARE_SOA_COLUMN(CovXZ, covXZ, float); -DECLARE_SOA_COLUMN(CovYY, covYY, float); -DECLARE_SOA_COLUMN(CovYZ, covYZ, float); -DECLARE_SOA_COLUMN(CovZZ, covZZ, float); -DECLARE_SOA_COLUMN(Flags, flags, uint16_t); // Run2, see CollisionFlagsRun2 | Run 3, see Vertex::Flags -DECLARE_SOA_COLUMN(Chi2, chi2, float); -DECLARE_SOA_COLUMN(NumContrib, numContrib, uint16_t); -DECLARE_SOA_COLUMN(CollisionTime, collisionTime, float); -DECLARE_SOA_COLUMN(CollisionTimeRes, collisionTimeRes, float); -DECLARE_SOA_COLUMN(CollisionTimeMask, collisionTimeMask, uint8_t); // TODO put nature of CollisionTimeRes here, e.g. MSB 0 = exact range / 1 = Gaussian uncertainty +DECLARE_SOA_INDEX_COLUMN(BC, bc); //! +DECLARE_SOA_COLUMN(PosX, posX, float); //! Vertex position +DECLARE_SOA_COLUMN(PosY, posY, float); //! +DECLARE_SOA_COLUMN(PosZ, posZ, float); //! +DECLARE_SOA_COLUMN(CovXX, covXX, float); //! Vertex covariance matrix +DECLARE_SOA_COLUMN(CovXY, covXY, float); //! +DECLARE_SOA_COLUMN(CovXZ, covXZ, float); //! +DECLARE_SOA_COLUMN(CovYY, covYY, float); //! +DECLARE_SOA_COLUMN(CovYZ, covYZ, float); //! +DECLARE_SOA_COLUMN(CovZZ, covZZ, float); //! +DECLARE_SOA_COLUMN(Flags, flags, uint16_t); //! Run2, see CollisionFlagsRun2 | Run 3, see Vertex::Flags +DECLARE_SOA_COLUMN(Chi2, chi2, float); //! +DECLARE_SOA_COLUMN(NumContrib, numContrib, uint16_t); //! Number of tracks at vertex +DECLARE_SOA_COLUMN(CollisionTime, collisionTime, float); //! +DECLARE_SOA_COLUMN(CollisionTimeRes, collisionTimeRes, float); //! +DECLARE_SOA_COLUMN(CollisionTimeMask, collisionTimeMask, uint8_t); //! Nature of CollisionTimeRes, MSB 0 = exact range / 1 = Gaussian uncertainty } // namespace collision -DECLARE_SOA_TABLE(Collisions, "AOD", "COLLISION", o2::soa::Index<>, collision::BCId, collision::PosX, collision::PosY, collision::PosZ, collision::CovXX, collision::CovXY, collision::CovXZ, collision::CovYY, collision::CovYZ, collision::CovZZ, collision::Flags, collision::Chi2, collision::NumContrib, collision::CollisionTime, collision::CollisionTimeRes, collision::CollisionTimeMask); +DECLARE_SOA_TABLE(Collisions, "AOD", "COLLISION", //! Time and vertex information of collision + o2::soa::Index<>, collision::BCId, + collision::PosX, collision::PosY, collision::PosZ, + collision::CovXX, collision::CovXY, collision::CovXZ, collision::CovYY, collision::CovYZ, collision::CovZZ, + collision::Flags, collision::Chi2, collision::NumContrib, + collision::CollisionTime, collision::CollisionTimeRes, collision::CollisionTimeMask); using Collision = Collisions::iterator; @@ -77,138 +83,168 @@ using Collision = Collisions::iterator; namespace track { // TRACKPAR TABLE definition -DECLARE_SOA_INDEX_COLUMN(Collision, collision); -DECLARE_SOA_COLUMN(TrackType, trackType, uint8_t); // TODO change to TrackTypeEnum when enums are supported -DECLARE_SOA_COLUMN(X, x, float); -DECLARE_SOA_COLUMN(Alpha, alpha, float); -DECLARE_SOA_COLUMN(Y, y, float); -DECLARE_SOA_COLUMN(Z, z, float); -DECLARE_SOA_COLUMN(Snp, snp, float); -DECLARE_SOA_COLUMN(Tgl, tgl, float); -DECLARE_SOA_COLUMN(Signed1Pt, signed1Pt, float); -DECLARE_SOA_EXPRESSION_COLUMN(RawPhi, phiraw, float, nasin(aod::track::snp) + aod::track::alpha); +DECLARE_SOA_INDEX_COLUMN(Collision, collision); //! +DECLARE_SOA_COLUMN(TrackType, trackType, uint8_t); //! TODO change to TrackTypeEnum when enums are supported +DECLARE_SOA_COLUMN(X, x, float); //! +DECLARE_SOA_COLUMN(Alpha, alpha, float); //! +DECLARE_SOA_COLUMN(Y, y, float); //! +DECLARE_SOA_COLUMN(Z, z, float); //! +DECLARE_SOA_COLUMN(Snp, snp, float); //! +DECLARE_SOA_COLUMN(Tgl, tgl, float); //! +DECLARE_SOA_COLUMN(Signed1Pt, signed1Pt, float); //! (sign of charge)/Pt [c/GeV] +DECLARE_SOA_EXPRESSION_COLUMN(RawPhi, phiraw, float, //! + nasin(aod::track::snp) + aod::track::alpha); // FIXME: make expression column when conditional nodes are supported in Gandiva -DECLARE_SOA_DYNAMIC_COLUMN(NormalizedPhi, phi, [](float phi) -> float { - constexpr float twopi = 2.0f * static_cast(M_PI); - if (phi < 0) - phi += twopi; - if (phi > twopi) - phi -= twopi; - return phi; -}); -DECLARE_SOA_EXPRESSION_COLUMN(Eta, eta, float, -1.f * nlog(ntan(0.25f * static_cast(M_PI) - 0.5f * natan(aod::track::tgl)))); -DECLARE_SOA_EXPRESSION_COLUMN(Pt, pt, float, nabs(1.f / aod::track::signed1Pt)); - -DECLARE_SOA_DYNAMIC_COLUMN(Sign, sign, [](float signed1Pt) -> short { return (signed1Pt > 0) ? 1 : -1; }); -DECLARE_SOA_DYNAMIC_COLUMN(Px, px, [](float signed1Pt, float snp, float alpha) -> float { - auto pt = 1.f / std::abs(signed1Pt); - float cs, sn; - math_utils::sincos(alpha, sn, cs); - auto r = std::sqrt((1.f - snp) * (1.f + snp)); - return pt * (r * cs - snp * sn); -}); -DECLARE_SOA_DYNAMIC_COLUMN(Py, py, [](float signed1Pt, float snp, float alpha) -> float { - auto pt = 1.f / std::abs(signed1Pt); - float cs, sn; - math_utils::sincos(alpha, sn, cs); - auto r = std::sqrt((1.f - snp) * (1.f + snp)); - return pt * (snp * cs + r * sn); -}); -DECLARE_SOA_DYNAMIC_COLUMN(Pz, pz, [](float signed1Pt, float tgl) -> float { - auto pt = 1.f / std::abs(signed1Pt); - return pt * tgl; -}); - -DECLARE_SOA_EXPRESSION_COLUMN(P, p, float, 0.5f * (ntan(0.25f * static_cast(M_PI) - 0.5f * natan(aod::track::tgl)) + 1.f / ntan(0.25f * static_cast(M_PI) - 0.5f * natan(aod::track::tgl))) / nabs(aod::track::signed1Pt)); +DECLARE_SOA_DYNAMIC_COLUMN(NormalizedPhi, phi, //! + [](float phi) -> float { + constexpr float twopi = 2.0f * static_cast(M_PI); + if (phi < 0) + phi += twopi; + if (phi > twopi) + phi -= twopi; + return phi; + }); +DECLARE_SOA_EXPRESSION_COLUMN(Eta, eta, float, //! Pseudo rapidity + -1.f * nlog(ntan(0.25f * static_cast(M_PI) - 0.5f * natan(aod::track::tgl)))); +DECLARE_SOA_EXPRESSION_COLUMN(Pt, pt, float, //! + nabs(1.f / aod::track::signed1Pt)); + +DECLARE_SOA_DYNAMIC_COLUMN(Sign, sign, //! Charge: positive: 1, negative: -1 + [](float signed1Pt) -> short { return (signed1Pt > 0) ? 1 : -1; }); +DECLARE_SOA_DYNAMIC_COLUMN(Px, px, //! Momentum in x-direction [GeV/c] + [](float signed1Pt, float snp, float alpha) -> float { + auto pt = 1.f / std::abs(signed1Pt); + float cs, sn; + math_utils::sincos(alpha, sn, cs); + auto r = std::sqrt((1.f - snp) * (1.f + snp)); + return pt * (r * cs - snp * sn); + }); +DECLARE_SOA_DYNAMIC_COLUMN(Py, py, //! Momentum in y-direction [GeV/c] + [](float signed1Pt, float snp, float alpha) -> float { + auto pt = 1.f / std::abs(signed1Pt); + float cs, sn; + math_utils::sincos(alpha, sn, cs); + auto r = std::sqrt((1.f - snp) * (1.f + snp)); + return pt * (snp * cs + r * sn); + }); +DECLARE_SOA_DYNAMIC_COLUMN(Pz, pz, //! Momentum in z-direction [GeV/c] + [](float signed1Pt, float tgl) -> float { + auto pt = 1.f / std::abs(signed1Pt); + return pt * tgl; + }); + +DECLARE_SOA_EXPRESSION_COLUMN(P, p, float, //! Absolute momentum [Gev/c] + 0.5f * (ntan(0.25f * static_cast(M_PI) - 0.5f * natan(aod::track::tgl)) + 1.f / ntan(0.25f * static_cast(M_PI) - 0.5f * natan(aod::track::tgl))) / nabs(aod::track::signed1Pt)); // TRACKPARCOV TABLE definition -DECLARE_SOA_COLUMN(SigmaY, sigmaY, float); -DECLARE_SOA_COLUMN(SigmaZ, sigmaZ, float); -DECLARE_SOA_COLUMN(SigmaSnp, sigmaSnp, float); -DECLARE_SOA_COLUMN(SigmaTgl, sigmaTgl, float); -DECLARE_SOA_COLUMN(Sigma1Pt, sigma1Pt, float); -DECLARE_SOA_COLUMN(RhoZY, rhoZY, int8_t); -DECLARE_SOA_COLUMN(RhoSnpY, rhoSnpY, int8_t); -DECLARE_SOA_COLUMN(RhoSnpZ, rhoSnpZ, int8_t); -DECLARE_SOA_COLUMN(RhoTglY, rhoTglY, int8_t); -DECLARE_SOA_COLUMN(RhoTglZ, rhoTglZ, int8_t); -DECLARE_SOA_COLUMN(RhoTglSnp, rhoTglSnp, int8_t); -DECLARE_SOA_COLUMN(Rho1PtY, rho1PtY, int8_t); -DECLARE_SOA_COLUMN(Rho1PtZ, rho1PtZ, int8_t); -DECLARE_SOA_COLUMN(Rho1PtSnp, rho1PtSnp, int8_t); -DECLARE_SOA_COLUMN(Rho1PtTgl, rho1PtTgl, int8_t); - -DECLARE_SOA_EXPRESSION_COLUMN(CYY, cYY, float, aod::track::sigmaY* aod::track::sigmaY); -DECLARE_SOA_EXPRESSION_COLUMN(CZY, cZY, float, (aod::track::rhoZY / 128.f) * (aod::track::sigmaZ * aod::track::sigmaY)); -DECLARE_SOA_EXPRESSION_COLUMN(CZZ, cZZ, float, aod::track::sigmaZ* aod::track::sigmaZ); -DECLARE_SOA_EXPRESSION_COLUMN(CSnpY, cSnpY, float, (aod::track::rhoSnpY / 128.f) * (aod::track::sigmaSnp * aod::track::sigmaY)); -DECLARE_SOA_EXPRESSION_COLUMN(CSnpZ, cSnpZ, float, (aod::track::rhoSnpZ / 128.f) * (aod::track::sigmaSnp * aod::track::sigmaZ)); -DECLARE_SOA_EXPRESSION_COLUMN(CSnpSnp, cSnpSnp, float, aod::track::sigmaSnp* aod::track::sigmaSnp); -DECLARE_SOA_EXPRESSION_COLUMN(CTglY, cTglY, float, (aod::track::rhoTglY / 128.f) * (aod::track::sigmaTgl * aod::track::sigmaY)); -DECLARE_SOA_EXPRESSION_COLUMN(CTglZ, cTglZ, float, (aod::track::rhoTglZ / 128.f) * (aod::track::sigmaTgl * aod::track::sigmaZ)); -DECLARE_SOA_EXPRESSION_COLUMN(CTglSnp, cTglSnp, float, (aod::track::rhoTglSnp / 128.f) * (aod::track::sigmaTgl * aod::track::sigmaSnp)); -DECLARE_SOA_EXPRESSION_COLUMN(CTglTgl, cTglTgl, float, aod::track::sigmaTgl* aod::track::sigmaTgl); -DECLARE_SOA_EXPRESSION_COLUMN(C1PtY, c1PtY, float, (aod::track::rho1PtY / 128.f) * (aod::track::sigma1Pt * aod::track::sigmaY)); -DECLARE_SOA_EXPRESSION_COLUMN(C1PtZ, c1PtZ, float, (aod::track::rho1PtZ / 128.f) * (aod::track::sigma1Pt * aod::track::sigmaZ)); -DECLARE_SOA_EXPRESSION_COLUMN(C1PtSnp, c1PtSnp, float, (aod::track::rho1PtSnp / 128.f) * (aod::track::sigma1Pt * aod::track::sigmaSnp)); -DECLARE_SOA_EXPRESSION_COLUMN(C1PtTgl, c1PtTgl, float, (aod::track::rho1PtTgl / 128.f) * (aod::track::sigma1Pt * aod::track::sigmaTgl)); -DECLARE_SOA_EXPRESSION_COLUMN(C1Pt21Pt2, c1Pt21Pt2, float, aod::track::sigma1Pt* aod::track::sigma1Pt); +DECLARE_SOA_COLUMN(SigmaY, sigmaY, float); //! +DECLARE_SOA_COLUMN(SigmaZ, sigmaZ, float); //! +DECLARE_SOA_COLUMN(SigmaSnp, sigmaSnp, float); //! +DECLARE_SOA_COLUMN(SigmaTgl, sigmaTgl, float); //! +DECLARE_SOA_COLUMN(Sigma1Pt, sigma1Pt, float); //! +DECLARE_SOA_COLUMN(RhoZY, rhoZY, int8_t); //! +DECLARE_SOA_COLUMN(RhoSnpY, rhoSnpY, int8_t); //! +DECLARE_SOA_COLUMN(RhoSnpZ, rhoSnpZ, int8_t); //! +DECLARE_SOA_COLUMN(RhoTglY, rhoTglY, int8_t); //! +DECLARE_SOA_COLUMN(RhoTglZ, rhoTglZ, int8_t); //! +DECLARE_SOA_COLUMN(RhoTglSnp, rhoTglSnp, int8_t); //! +DECLARE_SOA_COLUMN(Rho1PtY, rho1PtY, int8_t); //! +DECLARE_SOA_COLUMN(Rho1PtZ, rho1PtZ, int8_t); //! +DECLARE_SOA_COLUMN(Rho1PtSnp, rho1PtSnp, int8_t); //! +DECLARE_SOA_COLUMN(Rho1PtTgl, rho1PtTgl, int8_t); //! + +DECLARE_SOA_EXPRESSION_COLUMN(CYY, cYY, float, //! + aod::track::sigmaY* aod::track::sigmaY); +DECLARE_SOA_EXPRESSION_COLUMN(CZY, cZY, float, //! + (aod::track::rhoZY / 128.f) * (aod::track::sigmaZ * aod::track::sigmaY)); +DECLARE_SOA_EXPRESSION_COLUMN(CZZ, cZZ, float, //! + aod::track::sigmaZ* aod::track::sigmaZ); +DECLARE_SOA_EXPRESSION_COLUMN(CSnpY, cSnpY, float, //! + (aod::track::rhoSnpY / 128.f) * (aod::track::sigmaSnp * aod::track::sigmaY)); +DECLARE_SOA_EXPRESSION_COLUMN(CSnpZ, cSnpZ, float, //! + (aod::track::rhoSnpZ / 128.f) * (aod::track::sigmaSnp * aod::track::sigmaZ)); +DECLARE_SOA_EXPRESSION_COLUMN(CSnpSnp, cSnpSnp, float, //! + aod::track::sigmaSnp* aod::track::sigmaSnp); +DECLARE_SOA_EXPRESSION_COLUMN(CTglY, cTglY, float, //! + (aod::track::rhoTglY / 128.f) * (aod::track::sigmaTgl * aod::track::sigmaY)); +DECLARE_SOA_EXPRESSION_COLUMN(CTglZ, cTglZ, float, //! + (aod::track::rhoTglZ / 128.f) * (aod::track::sigmaTgl * aod::track::sigmaZ)); +DECLARE_SOA_EXPRESSION_COLUMN(CTglSnp, cTglSnp, float, //! + (aod::track::rhoTglSnp / 128.f) * (aod::track::sigmaTgl * aod::track::sigmaSnp)); +DECLARE_SOA_EXPRESSION_COLUMN(CTglTgl, cTglTgl, float, //! + aod::track::sigmaTgl* aod::track::sigmaTgl); +DECLARE_SOA_EXPRESSION_COLUMN(C1PtY, c1PtY, float, //! + (aod::track::rho1PtY / 128.f) * (aod::track::sigma1Pt * aod::track::sigmaY)); +DECLARE_SOA_EXPRESSION_COLUMN(C1PtZ, c1PtZ, float, //! + (aod::track::rho1PtZ / 128.f) * (aod::track::sigma1Pt * aod::track::sigmaZ)); +DECLARE_SOA_EXPRESSION_COLUMN(C1PtSnp, c1PtSnp, float, //! + (aod::track::rho1PtSnp / 128.f) * (aod::track::sigma1Pt * aod::track::sigmaSnp)); +DECLARE_SOA_EXPRESSION_COLUMN(C1PtTgl, c1PtTgl, float, //! + (aod::track::rho1PtTgl / 128.f) * (aod::track::sigma1Pt * aod::track::sigmaTgl)); +DECLARE_SOA_EXPRESSION_COLUMN(C1Pt21Pt2, c1Pt21Pt2, float, //! + aod::track::sigma1Pt* aod::track::sigma1Pt); // TRACKEXTRA TABLE definition -DECLARE_SOA_COLUMN(TPCInnerParam, tpcInnerParam, float); -DECLARE_SOA_COLUMN(Flags, flags, uint32_t); -DECLARE_SOA_COLUMN(ITSClusterMap, itsClusterMap, uint8_t); -DECLARE_SOA_COLUMN(TPCNClsFindable, tpcNClsFindable, uint8_t); -DECLARE_SOA_COLUMN(TPCNClsFindableMinusFound, tpcNClsFindableMinusFound, int8_t); -DECLARE_SOA_COLUMN(TPCNClsFindableMinusCrossedRows, tpcNClsFindableMinusCrossedRows, int8_t); -DECLARE_SOA_COLUMN(TPCNClsShared, tpcNClsShared, uint8_t); -DECLARE_SOA_COLUMN(TRDPattern, trdPattern, uint8_t); -DECLARE_SOA_COLUMN(ITSChi2NCl, itsChi2NCl, float); -DECLARE_SOA_COLUMN(TPCChi2NCl, tpcChi2NCl, float); -DECLARE_SOA_COLUMN(TRDChi2, trdChi2, float); -DECLARE_SOA_COLUMN(TOFChi2, tofChi2, float); -DECLARE_SOA_COLUMN(TPCSignal, tpcSignal, float); -DECLARE_SOA_COLUMN(TRDSignal, trdSignal, float); -DECLARE_SOA_COLUMN(TOFSignal, tofSignal, float); -DECLARE_SOA_COLUMN(Length, length, float); -DECLARE_SOA_COLUMN(TOFExpMom, tofExpMom, float); -DECLARE_SOA_COLUMN(TrackEtaEMCAL, trackEtaEmcal, float); -DECLARE_SOA_COLUMN(TrackPhiEMCAL, trackPhiEmcal, float); -DECLARE_SOA_DYNAMIC_COLUMN(PIDForTracking, pidForTracking, [](uint32_t flags) -> uint32_t { return flags >> 28; }); -DECLARE_SOA_DYNAMIC_COLUMN(TPCNClsFound, tpcNClsFound, [](uint8_t tpcNClsFindable, int8_t tpcNClsFindableMinusFound) -> int16_t { return (int16_t)tpcNClsFindable - tpcNClsFindableMinusFound; }); -DECLARE_SOA_DYNAMIC_COLUMN(TPCNClsCrossedRows, tpcNClsCrossedRows, [](uint8_t tpcNClsFindable, int8_t TPCNClsFindableMinusCrossedRows) -> int16_t { return (int16_t)tpcNClsFindable - TPCNClsFindableMinusCrossedRows; }); -DECLARE_SOA_DYNAMIC_COLUMN(ITSNCls, itsNCls, [](uint8_t itsClusterMap) -> uint8_t { - uint8_t itsNcls = 0; - constexpr uint8_t bit = 1; - for (int layer = 0; layer < 7; layer++) { - if (itsClusterMap & (bit << layer)) - itsNcls++; - } - return itsNcls; -}); -DECLARE_SOA_DYNAMIC_COLUMN(ITSNClsInnerBarrel, itsNClsInnerBarrel, [](uint8_t itsClusterMap) -> uint8_t { - uint8_t itsNclsInnerBarrel = 0; - constexpr uint8_t bit = 1; - for (int layer = 0; layer < 3; layer++) { - if (itsClusterMap & (bit << layer)) - itsNclsInnerBarrel++; - } - return itsNclsInnerBarrel; -}); - -DECLARE_SOA_DYNAMIC_COLUMN(TPCCrossedRowsOverFindableCls, tpcCrossedRowsOverFindableCls, +DECLARE_SOA_COLUMN(TPCInnerParam, tpcInnerParam, float); //! +DECLARE_SOA_COLUMN(Flags, flags, uint32_t); //! +DECLARE_SOA_COLUMN(ITSClusterMap, itsClusterMap, uint8_t); //! +DECLARE_SOA_COLUMN(TPCNClsFindable, tpcNClsFindable, uint8_t); //! +DECLARE_SOA_COLUMN(TPCNClsFindableMinusFound, tpcNClsFindableMinusFound, int8_t); //! +DECLARE_SOA_COLUMN(TPCNClsFindableMinusCrossedRows, tpcNClsFindableMinusCrossedRows, int8_t); //! +DECLARE_SOA_COLUMN(TPCNClsShared, tpcNClsShared, uint8_t); //! +DECLARE_SOA_COLUMN(TRDPattern, trdPattern, uint8_t); //! +DECLARE_SOA_COLUMN(ITSChi2NCl, itsChi2NCl, float); //! +DECLARE_SOA_COLUMN(TPCChi2NCl, tpcChi2NCl, float); //! +DECLARE_SOA_COLUMN(TRDChi2, trdChi2, float); //! +DECLARE_SOA_COLUMN(TOFChi2, tofChi2, float); //! +DECLARE_SOA_COLUMN(TPCSignal, tpcSignal, float); //! +DECLARE_SOA_COLUMN(TRDSignal, trdSignal, float); //! +DECLARE_SOA_COLUMN(TOFSignal, tofSignal, float); //! +DECLARE_SOA_COLUMN(Length, length, float); //! +DECLARE_SOA_COLUMN(TOFExpMom, tofExpMom, float); //! +DECLARE_SOA_COLUMN(TrackEtaEMCAL, trackEtaEmcal, float); //! +DECLARE_SOA_COLUMN(TrackPhiEMCAL, trackPhiEmcal, float); //! +DECLARE_SOA_DYNAMIC_COLUMN(PIDForTracking, pidForTracking, //! + [](uint32_t flags) -> uint32_t { return flags >> 28; }); +DECLARE_SOA_DYNAMIC_COLUMN(TPCNClsFound, tpcNClsFound, //! + [](uint8_t tpcNClsFindable, int8_t tpcNClsFindableMinusFound) -> int16_t { return (int16_t)tpcNClsFindable - tpcNClsFindableMinusFound; }); +DECLARE_SOA_DYNAMIC_COLUMN(TPCNClsCrossedRows, tpcNClsCrossedRows, //! + [](uint8_t tpcNClsFindable, int8_t TPCNClsFindableMinusCrossedRows) -> int16_t { return (int16_t)tpcNClsFindable - TPCNClsFindableMinusCrossedRows; }); +DECLARE_SOA_DYNAMIC_COLUMN(ITSNCls, itsNCls, //! + [](uint8_t itsClusterMap) -> uint8_t { + uint8_t itsNcls = 0; + constexpr uint8_t bit = 1; + for (int layer = 0; layer < 7; layer++) { + if (itsClusterMap & (bit << layer)) + itsNcls++; + } + return itsNcls; + }); +DECLARE_SOA_DYNAMIC_COLUMN(ITSNClsInnerBarrel, itsNClsInnerBarrel, //! + [](uint8_t itsClusterMap) -> uint8_t { + uint8_t itsNclsInnerBarrel = 0; + constexpr uint8_t bit = 1; + for (int layer = 0; layer < 3; layer++) { + if (itsClusterMap & (bit << layer)) + itsNclsInnerBarrel++; + } + return itsNclsInnerBarrel; + }); + +DECLARE_SOA_DYNAMIC_COLUMN(TPCCrossedRowsOverFindableCls, tpcCrossedRowsOverFindableCls, //! [](uint8_t tpcNClsFindable, int8_t tpcNClsFindableMinusCrossedRows) -> float { int16_t tpcNClsCrossedRows = (int16_t)tpcNClsFindable - tpcNClsFindableMinusCrossedRows; return (float)tpcNClsCrossedRows / (float)tpcNClsFindable; }); -DECLARE_SOA_DYNAMIC_COLUMN(TPCFractionSharedCls, tpcFractionSharedCls, [](uint8_t tpcNClsShared, uint8_t tpcNClsFindable, int8_t tpcNClsFindableMinusFound) -> float { - int16_t tpcNClsFound = (int16_t)tpcNClsFindable - tpcNClsFindableMinusFound; - return (float)tpcNClsShared / (float)tpcNClsFound; -}); +DECLARE_SOA_DYNAMIC_COLUMN(TPCFractionSharedCls, tpcFractionSharedCls, //! + [](uint8_t tpcNClsShared, uint8_t tpcNClsFindable, int8_t tpcNClsFindableMinusFound) -> float { + int16_t tpcNClsFound = (int16_t)tpcNClsFindable - tpcNClsFindableMinusFound; + return (float)tpcNClsShared / (float)tpcNClsFound; + }); } // namespace track -DECLARE_SOA_TABLE_FULL(StoredTracks, "Tracks", "AOD", "TRACK", +DECLARE_SOA_TABLE_FULL(StoredTracks, "Tracks", "AOD", "TRACK", //! o2::soa::Index<>, track::CollisionId, track::TrackType, track::X, track::Alpha, track::Y, track::Z, track::Snp, track::Tgl, @@ -219,7 +255,7 @@ DECLARE_SOA_TABLE_FULL(StoredTracks, "Tracks", "AOD", "TRACK", track::Pz, track::Sign); -DECLARE_SOA_EXTENDED_TABLE(Tracks, StoredTracks, "TRACK", +DECLARE_SOA_EXTENDED_TABLE(Tracks, StoredTracks, "TRACK", //! aod::track::Pt, aod::track::P, aod::track::Eta, @@ -230,7 +266,7 @@ DECLARE_SOA_TABLE_FULL(StoredTracksCov, "TracksCov", "AOD", "TRACKCOV", track::RhoZY, track::RhoSnpY, track::RhoSnpZ, track::RhoTglY, track::RhoTglZ, track::RhoTglSnp, track::Rho1PtY, track::Rho1PtZ, track::Rho1PtSnp, track::Rho1PtTgl); -DECLARE_SOA_EXTENDED_TABLE(TracksCov, StoredTracksCov, "TRACKCOV", +DECLARE_SOA_EXTENDED_TABLE(TracksCov, StoredTracksCov, "TRACKCOV", //! aod::track::CYY, aod::track::CZY, aod::track::CZZ, @@ -247,7 +283,7 @@ DECLARE_SOA_EXTENDED_TABLE(TracksCov, StoredTracksCov, "TRACKCOV", aod::track::C1PtTgl, aod::track::C1Pt21Pt2); -DECLARE_SOA_TABLE(TracksExtra, "AOD", "TRACKEXTRA", +DECLARE_SOA_TABLE(TracksExtra, "AOD", "TRACKEXTRA", //! track::TPCInnerParam, track::Flags, track::ITSClusterMap, track::TPCNClsFindable, track::TPCNClsFindableMinusFound, track::TPCNClsFindableMinusCrossedRows, track::TPCNClsShared, track::TRDPattern, track::ITSChi2NCl, @@ -271,75 +307,97 @@ using FullTrack = FullTracks::iterator; namespace fwdtrack { // FwdTracks and MFTTracks Columns definitions -DECLARE_SOA_INDEX_COLUMN(Collision, collision); -DECLARE_SOA_INDEX_COLUMN(BC, bc); -DECLARE_SOA_COLUMN(TrackType, trackType, uint8_t); // TODO change to ForwardTrackTypeEnum when enums are supported -DECLARE_SOA_COLUMN(X, x, float); // TrackParFwd parameters: x, y, z, phi, tan(lamba), q/pt -DECLARE_SOA_COLUMN(Y, y, float); -DECLARE_SOA_COLUMN(Z, z, float); -DECLARE_SOA_COLUMN(Phi, phi, float); -DECLARE_SOA_COLUMN(Tgl, tgl, float); -DECLARE_SOA_COLUMN(Signed1Pt, signed1Pt, float); -DECLARE_SOA_COLUMN(NClusters, nClusters, int8_t); -DECLARE_SOA_COLUMN(Chi2, chi2, float); -DECLARE_SOA_COLUMN(PDca, pDca, float); // PDca for MUONStandalone -DECLARE_SOA_COLUMN(RAtAbsorberEnd, rAtAbsorberEnd, float); // RAtAbsorberEnd for MUONStandalone tracks and GlobalMuonTrackstracks -DECLARE_SOA_COLUMN(Chi2MatchMCHMID, chi2MatchMCHMID, float); // MCH-MID Match Chi2 for MUONStandalone tracks -DECLARE_SOA_COLUMN(Chi2MatchMCHMFT, chi2MatchMCHMFT, float); // MCH-MFT Match Chi2 for GlobalMuonTracks -DECLARE_SOA_COLUMN(MatchScoreMCHMFT, matchScoreMCHMFT, float); // MCH-MFT Machine Learning Matching Score for GlobalMuonTracks -DECLARE_SOA_COLUMN(MatchMFTTrackID, matchMFTTrackID, int); // ID of matching MFT track for GlobalMuonTrack (ints while self indexing not available) -DECLARE_SOA_COLUMN(MatchMCHTrackID, matchMCHTrackID, int); // ID of matching MCH track for GlobalMuonTracks (ints while self indexing not available) - -DECLARE_SOA_DYNAMIC_COLUMN(Sign, sign, [](float signed1Pt) -> short { return (signed1Pt > 0) ? 1 : -1; }); -DECLARE_SOA_EXPRESSION_COLUMN(Eta, eta, float, -1.f * nlog(ntan(0.25f * static_cast(M_PI) - 0.5f * natan(aod::fwdtrack::tgl)))); -DECLARE_SOA_EXPRESSION_COLUMN(Pt, pt, float, nabs(1.f / aod::fwdtrack::signed1Pt)); -DECLARE_SOA_EXPRESSION_COLUMN(P, p, float, 0.5f * (ntan(0.25f * static_cast(M_PI) - 0.5f * natan(aod::fwdtrack::tgl)) + 1.f / ntan(0.25f * static_cast(M_PI) - 0.5f * natan(aod::fwdtrack::tgl))) / nabs(aod::fwdtrack::signed1Pt)); -DECLARE_SOA_DYNAMIC_COLUMN(Px, px, [](float pt, float phi) -> float { - return pt * std::cos(phi); -}); -DECLARE_SOA_DYNAMIC_COLUMN(Py, py, [](float pt, float phi) -> float { - return pt * std::sin(phi); -}); -DECLARE_SOA_DYNAMIC_COLUMN(Pz, pz, [](float pt, float tgl) -> float { - return pt * tgl; -}); +DECLARE_SOA_INDEX_COLUMN(Collision, collision); //! +DECLARE_SOA_INDEX_COLUMN(BC, bc); //! +DECLARE_SOA_COLUMN(TrackType, trackType, uint8_t); //! TODO change to ForwardTrackTypeEnum when enums are supported +DECLARE_SOA_COLUMN(X, x, float); //! TrackParFwd parameters: x, y, z, phi, tan(lamba), q/pt +DECLARE_SOA_COLUMN(Y, y, float); //! +DECLARE_SOA_COLUMN(Z, z, float); //! +DECLARE_SOA_COLUMN(Phi, phi, float); //! +DECLARE_SOA_COLUMN(Tgl, tgl, float); //! +DECLARE_SOA_COLUMN(Signed1Pt, signed1Pt, float); //! +DECLARE_SOA_COLUMN(NClusters, nClusters, int8_t); //! +DECLARE_SOA_COLUMN(Chi2, chi2, float); //! +DECLARE_SOA_COLUMN(PDca, pDca, float); //! PDca for MUONStandalone +DECLARE_SOA_COLUMN(RAtAbsorberEnd, rAtAbsorberEnd, float); //! RAtAbsorberEnd for MUONStandalone tracks and GlobalMuonTrackstracks +DECLARE_SOA_COLUMN(Chi2MatchMCHMID, chi2MatchMCHMID, float); //! MCH-MID Match Chi2 for MUONStandalone tracks +DECLARE_SOA_COLUMN(Chi2MatchMCHMFT, chi2MatchMCHMFT, float); //! MCH-MFT Match Chi2 for GlobalMuonTracks +DECLARE_SOA_COLUMN(MatchScoreMCHMFT, matchScoreMCHMFT, float); //! MCH-MFT Machine Learning Matching Score for GlobalMuonTracks +DECLARE_SOA_COLUMN(MatchMFTTrackID, matchMFTTrackID, int); //! ID of matching MFT track for GlobalMuonTrack (ints while self indexing not available) +DECLARE_SOA_COLUMN(MatchMCHTrackID, matchMCHTrackID, int); //! ID of matching MCH track for GlobalMuonTracks (ints while self indexing not available) + +DECLARE_SOA_DYNAMIC_COLUMN(Sign, sign, //! + [](float signed1Pt) -> short { return (signed1Pt > 0) ? 1 : -1; }); +DECLARE_SOA_EXPRESSION_COLUMN(Eta, eta, float, //! + -1.f * nlog(ntan(0.25f * static_cast(M_PI) - 0.5f * natan(aod::fwdtrack::tgl)))); +DECLARE_SOA_EXPRESSION_COLUMN(Pt, pt, float, //! + nabs(1.f / aod::fwdtrack::signed1Pt)); +DECLARE_SOA_EXPRESSION_COLUMN(P, p, float, //! + 0.5f * (ntan(0.25f * static_cast(M_PI) - 0.5f * natan(aod::fwdtrack::tgl)) + 1.f / ntan(0.25f * static_cast(M_PI) - 0.5f * natan(aod::fwdtrack::tgl))) / nabs(aod::fwdtrack::signed1Pt)); +DECLARE_SOA_DYNAMIC_COLUMN(Px, px, //! + [](float pt, float phi) -> float { + return pt * std::cos(phi); + }); +DECLARE_SOA_DYNAMIC_COLUMN(Py, py, //! + [](float pt, float phi) -> float { + return pt * std::sin(phi); + }); +DECLARE_SOA_DYNAMIC_COLUMN(Pz, pz, //! + [](float pt, float tgl) -> float { + return pt * tgl; + }); // FwdTracksCov columns definitions -DECLARE_SOA_COLUMN(SigmaX, sigmaX, float); -DECLARE_SOA_COLUMN(SigmaY, sigmaY, float); -DECLARE_SOA_COLUMN(SigmaPhi, sigmaPhi, float); -DECLARE_SOA_COLUMN(SigmaTgl, sigmaTgl, float); -DECLARE_SOA_COLUMN(Sigma1Pt, sigma1Pt, float); -DECLARE_SOA_COLUMN(RhoXY, rhoXY, int8_t); -DECLARE_SOA_COLUMN(RhoPhiX, rhoPhiX, int8_t); -DECLARE_SOA_COLUMN(RhoPhiY, rhoPhiY, int8_t); -DECLARE_SOA_COLUMN(RhoTglX, rhoTglX, int8_t); -DECLARE_SOA_COLUMN(RhoTglY, rhoTglY, int8_t); -DECLARE_SOA_COLUMN(RhoTglPhi, rhoTglPhi, int8_t); -DECLARE_SOA_COLUMN(Rho1PtX, rho1PtX, int8_t); -DECLARE_SOA_COLUMN(Rho1PtY, rho1PtY, int8_t); -DECLARE_SOA_COLUMN(Rho1PtPhi, rho1PtPhi, int8_t); -DECLARE_SOA_COLUMN(Rho1PtTgl, rho1PtTgl, int8_t); - -DECLARE_SOA_EXPRESSION_COLUMN(CXX, cXX, float, aod::fwdtrack::sigmaX* aod::fwdtrack::sigmaX); -DECLARE_SOA_EXPRESSION_COLUMN(CXY, cXY, float, (aod::fwdtrack::rhoXY / 128.f) * (aod::fwdtrack::sigmaX * aod::fwdtrack::sigmaY)); -DECLARE_SOA_EXPRESSION_COLUMN(CYY, cYY, float, aod::fwdtrack::sigmaY* aod::fwdtrack::sigmaY); -DECLARE_SOA_EXPRESSION_COLUMN(CPhiX, cPhiX, float, (aod::fwdtrack::rhoPhiX / 128.f) * (aod::fwdtrack::sigmaPhi * aod::fwdtrack::sigmaX)); -DECLARE_SOA_EXPRESSION_COLUMN(CPhiY, cPhiY, float, (aod::fwdtrack::rhoPhiY / 128.f) * (aod::fwdtrack::sigmaPhi * aod::fwdtrack::sigmaY)); -DECLARE_SOA_EXPRESSION_COLUMN(CPhiPhi, cPhiPhi, float, aod::fwdtrack::sigmaPhi* aod::fwdtrack::sigmaPhi); -DECLARE_SOA_EXPRESSION_COLUMN(CTglX, cTglX, float, (aod::fwdtrack::rhoTglX / 128.f) * (aod::fwdtrack::sigmaTgl * aod::fwdtrack::sigmaX)); -DECLARE_SOA_EXPRESSION_COLUMN(CTglY, cTglY, float, (aod::fwdtrack::rhoTglY / 128.f) * (aod::fwdtrack::sigmaTgl * aod::fwdtrack::sigmaY)); -DECLARE_SOA_EXPRESSION_COLUMN(CTglPhi, cTglPhi, float, (aod::fwdtrack::rhoTglPhi / 128.f) * (aod::fwdtrack::sigmaTgl * aod::fwdtrack::sigmaPhi)); -DECLARE_SOA_EXPRESSION_COLUMN(CTglTgl, cTglTgl, float, aod::fwdtrack::sigmaTgl* aod::fwdtrack::sigmaTgl); -DECLARE_SOA_EXPRESSION_COLUMN(C1PtY, c1PtY, float, (aod::fwdtrack::rho1PtY / 128.f) * (aod::fwdtrack::sigma1Pt * aod::fwdtrack::sigmaY)); -DECLARE_SOA_EXPRESSION_COLUMN(C1PtX, c1PtX, float, (aod::fwdtrack::rho1PtX / 128.f) * (aod::fwdtrack::sigma1Pt * aod::fwdtrack::sigmaX)); -DECLARE_SOA_EXPRESSION_COLUMN(C1PtPhi, c1PtPhi, float, (aod::fwdtrack::rho1PtPhi / 128.f) * (aod::fwdtrack::sigma1Pt * aod::fwdtrack::sigmaPhi)); -DECLARE_SOA_EXPRESSION_COLUMN(C1PtTgl, c1PtTgl, float, (aod::fwdtrack::rho1PtTgl / 128.f) * (aod::fwdtrack::sigma1Pt * aod::fwdtrack::sigmaTgl)); -DECLARE_SOA_EXPRESSION_COLUMN(C1Pt21Pt2, c1Pt21Pt2, float, aod::fwdtrack::sigma1Pt* aod::fwdtrack::sigma1Pt); +DECLARE_SOA_COLUMN(SigmaX, sigmaX, float); //! +DECLARE_SOA_COLUMN(SigmaY, sigmaY, float); //! +DECLARE_SOA_COLUMN(SigmaPhi, sigmaPhi, float); //! +DECLARE_SOA_COLUMN(SigmaTgl, sigmaTgl, float); //! +DECLARE_SOA_COLUMN(Sigma1Pt, sigma1Pt, float); //! +DECLARE_SOA_COLUMN(RhoXY, rhoXY, int8_t); //! +DECLARE_SOA_COLUMN(RhoPhiX, rhoPhiX, int8_t); //! +DECLARE_SOA_COLUMN(RhoPhiY, rhoPhiY, int8_t); //! +DECLARE_SOA_COLUMN(RhoTglX, rhoTglX, int8_t); //! +DECLARE_SOA_COLUMN(RhoTglY, rhoTglY, int8_t); //! +DECLARE_SOA_COLUMN(RhoTglPhi, rhoTglPhi, int8_t); //! +DECLARE_SOA_COLUMN(Rho1PtX, rho1PtX, int8_t); //! +DECLARE_SOA_COLUMN(Rho1PtY, rho1PtY, int8_t); //! +DECLARE_SOA_COLUMN(Rho1PtPhi, rho1PtPhi, int8_t); //! +DECLARE_SOA_COLUMN(Rho1PtTgl, rho1PtTgl, int8_t); //! + +DECLARE_SOA_EXPRESSION_COLUMN(CXX, cXX, float, //! + aod::fwdtrack::sigmaX* aod::fwdtrack::sigmaX); +DECLARE_SOA_EXPRESSION_COLUMN(CXY, cXY, float, //! + (aod::fwdtrack::rhoXY / 128.f) * (aod::fwdtrack::sigmaX * aod::fwdtrack::sigmaY)); +DECLARE_SOA_EXPRESSION_COLUMN(CYY, cYY, float, //! + aod::fwdtrack::sigmaY* aod::fwdtrack::sigmaY); +DECLARE_SOA_EXPRESSION_COLUMN(CPhiX, cPhiX, float, //! + (aod::fwdtrack::rhoPhiX / 128.f) * (aod::fwdtrack::sigmaPhi * aod::fwdtrack::sigmaX)); +DECLARE_SOA_EXPRESSION_COLUMN(CPhiY, cPhiY, float, //! + (aod::fwdtrack::rhoPhiY / 128.f) * (aod::fwdtrack::sigmaPhi * aod::fwdtrack::sigmaY)); +DECLARE_SOA_EXPRESSION_COLUMN(CPhiPhi, cPhiPhi, float, //! + aod::fwdtrack::sigmaPhi* aod::fwdtrack::sigmaPhi); +DECLARE_SOA_EXPRESSION_COLUMN(CTglX, cTglX, float, //! + (aod::fwdtrack::rhoTglX / 128.f) * (aod::fwdtrack::sigmaTgl * aod::fwdtrack::sigmaX)); +DECLARE_SOA_EXPRESSION_COLUMN(CTglY, cTglY, float, //! + (aod::fwdtrack::rhoTglY / 128.f) * (aod::fwdtrack::sigmaTgl * aod::fwdtrack::sigmaY)); +DECLARE_SOA_EXPRESSION_COLUMN(CTglPhi, cTglPhi, float, //! + (aod::fwdtrack::rhoTglPhi / 128.f) * (aod::fwdtrack::sigmaTgl * aod::fwdtrack::sigmaPhi)); +DECLARE_SOA_EXPRESSION_COLUMN(CTglTgl, cTglTgl, float, //! + aod::fwdtrack::sigmaTgl* aod::fwdtrack::sigmaTgl); +DECLARE_SOA_EXPRESSION_COLUMN(C1PtY, c1PtY, float, //! + (aod::fwdtrack::rho1PtY / 128.f) * (aod::fwdtrack::sigma1Pt * aod::fwdtrack::sigmaY)); +DECLARE_SOA_EXPRESSION_COLUMN(C1PtX, c1PtX, float, //! + (aod::fwdtrack::rho1PtX / 128.f) * (aod::fwdtrack::sigma1Pt * aod::fwdtrack::sigmaX)); +DECLARE_SOA_EXPRESSION_COLUMN(C1PtPhi, c1PtPhi, float, //! + (aod::fwdtrack::rho1PtPhi / 128.f) * (aod::fwdtrack::sigma1Pt * aod::fwdtrack::sigmaPhi)); +DECLARE_SOA_EXPRESSION_COLUMN(C1PtTgl, c1PtTgl, float, //! + (aod::fwdtrack::rho1PtTgl / 128.f) * (aod::fwdtrack::sigma1Pt * aod::fwdtrack::sigmaTgl)); +DECLARE_SOA_EXPRESSION_COLUMN(C1Pt21Pt2, c1Pt21Pt2, float, //! + aod::fwdtrack::sigma1Pt* aod::fwdtrack::sigma1Pt); } // namespace fwdtrack // MFTStandalone tracks -DECLARE_SOA_TABLE_FULL(StoredMFTTracks, "MFTTracks", "AOD", "MFTTRACK", +DECLARE_SOA_TABLE_FULL(StoredMFTTracks, "MFTTracks", "AOD", "MFTTRACK", //! o2::soa::Index<>, fwdtrack::CollisionId, fwdtrack::X, fwdtrack::Y, fwdtrack::Z, fwdtrack::Phi, fwdtrack::Tgl, fwdtrack::Signed1Pt, fwdtrack::NClusters, @@ -348,14 +406,14 @@ DECLARE_SOA_TABLE_FULL(StoredMFTTracks, "MFTTracks", "AOD", "MFTTRACK", fwdtrack::Pz, fwdtrack::Sign, fwdtrack::Chi2); -DECLARE_SOA_EXTENDED_TABLE(MFTTracks, StoredMFTTracks, "MFTTRACK", +DECLARE_SOA_EXTENDED_TABLE(MFTTracks, StoredMFTTracks, "MFTTRACK", //! aod::fwdtrack::Pt, aod::fwdtrack::Eta, aod::fwdtrack::P); using MFTTrack = MFTTracks::iterator; -// Tracks including MCH and/or MCH (plus optionally MFT) +// Tracks including MCH and/or MCH (plus optionally MFT) //! DECLARE_SOA_TABLE_FULL(StoredFwdTracks, "FwdTracks", "AOD", "FWDTRACK", o2::soa::Index<>, fwdtrack::CollisionId, fwdtrack::BCId, fwdtrack::TrackType, fwdtrack::X, fwdtrack::Y, fwdtrack::Z, fwdtrack::Phi, fwdtrack::Tgl, @@ -367,17 +425,17 @@ DECLARE_SOA_TABLE_FULL(StoredFwdTracks, "FwdTracks", "AOD", "FWDTRACK", fwdtrack::Chi2, fwdtrack::Chi2MatchMCHMID, fwdtrack::Chi2MatchMCHMFT, fwdtrack::MatchScoreMCHMFT, fwdtrack::MatchMFTTrackID, fwdtrack::MatchMCHTrackID); -DECLARE_SOA_EXTENDED_TABLE(FwdTracks, StoredFwdTracks, "FWDTRACK", - aod::fwdtrack::Eta, // NOTE the order is different here than in MFTTracks as table extension has to be unique +DECLARE_SOA_EXTENDED_TABLE(FwdTracks, StoredFwdTracks, "FWDTRACK", //! + aod::fwdtrack::Eta, // NOTE the order is different here than in MFTTracks as table extension has to be unique aod::fwdtrack::Pt, aod::fwdtrack::P); -DECLARE_SOA_TABLE_FULL(StoredFwdTracksCov, "FwdTracksCov", "AOD", "FWDTRACKCOV", +DECLARE_SOA_TABLE_FULL(StoredFwdTracksCov, "FwdTracksCov", "AOD", "FWDTRACKCOV", //! fwdtrack::SigmaX, fwdtrack::SigmaY, fwdtrack::SigmaPhi, fwdtrack::SigmaTgl, fwdtrack::Sigma1Pt, fwdtrack::RhoXY, fwdtrack::RhoPhiY, fwdtrack::RhoPhiX, fwdtrack::RhoTglX, fwdtrack::RhoTglY, fwdtrack::RhoTglPhi, fwdtrack::Rho1PtX, fwdtrack::Rho1PtY, fwdtrack::Rho1PtPhi, fwdtrack::Rho1PtTgl); -DECLARE_SOA_EXTENDED_TABLE(FwdTracksCov, StoredFwdTracksCov, "FWDTRACKCOV", +DECLARE_SOA_EXTENDED_TABLE(FwdTracksCov, StoredFwdTracksCov, "FWDTRACKCOV", //! aod::fwdtrack::CXX, aod::fwdtrack::CXY, aod::fwdtrack::CYY, @@ -402,22 +460,22 @@ using FullFwdTrack = FullFwdTracks::iterator; namespace unassignedtracks { -DECLARE_SOA_INDEX_COLUMN(Collision, collision); -DECLARE_SOA_INDEX_COLUMN(Track, track); +DECLARE_SOA_INDEX_COLUMN(Collision, collision); //! +DECLARE_SOA_INDEX_COLUMN(Track, track); //! } // namespace unassignedtracks -DECLARE_SOA_TABLE(UnassignedTracks, "AOD", "UNASSIGNEDTRACK", +DECLARE_SOA_TABLE(UnassignedTracks, "AOD", "UNASSIGNEDTRACK", //! unassignedtracks::CollisionId, unassignedtracks::TrackId); using UnassignedTrack = UnassignedTracks::iterator; namespace unassignedmfttracks { -DECLARE_SOA_INDEX_COLUMN(Collision, collision); -DECLARE_SOA_INDEX_COLUMN(MFTTrack, mfttrack); +DECLARE_SOA_INDEX_COLUMN(Collision, collision); //! +DECLARE_SOA_INDEX_COLUMN(MFTTrack, mfttrack); //! } // namespace unassignedmfttracks -DECLARE_SOA_TABLE(UnassignedMFTTracks, "AOD", "UNASSIGNEDMFTTR", +DECLARE_SOA_TABLE(UnassignedMFTTracks, "AOD", "UNASSIGNEDMFTTR", //! unassignedmfttracks::CollisionId, unassignedmfttracks::MFTTrackId); using UnassignedMFTTrack = UnassignedMFTTracks::iterator; @@ -425,13 +483,13 @@ using UnassignedMFTTrack = UnassignedMFTTracks::iterator; // HMPID information namespace hmpid { -DECLARE_SOA_INDEX_COLUMN(Track, track); -DECLARE_SOA_COLUMN(HMPIDSignal, hmpidSignal, float); -DECLARE_SOA_COLUMN(HMPIDDistance, hmpidDistance, float); -DECLARE_SOA_COLUMN(HMPIDQMip, hmpidQMip, short); +DECLARE_SOA_INDEX_COLUMN(Track, track); //! +DECLARE_SOA_COLUMN(HMPIDSignal, hmpidSignal, float); //! +DECLARE_SOA_COLUMN(HMPIDDistance, hmpidDistance, float); //! +DECLARE_SOA_COLUMN(HMPIDQMip, hmpidQMip, short); //! } // namespace hmpid -DECLARE_SOA_TABLE(HMPIDs, "AOD", "HMPID", +DECLARE_SOA_TABLE(HMPIDs, "AOD", "HMPID", //! hmpid::TrackId, hmpid::HMPIDSignal, hmpid::HMPIDDistance, @@ -440,32 +498,32 @@ using HMPID = HMPIDs::iterator; namespace calo { -DECLARE_SOA_INDEX_COLUMN(BC, bc); -DECLARE_SOA_COLUMN(CellNumber, cellNumber, int16_t); -DECLARE_SOA_COLUMN(Amplitude, amplitude, float); -DECLARE_SOA_COLUMN(Time, time, float); -DECLARE_SOA_COLUMN(CellType, cellType, int8_t); -DECLARE_SOA_COLUMN(CaloType, caloType, int8_t); +DECLARE_SOA_INDEX_COLUMN(BC, bc); //! +DECLARE_SOA_COLUMN(CellNumber, cellNumber, int16_t); //! +DECLARE_SOA_COLUMN(Amplitude, amplitude, float); //! +DECLARE_SOA_COLUMN(Time, time, float); //! +DECLARE_SOA_COLUMN(CellType, cellType, int8_t); //! +DECLARE_SOA_COLUMN(CaloType, caloType, int8_t); //! } // namespace calo -DECLARE_SOA_TABLE(Calos, "AOD", "CALO", calo::BCId, +DECLARE_SOA_TABLE(Calos, "AOD", "CALO", calo::BCId, //! calo::CellNumber, calo::Amplitude, calo::Time, calo::CellType, calo::CaloType); using Calo = Calos::iterator; namespace calotrigger { -DECLARE_SOA_INDEX_COLUMN(BC, bc); -DECLARE_SOA_COLUMN(FastOrAbsId, fastOrAbsId, int32_t); -DECLARE_SOA_COLUMN(L0Amplitude, l0Amplitude, float); -DECLARE_SOA_COLUMN(L0Time, l0Time, float); -DECLARE_SOA_COLUMN(L1TimeSum, l1TimeSum, int32_t); -DECLARE_SOA_COLUMN(NL0Times, nl0Times, int8_t); -DECLARE_SOA_COLUMN(TriggerBits, triggerBits, int32_t); -DECLARE_SOA_COLUMN(CaloType, caloType, int8_t); +DECLARE_SOA_INDEX_COLUMN(BC, bc); //! +DECLARE_SOA_COLUMN(FastOrAbsId, fastOrAbsId, int32_t); //! +DECLARE_SOA_COLUMN(L0Amplitude, l0Amplitude, float); //! +DECLARE_SOA_COLUMN(L0Time, l0Time, float); //! +DECLARE_SOA_COLUMN(L1TimeSum, l1TimeSum, int32_t); //! +DECLARE_SOA_COLUMN(NL0Times, nl0Times, int8_t); //! +DECLARE_SOA_COLUMN(TriggerBits, triggerBits, int32_t); //! +DECLARE_SOA_COLUMN(CaloType, caloType, int8_t); //! } // namespace calotrigger -DECLARE_SOA_TABLE(CaloTriggers, "AOD", "CALOTRIGGER", +DECLARE_SOA_TABLE(CaloTriggers, "AOD", "CALOTRIGGER", //! calotrigger::BCId, calotrigger::FastOrAbsId, calotrigger::L0Amplitude, calotrigger::L0Time, calotrigger::L1TimeSum, calotrigger::NL0Times, @@ -474,58 +532,65 @@ using CaloTrigger = CaloTriggers::iterator; namespace muon { -DECLARE_SOA_INDEX_COLUMN(BC, bc); -DECLARE_SOA_COLUMN(InverseBendingMomentum, inverseBendingMomentum, float); -DECLARE_SOA_COLUMN(ThetaX, thetaX, float); -DECLARE_SOA_COLUMN(ThetaY, thetaY, float); -DECLARE_SOA_COLUMN(ZMu, zMu, float); -DECLARE_SOA_COLUMN(BendingCoor, bendingCoor, float); -DECLARE_SOA_COLUMN(NonBendingCoor, nonBendingCoor, float); -DECLARE_SOA_COLUMN(Covariances, covariances, float[15]); -DECLARE_SOA_COLUMN(Chi2, chi2, float); -DECLARE_SOA_COLUMN(Chi2MatchTrigger, chi2MatchTrigger, float); -DECLARE_SOA_DYNAMIC_COLUMN(Eta, eta, [](float inverseBendingMomentum, float thetaX, float thetaY) -> float { - float pz = -std::sqrt(1.0 + std::tan(thetaY) * std::tan(thetaY)) / std::abs(inverseBendingMomentum); - float pt = std::abs(pz) * std::sqrt(std::tan(thetaX) * std::tan(thetaX) + std::tan(thetaY) * std::tan(thetaY)); - float eta = std::acos(pz / std::sqrt(pt * pt + pz * pz)); - eta = std::tan(0.5 * eta); - if (eta > 0.0) - return -std::log(eta); - else - return 0.0; -}); -DECLARE_SOA_DYNAMIC_COLUMN(Phi, phi, [](float thetaX, float thetaY) -> float { - float phi = std::atan2(std::tan(thetaY), std::tan(thetaX)); - constexpr float twopi = 2.0f * static_cast(M_PI); - return (phi >= 0.0 ? phi : phi + twopi); -}); -DECLARE_SOA_DYNAMIC_COLUMN(RAtAbsorberEnd, rAtAbsorberEnd, [](float bendingCoor, float nonBendingCoor, float zMu, float thetaX, float thetaY) -> float { - // linear extrapolation of the coordinates of the track to the position of the end of the absorber (-505 cm) - float dZ = -505. - zMu; - float NonBendingSlope = std::tan(thetaX); - float BendingSlope = std::tan(thetaY); - float xAbs = nonBendingCoor + NonBendingSlope * dZ; - float yAbs = bendingCoor + BendingSlope * dZ; - float rAtAbsorberEnd = std::sqrt(xAbs * xAbs + yAbs * yAbs); - return rAtAbsorberEnd; -}); -DECLARE_SOA_DYNAMIC_COLUMN(PDca, pDca, [](float inverseBendingMomentum, float thetaX, float thetaY, float bendingCoor, float nonBendingCoor, float zMu) -> float { - // linear extrapolation of the coordinates of the track to the position of the end of the absorber (-505 cm) - float dca = std::sqrt(bendingCoor * bendingCoor + nonBendingCoor * nonBendingCoor + zMu * zMu); - float pz = -std::sqrt(1.0 + std::tan(thetaY) * std::tan(thetaY)) / std::abs(inverseBendingMomentum); - float pt = std::abs(pz) * std::sqrt(std::tan(thetaX) * std::tan(thetaX) + std::tan(thetaY) * std::tan(thetaY)); - float pTot = std::sqrt(pt * pt + pz * pz); - float pDca = pTot * dca; - return pDca; -}); -DECLARE_SOA_EXPRESSION_COLUMN(Pt, pt, float, nsqrt(1.0f + ntan(aod::muon::thetaY) * ntan(aod::muon::thetaY)) * nsqrt(ntan(aod::muon::thetaX) * ntan(aod::muon::thetaX) + ntan(aod::muon::thetaY) * ntan(aod::muon::thetaY)) / nabs(aod::muon::inverseBendingMomentum)); -DECLARE_SOA_EXPRESSION_COLUMN(Px, px, float, -1.0f * ntan(aod::muon::thetaX) * nsqrt(1.0f + ntan(aod::muon::thetaY) * ntan(aod::muon::thetaY)) / nabs(aod::muon::inverseBendingMomentum)); -DECLARE_SOA_EXPRESSION_COLUMN(Py, py, float, -1.0f * ntan(aod::muon::thetaY) * nsqrt(1.0f + ntan(aod::muon::thetaY) * ntan(aod::muon::thetaY)) / nabs(aod::muon::inverseBendingMomentum)); -DECLARE_SOA_EXPRESSION_COLUMN(Pz, pz, float, -1.0f * nsqrt(1.0f + ntan(aod::muon::thetaY) * ntan(aod::muon::thetaY)) / nabs(aod::muon::inverseBendingMomentum)); -DECLARE_SOA_DYNAMIC_COLUMN(Sign, sign, [](float inverseBendingMomentum) -> short { return (inverseBendingMomentum > 0.0f) ? 1 : -1; }); +DECLARE_SOA_INDEX_COLUMN(BC, bc); //! +DECLARE_SOA_COLUMN(InverseBendingMomentum, inverseBendingMomentum, float); //! +DECLARE_SOA_COLUMN(ThetaX, thetaX, float); //! +DECLARE_SOA_COLUMN(ThetaY, thetaY, float); //! +DECLARE_SOA_COLUMN(ZMu, zMu, float); //! +DECLARE_SOA_COLUMN(BendingCoor, bendingCoor, float); //! +DECLARE_SOA_COLUMN(NonBendingCoor, nonBendingCoor, float); //! +DECLARE_SOA_COLUMN(Covariances, covariances, float[15]); //! +DECLARE_SOA_COLUMN(Chi2, chi2, float); //! +DECLARE_SOA_COLUMN(Chi2MatchTrigger, chi2MatchTrigger, float); //! +DECLARE_SOA_DYNAMIC_COLUMN(Eta, eta, //! + [](float inverseBendingMomentum, float thetaX, float thetaY) -> float { + float pz = -std::sqrt(1.0 + std::tan(thetaY) * std::tan(thetaY)) / std::abs(inverseBendingMomentum); + float pt = std::abs(pz) * std::sqrt(std::tan(thetaX) * std::tan(thetaX) + std::tan(thetaY) * std::tan(thetaY)); + float eta = std::acos(pz / std::sqrt(pt * pt + pz * pz)); + eta = std::tan(0.5 * eta); + if (eta > 0.0) + return -std::log(eta); + else + return 0.0; + }); +DECLARE_SOA_DYNAMIC_COLUMN(Phi, phi, //! + [](float thetaX, float thetaY) -> float { + float phi = std::atan2(std::tan(thetaY), std::tan(thetaX)); + constexpr float twopi = 2.0f * static_cast(M_PI); + return (phi >= 0.0 ? phi : phi + twopi); + }); +DECLARE_SOA_DYNAMIC_COLUMN(RAtAbsorberEnd, rAtAbsorberEnd, //! linear extrapolation of the coordinates of the track to the position of the end of the absorber (-505 cm) + [](float bendingCoor, float nonBendingCoor, float zMu, float thetaX, float thetaY) -> float { + float dZ = -505. - zMu; + float NonBendingSlope = std::tan(thetaX); + float BendingSlope = std::tan(thetaY); + float xAbs = nonBendingCoor + NonBendingSlope * dZ; + float yAbs = bendingCoor + BendingSlope * dZ; + float rAtAbsorberEnd = std::sqrt(xAbs * xAbs + yAbs * yAbs); + return rAtAbsorberEnd; + }); +DECLARE_SOA_DYNAMIC_COLUMN(PDca, pDca, //! linear extrapolation of the coordinates of the track to the position of the end of the absorber (-505 cm) + [](float inverseBendingMomentum, float thetaX, float thetaY, float bendingCoor, float nonBendingCoor, float zMu) -> float { + float dca = std::sqrt(bendingCoor * bendingCoor + nonBendingCoor * nonBendingCoor + zMu * zMu); + float pz = -std::sqrt(1.0 + std::tan(thetaY) * std::tan(thetaY)) / std::abs(inverseBendingMomentum); + float pt = std::abs(pz) * std::sqrt(std::tan(thetaX) * std::tan(thetaX) + std::tan(thetaY) * std::tan(thetaY)); + float pTot = std::sqrt(pt * pt + pz * pz); + float pDca = pTot * dca; + return pDca; + }); +DECLARE_SOA_EXPRESSION_COLUMN(Pt, pt, float, //! + nsqrt(1.0f + ntan(aod::muon::thetaY) * ntan(aod::muon::thetaY)) * nsqrt(ntan(aod::muon::thetaX) * ntan(aod::muon::thetaX) + ntan(aod::muon::thetaY) * ntan(aod::muon::thetaY)) / nabs(aod::muon::inverseBendingMomentum)); +DECLARE_SOA_EXPRESSION_COLUMN(Px, px, float, //! + -1.0f * ntan(aod::muon::thetaX) * nsqrt(1.0f + ntan(aod::muon::thetaY) * ntan(aod::muon::thetaY)) / nabs(aod::muon::inverseBendingMomentum)); +DECLARE_SOA_EXPRESSION_COLUMN(Py, py, float, //! + -1.0f * ntan(aod::muon::thetaY) * nsqrt(1.0f + ntan(aod::muon::thetaY) * ntan(aod::muon::thetaY)) / nabs(aod::muon::inverseBendingMomentum)); +DECLARE_SOA_EXPRESSION_COLUMN(Pz, pz, float, //! + -1.0f * nsqrt(1.0f + ntan(aod::muon::thetaY) * ntan(aod::muon::thetaY)) / nabs(aod::muon::inverseBendingMomentum)); +DECLARE_SOA_DYNAMIC_COLUMN(Sign, sign, //! + [](float inverseBendingMomentum) -> short { return (inverseBendingMomentum > 0.0f) ? 1 : -1; }); } // namespace muon -DECLARE_SOA_TABLE_FULL(StoredMuons, "Muons", "AOD", "MUON", +DECLARE_SOA_TABLE_FULL(StoredMuons, "Muons", "AOD", "MUON", //! muon::BCId, muon::InverseBendingMomentum, muon::ThetaX, muon::ThetaY, muon::ZMu, muon::BendingCoor, muon::NonBendingCoor, @@ -536,7 +601,7 @@ DECLARE_SOA_TABLE_FULL(StoredMuons, "Muons", "AOD", "MUON", muon::PDca, muon::Sign); -DECLARE_SOA_EXTENDED_TABLE(Muons, StoredMuons, "MUON", +DECLARE_SOA_EXTENDED_TABLE(Muons, StoredMuons, "MUON", //! aod::muon::Pt, aod::muon::Px, aod::muon::Py, @@ -548,17 +613,17 @@ using Muon = Muons::iterator; namespace muoncluster { -DECLARE_SOA_INDEX_COLUMN_FULL(Track, track, int, Muons, ""); // points to a muon track in the Muon table -DECLARE_SOA_COLUMN(X, x, float); -DECLARE_SOA_COLUMN(Y, y, float); -DECLARE_SOA_COLUMN(Z, z, float); -DECLARE_SOA_COLUMN(ErrX, errX, float); -DECLARE_SOA_COLUMN(ErrY, errY, float); -DECLARE_SOA_COLUMN(Charge, charge, float); -DECLARE_SOA_COLUMN(Chi2, chi2, float); +DECLARE_SOA_INDEX_COLUMN_FULL(Track, track, int, Muons, ""); //! points to a muon track in the Muon table +DECLARE_SOA_COLUMN(X, x, float); //! +DECLARE_SOA_COLUMN(Y, y, float); //! +DECLARE_SOA_COLUMN(Z, z, float); //! +DECLARE_SOA_COLUMN(ErrX, errX, float); //! +DECLARE_SOA_COLUMN(ErrY, errY, float); //! +DECLARE_SOA_COLUMN(Charge, charge, float); //! +DECLARE_SOA_COLUMN(Chi2, chi2, float); //! } // namespace muoncluster -DECLARE_SOA_TABLE(MuonClusters, "AOD", "MUONCLUSTER", +DECLARE_SOA_TABLE(MuonClusters, "AOD", "MUONCLUSTER", //! muoncluster::TrackId, muoncluster::X, muoncluster::Y, muoncluster::Z, muoncluster::ErrX, muoncluster::ErrY, @@ -568,26 +633,27 @@ using MuonCluster = MuonClusters::iterator; namespace zdc { -DECLARE_SOA_INDEX_COLUMN(BC, bc); -DECLARE_SOA_COLUMN(EnergyZEM1, energyZEM1, float); -DECLARE_SOA_COLUMN(EnergyZEM2, energyZEM2, float); -DECLARE_SOA_COLUMN(EnergyCommonZNA, energyCommonZNA, float); -DECLARE_SOA_COLUMN(EnergyCommonZNC, energyCommonZNC, float); -DECLARE_SOA_COLUMN(EnergyCommonZPA, energyCommonZPA, float); -DECLARE_SOA_COLUMN(EnergyCommonZPC, energyCommonZPC, float); -DECLARE_SOA_COLUMN(EnergySectorZNA, energySectorZNA, float[4]); -DECLARE_SOA_COLUMN(EnergySectorZNC, energySectorZNC, float[4]); -DECLARE_SOA_COLUMN(EnergySectorZPA, energySectorZPA, float[4]); -DECLARE_SOA_COLUMN(EnergySectorZPC, energySectorZPC, float[4]); -DECLARE_SOA_COLUMN(TimeZEM1, timeZEM1, float); -DECLARE_SOA_COLUMN(TimeZEM2, timeZEM2, float); -DECLARE_SOA_COLUMN(TimeZNA, timeZNA, float); -DECLARE_SOA_COLUMN(TimeZNC, timeZNC, float); -DECLARE_SOA_COLUMN(TimeZPA, timeZPA, float); -DECLARE_SOA_COLUMN(TimeZPC, timeZPC, float); +DECLARE_SOA_INDEX_COLUMN(BC, bc); //! +DECLARE_SOA_COLUMN(EnergyZEM1, energyZEM1, float); //! +DECLARE_SOA_COLUMN(EnergyZEM2, energyZEM2, float); //! +DECLARE_SOA_COLUMN(EnergyCommonZNA, energyCommonZNA, float); //! +DECLARE_SOA_COLUMN(EnergyCommonZNC, energyCommonZNC, float); //! +DECLARE_SOA_COLUMN(EnergyCommonZPA, energyCommonZPA, float); //! +DECLARE_SOA_COLUMN(EnergyCommonZPC, energyCommonZPC, float); //! +DECLARE_SOA_COLUMN(EnergySectorZNA, energySectorZNA, float[4]); //! +DECLARE_SOA_COLUMN(EnergySectorZNC, energySectorZNC, float[4]); //! +DECLARE_SOA_COLUMN(EnergySectorZPA, energySectorZPA, float[4]); //! +DECLARE_SOA_COLUMN(EnergySectorZPC, energySectorZPC, float[4]); //! +DECLARE_SOA_COLUMN(TimeZEM1, timeZEM1, float); //! +DECLARE_SOA_COLUMN(TimeZEM2, timeZEM2, float); //! +DECLARE_SOA_COLUMN(TimeZNA, timeZNA, float); //! +DECLARE_SOA_COLUMN(TimeZNC, timeZNC, float); //! +DECLARE_SOA_COLUMN(TimeZPA, timeZPA, float); //! +DECLARE_SOA_COLUMN(TimeZPC, timeZPC, float); //! } // namespace zdc -DECLARE_SOA_TABLE(Zdcs, "AOD", "ZDC", o2::soa::Index<>, zdc::BCId, zdc::EnergyZEM1, zdc::EnergyZEM2, +DECLARE_SOA_TABLE(Zdcs, "AOD", "ZDC", //! + o2::soa::Index<>, zdc::BCId, zdc::EnergyZEM1, zdc::EnergyZEM2, zdc::EnergyCommonZNA, zdc::EnergyCommonZNC, zdc::EnergyCommonZPA, zdc::EnergyCommonZPC, zdc::EnergySectorZNA, zdc::EnergySectorZNC, zdc::EnergySectorZPA, zdc::EnergySectorZPC, zdc::TimeZEM1, zdc::TimeZEM2, zdc::TimeZNA, zdc::TimeZNC, zdc::TimeZPA, zdc::TimeZPC); @@ -595,78 +661,88 @@ using Zdc = Zdcs::iterator; namespace fv0a { -DECLARE_SOA_INDEX_COLUMN(BC, bc); -DECLARE_SOA_COLUMN(Amplitude, amplitude, float[48]); -DECLARE_SOA_COLUMN(Time, time, float); -DECLARE_SOA_COLUMN(TriggerMask, triggerMask, uint8_t); +DECLARE_SOA_INDEX_COLUMN(BC, bc); //! +DECLARE_SOA_COLUMN(Amplitude, amplitude, float[48]); //! +DECLARE_SOA_COLUMN(Time, time, float); //! +DECLARE_SOA_COLUMN(TriggerMask, triggerMask, uint8_t); //! } // namespace fv0a -DECLARE_SOA_TABLE(FV0As, "AOD", "FV0A", o2::soa::Index<>, fv0a::BCId, fv0a::Amplitude, fv0a::Time, fv0a::TriggerMask); +DECLARE_SOA_TABLE(FV0As, "AOD", "FV0A", //! + o2::soa::Index<>, fv0a::BCId, fv0a::Amplitude, fv0a::Time, fv0a::TriggerMask); using FV0A = FV0As::iterator; // V0C table for Run2 only namespace fv0c { -DECLARE_SOA_INDEX_COLUMN(BC, bc); -DECLARE_SOA_COLUMN(Amplitude, amplitude, float[32]); -DECLARE_SOA_COLUMN(Time, time, float); +DECLARE_SOA_INDEX_COLUMN(BC, bc); //! +DECLARE_SOA_COLUMN(Amplitude, amplitude, float[32]); //! +DECLARE_SOA_COLUMN(Time, time, float); //! } // namespace fv0c -DECLARE_SOA_TABLE(FV0Cs, "AOD", "FV0C", o2::soa::Index<>, fv0c::BCId, fv0c::Amplitude, fv0c::Time); +DECLARE_SOA_TABLE(FV0Cs, "AOD", "FV0C", //! + o2::soa::Index<>, fv0c::BCId, fv0c::Amplitude, fv0c::Time); using FV0C = FV0Cs::iterator; namespace ft0 { -DECLARE_SOA_INDEX_COLUMN(BC, bc); -DECLARE_SOA_COLUMN(AmplitudeA, amplitudeA, float[96]); -DECLARE_SOA_COLUMN(AmplitudeC, amplitudeC, float[112]); -DECLARE_SOA_COLUMN(TimeA, timeA, float); -DECLARE_SOA_COLUMN(TimeC, timeC, float); -DECLARE_SOA_COLUMN(TriggerMask, triggerMask, uint8_t); +DECLARE_SOA_INDEX_COLUMN(BC, bc); //! +DECLARE_SOA_COLUMN(AmplitudeA, amplitudeA, float[96]); //! +DECLARE_SOA_COLUMN(AmplitudeC, amplitudeC, float[112]); //! +DECLARE_SOA_COLUMN(TimeA, timeA, float); //! +DECLARE_SOA_COLUMN(TimeC, timeC, float); //! +DECLARE_SOA_COLUMN(TriggerMask, triggerMask, uint8_t); //! } // namespace ft0 -DECLARE_SOA_TABLE(FT0s, "AOD", "FT0", o2::soa::Index<>, ft0::BCId, +DECLARE_SOA_TABLE(FT0s, "AOD", "FT0", //! + o2::soa::Index<>, ft0::BCId, ft0::AmplitudeA, ft0::AmplitudeC, ft0::TimeA, ft0::TimeC, ft0::TriggerMask); using FT0 = FT0s::iterator; namespace fdd { -DECLARE_SOA_INDEX_COLUMN(BC, bc); -DECLARE_SOA_COLUMN(AmplitudeA, amplitudeA, float[4]); -DECLARE_SOA_COLUMN(AmplitudeC, amplitudeC, float[4]); -DECLARE_SOA_COLUMN(TimeA, timeA, float); -DECLARE_SOA_COLUMN(TimeC, timeC, float); -DECLARE_SOA_COLUMN(TriggerMask, triggerMask, uint8_t); +DECLARE_SOA_INDEX_COLUMN(BC, bc); //! +DECLARE_SOA_COLUMN(AmplitudeA, amplitudeA, float[4]); //! +DECLARE_SOA_COLUMN(AmplitudeC, amplitudeC, float[4]); //! +DECLARE_SOA_COLUMN(TimeA, timeA, float); //! +DECLARE_SOA_COLUMN(TimeC, timeC, float); //! +DECLARE_SOA_COLUMN(TriggerMask, triggerMask, uint8_t); //! } // namespace fdd -DECLARE_SOA_TABLE(FDDs, "AOD", "FDD", o2::soa::Index<>, fdd::BCId, - fdd::AmplitudeA, fdd::AmplitudeC, fdd::TimeA, fdd::TimeC, +DECLARE_SOA_TABLE(FDDs, "AOD", "FDD", //! + o2::soa::Index<>, fdd::BCId, + fdd::AmplitudeA, fdd::AmplitudeC, + fdd::TimeA, fdd::TimeC, fdd::TriggerMask); using FDD = FDDs::iterator; namespace v0 { -DECLARE_SOA_INDEX_COLUMN_FULL(PosTrack, posTrack, int, Tracks, "_Pos"); -DECLARE_SOA_INDEX_COLUMN_FULL(NegTrack, negTrack, int, Tracks, "_Neg"); +DECLARE_SOA_INDEX_COLUMN_FULL(PosTrack, posTrack, int, Tracks, "_Pos"); //! +DECLARE_SOA_INDEX_COLUMN_FULL(NegTrack, negTrack, int, Tracks, "_Neg"); //! DECLARE_SOA_INDEX_COLUMN(Collision, collision); } // namespace v0 -DECLARE_SOA_TABLE(StoredV0s, "AOD", "V0", o2::soa::Index<>, v0::PosTrackId, v0::NegTrackId); -DECLARE_SOA_TABLE(TransientV0s, "AOD", "V0INDEX", v0::CollisionId); +DECLARE_SOA_TABLE(StoredV0s, "AOD", "V0", //! + o2::soa::Index<>, + v0::PosTrackId, v0::NegTrackId); +DECLARE_SOA_TABLE(TransientV0s, "AOD", "V0INDEX", //! + v0::CollisionId); using V0s = soa::Join; using V0 = V0s::iterator; namespace cascade { -DECLARE_SOA_INDEX_COLUMN(V0, v0); -DECLARE_SOA_INDEX_COLUMN_FULL(Bachelor, bachelor, int, Tracks, ""); -DECLARE_SOA_INDEX_COLUMN(Collision, collision); +DECLARE_SOA_INDEX_COLUMN(V0, v0); //! +DECLARE_SOA_INDEX_COLUMN_FULL(Bachelor, bachelor, int, Tracks, ""); //! +DECLARE_SOA_INDEX_COLUMN(Collision, collision); //! } // namespace cascade -DECLARE_SOA_TABLE(StoredCascades, "AOD", "CASCADE", o2::soa::Index<>, cascade::V0Id, cascade::BachelorId); -DECLARE_SOA_TABLE(TransientCascades, "AOD", "CASCADEINDEX", cascade::CollisionId); +DECLARE_SOA_TABLE(StoredCascades, "AOD", "CASCADE", //! + o2::soa::Index<>, cascade::V0Id, cascade::BachelorId); +DECLARE_SOA_TABLE(TransientCascades, "AOD", "CASCADEINDEX", //! + cascade::CollisionId); using Cascades = soa::Join; using Cascade = Cascades::iterator; @@ -674,65 +750,73 @@ using Cascade = Cascades::iterator; // ---- Run 2 tables ---- namespace run2 { -DECLARE_SOA_COLUMN(EventCuts, eventCuts, uint32_t); -DECLARE_SOA_COLUMN(TriggerMaskNext50, triggerMaskNext50, uint64_t); -DECLARE_SOA_COLUMN(SPDClustersL0, spdClustersL0, uint16_t); -DECLARE_SOA_COLUMN(SPDClustersL1, spdClustersL1, uint16_t); +DECLARE_SOA_COLUMN(EventCuts, eventCuts, uint32_t); //! +DECLARE_SOA_COLUMN(TriggerMaskNext50, triggerMaskNext50, uint64_t); //! +DECLARE_SOA_COLUMN(SPDClustersL0, spdClustersL0, uint16_t); //! +DECLARE_SOA_COLUMN(SPDClustersL1, spdClustersL1, uint16_t); //! } // namespace run2 -DECLARE_SOA_TABLE(Run2BCInfos, "AOD", "RUN2BCINFO", run2::EventCuts, run2::TriggerMaskNext50, - run2::SPDClustersL0, run2::SPDClustersL1) +DECLARE_SOA_TABLE(Run2BCInfos, "AOD", "RUN2BCINFO", //! + run2::EventCuts, run2::TriggerMaskNext50, + run2::SPDClustersL0, run2::SPDClustersL1); using Run2BCInfo = Run2BCInfos::iterator; // ---- MC tables ---- namespace mccollision { -DECLARE_SOA_INDEX_COLUMN(BC, bc); -DECLARE_SOA_COLUMN(GeneratorsID, generatorsID, short); -DECLARE_SOA_COLUMN(PosX, posX, float); -DECLARE_SOA_COLUMN(PosY, posY, float); -DECLARE_SOA_COLUMN(PosZ, posZ, float); -DECLARE_SOA_COLUMN(T, t, float); -DECLARE_SOA_COLUMN(Weight, weight, float); -DECLARE_SOA_COLUMN(ImpactParameter, impactParameter, float); +DECLARE_SOA_INDEX_COLUMN(BC, bc); //! +DECLARE_SOA_COLUMN(GeneratorsID, generatorsID, short); //! +DECLARE_SOA_COLUMN(PosX, posX, float); //! +DECLARE_SOA_COLUMN(PosY, posY, float); //! +DECLARE_SOA_COLUMN(PosZ, posZ, float); //! +DECLARE_SOA_COLUMN(T, t, float); //! +DECLARE_SOA_COLUMN(Weight, weight, float); //! +DECLARE_SOA_COLUMN(ImpactParameter, impactParameter, float); //! } // namespace mccollision -DECLARE_SOA_TABLE(McCollisions, "AOD", "MCCOLLISION", o2::soa::Index<>, mccollision::BCId, +DECLARE_SOA_TABLE(McCollisions, "AOD", "MCCOLLISION", //! + o2::soa::Index<>, mccollision::BCId, mccollision::GeneratorsID, - mccollision::PosX, mccollision::PosY, mccollision::PosZ, mccollision::T, mccollision::Weight, + mccollision::PosX, mccollision::PosY, mccollision::PosZ, + mccollision::T, mccollision::Weight, mccollision::ImpactParameter); using McCollision = McCollisions::iterator; namespace mcparticle { -DECLARE_SOA_INDEX_COLUMN(McCollision, mcCollision); -DECLARE_SOA_COLUMN(PdgCode, pdgCode, int); -DECLARE_SOA_COLUMN(StatusCode, statusCode, int); -DECLARE_SOA_COLUMN(Flags, flags, uint8_t); -DECLARE_SOA_COLUMN(Mother0, mother0, int); -DECLARE_SOA_COLUMN(Mother1, mother1, int); -DECLARE_SOA_COLUMN(Daughter0, daughter0, int); -DECLARE_SOA_COLUMN(Daughter1, daughter1, int); -DECLARE_SOA_COLUMN(Weight, weight, float); -DECLARE_SOA_COLUMN(Px, px, float); -DECLARE_SOA_COLUMN(Py, py, float); -DECLARE_SOA_COLUMN(Pz, pz, float); -DECLARE_SOA_COLUMN(E, e, float); -DECLARE_SOA_COLUMN(Vx, vx, float); -DECLARE_SOA_COLUMN(Vy, vy, float); -DECLARE_SOA_COLUMN(Vz, vz, float); -DECLARE_SOA_COLUMN(Vt, vt, float); -DECLARE_SOA_DYNAMIC_COLUMN(Phi, phi, [](float px, float py) -> float { return static_cast(M_PI) + std::atan2(-py, -px); }); -DECLARE_SOA_DYNAMIC_COLUMN(Eta, eta, [](float px, float py, float pz) -> float { return 0.5f * std::log((std::sqrt(px * px + py * py + pz * pz) + pz) / (std::sqrt(px * px + py * py + pz * pz) - pz)); }); -DECLARE_SOA_DYNAMIC_COLUMN(Pt, pt, [](float px, float py) -> float { return std::sqrt(px * px + py * py); }); -DECLARE_SOA_DYNAMIC_COLUMN(ProducedByGenerator, producedByGenerator, [](uint8_t flags) -> bool { return (flags & 0x1) == 0x0; }); +DECLARE_SOA_INDEX_COLUMN(McCollision, mcCollision); //! +DECLARE_SOA_COLUMN(PdgCode, pdgCode, int); //! +DECLARE_SOA_COLUMN(StatusCode, statusCode, int); //! +DECLARE_SOA_COLUMN(Flags, flags, uint8_t); //! +DECLARE_SOA_COLUMN(Mother0, mother0, int); //! +DECLARE_SOA_COLUMN(Mother1, mother1, int); //! +DECLARE_SOA_COLUMN(Daughter0, daughter0, int); //! +DECLARE_SOA_COLUMN(Daughter1, daughter1, int); //! +DECLARE_SOA_COLUMN(Weight, weight, float); //! +DECLARE_SOA_COLUMN(Px, px, float); //! +DECLARE_SOA_COLUMN(Py, py, float); //! +DECLARE_SOA_COLUMN(Pz, pz, float); //! +DECLARE_SOA_COLUMN(E, e, float); //! +DECLARE_SOA_COLUMN(Vx, vx, float); //! +DECLARE_SOA_COLUMN(Vy, vy, float); //! +DECLARE_SOA_COLUMN(Vz, vz, float); //! +DECLARE_SOA_COLUMN(Vt, vt, float); //! +DECLARE_SOA_DYNAMIC_COLUMN(Phi, phi, //! + [](float px, float py) -> float { return static_cast(M_PI) + std::atan2(-py, -px); }); +DECLARE_SOA_DYNAMIC_COLUMN(Eta, eta, //! + [](float px, float py, float pz) -> float { return 0.5f * std::log((std::sqrt(px * px + py * py + pz * pz) + pz) / (std::sqrt(px * px + py * py + pz * pz) - pz)); }); +DECLARE_SOA_DYNAMIC_COLUMN(Pt, pt, //! + [](float px, float py) -> float { return std::sqrt(px * px + py * py); }); +DECLARE_SOA_DYNAMIC_COLUMN(ProducedByGenerator, producedByGenerator, //! + [](uint8_t flags) -> bool { return (flags & 0x1) == 0x0; }); } // namespace mcparticle -DECLARE_SOA_TABLE(McParticles, "AOD", "MCPARTICLE", +DECLARE_SOA_TABLE(McParticles, "AOD", "MCPARTICLE", //! o2::soa::Index<>, mcparticle::McCollisionId, mcparticle::PdgCode, mcparticle::StatusCode, mcparticle::Flags, - mcparticle::Mother0, mcparticle::Mother1, mcparticle::Daughter0, mcparticle::Daughter1, mcparticle::Weight, + mcparticle::Mother0, mcparticle::Mother1, + mcparticle::Daughter0, mcparticle::Daughter1, mcparticle::Weight, mcparticle::Px, mcparticle::Py, mcparticle::Pz, mcparticle::E, mcparticle::Vx, mcparticle::Vy, mcparticle::Vz, mcparticle::Vt, mcparticle::Phi, @@ -743,39 +827,39 @@ using McParticle = McParticles::iterator; namespace mctracklabel { -DECLARE_SOA_INDEX_COLUMN(McParticle, mcParticle); -DECLARE_SOA_COLUMN(McMask, mcMask, uint16_t); +DECLARE_SOA_INDEX_COLUMN(McParticle, mcParticle); //! +DECLARE_SOA_COLUMN(McMask, mcMask, uint16_t); //! /// Bit mask to indicate detector mismatches (bit ON means mismatch) /// Bit 0-6: mismatch at ITS layer /// Bit 7-9: # of TPC mismatches in the ranges 0, 1, 2-3, 4-7, 8-15, 16-31, 32-63, >64 /// Bit 10: TRD, bit 11: TOF, bit 15: indicates negative label } // namespace mctracklabel -DECLARE_SOA_TABLE(McTrackLabels, "AOD", "MCTRACKLABEL", +DECLARE_SOA_TABLE(McTrackLabels, "AOD", "MCTRACKLABEL", //! mctracklabel::McParticleId, mctracklabel::McMask); using McTrackLabel = McTrackLabels::iterator; namespace mccalolabel { -DECLARE_SOA_INDEX_COLUMN(McParticle, mcParticle); -DECLARE_SOA_COLUMN(McMask, mcMask, uint16_t); +DECLARE_SOA_INDEX_COLUMN(McParticle, mcParticle); //! +DECLARE_SOA_COLUMN(McMask, mcMask, uint16_t); //! /// Bit mask to indicate detector mismatches (bit ON means mismatch) /// Bit 15: indicates negative label } // namespace mccalolabel -DECLARE_SOA_TABLE(McCaloLabels, "AOD", "MCCALOLABEL", +DECLARE_SOA_TABLE(McCaloLabels, "AOD", "MCCALOLABEL", //! mccalolabel::McParticleId, mccalolabel::McMask); using McCaloLabel = McCaloLabels::iterator; namespace mccollisionlabel { -DECLARE_SOA_INDEX_COLUMN(McCollision, mcCollision); -DECLARE_SOA_COLUMN(McMask, mcMask, uint16_t); +DECLARE_SOA_INDEX_COLUMN(McCollision, mcCollision); //! +DECLARE_SOA_COLUMN(McMask, mcMask, uint16_t); //! /// Bit mask to indicate collision mismatches (bit ON means mismatch) /// Bit 15: indicates negative label } // namespace mccollisionlabel -DECLARE_SOA_TABLE(McCollisionLabels, "AOD", "MCCOLLISLABEL", +DECLARE_SOA_TABLE(McCollisionLabels, "AOD", "MCCOLLISLABEL", //! mccollisionlabel::McCollisionId, mccollisionlabel::McMask); using McCollisionLabel = McCollisionLabels::iterator; @@ -783,32 +867,37 @@ using McCollisionLabel = McCollisionLabels::iterator; namespace indices { -DECLARE_SOA_INDEX_COLUMN(Collision, collision); -DECLARE_SOA_INDEX_COLUMN(BC, bc); -DECLARE_SOA_INDEX_COLUMN(Zdc, zdc); -DECLARE_SOA_INDEX_COLUMN(FV0A, fv0a); -DECLARE_SOA_INDEX_COLUMN(FV0C, fv0c); -DECLARE_SOA_INDEX_COLUMN(FT0, ft0); -DECLARE_SOA_INDEX_COLUMN(FDD, fdd); +DECLARE_SOA_INDEX_COLUMN(Collision, collision); //! +DECLARE_SOA_INDEX_COLUMN(BC, bc); //! +DECLARE_SOA_INDEX_COLUMN(Zdc, zdc); //! +DECLARE_SOA_INDEX_COLUMN(FV0A, fv0a); //! +DECLARE_SOA_INDEX_COLUMN(FV0C, fv0c); //! +DECLARE_SOA_INDEX_COLUMN(FT0, ft0); //! +DECLARE_SOA_INDEX_COLUMN(FDD, fdd); //! } // namespace indices // First entry: Collision #define INDEX_LIST_RUN2 indices::CollisionId, indices::ZdcId, indices::BCId, indices::FT0Id, indices::FV0AId, indices::FV0CId, indices::FDDId -DECLARE_SOA_INDEX_TABLE_EXCLUSIVE(Run2MatchedExclusive, BCs, "MA_RN2_EX", INDEX_LIST_RUN2); -DECLARE_SOA_INDEX_TABLE(Run2MatchedSparse, BCs, "MA_RN2_SP", INDEX_LIST_RUN2); +DECLARE_SOA_INDEX_TABLE_EXCLUSIVE(Run2MatchedExclusive, BCs, "MA_RN2_EX", INDEX_LIST_RUN2); //! +DECLARE_SOA_INDEX_TABLE(Run2MatchedSparse, BCs, "MA_RN2_SP", INDEX_LIST_RUN2); //! #define INDEX_LIST_RUN3 indices::CollisionId, indices::ZdcId, indices::BCId, indices::FT0Id, indices::FV0AId, indices::FDDId -DECLARE_SOA_INDEX_TABLE_EXCLUSIVE(Run3MatchedExclusive, BCs, "MA_RN3_EX", INDEX_LIST_RUN3); -DECLARE_SOA_INDEX_TABLE(Run3MatchedSparse, BCs, "MA_RN3_SP", INDEX_LIST_RUN3); +DECLARE_SOA_INDEX_TABLE_EXCLUSIVE(Run3MatchedExclusive, BCs, "MA_RN3_EX", INDEX_LIST_RUN3); //! +DECLARE_SOA_INDEX_TABLE(Run3MatchedSparse, BCs, "MA_RN3_SP", INDEX_LIST_RUN3); //! // First entry: BC -DECLARE_SOA_INDEX_TABLE_EXCLUSIVE(MatchedBCCollisionsExclusive, BCs, "MA_BCCOL_EX", indices::BCId, indices::CollisionId); -DECLARE_SOA_INDEX_TABLE(MatchedBCCollisionsSparse, BCs, "MA_BCCOL_SP", indices::BCId, indices::CollisionId); - -DECLARE_SOA_INDEX_TABLE_EXCLUSIVE(Run3MatchedToBCExclusive, BCs, "MA_RN3_BC_EX", indices::BCId, indices::ZdcId, indices::FT0Id, indices::FV0AId, indices::FDDId); -DECLARE_SOA_INDEX_TABLE(Run3MatchedToBCSparse, BCs, "MA_RN3_BC_SP", indices::BCId, indices::ZdcId, indices::FT0Id, indices::FV0AId, indices::FDDId); - -DECLARE_SOA_INDEX_TABLE(Run2MatchedToBCSparse, BCs, "MA_RN2_BC_SP", indices::BCId, indices::ZdcId, indices::FT0Id, indices::FV0AId, indices::FV0CId, indices::FDDId); +DECLARE_SOA_INDEX_TABLE_EXCLUSIVE(MatchedBCCollisionsExclusive, BCs, "MA_BCCOL_EX", //! + indices::BCId, indices::CollisionId); +DECLARE_SOA_INDEX_TABLE(MatchedBCCollisionsSparse, BCs, "MA_BCCOL_SP", //! + indices::BCId, indices::CollisionId); + +DECLARE_SOA_INDEX_TABLE_EXCLUSIVE(Run3MatchedToBCExclusive, BCs, "MA_RN3_BC_EX", //! + indices::BCId, indices::ZdcId, indices::FT0Id, indices::FV0AId, indices::FDDId); +DECLARE_SOA_INDEX_TABLE(Run3MatchedToBCSparse, BCs, "MA_RN3_BC_SP", //! + indices::BCId, indices::ZdcId, indices::FT0Id, indices::FV0AId, indices::FDDId); + +DECLARE_SOA_INDEX_TABLE(Run2MatchedToBCSparse, BCs, "MA_RN2_BC_SP", //! + indices::BCId, indices::ZdcId, indices::FT0Id, indices::FV0AId, indices::FV0CId, indices::FDDId); // Joins with collisions (only for sparse ones) // NOTE: index table needs to be always last argument From aa203be352a2ca689aef887cd609c5c2c5fc3503 Mon Sep 17 00:00:00 2001 From: Diego Stocco Date: Sat, 17 Apr 2021 10:39:06 +0200 Subject: [PATCH 147/770] Initialize patterns to 0 and add comparison operator (#5945) --- .../MID/include/DataFormatsMID/ColumnData.h | 8 +++++--- .../Detectors/MUON/MID/src/ColumnData.cxx | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/DataFormats/Detectors/MUON/MID/include/DataFormatsMID/ColumnData.h b/DataFormats/Detectors/MUON/MID/include/DataFormatsMID/ColumnData.h index 1992e44b033c7..85339a80b5b7a 100644 --- a/DataFormats/Detectors/MUON/MID/include/DataFormatsMID/ColumnData.h +++ b/DataFormats/Detectors/MUON/MID/include/DataFormatsMID/ColumnData.h @@ -26,9 +26,9 @@ namespace mid { /// Column data structure for MID struct ColumnData { - uint8_t deId = 0; ///< Index of the detection element - uint8_t columnId = 0; ///< Column in DE - std::array patterns; ///< Strip patterns + uint8_t deId = 0; ///< Index of the detection element + uint8_t columnId = 0; ///< Column in DE + std::array patterns{}; ///< Strip patterns /// Sets the bending plane pattern void setBendPattern(uint16_t pattern, int line) { patterns[line] = pattern; } @@ -51,6 +51,8 @@ struct ColumnData { bool isBPStripFired(int istrip, int line) const { return patterns[line] & (1 << istrip); } bool isStripFired(int istrip, int cathode, int line) const; + + bool operator==(const ColumnData& right) const; }; ColumnData operator|(const ColumnData& col1, const ColumnData& col2); diff --git a/DataFormats/Detectors/MUON/MID/src/ColumnData.cxx b/DataFormats/Detectors/MUON/MID/src/ColumnData.cxx index d0240c259b1d7..fcf1243fd9721 100644 --- a/DataFormats/Detectors/MUON/MID/src/ColumnData.cxx +++ b/DataFormats/Detectors/MUON/MID/src/ColumnData.cxx @@ -51,6 +51,23 @@ bool ColumnData::isStripFired(int istrip, int cathode, int line) const return (cathode == 0) ? isBPStripFired(istrip, line) : isNBPStripFired(istrip); } +bool ColumnData::operator==(const ColumnData& right) const +{ + /// Comparison operator + if (deId != right.deId) { + return false; + } + if (columnId != right.columnId) { + return false; + } + for (size_t ipat = 0; ipat < 5; ++ipat) { + if (patterns[ipat] != right.patterns[ipat]) { + return false; + } + } + return true; +} + ColumnData& operator|=(ColumnData& col1, const ColumnData& col2) { /// Merge operator for ColumnData From efa6e3c36ace5eb0d2b434b0b8ddabdf420199ff Mon Sep 17 00:00:00 2001 From: shahoian Date: Fri, 16 Apr 2021 21:21:05 +0200 Subject: [PATCH 148/770] RawFileWriter: fix in orbit limiting mechanism --- Detectors/Raw/src/RawFileWriter.cxx | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/Detectors/Raw/src/RawFileWriter.cxx b/Detectors/Raw/src/RawFileWriter.cxx index 0b6e3243ace83..5fa0bb2153f61 100644 --- a/Detectors/Raw/src/RawFileWriter.cxx +++ b/Detectors/Raw/src/RawFileWriter.cxx @@ -46,6 +46,10 @@ void RawFileWriter::close() if (!mFirstIRAdded.isDummy()) { // flushing and completing the last HBF makes sense only if data was added. auto irmax = getIRMax(); + // for CRU detectors link.updateIR and hence the irmax points on the last IR with data + 1 orbit + if (isCRUDetector()) { + irmax.orbit -= 1; + } for (auto& lnk : mSSpec2Link) { lnk.second.close(irmax); lnk.second.print(); @@ -172,7 +176,7 @@ void RawFileWriter::addData(uint16_t feeid, uint16_t cru, uint8_t lnk, uint8_t e if (link.discardData || ir.orbit - mHBFUtils.orbitFirst >= mHBFUtils.maxNOrbits) { if (!link.discardData) { link.discardData = true; - LOG(INFO) << "max. allowed orbit " << mHBFUtils.orbitFirst + mHBFUtils.maxNOrbits - 1 << " exceeded, " << link.describe() << " will discard further data"; + LOG(INFO) << "Orbit " << ir.orbit << ": max. allowed orbit " << mHBFUtils.orbitFirst + mHBFUtils.maxNOrbits - 1 << " exceeded, " << link.describe() << " will discard further data"; } return; } @@ -501,14 +505,9 @@ void RawFileWriter::LinkData::openHBFPage(const RDHAny& rdhn, uint32_t trigger) { /// create 1st page of the new HBF bool forceNewPage = false; - // for RORC detectors the TF flag is absent, instead the 1st trigger after the start of TF will define the 1st be interpreted as 1st TF - auto newTF_RORC = [this, &rdhn]() -> bool { - auto tfhbPrev = writer->mHBFUtils.getTFandHBinTF(this->updateIR.bc ? this->updateIR - 1 : this->updateIR); // updateIR was advanced by 1 BC wrt IR of the previous update - return this->writer->mHBFUtils.getTFandHBinTF(RDHUtils::getTriggerIR(rdhn)).first > tfhbPrev.first; // new TF_ID exceeds old one - }; - - if ((RDHUtils::getTriggerType(rdhn) & o2::trigger::TF) || (writer->isRORCDetector() && newTF_RORC())) { + if ((RDHUtils::getTriggerType(rdhn) & o2::trigger::TF) || + (writer->isRORCDetector() && writer->mHBFUtils.getTF(updateIR - 1) < writer->mHBFUtils.getTF(RDHUtils::getTriggerIR(rdhn)))) { if (writer->mVerbosity > -10) { LOGF(INFO, "Starting new TF for link FEEId 0x%04x", RDHUtils::getFEEID(rdhn)); } @@ -569,11 +568,7 @@ void RawFileWriter::LinkData::close(const IR& irf) return; // already closed } if (writer->isCRUDetector()) { // finalize last TF - auto irfin = irf; - if (irfin < updateIR) { - irfin = updateIR; - } - int tf = writer->mHBFUtils.getTF(irfin); + int tf = writer->mHBFUtils.getTF(irf); auto finalIR = writer->mHBFUtils.getIRTF(tf + 1) - 1; // last IR of the current TF fillEmptyHBHs(finalIR, false); } From 14219488d132235088aab823041ad11a26b28f2e Mon Sep 17 00:00:00 2001 From: Alla Maevskaya Date: Fri, 16 Apr 2021 18:44:46 +0300 Subject: [PATCH 149/770] bug fix for separate raw files name --- .../FT0/include/DataFormatsFT0/LookUpTable.h | 16 +++++++- .../FIT/FT0/simulation/src/Digits2Raw.cxx | 38 +++++++++---------- 2 files changed, 33 insertions(+), 21 deletions(-) diff --git a/DataFormats/Detectors/FIT/FT0/include/DataFormatsFT0/LookUpTable.h b/DataFormats/Detectors/FIT/FT0/include/DataFormatsFT0/LookUpTable.h index fcc4268871210..ce8cadb2d1f17 100644 --- a/DataFormats/Detectors/FIT/FT0/include/DataFormatsFT0/LookUpTable.h +++ b/DataFormats/Detectors/FIT/FT0/include/DataFormatsFT0/LookUpTable.h @@ -94,8 +94,6 @@ inline o2::ft0::Topo read_Topo(std::string_view str) throw std::invalid_argument("Expected 'Ch'"); } uint8_t pm_ch = std::strtol(ptr + 3, &ptr, 10); - // = (str[7] - '0') * 10 + (str[8] - '0') - 1; - /* res = std::from_chars(res.ptr+3, res.ptr+3+str.size(), pm_ch); */ uint8_t ep = side == 'C' ? 1 : 0; if (errno) { throw std::invalid_argument("Cannot read pm_ch"); @@ -145,11 +143,18 @@ class LookUpTable int getChannel(int link, int mcp, int ep) const { + if ((ep == 0 && (link > 7 && link < 11)) || + (ep == 1 && link == 8 && mcp > 8) || + (ep == 1 && link == 9 && mcp > 8)) { + LOG(INFO) << " channel is not conneted " + << " ep " << ep << " link " << link << " channel " << mcp; + } return mInvTopo[getIdx(link, mcp, ep)]; } int getLink(int channel) const { + return mTopoVector[channel].mPM; } int getMCP(int channel) const @@ -231,6 +236,12 @@ class LookUpTable static int getIdx(int link, int mcp, int ep) { assert(mcp < NUMBER_OF_MCPs); + /* if ((ep == 0 && (link > 7 && link < 11)) || */ + /* (ep == 1 && link == 8 && mcp > 8) || */ + /* (ep == 1 && link == 9 && mcp > 8)) { */ + /* LOG(INFO)<<" channel is not conneted "<<" ep "<GetEntry(ient); int nbc = digitsBC.size(); - LOG(DEBUG) << "Entry " << ient << " : " << nbc << " BCs stored"; + LOG(INFO) << "Entry " << ient << " : " << nbc << " BCs stored"; for (int ibc = 0; ibc < nbc; ibc++) { auto& bcd = digitsBC[ibc]; intRecord = bcd.getIntRecord(); @@ -172,7 +172,7 @@ void Digits2Raw::convertDigits(o2::ft0::Digit bcdigits, if (nlink != oldlink) { if (oldlink >= 0) { uint nGBTWords = uint((nchannels + 1) / 2); - LOG(INFO) << " oldlink " << oldlink << " old EP " << oldendpoint << " nGBTWords " << nGBTWords << " new link " << nlink << " ep " << ep; + LOG(DEBUG) << " oldlink " << oldlink << " old EP " << oldendpoint << " nGBTWords " << nGBTWords << " new link " << nlink << " ep " << ep; if ((nchannels % 2) == 1) { mRawEventData.mEventData[nchannels] = {}; } @@ -184,14 +184,14 @@ void Digits2Raw::convertDigits(o2::ft0::Digit bcdigits, if (mEndPointID == 1) { mFeeID += 8; } - LOG(INFO) << " new link start " << mFeeID << " " << mCruID << " " << mLinkID << " " << mEndPointID; + LOG(DEBUG) << " new link start " << mFeeID << " " << mCruID << " " << mLinkID << " " << mEndPointID; mWriter.addData(mFeeID, mCruID, mLinkID, mEndPointID, intRecord, data); } oldlink = nlink; oldendpoint = ep; mRawEventData.mEventHeader = makeGBTHeader(nlink, intRecord); nchannels = 0; - LOG(INFO) << " switch to new link " << nlink << " EP " << ep; + LOG(DEBUG) << " switch to new link " << nlink << " EP " << ep; } auto& newData = mRawEventData.mEventData[nchannels]; bool isAside = (pmchannels[ich].ChId < 96); @@ -243,20 +243,20 @@ void Digits2Raw::convertDigits(o2::ft0::Digit bcdigits, tcmdata.amplC = ampC; tcmdata.timeA = mTriggers.timeA; tcmdata.timeC = mTriggers.timeC; - LOG(INFO) << " TCM triggers read " - << " time A " << mTriggers.timeA << " time C " << mTriggers.timeC - << " amp A " << ampA << " amp C " << ampC - << " N A " << int(mTriggers.nChanA) << " N C " << int(mTriggers.nChanC) - << " trig " - << " ver " << mTriggers.getVertex() << " A " << mTriggers.getOrA() << " C " << mTriggers.getOrC(); + LOG(DEBUG) << " TCM triggers read " + << " time A " << mTriggers.timeA << " time C " << mTriggers.timeC + << " amp A " << ampA << " amp C " << ampC + << " N A " << int(mTriggers.nChanA) << " N C " << int(mTriggers.nChanC) + << " trig " + << " ver " << mTriggers.getVertex() << " A " << mTriggers.getOrA() << " C " << mTriggers.getOrC(); - LOG(INFO) << "TCMdata" - << " time A " << tcmdata.timeA << " time C " << tcmdata.timeC - << " amp A " << tcmdata.amplA << " amp C " << tcmdata.amplC - << " N A " << int(tcmdata.nChanA) << " N C " << int(tcmdata.nChanC) - << " trig " - << " ver " << tcmdata.vertex << " A " << tcmdata.orA << " C " << tcmdata.orC - << " size " << sizeof(tcmdata); + LOG(DEBUG) << "TCMdata" + << " time A " << tcmdata.timeA << " time C " << tcmdata.timeC + << " amp A " << tcmdata.amplA << " amp C " << tcmdata.amplC + << " N A " << int(tcmdata.nChanA) << " N C " << int(tcmdata.nChanC) + << " trig " + << " ver " << tcmdata.vertex << " A " << tcmdata.orA << " C " << tcmdata.orC + << " size " << sizeof(tcmdata); auto data = mRawEventData.to_vector(1); mLinkID = uint32_t(mLinkTCM); From 32d196c443c65d945d872c6249a25bedecef4c30 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 7 Apr 2021 08:35:51 +0200 Subject: [PATCH 150/770] GPU: Add option for memory scale factor to standalone benchmark --- GPU/GPUTracking/Benchmark/standalone.cxx | 2 ++ GPU/GPUTracking/Definitions/GPUSettingsList.h | 1 + 2 files changed, 3 insertions(+) diff --git a/GPU/GPUTracking/Benchmark/standalone.cxx b/GPU/GPUTracking/Benchmark/standalone.cxx index 376e44c4519d2..164a7fceb2094 100644 --- a/GPU/GPUTracking/Benchmark/standalone.cxx +++ b/GPU/GPUTracking/Benchmark/standalone.cxx @@ -20,6 +20,7 @@ #include "GPUQA.h" #include "GPUDisplayBackend.h" #include "genEvents.h" +#include "GPUMemorySizeScalers.h" #include #include @@ -482,6 +483,7 @@ int SetupReconstruction() if (configStandalone.proc.debugLevel >= 4) { rec->PrintKernelOccupancies(); } + rec->MemoryScalers()->factor *= configStandalone.memoryBufferScaleFactor; return (0); } diff --git a/GPU/GPUTracking/Definitions/GPUSettingsList.h b/GPU/GPUTracking/Definitions/GPUSettingsList.h index 9076e480529a2..c5edb7241e120 100644 --- a/GPU/GPUTracking/Definitions/GPUSettingsList.h +++ b/GPU/GPUTracking/Definitions/GPUSettingsList.h @@ -305,6 +305,7 @@ AddOption(rundEdx, int, -1, "", 0, "Enable dEdx processing") AddOption(runCompression, int, 1, "", 0, "Enable TPC Compression") AddOption(runTransformation, int, 1, "", 0, "Enable TPC Transformation") AddOption(runRefit, bool, false, "", 0, "Enable final track refit") +AddOption(memoryBufferScaleFactor, float, 1.f, "", 0, "Factor to scale buffer size estimations") AddHelp("help", 'h') AddHelpAll("helpall", 'H') AddSubConfig(GPUSettingsRec, rec) From bc8605c87c6aff002e67dcccce6b7972ebe8fc92 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 16 Apr 2021 11:10:57 +0200 Subject: [PATCH 151/770] Full system test: Was using wrong hmpid workflow --- prodtests/full-system-test/dpl-workflow.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/prodtests/full-system-test/dpl-workflow.sh b/prodtests/full-system-test/dpl-workflow.sh index b0c3dcea66c24..dad6677db1280 100755 --- a/prodtests/full-system-test/dpl-workflow.sh +++ b/prodtests/full-system-test/dpl-workflow.sh @@ -129,7 +129,7 @@ if [ $CTFINPUT == 0 ]; then WORKFLOW+="o2-cpv-reco-workflow $ARGS_ALL --input-type raw --output-type clusters --disable-root-input --disable-root-output $DISABLE_MC --pipeline CPVClusterizerSpec:$N_CPV | " WORKFLOW+="o2-emcal-reco-workflow $ARGS_ALL --input-type raw --output-type cells --disable-root-output $DISABLE_MC --pipeline EMCALRawToCellConverterSpec:$N_EMC | " WORKFLOW+="o2-zdc-raw2digits $ARGS_ALL --disable-root-output | " - WORKFLOW+="o2-hmpid-raw-to-digits-workflow $ARGS_ALL | " + WORKFLOW+="o2-hmpid-raw-to-digits-stream-workflow $ARGS_ALL | " WORKFLOW+="o2-itsmft-entropy-encoder-workflow $ARGS_ALL --runmft true | " WORKFLOW+="o2-ft0-entropy-encoder-workflow $ARGS_ALL | " @@ -145,7 +145,7 @@ if [ $CTFINPUT == 0 ]; then # Output workflow if [ ! -z $CTF_DIR ] ; then mkdir -p $CTF_DIR; fi if [ $CREATECTFDICT == 1 ] ; then - _DICT_="ctf_dictionary.root" + _DICT_="ctf_dictionary.root" if [ ! -z $CTF_DICT_DIR ] ; then mkdir -p $CTF_DICT_DIR; _DICT_="$CTF_DICT_DIR/$_DICT_" From 45cbf9d9e8181c65c85ac34b01485322c0a00c35 Mon Sep 17 00:00:00 2001 From: shahoian Date: Sat, 17 Apr 2021 19:57:22 +0200 Subject: [PATCH 152/770] FST: impose correct numeric format irrespecive of the locale --- prodtests/full_system_test.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/prodtests/full_system_test.sh b/prodtests/full_system_test.sh index 0e39047ec543b..0ac50ede4f58e 100755 --- a/prodtests/full_system_test.sh +++ b/prodtests/full_system_test.sh @@ -18,6 +18,8 @@ # --> utilities to query CPU count . ${O2_ROOT}/share/scripts/jobutils.sh +# make sure that correct format will be used irrespecive of the locale +LC_NUMERIC=C NEvents=${NEvents:-10} #550 for full TF (the number of PbPb events) NEventsQED=${NEventsQED:-1000} #35000 for full TF From 3b03926cb2dc8bad0727e0131bb95a500220e311 Mon Sep 17 00:00:00 2001 From: Francesco Noferini Date: Thu, 15 Apr 2021 10:10:07 +0200 Subject: [PATCH 153/770] add TOF cluster info reader --- Detectors/TOF/workflow/CMakeLists.txt | 7 +- .../TOFWorkflowUtils/CalibClusReaderSpec.h | 59 +++++++++++++ .../TOF/workflow/src/CalibClusReaderSpec.cxx | 86 +++++++++++++++++++ Detectors/TOF/workflow/src/cluscal-reader.cxx | 37 ++++++++ 4 files changed, 188 insertions(+), 1 deletion(-) create mode 100644 Detectors/TOF/workflow/include/TOFWorkflowUtils/CalibClusReaderSpec.h create mode 100644 Detectors/TOF/workflow/src/CalibClusReaderSpec.cxx create mode 100644 Detectors/TOF/workflow/src/cluscal-reader.cxx diff --git a/Detectors/TOF/workflow/CMakeLists.txt b/Detectors/TOF/workflow/CMakeLists.txt index 5bf8b38f0500a..ff9744e6be2ba 100644 --- a/Detectors/TOF/workflow/CMakeLists.txt +++ b/Detectors/TOF/workflow/CMakeLists.txt @@ -21,6 +21,7 @@ o2_add_library(TOFWorkflowUtils src/EntropyEncoderSpec.cxx src/EntropyDecoderSpec.cxx src/TOFCalClusInfoWriterSpec.cxx + src/CalibClusReaderSpec.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DPLUtils O2::TOFBase O2::DataFormatsTOF O2::TOFReconstruction) o2_add_executable(entropy-encoder-workflow @@ -38,8 +39,12 @@ o2_add_executable(cluster-writer-workflow COMPONENT_NAME tof PUBLIC_LINK_LIBRARIES O2::TOFWorkflowUtils) -o2_add_executable(cluster-calib +o2_add_executable(cluster-calib-workflow SOURCES src/cluster-calib.cxx COMPONENT_NAME tof PUBLIC_LINK_LIBRARIES O2::TOFWorkflowUtils) +o2_add_executable(cluscal-reader-workflow + SOURCES src/cluscal-reader.cxx + COMPONENT_NAME tof + PUBLIC_LINK_LIBRARIES O2::TOFWorkflowUtils) diff --git a/Detectors/TOF/workflow/include/TOFWorkflowUtils/CalibClusReaderSpec.h b/Detectors/TOF/workflow/include/TOFWorkflowUtils/CalibClusReaderSpec.h new file mode 100644 index 0000000000000..3df135e0a1747 --- /dev/null +++ b/Detectors/TOF/workflow/include/TOFWorkflowUtils/CalibClusReaderSpec.h @@ -0,0 +1,59 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file CalibClusReaderSpec.h + +#ifndef O2_TOF_CALIBCLUSREADER +#define O2_TOF_CALIBCLUSREADER + +#include "TFile.h" +#include "TTree.h" + +#include "Framework/ControlService.h" +#include "Framework/ConfigParamRegistry.h" +#include "Framework/DataProcessorSpec.h" +#include "Framework/Task.h" +#include "DataFormatsTOF/CosmicInfo.h" +#include "DataFormatsTOF/CalibInfoCluster.h" + +using namespace o2::framework; + +namespace o2 +{ +namespace tof +{ + +class CalibClusReader : public Task +{ + public: + CalibClusReader(bool isCosmics) : mIsCosmics(isCosmics) {} + ~CalibClusReader() override = default; + void init(InitContext& ic) final; + void run(ProcessingContext& pc) final; + + private: + void connectTree(const std::string& filename); + std::unique_ptr mFile = nullptr; + std::unique_ptr mTree = nullptr; + int mState = 0; + int mCurrentEntry = 0; + bool mIsCosmics = false; + std::vector mClusInfos, *mPclusInfos = &mClusInfos; + std::vector mCosmicInfo, *mPcosmicInfo = &mCosmicInfo; +}; + +/// create a processor spec +/// read cluster calib infos from a root file +DataProcessorSpec getCalibClusReaderSpec(bool isCosmics); + +} // namespace tof +} // namespace o2 + +#endif /* O2_TOF_CALIBCLUSREADER */ diff --git a/Detectors/TOF/workflow/src/CalibClusReaderSpec.cxx b/Detectors/TOF/workflow/src/CalibClusReaderSpec.cxx new file mode 100644 index 0000000000000..6c0cf94cc8ebc --- /dev/null +++ b/Detectors/TOF/workflow/src/CalibClusReaderSpec.cxx @@ -0,0 +1,86 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file CalibClusReaderSpec.cxx + +#include + +#include "Framework/ControlService.h" +#include "Framework/ConfigParamRegistry.h" +#include "TOFWorkflowUtils/CalibClusReaderSpec.h" +#include "Framework/Logger.h" + +using namespace o2::framework; +using namespace o2::tof; + +namespace o2 +{ +namespace tof +{ + +void CalibClusReader::init(InitContext& ic) +{ + LOG(INFO) << "Init Cluster reader!"; + auto filename = ic.options().get("tof-calclus-infile"); + connectTree(filename); +} + +void CalibClusReader::run(ProcessingContext& pc) +{ + auto ent = mTree->GetReadEntry() + 1; + assert(ent < mTree->GetEntries()); // this should not happen + mTree->GetEntry(ent); + LOG(INFO) << "Pushing " << mPclusInfos->size() << " TOF clusters calib info at entry " << ent; + pc.outputs().snapshot(Output{o2::header::gDataOriginTOF, "INFOCALCLUS", 0, Lifetime::Timeframe}, mClusInfos); + + if (mIsCosmics) { + LOG(INFO) << "Pushing " << mPcosmicInfo->size() << " TOF cosmics info at entry " << ent; + pc.outputs().snapshot(Output{o2::header::gDataOriginTOF, "INFOCOSMICS", 0, Lifetime::Timeframe}, mCosmicInfo); + } + + if (mTree->GetReadEntry() + 1 >= mTree->GetEntries()) { + pc.services().get().endOfStream(); + pc.services().get().readyToQuit(QuitRequest::Me); + } +} + +void CalibClusReader::connectTree(const std::string& filename) +{ + mTree.reset(nullptr); // in case it was already loaded + mFile.reset(TFile::Open(filename.c_str())); + assert(mFile && !mFile->IsZombie()); + mTree.reset((TTree*)mFile->Get("o2sim")); + assert(mTree); + mTree->SetBranchAddress("TOFClusterCalInfo", &mPclusInfos); + if (mIsCosmics) { + mTree->SetBranchAddress("TOFCosmics", &mPcosmicInfo); + } + LOG(INFO) << "Loaded tree from " << filename << " with " << mTree->GetEntries() << " entries"; +} + +DataProcessorSpec getCalibClusReaderSpec(bool isCosmics) +{ + std::vector outputs; + outputs.emplace_back(o2::header::gDataOriginTOF, "INFOCALCLUS", 0, Lifetime::Timeframe); + if (isCosmics) { + outputs.emplace_back(o2::header::gDataOriginTOF, "INFOCOSMICS", 0, Lifetime::Timeframe); + } + + return DataProcessorSpec{ + "tof-calclus-reader", + Inputs{}, + outputs, + AlgorithmSpec{adaptFromTask(isCosmics)}, + Options{ + {"tof-calclus-infile", VariantType::String, "tofclusCalInfo.root", {"Name of the input file"}}}}; +} + +} // namespace tof +} // namespace o2 diff --git a/Detectors/TOF/workflow/src/cluscal-reader.cxx b/Detectors/TOF/workflow/src/cluscal-reader.cxx new file mode 100644 index 0000000000000..d76b8c3c419d7 --- /dev/null +++ b/Detectors/TOF/workflow/src/cluscal-reader.cxx @@ -0,0 +1,37 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "TOFWorkflowUtils/CalibClusReaderSpec.h" +#include "CommonUtils/ConfigurableParam.h" +#include "Framework/ConfigParamSpec.h" + +using namespace o2::framework; + +// ------------------------------------------------------------------ + +// we need to add workflow options before including Framework/runDataProcessing +void customize(std::vector& workflowOptions) +{ + // option allowing to set parameters + workflowOptions.push_back(ConfigParamSpec{"cosmics", o2::framework::VariantType::Bool, false, {"If it has cosmics infos"}}); +} + +// ------------------------------------------------------------------ + +#include "Framework/runDataProcessing.h" + +WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) +{ + WorkflowSpec wf; + // Update the (declared) parameters if changed from the command line + auto isCosmics = cfgc.options().get("cosmics"); + wf.emplace_back(o2::tof::getCalibClusReaderSpec(isCosmics)); + return wf; +} From 08140d652d01c3d568c6269373ea4c8cf51bf450 Mon Sep 17 00:00:00 2001 From: Nazar Burmasov Date: Sat, 17 Apr 2021 17:46:43 +0200 Subject: [PATCH 154/770] Fix for the out-of-bounds access bug --- Detectors/AOD/src/AODProducerWorkflowSpec.cxx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Detectors/AOD/src/AODProducerWorkflowSpec.cxx b/Detectors/AOD/src/AODProducerWorkflowSpec.cxx index fe81361da901b..602fbf289e5e1 100644 --- a/Detectors/AOD/src/AODProducerWorkflowSpec.cxx +++ b/Detectors/AOD/src/AODProducerWorkflowSpec.cxx @@ -485,7 +485,9 @@ void AODProducerWorkflowDPL::run(ProcessingContext& pc) uint64_t firstVtxGlBC = minGlBC; uint64_t startBCofTF = startIR.toLong(); - firstVtxGlBC = std::round(startBCofTF + primVertices[0].getTimeStamp().getTimeStamp() / o2::constants::lhc::LHCBunchSpacingMUS); + if (!primVertices.empty()) { + firstVtxGlBC = std::round(startBCofTF + primVertices[0].getTimeStamp().getTimeStamp() / o2::constants::lhc::LHCBunchSpacingMUS); + } uint64_t tfNumber; int runNumber = 244918; // TODO: get real run number From 874f72f0e6307c1edddba423a807f753e08479eb Mon Sep 17 00:00:00 2001 From: Laurent Aphecetche Date: Sat, 17 Apr 2021 10:57:38 +0200 Subject: [PATCH 155/770] [MCH] Promote digit saturation to its own data member --- DataFormats/Detectors/MUON/MCH/CMakeLists.txt | 7 ++ .../MUON/MCH/include/DataFormatsMCH/Digit.h | 10 ++- DataFormats/Detectors/MUON/MCH/src/Digit.cxx | 36 +++++++--- .../Detectors/MUON/MCH/src/testDigit.cxx | 68 +++++++++++++++++++ 4 files changed, 109 insertions(+), 12 deletions(-) create mode 100644 DataFormats/Detectors/MUON/MCH/src/testDigit.cxx diff --git a/DataFormats/Detectors/MUON/MCH/CMakeLists.txt b/DataFormats/Detectors/MUON/MCH/CMakeLists.txt index 094a815c5cad5..212b779d33e8e 100644 --- a/DataFormats/Detectors/MUON/MCH/CMakeLists.txt +++ b/DataFormats/Detectors/MUON/MCH/CMakeLists.txt @@ -22,3 +22,10 @@ o2_add_executable(convert-bad-channels SOURCES src/convert-bad-channels.cxx COMPONENT_NAME mch PUBLIC_LINK_LIBRARIES O2::DataFormatsMCH Boost::program_options) + +o2_add_test(digit + SOURCES src/testDigit.cxx + PUBLIC_LINK_LIBRARIES O2::MCHBase + COMPONENT_NAME mch + LABELS muon;mch) + diff --git a/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/Digit.h b/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/Digit.h index 0be8764a664d7..68ffef16f8b54 100644 --- a/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/Digit.h +++ b/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/Digit.h @@ -17,6 +17,7 @@ #define ALICEO2_MCH_BASE_DIGIT_H_ #include "Rtypes.h" +#include namespace o2 { @@ -40,10 +41,10 @@ class Digit int32_t getTime() const { return mTFtime; } void setNofSamples(uint16_t n); - uint16_t nofSamples() const { return (mNofSamples & 0x7FFF); } + uint16_t nofSamples() const; void setSaturated(bool sat); - bool isSaturated() const { return ((mNofSamples & 0x8000) > 0); } + bool isSaturated() const; int getDetID() const { return mDetID; } @@ -56,13 +57,16 @@ class Digit private: int32_t mTFtime; /// time since the beginning of the time frame, in bunch crossing units uint16_t mNofSamples; /// number of samples in the signal + bool mIsSaturated; /// whether or not the digit amplitude is above saturation int mDetID; /// ID of the Detection Element to which the digit corresponds to int mPadID; /// PadIndex to which the digit corresponds to uint32_t mADC; /// Amplitude of signal - ClassDefNV(Digit, 3); + ClassDefNV(Digit, 4); }; //class Digit +std::ostream& operator<<(std::ostream& os, const Digit& d); + } //namespace mch } //namespace o2 #endif // ALICEO2_MCH_DIGIT_H_ diff --git a/DataFormats/Detectors/MUON/MCH/src/Digit.cxx b/DataFormats/Detectors/MUON/MCH/src/Digit.cxx index c0e5106cc6f04..92a1f81133448 100644 --- a/DataFormats/Detectors/MUON/MCH/src/Digit.cxx +++ b/DataFormats/Detectors/MUON/MCH/src/Digit.cxx @@ -10,35 +10,53 @@ #include "DataFormatsMCH/Digit.h" #include +#include +#include namespace o2::mch { +std::ostream& operator<<(std::ostream& os, const o2::mch::Digit& d) +{ + os << fmt::format("DetID {:4d} PadId {:6d} ADC {:10d} TFtime {:10d} NofSamples {:5d} {}", + d.getDetID(), d.getPadID(), d.getADC(), d.getTime(), d.nofSamples(), + d.isSaturated() ? "(S)" : ""); + return os; +} + bool closeEnough(double x, double y, double eps = 1E-6) { return std::fabs(x - y) <= eps * std::max(1.0, std::max(std::fabs(x), std::fabs(y))); } Digit::Digit(int detid, int pad, uint32_t adc, int32_t time, uint16_t nSamples, bool saturated) - : mTFtime(time), mDetID(detid), mPadID(pad), mADC(adc) + : mTFtime(time), mNofSamples(nSamples), mIsSaturated(saturated), mDetID(detid), mPadID(pad), mADC(adc) { setNofSamples(nSamples); - setSaturated(saturated); +} + +uint16_t Digit::nofSamples() const +{ + return mNofSamples; +} + +bool Digit::isSaturated() const +{ + return mIsSaturated; } void Digit::setNofSamples(uint16_t n) { - uint16_t sat = mNofSamples & 0x8000; - mNofSamples = (n & 0x7FFF) + sat; + constexpr uint64_t max10bits = (static_cast(1) << 10); + if (static_cast(n) >= max10bits) { + throw std::invalid_argument("mch digit nofsamples must fit within 10 bits"); + } + mNofSamples = n; } void Digit::setSaturated(bool sat) { - if (sat) { - mNofSamples |= 0x8000; - } else { - mNofSamples &= 0x7FFF; - } + mIsSaturated = sat; } bool Digit::operator==(const Digit& other) const diff --git a/DataFormats/Detectors/MUON/MCH/src/testDigit.cxx b/DataFormats/Detectors/MUON/MCH/src/testDigit.cxx new file mode 100644 index 0000000000000..72d161e36acee --- /dev/null +++ b/DataFormats/Detectors/MUON/MCH/src/testDigit.cxx @@ -0,0 +1,68 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include +#define BOOST_TEST_MODULE MCH Digit +#define BOOST_TEST_DYN_LINK +#include +#include +#include + +#include "DataFormatsMCH/Digit.h" + +int dummyDetId{712}; +int dummyPadId{0}; +unsigned long dummyADC{0}; +uint32_t dummyTime{0}; +uint16_t dummyNofSamples{0}; + +BOOST_AUTO_TEST_CASE(NofSamplesMustFitWithin10Bits) +{ + BOOST_CHECK_THROW(o2::mch::Digit d(dummyDetId, dummyPadId, dummyADC, dummyTime, 1025), std::invalid_argument); +} + +BOOST_AUTO_TEST_CASE(DefaultConstructorMakesNonSaturatedDigit) +{ + o2::mch::Digit d(dummyDetId, dummyPadId, dummyADC, dummyTime, dummyNofSamples); + BOOST_CHECK(d.isSaturated() == false); +} + +std::vector nsamples{ + 1 << 0, + 1 << 1, + 1 << 2, + 1 << 3, + 1 << 4, + 1 << 5, + 1 << 6, + 1 << 7, + 1 << 8, + 1 << 9}; + +BOOST_DATA_TEST_CASE(DefaultConstructorNofSamplesIsInvariant, + boost::unit_test::data::make(nsamples), nofSamples) +{ + o2::mch::Digit d(dummyDetId, dummyPadId, dummyADC, dummyTime, nofSamples); + BOOST_CHECK_EQUAL(d.nofSamples(), nofSamples); +} + +BOOST_DATA_TEST_CASE(SetSaturatedDoesNotAffectPublicNofSamples, + boost::unit_test::data::make(nsamples), nofSamples) +{ + o2::mch::Digit d(dummyDetId, dummyPadId, dummyADC, dummyTime, nofSamples); + + BOOST_TEST_INFO("setting saturation to true"); + d.setSaturated(true); + BOOST_CHECK_EQUAL(d.nofSamples(), nofSamples); + + BOOST_TEST_INFO("setting saturation to false"); + d.setSaturated(false); + BOOST_CHECK_EQUAL(d.nofSamples(), nofSamples); +} From f84f284ea36703a4bbf07f9dc87b8b9ba6e9e8a2 Mon Sep 17 00:00:00 2001 From: Laurent Aphecetche Date: Sat, 17 Apr 2021 11:05:11 +0200 Subject: [PATCH 156/770] [CTF] Add --no-grp option (to be used together with e.g. --onlyDet) --- .../CTF/workflow/src/ctf-writer-workflow.cxx | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/Detectors/CTF/workflow/src/ctf-writer-workflow.cxx b/Detectors/CTF/workflow/src/ctf-writer-workflow.cxx index 660591236d543..59703d645c946 100644 --- a/Detectors/CTF/workflow/src/ctf-writer-workflow.cxx +++ b/Detectors/CTF/workflow/src/ctf-writer-workflow.cxx @@ -31,6 +31,7 @@ void customize(std::vector& workflowOptions) options.push_back(ConfigParamSpec{"skipDet", VariantType::String, std::string{DetID::NONE}, {"comma separate list of detectors to skip"}}); options.push_back(ConfigParamSpec{"dict-per-det", VariantType::Bool, false, {"create dictionary file per detector"}}); options.push_back(ConfigParamSpec{"grpfile", VariantType::String, o2::base::NameConf::getGRPFileName(), {"name of the grp file"}}); + options.push_back(ConfigParamSpec{"no-grp", VariantType::Bool, false, {"do not read GRP file"}}); options.push_back(ConfigParamSpec{"output-type", VariantType::String, "ctf", {"output types: ctf (per TF) or dict (create dictionaries) or both or none"}}); std::swap(workflowOptions, options); } @@ -44,8 +45,23 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) long run = 0; bool doCTF = true, doDict = false, dictPerDet = false; if (!configcontext.helpOnCommandLine()) { - std::unique_ptr grp(o2::parameters::GRPObject::loadFrom(configcontext.options().get("grpfile"))); - dets = grp->getDetsReadOut(configcontext.options().get("onlyDet"), configcontext.options().get("skipDet")); + bool noGRP = configcontext.options().get("no-grp"); + auto onlyDet = configcontext.options().get("onlyDet"); + if (!noGRP) { + std::unique_ptr grp(o2::parameters::GRPObject::loadFrom(configcontext.options().get("grpfile"))); + dets = grp->getDetsReadOut(onlyDet, configcontext.options().get("skipDet")); + run = grp->getRun(); + } else { + dets.set(); // by default read all + auto mskOnly = DetID::getMask(configcontext.options().get("onlyDet")); + auto mskSkip = DetID::getMask(configcontext.options().get("skipDet")); + if (mskOnly.any()) { + dets &= mskOnly; + } else { + dets ^= mskSkip; + } + run = 0; + } auto outmode = configcontext.options().get("output-type"); dictPerDet = configcontext.options().get("dict-per-det"); if (outmode == "ctf") { @@ -63,7 +79,6 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) } else { throw std::invalid_argument("Invalid output-type"); } - run = grp->getRun(); } WorkflowSpec specs{o2::ctf::getCTFWriterSpec(dets, run, doCTF, doDict, dictPerDet)}; return std::move(specs); From c917f7450dfd33679a02b84f6af6c1614517695d Mon Sep 17 00:00:00 2001 From: Laurent Aphecetche Date: Sat, 17 Apr 2021 11:26:17 +0200 Subject: [PATCH 157/770] [MRRTF-109] Add MCH CTF --- DataFormats/Detectors/MUON/MCH/CMakeLists.txt | 9 +- .../MUON/MCH/include/DataFormatsMCH/CTF.h | 59 +++++ .../MCH/include/DataFormatsMCH/ROFRecord.h | 11 + DataFormats/Detectors/MUON/MCH/src/CTF.cxx | 24 ++ .../MUON/MCH/src/DataFormatsMCHLinkDef.h | 3 + .../Detectors/MUON/MCH/src/ROFRecord.cxx | 23 ++ Detectors/CTF/CMakeLists.txt | 24 +- Detectors/CTF/test/test_ctf_io_mch.cxx | 108 +++++++++ Detectors/CTF/workflow/CMakeLists.txt | 1 + Detectors/CTF/workflow/src/CTFReaderSpec.cxx | 8 + Detectors/CTF/workflow/src/CTFWriterSpec.cxx | 4 +- .../CTF/workflow/src/ctf-reader-workflow.cxx | 4 + Detectors/MUON/MCH/CMakeLists.txt | 1 + Detectors/MUON/MCH/CTF/CMakeLists.txt | 19 ++ Detectors/MUON/MCH/CTF/README.md | 78 +++++++ .../MUON/MCH/CTF/include/MCHCTF/CTFCoder.h | 163 +++++++++++++ .../MUON/MCH/CTF/include/MCHCTF/CTFHelper.h | 217 +++++++++++++++++ Detectors/MUON/MCH/CTF/src/CTFCoder.cxx | 81 +++++++ Detectors/MUON/MCH/CTF/src/CTFHelper.cxx | 15 ++ Detectors/MUON/MCH/CTF/test/circular-test.sh | 221 ++++++++++++++++++ Detectors/MUON/MCH/Workflow/CMakeLists.txt | 8 +- Detectors/MUON/MCH/Workflow/README.md | 11 + .../include/MCHWorkflow/EntropyDecoderSpec.h | 29 +++ .../MCH/Workflow/src/EntropyDecoderSpec.cxx | 96 ++++++++ .../Workflow/src/entropy-encoder-workflow.cxx | 120 ++++++++++ 25 files changed, 1323 insertions(+), 14 deletions(-) create mode 100644 DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/CTF.h create mode 100644 DataFormats/Detectors/MUON/MCH/src/CTF.cxx create mode 100644 DataFormats/Detectors/MUON/MCH/src/ROFRecord.cxx create mode 100644 Detectors/CTF/test/test_ctf_io_mch.cxx create mode 100644 Detectors/MUON/MCH/CTF/CMakeLists.txt create mode 100644 Detectors/MUON/MCH/CTF/README.md create mode 100644 Detectors/MUON/MCH/CTF/include/MCHCTF/CTFCoder.h create mode 100644 Detectors/MUON/MCH/CTF/include/MCHCTF/CTFHelper.h create mode 100644 Detectors/MUON/MCH/CTF/src/CTFCoder.cxx create mode 100644 Detectors/MUON/MCH/CTF/src/CTFHelper.cxx create mode 100644 Detectors/MUON/MCH/CTF/test/circular-test.sh create mode 100644 Detectors/MUON/MCH/Workflow/include/MCHWorkflow/EntropyDecoderSpec.h create mode 100644 Detectors/MUON/MCH/Workflow/src/EntropyDecoderSpec.cxx create mode 100644 Detectors/MUON/MCH/Workflow/src/entropy-encoder-workflow.cxx diff --git a/DataFormats/Detectors/MUON/MCH/CMakeLists.txt b/DataFormats/Detectors/MUON/MCH/CMakeLists.txt index 212b779d33e8e..31f318c7f564c 100644 --- a/DataFormats/Detectors/MUON/MCH/CMakeLists.txt +++ b/DataFormats/Detectors/MUON/MCH/CMakeLists.txt @@ -9,14 +9,17 @@ # submit itself to any jurisdiction. o2_add_library(DataFormatsMCH - SOURCES src/TrackMCH.cxx src/Digit.cxx - PUBLIC_LINK_LIBRARIES O2::CommonDataFormat) + SOURCES src/TrackMCH.cxx src/Digit.cxx + src/CTF.cxx src/ROFRecord.cxx + PUBLIC_LINK_LIBRARIES O2::CommonDataFormat + O2::DetectorsCommonDataFormats) o2_target_root_dictionary(DataFormatsMCH HEADERS include/DataFormatsMCH/Digit.h include/DataFormatsMCH/DsChannelGroup.h include/DataFormatsMCH/ROFRecord.h - include/DataFormatsMCH/TrackMCH.h) + include/DataFormatsMCH/TrackMCH.h + include/DataFormatsMCH/CTF.h) o2_add_executable(convert-bad-channels SOURCES src/convert-bad-channels.cxx diff --git a/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/CTF.h b/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/CTF.h new file mode 100644 index 0000000000000..c707f4c14e9b8 --- /dev/null +++ b/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/CTF.h @@ -0,0 +1,59 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file CTF.h +/// \author ruben.shahoyan@cern.ch +/// \brief Definitions for MCH CTF data + +#ifndef O2_MCH_CTF_H +#define O2_MCH_CTF_H + +#include +#include +#include "DetectorsCommonDataFormats/EncodedBlocks.h" +#include + +namespace o2 +{ +namespace mch +{ + +/// Header for a single CTF +struct CTFHeader { + uint32_t nROFs = 0; /// number of ROFrames in TF + uint32_t nDigits = 0; /// number of digits in TF + uint32_t firstOrbit = 0; /// 1st orbit of TF + uint16_t firstBC = 0; /// 1st BC of TF + + ClassDefNV(CTFHeader, 1); +}; + +/// wrapper for the Entropy-encoded clusters of the TF +struct CTF : public o2::ctf::EncodedBlocks { + + static constexpr size_t N = getNBlocks(); + enum Slots { BLC_bcIncROF, + BLC_orbitIncROF, + BLC_nDigitsROF, + BLC_tfTime, + BLC_nSamples, + BLC_isSaturated, + BLC_detID, + BLC_padID, + BLC_ADC }; + ClassDefNV(CTF, 1); +}; + +std::ostream& operator<<(std::ostream&, const CTFHeader&); + +} // namespace mch +} // namespace o2 + +#endif diff --git a/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/ROFRecord.h b/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/ROFRecord.h index e545cc9e6149d..0a9420733893d 100644 --- a/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/ROFRecord.h +++ b/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/ROFRecord.h @@ -18,6 +18,9 @@ #include "CommonDataFormat/InteractionRecord.h" #include "CommonDataFormat/RangeReference.h" +#include + +#include namespace o2 { @@ -51,6 +54,12 @@ class ROFRecord /// set the number of associated objects and the index of the first one void setDataRef(int firstIdx, int nEntries) { mDataRef.set(firstIdx, nEntries); } + bool operator==(const ROFRecord& other) const + { + return mBCData == other.mBCData && + mDataRef == other.mDataRef; + } + private: BCData mBCData{}; ///< interaction record DataRef mDataRef{}; ///< reference to the associated objects @@ -58,6 +67,8 @@ class ROFRecord ClassDefNV(ROFRecord, 1); }; +std::ostream& operator<<(std::ostream& os, const ROFRecord& rof); + } // namespace mch } // namespace o2 diff --git a/DataFormats/Detectors/MUON/MCH/src/CTF.cxx b/DataFormats/Detectors/MUON/MCH/src/CTF.cxx new file mode 100644 index 0000000000000..d22806fa87bcf --- /dev/null +++ b/DataFormats/Detectors/MUON/MCH/src/CTF.cxx @@ -0,0 +1,24 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include +#include +#include "DataFormatsMCH/CTF.h" +#include + +namespace o2::mch +{ +std::ostream& operator<<(std::ostream& os, const CTFHeader& ctf) +{ + os << fmt::format("nROFS {} nDigits {} firstOrbit {} firstBC {}", + ctf.nROFs, ctf.nDigits, ctf.firstOrbit, ctf.firstBC); + return os; +} +} // namespace o2::mch diff --git a/DataFormats/Detectors/MUON/MCH/src/DataFormatsMCHLinkDef.h b/DataFormats/Detectors/MUON/MCH/src/DataFormatsMCHLinkDef.h index e67cf0af64fe8..8043f514a711a 100644 --- a/DataFormats/Detectors/MUON/MCH/src/DataFormatsMCHLinkDef.h +++ b/DataFormats/Detectors/MUON/MCH/src/DataFormatsMCHLinkDef.h @@ -20,5 +20,8 @@ #pragma link C++ class o2::mch::DsChannelGroup + ; #pragma link C++ class o2::mch::Digit + ; #pragma link C++ class std::vector < o2::mch::Digit> + ; +#pragma link C++ struct o2::mch::CTFHeader + ; +#pragma link C++ struct o2::mch::CTF + ; +#pragma link C++ class o2::ctf::EncodedBlocks < o2::mch::CTFHeader, 9, uint32_t> + ; #endif diff --git a/DataFormats/Detectors/MUON/MCH/src/ROFRecord.cxx b/DataFormats/Detectors/MUON/MCH/src/ROFRecord.cxx new file mode 100644 index 0000000000000..a869fe4d166bd --- /dev/null +++ b/DataFormats/Detectors/MUON/MCH/src/ROFRecord.cxx @@ -0,0 +1,23 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "DataFormatsMCH/ROFRecord.h" +#include +#include + +namespace o2::mch +{ +std::ostream& operator<<(std::ostream& os, const ROFRecord& rof) +{ + os << fmt::format("{} FirstIdx: {:5d} LastIdx: {:5d}", + rof.getBCData().asString(), rof.getFirstIdx(), rof.getLastIdx()); + return os; +} +} // namespace o2::mch diff --git a/Detectors/CTF/CMakeLists.txt b/Detectors/CTF/CMakeLists.txt index 389aabf2bca7c..303bcf1ff93d2 100644 --- a/Detectors/CTF/CMakeLists.txt +++ b/Detectors/CTF/CMakeLists.txt @@ -23,21 +23,21 @@ o2_add_test(tpc SOURCES test/test_ctf_io_tpc.cxx COMPONENT_NAME ctf LABELS ctf) - + o2_add_test(ft0 PUBLIC_LINK_LIBRARIES O2::FT0Reconstruction O2::DataFormatsFT0 SOURCES test/test_ctf_io_ft0.cxx COMPONENT_NAME ctf LABELS ctf) - + o2_add_test(fv0 PUBLIC_LINK_LIBRARIES O2::FV0Reconstruction O2::DataFormatsFV0 SOURCES test/test_ctf_io_fv0.cxx COMPONENT_NAME ctf LABELS ctf) - + o2_add_test(fdd PUBLIC_LINK_LIBRARIES O2::FDDReconstruction O2::DataFormatsFDD @@ -58,15 +58,21 @@ o2_add_test(mid O2::MIDCTF SOURCES test/test_ctf_io_mid.cxx COMPONENT_NAME ctf - LABELS ctf) - + LABELS ctf;muon;mid) + +o2_add_test(mch + PUBLIC_LINK_LIBRARIES O2::MCHCTF + SOURCES test/test_ctf_io_mch.cxx + COMPONENT_NAME ctf + LABELS ctf;muon;mch) + o2_add_test(emcal PUBLIC_LINK_LIBRARIES O2::DataFormatsEMCAL O2::EMCALReconstruction SOURCES test/test_ctf_io_emcal.cxx COMPONENT_NAME ctf LABELS ctf) - + o2_add_test(phos PUBLIC_LINK_LIBRARIES O2::DataFormatsPHOS O2::PHOSReconstruction @@ -80,14 +86,14 @@ o2_add_test(cpv SOURCES test/test_ctf_io_cpv.cxx COMPONENT_NAME ctf LABELS ctf) - + o2_add_test(zdc PUBLIC_LINK_LIBRARIES O2::DataFormatsZDC O2::ZDCReconstruction SOURCES test/test_ctf_io_zdc.cxx COMPONENT_NAME ctf LABELS ctf) - + o2_add_test(trd PUBLIC_LINK_LIBRARIES O2::CTFWorkflow O2::DataFormatsTRD @@ -95,7 +101,7 @@ o2_add_test(trd SOURCES test/test_ctf_io_trd.cxx COMPONENT_NAME ctf LABELS ctf) - + o2_add_test(hmpid PUBLIC_LINK_LIBRARIES O2::CTFWorkflow O2::DataFormatsHMP diff --git a/Detectors/CTF/test/test_ctf_io_mch.cxx b/Detectors/CTF/test/test_ctf_io_mch.cxx new file mode 100644 index 0000000000000..ca8772a00c22d --- /dev/null +++ b/Detectors/CTF/test/test_ctf_io_mch.cxx @@ -0,0 +1,108 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#define BOOST_TEST_MODULE Test MCHCTFIO +#define BOOST_TEST_MAIN +#define BOOST_TEST_DYN_LINK +#include +#include "DetectorsCommonDataFormats/NameConf.h" +#include "MCHCTF/CTFCoder.h" +#include "DataFormatsMCH/CTF.h" +#include "DataFormatsMCH/ROFRecord.h" +#include "DataFormatsMCH/Digit.h" +#include "Framework/Logger.h" +#include +#include +#include +#include +#include + +using namespace o2::mch; + +BOOST_AUTO_TEST_CASE(CTFTest, *boost::unit_test::enabled()) +{ + std::vector rofs; + std::vector digs; + TStopwatch sw; + sw.Start(); + o2::InteractionRecord ir0(3, 5), ir(ir0); + + for (int irof = 0; irof < 1000; irof++) { + ir += 1 + gRandom->Integer(200); + int nch = 0; + while (nch == 0) { + nch = gRandom->Poisson(20); + } + int start = digs.size(); + for (int ich = 0; ich < nch; ich++) { + int16_t detID = 100 + gRandom->Integer(1025 - 100); + int16_t padID = gRandom->Integer(28672); + int32_t tfTime = ir.differenceInBC(ir0); + uint32_t adc = gRandom->Integer(1024 * 1024); + uint16_t nsamp = gRandom->Integer(1024); + auto& d = digs.emplace_back(detID, padID, adc, tfTime, nsamp); + bool sat = gRandom->Rndm() > 0.9; + d.setSaturated(sat); + } + rofs.emplace_back(ir, start, nch); + } + + sw.Start(); + std::vector vec; + { + CTFCoder coder; + coder.encode(vec, rofs, digs); // compress + } + sw.Stop(); + LOG(INFO) << "Compressed in " << sw.CpuTime() << " s"; + + // writing + { + sw.Start(); + auto* ctfImage = o2::mch::CTF::get(vec.data()); + TFile flOut("test_ctf_mch.root", "recreate"); + TTree ctfTree(std::string(o2::base::NameConf::CTFTREENAME).c_str(), "O2 CTF tree"); + ctfImage->print(); + ctfImage->appendToTree(ctfTree, "MCH"); + ctfTree.Write(); + sw.Stop(); + LOG(INFO) << "Wrote to tree in " << sw.CpuTime() << " s"; + } + + // reading + vec.clear(); + { + sw.Start(); + TFile flIn("test_ctf_mch.root"); + std::unique_ptr tree((TTree*)flIn.Get(std::string(o2::base::NameConf::CTFTREENAME).c_str())); + BOOST_CHECK(tree); + o2::mch::CTF::readFromTree(vec, *(tree.get()), "MCH"); + sw.Stop(); + LOG(INFO) << "Read back from tree in " << sw.CpuTime() << " s"; + } + + std::vector rofsD; + std::vector digsD; + + sw.Start(); + const auto ctfImage = o2::mch::CTF::getImage(vec.data()); + { + CTFCoder coder; + coder.decode(ctfImage, rofsD, digsD); // decompress + } + sw.Stop(); + LOG(INFO) << "Decompressed in " << sw.CpuTime() << " s"; + + LOG(INFO) << " BOOST_CHECK rofsD.size() " << rofsD.size() << " rofs.size() " << rofs.size() + << " BOOST_CHECK(digsD.size() " << digsD.size() << " digs.size()) " << digs.size(); + + BOOST_TEST(rofs == rofsD, boost::test_tools::per_element()); + BOOST_TEST(digs == digsD, boost::test_tools::per_element()); +} diff --git a/Detectors/CTF/workflow/CMakeLists.txt b/Detectors/CTF/workflow/CMakeLists.txt index ea5dcdfe51f98..36bec572920fa 100644 --- a/Detectors/CTF/workflow/CMakeLists.txt +++ b/Detectors/CTF/workflow/CMakeLists.txt @@ -33,6 +33,7 @@ o2_add_library(CTFWorkflow O2::FV0Workflow O2::FDDWorkflow O2::TOFWorkflow + O2::MCHWorkflow O2::MIDWorkflow O2::EMCALWorkflow O2::PHOSWorkflow diff --git a/Detectors/CTF/workflow/src/CTFReaderSpec.cxx b/Detectors/CTF/workflow/src/CTFReaderSpec.cxx index 14e7aea10fd91..a615a0d077a3d 100644 --- a/Detectors/CTF/workflow/src/CTFReaderSpec.cxx +++ b/Detectors/CTF/workflow/src/CTFReaderSpec.cxx @@ -31,6 +31,7 @@ #include "DataFormatsFDD/CTF.h" #include "DataFormatsTOF/CTF.h" #include "DataFormatsMID/CTF.h" +#include "DataFormatsMCH/CTF.h" #include "DataFormatsEMCAL/CTF.h" #include "DataFormatsPHOS/CTF.h" #include "DataFormatsCPV/CTF.h" @@ -199,6 +200,13 @@ void CTFReaderSpec::run(ProcessingContext& pc) setFirstTFOrbit(det.getName()); } + det = DetID::MCH; + if (detsTF[det]) { + auto& bufVec = pc.outputs().make>({det.getName()}, sizeof(o2::mch::CTF)); + o2::mch::CTF::readFromTree(bufVec, *(tree.get()), det.getName()); + setFirstTFOrbit(det.getName()); + } + det = DetID::EMC; if (detsTF[det]) { auto& bufVec = pc.outputs().make>({det.getName()}, sizeof(o2::emcal::CTF)); diff --git a/Detectors/CTF/workflow/src/CTFWriterSpec.cxx b/Detectors/CTF/workflow/src/CTFWriterSpec.cxx index 32193b3751eb0..b3b3a3cb875d2 100644 --- a/Detectors/CTF/workflow/src/CTFWriterSpec.cxx +++ b/Detectors/CTF/workflow/src/CTFWriterSpec.cxx @@ -16,7 +16,6 @@ #include "Framework/InputSpec.h" #include "CTFWorkflow/CTFWriterSpec.h" -#include "DataFormatsParameters/GRPObject.h" #include "DetectorsCommonDataFormats/CTFHeader.h" #include "DetectorsCommonDataFormats/NameConf.h" #include "DetectorsCommonDataFormats/EncodedBlocks.h" @@ -30,6 +29,7 @@ #include "DataFormatsFDD/CTF.h" #include "DataFormatsTOF/CTF.h" #include "DataFormatsMID/CTF.h" +#include "DataFormatsMCH/CTF.h" #include "DataFormatsEMCAL/CTF.h" #include "DataFormatsPHOS/CTF.h" #include "DataFormatsCPV/CTF.h" @@ -226,6 +226,7 @@ void CTFWriterSpec::run(ProcessingContext& pc) processDet(pc, DetID::FV0, header, treeOut.get()); processDet(pc, DetID::FDD, header, treeOut.get()); processDet(pc, DetID::MID, header, treeOut.get()); + processDet(pc, DetID::MCH, header, treeOut.get()); processDet(pc, DetID::EMC, header, treeOut.get()); processDet(pc, DetID::PHS, header, treeOut.get()); processDet(pc, DetID::CPV, header, treeOut.get()); @@ -301,6 +302,7 @@ void CTFWriterSpec::storeDictionaries() storeDictionary(DetID::FV0, header); storeDictionary(DetID::FDD, header); storeDictionary(DetID::MID, header); + storeDictionary(DetID::MCH, header); storeDictionary(DetID::EMC, header); storeDictionary(DetID::PHS, header); storeDictionary(DetID::CPV, header); diff --git a/Detectors/CTF/workflow/src/ctf-reader-workflow.cxx b/Detectors/CTF/workflow/src/ctf-reader-workflow.cxx index ee30a1165764c..b0a60fcbac9d1 100644 --- a/Detectors/CTF/workflow/src/ctf-reader-workflow.cxx +++ b/Detectors/CTF/workflow/src/ctf-reader-workflow.cxx @@ -29,6 +29,7 @@ #include "FDDWorkflow/EntropyDecoderSpec.h" #include "TOFWorkflowUtils/EntropyDecoderSpec.h" #include "MIDWorkflow/EntropyDecoderSpec.h" +#include "MCHWorkflow/EntropyDecoderSpec.h" #include "EMCALWorkflow/EntropyDecoderSpec.h" #include "PHOSWorkflow/EntropyDecoderSpec.h" #include "CPVWorkflow/EntropyDecoderSpec.h" @@ -103,6 +104,9 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) if (dets[DetID::MID]) { specs.push_back(o2::mid::getEntropyDecoderSpec()); } + if (dets[DetID::MCH]) { + specs.push_back(o2::mch::getEntropyDecoderSpec()); + } if (dets[DetID::EMC]) { specs.push_back(o2::emcal::getEntropyDecoderSpec()); } diff --git a/Detectors/MUON/MCH/CMakeLists.txt b/Detectors/MUON/MCH/CMakeLists.txt index f7ed4c12ed1a7..f8f78fbb9c993 100644 --- a/Detectors/MUON/MCH/CMakeLists.txt +++ b/Detectors/MUON/MCH/CMakeLists.txt @@ -17,6 +17,7 @@ add_subdirectory(Clustering) add_subdirectory(Simulation) add_subdirectory(Tracking) add_subdirectory(Raw) +add_subdirectory(CTF) add_subdirectory(Workflow) add_subdirectory(Conditions) add_subdirectory(Calibration) diff --git a/Detectors/MUON/MCH/CTF/CMakeLists.txt b/Detectors/MUON/MCH/CTF/CMakeLists.txt new file mode 100644 index 0000000000000..5ab7ec83b79c5 --- /dev/null +++ b/Detectors/MUON/MCH/CTF/CMakeLists.txt @@ -0,0 +1,19 @@ +# Copyright CERN and copyright holders of ALICE O2. This software is distributed +# under the terms of the GNU General Public License v3 (GPL Version 3), copied +# verbatim in the file "COPYING". +# +# See http://alice-o2.web.cern.ch/license for full licensing information. +# +# In applying this license CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization or +# submit itself to any jurisdiction. + +o2_add_library(MCHCTF + SOURCES src/CTFCoder.cxx src/CTFHelper.cxx + PUBLIC_LINK_LIBRARIES O2::DataFormatsMCH + O2::MCHBase + O2::DetectorsBase + O2::CommonDataFormat + O2::DetectorsCommonDataFormats + O2::rANS + ms_gsl::ms_gsl) diff --git a/Detectors/MUON/MCH/CTF/README.md b/Detectors/MUON/MCH/CTF/README.md new file mode 100644 index 0000000000000..6166d0c91dc88 --- /dev/null +++ b/Detectors/MUON/MCH/CTF/README.md @@ -0,0 +1,78 @@ + + +# MCH CTF + +This directory contains the classes to handle entropy encoding and decoding of +MCH digits (and their associated ROFRecord). + +# Circular test + +To idea of this test is to check that digits data stays unaltered when they go +through the encoding/decoding processing. + +``` +circular-test.sh [NROFPERTF] [NTF] [OCC] [SEED] +``` + +The [circular-test.sh](./test/circular-test.sh) script performs for a given set of +{ number of timeframes, number of rofs per timeframe, occupancy, seed }, a +variation of the operations described below. + +## Generate random digits and write them (debug binary format) + +``` +o2-mch-digits-random-generator-workflow -b + --nof-rofs-per-tf 3 + --max-nof-tfs 5 + --occupancy 0.01 + --seed 1 +| o2-mch-digits-writer-workflow -b + --binary-file-format 1 + --outfile digits_ref_rof_3_tf_5_occ_0.01_seed_1.data +``` + +Note the `--seed` option that _must_ be non-zero if you want to get +reproducible results when running several times. + + +## Read those digits and encode them in a CTF + +``` +o2-mch-digits-file-reader-workflow -b + --infile digits_ref.data +| o2-mch-entropy-encoder-workflow -b +| o2-ctf-writer-workflow -b + --onlyDet MCH --no-grp +``` + +## Read back the CTF, decode the digits, write them + +``` +o2-ctf-reader-workflow -b + --ctf-input o2_ctf_run00000000_orbit0000000000_tf0000000000.root +| o2-mch-digits-writer-workflow -b + --binary-file-format 1 + --outfile digits.data +``` + +## Dump the written digits in text form + +``` +o2-mch-digits-file-reader-workflow -b + --infile digits_ref.data +| o2-mch-digits-writer-workflow -b + --no-file + --txt + --print-digits +``` + +## Compare digits before after ctf encoding/decoding + +``` +ls -al digits.*data +shasum -a 256 digits*.data +``` + + diff --git a/Detectors/MUON/MCH/CTF/include/MCHCTF/CTFCoder.h b/Detectors/MUON/MCH/CTF/include/MCHCTF/CTFCoder.h new file mode 100644 index 0000000000000..d1077156c861a --- /dev/null +++ b/Detectors/MUON/MCH/CTF/include/MCHCTF/CTFCoder.h @@ -0,0 +1,163 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file CTFCoder.h +/// \author ruben.shahoyan@cern.ch +/// \brief class for entropy encoding/decoding of MCH digit data + +#ifndef O2_MCH_CTFCODER_H +#define O2_MCH_CTFCODER_H + +#include +#include +#include +#include +#include "DataFormatsMCH/CTF.h" +#include "DataFormatsMCH/ROFRecord.h" +#include "DataFormatsMCH/Digit.h" +#include "DetectorsCommonDataFormats/DetID.h" +#include "DetectorsBase/CTFCoderBase.h" +#include "MCHCTF/CTFHelper.h" +#include "rANS/rans.h" + +class TTree; + +namespace o2 +{ +namespace mch +{ + +class CTFCoder : public o2::ctf::CTFCoderBase +{ + public: + CTFCoder() : o2::ctf::CTFCoderBase(CTF::getNBlocks(), o2::detectors::DetID::MCH) {} + ~CTFCoder() = default; + + /// entropy-encode data to buffer with CTF + template + void encode(VEC& buff, const gsl::span& rofData, const gsl::span& digData); + + /// entropy decode data from buffer with CTF + template + void decode(const CTF::base& ec, VROF& rofVec, VCOL& digVec); + + void createCoders(const std::string& dictPath, o2::ctf::CTFCoderBase::OpType op); + + private: + void appendToTree(TTree& tree, CTF& ec); + void readFromTree(TTree& tree, int entry, std::vector& rofVec, std::vector& digVec); +}; + +/// entropy-encode clusters to buffer with CTF +template +void CTFCoder::encode(VEC& buff, const gsl::span& rofData, const gsl::span& digData) +{ + using MD = o2::ctf::Metadata::OptStore; + // what to do which each field: see o2::ctd::Metadata explanation + constexpr MD optField[CTF::getNBlocks()] = { + MD::EENCODE, // BLC_bcIncROF + MD::EENCODE, // BLC_orbitIncROF + MD::EENCODE, // BLC_nDigitsROF + MD::EENCODE, // BLC_tfTime + MD::EENCODE, // BLC_nSamples + MD::EENCODE, // BLC_isSaturated + MD::EENCODE, // BLC_detID + MD::EENCODE, // BLC_padID + MD::EENCODE // BLC_ADC + }; + CTFHelper helper(rofData, digData); + + // book output size with some margin + auto szIni = sizeof(CTFHeader) + helper.getSize() * 2. / 3; // will be autoexpanded if needed + buff.resize(szIni); + + auto ec = CTF::create(buff); + using ECB = CTF::base; + + ec->setHeader(helper.createHeader()); + ec->getANSHeader().majorVersion = 0; + ec->getANSHeader().minorVersion = 1; + // at every encoding the buffer might be autoexpanded, so we don't work with fixed pointer ec +#define ENCODEMCH(beg, end, slot, bits) CTF::get(buff.data())->encode(beg, end, int(slot), bits, optField[int(slot)], &buff, mCoders[int(slot)].get()); + // clang-format off + ENCODEMCH(helper.begin_bcIncROF(), helper.end_bcIncROF(), CTF::BLC_bcIncROF, 0); + ENCODEMCH(helper.begin_orbitIncROF(), helper.end_orbitIncROF(), CTF::BLC_orbitIncROF, 0); + ENCODEMCH(helper.begin_nDigitsROF(), helper.end_nDigitsROF(), CTF::BLC_nDigitsROF, 0); + + ENCODEMCH(helper.begin_tfTime(), helper.end_tfTime(), CTF::BLC_tfTime, 0); + ENCODEMCH(helper.begin_nSamples(), helper.end_nSamples(), CTF::BLC_nSamples, 0); + ENCODEMCH(helper.begin_isSaturated(), helper.end_isSaturated(), CTF::BLC_isSaturated, 0); + ENCODEMCH(helper.begin_detID(), helper.end_detID(), CTF::BLC_detID, 0); + ENCODEMCH(helper.begin_padID(), helper.end_padID(), CTF::BLC_padID, 0); + ENCODEMCH(helper.begin_ADC() , helper.end_ADC(), CTF::BLC_ADC, 0); + // clang-format on + // CTF::get(buff.data())->print(getPrefix()); +} + +/// decode entropy-encoded clusters to standard compact clusters +template +void CTFCoder::decode(const CTF::base& ec, VROF& rofVec, VCOL& digVec) +{ + auto header = ec.getHeader(); + ec.print(getPrefix()); + + std::vector bcInc, nSamples; + std::vector orbitInc, ADC, nDigits; + std::vector tfTime; + std::vector detID, padID; + std::vector isSaturated; + +#define DECODEMCH(part, slot) ec.decode(part, int(slot), mCoders[int(slot)].get()) + // clang-format off + DECODEMCH(bcInc, CTF::BLC_bcIncROF); + DECODEMCH(orbitInc, CTF::BLC_orbitIncROF); + DECODEMCH(nDigits, CTF::BLC_nDigitsROF); + + DECODEMCH(tfTime, CTF::BLC_tfTime); + DECODEMCH(nSamples, CTF::BLC_nSamples); + DECODEMCH(isSaturated, CTF::BLC_isSaturated); + DECODEMCH(detID, CTF::BLC_detID); + DECODEMCH(padID, CTF::BLC_padID); + DECODEMCH(ADC, CTF::BLC_ADC); + // clang-format on + // + rofVec.clear(); + digVec.clear(); + rofVec.reserve(header.nROFs); + digVec.reserve(header.nDigits); + + uint32_t firstEntry = 0, rofCount = 0, digCount = 0; + o2::InteractionRecord ir(header.firstBC, header.firstOrbit); + + for (uint32_t irof = 0; irof < header.nROFs; irof++) { + // restore ROFRecord + if (orbitInc[irof]) { // non-0 increment => new orbit + ir.bc = bcInc[irof]; // bcInc has absolute meaning + ir.orbit += orbitInc[irof]; + } else { + ir.bc += bcInc[irof]; + } + + firstEntry = digVec.size(); + for (auto ic = 0; ic < nDigits[irof]; ic++) { + digVec.emplace_back(Digit{detID[digCount], padID[digCount], ADC[digCount], tfTime[digCount], nSamples[digCount]}); + digVec.back().setSaturated(isSaturated[digCount]); + digCount++; + } + rofVec.emplace_back(ROFRecord{ir, int(firstEntry), static_cast(nDigits[irof])}); + } + assert(rofVec.size() == header.nROFs); + assert(digCount == header.nDigits); +} + +} // namespace mch +} // namespace o2 + +#endif // O2_MCH_CTFCODER_H diff --git a/Detectors/MUON/MCH/CTF/include/MCHCTF/CTFHelper.h b/Detectors/MUON/MCH/CTF/include/MCHCTF/CTFHelper.h new file mode 100644 index 0000000000000..86ae4e1ca9cbf --- /dev/null +++ b/Detectors/MUON/MCH/CTF/include/MCHCTF/CTFHelper.h @@ -0,0 +1,217 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file CTFHelper.h +/// \author ruben.shahoyan@cern.ch +/// \brief Helper for MCH CTF creation + +#ifndef O2_MCH_CTF_HELPER_H +#define O2_MCH_CTF_HELPER_H + +#include "DataFormatsMCH/ROFRecord.h" +#include "DataFormatsMCH/Digit.h" +#include "DataFormatsMCH/CTF.h" +#include + +namespace o2 +{ +namespace mch +{ + +class CTFHelper +{ + + public: + CTFHelper(const gsl::span& rofData, const gsl::span& digData) + : mROFData(rofData), mDigData(digData) {} + + CTFHeader createHeader() + { + CTFHeader h{uint32_t(mROFData.size()), uint32_t(mDigData.size()), 0, 0}; + if (mROFData.size()) { + h.firstOrbit = mROFData[0].getBCData().orbit; + h.firstBC = mROFData[0].getBCData().bc; + } + return h; + } + + size_t getSize() const { return mROFData.size() * sizeof(o2::mch::ROFRecord) + mDigData.size() * sizeof(o2::mch::Digit); } + + //>>> =========================== ITERATORS ======================================== + + template + class _Iter + { + public: + using difference_type = int64_t; + using value_type = T; + using pointer = const T*; + using reference = const T&; + using iterator_category = std::random_access_iterator_tag; + + _Iter(const gsl::span& data, bool end = false) : mData(data), mIndex(end ? M * data.size() : 0){}; + _Iter() = default; + + const I& operator++() + { + ++mIndex; + return (I&)(*this); + } + + const I& operator--() + { + mIndex--; + return (I&)(*this); + } + + difference_type operator-(const I& other) const { return mIndex - other.mIndex; } + + difference_type operator-(size_t idx) const { return mIndex - idx; } + + const I& operator-(size_t idx) + { + mIndex -= idx; + return (I&)(*this); + } + + bool operator!=(const I& other) const { return mIndex != other.mIndex; } + bool operator==(const I& other) const { return mIndex == other.mIndex; } + bool operator>(const I& other) const { return mIndex > other.mIndex; } + bool operator<(const I& other) const { return mIndex < other.mIndex; } + + protected: + gsl::span mData{}; + size_t mIndex = 0; + }; + + //_______________________________________________ + // BC difference wrt previous if in the same orbit, otherwise the abs.value. + // For the very 1st entry return 0 (diff wrt 1st BC in the CTF header) + class Iter_bcIncROF : public _Iter + { + public: + using _Iter::_Iter; + value_type operator*() const + { + if (mIndex) { + if (mData[mIndex].getBCData().orbit == mData[mIndex - 1].getBCData().orbit) { + return mData[mIndex].getBCData().bc - mData[mIndex - 1].getBCData().bc; + } else { + return mData[mIndex].getBCData().bc; + } + } + return 0; + } + }; + + //_______________________________________________ + // Orbit difference wrt previous. For the very 1st entry return 0 (diff wrt 1st BC in the CTF header) + class Iter_orbitIncROF : public _Iter + { + public: + using _Iter::_Iter; + value_type operator*() const { return mIndex ? mData[mIndex].getBCData().orbit - mData[mIndex - 1].getBCData().orbit : 0; } + }; + + //_______________________________________________ + // Number of entries in the ROF + class Iter_nDigitsROF : public _Iter + { + public: + using _Iter::_Iter; + value_type operator*() const { return mData[mIndex].getNEntries(); } + }; + + //_______________________________________________ + class Iter_tfTime : public _Iter + { + public: + using _Iter::_Iter; + value_type operator*() const { return mData[mIndex].getTime(); } + }; + + //_______________________________________________ + class Iter_nSamples : public _Iter + { + public: + using _Iter::_Iter; + value_type operator*() const { return mData[mIndex].nofSamples(); } + }; + + //_______________________________________________ + class Iter_isSaturated : public _Iter + { + public: + using _Iter::_Iter; + value_type operator*() const { return mData[mIndex].isSaturated(); } + }; + + //_______________________________________________ + class Iter_detID : public _Iter + { + public: + using _Iter::_Iter; + value_type operator*() const { return mData[mIndex].getDetID(); } + }; + + //_______________________________________________ + class Iter_padID : public _Iter + { + public: + using _Iter::_Iter; + value_type operator*() const { return mData[mIndex].getPadID(); } + }; + + //_______________________________________________ + class Iter_ADC : public _Iter + { + public: + using _Iter::_Iter; + value_type operator*() const { return mData[mIndex].getADC(); } + }; + + //<<< =========================== ITERATORS ======================================== + + Iter_bcIncROF begin_bcIncROF() const { return Iter_bcIncROF(mROFData, false); } + Iter_bcIncROF end_bcIncROF() const { return Iter_bcIncROF(mROFData, true); } + + Iter_orbitIncROF begin_orbitIncROF() const { return Iter_orbitIncROF(mROFData, false); } + Iter_orbitIncROF end_orbitIncROF() const { return Iter_orbitIncROF(mROFData, true); } + + Iter_nDigitsROF begin_nDigitsROF() const { return Iter_nDigitsROF(mROFData, false); } + Iter_nDigitsROF end_nDigitsROF() const { return Iter_nDigitsROF(mROFData, true); } + + Iter_tfTime begin_tfTime() const { return Iter_tfTime(mDigData, false); } + Iter_tfTime end_tfTime() const { return Iter_tfTime(mDigData, true); } + + Iter_nSamples begin_nSamples() const { return Iter_nSamples(mDigData, false); } + Iter_nSamples end_nSamples() const { return Iter_nSamples(mDigData, true); } + + Iter_isSaturated begin_isSaturated() const { return Iter_isSaturated(mDigData, false); } + Iter_isSaturated end_isSaturated() const { return Iter_isSaturated(mDigData, true); } + + Iter_detID begin_detID() const { return Iter_detID(mDigData, false); } + Iter_detID end_detID() const { return Iter_detID(mDigData, true); } + + Iter_padID begin_padID() const { return Iter_padID(mDigData, false); } + Iter_padID end_padID() const { return Iter_padID(mDigData, true); } + + Iter_ADC begin_ADC() const { return Iter_ADC(mDigData, false); } + Iter_ADC end_ADC() const { return Iter_ADC(mDigData, true); } + + private: + const gsl::span mROFData; + const gsl::span mDigData; +}; + +} // namespace mch +} // namespace o2 + +#endif diff --git a/Detectors/MUON/MCH/CTF/src/CTFCoder.cxx b/Detectors/MUON/MCH/CTF/src/CTFCoder.cxx new file mode 100644 index 0000000000000..5f9eb9c1fa4e5 --- /dev/null +++ b/Detectors/MUON/MCH/CTF/src/CTFCoder.cxx @@ -0,0 +1,81 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file CTFCoder.cxx +/// \author ruben.shahoyan@cern.ch +/// \brief class for entropy encoding/decoding of MCH data + +#include "MCHCTF/CTFCoder.h" +#include "CommonUtils/StringUtils.h" +#include + +using namespace o2::mch; + +///___________________________________________________________________________________ +// Register encoded data in the tree (Fill is not called, will be done by caller) +void CTFCoder::appendToTree(TTree& tree, CTF& ec) +{ + ec.appendToTree(tree, mDet.getName()); +} + +///___________________________________________________________________________________ +// extract and decode data from the tree +void CTFCoder::readFromTree(TTree& tree, int entry, std::vector& rofVec, std::vector& digVec) +{ + assert(entry >= 0 && entry < tree.GetEntries()); + CTF ec; + ec.readFromTree(tree, mDet.getName(), entry); + decode(ec, rofVec, digVec); +} + +///________________________________ +void CTFCoder::createCoders(const std::string& dictPath, o2::ctf::CTFCoderBase::OpType op) +{ + bool mayFail = true; // RS FIXME if the dictionary file is not there, do not produce exception + auto buff = readDictionaryFromFile(dictPath, mayFail); + if (!buff.size()) { + if (mayFail) { + return; + } + throw std::runtime_error("Failed to create CTF dictionaty"); + } + const auto* ctf = CTF::get(buff.data()); + + auto getFreq = [ctf](CTF::Slots slot) -> o2::rans::FrequencyTable { + o2::rans::FrequencyTable ft; + auto bl = ctf->getBlock(slot); + auto md = ctf->getMetadata(slot); + ft.addFrequencies(bl.getDict(), bl.getDict() + bl.getNDict(), md.min, md.max); + return std::move(ft); + }; + auto getProbBits = [ctf](CTF::Slots slot) -> int { + return ctf->getMetadata(slot).probabilityBits; + }; + + // just to get types + uint16_t bcInc, nDigits, nSamples; + uint32_t orbitInc, ADC; + int32_t tfTime; + int16_t detID, padID; + uint8_t isSaturated; +#define MAKECODER(part, slot) createCoder(op, getFreq(slot), getProbBits(slot), int(slot)) + + // clang-format off + MAKECODER(bcInc, CTF::BLC_bcIncROF); + MAKECODER(orbitInc, CTF::BLC_orbitIncROF); + MAKECODER(nDigits, CTF::BLC_nDigitsROF); + MAKECODER(tfTime, CTF::BLC_tfTime); + MAKECODER(nSamples, CTF::BLC_nSamples); + MAKECODER(isSaturated, CTF::BLC_isSaturated); + MAKECODER(detID, CTF::BLC_detID); + MAKECODER(padID, CTF::BLC_padID); + MAKECODER(ADC, CTF::BLC_ADC); + // clang-format on +} diff --git a/Detectors/MUON/MCH/CTF/src/CTFHelper.cxx b/Detectors/MUON/MCH/CTF/src/CTFHelper.cxx new file mode 100644 index 0000000000000..66421f99792a6 --- /dev/null +++ b/Detectors/MUON/MCH/CTF/src/CTFHelper.cxx @@ -0,0 +1,15 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file CTFHelper.cxx +/// \author ruben.shahoyan@cern.ch +/// \brief Helper for MCH CTF creation + +#include "MCHCTF/CTFHelper.h" diff --git a/Detectors/MUON/MCH/CTF/test/circular-test.sh b/Detectors/MUON/MCH/CTF/test/circular-test.sh new file mode 100644 index 0000000000000..57fc974b49ff3 --- /dev/null +++ b/Detectors/MUON/MCH/CTF/test/circular-test.sh @@ -0,0 +1,221 @@ +#!/bin/sh + +get_cmd_write_digits() { + if [ $# -eq 0 ]; then + echo "must at least specify the destination of the dump" + return + fi + local dest=$1 + local output=$2 + local format=${3:-missing} + local opt="" + local cmd="" + + if [ "$dest" = "binary" ]; then + opt="--binary-file-format $format" + elif [ "$dest" = "text" ]; then + opt="--txt" + elif [ "$dest" = "screen" ]; then + opt="--txt" + else + echo "dest=$dest is not one of {binary,text,screen}" + return + fi + + cmd="o2-mch-digits-writer-workflow -b " + cmd+=" $opt" + if [ $output ]; then + cmd+=" --outfile $output" + else + cmd+=" --no-file" + fi + echo $cmd +} + +run_workflow() { + local cmd=$1 + local msg=$2 + local verbose=$3 + + if [ ! -z $VERBOSE ]; then + verbose="verbose" + fi + + cmd+=" | o2-dpl-run --run -b" + + echo "#############" + echo "# $2" + echo "$cmd" + echo "#############" + + if [ "$verbose" = "verbose" ]; then + eval $cmd + else + eval $cmd &>/dev/null + fi +} + +generate_digits() { + local NROFPERTOF=${1:-1} + local NTF=${2:-1} + local OCC=${3:-0.0001} + local SEED=${4:-1} + local digitFile=${5:-UNKNOWN} + local format=${6:-3} + local cmd="" + + cmd="o2-mch-digits-random-generator-workflow -b " + cmd+="--nof-rofs-per-tf $NROFPERTF " + cmd+="--max-nof-tfs $NTF " + cmd+="--occupancy $OCC " + cmd+="--seed $SEED " + cmd+="| " + cmd+=$(get_cmd_write_digits binary $digitFile $format) + + run_workflow $cmd "Generate random digits and save them" verbose +} + +dump_digits() { + if [ $# -eq 0 ]; then + echo "must specify the name of the digit file to dump" + return + fi + local digitFile=${1:-digits.dump} + local dest=${2:-invalid} + local output=$3 + local format=$4 + local cmd="" + local verbose="" + + if [ "$dest" = "screen" ]; then + verbose=verbose + fi + + cmd="o2-mch-digits-file-reader-workflow -b --infile $digitFile | " + cmd+=$(get_cmd_write_digits $dest $output $format) + + run_workflow $cmd "Dump digits" $verbose +} + +create_ctf() { + if [ $# -eq 0 ]; then + echo "must specify the name of the digit file to compress" + return + fi + local digitsFile=$1 + local outputType=${2:-ctf} + local cmd="" + + cmd="o2-mch-digits-file-reader-workflow --infile ${digitsFile} -b | " + cmd+="o2-mch-entropy-encoder-workflow -b |" + cmd+="o2-ctf-writer-workflow --onlyDet MCH --no-grp --output-type $outputType -b" + + run_workflow $cmd "Read digits and create $outputType" +} + +get_ctfs() { + if [ $# -eq 0 ]; then + echo "must specify the number of tfs to look for" + return + fi + local ntf=$1 + local ctfs="" + local run=0 + local orbit=0 + + for tf in $(seq 0 $(($ntf - 1))); do + ctfs+=$(printf "o2_ctf_run%08d_orbit%010d_tf%010d.root " $run $orbit $tf) + done + ctfs=$(echo $ctfs | sed 's/.$//') # remove trailing coma + + echo "$ctfs" +} + +read_ctf() { + if [ $# -lt 2 ]; then + echo "must specify the CTF(s) to read and output digit filename" + return + fi + local ctfs=$1 + local ctfdigitfile=$2 + local format=$3 + local cmd="" + + cmd="o2-ctf-reader-workflow --onlyDet MCH --ctf-input ${ctfs} -b | " + cmd+=$(get_cmd_write_digits binary $ctfdigitfile $format) + + run_workflow $cmd "Read CTF and write digits" +} + +NROFPERTF=${1:-128} +NTF=${2:-1} +OCC=${3:-0.1} +SEED=${4:-1} +BINARY_FILE_FORMAT=${5:-3} +textDump=0 + +COUNT=$(( $NROFPERTF * $NTF * $OCC * 1064008 )) +COUNT=$(echo $COUNT | awk '{print int($0)}') + +if [ $COUNT -lt 100000 ]; then + # activate text dump if we don't have too many digits + textDump=1 +fi + +refdigits=digits_ref_rof_${NROFPERTF}_tf_${NTF}_occ_${OCC}_seed_${SEED} + +# Generate digits +generate_digits $NROFPERTF $NTF $OCC $SEED $refdigits.orig.data $BINARY_FILE_FORMAT + +# Dump the digits to verify sample-sink couple +dump_digits ${refdigits}.orig.data binary ${refdigits}.check.data $BINARY_FILE_FORMAT + +echo '# Remove dictionary data if any' +rm -f ctf_dictionary.root + +# read Digits and create CTF(s) files +create_ctf ${refdigits}.orig.data + +ctfs=$(get_ctfs $NTF) + +# read CTF and write digits +read_ctf $ctfs ${refdigits}.ctf.data $BINARY_FILE_FORMAT + +# # Dump the digits on screen' +# dump_digits ${refdigits}.ctf.data screen + +mkdir nodict && pushd nodict + +# Read digits and encode them, but only write out the frequencies dictionary +create_ctf ../${refdigits}.orig.data dict + +# Read digits and encode them in a CTF with external dict +create_ctf ../${refdigits}.orig.data + +ctfs=$(get_ctfs $NTF) + +# read CTF and write digits +read_ctf $ctfs ${refdigits}.nodict.ctf.data $BINARY_FILE_FORMAT + +popd + +if [ $textDump -eq 1 ]; then +# Make a text version of all digit files + for d in $(find . -name "digits*"); + do + dump_digits $d text $d.txt + done +fi + +echo '# Compare digits before after ctf encoding/decoding' +if [ $textDump -eq 1 ]; then + echo '# Text versions' + find . -name "digits*.txt" -exec shasum -a 256 {} \; | sort +fi +echo '# Binary versions' +find . -name "digits*.data" -exec shasum -a 256 {} \; | sort + +echo '# Sizes' +find . -name '*ctf_*' -exec ls -alh {} \; +find . -name 'digits*.data' -exec ls -alh {} \; + diff --git a/Detectors/MUON/MCH/Workflow/CMakeLists.txt b/Detectors/MUON/MCH/Workflow/CMakeLists.txt index fede649045e40..b36ed6e83bb33 100644 --- a/Detectors/MUON/MCH/Workflow/CMakeLists.txt +++ b/Detectors/MUON/MCH/Workflow/CMakeLists.txt @@ -10,11 +10,12 @@ o2_add_library(MCHWorkflow SOURCES src/DataDecoderSpec.cxx src/PreClusterFinderSpec.cxx src/ClusterFinderOriginalSpec.cxx + src/EntropyDecoderSpec.cxx TARGETVARNAME targetName PUBLIC_LINK_LIBRARIES O2::Framework O2::DPLUtils O2::MCHRawDecoder Boost::program_options O2::MCHRawImplHelpers RapidJSON::RapidJSON O2::MCHMappingInterface O2::MCHPreClustering O2::MCHMappingImpl4 O2::MCHRawElecMap O2::MCHBase - O2::DataFormatsMCH O2::MCHClustering) + O2::DataFormatsMCH O2::MCHClustering O2::MCHCTF) o2_add_executable( cru-page-reader-workflow @@ -130,3 +131,8 @@ o2_add_executable( COMPONENT_NAME mch PUBLIC_LINK_LIBRARIES O2::MCHWorkflow O2::MCHGeometryTransformer) +o2_add_executable( + entropy-encoder-workflow + SOURCES src/entropy-encoder-workflow.cxx + COMPONENT_NAME mch + PUBLIC_LINK_LIBRARIES O2::MCHWorkflow) diff --git a/Detectors/MUON/MCH/Workflow/README.md b/Detectors/MUON/MCH/Workflow/README.md index fd51444004b1b..ab05cc2f1cbff 100644 --- a/Detectors/MUON/MCH/Workflow/README.md +++ b/Detectors/MUON/MCH/Workflow/README.md @@ -9,6 +9,7 @@ * [Raw to digits](#raw-to-digits) * [Preclustering](#preclustering) * [Clustering](#clustering) +* [CTF encoding/decoding](#ctf-encodingdecoding) * [Local to global cluster transformation](#local-to-global-cluster-transformation) * [Tracking](#tracking) * [Original track finder](#original-track-finder) @@ -77,6 +78,16 @@ o2-mch-preclusters-to-clusters-original-workflow Take as input the list of all preclusters ([PreCluster](../Base/include/MCHBase/PreCluster.h)) in the current time frame, the list of all associated digits ([Digit](/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/Digit.h)) and the list of ROF records ([ROFRecord](../../../../DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/ROFRecord.h)) pointing to the preclusters associated to each interaction, with the data description "PRECLUSTERS", "PRECLUSTERDIGITS" and "PRECLUSTERROFS", respectively. Send the list of all clusters ([ClusterStruct](../Base/include/MCHBase/ClusterBlock.h)) in the time frame, the list of all associated digits ([Digit](/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/Digit.h)) and the list of ROF records ([ROFRecord](../../../../DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/ROFRecord.h)) pointing to the clusters associated to each interaction in three separate messages with the data description "CLUSTERS", "CLUSTERDIGITS" and "CLUSTERROFS", respectively. +## CTF encoding/decoding + +Entropy encoding is done be attaching the `o2-mch-entropy-encoder-workflow` to the output of `DIGITS` and `DIGITROF` data-descriptions, providing `Digit` and `ROFRecord` respectively. Afterwards the encoded data can be stored by the `o2-ctf-writer-workflow`. + +```shell +o2-raw-file-reader-workflow --input-conf raw/MCH/MCHraw.cfg | o2-mch-raw-to-digits-workflow | o2-mch-entropy-encoder-workflow | o2-ctf-writer-workflow --onlyDet MCH +``` + +The decoding is done automatically by the `o2-ctf-reader-workflow`. + ## Local to global cluster transformation The `o2-mch-clusters-transformer-workflow` takes as input the list of all clusters ([ClusterStruct](../Base/include/MCHBase/ClusterBlock.h)), in local reference frame, in the current time frame, with the data description "CLUSTERS". diff --git a/Detectors/MUON/MCH/Workflow/include/MCHWorkflow/EntropyDecoderSpec.h b/Detectors/MUON/MCH/Workflow/include/MCHWorkflow/EntropyDecoderSpec.h new file mode 100644 index 0000000000000..1e0d00e512770 --- /dev/null +++ b/Detectors/MUON/MCH/Workflow/include/MCHWorkflow/EntropyDecoderSpec.h @@ -0,0 +1,29 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file EntropyDecoderSpec.h +/// @brief Convert CTF (EncodedBlocks) to MCH {Digit,ROFRecord} stream + +#ifndef O2_MCH_ENTROPYDECODER_SPEC +#define O2_MCH_ENTROPYDECODER_SPEC + +#include "Framework/DataProcessorSpec.h" + +namespace o2 +{ +namespace mch +{ +/// create a processor spec +framework::DataProcessorSpec getEntropyDecoderSpec(); + +} // namespace mch +} // namespace o2 + +#endif diff --git a/Detectors/MUON/MCH/Workflow/src/EntropyDecoderSpec.cxx b/Detectors/MUON/MCH/Workflow/src/EntropyDecoderSpec.cxx new file mode 100644 index 0000000000000..38169938a17a9 --- /dev/null +++ b/Detectors/MUON/MCH/Workflow/src/EntropyDecoderSpec.cxx @@ -0,0 +1,96 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file EntropyDecoderSpec.cxx + +#include + +#include "Framework/ControlService.h" +#include "Framework/ConfigParamRegistry.h" +#include "MCHWorkflow/EntropyDecoderSpec.h" +#include "Framework/Task.h" +#include "MCHCTF/CTFCoder.h" +#include + +using namespace o2::framework; + +namespace o2 +{ +namespace mch +{ + +class EntropyDecoderSpec : public o2::framework::Task +{ + public: + EntropyDecoderSpec(); + ~EntropyDecoderSpec() override = default; + void run(o2::framework::ProcessingContext& pc) final; + void init(o2::framework::InitContext& ic) final; + void endOfStream(o2::framework::EndOfStreamContext& ec) final; + + private: + o2::mch::CTFCoder mCTFCoder; + TStopwatch mTimer; +}; + +EntropyDecoderSpec::EntropyDecoderSpec() +{ + mTimer.Stop(); + mTimer.Reset(); +} + +void EntropyDecoderSpec::init(o2::framework::InitContext& ic) +{ + std::string dictPath = ic.options().get("ctf-dict"); + if (!dictPath.empty() && dictPath != "none") { + mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Decoder); + } +} + +void EntropyDecoderSpec::run(ProcessingContext& pc) +{ + auto cput = mTimer.CpuTime(); + mTimer.Start(false); + + auto buff = pc.inputs().get>("ctf"); + + auto& rofs = pc.outputs().make>(OutputRef{"rofs"}); + auto& digits = pc.outputs().make>(OutputRef{"digits"}); + + // since the buff is const, we cannot use EncodedBlocks::relocate directly, instead we wrap its data to another flat object + const auto ctfImage = o2::mch::CTF::getImage(buff.data()); + mCTFCoder.decode(ctfImage, rofs, digits); + + mTimer.Stop(); + LOG(INFO) << "Decoded " << digits.size() << " MCH digits in " << rofs.size() << " ROFRecords in " << mTimer.CpuTime() - cput << " s"; +} + +void EntropyDecoderSpec::endOfStream(EndOfStreamContext& ec) +{ + LOGF(INFO, "MCH Entropy Decoding total timing: Cpu: %.3e Real: %.3e s in %d slots", + mTimer.CpuTime(), mTimer.RealTime(), mTimer.Counter() - 1); +} + +DataProcessorSpec getEntropyDecoderSpec() +{ + std::vector outputs{ + OutputSpec{{"rofs"}, "MCH", "DIGITROFS", 0, Lifetime::Timeframe}, + OutputSpec{{"digits"}, "MCH", "DIGITS", 0, Lifetime::Timeframe}}; + + return DataProcessorSpec{ + "mch-entropy-decoder", + Inputs{InputSpec{"ctf", "MCH", "CTFDATA", 0, Lifetime::Timeframe}}, + outputs, + AlgorithmSpec{adaptFromTask()}, + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"File of CTF decoding dictionary"}}}}; +} + +} // namespace mch +} // namespace o2 diff --git a/Detectors/MUON/MCH/Workflow/src/entropy-encoder-workflow.cxx b/Detectors/MUON/MCH/Workflow/src/entropy-encoder-workflow.cxx new file mode 100644 index 0000000000000..db3f070ddfdf4 --- /dev/null +++ b/Detectors/MUON/MCH/Workflow/src/entropy-encoder-workflow.cxx @@ -0,0 +1,120 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "CommonUtils/ConfigurableParam.h" +#include "DetectorsCommonDataFormats/DetID.h" +#include "Framework/ConfigParamRegistry.h" +#include "Framework/ConfigParamSpec.h" +#include "Framework/ControlService.h" +#include "Framework/DataProcessorSpec.h" +#include "Framework/Task.h" +#include "MCHCTF/CTFCoder.h" +#include +#include + +using namespace o2::framework; + +namespace o2 +{ +namespace mch +{ + +class EntropyEncoderSpec : public o2::framework::Task +{ + public: + EntropyEncoderSpec(); + ~EntropyEncoderSpec() override = default; + void run(o2::framework::ProcessingContext& pc) final; + void init(o2::framework::InitContext& ic) final; + void endOfStream(o2::framework::EndOfStreamContext& ec) final; + + private: + o2::mch::CTFCoder mCTFCoder; + TStopwatch mTimer; +}; + +EntropyEncoderSpec::EntropyEncoderSpec() +{ + mTimer.Stop(); + mTimer.Reset(); +} + +void EntropyEncoderSpec::init(o2::framework::InitContext& ic) +{ + std::string dictPath = ic.options().get("ctf-dict"); + if (!dictPath.empty() && dictPath != "none") { + mCTFCoder.createCoders(dictPath, o2::ctf::CTFCoderBase::OpType::Encoder); + } +} + +void EntropyEncoderSpec::run(ProcessingContext& pc) +{ + auto cput = mTimer.CpuTime(); + mTimer.Start(false); + auto rofs = pc.inputs().get>("rofs"); + auto digits = pc.inputs().get>("digits"); + + auto& buffer = pc.outputs().make>(Output{"MCH", "CTFDATA", 0, Lifetime::Timeframe}); + mCTFCoder.encode(buffer, rofs, digits); + auto eeb = CTF::get(buffer.data()); // cast to container pointer + eeb->compactify(); // eliminate unnecessary padding + buffer.resize(eeb->size()); // shrink buffer to strictly necessary size + // eeb->print(); + mTimer.Stop(); + LOG(INFO) << fmt::format("Created encoded data ({} digits and {} rofs) of size {} ({:5.1f} MB) for MCH in {:5.1f} s ", + digits.size(), rofs.size(), eeb->size(), eeb->size() / 1024.0 / 1024, mTimer.CpuTime() - cput); +} + +void EntropyEncoderSpec::endOfStream(EndOfStreamContext& ec) +{ + LOGF(INFO, "MCH Entropy Encoding total timing: Cpu: %.3e Real: %.3e s in %d slots", + mTimer.CpuTime(), mTimer.RealTime(), mTimer.Counter() - 1); +} + +DataProcessorSpec getEntropyEncoderSpec() +{ + std::vector inputs; + inputs.emplace_back("rofs", "MCH", "DIGITROFS", 0, Lifetime::Timeframe); + inputs.emplace_back("digits", "MCH", "DIGITS", 0, Lifetime::Timeframe); + + return DataProcessorSpec{ + "mch-entropy-encoder", + inputs, + Outputs{{"MCH", "CTFDATA", 0, Lifetime::Timeframe}}, + AlgorithmSpec{adaptFromTask()}, + Options{{"ctf-dict", VariantType::String, o2::base::NameConf::getCTFDictFileName(), {"Path to pre-computed CTF encoding dictionary to be used for encoding"}}}}; +} + +} // namespace mch +} // namespace o2 + +// ------------------------------------------------------------------ + +// we need to add workflow options before including Framework/runDataProcessing +void customize(std::vector& workflowOptions) +{ + // option allowing to set parameters + std::vector options{ConfigParamSpec{"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}}; + + std::swap(workflowOptions, options); +} + +// ------------------------------------------------------------------ + +#include "Framework/runDataProcessing.h" + +WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) +{ + WorkflowSpec wf; + // Update the (declared) parameters if changed from the command line + o2::conf::ConfigurableParam::updateFromString(cfgc.options().get("configKeyValues")); + wf.emplace_back(o2::mch::getEntropyEncoderSpec()); + return wf; +} From 032f2858dd7390b46c547c98464cc71319833534 Mon Sep 17 00:00:00 2001 From: Laurent Aphecetche Date: Sat, 17 Apr 2021 16:31:32 +0200 Subject: [PATCH 158/770] [MCH] Comply with naming conventions and remove tab --- .../Detectors/MUON/MCH/include/DataFormatsMCH/Digit.h | 2 +- DataFormats/Detectors/MUON/MCH/src/Digit.cxx | 4 ++-- DataFormats/Detectors/MUON/MCH/src/testDigit.cxx | 6 +++--- Detectors/MUON/MCH/CTF/CMakeLists.txt | 2 +- Detectors/MUON/MCH/CTF/include/MCHCTF/CTFHelper.h | 2 +- Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.cxx | 2 +- Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.cxx | 2 +- Detectors/MUON/MCH/DevIO/Digits/DigitWriter.cxx | 2 +- 8 files changed, 11 insertions(+), 11 deletions(-) diff --git a/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/Digit.h b/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/Digit.h index 68ffef16f8b54..5820cc79591c9 100644 --- a/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/Digit.h +++ b/DataFormats/Detectors/MUON/MCH/include/DataFormatsMCH/Digit.h @@ -41,7 +41,7 @@ class Digit int32_t getTime() const { return mTFtime; } void setNofSamples(uint16_t n); - uint16_t nofSamples() const; + uint16_t getNofSamples() const; void setSaturated(bool sat); bool isSaturated() const; diff --git a/DataFormats/Detectors/MUON/MCH/src/Digit.cxx b/DataFormats/Detectors/MUON/MCH/src/Digit.cxx index 92a1f81133448..e8599a854a37c 100644 --- a/DataFormats/Detectors/MUON/MCH/src/Digit.cxx +++ b/DataFormats/Detectors/MUON/MCH/src/Digit.cxx @@ -19,7 +19,7 @@ namespace o2::mch std::ostream& operator<<(std::ostream& os, const o2::mch::Digit& d) { os << fmt::format("DetID {:4d} PadId {:6d} ADC {:10d} TFtime {:10d} NofSamples {:5d} {}", - d.getDetID(), d.getPadID(), d.getADC(), d.getTime(), d.nofSamples(), + d.getDetID(), d.getPadID(), d.getADC(), d.getTime(), d.getNofSamples(), d.isSaturated() ? "(S)" : ""); return os; } @@ -35,7 +35,7 @@ Digit::Digit(int detid, int pad, uint32_t adc, int32_t time, uint16_t nSamples, setNofSamples(nSamples); } -uint16_t Digit::nofSamples() const +uint16_t Digit::getNofSamples() const { return mNofSamples; } diff --git a/DataFormats/Detectors/MUON/MCH/src/testDigit.cxx b/DataFormats/Detectors/MUON/MCH/src/testDigit.cxx index 72d161e36acee..83fe732561931 100644 --- a/DataFormats/Detectors/MUON/MCH/src/testDigit.cxx +++ b/DataFormats/Detectors/MUON/MCH/src/testDigit.cxx @@ -50,7 +50,7 @@ BOOST_DATA_TEST_CASE(DefaultConstructorNofSamplesIsInvariant, boost::unit_test::data::make(nsamples), nofSamples) { o2::mch::Digit d(dummyDetId, dummyPadId, dummyADC, dummyTime, nofSamples); - BOOST_CHECK_EQUAL(d.nofSamples(), nofSamples); + BOOST_CHECK_EQUAL(d.getNofSamples(), nofSamples); } BOOST_DATA_TEST_CASE(SetSaturatedDoesNotAffectPublicNofSamples, @@ -60,9 +60,9 @@ BOOST_DATA_TEST_CASE(SetSaturatedDoesNotAffectPublicNofSamples, BOOST_TEST_INFO("setting saturation to true"); d.setSaturated(true); - BOOST_CHECK_EQUAL(d.nofSamples(), nofSamples); + BOOST_CHECK_EQUAL(d.getNofSamples(), nofSamples); BOOST_TEST_INFO("setting saturation to false"); d.setSaturated(false); - BOOST_CHECK_EQUAL(d.nofSamples(), nofSamples); + BOOST_CHECK_EQUAL(d.getNofSamples(), nofSamples); } diff --git a/Detectors/MUON/MCH/CTF/CMakeLists.txt b/Detectors/MUON/MCH/CTF/CMakeLists.txt index 5ab7ec83b79c5..e436cf90fca5a 100644 --- a/Detectors/MUON/MCH/CTF/CMakeLists.txt +++ b/Detectors/MUON/MCH/CTF/CMakeLists.txt @@ -14,6 +14,6 @@ o2_add_library(MCHCTF O2::MCHBase O2::DetectorsBase O2::CommonDataFormat - O2::DetectorsCommonDataFormats + O2::DetectorsCommonDataFormats O2::rANS ms_gsl::ms_gsl) diff --git a/Detectors/MUON/MCH/CTF/include/MCHCTF/CTFHelper.h b/Detectors/MUON/MCH/CTF/include/MCHCTF/CTFHelper.h index 86ae4e1ca9cbf..1a1ed59888490 100644 --- a/Detectors/MUON/MCH/CTF/include/MCHCTF/CTFHelper.h +++ b/Detectors/MUON/MCH/CTF/include/MCHCTF/CTFHelper.h @@ -142,7 +142,7 @@ class CTFHelper { public: using _Iter::_Iter; - value_type operator*() const { return mData[mIndex].nofSamples(); } + value_type operator*() const { return mData[mIndex].getNofSamples(); } }; //_______________________________________________ diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.cxx b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.cxx index 60ad76e758130..37e68ac461760 100644 --- a/Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.cxx +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.cxx @@ -80,7 +80,7 @@ bool DigitWriterV0::write(std::ostream& out, std::vector digitsd0; for (int i = r.getFirstIdx(); i <= r.getLastIdx(); i++) { const Digit& d = digits[i]; - digitsd0.push_back(DigitD0{d.getTime(), d.nofSamples(), d.getDetID(), d.getPadID(), d.getADC()}); + digitsd0.push_back(DigitD0{d.getTime(), d.getNofSamples(), d.getDetID(), d.getPadID(), d.getADC()}); digitsd0.back().setSaturated(d.isSaturated()); } gsl::span d0(digitsd0); diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.cxx b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.cxx index b6f2942e5c742..6956934b607f9 100644 --- a/Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.cxx +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.cxx @@ -89,7 +89,7 @@ bool DigitWriterV1::write(std::ostream& out, std::vector digitsd0; for (const auto& d : digits) { - digitsd0.push_back(DigitD0{d.getTime(), d.nofSamples(), d.getDetID(), d.getPadID(), d.getADC()}); + digitsd0.push_back(DigitD0{d.getTime(), d.getNofSamples(), d.getDetID(), d.getPadID(), d.getADC()}); digitsd0.back().setSaturated(d.isSaturated()); } gsl::span d0(digitsd0); diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitWriter.cxx b/Detectors/MUON/MCH/DevIO/Digits/DigitWriter.cxx index 2b81b09af0cb8..0fb66d3ab22f0 100644 --- a/Detectors/MUON/MCH/DevIO/Digits/DigitWriter.cxx +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitWriter.cxx @@ -31,7 +31,7 @@ template <> std::string asString(o2::mch::Digit d) { return fmt::format("DetID {:4d} PadId {:10d} ADC {:10d} TFtime {:10d} NofSamples {:5d} {}", - d.getDetID(), d.getPadID(), d.getADC(), d.getTime(), d.nofSamples(), + d.getDetID(), d.getPadID(), d.getADC(), d.getTime(), d.getNofSamples(), d.isSaturated() ? "(S)" : ""); } template From a2a5462a925e70d45871032d6fd353fb9dc52aeb Mon Sep 17 00:00:00 2001 From: Andreas Morsch Date: Sat, 17 Apr 2021 20:14:05 +0200 Subject: [PATCH 159/770] FLUKA command lind configuration to switch to radiation studies --- Detectors/gconfig/CMakeLists.txt | 6 ++-- .../gconfig/include/SimSetup/FlukaParam.h | 34 +++++++++++++++++++ Detectors/gconfig/src/FlukaConfig.cxx | 18 ++++++++-- Detectors/gconfig/src/FlukaParam.cxx | 12 +++++++ Detectors/gconfig/src/GConfLinkDef.h | 2 ++ 5 files changed, 66 insertions(+), 6 deletions(-) create mode 100644 Detectors/gconfig/include/SimSetup/FlukaParam.h create mode 100644 Detectors/gconfig/src/FlukaParam.cxx diff --git a/Detectors/gconfig/CMakeLists.txt b/Detectors/gconfig/CMakeLists.txt index 2ac6f9809633e..36dde55254a1d 100644 --- a/Detectors/gconfig/CMakeLists.txt +++ b/Detectors/gconfig/CMakeLists.txt @@ -22,22 +22,22 @@ if (FlukaVMC_FOUND) message(STATUS "BUILDING WITH FLUKA") o2_add_library(FLUKASetup SOURCES src/FlukaConfig.cxx - PUBLIC_LINK_LIBRARIES MC::FlukaVMC FairRoot::Base O2::SimulationDataFormat O2::Generators ROOT::EGPythia6 + PUBLIC_LINK_LIBRARIES MC::FlukaVMC FairRoot::Base O2::SimulationDataFormat O2::Generators ROOT::EGPythia6 O2::SimSetup ) else() message(STATUS "BUILDING WITHOUT FLUKA") endif (FlukaVMC_FOUND) o2_add_library(SimSetup - SOURCES src/GlobalProcessCutSimParam.cxx src/SimSetup.cxx src/SetCuts.cxx + SOURCES src/GlobalProcessCutSimParam.cxx src/SimSetup.cxx src/SetCuts.cxx src/FlukaParam.cxx PUBLIC_LINK_LIBRARIES O2::CommonUtils O2::DetectorsBase ) o2_target_root_dictionary(SimSetup HEADERS include/SimSetup/SimSetup.h include/SimSetup/GlobalProcessCutSimParam.h + include/SimSetup/FlukaParam.h LINKDEF src/GConfLinkDef.h) - o2_add_test_root_macro(DecayConfig.C PUBLIC_LINK_LIBRARIES O2::SimSetup LABELS simsetup) diff --git a/Detectors/gconfig/include/SimSetup/FlukaParam.h b/Detectors/gconfig/include/SimSetup/FlukaParam.h new file mode 100644 index 0000000000000..d50ab91ba737b --- /dev/null +++ b/Detectors/gconfig/include/SimSetup/FlukaParam.h @@ -0,0 +1,34 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \author A+Morsch + +#include +#ifndef ALICEO2_EVENTGEN_FLUKAPARAM_H_ +#define ALICEO2_EVENTGEN_FLUKAPARAM_H_ + +#include "CommonUtils/ConfigurableParam.h" +#include "CommonUtils/ConfigurableParamHelper.h" + +namespace o2 +{ +/** + ** A parameter class/struct holding values for + ** FLUKA Transport Code + **/ +struct FlukaParam : public o2::conf::ConfigurableParamHelper { + bool activationSimulation = false; // whether FLUKA is used for activation studies + float activationHadronCut = 0.003; // hadron kinetic energy cut for activation studies + std::string scoringFile = ""; // input file for user scoring options + O2ParamDef(FlukaParam, "FlukaParam"); +}; +} // end namespace o2 + +#endif // ALICEO2_EVENTGEN_FLUKAPARAM_H_ diff --git a/Detectors/gconfig/src/FlukaConfig.cxx b/Detectors/gconfig/src/FlukaConfig.cxx index bdc3fa137f34c..2b97e4b8e2de6 100644 --- a/Detectors/gconfig/src/FlukaConfig.cxx +++ b/Detectors/gconfig/src/FlukaConfig.cxx @@ -16,6 +16,7 @@ #include "FairLogger.h" #include "FairModule.h" #include "Generators/DecayerPythia8.h" +#include "SimSetup/FlukaParam.h" #include "../commonConfig.C" // these are used in commonConfig.C @@ -38,21 +39,32 @@ void linkFlukaFiles() gSystem->Exec("ln -s $FLUKADATA/cohff.bin ."); gSystem->Exec("ln -s $FLUKADATA/fluodt.dat ."); gSystem->Exec("ln -s $FLUKADATA/random.dat ."); - // Copy the random seed - gSystem->Exec("cp $FLUKADATA/random.dat old.seed"); + gSystem->Exec("ln -s $FLUKADATA/dnr.dat ."); + gSystem->Exec("ln -s $FLUKADATA/nunstab.dat ."); // Give some meaningfull name to the output gSystem->Exec("ln -s fluka.out fort.11"); gSystem->Exec("ln -s fluka.err fort.15"); - gSystem->Exec("ln -fs $ALICE_ROOT/TFluka/macro/FlukaConfig.C Config.C"); gSystem->Exec("ln -fs $O2_ROOT/share/Detectors/gconfig/data/coreFlukaVmc.inp ."); } void Config() { + // linkFlukaFiles(); FairRunSim* run = FairRunSim::Instance(); TString* gModel = run->GetGeoModel(); TFluka* fluka = new TFluka("C++ Interface to Fluka", 0); + + // additional configuration paramters if requested from command line + auto& params = FlukaParam::Instance(); + auto isAct = params.activationSimulation; + if (isAct) { + LOG(INFO) << "Set special FLUKA parameters for activation simulation"; + auto hadronCut = params.activationHadronCut; + auto inpFile = params.scoringFile; + fluka->SetActivationSimulation(true, hadronCut); + fluka->SetUserScoringFileName(inpFile.c_str()); + } stackSetup(fluka, run); // setup decayer diff --git a/Detectors/gconfig/src/FlukaParam.cxx b/Detectors/gconfig/src/FlukaParam.cxx new file mode 100644 index 0000000000000..ea8e8aae3c31d --- /dev/null +++ b/Detectors/gconfig/src/FlukaParam.cxx @@ -0,0 +1,12 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "SimSetup/FlukaParam.h" +O2ParamImpl(o2::FlukaParam); diff --git a/Detectors/gconfig/src/GConfLinkDef.h b/Detectors/gconfig/src/GConfLinkDef.h index e24e3e66fd7a7..d2f89b2dbd297 100644 --- a/Detectors/gconfig/src/GConfLinkDef.h +++ b/Detectors/gconfig/src/GConfLinkDef.h @@ -18,5 +18,7 @@ #pragma link C++ class o2::conf::ConfigurableParam + ; #pragma link C++ class o2::GlobalProcessCutSimParam + ; #pragma link C++ class o2::conf::ConfigurableParamHelper < o2::GlobalProcessCutSimParam> + ; +#pragma link C++ class o2::FlukaParam+ ; +#pragma link C++ class o2::conf::ConfigurableParamHelper < o2::FlukaParam> + ; #endif From 89769db25916840901107ac343651194770d9769 Mon Sep 17 00:00:00 2001 From: Andreas Morsch Date: Sat, 17 Apr 2021 20:27:44 +0200 Subject: [PATCH 160/770] clang style corrections --- Detectors/gconfig/include/SimSetup/FlukaParam.h | 6 +++--- Detectors/gconfig/src/FlukaConfig.cxx | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Detectors/gconfig/include/SimSetup/FlukaParam.h b/Detectors/gconfig/include/SimSetup/FlukaParam.h index d50ab91ba737b..5e19ee0b4f611 100644 --- a/Detectors/gconfig/include/SimSetup/FlukaParam.h +++ b/Detectors/gconfig/include/SimSetup/FlukaParam.h @@ -24,9 +24,9 @@ namespace o2 ** FLUKA Transport Code **/ struct FlukaParam : public o2::conf::ConfigurableParamHelper { - bool activationSimulation = false; // whether FLUKA is used for activation studies - float activationHadronCut = 0.003; // hadron kinetic energy cut for activation studies - std::string scoringFile = ""; // input file for user scoring options + bool activationSimulation = false; // whether FLUKA is used for activation studies + float activationHadronCut = 0.003; // hadron kinetic energy cut for activation studies + std::string scoringFile = ""; // input file for user scoring options O2ParamDef(FlukaParam, "FlukaParam"); }; } // end namespace o2 diff --git a/Detectors/gconfig/src/FlukaConfig.cxx b/Detectors/gconfig/src/FlukaConfig.cxx index 2b97e4b8e2de6..a2f329fd4e3fc 100644 --- a/Detectors/gconfig/src/FlukaConfig.cxx +++ b/Detectors/gconfig/src/FlukaConfig.cxx @@ -61,7 +61,7 @@ void Config() if (isAct) { LOG(INFO) << "Set special FLUKA parameters for activation simulation"; auto hadronCut = params.activationHadronCut; - auto inpFile = params.scoringFile; + auto inpFile = params.scoringFile; fluka->SetActivationSimulation(true, hadronCut); fluka->SetUserScoringFileName(inpFile.c_str()); } From 40c91edd02d2c3511281a63a5266f00d20ae4c96 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Sun, 18 Apr 2021 16:55:15 +0200 Subject: [PATCH 161/770] Revert "Update trackextension.cxx (#5928)" (#5957) This reverts commit b26e4ae3c910c24584dda2947b5fb7b371fb75fc. --- Analysis/Tasks/trackextension.cxx | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/Analysis/Tasks/trackextension.cxx b/Analysis/Tasks/trackextension.cxx index 554764f7e75bf..3cb5e87cf6bc4 100644 --- a/Analysis/Tasks/trackextension.cxx +++ b/Analysis/Tasks/trackextension.cxx @@ -31,13 +31,10 @@ using namespace o2::framework::expressions; */ //**************************************************************************************** struct TrackExtensionTask { - Configurable pvMC{"pvMC", false, "option to use mc pv"}; Produces extendedTrackQuantities; - //aod::McCollision const& mcCollision - - void process(soa::Join::iterator const& collision, aod::McCollisions const& mcCollisions, aod::FullTracks const& tracks) + void process(aod::Collision const& collision, aod::FullTracks const& tracks) { for (auto& track : tracks) { @@ -46,11 +43,7 @@ struct TrackExtensionTask { if (track.trackType() == o2::aod::track::TrackTypeEnum::Run2Track && track.itsChi2NCl() != 0.f && track.tpcChi2NCl() != 0.f && std::abs(track.x()) < 10.f) { float magField = 5.0; // in kG (FIXME: get this from CCDB) auto trackPar = getTrackPar(track); - if (!pvMC) { - trackPar.propagateParamToDCA({collision.posX(), collision.posY(), collision.posZ()}, magField, &dca); - } else { - trackPar.propagateParamToDCA({collision.mcCollision().posX(), collision.mcCollision().posY(), collision.mcCollision().posZ()}, magField, &dca); - } + trackPar.propagateParamToDCA({collision.posX(), collision.posY(), collision.posZ()}, magField, &dca); } extendedTrackQuantities(dca[0], dca[1]); From e127cf58b9d333bae1fc11053331852ae7915ae6 Mon Sep 17 00:00:00 2001 From: Roberto Preghenella Date: Fri, 16 Apr 2021 08:08:21 +0200 Subject: [PATCH 162/770] Code to run simulation and analysis to inspect primary/secondary tracks that originate hits --- run/SimExamples/Inspect_Hits/left_trace.macro | 73 ++++++++++++ .../Inspect_Hits/plot_primary.macro | 54 +++++++++ .../Inspect_Hits/plot_secondary.macro | 55 +++++++++ .../Inspect_Hits/primary_and_hits.macro | 48 ++++++++ run/SimExamples/Inspect_Hits/run.sh | 34 ++++++ .../Inspect_Hits/secondary_and_hits.macro | 49 ++++++++ run/SimExamples/Inspect_Hits/style.macro | 110 ++++++++++++++++++ 7 files changed, 423 insertions(+) create mode 100644 run/SimExamples/Inspect_Hits/left_trace.macro create mode 100644 run/SimExamples/Inspect_Hits/plot_primary.macro create mode 100644 run/SimExamples/Inspect_Hits/plot_secondary.macro create mode 100644 run/SimExamples/Inspect_Hits/primary_and_hits.macro create mode 100755 run/SimExamples/Inspect_Hits/run.sh create mode 100644 run/SimExamples/Inspect_Hits/secondary_and_hits.macro create mode 100644 run/SimExamples/Inspect_Hits/style.macro diff --git a/run/SimExamples/Inspect_Hits/left_trace.macro b/run/SimExamples/Inspect_Hits/left_trace.macro new file mode 100644 index 0000000000000..3c3adb6bd033f --- /dev/null +++ b/run/SimExamples/Inspect_Hits/left_trace.macro @@ -0,0 +1,73 @@ +bool +leftTrace_golden(o2::MCTrack& t) +{ + bool trace = false; + trace |= t.leftTrace(o2::detectors::DetID::ITS); + trace |= t.leftTrace(o2::detectors::DetID::TPC); + trace |= t.leftTrace(o2::detectors::DetID::TRD); + trace |= t.leftTrace(o2::detectors::DetID::TOF); + return trace; +} + +bool +leftTrace_barrel(o2::MCTrack& t) +{ + bool trace = false; + trace |= t.leftTrace(o2::detectors::DetID::ITS); + trace |= t.leftTrace(o2::detectors::DetID::TPC); + trace |= t.leftTrace(o2::detectors::DetID::TRD); + trace |= t.leftTrace(o2::detectors::DetID::TOF); + trace |= t.leftTrace(o2::detectors::DetID::HMP); + trace |= t.leftTrace(o2::detectors::DetID::EMC); + trace |= t.leftTrace(o2::detectors::DetID::PHS); + trace |= t.leftTrace(o2::detectors::DetID::FV0); + trace |= t.leftTrace(o2::detectors::DetID::FT0); + return trace; +} + +bool +leftTrace_muon(o2::MCTrack& t) +{ + bool trace = false; + trace |= t.leftTrace(o2::detectors::DetID::ITS); + trace |= t.leftTrace(o2::detectors::DetID::FV0); + trace |= t.leftTrace(o2::detectors::DetID::FT0); + trace |= t.leftTrace(o2::detectors::DetID::MFT); + trace |= t.leftTrace(o2::detectors::DetID::MCH); + trace |= t.leftTrace(o2::detectors::DetID::MID); + return trace; +} + +bool +leftTrace_any(o2::MCTrack& t) +{ + return leftTrace_barrel(t) || leftTrace_muon(t); +} + + +std::function leftTrace_selected = leftTrace_barrel; + +/* +std::map leftTrace = { + {"golden", leftTrace_golden}, + {"barrel", leftTrace_barrel}, + {"muon" , leftTrace_muon} , + {"any" , leftTrace_any} +}; +*/ + +bool +leftTrace(o2::MCTrack& t, vector* tracks) { + if (leftTrace_selected(t)) return true; // this track has left trace in requested detectors + // if (leftTrace_barrel(t)) return true; // this track has left trace in requested detectors + // check if any of the daughters left trace + auto id1 = t.getFirstDaughterTrackId(); + auto id2 = t.getLastDaughterTrackId(); + if (id1 == -1) return false; // no daughters, no trace + bool trace = false; + for (int id = id1; id <= id2; ++id) { + auto d = tracks->at(id); + trace |= leftTrace(d, tracks); // at least one daughter has left trace + } + return trace; +} diff --git a/run/SimExamples/Inspect_Hits/plot_primary.macro b/run/SimExamples/Inspect_Hits/plot_primary.macro new file mode 100644 index 0000000000000..8873a5e4bca5b --- /dev/null +++ b/run/SimExamples/Inspect_Hits/plot_primary.macro @@ -0,0 +1,54 @@ +#include "style.macro" + +int rebinx = 1; +int rebiny = 1; + +void plot_primary(const char *fname, int pdg); + +void plot_primary(const char *fname) +{ + + std::vector pdgs = {11, 13, 22, 211, 321, 2112, 2212}; + for (int pdg : pdgs) + plot_primary(fname, pdg); + +} + +void +plot_primary(const char *fname, int pdg) +{ + + style(); + gStyle->SetPalette(1); + + auto c = new TCanvas("c", "c", 800, 400); + c->Divide(2, 1); + + auto fin = TFile::Open(fname); + auto hgen = (TH2*)fin->Get(Form("hEtaPtGen_%d", pdg)); + hgen->SetTitle(";#eta;#it{p}_{T} (GeV/#it{c})"); + hgen->RebinX(rebinx); + hgen->RebinY(rebiny); + auto hhit = (TH2*)fin->Get(Form("hEtaPtHit_%d", pdg)); + hhit->SetTitle(";#eta;#it{p}_{T} (GeV/#it{c})"); + hhit->RebinX(rebinx); + hhit->RebinY(rebiny); + + c->cd(1)->SetLogz(); + hgen->Draw("col"); + c->cd(2)->SetLogz(); + hhit->Draw("col"); + + c->cd(2)->SetLogz(); + auto heff = (TH2*)hhit->Clone("heff"); + heff->Divide(hhit, hgen, 1., 1., "B"); + heff->SetMinimum(1.e-3); + heff->SetMaximum(1.); + heff->Draw("col"); + + std::string fnameout = fname; + fnameout.erase(fnameout.find("root"), 4); + fnameout += std::to_string(pdg) + ".png"; + c->SaveAs(fnameout.c_str()); + +} diff --git a/run/SimExamples/Inspect_Hits/plot_secondary.macro b/run/SimExamples/Inspect_Hits/plot_secondary.macro new file mode 100644 index 0000000000000..950178cd1be46 --- /dev/null +++ b/run/SimExamples/Inspect_Hits/plot_secondary.macro @@ -0,0 +1,55 @@ +#include "style.macro" + +int rebinx = 10; +int rebiny = 10; + +void plot_secondary(const char *fname, int pdg); + +void plot_secondary(const char *fname) +{ + + std::vector pdgs = {11, 13, 22, 211, 321, 2112, 2212}; + for (int pdg : pdgs) + plot_secondary(fname, pdg); + +} + + +void +plot_secondary(const char *fname, int pdg) +{ + + style(); + gStyle->SetPalette(1); + + auto c = new TCanvas("c", "c", 800, 400); + c->Divide(2, 1); + + auto fin = TFile::Open(fname); + auto hgen = (TH2*)fin->Get(Form("hZRGen_%d", pdg)); + hgen->SetTitle(";z (cm);R (cm)"); + hgen->RebinX(rebinx); + hgen->RebinY(rebiny); + auto hhit = (TH2*)fin->Get(Form("hZRHit_%d", pdg)); + hhit->SetTitle(";z (cm);R (cm)"); + hhit->RebinX(rebinx); + hhit->RebinY(rebiny); + + c->cd(1)->SetLogz(); + hgen->Draw("col"); + c->cd(2)->SetLogz(); + hhit->Draw("col"); + + c->cd(2)->SetLogz(); + auto heff = (TH2*)hhit->Clone("heff"); + heff->Divide(hhit, hgen, 1., 1., "B"); + heff->SetMinimum(1.e-3); + heff->SetMaximum(1.); + heff->Draw("col"); + + std::string fnameout = fname; + fnameout.erase(fnameout.find("root"), 4); + fnameout += std::to_string(pdg) + ".png"; + c->SaveAs(fnameout.c_str()); + +} diff --git a/run/SimExamples/Inspect_Hits/primary_and_hits.macro b/run/SimExamples/Inspect_Hits/primary_and_hits.macro new file mode 100644 index 0000000000000..dd8ce743d58c0 --- /dev/null +++ b/run/SimExamples/Inspect_Hits/primary_and_hits.macro @@ -0,0 +1,48 @@ +#include "left_trace.macro" + +void +primary_and_hits(const char *fname, std::string where = "barrel") +{ + + if (where.compare("golden") == 0) leftTrace_selected = leftTrace_golden; + if (where.compare("barrel") == 0) leftTrace_selected = leftTrace_barrel; + if (where.compare("muon") == 0) leftTrace_selected = leftTrace_muon; + if (where.compare("any") == 0) leftTrace_selected = leftTrace_any; + + auto fin = TFile::Open(fname); + auto tin = (TTree*)fin->Get("o2sim"); + auto tracks = new vector; + tin->SetBranchAddress("MCTrack", &tracks); + auto nev = tin->GetEntries(); + + std::map hEtaPtGen, hEtaPtHit; + + for (int iev = 0; iev < nev; ++iev) { + tin->GetEntry(iev); + for (int itr = 0; itr < tracks->size(); ++itr) { + auto& t = tracks->at(itr); + if (!t.isPrimary()) continue; + if (!t.isTransported()) continue; + auto pdg = std::abs(t.GetPdgCode()); + if (hEtaPtGen.count(pdg) == 0) { + hEtaPtGen[pdg] = new TH2F(Form("hEtaPtGen_%d", pdg), "", 500, -25, 25., 100, 0., 1.); + hEtaPtHit[pdg] = new TH2F(Form("hEtaPtHit_%d", pdg), "", 500, -25, 25., 100, 0., 1.); + } + + hEtaPtGen[pdg]->Fill(t.GetEta(), t.GetPt()); + + if (!leftTrace(t, tracks)) continue; + + hEtaPtHit[pdg]->Fill(t.GetEta(), t.GetPt()); + + } + } + + std::string foutname = "primary_and_hits." + where + ".root"; + auto fout = TFile::Open(foutname.c_str(), "RECREATE"); + for (auto& h : hEtaPtGen) h.second->Write(); + for (auto& h : hEtaPtHit) h.second->Write(); + fout->Close(); + fin->Close(); + +} diff --git a/run/SimExamples/Inspect_Hits/run.sh b/run/SimExamples/Inspect_Hits/run.sh new file mode 100755 index 0000000000000..e30ba31f424c4 --- /dev/null +++ b/run/SimExamples/Inspect_Hits/run.sh @@ -0,0 +1,34 @@ +#! /usr/bin/env bash + +NRUNS=100 +NJOBS=4 +NEVENTS=1000 +GEANT=TGeant3 + +shopt -s extglob + +for I in $(seq -w 1 $NRUNS); do + + DIR="RUN$I" + mkdir $DIR + cp left_trace.macro $DIR/. + cp primary_and_hits.macro $DIR/. + cp secondary_and_hits.macro $DIR/. + cd $DIR + echo " --- starting run $I" + o2-sim -j $NJOBS -n $NEVENTS -e $GEANT -g pythia8 --skipModules ZDC --configKeyValues "Stack.pruneKine=false" &> o2-sim.log + + root -b -q -l "primary_and_hits.macro(\"o2sim_Kine.root\", \"barrel\")" & + root -b -q -l "primary_and_hits.macro(\"o2sim_Kine.root\", \"muon\")" & + root -b -q -l "primary_and_hits.macro(\"o2sim_Kine.root\", \"any\")" & + + root -b -q -l "secondary_and_hits.macro(\"o2sim_Kine.root\", \"barrel\")" & + root -b -q -l "secondary_and_hits.macro(\"o2sim_Kine.root\", \"muon\")" & + root -b -q -l "secondary_and_hits.macro(\"o2sim_Kine.root\", \"any\")" & + + wait + + rm !(*and_hits.*.root) + + cd .. +done diff --git a/run/SimExamples/Inspect_Hits/secondary_and_hits.macro b/run/SimExamples/Inspect_Hits/secondary_and_hits.macro new file mode 100644 index 0000000000000..9a21924e62b2d --- /dev/null +++ b/run/SimExamples/Inspect_Hits/secondary_and_hits.macro @@ -0,0 +1,49 @@ +#include "left_trace.macro" + +void +secondary_and_hits(const char *fname, std::string where = "barrel") +{ + + if (where.compare("golden") == 0) leftTrace_selected = leftTrace_golden; + if (where.compare("barrel") == 0) leftTrace_selected = leftTrace_barrel; + if (where.compare("muon") == 0) leftTrace_selected = leftTrace_muon; + if (where.compare("any") == 0) leftTrace_selected = leftTrace_any; + + auto fin = TFile::Open(fname); + auto tin = (TTree*)fin->Get("o2sim"); + auto tracks = new vector; + tin->SetBranchAddress("MCTrack", &tracks); + auto nev = tin->GetEntries(); + + std::map hZRGen, hZRHit; + + for (int iev = 0; iev < nev; ++iev) { + tin->GetEntry(iev); + for (int itr = 0; itr < tracks->size(); ++itr) { + auto& t = tracks->at(itr); + if (!t.isTransported()) continue; + auto pdg = std::abs(t.GetPdgCode()); + if (hZRGen.count(pdg) == 0) { + hZRGen[pdg] = new TH2F(Form("hZRGen_%d", pdg), "", 4000, -2000., 2000., 1000, 0., 1000.); + hZRHit[pdg] = new TH2F(Form("hZRHit_%d", pdg), "", 4000, -2000., 2000., 1000, 0., 1000); + } + + auto z = t.GetStartVertexCoordinatesZ(); + auto R = std::hypot(t.GetStartVertexCoordinatesX(), t.GetStartVertexCoordinatesY()); + hZRGen[pdg]->Fill(z, R); + + if (!leftTrace(t, tracks)) continue; + + hZRHit[pdg]->Fill(z, R); + + } + } + + std::string foutname = "secondary_and_hits." + where + ".root"; + auto fout = TFile::Open(foutname.c_str(), "RECREATE"); + for (auto& h : hZRGen) h.second->Write(); + for (auto& h : hZRHit) h.second->Write(); + fout->Close(); + fin->Close(); + +} diff --git a/run/SimExamples/Inspect_Hits/style.macro b/run/SimExamples/Inspect_Hits/style.macro new file mode 100644 index 0000000000000..71e31bff052ce --- /dev/null +++ b/run/SimExamples/Inspect_Hits/style.macro @@ -0,0 +1,110 @@ +#ifndef style_C +#define style_C + +void style() +{ + + gStyle->SetPadColor(0); + gStyle->SetPadBorderSize(0); + gStyle->SetPadBorderMode(0); + gStyle->SetPadTickX(1); + gStyle->SetPadTickY(1); + gStyle->SetCanvasColor(0); + gStyle->SetCanvasBorderMode(0); + gStyle->SetCanvasBorderSize(0); + gStyle->SetFrameBorderMode(0); + //gStyle->SetFrameLineColor(0); + gStyle->SetFrameFillColor(0); + + //gStyle->SetOptStat(00000); + //gStyle->SetTitleColor(0); + gStyle->SetTitleBorderSize(0); + // gStyle->SetTitleTextColor(0); + // gStyle->SetTitleFillColor(0); + + /* + gStyle->SetTitleColor(0); + gStyle->SetTitleBorderSize(0); + gStyle->SetTitleTextColor(0); + gStyle->SetTitleFillColor(0); + */ + // gStyle->SetPalette(1); + gStyle->SetCanvasColor(0); + gStyle->SetHistFillColor(0); + gStyle->SetHistFillStyle(0); + gStyle->SetOptStat(0); + // gStyle->SetPadTickX(1); + // gStyle->SetPadTickY(1); + gStyle->SetAxisColor(1, "X"); + gStyle->SetAxisColor(1, "Y"); + gStyle->SetAxisColor(1, "Z"); + /* + gStyle->SetLabelColor(0, "X"); + gStyle->SetLabelColor(0, "Y"); + gStyle->SetLabelColor(0, "Z"); + gStyle->SetTickLength(0.0, "X"); + gStyle->SetTickLength(0.0, "Y"); + gStyle->SetTickLength(0.0, "Z"); + */ + gStyle->SetTitleXSize(0.05); + gStyle->SetTitleYSize(0.05); + gStyle->SetNdivisions(506, "X"); + gStyle->SetNdivisions(506, "Y"); + gStyle->SetNdivisions(506, "Z"); + + //gStyle->SetPadGridX(1); + //gStyle->SetPadGridY(1); + + //gStyle->SetLabelOffset(0.02, "X"); + //gStyle->SetLabelOffset(0.01, "Y"); + //gStyle->SetLabelOffset(0.02, "Z"); + gStyle->SetLabelSize(0.04, "xyz"); + gStyle->SetTitleOffset(1.2,"xyz"); + gStyle->SetTitleFont(42,"xyz"); + + gStyle->SetTextFont(42); + gStyle->SetTextSize(0.06); + + gStyle->SetPadLeftMargin(0.15); + gStyle->SetPadRightMargin(0.05); + gStyle->SetPadBottomMargin(0.15); + gStyle->SetPadTopMargin(0.05); + + gROOT->ForceStyle(); + +} + +void SetGraphStyle(TGraph *g, Int_t m, Int_t c) +{ + g->SetMarkerStyle(m); + g->SetMarkerColor(c); + g->SetLineColor(c); + g->SetLineWidth(1); + g->SetFillStyle(0); + g->SetFillColor(0); + g->SetMarkerSize(2.0); + if (m == 28 || m == 34 || m == 23 || m == 32 || m == 22) + g->SetMarkerSize(2.5); + if (m == 27 || m == 33 || m == 30 || m == 29) + g->SetMarkerSize(3.0); +} + +void SetHistoStyle(TH1 *h, Int_t m, Int_t c, Int_t w = 1, Int_t s = 1) +{ + h->SetMarkerStyle(m); + h->SetMarkerColor(c); + h->SetLineColor(c); + h->SetLineWidth(w); + h->SetLineStyle(s); + h->SetFillStyle(0); + h->SetFillColor(0); + h->SetMarkerSize(2.0); + if (m == 28 || m == 34 || m == 23 || m == 32 || m == 22) + h->SetMarkerSize(2.5); + if (m == 27 || m == 33 || m == 30 || m == 29) + h->SetMarkerSize(3.0); + if (m == 0) + h->SetMarkerSize(0); +} + +#endif /* style_C */ From cd610d7adb288d74bf4467def9a7897af19713bf Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Sun, 18 Apr 2021 23:59:52 +0200 Subject: [PATCH 163/770] DPL: allow introspection of running workflow from InitContext (#5958) By doing something like: auto &workflow = initContext.get(); a given device can inspect the topology and act accordingly. --- .../include/Framework/DataProcessingDevice.h | 3 +- Framework/Core/include/Framework/DeviceSpec.h | 13 ++- .../include/Framework/RunningWorkflowInfo.h | 29 +++++++ Framework/Core/src/DataProcessingDevice.cxx | 12 +-- Framework/Core/src/runDataProcessing.cxx | 80 ++++++++++--------- .../TestWorkflows/src/o2DiamondWorkflow.cxx | 4 +- 6 files changed, 89 insertions(+), 52 deletions(-) create mode 100644 Framework/Core/include/Framework/RunningWorkflowInfo.h diff --git a/Framework/Core/include/Framework/DataProcessingDevice.h b/Framework/Core/include/Framework/DataProcessingDevice.h index 0d00b99e6a03a..1091f6816875c 100644 --- a/Framework/Core/include/Framework/DataProcessingDevice.h +++ b/Framework/Core/include/Framework/DataProcessingDevice.h @@ -23,6 +23,7 @@ #include "Framework/TimingInfo.h" #include "Framework/TerminationPolicy.h" #include "Framework/Tracing.h" +#include "Framework/RunningWorkflowInfo.h" #include #include @@ -81,7 +82,7 @@ struct DataProcessorContext { class DataProcessingDevice : public FairMQDevice { public: - DataProcessingDevice(DeviceSpec const& spec, ServiceRegistry&, DeviceState& state); + DataProcessingDevice(RunningWorkflowInfo const& runningWorkflow, RunningDeviceRef ref, ServiceRegistry&, DeviceState& state); void Init() final; void InitTask() final; void PreRun() final; diff --git a/Framework/Core/include/Framework/DeviceSpec.h b/Framework/Core/include/Framework/DeviceSpec.h index 4497d556d704d..26670a951a492 100644 --- a/Framework/Core/include/Framework/DeviceSpec.h +++ b/Framework/Core/include/Framework/DeviceSpec.h @@ -7,8 +7,8 @@ // In applying this license CERN does not waive the privileges and immunities // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef FRAMEWORK_DEVICESPEC_H -#define FRAMEWORK_DEVICESPEC_H +#ifndef O2_FRAMEWORK_DEVICESPEC_H_ +#define O2_FRAMEWORK_DEVICESPEC_H_ #include "Framework/WorkflowSpec.h" #include "Framework/ComputingResource.h" @@ -30,9 +30,7 @@ #include #include -namespace o2 -{ -namespace framework +namespace o2::framework { /// Concrete description of the device which will actually run @@ -65,6 +63,5 @@ struct DeviceSpec { unsigned short resourceMonitoringInterval; }; -} // namespace framework -} // namespace o2 -#endif +} // namespace o2::framework +#endif // O2_FRAMEWORK_DEVICESPEC_H_ diff --git a/Framework/Core/include/Framework/RunningWorkflowInfo.h b/Framework/Core/include/Framework/RunningWorkflowInfo.h new file mode 100644 index 0000000000000..fa88bc4b4a599 --- /dev/null +++ b/Framework/Core/include/Framework/RunningWorkflowInfo.h @@ -0,0 +1,29 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. +#ifndef O2_FRAMEWORK_RUNNINGWORKFLOWINFO_H_ +#define O2_FRAMEWORK_RUNNINGWORKFLOWINFO_H_ + +#include "Framework/DeviceSpec.h" +#include + +namespace o2::framework +{ + +struct RunningDeviceRef { + size_t index; // Index in the RunningWorkflowInfo::devices vector; +}; + +/// Information about the running workflow +struct RunningWorkflowInfo { + std::vector devices; +}; + +} // namespace o2::framework +#endif // RunningWorkflowInfo diff --git a/Framework/Core/src/DataProcessingDevice.cxx b/Framework/Core/src/DataProcessingDevice.cxx index 8a380fda37fc9..ce9d582194d70 100644 --- a/Framework/Core/src/DataProcessingDevice.cxx +++ b/Framework/Core/src/DataProcessingDevice.cxx @@ -78,15 +78,15 @@ void idle_timer(uv_timer_t* handle) ZoneScopedN("Idle timer"); } -DataProcessingDevice::DataProcessingDevice(DeviceSpec const& spec, ServiceRegistry& registry, DeviceState& state) - : mSpec{spec}, +DataProcessingDevice::DataProcessingDevice(RunningWorkflowInfo const& runningWorkflow, RunningDeviceRef ref, ServiceRegistry& registry, DeviceState& state) + : mSpec{runningWorkflow.devices[ref.index]}, mState{state}, - mInit{spec.algorithm.onInit}, + mInit{mSpec.algorithm.onInit}, mStatefulProcess{nullptr}, - mStatelessProcess{spec.algorithm.onProcess}, - mError{spec.algorithm.onError}, + mStatelessProcess{mSpec.algorithm.onProcess}, + mError{mSpec.algorithm.onError}, mConfigRegistry{nullptr}, - mAllocator{&mTimingInfo, ®istry, spec.outputs}, + mAllocator{&mTimingInfo, ®istry, mSpec.outputs}, mServiceRegistry{registry} { /// FIXME: move erro handling to a service? diff --git a/Framework/Core/src/runDataProcessing.cxx b/Framework/Core/src/runDataProcessing.cxx index 77b25c4827ec5..81b04a0c69177 100644 --- a/Framework/Core/src/runDataProcessing.cxx +++ b/Framework/Core/src/runDataProcessing.cxx @@ -42,6 +42,7 @@ #include "Framework/DriverInfo.h" #include "Framework/DriverControl.h" #include "Framework/CommandInfo.h" +#include "Framework/RunningWorkflowInfo.h" #include "DriverServerContext.h" #include "ControlServiceHelpers.h" #include "HTTPParser.h" @@ -975,12 +976,14 @@ void doDefaultWorkflowTerminationHook() } int doChild(int argc, char** argv, ServiceRegistry& serviceRegistry, - const o2::framework::DeviceSpec& spec, + RunningWorkflowInfo const& runningWorkflow, + RunningDeviceRef ref, TerminationPolicy errorPolicy, std::string const& defaultDriverClient, uv_loop_t* loop) { fair::Logger::SetConsoleColor(false); + DeviceSpec const& spec = runningWorkflow.devices[ref.index]; LOG(INFO) << "Spawing new device " << spec.id << " in process with pid " << getpid(); try { @@ -1005,6 +1008,8 @@ int doChild(int argc, char** argv, ServiceRegistry& serviceRegistry, std::unique_ptr deviceState; auto afterConfigParsingCallback = [&simpleRawDeviceService, + &runningWorkflow, + ref, &spec, &serviceRegistry, &deviceState, @@ -1017,11 +1022,12 @@ int doChild(int argc, char** argv, ServiceRegistry& serviceRegistry, serviceRegistry.registerService(ServiceRegistryHelpers::handleForService(simpleRawDeviceService.get())); serviceRegistry.registerService(ServiceRegistryHelpers::handleForService(&spec)); + serviceRegistry.registerService(ServiceRegistryHelpers::handleForService(&runningWorkflow)); // The decltype stuff is to be able to compile with both new and old // FairMQ API (one which uses a shared_ptr, the other one a unique_ptr. decltype(r.fDevice) device; - device = std::move(make_matching(spec, serviceRegistry, *deviceState.get())); + device = std::move(make_matching(runningWorkflow, ref, serviceRegistry, *deviceState.get())); dynamic_cast(device.get())->SetErrorPolicy(errorPolicy); serviceRegistry.get().setDevice(device.get()); @@ -1106,7 +1112,7 @@ int runStateMachine(DataProcessorSpecs const& workflow, boost::program_options::variables_map& varmap, std::string frameworkId) { - DeviceSpecs deviceSpecs; + RunningWorkflowInfo runningWorkflow; DeviceInfos infos; DeviceControls controls; DeviceExecutions deviceExecutions; @@ -1125,7 +1131,7 @@ int runStateMachine(DataProcessorSpecs const& workflow, DebugGUI* debugGUI = nullptr; void* window = nullptr; - decltype(debugGUI->getGUIDebugger(infos, deviceSpecs, dataProcessorInfos, metricsInfos, driverInfo, controls, driverControl)) debugGUICallback; + decltype(debugGUI->getGUIDebugger(infos, runningWorkflow.devices, dataProcessorInfos, metricsInfos, driverInfo, controls, driverControl)) debugGUICallback; // An empty frameworkId means this is the driver, so we initialise the GUI if (driverInfo.batch == false && frameworkId.empty()) { @@ -1190,7 +1196,7 @@ int runStateMachine(DataProcessorSpecs const& workflow, serverContext.loop = loop; serverContext.controls = &controls; serverContext.infos = &infos; - serverContext.specs = &deviceSpecs; + serverContext.specs = &runningWorkflow.devices; serverContext.metrics = &metricsInfos; serverContext.driver = &driverInfo; serverContext.metricProcessingCallbacks = &metricProcessingCallbacks; @@ -1319,7 +1325,7 @@ int runStateMachine(DataProcessorSpecs const& workflow, // This state is needed to fill the metadata structure // which contains how to run the current workflow dataProcessorInfos = previousDataProcessorInfos; - for (auto const& device : deviceSpecs) { + for (auto const& device : runningWorkflow.devices) { auto exists = std::find_if(dataProcessorInfos.begin(), dataProcessorInfos.end(), [id = device.id](DataProcessorInfo const& info) -> bool { return info.name == id; }); @@ -1352,14 +1358,14 @@ int runStateMachine(DataProcessorSpecs const& workflow, driverInfo.channelPolicies, driverInfo.completionPolicies, driverInfo.dispatchPolicies, - deviceSpecs, + runningWorkflow.devices, *resourceManager, driverInfo.uniqueWorkflowId, !varmap["no-IPC"].as(), driverInfo.resourcesMonitoringInterval, varmap["channel-prefix"].as()); metricProcessingCallbacks.clear(); - for (auto& device : deviceSpecs) { + for (auto& device : runningWorkflow.devices) { for (auto& service : device.services) { if (service.metricHandling) { metricProcessingCallbacks.push_back(service.metricHandling); @@ -1367,7 +1373,7 @@ int runStateMachine(DataProcessorSpecs const& workflow, } } preScheduleCallbacks.clear(); - for (auto& device : deviceSpecs) { + for (auto& device : runningWorkflow.devices) { for (auto& service : device.services) { if (service.preSchedule) { preScheduleCallbacks.push_back(service.preSchedule); @@ -1375,7 +1381,7 @@ int runStateMachine(DataProcessorSpecs const& workflow, } } postScheduleCallbacks.clear(); - for (auto& device : deviceSpecs) { + for (auto& device : runningWorkflow.devices) { for (auto& service : device.services) { if (service.postSchedule) { postScheduleCallbacks.push_back(service.postSchedule); @@ -1404,10 +1410,12 @@ int runStateMachine(DataProcessorSpecs const& workflow, if (driverControl.defaultStopped) { kill(getpid(), SIGSTOP); } - for (auto& spec : deviceSpecs) { - if (spec.id == frameworkId) { + for (size_t di = 0; di < runningWorkflow.devices.size(); di++) { + RunningDeviceRef ref{di}; + if (runningWorkflow.devices[di].id == frameworkId) { return doChild(driverInfo.argc, driverInfo.argv, - serviceRegistry, spec, + serviceRegistry, + runningWorkflow, ref, driverInfo.errorPolicy, driverInfo.defaultDriverClient, loop); @@ -1418,7 +1426,7 @@ int runStateMachine(DataProcessorSpecs const& workflow, for (auto& processor : workflow) { ss << " - " << processor.name << "\n"; } - for (auto& spec : deviceSpecs) { + for (auto& spec : runningWorkflow.devices) { ss << " - " << spec.name << "(" << spec.id << ")" << "\n"; } @@ -1436,7 +1444,7 @@ int runStateMachine(DataProcessorSpecs const& workflow, // because getGUIDebugger actually recreates the GUI state. if (window) { uv_timer_stop(&gui_timer); - guiContext.callback = debugGUI->getGUIDebugger(infos, deviceSpecs, dataProcessorInfos, metricsInfos, driverInfo, controls, driverControl); + guiContext.callback = debugGUI->getGUIDebugger(infos, runningWorkflow.devices, dataProcessorInfos, metricsInfos, driverInfo, controls, driverControl); guiContext.window = window; gui_timer.data = &guiContext; uv_timer_start(&gui_timer, gui_callback, 0, 20); @@ -1445,8 +1453,8 @@ int runStateMachine(DataProcessorSpecs const& workflow, break; case DriverState::MERGE_CONFIGS: { try { - controls.resize(deviceSpecs.size()); - deviceExecutions.resize(deviceSpecs.size()); + controls.resize(runningWorkflow.devices.size()); + deviceExecutions.resize(runningWorkflow.devices.size()); // Options which should be uniform across all // teh subworkflow invokations. @@ -1474,7 +1482,7 @@ int runStateMachine(DataProcessorSpecs const& workflow, driverControl.defaultStopped, driverInfo.port, dataProcessorInfos, - deviceSpecs, + runningWorkflow.devices, deviceExecutions, controls, driverInfo.uniqueWorkflowId); } catch (o2::framework::RuntimeErrorRef& ref) { @@ -1495,7 +1503,7 @@ int runStateMachine(DataProcessorSpecs const& workflow, LOG(INFO) << "Redeployment of configuration asked."; std::ostringstream forwardedStdin; WorkflowSerializationHelpers::dump(forwardedStdin, workflow, dataProcessorInfos, commandInfo); - infos.reserve(deviceSpecs.size()); + infos.reserve(runningWorkflow.devices.size()); // This is guaranteed to be a single CPU. unsigned parentCPU = -1; @@ -1512,13 +1520,13 @@ int runStateMachine(DataProcessorSpecs const& workflow, for (auto& callback : preScheduleCallbacks) { callback(serviceRegistry, varmap); } - for (size_t di = 0; di < deviceSpecs.size(); ++di) { - if (deviceSpecs[di].resource.hostname != driverInfo.deployHostname) { + for (size_t di = 0; di < runningWorkflow.devices.size(); ++di) { + if (runningWorkflow.devices[di].resource.hostname != driverInfo.deployHostname) { spawnRemoteDevice(forwardedStdin.str(), - deviceSpecs[di], controls[di], deviceExecutions[di], infos); + runningWorkflow.devices[di], controls[di], deviceExecutions[di], infos); } else { spawnDevice(forwardedStdin.str(), - deviceSpecs[di], driverInfo, + runningWorkflow.devices[di], driverInfo, controls[di], deviceExecutions[di], infos, serviceRegistry, varmap, loop, pollHandles, parentCPU, parentNode); } @@ -1545,8 +1553,8 @@ int runStateMachine(DataProcessorSpecs const& workflow, // Let's update the GUI one more time and then EXIT. LOG(INFO) << "Quitting"; driverInfo.states.push_back(DriverState::QUIT_REQUESTED); - } else if (infos.size() != deviceSpecs.size()) { - // If the number of deviceSpecs is different from + } else if (infos.size() != runningWorkflow.devices.size()) { + // If the number of devices is different from // the DeviceInfos it means the speicification // does not match what is running, so we need to do // further scheduling. @@ -1554,11 +1562,11 @@ int runStateMachine(DataProcessorSpecs const& workflow, driverInfo.states.push_back(DriverState::REDEPLOY_GUI); driverInfo.states.push_back(DriverState::SCHEDULE); driverInfo.states.push_back(DriverState::MERGE_CONFIGS); - } else if (deviceSpecs.empty() && driverInfo.batch == true) { + } else if (runningWorkflow.devices.empty() && driverInfo.batch == true) { LOG(INFO) << "No device resulting from the workflow. Quitting."; // If there are no deviceSpecs, we exit. driverInfo.states.push_back(DriverState::EXIT); - } else if (deviceSpecs.empty() && driverInfo.batch == false && !guiDeployedOnce) { + } else if (runningWorkflow.devices.empty() && driverInfo.batch == false && !guiDeployedOnce) { // In case of an empty workflow, we need to deploy the GUI at least once. driverInfo.states.push_back(DriverState::RUNNING); driverInfo.states.push_back(DriverState::REDEPLOY_GUI); @@ -1568,11 +1576,11 @@ int runStateMachine(DataProcessorSpecs const& workflow, { uint64_t inputProcessingStart = uv_hrtime(); auto inputProcessingLatency = inputProcessingStart - inputProcessingLast; - auto outputProcessing = processChildrenOutput(driverInfo, infos, deviceSpecs, controls, metricsInfos); + auto outputProcessing = processChildrenOutput(driverInfo, infos, runningWorkflow.devices, controls, metricsInfos); if (outputProcessing.didProcessMetric) { size_t timestamp = current_time_with_ms(); for (auto& callback : metricProcessingCallbacks) { - callback(serviceRegistry, metricsInfos, deviceSpecs, infos, driverInfo.metrics, timestamp); + callback(serviceRegistry, metricsInfos, runningWorkflow.devices, infos, driverInfo.metrics, timestamp); } for (auto& metricsInfo : metricsInfos) { std::fill(metricsInfo.changed.begin(), metricsInfo.changed.end(), false); @@ -1616,11 +1624,11 @@ int runStateMachine(DataProcessorSpecs const& workflow, } sigchld_requested = false; driverInfo.sigchldRequested = false; - auto outputProcessing = processChildrenOutput(driverInfo, infos, deviceSpecs, controls, metricsInfos); + auto outputProcessing = processChildrenOutput(driverInfo, infos, runningWorkflow.devices, controls, metricsInfos); if (outputProcessing.didProcessMetric) { size_t timestamp = current_time_with_ms(); for (auto& callback : metricProcessingCallbacks) { - callback(serviceRegistry, metricsInfos, deviceSpecs, infos, driverInfo.metrics, timestamp); + callback(serviceRegistry, metricsInfos, runningWorkflow.devices, infos, driverInfo.metrics, timestamp); } } hasError = processSigChild(infos); @@ -1647,7 +1655,7 @@ int runStateMachine(DataProcessorSpecs const& workflow, performanceMetrics.push_back("aod-bytes-read-uncompressed"); performanceMetrics.push_back("aod-bytes-read-compressed"); performanceMetrics.push_back("aod-file-read-info"); - ResourcesMonitoringHelper::dumpMetricsToJSON(metricsInfos, driverInfo.metrics, deviceSpecs, performanceMetrics); + ResourcesMonitoringHelper::dumpMetricsToJSON(metricsInfos, driverInfo.metrics, runningWorkflow.devices, performanceMetrics); } // This is a clean exit. Before we do so, if required, // we dump the configuration of all the devices so that @@ -1659,10 +1667,10 @@ int runStateMachine(DataProcessorSpecs const& workflow, return 0; } boost::property_tree::ptree finalConfig; - assert(infos.size() == deviceSpecs.size()); + assert(infos.size() == runningWorkflow.devices.size()); for (size_t di = 0; di < infos.size(); ++di) { auto info = infos[di]; - auto spec = deviceSpecs[di]; + auto spec = runningWorkflow.devices[di]; finalConfig.put_child(spec.name, info.currentConfig); } LOG(INFO) << "Dumping used configuration in dpl-config.json"; @@ -1672,11 +1680,11 @@ int runStateMachine(DataProcessorSpecs const& workflow, } else { cleanupSHM(driverInfo.uniqueWorkflowId); } - return calculateExitCode(driverInfo, deviceSpecs, infos); + return calculateExitCode(driverInfo, runningWorkflow.devices, infos); } case DriverState::PERFORM_CALLBACKS: for (auto& callback : driverControl.callbacks) { - callback(workflow, deviceSpecs, deviceExecutions, dataProcessorInfos, commandInfo); + callback(workflow, runningWorkflow.devices, deviceExecutions, dataProcessorInfos, commandInfo); } driverControl.callbacks.clear(); break; diff --git a/Framework/TestWorkflows/src/o2DiamondWorkflow.cxx b/Framework/TestWorkflows/src/o2DiamondWorkflow.cxx index f3be6a4a50238..6ca214f31dcb0 100644 --- a/Framework/TestWorkflows/src/o2DiamondWorkflow.cxx +++ b/Framework/TestWorkflows/src/o2DiamondWorkflow.cxx @@ -12,6 +12,7 @@ #include "Framework/DeviceSpec.h" #include "Framework/RawDeviceService.h" #include "Framework/ControlService.h" +#include "Framework/RunningWorkflowInfo.h" #include #include @@ -42,8 +43,9 @@ void customize(std::vector& policies) AlgorithmSpec simplePipe(std::string const& what, int minDelay) { - return AlgorithmSpec{adaptStateful([what, minDelay]() { + return AlgorithmSpec{adaptStateful([what, minDelay](RunningWorkflowInfo const& runningWorkflow) { srand(getpid()); + LOG(INFO) << "There are " << runningWorkflow.devices.size() << " devices in the workflow"; return adaptStateless([what, minDelay](DataAllocator& outputs, RawDeviceService& device) { device.device()->WaitFor(std::chrono::seconds(rand() % 2)); auto& bData = outputs.make(OutputRef{what}, 1); From 7b6453dd5e2f06c8a27ec55ada67793e0a740ade Mon Sep 17 00:00:00 2001 From: Piotr Konopka Date: Mon, 19 Apr 2021 08:57:52 +0200 Subject: [PATCH 164/770] Improvements for Flag Reasons and TRFCollections (#5941) * Provide a default FlagReason constructor for ROOT * Name and Detector getters for TRFCollections --- .../include/DataFormatsQualityControl/FlagReasons.h | 1 + .../DataFormatsQualityControl/TimeRangeFlagCollection.h | 3 +++ DataFormats/QualityControl/src/FlagReasons.cxx | 5 +++++ .../QualityControl/src/TimeRangeFlagCollection.cxx | 9 +++++++++ DataFormats/QualityControl/test/testFlagReasons.cxx | 3 +++ 5 files changed, 21 insertions(+) diff --git a/DataFormats/QualityControl/include/DataFormatsQualityControl/FlagReasons.h b/DataFormats/QualityControl/include/DataFormatsQualityControl/FlagReasons.h index 00e17ffb01e10..933401e001796 100644 --- a/DataFormats/QualityControl/include/DataFormatsQualityControl/FlagReasons.h +++ b/DataFormats/QualityControl/include/DataFormatsQualityControl/FlagReasons.h @@ -43,6 +43,7 @@ class FlagReason FlagReason(uint16_t id, const char* name, bool bad) : mId(id), mName(name), mBad(bad) {} public: + FlagReason(); FlagReason& operator=(const FlagReason&) = default; FlagReason(const FlagReason&) = default; bool operator==(const FlagReason& rhs) const; diff --git a/DataFormats/QualityControl/include/DataFormatsQualityControl/TimeRangeFlagCollection.h b/DataFormats/QualityControl/include/DataFormatsQualityControl/TimeRangeFlagCollection.h index a0dd08c2deb1b..c838eb722906b 100644 --- a/DataFormats/QualityControl/include/DataFormatsQualityControl/TimeRangeFlagCollection.h +++ b/DataFormats/QualityControl/include/DataFormatsQualityControl/TimeRangeFlagCollection.h @@ -54,6 +54,9 @@ class TimeRangeFlagCollection collection_t::const_iterator begin() const; collection_t::const_iterator end() const; + const std::string& getName() const; + const std::string& getDetector() const; + /// write data to ostream void streamTo(std::ostream& output) const; diff --git a/DataFormats/QualityControl/src/FlagReasons.cxx b/DataFormats/QualityControl/src/FlagReasons.cxx index eca5298601002..86f1a37da3814 100644 --- a/DataFormats/QualityControl/src/FlagReasons.cxx +++ b/DataFormats/QualityControl/src/FlagReasons.cxx @@ -16,6 +16,11 @@ namespace o2::quality_control { +FlagReason::FlagReason() +{ + *this = FlagReasonFactory::Invalid(); +} + std::ostream& operator<<(std::ostream& os, FlagReason const& my) { os << "Flag Reason: id - " << my.mId << ", name - " << my.mName << ", bad - " << (my.mBad ? "true" : "false"); diff --git a/DataFormats/QualityControl/src/TimeRangeFlagCollection.cxx b/DataFormats/QualityControl/src/TimeRangeFlagCollection.cxx index a981107596582..626b385856f58 100644 --- a/DataFormats/QualityControl/src/TimeRangeFlagCollection.cxx +++ b/DataFormats/QualityControl/src/TimeRangeFlagCollection.cxx @@ -73,4 +73,13 @@ std::ostream& operator<<(std::ostream& output, const TimeRangeFlagCollection& da return output; } +const std::string& TimeRangeFlagCollection::getName() const +{ + return mName; +} +const std::string& TimeRangeFlagCollection::getDetector() const +{ + return mDetID; +} + } // namespace o2::quality_control \ No newline at end of file diff --git a/DataFormats/QualityControl/test/testFlagReasons.cxx b/DataFormats/QualityControl/test/testFlagReasons.cxx index 4c5d479a75f8e..27936af831a98 100644 --- a/DataFormats/QualityControl/test/testFlagReasons.cxx +++ b/DataFormats/QualityControl/test/testFlagReasons.cxx @@ -27,6 +27,9 @@ BOOST_AUTO_TEST_CASE(FlagReasons) static_assert(std::is_constructible::value == false, "FlagReason should not be constructible outside of its static methods."); + FlagReason rDefault; + BOOST_CHECK_EQUAL(rDefault, FlagReasonFactory::Invalid()); + auto r1 = FlagReasonFactory::Unknown(); BOOST_CHECK_EQUAL(r1.getID(), 1); BOOST_CHECK_EQUAL(r1.getName(), "Unknown"); From b68812e814be757266adf2230429daa12d4931a0 Mon Sep 17 00:00:00 2001 From: shahoian Date: Mon, 19 Apr 2021 10:07:07 +0200 Subject: [PATCH 165/770] Fix: add missing option to its digit reader --- Detectors/ITSMFT/common/workflow/src/DigitReaderSpec.cxx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Detectors/ITSMFT/common/workflow/src/DigitReaderSpec.cxx b/Detectors/ITSMFT/common/workflow/src/DigitReaderSpec.cxx index 9f56dde5900bf..ec6ea26f258dd 100644 --- a/Detectors/ITSMFT/common/workflow/src/DigitReaderSpec.cxx +++ b/Detectors/ITSMFT/common/workflow/src/DigitReaderSpec.cxx @@ -135,7 +135,8 @@ DataProcessorSpec getITSDigitReaderSpec(bool useMC, bool useCalib, std::string d outputSpec, AlgorithmSpec{adaptFromTask(useMC, useCalib)}, Options{ - {"its-digit-infile", VariantType::String, defname, {"Name of the input digit file"}}}}; + {"its-digit-infile", VariantType::String, defname, {"Name of the input digit file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } DataProcessorSpec getMFTDigitReaderSpec(bool useMC, bool useCalib, std::string defname) From f31d3bf0f07b811cdd9ac949a5cd9b731fcd47e2 Mon Sep 17 00:00:00 2001 From: shahoian Date: Fri, 16 Apr 2021 00:48:27 +0200 Subject: [PATCH 166/770] ConfigurableParam to set I/O paths for ConfigurableParam The configurabe KeyValParam allows to set alter the input and output directories for ConfigurableParam INI files e.g. --configKeyValues "keyval.input_dir=XXX;keyval.output_dir=YYY" will make ConfigurableParam::updateFromFile and ConfigurableParam::writeIni methods to use directory XXX instead of current directory --- Common/Utils/CMakeLists.txt | 10 +++--- .../include/CommonUtils/ConfigurableParam.h | 9 +++++ .../Utils/include/CommonUtils/KeyValParam.h | 33 +++++++++++++++++ Common/Utils/src/CommonUtilsLinkDef.h | 3 ++ Common/Utils/src/ConfigurableParam.cxx | 35 +++++++++++++------ Common/Utils/src/KeyValParam.cxx | 15 ++++++++ 6 files changed, 91 insertions(+), 14 deletions(-) create mode 100644 Common/Utils/include/CommonUtils/KeyValParam.h create mode 100644 Common/Utils/src/KeyValParam.cxx diff --git a/Common/Utils/CMakeLists.txt b/Common/Utils/CMakeLists.txt index 87d6ad4ede1c5..9f21534c7a367 100644 --- a/Common/Utils/CMakeLists.txt +++ b/Common/Utils/CMakeLists.txt @@ -11,8 +11,9 @@ o2_add_library(CommonUtils SOURCES src/TreeStream.cxx src/TreeStreamRedirector.cxx src/RootChain.cxx src/CompStream.cxx src/ShmManager.cxx - src/ValueMonitor.cxx + src/ValueMonitor.cxx src/ConfigurableParamHelper.cxx src/ConfigurableParam.cxx src/RootSerializableKeyValueStore.cxx + src/KeyValParam.cxx PUBLIC_LINK_LIBRARIES ROOT::Hist ROOT::Tree Boost::iostreams O2::CommonDataFormat O2::Headers FairLogger::FairLogger) @@ -26,11 +27,12 @@ o2_target_root_dictionary(CommonUtils include/CommonUtils/RngHelper.h include/CommonUtils/StringUtils.h include/CommonUtils/ValueMonitor.h - include/CommonUtils/MemFileHelper.h + include/CommonUtils/MemFileHelper.h include/CommonUtils/ConfigurableParam.h include/CommonUtils/ConfigurableParamHelper.h include/CommonUtils/ConfigurationMacroHelper.h - include/CommonUtils/RootSerializableKeyValueStore.h) + include/CommonUtils/RootSerializableKeyValueStore.h + include/CommonUtils/KeyValParam.h) o2_add_test(TreeStream COMPONENT_NAME CommonUtils @@ -70,5 +72,5 @@ o2_add_test(MemFileHelper o2_add_executable(treemergertool COMPONENT_NAME CommonUtils - SOURCES src/TreeMergerTool.cxx + SOURCES src/TreeMergerTool.cxx PUBLIC_LINK_LIBRARIES O2::CommonUtils Boost::program_options ROOT::Core) diff --git a/Common/Utils/include/CommonUtils/ConfigurableParam.h b/Common/Utils/include/CommonUtils/ConfigurableParam.h index fd3e5dc4bad89..6567927609acb 100644 --- a/Common/Utils/include/CommonUtils/ConfigurableParam.h +++ b/Common/Utils/include/CommonUtils/ConfigurableParam.h @@ -169,6 +169,12 @@ class ConfigurableParam static void printAllRegisteredParamNames(); static void printAllKeyValuePairs(); + static const std::string& getInputDir() { return sInputDir; } + static const std::string& getOutputDir() { return sOutputDir; } + + static void setInputDir(const std::string& d) { sInputDir = d; } + static void setOutputDir(const std::string& d) { sOutputDir = d; } + static boost::property_tree::ptree readINI(std::string const& filepath); static boost::property_tree::ptree readJSON(std::string const& filepath); static boost::property_tree::ptree readConfigFile(std::string const& filepath); @@ -286,6 +292,9 @@ class ConfigurableParam // (stored as a vector of pairs ) static EnumRegistry* sEnumRegistry; + static std::string sInputDir; + static std::string sOutputDir; + void setRegisterMode(bool b) { sRegisterMode = b; } bool isInitialized() const { return sIsFullyInitialized; } diff --git a/Common/Utils/include/CommonUtils/KeyValParam.h b/Common/Utils/include/CommonUtils/KeyValParam.h new file mode 100644 index 0000000000000..173d53fc523ce --- /dev/null +++ b/Common/Utils/include/CommonUtils/KeyValParam.h @@ -0,0 +1,33 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \author ruben.shahoyan@cern.ch +/// \brief params for ConfigurableParam + +#ifndef COMMON_CONFIGURABLE_KEYVAL_PARAM_H_ +#define COMMON_CONFIGURABLE_KEYVAL_PARAM_H_ + +#include "CommonUtils/ConfigurableParam.h" +#include "CommonUtils/ConfigurableParamHelper.h" + +namespace o2 +{ +namespace conf +{ +struct KeyValParam : public o2::conf::ConfigurableParamHelper { + std::string input_dir = "none"; + std::string output_dir = "none"; + + O2ParamDef(KeyValParam, "keyval"); +}; +} // namespace conf +} // namespace o2 + +#endif diff --git a/Common/Utils/src/CommonUtilsLinkDef.h b/Common/Utils/src/CommonUtilsLinkDef.h index 85d699897219a..db1c758ad2549 100644 --- a/Common/Utils/src/CommonUtilsLinkDef.h +++ b/Common/Utils/src/CommonUtilsLinkDef.h @@ -24,4 +24,7 @@ #pragma link C++ class map < string, o2::utils::RootSerializableKeyValueStore::SerializedInfo> + ; #pragma link C++ class o2::utils::RootSerializableKeyValueStore + ; +#pragma link C++ class o2::conf::KeyValParam + ; +#pragma link C++ class o2::conf::ConfigurableParamHelper < o2::conf::KeyValParam> + ; + #endif diff --git a/Common/Utils/src/ConfigurableParam.cxx b/Common/Utils/src/ConfigurableParam.cxx index 8b87114f59ef4..17a85800447a0 100644 --- a/Common/Utils/src/ConfigurableParam.cxx +++ b/Common/Utils/src/ConfigurableParam.cxx @@ -11,6 +11,8 @@ //first version 8/2018, Sandro Wenzel #include "CommonUtils/ConfigurableParam.h" +#include "CommonUtils/StringUtils.h" +#include "CommonUtils/KeyValParam.h" #include #include #include @@ -43,6 +45,8 @@ std::vector* ConfigurableParam::sRegisteredParamClasses = nu boost::property_tree::ptree* ConfigurableParam::sPtree = nullptr; std::map>* ConfigurableParam::sKeyToStorageMap = nullptr; std::map* ConfigurableParam::sValueProvenanceMap = nullptr; +std::string ConfigurableParam::sInputDir = ""; +std::string ConfigurableParam::sOutputDir = ""; EnumRegistry* ConfigurableParam::sEnumRegistry = nullptr; bool ConfigurableParam::sIsFullyInitialized = false; @@ -203,17 +207,18 @@ int EnumLegalValues::getIntValue(const std::string& value) const void ConfigurableParam::writeINI(std::string const& filename, std::string const& keyOnly) { + auto outfilename = o2::utils::concat_string(sOutputDir, filename); initPropertyTree(); // update the boost tree before writing if (!keyOnly.empty()) { // write ini for selected key only try { boost::property_tree::ptree kTree; kTree.add_child(keyOnly, sPtree->get_child(keyOnly)); - boost::property_tree::write_ini(filename, kTree); + boost::property_tree::write_ini(outfilename, kTree); } catch (const boost::property_tree::ptree_bad_path& err) { LOG(FATAL) << "non-existing key " << keyOnly << " provided to writeINI"; } } else { - boost::property_tree::write_ini(filename, *sPtree); + boost::property_tree::write_ini(outfilename, *sPtree); } } @@ -221,16 +226,17 @@ void ConfigurableParam::writeINI(std::string const& filename, std::string const& boost::property_tree::ptree ConfigurableParam::readConfigFile(std::string const& filepath) { - if (!boost::filesystem::exists(filepath)) { - LOG(FATAL) << filepath << " : config file does not exist!"; + auto inpfilename = o2::utils::concat_string(sInputDir, filepath); + if (!boost::filesystem::exists(inpfilename)) { + LOG(FATAL) << inpfilename << " : config file does not exist!"; } boost::property_tree::ptree pt; - if (boost::iends_with(filepath, ".ini")) { - pt = readINI(filepath); - } else if (boost::iends_with(filepath, ".json")) { - pt = readJSON(filepath); + if (boost::iends_with(inpfilename, ".ini")) { + pt = readINI(inpfilename); + } else if (boost::iends_with(inpfilename, ".json")) { + pt = readJSON(inpfilename); } else { LOG(FATAL) << "Configuration file must have either .ini or .json extension"; } @@ -274,16 +280,17 @@ boost::property_tree::ptree ConfigurableParam::readJSON(std::string const& filep void ConfigurableParam::writeJSON(std::string const& filename, std::string const& keyOnly) { initPropertyTree(); // update the boost tree before writing + auto outfilename = o2::utils::concat_string(sOutputDir, filename); if (!keyOnly.empty()) { // write ini for selected key only try { boost::property_tree::ptree kTree; kTree.add_child(keyOnly, sPtree->get_child(keyOnly)); - boost::property_tree::write_json(filename, kTree); + boost::property_tree::write_json(outfilename, kTree); } catch (const boost::property_tree::ptree_bad_path& err) { LOG(FATAL) << "non-existing key " << keyOnly << " provided to writeJSON"; } } else { - boost::property_tree::write_json(filename, *sPtree); + boost::property_tree::write_json(outfilename, *sPtree); } } @@ -533,6 +540,14 @@ void ConfigurableParam::updateFromString(std::string const& configString) auto keyValues = toKeyValPairs(params); setValues(keyValues); + + const auto& kv = o2::conf::KeyValParam::Instance(); + if (getProvenance("keyval.input_dir") != kCODE) { + sInputDir = o2::utils::concat_string(o2::utils::rectifyDirectory(kv.input_dir)); + } + if (getProvenance("keyval.output_dir") != kCODE) { + sOutputDir = o2::utils::concat_string(o2::utils::rectifyDirectory(kv.output_dir)); + } } // setValues takes a vector of pairs where each pair is a key and value diff --git a/Common/Utils/src/KeyValParam.cxx b/Common/Utils/src/KeyValParam.cxx new file mode 100644 index 0000000000000..5e42b85591c42 --- /dev/null +++ b/Common/Utils/src/KeyValParam.cxx @@ -0,0 +1,15 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \author ruben.shahoyan@cern.ch +/// \brief params for ConfigurableParam + +#include "CommonUtils/KeyValParam.h" +O2ParamImpl(o2::conf::KeyValParam); From 0b9cee0834fa001f50a1ef5a2e4af699ce4d3822 Mon Sep 17 00:00:00 2001 From: shahoian Date: Mon, 19 Apr 2021 11:41:30 +0200 Subject: [PATCH 167/770] Fix: add missing option to its cluster reader --- Detectors/ITSMFT/common/workflow/src/ClusterReaderSpec.cxx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Detectors/ITSMFT/common/workflow/src/ClusterReaderSpec.cxx b/Detectors/ITSMFT/common/workflow/src/ClusterReaderSpec.cxx index 4d5e62fc2b4e8..77c8623a8f900 100644 --- a/Detectors/ITSMFT/common/workflow/src/ClusterReaderSpec.cxx +++ b/Detectors/ITSMFT/common/workflow/src/ClusterReaderSpec.cxx @@ -116,7 +116,8 @@ DataProcessorSpec getITSClusterReaderSpec(bool useMC, bool usePatterns) outputSpec, AlgorithmSpec{adaptFromTask(useMC, usePatterns)}, Options{ - {"its-cluster-infile", VariantType::String, "o2clus_its.root", {"Name of the input cluster file"}}}}; + {"its-cluster-infile", VariantType::String, "o2clus_its.root", {"Name of the input cluster file"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; } DataProcessorSpec getMFTClusterReaderSpec(bool useMC, bool usePatterns) From 4648d51745efa03d812f659f6434279eecbe062f Mon Sep 17 00:00:00 2001 From: Ionut Cristian Arsene Date: Mon, 19 Apr 2021 17:31:38 +0200 Subject: [PATCH 168/770] Removed nuclei PID from tableMaker and filterPP; few fixes (#5962) * Several changes (add support for MUON Run3 data model, removed TaskName, etc) * clang changes * a few fixes and changes of task names to avoid name conflicts * Removed nuclei PID from tableMaker and filterPP; few small fixes * clang fix Co-authored-by: Ionut Arsene --- Analysis/PWGDQ/include/PWGDQCore/VarManager.h | 2 +- Analysis/Tasks/PWGDQ/filterPP.cxx | 15 ++++------ Analysis/Tasks/PWGDQ/tableMaker.cxx | 29 ++++++------------- 3 files changed, 15 insertions(+), 31 deletions(-) diff --git a/Analysis/PWGDQ/include/PWGDQCore/VarManager.h b/Analysis/PWGDQ/include/PWGDQCore/VarManager.h index f63bee9b89657..1aca81eb795f0 100644 --- a/Analysis/PWGDQ/include/PWGDQCore/VarManager.h +++ b/Analysis/PWGDQ/include/PWGDQCore/VarManager.h @@ -537,7 +537,7 @@ void VarManager::FillTrack(T const& track, float* values) } } - if constexpr ((fillMap & ReducedMuonExtra) > 0) { + if constexpr ((fillMap & ReducedMuonExtra) > 0 || (fillMap & Muon) > 0) { values[kMuonInvBendingMomentum] = track.inverseBendingMomentum(); values[kMuonThetaX] = track.thetaX(); values[kMuonThetaY] = track.thetaY(); diff --git a/Analysis/Tasks/PWGDQ/filterPP.cxx b/Analysis/Tasks/PWGDQ/filterPP.cxx index 562279300e12e..256cca24b9037 100644 --- a/Analysis/Tasks/PWGDQ/filterPP.cxx +++ b/Analysis/Tasks/PWGDQ/filterPP.cxx @@ -61,20 +61,15 @@ using MyEvents = soa::Join; using MyEventsSelected = soa::Join; using MyBarrelTracks = soa::Join; + aod::pidRespTOFKa, aod::pidRespTOFPr, aod::pidRespTOFbeta>; using MyBarrelTracksSelected = soa::Join; + aod::pidRespTOFKa, aod::pidRespTOFPr, aod::pidRespTOFbeta, + aod::DQBarrelTrackCuts>; constexpr static uint32_t gkEventFillMap = VarManager::ObjTypes::BC | VarManager::ObjTypes::Collision; constexpr static uint32_t gkTrackFillMap = VarManager::ObjTypes::Track | VarManager::ObjTypes::TrackExtra | VarManager::ObjTypes::TrackDCA | VarManager::ObjTypes::TrackSelection | VarManager::ObjTypes::TrackCov | VarManager::ObjTypes::TrackPID; diff --git a/Analysis/Tasks/PWGDQ/tableMaker.cxx b/Analysis/Tasks/PWGDQ/tableMaker.cxx index d429d676f63bc..49085659fc0e4 100644 --- a/Analysis/Tasks/PWGDQ/tableMaker.cxx +++ b/Analysis/Tasks/PWGDQ/tableMaker.cxx @@ -47,12 +47,9 @@ void customize(std::vector& workflowOptions) using MyBarrelTracks = soa::Join; + aod::pidRespTOFKa, aod::pidRespTOFPr, aod::pidRespTOFbeta>; using MyEvents = soa::Join; using MyEventsNoCent = soa::Join; using MyMuons = aod::Muons; @@ -107,17 +104,9 @@ struct TableMaker { // TODO: filter on TPC dedx used temporarily until electron PID will be improved Filter barrelSelectedTracks = aod::track::trackType == uint8_t(aod::track::Run2Track) && o2::aod::track::pt >= fConfigBarrelTrackPtLow && nabs(o2::aod::track::eta) <= 0.9f && o2::aod::track::tpcSignal >= 70.0f && o2::aod::track::tpcSignal <= 100.0f && o2::aod::track::tpcChi2NCl < 4.0f && o2::aod::track::itsChi2NCl < 36.0f; - //Filter barrelSelectedTracks = aod::track::trackType == uint8_t(aod::track::Run2GlobalTrack); - //Filter barrelSelectedTracks = o2::aod::track::pt >= fConfigBarrelTrackPtLow && nabs(o2::aod::track::eta) <= 0.9f; - //Filter trackFilter = aod::track::trackType == aod::track::Run2GlobalTrack; - // TODO: some of the muon variables which could be used in the filter expression are currently DYNAMIC columns (e.g. eta) - // Add more basic muon cuts - // TODO: Use Partition to avoid the cross-talk between filters which use variables with the same name (e.g. pt for both barrel and muon tracks) - - // Replace by Filter when the bug is fixed - Partition selectedMuons = o2::aod::muon::pt >= fConfigMuonPtLow; - //Partition selectedMuons = o2::aod::fwdtrack::pt >= fConfigMuonPtLow; + Filter muonFilter = o2::aod::muon::pt >= fConfigMuonPtLow; + //Filter muonFilter = o2::aod::fwdtrack::pt >= fConfigMuonPtLow; void init(o2::framework::InitContext&) { @@ -150,7 +139,7 @@ struct TableMaker { VarManager::SetUseVars(AnalysisCut::fgUsedVars); // provide the list of required variables so that VarManager knows what to fill } - void process(MyEvent const& collision, MyMuons const& tracksMuon, aod::BCs const& bcs, soa::Filtered const& tracksBarrel) + void process(MyEvent const& collision, soa::Filtered const& tracksMuon, aod::BCs const& bcs, soa::Filtered const& tracksBarrel) { uint32_t triggerAliases = 0; for (int i = 0; i < kNaliases; i++) { @@ -212,9 +201,9 @@ struct TableMaker { track.trdSignal()); } - muonBasic.reserve(selectedMuons.size()); - muonExtra.reserve(selectedMuons.size()); - for (auto& muon : selectedMuons) { + muonBasic.reserve(tracksMuon.size()); + muonExtra.reserve(tracksMuon.size()); + for (auto& muon : tracksMuon) { if (muon.bcId() != collision.bcId()) { continue; } @@ -261,7 +250,7 @@ struct TableMaker { } if (classStr.Contains("Track")) { - dqhistograms::DefineHistograms(fHistMan, objArray->At(iclass)->GetName(), "track", "dca,its,tpcpid"); + dqhistograms::DefineHistograms(fHistMan, objArray->At(iclass)->GetName(), "track", "dca,its,tpcpid,tofpid"); } if (classStr.Contains("Muons")) { dqhistograms::DefineHistograms(fHistMan, objArray->At(iclass)->GetName(), "track", "muon"); From 40507b1206a719a245071b68a6db3e59f06f9c8c Mon Sep 17 00:00:00 2001 From: Sylvain Chapeland Date: Wed, 14 Apr 2021 11:24:34 +0200 Subject: [PATCH 169/770] readout.exe renaming --- Detectors/Raw/README.md | 2 +- Framework/TestWorkflows/README | 2 +- prodtests/full-system-test/convert-raw-to-tf-file.sh | 6 +++--- prodtests/full-system-test/generate_timeframe_files.sh | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Detectors/Raw/README.md b/Detectors/Raw/README.md index c10eacac4a0b7..37a40afea6739 100644 --- a/Detectors/Raw/README.md +++ b/Detectors/Raw/README.md @@ -48,7 +48,7 @@ See `Detectors/Raw/test/testHBFUtils.cxx` for details of usage of this class (al ## RawFileWriter A class to facilitate writing to files the MC data converted to raw data payload. Payload will be formatted according to CRU data -specifications and should be simular to produced by the readout.exe (and can be pumped into the DPL workflows) +specifications and should be simular to produced by the o2-readout-exe (and can be pumped into the DPL workflows) The detector code for MC to raw conversion should instatiate the RawFileWriter object and: diff --git a/Framework/TestWorkflows/README b/Framework/TestWorkflows/README index 6c55ce5170819..e5d5cd1127e0d 100644 --- a/Framework/TestWorkflows/README +++ b/Framework/TestWorkflows/README @@ -34,4 +34,4 @@ follows: --readout-proxy '--channel-config "name=readout-proxy,type=pair,method=connect,transport=shmem,address=ipc:///tmp/readout-pipe-0,rateLogging=1"' -These must match appropriately the configuration of `readout.exe`. +These must match appropriately the configuration of `o2-readout-exe`. diff --git a/prodtests/full-system-test/convert-raw-to-tf-file.sh b/prodtests/full-system-test/convert-raw-to-tf-file.sh index d642a54fb889a..e0675a35c103e 100755 --- a/prodtests/full-system-test/convert-raw-to-tf-file.sh +++ b/prodtests/full-system-test/convert-raw-to-tf-file.sh @@ -5,8 +5,8 @@ if [ `which StfBuilder 2> /dev/null | wc -l` == "0" ]; then echo ERROR: StfBuilder is not in the path exit 1 fi -if [ `which readout.exe 2> /dev/null | wc -l` == "0" ]; then - echo ERROR: readout.exe is not in the path +if [ `which o2-readout-exe 2> /dev/null | wc -l` == "0" ]; then + echo ERROR: o2-readout-exe is not in the path exit 1 fi @@ -29,7 +29,7 @@ sleep 15 echo Starting Readout export INFOLOGGER_OPTIONS="floodProtection=0" -readout.exe file:rdo_TF.cfg &> readout.log & +o2-readout-exe file:rdo_TF.cfg &> readout.log & RD_PID=$! echo Readout PID: $RD_PID diff --git a/prodtests/full-system-test/generate_timeframe_files.sh b/prodtests/full-system-test/generate_timeframe_files.sh index bee158db6954d..c297712b67a21 100755 --- a/prodtests/full-system-test/generate_timeframe_files.sh +++ b/prodtests/full-system-test/generate_timeframe_files.sh @@ -16,8 +16,8 @@ if [ `which StfBuilder 2> /dev/null | wc -l` == "0" ]; then echo ERROR: StfBuilder is not in the path exit 1 fi -if [ `which readout.exe 2> /dev/null | wc -l` == "0" ]; then - echo ERROR: readout.exe is not in the path +if [ `which o2-readout-exe 2> /dev/null | wc -l` == "0" ]; then + echo ERROR: o2-readout-exe is not in the path exit 1 fi if [ "0$O2_ROOT" == "0" ]; then From e0c73969c5a9d34bb255142100e7a0c8d220f022 Mon Sep 17 00:00:00 2001 From: Matthias Richter Date: Tue, 20 Apr 2021 09:42:45 +0200 Subject: [PATCH 170/770] Adding std vector header (#5963) Fixing a compilation error, need to include vector header. modified: Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.h --- Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.h | 1 + 1 file changed, 1 insertion(+) diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.h b/Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.h index ef6d896b760b5..e2d2710c7a05c 100644 --- a/Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.h +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.h @@ -14,6 +14,7 @@ #include "DigitFileFormat.h" #include #include +#include namespace o2::mch { From b654614b5299b3da93cc2599a8e073fbcf35856e Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Tue, 20 Apr 2021 09:43:31 +0200 Subject: [PATCH 171/770] DPL Analysis: enable index tables building from joins (#5961) * Joins (including extended tables) can now be used as Key and as index base for index tables * Updated assocoatedDerived.cxx example to demonstrate the usage * Added global index to HMPIDs table so it can be used for index building --- Analysis/Tutorials/src/associatedExample.cxx | 30 ++++++++++++++++++- Framework/Core/include/Framework/ASoA.h | 10 ++++++- .../include/Framework/AnalysisDataModel.h | 1 + .../Core/include/Framework/AnalysisHelpers.h | 20 +++++++++---- Framework/Core/src/AnalysisManagers.h | 15 ++++++++-- 5 files changed, 66 insertions(+), 10 deletions(-) diff --git a/Analysis/Tutorials/src/associatedExample.cxx b/Analysis/Tutorials/src/associatedExample.cxx index 225fe188dab9a..e0d99d633ffd8 100644 --- a/Analysis/Tutorials/src/associatedExample.cxx +++ b/Analysis/Tutorials/src/associatedExample.cxx @@ -30,6 +30,14 @@ DECLARE_SOA_COLUMN(Mult, mult, int32_t); DECLARE_SOA_TABLE(CollisionsExtra, "AOD", "COLEXTRA", collision::Mult); + +namespace indices +{ +DECLARE_SOA_INDEX_COLUMN(Track, track); +DECLARE_SOA_INDEX_COLUMN(HMPID, hmpid); +} // namespace indices + +DECLARE_SOA_INDEX_TABLE_USER(HMPIDTracksIndex, Tracks, "HMPIDTRKIDX", indices::TrackId, indices::HMPIDId); } // namespace o2::aod using namespace o2; @@ -118,6 +126,24 @@ struct ZTask { } }; +struct BuildHmpidIndex { + Builds idx; + void init(InitContext const&){}; +}; + +struct ConsumeHmpidIndex { + using exTracks = soa::Join; + void process(aod::Collision const& collision, exTracks const& tracks, aod::HMPIDs const&) + { + LOGF(INFO, "Collision [%d]", collision.globalIndex()); + for (auto& track : tracks) { + if (track.has_hmpid()) { + LOGF(INFO, "Track %d has HMPID info: %.2f", track.globalIndex(), track.hmpid().hmpidSignal()); + } + } + } +}; + WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { return WorkflowSpec{ @@ -125,5 +151,7 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) adaptAnalysisTask(cfgc, TaskName{"consume-etaphi"}), adaptAnalysisTask(cfgc, TaskName{"produce-mult"}), adaptAnalysisTask(cfgc, TaskName{"consume-mult"}), - adaptAnalysisTask(cfgc, TaskName{"partition-mult"})}; + adaptAnalysisTask(cfgc, TaskName{"partition-mult"}), + adaptAnalysisTask(cfgc), + adaptAnalysisTask(cfgc)}; } diff --git a/Framework/Core/include/Framework/ASoA.h b/Framework/Core/include/Framework/ASoA.h index e0ed4e5c059b7..151ea195fc196 100644 --- a/Framework/Core/include/Framework/ASoA.h +++ b/Framework/Core/include/Framework/ASoA.h @@ -119,6 +119,12 @@ constexpr auto make_originals_from_type() } } +template +constexpr auto make_originals_from_type(framework::pack) +{ + return make_originals_from_type(); +} + /// Policy class for columns which are chunked. This /// will make the compiler take the most generic (and /// slow approach). @@ -1502,6 +1508,7 @@ constexpr auto is_binding_compatible_v() using base_table_t = typename _Table_::table_t; \ using expression_pack_t = framework::pack<__VA_ARGS__>; \ using originals = soa::originals_pack_t<_Table_>; \ + using sources = originals; \ static constexpr char const* mLabel = #_Name_ "Extension"; \ static constexpr char const mOrigin[4] = _Origin_; \ static constexpr char const mDescription[16] = _Description_; \ @@ -1531,6 +1538,7 @@ constexpr auto is_binding_compatible_v() using Key = _Key_; \ using index_pack_t = framework::pack<__VA_ARGS__>; \ using originals = decltype(soa::extractBindings(index_pack_t{})); \ + using sources = typename _Name_::sources_t; \ static constexpr char const* mLabel = #_Name_; \ static constexpr char const mOrigin[4] = _Origin_; \ static constexpr char const mDescription[16] = _Description_; \ @@ -1932,7 +1940,7 @@ struct IndexTable : Table, H, Ts...> { using indexing_t = Key; using first_t = typename H::binding_t; using rest_t = framework::pack; - using sources_t = framework::pack; + using sources_t = originals_pack_t; IndexTable(std::shared_ptr table, uint64_t offset = 0) : base_t{table, offset} diff --git a/Framework/Core/include/Framework/AnalysisDataModel.h b/Framework/Core/include/Framework/AnalysisDataModel.h index c6715697ab8a1..42997095efe56 100644 --- a/Framework/Core/include/Framework/AnalysisDataModel.h +++ b/Framework/Core/include/Framework/AnalysisDataModel.h @@ -490,6 +490,7 @@ DECLARE_SOA_COLUMN(HMPIDQMip, hmpidQMip, short); //! } // namespace hmpid DECLARE_SOA_TABLE(HMPIDs, "AOD", "HMPID", //! + o2::soa::Index<>, hmpid::TrackId, hmpid::HMPIDSignal, hmpid::HMPIDDistance, diff --git a/Framework/Core/include/Framework/AnalysisHelpers.h b/Framework/Core/include/Framework/AnalysisHelpers.h index b3bedf085dfd5..801cb1a1d3bd0 100644 --- a/Framework/Core/include/Framework/AnalysisHelpers.h +++ b/Framework/Core/include/Framework/AnalysisHelpers.h @@ -117,7 +117,8 @@ struct Produces> : WritingCursor struct TableTransform { - using SOURCES = typename METADATA::originals; + using SOURCES = typename METADATA::sources; + using ORIGINALS = typename METADATA::originals; using metadata = METADATA; using sources = SOURCES; @@ -127,6 +128,11 @@ struct TableTransform { return SOURCES{}; } + constexpr auto originals_pack() const + { + return ORIGINALS{}; + } + template constexpr auto base_spec() const { @@ -283,8 +289,7 @@ struct IndexSparse { using rest_it_t = decltype(pack_from_tuple(iterators)); - int32_t idx = -1; - auto setValue = [&](auto& x) -> bool { + auto setValue = [&](auto& x, int idx) -> bool { using type = std::decay_t; constexpr auto position = framework::has_type_at_v(rest_it_t{}); @@ -309,10 +314,15 @@ struct IndexSparse { auto first = std::get(tables); for (auto& row : first) { - idx = row.template getId(); + auto idx = -1; + if constexpr (std::is_same_v) { + idx = row.globalIndex(); + } else { + idx = row.template getId(); + } std::apply( [&](auto&... x) { - (setValue(x), ...); + (setValue(x, idx), ...); }, iterators); diff --git a/Framework/Core/src/AnalysisManagers.h b/Framework/Core/src/AnalysisManagers.h index 896eef532a69c..f069a9591b4d6 100644 --- a/Framework/Core/src/AnalysisManagers.h +++ b/Framework/Core/src/AnalysisManagers.h @@ -259,11 +259,20 @@ struct OutputManager> { }; /// Builds specialization +template +static inline auto extractOriginalsVector(framework::pack, ProcessingContext& pc) +{ + return std::vector{extractOriginal(pc)...}; +} + template static inline auto extractTypedOriginal(ProcessingContext& pc) { - ///FIXME: this should be done in invokeProcess() as some of the originals may be compound tables - return O{pc.inputs().get(aod::MetadataTrait::metadata::tableLabel())->asArrowTable()}; + if constexpr (soa::is_type_with_originals_v) { + return O{extractOriginalsVector(soa::originals_pack_t{}, pc)}; + } else { + return O{pc.inputs().get(aod::MetadataTrait::metadata::tableLabel())->asArrowTable()}; + } } template @@ -284,7 +293,7 @@ struct OutputManager> { { return what.build(what.pack(), extractTypedOriginal::Key>(pc), - extractOriginalsTuple(what.sources_pack(), pc)); + extractOriginalsTuple(what.originals_pack(), pc)); } static bool finalize(ProcessingContext& pc, Builds& what) From aca9b9665a71133be2562de21130c6ed6ed56427 Mon Sep 17 00:00:00 2001 From: Piotr Konopka Date: Tue, 20 Apr 2021 09:56:59 +0200 Subject: [PATCH 172/770] AliECS dump: connect to the correct pipelined devices (#5924) Devices which are replicated have `_t` added at the end of the name, which we didn't respect in the generated workflow. Thus we should use `id` instead of `name`. --- Framework/Core/src/O2ControlHelpers.cxx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Framework/Core/src/O2ControlHelpers.cxx b/Framework/Core/src/O2ControlHelpers.cxx index 08f6f147006fc..19709cd007449 100644 --- a/Framework/Core/src/O2ControlHelpers.cxx +++ b/Framework/Core/src/O2ControlHelpers.cxx @@ -216,12 +216,12 @@ std::string findBinder(const std::vector& specs, const std::string& for (const auto& spec : specs) { for (const auto& inputChannel : spec.inputChannels) { if (inputChannel.method == ChannelMethod::Bind && inputChannel.name == channel) { - return spec.name; + return spec.id; } } for (const auto& outputChannel : spec.outputChannels) { if (outputChannel.method == ChannelMethod::Bind && outputChannel.name == channel) { - return spec.name; + return spec.id; } } } @@ -368,4 +368,4 @@ void dumpDeviceSpec2O2Control(std::string workflowName, } } -} // namespace o2::framework \ No newline at end of file +} // namespace o2::framework From 1a6371bf3473aa199175ac669502296c4f5c9460 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADt=20Ku=C4=8Dera?= Date: Tue, 20 Apr 2021 09:58:49 +0200 Subject: [PATCH 173/770] PWGHF: Several minor code improvements. (#5964) --- .../include/AnalysisCore/HFConfigurables.h | 25 ++- .../include/AnalysisCore/HFSelectorCuts.h | 162 +++++++++-------- .../Core/include/AnalysisCore/RecoDecay.h | 2 +- .../AnalysisDataModel/HFSecondaryVertex.h | 42 +++-- .../Tasks/PWGHF/HFCandidateCreator2Prong.cxx | 28 +-- .../Tasks/PWGHF/HFCandidateCreator3Prong.cxx | 34 ++-- .../Tasks/PWGHF/HFD0CandidateSelector.cxx | 46 ++--- .../PWGHF/HFDplusToPiKPiCandidateSelector.cxx | 24 +-- .../PWGHF/HFJpsiToEECandidateSelector.cxx | 26 +-- .../Tasks/PWGHF/HFLcCandidateSelector.cxx | 33 ++-- Analysis/Tasks/PWGHF/HFMCValidation.cxx | 40 ++-- .../Tasks/PWGHF/HFTrackIndexSkimsCreator.cxx | 171 +++++++++--------- Analysis/Tasks/PWGHF/HFTreeCreatorD0ToKPi.cxx | 7 +- .../Tasks/PWGHF/HFTreeCreatorLcToPKPi.cxx | 4 +- .../PWGHF/HFXicToPKPiCandidateSelector.cxx | 33 ++-- Analysis/Tasks/PWGHF/taskBPlus.cxx | 5 +- Analysis/Tasks/PWGHF/taskD0.cxx | 23 +-- Analysis/Tasks/PWGHF/taskDPlus.cxx | 20 +- Analysis/Tasks/PWGHF/taskJpsi.cxx | 23 +-- Analysis/Tasks/PWGHF/taskLc.cxx | 28 +-- Analysis/Tasks/PWGHF/taskX.cxx | 4 +- Analysis/Tasks/PWGHF/taskXic.cxx | 27 +-- 22 files changed, 398 insertions(+), 409 deletions(-) diff --git a/Analysis/Core/include/AnalysisCore/HFConfigurables.h b/Analysis/Core/include/AnalysisCore/HFConfigurables.h index 8ee314da4d83f..88458bccd3ca3 100644 --- a/Analysis/Core/include/AnalysisCore/HFConfigurables.h +++ b/Analysis/Core/include/AnalysisCore/HFConfigurables.h @@ -8,14 +8,14 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -// HF Configurable Classes -// -// Authors: Nima Zardoshti +/// \file HFConfigurables.h +/// \brief Heavy-flavour candidate preselection configurables for HFTrackIndexSkimsCreator +/// +/// \author Nima Zardoshti , CERN #ifndef O2_ANALYSIS_HFCONFIGURABLES_H #define O2_ANALYSIS_HFCONFIGURABLES_H -#include #include class HFTrackIndexSkimsCreatorConfigs @@ -24,37 +24,42 @@ class HFTrackIndexSkimsCreatorConfigs HFTrackIndexSkimsCreatorConfigs() = default; ~HFTrackIndexSkimsCreatorConfigs() = default; - // 2-prong cuts D0ToPiK + // 2-prong cuts + + // D0ToPiK double mPtD0ToPiKMin = 4.; //original value 0. double mInvMassD0ToPiKMin = 1.46; double mInvMassD0ToPiKMax = 2.26; double mCPAD0ToPiKMin = 0.75; double mImpParProductD0ToPiKMax = -0.00005; - // 2-prong cuts JpsiToEE + // JpsiToEE double mPtJpsiToEEMin = 4.; //original value 0. double mInvMassJpsiToEEMin = 2.5; double mInvMassJpsiToEEMax = 4.1; double mCPAJpsiToEEMin = -2; double mImpParProductJpsiToEEMax = 1000.; - // 3-prong cuts - DPlusToPiKPi + + // 3-prong cuts + + // DPlusToPiKPi double mPtDPlusToPiKPiMin = 4.; //original value 0. double mInvMassDPlusToPiKPiMin = 1.75; //original value 1.7 double mInvMassDPlusToPiKPiMax = 2.0; //original value 2.05 double mCPADPlusToPiKPiMin = 0.5; double mDecLenDPlusToPiKPiMin = 0.; - // 3-prong cuts - LcToPKPi + // LcToPKPi double mPtLcToPKPiMin = 4.; //original value 0. double mInvMassLcToPKPiMin = 2.15; //original value 2.1 double mInvMassLcToPKPiMax = 2.45; //original value 2.5 double mCPALcToPKPiMin = 0.5; double mDecLenLcToPKPiMin = 0.; - // 3-prong cuts - DsToPiKK + // DsToPiKK double mPtDsToPiKKMin = 4.; //original value 0. double mInvMassDsToPiKKMin = 1.75; //original value 1.7 double mInvMassDsToPiKKMax = 2.15; //original value 2.2 double mCPADsToPiKKMin = 0.5; double mDecLenDsToPiKKMin = 0.; - // 3-prong cuts - XicToPKPi + // XicToPKPi double mPtXicToPKPiMin = 1.; // double mInvMassXicToPKPiMin = 2.25; // double mInvMassXicToPKPiMax = 2.70; // diff --git a/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h b/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h index 054ba659d51f5..6909a9de4069d 100644 --- a/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h +++ b/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h @@ -8,16 +8,21 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +/// \file HFSelectorCuts.h +/// \brief Default pT bins and cut arrays for heavy-flavour selectors and analysis tasks + #ifndef HF_SELECTOR_CUTS_H_ #define HF_SELECTOR_CUTS_H_ + #include "Framework/Configurable.h" #include #include + namespace o2::analysis { namespace pdg { -enum code { +enum Code { kD0 = 421, kD0bar = -421, kDPlus = 411, @@ -25,9 +30,13 @@ enum code { kXiCPlus = 4232, kJpsi = 443 }; -} +} // namespace pdg -// accounts for the offset so that pt bin array can be used to also configure a histogram axis +/// Finds pT bin in a configurable array. +/// \param bins array of pT bins +/// \param value pT +/// \return index of the pT bin +/// \note Accounts for the offset so that pt bin array can be used to also configure a histogram axis. template int findBin(o2::framework::Configurable> const& bins, T2 value) { @@ -41,6 +50,7 @@ int findBin(o2::framework::Configurable> const& bins, T2 value) } // namespace per channel + namespace hf_cuts_single_track { static constexpr int npTBinsTrack = 6; @@ -109,31 +119,31 @@ constexpr double pTBins[npTBins + 1] = { auto pTBins_v = std::vector{pTBins, pTBins + npTBins + 1}; // default values for the cuts -constexpr double cuts[npTBins][nCutVars] = {{0.400, 350. * 1E-4, 0.8, 0.5, 0.5, 1000. * 1E-4, 1000. * 1E-4, -5000. * 1E-8, 0.80, 0., 0.}, /* pt<0.5*/ - {0.400, 350. * 1E-4, 0.8, 0.5, 0.5, 1000. * 1E-4, 1000. * 1E-4, -5000. * 1E-8, 0.80, 0., 0.}, /* 0.550 */ +constexpr double cuts[npTBins][nCutVars] = {{0.400, 350. * 1E-4, 0.8, 0.5, 0.5, 1000. * 1E-4, 1000. * 1E-4, -5000. * 1E-8, 0.80, 0., 0.}, /* 0 < pT < 0.5 */ + {0.400, 350. * 1E-4, 0.8, 0.5, 0.5, 1000. * 1E-4, 1000. * 1E-4, -5000. * 1E-8, 0.80, 0., 0.}, /* 0.5 < pT < 1 */ + {0.400, 300. * 1E-4, 0.8, 0.4, 0.4, 1000. * 1E-4, 1000. * 1E-4, -25000. * 1E-8, 0.80, 0., 0.}, /* 1 < pT < 1.5 */ + {0.400, 300. * 1E-4, 0.8, 0.4, 0.4, 1000. * 1E-4, 1000. * 1E-4, -25000. * 1E-8, 0.80, 0., 0.}, /* 1.5 < pT < 2 */ + {0.400, 300. * 1E-4, 0.8, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, -20000. * 1E-8, 0.90, 0., 0.}, /* 2 < pT < 2.5 */ + {0.400, 300. * 1E-4, 0.8, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, -20000. * 1E-8, 0.90, 0., 0.}, /* 2.5 < pT < 3 */ + {0.400, 300. * 1E-4, 0.8, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, -12000. * 1E-8, 0.85, 0., 0.}, /* 3 < pT < 3.5 */ + {0.400, 300. * 1E-4, 0.8, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, -12000. * 1E-8, 0.85, 0., 0.}, /* 3.5 < pT < 4 */ + {0.400, 300. * 1E-4, 0.8, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, -8000. * 1E-8, 0.85, 0., 0.}, /* 4 < pT < 4.5 */ + {0.400, 300. * 1E-4, 0.8, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, -8000. * 1E-8, 0.85, 0., 0.}, /* 4.5 < pT < 5 */ + {0.400, 300. * 1E-4, 0.8, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, -8000. * 1E-8, 0.85, 0., 0.}, /* 5 < pT < 5.5 */ + {0.400, 300. * 1E-4, 0.8, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, -8000. * 1E-8, 0.85, 0., 0.}, /* 5.5 < pT < 6 */ + {0.400, 300. * 1E-4, 0.8, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, -8000. * 1E-8, 0.85, 0., 0.}, /* 6 < pT < 6.5 */ + {0.400, 300. * 1E-4, 0.8, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, -8000. * 1E-8, 0.85, 0., 0.}, /* 6.5 < pT < 7 */ + {0.400, 300. * 1E-4, 0.8, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, -7000. * 1E-8, 0.85, 0., 0.}, /* 7 < pT < 7.5 */ + {0.400, 300. * 1E-4, 0.8, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, -7000. * 1E-8, 0.85, 0., 0.}, /* 7.5 < pT < 8 */ + {0.400, 300. * 1E-4, 0.9, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, -5000. * 1E-8, 0.85, 0., 0.}, /* 8 < pT < 9 */ + {0.400, 300. * 1E-4, 0.9, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, -5000. * 1E-8, 0.85, 0., 0.}, /* 9 < pT < 10 */ + {0.400, 300. * 1E-4, 0.9, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, -5000. * 1E-8, 0.85, 0., 0.}, /* 10 < pT < 12 */ + {0.400, 300. * 1E-4, 1.0, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, 10000. * 1E-8, 0.85, 0., 0.}, /* 12 < pT < 16 */ + {0.400, 300. * 1E-4, 1.0, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, 999999. * 1E-8, 0.85, 0., 0.}, /* 16 < pT < 20 */ + {0.400, 300. * 1E-4, 1.0, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, 999999. * 1E-8, 0.85, 0., 0.}, /* 20 < pT < 24 */ + {0.400, 300. * 1E-4, 1.0, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, 999999. * 1E-8, 0.85, 0., 0.}, /* 24 < pT < 36 */ + {0.400, 300. * 1E-4, 1.0, 0.7, 0.7, 1000. * 1E-4, 1000. * 1E-4, 999999. * 1E-8, 0.85, 0., 0.}, /* 36 < pT < 50 */ + {0.400, 300. * 1E-4, 1.0, 0.6, 0.6, 1000. * 1E-4, 1000. * 1E-4, 999999. * 1E-8, 0.80, 0., 0.}}; /* 50 < pT < 100 */ // row labels static const std::vector pTBinLabels = { @@ -188,16 +198,16 @@ constexpr double pTBins[npTBins + 1] = { auto pTBins_v = std::vector{pTBins, pTBins + npTBins + 1}; // default values for the cuts -constexpr double cuts[npTBins][nCutVars] = {{0.400, 0.4, 0.4, 0.4, 0.05, 0.09, 0.005, 0.}, /* pt<1 */ - {0.400, 0.4, 0.4, 0.4, 0.05, 0.09, 0.005, 0.}, /* 1 pTBinLabels = { @@ -237,20 +247,21 @@ constexpr double pTBins[npTBins + 1] = { 24., 36.}; auto pTBins_v = std::vector{pTBins, pTBins + npTBins + 1}; -//selections from pp at 5 TeV 2017 analysis https://alice-notes.web.cern.ch/node/808 -//variables: deltaInvMass ptPi ptK DecayLength NormalizedDecayLengthXY CosP CosPXY MaxNormalisedDeltaIP -constexpr double cuts[npTBins][nCutVars] = {{0.2, 0.3, 0.3, 0.07, 6., 0.96, 0.985, 2.5}, /* 1 pTBinLabels = { @@ -270,6 +281,7 @@ static const std::vector pTBinLabels = { // column labels static const std::vector cutVarLabels = {"deltaM", "pT Pi", "pT K", "decay length", "normalized decay length XY", "cos pointing angle", "cos pointing angle XY", "max normalized deltaIP"}; } // namespace hf_cuts_dplus_topikpi + namespace hf_cuts_xic_topkpi { static const int npTBins = 10; @@ -289,17 +301,18 @@ constexpr double pTBins[npTBins + 1] = { 24., 36.}; auto pTBins_v = std::vector{pTBins, pTBins + npTBins + 1}; -// m ptp ptk ptpi DCA sigmavtx dlenght cosp -constexpr double cuts[npTBins][nCutVars] = {{0.400, 0.4, 0.4, 0.4, 0.05, 0.09, 0.005, 0.}, /* pt<1 */ - {0.400, 0.4, 0.4, 0.4, 0.05, 0.09, 0.005, 0.}, /* 1 pTBinLabels = { @@ -339,15 +352,16 @@ constexpr double pTBins[npTBins + 1] = { auto pTBins_v = std::vector{pTBins, pTBins + npTBins + 1}; // default values for the cuts -constexpr double cuts[npTBins][nCutVars] = {{0.5, 0.2, 0.4, 1}, /* 0 pTBinLabels = { "pT bin 0", @@ -359,8 +373,10 @@ static const std::vector pTBinLabels = { "pT bin 6", "pT bin 7", "pT bin 8"}; + // column labels static const std::vector cutVarLabels = {"m", "DCA_xy", "DCA_z", "pT El"}; } // namespace hf_cuts_jpsi_toee } // namespace o2::analysis -#endif + +#endif // HF_SELECTOR_CUTS_H_ diff --git a/Analysis/Core/include/AnalysisCore/RecoDecay.h b/Analysis/Core/include/AnalysisCore/RecoDecay.h index 011939c9569b0..740d4ec43247c 100644 --- a/Analysis/Core/include/AnalysisCore/RecoDecay.h +++ b/Analysis/Core/include/AnalysisCore/RecoDecay.h @@ -9,7 +9,7 @@ // or submit itself to any jurisdiction. /// \file RecoDecay.h -/// \brief Implementation of the RecoDecay class. +/// \brief Implementation of the RecoDecay class /// /// \author Vít Kučera , CERN diff --git a/Analysis/DataModel/include/AnalysisDataModel/HFSecondaryVertex.h b/Analysis/DataModel/include/AnalysisDataModel/HFSecondaryVertex.h index 666d2ace1d8da..8d4a61c89cf4a 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/HFSecondaryVertex.h +++ b/Analysis/DataModel/include/AnalysisDataModel/HFSecondaryVertex.h @@ -9,7 +9,7 @@ // or submit itself to any jurisdiction. /// \file HFSecondaryVertex.h -/// \brief Definitions of tables of heavy-flavour decay candidates. +/// \brief Definitions of tables of heavy-flavour decay candidates /// /// \author Gian Michele Innocenti , CERN /// \author Vít Kučera , CERN @@ -19,8 +19,11 @@ #include "Framework/AnalysisDataModel.h" #include "AnalysisCore/RecoDecay.h" +#include "AnalysisCore/HFSelectorCuts.h" #include "AnalysisDataModel/PID/PIDResponse.h" +using namespace o2::analysis; + namespace o2::aod { namespace hf_seltrack @@ -217,19 +220,19 @@ enum DecayType { D0ToPiK = 0, template auto CtD0(const T& candidate) { - return candidate.ct(RecoDecay::getMassPDG(421)); + return candidate.ct(RecoDecay::getMassPDG(pdg::Code::kD0)); } template auto YD0(const T& candidate) { - return candidate.y(RecoDecay::getMassPDG(421)); + return candidate.y(RecoDecay::getMassPDG(pdg::Code::kD0)); } template auto ED0(const T& candidate) { - return candidate.e(RecoDecay::getMassPDG(421)); + return candidate.e(RecoDecay::getMassPDG(pdg::Code::kD0)); } template @@ -247,32 +250,33 @@ auto InvMassD0bar(const T& candidate) template auto CosThetaStarD0(const T& candidate) { - return candidate.cosThetaStar(array{RecoDecay::getMassPDG(kPiPlus), RecoDecay::getMassPDG(kKPlus)}, RecoDecay::getMassPDG(421), 1); + return candidate.cosThetaStar(array{RecoDecay::getMassPDG(kPiPlus), RecoDecay::getMassPDG(kKPlus)}, RecoDecay::getMassPDG(pdg::Code::kD0), 1); } template auto CosThetaStarD0bar(const T& candidate) { - return candidate.cosThetaStar(array{RecoDecay::getMassPDG(kKPlus), RecoDecay::getMassPDG(kPiPlus)}, RecoDecay::getMassPDG(421), 0); + return candidate.cosThetaStar(array{RecoDecay::getMassPDG(kKPlus), RecoDecay::getMassPDG(kPiPlus)}, RecoDecay::getMassPDG(pdg::Code::kD0), 0); } -// Jpsi → e+e- +// J/ψ → e+ e− + template auto CtJpsi(const T& candidate) { - return candidate.ct(RecoDecay::getMassPDG(443)); + return candidate.ct(RecoDecay::getMassPDG(pdg::Code::kJpsi)); } template auto YJpsi(const T& candidate) { - return candidate.y(RecoDecay::getMassPDG(443)); + return candidate.y(RecoDecay::getMassPDG(pdg::Code::kJpsi)); } template auto EJpsi(const T& candidate) { - return candidate.e(RecoDecay::getMassPDG(443)); + return candidate.e(RecoDecay::getMassPDG(pdg::Code::kJpsi)); } template @@ -392,19 +396,19 @@ enum DecayType { DPlusToPiKPi = 0, template auto CtDPlus(const T& candidate) { - return candidate.ct(RecoDecay::getMassPDG(411)); + return candidate.ct(RecoDecay::getMassPDG(pdg::Code::kDPlus)); } template auto YDPlus(const T& candidate) { - return candidate.y(RecoDecay::getMassPDG(411)); + return candidate.y(RecoDecay::getMassPDG(pdg::Code::kDPlus)); } template auto EDPlus(const T& candidate) { - return candidate.e(RecoDecay::getMassPDG(411)); + return candidate.e(RecoDecay::getMassPDG(pdg::Code::kDPlus)); } template @@ -418,19 +422,19 @@ auto InvMassDPlus(const T& candidate) template auto CtLc(const T& candidate) { - return candidate.ct(RecoDecay::getMassPDG(4122)); + return candidate.ct(RecoDecay::getMassPDG(pdg::Code::kLambdaCPlus)); } template auto YLc(const T& candidate) { - return candidate.y(RecoDecay::getMassPDG(4122)); + return candidate.y(RecoDecay::getMassPDG(pdg::Code::kLambdaCPlus)); } template auto ELc(const T& candidate) { - return candidate.e(RecoDecay::getMassPDG(4122)); + return candidate.e(RecoDecay::getMassPDG(pdg::Code::kLambdaCPlus)); } template @@ -450,19 +454,19 @@ auto InvMassLcpiKp(const T& candidate) template auto CtXic(const T& candidate) { - return candidate.ct(RecoDecay::getMassPDG(4232)); + return candidate.ct(RecoDecay::getMassPDG(pdg::Code::kXiCPlus)); } template auto YXic(const T& candidate) { - return candidate.y(RecoDecay::getMassPDG(4232)); + return candidate.y(RecoDecay::getMassPDG(pdg::Code::kXiCPlus)); } template auto EXic(const T& candidate) { - return candidate.e(RecoDecay::getMassPDG(4232)); + return candidate.e(RecoDecay::getMassPDG(pdg::Code::kXiCPlus)); } template diff --git a/Analysis/Tasks/PWGHF/HFCandidateCreator2Prong.cxx b/Analysis/Tasks/PWGHF/HFCandidateCreator2Prong.cxx index 6e652e34c52a3..44268abd4ba9d 100644 --- a/Analysis/Tasks/PWGHF/HFCandidateCreator2Prong.cxx +++ b/Analysis/Tasks/PWGHF/HFCandidateCreator2Prong.cxx @@ -164,24 +164,24 @@ struct HFCandidateCreator2ProngMC { // D0(bar) → π± K∓ //Printf("Checking D0(bar) → π± K∓"); - indexRec = RecoDecay::getMatchedMCRec(particlesMC, arrayDaughters, 421, array{+kPiPlus, -kKPlus}, true, &sign); + indexRec = RecoDecay::getMatchedMCRec(particlesMC, arrayDaughters, pdg::Code::kD0, array{+kPiPlus, -kKPlus}, true, &sign); if (indexRec > -1) { - flag = sign * (1 << D0ToPiK); + flag = sign * (1 << DecayType::D0ToPiK); } - // J/ψ → e+ e- + // J/ψ → e+ e− if (flag == 0) { - //Printf("Checking J/ψ → e+ e-"); - indexRec = RecoDecay::getMatchedMCRec(particlesMC, std::move(arrayDaughters), 443, array{+kElectron, -kElectron}, true); + //Printf("Checking J/ψ → e+ e−"); + indexRec = RecoDecay::getMatchedMCRec(particlesMC, std::move(arrayDaughters), pdg::Code::kJpsi, array{+kElectron, -kElectron}, true); if (indexRec > -1) { - flag = 1 << JpsiToEE; + flag = 1 << DecayType::JpsiToEE; } } // Check whether the particle is non-prompt (from a b quark). if (flag != 0) { auto particle = particlesMC.iteratorAt(indexRec); - origin = (RecoDecay::getMother(particlesMC, particle, 5, true) > -1 ? NonPrompt : Prompt); + origin = (RecoDecay::getMother(particlesMC, particle, kBottom, true) > -1 ? OriginType::NonPrompt : OriginType::Prompt); } rowMCMatchRec(flag, origin); @@ -195,21 +195,21 @@ struct HFCandidateCreator2ProngMC { // D0(bar) → π± K∓ //Printf("Checking D0(bar) → π± K∓"); - if (RecoDecay::isMatchedMCGen(particlesMC, particle, 421, array{+kPiPlus, -kKPlus}, true, &sign)) { - flag = sign * (1 << D0ToPiK); + if (RecoDecay::isMatchedMCGen(particlesMC, particle, pdg::Code::kD0, array{+kPiPlus, -kKPlus}, true, &sign)) { + flag = sign * (1 << DecayType::D0ToPiK); } - // J/ψ → e+ e- + // J/ψ → e+ e− if (flag == 0) { - //Printf("Checking J/ψ → e+ e-"); - if (RecoDecay::isMatchedMCGen(particlesMC, particle, 443, array{+kElectron, -kElectron}, true)) { - flag = 1 << JpsiToEE; + //Printf("Checking J/ψ → e+ e−"); + if (RecoDecay::isMatchedMCGen(particlesMC, particle, pdg::Code::kJpsi, array{+kElectron, -kElectron}, true)) { + flag = 1 << DecayType::JpsiToEE; } } // Check whether the particle is non-prompt (from a b quark). if (flag != 0) { - origin = (RecoDecay::getMother(particlesMC, particle, 5, true) > -1 ? NonPrompt : Prompt); + origin = (RecoDecay::getMother(particlesMC, particle, kBottom, true) > -1 ? OriginType::NonPrompt : OriginType::Prompt); } rowMCMatchGen(flag, origin); diff --git a/Analysis/Tasks/PWGHF/HFCandidateCreator3Prong.cxx b/Analysis/Tasks/PWGHF/HFCandidateCreator3Prong.cxx index 324cb7b661ab4..d87d648c06eb9 100644 --- a/Analysis/Tasks/PWGHF/HFCandidateCreator3Prong.cxx +++ b/Analysis/Tasks/PWGHF/HFCandidateCreator3Prong.cxx @@ -162,9 +162,9 @@ struct HFCandidateCreator3ProngMC { int8_t channel = 0; std::vector arrDaughIndex; std::array arrPDGDaugh; - std::array arrPDGResonant1 = {2212, 313}; // Λc± → p± K* - std::array arrPDGResonant2 = {2224, 321}; // Λc± → Δ(1232)±± K∓ - std::array arrPDGResonant3 = {3124, 211}; // Λc± → Λ(1520) π± + std::array arrPDGResonant1 = {kProton, 313}; // Λc± → p± K* + std::array arrPDGResonant2 = {2224, kKPlus}; // Λc± → Δ(1232)±± K∓ + std::array arrPDGResonant3 = {3124, kPiPlus}; // Λc± → Λ(1520) π± // Match reconstructed candidates. for (auto& candidate : candidates) { @@ -177,17 +177,17 @@ struct HFCandidateCreator3ProngMC { // D± → π± K∓ π± //Printf("Checking D± → π± K∓ π±"); - indexRec = RecoDecay::getMatchedMCRec(particlesMC, arrayDaughters, 411, array{+kPiPlus, -kKPlus, +kPiPlus}, true, &sign); + indexRec = RecoDecay::getMatchedMCRec(particlesMC, arrayDaughters, pdg::Code::kDPlus, array{+kPiPlus, -kKPlus, +kPiPlus}, true, &sign); if (indexRec > -1) { - flag = sign * (1 << DPlusToPiKPi); + flag = sign * (1 << DecayType::DPlusToPiKPi); } // Λc± → p± K∓ π± if (flag == 0) { //Printf("Checking Λc± → p± K∓ π±"); - indexRec = RecoDecay::getMatchedMCRec(particlesMC, arrayDaughters, 4122, array{+kProton, -kKPlus, +kPiPlus}, true, &sign, 2); + indexRec = RecoDecay::getMatchedMCRec(particlesMC, arrayDaughters, pdg::Code::kLambdaCPlus, array{+kProton, -kKPlus, +kPiPlus}, true, &sign, 2); if (indexRec > -1) { - flag = sign * (1 << LcToPKPi); + flag = sign * (1 << DecayType::LcToPKPi); //Printf("Flagging the different Λc± → p± K∓ π± decay channels"); RecoDecay::getDaughters(particlesMC, particlesMC.iteratorAt(indexRec), &arrDaughIndex, array{0}, 1); @@ -210,16 +210,16 @@ struct HFCandidateCreator3ProngMC { // Ξc± → p± K∓ π± if (flag == 0) { //Printf("Checking Ξc± → p± K∓ π±"); - indexRec = RecoDecay::getMatchedMCRec(particlesMC, std::move(arrayDaughters), 4232, array{+kProton, -kKPlus, +kPiPlus}, true, &sign); + indexRec = RecoDecay::getMatchedMCRec(particlesMC, std::move(arrayDaughters), pdg::Code::kXiCPlus, array{+kProton, -kKPlus, +kPiPlus}, true, &sign); if (indexRec > -1) { - flag = sign * (1 << XicToPKPi); + flag = sign * (1 << DecayType::XicToPKPi); } } // Check whether the particle is non-prompt (from a b quark). if (flag != 0) { auto particle = particlesMC.iteratorAt(indexRec); - origin = (RecoDecay::getMother(particlesMC, particle, 5, true) > -1 ? NonPrompt : Prompt); + origin = (RecoDecay::getMother(particlesMC, particle, kBottom, true) > -1 ? OriginType::NonPrompt : OriginType::Prompt); } rowMCMatchRec(flag, origin, channel); @@ -235,15 +235,15 @@ struct HFCandidateCreator3ProngMC { // D± → π± K∓ π± //Printf("Checking D± → π± K∓ π±"); - if (RecoDecay::isMatchedMCGen(particlesMC, particle, 411, array{+kPiPlus, -kKPlus, +kPiPlus}, true, &sign)) { - flag = sign * (1 << DPlusToPiKPi); + if (RecoDecay::isMatchedMCGen(particlesMC, particle, pdg::Code::kDPlus, array{+kPiPlus, -kKPlus, +kPiPlus}, true, &sign)) { + flag = sign * (1 << DecayType::DPlusToPiKPi); } // Λc± → p± K∓ π± if (flag == 0) { //Printf("Checking Λc± → p± K∓ π±"); - if (RecoDecay::isMatchedMCGen(particlesMC, particle, 4122, array{+kProton, -kKPlus, +kPiPlus}, true, &sign, 2)) { - flag = sign * (1 << LcToPKPi); + if (RecoDecay::isMatchedMCGen(particlesMC, particle, pdg::Code::kLambdaCPlus, array{+kProton, -kKPlus, +kPiPlus}, true, &sign, 2)) { + flag = sign * (1 << DecayType::LcToPKPi); //Printf("Flagging the different Λc± → p± K∓ π± decay channels"); RecoDecay::getDaughters(particlesMC, particle, &arrDaughIndex, array{0}, 1); @@ -266,14 +266,14 @@ struct HFCandidateCreator3ProngMC { // Ξc± → p± K∓ π± if (flag == 0) { //Printf("Checking Ξc± → p± K∓ π±"); - if (RecoDecay::isMatchedMCGen(particlesMC, particle, 4232, array{+kProton, -kKPlus, +kPiPlus}, true, &sign)) { - flag = sign * (1 << XicToPKPi); + if (RecoDecay::isMatchedMCGen(particlesMC, particle, pdg::Code::kXiCPlus, array{+kProton, -kKPlus, +kPiPlus}, true, &sign)) { + flag = sign * (1 << DecayType::XicToPKPi); } } // Check whether the particle is non-prompt (from a b quark). if (flag != 0) { - origin = (RecoDecay::getMother(particlesMC, particle, 5, true) > -1 ? NonPrompt : Prompt); + origin = (RecoDecay::getMother(particlesMC, particle, kBottom, true) > -1 ? OriginType::NonPrompt : OriginType::Prompt); } rowMCMatchGen(flag, origin, channel); diff --git a/Analysis/Tasks/PWGHF/HFD0CandidateSelector.cxx b/Analysis/Tasks/PWGHF/HFD0CandidateSelector.cxx index 2c271156b9b9d..2abe0b7bb10a0 100644 --- a/Analysis/Tasks/PWGHF/HFD0CandidateSelector.cxx +++ b/Analysis/Tasks/PWGHF/HFD0CandidateSelector.cxx @@ -9,26 +9,23 @@ // or submit itself to any jurisdiction. /// \file HFD0CandidateSelector.cxx -/// \brief D0 selection task. +/// \brief D0 selection task /// /// \author Nima Zardoshti , CERN #include "Framework/runDataProcessing.h" #include "Framework/AnalysisTask.h" -#include "AnalysisCore/HFSelectorCuts.h" #include "AnalysisDataModel/HFSecondaryVertex.h" #include "AnalysisDataModel/HFCandidateSelectionTables.h" using namespace o2; using namespace o2::framework; using namespace o2::aod::hf_cand_prong2; -using namespace o2::analysis; using namespace o2::analysis::hf_cuts_d0_topik; /// Struct for applying D0 selection cuts struct HFD0CandidateSelector { - Produces hfSelD0Candidate; Configurable d_pTCandMin{"d_pTCandMin", 0., "Lower bound of candidate pT"}; @@ -64,7 +61,7 @@ struct HFD0CandidateSelector { return true; } - /// Conjugate independent toplogical cuts + /// Conjugate-independent topological cuts /// \param hfCandProng2 is candidate /// \return true if candidate passes all cuts template @@ -96,10 +93,10 @@ struct HFD0CandidateSelector { //decay exponentail law, with tau = beta*gamma*ctau //decay length > ctau retains (1-1/e) - if (TMath::Abs(hfCandProng2.impactParameterNormalised0()) < 0.5 || TMath::Abs(hfCandProng2.impactParameterNormalised1()) < 0.5) { + if (std::abs(hfCandProng2.impactParameterNormalised0()) < 0.5 || std::abs(hfCandProng2.impactParameterNormalised1()) < 0.5) { return false; } - double decayLengthCut = TMath::Min((hfCandProng2.p() * 0.0066) + 0.01, 0.06); + double decayLengthCut = std::min((hfCandProng2.p() * 0.0066) + 0.01, 0.06); if (hfCandProng2.decayLength() * hfCandProng2.decayLength() < decayLengthCut * decayLengthCut) { return false; } @@ -109,7 +106,7 @@ struct HFD0CandidateSelector { return true; } - /// Conjugate dependent toplogical cuts + /// Conjugate-dependent topological cuts /// \param hfCandProng2 is candidate /// \param trackPion is the track with the pion hypothesis /// \param trackKaon is the track with the kaon hypothesis @@ -125,11 +122,11 @@ struct HFD0CandidateSelector { } if (trackPion.sign() > 0) { //invariant mass cut - if (TMath::Abs(InvMassD0(hfCandProng2) - RecoDecay::getMassPDG(pdg::code::kD0)) > cuts->get(pTBin, "m")) { + if (std::abs(InvMassD0(hfCandProng2) - RecoDecay::getMassPDG(pdg::Code::kD0)) > cuts->get(pTBin, "m")) { return false; } } else { - if (TMath::Abs(InvMassD0bar(hfCandProng2) - RecoDecay::getMassPDG(pdg::code::kD0)) > cuts->get(pTBin, "m")) { + if (std::abs(InvMassD0bar(hfCandProng2) - RecoDecay::getMassPDG(pdg::Code::kD0)) > cuts->get(pTBin, "m")) { return false; } } @@ -137,16 +134,16 @@ struct HFD0CandidateSelector { if (trackPion.pt() < cuts->get(pTBin, "pT Pi") || trackKaon.pt() < cuts->get(pTBin, "pT K")) { return false; //cut on daughter pT } - if (TMath::Abs(trackPion.dcaPrim0()) > cuts->get(pTBin, "d0pi") || TMath::Abs(trackKaon.dcaPrim0()) > cuts->get(pTBin, "d0K")) { + if (std::abs(trackPion.dcaPrim0()) > cuts->get(pTBin, "d0pi") || std::abs(trackKaon.dcaPrim0()) > cuts->get(pTBin, "d0K")) { return false; //cut on daughter dca - need to add secondary vertex constraint here } if (trackPion.sign() > 0) { //cut on cos(theta *) - if (TMath::Abs(CosThetaStarD0(hfCandProng2)) > cuts->get(pTBin, "cos theta*")) { + if (std::abs(CosThetaStarD0(hfCandProng2)) > cuts->get(pTBin, "cos theta*")) { return false; } } else { - if (TMath::Abs(CosThetaStarD0bar(hfCandProng2)) > cuts->get(pTBin, "cos theta*")) { + if (std::abs(CosThetaStarD0bar(hfCandProng2)) > cuts->get(pTBin, "cos theta*")) { return false; } } @@ -161,7 +158,7 @@ struct HFD0CandidateSelector { template bool validTPCPID(const T& track) { - if (TMath::Abs(track.pt()) < d_pidTPCMinpT || TMath::Abs(track.pt()) >= d_pidTPCMaxpT) { + if (track.pt() < d_pidTPCMinpT || track.pt() >= d_pidTPCMaxpT) { return false; } //if (track.TPCNClsFindable() < d_TPCNClsFindablePIDCut) return false; @@ -175,7 +172,7 @@ struct HFD0CandidateSelector { template bool validTOFPID(const T& track) { - if (TMath::Abs(track.pt()) < d_pidTOFMinpT || TMath::Abs(track.pt()) >= d_pidTOFMaxpT) { + if (track.pt() < d_pidTOFMinpT || track.pt() >= d_pidTOFMaxpT) { return false; } return true; @@ -185,13 +182,12 @@ struct HFD0CandidateSelector { /// \param track is the track /// \param nPDG is the flavour hypothesis PDG number /// \param nSigmaCut is the nsigma threshold to test against - /// \note nPDG=211 pion nPDG=321 kaon /// \return true if track satisfies TPC PID hypothesis for given Nsigma cut template bool selectionPIDTPC(const T& track, int nPDG, double nSigmaCut) { double nSigma = 100.0; //arbitarily large value - nPDG = TMath::Abs(nPDG); + nPDG = std::abs(nPDG); if (nPDG == kPiPlus) { nSigma = track.tpcNSigmaPi(); } else if (nPDG == kKPlus) { @@ -199,20 +195,19 @@ struct HFD0CandidateSelector { } else { return false; } - return nSigma < nSigmaCut; + return std::abs(nSigma) < nSigmaCut; } /// Check if track is compatible with given TOF NSigma cut for a given flavour hypothesis /// \param track is the track /// \param nPDG is the flavour hypothesis PDG number /// \param nSigmaCut is the nSigma threshold to test against - /// \note nPDG=211 pion nPDG=321 kaon /// \return true if track satisfies TOF PID hypothesis for given NSigma cut template bool selectionPIDTOF(const T& track, int nPDG, double nSigmaCut) { double nSigma = 100.0; //arbitarily large value - nPDG = TMath::Abs(nPDG); + nPDG = std::abs(nPDG); if (nPDG == kPiPlus) { nSigma = track.tofNSigmaPi(); } else if (nPDG == kKPlus) { @@ -220,13 +215,12 @@ struct HFD0CandidateSelector { } else { return false; } - return nSigma < nSigmaCut; + return std::abs(nSigma) < nSigmaCut; } /// PID selection on daughter track /// \param track is the daughter track /// \param nPDG is the PDG code of the flavour hypothesis - /// \note nPDG=211 pion nPDG=321 kaon /// \return 1 if successful PID match, 0 if successful PID rejection, -1 if no PID info template int selectionPID(const T& track, int nPDG) @@ -281,7 +275,7 @@ struct HFD0CandidateSelector { int statusD0 = 0; int statusD0bar = 0; - if (!(hfCandProng2.hfflag() & 1 << D0ToPiK)) { + if (!(hfCandProng2.hfflag() & 1 << DecayType::D0ToPiK)) { hfSelD0Candidate(statusD0, statusD0bar); continue; } @@ -297,7 +291,7 @@ struct HFD0CandidateSelector { continue; } - //conjugate independent topological selection + //conjugate-independent topological selection if (!selectionTopol(hfCandProng2)) { hfSelD0Candidate(statusD0, statusD0bar); continue; @@ -306,9 +300,9 @@ struct HFD0CandidateSelector { //implement filter bit 4 cut - should be done before this task at the track selection level //need to add special cuts (additional cuts on decay length and d0 norm) - //conjugate dependent toplogical selection for D0 + //conjugate-dependent topological selection for D0 bool topolD0 = selectionTopolConjugate(hfCandProng2, trackPos, trackNeg); - //conjugate dependent toplogical selection for D0bar + //conjugate-dependent topological selection for D0bar bool topolD0bar = selectionTopolConjugate(hfCandProng2, trackNeg, trackPos); if (!topolD0 && !topolD0bar) { diff --git a/Analysis/Tasks/PWGHF/HFDplusToPiKPiCandidateSelector.cxx b/Analysis/Tasks/PWGHF/HFDplusToPiKPiCandidateSelector.cxx index 247a1f9f9a675..08ef9ec15c90b 100644 --- a/Analysis/Tasks/PWGHF/HFDplusToPiKPiCandidateSelector.cxx +++ b/Analysis/Tasks/PWGHF/HFDplusToPiKPiCandidateSelector.cxx @@ -9,26 +9,22 @@ // or submit itself to any jurisdiction. /// \file HFDplusToPiKPiCandidateSelector.cxx -/// \brief Dplus->piKpi selection task. +/// \brief Dplus->piKpi selection task /// /// \author Fabio Catalano , Politecnico and INFN Torino -#include "TMath.h" #include "Framework/runDataProcessing.h" #include "Framework/AnalysisTask.h" #include "AnalysisDataModel/HFSecondaryVertex.h" #include "AnalysisDataModel/HFCandidateSelectionTables.h" -#include "AnalysisCore/HFSelectorCuts.h" using namespace o2; using namespace o2::framework; using namespace o2::aod::hf_cand_prong3; -using namespace o2::analysis; using namespace o2::analysis::hf_cuts_dplus_topikpi; /// Struct for applying Dplus to piKpi selection cuts struct HFDplusToPiKPiCandidateSelector { - Produces hfSelDplusToPiKPiCandidate; Configurable d_pTCandMin{"d_pTCandMin", 1., "Lower bound of candidate pT"}; @@ -80,7 +76,7 @@ struct HFDplusToPiKPiCandidateSelector { if (trackPion1.pt() < cuts->get(pTBin, "pT Pi") || trackKaon.pt() < cuts->get(pTBin, "pT K") || trackPion2.pt() < cuts->get(pTBin, "pT Pi")) { return false; // cut on daughter pT } - if (TMath::Abs(InvMassDPlus(hfCandProng3) - RecoDecay::getMassPDG(pdg::code::kDPlus)) > cuts->get(pTBin, "deltaM")) { + if (std::abs(InvMassDPlus(hfCandProng3) - RecoDecay::getMassPDG(pdg::Code::kDPlus)) > cuts->get(pTBin, "deltaM")) { return false; // invariant mass cut } if (hfCandProng3.decayLength() < cuts->get(pTBin, "decay length")) { @@ -95,7 +91,7 @@ struct HFDplusToPiKPiCandidateSelector { if (hfCandProng3.cpaXY() < cuts->get(pTBin, "cos pointing angle XY")) { return false; } - if (TMath::Abs(hfCandProng3.maxNormalisedDeltaIP()) > cuts->get(pTBin, "max normalized deltaIP")) { + if (std::abs(hfCandProng3.maxNormalisedDeltaIP()) > cuts->get(pTBin, "max normalized deltaIP")) { return false; } return true; @@ -108,7 +104,7 @@ struct HFDplusToPiKPiCandidateSelector { template bool validTPCPID(const T& track) { - if (TMath::Abs(track.pt()) < d_pidTPCMinpT || TMath::Abs(track.pt()) >= d_pidTPCMaxpT) { + if (track.pt() < d_pidTPCMinpT || track.pt() >= d_pidTPCMaxpT) { return false; } //if (track.TPCNClsFindable() < d_TPCNClsFindablePIDCut) { @@ -124,7 +120,7 @@ struct HFDplusToPiKPiCandidateSelector { template bool validTOFPID(const T& track) { - if (TMath::Abs(track.pt()) < d_pidTOFMinpT || TMath::Abs(track.pt()) >= d_pidTOFMaxpT) { + if (track.pt() < d_pidTOFMinpT || track.pt() >= d_pidTOFMaxpT) { return false; } return true; @@ -140,7 +136,7 @@ struct HFDplusToPiKPiCandidateSelector { bool selectionPIDTPC(const T& track, int nPDG, int nSigmaCut) { double nSigma = 100.0; //arbitarily large value - nPDG = TMath::Abs(nPDG); + nPDG = std::abs(nPDG); if (nPDG == kPiPlus) { nSigma = track.tpcNSigmaPi(); } else if (nPDG == kKPlus) { @@ -148,7 +144,7 @@ struct HFDplusToPiKPiCandidateSelector { } else { return false; } - return nSigma < nSigmaCut; + return std::abs(nSigma) < nSigmaCut; } /// Check if track is compatible with given TOF NSigma cut for a given flavour hypothesis @@ -161,7 +157,7 @@ struct HFDplusToPiKPiCandidateSelector { bool selectionPIDTOF(const T& track, int nPDG, int nSigmaCut) { double nSigma = 100.0; //arbitarily large value - nPDG = TMath::Abs(nPDG); + nPDG = std::abs(nPDG); if (nPDG == kPiPlus) { nSigma = track.tofNSigmaPi(); } else if (nPDG == kKPlus) { @@ -169,7 +165,7 @@ struct HFDplusToPiKPiCandidateSelector { } else { return false; } - return nSigma < nSigmaCut; + return std::abs(nSigma) < nSigmaCut; } /// PID selection on daughter track @@ -215,7 +211,7 @@ struct HFDplusToPiKPiCandidateSelector { auto statusDplusToPiKPi = 0; // final selection flag : 0-rejected 1-accepted - if (!(hfCandProng3.hfflag() & 1 << DPlusToPiKPi)) { + if (!(hfCandProng3.hfflag() & 1 << DecayType::DPlusToPiKPi)) { hfSelDplusToPiKPiCandidate(statusDplusToPiKPi); continue; } diff --git a/Analysis/Tasks/PWGHF/HFJpsiToEECandidateSelector.cxx b/Analysis/Tasks/PWGHF/HFJpsiToEECandidateSelector.cxx index 2b4ce13f48fd8..16d8fba506e57 100644 --- a/Analysis/Tasks/PWGHF/HFJpsiToEECandidateSelector.cxx +++ b/Analysis/Tasks/PWGHF/HFJpsiToEECandidateSelector.cxx @@ -9,25 +9,23 @@ // or submit itself to any jurisdiction. /// \file HFJpsiToEECandidateSelector.cxx -/// \brief Jpsi selection task. +/// \brief J/ψ → e+ e− selection task +/// /// \author Biao Zhang , CCNU /// \author Nima Zardoshti , CERN #include "Framework/runDataProcessing.h" #include "Framework/AnalysisTask.h" -#include "AnalysisCore/HFSelectorCuts.h" #include "AnalysisDataModel/HFSecondaryVertex.h" #include "AnalysisDataModel/HFCandidateSelectionTables.h" + using namespace o2; using namespace o2::framework; using namespace o2::aod::hf_cand_prong2; -using namespace o2::analysis; using namespace o2::analysis::hf_cuts_jpsi_toee; -/// Struct for applying Jpsi selection cuts - +/// Struct for applying J/ψ → e+ e− selection cuts struct HFJpsiToEECandidateSelector { - Produces hfSelJpsiToEECandidate; Configurable d_pTCandMin{"d_pTCandMin", 0., "Lower bound of candidate pT"}; @@ -54,7 +52,7 @@ struct HFJpsiToEECandidateSelector { return true; } - /// Conjugate independent toplogical cuts + /// Conjugate-independent topological cuts /// \param hfCandProng2 is candidate /// \param trackPositron is the track with the positron hypothesis /// \param trackElectron is the track with the electron hypothesis @@ -72,17 +70,17 @@ struct HFJpsiToEECandidateSelector { return false; //check that the candidate pT is within the analysis range } - if (TMath::Abs(InvMassJpsiToEE(hfCandProng2) - RecoDecay::getMassPDG(pdg::code::kJpsi)) > cuts->get(pTBin, "m")) { + if (std::abs(InvMassJpsiToEE(hfCandProng2) - RecoDecay::getMassPDG(pdg::Code::kJpsi)) > cuts->get(pTBin, "m")) { return false; } if (trackElectron.pt() < cuts->get(pTBin, "pT El") || trackPositron.pt() < cuts->get(pTBin, "pT El")) { return false; //cut on daughter pT } - if (TMath::Abs(trackElectron.dcaPrim0()) > cuts->get(pTBin, "DCA_xy") || TMath::Abs(trackPositron.dcaPrim0()) > cuts->get(pTBin, "DCA_xy")) { + if (std::abs(trackElectron.dcaPrim0()) > cuts->get(pTBin, "DCA_xy") || std::abs(trackPositron.dcaPrim0()) > cuts->get(pTBin, "DCA_xy")) { return false; //cut on daughter dca - need to add secondary vertex constraint here } - if (TMath::Abs(trackElectron.dcaPrim1()) > cuts->get(pTBin, "DCA_z") || TMath::Abs(trackPositron.dcaPrim1()) > cuts->get(pTBin, "DCA_z")) { + if (std::abs(trackElectron.dcaPrim1()) > cuts->get(pTBin, "DCA_z") || std::abs(trackPositron.dcaPrim1()) > cuts->get(pTBin, "DCA_z")) { return false; //cut on daughter dca - need to add secondary vertex constraint here } @@ -96,7 +94,7 @@ struct HFJpsiToEECandidateSelector { template bool validTPCPID(const T& track) { - if (TMath::Abs(track.pt()) < d_pidTPCMinpT || TMath::Abs(track.pt()) >= d_pidTPCMaxpT) { + if (track.pt() < d_pidTPCMinpT || track.pt() >= d_pidTPCMaxpT) { return false; } //if (track.TPCNClsFindable() < d_TPCNClsFindablePIDCut) return false; @@ -113,8 +111,9 @@ struct HFJpsiToEECandidateSelector { if (nSigmaCut > 999.) { return true; } - return track.tpcNSigmaEl() < nSigmaCut; + return std::abs(track.tpcNSigmaEl()) < nSigmaCut; } + /// PID selection on daughter track /// \param track is the daughter track /// \return 1 if successful PID match, 0 if successful PID rejection, -1 if no PID info @@ -133,6 +132,7 @@ struct HFJpsiToEECandidateSelector { return -1; //no PID info } } + void process(aod::HfCandProng2 const& hfCandProng2s, aod::BigTracksPID const&) { @@ -141,7 +141,7 @@ struct HFJpsiToEECandidateSelector { auto trackPos = hfCandProng2.index0_as(); //positive daughter auto trackNeg = hfCandProng2.index1_as(); //negative daughter - if (!(hfCandProng2.hfflag() & 1 << JpsiToEE)) { + if (!(hfCandProng2.hfflag() & 1 << DecayType::JpsiToEE)) { hfSelJpsiToEECandidate(0); continue; } diff --git a/Analysis/Tasks/PWGHF/HFLcCandidateSelector.cxx b/Analysis/Tasks/PWGHF/HFLcCandidateSelector.cxx index 4fee002888e69..2ac20fbc01ad5 100644 --- a/Analysis/Tasks/PWGHF/HFLcCandidateSelector.cxx +++ b/Analysis/Tasks/PWGHF/HFLcCandidateSelector.cxx @@ -9,7 +9,7 @@ // or submit itself to any jurisdiction. /// \file HFLcCandidateSelector.cxx -/// \brief Lc->pKpi selection task. +/// \brief Λc± → p± K∓ π± selection task /// /// \author Luigi Dello Stritto , University and INFN SALERNO /// \author Nima Zardoshti , CERN @@ -18,17 +18,14 @@ #include "Framework/AnalysisTask.h" #include "AnalysisDataModel/HFSecondaryVertex.h" #include "AnalysisDataModel/HFCandidateSelectionTables.h" -#include "AnalysisCore/HFSelectorCuts.h" using namespace o2; using namespace o2::framework; using namespace o2::aod::hf_cand_prong3; -using namespace o2::analysis; using namespace o2::analysis::hf_cuts_lc_topkpi; /// Struct for applying Lc selection cuts struct HFLcCandidateSelector { - Produces hfSelLcCandidate; Configurable d_pTCandMin{"d_pTCandMin", 0., "Lower bound of candidate pT"}; @@ -65,7 +62,7 @@ struct HFLcCandidateSelector { return true; } - /// Conjugate independent toplogical cuts + /// Conjugate-independent topological cuts /// \param hfCandProng3 is candidate /// \return true if candidate passes all cuts template @@ -96,7 +93,7 @@ struct HFLcCandidateSelector { return true; } - /// Conjugate dependent toplogical cuts + /// Conjugate-dependent topological cuts /// \param hfCandProng3 is candidate /// \param trackProton is the track with the proton hypothesis /// \param trackPion is the track with the pion hypothesis @@ -117,11 +114,11 @@ struct HFLcCandidateSelector { } if (trackProton.globalIndex() == hfCandProng3.index0Id()) { - if (TMath::Abs(InvMassLcpKpi(hfCandProng3) - RecoDecay::getMassPDG(pdg::code::kLambdaCPlus)) > cuts->get(pTBin, "m")) { + if (std::abs(InvMassLcpKpi(hfCandProng3) - RecoDecay::getMassPDG(pdg::Code::kLambdaCPlus)) > cuts->get(pTBin, "m")) { return false; } } else { - if (TMath::Abs(InvMassLcpiKp(hfCandProng3) - RecoDecay::getMassPDG(pdg::code::kLambdaCPlus)) > cuts->get(pTBin, "m")) { + if (std::abs(InvMassLcpiKp(hfCandProng3) - RecoDecay::getMassPDG(pdg::Code::kLambdaCPlus)) > cuts->get(pTBin, "m")) { return false; } } @@ -136,7 +133,7 @@ struct HFLcCandidateSelector { template bool validTPCPID(const T& track) { - if (TMath::Abs(track.pt()) < d_pidTPCMinpT || TMath::Abs(track.pt()) >= d_pidTPCMaxpT) { + if (track.pt() < d_pidTPCMinpT || track.pt() >= d_pidTPCMaxpT) { return false; } //if (track.TPCNClsFindable() < d_TPCNClsFindablePIDCut) return false; @@ -150,7 +147,7 @@ struct HFLcCandidateSelector { template bool validTOFPID(const T& track) { - if (TMath::Abs(track.pt()) < d_pidTOFMinpT || TMath::Abs(track.pt()) >= d_pidTOFMaxpT) { + if (track.pt() < d_pidTOFMinpT || track.pt() >= d_pidTOFMaxpT) { return false; } return true; @@ -160,13 +157,12 @@ struct HFLcCandidateSelector { /// \param track is the track /// \param nPDG is the flavour hypothesis PDG number /// \param nSigmaCut is the nsigma threshold to test against - /// \note nPDG=2212 proton nPDG=211 pion nPDG=321 kaon /// \return true if track satisfies TPC PID hypothesis for given Nsigma cut template bool selectionPIDTPC(const T& track, int nPDG, int nSigmaCut) { double nSigma = 100.; //arbitarily large value - nPDG = TMath::Abs(nPDG); + nPDG = std::abs(nPDG); if (nPDG == kProton) { nSigma = track.tpcNSigmaPr(); } else if (nPDG == kKPlus) { @@ -176,20 +172,19 @@ struct HFLcCandidateSelector { } else { return false; } - return nSigma < nSigmaCut; + return std::abs(nSigma) < nSigmaCut; } /// Check if track is compatible with given TOF NSigma cut for a given flavour hypothesis /// \param track is the track /// \param nPDG is the flavour hypothesis PDG number /// \param nSigmaCut is the nSigma threshold to test against - /// \note nPDG=2212 proton nPDG=211 pion nPDG=321 kaon /// \return true if track satisfies TOF PID hypothesis for given NSigma cut template bool selectionPIDTOF(const T& track, int nPDG, int nSigmaCut) { double nSigma = 100.; //arbitarily large value - nPDG = TMath::Abs(nPDG); + nPDG = std::abs(nPDG); if (nPDG == kProton) { nSigma = track.tofNSigmaPr(); } else if (nPDG == kKPlus) { @@ -199,7 +194,7 @@ struct HFLcCandidateSelector { } else { return false; } - return nSigma < nSigmaCut; + return std::abs(nSigma) < nSigmaCut; } /// PID selection on daughter track @@ -259,7 +254,7 @@ struct HFLcCandidateSelector { auto statusLcpKpi = 0; auto statusLcpiKp = 0; - if (!(hfCandProng3.hfflag() & 1 << LcToPKPi)) { + if (!(hfCandProng3.hfflag() & 1 << DecayType::LcToPKPi)) { hfSelLcCandidate(statusLcpKpi, statusLcpiKp); continue; } @@ -278,13 +273,13 @@ struct HFLcCandidateSelector { //implement filter bit 4 cut - should be done before this task at the track selection level - //conjugate independent topological selection + //conjugate-independent topological selection if (!selectionTopol(hfCandProng3)) { hfSelLcCandidate(statusLcpKpi, statusLcpiKp); continue; } - //conjugate dependent toplogical selection for Lc + //conjugate-dependent topological selection for Lc bool topolLcpKpi = selectionTopolConjugate(hfCandProng3, trackPos1, trackNeg1, trackPos2); bool topolLcpiKp = selectionTopolConjugate(hfCandProng3, trackPos2, trackNeg1, trackPos1); diff --git a/Analysis/Tasks/PWGHF/HFMCValidation.cxx b/Analysis/Tasks/PWGHF/HFMCValidation.cxx index d7dc5d2e7c70c..5c1ed48bf699e 100644 --- a/Analysis/Tasks/PWGHF/HFMCValidation.cxx +++ b/Analysis/Tasks/PWGHF/HFMCValidation.cxx @@ -9,7 +9,8 @@ // or submit itself to any jurisdiction. /// \file HFMCValidation.cxx -/// \brief MonteCarlo Validation Code -- Gen and Rec Level validation +/// \brief Monte Carlo validation task +/// \note Gen. and rec. level validation /// /// \author Antonio Palasciano , Università degli Studi di Bari & INFN, Sezione di Bari /// \author Vít Kučera , CERN @@ -22,9 +23,8 @@ using namespace o2; using namespace o2::framework; -using namespace o2::aod::hf_cand_prong2; -using namespace o2::aod::hf_cand_prong3; using namespace o2::framework::expressions; +using namespace o2::aod; /// Gen Level Validation /// @@ -47,10 +47,10 @@ struct ValidationGenLevel { {"hCountAverageB", "Event counter - Average Number Beauty quark; Events Per Collision; entries", {HistType::kTH1F, {{20, 0., 20.}}}}, {"hCountAverageCbar", "Event counter - Average Number Anti-Charm quark; Events Per Collision; entries", {HistType::kTH1F, {{20, 0., 20.}}}}, {"hCountAverageBbar", "Event counter - Average Number Anti-Beauty quark; Events Per Collision; entries", {HistType::kTH1F, {{20, 0., 20.}}}}, - {"hCouterPerCollisionDzero", "Event counter - D0; Events Per Collision; entries", {HistType::kTH1F, {{10, -0.5, +9.5}}}}, - {"hCouterPerCollisionDplus", "Event counter - DPlus; Events Per Collision; entries", {HistType::kTH1F, {{10, -0.5, +9.5}}}}, - {"hCouterPerCollisionDstar", "Event counter - Dstar; Events Per Collision; entries", {HistType::kTH1F, {{10, -0.5, +9.5}}}}, - {"hCouterPerCollisionLambdaC", "Event counter - LambdaC; Events Per Collision; entries", {HistType::kTH1F, {{10, -0.5, +9.5}}}}}}; + {"hCounterPerCollisionDzero", "Event counter - D0; Events Per Collision; entries", {HistType::kTH1F, {{10, -0.5, +9.5}}}}, + {"hCounterPerCollisionDplus", "Event counter - DPlus; Events Per Collision; entries", {HistType::kTH1F, {{10, -0.5, +9.5}}}}, + {"hCounterPerCollisionDstar", "Event counter - Dstar; Events Per Collision; entries", {HistType::kTH1F, {{10, -0.5, +9.5}}}}, + {"hCounterPerCollisionLambdaC", "Event counter - LambdaC; Events Per Collision; entries", {HistType::kTH1F, {{10, -0.5, +9.5}}}}}}; void process(aod::McCollision const& mccollision, aod::McParticles const& particlesMC) { @@ -63,8 +63,8 @@ struct ValidationGenLevel { double pxDiff, pyDiff, pzDiff; //Particles and their decay checked in the second part of the task - std::array PDGArrayParticle = {411, 413, 421, 4122}; - std::array, 4> arrPDGFinal = {{{211, 211, -321}, {211, 211, -321}, {-321, 211, 0}, {2212, -321, 211}}}; + std::array PDGArrayParticle = {pdg::Code::kDPlus, 413, pdg::Code::kD0, pdg::Code::kLambdaCPlus}; + std::array, 4> arrPDGFinal = {{{kPiPlus, kPiPlus, -kKPlus}, {kPiPlus, kPiPlus, -kKPlus}, {-kKPlus, kPiPlus, 0}, {kProton, -kKPlus, kPiPlus}}}; int counter[4] = {0, 0, 0, 0}; std::vector listDaughters; @@ -76,16 +76,16 @@ struct ValidationGenLevel { auto mother = particlesMC.iteratorAt(particle.mother0()); if (particlePdgCode != mother.pdgCode()) { switch (particlePdgCode) { - case 4: + case kCharm: cPerCollision++; break; - case -4: + case kCharmBar: cBarPerCollision++; break; - case 5: + case kBottom: bPerCollision++; break; - case -5: + case kBottomBar: bBarPerCollision++; break; } @@ -133,10 +133,10 @@ struct ValidationGenLevel { registry.fill(HIST("hCountAverageB"), bPerCollision); registry.fill(HIST("hCountAverageCbar"), cBarPerCollision); registry.fill(HIST("hCountAverageBbar"), bBarPerCollision); - registry.fill(HIST("hCouterPerCollisionDplus"), counter[0]); - registry.fill(HIST("hCouterPerCollisionDstar"), counter[1]); - registry.fill(HIST("hCouterPerCollisionDzero"), counter[2]); - registry.fill(HIST("hCouterPerCollisionLambdaC"), counter[3]); + registry.fill(HIST("hCounterPerCollisionDplus"), counter[0]); + registry.fill(HIST("hCounterPerCollisionDstar"), counter[1]); + registry.fill(HIST("hCounterPerCollisionDzero"), counter[2]); + registry.fill(HIST("hCounterPerCollisionLambdaC"), counter[3]); } }; @@ -168,11 +168,11 @@ struct ValidationRecLevel { double pxDiff, pyDiff, pzDiff, pDiff; double decayLength; for (auto& candidate : candidates) { - if (!(candidate.hfflag() & 1 << D0ToPiK)) { + if (!(candidate.hfflag() & 1 << hf_cand_prong2::DecayType::D0ToPiK)) { continue; } - if (std::abs(candidate.flagMCMatchRec()) == 1 << D0ToPiK) { - indexParticle = RecoDecay::getMother(particlesMC, candidate.index0_as().mcParticle(), 421, true); + if (std::abs(candidate.flagMCMatchRec()) == 1 << hf_cand_prong2::DecayType::D0ToPiK) { + indexParticle = RecoDecay::getMother(particlesMC, candidate.index0_as().mcParticle(), pdg::Code::kD0, true); auto mother = particlesMC.iteratorAt(indexParticle); registry.fill(HIST("histPt"), candidate.pt() - mother.pt()); registry.fill(HIST("histPx"), candidate.px() - mother.px()); diff --git a/Analysis/Tasks/PWGHF/HFTrackIndexSkimsCreator.cxx b/Analysis/Tasks/PWGHF/HFTrackIndexSkimsCreator.cxx index 01d2d4fadbd6b..4de9237723504 100644 --- a/Analysis/Tasks/PWGHF/HFTrackIndexSkimsCreator.cxx +++ b/Analysis/Tasks/PWGHF/HFTrackIndexSkimsCreator.cxx @@ -17,20 +17,18 @@ #include "Framework/runDataProcessing.h" #include "Framework/AnalysisTask.h" +#include "Framework/HistogramRegistry.h" #include "DetectorsVertexing/DCAFitterN.h" #include "AnalysisDataModel/HFSecondaryVertex.h" #include "AnalysisCore/trackUtilities.h" #include "AnalysisCore/HFConfigurables.h" -#include "AnalysisCore/HFSelectorCuts.h" //#include "AnalysisDataModel/Centrality.h" -#include "Framework/HistogramRegistry.h" #include using namespace o2; using namespace o2::framework; using namespace o2::framework::expressions; -using namespace o2::aod::hf_cand_prong2; -using namespace o2::aod::hf_cand_prong3; +using namespace o2::aod; using namespace o2::analysis; using namespace o2::analysis::hf_cuts_single_track; @@ -203,26 +201,27 @@ struct HFTrackIndexSkimsCreator { HistogramRegistry registry{ "registry", {{"hNTracks", ";# of tracks;entries", {HistType::kTH1F, {{2500, 0., 25000.}}}}, - //2prong histograms + // 2-prong histograms {"hvtx2_x", "2-prong candidates;#it{x}_{sec. vtx.} (cm);entries", {HistType::kTH1F, {{1000, -2., 2.}}}}, {"hvtx2_y", "2-prong candidates;#it{y}_{sec. vtx.} (cm);entries", {HistType::kTH1F, {{1000, -2., 2.}}}}, {"hvtx2_z", "2-prong candidates;#it{z}_{sec. vtx.} (cm);entries", {HistType::kTH1F, {{1000, -20., 20.}}}}, {"hNCand2Prong", "2-prong candidates preselected;# of candidates;entries", {HistType::kTH1F, {{2000, 0., 200000.}}}}, {"hNCand2ProngVsNTracks", "2-prong candidates preselected;# of selected tracks;# of candidates;entries", {HistType::kTH2F, {{2500, 0., 25000.}, {2000, 0., 200000.}}}}, - {"hmassD0ToPiK", "D0 candidates;inv. mass (#pi K) (GeV/#it{c}^{2});entries", {HistType::kTH1F, {{500, 0., 5.}}}}, - {"hmassJpsiToEE", "Jpsi candidates;inv. mass (e+ e-) (GeV/#it{c}^{2});entries", {HistType::kTH1F, {{500, 0., 5.}}}}, - //3prong histograms + {"hmassD0ToPiK", "D^{0} candidates;inv. mass (#pi K) (GeV/#it{c}^{2});entries", {HistType::kTH1F, {{500, 0., 5.}}}}, + {"hmassJpsiToEE", "J/#psi candidates;inv. mass (e^{#plus} e^{#minus}) (GeV/#it{c}^{2});entries", {HistType::kTH1F, {{500, 0., 5.}}}}, + // 3-prong histograms {"hvtx3_x", "3-prong candidates;#it{x}_{sec. vtx.} (cm);entries", {HistType::kTH1F, {{1000, -2., 2.}}}}, {"hvtx3_y", "3-prong candidates;#it{y}_{sec. vtx.} (cm);entries", {HistType::kTH1F, {{1000, -2., 2.}}}}, {"hvtx3_z", "3-prong candidates;#it{z}_{sec. vtx.} (cm);entries", {HistType::kTH1F, {{1000, -20., 20.}}}}, {"hNCand3Prong", "3-prong candidates preselected;# of candidates;entries", {HistType::kTH1F, {{5000, 0., 500000.}}}}, {"hNCand3ProngVsNTracks", "3-prong candidates preselected;# of selected tracks;# of candidates;entries", {HistType::kTH2F, {{2500, 0., 25000.}, {5000, 0., 500000.}}}}, - {"hmassDPlusToPiKPi", "D+ candidates;inv. mass (#pi K #pi) (GeV/#it{c}^{2});entries", {HistType::kTH1F, {{500, 0., 5.}}}}, - {"hmassLcToPKPi", "Lc candidates;inv. mass (p K #pi) (GeV/#it{c}^{2});entries", {HistType::kTH1F, {{500, 0., 5.}}}}, - {"hmassDsToPiKK", "Ds candidates;inv. mass (K K #pi) (GeV/#it{c}^{2});entries", {HistType::kTH1F, {{500, 0., 5.}}}}, - {"hmassXicToPKPi", "Xic candidates;inv. mass (p K #pi) (GeV/#it{c}^{2});entries", {HistType::kTH1F, {{500, 0., 5.}}}}}}; + {"hmassDPlusToPiKPi", "D^{#plus} candidates;inv. mass (#pi K #pi) (GeV/#it{c}^{2});entries", {HistType::kTH1F, {{500, 0., 5.}}}}, + {"hmassLcToPKPi", "#Lambda_{c} candidates;inv. mass (p K #pi) (GeV/#it{c}^{2});entries", {HistType::kTH1F, {{500, 0., 5.}}}}, + {"hmassDsToPiKK", "D_{s} candidates;inv. mass (K K #pi) (GeV/#it{c}^{2});entries", {HistType::kTH1F, {{500, 0., 5.}}}}, + {"hmassXicToPKPi", "#Xi_{c} candidates;inv. mass (p K #pi) (GeV/#it{c}^{2});entries", {HistType::kTH1F, {{500, 0., 5.}}}}}}; Filter filterSelectTracks = (aod::hf_seltrack::isSelProng > 0); + using SelectedTracks = soa::Filtered>; // FIXME @@ -265,86 +264,86 @@ struct HFTrackIndexSkimsCreator { } //FIXME move above process function - const int n2ProngDecays = N2ProngDecays; //number of two prong hadron types - const int n3ProngDecays = N3ProngDecays; //number of three prong hadron types - int n2ProngBit = TMath::Power(2, n2ProngDecays) - 1; //bit value for 2 prongs candidates where each candidiate is one bit and they are all set it 1 - int n3ProngBit = TMath::Power(2, n3ProngDecays) - 1; //bit value for 3 prongs candidates where each candidiate is one bit and they are all set it 1 + const int n2ProngDecays = hf_cand_prong2::DecayType::N2ProngDecays; // number of 2-prong hadron types + const int n3ProngDecays = hf_cand_prong3::DecayType::N3ProngDecays; // number of 3-prong hadron types + int n2ProngBit = (1 << n2ProngDecays) - 1; // bit value for 2-prong candidates where each candidiate is one bit and they are all set to 1 + int n3ProngBit = (1 << n3ProngDecays) - 1; // bit value for 3-prong candidates where each candidiate is one bit and they are all set to 1 //retrieve cuts from json - to be made pT dependent when option appears in json - const int nCuts2Prong = 4; //how many different selections are made on 2-prongs + const int nCuts2Prong = 4; // how many different selections are made on 2-prongs double cut2ProngPtCandMin[n2ProngDecays]; double cut2ProngInvMassCandMin[n2ProngDecays]; double cut2ProngInvMassCandMax[n2ProngDecays]; double cut2ProngCPACandMin[n2ProngDecays]; double cut2ProngImpParProductCandMax[n2ProngDecays]; - cut2ProngPtCandMin[D0ToPiK] = configs->mPtD0ToPiKMin; - cut2ProngInvMassCandMin[D0ToPiK] = configs->mInvMassD0ToPiKMin; - cut2ProngInvMassCandMax[D0ToPiK] = configs->mInvMassD0ToPiKMax; - cut2ProngCPACandMin[D0ToPiK] = configs->mCPAD0ToPiKMin; - cut2ProngImpParProductCandMax[D0ToPiK] = configs->mImpParProductD0ToPiKMax; + cut2ProngPtCandMin[hf_cand_prong2::DecayType::D0ToPiK] = configs->mPtD0ToPiKMin; + cut2ProngInvMassCandMin[hf_cand_prong2::DecayType::D0ToPiK] = configs->mInvMassD0ToPiKMin; + cut2ProngInvMassCandMax[hf_cand_prong2::DecayType::D0ToPiK] = configs->mInvMassD0ToPiKMax; + cut2ProngCPACandMin[hf_cand_prong2::DecayType::D0ToPiK] = configs->mCPAD0ToPiKMin; + cut2ProngImpParProductCandMax[hf_cand_prong2::DecayType::D0ToPiK] = configs->mImpParProductD0ToPiKMax; - cut2ProngPtCandMin[JpsiToEE] = configs->mPtJpsiToEEMin; - cut2ProngInvMassCandMin[JpsiToEE] = configs->mInvMassJpsiToEEMin; - cut2ProngInvMassCandMax[JpsiToEE] = configs->mInvMassJpsiToEEMax; - cut2ProngCPACandMin[JpsiToEE] = configs->mCPAJpsiToEEMin; - cut2ProngImpParProductCandMax[JpsiToEE] = configs->mImpParProductJpsiToEEMax; + cut2ProngPtCandMin[hf_cand_prong2::DecayType::JpsiToEE] = configs->mPtJpsiToEEMin; + cut2ProngInvMassCandMin[hf_cand_prong2::DecayType::JpsiToEE] = configs->mInvMassJpsiToEEMin; + cut2ProngInvMassCandMax[hf_cand_prong2::DecayType::JpsiToEE] = configs->mInvMassJpsiToEEMax; + cut2ProngCPACandMin[hf_cand_prong2::DecayType::JpsiToEE] = configs->mCPAJpsiToEEMin; + cut2ProngImpParProductCandMax[hf_cand_prong2::DecayType::JpsiToEE] = configs->mImpParProductJpsiToEEMax; - const int nCuts3Prong = 4; //how many different selections are made on 3-prongs + const int nCuts3Prong = 4; // how many different selections are made on 3-prongs double cut3ProngPtCandMin[n3ProngDecays]; double cut3ProngInvMassCandMin[n3ProngDecays]; double cut3ProngInvMassCandMax[n3ProngDecays]; double cut3ProngCPACandMin[n3ProngDecays]; double cut3ProngDecLenCandMin[n3ProngDecays]; - cut3ProngPtCandMin[DPlusToPiKPi] = configs->mPtDPlusToPiKPiMin; - cut3ProngInvMassCandMin[DPlusToPiKPi] = configs->mInvMassDPlusToPiKPiMin; - cut3ProngInvMassCandMax[DPlusToPiKPi] = configs->mInvMassDPlusToPiKPiMax; - cut3ProngCPACandMin[DPlusToPiKPi] = configs->mCPADPlusToPiKPiMin; - cut3ProngDecLenCandMin[DPlusToPiKPi] = configs->mDecLenDPlusToPiKPiMin; - - cut3ProngPtCandMin[LcToPKPi] = configs->mPtLcToPKPiMin; - cut3ProngInvMassCandMin[LcToPKPi] = configs->mInvMassLcToPKPiMin; - cut3ProngInvMassCandMax[LcToPKPi] = configs->mInvMassLcToPKPiMax; - cut3ProngCPACandMin[LcToPKPi] = configs->mCPALcToPKPiMin; - cut3ProngDecLenCandMin[LcToPKPi] = configs->mDecLenLcToPKPiMin; - - cut3ProngPtCandMin[DsToPiKK] = configs->mPtDsToPiKKMin; - cut3ProngInvMassCandMin[DsToPiKK] = configs->mInvMassDsToPiKKMin; - cut3ProngInvMassCandMax[DsToPiKK] = configs->mInvMassDsToPiKKMax; - cut3ProngCPACandMin[DsToPiKK] = configs->mCPADsToPiKKMin; - cut3ProngDecLenCandMin[DsToPiKK] = configs->mDecLenDsToPiKKMin; - - cut3ProngPtCandMin[XicToPKPi] = configs->mPtXicToPKPiMin; - cut3ProngInvMassCandMin[XicToPKPi] = configs->mInvMassXicToPKPiMin; - cut3ProngInvMassCandMax[XicToPKPi] = configs->mInvMassXicToPKPiMax; - cut3ProngCPACandMin[XicToPKPi] = configs->mCPAXicToPKPiMin; - cut3ProngDecLenCandMin[XicToPKPi] = configs->mDecLenXicToPKPiMin; + cut3ProngPtCandMin[hf_cand_prong3::DecayType::DPlusToPiKPi] = configs->mPtDPlusToPiKPiMin; + cut3ProngInvMassCandMin[hf_cand_prong3::DecayType::DPlusToPiKPi] = configs->mInvMassDPlusToPiKPiMin; + cut3ProngInvMassCandMax[hf_cand_prong3::DecayType::DPlusToPiKPi] = configs->mInvMassDPlusToPiKPiMax; + cut3ProngCPACandMin[hf_cand_prong3::DecayType::DPlusToPiKPi] = configs->mCPADPlusToPiKPiMin; + cut3ProngDecLenCandMin[hf_cand_prong3::DecayType::DPlusToPiKPi] = configs->mDecLenDPlusToPiKPiMin; + + cut3ProngPtCandMin[hf_cand_prong3::DecayType::LcToPKPi] = configs->mPtLcToPKPiMin; + cut3ProngInvMassCandMin[hf_cand_prong3::DecayType::LcToPKPi] = configs->mInvMassLcToPKPiMin; + cut3ProngInvMassCandMax[hf_cand_prong3::DecayType::LcToPKPi] = configs->mInvMassLcToPKPiMax; + cut3ProngCPACandMin[hf_cand_prong3::DecayType::LcToPKPi] = configs->mCPALcToPKPiMin; + cut3ProngDecLenCandMin[hf_cand_prong3::DecayType::LcToPKPi] = configs->mDecLenLcToPKPiMin; + + cut3ProngPtCandMin[hf_cand_prong3::DecayType::DsToPiKK] = configs->mPtDsToPiKKMin; + cut3ProngInvMassCandMin[hf_cand_prong3::DecayType::DsToPiKK] = configs->mInvMassDsToPiKKMin; + cut3ProngInvMassCandMax[hf_cand_prong3::DecayType::DsToPiKK] = configs->mInvMassDsToPiKKMax; + cut3ProngCPACandMin[hf_cand_prong3::DecayType::DsToPiKK] = configs->mCPADsToPiKKMin; + cut3ProngDecLenCandMin[hf_cand_prong3::DecayType::DsToPiKK] = configs->mDecLenDsToPiKKMin; + + cut3ProngPtCandMin[hf_cand_prong3::DecayType::XicToPKPi] = configs->mPtXicToPKPiMin; + cut3ProngInvMassCandMin[hf_cand_prong3::DecayType::XicToPKPi] = configs->mInvMassXicToPKPiMin; + cut3ProngInvMassCandMax[hf_cand_prong3::DecayType::XicToPKPi] = configs->mInvMassXicToPKPiMax; + cut3ProngCPACandMin[hf_cand_prong3::DecayType::XicToPKPi] = configs->mCPAXicToPKPiMin; + cut3ProngDecLenCandMin[hf_cand_prong3::DecayType::XicToPKPi] = configs->mDecLenXicToPKPiMin; bool cutStatus2Prong[n2ProngDecays][nCuts2Prong]; bool cutStatus3Prong[n3ProngDecays][nCuts3Prong]; - int nCutStatus2ProngBit = TMath::Power(2, nCuts2Prong) - 1; //bit value for selection status for each 2 prongs candidate where each selection is one bit and they are all set it 1 - int nCutStatus3ProngBit = TMath::Power(2, nCuts3Prong) - 1; //bit value for selection status for each 2 prongs candidate where each selection is one bit and they are all set it 1 + int nCutStatus2ProngBit = (1 << nCuts2Prong) - 1; // bit value for selection status for each 2-prong candidate where each selection is one bit and they are all set to 1 + int nCutStatus3ProngBit = (1 << nCuts3Prong) - 1; // bit value for selection status for each 3-prong candidate where each selection is one bit and they are all set to 1 array, n2ProngDecays> arr2Mass1; - arr2Mass1[D0ToPiK] = array{massPi, massK}; - arr2Mass1[JpsiToEE] = array{massElectron, massElectron}; + arr2Mass1[hf_cand_prong2::DecayType::D0ToPiK] = array{massPi, massK}; + arr2Mass1[hf_cand_prong2::DecayType::JpsiToEE] = array{massElectron, massElectron}; array, n2ProngDecays> arr2Mass2; - arr2Mass2[D0ToPiK] = array{massK, massPi}; - arr2Mass2[JpsiToEE] = array{massElectron, massElectron}; + arr2Mass2[hf_cand_prong2::DecayType::D0ToPiK] = array{massK, massPi}; + arr2Mass2[hf_cand_prong2::DecayType::JpsiToEE] = array{massElectron, massElectron}; array, n3ProngDecays> arr3Mass1; - arr3Mass1[DPlusToPiKPi] = array{massPi, massK, massPi}; - arr3Mass1[LcToPKPi] = array{massProton, massK, massPi}; - arr3Mass1[DsToPiKK] = array{massK, massK, massPi}; - arr3Mass1[XicToPKPi] = array{massProton, massK, massPi}; + arr3Mass1[hf_cand_prong3::DecayType::DPlusToPiKPi] = array{massPi, massK, massPi}; + arr3Mass1[hf_cand_prong3::DecayType::LcToPKPi] = array{massProton, massK, massPi}; + arr3Mass1[hf_cand_prong3::DecayType::DsToPiKK] = array{massK, massK, massPi}; + arr3Mass1[hf_cand_prong3::DecayType::XicToPKPi] = array{massProton, massK, massPi}; array, n3ProngDecays> arr3Mass2; - arr3Mass2[DPlusToPiKPi] = array{massPi, massK, massPi}; - arr3Mass2[LcToPKPi] = array{massPi, massK, massProton}; - arr3Mass2[DsToPiKK] = array{massPi, massK, massK}; - arr3Mass2[XicToPKPi] = array{massPi, massK, massProton}; + arr3Mass2[hf_cand_prong3::DecayType::DPlusToPiKPi] = array{massPi, massK, massPi}; + arr3Mass2[hf_cand_prong3::DecayType::LcToPKPi] = array{massPi, massK, massProton}; + arr3Mass2[hf_cand_prong3::DecayType::DsToPiKK] = array{massPi, massK, massK}; + arr3Mass2[hf_cand_prong3::DecayType::XicToPKPi] = array{massPi, massK, massProton}; double mass2ProngHypo1[n2ProngDecays]; double mass2ProngHypo2[n2ProngDecays]; @@ -372,7 +371,7 @@ struct HFTrackIndexSkimsCreator { df3.setMinRelChi2Change(d_minrelchi2change); df3.setUseAbsDCA(useAbsDCA); - //used to calculate number of candidiates per event + // used to calculate number of candidiates per event auto nCand2 = rowTrackIndexProng2.lastIndex(); auto nCand3 = rowTrackIndexProng3.lastIndex(); @@ -420,7 +419,7 @@ struct HFTrackIndexSkimsCreator { } int iDebugCut = 0; - // 2prong invariant-mass cut + // 2-prong invariant-mass cut if (sel2ProngStatus > 0) { auto arrMom = array{ array{trackPos1.px(), trackPos1.py(), trackPos1.pz()}, @@ -522,16 +521,16 @@ struct HFTrackIndexSkimsCreator { if (isSelected2ProngCand & 1 << n2) { if ((cut2ProngInvMassCandMin[n2] < 0. && cut2ProngInvMassCandMax[n2] <= 0.) || (mass2ProngHypo1[n2] >= cut2ProngInvMassCandMin[n2] && mass2ProngHypo1[n2] < cut2ProngInvMassCandMax[n2])) { mass2ProngHypo1[n2] = RecoDecay::M(arrMom, arr2Mass1[n2]); - if (n2 == D0ToPiK) { + if (n2 == hf_cand_prong2::DecayType::D0ToPiK) { registry.get(HIST("hmassD0ToPiK"))->Fill(mass2ProngHypo1[n2]); } - if (n2 == JpsiToEE) { + if (n2 == hf_cand_prong2::DecayType::JpsiToEE) { registry.get(HIST("hmassJpsiToEE"))->Fill(mass2ProngHypo1[n2]); } } if ((cut2ProngInvMassCandMin[n2] < 0. && cut2ProngInvMassCandMax[n2] <= 0.) || (mass2ProngHypo2[n2] >= cut2ProngInvMassCandMin[n2] && mass2ProngHypo2[n2] < cut2ProngInvMassCandMax[n2])) { mass2ProngHypo2[n2] = RecoDecay::M(arrMom, arr2Mass2[n2]); - if (n2 == D0ToPiK) { + if (n2 == hf_cand_prong2::DecayType::D0ToPiK) { registry.get(HIST("hmassD0ToPiK"))->Fill(mass2ProngHypo1[n2]); } } @@ -569,7 +568,7 @@ struct HFTrackIndexSkimsCreator { } int iDebugCut = 0; - // 3prong invariant-mass cut + // 3-prong invariant-mass cut auto arr3Mom = array{ array{trackPos1.px(), trackPos1.py(), trackPos1.pz()}, array{trackNeg1.px(), trackNeg1.py(), trackNeg1.pz()}, @@ -690,28 +689,28 @@ struct HFTrackIndexSkimsCreator { if (isSelected3ProngCand & 1 << n3) { if ((cut3ProngInvMassCandMin[n3] < 0. && cut3ProngInvMassCandMax[n3] <= 0.) || (mass3ProngHypo1[n3] >= cut3ProngInvMassCandMin[n3] && mass3ProngHypo1[n3] < cut3ProngInvMassCandMax[n3])) { mass3ProngHypo1[n3] = RecoDecay::M(arr3Mom, arr3Mass1[n3]); - if (n3 == DPlusToPiKPi) { + if (n3 == hf_cand_prong3::DecayType::DPlusToPiKPi) { registry.get(HIST("hmassDPlusToPiKPi"))->Fill(mass3ProngHypo1[n3]); } - if (n3 == LcToPKPi) { + if (n3 == hf_cand_prong3::DecayType::LcToPKPi) { registry.get(HIST("hmassLcToPKPi"))->Fill(mass3ProngHypo1[n3]); } - if (n3 == DsToPiKK) { + if (n3 == hf_cand_prong3::DecayType::DsToPiKK) { registry.get(HIST("hmassDsToPiKK"))->Fill(mass3ProngHypo1[n3]); } - if (n3 == XicToPKPi) { + if (n3 == hf_cand_prong3::DecayType::XicToPKPi) { registry.get(HIST("hmassXicToPKPi"))->Fill(mass3ProngHypo1[n3]); } } if ((cut3ProngInvMassCandMin[n3] < 0. && cut3ProngInvMassCandMax[n3] <= 0.) || (mass3ProngHypo2[n3] >= cut3ProngInvMassCandMin[n3] && mass3ProngHypo2[n3] < cut3ProngInvMassCandMax[n3])) { mass3ProngHypo2[n3] = RecoDecay::M(arr3Mom, arr3Mass2[n3]); - if (n3 == LcToPKPi) { + if (n3 == hf_cand_prong3::DecayType::LcToPKPi) { registry.get(HIST("hmassLcToPKPi"))->Fill(mass3ProngHypo2[n3]); } - if (n3 == DsToPiKK) { + if (n3 == hf_cand_prong3::DecayType::DsToPiKK) { registry.get(HIST("hmassDsToPiKK"))->Fill(mass3ProngHypo2[n3]); } - if (n3 == XicToPKPi) { + if (n3 == hf_cand_prong3::DecayType::XicToPKPi) { registry.get(HIST("hmassXicToPKPi"))->Fill(mass3ProngHypo2[n3]); } } @@ -741,7 +740,7 @@ struct HFTrackIndexSkimsCreator { } int iDebugCut = 0; - // 3prong invariant-mass cut + // 3-prong invariant-mass cut auto arr3Mom = array{ array{trackNeg1.px(), trackNeg1.py(), trackNeg1.pz()}, array{trackPos1.px(), trackPos1.py(), trackPos1.pz()}, @@ -863,28 +862,28 @@ struct HFTrackIndexSkimsCreator { if (isSelected3ProngCand & 1 << n3) { if ((cut3ProngInvMassCandMin[n3] < 0. && cut3ProngInvMassCandMax[n3] <= 0.) || (mass3ProngHypo1[n3] >= cut3ProngInvMassCandMin[n3] && mass3ProngHypo1[n3] < cut3ProngInvMassCandMax[n3])) { mass3ProngHypo1[n3] = RecoDecay::M(arr3Mom, arr3Mass1[n3]); - if (n3 == DPlusToPiKPi) { + if (n3 == hf_cand_prong3::DecayType::DPlusToPiKPi) { registry.get(HIST("hmassDPlusToPiKPi"))->Fill(mass3ProngHypo1[n3]); } - if (n3 == LcToPKPi) { + if (n3 == hf_cand_prong3::DecayType::LcToPKPi) { registry.get(HIST("hmassLcToPKPi"))->Fill(mass3ProngHypo1[n3]); } - if (n3 == DsToPiKK) { + if (n3 == hf_cand_prong3::DecayType::DsToPiKK) { registry.get(HIST("hmassDsToPiKK"))->Fill(mass3ProngHypo1[n3]); } - if (n3 == XicToPKPi) { + if (n3 == hf_cand_prong3::DecayType::XicToPKPi) { registry.get(HIST("hmassXicToPKPi"))->Fill(mass3ProngHypo1[n3]); } } if ((cut3ProngInvMassCandMin[n3] < 0. && cut3ProngInvMassCandMax[n3] <= 0.) || (mass3ProngHypo2[n3] >= cut3ProngInvMassCandMin[n3] && mass3ProngHypo2[n3] < cut3ProngInvMassCandMax[n3])) { mass3ProngHypo2[n3] = RecoDecay::M(arr3Mom, arr3Mass2[n3]); - if (n3 == LcToPKPi) { + if (n3 == hf_cand_prong3::DecayType::LcToPKPi) { registry.get(HIST("hmassLcToPKPi"))->Fill(mass3ProngHypo2[n3]); } - if (n3 == DsToPiKK) { + if (n3 == hf_cand_prong3::DecayType::DsToPiKK) { registry.get(HIST("hmassDsToPiKK"))->Fill(mass3ProngHypo2[n3]); } - if (n3 == XicToPKPi) { + if (n3 == hf_cand_prong3::DecayType::XicToPKPi) { registry.get(HIST("hmassXicToPKPi"))->Fill(mass3ProngHypo2[n3]); } } diff --git a/Analysis/Tasks/PWGHF/HFTreeCreatorD0ToKPi.cxx b/Analysis/Tasks/PWGHF/HFTreeCreatorD0ToKPi.cxx index ab2e7470d9eec..c2cad6d88d7a5 100644 --- a/Analysis/Tasks/PWGHF/HFTreeCreatorD0ToKPi.cxx +++ b/Analysis/Tasks/PWGHF/HFTreeCreatorD0ToKPi.cxx @@ -149,13 +149,14 @@ struct CandidateTreeWriter { Produces rowCandidateFull; Produces rowCandidateFullEvents; Produces rowCandidateFullParticles; + void init(InitContext const&) { } - using CandType = soa::Join; + void process(aod::Collisions const& collisions, aod::McCollisions const& mccollisions, - CandType const& candidates, + soa::Join const& candidates, soa::Join const& particles, aod::BigTracksPID const& tracks) { @@ -249,7 +250,7 @@ struct CandidateTreeWriter { // Filling particle properties rowCandidateFullParticles.reserve(particles.size()); for (auto& particle : particles) { - if (std::abs(particle.flagMCMatchGen()) == 1 << D0ToPiK) { + if (std::abs(particle.flagMCMatchGen()) == 1 << DecayType::D0ToPiK) { rowCandidateFullParticles( particle.mcCollision().bcId(), particle.pt(), diff --git a/Analysis/Tasks/PWGHF/HFTreeCreatorLcToPKPi.cxx b/Analysis/Tasks/PWGHF/HFTreeCreatorLcToPKPi.cxx index f233e44e55a63..64a412e4ff189 100644 --- a/Analysis/Tasks/PWGHF/HFTreeCreatorLcToPKPi.cxx +++ b/Analysis/Tasks/PWGHF/HFTreeCreatorLcToPKPi.cxx @@ -176,9 +176,11 @@ struct CandidateTreeWriter { Produces rowCandidateFull; Produces rowCandidateFullEvents; Produces rowCandidateFullParticles; + void init(InitContext const&) { } + void process(aod::Collisions const& collisions, aod::McCollisions const& mccollisions, soa::Join const& candidates, @@ -290,7 +292,7 @@ struct CandidateTreeWriter { // Filling particle properties rowCandidateFullParticles.reserve(particles.size()); for (auto& particle : particles) { - if (std::abs(particle.flagMCMatchGen()) == 1 << LcToPKPi) { + if (std::abs(particle.flagMCMatchGen()) == 1 << DecayType::LcToPKPi) { rowCandidateFullParticles( particle.mcCollision().bcId(), particle.pt(), diff --git a/Analysis/Tasks/PWGHF/HFXicToPKPiCandidateSelector.cxx b/Analysis/Tasks/PWGHF/HFXicToPKPiCandidateSelector.cxx index a4b06305f0c67..43d655e55ed8b 100644 --- a/Analysis/Tasks/PWGHF/HFXicToPKPiCandidateSelector.cxx +++ b/Analysis/Tasks/PWGHF/HFXicToPKPiCandidateSelector.cxx @@ -9,7 +9,7 @@ // or submit itself to any jurisdiction. /// \file HFXicToPKPiCandidateSelector.cxx -/// \brief Xic->pKpi selection task. +/// \brief Ξc± → p± K∓ π± selection task /// \note Inspired from HFLcCandidateSelector.cxx /// /// \author Mattia Faggin , University and INFN PADOVA @@ -23,7 +23,6 @@ using namespace o2; using namespace o2::framework; using namespace o2::aod::hf_cand_prong3; -using namespace o2::analysis; using namespace o2::analysis::hf_cuts_xic_topkpi; /// Struct for applying Xic selection cuts @@ -63,7 +62,7 @@ struct HFXicToPKPiCandidateSelector { return true; } - /// Conjugate independent toplogical cuts + /// Conjugate-independent topological cuts /// \param hfCandProng3 is candidate /// \return true if candidate passes all cuts template @@ -93,7 +92,7 @@ struct HFXicToPKPiCandidateSelector { return true; } - /// Conjugate dependent toplogical cuts + /// Conjugate-dependent topological cuts /// \param hfCandProng3 is candidate /// \param trackProton is the track with the proton hypothesis /// \param trackPion is the track with the pion hypothesis @@ -114,11 +113,11 @@ struct HFXicToPKPiCandidateSelector { } if (trackProton.globalIndex() == hfCandProng3.index0Id()) { - if (TMath::Abs(InvMassXicToPKPi(hfCandProng3) - RecoDecay::getMassPDG(pdg::code::kXiCPlus)) > cuts->get(pTBin, "m")) { + if (std::abs(InvMassXicToPKPi(hfCandProng3) - RecoDecay::getMassPDG(pdg::Code::kXiCPlus)) > cuts->get(pTBin, "m")) { return false; } } else { - if (TMath::Abs(InvMassXicToPiKP(hfCandProng3) - RecoDecay::getMassPDG(pdg::code::kXiCPlus)) > cuts->get(pTBin, "m")) { + if (std::abs(InvMassXicToPiKP(hfCandProng3) - RecoDecay::getMassPDG(pdg::Code::kXiCPlus)) > cuts->get(pTBin, "m")) { return false; } } @@ -133,7 +132,7 @@ struct HFXicToPKPiCandidateSelector { template bool validTPCPID(const T& track) { - if (TMath::Abs(track.pt()) < d_pidTPCMinpT || TMath::Abs(track.pt()) >= d_pidTPCMaxpT) { + if (track.pt() < d_pidTPCMinpT || track.pt() >= d_pidTPCMaxpT) { return false; } //if (track.TPCNClsFindable() < d_TPCNClsFindablePIDCut) return false; @@ -147,7 +146,7 @@ struct HFXicToPKPiCandidateSelector { template bool validTOFPID(const T& track) { - if (TMath::Abs(track.pt()) < d_pidTOFMinpT || TMath::Abs(track.pt()) >= d_pidTOFMaxpT) { + if (track.pt() < d_pidTOFMinpT || track.pt() >= d_pidTOFMaxpT) { return false; } return true; @@ -163,7 +162,7 @@ struct HFXicToPKPiCandidateSelector { bool selectionPIDTPC(const T& track, int nPDG, int nSigmaCut) { double nSigma = 99.; //arbitarily large value - nPDG = TMath::Abs(nPDG); + nPDG = std::abs(nPDG); if (nPDG == kProton) { nSigma = track.tpcNSigmaPr(); } else if (nPDG == kKPlus) { @@ -174,7 +173,7 @@ struct HFXicToPKPiCandidateSelector { return false; } - return nSigma < nSigmaCut; + return std::abs(nSigma) < nSigmaCut; } /// Check if track is compatible with given TOF NSigma cut for a given flavour hypothesis @@ -187,7 +186,7 @@ struct HFXicToPKPiCandidateSelector { bool selectionPIDTOF(const T& track, int nPDG, int nSigmaCut) { double nSigma = 99.; //arbitarily large value - nPDG = TMath::Abs(nPDG); + nPDG = std::abs(nPDG); if (nPDG == kProton) { nSigma = track.tofNSigmaPr(); } else if (nPDG == kKPlus) { @@ -198,7 +197,7 @@ struct HFXicToPKPiCandidateSelector { return false; } - return nSigma < nSigmaCut; + return std::abs(nSigma) < nSigmaCut; } /// PID selection on daughter track @@ -260,11 +259,11 @@ struct HFXicToPKPiCandidateSelector { } else { statusTPC = 2; //positive PID } - } + } else{ statusTPC = -1; //no PID info } - + /// TOF if (validTOFPID(track)) { if (!selectionPIDTOF(track, nPDG, d_nSigmaTOF)) { @@ -300,7 +299,7 @@ struct HFXicToPKPiCandidateSelector { auto statusXicToPKPi = 0; auto statusXicToPiKP = 0; - if (!(hfCandProng3.hfflag() & 1 << XicToPKPi)) { + if (!(hfCandProng3.hfflag() & 1 << DecayType::XicToPKPi)) { hfSelXicToPKPiCandidate(statusXicToPKPi, statusXicToPiKP); continue; } @@ -330,13 +329,13 @@ struct HFXicToPKPiCandidateSelector { //implement filter bit 4 cut - should be done before this task at the track selection level - //conjugate independent topological selection + //conjugate-independent topological selection if (!selectionTopol(hfCandProng3)) { hfSelXicToPKPiCandidate(statusXicToPKPi, statusXicToPiKP); continue; } - //conjugate dependent topplogical selection for Xic + //conjugate-dependent topplogical selection for Xic topolXicToPKPi = selectionTopolConjugate(hfCandProng3, trackPos1, trackNeg1, trackPos2); topolXicToPiKP = selectionTopolConjugate(hfCandProng3, trackPos2, trackNeg1, trackPos1); diff --git a/Analysis/Tasks/PWGHF/taskBPlus.cxx b/Analysis/Tasks/PWGHF/taskBPlus.cxx index 1bcc99ec3ead6..d6f791a67a29b 100644 --- a/Analysis/Tasks/PWGHF/taskBPlus.cxx +++ b/Analysis/Tasks/PWGHF/taskBPlus.cxx @@ -22,8 +22,8 @@ using namespace o2; using namespace o2::framework; -using namespace o2::aod::hf_cand_prong2; using namespace o2::framework::expressions; +using namespace o2::aod::hf_cand_prong2; void customize(std::vector& workflowOptions) { @@ -45,12 +45,13 @@ struct TaskBplus { Configurable cutEtaCandMax{"cutEtaCandMax", -1., "max. cand. pseudorapidity"}; Filter filterSelectCandidates = (aod::hf_selcandidate_d0::isSelD0 >= d_selectionFlagD0 || aod::hf_selcandidate_d0::isSelD0bar >= d_selectionFlagD0bar); + Partition positiveTracks = aod::track::signed1Pt >= 0.f; void process(aod::Collision const&, aod::BigTracks const&, soa::Filtered> const& candidates) { for (auto& candidate : candidates) { - if (!(candidate.hfflag() & 1 << D0ToPiK)) { + if (!(candidate.hfflag() & 1 << DecayType::D0ToPiK)) { continue; } if (cutEtaCandMax >= 0. && std::abs(candidate.eta()) > cutEtaCandMax) { diff --git a/Analysis/Tasks/PWGHF/taskD0.cxx b/Analysis/Tasks/PWGHF/taskD0.cxx index 5fae997adc6fc..5ab2a11bdf315 100644 --- a/Analysis/Tasks/PWGHF/taskD0.cxx +++ b/Analysis/Tasks/PWGHF/taskD0.cxx @@ -16,17 +16,15 @@ #include "Framework/AnalysisTask.h" #include "Framework/HistogramRegistry.h" -#include "AnalysisCore/HFSelectorCuts.h" #include "AnalysisDataModel/HFSecondaryVertex.h" #include "AnalysisDataModel/HFCandidateSelectionTables.h" using namespace o2; -using namespace o2::analysis; -using namespace o2::analysis::hf_cuts_d0_topik; using namespace o2::framework; +using namespace o2::framework::expressions; using namespace o2::aod::hf_cand; using namespace o2::aod::hf_cand_prong2; -using namespace o2::framework::expressions; +using namespace o2::analysis::hf_cuts_d0_topik; void customize(std::vector& workflowOptions) { @@ -47,7 +45,6 @@ struct TaskD0 { Configurable d_selectionFlagD0{"d_selectionFlagD0", 1, "Selection Flag for D0"}; Configurable d_selectionFlagD0bar{"d_selectionFlagD0bar", 1, "Selection Flag for D0bar"}; Configurable cutYCandMax{"cutYCandMax", -1., "max. cand. rapidity"}; - Configurable> bins{"pTBins", std::vector{hf_cuts_d0_topik::pTBins_v}, "pT bin limits"}; void init(o2::framework::InitContext&) @@ -74,7 +71,7 @@ struct TaskD0 { void process(soa::Filtered> const& candidates) { for (auto& candidate : candidates) { - if (!(candidate.hfflag() & 1 << D0ToPiK)) { + if (!(candidate.hfflag() & 1 << DecayType::D0ToPiK)) { continue; } if (cutYCandMax >= 0. && std::abs(YD0(candidate)) > cutYCandMax) { @@ -139,21 +136,20 @@ struct TaskD0MC { // MC rec. //Printf("MC Candidates: %d", candidates.size()); for (auto& candidate : candidates) { - if (!(candidate.hfflag() & 1 << D0ToPiK)) { + if (!(candidate.hfflag() & 1 << DecayType::D0ToPiK)) { continue; } if (cutYCandMax >= 0. && std::abs(YD0(candidate)) > cutYCandMax) { - //Printf("MC Rec.: Y rejection: %g", YD0(candidate)); continue; } - if (std::abs(candidate.flagMCMatchRec()) == 1 << D0ToPiK) { + if (std::abs(candidate.flagMCMatchRec()) == 1 << DecayType::D0ToPiK) { // Get the corresponding MC particle. - auto indexMother = RecoDecay::getMother(particlesMC, candidate.index0_as().mcParticle_as>(), pdg::code::kD0, true); + auto indexMother = RecoDecay::getMother(particlesMC, candidate.index0_as().mcParticle_as>(), pdg::Code::kD0, true); auto particleMother = particlesMC.iteratorAt(indexMother); registry.fill(HIST("hPtGenSig"), particleMother.pt()); // gen. level pT auto ptRec = candidate.pt(); registry.fill(HIST("hPtRecSig"), ptRec); // rec. level pT - if (candidate.originMCRec() == Prompt) { + if (candidate.originMCRec() == OriginType::Prompt) { registry.fill(HIST("hPtRecSigPrompt"), ptRec); // rec. level pT, prompt } else { registry.fill(HIST("hPtRecSigNonPrompt"), ptRec); // rec. level pT, non-prompt @@ -169,14 +165,13 @@ struct TaskD0MC { // MC gen. //Printf("MC Particles: %d", particlesMC.size()); for (auto& particle : particlesMC) { - if (std::abs(particle.flagMCMatchGen()) == 1 << D0ToPiK) { + if (std::abs(particle.flagMCMatchGen()) == 1 << DecayType::D0ToPiK) { if (cutYCandMax >= 0. && std::abs(RecoDecay::Y(array{particle.px(), particle.py(), particle.pz()}, RecoDecay::getMassPDG(particle.pdgCode()))) > cutYCandMax) { - //Printf("MC Gen.: Y rejection: %g", RecoDecay::Y(array{particle.px(), particle.py(), particle.pz()}, RecoDecay::getMassPDG(particle.pdgCode()))); continue; } auto ptGen = particle.pt(); registry.fill(HIST("hPtGen"), ptGen); - if (particle.originMCGen() == Prompt) { + if (particle.originMCGen() == OriginType::Prompt) { registry.fill(HIST("hPtGenPrompt"), ptGen); } else { registry.fill(HIST("hPtGenNonPrompt"), ptGen); diff --git a/Analysis/Tasks/PWGHF/taskDPlus.cxx b/Analysis/Tasks/PWGHF/taskDPlus.cxx index 67b9574f44545..f829f490ae517 100644 --- a/Analysis/Tasks/PWGHF/taskDPlus.cxx +++ b/Analysis/Tasks/PWGHF/taskDPlus.cxx @@ -19,13 +19,11 @@ #include "Framework/HistogramRegistry.h" #include "AnalysisDataModel/HFSecondaryVertex.h" #include "AnalysisDataModel/HFCandidateSelectionTables.h" -#include "AnalysisCore/HFSelectorCuts.h" using namespace o2; using namespace o2::framework; -using namespace o2::aod::hf_cand_prong3; using namespace o2::framework::expressions; -using namespace o2::analysis; +using namespace o2::aod::hf_cand_prong3; void customize(std::vector& workflowOptions) { @@ -76,7 +74,7 @@ struct TaskDPlus { { for (auto& candidate : candidates) { //not possible in Filter since expressions do not support binary operators - if (!(candidate.hfflag() & 1 << DPlusToPiKPi)) { + if (!(candidate.hfflag() & 1 << DecayType::DPlusToPiKPi)) { continue; } if (cutYCandMax >= 0. && std::abs(YDPlus(candidate)) > cutYCandMax) { @@ -132,20 +130,21 @@ struct TaskDPlusMC { soa::Join const& particlesMC, aod::BigTracksMC const& tracks) { // MC rec. + //Printf("MC Candidates: %d", candidates.size()); for (auto& candidate : candidates) { //not possible in Filter since expressions do not support binary operators - if (!(candidate.hfflag() & 1 << DPlusToPiKPi)) { + if (!(candidate.hfflag() & 1 << DecayType::DPlusToPiKPi)) { continue; } if (cutYCandMax >= 0. && std::abs(YDPlus(candidate)) > cutYCandMax) { continue; } - if (std::abs(candidate.flagMCMatchRec()) == 1 << DPlusToPiKPi) { + if (std::abs(candidate.flagMCMatchRec()) == 1 << DecayType::DPlusToPiKPi) { // Get the corresponding MC particle. - auto indexMother = RecoDecay::getMother(particlesMC, candidate.index0_as().mcParticle_as>(), pdg::code::kDPlus, true); + auto indexMother = RecoDecay::getMother(particlesMC, candidate.index0_as().mcParticle_as>(), pdg::Code::kDPlus, true); auto particleMother = particlesMC.iteratorAt(indexMother); - registry.fill(HIST("hPtGenSig"), particleMother.pt()); //gen. level pT - registry.fill(HIST("hPtRecSig"), candidate.pt()); //rec. level pT + registry.fill(HIST("hPtGenSig"), particleMother.pt()); // gen. level pT + registry.fill(HIST("hPtRecSig"), candidate.pt()); // rec. level pT registry.fill(HIST("hCPARecSig"), candidate.cpa()); registry.fill(HIST("hEtaRecSig"), candidate.eta()); } else { @@ -155,8 +154,9 @@ struct TaskDPlusMC { } } // MC gen. + //Printf("MC Particles: %d", particlesMC.size()); for (auto& particle : particlesMC) { - if (std::abs(particle.flagMCMatchGen()) == 1 << DPlusToPiKPi) { + if (std::abs(particle.flagMCMatchGen()) == 1 << DecayType::DPlusToPiKPi) { if (cutYCandMax >= 0. && std::abs(RecoDecay::Y(array{particle.px(), particle.py(), particle.pz()}, RecoDecay::getMassPDG(particle.pdgCode()))) > cutYCandMax) { continue; } diff --git a/Analysis/Tasks/PWGHF/taskJpsi.cxx b/Analysis/Tasks/PWGHF/taskJpsi.cxx index 046eb75f4db30..fb2bf1b0e4345 100644 --- a/Analysis/Tasks/PWGHF/taskJpsi.cxx +++ b/Analysis/Tasks/PWGHF/taskJpsi.cxx @@ -14,18 +14,17 @@ /// \author Gian Michele Innocenti , CERN /// \author Vít Kučera , CERN /// \author Biao Zhang , CCNU + #include "Framework/AnalysisTask.h" #include "Framework/HistogramRegistry.h" -#include "AnalysisCore/HFSelectorCuts.h" #include "AnalysisDataModel/HFSecondaryVertex.h" #include "AnalysisDataModel/HFCandidateSelectionTables.h" using namespace o2; -using namespace o2::analysis; -using namespace o2::analysis::hf_cuts_jpsi_toee; using namespace o2::framework; -using namespace o2::aod::hf_cand_prong2; using namespace o2::framework::expressions; +using namespace o2::aod::hf_cand_prong2; +using namespace o2::analysis::hf_cuts_jpsi_toee; void customize(std::vector& workflowOptions) { @@ -65,10 +64,9 @@ struct TaskJpsi { Filter filterSelectCandidates = (aod::hf_selcandidate_jpsi::isSelJpsiToEE >= d_selectionFlagJpsi); void process(soa::Filtered> const& candidates) - // void process(aod::HfCandProng2 const& candidates) { for (auto& candidate : candidates) { - if (!(candidate.hfflag() & 1 << JpsiToEE)) { + if (!(candidate.hfflag() & 1 << DecayType::JpsiToEE)) { continue; } if (cutYCandMax >= 0. && std::abs(YJpsi(candidate)) > cutYCandMax) { @@ -110,6 +108,7 @@ struct TaskJpsiMC { Configurable d_selectionFlagJpsi{"d_selectionFlagJpsi", 1, "Selection Flag for Jpsi"}; Configurable cutYCandMax{"cutYCandMax", -1., "max. cand. rapidity"}; + Filter filterSelectCandidates = (aod::hf_selcandidate_jpsi::isSelJpsiToEE >= d_selectionFlagJpsi); void process(soa::Filtered> const& candidates, @@ -118,19 +117,18 @@ struct TaskJpsiMC { // MC rec. //Printf("MC Candidates: %d", candidates.size()); for (auto& candidate : candidates) { - if (!(candidate.hfflag() & 1 << JpsiToEE)) { + if (!(candidate.hfflag() & 1 << DecayType::JpsiToEE)) { continue; } if (cutYCandMax >= 0. && std::abs(YJpsi(candidate)) > cutYCandMax) { - //Printf("MC Rec.: Y rejection: %g", YJpsi(candidate)); continue; } - if (candidate.flagMCMatchRec() == 1 << JpsiToEE) { + if (candidate.flagMCMatchRec() == 1 << DecayType::JpsiToEE) { //Get the corresponding MC particle. auto indexMother = RecoDecay::getMother(particlesMC, candidate.index0_as().mcParticle_as>(), 443, true); auto particleMother = particlesMC.iteratorAt(indexMother); - registry.fill(HIST("hPtGenSig"), particleMother.pt()); //gen. level pT - registry.fill(HIST("hPtRecSig"), candidate.pt()); //rec. level pT + registry.fill(HIST("hPtGenSig"), particleMother.pt()); // gen. level pT + registry.fill(HIST("hPtRecSig"), candidate.pt()); // rec. level pT registry.fill(HIST("hCPARecSig"), candidate.cpa()); registry.fill(HIST("hEtaRecSig"), candidate.eta()); } else { @@ -142,9 +140,8 @@ struct TaskJpsiMC { // MC gen. //Printf("MC Particles: %d", particlesMC.size()); for (auto& particle : particlesMC) { - if (particle.flagMCMatchGen() == 1 << JpsiToEE) { + if (particle.flagMCMatchGen() == 1 << DecayType::JpsiToEE) { if (cutYCandMax >= 0. && std::abs(RecoDecay::Y(array{particle.px(), particle.py(), particle.pz()}, RecoDecay::getMassPDG(particle.pdgCode()))) > cutYCandMax) { - //Printf("MC Gen.: Y rejection: %g", RecoDecay::Y(array{particle.px(), particle.py(), particle.pz()}, RecoDecay::getMassPDG(particle.pdgCode()))); continue; } registry.fill(HIST("hPtGen"), particle.pt()); diff --git a/Analysis/Tasks/PWGHF/taskLc.cxx b/Analysis/Tasks/PWGHF/taskLc.cxx index c4f73e7afc6ab..bd45775daafe9 100644 --- a/Analysis/Tasks/PWGHF/taskLc.cxx +++ b/Analysis/Tasks/PWGHF/taskLc.cxx @@ -9,7 +9,7 @@ // or submit itself to any jurisdiction. /// \file taskLc.cxx -/// \brief Lc± analysis task +/// \brief Λc± → p± K∓ π± analysis task /// \note Extended from taskD0 /// /// \author Luigi Dello Stritto , University and INFN SALERNO @@ -19,13 +19,11 @@ #include "Framework/HistogramRegistry.h" #include "AnalysisDataModel/HFSecondaryVertex.h" #include "AnalysisDataModel/HFCandidateSelectionTables.h" -#include "AnalysisCore/HFSelectorCuts.h" using namespace o2; using namespace o2::framework; -using namespace o2::aod::hf_cand_prong3; using namespace o2::framework::expressions; -using namespace o2::analysis; +using namespace o2::aod::hf_cand_prong3; void customize(std::vector& workflowOptions) { @@ -35,7 +33,7 @@ void customize(std::vector& workflowOptions) #include "Framework/runDataProcessing.h" -/// Lc± analysis task +/// Λc± → p± K∓ π± analysis task struct TaskLc { HistogramRegistry registry{ "registry", @@ -46,7 +44,6 @@ struct TaskLc { Configurable d_selectionFlagLc{"d_selectionFlagLc", 1, "Selection Flag for Lc"}; Configurable cutYCandMax{"cutYCandMax", -1., "max. cand. rapidity"}; - Configurable> bins{"pTBins", std::vector{hf_cuts_lc_topkpi::pTBins_v}, "pT bin limits"}; Filter filterSelectCandidates = (aod::hf_selcandidate_lc::isSelLcpKpi >= d_selectionFlagLc || aod::hf_selcandidate_lc::isSelLcpiKp >= d_selectionFlagLc); @@ -72,11 +69,10 @@ struct TaskLc { void process(soa::Filtered> const& candidates) { for (auto& candidate : candidates) { - if (!(candidate.hfflag() & 1 << LcToPKPi)) { + if (!(candidate.hfflag() & 1 << DecayType::LcToPKPi)) { continue; } if (cutYCandMax >= 0. && std::abs(YLc(candidate)) > cutYCandMax) { - //Printf("Candidate: Y rejection: %g", YLc(candidate)); continue; } if (candidate.isSelLcpKpi() >= d_selectionFlagLc) { @@ -132,22 +128,19 @@ struct TaskLcMC { { // MC rec. //Printf("MC Candidates: %d", candidates.size()); - for (auto& candidate : candidates) { - if (!(candidate.hfflag() & 1 << LcToPKPi)) { + if (!(candidate.hfflag() & 1 << DecayType::LcToPKPi)) { continue; } if (cutYCandMax >= 0. && std::abs(YLc(candidate)) > cutYCandMax) { - //Printf("MC Rec.: Y rejection: %g", YLc(candidate)); continue; } - - if (std::abs(candidate.flagMCMatchRec()) == 1 << LcToPKPi) { + if (std::abs(candidate.flagMCMatchRec()) == 1 << DecayType::LcToPKPi) { // Get the corresponding MC particle. - auto indexMother = RecoDecay::getMother(particlesMC, candidate.index0_as().mcParticle_as>(), pdg::code::kLambdaCPlus, true); + auto indexMother = RecoDecay::getMother(particlesMC, candidate.index0_as().mcParticle_as>(), pdg::Code::kLambdaCPlus, true); auto particleMother = particlesMC.iteratorAt(indexMother); - registry.fill(HIST("hPtGenSig"), particleMother.pt()); //gen. level pT - registry.fill(HIST("hPtRecSig"), candidate.pt()); //rec. level pT + registry.fill(HIST("hPtGenSig"), particleMother.pt()); // gen. level pT + registry.fill(HIST("hPtRecSig"), candidate.pt()); // rec. level pT registry.fill(HIST("hCPARecSig"), candidate.cpa()); registry.fill(HIST("hEtaRecSig"), candidate.eta()); } else { @@ -159,9 +152,8 @@ struct TaskLcMC { // MC gen. //Printf("MC Particles: %d", particlesMC.size()); for (auto& particle : particlesMC) { - if (std::abs(particle.flagMCMatchGen()) == 1 << LcToPKPi) { + if (std::abs(particle.flagMCMatchGen()) == 1 << DecayType::LcToPKPi) { if (cutYCandMax >= 0. && std::abs(RecoDecay::Y(array{particle.px(), particle.py(), particle.pz()}, RecoDecay::getMassPDG(particle.pdgCode()))) > cutYCandMax) { - //Printf("MC Gen.: Y rejection: %g", RecoDecay::Y(array{particle.px(), particle.py(), particle.pz()}, RecoDecay::getMassPDG(particle.pdgCode()))); continue; } registry.fill(HIST("hPtGen"), particle.pt()); diff --git a/Analysis/Tasks/PWGHF/taskX.cxx b/Analysis/Tasks/PWGHF/taskX.cxx index 00fc8284f06f2..dc09e448604e8 100644 --- a/Analysis/Tasks/PWGHF/taskX.cxx +++ b/Analysis/Tasks/PWGHF/taskX.cxx @@ -21,8 +21,8 @@ using namespace o2; using namespace o2::framework; -using namespace o2::aod::hf_cand_prong2; using namespace o2::framework::expressions; +using namespace o2::aod::hf_cand_prong2; void customize(std::vector& workflowOptions) { @@ -48,7 +48,7 @@ struct TaskX { void process(aod::Collision const&, aod::BigTracks const& tracks, soa::Filtered> const& candidates) { for (auto& candidate : candidates) { - if (!(candidate.hfflag() & 1 << JpsiToEE)) { + if (!(candidate.hfflag() & 1 << DecayType::JpsiToEE)) { continue; } if (cutYCandMax >= 0. && std::abs(YJpsi(candidate)) > cutYCandMax) { diff --git a/Analysis/Tasks/PWGHF/taskXic.cxx b/Analysis/Tasks/PWGHF/taskXic.cxx index 8a845ac6d81ee..642fb0efbc8a7 100644 --- a/Analysis/Tasks/PWGHF/taskXic.cxx +++ b/Analysis/Tasks/PWGHF/taskXic.cxx @@ -9,7 +9,7 @@ // or submit itself to any jurisdiction. /// \file taskXic.cxx -/// \brief Xic± analysis task +/// \brief Ξc± analysis task /// \note Inspired from taskLc.cxx /// /// \author Mattia Faggin , University and INFN PADOVA @@ -18,13 +18,11 @@ #include "Framework/HistogramRegistry.h" #include "AnalysisDataModel/HFSecondaryVertex.h" #include "AnalysisDataModel/HFCandidateSelectionTables.h" -#include "AnalysisCore/HFSelectorCuts.h" using namespace o2; using namespace o2::framework; -using namespace o2::aod::hf_cand_prong3; using namespace o2::framework::expressions; -using namespace o2::analysis; +using namespace o2::aod::hf_cand_prong3; void customize(std::vector& workflowOptions) { @@ -34,7 +32,7 @@ void customize(std::vector& workflowOptions) #include "Framework/runDataProcessing.h" -/// Xic± analysis task +/// Ξc± analysis task struct TaskXic { HistogramRegistry registry{ "registry", @@ -45,7 +43,6 @@ struct TaskXic { Configurable d_selectionFlagXic{"d_selectionFlagXic", 1, "Selection Flag for Xic"}; Configurable cutYCandMax{"cutYCandMax", -1., "max. cand. rapidity"}; - Configurable> bins{"pTBins", std::vector{hf_cuts_d0_topik::pTBins_v}, "pT bin limits"}; void init(o2::framework::InitContext&) @@ -67,15 +64,13 @@ struct TaskXic { Filter filterSelectCandidates = (aod::hf_selcandidate_xic::isSelXicToPKPi >= d_selectionFlagXic || aod::hf_selcandidate_xic::isSelXicToPiKP >= d_selectionFlagXic); - //void process(aod::HfCandProng3 const& candidates) void process(soa::Filtered> const& candidates) { for (auto& candidate : candidates) { - if (!(candidate.hfflag() & 1 << XicToPKPi)) { + if (!(candidate.hfflag() & 1 << DecayType::XicToPKPi)) { continue; } if (cutYCandMax >= 0. && std::abs(YXic(candidate)) > cutYCandMax) { - //Printf("Candidate: Y rejection: %g", YXic(candidate)); continue; } if (candidate.isSelXicToPKPi() >= d_selectionFlagXic) { @@ -131,19 +126,18 @@ struct TaskXicMC { // MC rec. //Printf("MC Candidates: %d", candidates.size()); for (auto& candidate : candidates) { - if (!(candidate.hfflag() & 1 << XicToPKPi)) { + if (!(candidate.hfflag() & 1 << DecayType::XicToPKPi)) { continue; } if (cutYCandMax >= 0. && std::abs(YXic(candidate)) > cutYCandMax) { - //Printf("MC Rec.: Y rejection: %g", YXic(candidate)); continue; } - if (std::abs(candidate.flagMCMatchRec()) == 1 << XicToPKPi) { + if (std::abs(candidate.flagMCMatchRec()) == 1 << DecayType::XicToPKPi) { // Get the corresponding MC particle. - auto indexMother = RecoDecay::getMother(particlesMC, candidate.index0_as().mcParticle_as>(), pdg::code::kXiCPlus, true); + auto indexMother = RecoDecay::getMother(particlesMC, candidate.index0_as().mcParticle_as>(), pdg::Code::kXiCPlus, true); auto particleMother = particlesMC.iteratorAt(indexMother); - registry.fill(HIST("hPtGenSig"), particleMother.pt()); //gen. level pT - registry.fill(HIST("hPtRecSig"), candidate.pt()); //rec. level pT + registry.fill(HIST("hPtGenSig"), particleMother.pt()); // gen. level pT + registry.fill(HIST("hPtRecSig"), candidate.pt()); // rec. level pT registry.fill(HIST("hCPARecSig"), candidate.cpa()); registry.fill(HIST("hEtaRecSig"), candidate.eta()); } else { @@ -155,9 +149,8 @@ struct TaskXicMC { // MC gen. //Printf("MC Particles: %d", particlesMC.size()); for (auto& particle : particlesMC) { - if (std::abs(particle.flagMCMatchGen()) == 1 << XicToPKPi) { + if (std::abs(particle.flagMCMatchGen()) == 1 << DecayType::XicToPKPi) { if (cutYCandMax >= 0. && std::abs(RecoDecay::Y(array{particle.px(), particle.py(), particle.pz()}, RecoDecay::getMassPDG(particle.pdgCode()))) > cutYCandMax) { - //Printf("MC Gen.: Y rejection: %g", RecoDecay::Y(array{particle.px(), particle.py(), particle.pz()}, RecoDecay::getMassPDG(particle.pdgCode()))); continue; } registry.fill(HIST("hPtGen"), particle.pt()); From f72c2863316d1301edd35a0686f95f6a789af2e6 Mon Sep 17 00:00:00 2001 From: frmanso Date: Tue, 20 Apr 2021 09:59:19 +0200 Subject: [PATCH 174/770] New version of the MFT readout cables (#5966) Co-authored-by: manso --- .../MFT/base/include/MFTBase/HalfCone.h | 4 + Detectors/ITSMFT/MFT/base/src/HalfCone.cxx | 1034 +++++++++++++---- 2 files changed, 782 insertions(+), 256 deletions(-) diff --git a/Detectors/ITSMFT/MFT/base/include/MFTBase/HalfCone.h b/Detectors/ITSMFT/MFT/base/include/MFTBase/HalfCone.h index 8514c28deebac..6f503aac9916f 100644 --- a/Detectors/ITSMFT/MFT/base/include/MFTBase/HalfCone.h +++ b/Detectors/ITSMFT/MFT/base/include/MFTBase/HalfCone.h @@ -28,6 +28,10 @@ class HalfCone public: HalfCone(); + void makeAirVentilation(TGeoVolumeAssembly* HalfConeVolume, Int_t half, Int_t signe); + void makeMotherBoards(TGeoVolumeAssembly* HalfConeVolume, Int_t half, Int_t signe, Double_t tyMB0, Double_t tyMB0_3, Double_t tzMB0); + void makeFlexCables(TGeoVolumeAssembly* HalfConeVolume, Int_t half, Int_t signe); + void makeReadoutCables(TGeoVolumeAssembly* HalfConeVolume, Int_t half, Int_t signe); ~HalfCone(); diff --git a/Detectors/ITSMFT/MFT/base/src/HalfCone.cxx b/Detectors/ITSMFT/MFT/base/src/HalfCone.cxx index 240e0c2abc73c..8da3ebbb60742 100644 --- a/Detectors/ITSMFT/MFT/base/src/HalfCone.cxx +++ b/Detectors/ITSMFT/MFT/base/src/HalfCone.cxx @@ -28,6 +28,7 @@ #include "TGeoVolume.h" #include "TGeoXtru.h" #include "TMath.h" +#include // for TGeoTrap #include "MFTBase/Constants.h" #include "MFTBase/HalfCone.h" @@ -1268,6 +1269,7 @@ TGeoVolumeAssembly* HalfCone::createHalfCone(Int_t half) Double_t r_final_z; Double_t tyMB0; + Double_t tyMB0_3; Double_t tzMB0; if (half == 0) { @@ -1280,6 +1282,7 @@ TGeoVolumeAssembly* HalfCone::createHalfCone(Int_t half) r_final_z = 0; tyMB0 = -16.72; + tyMB0_3 = -18.0; tzMB0 = -(45.3 + 46.7) / 2; } @@ -1293,6 +1296,7 @@ TGeoVolumeAssembly* HalfCone::createHalfCone(Int_t half) r_final_z = 180; tyMB0 = 16.72; + tyMB0_3 = 18.0; tzMB0 = -(45.3 + 46.7) / 2; } @@ -1531,56 +1535,7 @@ TGeoVolumeAssembly* HalfCone::createHalfCone(Int_t half) HalfConeVolume->AddNode(frame_back, 6, c_final); HalfConeVolume->AddNode(colonne_mb, 7, c_final); - //========================== Mother Boards - //========================================= - - // ============= MotherBoard 0 and 1 - Double_t mMB0cu[3]; - Double_t mMB0fr4; - Double_t mMB0pol; - Double_t mMB0epo; - // Sizes - mMB0cu[0] = {13.65}; - mMB0cu[1] = {0.00615}; // 122.5 microns * taux d'occupation 50% = 61.5 microns - mMB0cu[2] = {2.39}; - mMB0fr4 = 0.1; // 1 mm - mMB0pol = 0.0150; // 150 microns - mMB0epo = 0.0225; // 225 microns - // Materials - auto* mCu = gGeoManager->GetMedium("MFT_Cu$"); - auto* mFR4 = gGeoManager->GetMedium("MFT_FR4$"); - auto* mPol = gGeoManager->GetMedium("MFT_Polyimide$"); - auto* mEpo = gGeoManager->GetMedium("MFT_Epoxy$"); - auto* mInox = gGeoManager->GetMedium("MFT_Inox$"); - - auto* MotherBoard0 = new TGeoVolumeAssembly(Form("MotherBoard0_H%d", half)); - // 4 layers - TGeoVolume* vMB0cu = gGeoManager->MakeBox("vMB0cu", mCu, mMB0cu[0] / 2, - mMB0cu[1] / 2, mMB0cu[2] / 2); - TGeoVolume* vMB0fr4 = gGeoManager->MakeBox("vMB0fr4", mFR4, mMB0cu[0] / 2, - mMB0fr4 / 2, mMB0cu[2] / 2); - TGeoVolume* vMB0pol = gGeoManager->MakeBox("vMB0pol", mPol, mMB0cu[0] / 2, - mMB0pol / 2, mMB0cu[2] / 2); - TGeoVolume* vMB0epo = gGeoManager->MakeBox("vMB0epo", mEpo, mMB0cu[0] / 2, - mMB0epo / 2, mMB0cu[2] / 2); - // Screws = Head + Thread - TGeoVolume* vMB0screwH = gGeoManager->MakeTube("vMB0screwH", mInox, 0.0, - 0.7 / 2, 0.35 / 2); // tete - TGeoVolume* vMB0screwT = gGeoManager->MakeTube("vMB0screwT", mInox, 0.0, - 0.4 / 2, 1.2 / 2); // filetage - // Insert Sertitec - TGeoVolume* vMB0serti = gGeoManager->MakeTube("vMB0serti", mInox, 0.16 / 2, - 0.556 / 2, 0.15 / 2); // tete - - vMB0cu->SetLineColor(kRed); - vMB0fr4->SetLineColor(kBlack); - vMB0pol->SetLineColor(kGreen); - vMB0epo->SetLineColor(kBlue); - vMB0screwH->SetLineColor(kOrange); - vMB0screwT->SetLineColor(kOrange); - vMB0serti->SetLineColor(kOrange); - // Positioning the layers - MotherBoard0->AddNode(vMB0cu, 1); + // ======================== Mother Boards and Services ======================= Int_t signe; if (half == 0) { signe = -1; @@ -1588,212 +1543,17 @@ TGeoVolumeAssembly* HalfCone::createHalfCone(Int_t half) if (half == 1) { signe = +1; } - auto* t_MB0fr4 = new TGeoTranslation("translation_fr4", 0.0, - signe * (mMB0fr4 + mMB0cu[1]) / 2, 0.0); - t_MB0fr4->RegisterYourself(); - MotherBoard0->AddNode(vMB0fr4, 1, t_MB0fr4); - auto* t_MB0pol = - new TGeoTranslation("translation_pol", 0.0, - signe * (mMB0fr4 + (mMB0cu[1] + mMB0pol) / 2), 0.0); - t_MB0pol->RegisterYourself(); - MotherBoard0->AddNode(vMB0pol, 1, t_MB0pol); - auto* t_MB0epo = new TGeoTranslation( - "translation_epo", 0.0, - signe * (mMB0fr4 + mMB0pol + (mMB0cu[1] + mMB0epo) / 2), 0.0); - t_MB0epo->RegisterYourself(); - MotherBoard0->AddNode(vMB0epo, 1, t_MB0epo); - auto* r_MB0screw = new TGeoRotation("rotation_vMB0screw", 0, 90, 0); - auto* t_MB0screwH1 = new TGeoCombiTrans( - mMB0cu[0] / 2 - 1.65, - signe * (mMB0fr4 + mMB0pol + mMB0epo + (mMB0cu[1] + 0.35) / 2), 0.0, - r_MB0screw); - t_MB0screwH1->RegisterYourself(); - auto* t_MB0screwT1 = new TGeoCombiTrans( - mMB0cu[0] / 2 - 1.65, -signe * (mMB0cu[1] + 1.2) / 2, 0.0, r_MB0screw); - t_MB0screwT1->RegisterYourself(); - auto* t_MB0screwH2 = new TGeoCombiTrans( - -(mMB0cu[0] / 2 - 1.65), - signe * (mMB0fr4 + mMB0pol + mMB0epo + (mMB0cu[1] + 0.35) / 2), 0.0, - r_MB0screw); - t_MB0screwH2->RegisterYourself(); - auto* t_MB0screwT2 = new TGeoCombiTrans( - -(mMB0cu[0] / 2 - 1.65), -signe * (mMB0cu[1] + 1.2) / 2, 0.0, r_MB0screw); - t_MB0screwT2->RegisterYourself(); - auto* t_MB0serti1 = new TGeoCombiTrans( - mMB0cu[0] / 2 - 2.65, - signe * (mMB0fr4 + mMB0pol + mMB0epo + (mMB0cu[1] + 0.153) / 2), 0.0, - r_MB0screw); - t_MB0serti1->RegisterYourself(); - auto* t_MB0serti2 = new TGeoCombiTrans( - -(mMB0cu[0] / 2 - 2.65), - signe * (mMB0fr4 + mMB0pol + mMB0epo + (mMB0cu[1] + 0.153) / 2), 0.0, - r_MB0screw); - t_MB0serti2->RegisterYourself(); - MotherBoard0->AddNode(vMB0screwH, 1, t_MB0screwH1); - MotherBoard0->AddNode(vMB0screwT, 1, t_MB0screwT1); - MotherBoard0->AddNode(vMB0screwH, 1, t_MB0screwH2); - MotherBoard0->AddNode(vMB0screwT, 1, t_MB0screwT2); - MotherBoard0->AddNode(vMB0serti, 1, t_MB0serti1); - MotherBoard0->AddNode(vMB0serti, 1, t_MB0serti2); + makeMotherBoards(HalfConeVolume, half, signe, tyMB0, tyMB0_3, tzMB0); + makeAirVentilation(HalfConeVolume, half, signe); + makeFlexCables(HalfConeVolume, half, signe); + makeReadoutCables(HalfConeVolume, half, signe); + // =========================================================================== - // Positioning the board - auto* t_MB0 = new TGeoTranslation("translation_MB0", 0.0, tyMB0, tzMB0); - t_MB0->RegisterYourself(); - auto* t_MB1 = new TGeoTranslation( - "translation_MB1", 0.0, tyMB0, - tzMB0 - 3.3); // 3.3 cm is the interdistance between disk 0 and 1 - t_MB1->RegisterYourself(); - auto* r_MB0 = new TGeoRotation("rotation_MB0", 0.0, 0.0, 0.0); - r_MB0->RegisterYourself(); - auto* p_MB0 = new TGeoCombiTrans(*t_MB0, *r_MB0); - p_MB0->RegisterYourself(); - auto* p_MB1 = new TGeoCombiTrans(*t_MB1, *r_MB0); - p_MB1->RegisterYourself(); - // Final addition of the board - HalfConeVolume->AddNode(MotherBoard0, 1, p_MB0); - HalfConeVolume->AddNode(MotherBoard0, 1, p_MB1); - - auto* MotherBoard0_1 = - new TGeoVolumeAssembly(Form("MotherBoard0_1_H%d", half)); - // 4 layers - TGeoVolume* vMB0cu_1 = - gGeoManager->MakeBox("vMB0cu_1", mCu, 18.0 / 2, mMB0cu[1] / 2, 1.2 / 2); - TGeoVolume* vMB0fr4_1 = - gGeoManager->MakeBox("vMB0fr4_1", mFR4, 18.0 / 2, mMB0fr4 / 2, 1.2 / 2); - TGeoVolume* vMB0pol_1 = - gGeoManager->MakeBox("vMB0pol_1", mPol, 18.0 / 2, mMB0pol / 2, 1.2 / 2); - TGeoVolume* vMB0epo_1 = - gGeoManager->MakeBox("vMB0epo_1", mEpo, 18.0 / 2, mMB0epo / 2, 1.2 / 2); - vMB0cu_1->SetLineColor(kRed); - vMB0fr4_1->SetLineColor(kBlack); - vMB0pol_1->SetLineColor(kGreen); - vMB0epo_1->SetLineColor(kBlue); - - MotherBoard0_1->AddNode(vMB0cu_1, 1); - MotherBoard0_1->AddNode(vMB0fr4_1, 1, t_MB0fr4); - MotherBoard0_1->AddNode(vMB0pol_1, 1, t_MB0pol); - MotherBoard0_1->AddNode(vMB0epo_1, 1, t_MB0epo); - - // ================ MotherBoard 2 - Double_t mMB2cu[4]; - Double_t mMB2fr4; - Double_t mMB2pol; - Double_t mMB2epo; - // Sizes - mMB2cu[0] = {24.0}; - mMB2cu[1] = {21.0}; - mMB2cu[2] = {0.0079}; // 315 microns * taux d'occupation 25% = 79 microns - mMB2cu[3] = {8.5}; - mMB2fr4 = 0.2; // 2 mm - mMB2pol = 0.0175; // 175 microns - mMB2epo = 0.0075; // 75 microns - auto* MotherBoard2 = new TGeoVolumeAssembly(Form("MotherBoard2_H%d", half)); - // 4 layers - TGeoVolume* vMB2cu = - gGeoManager->MakeTrd1("vMB2cu", mCu, mMB2cu[0] / 2, mMB2cu[1] / 2, - mMB2cu[2] / 2, mMB2cu[3] / 2); - TGeoVolume* vMB2fr4 = - gGeoManager->MakeTrd1("vMB2fr4", mFR4, mMB2cu[0] / 2, mMB2cu[1] / 2, - mMB2fr4 / 2, mMB2cu[3] / 2); - TGeoVolume* vMB2pol = - gGeoManager->MakeTrd1("vMB2pol", mPol, mMB2cu[0] / 2, mMB2cu[1] / 2, - mMB2pol / 2, mMB2cu[3] / 2); - TGeoVolume* vMB2epo = - gGeoManager->MakeTrd1("vMB2epo", mEpo, mMB2cu[0] / 2, mMB2cu[1] / 2, - mMB2epo / 2, mMB2cu[3] / 2); - - vMB2cu->SetLineColor(kRed); - vMB2fr4->SetLineColor(kBlack); - vMB2pol->SetLineColor(kGreen); - vMB2epo->SetLineColor(kBlue); - - auto* t_MB2fr4 = new TGeoTranslation("translation_fr4", 0.0, - signe * (mMB2fr4 + mMB2cu[2]) / 2, 0.0); - t_MB2fr4->RegisterYourself(); - auto* t_MB2pol = - new TGeoTranslation("translation_pol", 0.0, - signe * (mMB2fr4 + (mMB2cu[2] + mMB2pol) / 2), 0.0); - t_MB2pol->RegisterYourself(); - auto* t_MB2epo = new TGeoTranslation( - "translation_epo", 0.0, - signe * (mMB2fr4 + mMB2pol + (mMB2cu[2] + mMB2epo) / 2), 0.0); - t_MB2epo->RegisterYourself(); - - MotherBoard2->AddNode(vMB2cu, 1); - MotherBoard2->AddNode(vMB2fr4, 1, t_MB2fr4); - MotherBoard2->AddNode(vMB2pol, 1, t_MB2pol); - MotherBoard2->AddNode(vMB2epo, 1, t_MB2epo); - for (Float_t i = -1; i < 3; i++) { - auto* t_MB2serti1 = new TGeoTranslation( - "translationMB2serti1", 8.5, -signe * (mMB2cu[2] + 0.153) / 2, 1.3 * i); - t_MB2serti1->RegisterYourself(); - auto* t_MB2serti2 = - new TGeoTranslation("translationMB2serti2", -8.5, - -signe * (mMB2cu[2] + 0.153) / 2, 1.3 * i); - t_MB2serti2->RegisterYourself(); - auto* p_MB2serti1 = new TGeoCombiTrans(*t_MB2serti1, *r_MB0screw); - p_MB2serti1->RegisterYourself(); - auto* p_MB2serti2 = new TGeoCombiTrans(*t_MB2serti2, *r_MB0screw); - p_MB2serti2->RegisterYourself(); - MotherBoard2->AddNode(vMB0serti, 1, p_MB2serti1); - MotherBoard2->AddNode(vMB0serti, 1, p_MB2serti2); - } - - for (Float_t i = -2; i < 1; i++) { - auto* t_MB2serti3 = new TGeoTranslation( - "translationMB2serti3", 0.7, -signe * (mMB2cu[2] + 0.153) / 2, 1.3 * i); - t_MB2serti3->RegisterYourself(); - auto* t_MB2serti4 = - new TGeoTranslation("translationMB2serti4", -0.7, - -signe * (mMB2cu[2] + 0.153) / 2, 1.3 * i); - t_MB2serti4->RegisterYourself(); - auto* p_MB2serti3 = new TGeoCombiTrans(*t_MB2serti3, *r_MB0screw); - p_MB2serti3->RegisterYourself(); - auto* p_MB2serti4 = new TGeoCombiTrans(*t_MB2serti4, *r_MB0screw); - p_MB2serti4->RegisterYourself(); - MotherBoard2->AddNode(vMB0serti, 1, p_MB2serti3); - MotherBoard2->AddNode(vMB0serti, 1, p_MB2serti4); - } - - for (Float_t i = -2; i < 2; i++) { - auto* t_MB2serti5 = - new TGeoTranslation("translationMB2serti5", 7.0 * i + 3.5, - -signe * (mMB2cu[2] + 0.153) / 2, -2.5); - t_MB2serti5->RegisterYourself(); - auto* p_MB2serti5 = new TGeoCombiTrans(*t_MB2serti5, *r_MB0screw); - p_MB2serti5->RegisterYourself(); - auto* t_MB2serti6 = - new TGeoTranslation("translationMB2serti6", 7.0 * i + 3.5, - -signe * (mMB2cu[2] + 0.153) / 2, -3.5); - t_MB2serti6->RegisterYourself(); - auto* p_MB2serti6 = new TGeoCombiTrans(*t_MB2serti6, *r_MB0screw); - p_MB2serti6->RegisterYourself(); - MotherBoard2->AddNode(vMB0serti, 1, p_MB2serti5); - MotherBoard2->AddNode(vMB0serti, 1, p_MB2serti6); - } - // Connector board of MB0 on MB2 - auto* t_MotherBoard0_1 = - new TGeoTranslation("translation_MB0_1", 0.0, -signe * (-0.5), 3.5); - t_MotherBoard0_1->RegisterYourself(); - auto* t_MotherBoard0_2 = - new TGeoTranslation("translation_MB0_2", 0.0, -signe * (-0.5), 1.5); - t_MotherBoard0_2->RegisterYourself(); - MotherBoard2->AddNode(MotherBoard0_1, 1, t_MotherBoard0_1); - MotherBoard2->AddNode(MotherBoard0_1, 1, t_MotherBoard0_2); - // Positioning the board - auto* t_MotherBoard2 = new TGeoTranslation( - "translation_MB2", 0.0, - -signe * (-20.52 + mMB2fr4 + mMB2pol + mMB2epo + 2.2 * TMath::Sin(19.0)), - -62.8 + 2.2 * TMath::Cos(19.0)); - t_MotherBoard2->RegisterYourself(); - auto* r_MotherBoard2 = - new TGeoRotation("rotation_MB2", 0.0, -signe * (-19.0), 0.0); - r_MotherBoard2->RegisterYourself(); - auto* p_MB2 = new TGeoCombiTrans(*t_MotherBoard2, *r_MotherBoard2); - p_MB2->RegisterYourself(); - HalfConeVolume->AddNode(MotherBoard2, 1, p_MB2); + return HalfConeVolume; +} - //======================== Air ventilation ========================== +void HalfCone::makeAirVentilation(TGeoVolumeAssembly* HalfConeVolume, Int_t half, Int_t signe) +{ TGeoMedium* mVentilation = gGeoManager->GetMedium("MFT_Polypropylene$"); // Bottom TGeoSubtraction* vent_subB1; @@ -1990,6 +1750,768 @@ TGeoVolumeAssembly* HalfCone::createHalfCone(Int_t half) auto* p_airT4 = new TGeoCombiTrans(*t_airT4, *r_airT4); p_airT4->RegisterYourself(); HalfConeVolume->AddNode(vent_T4, 1, p_airT4); - //=================================================================== - return HalfConeVolume; +} + +void HalfCone::makeMotherBoards(TGeoVolumeAssembly* HalfConeVolume, Int_t half, Int_t signe, Double_t tyMB0, Double_t tyMB0_3, Double_t tzMB0) +{ + // ============= MotherBoard 0 and 1 + Double_t mMB0cu[3]; + Double_t mMB0fr4; + Double_t mMB0pol; + Double_t mMB0epo; + // Sizes + mMB0cu[0] = {14.00}; // 13.65 old + mMB0cu[1] = {0.00615}; // 122.5 microns * taux d'occupation 50% = 61.5 microns + mMB0cu[2] = {2.45}; // 2.39 old + mMB0fr4 = 0.1; // 1 m + mMB0pol = 0.0150; // 150 microns + mMB0epo = 0.0225; // 225 microns + + // Materials + auto* mCu = gGeoManager->GetMedium("MFT_Cu$"); + auto* mFR4 = gGeoManager->GetMedium("MFT_FR4$"); + auto* mPol = gGeoManager->GetMedium("MFT_Polyimide$"); + auto* mEpo = gGeoManager->GetMedium("MFT_Epoxy$"); + auto* mInox = gGeoManager->GetMedium("MFT_Inox$"); + auto* mPolyu = gGeoManager->GetMedium("MFT_Polyurethane$"); + + // Mother boards connected to the first three disk + auto* MotherBoard0 = new TGeoVolumeAssembly(Form("MotherBoard0_H%d", half)); + // 4 layers + TGeoVolume* vMB0cu = gGeoManager->MakeBox("vMB0cu", mCu, mMB0cu[0] / 2, mMB0cu[1] / 2, mMB0cu[2] / 2); + TGeoVolume* vMB0fr4 = gGeoManager->MakeBox("vMB0fr4", mFR4, mMB0cu[0] / 2, mMB0fr4 / 2, mMB0cu[2] / 2); + TGeoVolume* vMB0pol = gGeoManager->MakeBox("vMB0pol", mPol, mMB0cu[0] / 2, mMB0pol / 2, mMB0cu[2] / 2); + TGeoVolume* vMB0epo = gGeoManager->MakeBox("vMB0epo", mEpo, mMB0cu[0] / 2, mMB0epo / 2, mMB0cu[2] / 2); + + // Screws = Head + Thread + TGeoVolume* vMB0screwH = gGeoManager->MakeTube("vMB0screwH", mInox, 0.0, 0.7 / 2, 0.35 / 2); // tete + TGeoVolume* vMB0screwT = gGeoManager->MakeTube("vMB0screwT", mInox, 0.0, 0.4 / 2, 0.95 / 2); // filetage + // Insert Sertitec + TGeoVolume* vMB0serti = gGeoManager->MakeTube("vMB0serti", mInox, 0.16 / 2, 0.556 / 2, 0.15 / 2); // tete + + Float_t heigthConnector = 0.4; // male + female + TGeoVolume* vConnector = gGeoManager->MakeBox("vConnector", mPolyu, 6.2 / 2, heigthConnector / 2, 1.4 / 2); // in liquid-crystal polymer --> polyurethane? + vMB0cu->SetLineColor(kGreen); + vMB0fr4->SetLineColor(kBlack); + vMB0pol->SetLineColor(kBlue); + vMB0epo->SetLineColor(kGreen); + vMB0screwH->SetLineColor(kOrange); + vMB0screwT->SetLineColor(kOrange); + vMB0serti->SetLineColor(kOrange); + vConnector->SetLineColor(kGray + 3); + + // Positioning the layers + MotherBoard0->AddNode(vMB0cu, 1); + + auto* t_MB0fr4 = new TGeoTranslation("translation_fr4", 0.0, signe * (mMB0fr4 + mMB0cu[1]) / 2, 0.0); + t_MB0fr4->RegisterYourself(); + MotherBoard0->AddNode(vMB0fr4, 1, t_MB0fr4); + auto* t_MB0pol = + new TGeoTranslation("translation_pol", 0.0, signe * (mMB0fr4 + (mMB0cu[1] + mMB0pol) / 2), 0.0); + t_MB0pol->RegisterYourself(); + MotherBoard0->AddNode(vMB0pol, 1, t_MB0pol); + auto* t_MB0epo = new TGeoTranslation("translation_epo", 0.0, signe * (mMB0fr4 + mMB0pol + (mMB0cu[1] + mMB0epo) / 2), 0.0); + t_MB0epo->RegisterYourself(); + MotherBoard0->AddNode(vMB0epo, 1, t_MB0epo); + auto* r_MB0screw = new TGeoRotation("rotation_vMB0screw", 0, 90, 0); + auto* t_MB0screwH1 = new TGeoCombiTrans(mMB0cu[0] / 2 - 1.65, signe * (mMB0fr4 + mMB0pol + mMB0epo + (mMB0cu[1] + 0.35) / 2), 0.0, r_MB0screw); + t_MB0screwH1->RegisterYourself(); + auto* t_MB0screwT1 = new TGeoCombiTrans(mMB0cu[0] / 2 - 1.65, -signe * (mMB0cu[1] + 0.95) / 2, 0.0, r_MB0screw); + t_MB0screwT1->RegisterYourself(); + auto* t_MB0screwH2 = new TGeoCombiTrans(-(mMB0cu[0] / 2 - 1.65), signe * (mMB0fr4 + mMB0pol + mMB0epo + (mMB0cu[1] + 0.35) / 2), 0.0, r_MB0screw); + t_MB0screwH2->RegisterYourself(); + auto* t_MB0screwT2 = new TGeoCombiTrans(-(mMB0cu[0] / 2 - 1.65), -signe * (mMB0cu[1] + 0.95) / 2, 0.0, r_MB0screw); + t_MB0screwT2->RegisterYourself(); + auto* t_MB0serti1 = new TGeoCombiTrans(mMB0cu[0] / 2 - 2.65, signe * (mMB0fr4 + mMB0pol + mMB0epo + (mMB0cu[1] + 0.153) / 2), 0.0, r_MB0screw); + t_MB0serti1->RegisterYourself(); + auto* t_MB0serti2 = new TGeoCombiTrans(-(mMB0cu[0] / 2 - 2.65), signe * (mMB0fr4 + mMB0pol + mMB0epo + (mMB0cu[1] + 0.153) / 2), 0.0, r_MB0screw); + t_MB0serti2->RegisterYourself(); + auto* t_MB0Connector = new TGeoTranslation("translation_connector", 0.0, signe * (-mMB0cu[1] - 0.2), 0.0); + t_MB0Connector->RegisterYourself(); + + MotherBoard0->AddNode(vMB0screwH, 1, t_MB0screwH1); + MotherBoard0->AddNode(vMB0screwT, 1, t_MB0screwT1); + MotherBoard0->AddNode(vMB0screwH, 1, t_MB0screwH2); + MotherBoard0->AddNode(vMB0screwT, 1, t_MB0screwT2); + MotherBoard0->AddNode(vMB0serti, 1, t_MB0serti1); + MotherBoard0->AddNode(vMB0serti, 1, t_MB0serti2); + MotherBoard0->AddNode(vConnector, 1, t_MB0Connector); + + // Positioning the boards on the disks + Float_t shift = 0.23; + Float_t shift3 = 0.09; + auto* t_disk0 = new TGeoTranslation("translation_disk0", 0.0, tyMB0 - signe * shift, tzMB0); + t_disk0->RegisterYourself(); + auto* t_disk1 = new TGeoTranslation("translation_disk1", 0.0, tyMB0 - signe * shift, tzMB0 - 3.3); + t_disk1->RegisterYourself(); + auto* t_disk2 = new TGeoTranslation("translation_disk2", 0.0, tyMB0_3 - signe * shift3, tzMB0 - 7.1); + t_disk2->RegisterYourself(); + auto* r_MB0 = new TGeoRotation("rotation_MB0", 0.0, 0.0, 0.0); + r_MB0->RegisterYourself(); + auto* p_disk0 = new TGeoCombiTrans(*t_disk0, *r_MB0); + p_disk0->RegisterYourself(); + auto* p_disk1 = new TGeoCombiTrans(*t_disk1, *r_MB0); + p_disk1->RegisterYourself(); + auto* p_disk2 = new TGeoCombiTrans(*t_disk2, *r_MB0); + p_disk2->RegisterYourself(); + // Final addition of the boards + HalfConeVolume->AddNode(MotherBoard0, 1, p_disk0); + HalfConeVolume->AddNode(MotherBoard0, 1, p_disk1); + HalfConeVolume->AddNode(MotherBoard0, 1, p_disk2); + + // Small boards on to the main mother board + auto* MotherBoard0_1 = new TGeoVolumeAssembly(Form("MotherBoard0_1_H%d", half)); + // 4 layers + TGeoVolume* vMB0cu_1 = + gGeoManager->MakeBox("vMB0cu_1", mCu, 18.0 / 2, mMB0cu[1] / 2, 1.2 / 2); + TGeoVolume* vMB0fr4_1 = + gGeoManager->MakeBox("vMB0fr4_1", mFR4, 18.0 / 2, mMB0fr4 / 2, 1.2 / 2); + TGeoVolume* vMB0pol_1 = + gGeoManager->MakeBox("vMB0pol_1", mPol, 18.0 / 2, mMB0pol / 2, 1.2 / 2); + TGeoVolume* vMB0epo_1 = + gGeoManager->MakeBox("vMB0epo_1", mEpo, 18.0 / 2, mMB0epo / 2, 1.2 / 2); + vMB0cu_1->SetLineColor(kGreen); + vMB0fr4_1->SetLineColor(kBlack); + vMB0pol_1->SetLineColor(kBlue); + vMB0epo_1->SetLineColor(kGreen); + MotherBoard0_1->AddNode(vMB0cu_1, 1); + MotherBoard0_1->AddNode(vMB0fr4_1, 1, t_MB0fr4); + MotherBoard0_1->AddNode(vMB0pol_1, 1, t_MB0pol); + MotherBoard0_1->AddNode(vMB0epo_1, 1, t_MB0epo); + + // ================ Main Mother Board + Double_t mMB2cu[4]; + Double_t mMB2fr4; + Double_t mMB2pol; + Double_t mMB2epo; + // Sizes + mMB2cu[0] = {24.0}; + mMB2cu[1] = {21.0}; + mMB2cu[2] = {0.0079}; // 315 microns * taux d'occupation 25% = 79 microns + mMB2cu[3] = {8.5}; + mMB2fr4 = 0.2; // 2 mm + mMB2pol = 0.0175; // 175 microns + mMB2epo = 0.0075; // 75 microns + auto* MotherBoard2 = new TGeoVolumeAssembly(Form("MotherBoard2_H%d", half)); + // 4 layers + TGeoVolume* vMB2cu = + gGeoManager->MakeTrd1("vMB2cu", mCu, mMB2cu[0] / 2, mMB2cu[1] / 2, + mMB2cu[2] / 2, mMB2cu[3] / 2); + TGeoVolume* vMB2fr4 = + gGeoManager->MakeTrd1("vMB2fr4", mFR4, mMB2cu[0] / 2, mMB2cu[1] / 2, + mMB2fr4 / 2, mMB2cu[3] / 2); + TGeoVolume* vMB2pol = + gGeoManager->MakeTrd1("vMB2pol", mPol, mMB2cu[0] / 2, mMB2cu[1] / 2, + mMB2pol / 2, mMB2cu[3] / 2); + TGeoVolume* vMB2epo = + gGeoManager->MakeTrd1("vMB2epo", mEpo, mMB2cu[0] / 2, mMB2cu[1] / 2, + mMB2epo / 2, mMB2cu[3] / 2); + vMB2cu->SetLineColor(kGreen); + vMB2fr4->SetLineColor(kBlack); + vMB2pol->SetLineColor(kBlue); + vMB2epo->SetLineColor(kGreen + 2); + auto* t_MB2fr4 = new TGeoTranslation("translation_fr4", 0.0, + signe * (mMB2fr4 + mMB2cu[2]) / 2, 0.0); + t_MB2fr4->RegisterYourself(); + auto* t_MB2pol = + new TGeoTranslation("translation_pol", 0.0, + signe * (mMB2fr4 + (mMB2cu[2] + mMB2pol) / 2), 0.0); + t_MB2pol->RegisterYourself(); + auto* t_MB2epo = new TGeoTranslation( + "translation_epo", 0.0, + signe * (mMB2fr4 + mMB2pol + (mMB2cu[2] + mMB2epo) / 2), 0.0); + t_MB2epo->RegisterYourself(); + MotherBoard2->AddNode(vMB2cu, 1); + MotherBoard2->AddNode(vMB2fr4, 1, t_MB2fr4); + MotherBoard2->AddNode(vMB2pol, 1, t_MB2pol); + MotherBoard2->AddNode(vMB2epo, 1, t_MB2epo); + + for (Float_t i = -1; i < 3; i++) { + auto* t_MB2serti1 = new TGeoTranslation( + "translationMB2serti1", 8.5, -signe * (mMB2cu[2] + 0.153) / 2, 1.3 * i); + t_MB2serti1->RegisterYourself(); + auto* t_MB2serti2 = + new TGeoTranslation("translationMB2serti2", -8.5, + -signe * (mMB2cu[2] + 0.153) / 2, 1.3 * i); + t_MB2serti2->RegisterYourself(); + auto* p_MB2serti1 = new TGeoCombiTrans(*t_MB2serti1, *r_MB0screw); + p_MB2serti1->RegisterYourself(); + auto* p_MB2serti2 = new TGeoCombiTrans(*t_MB2serti2, *r_MB0screw); + p_MB2serti2->RegisterYourself(); + MotherBoard2->AddNode(vMB0serti, 1, p_MB2serti1); + MotherBoard2->AddNode(vMB0serti, 1, p_MB2serti2); + } + + for (Float_t i = -2; i < 1; i++) { + auto* t_MB2serti3 = new TGeoTranslation( + "translationMB2serti3", 0.7, -signe * (mMB2cu[2] + 0.153) / 2, 1.3 * i); + t_MB2serti3->RegisterYourself(); + auto* t_MB2serti4 = + new TGeoTranslation("translationMB2serti4", -0.7, + -signe * (mMB2cu[2] + 0.153) / 2, 1.3 * i); + t_MB2serti4->RegisterYourself(); + auto* p_MB2serti3 = new TGeoCombiTrans(*t_MB2serti3, *r_MB0screw); + p_MB2serti3->RegisterYourself(); + auto* p_MB2serti4 = new TGeoCombiTrans(*t_MB2serti4, *r_MB0screw); + p_MB2serti4->RegisterYourself(); + MotherBoard2->AddNode(vMB0serti, 1, p_MB2serti3); + MotherBoard2->AddNode(vMB0serti, 1, p_MB2serti4); + } + + for (Float_t i = -2; i < 2; i++) { + auto* t_MB2serti5 = + new TGeoTranslation("translationMB2serti5", 7.0 * i + 3.5, + -signe * (mMB2cu[2] + 0.153) / 2, -2.5); + t_MB2serti5->RegisterYourself(); + auto* p_MB2serti5 = new TGeoCombiTrans(*t_MB2serti5, *r_MB0screw); + p_MB2serti5->RegisterYourself(); + auto* t_MB2serti6 = + new TGeoTranslation("translationMB2serti6", 7.0 * i + 3.5, + -signe * (mMB2cu[2] + 0.153) / 2, -3.5); + t_MB2serti6->RegisterYourself(); + auto* p_MB2serti6 = new TGeoCombiTrans(*t_MB2serti6, *r_MB0screw); + p_MB2serti6->RegisterYourself(); + MotherBoard2->AddNode(vMB0serti, 1, p_MB2serti5); + MotherBoard2->AddNode(vMB0serti, 1, p_MB2serti6); + } + // Two boards (from the two first disks) located on the main mother board + auto* t_MotherBoard0_1 = + new TGeoTranslation("translation_MB0_1", 0.0, -signe * (-heigthConnector - mMB2cu[2] - mMB2fr4 - mMB2pol - mMB2epo), 3.5); + t_MotherBoard0_1->RegisterYourself(); + auto* t_MotherBoard0_2 = + new TGeoTranslation("translation_MB0_2", 0.0, -signe * (-heigthConnector - mMB2cu[2] - mMB2fr4 - mMB2pol - mMB2epo), 1.5); + + t_MotherBoard0_2->RegisterYourself(); + MotherBoard2->AddNode(MotherBoard0_1, 1, t_MotherBoard0_1); + MotherBoard2->AddNode(MotherBoard0_1, 2, t_MotherBoard0_2); + + TGeoVolume* vConnector2 = gGeoManager->MakeBox("vConnector2", mPolyu, 12.00 / 2, heigthConnector / 2, 0.7 / 2); + TGeoVolume* vConnector2p = gGeoManager->MakeBox("vConnector2p", mPolyu, 6.00 / 2, heigthConnector / 2, 0.7 / 2); + // === Readout cables connectors === + + TGeoVolume* vConnectorRC = gGeoManager->MakeBox("vConnectorRC-MB2", mPolyu, 6.00 / 2, heigthConnector / 2, 1.4 / 2); + // ================================== + Double_t yMB2Connector = signe * (mMB2cu[2] / 2 + mMB2fr4 + mMB2pol + mMB2epo + heigthConnector / 2); + auto* t_MB2Connector1 = new TGeoTranslation("translation_connector1", 0.0, yMB2Connector, 1.5); + t_MB2Connector1->RegisterYourself(); + auto* t_MB2Connector2 = new TGeoTranslation("translation_connector2", 0.0, yMB2Connector, 3.5); + t_MB2Connector2->RegisterYourself(); + auto* t_MB2ConnectorRC_1 = new TGeoTranslation("translation_connectorRC_1", 3.5, yMB2Connector, -0.5); + t_MB2ConnectorRC_1->RegisterYourself(); + auto* t_MB2ConnectorRC_2 = new TGeoTranslation("translation_connectorRC_2", -3.5, yMB2Connector, -0.5); + t_MB2ConnectorRC_1->RegisterYourself(); + auto* t_MB2ConnectorRC_3 = new TGeoTranslation("translation_connectorRC_3", 7.0, yMB2Connector, -3.5); + t_MB2ConnectorRC_2->RegisterYourself(); + auto* t_MB2ConnectorRC_4 = new TGeoTranslation("translation_connectorRC_4", -7.0, yMB2Connector, -3.5); + t_MB2ConnectorRC_2->RegisterYourself(); + + yMB2Connector = signe * (-mMB2cu[2] / 2 - heigthConnector / 2); + auto* t_MB2ConnectorRCp_1 = new TGeoTranslation("translation_connectorRCp_1", 4.0, yMB2Connector, 0.5); + t_MB2ConnectorRCp_1->RegisterYourself(); + auto* t_MB2ConnectorRCp_2 = new TGeoTranslation("translation_connectorRCp_2", -4.0, yMB2Connector, 0.5); + t_MB2ConnectorRCp_2->RegisterYourself(); + auto* t_MB2ConnectorRCp_3 = new TGeoTranslation("translation_connectorRCp_3", 7.0, yMB2Connector, -3.5); + t_MB2ConnectorRCp_3->RegisterYourself(); + auto* t_MB2ConnectorRCp_4 = new TGeoTranslation("translation_connectorRCp_4", -7.0, yMB2Connector, -3.5); + t_MB2ConnectorRCp_4->RegisterYourself(); + + vConnector2->SetLineColor(kGray + 3); + vConnectorRC->SetLineColor(kGray + 3); + MotherBoard2->AddNode(vConnector2, 1, t_MB2Connector1); + MotherBoard2->AddNode(vConnector2, 1, t_MB2Connector2); + MotherBoard2->AddNode(vConnectorRC, 1, t_MB2ConnectorRC_1); + MotherBoard2->AddNode(vConnectorRC, 1, t_MB2ConnectorRC_2); + MotherBoard2->AddNode(vConnectorRC, 1, t_MB2ConnectorRC_3); + MotherBoard2->AddNode(vConnectorRC, 1, t_MB2ConnectorRC_4); + MotherBoard2->AddNode(vConnectorRC, 1, t_MB2ConnectorRCp_1); + MotherBoard2->AddNode(vConnectorRC, 1, t_MB2ConnectorRCp_2); + MotherBoard2->AddNode(vConnectorRC, 1, t_MB2ConnectorRCp_3); + MotherBoard2->AddNode(vConnectorRC, 1, t_MB2ConnectorRCp_4); + + // Positioning the main mother board + auto* t_MotherBoard2 = new TGeoTranslation( + "translation_MB2", 0.0, + -signe * (-20.52 + mMB2fr4 + mMB2pol + mMB2epo + 2.2 * TMath::Sin(19.0)), + -62.8 + 2.2 * TMath::Cos(19.0)); + t_MotherBoard2->RegisterYourself(); + auto* r_MotherBoard2 = + new TGeoRotation("rotation_MB2", 0.0, -signe * (-19.0), 0.0); + r_MotherBoard2->RegisterYourself(); + auto* p_MB2 = new TGeoCombiTrans(*t_MotherBoard2, *r_MotherBoard2); + p_MB2->RegisterYourself(); + HalfConeVolume->AddNode(MotherBoard2, 1, p_MB2); +} + +void HalfCone::makeFlexCables(TGeoVolumeAssembly* HalfConeVolume, Int_t half, Int_t signe) +{ + auto* mCu = gGeoManager->GetMedium("MFT_Cu$"); + // Flat cables between disk 0 and main board + Float_t width_flat = 1.0; // 4 flexs, fully arbitrary! + Float_t thickness_flat = 0.0041; // 10 microns lines (228 lines, 0.0175x0.1 mm2) + 31 microns ground plane (~width 70 mm, thickness 0.0175mm) + Double_t theta1 = -22.70 + signe * 16.5; + Double_t theta2 = 22.60 + signe * 16.5; + TGeoVolume* vFlat0_1 = gGeoManager->MakeTubs("vFlat0_1", mCu, 15.0, 15.0 + thickness_flat, width_flat / 2., theta1, theta2); + TGeoVolume* vFlat0_2 = gGeoManager->MakeTubs("vFlat0_2", mCu, 15.0, 15.0 + thickness_flat, width_flat / 2., theta1, theta2); + TGeoVolume* vFlat0_3 = gGeoManager->MakeTubs("vFlat0_3", mCu, 15.0, 15.0 + thickness_flat, width_flat / 2., theta1, theta2); + TGeoVolume* vFlat0_4 = gGeoManager->MakeTubs("vFlat0_4", mCu, 15.0, 15.0 + thickness_flat, width_flat / 2., theta1, theta2); + auto* t_flat0_1 = new TGeoTranslation("translation_flat0_1", 4.5, signe * 5.0, -56.73); + t_flat0_1->RegisterYourself(); + auto* t_flat0_2 = new TGeoTranslation("translation_flat0_2", 1.5, signe * 5.0, -56.73); + t_flat0_2->RegisterYourself(); + auto* t_flat0_3 = new TGeoTranslation("translation_flat0_3", -1.5, signe * 5.0, -56.73); + t_flat0_3->RegisterYourself(); + auto* t_flat0_4 = new TGeoTranslation("translation_flat0_4", -4.5, signe * 5.0, -56.73); + t_flat0_4->RegisterYourself(); + auto* r_flat0 = new TGeoRotation("rotation_flat0", signe * 90.0, signe * 90.0, 0.0); + r_flat0->RegisterYourself(); + auto* p_flat0_1 = new TGeoCombiTrans(*t_flat0_1, *r_flat0); + p_flat0_1->RegisterYourself(); + auto* p_flat0_2 = new TGeoCombiTrans(*t_flat0_2, *r_flat0); + p_flat0_2->RegisterYourself(); + auto* p_flat0_3 = new TGeoCombiTrans(*t_flat0_3, *r_flat0); + p_flat0_3->RegisterYourself(); + auto* p_flat0_4 = new TGeoCombiTrans(*t_flat0_4, *r_flat0); + p_flat0_4->RegisterYourself(); + HalfConeVolume->AddNode(vFlat0_1, 1, p_flat0_1); + HalfConeVolume->AddNode(vFlat0_2, 1, p_flat0_2); + HalfConeVolume->AddNode(vFlat0_3, 1, p_flat0_3); + HalfConeVolume->AddNode(vFlat0_4, 1, p_flat0_4); + + // Flat lines between disk 1 and main board + theta1 = -32.0 + signe * 24.69; + theta2 = 32.7 + signe * 24.69; + TGeoVolume* vFlat1_1 = gGeoManager->MakeTubs("vFlat1_1", mCu, 6.0, 6.00 + thickness_flat, width_flat / 2., theta1, theta2); + TGeoVolume* vFlat1_2 = gGeoManager->MakeTubs("vFlat1_2", mCu, 6.0, 6.00 + thickness_flat, width_flat / 2., theta1, theta2); + TGeoVolume* vFlat1_3 = gGeoManager->MakeTubs("vFlat1_3", mCu, 6.0, 6.00 + thickness_flat, width_flat / 2., theta1, theta2); + TGeoVolume* vFlat1_4 = gGeoManager->MakeTubs("vFlat1_4", mCu, 6.0, 6.00 + thickness_flat, width_flat / 2., theta1, theta2); + auto* t_flat1_1 = new TGeoTranslation("translation_flat1_1", 3., signe * 13.4, -55.6); + t_flat1_1->RegisterYourself(); + auto* t_flat1_2 = new TGeoTranslation("translation_flat1_2", 1., signe * 13.4, -55.6); + t_flat1_2->RegisterYourself(); + auto* t_flat1_3 = new TGeoTranslation("translation_flat1_3", -1., signe * 13.4, -55.6); + t_flat1_3->RegisterYourself(); + auto* t_flat1_4 = new TGeoTranslation("translation_flat1_4", -3., signe * 13.4, -55.6); + t_flat1_4->RegisterYourself(); + auto* r_flat1 = new TGeoRotation("rotation_flat1", signe * 90.0, signe * 90.0, 0.0); + r_flat1->RegisterYourself(); + auto* p_flat1_1 = new TGeoCombiTrans(*t_flat1_1, *r_flat1); + p_flat1_1->RegisterYourself(); + auto* p_flat1_2 = new TGeoCombiTrans(*t_flat1_2, *r_flat1); + p_flat1_2->RegisterYourself(); + auto* p_flat1_3 = new TGeoCombiTrans(*t_flat1_3, *r_flat1); + p_flat1_3->RegisterYourself(); + auto* p_flat1_4 = new TGeoCombiTrans(*t_flat1_4, *r_flat1); + p_flat1_4->RegisterYourself(); + HalfConeVolume->AddNode(vFlat1_1, 1, p_flat1_1); + HalfConeVolume->AddNode(vFlat1_2, 1, p_flat1_2); + HalfConeVolume->AddNode(vFlat1_3, 1, p_flat1_3); + HalfConeVolume->AddNode(vFlat1_4, 1, p_flat1_4); + + // Flat lines between disk 2 and main board + width_flat = 14.0; + thickness_flat = 0.017; // 3 microns lines (268 lines, 0.0175x0.09 mm2), 14 microns ground plane (140 mm x 0.0175mm) including flex ~20% longer in o2! + TGeoVolume* vFlat2 = gGeoManager->MakeBox("vFlat2", mCu, width_flat / 2, thickness_flat / 2, 2.3 / 2); + auto* t_flat2 = new TGeoTranslation("translation_flat2", 0.0, -signe * 18.35, -55.45); + t_flat2->RegisterYourself(); + auto* r_flat2 = new TGeoRotation("rotation_flat2", 0.0, -signe * (18.), 0.0); + r_flat2->RegisterYourself(); + auto* p_flat2 = new TGeoCombiTrans(*t_flat2, *r_flat2); + p_flat2->RegisterYourself(); + HalfConeVolume->AddNode(vFlat2, 1, p_flat2); +} + +void HalfCone::makeReadoutCables(TGeoVolumeAssembly* HalfConeVolume, Int_t half, Int_t signe) +{ + auto* mCu = gGeoManager->GetMedium("MFT_Cu$"); + + // Connector + Float_t heigthConnector = 0.4; // male + female + auto* mPolyu = gGeoManager->GetMedium("MFT_Polyurethane$"); + TGeoVolume* vConnectorRC = gGeoManager->MakeBox("vConnectorRC", mPolyu, 6.00 / 2, heigthConnector / 2, 1.4 / 2); + vConnectorRC->SetLineColor(kGray + 3); + + // Fondamental numbers for the sections of Copper in the 2 types of readout cables + Double_t section_ROcable_48pairs = 0.26544; // in cm2 + Double_t section_ROcable_16pairs = 0.08848; // in cm2 + + // Starting from the MFT backside: from the patch panel to MB2 + Double_t mRO1[3]; + mRO1[0] = {14.0}; //width + mRO1[1] = (16 * section_ROcable_48pairs + 6 * section_ROcable_16pairs) / mRO1[0]; // thickness + mRO1[2] = {5.0}; // length + TGeoVolume* vRO1 = gGeoManager->MakeBox("vRO1", mCu, mRO1[0] / 2, mRO1[1] / 2, mRO1[2] / 2); + auto* t_RO1 = new TGeoTranslation("translation_RO1", 0.0, -signe * 28.0, -79.45); + t_RO1->RegisterYourself(); + + Double_t mRO2[3]; + mRO2[0] = mRO1[0]; + mRO2[1] = (14 * section_ROcable_48pairs + 5 * section_ROcable_16pairs) / mRO2[0]; + mRO2[2] = {3.0}; + TGeoVolume* vRO2 = gGeoManager->MakeBox("vRO2", mCu, mRO2[0] / 2, mRO2[1] / 2, mRO2[2] / 2); + auto* t_RO2 = new TGeoTranslation("translation_RO2", 0.0, -signe * 28.0, -79.45 + mRO1[2] / 2 + mRO2[2] / 2); + t_RO2->RegisterYourself(); + + Double_t mRO3[3]; + mRO3[0] = mRO1[0]; + mRO3[1] = (12 * section_ROcable_48pairs + 4 * section_ROcable_16pairs) / mRO3[0]; + mRO3[2] = {3.6}; + TGeoVolume* vRO3 = gGeoManager->MakeBox("vRO3", mCu, mRO3[0] / 2, mRO3[1] / 2, mRO3[2] / 2); + auto* t_RO3 = new TGeoTranslation("translation_RO3", 0.0, -signe * 28.0, -79.45 + mRO1[2] / 2 + mRO2[2] + mRO3[2] / 2); + t_RO3->RegisterYourself(); + + Double_t eRO4 = 12 * section_ROcable_48pairs / mRO1[0]; + TGeoVolume* vRO4 = gGeoManager->MakeTubs("vRO4", mCu, 6.5, 6.5 + eRO4, mRO1[0] / 2, -21.0 + signe * 26.11, 21.0 + signe * 26.11); + auto* t_RO4 = new TGeoTranslation("translation_RO4", 0.0, signe * 21.4, -70.9); + t_RO4->RegisterYourself(); + auto* r_RO4 = new TGeoRotation("rotation_RO4", signe * 90.0, signe * 90.0, 0.0); + r_RO4->RegisterYourself(); + auto* p_RO4 = new TGeoCombiTrans(*t_RO4, *r_RO4); + p_RO4->RegisterYourself(); + HalfConeVolume->AddNode(vRO4, 1, p_RO4); + + // RO5 = cable connected to the upper part of MB2 + Double_t mRO5[3]; + mRO5[0] = {4.5}; + mRO5[1] = section_ROcable_48pairs / mRO5[0]; + mRO5[2] = {7.071}; + TGeoVolume* vRO5 = gGeoManager->MakeBox("vRO5", mCu, mRO5[0] / 2, mRO5[1] / 2, mRO5[2] / 2); + auto* t_RO5_1 = new TGeoTranslation("translation_RO5_1", 3.5, -signe * (20.83 + mRO5[2] / 2 * TMath::Sin(45.0 * TMath::Pi() / 180)), -61 - mRO5[2] / 2 * TMath::Cos(45 * TMath::Pi() / 180)); + t_RO5_1->RegisterYourself(); + auto* t_RO5_2 = new TGeoTranslation("translation_RO5_1", -3.5, -signe * (20.83 + mRO5[2] / 2 * TMath::Sin(45.0 * TMath::Pi() / 180)), -61 - mRO5[2] / 2 * TMath::Cos(45 * TMath::Pi() / 180)); + t_RO5_2->RegisterYourself(); + auto* r_RO5 = new TGeoRotation("rotation_RO5", 0.0, -signe * (45.0), 0.0); + r_RO5->RegisterYourself(); + auto* p_RO5_1 = new TGeoCombiTrans(*t_RO5_1, *r_RO5); + p_RO5_1->RegisterYourself(); + auto* p_RO5_2 = new TGeoCombiTrans(*t_RO5_2, *r_RO5); + p_RO5_2->RegisterYourself(); + + // =========== TGeoTrap ---> trapezoid shapes =============== + Float_t length = 2.20 / 2; + Float_t angleZ = 69.; + Float_t angleXY = -signe * 50.; + Float_t width = 3.5; + Float_t thickness = (section_ROcable_48pairs / width) / TMath::Cos(angleXY * TMath::Pi() / 180); // special thickness!! + TGeoVolume* vRO6 = new TGeoVolume("vRO6", new TGeoTrap(length, angleZ, angleXY, width / 2, thickness / 2, thickness / 2, 0., width / 2, thickness / 2, thickness / 2, 0.), mCu); + Double_t yRO6 = -signe * (22.45 + length * 1.26 * TMath::Sin(angleZ * TMath::Pi() / 180)); + Double_t zRO6 = -64.1 - length * 2. * TMath::Cos(angleZ * TMath::Pi() / 180); + auto* t_RO6 = new TGeoTranslation("translation_RO6", 5.3, yRO6, zRO6); + t_RO6->RegisterYourself(); + auto* r_RO6 = new TGeoRotation("rotation_RO6", signe * 90.0, -signe * (0), 0.0); + r_RO6->RegisterYourself(); + auto* p_RO6 = new TGeoCombiTrans(*t_RO6, *r_RO6); + p_RO6->RegisterYourself(); + + TGeoVolume* vRO7 = new TGeoVolume("vRO7", new TGeoTrap(length, angleZ, -angleXY, width / 2, thickness / 2, thickness / 2, 0., width / 2, thickness / 2, thickness / 2, 0.), mCu); + auto* t_RO7 = new TGeoTranslation("translation_RO6", -5.3, yRO6, zRO6); + t_RO7->RegisterYourself(); + auto* r_RO7 = new TGeoRotation("rotation_RO7", signe * 90.0, -signe * (0), 0.0); + r_RO7->RegisterYourself(); + auto* p_RO7 = new TGeoCombiTrans(*t_RO7, *r_RO7); + p_RO7->RegisterYourself(); + + // ============= under the main mother board ============= + Double_t mRO8[3]; + mRO8[0] = mRO5[0]; // width + mRO8[1] = 2 * section_ROcable_48pairs / mRO8[0]; // thickness, 2 cables coded in one cable + mRO8[2] = {6.40}; // length + TGeoVolume* vRO8 = gGeoManager->MakeBox("vRO8", mCu, mRO8[0] / 2, mRO8[1] / 2, mRO8[2] / 2); + Double_t yRO8 = -signe * (19.1 + mRO8[2] / 2 * TMath::Sin(19.0 * TMath::Pi() / 180)); + Double_t zRO8 = -59.95 - mRO8[2] / 2 * TMath::Cos(19.0 * TMath::Pi() / 180); + auto* t_RO8_1 = new TGeoTranslation("translation_RO8_1", 3.5, yRO8, zRO8); + t_RO8_1->RegisterYourself(); + auto* t_RO8_2 = new TGeoTranslation("translation_RO8_1", -3.5, yRO8, zRO8); + t_RO8_2->RegisterYourself(); + auto* r_RO8 = new TGeoRotation("rotation_RO8", 0.0, -signe * (19.0), 0.0); + r_RO8->RegisterYourself(); + auto* p_RO8_1 = new TGeoCombiTrans(*t_RO8_1, *r_RO8); + p_RO8_1->RegisterYourself(); + auto* p_RO8_2 = new TGeoCombiTrans(*t_RO8_2, *r_RO8); + p_RO8_2->RegisterYourself(); + + Double_t mRO9[3]; + mRO9[0] = mRO5[0]; // width + mRO9[1] = 2 * section_ROcable_48pairs / mRO9[0]; // thickness, 2 cables coded in one cable + mRO9[2] = {4.5}; // length + TGeoVolume* vRO9 = gGeoManager->MakeBox("vRO9", mCu, mRO9[0] / 2, mRO9[1] / 2, mRO9[2] / 2); + auto* t_RO9_1 = new TGeoTranslation("translation_RO9_1", 3.5, -signe * (23.5), -66.15); + t_RO9_1->RegisterYourself(); + auto* t_RO9_2 = new TGeoTranslation("translation_RO9_2", -3.5, -signe * (23.5), -66.15); + t_RO9_2->RegisterYourself(); + auto* r_RO9 = new TGeoRotation("rotation_RO9", 0.0, -signe * (90.0), 0.0); + r_RO9->RegisterYourself(); + auto* p_RO9_1 = new TGeoCombiTrans(*t_RO9_1, *r_RO9); + p_RO9_1->RegisterYourself(); + auto* p_RO9_2 = new TGeoCombiTrans(*t_RO9_2, *r_RO9); + p_RO9_2->RegisterYourself(); + + // =========== For the 2 latest disks ================ + // ============= Disk 3 ============ + length = 6.9 / 2; + angleZ = -45.; + angleXY = 0.; + thickness = 3.5; // inversion width/thickness! this is the width + width = section_ROcable_48pairs / thickness; // inversion width/thickness! this is the thickness + // ==== front + TGeoVolume* vRO_D3_1 = new TGeoVolume("vRO_D3_1", new TGeoTrap(length, angleZ + 10., angleXY, width / 2, thickness / 2, thickness / 2, 0., width / 2, thickness / 2, thickness / 2, 0.), mCu); + auto* t_ROD3_1 = new TGeoTranslation("translation_ROD3_1", 4.5, -signe * (20.9 + length * TMath::Cos(angleZ * TMath::Pi() / 180)), -67.4); + t_ROD3_1->RegisterYourself(); + auto* r_ROD3_1 = new TGeoRotation("rotation_ROD3_1", signe * 180.0, signe * (90), 0.0); + r_ROD3_1->RegisterYourself(); + auto* p_ROD3_1 = new TGeoCombiTrans(*t_ROD3_1, *r_ROD3_1); + p_ROD3_1->RegisterYourself(); + + TGeoVolume* vRO_D3_2 = new TGeoVolume("vRO_D3_2", new TGeoTrap(length, -angleZ - 10., angleXY, width / 2, thickness / 2, thickness / 2, 0., width / 2, thickness / 2, thickness / 2, 0.), mCu); + auto* t_ROD3_2 = new TGeoTranslation("translation_ROD3_2", -4.5, -signe * (20.9 + length * TMath::Cos(angleZ * TMath::Pi() / 180)), -67.4); + t_ROD3_2->RegisterYourself(); + auto* r_ROD3_2 = new TGeoRotation("rotation_ROD3_2", signe * 180.0, signe * (90), 0.0); + r_ROD3_2->RegisterYourself(); + auto* p_ROD3_2 = new TGeoCombiTrans(*t_ROD3_2, *r_ROD3_2); + p_ROD3_2->RegisterYourself(); + + // ===== rear + TGeoVolume* vRO_D3_3 = new TGeoVolume("vRO_D3_3", new TGeoTrap(length + 0.4, angleZ + 10., angleXY, width / 2, thickness / 2, thickness / 2, 0., width / 2, thickness / 2, thickness / 2, 0.), mCu); + auto* t_ROD3_3 = new TGeoTranslation("translation_ROD3_3", 4.5, -signe * (21.3 + length * TMath::Cos(angleZ * TMath::Pi() / 180)), -69.4); + t_ROD3_3->RegisterYourself(); + auto* r_ROD3_3 = new TGeoRotation("rotation_ROD3_3", signe * 180.0, signe * (90), 0.0); + r_ROD3_3->RegisterYourself(); + auto* p_ROD3_3 = new TGeoCombiTrans(*t_ROD3_3, *r_ROD3_3); + p_ROD3_3->RegisterYourself(); + + TGeoVolume* vRO_D3_4 = new TGeoVolume("vRO_D3_4", new TGeoTrap(length + 0.4, -angleZ - 10., angleXY, width / 2, thickness / 2, thickness / 2, 0., width / 2, thickness / 2, thickness / 2, 0.), mCu); + auto* t_ROD3_4 = new TGeoTranslation("translation_ROD3_4", -4.5, -signe * (21.3 + length * TMath::Cos(angleZ * TMath::Pi() / 180)), -69.4); + t_ROD3_4->RegisterYourself(); + auto* r_ROD3_4 = new TGeoRotation("rotation_ROD3_4", signe * 180.0, signe * (90), 0.0); + r_ROD3_4->RegisterYourself(); + auto* p_ROD3_4 = new TGeoCombiTrans(*t_ROD3_4, *r_ROD3_4); + p_ROD3_4->RegisterYourself(); + + auto* t_ConnectorRC3_1 = new TGeoTranslation("translation_RC3_1", 5.9, -signe * (20.2), -67.87 + heigthConnector / 2); + t_ConnectorRC3_1->RegisterYourself(); + auto* r_ConnectorRC3_1 = new TGeoRotation("rotation_RC3_1", 0.0, 90, 0.0); + r_ConnectorRC3_1->RegisterYourself(); + auto* p_ConnectorRC3_1 = new TGeoCombiTrans(*t_ConnectorRC3_1, *r_ConnectorRC3_1); + p_ConnectorRC3_1->RegisterYourself(); + auto* t_ConnectorRC3_2 = new TGeoTranslation("translation_RC3_2", -5.9, -signe * (20.2), -67.87 + heigthConnector / 2); + t_ConnectorRC3_2->RegisterYourself(); + auto* p_ConnectorRC3_2 = new TGeoCombiTrans(*t_ConnectorRC3_2, *r_ConnectorRC3_1); + p_ConnectorRC3_2->RegisterYourself(); + auto* t_ConnectorRC3_3 = new TGeoTranslation("translation_RC3_3", 5.9, -signe * (20.2), -68.93 - heigthConnector / 2); + t_ConnectorRC3_3->RegisterYourself(); + auto* p_ConnectorRC3_3 = new TGeoCombiTrans(*t_ConnectorRC3_3, *r_ConnectorRC3_1); + p_ConnectorRC3_3->RegisterYourself(); + auto* t_ConnectorRC3_4 = new TGeoTranslation("translation_RC3_4", -5.9, -signe * (20.2), -68.93 - heigthConnector / 2); + t_ConnectorRC3_4->RegisterYourself(); + auto* p_ConnectorRC3_4 = new TGeoCombiTrans(*t_ConnectorRC3_4, *r_ConnectorRC3_1); + p_ConnectorRC3_4->RegisterYourself(); + + // ============== Disk 4 ================ + length = 6.3 / 2; + angleZ = -20.; + angleXY = 0.; + thickness = 3.5; // inversion width and thickness! this is the width + width = section_ROcable_48pairs / thickness; // inversion width and thickness! this is the thickness + Float_t xD4 = 6.1; + Float_t yD4 = 21.6; + // ===== front + TGeoVolume* vRO_D4_1 = new TGeoVolume("vRO_D4_1", new TGeoTrap(length, angleZ, angleXY, width / 2, thickness / 2, thickness / 2, 0., width / 2, thickness / 2, thickness / 2, 0.), mCu); + auto* t_ROD4_1 = new TGeoTranslation("translation_ROD4_1", xD4, -signe * (yD4 + length * TMath::Cos(angleZ * TMath::Pi() / 180)), -75.8); + t_ROD4_1->RegisterYourself(); + auto* r_ROD4_1 = new TGeoRotation("rotation_ROD4_1", signe * 180.0, signe * (90), 0.0); + r_ROD4_1->RegisterYourself(); + auto* p_ROD4_1 = new TGeoCombiTrans(*t_ROD4_1, *r_ROD3_1); + p_ROD4_1->RegisterYourself(); + + TGeoVolume* vRO_D4_2 = new TGeoVolume("vRO_D4_2", new TGeoTrap(length, -angleZ, angleXY, width / 2, thickness / 2, thickness / 2, 0., width / 2, thickness / 2, thickness / 2, 0.), mCu); + auto* t_ROD4_2 = new TGeoTranslation("translation_ROD4_2", -xD4, -signe * (yD4 + length * TMath::Cos(angleZ * TMath::Pi() / 180)), -75.8); + t_ROD4_2->RegisterYourself(); + auto* r_ROD4_2 = new TGeoRotation("rotation_ROD4_2", signe * 180.0, signe * (90), 0.0); + r_ROD4_2->RegisterYourself(); + auto* p_ROD4_2 = new TGeoCombiTrans(*t_ROD4_2, *r_ROD4_2); + p_ROD4_2->RegisterYourself(); + + // ===== rear + TGeoVolume* vRO_D4_3 = new TGeoVolume("vRO_D4_3", new TGeoTrap(length, angleZ, angleXY, width / 2, thickness / 2, thickness / 2, 0., width / 2, thickness / 2, thickness / 2, 0.), mCu); + auto* t_ROD4_3 = new TGeoTranslation("translation_ROD4_3", xD4, -signe * (yD4 + length * TMath::Cos(angleZ * TMath::Pi() / 180)), -77.8); + t_ROD4_3->RegisterYourself(); + auto* r_ROD4_3 = new TGeoRotation("rotation_ROD4_3", signe * 180.0, signe * (90), 0.0); + r_ROD4_3->RegisterYourself(); + auto* p_ROD4_3 = new TGeoCombiTrans(*t_ROD4_3, *r_ROD3_3); + p_ROD4_3->RegisterYourself(); + + TGeoVolume* vRO_D4_4 = new TGeoVolume("vRO_D4_4", new TGeoTrap(length, -angleZ, angleXY, width / 2, thickness / 2, thickness / 2, 0., width / 2, thickness / 2, thickness / 2, 0.), mCu); + auto* t_ROD4_4 = new TGeoTranslation("translation_ROD4_4", -xD4, -signe * (yD4 + length * TMath::Cos(angleZ * TMath::Pi() / 180)), -77.8); + t_ROD4_4->RegisterYourself(); + auto* r_ROD4_4 = new TGeoRotation("rotation_ROD4_4", signe * 180.0, signe * (90), 0.0); + r_ROD4_4->RegisterYourself(); + auto* p_ROD4_4 = new TGeoCombiTrans(*t_ROD4_4, *r_ROD4_4); + p_ROD4_4->RegisterYourself(); + + // Middle + // 16 pairs cable + width = section_ROcable_16pairs / thickness; // inversion width and thickness! this is thickness... + TGeoVolume* vRO_D4_5 = new TGeoVolume("vRO_D4_5", new TGeoTrap(length, 0., 0., width / 2, thickness / 2, thickness / 2, 0., width / 2, thickness / 2, thickness / 2, 0.), mCu); + auto* t_ROD4_5 = new TGeoTranslation("translation_ROD4_5", 0, -signe * (yD4 + length - 0.2), -75.8); + t_ROD4_5->RegisterYourself(); + auto* r_ROD4_5 = new TGeoRotation("rotation_ROD4_5", signe * 180.0, signe * (90), 0.0); + r_ROD4_5->RegisterYourself(); + auto* p_ROD4_5 = new TGeoCombiTrans(*t_ROD4_5, *r_ROD4_5); + p_ROD4_5->RegisterYourself(); + TGeoVolume* vRO_D4_6 = new TGeoVolume("vRO_D4_6", new TGeoTrap(length, 0., 0., width / 2, thickness / 2, thickness / 2, 0., width / 2, thickness / 2, thickness / 2, 0.), mCu); + auto* t_ROD4_6 = new TGeoTranslation("translation_ROD4_6", 0, -signe * (yD4 + length - 0.2), -77.8); + t_ROD4_6->RegisterYourself(); + auto* r_ROD4_6 = new TGeoRotation("rotation_ROD4_6", signe * 180.0, signe * (90), 0.0); + r_ROD4_6->RegisterYourself(); + auto* p_ROD4_6 = new TGeoCombiTrans(*t_ROD4_6, *r_ROD4_6); + p_ROD4_6->RegisterYourself(); + + auto* t_ConnectorRC4_1 = new TGeoTranslation("translation_RC4_1", 7.5, -signe * (21.5), -76.26 + heigthConnector / 2); + t_ConnectorRC4_1->RegisterYourself(); + auto* p_ConnectorRC4_1 = new TGeoCombiTrans(*t_ConnectorRC4_1, *r_ConnectorRC3_1); + p_ConnectorRC4_1->RegisterYourself(); + auto* t_ConnectorRC4_2 = new TGeoTranslation("translation_RC4_2", -7.5, -signe * (21.5), -76.26 + heigthConnector / 2); + t_ConnectorRC4_2->RegisterYourself(); + auto* p_ConnectorRC4_2 = new TGeoCombiTrans(*t_ConnectorRC4_2, *r_ConnectorRC3_1); + p_ConnectorRC4_2->RegisterYourself(); + auto* t_ConnectorRC4_3 = new TGeoTranslation("translation_RC4_3", 7.5, -signe * (21.5), -77.34 - heigthConnector / 2); + t_ConnectorRC4_3->RegisterYourself(); + auto* p_ConnectorRC4_3 = new TGeoCombiTrans(*t_ConnectorRC4_3, *r_ConnectorRC3_1); + p_ConnectorRC4_3->RegisterYourself(); + auto* t_ConnectorRC4_4 = new TGeoTranslation("translation_RC4_4", -7.5, -signe * (21.5), -77.34 - heigthConnector / 2); + t_ConnectorRC4_4->RegisterYourself(); + auto* p_ConnectorRC4_4 = new TGeoCombiTrans(*t_ConnectorRC4_4, *r_ConnectorRC3_1); + p_ConnectorRC4_4->RegisterYourself(); + auto* t_ConnectorRC4_5 = new TGeoTranslation("translation_RC4_5", 0, -signe * (21.5), -76.26 + heigthConnector / 2); + t_ConnectorRC4_5->RegisterYourself(); + auto* p_ConnectorRC4_5 = new TGeoCombiTrans(*t_ConnectorRC4_5, *r_ConnectorRC3_1); + p_ConnectorRC4_5->RegisterYourself(); + auto* t_ConnectorRC4_6 = new TGeoTranslation("translation_RC4_6", 0, -signe * (21.5), -77.34 - heigthConnector / 2); + t_ConnectorRC4_6->RegisterYourself(); + auto* p_ConnectorRC4_6 = new TGeoCombiTrans(*t_ConnectorRC4_6, *r_ConnectorRC3_1); + p_ConnectorRC4_6->RegisterYourself(); + + // ========== For the RO Supply Unit (PSU) ========== + length = 1.6 / 2; + angleZ = 70.; + angleXY = -signe * 25.; + width = 3.5; + thickness = section_ROcable_16pairs / width / TMath::Cos(angleZ * TMath::Pi() / 180); + TGeoVolume* vRO_PSU_1 = new TGeoVolume("vRO_PSU_1", new TGeoTrap(length, angleZ, angleXY, width / 2, thickness / 2, thickness / 2, 0., width / 2, thickness / 2, thickness / 2, 0.), mCu); + Double_t yPSU = -signe * (24.8 + length * 1.26 * TMath::Sin(angleZ * TMath::Pi() / 180)); + Double_t zPSU = -71.1 - length * 2. * TMath::Cos(angleZ * TMath::Pi() / 180); + auto* t_RO_PSU_1 = new TGeoTranslation("translation_RO_PSU_1", 5.0, yPSU, zPSU); + t_RO_PSU_1->RegisterYourself(); + auto* r_RO_PSU_1 = new TGeoRotation("rotation_RO_PSU_1", signe * 90.0, -signe * (0), 0.0); + r_RO_PSU_1->RegisterYourself(); + auto* p_RO_PSU_1 = new TGeoCombiTrans(*t_RO_PSU_1, *r_RO_PSU_1); + p_RO_PSU_1->RegisterYourself(); + + TGeoVolume* vRO_PSU_2 = new TGeoVolume("vRO_PSU_2", new TGeoTrap(length, angleZ, -angleXY, width / 2, thickness / 2, thickness / 2, 0., width / 2, thickness / 2, thickness / 2, 0.), mCu); + auto* t_RO_PSU_2 = new TGeoTranslation("translation_RO_PSU_2", -5.0, yPSU, zPSU); + t_RO_PSU_2->RegisterYourself(); + auto* r_RO_PSU_2 = new TGeoRotation("rotation_RO_PSU_2", signe * 90.0, -signe * (0), 0.0); + r_RO_PSU_2->RegisterYourself(); + auto* p_RO_PSU_2 = new TGeoCombiTrans(*t_RO_PSU_2, *r_RO_PSU_2); + p_RO_PSU_2->RegisterYourself(); + + zPSU = -72.98 - length * 2. * TMath::Cos(angleZ * TMath::Pi() / 180); + TGeoVolume* vRO_PSU_3 = new TGeoVolume("vRO_PSU_3", new TGeoTrap(length, -angleZ, angleXY, width / 2, thickness / 2, thickness / 2, 0., width / 2, thickness / 2, thickness / 2, 0.), mCu); + auto* t_RO_PSU_3 = new TGeoTranslation("translation_RO_PSU_3", 5.0, yPSU, zPSU); + t_RO_PSU_3->RegisterYourself(); + auto* r_RO_PSU_3 = new TGeoRotation("rotation_RO_PSU_3", signe * 90.0, -signe * (0), 0.0); + r_RO_PSU_3->RegisterYourself(); + auto* p_RO_PSU_3 = new TGeoCombiTrans(*t_RO_PSU_3, *r_RO_PSU_3); + p_RO_PSU_3->RegisterYourself(); + + TGeoVolume* vRO_PSU_4 = new TGeoVolume("vRO_PSU_4", new TGeoTrap(length, -angleZ, -angleXY, width / 2, thickness / 2, thickness / 2, 0., width / 2, thickness / 2, thickness / 2, 0.), mCu); + auto* t_RO_PSU_4 = new TGeoTranslation("translation_RO_PSU_4", -5.0, yPSU, zPSU); + t_RO_PSU_4->RegisterYourself(); + auto* r_RO_PSU_4 = new TGeoRotation("rotation_RO_PSU_4", signe * 90.0, -signe * (0), 0.0); + r_RO_PSU_4->RegisterYourself(); + auto* p_RO_PSU_4 = new TGeoCombiTrans(*t_RO_PSU_4, *r_RO_PSU_4); + p_RO_PSU_4->RegisterYourself(); + + auto* t_ConnectorPSU_1 = new TGeoTranslation("translation_PSU_1", 6.9, -signe * (23.5), -70.44 - heigthConnector / 2); + t_ConnectorPSU_1->RegisterYourself(); + auto* p_ConnectorPSU_1 = new TGeoCombiTrans(*t_ConnectorPSU_1, *r_ConnectorRC3_1); + p_ConnectorPSU_1->RegisterYourself(); + auto* t_ConnectorPSU_2 = new TGeoTranslation("translation_PSU_2", -6.9, -signe * (23.5), -70.44 - heigthConnector / 2); + t_ConnectorPSU_2->RegisterYourself(); + auto* p_ConnectorPSU_2 = new TGeoCombiTrans(*t_ConnectorPSU_2, *r_ConnectorRC3_1); + p_ConnectorPSU_2->RegisterYourself(); + auto* t_ConnectorPSU_3 = new TGeoTranslation("translation_PSU_3", 6.9, -signe * (23.5), -74.77 + heigthConnector / 2); + t_ConnectorPSU_3->RegisterYourself(); + auto* p_ConnectorPSU_3 = new TGeoCombiTrans(*t_ConnectorPSU_3, *r_ConnectorRC3_1); + p_ConnectorPSU_3->RegisterYourself(); + auto* t_ConnectorPSU_4 = new TGeoTranslation("translation_PSU_4", -6.9, -signe * (23.5), -74.77 + heigthConnector / 2); + t_ConnectorPSU_4->RegisterYourself(); + auto* p_ConnectorPSU_4 = new TGeoCombiTrans(*t_ConnectorPSU_4, *r_ConnectorRC3_1); + p_ConnectorPSU_4->RegisterYourself(); + + vRO1->SetLineColor(kGray + 3); + vRO2->SetLineColor(kBlue); + vRO3->SetLineColor(kGray + 2); + vRO4->SetLineColor(kGray + 1); + vRO5->SetLineColor(kGray); + vRO6->SetLineColor(kGray); + vRO7->SetLineColor(kGray); + vRO8->SetLineColor(kGray); + vRO9->SetLineColor(kGray); + vRO_D3_1->SetLineColor(kGray); + vRO_D3_2->SetLineColor(kGray); + vRO_D3_3->SetLineColor(kGray); + vRO_D3_4->SetLineColor(kGray); + vRO_D4_1->SetLineColor(kGray); + vRO_D4_2->SetLineColor(kGray); + vRO_D4_3->SetLineColor(kGray); + vRO_D4_4->SetLineColor(kGray); + vRO_D4_5->SetLineColor(kGray); + vRO_D4_6->SetLineColor(kGray); + vRO_PSU_1->SetLineColor(kGray); + vRO_PSU_2->SetLineColor(kGray); + vRO_PSU_3->SetLineColor(kGray); + vRO_PSU_4->SetLineColor(kGray); + + HalfConeVolume->AddNode(vRO1, 1, t_RO1); + HalfConeVolume->AddNode(vRO2, 1, t_RO2); + HalfConeVolume->AddNode(vRO3, 1, t_RO3); + HalfConeVolume->AddNode(vRO4, 1, p_RO4); + HalfConeVolume->AddNode(vRO5, 1, p_RO5_1); + HalfConeVolume->AddNode(vRO5, 1, p_RO5_2); + HalfConeVolume->AddNode(vRO6, 1, p_RO6); + HalfConeVolume->AddNode(vRO7, 1, p_RO7); + HalfConeVolume->AddNode(vRO8, 1, p_RO8_1); + HalfConeVolume->AddNode(vRO8, 1, p_RO8_2); + HalfConeVolume->AddNode(vRO9, 1, p_RO9_1); + HalfConeVolume->AddNode(vRO9, 1, p_RO9_2); + HalfConeVolume->AddNode(vRO_D3_1, 1, p_ROD3_1); + HalfConeVolume->AddNode(vRO_D3_2, 1, p_ROD3_2); + HalfConeVolume->AddNode(vRO_D3_3, 1, p_ROD3_3); + HalfConeVolume->AddNode(vRO_D3_4, 1, p_ROD3_4); + HalfConeVolume->AddNode(vConnectorRC, 1, p_ConnectorRC3_1); + HalfConeVolume->AddNode(vConnectorRC, 1, p_ConnectorRC3_2); + HalfConeVolume->AddNode(vConnectorRC, 1, p_ConnectorRC3_3); + HalfConeVolume->AddNode(vConnectorRC, 1, p_ConnectorRC3_4); + + HalfConeVolume->AddNode(vRO_D4_1, 1, p_ROD4_1); + HalfConeVolume->AddNode(vRO_D4_2, 1, p_ROD4_2); + HalfConeVolume->AddNode(vRO_D4_3, 1, p_ROD4_3); + HalfConeVolume->AddNode(vRO_D4_4, 1, p_ROD4_4); + HalfConeVolume->AddNode(vRO_D4_5, 1, p_ROD4_5); + HalfConeVolume->AddNode(vRO_D4_6, 1, p_ROD4_6); + HalfConeVolume->AddNode(vConnectorRC, 1, p_ConnectorRC4_1); + HalfConeVolume->AddNode(vConnectorRC, 1, p_ConnectorRC4_2); + HalfConeVolume->AddNode(vConnectorRC, 1, p_ConnectorRC4_3); + HalfConeVolume->AddNode(vConnectorRC, 1, p_ConnectorRC4_4); + HalfConeVolume->AddNode(vConnectorRC, 1, p_ConnectorRC4_5); + HalfConeVolume->AddNode(vConnectorRC, 1, p_ConnectorRC4_6); + + HalfConeVolume->AddNode(vRO_PSU_1, 1, p_RO_PSU_1); + HalfConeVolume->AddNode(vRO_PSU_2, 1, p_RO_PSU_2); + HalfConeVolume->AddNode(vRO_PSU_3, 1, p_RO_PSU_3); + HalfConeVolume->AddNode(vRO_PSU_4, 1, p_RO_PSU_4); + HalfConeVolume->AddNode(vConnectorRC, 1, p_ConnectorPSU_1); + HalfConeVolume->AddNode(vConnectorRC, 1, p_ConnectorPSU_2); + HalfConeVolume->AddNode(vConnectorRC, 1, p_ConnectorPSU_3); + HalfConeVolume->AddNode(vConnectorRC, 1, p_ConnectorPSU_4); } From 72291f9a3f0787963039f4af30061d31347f7d66 Mon Sep 17 00:00:00 2001 From: Diego Stocco Date: Tue, 20 Apr 2021 10:00:32 +0200 Subject: [PATCH 175/770] [MRRTF-33] Update the MID CRU User Logic data format (#5946) --- Detectors/MUON/MID/Raw/CMakeLists.txt | 8 +- Detectors/MUON/MID/Raw/exe/rawdump.cxx | 28 +-- .../MUON/MID/Raw/include/MIDRaw/Decoder.h | 26 +- .../MID/Raw/include/MIDRaw/ELinkDataShaper.h | 70 ++++++ .../MID/Raw/include/MIDRaw/ELinkDecoder.h | 17 +- .../MID/Raw/include/MIDRaw/ELinkManager.h | 82 +++++++ .../MUON/MID/Raw/include/MIDRaw/Encoder.h | 12 +- .../MUON/MID/Raw/include/MIDRaw/FEEIdConfig.h | 30 +-- .../MID/Raw/include/MIDRaw/GBTOutputHandler.h | 2 +- .../Raw/include/MIDRaw/GBTUserLogicEncoder.h | 6 +- .../MIDRaw/{GBTDecoder.h => LinkDecoder.h} | 23 +- Detectors/MUON/MID/Raw/include/MIDRaw/Utils.h | 36 +++ Detectors/MUON/MID/Raw/src/Decoder.cxx | 32 +-- .../MUON/MID/Raw/src/ELinkDataShaper.cxx | 210 +++++++++++++++++ Detectors/MUON/MID/Raw/src/ELinkDecoder.cxx | 14 +- Detectors/MUON/MID/Raw/src/ELinkManager.cxx | 77 ++++++ Detectors/MUON/MID/Raw/src/Encoder.cxx | 84 ++++--- Detectors/MUON/MID/Raw/src/FEEIdConfig.cxx | 62 +++-- .../MUON/MID/Raw/src/GBTUserLogicEncoder.cxx | 14 +- .../src/{GBTDecoder.cxx => LinkDecoder.cxx} | 223 ++++++++++++++++-- Detectors/MUON/MID/Raw/test/bench_Raw.cxx | 8 +- Detectors/MUON/MID/Raw/test/testRaw.cxx | 15 +- .../MID/Workflow/src/RawGBTDecoderSpec.cxx | 6 +- 23 files changed, 898 insertions(+), 187 deletions(-) create mode 100644 Detectors/MUON/MID/Raw/include/MIDRaw/ELinkDataShaper.h create mode 100644 Detectors/MUON/MID/Raw/include/MIDRaw/ELinkManager.h rename Detectors/MUON/MID/Raw/include/MIDRaw/{GBTDecoder.h => LinkDecoder.h} (58%) create mode 100644 Detectors/MUON/MID/Raw/include/MIDRaw/Utils.h create mode 100644 Detectors/MUON/MID/Raw/src/ELinkDataShaper.cxx create mode 100644 Detectors/MUON/MID/Raw/src/ELinkManager.cxx rename Detectors/MUON/MID/Raw/src/{GBTDecoder.cxx => LinkDecoder.cxx} (59%) diff --git a/Detectors/MUON/MID/Raw/CMakeLists.txt b/Detectors/MUON/MID/Raw/CMakeLists.txt index ed199cef2e14b..946f6ed8b13aa 100644 --- a/Detectors/MUON/MID/Raw/CMakeLists.txt +++ b/Detectors/MUON/MID/Raw/CMakeLists.txt @@ -16,12 +16,14 @@ o2_add_library( src/DecodedDataAggregator.cxx src/Decoder.cxx src/ElectronicsDelay.cxx + src/ELinkDataShaper.cxx src/ELinkDecoder.cxx + src/ELinkManager.cxx src/Encoder.cxx src/FEEIdConfig.cxx - src/GBTDecoder.cxx src/GBTOutputHandler.cxx src/GBTUserLogicEncoder.cxx + src/LinkDecoder.cxx src/RawFileReader.cxx PUBLIC_LINK_LIBRARIES ms_gsl::ms_gsl @@ -30,7 +32,9 @@ o2_add_library( O2::DPLUtils O2::CommonConstants O2::DetectorsRaw - O2::MIDBase) + O2::MIDBase + TARGETVARNAME midrawtarget) +# target_compile_definitions(${midrawtarget} PRIVATE "MID_RAW_VECTORS") add_subdirectory(exe) diff --git a/Detectors/MUON/MID/Raw/exe/rawdump.cxx b/Detectors/MUON/MID/Raw/exe/rawdump.cxx index e61651bd32cb4..d42f3ee6c1add 100644 --- a/Detectors/MUON/MID/Raw/exe/rawdump.cxx +++ b/Detectors/MUON/MID/Raw/exe/rawdump.cxx @@ -19,32 +19,10 @@ #include "DPLUtils/RawParser.h" #include "MIDRaw/Decoder.h" #include "MIDRaw/RawFileReader.h" +#include "MIDRaw/Utils.h" namespace po = boost::program_options; -std::string getOutFilename(const char* inFilename, const char* outDir) -{ - std::string basename(inFilename); - std::string fdir = "./"; - auto pos = basename.find_last_of("/"); - if (pos != std::string::npos) { - basename.erase(0, pos + 1); - fdir = inFilename; - fdir.erase(pos); - } - basename.insert(0, "dump_"); - basename += ".txt"; - std::string outputDir(outDir); - if (outputDir.empty()) { - outputDir = fdir; - } - if (outputDir.back() != '/') { - outputDir += "/"; - } - std::string outFilename = outputDir + basename; - return outFilename; -} - template void decode(o2::mid::Decoder& decoder, gsl::span payload, const RDH& rdh, std::ostream& out) { @@ -103,7 +81,7 @@ int main(int argc, char* argv[]) std::vector inputfiles{vm["input"].as>()}; - bool runDecoder = (vm.count("decode") > 0); + bool runDecoder = (vm.count("decode") > 0 && vm["decode"].as() == true); std::unique_ptr decoder{nullptr}; std::ofstream outFile; @@ -135,7 +113,7 @@ int main(int argc, char* argv[]) } decode(*decoder, payload, *rdhPtr, out); } else if (!isRdhOnly) { - bool isBare = (o2::raw::RDHUtils::getLinkID(rdhPtr) != o2::mid::raw::sUserLogicLinkID); + bool isBare = o2::mid::raw::isBare(*rdhPtr); size_t wordLength = isBare ? 16 : 32; for (size_t iword = 0; iword < payload.size(); iword += wordLength) { auto word = payload.subspan(iword, wordLength); diff --git a/Detectors/MUON/MID/Raw/include/MIDRaw/Decoder.h b/Detectors/MUON/MID/Raw/include/MIDRaw/Decoder.h index b1a8658b4d61d..82e7224e81c14 100644 --- a/Detectors/MUON/MID/Raw/include/MIDRaw/Decoder.h +++ b/Detectors/MUON/MID/Raw/include/MIDRaw/Decoder.h @@ -16,8 +16,10 @@ #define O2_MID_DECODER_H #include +#if !defined(MID_RAW_VECTORS) +#include +#endif #include -#include #include #include "DataFormatsMID/ROFRecord.h" #include "DetectorsRaw/RDHUtils.h" @@ -25,7 +27,8 @@ #include "MIDRaw/CrateParameters.h" #include "MIDRaw/ElectronicsDelay.h" #include "MIDRaw/FEEIdConfig.h" -#include "MIDRaw/GBTDecoder.h" +#include "MIDRaw/LinkDecoder.h" +#include "MIDRaw/Utils.h" #include "DataFormatsMID/ROBoard.h" namespace o2 @@ -43,8 +46,12 @@ class Decoder void process(gsl::span payload, const RDH& rdh) { /// Processes the page - auto feeId = mGetFEEID(rdh); - mGBTDecoders[feeId]->process(payload, o2::raw::RDHUtils::getHeartBeatOrbit(rdh), mData, mROFRecords); + auto feeId = o2::raw::RDHUtils::getFEEID(rdh); +#if defined(MID_RAW_VECTORS) + mLinkDecoders[feeId]->process(payload, o2::raw::RDHUtils::getHeartBeatOrbit(rdh), mData, mROFRecords); +#else + mLinkDecoders.find(feeId)->second->process(payload, o2::raw::RDHUtils::getHeartBeatOrbit(rdh), mData, mROFRecords); +#endif } /// Gets the vector of data const std::vector& getData() const { return mData; } @@ -55,17 +62,18 @@ class Decoder void clear(); protected: - /// Gets the feeID - std::function mGetFEEID{[](const o2::header::RDHAny& rdh) { return o2::raw::RDHUtils::getFEEID(rdh); }}; - - std::array, crateparams::sNGBTs> mGBTDecoders{nullptr}; /// GBT decoders +#if defined(MID_RAW_VECTORS) + std::vector> mLinkDecoders{}; /// GBT decoders +#else + std::unordered_map> mLinkDecoders{}; /// GBT decoders +#endif private: std::vector mData{}; /// Vector of output data std::vector mROFRecords{}; /// List of ROF records }; -std::unique_ptr createDecoder(const o2::header::RDHAny& rdh, bool isDebugMode, ElectronicsDelay& electronicsDelay, const CrateMasks& crateMasks, const FEEIdConfig& feeIdConfig); +std::unique_ptr createDecoder(const o2::header::RDHAny& rdh, bool isDebugMode, const ElectronicsDelay& electronicsDelay, const CrateMasks& crateMasks, const FEEIdConfig& feeIdConfig); std::unique_ptr createDecoder(const o2::header::RDHAny& rdh, bool isDebugMode, const char* electronicsDelayFile = "", const char* crateMasksFile = "", const char* feeIdConfigFile = ""); } // namespace mid diff --git a/Detectors/MUON/MID/Raw/include/MIDRaw/ELinkDataShaper.h b/Detectors/MUON/MID/Raw/include/MIDRaw/ELinkDataShaper.h new file mode 100644 index 0000000000000..1a2099067ce49 --- /dev/null +++ b/Detectors/MUON/MID/Raw/include/MIDRaw/ELinkDataShaper.h @@ -0,0 +1,70 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file MIDRaw/ELinkDataShaper.h +/// \brief Properly formats and sets the absolute timestamp of the raw data +/// \author Diego Stocco +/// \date 18 March 2021 +#ifndef O2_MID_ELINKDATASHAPER_H +#define O2_MID_ELINKDATASHAPER_H + +#include +#include +#include "CommonDataFormat/InteractionRecord.h" +#include "DataFormatsMID/ROBoard.h" +#include "DataFormatsMID/ROFRecord.h" +#include "MIDRaw/ElectronicsDelay.h" +#include "MIDRaw/ELinkDecoder.h" + +namespace o2 +{ +namespace mid +{ +class ELinkDataShaper +{ + public: + ELinkDataShaper(bool isDebugMode, bool isLoc, uint8_t uniqueId); + /// Main function to be executed when decoding is done + inline void onDone(const ELinkDecoder& decoder, std::vector& data, std::vector& rofs) { std::invoke(mOnDone, this, decoder, data, rofs); } + + void set(uint32_t orbit); + + /// Sets the delay in the electronics + void setElectronicsDelay(const ElectronicsDelay& electronicsDelay) { mElectronicsDelay = electronicsDelay; } + + private: + uint8_t mUniqueId{0}; /// UniqueId + uint32_t mRDHOrbit{0}; /// RDH orbit + bool mReceivedCalibration{false}; /// Flag to indicate if the calibration trigger was received + ElectronicsDelay mElectronicsDelay{}; /// Delays in the electronics + + InteractionRecord mIR{}; /// Interaction record + uint16_t mExpectedFETClock{}; /// Expected FET clock + uint16_t mLastClock{}; /// Last clock + + typedef void (ELinkDataShaper::*OnDoneFunction)(const ELinkDecoder&, std::vector& data, std::vector& rofs); + OnDoneFunction mOnDone{&ELinkDataShaper::onDoneLoc}; ///! Processes the board + + void onDoneLoc(const ELinkDecoder& decoder, std::vector& data, std::vector& rofs); + void onDoneLocDebug(const ELinkDecoder& decoder, std::vector& data, std::vector& rofs); + void onDoneReg(const ELinkDecoder&, std::vector& data, std::vector& rofs){}; /// Dummy function + void onDoneRegDebug(const ELinkDecoder& decoder, std::vector& data, std::vector& rofs); + + void addLoc(const ELinkDecoder& decoder, EventType eventType, uint16_t correctedClock, std::vector& data, std::vector& rofs); + bool checkLoc(const ELinkDecoder& decoder); + EventType processCalibrationTrigger(uint16_t localClock); + void processOrbitTrigger(uint16_t localClock, uint8_t triggerWord); + EventType processSelfTriggered(uint16_t localClock, uint16_t& correctedClock); + bool processTrigger(const ELinkDecoder& decoder, EventType& eventType, uint16_t& correctedClock); +}; +} // namespace mid +} // namespace o2 + +#endif /* O2_MID_ELINKDATASHAPER_H */ diff --git a/Detectors/MUON/MID/Raw/include/MIDRaw/ELinkDecoder.h b/Detectors/MUON/MID/Raw/include/MIDRaw/ELinkDecoder.h index 3be3e641204a7..f5b6857459556 100644 --- a/Detectors/MUON/MID/Raw/include/MIDRaw/ELinkDecoder.h +++ b/Detectors/MUON/MID/Raw/include/MIDRaw/ELinkDecoder.h @@ -28,6 +28,7 @@ namespace mid class ELinkDecoder { public: + void setBareDecoder(bool isBare); /// Adds a byte inline void add(const uint8_t byte) { mBytes.emplace_back(byte); } void addAndComputeSize(const uint8_t byte); @@ -35,7 +36,7 @@ class ELinkDecoder bool addCore(ITERATOR& it, const ITERATOR& end) { /// Adds the first 5 bytes - auto remaining = sMinimumSize - mBytes.size(); + auto remaining = mMinimumSize - mBytes.size(); return add(it, end, remaining); } template @@ -44,7 +45,7 @@ class ELinkDecoder /// Adds the board bytes auto remaining = mTotalSize - mBytes.size(); if (add(it, end, remaining)) { - if (mTotalSize == sMinimumSize) { + if (mTotalSize == mMinimumSize) { computeSize(); remaining = mTotalSize - mBytes.size(); if (remaining) { @@ -57,7 +58,7 @@ class ELinkDecoder } /// Adds the first 5 bytes - inline bool addCore(size_t& idx, gsl::span payload, size_t step) { return add(idx, payload, sMinimumSize - mBytes.size(), step); } + inline bool addCore(size_t& idx, gsl::span payload, size_t step) { return add(idx, payload, mMinimumSize - mBytes.size(), step); } bool add(size_t& idx, gsl::span payload, size_t step); @@ -76,6 +77,8 @@ class ELinkDecoder inline uint8_t getId() const { return (mBytes[4] >> 4) & 0xF; } /// Gets the inputs inline uint8_t getInputs() const { return (mBytes[4] & 0xF); } + /// Gets the crate ID when available + inline uint8_t getCrateId() const { return (mBytes[5] >> 4) & 0xF; } uint16_t getPattern(int cathode, int chamber) const; /// Gets the number of bytes read inline size_t getNBytes() const { return mBytes.size(); } @@ -99,10 +102,10 @@ class ELinkDecoder void computeSize(); - static constexpr size_t sMinimumSize{5}; /// Minimum size of the buffer - static constexpr size_t sMaximumSize{21}; /// Maximum size of the buffer - std::vector mBytes{}; /// Vector with encoded information - size_t mTotalSize{sMinimumSize}; /// Expected size of the read-out buffer + size_t mMinimumSize{5}; /// Minimum size of the buffer + size_t mMaximumSize{21}; /// Maximum size of the buffer + std::vector mBytes{}; /// Vector with encoded information + size_t mTotalSize{mMinimumSize}; /// Expected size of the read-out buffer }; } // namespace mid } // namespace o2 diff --git a/Detectors/MUON/MID/Raw/include/MIDRaw/ELinkManager.h b/Detectors/MUON/MID/Raw/include/MIDRaw/ELinkManager.h new file mode 100644 index 0000000000000..de619ede936da --- /dev/null +++ b/Detectors/MUON/MID/Raw/include/MIDRaw/ELinkManager.h @@ -0,0 +1,82 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file MIDRaw/ELinkManager.h +/// \brief MID e-link data shaper manager +/// \author Diego Stocco +/// \date 18 March 2021 +#ifndef O2_MID_ELINKMANAGER_H +#define O2_MID_ELINKMANAGER_H + +#include +#if defined(MID_RAW_VECTORS) +#include +#else +#include +#endif +#include "MIDRaw/ELinkDataShaper.h" +#include "MIDRaw/ELinkDecoder.h" +#include "MIDRaw/ElectronicsDelay.h" +#include "MIDRaw/FEEIdConfig.h" + +namespace o2 +{ +namespace mid +{ +class ELinkManager +{ + public: + void init(uint16_t feeId, bool isDebugMode, bool isBare = false, const ElectronicsDelay& electronicsDelay = ElectronicsDelay(), const FEEIdConfig& feeIdConfig = FEEIdConfig()); + + void set(uint32_t orbit); + + /// Main function to be executed when decoding is done + inline void onDone(const ELinkDecoder& decoder, uint8_t boardUniqueId, std::vector& data, std::vector& rofs) { return onDone(decoder, raw::getCrateId(boardUniqueId), raw::getLocId(boardUniqueId), data, rofs); } + + /// Main function to be executed when decoding is done + inline void onDone(const ELinkDecoder& decoder, std::vector& data, std::vector& rofs) { return onDone(decoder, decoder.getCrateId(), decoder.getId(), data, rofs); } + +#if defined(MID_RAW_VECTORS) + /// Returns the decoder + inline ELinkDecoder& getDecoder(uint8_t boardUniqueId, bool isLoc) { return mDecoders[mIndex(raw::getCrateId(boardUniqueId), raw::getLocId(boardUniqueId), isLoc)]; } + + /// Main function to be executed when decoding is done + inline void onDone(const ELinkDecoder& decoder, uint8_t crateId, uint8_t locId, std::vector& data, std::vector& rofs) + { + return mDataShapers[mIndex(crateId, locId, raw::isLoc(decoder.getStatusWord()))].onDone(decoder, data, rofs); + } + + private: + std::function mIndex{}; ///! Function that returns the index in the vector + std::vector mDataShapers; /// Vector with data shapers for each loc and reg board + std::vector mDecoders; /// Vector with decoders for each loc and reg board + +#else + /// Returns the decoder + inline ELinkDecoder& getDecoder(uint8_t boardUniqueId, bool isLoc) { return mDecoders.find(makeUniqueId(isLoc, boardUniqueId))->second; } + + /// Main function to be executed when decoding is done + inline void onDone(const ELinkDecoder& decoder, uint8_t crateId, uint8_t locId, std::vector& data, std::vector& rofs) + { + return mDataShapers.find(makeUniqueId(raw::isLoc(decoder.getStatusWord()), raw::makeUniqueLocID(crateId, locId)))->second.onDone(decoder, data, rofs); + } + + private: + /// Makes a ID which is unique for local and regional board + inline uint16_t makeUniqueId(bool isLoc, uint8_t uniqueId) { return (isLoc ? 0 : (1 << 8)) | uniqueId; } + std::unordered_map mDataShapers; /// Data shapers for each loc and reg board + std::unordered_map mDecoders; /// Decoders for each loc and reg board + +#endif +}; +} // namespace mid +} // namespace o2 + +#endif /* O2_MID_ELINKMANAGER_H */ diff --git a/Detectors/MUON/MID/Raw/include/MIDRaw/Encoder.h b/Detectors/MUON/MID/Raw/include/MIDRaw/Encoder.h index 780ce34aa083b..f2445844b9bfb 100644 --- a/Detectors/MUON/MID/Raw/include/MIDRaw/Encoder.h +++ b/Detectors/MUON/MID/Raw/include/MIDRaw/Encoder.h @@ -51,9 +51,9 @@ class Encoder private: void completeWord(std::vector& buffer); - void writePayload(uint16_t feeId, const InteractionRecord& ir); + void writePayload(uint16_t linkId, const InteractionRecord& ir); void onOrbitChange(uint32_t orbit); - // Returns the interaction record expected for the orbit trigger + /// Returns the interaction record expected for the orbit trigger inline InteractionRecord getOrbitIR(uint32_t orbit) const { return {o2::constants::lhc::LHCMaxBunches - 1, orbit}; } o2::raw::RawFileWriter mRawWriter{o2::header::gDataOriginMID}; /// Raw file writer @@ -63,10 +63,10 @@ class Encoder FEEIdConfig mFEEIdConfig{}; /// Crate FEEId mapper InteractionRecord mLastIR{}; /// Last interaction record - std::array mGBTEncoders{}; /// Array of encoders per link - std::array, crateparams::sNGBTs> mOrbitResponse{}; /// Response to orbit trigger - std::array, crateparams::sNGBTs> mOrbitResponseWord{}; /// CRU word for response to orbit trigger - std::array mGBTIds{}; /// Array of GBT Ids + std::array mGBTIds{}; /// Array of GBT Ids + std::array mGBTEncoders{}; /// Array of encoders per link + std::array, 4> mOrbitResponse{}; /// Response to orbit trigger + std::array, 4> mOrbitResponseWord{}; /// CRU word for response to orbit trigger }; } // namespace mid } // namespace o2 diff --git a/Detectors/MUON/MID/Raw/include/MIDRaw/FEEIdConfig.h b/Detectors/MUON/MID/Raw/include/MIDRaw/FEEIdConfig.h index 6c0f057c4a90c..42e71de87e84d 100644 --- a/Detectors/MUON/MID/Raw/include/MIDRaw/FEEIdConfig.h +++ b/Detectors/MUON/MID/Raw/include/MIDRaw/FEEIdConfig.h @@ -30,36 +30,36 @@ class FEEIdConfig FEEIdConfig(const char* filename); ~FEEIdConfig() = default; - uint16_t getFeeId(uint32_t uniqueId) const; + uint16_t getGBTUniqueId(uint32_t linkUniqueId) const; - /// Gets the FEE ID from the physical ID of the link - uint16_t getFeeId(uint8_t linkId, uint8_t endPointId, uint16_t cruId) const { return getFeeId(getGBTId(linkId, endPointId, cruId)); } + inline const std::vector& getGBTUniqueIdsInLink(uint16_t feeId) const { return mGBTUniqueIdsInLink.find(feeId)->second; } + + /// Gets the GBT unique ID from the physical ID of the link + uint16_t getGBTUniqueId(uint8_t linkId, uint8_t endPointId, uint16_t cruId) const { return getGBTUniqueId(getLinkUniqueId(linkId, endPointId, cruId)); } /// Gets a uniqueID from the combination of linkId, endPointId and cruId; - inline uint32_t getGBTId(uint8_t linkId, uint8_t endPointId, uint16_t cruId) const { return (linkId + 1) << ((endPointId == 1) ? 8U : 0U) | (cruId << 16U); } + inline uint32_t getLinkUniqueId(uint8_t linkId, uint8_t endPointId, uint16_t cruId) const { return (linkId + 1) << ((endPointId == 1) ? 8U : 0U) | (cruId << 16U); } /// Gets the CRU ID - inline uint16_t getCRUId(uint32_t gbtId) const { return gbtId >> 16; } + inline uint16_t getCRUId(uint32_t linkUniqueId) const { return linkUniqueId >> 16; } /// Gets the end point id - inline uint8_t getEndPointId(uint32_t gbtId) const { return (gbtId & 0xFF00) ? 1 : 0; } + inline uint8_t getEndPointId(uint32_t linkUniqueId) const { return (linkUniqueId & 0xFF00) ? 1 : 0; } /// Gets the Link ID - inline uint8_t getLinkId(uint32_t gbtId) const { return ((gbtId >> (8U * getEndPointId(gbtId))) & 0xFF) - 1; } + inline uint8_t getLinkId(uint32_t linkUniqueId) const { return ((linkUniqueId >> (8U * getEndPointId(linkUniqueId))) & 0xFF) - 1; } - std::vector getConfiguredFeeIds() const; - std::vector getConfiguredGBTIds() const; + std::vector getConfiguredGBTUniqueIDs() const; + std::vector getConfiguredLinkUniqueIDs() const; + std::vector getConfiguredFEEIDs() const; void write(const char* filename) const; private: bool load(const char* filename); - std::unordered_map mGBTIdToFeeId; /// Correspondence between GBT Id and FeeId + std::unordered_map mLinkUniqueIdToGBTUniqueId{}; /// Correspondence between link unique ID and GBT unique Id + std::unordered_map mGBTUniqueIdToFeeId{}; /// Correspondence between GBT unique ID and FEE ID + std::unordered_map> mGBTUniqueIdsInLink{}; /// Input GBT links in output link }; -namespace raw -{ -static constexpr uint8_t sUserLogicLinkID = 15; -} - } // namespace mid } // namespace o2 diff --git a/Detectors/MUON/MID/Raw/include/MIDRaw/GBTOutputHandler.h b/Detectors/MUON/MID/Raw/include/MIDRaw/GBTOutputHandler.h index 956546b654468..58f4cba3952ca 100644 --- a/Detectors/MUON/MID/Raw/include/MIDRaw/GBTOutputHandler.h +++ b/Detectors/MUON/MID/Raw/include/MIDRaw/GBTOutputHandler.h @@ -33,7 +33,7 @@ class GBTOutputHandler { public: /// Sets the FEE Id - void setFeeId(uint16_t feeId) { mFeeId = feeId; } + void setGBTUniqueId(uint16_t feeId) { mFeeId = feeId; } void set(uint32_t orbit, std::vector& data, std::vector& rofs); diff --git a/Detectors/MUON/MID/Raw/include/MIDRaw/GBTUserLogicEncoder.h b/Detectors/MUON/MID/Raw/include/MIDRaw/GBTUserLogicEncoder.h index a9d20d8333e77..21afb0622d46f 100644 --- a/Detectors/MUON/MID/Raw/include/MIDRaw/GBTUserLogicEncoder.h +++ b/Detectors/MUON/MID/Raw/include/MIDRaw/GBTUserLogicEncoder.h @@ -41,8 +41,7 @@ class GBTUserLogicEncoder /// Sets the mask void setMask(uint8_t mask) { mMask = mask; } - /// Sets the feeID - void setFeeId(uint16_t feeId) { mFeeId = feeId; } + void setGBTUniqueId(uint16_t gbtUniqueId); /// Sets the delay in the electronics void setElectronicsDelay(const ElectronicsDelay& electronicsDelay) { mElectronicsDelay = electronicsDelay; } @@ -52,7 +51,8 @@ class GBTUserLogicEncoder void addShort(std::vector& buffer, uint16_t shortWord) const; std::map> mBoards{}; /// Vector with boards - uint16_t mFeeId{0}; /// FEE ID + uint8_t mCrateId{0}; /// Crate ID + uint8_t mOffset{0}; /// GBT ID offset uint8_t mMask{0xFF}; /// GBT mask ElectronicsDelay mElectronicsDelay; /// Delays in the electronics }; diff --git a/Detectors/MUON/MID/Raw/include/MIDRaw/GBTDecoder.h b/Detectors/MUON/MID/Raw/include/MIDRaw/LinkDecoder.h similarity index 58% rename from Detectors/MUON/MID/Raw/include/MIDRaw/GBTDecoder.h rename to Detectors/MUON/MID/Raw/include/MIDRaw/LinkDecoder.h index c456b12b2b317..d38390ad5202a 100644 --- a/Detectors/MUON/MID/Raw/include/MIDRaw/GBTDecoder.h +++ b/Detectors/MUON/MID/Raw/include/MIDRaw/LinkDecoder.h @@ -8,31 +8,32 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// \file MIDRaw/GBTDecoder.h -/// \brief Class interface for the MID GBT decoder +/// \file MIDRaw/LinkDecoder.h +/// \brief Class interface for the MID link decoder /// \author Diego Stocco /// \date 07 November 2020 -#ifndef O2_MID_GBTDECODER_H -#define O2_MID_GBTDECODER_H +#ifndef O2_MID_LINKDECODER_H +#define O2_MID_LINKDECODER_H #include #include #include #include "DetectorsRaw/RDHUtils.h" #include "Headers/RAWDataHeader.h" +#include "DataFormatsMID/ROBoard.h" #include "DataFormatsMID/ROFRecord.h" #include "MIDRaw/ElectronicsDelay.h" -#include "DataFormatsMID/ROBoard.h" +#include "MIDRaw/FEEIdConfig.h" namespace o2 { namespace mid { -class GBTDecoder +class LinkDecoder { public: - GBTDecoder(std::function, uint32_t orbit, std::vector& data, std::vector& rofs)> decode) : mDecode(decode) {} + LinkDecoder(std::function, uint32_t orbit, std::vector& data, std::vector& rofs)> decode) : mDecode(decode) {} void process(gsl::span payload, uint32_t orbit, std::vector& data, std::vector& rofs); template @@ -45,10 +46,12 @@ class GBTDecoder std::function, uint32_t orbit, std::vector& data, std::vector& rofs)> mDecode{nullptr}; }; -std::unique_ptr createGBTDecoder(const o2::header::RDHAny& rdh, uint16_t feeId, bool isDebugMode, uint8_t mask, const ElectronicsDelay& electronicsDelay); -std::unique_ptr createGBTDecoder(uint16_t feeId, bool isBare = false, bool isDebugMode = false, uint8_t mask = 0xFF, const ElectronicsDelay& electronicsDelay = ElectronicsDelay()); +std::unique_ptr createGBTDecoder(const o2::header::RDHAny& rdh, uint16_t feeId, bool isDebugMode, uint8_t mask, const ElectronicsDelay& electronicsDelay); + +std::unique_ptr createLinkDecoder(const o2::header::RDHAny& rdh, uint16_t feeId, bool isDebugMode, uint8_t mask, const ElectronicsDelay& electronicsDelay, const FEEIdConfig& feeIdConfig); +std::unique_ptr createLinkDecoder(uint16_t feeId, bool isBare = false, bool isDebugMode = false, uint8_t mask = 0xFF, const ElectronicsDelay& electronicsDelay = ElectronicsDelay(), const FEEIdConfig& feeIdConfig = FEEIdConfig()); } // namespace mid } // namespace o2 -#endif /* O2_MID_GBTDECODER_H */ +#endif /* O2_MID_LINKDECODER_H */ diff --git a/Detectors/MUON/MID/Raw/include/MIDRaw/Utils.h b/Detectors/MUON/MID/Raw/include/MIDRaw/Utils.h new file mode 100644 index 0000000000000..89055f4e6919f --- /dev/null +++ b/Detectors/MUON/MID/Raw/include/MIDRaw/Utils.h @@ -0,0 +1,36 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file MIDRaw/Utils.h +/// \brief Raw data utilities for MID +/// \author Diego Stocco +/// \date 19 November 2019 +#ifndef O2_MID_UTILS_H +#define O2_MID_UTILS_H + +#include "Headers/RDHAny.h" +#include "DetectorsRaw/RDHUtils.h" + +namespace o2 +{ +namespace mid +{ +namespace raw +{ +static constexpr uint8_t sUserLogicLinkID = 15; // Link ID for the user logic + +/// Test if the data comes from the common logic +inline bool isBare(const o2::header::RDHAny& rdh) { return (o2::raw::RDHUtils::getLinkID(rdh) != sUserLogicLinkID); } + +} // namespace raw +} // namespace mid +} // namespace o2 + +#endif /* O2_MID_UTILS_H */ diff --git a/Detectors/MUON/MID/Raw/src/Decoder.cxx b/Detectors/MUON/MID/Raw/src/Decoder.cxx index f29d4cb4dde88..582720805017d 100644 --- a/Detectors/MUON/MID/Raw/src/Decoder.cxx +++ b/Detectors/MUON/MID/Raw/src/Decoder.cxx @@ -23,27 +23,17 @@ namespace o2 namespace mid { -// namespace impl -// { -class FEEIDGetterImpl -{ - public: - FEEIDGetterImpl(const FEEIdConfig& feeIdConfig) : mFeeIdConfig(feeIdConfig) {} - uint16_t operator()(const o2::header::RDHAny& rdh) { return mFeeIdConfig.getFeeId(o2::raw::RDHUtils::getLinkID(rdh), o2::raw::RDHUtils::getEndPointID(rdh), o2::raw::RDHUtils::getCRUID(rdh)); } - - private: - FEEIdConfig mFeeIdConfig{}; -}; -// } // namespace impl - -Decoder::Decoder(bool isDebugMode, bool isBare, const ElectronicsDelay& electronicsDelay, const CrateMasks& crateMasks, const FEEIdConfig& feeIdConfig) : mData(), mROFRecords(), mGBTDecoders() +Decoder::Decoder(bool isDebugMode, bool isBare, const ElectronicsDelay& electronicsDelay, const CrateMasks& crateMasks, const FEEIdConfig& feeIdConfig) : mData(), mROFRecords(), mLinkDecoders() { /// Constructor - for (uint16_t igbt = 0; igbt < crateparams::sNGBTs; ++igbt) { - mGBTDecoders[igbt] = createGBTDecoder(igbt, isBare, isDebugMode, crateMasks.getMask(igbt), electronicsDelay); - } - if (isBare) { - mGetFEEID = FEEIDGetterImpl(feeIdConfig); + auto feeIds = isBare ? feeIdConfig.getConfiguredGBTUniqueIDs() : feeIdConfig.getConfiguredFEEIDs(); + + for (auto& feeId : feeIds) { +#if defined(MID_RAW_VECTORS) + mLinkDecoders.emplace_back(createLinkDecoder(feeId, isBare, isDebugMode, crateMasks.getMask(feeId), electronicsDelay, feeIdConfig)); +#else + mLinkDecoders.emplace(feeId, createLinkDecoder(feeId, isBare, isDebugMode, crateMasks.getMask(feeId), electronicsDelay, feeIdConfig)); +#endif } } @@ -69,10 +59,10 @@ void Decoder::process(gsl::span bytes) } } -std::unique_ptr createDecoder(const o2::header::RDHAny& rdh, bool isDebugMode, ElectronicsDelay& electronicsDelay, const CrateMasks& crateMasks, const FEEIdConfig& feeIdConfig) +std::unique_ptr createDecoder(const o2::header::RDHAny& rdh, bool isDebugMode, const ElectronicsDelay& electronicsDelay, const CrateMasks& crateMasks, const FEEIdConfig& feeIdConfig) { /// Creates the decoder from the RDH info - bool isBare = (o2::raw::RDHUtils::getLinkID(rdh) != raw::sUserLogicLinkID); + bool isBare = raw::isBare(rdh); return std::make_unique(isDebugMode, isBare, electronicsDelay, crateMasks, feeIdConfig); } std::unique_ptr createDecoder(const o2::header::RDHAny& rdh, bool isDebugMode, const char* electronicsDelayFile, const char* crateMasksFile, const char* feeIdConfigFile) diff --git a/Detectors/MUON/MID/Raw/src/ELinkDataShaper.cxx b/Detectors/MUON/MID/Raw/src/ELinkDataShaper.cxx new file mode 100644 index 0000000000000..bafa61b2aa0c7 --- /dev/null +++ b/Detectors/MUON/MID/Raw/src/ELinkDataShaper.cxx @@ -0,0 +1,210 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file MID/Raw/src/ELinkDataShaper.cxx +/// \brief Properly formats and sets the absolute timestamp of the raw data +/// \author Diego Stocco +/// \date 18 March 2021 + +#include "MIDRaw/ELinkDataShaper.h" + +#include "CommonConstants/LHCConstants.h" + +namespace o2 +{ +namespace mid +{ + +ELinkDataShaper::ELinkDataShaper(bool isDebugMode, bool isLoc, uint8_t uniqueId) : mUniqueId(uniqueId) +{ + /// Ctr + if (isDebugMode) { + if (isLoc) { + mOnDone = &ELinkDataShaper::onDoneLocDebug; + } else { + mOnDone = &ELinkDataShaper::onDoneRegDebug; + } + } else { + if (isLoc) { + mOnDone = &ELinkDataShaper::onDoneLoc; + } else { + mOnDone = &ELinkDataShaper::onDoneReg; + } + } +} + +void ELinkDataShaper::set(uint32_t orbit) +{ + /// Sets the orbit and the output data vectors + mRDHOrbit = orbit; + + if (mIR.isDummy()) { + mIR.bc = 0; + // The reset changes depending on the way we synch with the orbit + // (see processOrbitTrigger for details) + // FIXME: pick one of the two + // mIR.orbit = orbit - 1; // with orbit increase + mIR.orbit = orbit; // with reset to RDH + mLastClock = constants::lhc::LHCMaxBunches; + } +} + +bool ELinkDataShaper::checkLoc(const ELinkDecoder& decoder) +{ + /// Performs checks on the local board + return (decoder.getId() == (mUniqueId & 0xF)); +} + +EventType ELinkDataShaper::processSelfTriggered(uint16_t localClock, uint16_t& correctedClock) +{ + /// Processes the self-triggered event + correctedClock = localClock - mElectronicsDelay.BCToLocal; + if (mReceivedCalibration && (localClock == mExpectedFETClock)) { + // Reset the calibration flag for this e-link + mReceivedCalibration = false; + return EventType::Dead; + } + return EventType::Standard; +} + +EventType ELinkDataShaper::processCalibrationTrigger(uint16_t localClock) +{ + /// Processes the calibration event + mExpectedFETClock = localClock + mElectronicsDelay.calibToFET; + mReceivedCalibration = true; + return EventType::Noise; +} + +void ELinkDataShaper::processOrbitTrigger(uint16_t localClock, uint8_t triggerWord) +{ + /// Processes the orbit trigger event + + // The local clock is reset: we are now in synch with the new HB + // We have two ways to account for the orbit change: + // - increase the orbit counter by 1 for this e-link + // (CAVEAT: synch is lost if we lose some orbit) + // - set the orbit to the one found in RDH + // (CAVEAT: synch is lost if we have lot of data, spanning over two orbits) + // FIXME: pick one of the two + // ++mIR.orbit; // orbit increase + mIR.orbit = mRDHOrbit; // reset to RDH + if ((triggerWord & raw::sSOX) == 0) { + mLastClock = localClock; + } + // The orbit trigger resets the clock. + // If we received a calibration trigger, we need to change the value of the expected clock accordingly + if (mReceivedCalibration) { + mExpectedFETClock -= (localClock + 1); + } +} + +bool ELinkDataShaper::processTrigger(const ELinkDecoder& decoder, EventType& eventType, uint16_t& correctedClock) +{ + /// Processes the trigger information + /// Returns true if the event should be further processed, + /// returns false otherwise. + auto localClock = decoder.getCounter(); + + if (decoder.getTriggerWord() == 0) { + // This is a self-triggered event + eventType = processSelfTriggered(localClock, correctedClock); + return true; + } + + // From here we treat triggered events + bool goOn = false; + correctedClock = localClock; + if (decoder.getTriggerWord() & raw::sCALIBRATE) { + // This is an answer to a calibration trigger + eventType = processCalibrationTrigger(localClock); + goOn = true; + } + + if (decoder.getTriggerWord() & raw::sORB) { + // This is the answer to an orbit trigger + processOrbitTrigger(localClock, decoder.getTriggerWord()); + eventType = EventType::Standard; + } + + return goOn; +} + +void ELinkDataShaper::addLoc(const ELinkDecoder& decoder, EventType eventType, uint16_t correctedClock, std::vector& data, std::vector& rofs) +{ + /// Adds the local board to the output data vector + auto firstEntry = data.size(); + data.push_back({decoder.getStatusWord(), decoder.getTriggerWord(), mUniqueId, decoder.getInputs()}); + InteractionRecord intRec(mIR.bc + correctedClock, mIR.orbit); + rofs.emplace_back(intRec, eventType, firstEntry, 1); + for (int ich = 0; ich < 4; ++ich) { + if ((data.back().firedChambers & (1 << ich))) { + data.back().patternsBP[ich] = decoder.getPattern(0, ich); + data.back().patternsNBP[ich] = decoder.getPattern(1, ich); + } + } +} + +void ELinkDataShaper::onDoneLoc(const ELinkDecoder& decoder, std::vector& data, std::vector& rofs) +{ + /// Performs action on decoded local board + EventType eventType; + uint16_t correctedClock; + if (processTrigger(decoder, eventType, correctedClock) && checkLoc(decoder)) { + addLoc(decoder, eventType, correctedClock, data, rofs); + } +} + +void ELinkDataShaper::onDoneLocDebug(const ELinkDecoder& decoder, std::vector& data, std::vector& rofs) +{ + /// This always adds the local board to the output, without performing tests + EventType eventType; + uint16_t correctedClock; + processTrigger(decoder, eventType, correctedClock); + addLoc(decoder, eventType, correctedClock, data, rofs); + if (decoder.getTriggerWord() & raw::sORB) { + // The local clock is increased when receiving an orbit trigger, + // but the local counter returned in answering the trigger + // belongs to the previous orbit + --rofs.back().interactionRecord.orbit; + } +} + +void ELinkDataShaper::onDoneRegDebug(const ELinkDecoder& decoder, std::vector& data, std::vector& rofs) +{ + /// Performs action on decoded regional board in debug mode. + EventType eventType; + uint16_t correctedClock; + processTrigger(decoder, eventType, correctedClock); + // If we want to distinguish the two regional e-links, we can use the link ID instead + auto firstEntry = data.size(); + data.push_back({decoder.getStatusWord(), decoder.getTriggerWord(), mUniqueId, decoder.getInputs()}); + + auto orbit = (decoder.getTriggerWord() & raw::sORB) ? mIR.orbit - 1 : mIR.orbit; + + InteractionRecord intRec(mIR.bc + correctedClock, orbit); + if (decoder.getTriggerWord() == 0) { + if (intRec.bc < mElectronicsDelay.regToLocal) { + // In the tests, the HB does not really correspond to a change of orbit + // So we need to keep track of the last clock at which the HB was received + // and come back to that value + // FIXME: Remove this part as well as mLastClock when tests are no more needed + intRec -= (constants::lhc::LHCMaxBunches - mLastClock - 1); + } + // This is a self-triggered event. + // In this case the regional card needs to wait to receive the tracklet decision of each local + // which result in a delay that needs to be subtracted if we want to be able to synchronize + // local and regional cards for the checks + intRec -= mElectronicsDelay.regToLocal; + } + rofs.emplace_back(intRec, eventType, firstEntry, 1); +} + +} // namespace mid +} // namespace o2 diff --git a/Detectors/MUON/MID/Raw/src/ELinkDecoder.cxx b/Detectors/MUON/MID/Raw/src/ELinkDecoder.cxx index c18234952963f..6b3dcb9400f68 100644 --- a/Detectors/MUON/MID/Raw/src/ELinkDecoder.cxx +++ b/Detectors/MUON/MID/Raw/src/ELinkDecoder.cxx @@ -20,6 +20,14 @@ namespace o2 namespace mid { +void ELinkDecoder::setBareDecoder(bool isBare) +{ + /// Sets the decoder type + mMinimumSize = isBare ? 5 : 6; + mMaximumSize = isBare ? 21 : 22; + mTotalSize = mMinimumSize; +} + bool ELinkDecoder::add(size_t& idx, gsl::span payload, size_t nBytes, size_t step) { /// Fills inner bytes vector @@ -41,7 +49,7 @@ bool ELinkDecoder::add(size_t& idx, gsl::span payload, size_t ste /// Adds the bytes of the board auto remaining = mTotalSize - mBytes.size(); if (add(idx, payload, remaining, step)) { - if (mTotalSize == sMinimumSize) { + if (mTotalSize == mMinimumSize) { computeSize(); remaining = mTotalSize - mBytes.size(); if (remaining) { @@ -57,7 +65,7 @@ void ELinkDecoder::addAndComputeSize(uint8_t byte) { /// Adds next byte and computes the expected data size mBytes.emplace_back(byte); - if (mBytes.size() == sMinimumSize) { + if (mBytes.size() == mMinimumSize) { computeSize(); } } @@ -81,7 +89,7 @@ void ELinkDecoder::reset() { /// Reset inner objects mBytes.clear(); - mTotalSize = sMinimumSize; + mTotalSize = mMinimumSize; } uint16_t ELinkDecoder::getPattern(int cathode, int chamber) const diff --git a/Detectors/MUON/MID/Raw/src/ELinkManager.cxx b/Detectors/MUON/MID/Raw/src/ELinkManager.cxx new file mode 100644 index 0000000000000..6efeda73fd86c --- /dev/null +++ b/Detectors/MUON/MID/Raw/src/ELinkManager.cxx @@ -0,0 +1,77 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file MID/Raw/src/ELinkManager.cxx +/// \brief MID e-link data shaper manager +/// \author Diego Stocco +/// \date 18 March 2021 + +#include "MIDRaw/ELinkManager.h" +#include "MIDRaw/CrateParameters.h" + +namespace o2 +{ +namespace mid +{ +void ELinkManager::init(uint16_t feeId, bool isDebugMode, bool isBare, const ElectronicsDelay& electronicsDelay, const FEEIdConfig& feeIdConfig) +{ + /// Initializer + auto gbtUniqueIds = isBare ? std::vector{feeId} : feeIdConfig.getGBTUniqueIdsInLink(feeId); + + for (auto& gbtUniqueId : gbtUniqueIds) { + auto crateId = crateparams::getCrateIdFromGBTUniqueId(gbtUniqueId); + uint8_t offset = crateparams::getGBTIdInCrate(gbtUniqueId) * 8; + for (int ilink = 0; ilink < 10; ++ilink) { + bool isLoc = ilink < 8; + auto uniqueId = raw::makeUniqueLocID(crateId, ilink % 8 + offset); + ELinkDataShaper shaper(isDebugMode, isLoc, uniqueId); + shaper.setElectronicsDelay(electronicsDelay); +#if defined(MID_RAW_VECTORS) + mDataShapers.emplace_back(shaper); +#else + auto uniqueRegLocId = makeUniqueId(isLoc, uniqueId); + mDataShapers.emplace(uniqueRegLocId, shaper); +#endif + + if (isBare) { + ELinkDecoder decoder; + decoder.setBareDecoder(true); +#if defined(MID_RAW_VECTORS) + mDecoders.emplace_back(decoder); +#else + mDecoders.emplace(uniqueRegLocId, decoder); +#endif + } + } + } + +#if defined(MID_RAW_VECTORS) + if (isBare) { + mIndex = [](uint8_t, uint8_t locId, bool isLoc) { return 8 * (1 - static_cast(isLoc)) + (locId % 8); }; + } else { + mIndex = [](uint8_t crateId, uint8_t locId, bool isLoc) { return 10 * (2 * (crateId % 4) + (locId / 8)) + 8 * (1 - static_cast(isLoc)) + (locId % 8); }; + } +#endif +} + +void ELinkManager::set(uint32_t orbit) +{ + /// Setup the orbit + for (auto& shaper : mDataShapers) { +#if defined(MID_RAW_VECTORS) + shaper.set(orbit); +#else + shaper.second.set(orbit); +#endif + } +} + +} // namespace mid +} // namespace o2 diff --git a/Detectors/MUON/MID/Raw/src/Encoder.cxx b/Detectors/MUON/MID/Raw/src/Encoder.cxx index 6bcda641d0afa..6e45a6d815bf7 100644 --- a/Detectors/MUON/MID/Raw/src/Encoder.cxx +++ b/Detectors/MUON/MID/Raw/src/Encoder.cxx @@ -18,6 +18,7 @@ #include "DetectorsRaw/HBFUtils.h" #include "DetectorsRaw/RDHUtils.h" #include "MIDRaw/CrateMasks.h" +#include "MIDRaw/Utils.h" #include namespace o2 @@ -30,24 +31,33 @@ void Encoder::init(const char* filename, bool perLink, int verbosity, bool debug /// Initializes links CrateMasks masks; - auto gbtIds = mFEEIdConfig.getConfiguredGBTIds(); + auto linkUniqueIds = mFEEIdConfig.getConfiguredLinkUniqueIDs(); + + // Initialises the GBT link encoders + for (auto& linkUniqueId : linkUniqueIds) { + auto gbtUniqueId = mFEEIdConfig.getGBTUniqueId(linkUniqueId); + mGBTEncoders[gbtUniqueId].setGBTUniqueId(gbtUniqueId); + mGBTEncoders[gbtUniqueId].setMask(masks.getMask(gbtUniqueId)); + mGBTIds[gbtUniqueId] = linkUniqueId; + } + // Initializes the output link + auto ir = getOrbitIR(0); mRawWriter.setVerbosity(verbosity); - int lcnt = 0; - for (auto& gbtId : gbtIds) { - auto feeId = mFEEIdConfig.getFeeId(gbtId); - mRawWriter.registerLink(feeId, mFEEIdConfig.getCRUId(gbtId), raw::sUserLogicLinkID, mFEEIdConfig.getEndPointId(gbtId), perLink ? fmt::format("{:s}_L{:d}.raw", filename, lcnt) : fmt::format("{:s}.raw", filename)); - mGBTEncoders[feeId].setFeeId(feeId); - mGBTEncoders[feeId].setMask(masks.getMask(feeId)); - mGBTIds[feeId] = gbtId; - lcnt++; - - // Initializes the trigger response to be added to the empty HBs - auto ir = getOrbitIR(0); - mGBTEncoders[feeId].processTrigger(ir, raw::sORB); - mGBTEncoders[feeId].flush(mOrbitResponse[feeId], ir); - mOrbitResponseWord[feeId] = mOrbitResponse[feeId]; - completeWord(mOrbitResponseWord[feeId]); + for (uint16_t cruId = 0; cruId < 2; ++cruId) { + for (uint8_t epId = 0; epId < 2; ++epId) { + uint16_t feeId = 2 * cruId + epId; + mRawWriter.registerLink(feeId, cruId, raw::sUserLogicLinkID, epId, perLink ? fmt::format("{:s}_L{:d}.raw", filename, feeId) : fmt::format("{:s}.raw", filename)); + + for (auto gbtUniqueId : mFEEIdConfig.getGBTUniqueIdsInLink(feeId)) { + // Initializes the trigger response to be added to the empty HBs + mGBTEncoders[gbtUniqueId].processTrigger(ir, raw::sORB); + mGBTEncoders[gbtUniqueId].flush(mOrbitResponse[feeId], ir); + } + + mOrbitResponseWord[feeId] = mOrbitResponse[feeId]; + completeWord(mOrbitResponseWord[feeId]); + } } mRawWriter.setEmptyPageCallBack(this); @@ -58,19 +68,16 @@ void Encoder::init(const char* filename, bool perLink, int verbosity, bool debug void Encoder::emptyHBFMethod(const o2::header::RDHAny* rdh, std::vector& toAdd) const { /// Response to orbit triggers in empty HBFs - auto feeId = o2::raw::RDHUtils::getFEEID(rdh); - toAdd = mOrbitResponseWord[feeId]; + toAdd = mOrbitResponseWord[o2::raw::RDHUtils::getFEEID(rdh)]; } void Encoder::onOrbitChange(uint32_t orbit) { /// Performs action when orbit changes auto ir = getOrbitIR(orbit); - for (uint16_t feeId = 0; feeId < crateparams::sNGBTs; ++feeId) { + for (uint16_t feeId = 0; feeId < 4; ++feeId) { // Write the data corresponding to the previous orbit - if (!mGBTEncoders[feeId].isEmpty()) { - writePayload(feeId, ir); - } + writePayload(feeId, ir); } } @@ -90,12 +97,20 @@ void Encoder::writePayload(uint16_t feeId, const InteractionRecord& ir) { /// Writes data - // The first part of data is the answer to the orbit trigger - std::vector buf = mOrbitResponse[feeId]; - // Then we flush the received data - mGBTEncoders[feeId].flush(buf, ir); + std::vector buf; + for (auto& gbtUniqueId : mFEEIdConfig.getGBTUniqueIdsInLink(feeId)) { + if (!mGBTEncoders[gbtUniqueId].isEmpty()) { + mGBTEncoders[gbtUniqueId].flush(buf, ir); + } + } + if (buf.empty()) { + return; + } + + // Add the orbit response + buf.insert(buf.begin(), mOrbitResponse[feeId].begin(), mOrbitResponse[feeId].end()); completeWord(buf); - mRawWriter.addData(feeId, mFEEIdConfig.getCRUId(mGBTIds[feeId]), raw::sUserLogicLinkID, mFEEIdConfig.getEndPointId(mGBTIds[feeId]), ir, buf); + mRawWriter.addData(feeId, feeId / 2, raw::sUserLogicLinkID, feeId % 2, ir, buf); } void Encoder::finalize(bool closeFile) @@ -106,16 +121,15 @@ void Encoder::finalize(bool closeFile) mLastIR.orbit = mRawWriter.getHBFUtils().orbitFirst; } auto ir = getOrbitIR(mLastIR.orbit); - for (uint16_t feeId = 0; feeId < crateparams::sNGBTs; ++feeId) { + auto nextIr = getOrbitIR(mLastIR.orbit + 1); + for (uint16_t feeId = 0; feeId < 4; ++feeId) { + auto ir = getOrbitIR(mLastIR.orbit); // Write the last payload writePayload(feeId, ir); - if (!mGBTEncoders[feeId].isEmpty()) { - // Since the regional response comes after few clocks, - // we might have the corresponding regional cards in the next orbit. - // If this is the case, we flush all data of the next orbit - ++ir.orbit; - writePayload(feeId, ir); - } + // Since the regional response comes after few clocks, + // we might have the corresponding regional cards in the next orbit. + // If this is the case, we flush all data of the next orbit + writePayload(feeId, nextIr); } if (closeFile) { mRawWriter.close(); diff --git a/Detectors/MUON/MID/Raw/src/FEEIdConfig.cxx b/Detectors/MUON/MID/Raw/src/FEEIdConfig.cxx index 055d4f60251b8..1b0b7b9d48b5f 100644 --- a/Detectors/MUON/MID/Raw/src/FEEIdConfig.cxx +++ b/Detectors/MUON/MID/Raw/src/FEEIdConfig.cxx @@ -26,49 +26,66 @@ namespace o2 { namespace mid { -FEEIdConfig::FEEIdConfig() : mGBTIdToFeeId() +FEEIdConfig::FEEIdConfig() : mLinkUniqueIdToGBTUniqueId(), mGBTUniqueIdToFeeId(), mGBTUniqueIdsInLink() { /// Default constructor for (uint16_t iside = 0; iside < 2; ++iside) { + uint16_t cruId = iside; for (uint8_t igbt = 0; igbt < crateparams::sNGBTsPerSide; ++igbt) { - mGBTIdToFeeId[getGBTId(igbt % 12, igbt / 12, iside)] = igbt + crateparams::sNGBTsPerSide * iside; + uint8_t epId = igbt / 8; + uint16_t feeId = 2 * cruId + epId; + uint16_t gbtUniqueId = igbt + crateparams::sNGBTsPerSide * iside; + mLinkUniqueIdToGBTUniqueId[getLinkUniqueId(igbt % 8, epId, iside)] = gbtUniqueId; + mGBTUniqueIdToFeeId[gbtUniqueId] = feeId; + mGBTUniqueIdsInLink[feeId].emplace_back(gbtUniqueId); } } } -FEEIdConfig::FEEIdConfig(const char* filename) : mGBTIdToFeeId() +FEEIdConfig::FEEIdConfig(const char* filename) : mLinkUniqueIdToGBTUniqueId() { /// Construct from file load(filename); } -uint16_t FEEIdConfig::getFeeId(uint32_t uniqueId) const +uint16_t FEEIdConfig::getGBTUniqueId(uint32_t linkUniqueId) const { /// Gets the feeId from the physical ID of the link - auto feeId = mGBTIdToFeeId.find(uniqueId); - if (feeId == mGBTIdToFeeId.end()) { - LOGF(ERROR, "No FeeId found for: CRUId: %i LinkId: %i EndPointId: %i", getCRUId(uniqueId), getLinkId(uniqueId), getEndPointId(uniqueId)); + auto feeId = mLinkUniqueIdToGBTUniqueId.find(linkUniqueId); + if (feeId == mLinkUniqueIdToGBTUniqueId.end()) { + LOGF(ERROR, "No FeeId found for: CRUId: %i LinkId: %i EndPointId: %i", getCRUId(linkUniqueId), getLinkId(linkUniqueId), getEndPointId(linkUniqueId)); return 0xFFFF; } return feeId->second; } -std::vector FEEIdConfig::getConfiguredFeeIds() const +std::vector FEEIdConfig::getConfiguredGBTUniqueIDs() const { /// Returns the sorted list of configured FEE IDs std::vector configIds; - for (auto& item : mGBTIdToFeeId) { + for (auto& item : mLinkUniqueIdToGBTUniqueId) { configIds.emplace_back(item.second); } std::sort(configIds.begin(), configIds.end()); return configIds; } -std::vector FEEIdConfig::getConfiguredGBTIds() const +std::vector FEEIdConfig::getConfiguredLinkUniqueIDs() const { /// Returns the sorted list of configured GBT IDs std::vector configIds; - for (auto& item : mGBTIdToFeeId) { + for (auto& item : mLinkUniqueIdToGBTUniqueId) { + configIds.emplace_back(item.first); + } + std::sort(configIds.begin(), configIds.end()); + return configIds; +} + +std::vector FEEIdConfig::getConfiguredFEEIDs() const +{ + /// Returns the sorted list of configured FEE Ids + std::vector configIds; + for (auto& item : mGBTUniqueIdsInLink) { configIds.emplace_back(item.first); } std::sort(configIds.begin(), configIds.end()); @@ -82,14 +99,17 @@ bool FEEIdConfig::load(const char* filename) /// feeId linkId endPointId cruId /// with one line per link - mGBTIdToFeeId.clear(); + mLinkUniqueIdToGBTUniqueId.clear(); + mGBTUniqueIdToFeeId.clear(); + mGBTUniqueIdsInLink.clear(); std::ifstream inFile(filename); if (!inFile.is_open()) { return false; } std::string line, token; while (std::getline(inFile, line)) { - if (std::count(line.begin(), line.end(), ' ') < 3) { + int nSpaces = std::count(line.begin(), line.end(), ' '); + if (nSpaces < 3) { continue; } if (line.find('#') < line.find(' ')) { @@ -98,14 +118,22 @@ bool FEEIdConfig::load(const char* filename) std::stringstream ss; ss << line; std::getline(ss, token, ' '); - uint16_t feeId = std::atoi(token.c_str()); + uint16_t gbtUniqueId = std::atoi(token.c_str()); std::getline(ss, token, ' '); uint8_t linkId = std::atoi(token.c_str()); std::getline(ss, token, ' '); uint8_t endPointId = std::atoi(token.c_str()); std::getline(ss, token, ' '); uint16_t cruId = std::atoi(token.c_str()); - mGBTIdToFeeId[getGBTId(linkId, endPointId, cruId)] = feeId; + std::getline(ss, token, ' '); + uint16_t feeId = 2 * cruId + endPointId; + if (nSpaces > 3) { + feeId = std::atoi(token.c_str()); + std::getline(ss, token, ' '); + } + mLinkUniqueIdToGBTUniqueId[getLinkUniqueId(linkId, endPointId, cruId)] = gbtUniqueId; + mGBTUniqueIdToFeeId[gbtUniqueId] = feeId; + mGBTUniqueIdsInLink[feeId].emplace_back(gbtUniqueId); } inFile.close(); return true; @@ -115,8 +143,8 @@ void FEEIdConfig::write(const char* filename) const { /// Writes the FEE Ids to a configuration file std::ofstream outFile(filename); - for (auto& id : mGBTIdToFeeId) { - outFile << id.first << " " << (id.second & 0xFF) << " " << ((id.second >> 8) & 0xFF) << " " << ((id.second >> 16) & 0xFF) << std::endl; + for (auto& id : mLinkUniqueIdToGBTUniqueId) { + outFile << id.second << " " << getLinkId(id.first) << " " << getEndPointId(id.first) << " " << getCRUId(id.first) << " " << mGBTUniqueIdToFeeId.find(id.second)->second << std::endl; } outFile.close(); } diff --git a/Detectors/MUON/MID/Raw/src/GBTUserLogicEncoder.cxx b/Detectors/MUON/MID/Raw/src/GBTUserLogicEncoder.cxx index 247121de44a8f..e0005dc88391a 100644 --- a/Detectors/MUON/MID/Raw/src/GBTUserLogicEncoder.cxx +++ b/Detectors/MUON/MID/Raw/src/GBTUserLogicEncoder.cxx @@ -22,6 +22,13 @@ namespace o2 namespace mid { +void GBTUserLogicEncoder::setGBTUniqueId(uint16_t gbtUniqueId) +{ + /// Sets the information associated to the GBT unique ID + mCrateId = crateparams::getCrateIdFromGBTUniqueId(gbtUniqueId); + mOffset = 8 * crateparams::getGBTIdInCrate(gbtUniqueId); +} + void GBTUserLogicEncoder::addShort(std::vector& buffer, uint16_t shortWord) const { /// Adds a 16 bits word @@ -35,11 +42,11 @@ void GBTUserLogicEncoder::processTrigger(const InteractionRecord& ir, uint8_t tr auto& vec = mBoards[ir]; for (uint8_t ireg = 0; ireg < 2; ++ireg) { uint8_t firedLoc = (mMask >> (4 * ireg)) & 0xF; - vec.push_back({raw::sSTARTBIT, triggerWord, ireg, firedLoc}); + vec.push_back({raw::sSTARTBIT, triggerWord, static_cast(ireg + mOffset), firedLoc}); } for (uint8_t iloc = 0; iloc < 8; ++iloc) { if (mMask & (1 << iloc)) { - vec.push_back({raw::sSTARTBIT | raw::sCARDTYPE, triggerWord, static_cast(iloc + 8 * crateparams::getGBTIdInCrate(mFeeId)), 0}); + vec.push_back({raw::sSTARTBIT | raw::sCARDTYPE, triggerWord, static_cast(iloc + mOffset), 0}); if (triggerWord & (raw::sSOX | raw::sEOX)) { /// Write masks for (int ich = 0; ich < 4; ++ich) { @@ -59,7 +66,7 @@ void GBTUserLogicEncoder::addRegionalBoards(uint8_t activeBoards, InteractionRec for (uint8_t ireg = 0; ireg < 2; ++ireg) { uint8_t firedLoc = (activeBoards >> (4 * ireg)) & 0xF; if (firedLoc > 0) { - vec.push_back({raw::sSTARTBIT, 0, ireg, firedLoc}); + vec.push_back({raw::sSTARTBIT, 0, static_cast(ireg + mOffset), firedLoc}); } } } @@ -91,6 +98,7 @@ void GBTUserLogicEncoder::flush(std::vector& buffer, const InteractionReco buffer.emplace_back(loc.triggerWord); addShort(buffer, item.first.bc); buffer.emplace_back((raw::getLocId(loc.boardId) << 4) | loc.firedChambers); + buffer.emplace_back(mCrateId << 4); if (raw::isLoc(loc.statusWord)) { for (int ich = 4; ich >= 0; --ich) { if (loc.firedChambers & (1 << ich)) { diff --git a/Detectors/MUON/MID/Raw/src/GBTDecoder.cxx b/Detectors/MUON/MID/Raw/src/LinkDecoder.cxx similarity index 59% rename from Detectors/MUON/MID/Raw/src/GBTDecoder.cxx rename to Detectors/MUON/MID/Raw/src/LinkDecoder.cxx index 62d6a496522af..2064eeacb92ac 100644 --- a/Detectors/MUON/MID/Raw/src/GBTDecoder.cxx +++ b/Detectors/MUON/MID/Raw/src/LinkDecoder.cxx @@ -8,16 +8,18 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// \file MID/Raw/src/GBTDecoder.cxx +/// \file MID/Raw/src/LinkDecoder.cxx /// \brief Class interface for the MID GBT decoder /// \author Diego Stocco /// \date 07 November 2020 -#include "MIDRaw/GBTDecoder.h" +#include "MIDRaw/LinkDecoder.h" +#include "DataFormatsMID/ROBoard.h" +#include "MIDRaw/ELinkManager.h" #include "MIDRaw/FEEIdConfig.h" #include "MIDRaw/GBTOutputHandler.h" -#include "DataFormatsMID/ROBoard.h" +#include "MIDRaw/Utils.h" namespace o2 { @@ -25,12 +27,96 @@ namespace mid { namespace impl { + +class GBTUserLogicDecoderImplV2 +{ + public: + GBTUserLogicDecoderImplV2(uint16_t ulFeeId, bool isDebugMode = false, const ElectronicsDelay& electronicsDelay = ElectronicsDelay(), const FEEIdConfig& feeIdConfig = FEEIdConfig()) + { + mElinkManager.init(ulFeeId, isDebugMode, false, electronicsDelay, feeIdConfig); + mELinkDecoder.setBareDecoder(false); + } + + void operator()(gsl::span payload, uint32_t orbit, std::vector& data, std::vector& rofs) + { + /// Decodes the buffer + mElinkManager.set(orbit); + // for (auto& byte : payload) { + auto it = payload.begin(); + auto end = payload.end(); + while (it != end) { + if (mELinkDecoder.isZero(*it)) { + // The e-link decoder is empty, meaning that we expect a new board. + // The first byte of the board should have the STARTBIT on. + // If this is not the case, we move to the next byte. + // Notice that the payload has zeros until the end of the 256 bits word: + // a) when moving from the regional high to regional low + // b) at the end of the HBF + ++it; + continue; + } + + if (mELinkDecoder.add(it, end)) { + mElinkManager.onDone(mELinkDecoder, data, rofs); + mELinkDecoder.reset(); + } + } + } + + private: + ELinkDecoder mELinkDecoder{}; /// E-link decoder + ELinkManager mElinkManager{}; /// ELinkManager +}; + +class GBTUserLogicDecoderImplV1 +{ + public: + GBTUserLogicDecoderImplV1(uint16_t feeId, bool isDebugMode = false, const ElectronicsDelay& electronicsDelay = ElectronicsDelay()) + { + mCrateId = crateparams::getCrateIdFromGBTUniqueId(feeId); + mOffset = 8 * crateparams::getGBTIdInCrate(feeId); + mElinkManager.init(feeId, isDebugMode, true, electronicsDelay); + } + + void operator()(gsl::span payload, uint32_t orbit, std::vector& data, std::vector& rofs) + { + /// Decodes the buffer + mElinkManager.set(orbit); + // for (auto& byte : payload) { + auto it = payload.begin(); + auto end = payload.end(); + while (it != end) { + if (mELinkDecoder.isZero(*it)) { + // The e-link decoder is empty, meaning that we expect a new board. + // The first byte of the board should have the STARTBIT on. + // If this is not the case, we move to the next byte. + // Notice that the payload has zeros until the end of the 256 bits word: + // a) when moving from the regional high to regional low + // b) at the end of the HBF + ++it; + continue; + } + + if (mELinkDecoder.add(it, end)) { + mElinkManager.onDone(mELinkDecoder, mCrateId, mOffset + mELinkDecoder.getId() % 8, data, rofs); + mELinkDecoder.reset(); + } + } + } + + private: + uint8_t mCrateId{0}; /// Crate ID + uint8_t mOffset{0}; /// Loc ID offset + ELinkDecoder mELinkDecoder{}; /// E-link decoder + ELinkManager mElinkManager{}; /// ELinkManager +}; + class GBTUserLogicDecoderImpl { public: - GBTUserLogicDecoderImpl(uint16_t feeId, bool isDebugMode = false, uint8_t mask = 0xFF, const ElectronicsDelay& electronicsDelay = ElectronicsDelay()) + GBTUserLogicDecoderImpl(uint16_t feeId, bool isDebugMode = false, const ElectronicsDelay& electronicsDelay = ElectronicsDelay()) { - mOutputHandler.setFeeId(feeId); + mOutputHandler.setGBTUniqueId(feeId); mOutputHandler.setElectronicsDelay(electronicsDelay); if (isDebugMode) { mOnDoneLoc = &GBTOutputHandler::onDoneLocDebug; @@ -80,13 +166,108 @@ class GBTUserLogicDecoderImpl OnDoneFunction mOnDoneReg{&GBTOutputHandler::onDoneReg}; ///! Processes the regional board }; +class GBTBareDecoderImplV1 +{ + public: + GBTBareDecoderImplV1(uint16_t feeId, bool isDebugMode = false, uint8_t mask = 0xFF, const ElectronicsDelay& electronicsDelay = ElectronicsDelay()) : mIsDebugMode(isDebugMode), mMask(mask) + { + /// Constructors + mElinkManager.init(feeId, isDebugMode, true, electronicsDelay); + auto crateId = crateparams::getCrateIdFromGBTUniqueId(feeId); + auto offset = 8 * crateparams::getGBTIdInCrate(feeId); + for (int ilink = 0; ilink < 10; ++ilink) { + mBoardUniqueIds.emplace_back(raw::makeUniqueLocID(crateId, offset + ilink % 8)); + } + } + + void operator()(gsl::span payload, uint32_t orbit, std::vector& data, std::vector& rofs) + { + /// Decodes the buffer + mElinkManager.set(orbit); + mData = &data; + mROFs = &rofs; + + uint8_t byte = 0; + size_t ilink = 0, linkMask = 0, byteOffset = 0; + + for (int ireg = 0; ireg < 2; ++ireg) { + byteOffset = 5 * ireg; + if (mIsDebugMode) { + ilink = 8 + ireg; + linkMask = (1 << ilink); + for (size_t idx = byteOffset + 4; idx < payload.size(); idx += 16) { + byte = payload[idx]; + if ((mIsFeeding & linkMask) || byte) { + processRegDebug(ilink, byte); + } + } + } + for (int ib = 0; ib < 4; ++ib) { + ilink = ib + 4 * ireg; + linkMask = (1 << ilink); + if (mMask & linkMask) { + for (size_t idx = byteOffset + ib; idx < payload.size(); idx += 16) { + byte = payload[idx]; + if ((mIsFeeding & linkMask) || byte) { + processLoc(ilink, byte); + } + } + } + } + } + } + + private: + void processLoc(size_t ilink, uint8_t byte) + { + /// Processes the local board information + auto& decoder = mElinkManager.getDecoder(mBoardUniqueIds[ilink], true); + if (decoder.getNBytes() > 0) { + decoder.addAndComputeSize(byte); + if (decoder.isComplete()) { + mElinkManager.onDone(decoder, mBoardUniqueIds[ilink], *mData, *mROFs); + decoder.reset(); + mIsFeeding &= (~(1 << ilink)); + } + } else if ((byte & (raw::sSTARTBIT | raw::sCARDTYPE)) == (raw::sSTARTBIT | raw::sCARDTYPE)) { + decoder.add(byte); + mIsFeeding |= (1 << ilink); + } + } + + void processRegDebug(size_t ilink, uint8_t byte) + { + /// Processes the regional board information in debug mode + auto& decoder = mElinkManager.getDecoder(mBoardUniqueIds[ilink], false); + if (decoder.getNBytes() > 0) { + decoder.add(byte); + if (decoder.isComplete()) { + mElinkManager.onDone(decoder, mBoardUniqueIds[ilink], *mData, *mROFs); + decoder.reset(); + mIsFeeding &= (~(1 << ilink)); + } + } else if (byte & raw::sSTARTBIT) { + decoder.add(byte); + mIsFeeding |= (1 << ilink); + } + } + + bool mIsDebugMode{false}; /// Debug mode + uint8_t mMask{0xFF}; /// GBT mask + uint16_t mIsFeeding{0}; /// Flag to check if the e-link is feeding + ELinkManager mElinkManager{}; /// ELinkManager + std::vector mBoardUniqueIds{}; /// Unique board IDs + std::vector* mData{nullptr}; ///! Data not owner + std::vector* mROFs{nullptr}; ///! ROFRecords not owner +}; + class GBTBareDecoderImpl { public: GBTBareDecoderImpl(uint16_t feeId, bool isDebugMode = false, uint8_t mask = 0xFF, const ElectronicsDelay& electronicsDelay = ElectronicsDelay()) : mIsDebugMode(isDebugMode), mMask(mask) { /// Constructor - mOutputHandler.setFeeId(feeId); + mOutputHandler.setGBTUniqueId(feeId); mOutputHandler.setElectronicsDelay(electronicsDelay); if (isDebugMode) { mOnDoneLoc = &GBTOutputHandler::onDoneLocDebug; @@ -183,7 +364,7 @@ class GBTBareDecoderLinkImpl GBTBareDecoderLinkImpl(uint16_t feeId, bool isDebugMode = false, uint8_t mask = 0xFF, const ElectronicsDelay& electronicsDelay = ElectronicsDelay()) : mIsDebugMode(isDebugMode), mMask(mask) { /// Constructor - mOutputHandler.setFeeId(feeId); + mOutputHandler.setGBTUniqueId(feeId); mOutputHandler.setElectronicsDelay(electronicsDelay); mIsDebugMode = isDebugMode; if (isDebugMode) { @@ -269,7 +450,7 @@ class GBTBareDecoderInsertImpl GBTBareDecoderInsertImpl(uint16_t feeId, bool isDebugMode = false, uint8_t mask = 0xFF, const ElectronicsDelay& electronicsDelay = ElectronicsDelay()) : mIsDebugMode(isDebugMode), mMask(mask) { /// Constructor - mOutputHandler.setFeeId(feeId); + mOutputHandler.setGBTUniqueId(feeId); mOutputHandler.setElectronicsDelay(electronicsDelay); if (isDebugMode) { mOnDoneLoc = &GBTOutputHandler::onDoneLocDebug; @@ -334,28 +515,38 @@ class GBTBareDecoderInsertImpl } // namespace impl -void GBTDecoder::process(gsl::span payload, uint32_t orbit, std::vector& data, std::vector& rofs) +void LinkDecoder::process(gsl::span payload, uint32_t orbit, std::vector& data, std::vector& rofs) { /// Decodes the data mDecode(payload, orbit, data, rofs); } -std::unique_ptr createGBTDecoder(const o2::header::RDHAny& rdh, uint16_t feeId, bool isDebugMode, uint8_t mask, const ElectronicsDelay& electronicsDelay) +std::unique_ptr createGBTDecoder(const o2::header::RDHAny& rdh, uint16_t feeId, bool isDebugMode, uint8_t mask, const ElectronicsDelay& electronicsDelay) +{ + /// Creates the correct implementation of the GBT decoder + if (raw::isBare(rdh)) { + return std::make_unique(impl::GBTBareDecoderImplV1(feeId, isDebugMode, mask, electronicsDelay)); + } + std::cout << "Error: GBT decoder not defined for UL. Please use Link decoder instead" << std::endl; + return nullptr; +} + +std::unique_ptr createLinkDecoder(const o2::header::RDHAny& rdh, uint16_t feeId, bool isDebugMode, uint8_t mask, const ElectronicsDelay& electronicsDelay, const FEEIdConfig& feeIdConfig) { /// Creates the correct implementation of the GBT decoder - if (o2::raw::RDHUtils::getLinkID(rdh) == raw::sUserLogicLinkID) { - return std::make_unique(impl::GBTUserLogicDecoderImpl(feeId, isDebugMode, mask, electronicsDelay)); + if (raw::isBare(rdh)) { + return std::make_unique(impl::GBTBareDecoderImplV1(feeId, isDebugMode, mask, electronicsDelay)); } - return std::make_unique(impl::GBTBareDecoderImpl(feeId, isDebugMode, mask, electronicsDelay)); + return std::make_unique(impl::GBTUserLogicDecoderImplV2(feeId, isDebugMode, electronicsDelay, feeIdConfig)); } -std::unique_ptr createGBTDecoder(uint16_t feeId, bool isBare, bool isDebugMode, uint8_t mask, const ElectronicsDelay& electronicsDelay) +std::unique_ptr createLinkDecoder(uint16_t feeId, bool isBare, bool isDebugMode, uint8_t mask, const ElectronicsDelay& electronicsDelay, const FEEIdConfig& feeIdConfig) { /// Creates the correct implementation of the GBT decoder if (isBare) { - return std::make_unique(impl::GBTBareDecoderImpl(feeId, isDebugMode, mask, electronicsDelay)); + return std::make_unique(impl::GBTBareDecoderImplV1(feeId, isDebugMode, mask, electronicsDelay)); } - return std::make_unique(impl::GBTUserLogicDecoderImpl(feeId, isDebugMode, mask, electronicsDelay)); + return std::make_unique(impl::GBTUserLogicDecoderImplV2(feeId, isDebugMode, electronicsDelay, feeIdConfig)); } } // namespace mid diff --git a/Detectors/MUON/MID/Raw/test/bench_Raw.cxx b/Detectors/MUON/MID/Raw/test/bench_Raw.cxx index 3a4c11180d5cb..4ebc6145da42a 100644 --- a/Detectors/MUON/MID/Raw/test/bench_Raw.cxx +++ b/Detectors/MUON/MID/Raw/test/bench_Raw.cxx @@ -23,7 +23,7 @@ #include "MIDBase/DetectorParameters.h" #include "MIDRaw/Decoder.h" #include "MIDRaw/Encoder.h" -#include "MIDRaw/GBTDecoder.h" +#include "MIDRaw/LinkDecoder.h" o2::mid::ColumnData getColData(uint8_t deId, uint8_t columnId, uint16_t nbp = 0, uint16_t bp1 = 0, uint16_t bp2 = 0, uint16_t bp3 = 0, uint16_t bp4 = 0) { @@ -122,9 +122,9 @@ static void BM_Decoder(benchmark::State& state) state.counters["num"] = benchmark::Counter(num, benchmark::Counter::kIsRate); } -static void BM_GBTDecoder(benchmark::State& state) +static void BM_LinkDecoder(benchmark::State& state) { - auto decoder = o2::mid::createGBTDecoder(0); + auto decoder = o2::mid::createLinkDecoder(0); int nTF = state.range(0); int nEventPerTF = state.range(1); @@ -164,7 +164,7 @@ static void CustomArguments(benchmark::internal::Benchmark* bench) bench->Args({1, 100, 4}); } -BENCHMARK(BM_GBTDecoder)->Apply(CustomArguments)->Unit(benchmark::kNanosecond); +BENCHMARK(BM_LinkDecoder)->Apply(CustomArguments)->Unit(benchmark::kNanosecond); BENCHMARK(BM_Decoder)->Apply(CustomArguments)->Unit(benchmark::kNanosecond); BENCHMARK_MAIN(); diff --git a/Detectors/MUON/MID/Raw/test/testRaw.cxx b/Detectors/MUON/MID/Raw/test/testRaw.cxx index 76e8b44a631e7..5981278bc1d5f 100644 --- a/Detectors/MUON/MID/Raw/test/testRaw.cxx +++ b/Detectors/MUON/MID/Raw/test/testRaw.cxx @@ -32,9 +32,9 @@ #include "MIDRaw/CrateParameters.h" #include "MIDRaw/DecodedDataAggregator.h" #include "MIDRaw/Decoder.h" -#include "MIDRaw/GBTDecoder.h" -#include "MIDRaw/GBTUserLogicEncoder.h" #include "MIDRaw/Encoder.h" +#include "MIDRaw/GBTUserLogicEncoder.h" +#include "MIDRaw/LinkDecoder.h" BOOST_AUTO_TEST_SUITE(o2_mid_raw) @@ -193,9 +193,9 @@ BOOST_AUTO_TEST_CASE(GBTUserLogicDecoder) uint8_t crateId = 5; uint8_t linkInCrate = 0; - uint16_t feeId = o2::mid::crateparams::makeGBTUniqueId(crateId, linkInCrate); + uint16_t gbtUniqueId = o2::mid::crateparams::makeGBTUniqueId(crateId, linkInCrate); o2::mid::GBTUserLogicEncoder encoder; - encoder.setFeeId(feeId); + encoder.setGBTUniqueId(gbtUniqueId); for (auto& item : inData) { encoder.process(item.second, o2::InteractionRecord(item.first, 0)); } @@ -204,9 +204,10 @@ BOOST_AUTO_TEST_CASE(GBTUserLogicDecoder) o2::header::RAWDataHeader rdh; auto memSize = buf.size() + 64; rdh.word1 |= (memSize | (memSize << 16)); - // Sets the feeId - rdh.word0 |= ((5 * 2) << 16); - auto decoder = o2::mid::createGBTDecoder(feeId); + // Sets the linkId + uint16_t feeId = gbtUniqueId / 8; + rdh.word0 |= (feeId << 16); + auto decoder = o2::mid::createLinkDecoder(feeId); std::vector data; std::vector rofs; std::vector convertedBuffer(buf.size()); diff --git a/Detectors/MUON/MID/Workflow/src/RawGBTDecoderSpec.cxx b/Detectors/MUON/MID/Workflow/src/RawGBTDecoderSpec.cxx index c6289dc59780e..10fa9a3afd067 100644 --- a/Detectors/MUON/MID/Workflow/src/RawGBTDecoderSpec.cxx +++ b/Detectors/MUON/MID/Workflow/src/RawGBTDecoderSpec.cxx @@ -28,9 +28,9 @@ #include "Framework/Task.h" #include "Headers/RDHAny.h" #include "DetectorsRaw/RDHUtils.h" -#include "DataFormatsMID/ROFRecord.h" -#include "MIDRaw/GBTDecoder.h" #include "DataFormatsMID/ROBoard.h" +#include "DataFormatsMID/ROFRecord.h" +#include "MIDRaw/LinkDecoder.h" namespace o2 { @@ -89,7 +89,7 @@ class RawGBTDecoderDeviceDPL } private: - std::unique_ptr mDecoder{nullptr}; + std::unique_ptr mDecoder{nullptr}; bool mIsDebugMode{false}; std::vector mFeeIds{}; CrateMasks mCrateMasks{}; From 19767f9a7494420049020347243056fd54838355 Mon Sep 17 00:00:00 2001 From: Laurent Aphecetche Date: Tue, 20 Apr 2021 10:02:12 +0200 Subject: [PATCH 176/770] [MCH] :hammer: Small utility to export mapping to a simple Root tree (#5906) --- Detectors/MUON/MCH/Mapping/cli/CMakeLists.txt | 13 ++ .../MUON/MCH/Mapping/cli/export-to-tree.cxx | 140 ++++++++++++++++++ 2 files changed, 153 insertions(+) create mode 100644 Detectors/MUON/MCH/Mapping/cli/export-to-tree.cxx diff --git a/Detectors/MUON/MCH/Mapping/cli/CMakeLists.txt b/Detectors/MUON/MCH/Mapping/cli/CMakeLists.txt index 558df952a47d6..da89f1b4a4f28 100644 --- a/Detectors/MUON/MCH/Mapping/cli/CMakeLists.txt +++ b/Detectors/MUON/MCH/Mapping/cli/CMakeLists.txt @@ -14,3 +14,16 @@ foreach(impl RANGE 3 4) COMPONENT_NAME mch PUBLIC_LINK_LIBRARIES O2::MCHMappingImpl${impl} Boost::program_options) endforeach() + +foreach(impl RANGE 3 4) + o2_add_executable(mapping-export-to-tree${impl} + SOURCES export-to-tree.cxx + COMPONENT_NAME mch + PUBLIC_LINK_LIBRARIES O2::MCHMappingImpl${impl} Boost::program_options + ROOT::Tree + TARGETVARNAME targetName) + if(impl EQUAL 3) + target_compile_definitions(${targetName} PRIVATE RUN2) + endif() +endforeach() + diff --git a/Detectors/MUON/MCH/Mapping/cli/export-to-tree.cxx b/Detectors/MUON/MCH/Mapping/cli/export-to-tree.cxx new file mode 100644 index 0000000000000..c49e69003233f --- /dev/null +++ b/Detectors/MUON/MCH/Mapping/cli/export-to-tree.cxx @@ -0,0 +1,140 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "MCHMappingInterface/Segmentation.h" +#include +#include +#include +#include +#include +#include + +namespace po = boost::program_options; +using namespace o2::mch::mapping; + +#ifdef RUN2 +constexpr bool run2{true}; +#else +constexpr bool run2{false}; +#endif + +constexpr int MaxNofPadsPerDE{28672}; +struct DePads { + int nDePad; + int deid; + int dsid[MaxNofPadsPerDE]; + int dsch[MaxNofPadsPerDE]; + float x[MaxNofPadsPerDE]; + float y[MaxNofPadsPerDE]; + float dx[MaxNofPadsPerDE]; + float dy[MaxNofPadsPerDE]; +}; + +void createPadBranches(TTree& tree, DePads& depads) +{ + tree.Branch("nDePad", &depads.nDePad, "nDePad/I") + ->SetTitle("Number of pads in detection element"); + tree.Branch("deid", &depads.deid, "deid/I") + ->SetTitle("Detection element id"); + tree.Branch(fmt::format("DePad_{}", run2 ? "manu" : "dsid").c_str(), + &depads.dsid, + fmt::format("DePad_{}[nDePad]/I", run2 ? "manu" : "dsid").c_str()) + ->SetTitle("FEE id of n-th pad of this detection element (cm)"); + tree.Branch(fmt::format("DePad_{}", run2 ? "ch" : "dsch").c_str(), + &depads.dsch, + fmt::format("DePad_{}[nDePad]/I", run2 ? "ch" : "dsch").c_str()) + ->SetTitle("FEE channel of n-th pad of this detection element (cm)"); + tree.Branch("DePad_x", &depads.x, "DePad_x[nDePad]/F") + ->SetTitle("x position of n-th pad of this detection element (cm)"); + tree.Branch("DePad_y", &depads.y, "DePad_y[nDePad]/F") + ->SetTitle("y position of n-th pad of this detection element (cm)"); + tree.Branch("DePad_dx", &depads.dx, "DePad_dx[nDePad]/F") + ->SetTitle("half size in x direction of n-th pad of this detection element (cm)"); + tree.Branch("DePad_dy", &depads.dy, "DePad_dy[nDePad]/F") + ->SetTitle("half size in y direction of n-th pad of this detection element (cm)"); +} + +/** + * This small program creates a Root TTree with MCH mapping. + * + * There is one entry per MCH detection element, describing the + * basic features of all the pads of that detection element : + * + * - electronic location : FEE board id (aka dual sampa id + * and FEE channel id (aka dual sampa channel) + * - geometric location : (x,y) positions (cm) within the detection element + * - geometric size : (dx,dy) half-sizes (cm) + * + */ + +int main(int argc, char** argv) +{ + std::string outputFileName; + po::variables_map vm; + po::options_description options("options"); + std::string defaultName = fmt::format("mch-mapping{}-tree.root", run2 ? "-run2" : ""); + // clang-format off + options.add_options() + ("help,h", "produce help message") + ("outfile,o",po::value(&outputFileName)->default_value(defaultName),"path to output file") + ; + // clang-format on + + po::options_description cmdline; + cmdline.add(options); + + po::store(po::command_line_parser(argc, argv).options(cmdline).run(), vm); + + if (vm.count("help")) { + std::cout << fmt::format("This program exports the MCH {}mapping to a Root tree\n", + run2 ? "(Run2 version) " : ""); + std::cout << " --outfile path to the output file containing the Root tree"; + std::cout << options << "\n"; + return 2; + } + + try { + po::notify(vm); + } catch (boost::program_options::error& e) { + std::cout << "Error: " << e.what() << "\n"; + exit(1); + } + + TFile fout(outputFileName.c_str(), "RECREATE"); + if (!fout.IsOpen()) { + std::cout << "Cannot open output file " << outputFileName << "\n"; + exit(2); + } + + TTree tree("mchpads", "Muon Chamber Pads"); + DePads depads; + createPadBranches(tree, depads); + + forEachDetectionElement([&depads, &tree](int deid) { + Segmentation seg{deid}; + if (seg.nofPads() > MaxNofPadsPerDE) { + throw std::logic_error(fmt::format("Something is wrong : max number of pads should be below {} but got {}", MaxNofPadsPerDE, seg.nofPads())); + } + depads.nDePad = seg.nofPads(); + depads.deid = deid; + for (auto padid = 0; padid < depads.nDePad; padid++) { + depads.dsid[padid] = seg.padDualSampaId(padid); + depads.dsch[padid] = seg.padDualSampaChannel(padid); + depads.x[padid] = seg.padPositionX(padid); + depads.y[padid] = seg.padPositionY(padid); + depads.dx[padid] = seg.padSizeX(padid) / 2.0; + depads.dy[padid] = seg.padSizeY(padid) / 2.0; + } + tree.Fill(); + }); + + tree.Write(); + return 0; +} From 95db79b23a55ec5e0ba6f5cf18b3b9ae7ddc6dc4 Mon Sep 17 00:00:00 2001 From: Laurent Aphecetche Date: Sat, 17 Apr 2021 10:47:14 +0200 Subject: [PATCH 177/770] [MRRTF-116] [MCH] Make digit binary files 100% reproducibles --- .../MUON/MCH/DevIO/Digits/CMakeLists.txt | 2 + Detectors/MUON/MCH/DevIO/Digits/DigitD0.h | 10 +- .../MUON/MCH/DevIO/Digits/DigitFileFormat.cxx | 6 +- .../MUON/MCH/DevIO/Digits/DigitFileFormat.h | 2 +- Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.cxx | 5 +- Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.cxx | 9 +- Detectors/MUON/MCH/DevIO/Digits/DigitIOV2.cxx | 110 ++++++++++++ Detectors/MUON/MCH/DevIO/Digits/DigitIOV2.h | 58 +++++++ Detectors/MUON/MCH/DevIO/Digits/DigitIOV3.cxx | 159 ++++++++++++++++++ Detectors/MUON/MCH/DevIO/Digits/DigitIOV3.h | 42 +++++ .../MUON/MCH/DevIO/Digits/DigitReaderImpl.cxx | 31 +--- .../MUON/MCH/DevIO/Digits/DigitReaderImpl.h | 24 --- .../MUON/MCH/DevIO/Digits/DigitWriterImpl.cxx | 7 + .../MUON/MCH/DevIO/Digits/DigitWriterImpl.h | 13 -- Detectors/MUON/MCH/DevIO/Digits/IO.cxx | 45 +++++ Detectors/MUON/MCH/DevIO/Digits/IO.h | 22 +++ Detectors/MUON/MCH/DevIO/Digits/IOStruct.h | 52 ++++++ .../MUON/MCH/DevIO/Digits/testDigitIO.cxx | 32 +++- .../MUON/MCH/DevIO/Digits/testDigitIOV0.cxx | 2 + 19 files changed, 551 insertions(+), 80 deletions(-) create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitIOV2.cxx create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitIOV2.h create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitIOV3.cxx create mode 100644 Detectors/MUON/MCH/DevIO/Digits/DigitIOV3.h create mode 100644 Detectors/MUON/MCH/DevIO/Digits/IO.cxx create mode 100644 Detectors/MUON/MCH/DevIO/Digits/IO.h create mode 100644 Detectors/MUON/MCH/DevIO/Digits/IOStruct.h diff --git a/Detectors/MUON/MCH/DevIO/Digits/CMakeLists.txt b/Detectors/MUON/MCH/DevIO/Digits/CMakeLists.txt index 8bee62acd48b2..1b03dad18be6f 100644 --- a/Detectors/MUON/MCH/DevIO/Digits/CMakeLists.txt +++ b/Detectors/MUON/MCH/DevIO/Digits/CMakeLists.txt @@ -12,6 +12,8 @@ o2_add_library(MCHDigitIO SOURCES DigitWriter.cxx DigitReader.cxx DigitFileFormat.cxx DigitReaderImpl.cxx DigitWriterImpl.cxx DigitIOV0.cxx DigitIOV1.cxx + DigitIOV2.cxx DigitIOV3.cxx + IO.cxx PUBLIC_LINK_LIBRARIES ms_gsl::ms_gsl fmt::fmt O2::DataFormatsMCH) o2_add_test(digits-io diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitD0.h b/Detectors/MUON/MCH/DevIO/Digits/DigitD0.h index 6986b16ba016c..5a9c097ca58dc 100644 --- a/Detectors/MUON/MCH/DevIO/Digits/DigitD0.h +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitD0.h @@ -16,11 +16,11 @@ namespace o2::mch::io::impl { struct DigitD0 { - int32_t tfTime; /// time since the beginning of the time frame, in bunch crossing units - uint16_t nofSamples; /// number of samples in the signal + saturated bit - int detID; /// ID of the Detection Element to which the digit corresponds to - int padID; /// PadIndex to which the digit corresponds to - uint32_t adc; /// Amplitude of signal + int32_t tfTime{0}; /// time since the beginning of the time frame, in bunch crossing units + uint16_t nofSamples{0}; /// number of samples in the signal + saturated bit + int detID{0}; /// ID of the Detection Element to which the digit corresponds to + int padID{0}; /// PadIndex to which the digit corresponds to + uint32_t adc{0}; /// Amplitude of signal void setNofSamples(uint16_t n) { nofSamples = (nofSamples & 0x8000) + (n & 0x7FFF); } uint16_t getNofSamples() const { return (nofSamples & 0x7FFF); } diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitFileFormat.cxx b/Detectors/MUON/MCH/DevIO/Digits/DigitFileFormat.cxx index 4ad0ff8463f94..4ae0f8fd72a3b 100644 --- a/Detectors/MUON/MCH/DevIO/Digits/DigitFileFormat.cxx +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitFileFormat.cxx @@ -17,9 +17,11 @@ namespace o2::mch::io { -std::array digitFileFormats = { +std::array digitFileFormats = { DigitFileFormat{2305844383603244847}, - DigitFileFormat{1224998065220435759}}; + DigitFileFormat{1224998065220435759}, + DigitFileFormat{63069292639436591}, + DigitFileFormat{1215990797246349103}}; std::ostream& operator<<(std::ostream& os, const DigitFileFormat& dff) { diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitFileFormat.h b/Detectors/MUON/MCH/DevIO/Digits/DigitFileFormat.h index 7663e7a34ab77..4ea2a627bcc4c 100644 --- a/Detectors/MUON/MCH/DevIO/Digits/DigitFileFormat.h +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitFileFormat.h @@ -36,7 +36,7 @@ struct DigitFileFormat { }; }; -extern std::array digitFileFormats; +extern std::array digitFileFormats; std::ostream& operator<<(std::ostream&, const DigitFileFormat&); diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.cxx b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.cxx index 37e68ac461760..18f0856a1c2d9 100644 --- a/Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.cxx +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV0.cxx @@ -18,6 +18,7 @@ #include #include "DigitFileFormat.h" #include "CommonDataFormat/InteractionRecord.h" +#include "IOStruct.h" // // V0 was prior to the introduction of rofs, so the file format is @@ -50,7 +51,7 @@ bool DigitReaderV0::read(std::istream& in, // note the input vectors are not cleared as this is the responsability // of the calling class, if need be. std::vector digitsd0; - bool ok = readBinary(in, digitsd0, "digits"); + bool ok = readBinaryStruct(in, digitsd0, "digits"); if (!ok) { return false; } @@ -84,7 +85,7 @@ bool DigitWriterV0::write(std::ostream& out, digitsd0.back().setSaturated(d.isSaturated()); } gsl::span d0(digitsd0); - bool ok = binary(out, d0); + bool ok = writeBinaryStruct(out, d0); if (!ok) { return false; } diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.cxx b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.cxx index 6956934b607f9..e6e6bc137873b 100644 --- a/Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.cxx +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV1.cxx @@ -15,6 +15,7 @@ #include "DigitFileFormat.h" #include "DigitReader.h" #include +#include "IOStruct.h" namespace { @@ -55,13 +56,13 @@ bool DigitReaderV1::read(std::istream& in, // note the input vectors are not cleared as this is the responsability // of the calling class, if need be. - bool ok = readBinary(in, rofs, "rofs"); + bool ok = readBinaryStruct(in, rofs, "rofs"); if (!ok) { return false; } std::vector digitsd0; - ok = readBinary(in, digitsd0, "digits"); + ok = readBinaryStruct(in, digitsd0, "digits"); if (!ok) { return false; } @@ -85,7 +86,7 @@ bool DigitWriterV1::write(std::ostream& out, if (rofs.empty()) { return false; } - bool ok = impl::binary(out, rofs); + bool ok = writeBinaryStruct(out, rofs); std::vector digitsd0; for (const auto& d : digits) { @@ -93,7 +94,7 @@ bool DigitWriterV1::write(std::ostream& out, digitsd0.back().setSaturated(d.isSaturated()); } gsl::span d0(digitsd0); - ok &= impl::binary(out, d0); + ok &= writeBinaryStruct(out, d0); return ok; } diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitIOV2.cxx b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV2.cxx new file mode 100644 index 0000000000000..5fc579eab29a8 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV2.cxx @@ -0,0 +1,110 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "DigitIOV2.h" +#include +#include +#include "DataFormatsMCH/Digit.h" +#include "DataFormatsMCH/ROFRecord.h" +#include +#include +#include "DigitFileFormat.h" +#include "CommonDataFormat/InteractionRecord.h" +#include "IO.h" + +// +// V2 was prior to the introduction of rofs, so the file format is +// simply a set of consecutive [nofDigits|list of digits] blocks +// + +namespace o2::mch::io::impl +{ +void DigitReaderV2::count(std::istream& in, size_t& ntfs, size_t& nrofs, size_t& ndigits) +{ + auto dff = digitFileFormats[2]; + rewind(in); + ndigits = 0; + nrofs = 0; + ntfs = 0; + int ndig{0}; + + while ((ndig = advance(in, dff.digitSize, "digits")) >= 0) { + ndigits += ndig; + ++nrofs; + ++ntfs; + } + rewind(in); +} + +bool DigitReaderV2::read(std::istream& in, + std::vector& digits, + std::vector& rofs) +{ + if (in.peek() == EOF) { + return false; + } + // note the input vectors are not cleared as this is the responsability + // of the calling class, if need be. + int ndigits = readNofItems(in, "digits"); + + for (int i = 0; i < ndigits; i++) { + uint32_t tfTime; + uint16_t nofSamples; + uint8_t sat; + uint32_t deID; + uint32_t padID; + uint32_t adc; + in.read(reinterpret_cast(&tfTime), sizeof(uint32_t)); + in.read(reinterpret_cast(&nofSamples), sizeof(uint16_t)); + in.read(reinterpret_cast(&sat), sizeof(uint8_t)); + in.read(reinterpret_cast(&deID), sizeof(uint32_t)); + in.read(reinterpret_cast(&padID), sizeof(uint32_t)); + in.read(reinterpret_cast(&adc), sizeof(uint32_t)); + digits.emplace_back(deID, padID, adc, tfTime, nofSamples, sat > 0); + } + + rofs.emplace_back(o2::InteractionRecord(0, mCurrentROF), 0, ndigits); + ++mCurrentROF; + return !in.fail(); +} + +void DigitReaderV2::rewind(std::istream& in) +{ + DigitReaderImpl::rewind(in); + mCurrentROF = 0; +} + +bool DigitWriterV2::write(std::ostream& out, + gsl::span digits, + gsl::span rofs) +{ + // V2 format had no notion of rofs, so we strip them + for (auto r : rofs) { + writeNofItems(out, r.getNEntries()); + for (int i = r.getFirstIdx(); i <= r.getLastIdx(); i++) { + const Digit& d = digits[i]; + uint32_t tfTime = d.getTime(); + uint16_t nofSamples = d.getNofSamples(); + uint32_t deID = d.getDetID(); + uint32_t padID = d.getPadID(); + uint32_t adc = d.getADC(); + uint8_t sat = d.isSaturated(); + out.write(reinterpret_cast(&tfTime), sizeof(uint32_t)); + out.write(reinterpret_cast(&nofSamples), sizeof(uint16_t)); + out.write(reinterpret_cast(&sat), sizeof(uint8_t)); + out.write(reinterpret_cast(&deID), sizeof(uint32_t)); + out.write(reinterpret_cast(&padID), sizeof(uint32_t)); + out.write(reinterpret_cast(&adc), sizeof(uint32_t)); + } + } + return !out.fail(); +} + +} // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitIOV2.h b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV2.h new file mode 100644 index 0000000000000..27a88a73df1be --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV2.h @@ -0,0 +1,58 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#pragma once + +#include "DigitReaderImpl.h" +#include "DigitWriterImpl.h" +#include +#include + +/* + * Digit file format 0 is storing Digits version D0 + * with no ROF (i.e. just a set of nDigits|DigitsD0|...) + */ + +namespace o2::mch::io::impl +{ +/** + * Reader for digit file format 0 + */ +class DigitReaderV2 : public DigitReaderImpl +{ + public: + void count(std::istream& in, size_t& ntfs, size_t& nrofs, size_t& ndigits) override; + bool read(std::istream& in, + std::vector& digits, + std::vector& rofs) override; + void rewind(std::istream& in); + + private: + int mCurrentROF{0}; +}; + +/** + * Writer for digit file format 0 + */ +struct DigitWriterV2 : public DigitWriterImpl { + + /** write rofs, digits at the current position in the output stream + * @param digits vector of Digits, must not be empty + * @param rofs vector of ROFRecord, might be empty + * @returns true if writing was successull, false otherwise + */ + bool write(std::ostream& out, + gsl::span digits, + gsl::span rofs) override; + + bool mBinary; +}; + +} // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitIOV3.cxx b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV3.cxx new file mode 100644 index 0000000000000..4b22cc7481903 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV3.cxx @@ -0,0 +1,159 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "DigitIOV3.h" +#include "DataFormatsMCH/Digit.h" +#include "DataFormatsMCH/ROFRecord.h" +#include "DigitFileFormat.h" +#include "DigitReader.h" +#include +#include "IOStruct.h" + +namespace o2::mch::io::impl +{ +std::pair advanceOneEvent(std::istream& in) +{ + auto dff = digitFileFormats[3]; + int nrofs = advance(in, dff.rofSize, "rofs"); + if (nrofs < 0) { + return std::make_pair(-1, -1); + } + int ndigits = advance(in, dff.digitSize, "digits"); + return std::make_pair(nrofs, ndigits); +} + +void DigitReaderV3::count(std::istream& in, size_t& ntfs, size_t& nrofs, size_t& ndigits) +{ + rewind(in); + ndigits = 0; + nrofs = 0; + ntfs = 0; + std::pair pairs; + std::pair invalid{-1, -1}; + + while ((pairs = advanceOneEvent(in)) != invalid) { + ndigits += pairs.second; + nrofs += pairs.first; + ++ntfs; + } + rewind(in); +} + +bool DigitReaderV3::read(std::istream& in, + std::vector& digits, + std::vector& rofs) +{ + if (in.peek() == EOF) { + return false; + } + // note the input vectors are not cleared as this is the responsability + // of the calling class, if need be. + + int nrofs = readNofItems(in, "rofs"); + if (in.fail()) { + return false; + } + + for (auto i = 0; i < nrofs; i++) { + uint16_t bc; + uint32_t orbit; + uint32_t firstIdx; + uint32_t nentries; + in.read(reinterpret_cast(&bc), sizeof(uint16_t)); + in.read(reinterpret_cast(&orbit), sizeof(uint32_t)); + in.read(reinterpret_cast(&firstIdx), sizeof(uint32_t)); + in.read(reinterpret_cast(&nentries), sizeof(uint32_t)); + rofs.emplace_back(o2::InteractionRecord{bc, orbit}, firstIdx, nentries); + if (in.fail()) { + return false; + } + } + + int ndigits = readNofItems(in, "digits"); + if (in.fail()) { + return false; + } + + for (int i = 0; i < ndigits; i++) { + uint32_t tfTime; + uint16_t nofSamples; + uint32_t deID; + uint32_t padID; + uint32_t adc; + uint8_t sat; + in.read(reinterpret_cast(&tfTime), sizeof(uint32_t)); + in.read(reinterpret_cast(&nofSamples), sizeof(uint16_t)); + in.read(reinterpret_cast(&sat), sizeof(uint8_t)); + in.read(reinterpret_cast(&deID), sizeof(uint32_t)); + in.read(reinterpret_cast(&padID), sizeof(uint32_t)); + in.read(reinterpret_cast(&adc), sizeof(uint32_t)); + digits.emplace_back(deID, padID, adc, tfTime, nofSamples, sat > 0); + if (in.fail()) { + return false; + } + } + return true; +} + +void DigitReaderV3::rewind(std::istream& in) +{ + DigitReaderImpl::rewind(in); +} + +bool DigitWriterV3::write(std::ostream& out, + gsl::span digits, + gsl::span rofs) +{ + if (rofs.empty()) { + return false; + } + writeNofItems(out, rofs.size()); + if (out.fail()) { + return false; + } + for (auto r : rofs) { + uint16_t bc = r.getBCData().bc; + uint32_t orbit = r.getBCData().orbit; + uint32_t firstIdx = r.getFirstIdx(); + uint32_t nentries = r.getNEntries(); + out.write(reinterpret_cast(&bc), sizeof(uint16_t)); + out.write(reinterpret_cast(&orbit), sizeof(uint32_t)); + out.write(reinterpret_cast(&firstIdx), sizeof(uint32_t)); + out.write(reinterpret_cast(&nentries), sizeof(uint32_t)); + if (out.fail()) { + return false; + } + } + + writeNofItems(out, digits.size()); + if (out.fail()) { + return false; + } + for (const auto& d : digits) { + uint32_t tfTime = d.getTime(); + uint16_t nofSamples = d.getNofSamples(); + uint32_t deID = d.getDetID(); + uint32_t padID = d.getPadID(); + uint32_t adc = d.getADC(); + uint8_t sat = d.isSaturated(); + out.write(reinterpret_cast(&tfTime), sizeof(uint32_t)); + out.write(reinterpret_cast(&nofSamples), sizeof(uint16_t)); + out.write(reinterpret_cast(&sat), sizeof(uint8_t)); + out.write(reinterpret_cast(&deID), sizeof(uint32_t)); + out.write(reinterpret_cast(&padID), sizeof(uint32_t)); + out.write(reinterpret_cast(&adc), sizeof(uint32_t)); + if (out.fail()) { + return false; + } + } + return true; +} + +} // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitIOV3.h b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV3.h new file mode 100644 index 0000000000000..c3117dfad934f --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitIOV3.h @@ -0,0 +1,42 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#pragma once + +#include "DigitReaderImpl.h" +#include +#include "DataFormatsMCH/ROFRecord.h" +#include +#include "DigitWriterImpl.h" + +namespace o2::mch::io::impl +{ +class DigitReaderV3 : public DigitReaderImpl +{ + public: + void count(std::istream& in, size_t& ntfs, size_t& nrofs, size_t& ndigits) override; + bool read(std::istream& in, + std::vector& digits, + std::vector& rofs) override; + void rewind(std::istream& in); +}; + +struct DigitWriterV3 : public DigitWriterImpl { + /** write rofs, digits at the current position in the output stream + * @param digits vector of Digits, must not be empty + * @param rofs vector of ROFRecord, might be empty + * @returns true if writing was successull, false otherwise + */ + bool write(std::ostream& out, + gsl::span digits, + gsl::span rofs) override; +}; + +} // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.cxx b/Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.cxx index f4a69450cc5e1..cf2d6a50a03a6 100644 --- a/Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.cxx +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.cxx @@ -14,6 +14,8 @@ #include #include "DigitIOV0.h" #include "DigitIOV1.h" +#include "DigitIOV2.h" +#include "DigitIOV3.h" #include namespace o2::mch::io::impl @@ -26,9 +28,15 @@ std::unique_ptr createDigitReaderImpl(int version) return std::make_unique(); case 1: return std::make_unique(); + case 2: + return std::make_unique(); + case 3: + return std::make_unique(); default: break; }; + throw std::invalid_argument(fmt::format("DigitFileFormat version {} not implemented yet", + version)); return nullptr; } @@ -38,27 +46,4 @@ void DigitReaderImpl::rewind(std::istream& in) in.seekg(sizeof(DigitFileFormat)); } -int readNofItems(std::istream& in, const char* itemName) -{ - int nitems(-1); - in.read(reinterpret_cast(&nitems), sizeof(int)); - if (in.fail() || nitems < 0) { - throw std::length_error(fmt::format("invalid input : cannot get number of {}", itemName)); - } - return nitems; -} - -int advance(std::istream& in, size_t itemByteSize, const char* itemName) -{ - if (in.peek() == EOF) { - return -1; - } - // get the number of items - int nitems = readNofItems(in, itemName); - // move forward of n items - auto current = in.tellg(); - in.seekg(current + static_cast(nitems * itemByteSize)); - return nitems; -} - } // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.h b/Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.h index e2d2710c7a05c..6fcf9a32df89c 100644 --- a/Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.h +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitReaderImpl.h @@ -35,30 +35,6 @@ struct DigitReaderImpl { void rewind(std::istream& in); }; -int readNofItems(std::istream& in, const char* itemName); - -int advance(std::istream& in, size_t itemByteSize, const char* itemName); - -template -bool readBinary(std::istream& in, std::vector& items, const char* itemName) -{ - if (in.peek() == EOF) { - return false; - } - // get the number of items - int nitems = readNofItems(in, itemName); - // get the items if any - if (nitems > 0) { - auto offset = items.size(); - items.resize(offset + nitems); - in.read(reinterpret_cast(&items[offset]), nitems * sizeof(T)); - if (in.fail()) { - throw std::length_error(fmt::format("invalid input : cannot read {} {}", nitems, itemName)); - } - } - return true; -} - std::unique_ptr createDigitReaderImpl(int version); } // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitWriterImpl.cxx b/Detectors/MUON/MCH/DevIO/Digits/DigitWriterImpl.cxx index c6717933a976f..baed13829d9be 100644 --- a/Detectors/MUON/MCH/DevIO/Digits/DigitWriterImpl.cxx +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitWriterImpl.cxx @@ -11,6 +11,8 @@ #include "DigitWriterImpl.h" #include "DigitIOV0.h" #include "DigitIOV1.h" +#include "DigitIOV2.h" +#include "DigitIOV3.h" #include namespace o2::mch::io::impl @@ -22,6 +24,10 @@ std::unique_ptr createDigitWriterImpl(int version) return std::make_unique(); case 1: return std::make_unique(); + case 2: + return std::make_unique(); + case 3: + return std::make_unique(); default: break; }; @@ -29,4 +35,5 @@ std::unique_ptr createDigitWriterImpl(int version) version)); return nullptr; } + } // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/DigitWriterImpl.h b/Detectors/MUON/MCH/DevIO/Digits/DigitWriterImpl.h index 9cc6ab3f3d4f5..93d815e4a7c57 100644 --- a/Detectors/MUON/MCH/DevIO/Digits/DigitWriterImpl.h +++ b/Detectors/MUON/MCH/DevIO/Digits/DigitWriterImpl.h @@ -36,18 +36,5 @@ struct DigitWriterImpl { gsl::span rofs) = 0; }; -template -bool binary(std::ostream& os, - gsl::span items) -{ - int nofItems = items.size(); - if (!nofItems) { - return !os.bad(); - } - os.write(reinterpret_cast(&nofItems), sizeof(int)); - os.write(reinterpret_cast(items.data()), items.size_bytes()); - return !os.bad(); -} - std::unique_ptr createDigitWriterImpl(int version); } // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/IO.cxx b/Detectors/MUON/MCH/DevIO/Digits/IO.cxx new file mode 100644 index 0000000000000..649d03e447cc7 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/IO.cxx @@ -0,0 +1,45 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "IO.h" +#include +#include +#include + +namespace o2::mch::io::impl +{ +int readNofItems(std::istream& in, const char* itemName) +{ + int nitems(-1); + in.read(reinterpret_cast(&nitems), sizeof(int)); + if (in.fail() || nitems < 0) { + throw std::length_error(fmt::format("invalid input : cannot get number of {}", itemName)); + } + return nitems; +} + +void writeNofItems(std::ostream& out, uint32_t nofItems) +{ + out.write(reinterpret_cast(&nofItems), sizeof(uint32_t)); +} + +int advance(std::istream& in, size_t itemByteSize, const char* itemName) +{ + if (in.peek() == EOF) { + return -1; + } + // get the number of items + int nitems = readNofItems(in, itemName); + // move forward of n items + auto current = in.tellg(); + in.seekg(current + static_cast(nitems * itemByteSize)); + return nitems; +} +} // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/IO.h b/Detectors/MUON/MCH/DevIO/Digits/IO.h new file mode 100644 index 0000000000000..05d9b8e540c68 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/IO.h @@ -0,0 +1,22 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#pragma once + +#include +#include + +namespace o2::mch::io::impl +{ +int readNofItems(std::istream& in, const char* itemName); +void writeNofItems(std::ostream& out, uint32_t nofItems); +int advance(std::istream& in, size_t itemByteSize, const char* itemName); + +} // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/IOStruct.h b/Detectors/MUON/MCH/DevIO/Digits/IOStruct.h new file mode 100644 index 0000000000000..9d2b8cc120ace --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/IOStruct.h @@ -0,0 +1,52 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#pragma once + +#include +#include +#include "IO.h" +#include + +namespace o2::mch::io::impl +{ +template +bool writeBinaryStruct(std::ostream& os, + gsl::span items) +{ + uint32_t nofItems = static_cast(items.size()); + if (!nofItems) { + return !os.bad(); + } + writeNofItems(os, nofItems); + os.write(reinterpret_cast(items.data()), items.size_bytes()); + return !os.bad(); +} +template +bool readBinaryStruct(std::istream& in, std::vector& items, const char* itemName) +{ + if (in.peek() == EOF) { + return false; + } + // get the number of items + int nitems = readNofItems(in, itemName); + // get the items if any + if (nitems > 0) { + auto offset = items.size(); + items.resize(offset + nitems); + in.read(reinterpret_cast(&items[offset]), nitems * sizeof(T)); + if (in.fail()) { + throw std::length_error(fmt::format("invalid input : cannot read {} {}", nitems, itemName)); + } + } + return true; +} + +} // namespace o2::mch::io::impl diff --git a/Detectors/MUON/MCH/DevIO/Digits/testDigitIO.cxx b/Detectors/MUON/MCH/DevIO/Digits/testDigitIO.cxx index 0c27d1e1de527..d6a54f17d2cc8 100644 --- a/Detectors/MUON/MCH/DevIO/Digits/testDigitIO.cxx +++ b/Detectors/MUON/MCH/DevIO/Digits/testDigitIO.cxx @@ -27,6 +27,7 @@ #include #include #include "DigitReaderImpl.h" +#include "IO.h" using namespace o2::mch; using namespace o2::mch::io; @@ -63,6 +64,18 @@ BOOST_AUTO_TEST_CASE(DigitFileFormatV1Value) BOOST_CHECK_EQUAL(sizeof(o2::mch::ROFRecord), v1.rofSize); } +BOOST_AUTO_TEST_CASE(DigitFileFormatV2Value) +{ + DigitFileFormat v2 = createFormat(2, 0, 19, 1, 14, false, false); + BOOST_CHECK_EQUAL(isValid(v2), true); +} + +BOOST_AUTO_TEST_CASE(DigitFileFormatV3Value) +{ + DigitFileFormat v3 = createFormat(3, 0, 19, 1, 14, false, true); + BOOST_CHECK_EQUAL(isValid(v3), true); +} + BOOST_DATA_TEST_CASE(WriteMustReturnFalseIfDigitVectorIsEmpty, digitFileFormats, digitFileFormat) { std::ostringstream str; @@ -84,8 +97,8 @@ BOOST_DATA_TEST_CASE(WriteMustReturnFalseIfDigitVectorIsEmpty, digitFileFormats, BOOST_DATA_TEST_CASE(BinaryWriteMustReturnFalseIfRofVectorIsEmpty, digitFileFormats, digitFileFormat) { - if (digitFileFormat.fileVersion == 0) { - return; //V0 is the exception as it predates ROFs + if (not digitFileFormat.hasRof) { + return; } std::ostringstream str; std::vector rofs; @@ -131,7 +144,10 @@ std::vector createDummyFixedDigits(int n) int32_t dummyTime{1000}; uint16_t dummySamples{10}; for (int i = 0; i < n; i++) { - digits.emplace_back(100, i, dummyADC + i, dummyTime + i * 100, dummySamples + i * 10); + auto& d = digits.emplace_back(100, i, dummyADC + i, dummyTime + i * 100, dummySamples + i * 10); + if (i == 7 || i == 23) { + d.setSaturated(true); + } } return digits; } @@ -219,7 +235,7 @@ BOOST_DATA_TEST_CASE(TestDataHasExpectedNofTFs, digitFileFormats, digitFileForma writeTestData(buffer, digitFileFormat); DigitReader dr(buffer); - if (digitFileFormat.fileVersion == 0) { + if (not digitFileFormat.hasRof) { BOOST_CHECK_EQUAL(dr.nofTimeFrames(), NROFS); } else { BOOST_CHECK_EQUAL(dr.nofTimeFrames(), testData.size()); @@ -268,12 +284,14 @@ BOOST_DATA_TEST_CASE(CheckReader, digitFileFormats, digitFileFormat) BOOST_CHECK_EQUAL(rofs[0].getLastIdx(), digits_per_tf[itf] - 1); } dr.read(digits, rofs); - int ndigits_4th_tf = digitFileFormat.fileVersion == 0 ? 8 : 26; + int ndigits_4th_tf = not digitFileFormat.hasRof ? 8 : 26; BOOST_CHECK_EQUAL(digits.size(), ndigits_4th_tf); - if (digitFileFormat.fileVersion == 0) { + if (not digitFileFormat.hasRof) { BOOST_CHECK_EQUAL(rofs.size(), 1); BOOST_CHECK_EQUAL(rofs[0].getFirstIdx(), 0); BOOST_CHECK_EQUAL(rofs[0].getLastIdx(), 7); + BOOST_CHECK_EQUAL(digits[7].getADC(), 47); + BOOST_CHECK_EQUAL(digits[7].isSaturated(), true); } else { BOOST_CHECK_EQUAL(rofs.size(), 3); BOOST_CHECK_EQUAL(rofs[0].getFirstIdx(), 0); @@ -282,5 +300,7 @@ BOOST_DATA_TEST_CASE(CheckReader, digitFileFormats, digitFileFormat) BOOST_CHECK_EQUAL(rofs[1].getLastIdx(), 15); BOOST_CHECK_EQUAL(rofs[2].getFirstIdx(), 16); BOOST_CHECK_EQUAL(rofs[2].getLastIdx(), 25); + BOOST_CHECK_EQUAL(digits[23].getADC(), 63); + BOOST_CHECK_EQUAL(digits[23].isSaturated(), true); } } diff --git a/Detectors/MUON/MCH/DevIO/Digits/testDigitIOV0.cxx b/Detectors/MUON/MCH/DevIO/Digits/testDigitIOV0.cxx index 8e4d7a0eb83b4..04f6e4a8566f2 100644 --- a/Detectors/MUON/MCH/DevIO/Digits/testDigitIOV0.cxx +++ b/Detectors/MUON/MCH/DevIO/Digits/testDigitIOV0.cxx @@ -29,6 +29,8 @@ #include "DigitReaderImpl.h" #include "TestFileV0.h" #include "DigitD0.h" +#include "IO.h" + using namespace o2::mch; using namespace o2::mch::io; From 2ee0818bf63d2369d3a498c942447d8f275f90e9 Mon Sep 17 00:00:00 2001 From: Laurent Aphecetche Date: Wed, 14 Apr 2021 21:48:43 +0200 Subject: [PATCH 178/770] [MRRTF-111] [MCH] Debug workflow to generate random digits --- .../MUON/MCH/DevIO/Digits/CMakeLists.txt | 24 +- Detectors/MUON/MCH/DevIO/Digits/README.md | 67 +++++- .../digits-random-generator-workflow.cxx | 210 ++++++++++++++++++ 3 files changed, 291 insertions(+), 10 deletions(-) create mode 100644 Detectors/MUON/MCH/DevIO/Digits/digits-random-generator-workflow.cxx diff --git a/Detectors/MUON/MCH/DevIO/Digits/CMakeLists.txt b/Detectors/MUON/MCH/DevIO/Digits/CMakeLists.txt index 1b03dad18be6f..c5dd73e5d07f0 100644 --- a/Detectors/MUON/MCH/DevIO/Digits/CMakeLists.txt +++ b/Detectors/MUON/MCH/DevIO/Digits/CMakeLists.txt @@ -34,19 +34,31 @@ o2_add_executable(digits-r23-workflow PUBLIC_LINK_LIBRARIES O2::Framework O2::DataFormatsMCH O2::MCHBase O2::MCHMappingImpl3) +add_library(MCHDigitIOBaseTask OBJECT) +add_library(O2::MCHDigitIOBaseTask ALIAS MCHDigitIOBaseTask) +target_link_libraries(MCHDigitIOBaseTask PUBLIC O2::DataFormatsMCH O2::Framework) + +target_sources(MCHDigitIOBaseTask PRIVATE DigitIOBaseTask.cxx) + o2_add_executable( digits-writer-workflow - SOURCES digits-writer-workflow.cxx DigitIOBaseTask.cxx + SOURCES digits-writer-workflow.cxx COMPONENT_NAME mch - PUBLIC_LINK_LIBRARIES O2::Framework O2::DPLUtils Boost::program_options - O2::MCHBase O2::MCHRawDecoder O2::DataFormatsMCH - O2::MCHDigitIO) + PUBLIC_LINK_LIBRARIES O2::DPLUtils Boost::program_options + O2::MCHBase O2::MCHRawDecoder + O2::MCHDigitIO O2::MCHDigitIOBaseTask) o2_add_executable( digits-file-reader-workflow - SOURCES digits-file-reader-workflow.cxx DigitIOBaseTask.cxx + SOURCES digits-file-reader-workflow.cxx + COMPONENT_NAME mch + PUBLIC_LINK_LIBRARIES O2::MCHBase O2::MCHDigitIO O2::MCHDigitIOBaseTask) + +o2_add_executable( + digits-random-generator-workflow + SOURCES digits-random-generator-workflow.cxx COMPONENT_NAME mch - PUBLIC_LINK_LIBRARIES O2::Framework O2::DataFormatsMCH O2::MCHBase O2::MCHDigitIO) + PUBLIC_LINK_LIBRARIES O2::MCHBase O2::MCHMappingImpl4 O2::MCHDigitIO O2::MCHDigitIOBaseTask) o2_add_executable( digits-file-dumper diff --git a/Detectors/MUON/MCH/DevIO/Digits/README.md b/Detectors/MUON/MCH/DevIO/Digits/README.md index a82b81b5a7f81..5a51f2538e499 100644 --- a/Detectors/MUON/MCH/DevIO/Digits/README.md +++ b/Detectors/MUON/MCH/DevIO/Digits/README.md @@ -2,6 +2,18 @@ \page refDetectorsMUONMCHDevIODigits DigitsIO /doxy --> + + +* [Utilities to read and write MCH Digits in non-CTF formats (mostly for debug)](#utilities-to-read-and-write-mch-digits-in-non-ctf-formats-mostly-for-debug) + * [Standalone programs (i.e. not DPL devices)](#standalone-programs-ie-not-dpl-devices) + * [Digit file dumper](#digit-file-dumper) + * [DPL devices](#dpl-devices) + * [Digit file reader (aka sampler) device](#digit-file-reader-aka-sampler-device) + * [Digit writer (aka sink) device](#digit-writer-aka-sink-device) + * [Digit ID converter (from Run2 to Run3)](#digit-id-converter-from-run2-to-run3) + * [Digit random generator](#digit-random-generator) + + # Utilities to read and write MCH Digits in non-CTF formats (mostly for debug) The MCH digits can be stored in binary format for debug purpose. @@ -13,9 +25,9 @@ have the same version (named D0). The file version number changes whenever the | File version | Digit version | contains ROF | ROF version | support | |:------------:|:-------------:|:------------:|:-----------:|:---------:| -| 0 | 0 | no | 0 | yes | -| 1 | 0 | yes | 0 | yes | -| 2 | 1 | yes | 0 | planned | +| 0 | 0 | no | (0) | yes | +| 1 | 0 | yes | 1 | yes | +| 2 | 1 | yes | 1 | planned | ## Standalone programs (i.e. not DPL devices) @@ -47,7 +59,6 @@ it is the V0 version, which might or not might be the case... ``` o2-mch-digits-file-reader-workflow --infile arg input file name - [--verbose] print some basic information while processing [--max-nof-tfs] max number of timeframes to process [--first-tf] first timeframe to process [--max-nof-rofs] max number of ROFs to process @@ -80,8 +91,56 @@ option is used) or to screen (if `--no-file` option is used) ``` o2-mch-digits-r23-workflow + [--verbose] print ids being converted ``` A device that reads digits with ids in Run2 convention and outputs digits with ids in Run3 convention. Note that expected input spec is `MCH/DIGITSRUN2` and the output one is `MCH/DIGITS` + +### Digit random generator + +``` +o2-mch-digits-random-generator-workflow + [--first-tf] arg (=0) first timeframe to generate + [--max-nof-tfs] arg (=2147483647) max number of timeframes to generate + [--nof-rofs-per-tf] number of ROFs to generate in each timeframe + [--occupancy] fraction of pads to generate digits for + [--print-digits] print digits + [--print-tfs] print number of digits and rofs per tf +``` + +Generate a fixed number of digits (equal to the total number of MCH pads +times the occupancy) per ROFRecord for a fixed number of ROFRecord per time frames, + for a fixed number of timeframes. + +Note that the occupancy **must** be strictly positive and less than or equal to 1. + +Example of use : generate digits (with 1% occupancy, 128 ROFs per TF, 10 TFs) and +dump them into debug binary form : + +``` +o2-mch-digits-random-generator-workflow -b + --max-nof-tfs 10 + --nof-rofs-per-tf 128 + --occupancy 0.01 | +o2-mch-digits-writer-workflow -b + --print-tfs + --binary-file-format 1 + --outfile digits.v1.out +``` + +``` +$ ls -alrth digits.v1.out +-rw-r--r-- 1 laurent staff 258M 15 avr 10:30 digits.v1.out + +$ o2-mch-digits-file-dumper --infile digits.v1.out -c -d +[ file version 1 digit version 0 size 20 rof version 1 size 16 hasRof true run2ids false ] formatWord 1224998065220435759 +nTFs 10 nROFs 1280 nDigits 13506560 +``` + +The generated digit file can then be injected into other workflows using +`o2-mch-digits-file-reader-workflow` described above. +(digits do not _need_ to be written to disc, the `o2-mch-digits-random-generator-workflow` + can of course also be used as the first stage of a multi device workflow + using pipes). diff --git a/Detectors/MUON/MCH/DevIO/Digits/digits-random-generator-workflow.cxx b/Detectors/MUON/MCH/DevIO/Digits/digits-random-generator-workflow.cxx new file mode 100644 index 0000000000000..bbb2d96155053 --- /dev/null +++ b/Detectors/MUON/MCH/DevIO/Digits/digits-random-generator-workflow.cxx @@ -0,0 +1,210 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "CommonDataFormat/InteractionRecord.h" +#include "DataFormatsMCH/Digit.h" +#include "DataFormatsMCH/ROFRecord.h" +#include "DigitIOBaseTask.h" +#include "Framework/ConfigParamRegistry.h" +#include "Framework/ConfigParamSpec.h" +#include "Framework/ControlService.h" +#include "Framework/DataProcessorSpec.h" +#include "Framework/DataSpecUtils.h" +#include "Framework/Lifetime.h" +#include "Framework/Logger.h" +#include "Framework/Output.h" +#include "Framework/Task.h" +#include "Framework/WorkflowSpec.h" +#include "MCHMappingInterface/Segmentation.h" +#include "ProgOptions.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * This executable generate random MCH digits and their associated ROFRecords. + * + */ + +using namespace o2::framework; + +using namespace o2::mch; + +namespace +{ +std::array getDeIds() +{ + static std::array deids; + static bool first = true; + if (first) { + int i{0}; + o2::mch::mapping::forEachDetectionElement([&](int deid) { + deids[i++] = deid; + }); + first = false; + } + return deids; +} + +std::array getNofPads() +{ + static bool first = true; + static std::array npads; + if (first) { + int i{0}; + auto deids = getDeIds(); + for (auto deid : deids) { + o2::mch::mapping::Segmentation seg(deid); + int16_t nofPads = static_cast(seg.nofPads()); + npads[i++] = nofPads; + } + first = false; + } + return npads; +} +} // namespace + +constexpr const char* OPTNAME_NOF_ROFS_PER_TF = "nof-rofs-per-tf"; +constexpr const char* OPTNAME_OCCUPANCY = "occupancy"; +constexpr const char* OPTNAME_SEED = "seed"; + +class DigitGenerator : public o2::mch::io::DigitIOBaseTask +{ + public: + void init(InitContext& ic) + { + io::DigitIOBaseTask::init(ic); // init common options + mOccupancy = ic.options().get(OPTNAME_OCCUPANCY); + if (mOccupancy <= 0.0 || mOccupancy > 1.0) { + throw std::invalid_argument("occupancy must be between >0 and <=1"); + } + mNofRofPerTimeFrame = ic.options().get(OPTNAME_NOF_ROFS_PER_TF); + mSeed = ic.options().get(OPTNAME_SEED); + + if (!mSeed) { + std::random_device rd; + mSeed = rd(); + } + mMersenneTwister.seed(mSeed); + + LOGP(INFO, + "Will generate {:7.2f}% of pads in {:4d} ROFs " + "per timeframe, for {:4d} timeframes", + mOccupancy * 100.0, mNofRofPerTimeFrame, mMaxNofTimeFrames); + } + + void run(ProcessingContext& pc) + { + if (mNofProcessedTFs >= mMaxNofTimeFrames) { + pc.services().get().endOfStream(); + return; + } + + if (shouldProcess()) { + incNofProcessedTFs(); + std::vector digits; + std::vector rofs; + int ndigits{0}; + + for (auto i = 0; i < mNofRofPerTimeFrame; i++) { + auto n = generateRandomDigits(mOccupancy, digits); + o2::InteractionRecord ir{mBC, mOrbit}; + rofs.emplace_back(ir, ndigits, n); + ndigits += n; + mOrbit++; + } + pc.outputs().snapshot(OutputRef{"rofs"}, rofs); + pc.outputs().snapshot(OutputRef{"digits"}, digits); + printSummary(digits, rofs); + printFull(digits, rofs); + } + incTFid(); + } + + /** + * Populate the digits vector with (Nmch * occupancy) digits + * where Nmch is the total number of channels in MCH (1064008) + * + * Each member variable of the digit is uniformly distributed within + * its expected range, as an attempt to maximize the entropy of the + * generated digits, which can be handy to test the efficiency of the + * entropy encoder used to create the Compressed Time Frame (CTF) for instance. + * + * @param occupancy is a number between 0 and 1. + * @digits a vector where the generated digits will be appended. + * That vector is not cleared by this function, so digits can + * be accumulated if need be. + * @returns the number of digits added to the input digits vector. + */ + int generateRandomDigits(float occupancy, + std::vector& digits) + { + int n{0}; + std::uniform_int_distribution adc{0, 1024 * 1024}; + std::uniform_int_distribution tfTime{0, 512 * 3564}; + std::uniform_int_distribution nofSamples{0, 1023}; + std::uniform_real_distribution sat{0.0, 1.0}; + + auto deids = getDeIds(); + auto nofPadsPerDe = getNofPads(); + auto& mt = mMersenneTwister; + + for (auto i = 0; i < deids.size(); i++) { + auto deid = deids[i]; + int16_t nofPads = static_cast(nofPadsPerDe[i]); + std::uniform_int_distribution padid{0, nofPads}; + int nch = nofPads * occupancy; + for (int i = 0; i < nch; i++) { + auto p = padid(mt); + bool isSaturated = (sat(mt) > 0.9); + digits.emplace_back(deid, p, tfTime(mt), adc(mt), nofSamples(mt), isSaturated); + ++n; + } + } + return n; + } + + private: + float mOccupancy = 1.0; + uint16_t mBC = 0; + uint32_t mOrbit = 0; + int mNofRofPerTimeFrame = 100; + int mSeed = 0; + std::mt19937 mMersenneTwister; +}; + +#include "Framework/runDataProcessing.h" + +using namespace o2::mch; + +WorkflowSpec defineDataProcessing(const ConfigContext& cc) +{ + auto commonOptions = o2::mch::io::getCommonOptions(); + auto options = Options{ + {OPTNAME_OCCUPANCY, VariantType::Float, 0.01f, {"occupancy (fraction of fired pad per DE per ROF)"}}, + {OPTNAME_SEED, VariantType::Int, 0, {"seed for number generator (if 0 use default_seed)"}}, + {OPTNAME_NOF_ROFS_PER_TF, VariantType::Int, 100, {"number of ROFs per timeframe"}}}; + options.insert(options.end(), commonOptions.begin(), commonOptions.end()); + + return WorkflowSpec{ + DataProcessorSpec{ + "mch-digits-random-generator", + Inputs{}, + Outputs{OutputSpec{{"digits"}, "MCH", "DIGITS", 0, Lifetime::Timeframe}, + OutputSpec{{"rofs"}, "MCH", "DIGITROFS", 0, Lifetime::Timeframe}}, + AlgorithmSpec{adaptFromTask()}, + options}}; +} From 4fabbe2cee3f097683b8d50d44a80456d6c6f733 Mon Sep 17 00:00:00 2001 From: sy-c Date: Tue, 20 Apr 2021 18:08:02 +0200 Subject: [PATCH 179/770] infologger renaming (#5926) * infologger renaming * clang-format * Update convert-raw-to-tf-file.sh Co-authored-by: Giulio Eulisse <10544+ktf@users.noreply.github.com> --- .../MUON/MCH/Calibration/test/test-mch-pedestal-calibration.sh | 2 +- Framework/Core/src/CommonServices.cxx | 2 +- Framework/Core/src/DeviceSpecHelpers.cxx | 2 +- Framework/Core/src/runDataProcessing.cxx | 2 +- Framework/Core/test/test_InfoLogger.cxx | 2 +- prodtests/full-system-test/convert-raw-to-tf-file.sh | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Detectors/MUON/MCH/Calibration/test/test-mch-pedestal-calibration.sh b/Detectors/MUON/MCH/Calibration/test/test-mch-pedestal-calibration.sh index dbd435b48941c..fbbbb8c5622e5 100755 --- a/Detectors/MUON/MCH/Calibration/test/test-mch-pedestal-calibration.sh +++ b/Detectors/MUON/MCH/Calibration/test/test-mch-pedestal-calibration.sh @@ -1,6 +1,6 @@ #! /bin/bash -export INFOLOGGER_MODE=stdout +export O2_INFOLOGGER_MODE=stdout export SCRIPTDIR=$(readlink -f $(dirname $0)) INPUT="$1" diff --git a/Framework/Core/src/CommonServices.cxx b/Framework/Core/src/CommonServices.cxx index 418046413f9d6..55757c16b5d2d 100644 --- a/Framework/Core/src/CommonServices.cxx +++ b/Framework/Core/src/CommonServices.cxx @@ -195,7 +195,7 @@ o2::framework::ServiceSpec CommonServices::infologgerSpec() [](ServiceRegistry& services, DeviceState&, fair::mq::ProgOptions& options) -> ServiceHandle { auto infoLoggerMode = options.GetPropertyAsString("infologger-mode"); if (infoLoggerMode != "") { - setenv("INFOLOGGER_MODE", infoLoggerMode.c_str(), 1); + setenv("O2_INFOLOGGER_MODE", infoLoggerMode.c_str(), 1); } auto infoLoggerService = new InfoLogger; auto infoLoggerContext = &services.get(); diff --git a/Framework/Core/src/DeviceSpecHelpers.cxx b/Framework/Core/src/DeviceSpecHelpers.cxx index f6e38e3c4cd47..ac76eddbc91fd 100644 --- a/Framework/Core/src/DeviceSpecHelpers.cxx +++ b/Framework/Core/src/DeviceSpecHelpers.cxx @@ -1229,7 +1229,7 @@ boost::program_options::options_description DeviceSpecHelpers::getForwardedDevic ("configuration,cfg", bpo::value(), "configuration connection string") // ("driver-client-backend", bpo::value(), "driver connection string") // ("monitoring-backend", bpo::value(), "monitoring connection string") // - ("infologger-mode", bpo::value(), "INFOLOGGER_MODE override") // + ("infologger-mode", bpo::value(), "O2_INFOLOGGER_MODE override") // ("infologger-severity", bpo::value(), "minimun FairLogger severity which goes to info logger") // ("child-driver", bpo::value(), "external driver to start childs with (e.g. valgrind)"); // diff --git a/Framework/Core/src/runDataProcessing.cxx b/Framework/Core/src/runDataProcessing.cxx index 81b04a0c69177..465af3e7ab1ce 100644 --- a/Framework/Core/src/runDataProcessing.cxx +++ b/Framework/Core/src/runDataProcessing.cxx @@ -998,7 +998,7 @@ int doChild(int argc, char** argv, ServiceRegistry& serviceRegistry, ("driver-client-backend", bpo::value()->default_value(defaultDriverClient), "backend for device -> driver communicataon: stdout://: use stdout, ws://: use websockets") // ("infologger-severity", bpo::value()->default_value(""), "minimum FairLogger severity to send to InfoLogger") // ("configuration,cfg", bpo::value()->default_value("command-line"), "configuration backend") // - ("infologger-mode", bpo::value()->default_value(""), "INFOLOGGER_MODE override"); + ("infologger-mode", bpo::value()->default_value(""), "O2_INFOLOGGER_MODE override"); r.fConfig.AddToCmdLineOptions(optsDesc, true); }); diff --git a/Framework/Core/test/test_InfoLogger.cxx b/Framework/Core/test/test_InfoLogger.cxx index e287f6d70a180..4760331158b58 100644 --- a/Framework/Core/test/test_InfoLogger.cxx +++ b/Framework/Core/test/test_InfoLogger.cxx @@ -20,7 +20,7 @@ BOOST_AUTO_TEST_CASE(InfoLoggerTest) { // define infologger output to stdout, as we don't want to use the default infoLoggerD pipe which might not be running here - setenv("INFOLOGGER_MODE", "stdout", 1); + setenv("O2_INFOLOGGER_MODE", "stdout", 1); // create the infologger interface InfoLogger theLog; diff --git a/prodtests/full-system-test/convert-raw-to-tf-file.sh b/prodtests/full-system-test/convert-raw-to-tf-file.sh index e0675a35c103e..a7d46b9658bcd 100755 --- a/prodtests/full-system-test/convert-raw-to-tf-file.sh +++ b/prodtests/full-system-test/convert-raw-to-tf-file.sh @@ -28,7 +28,7 @@ echo StfBuilder PID: $STF_PID, waiting 15 seconds sleep 15 echo Starting Readout -export INFOLOGGER_OPTIONS="floodProtection=0" +export O2_INFOLOGGER_OPTIONS="floodProtection=0" o2-readout-exe file:rdo_TF.cfg &> readout.log & RD_PID=$! echo Readout PID: $RD_PID From 88deef4b15b0346dbf0a0cbd3c3f19cb0715099e Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 20 Apr 2021 10:06:18 +0200 Subject: [PATCH 180/770] rename GPU debug ROOT dump from debug.root to gpudebug.root --- GPU/GPUTracking/Debug/GPUROOTDumpCore.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/GPUTracking/Debug/GPUROOTDumpCore.cxx b/GPU/GPUTracking/Debug/GPUROOTDumpCore.cxx index 04902beae69fb..fe353f710c1f4 100644 --- a/GPU/GPUTracking/Debug/GPUROOTDumpCore.cxx +++ b/GPU/GPUTracking/Debug/GPUROOTDumpCore.cxx @@ -24,7 +24,7 @@ std::weak_ptr GPUROOTDumpCore::sInstance; GPUROOTDumpCore::GPUROOTDumpCore() { - mFile.reset(new TFile("debug.root", "recreate")); + mFile.reset(new TFile("gpudebug.root", "recreate")); } GPUROOTDumpCore::~GPUROOTDumpCore() From 1196a068549c05597c643e3f51f3bad181048f66 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 20 Apr 2021 10:06:42 +0200 Subject: [PATCH 181/770] Full system test raw to TF file conversion: remove all log files --- prodtests/full-system-test/convert-raw-to-tf-file.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/prodtests/full-system-test/convert-raw-to-tf-file.sh b/prodtests/full-system-test/convert-raw-to-tf-file.sh index a7d46b9658bcd..78be9ad0e4f8d 100755 --- a/prodtests/full-system-test/convert-raw-to-tf-file.sh +++ b/prodtests/full-system-test/convert-raw-to-tf-file.sh @@ -12,7 +12,7 @@ fi pushd raw -rm -Rf timeframe rdo_TF.cfg +rm -Rf timeframe rdo_TF.cfg *.log if [ `ls | grep -v "^[A-Z0-9]\{3\}\$" | wc -l` != "0" ]; then echo Unexpected data in raw folder exit 1 @@ -56,7 +56,7 @@ if [ -d /proc/$STF_PID ]; then fi mv 20* timeframe -rm -f readout.log stfbuilder.log +rm -f *.log rdo_TF.cfg echo Done From 2cfe6e6b1a4dadb4cf400650b71f52e7fbb81b2e Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 20 Apr 2021 10:15:10 +0200 Subject: [PATCH 182/770] GPU: Create debug ROOT file only when filled with debug content --- GPU/GPUTracking/Debug/GPUROOTDumpCore.cxx | 16 ++++++++++------ GPU/GPUTracking/Debug/GPUROOTDumpCore.h | 7 +++++-- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/GPU/GPUTracking/Debug/GPUROOTDumpCore.cxx b/GPU/GPUTracking/Debug/GPUROOTDumpCore.cxx index fe353f710c1f4..3c4e4f197d753 100644 --- a/GPU/GPUTracking/Debug/GPUROOTDumpCore.cxx +++ b/GPU/GPUTracking/Debug/GPUROOTDumpCore.cxx @@ -22,17 +22,18 @@ using namespace GPUCA_NAMESPACE::gpu; std::weak_ptr GPUROOTDumpCore::sInstance; -GPUROOTDumpCore::GPUROOTDumpCore() +GPUROOTDumpCore::GPUROOTDumpCore(GPUROOTDumpCore::GPUROOTDumpCorePrivate) { - mFile.reset(new TFile("gpudebug.root", "recreate")); } GPUROOTDumpCore::~GPUROOTDumpCore() { - for (unsigned int i = 0; i < mBranches.size(); i++) { - mBranches[i]->write(); + if (mFile) { + for (unsigned int i = 0; i < mBranches.size(); i++) { + mBranches[i]->write(); + } + mFile->Close(); } - mFile->Close(); } std::shared_ptr GPUROOTDumpCore::getAndCreate() @@ -42,7 +43,7 @@ std::shared_ptr GPUROOTDumpCore::getAndCreate() } std::shared_ptr retVal = sInstance.lock(); if (!retVal) { - retVal = std::make_shared(); + retVal = std::make_shared(GPUROOTDumpCorePrivate()); sInstance = retVal; } lock.clear(std::memory_order_release); @@ -56,6 +57,9 @@ GPUROOTDumpBase::GPUROOTDumpBase() throw std::runtime_error("No instance of GPUROOTDumpCore exists"); } p->mBranches.emplace_back(this); + if (!p->mFile) { + p->mFile.reset(new TFile("gpudebug.root", "recreate")); + } p->mFile->cd(); } diff --git a/GPU/GPUTracking/Debug/GPUROOTDumpCore.h b/GPU/GPUTracking/Debug/GPUROOTDumpCore.h index 8e5866dfa5c0b..4f7aa10fe7545 100644 --- a/GPU/GPUTracking/Debug/GPUROOTDumpCore.h +++ b/GPU/GPUTracking/Debug/GPUROOTDumpCore.h @@ -41,12 +41,15 @@ class GPUROOTDumpCore #if !defined(GPUCA_NO_ROOT) && !defined(GPUCA_GPUCODE) friend class GPUReconstruction; friend class GPUROOTDumpBase; - //template friend class GPUROOTDump; + + private: + struct GPUROOTDumpCorePrivate { + }; public: GPUROOTDumpCore(const GPUROOTDumpCore&) = delete; GPUROOTDumpCore operator=(const GPUROOTDumpCore&) = delete; - GPUROOTDumpCore(); // Public since used with new, but should not be created manually. + GPUROOTDumpCore(GPUROOTDumpCorePrivate); // Cannot be declared private directly since used with new ~GPUROOTDumpCore(); private: From 8aa0e7f06ebd6f828d6fbdd46befa306190c2fff Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 20 Apr 2021 11:57:45 +0200 Subject: [PATCH 183/770] Full system test: Add MFT dictionary --- prodtests/full_system_test.sh | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/prodtests/full_system_test.sh b/prodtests/full_system_test.sh index 0ac50ede4f58e..78c410e9dd33d 100755 --- a/prodtests/full_system_test.sh +++ b/prodtests/full_system_test.sh @@ -82,11 +82,14 @@ taskwrapper digi.log o2-sim-digitizer-workflow -n $NEvents --simPrefixQED qed/o2 [ $SPLITTRDDIGI == "1" ] && taskwrapper digiTRD.log o2-sim-digitizer-workflow -n $NEvents ${NOMCLABELS} --onlyDet TRD --shm-segment-size $SHMSIZE ${GLOBALDPLOPT} --incontext collisioncontext.root ${DIGITRDOPTREAL} touch digiTRD.log_done -if [ "0$GENERATE_ITS_DICTIONARY" == "01" ]; then - taskwrapper itsdict1.log o2-its-reco-workflow --trackerCA --disable-mc --configKeyValues '"fastMultConfig.cutMultClusLow=30000;fastMultConfig.cutMultClusHigh=2000000;fastMultConfig.cutMultVtxHigh=500"' +if [ "0$GENERATE_ITSMFT_DICTIONARIES" == "01" ]; then + taskwrapper itsmftdict1.log o2-its-reco-workflow --trackerCA --disable-mc --configKeyValues '"fastMultConfig.cutMultClusLow=30000;fastMultConfig.cutMultClusHigh=2000000;fastMultConfig.cutMultVtxHigh=500"' cp ~/alice/O2/Detectors/ITSMFT/ITS/macros/test/CreateDictionaries.C . - taskwrapper itsdict2.log root -b -q CreateDictionaries.C++ - rm -f CreateDictionaries_C* + taskwrapper itsmftdict2.log root -b -q CreateDictionaries.C++ + taskwrapper itsmftdict3.log o2-mft-reco-workflow --disable-mc + cp ~/alice/O2/Detectors/ITSMFT/MFT/macros/test/CheckTopologies.C . + taskwrapper itsmftdict4.log root -b -q CheckTopologies.C++ + rm -f CheckTopologies_C* fi mkdir -p raw @@ -97,7 +100,7 @@ taskwrapper fv0raw.log o2-fv0-digi2raw --file-per-link -o raw/FV0 taskwrapper fddraw.log o2-fdd-digit2raw --file-per-link -o raw/FDD taskwrapper tpcraw.log o2-tpc-digits-to-rawzs --file-for link -i tpcdigits.root -o raw/TPC taskwrapper tofraw.log o2-tof-reco-workflow ${GLOBALDPLOPT} --tof-raw-file-for link --output-type raw --tof-raw-outdir raw/TOF -taskwrapper midraw.log o2-mid-digits-to-raw-workflow ${GLOBALDPLOPT} --mid-raw-outdir raw/MID --mid-raw-perlink +taskwrapper midraw.log o2-mid-digits-to-raw-workflow ${GLOBALDPLOPT} --mid-raw-outdir raw/MID --mid-raw-perlink taskwrapper emcraw.log o2-emcal-rawcreator --file-for link -o raw/EMC taskwrapper phsraw.log o2-phos-digi2raw --file-for link -o raw/PHS taskwrapper cpvraw.log o2-cpv-digi2raw --file-for link -o raw/CPV From e70eab34f415b953755c6e92f0f8ef92499274e9 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 20 Apr 2021 14:12:20 +0200 Subject: [PATCH 184/770] GPU: Fix initialiaztion order in TRDTracker class --- GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx index fec9f3f3ff921..b414e9ba04b8a 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx @@ -105,7 +105,7 @@ void* GPUTRDTracker_t::SetPointersTracks(void* base) } template -GPUTRDTracker_t::GPUTRDTracker_t() : mR(nullptr), mIsInitialized(false), mTrkltTransfNeeded(true), mDoImpactAngleHistograms(false), mProcessPerTimeFrame(false), mMemoryPermanent(-1), mMemoryTracklets(-1), mMemoryTracks(-1), mNMaxCollisions(1), mNMaxTracks(0), mNMaxSpacePoints(0), mTracks(nullptr), mNCandidates(1), mNCollisions(1), mNTracks(0), mNEvents(0), mTriggerRecordIndices(nullptr), mTriggerRecordTimes(nullptr), mTracklets(nullptr), mTrackletIndices(nullptr), mMaxThreads(100), mNTracklets(0), mTrackletIndexArray(nullptr), mHypothesis(nullptr), mNAngleHistogramBins(25), mAngleHistogramRange(50), mCandidates(nullptr), mSpacePoints(nullptr), mAngleDiffSums(nullptr), mAngleDiffCounters(nullptr), mTrackletLabels(nullptr), mGeo(nullptr), mRPhiA2(0), mRPhiB(0), mRPhiC2(0), mDyA2(0), mDyB(0), mDyC2(0), mAngleToDyA(0), mAngleToDyB(0), mAngleToDyC(0), mDebugOutput(false), mTimeWindow(.1f), mRadialOffset(-0.1), mMaxEta(0.84f), mExtraRoadY(2.f), mRoadZ(18.f), mZCorrCoefNRC(1.4f), mMCEvent(nullptr), mDebug(new GPUTRDTrackerDebug()) +GPUTRDTracker_t::GPUTRDTracker_t() : mR(nullptr), mIsInitialized(false), mTrkltTransfNeeded(true), mProcessPerTimeFrame(false), mDoImpactAngleHistograms(false), mNAngleHistogramBins(25), mAngleHistogramRange(50), mMemoryPermanent(-1), mMemoryTracklets(-1), mMemoryTracks(-1), mNMaxCollisions(1), mNMaxTracks(0), mNMaxSpacePoints(0), mTracks(nullptr), mNCandidates(1), mNCollisions(1), mNTracks(0), mNEvents(0), mTriggerRecordIndices(nullptr), mTriggerRecordTimes(nullptr), mTracklets(nullptr), mTrackletIndices(nullptr), mMaxThreads(100), mNTracklets(0), mTrackletIndexArray(nullptr), mHypothesis(nullptr), mCandidates(nullptr), mSpacePoints(nullptr), mAngleDiffSums(nullptr), mAngleDiffCounters(nullptr), mTrackletLabels(nullptr), mGeo(nullptr), mRPhiA2(0), mRPhiB(0), mRPhiC2(0), mDyA2(0), mDyB(0), mDyC2(0), mAngleToDyA(0), mAngleToDyB(0), mAngleToDyC(0), mDebugOutput(false), mTimeWindow(.1f), mRadialOffset(-0.1), mMaxEta(0.84f), mExtraRoadY(2.f), mRoadZ(18.f), mZCorrCoefNRC(1.4f), mMCEvent(nullptr), mDebug(new GPUTRDTrackerDebug()) { //-------------------------------------------------------------------- // Default constructor From dc9eea0f1027c7317769828aa62fa1a089c527a6 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 20 Apr 2021 16:06:49 +0200 Subject: [PATCH 185/770] GPU: Require at least CUDA 11.3 --- dependencies/FindO2GPU.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dependencies/FindO2GPU.cmake b/dependencies/FindO2GPU.cmake index becee654d8714..4c82ba0b723fc 100644 --- a/dependencies/FindO2GPU.cmake +++ b/dependencies/FindO2GPU.cmake @@ -27,7 +27,7 @@ string(TOUPPER "${ENABLE_HIP}" ENABLE_HIP) # Detect and enable CUDA if(ENABLE_CUDA) - set(CUDA_MINIMUM_VERSION "11.0") + set(CUDA_MINIMUM_VERSION "11.3") set(CMAKE_CUDA_STANDARD 17) set(CMAKE_CUDA_STANDARD_REQUIRED TRUE) include(CheckLanguage) From b0ead5f0c430eb92e7772e6443e48b98b3a4beca Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 20 Apr 2021 16:07:00 +0200 Subject: [PATCH 186/770] GPU: Require clang >= 13 for OpenCL2 compilation --- dependencies/FindO2GPU.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dependencies/FindO2GPU.cmake b/dependencies/FindO2GPU.cmake index 4c82ba0b723fc..f3008f604b072 100644 --- a/dependencies/FindO2GPU.cmake +++ b/dependencies/FindO2GPU.cmake @@ -117,7 +117,7 @@ if(ENABLE_OPENCL2) find_program(LLVM_SPIRV llvm-spirv) if(Clang_FOUND AND LLVM_FOUND - AND LLVM_PACKAGE_VERSION VERSION_GREATER_EQUAL 10.0) + AND LLVM_PACKAGE_VERSION VERSION_GREATER_EQUAL 13.0) set(OPENCL2_COMPATIBLE_CLANG_FOUND ON) endif() if(OpenCL_VERSION_STRING VERSION_GREATER_EQUAL 2.0 From 4f215eed5dafc078b003b470fbca2a364ae8d060 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 20 Apr 2021 18:10:49 +0200 Subject: [PATCH 187/770] GPU: Use __constant__ constexpr with CUDA, available since toolkit 11.3 --- GPU/Common/GPUCommonDefAPI.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/Common/GPUCommonDefAPI.h b/GPU/Common/GPUCommonDefAPI.h index d0bcd25b38673..7b36b2e8c9bb0 100644 --- a/GPU/Common/GPUCommonDefAPI.h +++ b/GPU/Common/GPUCommonDefAPI.h @@ -171,7 +171,7 @@ #define GPUshared() __shared__ #define GPUglobal() #define GPUconstant() __constant__ - #define GPUconstexpr() __constant__ + #define GPUconstexpr() constexpr __constant__ #define GPUprivate() #define GPUgeneric() #define GPUbarrier() __syncthreads() From f7f49c1a0152cf2312eff507b3f378e9f2623b8d Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 21 Apr 2021 17:43:03 +0200 Subject: [PATCH 188/770] Add missing header needed for GCC >= 10 --- Detectors/MUON/MCH/DevIO/Digits/TestFileV0.cxx | 1 + 1 file changed, 1 insertion(+) diff --git a/Detectors/MUON/MCH/DevIO/Digits/TestFileV0.cxx b/Detectors/MUON/MCH/DevIO/Digits/TestFileV0.cxx index 67bef0b5069af..9060777bedfb6 100644 --- a/Detectors/MUON/MCH/DevIO/Digits/TestFileV0.cxx +++ b/Detectors/MUON/MCH/DevIO/Digits/TestFileV0.cxx @@ -9,6 +9,7 @@ // or submit itself to any jurisdiction. #include +#include std::array v0_buffer = { 0x2F, 0x3F, 0x00, 0x00, 0x40, 0x01, 0x00, 0x20, From 2cdbed4a3d3fd43dbde31c79a0fe47423380c8f9 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 21 Apr 2021 21:08:31 +0200 Subject: [PATCH 189/770] GPU TRD: Fix typo --- GPU/GPUTracking/TRDTracking/GPUTRDTrackletWord.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTrackletWord.h b/GPU/GPUTracking/TRDTracking/GPUTRDTrackletWord.h index 2ae5b562bb518..d5901182f2e5a 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTrackletWord.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTrackletWord.h @@ -58,7 +58,7 @@ class GPUTRDTrackletWord GPUd() int GetDetector() const { return mHCId / 2; } GPUd() int GetHCId() const { return mHCId; } GPUd() float GetdYdX() const { return (GetdYbin() * 140e-4f / 3.f); } - GPUd() float GetDy() const { return GetdYbin() * 140e-4f; } + GPUd() float GetdY() const { return GetdYbin() * 140e-4f; } GPUd() float GetY() const { return (GetYbin() * 160e-4f); } GPUd() unsigned int GetTrackletWord() const { return mTrackletWord; } From 58d7be839df30bb7786c6caaa224202864e6bf6f Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Tue, 9 Feb 2021 16:37:08 +0100 Subject: [PATCH 190/770] [ALIGN] vanilla copy from AliRoot --- Detectors/Align/ALIGNLinkDef.h | 32 + Detectors/Align/AliAlgAux.cxx | 137 ++ Detectors/Align/AliAlgAux.h | 132 ++ Detectors/Align/AliAlgConstraint.cxx | 343 +++++ Detectors/Align/AliAlgConstraint.h | 71 + Detectors/Align/AliAlgDOFStat.cxx | 89 ++ Detectors/Align/AliAlgDOFStat.h | 47 + Detectors/Align/AliAlgDet.cxx | 725 +++++++++ Detectors/Align/AliAlgDet.h | 217 +++ Detectors/Align/AliAlgDetHMPID.cxx | 70 + Detectors/Align/AliAlgDetHMPID.h | 33 + Detectors/Align/AliAlgDetITS.cxx | 305 ++++ Detectors/Align/AliAlgDetITS.h | 62 + Detectors/Align/AliAlgDetTOF.cxx | 77 + Detectors/Align/AliAlgDetTOF.h | 33 + Detectors/Align/AliAlgDetTPC.cxx | 83 ++ Detectors/Align/AliAlgDetTPC.h | 33 + Detectors/Align/AliAlgDetTRD.cxx | 154 ++ Detectors/Align/AliAlgDetTRD.h | 64 + Detectors/Align/AliAlgMPRecord.cxx | 325 ++++ Detectors/Align/AliAlgMPRecord.h | 102 ++ Detectors/Align/AliAlgPoint.cxx | 373 +++++ Detectors/Align/AliAlgPoint.h | 229 +++ Detectors/Align/AliAlgRes.cxx | 300 ++++ Detectors/Align/AliAlgRes.h | 128 ++ Detectors/Align/AliAlgResFast.cxx | 168 +++ Detectors/Align/AliAlgResFast.h | 92 ++ Detectors/Align/AliAlgSens.cxx | 487 ++++++ Detectors/Align/AliAlgSens.h | 99 ++ Detectors/Align/AliAlgSensHMPID.cxx | 150 ++ Detectors/Align/AliAlgSensHMPID.h | 36 + Detectors/Align/AliAlgSensITS.cxx | 131 ++ Detectors/Align/AliAlgSensITS.h | 36 + Detectors/Align/AliAlgSensTOF.cxx | 176 +++ Detectors/Align/AliAlgSensTOF.h | 40 + Detectors/Align/AliAlgSensTPC.cxx | 151 ++ Detectors/Align/AliAlgSensTPC.h | 41 + Detectors/Align/AliAlgSensTRD.cxx | 225 +++ Detectors/Align/AliAlgSensTRD.h | 42 + Detectors/Align/AliAlgSteer.cxx | 2052 ++++++++++++++++++++++++++ Detectors/Align/AliAlgSteer.h | 419 ++++++ Detectors/Align/AliAlgTrack.cxx | 1513 +++++++++++++++++++ Detectors/Align/AliAlgTrack.h | 220 +++ Detectors/Align/AliAlgVol.cxx | 837 +++++++++++ Detectors/Align/AliAlgVol.h | 214 +++ Detectors/Align/AliAlgVtx.cxx | 68 + Detectors/Align/AliAlgVtx.h | 49 + Detectors/Align/CMakeLists.txt | 113 ++ Detectors/Align/Mille.cxx | 226 +++ Detectors/Align/Mille.h | 58 + 50 files changed, 11807 insertions(+) create mode 100644 Detectors/Align/ALIGNLinkDef.h create mode 100644 Detectors/Align/AliAlgAux.cxx create mode 100644 Detectors/Align/AliAlgAux.h create mode 100644 Detectors/Align/AliAlgConstraint.cxx create mode 100644 Detectors/Align/AliAlgConstraint.h create mode 100644 Detectors/Align/AliAlgDOFStat.cxx create mode 100644 Detectors/Align/AliAlgDOFStat.h create mode 100644 Detectors/Align/AliAlgDet.cxx create mode 100644 Detectors/Align/AliAlgDet.h create mode 100644 Detectors/Align/AliAlgDetHMPID.cxx create mode 100644 Detectors/Align/AliAlgDetHMPID.h create mode 100644 Detectors/Align/AliAlgDetITS.cxx create mode 100644 Detectors/Align/AliAlgDetITS.h create mode 100644 Detectors/Align/AliAlgDetTOF.cxx create mode 100644 Detectors/Align/AliAlgDetTOF.h create mode 100644 Detectors/Align/AliAlgDetTPC.cxx create mode 100644 Detectors/Align/AliAlgDetTPC.h create mode 100644 Detectors/Align/AliAlgDetTRD.cxx create mode 100644 Detectors/Align/AliAlgDetTRD.h create mode 100644 Detectors/Align/AliAlgMPRecord.cxx create mode 100644 Detectors/Align/AliAlgMPRecord.h create mode 100644 Detectors/Align/AliAlgPoint.cxx create mode 100644 Detectors/Align/AliAlgPoint.h create mode 100644 Detectors/Align/AliAlgRes.cxx create mode 100644 Detectors/Align/AliAlgRes.h create mode 100644 Detectors/Align/AliAlgResFast.cxx create mode 100644 Detectors/Align/AliAlgResFast.h create mode 100644 Detectors/Align/AliAlgSens.cxx create mode 100644 Detectors/Align/AliAlgSens.h create mode 100644 Detectors/Align/AliAlgSensHMPID.cxx create mode 100644 Detectors/Align/AliAlgSensHMPID.h create mode 100644 Detectors/Align/AliAlgSensITS.cxx create mode 100644 Detectors/Align/AliAlgSensITS.h create mode 100644 Detectors/Align/AliAlgSensTOF.cxx create mode 100644 Detectors/Align/AliAlgSensTOF.h create mode 100644 Detectors/Align/AliAlgSensTPC.cxx create mode 100644 Detectors/Align/AliAlgSensTPC.h create mode 100644 Detectors/Align/AliAlgSensTRD.cxx create mode 100644 Detectors/Align/AliAlgSensTRD.h create mode 100644 Detectors/Align/AliAlgSteer.cxx create mode 100644 Detectors/Align/AliAlgSteer.h create mode 100644 Detectors/Align/AliAlgTrack.cxx create mode 100644 Detectors/Align/AliAlgTrack.h create mode 100644 Detectors/Align/AliAlgVol.cxx create mode 100644 Detectors/Align/AliAlgVol.h create mode 100644 Detectors/Align/AliAlgVtx.cxx create mode 100644 Detectors/Align/AliAlgVtx.h create mode 100644 Detectors/Align/CMakeLists.txt create mode 100644 Detectors/Align/Mille.cxx create mode 100644 Detectors/Align/Mille.h diff --git a/Detectors/Align/ALIGNLinkDef.h b/Detectors/Align/ALIGNLinkDef.h new file mode 100644 index 0000000000000..8b1a36a5b8ca5 --- /dev/null +++ b/Detectors/Align/ALIGNLinkDef.h @@ -0,0 +1,32 @@ +#ifdef __CINT__ + +#pragma link off all globals; +#pragma link off all classes; +#pragma link off all functions; + +//#pragma link C++ class AliAlgAux; +#pragma link C++ class AliAlgDet+; +#pragma link C++ class AliAlgDetITS+; +#pragma link C++ class AliAlgDetTOF+; +#pragma link C++ class AliAlgDetTPC+; +#pragma link C++ class AliAlgDetTRD+; +#pragma link C++ class AliAlgDetHMPID+; +#pragma link C++ class AliAlgMPRecord+; +#pragma link C++ class AliAlgPoint+; +#pragma link C++ class AliAlgSens+; +#pragma link C++ class AliAlgSensITS+; +#pragma link C++ class AliAlgSensTOF+; +#pragma link C++ class AliAlgSensTPC+; +#pragma link C++ class AliAlgSensTRD+; +#pragma link C++ class AliAlgSensHMPID+; +#pragma link C++ class AliAlgSteer+; +#pragma link C++ class AliAlgTrack+; +#pragma link C++ class AliAlgVol+; +#pragma link C++ class AliAlgVtx+; +#pragma link C++ class AliAlgRes+; +#pragma link C++ class AliAlgResFast+; +#pragma link C++ class AliAlgConstraint+; +#pragma link C++ class AliAlgDOFStat+; +#pragma link C++ class AliAlgAux; + +#endif diff --git a/Detectors/Align/AliAlgAux.cxx b/Detectors/Align/AliAlgAux.cxx new file mode 100644 index 0000000000000..bcf2d697585d7 --- /dev/null +++ b/Detectors/Align/AliAlgAux.cxx @@ -0,0 +1,137 @@ +/************************************************************************** + * 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. * + **************************************************************************/ + +#include "AliAlgAux.h" +#include "AliCDBId.h" +#include "AliCDBManager.h" +#include "AliLog.h" +#include +#include +#include +#include +#include +#include + +//_______________________________________________________________ +void AliAlgAux::PrintBits(ULong64_t patt, Int_t maxBits) +{ + // print maxBits of the pattern + maxBits = Min(64,maxBits); + for (int i=0;i>i)&0x1) ? '+':'-'); +} + +//_______________________________________________________________ +AliCDBId* AliAlgAux::FindCDBId(const TList* cdbList,const TString& key) +{ + // Find enty for the key in the cdbList and create its CDBId + // User must take care of deleting created CDBId + TIter next(cdbList); + TObjString* entry; + while ( (entry=(TObjString*)next()) ) if (entry->GetString().Contains(key)) break; + if (!entry) return 0; + return AliCDBId::MakeFromString(entry->GetString()); + // +} + +//_________________________________________________________ +void AliAlgAux::RectifyOCDBUri(TString& inp) +{ + // render URI from cdbMap to usable form + TString uri = ""; + int ind; + if (inp.BeginsWith("alien:/")) { // alien folder + TPRegexp fr("[Ff]older=/"); + if ( (ind=inp.Index(fr))>0 ) inp.Remove(0,ind); + ind = inp.First('?'); + if (ind>0) inp.Resize(ind); + inp.Prepend("alien://"); + } + else if (inp.BeginsWith("local:/")) { + ind = inp.First('?'); + if (ind>0) inp.Resize(ind); + } + else { + AliFatalGeneralF("::RectifyOCDBUri","Failed to extract OCDB URI from %s",inp.Data()); + } + // +} + +//_________________________________________________________ +Bool_t AliAlgAux::PreloadOCDB(int run, const TMap* cdbMap, const TList* cdbList) +{ + // Load OCDB paths for given run from pair of cdbMap / cdbList + // as they are usually stored in the UserInfo list of esdTree + // In order to avoid unnecessary uploads, the objects are not actually + // loaded/cached but just added as specific paths with version + // + TObjString *ostr,*okey; + TString uriDef,uri,key; + // + CleanOCDB(); + // + ostr = (TObjString*)cdbMap->GetValue("default"); + RectifyOCDBUri( uriDef=ostr->GetString() ); + AliInfoGeneralF("","Default storage %s",uriDef.Data()); + // + AliCDBManager* man = AliCDBManager::Instance(); + man->SetDefaultStorage(uriDef.Data()); + man->SetRun(run); + // + TIter nextM(cdbMap); + while ( (okey=(TObjString*)nextM()) ) { + if ( (key=okey->GetString())=="default") continue; + ostr = (TObjString*)cdbMap->GetValue(okey); + RectifyOCDBUri( uri=ostr->GetString() ); + // fetch object from the list + AliCDBId* cdbID = FindCDBId(cdbList,key); + int ver=-1,sver=-1; + if (cdbID) { + ver = cdbID->GetVersion(); + sver= cdbID->GetSubVersion(); + delete cdbID; + } + else { + AliWarningGeneralF("::PreloadOCDB","Key %s has special storage %s but absent in the cdbList", + key.Data(),uri.Data()); + } + AliInfoGeneralF("::PreloadOCDB","Setting storage for %s to %s",key.Data(),uri.Data()); + man->SetSpecificStorage(key.Data(),uri.Data(),ver,sver); + } + // + return kTRUE; +} + +//_________________________________________________________ +void AliAlgAux::CleanOCDB() +{ + // brings OCDB to virgin state + Bool_t isGrid = gGrid!=0; + AliCDBManager::Destroy(); + if (isGrid && !gGrid) TGrid::Connect("alien://"); +} + +//__________________________________________ +int AliAlgAux::FindKeyIndex(int key, const int *arr, int n) +{ + // finds index of key in the array + int imn=0,imx=n-1; + while (imx>=imn) { + int mid = (imx+imn)>>1; + if (arr[mid]==key) return mid; + if (arr[mid] +#include +class AliCDBId; +class TMap; +class TList; + +using namespace TMath; + +/*-------------------------------------------------------- + Collection of auxillary methods + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + + +namespace AliAlgAux { + const double kAlmostZeroD = 1e-15; + const float kAlmostZeroF = 1e-11; + const double kAlmostOneD = 1.-kAlmostZeroD; + const float kAlmostOneF = 1.-kAlmostZeroF; + const double kTinyDist = 1.e-7; // ignore distances less that this + // + enum {kColl,kCosm,kNTrackTypes}; + // + inline Double_t Sector2Alpha(int sect); + inline Int_t Phi2Sector(double alpha); + inline Double_t SectorDAlpha() {return Pi()/9;} + // + template void BringTo02Pi(F &phi); + template void BringToPiPM(F &phi); + template Bool_t OKforPhiMin(F phiMin,F phi); + template Bool_t OKforPhiMax(F phiMax,F phi); + template F MeanPhiSmall(F phi0, F phi1); + template F DeltaPhiSmall(F phi0, F phi1); + template Bool_t SmallerAbs(F d, F tolD) {return Abs(d) Bool_t Smaller(F d, F tolD) {return d +inline void AliAlgAux::BringTo02Pi(F &phi) { + // bring phi to 0-2pi range + if (phi<0) phi+=TwoPi(); else if (phi>TwoPi()) phi-=TwoPi(); +} + +//_________________________________________________________________________________ +template +inline void AliAlgAux::BringToPiPM(F &phi) { + // bring phi to -pi:pi range + if (phi>Pi()) phi-=TwoPi(); +} +//_________________________________________________________________________________ +template +inline Bool_t AliAlgAux::OKforPhiMin(F phiMin,F phi) { + // check if phi is above the phiMin, phi's must be in 0-2pi range + F dphi = phi-phiMin; + return ((dphi>0 && dphi +inline Bool_t AliAlgAux::OKforPhiMax(F phiMax,F phi) { + // check if phi is below the phiMax, phi's must be in 0-2pi range + F dphi = phi-phiMax; + return ((dphi<0 && dphi>-Pi()) || dphi>Pi()) ? kTRUE:kFALSE; +} + +//_________________________________________________________________________________ +template +inline F AliAlgAux::MeanPhiSmall(F phi0, F phi1) { + // return mean phi, assume phis in 0:2pi + F phi; + if (!OKforPhiMin(phi0,phi1)) {phi=phi0; phi0=phi1; phi1=phi;} + if (phi0>phi1) phi = (phi1 - (TwoPi()-phi0))/2; // wrap + else phi = (phi0+phi1)/2; + BringTo02Pi(phi); + return phi; +} + +//_________________________________________________________________________________ +template +inline F AliAlgAux::DeltaPhiSmall(F phi0, F phi1) { + // return delta phi, assume phis in 0:2pi + F del; + if (!OKforPhiMin(phi0,phi1)) {del=phi0; phi0=phi1; phi1=del;} + del = phi1 - phi0; + if (del<0) del += TwoPi(); + return del; +} + +//_________________________________________________________________________________ +inline Int_t AliAlgAux::NumberOfBitsSet(UInt_t x) { + // count number of non-0 bits in 32bit word + x = x - ((x >> 1) & 0x55555555); + x = (x & 0x33333333) + ((x >> 2) & 0x33333333); + return (((x + (x >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; +} + +//_________________________________________________________________________________ +inline Double_t AliAlgAux::Sector2Alpha(int sect) { + // get barrel sector alpha in -pi:pi format + if (sect>8)sect-=18; return (sect+0.5)*SectorDAlpha(); +} + +//_________________________________________________________________________________ +inline Int_t AliAlgAux::Phi2Sector(double phi) { + // get barrel sector from phi in -pi:pi format + int sect = Nint( (phi*RadToDeg()-10)/20. ); + if (sect<0) sect+=18; + return sect; +} + +#endif diff --git a/Detectors/Align/AliAlgConstraint.cxx b/Detectors/Align/AliAlgConstraint.cxx new file mode 100644 index 0000000000000..844fc7f66dcf8 --- /dev/null +++ b/Detectors/Align/AliAlgConstraint.cxx @@ -0,0 +1,343 @@ +/************************************************************************** + * 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. * + **************************************************************************/ + +#include "AliAlgConstraint.h" +#include "AliAlignObjParams.h" +#include "AliAlgAux.h" +#include "AliLog.h" +#include +#include +#include + +ClassImp(AliAlgConstraint); + +using namespace AliAlgAux; +using namespace TMath; + +//___________________________________________________________________ +AliAlgConstraint::AliAlgConstraint(const char* name,const char* title) + :TNamed(name,title) + ,fConstraint(0) + ,fParent(0) + ,fChildren(2) +{ + // def. c-tor + for (int i=kNDOFGeom;i--;) fSigma[i] = 0; +} + +//___________________________________________________________________ +AliAlgConstraint::~AliAlgConstraint() +{ + // d-tor + delete fParent; +} + +//___________________________________________________________________ +void AliAlgConstraint::SetParent(const AliAlgVol* par) +{ + fParent = par; + TString nm = GetName(); + if (nm.IsNull()) { + if (par) SetNameTitle(par->GetSymName(),"Automatic"); + else SetNameTitle("GLOBAL","Automatic"); + } +} + + +//______________________________________________________ +void AliAlgConstraint::WriteChildrenConstraints(FILE* conOut) const +{ + // write for PEDE eventual constraints on children movement in parent frame + // + enum {kOff,kOn,kOnOn}; + enum {kConstr,kMeas}; + const char* comment[3] = {" ","! ","!!"}; + const char* kKeyConstr[2] = {"constraint","measurement"}; + // + Bool_t doJac = !GetNoJacobian(); // do we need jacobian evaluation? + int nch = GetNChildren(); + float *cstrArr = new float[nch*kNDOFGeom*kNDOFGeom]; + memset(cstrArr,0,nch*kNDOFGeom*kNDOFGeom*sizeof(float)); + // we need for each children the matrix for vector transformation from children frame + // (in which its DOFs are defined, LOC or TRA) to this parent variation frame + // matRel = mPar^-1*mChild + TGeoHMatrix mPar; + // + // in case of parent assigned use its matrix, + // otherwise Alice global frame is assumed to be the parent -> Unit matrix + if (fParent && doJac) { + if (fParent->IsFrameTRA()) fParent->GetMatrixT2G(mPar); // tracking to global + else mPar = fParent->GetMatrixL2GIdeal(); // local to global + mPar = mPar.Inverse(); + } + // + float *jac = cstrArr; + int nContCh[kNDOFGeom] = {0}; // we need at least on contributing children DOF to constrain the parent DOF + for (int ich=0;ichIsFrameTRA()) child->GetMatrixT2G(matRel); // tracking to global + else matRel = child->GetMatrixL2GIdeal(); // local to global + matRel.MultiplyLeft(&mPar); + ConstrCoefGeom(matRel,jac); + // + for (int ics=0;icsIsFreeDOF(ip) && child->GetParErr(ip)>=0) nContCh[ip]++; + } + } + } + else { // simple constraint on the sum of requested DOF + // + for (int ip=0;ipIsFreeDOF(ip) && child->GetParErr(ip)>=0) nContCh[ip]++; + jac[ip*kNDOFGeom+ip] = 1.; + } + } + jac += kNDOFGeom*kNDOFGeom; // matrix for next slot + } + // + for (int ics=0;ics0 ? kOff : kOn; // do we comment this constraint? + // + if (cmtStatus) AliInfoF("No contributors to constraint of %3s of %s",GetDOFName(ics),GetName()); + // + if (fSigma[ics]>0) { + fprintf(conOut,"\n%s%s\t%e\t%e\t%s %s of %s %s\n",comment[cmtStatus],kKeyConstr[kMeas],0.0,fSigma[ics], + comment[kOnOn],GetDOFName(ics),GetName(),GetTitle()); + } + else { + fprintf(conOut,"\n%s%s\t%e\t%s %s of %s %s\n",comment[cmtStatus],kKeyConstr[kConstr],0.0, + comment[kOnOn],GetDOFName(ics),GetName(),GetTitle()); + } + for (int ich=0;ichIsFreeDOF(ip)&&!IsZeroAbs(jv)&& child->GetParErr(ip)>=0) + fprintf(conOut,"%9d %+.3e\t",child->GetParLab(ip),jv); + } // loop over DOF's of children contributing to this constraint + // now, after comment, write disabled constraints + fprintf(conOut,"%s ",comment[kOn]); + if (doJac) { + for (int ip=0;ipIsFreeDOF(ip)&&!IsZeroAbs(jv)&& child->GetParErr(ip)>=0) continue; + fprintf(conOut,"%9d %+.3e\t",child->GetParLab(ip),jv); + } // loop over DOF's of children contributing to this constraint + } + fprintf(conOut,"%s from %s\n",comment[kOnOn],child->GetName()); + } // loop over children + } // loop over constraints in parent volume + // + delete[] cstrArr; +} + +//______________________________________________________ +void AliAlgConstraint::CheckConstraint() const +{ + // check how the constraints are satysfied + // + int nch = GetNChildren(); + if (!nch) return; + // + Bool_t doJac = !GetNoJacobian(); // do we need jacobian evaluation? + float *cstrArr = new float[nch*kNDOFGeom*kNDOFGeom]; + memset(cstrArr,0,nch*kNDOFGeom*kNDOFGeom*sizeof(float)); + // we need for each children the matrix for vector transformation from children frame + // (in which its DOFs are defined, LOC or TRA) to this parent variation frame + // matRel = mPar^-1*mChild + TGeoHMatrix mPar; + // in case of parent assigned use its matrix, + // otherwise Alice global frame is assumed to be the parent -> Unit matrix + if (fParent && doJac) { + if (fParent->IsFrameTRA()) fParent->GetMatrixT2G(mPar); // tracking to global + else mPar = fParent->GetMatrixL2GIdeal(); // local to global + mPar = mPar.Inverse(); + } + // + float *jac = cstrArr; + double parsTotEx[kNDOFGeom] = {0}; // explicitly calculated total modification + double parsTotAn[kNDOFGeom] = {0}; // analyticaly calculated total modification + // + printf("\n\n ----- Constraints Validation for %s %s ------\n",GetName(),GetTitle()); + printf(" chld| "); + for (int jp=0;jpGetParVal(jc); // child params in child frame + printf("#%3d | ",ich); + // + if (doJac) { + TGeoHMatrix matRel; + if (child->IsFrameTRA()) child->GetMatrixT2G(matRel); // tracking to global + else matRel = child->GetMatrixL2GIdeal(); // local to global + // + matRel.MultiplyLeft(&mPar); + ConstrCoefGeom(matRel,jac); // Jacobian for analytical constraint used by MillePeded + // + TGeoHMatrix tau; + child->Delta2Matrix(tau,parsC); // child correction matrix in the child frame + const TGeoHMatrix& matreli = matRel.Inverse(); + tau.Multiply(&matreli); + tau.MultiplyLeft(&matRel); // child correction matrix in the parent frame + AliAlignObjParams tmpPar; + tmpPar.SetMatrix(tau); + tmpPar.GetTranslation(&parsPEx[0]); + tmpPar.GetAngles(&parsPEx[3]); // explicitly calculated child params in parent frame + // + // analytically calculated child params in parent frame + for (int jp=0;jpIsFreeDOF(jc) && child->GetParErr(jc)>=0; + if (acc) { printf(" %+.3e ",parsC[jc]); parsTotAn[jc] += parsC[jc];} + else printf(" /* %+.3e */ ",parsC[jc]); // just for info, not in the constraint + } + } + printf(" | "); + for (int jc=0;jcGetSymName()); + } + // + printf(" Tot | "); + for (int jp=0;jpGetParVal(jp)); // parent proper corrections + else printf(" no parent -> %s ",doJac ? "Global":"Simple"); + printf(" ! <----- %s\n",GetName()); + // + printf(" Sig | "); + for (int jp=0;jpX approximation... + const double cf[kNDOFGeom] = {1,1,1,DegToRad(),DegToRad(),DegToRad()}; + // + // since the TAU is supposed to convert local corrections in the child frame to corrections + // in the parent frame, we scale angular degrees of freedom back to degrees and assign the + // sign of S in the S*sin(angle) in the matrix, so that the final correction has a correct + // sign, due to the choice of euler angles in the AliAlignObj::AnglesToMatrix + // costhe*cosphi; -costhe*sinphi; sinthe; + // sinpsi*sinthe*cosphi + cospsi*sinphi; -sinpsi*sinthe*sinphi + cospsi*cosphi; -costhe*sinpsi; + // -cospsi*sinthe*cosphi + sinpsi*sinphi; cospsi*sinthe*sinphi + sinpsi*cosphi; costhe*cospsi; + // + const double kJTol = 1e-4; // treat derivatives below this threshold as 0 + const double sgc[kNDOFGeom] = {1.,1.,1.,-RadToDeg(),RadToDeg(),-RadToDeg()}; + // + double dDPar[kNDOFGeom][4][4] = { + // dDX[4][4] + {{0,0,0,0},{0,0,0,0},{0,0,0,0},{rd[0],rd[3],rd[6],0}}, + // dDY[4][4] + {{0,0,0,0},{0,0,0,0},{0,0,0,0},{rd[1],rd[4],rd[7],0}}, + // dDZ[4][4] + {{0,0,0,0},{0,0,0,0},{0,0,0,0},{rd[2],rd[5],rd[8],0}}, + // dDPSI[4][4] + {{rd[2]*ri[3]-rd[1]*ri[6],rd[2]*ri[4]-rd[1]*ri[7],rd[2]*ri[5]-rd[1]*ri[8],0}, + {rd[5]*ri[3]-rd[4]*ri[6],rd[5]*ri[4]-rd[4]*ri[7],rd[5]*ri[5]-rd[4]*ri[8],0}, + {rd[8]*ri[3]-rd[7]*ri[6],rd[8]*ri[4]-rd[7]*ri[7],rd[8]*ri[5]-rd[7]*ri[8],0}, + {rd[2]*ti[1]-rd[1]*ti[2],rd[5]*ti[1]-rd[4]*ti[2],rd[8]*ti[1]-rd[7]*ti[2],0}}, + // dDTHT[4][4] + {{rd[0]*ri[6]-rd[2]*ri[0], rd[0]*ri[7]-rd[2]*ri[1], rd[0]*ri[8]-rd[2]*ri[2],0}, + {rd[3]*ri[6]-rd[5]*ri[0], rd[3]*ri[7]-rd[5]*ri[1], rd[3]*ri[8]-rd[5]*ri[2],0}, + {rd[6]*ri[6]-rd[8]*ri[0], rd[6]*ri[7]-rd[8]*ri[1], rd[6]*ri[8]-rd[8]*ri[2],0}, + {rd[0]*ti[2]-rd[2]*ti[0], rd[3]*ti[2]-rd[5]*ti[0], rd[6]*ti[2]-rd[8]*ti[0],0}}, + // dDPHI[4][4] + {{rd[1]*ri[0]-rd[0]*ri[3],rd[1]*ri[1]-rd[0]*ri[4],rd[1]*ri[2]-rd[0]*ri[5],0}, + {rd[4]*ri[0]-rd[3]*ri[3],rd[4]*ri[1]-rd[3]*ri[4],rd[4]*ri[2]-rd[3]*ri[5],0}, + {rd[7]*ri[0]-rd[6]*ri[3],rd[7]*ri[1]-rd[6]*ri[4],rd[7]*ri[2]-rd[6]*ri[5],0}, + {rd[1]*ti[0]-rd[0]*ti[1],rd[4]*ti[0]-rd[3]*ti[1],rd[7]*ti[0]-rd[6]*ti[1],0}}, + }; + // + for (int cs=0;cskJTol) ? jval : 0; // [cs][ip] + } + } +} + +//______________________________________________________ +void AliAlgConstraint::Print(const Option_t *) const +{ + // print info + printf("Constraint on "); + for (int i=0;iGetName()); + } +} diff --git a/Detectors/Align/AliAlgConstraint.h b/Detectors/Align/AliAlgConstraint.h new file mode 100644 index 0000000000000..a59d61e3ec6a4 --- /dev/null +++ b/Detectors/Align/AliAlgConstraint.h @@ -0,0 +1,71 @@ +#ifndef ALIALGCONSTRAINT_H +#define ALIALGCONSTRAINT_H + +#include +#include +#include +#include "AliAlgVol.h" + +/*-------------------------------------------------------- + Descriptor of geometrical constraint: the cumulative + corrections of children for requested DOFs in the frame of + parent (of LAB if parent is not defined) forced to be 0. + The parent - child relationship need not to be real + + Constraint wil be quazi-exact (Lagrange multiplier) if + corresponding sigma = 0, or of gaussian type is sigma>0 + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + + +class AliAlgConstraint : public TNamed +{ + public: + enum {kNDOFGeom=AliAlgVol::kNDOFGeom}; + enum {kNoJacobianBit=BIT(14)}; + // + AliAlgConstraint(const char* name=0,const char* title=0); + virtual ~AliAlgConstraint(); + // + void SetParent(const AliAlgVol* par); + const AliAlgVol* GetParent() const {return fParent;} + // + Int_t GetNChildren() const {return fChildren.GetEntriesFast();} + AliAlgVol* GetChild(int i) const {return (AliAlgVol*)fChildren[i];} + void AddChild(const AliAlgVol* v) {if (v) fChildren.AddLast((AliAlgVol*)v);} + // + Bool_t IsDOFConstrained(Int_t dof) const {return fConstraint&0x1< +#include + +using namespace TMath; + +ClassImp(AliAlgDOFStat) + +//_________________________________________________________ +AliAlgDOFStat::AliAlgDOFStat(Int_t n) + : TNamed("DOFstat","DOF statistics") + ,fNDOFs(n) + ,fNMerges(1) + ,fStat(0) +{ + // def c-tor + if (fNDOFs) { + fStat = new Int_t[n]; + memset(fStat,0,fNDOFs*sizeof(Int_t)); + } + // +} + +//_________________________________________________________ +AliAlgDOFStat::~AliAlgDOFStat() +{ + // d-r + delete[] fStat; +} + + +//____________________________________________ +void AliAlgDOFStat::Print(Option_t*) const +{ + // print info + printf("NDOFs: %d, NMerges: %d\n",fNDOFs,fNMerges); + // +} + +//____________________________________________ +TH1F* AliAlgDOFStat::CreateHisto(AliAlgSteer* st) const +{ + // create histo with stat. If steer object is supplied, build labels + if (!fNDOFs) return 0; + TH1F* h = new TH1F("DOFstat","statistics per DOF",fNDOFs,0,fNDOFs); + for (int i=fNDOFs;i--;) { + h->SetBinContent(i+1,fStat[i]); + if (st) h->GetXaxis()->SetBinLabel(i+1,st->GetDOFLabelTxt(i)); + } + return h; +} + +//______________________________________________________________________________ +Long64_t AliAlgDOFStat::Merge(TCollection *list) +{ + // merge statistics + int nmerged = 0; + TIter next(list); + TObject *obj; + while((obj=next())) { + AliAlgDOFStat* stAdd = dynamic_cast(obj); + if (!stAdd) continue; + if (fNDOFs != stAdd->fNDOFs) { + AliErrorF("Different NDOF: %d vs %d",fNDOFs,stAdd->fNDOFs); + return 0; + } + for (int i=fNDOFs;i--;) fStat[i]+=stAdd->fStat[i]; + fNMerges += stAdd->fNMerges; + nmerged++; + } + return nmerged; +} diff --git a/Detectors/Align/AliAlgDOFStat.h b/Detectors/Align/AliAlgDOFStat.h new file mode 100644 index 0000000000000..96de03687fc06 --- /dev/null +++ b/Detectors/Align/AliAlgDOFStat.h @@ -0,0 +1,47 @@ +#ifndef ALIALGDOFSTAT_H +#define ALIALGDOFSTAT_H + +/*-------------------------------------------------------- + Mergable bbject for statistics of points used by each DOF + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + +#include +class AliAlgSteer; +class TH1F; +class TCollection; + +class AliAlgDOFStat : public TNamed +{ + public: + AliAlgDOFStat(Int_t n=0); + virtual ~AliAlgDOFStat(); + // + Int_t GetNDOFs() const {return fNDOFs;} + Int_t GetStat(int idf) const {return idf +#include +#include +#include +#include + +ClassImp(AliAlgDet) + +using namespace AliAlgAux; + +//____________________________________________ +AliAlgDet::AliAlgDet() +: fNDOFs(0) + ,fVolIDMin(-1) + ,fVolIDMax(-1) + ,fNSensors(0) + ,fSID2VolID(0) + ,fNProcPoints(0) + // + ,fNCalibDOF(0) + ,fNCalibDOFFree(0) + ,fCalibDOF(0) + ,fFirstParGloID(-1) + ,fParVals(0) + ,fParErrs(0) + ,fParLabs(0) + // + ,fUseErrorParam(0) + ,fSensors() + ,fVolumes() + // + ,fNPoints(0) + ,fPoolNPoints(0) + ,fPoolFreePointID(0) + ,fPointsPool() + ,fAlgSteer(0) +{ + // def c-tor + SetUniqueID(AliAlgSteer::kUndefined); // derived detectors must override this + fAddError[0] = fAddError[1] = 0; + // + for (int i=0;iGetFriendTrack()); + const AliTrackPointArray* trP(trF->GetTrackPointArray()); + // + int np(trP->GetNPoints()); + int npSel(0); + AliAlgPoint* apnt(0); + for (int ip=0;ipGetVolumeID()[ip]; + if (!SensorOfDetector(vid)) continue; + apnt = GetSensorByVolId(vid)->TrackPoint2AlgPoint(ip, trP, esdTr); + if (!apnt) continue; + algTrack->AddPoint(apnt); + if (inv) apnt->SetInvDir(); + npSel++; + fNPoints++; + } + // + return npSel; +} + +//_________________________________________________________ +void AliAlgDet::AcknowledgeNewRun(Int_t run) +{ + // update parameters needed to process this run + + // detector should be able to undo alignment/calibration used during the reco + UpdateL2GRecoMatrices(); + +} + +//_________________________________________________________ +void AliAlgDet::UpdateL2GRecoMatrices() +{ + // Update L2G matrices used for data reconstruction + // + AliCDBManager* man = AliCDBManager::Instance(); + AliCDBEntry* ent = man->Get(Form("%s/Align/Data",GetName())); + const TClonesArray *algArr = (const TClonesArray*)ent->GetObject(); + // + int nvol = GetNVolumes(); + for (int iv=0;ivGetParent()) vol->UpdateL2GRecoMatrices(algArr,0); + } + // +} + + +//_________________________________________________________ +void AliAlgDet::ApplyAlignmentFromMPSol() +{ + // apply alignment from millepede solution array to reference alignment level + AliInfo("Applying alignment from Millepede solution"); + for (int isn=GetNSensors();isn--;) GetSensor(isn)->ApplyAlignmentFromMPSol(); +} + +//_________________________________________________________ +void AliAlgDet::CacheReferenceOCDB() +{ + // if necessary, detector may fetch here some reference OCDB data + // + // cache global deltas to avoid preicision problem + AliCDBManager* man = AliCDBManager::Instance(); + AliCDBEntry* ent = man->Get(Form("%s/Align/Data",GetName())); + TObjArray* arr = (TObjArray*)ent->GetObject(); + for (int i=arr->GetEntriesFast();i--;) { + const AliAlignObjParams* par = (const AliAlignObjParams*)arr->At(i); + AliAlgVol* vol = GetVolume(par->GetSymName()); + if (!vol) {AliErrorF("Volume %s not found",par->GetSymName()); continue;} + TGeoHMatrix delta; + par->GetMatrix(delta); + vol->SetGlobalDeltaRef(delta); + } +} + + +//_________________________________________________________ +AliAlgPoint* AliAlgDet::GetPointFromPool() +{ + // fetch or create new free point from the pool. + // detector may override this method to create its own points derived from AliAlgPoint + // + if (fPoolFreePointID>=fPoolNPoints) { // expand pool + fPointsPool.AddAtAndExpand(new AliAlgPoint(), fPoolNPoints++); + } + // + AliAlgPoint* pnt = (AliAlgPoint*) fPointsPool.UncheckedAt(fPoolFreePointID++); + pnt->Clear(); + return pnt; + // +} + +//_________________________________________________________ +void AliAlgDet::ResetPool() +{ + // declare pool free + fPoolFreePointID = 0; + fNPoints = 0; +} + +//_________________________________________________________ +void AliAlgDet::DefineVolumes() +{ + // dummy method + AliError("This method must be implemented by specific detector"); +} + +//_________________________________________________________ +void AliAlgDet::AddVolume(AliAlgVol* vol) +{ + // add volume + if (GetVolume(vol->GetSymName())) { + AliFatalF("Volume %s was already added to %s",vol->GetName(),GetName()); + } + fVolumes.AddLast(vol); + if (vol->IsSensor()) { + fSensors.AddLast(vol); + ((AliAlgSens*)vol)->SetDetector(this); + Int_t vid = ((AliAlgSens*)vol)->GetVolID(); + if (fVolIDMin<0 || vidfVolIDMax) fVolIDMax = vid; + } + // +} + +//_________________________________________________________ +void AliAlgDet::DefineMatrices() +{ + // define transformation matrices. Detectors may override this method + // + TGeoHMatrix mtmp; + // + TIter next(&fVolumes); + AliAlgVol* vol(0); + while ( (vol=(AliAlgVol*)next()) ) { + // modified global-local matrix + vol->PrepareMatrixL2G(); + // ideal global-local matrix + vol->PrepareMatrixL2GIdeal(); + // + } + // Now set tracking-local matrix (MUST be done after ALL L2G matrices are done!) + // Attention: for sensor it is a real tracking matrix extracted from + // the geometry but for container alignable volumes the tracking frame + // is used for as the reference for the alignment parameters only, + // see its definition in the AliAlgVol::PrepateMatrixT2L + next.Reset(); + while ( (vol=(AliAlgVol*)next()) ) { + vol->PrepareMatrixT2L(); + if (vol->IsSensor()) ((AliAlgSens*)vol)->PrepareMatrixClAlg(); // alignment matrix + } + // +} + +//_________________________________________________________ +void AliAlgDet::SortSensors() +{ + // build local tables for internal numbering + fNSensors = fSensors.GetEntriesFast(); + if (!fNSensors) { + AliWarning("No sensors defined"); + return; + } + fSensors.Sort(); + fSID2VolID = new Int_t[fNSensors]; // cash id's for fast binary search + for (int i=0;iGetVolID(); + GetSensor(i)->SetSID(i); + } + // +} + +//_________________________________________________________ +Int_t AliAlgDet::InitGeom() +{ + // define hiearchy, initialize matrices, return number of global parameters + if (GetInitGeomDone()) return 0; + // + DefineVolumes(); + SortSensors(); // VolID's must be in increasing order + DefineMatrices(); + // + // calculate number of global parameters + int nvol = GetNVolumes(); + fNDOFs = 0; + for (int iv=0;ivGetNDOFs(); + } + // + fNDOFs += fNCalibDOF; + SetInitGeomDone(); + return fNDOFs; +} + +//_________________________________________________________ +Int_t AliAlgDet::AssignDOFs() +{ + // assign DOFs IDs, parameters + // + int gloCount0(fAlgSteer->GetNDOFs()), gloCount(fAlgSteer->GetNDOFs()); + Float_t* pars = fAlgSteer->GetGloParVal(); + Float_t* errs = fAlgSteer->GetGloParErr(); + Int_t* labs = fAlgSteer->GetGloParLab(); + // + // assign calibration DOFs + fFirstParGloID = gloCount; + fParVals = pars + gloCount; + fParErrs = errs + gloCount; + fParLabs = labs + gloCount; + for (int icl=0;iclGetParent()) vol->AssignDOFs(gloCount,pars,errs,labs); + } + // + + if (fNDOFs != gloCount-gloCount0) AliFatalF("Mismatch between declared %d and initialized %d DOFs for %s", + fNDOFs,gloCount-gloCount0,GetName()); + + return fNDOFs; +} + +//_________________________________________________________ +void AliAlgDet::InitDOFs() +{ + // initialize free parameters + if (GetInitDOFsDone()) AliFatalF("Something is wrong, DOFs are already initialized for %s",GetName()); + // + // process calibration DOFs + for (int i=0;iInitDOFs(); + // + CalcFree(kTRUE); + // + SetInitDOFsDone(); + return; +} + +//_________________________________________________________ +Int_t AliAlgDet::VolID2SID(Int_t vid) const +{ + // find SID corresponding to VolID + int mn(0),mx(fNSensors-1); + while (mx>=mn) { + int md( (mx+mn)>>1 ), vids(GetSensor(md)->GetVolID()); + if (vidvids) mn = md+1; + else return md; + } + return -1; +} + +//____________________________________________ +void AliAlgDet::Print(const Option_t *opt) const +{ + // print info + TString opts = opt; + opts.ToLower(); + printf("\nDetector:%5s %5d volumes %5d sensors {VolID: %5d-%5d} Def.Sys.Err: %.4e %.4e | Stat:%d\n", + GetName(),GetNVolumes(),GetNSensors(),GetVolIDMin(), + GetVolIDMax(),fAddError[0],fAddError[1],fNProcPoints); + // + printf("Errors assignment: "); + if (fUseErrorParam) printf("param %d\n",fUseErrorParam); + else printf("from TrackPoints\n"); + // + printf("Allowed in Collisions: %7s | Cosmic: %7s\n", + IsDisabled(kColl) ? " NO ":" YES ",IsDisabled(kCosm) ? " NO ":" YES "); + // + printf("Obligatory in Collisions: %7s | Cosmic: %7s\n", + IsObligatory(kColl) ? " YES ":" NO ",IsObligatory(kCosm) ? " YES ":" NO "); + // + printf("Sel. flags in Collisions: 0x%05lx | Cosmic: 0x%05lx\n", + fTrackFlagSel[kColl],fTrackFlagSel[kCosm]); + // + printf("Min.points in Collisions: %7d | Cosmic: %7d\n", + fNPointsSel[kColl],fNPointsSel[kCosm]); + // + if (!(IsDisabledColl()&&IsDisabledCosm()) && opts.Contains("long")) + for (int iv=0;ivPrint(opt); + // + for (int i=0;i=AliAlgSteer::kNDetectors) AliFatalF("Detector typeID %d exceeds allowed range %d:%d", + tp,0,AliAlgSteer::kNDetectors-1); + SetUniqueID(tp); +} + +//____________________________________________ +void AliAlgDet::SetAddError(double sigy, double sigz) +{ + // add syst error to all sensors + AliInfoF("Adding sys.error %.4e %.4e to all sensors",sigy,sigz); + fAddError[0] = sigy; + fAddError[1] = sigz; + for (int isn=GetNSensors();isn--;) GetSensor(isn)->SetAddError(sigy,sigz); + // +} + +//____________________________________________ +void AliAlgDet::SetUseErrorParam(Int_t v) +{ + // set type of points error parameterization + AliFatal("UpdatePointByTrackInfo is not implemented for this detector"); + // +} + +//____________________________________________ +void AliAlgDet::UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const +{ + // update point using specific error parameterization + AliFatal("If needed, this method has to be implemented for specific detector"); +} + +//____________________________________________ +void AliAlgDet::SetObligatory(Int_t tp,Bool_t v) +{ + // mark detector presence obligatory in the track + fObligatory[tp] = v; + fAlgSteer->SetObligatoryDetector(GetDetID(),tp,v); +} + +//______________________________________________________ +void AliAlgDet::WritePedeInfo(FILE* parOut, const Option_t *opt) const +{ + // contribute to params and constraints template files for PEDE + fprintf(parOut,"\n!!\t\tDetector:\t%s\tNDOFs: %d\n",GetName(),GetNDOFs()); + // + // parameters + int nvol = GetNVolumes(); + for (int iv=0;ivGetParent()) vol->WritePedeInfo(parOut,opt); + } + // +} + +//______________________________________________________ +void AliAlgDet::WriteCalibrationResults() const +{ + // store calibration results + WriteAlignmentResults(); + // + // eventually we may write other calibrations +} + +//______________________________________________________ +void AliAlgDet::WriteAlignmentResults() const +{ + // store updated alignment + TClonesArray* arr = new TClonesArray("AliAlignObjParams",10); + // + int nvol = GetNVolumes(); + for (int iv=0;ivGetParent()) vol->CreateAlignmentObjects(arr); + } + // + AliCDBManager* man = AliCDBManager::Instance(); + AliCDBMetaData* md = new AliCDBMetaData(); + md->SetResponsible(fAlgSteer->GetOutCDBResponsible()); + md->SetComment(fAlgSteer->GetOutCDBResponsible()); + // + AliCDBId id(Form("%s/Align/Data",GetName()),fAlgSteer->GetOutCDBRunMin(),fAlgSteer->GetOutCDBRunMax()); + man->Put(arr,id,md); + // + delete arr; +} + +//______________________________________________________ +Bool_t AliAlgDet::OwnsDOFID(Int_t id) const +{ + // check if DOF ID belongs to this detector + for (int iv=GetNVolumes();iv--;) { + AliAlgVol* vol = GetVolume(iv); // check only top level volumes + if (!vol->GetParent() && vol->OwnsDOFID(id)) return kTRUE; + } + // calibration DOF? + if (id>=fFirstParGloID && idGetParent()) continue; // check only top level volumes + if ( (vol=vol->GetVolOfDOFID(id)) ) return vol; + } + return 0; +} + +//______________________________________________________ +void AliAlgDet::Terminate() +{ + // called at the end of processing + // if (IsDisabled()) return; + int nvol = GetNVolumes(); + fNProcPoints = 0; + AliAlgDOFStat* st = fAlgSteer->GetDOFStat(); + for (int iv=0;ivGetParent()) fNProcPoints += vol->FinalizeStat(st); + } + FillDOFStat(st); // fill stat for calib dofs +} + +//________________________________________ +void AliAlgDet::AddAutoConstraints() const +{ + // adds automatic constraints + int nvol = GetNVolumes(); + for (int iv=0;ivGetParent()) vol->AddAutoConstraints((TObjArray*)fAlgSteer->GetConstraints()); + } +} + +//________________________________________ +void AliAlgDet::FixNonSensors() +{ + // fix all non-sensor volumes + for (int i=GetNVolumes();i--;) { + AliAlgVol *vol = GetVolume(i); + if (vol->IsSensor()) continue; + vol->SetFreeDOFPattern(0); + vol->SetChildrenConstrainPattern(0); + } +} + +//________________________________________ +int AliAlgDet::SelectVolumes(TObjArray* arr, int lev, const char* match) +{ + // select volumes matching to pattern and/or hierarchy level + // + if (!arr) return 0; + int nadd = 0; + TString mts=match, syms; + for (int i=GetNVolumes();i--;) { + AliAlgVol *vol = GetVolume(i); + if (lev>=0 && vol->CountParents()!=lev) continue; // wrong level + if (!mts.IsNull() && !(syms=vol->GetSymName()).Contains(mts)) continue; //wrong name + arr->AddLast(vol); + nadd++; + } + // + return nadd; +} + +//________________________________________ +void AliAlgDet::SetFreeDOFPattern(UInt_t pat, int lev,const char* match) +{ + // set free DOFs to volumes matching either to hierarchy level or + // whose name contains match + // + TString mts=match, syms; + for (int i=GetNVolumes();i--;) { + AliAlgVol *vol = GetVolume(i); + if (lev>=0 && vol->CountParents()!=lev) continue; // wrong level + if (!mts.IsNull() && !(syms=vol->GetSymName()).Contains(mts)) continue; //wrong name + vol->SetFreeDOFPattern(pat); + } + // +} + +//________________________________________ +void AliAlgDet::SetDOFCondition(int dof, float condErr ,int lev,const char* match) +{ + // set condition for DOF of volumes matching either to hierarchy level or + // whose name contains match + // + TString mts=match, syms; + for (int i=GetNVolumes();i--;) { + AliAlgVol *vol = GetVolume(i); + if (lev>=0 && vol->CountParents()!=lev) continue; // wrong level + if (!mts.IsNull() && !(syms=vol->GetSymName()).Contains(mts)) continue; //wrong name + if (dof>=vol->GetNDOFs()) continue; + vol->SetParErr(dof, condErr); + if (condErr>=0 && !vol->IsFreeDOF(dof)) vol->SetFreeDOF(dof); + //if (condErr<0 && vol->IsFreeDOF(dof)) vol->FixDOF(dof); + } + // +} + +//________________________________________ +void AliAlgDet::ConstrainOrphans(const double* sigma, const char* match) +{ + // additional constraint on volumes w/o parents (optionally containing "match" in symname) + // sigma<0 : dof is not contrained + // sigma=0 : dof constrained exactly (Lagrange multiplier) + // sigma>0 : dof constrained by gaussian constraint + // + TString mts=match, syms; + AliAlgConstraint* constr = new AliAlgConstraint(); + for (int i=0;i=0) constr->ConstrainDOF(i); + else constr->UnConstrainDOF(i); + constr->SetSigma(i,sigma[i]); + } + for (int i=GetNVolumes();i--;) { + AliAlgVol *vol = GetVolume(i); + if (vol->GetParent()) continue; // wrong level + if (!mts.IsNull() && !(syms=vol->GetSymName()).Contains(mts)) continue; //wrong name + constr->AddChild(vol); + } + // + if (!constr->GetNChildren()) { + AliInfoF("No volume passed filter %s",match); + delete constr; + } + else ((TObjArray*)fAlgSteer->GetConstraints())->Add(constr); + // +} + +//________________________________________ +void AliAlgDet::SetFreeDOF(Int_t dof) +{ + // set detector free dof + if (dof>=kNMaxKalibDOF) {AliFatalF("Detector CalibDOFs limited to %d, requested %d",kNMaxKalibDOF,dof);} + fCalibDOF |= 0x1<=kNMaxKalibDOF) {AliFatalF("Detector CalibDOFs limited to %d, requested %d",kNMaxKalibDOF,dof);} + fCalibDOF &=~(0x1<AddStat(dof,stat); + } + // +} + +//______________________________________________________ +void AliAlgDet::WriteSensorPositions(const char* outFName) +{ + // create tree with sensors ideal, ref and reco positions + int ns = GetNSensors(); + double loc[3]={0}; + // ------- local container type for dumping sensor positions ------ + typedef struct { + int volID; // volume id + double pId[3]; // ideal + double pRf[3]; // reference + double pRc[3]; // reco-time + } snpos_t; + snpos_t spos; // + TFile* fl = TFile::Open(outFName,"recreate"); + TTree* tr = new TTree("snpos",Form("sensor poisitions for %s",GetName())); + tr->Branch("volID",&spos.volID,"volID/I"); + tr->Branch("pId",&spos.pId,"pId[3]/D"); + tr->Branch("pRf",&spos.pRf,"pRf[3]/D"); + tr->Branch("pRc",&spos.pRc,"pRc[3]/D"); + // + for (int isn=0;isnGetVolID(); + sens->GetMatrixL2GIdeal().LocalToMaster(loc,spos.pId); + sens->GetMatrixL2G().LocalToMaster(loc,spos.pRf); + sens->GetMatrixL2GReco().LocalToMaster(loc,spos.pRc); + tr->Fill(); + } + tr->Write(); + delete tr; + fl->Close(); + delete fl; +} diff --git a/Detectors/Align/AliAlgDet.h b/Detectors/Align/AliAlgDet.h new file mode 100644 index 0000000000000..097e2ca5d3c02 --- /dev/null +++ b/Detectors/Align/AliAlgDet.h @@ -0,0 +1,217 @@ +#ifndef ALIALGDET_H +#define ALIALGDET_H + +#include +#include +#include +#include "AliAlgAux.h" +#include "AliESDtrack.h" +class AliAlgTrack; +class AliAlgDOFStat; +class AliAlgPoint; +class AliAlgSens; +class AliAlgVol; +class AliAlgSteer; +class AliTrackPointArray; +class AliExternalTrackParam; +class TH1; + +/*-------------------------------------------------------- + Base class for detector: wrapper for set of volumes + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + +class AliAlgDet : public TNamed +{ + public: + enum {kInitGeomDone=BIT(14),kInitDOFsDone=BIT(15)}; + enum {kNMaxKalibDOF=64}; + // + AliAlgDet(); + AliAlgDet(const char* name, const char* title=""); + virtual ~AliAlgDet(); + Int_t GetDetID() const {return GetUniqueID();} + void SetDetID(UInt_t tp); + // + virtual void CacheReferenceOCDB(); + virtual void AcknowledgeNewRun(Int_t run); + virtual void UpdateL2GRecoMatrices(); + virtual void ApplyAlignmentFromMPSol(); + // + Int_t VolID2SID(Int_t vid) const; + Int_t SID2VolID(Int_t sid) const {return sid=fVolIDMin && vid<=fVolIDMax;} + void SetAddError(double y, double z); + const Double_t* GetAddError() const {return fAddError;} + // + Int_t GetNPoints() const {return fNPoints;} + // + void SetAlgSteer(AliAlgSteer* s) {fAlgSteer = s;} + AliAlgSens* GetSensor(Int_t id) const {return (AliAlgSens*)fSensors.UncheckedAt(id);} + AliAlgSens* GetSensorByVolId(Int_t vid) const {int sid=VolID2SID(vid); return sid<0 ? 0:GetSensor(sid);} + AliAlgSens* GetSensor(const char* symname) const {return (AliAlgSens*)fSensors.FindObject(symname);} + AliAlgVol* GetVolume(Int_t id) const {return (AliAlgVol*)fVolumes.UncheckedAt(id);} + AliAlgVol* GetVolume(const char* symname) const {return (AliAlgVol*)fVolumes.FindObject(symname);} + // + Bool_t OwnsDOFID(Int_t id) const; + AliAlgVol* GetVolOfDOFID(Int_t id) const; + // + Int_t GetDetLabel() const {return (GetDetID()+1)*1000000;} + void SetFreeDOF(Int_t dof); + void FixDOF(Int_t dof); + void SetFreeDOFPattern(ULong64_t pat) {fCalibDOF = pat; CalcFree();} + Bool_t IsFreeDOF(Int_t dof) const {return (fCalibDOF&(0x1<GetStatus()&fTrackFlagSel[trtype]) == fTrackFlagSel[trtype]; +} + +#endif diff --git a/Detectors/Align/AliAlgDetHMPID.cxx b/Detectors/Align/AliAlgDetHMPID.cxx new file mode 100644 index 0000000000000..b183110b29f72 --- /dev/null +++ b/Detectors/Align/AliAlgDetHMPID.cxx @@ -0,0 +1,70 @@ +/************************************************************************** + * 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. * + **************************************************************************/ + +#include "AliAlgDetHMPID.h" +#include "AliHMPIDParam.h" +#include "AliAlgVol.h" +#include "AliAlgSensHMPID.h" +#include "AliAlgSteer.h" +#include "AliGeomManager.h" +#include "AliESDtrack.h" +#include "AliLog.h" +#include + +ClassImp(AliAlgDetHMPID); + +//____________________________________________ +AliAlgDetHMPID::AliAlgDetHMPID(const char* title) +{ + // default c-tor + SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kHMPID),title); + SetDetID(AliAlgSteer::kHMPID); +} + +//____________________________________________ +AliAlgDetHMPID::~AliAlgDetHMPID() +{ + // d-tor +} + +//____________________________________________ +void AliAlgDetHMPID::DefineVolumes() +{ + // define HMPID volumes + // + int labDet = GetDetLabel(); + AliGeomManager::ELayerID idHMPID = AliGeomManager::kHMPID; + for(Int_t iCh=AliHMPIDParam::kMinCh;iCh<=AliHMPIDParam::kMaxCh;iCh++) { + const char *symname = Form("/HMPID/Chamber%i",iCh); + if (!gGeoManager->GetAlignableEntry(symname)) { + AliErrorF("Did not find alignable %s",symname); + continue; + } + UShort_t vid = AliGeomManager::LayerToVolUID(idHMPID,iCh); + int iid = labDet + (1+iCh)*10000; + AliAlgSensHMPID* sens = new AliAlgSensHMPID(symname,vid,iid); + AddVolume(sens); + }//iCh loop + // +} + +//____________________________________________ +Bool_t AliAlgDetHMPID::AcceptTrack(const AliESDtrack* trc, Int_t trtype) const +{ + // test if detector had seed this track + if (!CheckFlags(trc,trtype)) return kFALSE; + if (trc->GetNcls(1) +#include + +using namespace TMath; +using namespace AliAlgAux; + +ClassImp(AliAlgDetITS); + +const Char_t* AliAlgDetITS::fgkHitsSel[AliAlgDetITS::kNSPDSelTypes] = + {"SPDNoSel","SPDBoth","SPDAny","SPD0","SPD1"}; + + +//____________________________________________ +AliAlgDetITS::AliAlgDetITS(const char* title) +{ + // default c-tor + SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kITS),title); + SetDetID(AliAlgSteer::kITS); + SetUseErrorParam(); + SetITSSelPatternColl(); + SetITSSelPatternCosm(); +} + +//____________________________________________ +AliAlgDetITS::~AliAlgDetITS() +{ + // d-tor +} + +//____________________________________________ +void AliAlgDetITS::DefineVolumes() +{ + // define ITS volumes + // + const int kNSPDSect = 10; + AliAlgVol *volITS=0,*hstave=0,*ladd=0; + AliAlgSensITS *sens=0; + // + int labDet = GetDetLabel(); + AddVolume( volITS = new AliAlgVol("ITS",labDet) ); + // + // SPD + AliAlgVol *sect[kNSPDSect] = {0}; + for (int isc=0;iscSetParent(volITS); + } + for (int ilr=0;ilr<=1;ilr++) { // SPD layers + // + int cntVolID=0,staveCnt=0; + int nst = AliITSgeomTGeo::GetNLadders(ilr+1)/kNSPDSect; // 2 or 4 staves per sector + for (int isc=0;iscSetParent(sect[isc]); + hstave->SetInternalID(iid); + for (int isn=0;isn<2;isn++) { // "ladder" (sensor) + int iids = iid + (1+isn); + AddVolume( sens = + new AliAlgSensITS(Form("ITS/SPD%d/Sector%d/Stave%d/HalfStave%d/Ladder%d", + ilr,isc,ist,ihst,isn+ihst*2), + AliGeomManager::LayerToVolUID(ilr+1,cntVolID++), iids) ); + sens->SetParent(hstave); + } + } + } // staves of SPDi + } // sectors + } // SPD layers + // + // SDD + for (int ilr=2;ilr<=3;ilr++) { // layer + int cntVolID=0, staveCnt=0; + for (int ist=0;istSetParent(volITS); + for (int isn=0;isnSetParent(ladd); + } + } // ladder + } // layer + // + // SSD + for (int ilr=4;ilr<=5;ilr++) { // layer + int cntVolID=0,staveCnt=0; + for (int ist=0;istSetParent(volITS); + for (int isn=0;isnSetParent(ladd); + } + } // ladder + } // layer + // + // +} + +//____________________________________________ +void AliAlgDetITS::Print(const Option_t *opt) const +{ + AliAlgDet::Print(opt); + printf("Sel.pattern Collisions: %7s | Cosmic: %7s\n", + GetITSPattName(fITSPatt[kColl]),GetITSPattName(fITSPatt[kCosm])); +} + +//____________________________________________ +Bool_t AliAlgDetITS::AcceptTrack(const AliESDtrack* trc,Int_t trtype) const +{ + // test if detector had seed this track + if (!CheckFlags(trc,trtype)) return kFALSE; + if (trc->GetNcls(0)GetVolID(); + int lrs = AliGeomManager::VolUIDToLayer(vid); + if ( (lrs-AliGeomManager::kSPD1) == ilr) sens->SetAddError(sigY,sigZ); + } +} + +//____________________________________________ +void AliAlgDetITS::SetSkipLr(int ilr) +{ + // exclude sensor of the layer from alignment + for (int isn=GetNSensors();isn--;) { + AliAlgSensITS* sens = (AliAlgSensITS*)GetSensor(isn); + int vid = sens->GetVolID(); + int lrs = AliGeomManager::VolUIDToLayer(vid); + if ( (lrs-AliGeomManager::kSPD1) == ilr) sens->SetSkip(); + } +} + +//_________________________________________________ +void AliAlgDetITS::SetUseErrorParam(Int_t v) +{ + // set type of points error parameterization + fUseErrorParam = v; +} + +//_________________________________________________ +Bool_t AliAlgDetITS::CheckHitPattern(const AliESDtrack* trc, Int_t sel) +{ + // check if track hit pattern is ok + switch (sel) { + case kSPDBoth: + if (!trc->HasPointOnITSLayer(0) || !trc->HasPointOnITSLayer(1)) return kFALSE; + break; + case kSPDAny: + if (!trc->HasPointOnITSLayer(0) && !trc->HasPointOnITSLayer(1)) return kFALSE; + break; + case kSPD0: + if (!trc->HasPointOnITSLayer(0)) return kFALSE; + break; + case kSPD1: + if (!trc->HasPointOnITSLayer(1)) return kFALSE; + break; + default: break; + } + return kTRUE; +} + +//_________________________________________________ +void AliAlgDetITS::UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const +{ + // update point using specific error parameterization + // the track must be in the detector tracking frame + const AliAlgSens* sens = pnt->GetSensor(); + int vid = sens->GetVolID(); + int lr = AliGeomManager::VolUIDToLayer(vid)-1; + double angPol = ATan(t->GetTgl()); + double angAz = ASin(t->GetSnp()); + double errY,errZ; + GetErrorParamAngle(lr,angPol,angAz,errY,errZ); + const double *sysE = sens->GetAddError(); // additional syst error + // + pnt->SetYZErrTracking(errY*errY+sysE[0]*sysE[0],0,errZ*errZ+sysE[1]*sysE[1]); + pnt->Init(); + // +} +//-------------------------------------------------------------------------- +void AliAlgDetITS::GetErrorParamAngle(int layer, double anglePol, double angleAzi, double &erry, double &errz) const +{ + // Modified version of AliITSClusterParam::GetErrorParamAngle + // Calculate cluster position error (parametrization extracted from rp-hit + // residuals, as a function of angle between track and det module plane. + // Origin: M.Lunardon, S.Moretto) + // + const int kNcfSPDResX = 21; + const float kCfSPDResX[kNcfSPDResX] = {+1.1201e+01,+2.0903e+00,-2.2909e-01,-2.6413e-01,+4.2135e-01,-3.7190e-01, + +4.2339e-01,+1.8679e-01,-5.1249e-01,+1.8421e-01,+4.8849e-02,-4.3127e-01, + -1.1148e-01,+3.1984e-03,-2.5743e-01,-6.6408e-02,+3.0756e-01,+2.6809e-01, + -5.0339e-03,-1.4964e-01,-1.1001e-01}; + const float kSPDazMax=56.000000; + // + /* + const int kNcfSPDMeanX = 16; + const float kCfSPDMeanX[kNcfSPDMeanX] = {-1.2532e+00,-3.8185e-01,-8.9039e-01,+2.6648e+00,+7.0361e-01,+1.2298e+00, + +3.2871e-01,+7.8487e-02,-1.6792e-01,-1.3966e-01,-3.1670e-01,-2.1795e-01, + -1.9451e-01,-4.9347e-02,-1.9186e-01,-1.9195e-01}; + */ + // + const int kNcfSPDResZ = 5; + const float kCfSPDResZ[kNcfSPDResZ] = {+9.2384e+01,+3.4352e-01,-2.7317e+01,-1.4642e-01,+2.0868e+00}; + const float kSPDpolMin=34.358002, kSPDpolMax=145.000000; + // + const Double_t kMaxSigmaSDDx=100.; + const Double_t kMaxSigmaSDDz=400.; + const Double_t kMaxSigmaSSDx=100.; + const Double_t kMaxSigmaSSDz=1000.; + // + const Double_t kParamSDDx[2]={30.93,0.059}; + const Double_t kParamSDDz[2]={33.09,0.011}; + const Double_t kParamSSDx[2]={18.64,-0.0046}; + const Double_t kParamSSDz[2]={784.4,-0.828}; + Double_t sigmax=1000.0,sigmaz=1000.0; + //Double_t biasx = 0.0; + + angleAzi = Abs(angleAzi); + anglePol = Abs(anglePol); + // + if(angleAzi>0.5*Pi()) angleAzi = Pi()-angleAzi; + if(anglePol>0.5*Pi()) anglePol = Pi()-anglePol; + Double_t angleAziDeg = angleAzi*RadToDeg(); + Double_t anglePolDeg = anglePol*RadToDeg(); + // + if(layer==0 || layer==1) { // SPD + // + float phiInt = angleAziDeg/kSPDazMax; // mapped to -1:1 + if (phiInt>1) phiInt = 1; else if (phiInt<-1) phiInt = -1; + float phiAbsInt = (TMath::Abs(angleAziDeg+angleAziDeg) - kSPDazMax)/kSPDazMax; // mapped to -1:1 + if (phiAbsInt>1) phiAbsInt = 1; else if (phiAbsInt<-1) phiAbsInt = -1; + anglePolDeg += 90; // the parameterization was provided in polar angle (90 deg - normal to sensor) + float polInt = (anglePolDeg+anglePolDeg - (kSPDpolMax+kSPDpolMin))/(kSPDpolMax-kSPDpolMin); // mapped to -1:1 + if (polInt>1) polInt = 1; else if (polInt<-1) polInt = -1; + // + sigmax = AliCheb3DCalc::ChebEval1D(phiAbsInt, kCfSPDResX , kNcfSPDResX); + //biasx = AliCheb3DCalc::ChebEval1D(phiInt , kCfSPDMeanX, kNcfSPDMeanX); + sigmaz = AliCheb3DCalc::ChebEval1D(polInt , kCfSPDResZ , kNcfSPDResZ); + // + // for the moment for the SPD only, need to decide where to put it + //biasx *= 1e-4; + + } else if(layer==2 || layer==3) { // SDD + + sigmax = angleAziDeg*kParamSDDx[1]+kParamSDDx[0]; + sigmaz = kParamSDDz[0]+kParamSDDz[1]*anglePolDeg; + if(sigmax > kMaxSigmaSDDx) sigmax = kMaxSigmaSDDx; + if(sigmaz > kMaxSigmaSDDz) sigmax = kMaxSigmaSDDz; + + } else if(layer==4 || layer==5) { // SSD + + sigmax = angleAziDeg*kParamSSDx[1]+kParamSSDx[0]; + sigmaz = kParamSSDz[0]+kParamSSDz[1]*anglePolDeg; + if(sigmax > kMaxSigmaSSDx) sigmax = kMaxSigmaSSDx; + if(sigmaz > kMaxSigmaSSDz) sigmax = kMaxSigmaSSDz; + } + // convert from micron to cm + erry = 1.e-4*sigmax; + errz = 1.e-4*sigmaz; +} diff --git a/Detectors/Align/AliAlgDetITS.h b/Detectors/Align/AliAlgDetITS.h new file mode 100644 index 0000000000000..c450644fc4704 --- /dev/null +++ b/Detectors/Align/AliAlgDetITS.h @@ -0,0 +1,62 @@ +#ifndef ALIALGDETITS_H +#define ALIALGDETITS_H + +#include "AliAlgDet.h" +#include "AliAlgAux.h" + +/*-------------------------------------------------------- + ITS detector wrapper + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + + +class AliAlgDetITS : public AliAlgDet +{ + public: + // + enum ITSSel_t {kSPDNoSel,kSPDBoth,kSPDAny,kSPD0,kSPD1,kNSPDSelTypes}; + // + AliAlgDetITS(const char* title=""); + virtual ~AliAlgDetITS(); + // + virtual void DefineVolumes(); + // + Bool_t AcceptTrack(const AliESDtrack* trc,Int_t trtype) const; + + void SetAddErrorLr(int ilr, double sigY, double sigZ); + void SetSkipLr(int ilr); + // + virtual void UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const; + virtual void SetUseErrorParam(Int_t v=1); + void SetITSSelPattern(Int_t trtype, ITSSel_t sel) {fITSPatt[trtype]=sel;} + void SetITSSelPatternColl(ITSSel_t sel=kSPDAny) {SetITSSelPattern(AliAlgAux::kColl,sel);} + void SetITSSelPatternCosm(ITSSel_t sel=kSPDNoSel) {SetITSSelPattern(AliAlgAux::kCosm,sel);} + + Int_t GetITSSelPattern(int tp) const {return fITSPatt[tp];} + Int_t GetITSSelPatternColl() const {return fITSPatt[AliAlgAux::kColl];} + Int_t GetITSSelPatternCosm() const {return fITSPatt[AliAlgAux::kCosm];} + // + virtual void Print(const Option_t *opt="") const; + // + static Bool_t CheckHitPattern(const AliESDtrack* trc, Int_t sel); + static const char* GetITSPattName(Int_t sel) {return sel + +ClassImp(AliAlgDetTOF); + +//____________________________________________ +AliAlgDetTOF::AliAlgDetTOF(const char* title) +{ + // default c-tor + SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kTOF),title); + SetDetID(AliAlgSteer::kTOF); +} + +//____________________________________________ +AliAlgDetTOF::~AliAlgDetTOF() +{ + // d-tor +} + +//____________________________________________ +void AliAlgDetTOF::DefineVolumes() +{ + // define TOF volumes + // + const int kNSect = 18, kNStrips = AliTOFGeometry::NStripA()+2*AliTOFGeometry::NStripB()+2*AliTOFGeometry::NStripC(); + int labDet = GetDetLabel(); + AliAlgSensTOF *strip=0; + // + // AddVolume( volTOF = new AliAlgVol("TOF") ); // no main volume, why? + AliAlgVol *sect[kNSect] = {0}; + // + for (int isc=0;iscGetAlignableEntry(symname)) continue; + AddVolume( strip=new AliAlgSensTOF(symname,vid,iid,isc) ); + strip->SetParent(sect[isc]); + } // strip + } // layer + // +} + +//____________________________________________ +Bool_t AliAlgDetTOF::AcceptTrack(const AliESDtrack* trc,Int_t trtype) const +{ + // test if detector had seed this track + return CheckFlags(trc,trtype); +} diff --git a/Detectors/Align/AliAlgDetTOF.h b/Detectors/Align/AliAlgDetTOF.h new file mode 100644 index 0000000000000..72d96db3539a7 --- /dev/null +++ b/Detectors/Align/AliAlgDetTOF.h @@ -0,0 +1,33 @@ +#ifndef ALIALGDETTOF_H +#define ALIALGDETTOF_H + +#include "AliAlgDet.h" + +/*-------------------------------------------------------- + Wrapper for TOF detector + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + +class AliAlgDetTOF : public AliAlgDet +{ + public: + AliAlgDetTOF(const char* title=""); + virtual ~AliAlgDetTOF(); + // + virtual void DefineVolumes(); + // + Bool_t AcceptTrack(const AliESDtrack* trc,Int_t trtype) const; + // + protected: + // + // -------- dummies -------- + AliAlgDetTOF(const AliAlgDetTOF&); + AliAlgDetTOF& operator=(const AliAlgDetTOF&); + // + protected: + + ClassDef(AliAlgDetTOF,1); +}; + +#endif diff --git a/Detectors/Align/AliAlgDetTPC.cxx b/Detectors/Align/AliAlgDetTPC.cxx new file mode 100644 index 0000000000000..c090d12b22f2f --- /dev/null +++ b/Detectors/Align/AliAlgDetTPC.cxx @@ -0,0 +1,83 @@ +/************************************************************************** + * 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. * + **************************************************************************/ + +#include "AliAlgDetTPC.h" +#include "AliAlgVol.h" +#include "AliAlgSensTPC.h" +#include "AliAlgSteer.h" +#include "AliGeomManager.h" +#include "AliESDtrack.h" +#include "AliLog.h" +#include + +ClassImp(AliAlgDetTPC); + +//____________________________________________ +AliAlgDetTPC::AliAlgDetTPC(const char* title) +{ + // default c-tor + SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kTPC),title); + SetDetID(AliAlgSteer::kTPC); +} + +//____________________________________________ +AliAlgDetTPC::~AliAlgDetTPC() +{ + // d-tor +} + +//____________________________________________ +void AliAlgDetTPC::DefineVolumes() +{ + // define TPC volumes + // + const int kNSect = 18, kAC=2, kIOROC=2; + const char* kSide[kAC] = {"A","C"}; + const char* kROC[kIOROC] = {"Inner","Outer"}; + // AliAlgSensTPC *chamb=0; + // + int labDet = GetDetLabel(); + AliAlgVol* volTPC = new AliAlgVol("ALIC_1/TPC_M_1",labDet); + AddVolume( volTPC ); + // + + for (int roc=0;rocGetAlignableEntry(symname)) { + AliErrorF("Did not find alignable %s",symname); + continue; + } + Int_t iid = side*kNSect+isc; + UShort_t vid = AliGeomManager::LayerToVolUID(AliGeomManager::kTPC1+roc,iid); + iid = labDet + (1+side)*10000 + (1+isc)*100+(1+roc); + AliAlgSensTPC* sens = new AliAlgSensTPC(symname,vid,iid,isc); + sens->SetParent(volTPC); + AddVolume(sens); + } // sector ID + } // A/C + } // inner/outer + // +} + +//____________________________________________ +Bool_t AliAlgDetTPC::AcceptTrack(const AliESDtrack* trc, Int_t trtype) const +{ + // test if detector had seed this track + if (!CheckFlags(trc,trtype)) return kFALSE; + if (trc->GetNcls(1) +#include + +using namespace TMath; + +ClassImp(AliAlgDetTRD); + +const char* AliAlgDetTRD::fgkCalibDOFName[AliAlgDetTRD::kNCalibParams]={"DZdTglNRC","DVDriftT"}; + +//____________________________________________ +AliAlgDetTRD::AliAlgDetTRD(const char* title) + : AliAlgDet() + ,fNonRCCorrDzDtgl(0) + ,fCorrDVT(0) +{ + // default c-tor + SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kTRD),title); + SetDetID(AliAlgSteer::kTRD); + fExtraErrRC[0] = fExtraErrRC[1] = 0; + // + // ad hoc correction + SetNonRCCorrDzDtgl(); + SetExtraErrRC(); + fNCalibDOF = kNCalibParams; +} + + +//____________________________________________ +AliAlgDetTRD::~AliAlgDetTRD() +{ + // d-tor +} + +//____________________________________________ +void AliAlgDetTRD::DefineVolumes() +{ + // define TRD volumes + // + const int kNSect = 18, kNStacks = 5, kNLayers = 6; + AliAlgSensTRD *chamb=0; + // + int labDet = GetDetLabel(); + // AddVolume( volTRD = new AliAlgVol("TRD") ); // no main volume, why? + AliAlgVol *sect[kNSect] = {0}; + // + for (int ilr=0;ilrGetAlignableEntry(symname)) continue; + UShort_t vid = AliGeomManager::LayerToVolUID(AliGeomManager::kTRD1+ilr,ich); + AddVolume( chamb = new AliAlgSensTRD(symname,vid,iid/*lid*/,isector) ); + iid = labDet + (1+isector)*100; + if (!sect[isector]) sect[isector] = new AliAlgVol(Form("TRD/sm%02d",isector),iid); + chamb->SetParent(sect[isector]); + } // chamber + } // layer + // + for (int isc=0;iscGetTRDntracklets() +#include + + +using namespace TMath; +using namespace AliAlgAux; + +//_________________________________________________________ +AliAlgMPRecord::AliAlgMPRecord() + :fTrackID(0) + ,fTimeStamp(0) + ,fNResid(0) + ,fNVarLoc(0) + ,fNVarGlo(0) + ,fNDLocTot(0) + ,fNDGloTot(0) + ,fNMeas(0) + ,fChi2Ini(0) + ,fQ2Pt(0) + ,fTgl(0) + ,fNDLoc(0) + ,fNDGlo(0) + ,fVolID(0) + ,fResid(0) + ,fResErr(0) + ,fIDLoc(0) + ,fIDGlo(0) + ,fDLoc(0) + ,fDGlo(0) + // + ,fNResidBook(0) + ,fNDLocTotBook(0) + ,fNDGloTotBook(0) +{ + // def c-tor + +} + +//_________________________________________________________ +AliAlgMPRecord::~AliAlgMPRecord() +{ + // d-tor + delete[] fNDLoc; + delete[] fNDGlo; + delete[] fVolID; + delete[] fResid; + delete[] fResErr; + delete[] fIDLoc; + delete[] fIDGlo; + delete[] fDLoc; + delete[] fDGlo; +} + +//_________________________________________________________ +void AliAlgMPRecord::DummyRecord(Float_t res, Float_t err, Float_t dGlo, Int_t labGlo) +{ + // create dummy residuals record + if (!fNDGlo) Resize(1,1,1); + fChi2Ini = 0; + fNMeas = 1; + fNResid = 1; + fNVarLoc = 0; + fNVarGlo = 1; + fIDGlo[0] = labGlo; + fDGlo[0] = dGlo; + fNDGlo[0] = 1; + fVolID[0] = -1; + fResid[0] = res; + fResErr[0] = err; + // + fIDLoc[0] = 0; + fNDLoc[0] = 0; + fDLoc[0] = 0; + fNDGloTot = 1; + fNDLocTot = 0; + // +} + +//_________________________________________________________ +Bool_t AliAlgMPRecord::FillTrack(const AliAlgTrack* trc, const Int_t *id2Lab) +{ + // fill track info, optionally substitutind glopar par ID by label + // + if (!trc->GetDerivDone()) { + AliError("Track derivatives are not yet evaluated"); + return kFALSE; + } + fNVarLoc = trc->GetNLocPar(); // number of local degrees of freedom in the track + fNResid = 0; + fNDLocTot = 0; + fNDGloTot = 0; + fChi2Ini = trc->GetChi2Ini(); + fQ2Pt = trc->GetSigned1Pt(); + fTgl = trc->GetTgl(); + fNMeas = 0; + SetCosmic(trc->IsCosmic()); + // 1) check sizes for buffers, expand if needed + int np = trc->GetNPoints(); + int nres = 0; + int nlocd = 0; + int nglod = 0; + for (int ip=np;ip--;) { + AliAlgPoint* pnt = trc->GetPoint(ip); + int ngl = pnt->GetNGloDOFs(); // number of DOF's this point depends on + if (pnt->ContainsMeasurement()) { + nres += 2; // every point has 2 residuals + nlocd += fNVarLoc+fNVarLoc; // each residual has max fNVarLoc local derivatives + nglod += ngl + ngl; // number of global derivatives + fNMeas++; + } + if (pnt->ContainsMaterial()) { + int nmatpar = pnt->GetNMatPar(); + nres += nmatpar; // each point with materials has nmatpar fake residuals + nlocd += nmatpar; // and nmatpar non-0 local derivatives (orthogonal) + } + } + // + Resize(nres,nlocd,nglod); + int nParETP = trc->GetNLocExtPar(); // numnber of local parameters for reference track param + // + const int* gloParID = trc->GetGloParID(); // IDs of global DOFs this track depends on + for (int ip=0;ipGetPoint(ip); + if (pnt->ContainsMeasurement()) { + int gloOffs = pnt->GetDGloOffs(); // 1st entry of global derivatives for this point + int nDGlo = pnt->GetNGloDOFs(); // number of global derivatives (number of DOFs it depends on) + if (!pnt->IsStatOK()) pnt->IncrementStat(); + // + for (int idim=0;idim<2;idim++) { // 2 dimensional orthogonal measurement + fNDGlo[fNResid] = 0; + fVolID[fNResid] = pnt->GetSensor()->GetVolID()+1; + // + // measured residual/error + fResid[ fNResid] = trc->GetResidual(idim,ip); + fResErr[fNResid] = Sqrt(pnt->GetErrDiag(idim)); + // + // derivatives over local params + const double* deriv = trc->GetDResDLoc(idim,ip); // array of Dresidual/Dparams_loc + int nnon0 = 0; + for (int j=0;jGetMinLocVarID(); // point may depend on material variables starting from this one + int lp1 = pnt->GetMaxLocVarID(); // and up to this one (exclusive) + for (int j=lp0;jGetDResDGlo(idim, gloOffs); + const int* gloIDP = gloParID + gloOffs; + for (int j=0;jContainsMaterial()) { // material point can add 4 or 5 otrhogonal pseudo-measurements + int nmatpar = pnt->GetNMatPar(); // residuals (correction expectation value) + // const float* expMatCorr = pnt->GetMatCorrExp(); // expected corrections (diagonalized) + const float* expMatCov = pnt->GetMatCorrCov(); // their diagonalized error matrix + int offs = pnt->GetMaxLocVarID() - nmatpar; // start of material variables + // here all derivatives are 1 = dx/dx + for (int j=0;jfNResidBook) { + delete[] fNDLoc; + delete[] fNDGlo; + delete[] fVolID; + delete[] fResid; + delete[] fResErr; + fNDLoc = new Short_t[nresid]; + fNDGlo = new Int_t[nresid]; + fVolID = new Int_t[nresid]; + fResid = new Float_t[nresid]; + fResErr = new Float_t[nresid]; + fNResidBook = nresid; + memset(fNDLoc,0,nresid*sizeof(Short_t)); + memset(fNDGlo,0,nresid*sizeof(Int_t)); + memset(fVolID,0,nresid*sizeof(Int_t)); + memset(fResid,0,nresid*sizeof(Float_t)); + memset(fResErr,0,nresid*sizeof(Float_t)); + } + if (nloc>fNDLocTotBook) { + delete[] fIDLoc; + delete[] fDLoc; + fIDLoc = new Short_t[nloc]; + fDLoc = new Float_t[nloc]; + fNDLocTotBook = nloc; + memset(fIDLoc,0,nloc*sizeof(Short_t)); + memset(fDLoc,0,nloc*sizeof(Float_t)); + } + if (nglo>fNDGloTotBook) { + delete[] fIDGlo; + delete[] fDGlo; + fIDGlo = new Int_t[nglo]; + fDGlo = new Float_t[nglo]; + fNDGloTotBook = nglo; + memset(fIDGlo,0,nglo*sizeof(Int_t)); + memset(fDGlo,0,nglo*sizeof(Float_t)); + } + // +} + +//____________________________________________ +void AliAlgMPRecord::Clear(const Option_t *) +{ + // reset record + TObject::Clear(); + ResetBit(0xffffffff); + fNResid = 0; + fNVarLoc = 0; + fNVarGlo = 0; + fNDLocTot = 0; + fNDGloTot = 0; +} + +//____________________________________________ +void AliAlgMPRecord::Print(const Option_t *) const +{ + // print info + // + printf("Track %d Event TimeStamp:%d Run:%d\n", + fTrackID,fTimeStamp,GetRun()); + printf("Nmeas:%3d Q/pt:%+.2e Tgl:%+.2e Chi2Ini:%.1f\n",fNMeas,fQ2Pt,fTgl,fChi2Ini); + printf("NRes: %3d NLoc: %3d NGlo:%3d | Stored: Loc:%3d Glo:%5d\n", + fNResid,fNVarLoc,fNVarGlo,fNDLocTot,fNDGloTot); + // + int curLoc=0,curGlo=0; + const int kNColLoc=5; + for (int ir=0;irfIDGlo[jd]%100) {printf("\n");/* eolOK = kTRUE;*/} + printf("[%5d] %+.2e ",fIDGlo[jd],fDGlo[jd]); + // if (((id+1)%kNColGlo)==0) + // else eolOK = kFALSE; + prvID=fIDGlo[jd]%100; + } + // if (!eolOK) printf("\n"); + printf("\n"); + curGlo += ndglo; + // + } +} diff --git a/Detectors/Align/AliAlgMPRecord.h b/Detectors/Align/AliAlgMPRecord.h new file mode 100644 index 0000000000000..86bbef79db88b --- /dev/null +++ b/Detectors/Align/AliAlgMPRecord.h @@ -0,0 +1,102 @@ +#ifndef ALIALGMPRECORD_H +#define ALIALGMPRECORD_H + +#include +class AliAlgTrack; + +/*-------------------------------------------------------- + Millepede record in root format (can be converted to proper + pede binary format. + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + + +class AliAlgMPRecord : public TObject +{ + public: + enum {kCosmicBit=BIT(14)}; + // + AliAlgMPRecord(); + virtual ~AliAlgMPRecord(); + // + Int_t GetRun() const {return GetUniqueID();} + void SetRun(Int_t r) {SetUniqueID(r);} + UInt_t GetTimeStamp() const {return fTimeStamp;} + void SetTimeStamp(UInt_t t) {fTimeStamp = t;} + UInt_t GetTrackID() const {return fTrackID;} + void SetTrackID(UInt_t t) {fTrackID = t;} + Bool_t IsCosmic() const {return TestBit(kCosmicBit);} + void SetCosmic(Bool_t v=kTRUE) {SetBit(kCosmicBit,v);} + // + Int_t GetNVarGlo() const {return fNVarGlo;} + void SetNVarGlo(int n) {fNVarGlo = n;} + // + Int_t GetNResid() const {return fNResid;} + Int_t GetNVarLoc() const {return fNVarLoc;} + // + Int_t GetNDLoc(int id) const {return fNDLoc[id];} + Int_t GetNDGlo(int id) const {return fNDGlo[id];} + Int_t GetVolID(int id) const {return fVolID ? fVolID[id]-1:-1;} + Float_t GetResid(int id) const {return fResid[id];} + Float_t GetResErr(int id) const {return fResErr[id];} + // + Float_t GetChi2Ini() const {return fChi2Ini;} + Float_t GetQ2Pt() const {return fQ2Pt;} + Float_t GetTgl() const {return fTgl;} + Int_t GetNDLocTot() const {return fNDLocTot;} + Int_t GetNDGloTot() const {return fNDGloTot;} + const Float_t* GetArrGlo() const {return fDGlo;} + const Float_t* GetArrLoc() const {return fDLoc;} + const Short_t* GetArrLabLoc() const {return fIDLoc;} + const Int_t* GetArrLabGlo() const {return fIDGlo;} + // + Bool_t FillTrack(const AliAlgTrack* trc, const Int_t *id2Lab=0); + void DummyRecord(Float_t res, Float_t err, Float_t dGlo, Int_t labGlo); + // + void Resize(Int_t nresid, Int_t nloc, Int_t nglo); + // + virtual void Clear(const Option_t *opt=""); + virtual void Print(const Option_t *opt="") const; + // + protected: + // + // ------- dummies -------- + AliAlgMPRecord(const AliAlgMPRecord&); + AliAlgMPRecord& operator=(const AliAlgMPRecord&); + // + protected: + // + UInt_t fTrackID; // track in the event + UInt_t fTimeStamp; // event time stamp + Int_t fNResid; // number of residuals for the track (=2 npoints) + Int_t fNVarLoc; // number of local variables for the track + Int_t fNVarGlo; // number of global variables defined + Int_t fNDLocTot; // total number of non-zero local derivatives + Int_t fNDGloTot; // total number of non-zero global derivatives + Int_t fNMeas; // number of measured points + Float_t fChi2Ini; // chi2 of initial kalman fit + Float_t fQ2Pt; // q/pt at ref point + Float_t fTgl; // dip angle at ref point + // + Short_t* fNDLoc; //[fNResid] number of non-0 local derivatives per residual + Int_t* fNDGlo; //[fNResid] number of non-0 global derivatives per residual + Int_t* fVolID; //[fNResid] volume id + 1 (0 - not a volume) + Float_t* fResid; //[fNResid] residuals + Float_t* fResErr; //[fNResid] error associated to residual + // + Short_t* fIDLoc; //[fNDLocTot] ID of local variables for non-0 local derivatives + Int_t* fIDGlo; //[fNDGloTot] ID of global variables for non-0 global derivatives + Float_t* fDLoc; //[fNDLocTot] non-0 local derivatives + Float_t* fDGlo; //[fNDGloTot] non-0 global derivatives + // + // aux info + Int_t fNResidBook; //! number of slots booked for residuals + Int_t fNDLocTotBook; //! number of slots booked for local derivatives + Int_t fNDGloTotBook; //! number of slots booked for global derivatives + // + ClassDef(AliAlgMPRecord,4); +}; + + +#endif diff --git a/Detectors/Align/AliAlgPoint.cxx b/Detectors/Align/AliAlgPoint.cxx new file mode 100644 index 0000000000000..c469c209146a5 --- /dev/null +++ b/Detectors/Align/AliAlgPoint.cxx @@ -0,0 +1,373 @@ +/************************************************************************** + * 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. * + **************************************************************************/ + +#include +#include +#include +#include "AliAlgPoint.h" +#include "AliAlgAux.h" +#include "AliExternalTrackParam.h" + +using namespace AliAlgAux; +using namespace TMath; + +//_____________________________________ +AliAlgPoint::AliAlgPoint() + :fMinLocVarID(0) + ,fMaxLocVarID(0) + ,fDetID(-1) + ,fSID(-1) + ,fAlphaSens(0) + ,fXSens(0) + ,fCosDiagErr(0) + ,fSinDiagErr(0) + ,fX2X0(0) + ,fXTimesRho(0) + ,fNGloDOFs(0) + ,fDGloOffs(0) + ,fSensor(0) +{ + // def c-tor + for (int i=3;i--;) { + fXYZTracking[i] = 0; + fErrYZTracking[i] = 0; + } + memset(fMatCorrExp,0,5*sizeof(float)); + memset(fMatCorrCov,0,5*sizeof(float)); + memset(fMatDiag,0,5*5*sizeof(float)); + // + memset(fTrParamWSA,0,5*sizeof(double)); + memset(fTrParamWSB,0,5*sizeof(double)); + // +} + +//_____________________________________ +void AliAlgPoint::Init() +{ + // compute aux info + const double kCorrToler = 1e-6; + const double kDiagToler = 1e-14; + // + // compute parameters of tranformation to diagonal error matrix + if (!IsZeroPos(fErrYZTracking[0]+fErrYZTracking[2])) { + // + // is there a correlation? + if (SmallerAbs(fErrYZTracking[1]*fErrYZTracking[1]/(fErrYZTracking[0]*fErrYZTracking[2]),kCorrToler)) { + fCosDiagErr = 1.; + fSinDiagErr = 0.; + fErrDiag[0] = fErrYZTracking[0]; + fErrDiag[1] = fErrYZTracking[2]; + } + else { + double dfd = 0.5*(fErrYZTracking[2] - fErrYZTracking[0]); + double phi = 0; + // special treatment if errors are equal + if (Abs(dfd)0 ? (Pi()*0.25) : (Pi()*0.75); + else phi = 0.5*ATan2(fErrYZTracking[1],dfd); + // + fCosDiagErr = Cos(phi); + fSinDiagErr = Sin(phi); + // + // double det = dfd*dfd + fErrYZTracking[1]*fErrYZTracking[1]; + // det = det>0 ? Sqrt(det) : 0; + // double smd = 0.5*(fErrYZTracking[0] + fErrYZTracking[2]); + // fErrDiag[0] = smd + det; + // fErrDiag[1] = smd - det; + double xterm = 2*fCosDiagErr*fSinDiagErr*fErrYZTracking[1]; + double cc = fCosDiagErr*fCosDiagErr; + double ss = fSinDiagErr*fSinDiagErr; + fErrDiag[0] = fErrYZTracking[0]*cc + fErrYZTracking[2]*ss - xterm; + fErrDiag[1] = fErrYZTracking[0]*ss + fErrYZTracking[2]*cc + xterm; + } + } + // +} + +//_____________________________________ +void AliAlgPoint::UpdatePointByTrackInfo(const AliExternalTrackParam* t) +{ + // recalculate point errors using info about the track in the sensor tracking frame + fSensor->UpdatePointByTrackInfo(this, t); +} + +//_____________________________________ +void AliAlgPoint::Print(Option_t* opt) const +{ + // print + TString opts = opt; + opts.ToLower(); + printf("%cDet%d SID:%4d Alp:%+.3f X:%+9.4f Meas:%s Mat: ",IsInvDir() ? '*':' ', + GetDetID(),GetSID(),GetAlphaSens(),GetXSens(),ContainsMeasurement() ? "ON":"OFF"); + if (!ContainsMaterial()) printf("OFF\n"); + else printf("x2X0: %.4f x*rho: %.4f | pars:[%3d:%3d)\n",GetX2X0(),GetXTimesRho(),GetMinLocVarID(),GetMaxLocVarID()); + // + if (opts.Contains("meas") && ContainsMeasurement()) { + printf(" MeasPnt: Xtr: %+9.4f Ytr: %+8.4f Ztr: %+9.4f | ErrYZ: %+e %+e %+e | %d DOFglo\n", + GetXTracking(),GetYTracking(),GetZTracking(), + fErrYZTracking[0],fErrYZTracking[1],fErrYZTracking[2],GetNGloDOFs()); + printf(" DiagErr: %+e %+e\n", fErrDiag[0], fErrDiag[1]); + } + // + if (opts.Contains("mat") && ContainsMaterial()) { + printf(" MatCorr Exp(ELOSS): %+.4e %+.4e %+.4e %+.4e %+.4e\n", + fMatCorrExp[0], fMatCorrExp[1], fMatCorrExp[2], fMatCorrExp[3], fMatCorrExp[4]); + printf(" MatCorr Cov (diag): %+.4e %+.4e %+.4e %+.4e %+.4e\n", + fMatCorrCov[0], fMatCorrCov[1], fMatCorrCov[2], fMatCorrCov[3], fMatCorrCov[4]); + // + if (opts.Contains("umat")) { + float covUndiag[15]; + memset(covUndiag,0,15*sizeof(float)); + int np = GetNMatPar(); + for (int i=0;iIsInvDir()==kTRUE) ranged in increasing X + // lower leg - in decreasing X + AliAlgPoint* pnt = (AliAlgPoint*)b; + double x = GetXPoint(); + double xp = pnt->GetXPoint(); + if (!IsInvDir()) { // track propagates from low to large X via this point + if (!pnt->IsInvDir()) { // via this one also + return x>xp ? -1:1; + } + else return -1; // range points of lower leg 1st + } + else { // this point is from upper cosmic leg: track propagates from large to low X + if (pnt->IsInvDir()) { // this one also + return x>xp ? 1:-1; + } + else return 1; // other point is from lower leg + } + // +} + +//__________________________________________________________________ +void AliAlgPoint::GetXYZGlo(Double_t r[3]) const +{ + // position in lab frame + double cs=TMath::Cos(fAlphaSens); + double sn=TMath::Sin(fAlphaSens); + double x=GetXPoint(); + r[0] = x*cs - GetYTracking()*sn; + r[1] = x*sn + GetYTracking()*cs; + r[2] = GetZTracking(); + // +} + +//__________________________________________________________________ +Double_t AliAlgPoint::GetPhiGlo() const +{ + // phi angle (-pi:pi) in global frame + double xyz[3]; + GetXYZGlo(xyz); + return ATan2(xyz[1],xyz[0]); +} + +//__________________________________________________________________ +Int_t AliAlgPoint::GetAliceSector() const +{ + // get global sector ID corresponding to this point phi + return Phi2Sector(GetPhiGlo()); +} + +//__________________________________________________________________ +void AliAlgPoint::SetMatCovDiagonalizationMatrix(const TMatrixD& d) +{ + // save non-sym matrix for material corrections cov.matrix diagonalization + // (actually, the eigenvectors are stored) + int sz = d.GetNrows(); + for (int i=sz;i--;) for (int j=sz;j--;) fMatDiag[i][j] = d(i,j); +} + +//__________________________________________________________________ +void AliAlgPoint::SetMatCovDiag(const TVectorD& v) +{ + // save material correction diagonalized matrix + // (actually, the eigenvalues are stored w/o reordering them to correspond to the + // AliExternalTrackParam variables) + for (int i=v.GetNrows();i--;) fMatCorrCov[i] = v(i); +} + +//__________________________________________________________________ +void AliAlgPoint::UnDiagMatCorr(const double* diag, double* nodiag) const +{ + // transform material corrections from the frame diagonalizing the errors to point frame + // nodiag = fMatDiag * diag + int np = GetNMatPar(); + for (int ip=np;ip--;) { + double v = 0; + for (int jp=np;jp--;) v += fMatDiag[ip][jp]*diag[jp]; + nodiag[ip] = v; + } + // +} + +//__________________________________________________________________ +void AliAlgPoint::UnDiagMatCorr(const float* diag, float* nodiag) const +{ + // transform material corrections from the frame diagonalizing the errors to point frame + // nodiag = fMatDiag * diag + int np = GetNMatPar(); + for (int ip=np;ip--;) { + double v = 0; + for (int jp=np;jp--;) v += double(fMatDiag[ip][jp])*diag[jp]; + nodiag[ip] = v; + } + // +} + +//__________________________________________________________________ +void AliAlgPoint::DiagMatCorr(const double* nodiag, double* diag) const +{ + // transform material corrections from the AliExternalTrackParam frame to + // the frame diagonalizing the errors + // diag = fMatDiag^T * nodiag + int np = GetNMatPar(); + for (int ip=np;ip--;) { + double v = 0; + for (int jp=np;jp--;) v += fMatDiag[jp][ip]*nodiag[jp]; + diag[ip] = v; + } + // +} + +//__________________________________________________________________ +void AliAlgPoint::DiagMatCorr(const float* nodiag, float* diag) const +{ + // transform material corrections from the AliExternalTrackParam frame to + // the frame diagonalizing the errors + // diag = fMatDiag^T * nodiag + int np = GetNMatPar(); + for (int ip=np;ip--;) { + double v = 0; + for (int jp=np;jp--;) v += double(fMatDiag[jp][ip])*nodiag[jp]; + diag[ip] = v; + } + // +} + +//__________________________________________________________________ +void AliAlgPoint::GetTrWSA(AliExternalTrackParam& etp) const +{ + // assign WSA (after material corrections) parameters to supplied track + double covDum[15]={ + 1.e-4, + 0 ,1.e-4, + 0 , 0,1.e-4, + 0 , 0, 0,1.e-4, + 0 , 0, 0, 0,1e-4 + }; + etp.Set(GetXPoint(),GetAlphaSens(),fTrParamWSA,covDum); +} + +//__________________________________________________________________ +void AliAlgPoint::GetTrWSB(AliExternalTrackParam& etp) const +{ + // assign WSB parameters (before material corrections) to supplied track + double covDum[15]={ + 1.e-4, + 0 ,1.e-4, + 0 , 0,1.e-4, + 0 , 0, 0,1.e-4, + 0 , 0, 0, 0,1e-4 + }; + etp.Set(GetXPoint(),GetAlphaSens(),fTrParamWSB,covDum); +} diff --git a/Detectors/Align/AliAlgPoint.h b/Detectors/Align/AliAlgPoint.h new file mode 100644 index 0000000000000..ef12ea4d62833 --- /dev/null +++ b/Detectors/Align/AliAlgPoint.h @@ -0,0 +1,229 @@ +#ifndef ALIALGPOINT_H +#define ALIALGPOINT_H + +#include +#include +#include +#include "AliAlgSens.h" + +class AliExternalTrackParam; + +/*-------------------------------------------------------- + Meausered point in the sensor. + The measurement is in the tracking frame. + Apart from measurement may contain also material information. + Cashes residuals and track positions at its reference X + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + + +class AliAlgPoint : public TObject +{ + public: + enum {kMaterialBit=BIT(14) // point contains material + ,kMeasurementBit=BIT(15) // point contains measurement + ,kUpdateFromTrackBit=BIT(16) // point needs to recalculate itself using track info + ,kVaryELossBit=BIT(17) // ELoss variation allowed + ,kUseBzOnly=BIT(18) // use only Bz component (ITS) + ,kInvDir=BIT(19) // propagation via this point is in decreasing X direction (upper cosmic leg) + ,kStatOK=BIT(20) // point is accounted in global statistics + }; + enum {kParY = 0 // track parameters + ,kParZ + ,kParSnp + ,kParTgl + ,kParQ2Pt, + kNMSPar=4,kNELossPar=1,kNMatDOFs=kNMSPar+kNELossPar}; + enum {kX,kY,kZ}; + // + AliAlgPoint(); + virtual ~AliAlgPoint() {} + // + void Init(); + void UpdatePointByTrackInfo(const AliExternalTrackParam* t); + // + Double_t GetAlphaSens() const {return fAlphaSens;} + Double_t GetXSens() const {return fXSens;} + Double_t GetXPoint() const {return fXSens + GetXTracking();} + Double_t GetXTracking() const {return fXYZTracking[0];} + Double_t GetYTracking() const {return fXYZTracking[1];} + Double_t GetZTracking() const {return fXYZTracking[2];} + const Double_t* GetYZTracking() const {return &fXYZTracking[1];} + const Double_t* GetXYZTracking() const {return fXYZTracking;} + const Double_t* GetYZErrTracking() const {return fErrYZTracking;} + // + const AliAlgSens* GetSensor() const {return fSensor;} + UInt_t GetVolID() const {return fSensor->GetVolID();} + void SetSensor(AliAlgSens* s) {fSensor = s;} + Int_t GetDetID() const {return fDetID;} + Int_t GetSID() const {return fSID;} + Int_t GetMinLocVarID() const {return fMinLocVarID;} + Int_t GetMaxLocVarID() const {return fMaxLocVarID;} + Int_t GetNMatPar() const; + Bool_t ContainsMaterial() const {return TestBit(kMaterialBit);} + Bool_t ContainsMeasurement() const {return TestBit(kMeasurementBit);} + Bool_t GetNeedUpdateFromTrack() const {return TestBit(kUpdateFromTrackBit);} + Bool_t GetELossVaried() const {return TestBit(kVaryELossBit);} + Bool_t GetUseBzOnly() const {return TestBit(kUseBzOnly);} + Bool_t IsInvDir() const {return TestBit(kInvDir);} + Bool_t IsStatOK() const {return TestBit(kStatOK);} + // + Double_t GetXTimesRho() const {return fXTimesRho;} + Double_t GetX2X0() const {return fX2X0;} + void SetXTimesRho(double v) {fXTimesRho = v;} + void SetX2X0(double v) {fX2X0 = v;} + // + void SetDetID(Int_t id) {fDetID = (Char_t)id;} + void SetSID(Int_t id) {fSID = (Short_t)id;} + // + void SetMinLocVarID(Int_t id) {fMinLocVarID = id;} + void SetMaxLocVarID(Int_t id) {fMaxLocVarID = id;} + void SetELossVaried(Bool_t v=kTRUE) {SetBit(kVaryELossBit,v);} + void SetContainsMaterial(Bool_t v=kTRUE) {SetBit(kMaterialBit,v);} + void SetContainsMeasurement(Bool_t v=kTRUE) {SetBit(kMeasurementBit,v);} + void SetNeedUpdateFromTrack(Bool_t v=kTRUE ) {SetBit(kUpdateFromTrackBit,v);} + void SetUseBzOnly(Bool_t v=kTRUE) {SetBit(kUseBzOnly,v);} + void SetInvDir(Bool_t v=kTRUE) {SetBit(kInvDir,v);} + void SetStatOK(Bool_t v=kTRUE) {SetBit(kStatOK,v);} + // + void GetResidualsDiag(const double* pos, double &resU, double &resV) const; + void DiagonalizeResiduals(double rY, double rZ, double &resU, double &resV) const; + // + void SetAlphaSens(double a) {fAlphaSens = a;} + void SetXSens(double x) {fXSens = x;} + void SetXYZTracking(const double r[3]) {for (int i=3;i--;) fXYZTracking[i]=r[i];} + void SetXYZTracking(double x,double y,double z); + void SetYZErrTracking(double sy2, double syz, double sz2); + void SetYZErrTracking(const double *err) {for (int i=3;i--;) fErrYZTracking[i]=err[i];} + Double_t GetErrDiag(int i) const {return fErrDiag[i];} + // + Double_t* GetTrParamWSA() const {return (Double_t*)fTrParamWSA;} + Double_t* GetTrParamWSB() const {return (Double_t*)fTrParamWSB;} + Double_t GetTrParamWSA(int ip) const {return fTrParamWSA[ip];} + Double_t GetTrParamWSB(int ip) const {return fTrParamWSB[ip];} + void GetTrWSA(AliExternalTrackParam& etp) const; + void GetTrWSB(AliExternalTrackParam& etp) const; + void SetTrParamWSA(const double* param) {for (int i=5;i--;) fTrParamWSA[i] = param[i];} + void SetTrParamWSB(const double* param) {for (int i=5;i--;) fTrParamWSB[i] = param[i];} + Double_t GetResidY() const {return GetTrParamWSA(kParY) - GetYTracking();} + Double_t GetResidZ() const {return GetTrParamWSA(kParZ) - GetZTracking();} + // + void SetMatCovDiagonalizationMatrix(const TMatrixD& d); + void SetMatCovDiag(const TVectorD& v); + void SetMatCovDiagElem(int i, double err2) {fMatCorrCov[i] = err2;} + void UnDiagMatCorr(const double* diag, double* nodiag) const; + void DiagMatCorr(const double* nodiag, double* diag) const; + void UnDiagMatCorr(const float* diag, float* nodiag) const; + void DiagMatCorr(const float* nodiag, float* diag) const; + // + void SetMatCorrExp(Double_t *p) {for (int i=5;i--;) fMatCorrExp[i] = p[i];} + Float_t* GetMatCorrExp() const {return (float*)fMatCorrExp;} + Float_t* GetMatCorrCov() const {return (float*)fMatCorrCov;} + // + void GetXYZGlo(Double_t r[3]) const; + Double_t GetPhiGlo() const; + Int_t GetAliceSector() const; + // + Int_t GetNGloDOFs() const {return fNGloDOFs;} + Int_t GetDGloOffs() const {return fDGloOffs;} + void SetNGloDOFs(int n) {fNGloDOFs = n;} + void SetDGloOffs(int n) {fDGloOffs = n;} + // + void IncrementStat(); + // + virtual void DumpCoordinates() const; + virtual void Print(Option_t* option = "") const; + virtual void Clear(Option_t* option = ""); + // + protected: + virtual Bool_t IsSortable() const {return kTRUE;} + virtual Int_t Compare(const TObject* a) const; + // + // ---------- dummies ---------- + AliAlgPoint(const AliAlgPoint&); + AliAlgPoint& operator=(const AliAlgPoint&); + // + protected: + // + Int_t fMinLocVarID; // The residuals/derivatives depend on fNLocExtPar params + // and point params>=fMinLocVarID. + Int_t fMaxLocVarID; // The residuals/derivatives depend on fNLocExtPar params + // and point paramsIncrementStat(); + SetStatOK(); +} + + +#endif diff --git a/Detectors/Align/AliAlgRes.cxx b/Detectors/Align/AliAlgRes.cxx new file mode 100644 index 0000000000000..79f1e75ba0f3b --- /dev/null +++ b/Detectors/Align/AliAlgRes.cxx @@ -0,0 +1,300 @@ +/************************************************************************** + * 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. * + **************************************************************************/ + +#include "AliAlgRes.h" +#include "AliAlgTrack.h" +#include "AliAlgPoint.h" +#include "AliAlgSens.h" +#include "AliLog.h" +#include +#include +#include + +using namespace TMath; + +ClassImp(AliAlgRes) + +//____________________________________ +AliAlgRes::AliAlgRes() +: fRun(0) + ,fBz(0) + ,fTimeStamp(0) + ,fTrackID(0) + ,fNPoints(0) + ,fNBook(0) + ,fChi2(0) + ,fChi2Ini(0) + ,fChi2K(0) + ,fQ2Pt(0) + ,fX(0) + ,fY(0) + ,fZ(0) + ,fSnp(0) + ,fTgl(0) + ,fAlpha(0) + ,fDY(0) + ,fDZ(0) + ,fDYK(0) + ,fDZK(0) + ,fSigY2(0) + ,fSigYZ(0) + ,fSigZ2(0) + ,fSigY2K(0) + ,fSigYZK(0) + ,fSigZ2K(0) + ,fVolID(0) + ,fLabel(0) +{ + // def c-tor +} + +//________________________________________________ +AliAlgRes::~AliAlgRes() +{ + // d-tor + delete[] fX; + delete[] fY; + delete[] fZ; + delete[] fSnp; + delete[] fTgl; + delete[] fAlpha; + delete[] fDY; + delete[] fDZ; + delete[] fSigY2; + delete[] fSigYZ; + delete[] fSigZ2; + delete[] fDYK; + delete[] fDZK; + delete[] fSigY2K; + delete[] fSigYZK; + delete[] fSigZ2K; + delete[] fVolID; + delete[] fLabel; +} + +//________________________________________________ +void AliAlgRes::Resize(Int_t np) +{ + // resize container + if (np>fNBook) { + delete[] fX; + delete[] fY; + delete[] fZ; + delete[] fSnp; + delete[] fTgl; + delete[] fAlpha; + delete[] fDY; + delete[] fDZ; + delete[] fSigY2; + delete[] fSigYZ; + delete[] fSigZ2; + delete[] fDYK; + delete[] fDZK; + delete[] fSigY2K; + delete[] fSigYZK; + delete[] fSigZ2K; + delete[] fVolID; + delete[] fLabel; + // + fNBook = 100+np; + fX = new Float_t[fNBook]; + fY = new Float_t[fNBook]; + fZ = new Float_t[fNBook]; + fSnp = new Float_t[fNBook]; + fTgl = new Float_t[fNBook]; + fAlpha = new Float_t[fNBook]; + fDY = new Float_t[fNBook]; + fDZ = new Float_t[fNBook]; + fSigY2 = new Float_t[fNBook]; + fSigYZ = new Float_t[fNBook]; + fSigZ2 = new Float_t[fNBook]; + fDYK = new Float_t[fNBook]; + fDZK = new Float_t[fNBook]; + fSigY2K = new Float_t[fNBook]; + fSigYZK = new Float_t[fNBook]; + fSigZ2K = new Float_t[fNBook]; + fVolID = new Int_t[fNBook]; + fLabel = new Int_t[fNBook]; + // + memset(fX , 0,fNBook*sizeof(Float_t)); + memset(fY , 0,fNBook*sizeof(Float_t)); + memset(fZ , 0,fNBook*sizeof(Float_t)); + memset(fSnp , 0,fNBook*sizeof(Float_t)); + memset(fTgl , 0,fNBook*sizeof(Float_t)); + memset(fAlpha, 0,fNBook*sizeof(Float_t)); + memset(fDY , 0,fNBook*sizeof(Float_t)); + memset(fDZ , 0,fNBook*sizeof(Float_t)); + memset(fSigY2, 0,fNBook*sizeof(Float_t)); + memset(fSigYZ, 0,fNBook*sizeof(Float_t)); + memset(fSigZ2, 0,fNBook*sizeof(Float_t)); + memset(fDYK , 0,fNBook*sizeof(Float_t)); + memset(fDZK , 0,fNBook*sizeof(Float_t)); + memset(fSigY2K,0,fNBook*sizeof(Float_t)); + memset(fSigYZK,0,fNBook*sizeof(Float_t)); + memset(fSigZ2K,0,fNBook*sizeof(Float_t)); + memset(fVolID, 0,fNBook*sizeof(Int_t)); + memset(fLabel, 0,fNBook*sizeof(Int_t)); + } + // +} + +//____________________________________________ +void AliAlgRes::Clear(const Option_t *) +{ + // reset record + TObject::Clear(); + ResetBit(0xffffffff); + fNPoints = 0; + fRun = 0; + fTimeStamp = 0; + fTrackID = 0; + fChi2 = 0; + fChi2K= 0; + fQ2Pt = 0; + // +} + +//____________________________________________ +void AliAlgRes::Print(const Option_t *opt) const +{ + // print info + TString opts = opt; opts.ToLower(); + Bool_t lab = opts.Contains("l"); + printf("%5sTr.",IsCosmic() ? "Cosm.":"Coll."); + if (IsCosmic()) printf("%2d/%2d ",fTrackID>>16,fTrackID&0xffff); + else printf("%5d ",fTrackID); + printf("Run:%6d Bz:%+4.1f Np: %3d q/Pt:%+.4f | Chi2: Ini: %6.1f LinSol:%6.1f Kalm:%6.1f |Vtx:%3s| TStamp:%d\n", + fRun,fBz,fNPoints,fQ2Pt,fChi2Ini,fChi2,fChi2K,HasVertex() ? "ON":"OFF",fTimeStamp); + if (opts.Contains("r")) { + Bool_t ers = opts.Contains("e"); + printf("%5s %7s %s %7s %7s %7s %5s %5s %9s %9s", + " VID "," Label "," Alp "," X "," Y "," Z "," Snp "," Tgl "," DY "," DZ "); + if (ers) printf(" %8s %8s %8s"," pSgYY "," pSgYZ "," pSgZZ "); // cluster errors + if (GetKalmanDone()) { + printf(" %9s %9s"," DYK "," DZK "); + if (ers) printf(" %8s %8s %8s"," tSgYY "," tSgYZ "," tSgZZ "); // track errors + } + printf("\n"); + for (int i=0;iGetNPoints(); + if (trc->GetInnerPoint()->ContainsMeasurement()) { + SetHasVertex(); + nps = np; + } + else nps = np-1; // ref point is dummy? + if (nps<0) return kTRUE; + SetCosmic(trc->IsCosmic()); + // + SetNPoints(nps); + fQ2Pt = trc->GetSigned1Pt(); + fChi2 = trc->GetChi2(); + fChi2Ini = trc->GetChi2Ini(); + int nfill = 0; + for (int i=0;iGetPoint(i); + int inv = pnt->IsInvDir() ? -1:1; // Flag invertion for cosmic upper leg + if (!pnt->ContainsMeasurement()) continue; + if (!pnt->IsStatOK()) pnt->IncrementStat(); + fVolID[nfill] = pnt->GetVolID(); + fLabel[nfill] = pnt->GetSensor()->GetInternalID(); + fAlpha[nfill] = pnt->GetAlphaSens(); + fX[nfill] = pnt->GetXPoint()*inv; + fY[nfill] = pnt->GetYTracking(); + fZ[nfill] = pnt->GetZTracking(); + fDY[nfill] = pnt->GetResidY(); + fDZ[nfill] = pnt->GetResidZ(); + fSigY2[nfill] = pnt->GetYZErrTracking()[0]; + fSigYZ[nfill] = pnt->GetYZErrTracking()[1]; + fSigZ2[nfill] = pnt->GetYZErrTracking()[2]; + // + fSnp[nfill] = pnt->GetTrParamWSA()[AliAlgPoint::kParSnp]; + fTgl[nfill] = pnt->GetTrParamWSA()[AliAlgPoint::kParTgl]; + // + nfill++; + } + if (nfill!=nps) { + trc->Print("p"); + AliFatalF("Something is wrong: %d residuals were stored instead of %d",nfill,nps); + } + // + SetKalmanDone(kFALSE); + int nfilk=0; + if (doKalman && trc->ResidKalman()) { + for (int i=0;iGetPoint(i); + if (!pnt->ContainsMeasurement()) continue; + if (fVolID[nfilk] != int(pnt->GetVolID())) { + AliFatalF("Mismatch in Kalman filling for point %d: filled VID:%d, point VID:%d", + i,fVolID[nfilk],pnt->GetVolID()); + } + const double* wsA = pnt->GetTrParamWSA(); + fDYK[nfilk] = pnt->GetResidY(); + fDZK[nfilk] = pnt->GetResidZ(); + fSigY2K[nfilk] = wsA[2]; + fSigYZK[nfilk] = wsA[3]; + fSigZ2K[nfilk] = wsA[4]; + // + nfilk++; + } + // + fChi2K = trc->GetChi2(); + SetKalmanDone(kTRUE); + } + + return kTRUE; +} + +//_________________________________________________ +Float_t AliAlgRes::GetXLab(int i) const +{ + // cluster lab X + return Abs(fX[i])*Cos(fAlpha[i]) - fY[i]*Sin(fAlpha[i]); +} + +//_________________________________________________ +Float_t AliAlgRes::GetYLab(int i) const +{ + // cluster lab Y + return Abs(fX[i])*Sin(fAlpha[i]) + fY[i]*Cos(fAlpha[i]); +} + +//_________________________________________________ +Float_t AliAlgRes::GetZLab(int i) const +{ + // cluster lab Z + return fZ[i]; +} diff --git a/Detectors/Align/AliAlgRes.h b/Detectors/Align/AliAlgRes.h new file mode 100644 index 0000000000000..55a1735ac9a39 --- /dev/null +++ b/Detectors/Align/AliAlgRes.h @@ -0,0 +1,128 @@ +#ifndef ALIALGRES_H +#define ALIALGRES_H + +#include +#include +class AliAlgTrack; + +/*-------------------------------------------------------- + Container for control residuals + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + + + +class AliAlgRes: public TObject +{ + public: + enum {kCosmicBit=BIT(14),kVertexBit=BIT(15),kKalmanDoneBit=BIT(16)}; + // + AliAlgRes(); + virtual ~AliAlgRes(); + // + void SetRun(int r) {fRun = r;} + void SetBz(float v) {fBz = v;} + void SetTimeStamp(UInt_t v) {fTimeStamp = v;} + void SetTrackID(UInt_t v) {fTrackID = v;} + void SetNPoints(Int_t n) {fNPoints=n; Resize(n);} + // + Bool_t IsCosmic() const {return TestBit(kCosmicBit);} + Bool_t HasVertex() const {return TestBit(kVertexBit);} + void SetCosmic(Bool_t v=kTRUE) {SetBit(kCosmicBit,v);} + void SetHasVertex(Bool_t v=kTRUE) {SetBit(kVertexBit,v);} + // + Bool_t GetKalmanDone() const {return TestBit(kKalmanDoneBit);} + void SetKalmanDone(Bool_t v=kTRUE) {SetBit(kKalmanDoneBit,v);} + // + Int_t GetRun() const {return fRun;} + Float_t GetBz() const {return fBz;} + UInt_t GetTimeStamp() const {return fTimeStamp;} + UInt_t GetTrackID() const {return fTrackID;} + Int_t GetNPoints() const {return fNPoints;} + Int_t GetNBook() const {return fNBook;} + Float_t GetChi2() const {return fChi2;} + Float_t GetChi2Ini() const {return fChi2Ini;} + Float_t GetChi2K() const {return fChi2K;} + Float_t GetQ2Pt() const {return fQ2Pt;} + Float_t GetX(int i) const {return fX[i];} + Float_t GetY(int i) const {return fY[i];} + Float_t GetZ(int i) const {return fZ[i];} + Float_t GetSnp(int i) const {return fSnp[i];} + Float_t GetTgl(int i) const {return fTgl[i];} + Float_t GetAlpha(int i) const {return fAlpha[i];} + Float_t GetDY(int i) const {return fDY[i];} + Float_t GetDZ(int i) const {return fDZ[i];} + Float_t GetDYK(int i) const {return fDYK[i];} + Float_t GetDZK(int i) const {return fDZK[i];} + // + Float_t GetSigY2K(int i) const {return fSigY2K[i];} + Float_t GetSigYZK(int i) const {return fSigYZK[i];} + Float_t GetSigZ2K(int i) const {return fSigZ2K[i];} + Float_t GetSigmaYK(int i) const {return TMath::Sqrt(fSigY2K[i]);} + Float_t GetSigmaZK(int i) const {return TMath::Sqrt(fSigZ2K[i]);} + // + Float_t GetSigY2(int i) const {return fSigY2[i];} + Float_t GetSigYZ(int i) const {return fSigYZ[i];} + Float_t GetSigZ2(int i) const {return fSigZ2[i];} + Float_t GetSigmaY(int i) const {return TMath::Sqrt(fSigY2[i]);} + Float_t GetSigmaZ(int i) const {return TMath::Sqrt(fSigZ2[i]);} + // + Float_t GetSigY2Tot(int i) const {return fSigY2K[i]+fSigY2[i];} + Float_t GetSigYZTot(int i) const {return fSigYZK[i]+fSigYZ[i];} + Float_t GetSigZ2Tot(int i) const {return fSigZ2K[i]+fSigZ2[i];} + Float_t GetSigmaYTot(int i) const {return TMath::Sqrt(GetSigY2Tot(i));} + Float_t GetSigmaZTot(int i) const {return TMath::Sqrt(GetSigZ2Tot(i));} + // + Int_t GetVolID(int i) const {return fVolID[i];} + // + Float_t GetXLab(int i) const; + Float_t GetYLab(int i) const; + Float_t GetZLab(int i) const; + // + Bool_t FillTrack(AliAlgTrack* trc, Bool_t doKalman=kTRUE); + void Resize(Int_t n); + virtual void Clear(const Option_t *opt=""); + virtual void Print(const Option_t *opt="re") const; + // + protected: + // + // -------- dummies -------- + AliAlgRes(const AliAlgRes&); + AliAlgRes& operator=(const AliAlgRes&); + // + protected: + // + Int_t fRun; // run + Float_t fBz; // field + UInt_t fTimeStamp; // event time + UInt_t fTrackID; // track ID + Int_t fNPoints; // n meas points + Int_t fNBook; //! booked lenfth + Float_t fChi2; // chi2 after solution + Float_t fChi2Ini; // chi2 before solution + Float_t fChi2K; // chi2 from kalman + Float_t fQ2Pt; // Q/Pt at reference point + Float_t* fX; //[fNPoints] tracking X of cluster + Float_t* fY; //[fNPoints] tracking Y of cluster + Float_t* fZ; //[fNPoints] tracking Z of cluster + Float_t* fSnp; //[fNPoints] track Snp + Float_t* fTgl; //[fNPoints] track Tgl + Float_t* fAlpha; //[fNPoints] track alpha + Float_t* fDY; //[fNPoints] Y residual (track - meas) + Float_t* fDZ; //[fNPoints] Z residual (track - meas) + Float_t* fDYK; //[fNPoints] Y residual (track - meas) Kalman + Float_t* fDZK; //[fNPoints] Z residual (track - meas) Kalman + Float_t* fSigY2; //[fNPoints] Y err^2 + Float_t* fSigYZ; //[fNPoints] YZ err + Float_t* fSigZ2; //[fNPoints] Z err^2 + Float_t* fSigY2K; //[fNPoints] Y err^2 of Kalman track smoothing + Float_t* fSigYZK; //[fNPoints] YZ err of Kalman track smoothing + Float_t* fSigZ2K; //[fNPoints] Z err^2 of Kalman track smoothing + Int_t* fVolID; //[fNPoints] volume id (0 for vertex constraint) + Int_t* fLabel; //[fNPoints] label of the volume + // + ClassDef(AliAlgRes,2); +}; + +#endif diff --git a/Detectors/Align/AliAlgResFast.cxx b/Detectors/Align/AliAlgResFast.cxx new file mode 100644 index 0000000000000..dc48e6992c192 --- /dev/null +++ b/Detectors/Align/AliAlgResFast.cxx @@ -0,0 +1,168 @@ +/************************************************************************** + * 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. * + **************************************************************************/ + +#include "AliAlgResFast.h" +#include "AliAlgTrack.h" +#include "AliAlgPoint.h" +#include "AliAlgSens.h" +#include "AliLog.h" +#include +#include +#include + +using namespace TMath; + +ClassImp(AliAlgResFast) + +//____________________________________ +AliAlgResFast::AliAlgResFast() +: fNPoints(0) + ,fNMatSol(0) + ,fNBook(0) + ,fChi2(0) + ,fChi2Ini(0) + ,fD0(0) + ,fD1(0) + ,fSig0(0) + ,fSig1(0) + ,fVolID(0) + ,fLabel(0) + ,fSolMat(0) + ,fMatErr(0) +{ + // def c-tor + for (int i=5;i--;) fTrCorr[i] = 0; +} + +//________________________________________________ +AliAlgResFast::~AliAlgResFast() +{ + // d-tor + delete[] fD0; + delete[] fD1; + delete[] fSig0; + delete[] fSig1; + delete[] fVolID; + delete[] fLabel; + delete[] fSolMat; + delete[] fMatErr; +} + +//________________________________________________ +void AliAlgResFast::Resize(Int_t np) +{ + // resize container + if (np>fNBook) { + delete[] fD0; + delete[] fD1; + delete[] fSig0; + delete[] fSig1; + delete[] fVolID; + delete[] fLabel; + delete[] fSolMat; + delete[] fMatErr; + // + fNBook = 30+np; + fD0 = new Float_t[fNBook]; + fD1 = new Float_t[fNBook]; + fSig0 = new Float_t[fNBook]; + fSig1 = new Float_t[fNBook]; + fVolID = new Int_t[fNBook]; + fLabel = new Int_t[fNBook]; + fSolMat = new Float_t[fNBook*4]; // at most 4 material params per point + fMatErr = new Float_t[fNBook*4]; // at most 4 material params per point + // + memset(fD0 , 0,fNBook*sizeof(Float_t)); + memset(fD1 , 0,fNBook*sizeof(Float_t)); + memset(fSig0, 0,fNBook*sizeof(Float_t)); + memset(fSig1, 0,fNBook*sizeof(Float_t)); + memset(fVolID, 0,fNBook*sizeof(Int_t)); + memset(fLabel, 0,fNBook*sizeof(Int_t)); + memset(fSolMat, 0,4*fNBook*sizeof(Int_t)); + memset(fMatErr, 0,4*fNBook*sizeof(Int_t)); + } + // +} + +//____________________________________________ +void AliAlgResFast::Clear(const Option_t *) +{ + // reset record + fNPoints = 0; + fNMatSol = 0; + fTrCorr[4] = 0; // rest will be 100% overwritten + // +} + +//____________________________________________ +void AliAlgResFast::Print(const Option_t */*opt*/) const +{ + // print info + printf("%3s:%1s (%9s/%5s) %6s | [ %7s:%7s ]\n","Pnt","M","Label", + "VolID","Sigma","resid","pull/LG"); + for (int irs=0;irs0 ? fD0[irs]/fSig0[irs]:-99); + printf("%3d:%1d (%9d/%5d) %6.4f | [%+.2e:%+7.2f]\n", + irs,1, fLabel[irs],fVolID[irs],fSig1[irs],fD1[irs], + fSig1[irs]>0 ? fD1[irs]/fSig1[irs]:-99); + } + // + printf("CorrETP: "); + for (int i=0;i<5;i++) printf("%+.3f ",fTrCorr[i]); printf("\n"); + printf("MatCorr (corr/sig:pull)\n"); + int nmp = fNMatSol/4; + int cnt = 0; + for (int imp=0;imp0 ? fSolMat[cnt]/fMatErr[cnt] : -99); + cnt++; + } + printf("\n"); + } + // +} + +//____________________________________________ +void AliAlgResFast::SetResSigMeas(int ip, int ord, float res, float sig) +{ + // assign residual and error for measurement + if (ord==0) { + fD0[ip] = res; + fSig0[ip] = sig; + } + else { + fD1[ip] = res; + fSig1[ip] = sig; + } +} + +//____________________________________________ +void AliAlgResFast::SetMatCorr(int id, float res, float sig) +{ + // assign residual and error for material correction + fSolMat[id] = res; + fMatErr[id] = sig; +} + +//____________________________________________ +void AliAlgResFast::SetLabel(int ip, Int_t lab, Int_t vol) +{ + // set label/volid of measured volume + fVolID[ip] = vol; + fLabel[ip] = lab; +} diff --git a/Detectors/Align/AliAlgResFast.h b/Detectors/Align/AliAlgResFast.h new file mode 100644 index 0000000000000..e82e2f627d39e --- /dev/null +++ b/Detectors/Align/AliAlgResFast.h @@ -0,0 +1,92 @@ +#ifndef ALIALGRESFAST_H +#define ALIALGRESFAST_H + +#include + +/*-------------------------------------------------------- + Container for control fast residuals evaluated via derivatives + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + + + +class AliAlgResFast: public TObject +{ + public: + enum {kCosmicBit=BIT(14),kVertexBit=BIT(15)}; + // + AliAlgResFast(); + virtual ~AliAlgResFast(); + // + void SetNPoints(Int_t n) {fNPoints=n; Resize(n);} + void SetNMatSol(Int_t n) {fNMatSol = n;} + // + void SetChi2(float v) {fChi2 = v;} + Float_t GetChi2() const {return fChi2;} + // + void SetChi2Ini(float v) {fChi2Ini = v;} + Float_t GetChi2Ini() const {return fChi2Ini;} + // + Bool_t IsCosmic() const {return TestBit(kCosmicBit);} + Bool_t HasVertex() const {return TestBit(kVertexBit);} + void SetCosmic(Bool_t v=kTRUE) {SetBit(kCosmicBit,v);} + void SetHasVertex(Bool_t v=kTRUE) {SetBit(kVertexBit,v);} + // + Int_t GetNPoints() const {return fNPoints;} + Int_t GetNMatSol() const {return fNMatSol;} + Int_t GetNBook() const {return fNBook;} + Float_t GetD0(int i) const {return fD0[i];} + Float_t GetD1(int i) const {return fD1[i];} + Float_t GetSig0(int i) const {return fSig0[i];} + Float_t GetSig1(int i) const {return fSig1[i];} + Int_t GetVolID(int i) const {return fVolID[i];} + Int_t GetLabel(int i) const {return fLabel[i];} + // + Float_t* GetTrCor() const {return (Float_t*)fTrCorr;} + Float_t* GetD0() const {return (Float_t*)fD0;} + Float_t* GetD1() const {return (Float_t*)fD1;} + Float_t* GetSig0() const {return (Float_t*)fSig0;} + Float_t* GetSig1() const {return (Float_t*)fSig1;} + Int_t* GetVolID() const {return (Int_t*)fVolID;} + Int_t* GetLaber() const {return (Int_t*)fLabel;} + Float_t* GetSolMat() const {return (Float_t*)fSolMat;} + Float_t* GetMatErr() const {return (Float_t*)fMatErr;} + // + void SetResSigMeas(int ip, int ord, float res, float sig); + void SetMatCorr(int id, float res, float sig); + void SetLabel(int ip, Int_t lab, Int_t vol); + // + void Resize(Int_t n); + virtual void Clear(const Option_t *opt=""); + virtual void Print(const Option_t *opt="") const; + // + protected: + // + // -------- dummies -------- + AliAlgResFast(const AliAlgResFast&); + AliAlgResFast& operator=(const AliAlgResFast&); + // + protected: + // + Int_t fNPoints; // n meas points + Int_t fNMatSol; // n local params - ExtTrPar corrections + Int_t fNBook; //! booked lenfth + Float_t fChi2; // chi2 + Float_t fChi2Ini; // chi2 before local fit + // + Float_t fTrCorr[5]; // correction to ExternalTrackParam + Float_t* fD0; //[fNPoints] 1st residual (track - meas) + Float_t* fD1; //[fNPoints] 2ns residual (track - meas) + Float_t* fSig0; //[fNPoints] ort. error 0 + Float_t* fSig1; //[fNPoints] ort. errir 1 + Int_t* fVolID; //[fNPoints] volume id (0 for vertex constraint) + Int_t* fLabel; //[fNPoints] label of the volume + // + Float_t* fSolMat; //[fNMatSol] // material corrections + Float_t* fMatErr; //[fNMatSol] // material corrections errors + // + ClassDef(AliAlgResFast,1); +}; + +#endif diff --git a/Detectors/Align/AliAlgSens.cxx b/Detectors/Align/AliAlgSens.cxx new file mode 100644 index 0000000000000..27667131ed6eb --- /dev/null +++ b/Detectors/Align/AliAlgSens.cxx @@ -0,0 +1,487 @@ +/************************************************************************** + * 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. * + **************************************************************************/ + +#include +#include +#include "AliAlgSens.h" +#include "AliAlgAux.h" +#include "AliLog.h" +#include "AliGeomManager.h" +#include "AliExternalTrackParam.h" +#include "AliAlgPoint.h" +#include "AliAlgDet.h" +#include "AliAlgDOFStat.h" + +ClassImp(AliAlgSens) + +using namespace AliAlgAux; +using namespace TMath; + +//_________________________________________________________ +AliAlgSens::AliAlgSens(const char* name,Int_t vid, Int_t iid) + : AliAlgVol(name,iid) + ,fSID(0) + ,fDet(0) + ,fMatClAlg() + ,fMatClAlgReco() +{ + // def c-tor + SetVolID(vid); + fAddError[0] = fAddError[1] = 0; + fConstrChild = 0; // sensors don't have children +} + +//_________________________________________________________ +AliAlgSens::~AliAlgSens() +{ + // d-tor +} + +//_________________________________________________________ +void AliAlgSens::DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv) const +{ + // Jacobian of position in sensor tracking frame (tra) vs sensor LOCAL frame + // parameters in TGeoHMatrix convention. + // Result is stored in array deriv as linearized matrix 6x3 + const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5}; + double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3]; + TGeoHMatrix matMod; + // + memset(delta,0,kNDOFGeom*sizeof(double)); + memset(deriv,0,kNDOFGeom*3*sizeof(double)); + const double *tra = pnt->GetXYZTracking(); + // + for (int ip=kNDOFGeom;ip--;) { + // + if (!IsFreeDOF(ip)) continue; + // + double var = kDelta[ip]; + delta[ip] -= var; + // variation matrix in tracking frame for variation in sensor LOCAL frame + GetDeltaT2LmodLOC(matMod, delta); + matMod.LocalToMaster(tra,pos0); // varied position in tracking frame + // + delta[ip] += 0.5*var; + GetDeltaT2LmodLOC(matMod, delta); + matMod.LocalToMaster(tra,pos1); // varied position in tracking frame + // + delta[ip] += var; + GetDeltaT2LmodLOC(matMod, delta); + matMod.LocalToMaster(tra,pos2); // varied position in tracking frame + // + delta[ip] += 0.5*var; + GetDeltaT2LmodLOC(matMod, delta); + matMod.LocalToMaster(tra,pos3); // varied position in tracking frame + // + delta[ip] = 0; + double *curd = deriv + ip*3; + for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var; + } + // +} + +//_________________________________________________________ +void AliAlgSens::DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const +{ + // Jacobian of position in sensor tracking frame (tra) vs parent volume LOCAL frame parameters. + // NO check of parentship is done! + // Result is stored in array deriv as linearized matrix 6x3 + const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5}; + double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3]; + TGeoHMatrix matMod; + // this is the matrix for transition from sensor to parent volume local frames: LOC=matRel*loc + TGeoHMatrix matRel = parent->GetMatrixL2GIdeal().Inverse(); + matRel *= GetMatrixL2GIdeal(); + // + memset(delta,0,kNDOFGeom*sizeof(double)); + memset(deriv,0,kNDOFGeom*3*sizeof(double)); + const double *tra = pnt->GetXYZTracking(); + // + for (int ip=kNDOFGeom;ip--;) { + // + if (!IsFreeDOF(ip)) continue; + // + double var = kDelta[ip]; + delta[ip] -= var; + GetDeltaT2LmodLOC(matMod, delta, matRel); + matMod.LocalToMaster(tra,pos0); // varied position in tracking frame + // + delta[ip] += 0.5*var; + GetDeltaT2LmodLOC(matMod, delta, matRel); + matMod.LocalToMaster(tra,pos1); // varied position in tracking frame + // + delta[ip] += var; + GetDeltaT2LmodLOC(matMod, delta, matRel); + matMod.LocalToMaster(tra,pos2); // varied position in tracking frame + // + delta[ip] += 0.5*var; + GetDeltaT2LmodLOC(matMod, delta, matRel); + matMod.LocalToMaster(tra,pos3); // varied position in tracking frame + // + delta[ip] = 0; + double *curd = deriv + ip*3; + for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var; + } + // +} + +//_________________________________________________________ +void AliAlgSens::DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv) const +{ + // Jacobian of position in sensor tracking frame (tra) vs sensor TRACKING + // frame parameters in TGeoHMatrix convention, i.e. the modified parameter is + // tra' = tau*tra + // + // Result is stored in array deriv as linearized matrix 6x3 + const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5}; + double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3]; + TGeoHMatrix matMod; + // + memset(delta,0,kNDOFGeom*sizeof(double)); + memset(deriv,0,kNDOFGeom*3*sizeof(double)); + const double *tra = pnt->GetXYZTracking(); + // + for (int ip=kNDOFGeom;ip--;) { + // + if (!IsFreeDOF(ip)) continue; + // + double var = kDelta[ip]; + delta[ip] -= var; + GetDeltaT2LmodTRA(matMod,delta); + matMod.LocalToMaster(tra,pos0); // varied position in tracking frame + // + delta[ip] += 0.5*var; + GetDeltaT2LmodTRA(matMod,delta); + matMod.LocalToMaster(tra,pos1); // varied position in tracking frame + // + delta[ip] += var; + GetDeltaT2LmodTRA(matMod,delta); + matMod.LocalToMaster(tra,pos2); // varied position in tracking frame + // + delta[ip] += 0.5*var; + GetDeltaT2LmodTRA(matMod,delta); + matMod.LocalToMaster(tra,pos3); // varied position in tracking frame + // + delta[ip] = 0; + double *curd = deriv + ip*3; + for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var; + } + // +} + +//_________________________________________________________ +void AliAlgSens::DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const +{ + // Jacobian of position in sensor tracking frame (tra) vs sensor TRACKING + // frame parameters in TGeoHMatrix convention, i.e. the modified parameter is + // tra' = tau*tra + // + // Result is stored in array deriv as linearized matrix 6x3 + const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5}; + double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3]; + TGeoHMatrix matMod; + // + // 1st we need a matrix for transition between child and parent TRACKING frames + // Let TRA,LOC are positions in tracking and local frame of parent, linked as LOC=T2L*TRA + // and tra,loc are positions in tracking and local frame of child, linked as loc=t2l*tra + // The loc and LOC are linked as LOC=R*loc, where R = L2G^-1*l2g, with L2G and l2g + // local2global matrices for parent and child + // + // Then, TRA = T2L^-1*LOC = T2L^-1*R*loc = T2L^-1*R*t2l*tra + // -> TRA = matRel*tra, with matRel = T2L^-1*L2G^-1 * l2g*t2l + // Note that l2g*t2l are tracking to global matrices + TGeoHMatrix matRel,t2gP; + GetMatrixT2G(matRel); // t2g matrix of child + parent->GetMatrixT2G(t2gP); // t2g matrix of parent + const TGeoHMatrix& t2gpi = t2gP.Inverse(); + matRel.MultiplyLeft(&t2gpi); + // + memset(delta,0,kNDOFGeom*sizeof(double)); + memset(deriv,0,kNDOFGeom*3*sizeof(double)); + const double *tra = pnt->GetXYZTracking(); + // + for (int ip=kNDOFGeom;ip--;) { + // + if (!IsFreeDOF(ip)) continue; + // + double var = kDelta[ip]; + delta[ip] -= var; + GetDeltaT2LmodTRA(matMod,delta,matRel); + matMod.LocalToMaster(tra,pos0); // varied position in tracking frame + // + delta[ip] += 0.5*var; + GetDeltaT2LmodTRA(matMod,delta,matRel); + matMod.LocalToMaster(tra,pos1); // varied position in tracking frame + // + delta[ip] += var; + GetDeltaT2LmodTRA(matMod,delta,matRel); + matMod.LocalToMaster(tra,pos2); // varied position in tracking frame + // + delta[ip] += 0.5*var; + GetDeltaT2LmodTRA(matMod,delta,matRel); + matMod.LocalToMaster(tra,pos3); // varied position in tracking frame + // + delta[ip] = 0; + double *curd = deriv + ip*3; + for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var; + } + // +} + +//_________________________________________________________ +void AliAlgSens::DPosTraDParGeom(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const +{ + // calculate point position derivatives in tracking frame of sensor + // vs standard geometrical DOFs of its parent volume (if parent!=0) or sensor itself + Frame_t frame = parent ? parent->GetVarFrame() : GetVarFrame(); + switch(frame) { + case kLOC : parent ? DPosTraDParGeomLOC(pnt,deriv,parent) : DPosTraDParGeomLOC(pnt,deriv); + break; + case kTRA : parent ? DPosTraDParGeomTRA(pnt,deriv,parent) : DPosTraDParGeomTRA(pnt,deriv); + break; + default : AliErrorF("Alignment frame %d is not implemented",parent->GetVarFrame()); + break; + } +} + +//__________________________________________________________________ +void AliAlgSens::GetModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const Double_t *delta) const +{ + // prepare the sensitive module tracking2local matrix from its current T2L matrix + // by applying local delta of modification of LOCAL frame: + // loc' = delta*loc = T2L'*tra = T2L'*T2L^-1*loc -> T2L' = delta*T2L + Delta2Matrix(matMod, delta); + matMod.Multiply(&GetMatrixT2L()); +} + + +//__________________________________________________________________ +void AliAlgSens::GetModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const Double_t *delta) const +{ + // prepare the sensitive module tracking2local matrix from its current T2L matrix + // by applying local delta of modification of TRACKING frame: + // loc' = T2L'*tra = T2L*delta*tra -> T2L' = T2L*delta + Delta2Matrix(matMod, delta); + matMod.MultiplyLeft(&GetMatrixT2L()); +} + +//__________________________________________________________________ +void AliAlgSens::AddChild(AliAlgVol*) +{ + AliFatalF("Sensor volume cannot have childs: id=%d %s",GetVolID(),GetName()); +} + +//__________________________________________________________________ +Int_t AliAlgSens::Compare(const TObject* b) const +{ + // compare VolIDs + return GetUniqueID()GetUniqueID() ? -1 : 1; +} + +//__________________________________________________________________ +void AliAlgSens::SetTrackingFrame() +{ + // define tracking frame of the sensor + // AliWarningF("Generic method called for %s",GetSymName()); + double tra[3]={0},glo[3]; + TGeoHMatrix t2g; + GetMatrixT2G(t2g); + t2g.LocalToMaster(tra,glo); + fX = Sqrt(glo[0]*glo[0]+glo[1]*glo[1]); + fAlp = ATan2(glo[1],glo[0]); + AliAlgAux::BringToPiPM(fAlp); + // +} + +//____________________________________________ +void AliAlgSens::Print(const Option_t *opt) const +{ + // print info + TString opts = opt; + opts.ToLower(); + printf("Lev:%2d IntID:%7d %s VId:%6d X:%8.4f Alp:%+.4f | Err: %.4e %.4e | Used Points: %d\n", + CountParents(), GetInternalID(), GetSymName(), GetVolID(), fX, fAlp, + fAddError[0],fAddError[1],fNProcPoints); + printf(" DOFs: Tot: %d (offs: %5d) Free: %d Geom: %d {",fNDOFs,fFirstParGloID,fNDOFFree,fNDOFGeomFree); + for (int i=0;iUpdatePointByTrackInfo(pnt,t); +} + +//____________________________________________ +void AliAlgSens::DPosTraDParCalib(const AliAlgPoint* pnt,double* deriv,int calibID,const AliAlgVol* parent) const +{ + // calculate point position X,Y,Z derivatives wrt calibration parameter calibID of given parent + // parent=0 means top detector object calibration + // + deriv[0]=deriv[1]=deriv[2]=0; +} + +//______________________________________________________ +Int_t AliAlgSens::FinalizeStat(AliAlgDOFStat* st) +{ + // finalize statistics on processed points + if (st) FillDOFStat(st); + return fNProcPoints; +} + +//_________________________________________________________________ +void AliAlgSens::UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix *cumulDelta) +{ + // recreate fMatL2GReco matrices from ideal L2G matrix and alignment objects + // used during data reconstruction. + // On top of what each volume does, also update misalignment matrix inverse + // + AliAlgVol::UpdateL2GRecoMatrices(algArr,cumulDelta); + PrepareMatrixClAlgReco(); + // +} + +/* +//_________________________________________________________________ +AliAlgPoint* AliAlgSens::TrackPoint2AlgPoint(int, const AliTrackPointArray*, const AliESDtrack*) +{ + // dummy converter + AliError("Generic method, must be implemented in specific sensor"); + return 0; +} +*/ + +//_________________________________________________________________ +void AliAlgSens::ApplyAlignmentFromMPSol() +{ + // apply to the tracking coordinates in the sensor frame the full chain + // of alignments found by MP for this sensor and its parents + // + const AliAlgVol* vol = this; + TGeoHMatrix deltaG; + // create global combined delta: + // DeltaG = deltaG_0*...*deltaG_j, where delta_i is global delta of each member of hierarchy + while(vol) { + TGeoHMatrix deltaGJ; + vol->CreateAlignmenMatrix(deltaGJ); + deltaG.MultiplyLeft(&deltaGJ); + vol = vol->GetParent(); + } + // + // update misaligned L2G matrix + deltaG *= GetMatrixL2GIdeal(); + SetMatrixL2G(deltaG); + // + // update local misalignment matrix + PrepareMatrixClAlg(); + // +} + +/* +//_________________________________________________________________ +void AliAlgSens::ApplyAlignmentFromMPSol() +{ + // apply to the tracking coordinates in the sensor frame the full chain + // of alignments found by MP for this sensor and its parents + double delta[kNDOFGeom]={0}; + // + TGeoHMatrix matMod; + // + // sensor proper variation + GetParValGeom(delta); + IsFrameTRA() ? GetDeltaT2LmodTRA(matMod,delta) : GetDeltaT2LmodLOC(matMod,delta); + fMatClAlg.MultiplyLeft(&matMod); + // + AliAlgVol* parent = this; + while ((parent==parent->GetParent())) { + // this is the matrix for transition from sensor to parent volume frame + parent->GetParValGeom(delta); + TGeoHMatrix matRel,t2gP; + if (parent->IsFrameTRA()) { + GetMatrixT2G(matRel); // t2g matrix of child + parent->GetMatrixT2G(t2gP); // t2g matrix of parent + matRel.MultiplyLeft(&t2gP.Inverse()); + GetDeltaT2LmodTRA(matMod, delta, matRel); + } + else { + matRel = parent->GetMatrixL2GIdeal().Inverse(); + matRel *= GetMatrixL2GIdeal(); + GetDeltaT2LmodLOC(matMod, delta, matRel); + } + fMatClAlg.MultiplyLeft(&matMod); + } + // +} + +*/ diff --git a/Detectors/Align/AliAlgSens.h b/Detectors/Align/AliAlgSens.h new file mode 100644 index 0000000000000..865a0271c2645 --- /dev/null +++ b/Detectors/Align/AliAlgSens.h @@ -0,0 +1,99 @@ +#ifndef ALIALGSENS_H +#define ALIALGSENS_H + +#include "AliAlgVol.h" +#include + +class AliTrackPointArray; +class AliESDtrack; +class AliAlgDet; +class AliAlgPoint; +class TObjArray; +class AliExternalTrackParam; +class AliAlgDOFStat; +class TCloneArray; + +/*-------------------------------------------------------- + End-chain alignment volume in detector branch, where the actual measurement is done. + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + + +class AliAlgSens : public AliAlgVol +{ + public: + // + AliAlgSens(const char* name=0, Int_t vid=0, Int_t iid=0); + virtual ~AliAlgSens(); + // + virtual void AddChild(AliAlgVol*); + // + void SetDetector(AliAlgDet* det) {fDet = det;} + AliAlgDet* GetDetector() const {return fDet;} + // + Int_t GetSID() const {return fSID;} + void SetSID(int s) {fSID = s;} + // + void IncrementStat() {fNProcPoints++;} + // + // derivatives calculation + virtual void DPosTraDParCalib(const AliAlgPoint* pnt,double* deriv,int calibID,const AliAlgVol* parent=0) const; + virtual void DPosTraDParGeom(const AliAlgPoint* pnt, double* deriv,const AliAlgVol* parent=0) const; + // + virtual void DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv) const; + virtual void DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv) const; + virtual void DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const; + virtual void DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const; + // + void GetModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const Double_t *delta) const; + void GetModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const Double_t *delta) const; + // + virtual void ApplyAlignmentFromMPSol(); + // + void SetAddError(double y, double z) {fAddError[0]=y;fAddError[1]=z;} + const Double_t* GetAddError() const {return fAddError;} + // + virtual void PrepareMatrixT2L(); + // + virtual void SetTrackingFrame(); + virtual Bool_t IsSensor() const {return kTRUE;} + virtual void Print(const Option_t *opt="") const; + // + virtual void UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const; + virtual void UpdateL2GRecoMatrices(const TClonesArray* algArr,const TGeoHMatrix* cumulDelta); + // + virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t) = 0; + // + virtual Int_t FinalizeStat(AliAlgDOFStat* h=0); + // + virtual void PrepareMatrixClAlg(); + virtual void PrepareMatrixClAlgReco(); + const TGeoHMatrix& GetMatrixClAlg() const {return fMatClAlg;} + const TGeoHMatrix& GetMatrixClAlgReco() const {return fMatClAlgReco;} + void SetMatrixClAlg(const TGeoHMatrix& m) {fMatClAlg = m;} + void SetMatrixClAlgReco(const TGeoHMatrix& m) {fMatClAlgReco = m;} + // + protected: + // + virtual Bool_t IsSortable() const {return kTRUE;} + virtual Int_t Compare(const TObject* a) const; + // + // --------- dummies ----------- + AliAlgSens(const AliAlgSens&); + AliAlgSens& operator=(const AliAlgSens&); + // + protected: + // + Int_t fSID; // sensor id in detector + Double_t fAddError[2]; // additional error increment for measurement + AliAlgDet* fDet; // pointer on detector + TGeoHMatrix fMatClAlg; // reference cluster alignment matrix in tracking frame + TGeoHMatrix fMatClAlgReco; // reco-time cluster alignment matrix in tracking frame + + // + ClassDef(AliAlgSens,1) +}; + + +#endif diff --git a/Detectors/Align/AliAlgSensHMPID.cxx b/Detectors/Align/AliAlgSensHMPID.cxx new file mode 100644 index 0000000000000..e49439c3d7d49 --- /dev/null +++ b/Detectors/Align/AliAlgSensHMPID.cxx @@ -0,0 +1,150 @@ +/************************************************************************** + * 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. * + **************************************************************************/ + +#include "AliAlgSensHMPID.h" +#include "AliAlgAux.h" +#include "AliLog.h" +#include "AliTrackPointArray.h" +#include "AliESDtrack.h" +#include "AliAlgPoint.h" +#include "AliAlgDet.h" + +ClassImp(AliAlgSensHMPID) + +using namespace AliAlgAux; +using namespace TMath; + +//_________________________________________________________ +AliAlgSensHMPID::AliAlgSensHMPID(const char* name,Int_t vid, Int_t iid, Int_t isec) + :AliAlgSens(name,vid,iid) +{ + // def c-tor +} + +//_________________________________________________________ +AliAlgSensHMPID::~AliAlgSensHMPID() +{ + // d-tor +} +/* +//__________________________________________________________________ +void AliAlgSensHMPID::SetTrackingFrame() +{ + // define tracking frame of the sensor: just rotation by sector angle + fAlp = Sector2Alpha(fSector); + fX = 0; +} +*/ + +//____________________________________________ +void AliAlgSensHMPID::PrepareMatrixT2L() +{ + // creat T2L matrix + double loc[3]={0,0,0},glo[3]; + GetMatrixL2GIdeal().LocalToMaster(loc,glo); + double alp = ATan2(glo[1],glo[0]); + double x = Sqrt(glo[0]*glo[0]+glo[1]*glo[1]); + TGeoHMatrix t2l; + t2l.SetDx(x); + t2l.RotateZ(alp*RadToDeg()); + const TGeoHMatrix& l2gi = GetMatrixL2GIdeal().Inverse(); + t2l.MultiplyLeft(&l2gi); + /* + const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(GetVolID()); + if (!t2l) { + Print("long"); + AliFatalF("Failed to find T2L matrix for VID:%d %s",GetVolID(),GetSymName()); + } + */ + SetMatrixT2L(t2l); + // +} + +//____________________________________________ +AliAlgPoint* AliAlgSensHMPID::TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack*) +{ + // convert the pntId-th point to AliAlgPoint + // + AliAlgDet* det = GetDetector(); + AliAlgPoint* pnt = det->GetPointFromPool(); + pnt->SetSensor(this); + // + double tra[3],locId[3],loc[3], + glo[3] = {trpArr->GetX()[pntId], trpArr->GetY()[pntId], trpArr->GetZ()[pntId]}; + const TGeoHMatrix& matL2Grec = GetMatrixL2GReco(); // local to global matrix used for reconstruction + const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation + // + // undo reco-time alignment + matL2Grec.MasterToLocal(glo,locId); // go to local frame using reco-time matrix, here we recover ideal measurement + // + GetMatrixClAlg().LocalToMaster(locId,loc); // apply alignment + // + matT2L.MasterToLocal(loc,tra); // go to tracking frame + // + /* + double gloT[3]; + TGeoHMatrix t2g; + GetMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); + printf("\n%5d %s\n",GetVolID(), GetSymName()); + printf("GloOR: %+.4e %+.4e %+.4e\n",glo[0],glo[1],glo[2]); + printf("LocID: %+.4e %+.4e %+.4e\n",locId[0],locId[1],locId[2]); + printf("LocML: %+.4e %+.4e %+.4e\n",loc[0],loc[1],loc[2]); + printf("Tra : %+.4e %+.4e %+.4e\n",tra[0],tra[1],tra[2]); + printf("GloTR: %+.4e %+.4e %+.4e\n",gloT[0],gloT[1],gloT[2]); + */ + // + if (!det->GetUseErrorParam()) { + // convert error + TGeoHMatrix hcov; + Double_t hcovel[9]; + const Float_t *pntcov = trpArr->GetCov()+pntId*6; // 6 elements per error matrix + hcovel[0] = double(pntcov[0]); + hcovel[1] = double(pntcov[1]); + hcovel[2] = double(pntcov[2]); + hcovel[3] = double(pntcov[1]); + hcovel[4] = double(pntcov[3]); + hcovel[5] = double(pntcov[4]); + hcovel[6] = double(pntcov[2]); + hcovel[7] = double(pntcov[4]); + hcovel[8] = double(pntcov[5]); + hcov.SetRotation(hcovel); + hcov.Multiply(&matL2Grec); + const TGeoHMatrix& l2gi = matL2Grec.Inverse(); + hcov.MultiplyLeft(&l2gi); // errors in local frame + hcov.Multiply(&matT2L); + const TGeoHMatrix& t2li = matT2L.Inverse(); + hcov.MultiplyLeft(&t2li); // errors in tracking frame + // + Double_t *hcovscl = hcov.GetRotationMatrix(); + const double *sysE = GetAddError(); // additional syst error + pnt->SetYZErrTracking(hcovscl[4]+sysE[0]*sysE[0],hcovscl[5],hcovscl[8]+sysE[1]*sysE[1]); + } + else { // errors will be calculated just before using the point in the fit, using track info + pnt->SetYZErrTracking(0,0,0); + pnt->SetNeedUpdateFromTrack(); + } + pnt->SetXYZTracking(tra[0],tra[1],tra[2]); + pnt->SetAlphaSens(GetAlpTracking()); + pnt->SetXSens(GetXTracking()); + pnt->SetDetID(det->GetDetID()); + pnt->SetSID(GetSID()); + // + pnt->SetContainsMeasurement(); + // + pnt->Init(); + // + return pnt; + // +} diff --git a/Detectors/Align/AliAlgSensHMPID.h b/Detectors/Align/AliAlgSensHMPID.h new file mode 100644 index 0000000000000..b562465da0d90 --- /dev/null +++ b/Detectors/Align/AliAlgSensHMPID.h @@ -0,0 +1,36 @@ +#ifndef ALIALGSENSHMPID_H +#define ALIALGSENSHMPID_H + +#include "AliAlgSens.h" + + +class TObjArray; +class AliTrackPointArray; +class AliESDtrack; +class AliAlgPoint; + + +/*-------------------------------------------------------- + HMPID sensor (chamber) + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + + +class AliAlgSensHMPID : public AliAlgSens +{ + public: + AliAlgSensHMPID(const char* name=0, Int_t vid=0, Int_t iid=0, Int_t isec=0); + virtual ~AliAlgSensHMPID(); + // + virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); + // virtual void SetTrackingFrame(); + virtual void PrepareMatrixT2L(); + // + protected: + // + ClassDef(AliAlgSensHMPID,1) +}; + + +#endif diff --git a/Detectors/Align/AliAlgSensITS.cxx b/Detectors/Align/AliAlgSensITS.cxx new file mode 100644 index 0000000000000..afeb08e3dc492 --- /dev/null +++ b/Detectors/Align/AliAlgSensITS.cxx @@ -0,0 +1,131 @@ +/************************************************************************** + * 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. * + **************************************************************************/ + +#include "AliAlgSensITS.h" +#include "AliAlgAux.h" +#include "AliLog.h" +#include "AliTrackPointArray.h" +#include "AliESDtrack.h" +#include "AliAlgPoint.h" +#include "AliAlgDet.h" + +ClassImp(AliAlgSensITS) + +using namespace AliAlgAux; +using namespace TMath; + +//_________________________________________________________ +AliAlgSensITS::AliAlgSensITS(const char* name,Int_t vid, Int_t iid) + : AliAlgSens(name,vid,iid) +{ + // def c-tor +} + +//_________________________________________________________ +AliAlgSensITS::~AliAlgSensITS() +{ + // d-tor +} +/* +//__________________________________________________________________ +void AliAlgSensITS::SetTrackingFrame() +{ + // define tracking frame of the sensor + double tra[3]={0},loc[3],glo[3]; + // ITS defines tracking frame with origin in sensor, others at 0 + GetMatrixT2L().LocalToMaster(tra,loc); + GetMatrixL2GIdeal().LocalToMaster(loc,glo); + fX = Sqrt(glo[0]*glo[0]+glo[1]*glo[1]); + fAlp = ATan2(glo[1],glo[0]); + AliAlgAux::BringToPiPM(fAlp); +} +*/ + +//____________________________________________ +AliAlgPoint* AliAlgSensITS::TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack*) +{ + // convert the pntId-th point to AliAlgPoint + // + AliAlgDet* det = GetDetector(); + AliAlgPoint* pnt = det->GetPointFromPool(); + pnt->SetSensor(this); + // + double tra[3],locId[3],loc[3], + glo[3] = {trpArr->GetX()[pntId], trpArr->GetY()[pntId], trpArr->GetZ()[pntId]}; + const TGeoHMatrix& matL2Grec = GetMatrixL2GReco(); // local to global matrix used for reconstruction + const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation + // + // undo reco-time alignment + matL2Grec.MasterToLocal(glo,locId); // go to local frame using reco-time matrix, here we recover ideal measurement + // + GetMatrixClAlg().LocalToMaster(locId,loc); // apply alignment + // + matT2L.MasterToLocal(loc,tra); // go to tracking frame + // + /* + double gloT[3]; + TGeoHMatrix t2g; + GetMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); + printf("\n%5d %s\n",GetVolID(), GetSymName()); + printf("GloOR: %+.4e %+.4e %+.4e\n",glo[0],glo[1],glo[2]); + printf("LocID: %+.4e %+.4e %+.4e\n",locId[0],locId[1],locId[2]); + printf("LocML: %+.4e %+.4e %+.4e\n",loc[0],loc[1],loc[2]); + printf("Tra : %+.4e %+.4e %+.4e\n",tra[0],tra[1],tra[2]); + printf("GloTR: %+.4e %+.4e %+.4e\n",gloT[0],gloT[1],gloT[2]); + */ + // + if (!det->GetUseErrorParam()) { + // convert error + TGeoHMatrix hcov; + Double_t hcovel[9]; + const Float_t *pntcov = trpArr->GetCov()+pntId*6; // 6 elements per error matrix + hcovel[0] = double(pntcov[0]); + hcovel[1] = double(pntcov[1]); + hcovel[2] = double(pntcov[2]); + hcovel[3] = double(pntcov[1]); + hcovel[4] = double(pntcov[3]); + hcovel[5] = double(pntcov[4]); + hcovel[6] = double(pntcov[2]); + hcovel[7] = double(pntcov[4]); + hcovel[8] = double(pntcov[5]); + hcov.SetRotation(hcovel); + hcov.Multiply(&matL2Grec); + const TGeoHMatrix& l2gi = matL2Grec.Inverse(); + hcov.MultiplyLeft(&l2gi); // errors in local frame + hcov.Multiply(&matT2L); + const TGeoHMatrix& t2li = matT2L.Inverse(); + hcov.MultiplyLeft(&t2li); // errors in tracking frame + // + Double_t *hcovscl = hcov.GetRotationMatrix(); + const double *sysE = GetAddError(); // additional syst error + pnt->SetYZErrTracking(hcovscl[4]+sysE[0]*sysE[0],hcovscl[5],hcovscl[8]+sysE[1]*sysE[1]); + } + else { // errors will be calculated just before using the point in the fit, using track info + pnt->SetYZErrTracking(0,0,0); + pnt->SetNeedUpdateFromTrack(); + } + pnt->SetXYZTracking(tra[0],tra[1],tra[2]); + pnt->SetAlphaSens(GetAlpTracking()); + pnt->SetXSens(GetXTracking()); + pnt->SetDetID(det->GetDetID()); + pnt->SetSID(GetSID()); + // + pnt->SetContainsMeasurement(); + // + pnt->Init(); + // + return pnt; + // +} diff --git a/Detectors/Align/AliAlgSensITS.h b/Detectors/Align/AliAlgSensITS.h new file mode 100644 index 0000000000000..0ee39e37e163b --- /dev/null +++ b/Detectors/Align/AliAlgSensITS.h @@ -0,0 +1,36 @@ +#ifndef ALIALGSENSITS_H +#define ALIALGSENSITS_H + +#include "AliAlgSens.h" + + +class TObjArray; +class AliTrackPointArray; +class AliESDtrack; +class AliAlgPoint; + + +/*-------------------------------------------------------- + ITS sensor + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + + +class AliAlgSensITS : public AliAlgSens +{ + public: + AliAlgSensITS(const char* name=0, Int_t vid=0, Int_t iid=0); + virtual ~AliAlgSensITS(); + // + virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); + + // virtual void SetTrackingFrame(); + // + protected: + // + ClassDef(AliAlgSensITS,1) +}; + + +#endif diff --git a/Detectors/Align/AliAlgSensTOF.cxx b/Detectors/Align/AliAlgSensTOF.cxx new file mode 100644 index 0000000000000..07113440c9844 --- /dev/null +++ b/Detectors/Align/AliAlgSensTOF.cxx @@ -0,0 +1,176 @@ +/************************************************************************** + * 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. * + **************************************************************************/ + +#include "AliAlgSensTOF.h" +#include "AliAlgAux.h" +#include "AliAlgDetTOF.h" +#include "AliLog.h" +#include "AliAlgPoint.h" +#include "AliTrackPointArray.h" +#include "AliESDtrack.h" + +ClassImp(AliAlgSensTOF) + +using namespace AliAlgAux; +using namespace TMath; + +//_________________________________________________________ +AliAlgSensTOF::AliAlgSensTOF(const char* name,Int_t vid, Int_t iid, Int_t isec) + :AliAlgSens(name,vid,iid) + ,fSector(isec) +{ + // def c-tor +} + +//_________________________________________________________ +AliAlgSensTOF::~AliAlgSensTOF() +{ + // d-tor +} + +/* +//__________________________________________________________________ +void AliAlgSensTOF::SetTrackingFrame() +{ + // define tracking frame of the sensor: just rotation by sector angle + fAlp = Sector2Alpha(fSector); + fX = 0; +} +*/ + +//____________________________________________ +void AliAlgSensTOF::PrepareMatrixT2L() +{ + // extract from geometry T2L matrix + double alp = Sector2Alpha(fSector); + double loc[3]={0,0,0},glo[3]; + GetMatrixL2GIdeal().LocalToMaster(loc,glo); + double x = Sqrt(glo[0]*glo[0]+glo[1]*glo[1]); + TGeoHMatrix t2l; + t2l.SetDx(x); + t2l.RotateZ(alp*RadToDeg()); + const TGeoHMatrix& l2gi = GetMatrixL2GIdeal().Inverse(); + t2l.MultiplyLeft(&l2gi); + /* + const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(GetVolID()); + if (!t2l) { + Print("long"); + AliFatalF("Failed to find T2L matrix for VID:%d %s",GetVolID(),GetSymName()); + } + */ + SetMatrixT2L(t2l); + // +} + +//____________________________________________ +AliAlgPoint* AliAlgSensTOF::TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* tr) +{ + // convert the pntId-th point to AliAlgPoint, detectors may override this method + // + // TOF stores in the trackpoints X,Y with alignment applied but Z w/o alignment!!! + // -> need special treatment unless data are already corrected + // + AliAlgDetTOF* det = (AliAlgDetTOF*)GetDetector(); + AliAlgPoint* pnt = det->GetPointFromPool(); + pnt->SetSensor(this); + // + double tra[3],locId[3],loc[3],traId[3], + glo[3] = {trpArr->GetX()[pntId], trpArr->GetY()[pntId], trpArr->GetZ()[pntId]}; + const TGeoHMatrix& matL2Grec = GetMatrixL2GReco(); // local to global matrix used for reconstruction + const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation + // + // >>>------------- here we fix the z by emulating Misalign action in the tracking frame ------>>> + if (!trpArr->TestBit(AliTrackPointArray::kTOFBugFixed)) { + // + // we need reco-time alignment matrix in tracking frame, T^-1 * delta * T, where delta is local alignment matrix + TGeoHMatrix mClAlgTrec = GetMatrixClAlgReco(); + mClAlgTrec.Multiply(&GetMatrixT2L()); + const TGeoHMatrix& t2li = GetMatrixT2L().Inverse(); + mClAlgTrec.MultiplyLeft(&t2li); + TGeoHMatrix mT2G; + GetMatrixT2G(mT2G); + mT2G.MasterToLocal(glo,tra); // we are in tracking frame, with original wrong alignment + mClAlgTrec.MasterToLocal(tra,traId); // here we have almost ideal X,Y and wrong Z + const double *trans = mClAlgTrec.GetTranslation(); + const double *rotmt = mClAlgTrec.GetRotationMatrix(); + tra[2] = trans[2] + traId[0]*rotmt[6]+traId[1]*rotmt[7]+tra[2]*rotmt[8]; //we got misaligned Z + mT2G.LocalToMaster(tra,glo); + // + } + // now continue as usual + // <<<------------- here we fix the z by emulating Misalign action in the tracking frame ------<<< + // + // undo reco-time alignment + matL2Grec.MasterToLocal(glo,locId); // go to local frame using reco-time matrix, here we recover ideal measurement + // + GetMatrixClAlg().LocalToMaster(locId,loc); // apply alignment + // + matT2L.MasterToLocal(loc,tra); // go to tracking frame + // + /* + double gloT[3]; + TGeoHMatrix t2g; + GetMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); + printf("\n%5d %s\n",GetVolID(), GetSymName()); + printf("GloOR: %+.4e %+.4e %+.4e\n",glo[0],glo[1],glo[2]); + printf("LocID: %+.4e %+.4e %+.4e\n",locId[0],locId[1],locId[2]); + printf("LocML: %+.4e %+.4e %+.4e\n",loc[0],loc[1],loc[2]); + printf("Tra : %+.4e %+.4e %+.4e\n",tra[0],tra[1],tra[2]); + printf("GloTR: %+.4e %+.4e %+.4e\n",gloT[0],gloT[1],gloT[2]); + */ + // + if (!det->GetUseErrorParam()) { + // convert error + TGeoHMatrix hcov; + Double_t hcovel[9]; + const Float_t *pntcov = trpArr->GetCov()+pntId*6; // 6 elements per error matrix + hcovel[0] = double(pntcov[0]); + hcovel[1] = double(pntcov[1]); + hcovel[2] = double(pntcov[2]); + hcovel[3] = double(pntcov[1]); + hcovel[4] = double(pntcov[3]); + hcovel[5] = double(pntcov[4]); + hcovel[6] = double(pntcov[2]); + hcovel[7] = double(pntcov[4]); + hcovel[8] = double(pntcov[5]); + hcov.SetRotation(hcovel); + hcov.Multiply(&matL2Grec); + const TGeoHMatrix& l2gi = matL2Grec.Inverse(); + hcov.MultiplyLeft(&l2gi); // errors in local frame + hcov.Multiply(&matT2L); + const TGeoHMatrix& t2li = matT2L.Inverse(); + hcov.MultiplyLeft(&t2li); // errors in tracking frame + // + Double_t *hcovscl = hcov.GetRotationMatrix(); + const double *sysE = GetAddError(); // additional syst error + pnt->SetYZErrTracking(hcovscl[4]+sysE[0]*sysE[0],hcovscl[5],hcovscl[8]+sysE[1]*sysE[1]); + } + else { // errors will be calculated just before using the point in the fit, using track info + pnt->SetYZErrTracking(0,0,0); + pnt->SetNeedUpdateFromTrack(); + } + pnt->SetXYZTracking(tra[0],tra[1],tra[2]); + pnt->SetAlphaSens(GetAlpTracking()); + pnt->SetXSens(GetXTracking()); + pnt->SetDetID(det->GetDetID()); + pnt->SetSID(GetSID()); + // + pnt->SetContainsMeasurement(); + // + pnt->Init(); + // + return pnt; + // +} diff --git a/Detectors/Align/AliAlgSensTOF.h b/Detectors/Align/AliAlgSensTOF.h new file mode 100644 index 0000000000000..fab786a58da87 --- /dev/null +++ b/Detectors/Align/AliAlgSensTOF.h @@ -0,0 +1,40 @@ +#ifndef ALIALGSENSTOF_H +#define ALIALGSENSTOF_H + +#include "AliAlgSens.h" + +class AliTrackPointArray; +class AliESDtrack; +class AliAlgPoint; +class TObjArray; + + +/*-------------------------------------------------------- + TOF sensor + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + + +class AliAlgSensTOF : public AliAlgSens +{ + public: + AliAlgSensTOF(const char* name=0, Int_t vid=0, Int_t iid=0, Int_t isec=0); + virtual ~AliAlgSensTOF(); + // + virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); + // virtual void SetTrackingFrame(); + virtual void PrepareMatrixT2L(); + // + Int_t GetSector() const {return fSector;} + void SetSector(UInt_t sc) {fSector = (UChar_t)sc;} + // + protected: + // + UChar_t fSector; // sector ID + // + ClassDef(AliAlgSensTOF,1) +}; + + +#endif diff --git a/Detectors/Align/AliAlgSensTPC.cxx b/Detectors/Align/AliAlgSensTPC.cxx new file mode 100644 index 0000000000000..e8ef91c9d2f23 --- /dev/null +++ b/Detectors/Align/AliAlgSensTPC.cxx @@ -0,0 +1,151 @@ +/************************************************************************** + * 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. * + **************************************************************************/ + +#include "AliAlgSensTPC.h" +#include "AliAlgAux.h" +#include "AliLog.h" +#include "AliTrackPointArray.h" +#include "AliESDtrack.h" +#include "AliAlgPoint.h" +#include "AliAlgDet.h" + +ClassImp(AliAlgSensTPC) + +using namespace AliAlgAux; +using namespace TMath; + +//_________________________________________________________ +AliAlgSensTPC::AliAlgSensTPC(const char* name,Int_t vid, Int_t iid, Int_t isec) + :AliAlgSens(name,vid,iid) + ,fSector(isec) +{ + // def c-tor +} + +//_________________________________________________________ +AliAlgSensTPC::~AliAlgSensTPC() +{ + // d-tor +} +/* +//__________________________________________________________________ +void AliAlgSensTPC::SetTrackingFrame() +{ + // define tracking frame of the sensor: just rotation by sector angle + fAlp = Sector2Alpha(fSector); + fX = 0; +} +*/ + +//____________________________________________ +void AliAlgSensTPC::PrepareMatrixT2L() +{ + // extract from geometry T2L matrix + double alp = Sector2Alpha(fSector); + double loc[3]={0,0,0},glo[3]; + GetMatrixL2GIdeal().LocalToMaster(loc,glo); + double x = Sqrt(glo[0]*glo[0]+glo[1]*glo[1]); + TGeoHMatrix t2l; + t2l.SetDx(x); + t2l.RotateZ(alp*RadToDeg()); + const TGeoHMatrix& l2gi = GetMatrixL2GIdeal().Inverse(); + t2l.MultiplyLeft(&l2gi); + /* + const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(GetVolID()); + if (!t2l) { + Print("long"); + AliFatalF("Failed to find T2L matrix for VID:%d %s",GetVolID(),GetSymName()); + } + */ + SetMatrixT2L(t2l); + // +} + +//____________________________________________ +AliAlgPoint* AliAlgSensTPC::TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack*) +{ + // convert the pntId-th point to AliAlgPoint + // + AliAlgDet* det = GetDetector(); + AliAlgPoint* pnt = det->GetPointFromPool(); + pnt->SetSensor(this); + // + double tra[3],locId[3],loc[3], + glo[3] = {trpArr->GetX()[pntId], trpArr->GetY()[pntId], trpArr->GetZ()[pntId]}; + const TGeoHMatrix& matL2Grec = GetMatrixL2GReco(); // local to global matrix used for reconstruction + const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation + // + // undo reco-time alignment + matL2Grec.MasterToLocal(glo,locId); // go to local frame using reco-time matrix, here we recover ideal measurement + // + GetMatrixClAlg().LocalToMaster(locId,loc); // apply alignment + // + matT2L.MasterToLocal(loc,tra); // go to tracking frame + // + /* + double gloT[3]; + TGeoHMatrix t2g; + GetMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); + printf("\n%5d %s\n",GetVolID(), GetSymName()); + printf("GloOR: %+.4e %+.4e %+.4e\n",glo[0],glo[1],glo[2]); + printf("LocID: %+.4e %+.4e %+.4e\n",locId[0],locId[1],locId[2]); + printf("LocML: %+.4e %+.4e %+.4e\n",loc[0],loc[1],loc[2]); + printf("Tra : %+.4e %+.4e %+.4e\n",tra[0],tra[1],tra[2]); + printf("GloTR: %+.4e %+.4e %+.4e\n",gloT[0],gloT[1],gloT[2]); + */ + // + if (!det->GetUseErrorParam()) { + // convert error + TGeoHMatrix hcov; + Double_t hcovel[9]; + const Float_t *pntcov = trpArr->GetCov()+pntId*6; // 6 elements per error matrix + hcovel[0] = double(pntcov[0]); + hcovel[1] = double(pntcov[1]); + hcovel[2] = double(pntcov[2]); + hcovel[3] = double(pntcov[1]); + hcovel[4] = double(pntcov[3]); + hcovel[5] = double(pntcov[4]); + hcovel[6] = double(pntcov[2]); + hcovel[7] = double(pntcov[4]); + hcovel[8] = double(pntcov[5]); + hcov.SetRotation(hcovel); + hcov.Multiply(&matL2Grec); + const TGeoHMatrix& l2gi = matL2Grec.Inverse(); + hcov.MultiplyLeft(&l2gi); // errors in local frame + hcov.Multiply(&matT2L); + const TGeoHMatrix& t2li = matT2L.Inverse(); + hcov.MultiplyLeft(&t2li); // errors in tracking frame + // + Double_t *hcovscl = hcov.GetRotationMatrix(); + const double *sysE = GetAddError(); // additional syst error + pnt->SetYZErrTracking(hcovscl[4]+sysE[0]*sysE[0],hcovscl[5],hcovscl[8]+sysE[1]*sysE[1]); + } + else { // errors will be calculated just before using the point in the fit, using track info + pnt->SetYZErrTracking(0,0,0); + pnt->SetNeedUpdateFromTrack(); + } + pnt->SetXYZTracking(tra[0],tra[1],tra[2]); + pnt->SetAlphaSens(GetAlpTracking()); + pnt->SetXSens(GetXTracking()); + pnt->SetDetID(det->GetDetID()); + pnt->SetSID(GetSID()); + // + pnt->SetContainsMeasurement(); + // + pnt->Init(); + // + return pnt; + // +} diff --git a/Detectors/Align/AliAlgSensTPC.h b/Detectors/Align/AliAlgSensTPC.h new file mode 100644 index 0000000000000..ef8822ad61d13 --- /dev/null +++ b/Detectors/Align/AliAlgSensTPC.h @@ -0,0 +1,41 @@ +#ifndef ALIALGSENSTPC_H +#define ALIALGSENSTPC_H + +#include "AliAlgSens.h" + + +class TObjArray; +class AliTrackPointArray; +class AliESDtrack; +class AliAlgPoint; + + +/*-------------------------------------------------------- + TPC sensor (chamber) + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + + +class AliAlgSensTPC : public AliAlgSens +{ + public: + AliAlgSensTPC(const char* name=0, Int_t vid=0, Int_t iid=0, Int_t isec=0); + virtual ~AliAlgSensTPC(); + // + Int_t GetSector() const {return fSector;} + void SetSector(UInt_t sc) {fSector = (UChar_t)sc;} + // + virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); + // virtual void SetTrackingFrame(); + virtual void PrepareMatrixT2L(); + // + protected: + // + UChar_t fSector; // sector ID + + ClassDef(AliAlgSensTPC,1) +}; + + +#endif diff --git a/Detectors/Align/AliAlgSensTRD.cxx b/Detectors/Align/AliAlgSensTRD.cxx new file mode 100644 index 0000000000000..80764315d974a --- /dev/null +++ b/Detectors/Align/AliAlgSensTRD.cxx @@ -0,0 +1,225 @@ +/************************************************************************** + * 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. * + **************************************************************************/ + +#include "AliAlgSensTRD.h" +#include "AliTRDgeometry.h" +#include "AliAlgDetTRD.h" +#include "AliAlgAux.h" +#include "AliLog.h" +#include "AliAlgPoint.h" +#include "AliTrackPointArray.h" +#include "AliESDtrack.h" +#include "AliTrackerBase.h" + +ClassImp(AliAlgSensTRD) + +using namespace AliAlgAux; +using namespace TMath; + +//_________________________________________________________ +AliAlgSensTRD::AliAlgSensTRD(const char* name,Int_t vid, Int_t iid, Int_t isec) + :AliAlgSens(name,vid,iid) + ,fSector(isec) +{ + // def c-tor +} + +//_________________________________________________________ +AliAlgSensTRD::~AliAlgSensTRD() +{ + // d-tor +} +/* +//__________________________________________________________________ +void AliAlgSensTRD::SetTrackingFrame() +{ + // define tracking frame of the sensor: just rotation by sector angle + fAlp = Sector2Alpha(fSector); + fX = 0; +} +*/ + +//____________________________________________ +void AliAlgSensTRD::PrepareMatrixT2L() +{ + // extract from geometry T2L matrix + double alp = Sector2Alpha(fSector); + double loc[3]={0,0,0},glo[3]; + GetMatrixL2GIdeal().LocalToMaster(loc,glo); + double x = Sqrt(glo[0]*glo[0]+glo[1]*glo[1]); + TGeoHMatrix t2l; + t2l.SetDx(x); + t2l.RotateZ(alp*RadToDeg()); + const TGeoHMatrix& l2gi = GetMatrixL2GIdeal().Inverse(); + t2l.MultiplyLeft(&l2gi); + /* + const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(GetVolID()); + if (!t2l) { + Print("long"); + AliFatalF("Failed to find T2L matrix for VID:%d %s",GetVolID(),GetSymName()); + } + */ + SetMatrixT2L(t2l); + // +} + +//____________________________________________ +void AliAlgSensTRD::DPosTraDParCalib(const AliAlgPoint* pnt,double* deriv,int calibID,const AliAlgVol* parent) const +{ + // calculate point position X,Y,Z derivatives wrt calibration parameter calibID of given parent + // parent=0 means top detector object calibration + // + deriv[0]=deriv[1]=deriv[2]=0; + // + if (!parent) { // TRD detector global calibration + // + switch (calibID) { + case AliAlgDetTRD::kCalibNRCCorrDzDtgl: + { // correction for Non-Crossing tracklets Z,Y shift: Z -> Z + calib*tgl, Y -> Y + calib*tgl*tilt*sign(tilt); + double sgYZ = pnt->GetYZErrTracking()[1]; // makes sense only for nonRC tracklets + if (Abs(sgYZ)>0.01) { + const double kTilt = 2.*TMath::DegToRad(); + deriv[2] = pnt->GetTrParamWSA()[AliAlgPoint::kParTgl]; + deriv[1] = deriv[2]*Sign(kTilt,sgYZ); + } + break; + } + // + case AliAlgDetTRD::kCalibDVT: + { // correction for bias in VdriftT + // error in VdriftT equivalent to shift in X at which Y measurement is evaluated + // Y -> Y + dVdriftT * tg_phi, where tg_phi is the slope of the track in YX plane + double snp=pnt->GetTrParamWSA(AliAlgPoint::kParSnp),slpY=snp/Sqrt((1-snp)*(1+snp)); + deriv[1] = slpY; + break; + } + + default: break; + }; + } + // +} + +//____________________________________________ +AliAlgPoint* AliAlgSensTRD::TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* tr) +{ + // convert the pntId-th point to AliAlgPoint + // + AliAlgDetTRD* det = (AliAlgDetTRD*)GetDetector(); + AliAlgPoint* pnt = det->GetPointFromPool(); + pnt->SetSensor(this); + // + double tra[3],locId[3],loc[3], + glo[3] = {trpArr->GetX()[pntId], trpArr->GetY()[pntId], trpArr->GetZ()[pntId]}; + const TGeoHMatrix& matL2Grec = GetMatrixL2GReco(); // local to global matrix used for reconstruction + const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation + // + // undo reco-time alignment + matL2Grec.MasterToLocal(glo,locId); // go to local frame using reco-time matrix, here we recover ideal measurement + // + GetMatrixClAlg().LocalToMaster(locId,loc); // apply alignment + // + matT2L.MasterToLocal(loc,tra); // go to tracking frame + // + /* + double gloT[3]; + TGeoHMatrix t2g; + GetMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); + printf("\n%5d %s\n",GetVolID(), GetSymName()); + printf("GloOR: %+.4e %+.4e %+.4e\n",glo[0],glo[1],glo[2]); + printf("LocID: %+.4e %+.4e %+.4e\n",locId[0],locId[1],locId[2]); + printf("LocML: %+.4e %+.4e %+.4e\n",loc[0],loc[1],loc[2]); + printf("Tra : %+.4e %+.4e %+.4e\n",tra[0],tra[1],tra[2]); + printf("GloTR: %+.4e %+.4e %+.4e\n",gloT[0],gloT[1],gloT[2]); + */ + // + if (!det->GetUseErrorParam()) { + // convert error + TGeoHMatrix hcov; + Double_t hcovel[9]; + const Float_t *pntcov = trpArr->GetCov()+pntId*6; // 6 elements per error matrix + hcovel[0] = double(pntcov[0]); + hcovel[1] = double(pntcov[1]); + hcovel[2] = double(pntcov[2]); + hcovel[3] = double(pntcov[1]); + hcovel[4] = double(pntcov[3]); + hcovel[5] = double(pntcov[4]); + hcovel[6] = double(pntcov[2]); + hcovel[7] = double(pntcov[4]); + hcovel[8] = double(pntcov[5]); + hcov.SetRotation(hcovel); + hcov.Multiply(&matL2Grec); + const TGeoHMatrix& l2gi = matL2Grec; + hcov.MultiplyLeft(&l2gi); // errors in local frame + hcov.Multiply(&matT2L); + const TGeoHMatrix& t2li = matT2L.Inverse(); + hcov.MultiplyLeft(&t2li); // errors in tracking frame + // + Double_t *hcovscl = hcov.GetRotationMatrix(); + const double *sysE = GetAddError(); // additional syst error + pnt->SetYZErrTracking(hcovscl[4]+sysE[0]*sysE[0],hcovscl[5],hcovscl[8]+sysE[1]*sysE[1]); + } + else { // errors will be calculated just before using the point in the fit, using track info + pnt->SetYZErrTracking(0,0,0); + pnt->SetNeedUpdateFromTrack(); + } + pnt->SetXYZTracking(tra[0],tra[1],tra[2]); + pnt->SetAlphaSens(GetAlpTracking()); + pnt->SetXSens(GetXTracking()); + pnt->SetDetID(det->GetDetID()); + pnt->SetSID(GetSID()); + // + pnt->SetContainsMeasurement(); + // + // Apply calibrations + // Correction for NonRC points to account for most probable Z for non-crossing + { + const double kTilt = 2.*TMath::DegToRad(); + // is it pad crrossing? + double* errYZ = (double*) pnt->GetYZErrTracking(); + double sgYZ = errYZ[1]; + if (TMath::Abs(sgYZ)<0.01) { // crossing + // increase errors since the error + const double* extraErrRC = det->GetExtraErrRC(); + errYZ[0] += extraErrRC[0]*extraErrRC[0]; + errYZ[2] += extraErrRC[1]*extraErrRC[1]; + } + else { // account for probability to not cross the row + double* pYZ = (double*)pnt->GetYZTracking(); + double corrZ = det->GetNonRCCorrDzDtglWithCal()*tr->GetTgl(); + pYZ[1] += corrZ; + pYZ[0] += corrZ*Sign(kTilt,sgYZ); // Y and Z are correlated + } + } + // + // Correction for DVT, equivalent to shift in X at which Y is evaluated: dY = tg_phi * dvt + { + double dvt = det->GetCorrDVTWithCal(); + if (Abs(dvt)>kAlmostZeroD) { + AliExternalTrackParam trc = *tr; + if (!trc.RotateParamOnly(GetAlpTracking())) return 0; + double snp = trc.GetSnpAt(pnt->GetXPoint(),AliTrackerBase::GetBz()); + if (Abs(snp)>kAlmostOneD) return 0; + double slpY = snp/Sqrt((1-snp)*(1+snp)); + double* pYZ = (double*)pnt->GetYZTracking(); + pYZ[0] += dvt*slpY; + } + } + // + pnt->Init(); + // + return pnt; + // +} diff --git a/Detectors/Align/AliAlgSensTRD.h b/Detectors/Align/AliAlgSensTRD.h new file mode 100644 index 0000000000000..d0c6d094a8416 --- /dev/null +++ b/Detectors/Align/AliAlgSensTRD.h @@ -0,0 +1,42 @@ +#ifndef ALIALGSENSTRD_H +#define ALIALGSENSTRD_H + +#include "AliAlgSens.h" +class AliTrackPointArray; +class AliESDtrack; +class AliAlgPoint; +class TObjArray; + + +/*-------------------------------------------------------- + TRD sensor + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + + +class AliAlgSensTRD : public AliAlgSens +{ + public: + AliAlgSensTRD(const char* name=0, Int_t vid=0, Int_t iid=0, Int_t isec=0); + virtual ~AliAlgSensTRD(); + // + Int_t GetSector() const {return fSector;} + void SetSector(UInt_t sc) {fSector = (UChar_t)sc;} + // + virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); + // + virtual void DPosTraDParCalib(const AliAlgPoint* pnt,double* deriv,int calibID,const AliAlgVol* parent=0) const; + // + // virtual void SetTrackingFrame(); + virtual void PrepareMatrixT2L(); + // + protected: + // + UChar_t fSector; // sector ID + + ClassDef(AliAlgSensTRD,1) +}; + + +#endif diff --git a/Detectors/Align/AliAlgSteer.cxx b/Detectors/Align/AliAlgSteer.cxx new file mode 100644 index 0000000000000..1097b8fbc3df4 --- /dev/null +++ b/Detectors/Align/AliAlgSteer.cxx @@ -0,0 +1,2052 @@ +/************************************************************************** + * 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. * + **************************************************************************/ + +#include "AliAlgSteer.h" +#include "AliLog.h" +#include "AliAlgAux.h" +#include "AliAlgPoint.h" +#include "AliAlgDet.h" +#include "AliAlgVol.h" +#include "AliAlgDetITS.h" +#include "AliAlgDetTPC.h" +#include "AliAlgDetTRD.h" +#include "AliAlgDetTOF.h" +#include "AliAlgVtx.h" +#include "AliAlgMPRecord.h" +#include "AliAlgRes.h" +#include "AliAlgResFast.h" +#include "AliAlgConstraint.h" +#include "AliAlgDOFStat.h" +#include "AliTrackerBase.h" +#include "AliESDCosmicTrack.h" +#include "AliESDtrack.h" +#include "AliESDEvent.h" +#include "AliESDVertex.h" +#include "AliRecoParam.h" +#include "AliCDBRunRange.h" +#include "AliCDBManager.h" +#include "AliCDBEntry.h" +#include "Mille.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace TMath; +using namespace AliAlgAux; +using std::ifstream; + +ClassImp(AliAlgSteer) + +const Char_t* AliAlgSteer::fgkMPDataExt = ".mille"; +const Char_t* AliAlgSteer::fgkDetectorName[AliAlgSteer::kNDetectors] = {"ITS", "TPC", "TRD", "TOF", "HMPID" }; +const Int_t AliAlgSteer::fgkSkipLayers[AliAlgSteer::kNLrSkip] = {AliGeomManager::kPHOS1,AliGeomManager::kPHOS2, + AliGeomManager::kMUON,AliGeomManager::kEMCAL}; + +const Char_t* AliAlgSteer::fgkStatClName[AliAlgSteer::kNStatCl] = {"Inp: ","Acc: "}; +const Char_t* AliAlgSteer::fgkStatName[AliAlgSteer::kMaxStat] = + {"runs","Ev.Coll", "Ev.Cosm", "Trc.Coll", "Trc.Cosm"}; + + +const Char_t* AliAlgSteer::fgkHStatName[AliAlgSteer::kNHVars] = { + "Runs","Ev.Inp","Ev.VtxOK","Tr.Inp","Tr.2Fit","Tr.2FitVC","Tr.2PrMat","Tr.2ResDer","Tr.Stored","Tr.Acc","Tr.ContRes"}; + + +//________________________________________________________________ +AliAlgSteer::AliAlgSteer(const char* configMacro, int refRun) + :fNDet(0) + ,fNDOFs(0) + ,fRunNumber(-1) + ,fFieldOn(kFALSE) + ,fTracksType(kColl) + ,fAlgTrack(0) + ,fVtxSens(0) + ,fConstraints() + ,fSelEventSpecii(AliRecoParam::kCosmic|AliRecoParam::kLowMult|AliRecoParam::kHighMult|AliRecoParam::kDefault) + ,fCosmicSelStrict(kFALSE) + ,fVtxMinCont(-1) + ,fVtxMaxCont(-1) + ,fVtxMinContVC(10) + ,fMinITSClforVC(3) + ,fITSPattforVC(AliAlgDetITS::kSPDAny) + ,fMaxChi2forVC(10) + // + ,fGloParVal(0) + ,fGloParErr(0) + ,fGloParLab(0) + ,fOrderedLbl(0) + ,fLbl2ID(0) + ,fRefPoint(0) + ,fESDTree(0) + ,fESDEvent(0) + ,fVertex(0) + ,fControlFrac(1.0) + ,fMPOutType(kMille|kMPRec|kContR) + ,fMille(0) + ,fMPRecord(0) + ,fCResid(0) + ,fMPRecTree(0) + ,fResidTree(0) + ,fMPRecFile(0) + ,fResidFile(0) + ,fMilleDBuffer() + ,fMilleIBuffer() + ,fMPDatFileName("mpData") + ,fMPParFileName("mpParams.txt") + ,fMPConFileName("mpConstraints.txt") + ,fMPSteerFileName("mpSteer.txt") + ,fResidFileName("mpControlRes.root") + ,fMilleOutBin(kTRUE) + ,fDoKalmanResid(kTRUE) + // + ,fOutCDBPath("local://outOCDB") + ,fOutCDBComment("AliAlgSteer") + ,fOutCDBResponsible("") + // + ,fDOFStat(0) + ,fHistoStat(0) + // + ,fConfMacroName(configMacro) + ,fRecoOCDBConf("configRecoOCDB.C") + ,fRefOCDBConf("configRefOCDB.C") + ,fRefRunNumber(refRun) + ,fRefOCDBLoaded(0) + ,fUseRecoOCDB(kTRUE) +{ + // def c-tor + for (int i=kNDetectors;i--;) { + fDetectors[i] = 0; + fDetPos[i] = -1; + } + SetPtMinColl(); + SetPtMinCosm(); + SetEtaMaxColl(); + SetEtaMaxCosm(); + SetMinDetAccColl(); + SetMinDetAccCosm(); + for (int i=0;iProcessLine(Form(".x %s+g((AliAlgSteer*)%p)",fConfMacroName.Data(),this)); + if (!GetInitDOFsDone()) InitDOFs(); + if (!GetNDOFs()) AliFatalF("No DOFs found, initialization with %s failed", + fConfMacroName.Data()); + } + +} + +//________________________________________________________________ +AliAlgSteer::~AliAlgSteer() +{ + // d-tor + if (fMPRecFile) CloseMPRecOutput(); + if (fMille) CloseMilleOutput(); + if (fResidFile) CloseResidOutput(); + // + delete fAlgTrack; + delete[] fGloParVal; + delete[] fGloParErr; + delete[] fGloParLab; + for (int i=0;iSetInternalID(1); + fVtxSens->PrepareMatrixL2G(); + fVtxSens->PrepareMatrixL2GIdeal(); + dofCnt += fVtxSens->GetNDOFs(); + // + for (int i=0;iInitGeom(); + if (!dofCnt) AliFatal("No DOFs found"); + // + // + for (int idt=0;idtIsDisabled()) continue; + det->CacheReferenceOCDB(); + } + // + fGloParVal = new Float_t[dofCnt]; + fGloParErr = new Float_t[dofCnt]; + fGloParLab = new Int_t[dofCnt]; + fOrderedLbl = new Int_t[dofCnt]; + fLbl2ID = new Int_t[dofCnt]; + memset(fGloParVal,0,dofCnt*sizeof(Float_t)); + memset(fGloParErr,0,dofCnt*sizeof(Float_t)); + memset(fGloParLab,0,dofCnt*sizeof(Int_t)); + memset(fOrderedLbl,0,dofCnt*sizeof(Int_t)); + memset(fLbl2ID,0,dofCnt*sizeof(Int_t)); + AssignDOFs(); + AliInfoF("Booked %d global parameters",dofCnt); + // + SetInitGeomDone(); + // +} + +//________________________________________________________________ +void AliAlgSteer::InitDOFs() +{ + // scan all free global parameters, link detectors to array of params + // + if (GetInitDOFsDone()) { + AliInfoF("InitDOFs was already done, just reassigning %d DOFs arrays/labels",fNDOFs); + AssignDOFs(); + return; + } + // + fNDOFs = 0; + int ndfAct = 0; + AssignDOFs(); + // + int nact = 0; + fVtxSens->InitDOFs(); + for (int i=0;iInitDOFs(); + if (det->IsDisabled()) continue; + nact++; + ndfAct += det->GetNDOFs(); + } + for (int i=0;i0) ndfOld = fNDOFs; + fNDOFs = 0; + // + fVtxSens->AssignDOFs(fNDOFs,fGloParVal,fGloParErr,fGloParLab); + // + for (int idt=0;idtIsDisabled()) continue; + fNDOFs += det->AssignDOFs(); + } + AliInfoF("Assigned parameters/labels arrays for %d DOFs",fNDOFs); + if (ndfOld>-1 && ndfOld != fNDOFs) AliErrorF("Recalculated NDOFs=%d not equal to saved NDOFs=%d",fNDOFs,ndfOld); + // + // build Lbl <-> parID table + Sort(fNDOFs,fGloParLab,fLbl2ID,kFALSE); // sort in increasing order + for (int i=fNDOFs;i--;) fOrderedLbl[i] = fGloParLab[fLbl2ID[i]]; + // +} + +//________________________________________________________________ +void AliAlgSteer::AddDetector(UInt_t id, AliAlgDet* det) +{ + // add detector participating in the alignment, optionally constructed externally + // + if (!fRefOCDBLoaded) LoadRefOCDB(); + // + if (id>=kNDetectors) AliFatalF("Detector typeID %d exceeds allowed range %d:%d", + id,0,kNDetectors-1); + // + if (fDetPos[id]!=-1) AliFatalF("Detector %d was already added",id); + if (!det) { + switch(id) { + case kITS: det = new AliAlgDetITS(GetDetNameByDetID(kITS)); break; + case kTPC: det = new AliAlgDetTPC(GetDetNameByDetID(kTPC)); break; + case kTRD: det = new AliAlgDetTRD(GetDetNameByDetID(kTRD)); break; + case kTOF: det = new AliAlgDetTOF(GetDetNameByDetID(kTOF)); break; + default: AliFatalF("%d not implemented yet",id); break; + }; + } + // + fDetectors[fNDet] = det; + fDetPos[id] = fNDet; + det->SetAlgSteer(this); + for (int i=0;iIsObligatory(i)); + fNDet++; + // +} + +//_________________________________________________________ +void AliAlgSteer::AddDetector(AliAlgDet* det) +{ + // add detector constructed externally to alignment framework + AddDetector(det->GetDetID(), det); +} + +//_________________________________________________________ +Bool_t AliAlgSteer::CheckDetectorPattern(UInt_t patt) const +{ + //validate detector pattern + return ((patt & fObligatoryDetPattern[fTracksType]) == + fObligatoryDetPattern[fTracksType]) && + NumberOfBitsSet(patt)>=fMinDetAcc[fTracksType]; +} + +//_________________________________________________________ +Bool_t AliAlgSteer::CheckDetectorPoints(const int* npsel) const +{ + //validate detectors pattern according to number of selected points + int ndOK = 0; + for (int idt=0;idtIsDisabled(fTracksType)) continue; + if (npsel[idt]GetNPointsSel(fTracksType)) { + if (det->IsObligatory(fTracksType)) return kFALSE; + continue; + } + ndOK++; + } + return ndOK>=fMinDetAcc[fTracksType]; +} + +//_________________________________________________________ +UInt_t AliAlgSteer::AcceptTrack(const AliESDtrack* esdTr, Bool_t strict) const +{ + // decide if the track should be processed + AliAlgDet* det = 0; + UInt_t detAcc = 0; + if (fFieldOn && esdTr->Pt()Eta())>fEtaMax[fTracksType]) return 0; + // + for (int idet=0;idetIsDisabled(fTracksType)) continue; + if (!det->AcceptTrack(esdTr,fTracksType)) { + if (strict && det->IsObligatory(fTracksType)) return 0; + else continue; + } + // + detAcc |= 0x1<GetField() || + !SmallerAbs(fESDEvent->GetMagneticField()-AliTrackerBase::GetBz(),5e-4)) ) { + fESDEvent->InitMagneticField(); + } +} + +//_________________________________________________________ +Bool_t AliAlgSteer::ProcessEvent(const AliESDEvent* esdEv) +{ + // process event + const int kProcStatFreq = 100; + static int evCount=0; + if (!(evCount%kProcStatFreq)) { + ProcInfo_t procInfo; + gSystem->GetProcInfo(&procInfo); + AliInfoF("ProcStat: CPUusr: %6d CPUsys: %6d RMem:%6d VMem:%6d", + int(procInfo.fCpuUser), int(procInfo.fCpuSys), + int(procInfo.fMemResident/1024),int(procInfo.fMemVirtual/1024)); + } + evCount++; + // + SetESDEvent(esdEv); + // + if (esdEv->GetRunNumber() != GetRunNumber()) SetRunNumber(esdEv->GetRunNumber()); + // + if (!(esdEv->GetEventSpecie()&fSelEventSpecii)) { +#if DEBUG>2 + AliInfoF("Reject: specie does not match, allowed 0x%0x",fSelEventSpecii); +#endif + return kFALSE; + } + // + SetCosmic(esdEv->GetEventSpecie()==AliRecoParam::kCosmic || + (esdEv->GetNumberOfCosmicTracks()>0 && !esdEv->GetPrimaryVertexTracks()->GetStatus())); + // + FillStatHisto( kEvInp ); + // +#if DEBUG>2 + AliInfoF("Processing event %d of ev.specie %d -> Ntr: %4d NtrCosm: %d", + esdEv->GetEventNumberInFile(),esdEv->GetEventSpecie(), + esdEv->GetNumberOfTracks(),esdEv->GetNumberOfCosmicTracks()); +#endif + // + SetFieldOn(Abs(esdEv->GetMagneticField())>kAlmost0Field); + if (!IsCosmic() && !CheckSetVertex(esdEv->GetPrimaryVertexTracks())) return kFALSE; + FillStatHisto( kEvVtx ); + // + int ntr=0,accTr = 0; + if (IsCosmic()) { + fStat[kInpStat][kEventCosm]++; + ntr = esdEv->GetNumberOfCosmicTracks(); + FillStatHisto( kTrackInp, ntr); + for (int itr=0;itrGetCosmicTrack(itr)); + } + if (accTr) fStat[kAccStat][kEventCosm]++; + } + else { + fStat[kInpStat][kEventColl]++; + ntr = esdEv->GetNumberOfTracks(); + FillStatHisto( kTrackInp, ntr); + for (int itr=0;itrGetTrack(itr)); + /* + if (accTr>accTrOld && fCResid) { + int ndf = fCResid->GetNPoints()*2-5; + if (fCResid->GetChi2()/ndf>20 || !fCResid->GetKalmanDone() + || fCResid->GetChi2K()/ndf>20) { + printf("BAD FIT for %d\n",itr); + } + fCResid->Print("er"); + } + */ + } + if (accTr) fStat[kAccStat][kEventColl]++; + } + // + FillStatHisto( kTrackAcc, accTr); + // + if (accTr) { + AliInfoF("Processed event %d of ev.specie %d -> Accepted: %4d of %4d tracks", + esdEv->GetEventNumberInFile(),esdEv->GetEventSpecie(),accTr,ntr); + } + return kTRUE; +} + +//_________________________________________________________ +Bool_t AliAlgSteer::ProcessTrack(const AliESDtrack* esdTr) +{ + // process single track + // + fStat[kInpStat][kTrackColl]++; + fESDTrack[0] = esdTr; + fESDTrack[1] = 0; + // + int nPnt = 0; + const AliESDfriendTrack* trF = esdTr->GetFriendTrack(); + if (!trF) return kFALSE; + const AliTrackPointArray* trPoints = trF->GetTrackPointArray(); + if (!trPoints || (nPnt=trPoints->GetNPoints())<1) return kFALSE; + // + UInt_t detAcc = AcceptTrack(esdTr); + if (!detAcc) return kFALSE; + // + ResetDetectors(); + fAlgTrack->Clear(); + // + // process the track points for each detector, + AliAlgDet* det = 0; + for (int idet=0;idetProcessPoints(esdTr, fAlgTrack) < det->GetNPointsSel(kColl)) { + detAcc &= ~(0x1<IsObligatory(kColl)) return kFALSE; + } + if (NumberOfBitsSet(detAcc)GetNPoints()SetContainsMeasurement(kFALSE); + fRefPoint->SetContainsMaterial(kFALSE); + fAlgTrack->AddPoint(fRefPoint); // reference point which the track will refer to + // + fAlgTrack->CopyFrom(esdTr); + if (!GetFieldOn()) fAlgTrack->ImposePtBOff(fDefPtBOff[AliAlgAux::kColl]); + fAlgTrack->SetFieldON( GetFieldOn() ); + fAlgTrack->SortPoints(); + // + // at this stage the points are sorted from maxX to minX, the latter corresponding to + // reference point (e.g. vertex) with X~0. The fAlgTrack->GetInnerPointID() points on it, + // hence fAlgTrack->GetInnerPointID() is the 1st really measured point. We will set the + // alpha of the reference point to alpha of the barrel sector corresponding to this + // 1st measured point + int pntMeas = fAlgTrack->GetInnerPointID()-1; + if (pntMeas<0) { // this should not happen + fAlgTrack->Print("p meas"); + AliFatal("AliAlgTrack->GetInnerPointID() cannot be 0"); + } + // do we want to add the vertex as a measured point ? + if (!AddVertexConstraint()) { // no constrain, just reference point w/o measurement + fRefPoint->SetXYZTracking(0,0,0); + fRefPoint->SetAlphaSens(Sector2Alpha(fAlgTrack->GetPoint(pntMeas)->GetAliceSector())); + } + else FillStatHisto( kTrackFitInpVC ); + // + FillStatHisto( kTrackFitInp ); + if (!fAlgTrack->IniFit()) return kFALSE; + FillStatHisto( kTrackProcMatInp ); + if (!fAlgTrack->ProcessMaterials()) return kFALSE; + fAlgTrack->DefineDOFs(); + // + FillStatHisto( kTrackResDerInp ); + if (!fAlgTrack->CalcResidDeriv()) return kFALSE; + // + if (!StoreProcessedTrack( fMPOutType&~kContR )) return kFALSE; // store derivatives for MP + // + if (GetProduceControlRes() && // need control residuals, ignore selection fraction if this is the + (fMPOutType==kContR || gRandom->Rndm()GetNContributors(); + if (fVtxMinCont>0 && fVtxMinCont>ncont) { +#if DEBUG>2 + AliInfoF("Rejecting event with %d vertex contributors (min %d asked)",ncont,fVtxMinCont); +#endif + return kFALSE; + } + if (fVtxMaxCont>0 && ncont>fVtxMaxCont) { +#if DEBUG>2 + AliInfoF("Rejecting event with %d vertex contributors (max %d asked)",ncont,fVtxMaxCont); +#endif + return kFALSE; + } + fVertex = (ncont>=fVtxMinContVC) ? vtx : 0; // use vertex as a constraint + return kTRUE; +} + +//_________________________________________________________ +Bool_t AliAlgSteer::ProcessTrack(const AliESDCosmicTrack* cosmTr) +{ + // process single cosmic track + // + fStat[kInpStat][kTrackCosm]++; + int nPnt = 0; + fESDTrack[0] = 0; + fESDTrack[1] = 0; + // + for (int leg=kNCosmLegs;leg--;) { + const AliESDtrack* esdTr = + fESDEvent->GetTrack(leg==kCosmLow ? + cosmTr->GetESDLowerTrackIndex():cosmTr->GetESDUpperTrackIndex()); + const AliESDfriendTrack* trF = esdTr->GetFriendTrack(); + if (!trF) return kFALSE; + const AliTrackPointArray* trPoints = trF->GetTrackPointArray(); + if (!trPoints || (nPnt+=trPoints->GetNPoints())<1) return kFALSE; + // + fESDTrack[leg] = esdTr; + } + // + UInt_t detAcc = AcceptTrackCosmic(fESDTrack); + if (!detAcc) return kFALSE; + // + ResetDetectors(); + fAlgTrack->Clear(); + fAlgTrack->SetCosmic(kTRUE); + // + // process the track points for each detector, + // fill needed points (tracking frame) in the fAlgTrack + fRefPoint->SetContainsMeasurement(kFALSE); + fRefPoint->SetContainsMaterial(kFALSE); + fAlgTrack->AddPoint(fRefPoint); // reference point which the track will refer to + // + AliAlgDet* det = 0; + Int_t npsel[kNDetectors] = {0}; + for (int nPleg=0,leg=kNCosmLegs;leg--;) { + for (int idet=0;idetProcessPoints(fESDTrack[leg],fAlgTrack, leg==kCosmUp); + if (npGetNPointsSel(kCosm) && fCosmicSelStrict && + det->IsObligatory(kCosm)) return kFALSE; + npsel[idet] += np; + nPleg += np; + } + if (nPlegCopyFrom(cosmTr); + if (!GetFieldOn()) fAlgTrack->ImposePtBOff(fDefPtBOff[AliAlgAux::kCosm]); + fAlgTrack->SetFieldON( GetFieldOn() ); + fAlgTrack->SortPoints(); + // + // at this stage the points are sorted from maxX to minX, the latter corresponding to + // reference point (e.g. vertex) with X~0. The fAlgTrack->GetInnerPointID() points on it, + // hence fAlgTrack->GetInnerPointID() is the 1st really measured point. We will set the + // alpha of the reference point to alpha of the barrel sector corresponding to this + // 1st measured point + int pntMeas = fAlgTrack->GetInnerPointID()-1; + if (pntMeas<0) { // this should not happen + fAlgTrack->Print("p meas"); + AliFatal("AliAlgTrack->GetInnerPointID() cannot be 0"); + } + fRefPoint->SetAlphaSens(Sector2Alpha(fAlgTrack->GetPoint(pntMeas)->GetAliceSector())); + // + FillStatHisto( kTrackFitInp ); + if (!fAlgTrack->IniFit()) return kFALSE; + // + FillStatHisto( kTrackProcMatInp ); + if (!fAlgTrack->ProcessMaterials()) return kFALSE; + fAlgTrack->DefineDOFs(); + // + FillStatHisto( kTrackResDerInp ); + if (!fAlgTrack->CalcResidDeriv()) return kFALSE; + // + if (!StoreProcessedTrack( fMPOutType&~kContR )) return kFALSE; // store derivatives for MP + // + if (GetProduceControlRes() && // need control residuals, ignore selection fraction if this is the + (fMPOutType==kContR || gRandom->Rndm()GetDerivDone()) { + AliError("Track derivatives are not yet evaluated"); + return kFALSE; + } + int np(fAlgTrack->GetNPoints()),nDGloTot(0); // total number global derivatives stored + int nParETP(fAlgTrack->GetNLocExtPar()); // numnber of local parameters for reference track param + int nVarLoc(fAlgTrack->GetNLocPar()); // number of local degrees of freedom in the track + float* buffDL(0),*buffDG(0); // faster acces arrays + int *buffI(0); + // + const int* gloParID(fAlgTrack->GetGloParID()); // IDs of global DOFs this track depends on + for (int ip=0;ipGetPoint(ip); + if (pnt->ContainsMeasurement()) { + int gloOffs = pnt->GetDGloOffs(); // 1st entry of global derivatives for this point + int nDGlo = pnt->GetNGloDOFs(); // number of global derivatives (number of DOFs it depends on) + if (!pnt->IsStatOK()) pnt->IncrementStat(); + // check buffer sizes + { + if (fMilleDBuffer.GetSize()GetDResDLoc(idim,ip); // array of Dresidual/Dparams_loc + // derivatives over reference track parameters + for (int j=0;jGetMinLocVarID(), lp1 = pnt->GetMaxLocVarID(); + for (int j=lp0;jGetDResDGlo(idim, gloOffs); + const int* gloIDP(gloParID + gloOffs); + for (int j=0;jmille(nVarLoc,buffDL, nGlo,buffDG, buffI, + fAlgTrack->GetResidual(idim,ip),Sqrt(pnt->GetErrDiag(idim))); + nDGloTot += nGlo; + // + } + } + if (pnt->ContainsMaterial()) { // material point can add 4 or 5 otrhogonal pseudo-measurements + memset(buffDL,0,nVarLoc*sizeof(float)); + int nmatpar = pnt->GetNMatPar(); // residuals (correction expectation value) + // const float* expMatCorr = pnt->GetMatCorrExp(); // expected corrections (diagonalized) + const float* expMatCov = pnt->GetMatCorrCov(); // their diagonalized error matrix + int offs = pnt->GetMaxLocVarID() - nmatpar; // start of material variables + // here all derivatives are 1 = dx/dx + for (int j=0;jmille(nVarLoc,buffDL,0,buffDG,buffI,expMatCorr[j],Sqrt(expMatCov[j])); + // expectation for MS effect is 0 + fMille->mille(nVarLoc,buffDL,0,buffDG,buffI,0,Sqrt(expMatCov[j])); + buffDL[j1] = 0.0; // reset buffer + } + } // material "measurement" + } // loop over points + // + if (!nDGloTot) { + AliInfo("Track does not depend on free global parameters, discard"); + fMille->kill(); + return kFALSE; + } + fMille->end(); // store the record + return kTRUE; +} + +//_________________________________________________________ +Bool_t AliAlgSteer::FillMPRecData() +{ + // store MP2 in MPRecord format + if (!fMPRecord) InitMPRecOutput(); + // + fMPRecord->Clear(); + if (!fMPRecord->FillTrack(fAlgTrack,fGloParLab)) return kFALSE; + fMPRecord->SetRun(fRunNumber); + fMPRecord->SetTimeStamp(fESDEvent->GetTimeStamp()); + UInt_t tID = 0xffff & UInt_t(fESDTrack[0]->GetID()); + if (IsCosmic()) tID |= (0xffff & UInt_t(fESDTrack[1]->GetID()))<<16; + fMPRecord->SetTrackID(tID); + fMPRecTree->Fill(); + return kTRUE; +} + +//_________________________________________________________ +Bool_t AliAlgSteer::FillControlData() +{ + // store control residuals + if (!fCResid) InitResidOutput(); + // + int nps,np = fAlgTrack->GetNPoints(); + nps = (!fRefPoint->ContainsMeasurement()) ? np-1 : np; // ref point is dummy? + if (nps<0) return kTRUE; + // + fCResid->Clear(); + if (!fCResid->FillTrack(fAlgTrack, fDoKalmanResid)) return kFALSE; + fCResid->SetRun(fRunNumber); + fCResid->SetTimeStamp(fESDEvent->GetTimeStamp()); + fCResid->SetBz(fESDEvent->GetMagneticField()); + UInt_t tID = 0xffff & UInt_t(fESDTrack[0]->GetID()); + if (IsCosmic()) tID |= (0xffff & UInt_t(fESDTrack[1]->GetID()))<<16; + fCResid->SetTrackID(tID); + // + fResidTree->Fill(); + FillStatHisto( kTrackControl ); + // + return kTRUE; +} + +//_________________________________________________________ +void AliAlgSteer::SetRunNumber(Int_t run) +{ + if (run==fRunNumber) return; // nothing to do + // + AcknowledgeNewRun(run); +} + +//_________________________________________________________ +void AliAlgSteer::AcknowledgeNewRun(Int_t run) +{ + // load needed info for new run + if (run==fRunNumber) return; // nothing to do + if (run>0) { + fStat[kAccStat][kRun]++; + } + if (fRunNumber>0) FillStatHisto( kRunDone ); + fRunNumber = run; + AliInfoF("Processing new run %d",fRunNumber); + // + // setup magnetic field + if (fESDEvent && + (!TGeoGlobalMagField::Instance()->GetField() || + !SmallerAbs(fESDEvent->GetMagneticField()-AliTrackerBase::GetBz(),5e-4)) ) { + fESDEvent->InitMagneticField(); + } + // + if (!fUseRecoOCDB) { + AliWarning("Reco-time OCDB will NOT be preloaded"); + return; + } + LoadRecoTimeOCDB(); + // + for (int idet=0;idetIsDisabled()) det->AcknowledgeNewRun(run); + } + // + // bring to virgin state + // CleanOCDB(); + // + // LoadRefOCDB(); //??? we need to get back reference OCDB ??? + // + fStat[kInpStat][kRun]++; + // +} + +//_________________________________________________________ +Bool_t AliAlgSteer::LoadRecoTimeOCDB() +{ + // Load OCDB paths used for the reconstruction of data being processed + // In order to avoid unnecessary uploads, the objects are not actually + // loaded/cached but just added as specific paths with version + AliInfoF("Preloading Reco-Time OCDB for run %d from ESD UserInfo list",fRunNumber); + // + CleanOCDB(); + // + if (!fRecoOCDBConf.IsNull() && !gSystem->AccessPathName(fRecoOCDBConf.Data(), kFileExists)) { + AliInfoF("Executing reco-time OCDB setup macro %s",fRecoOCDBConf.Data()); + gROOT->ProcessLine(Form(".x %s(%d)",fRecoOCDBConf.Data(),fRunNumber)); + if (AliCDBManager::Instance()->IsDefaultStorageSet()) return kTRUE; + AliFatalF("macro %s failed to configure reco-time OCDB",fRecoOCDBConf.Data()); + } + else AliWarningF("No reco-time OCDB config macro %s is found, will use ESD:UserInfo", + fRecoOCDBConf.Data()); + // + if (!fESDTree) AliFatal("Cannot preload Reco-Time OCDB since the ESD tree is not set"); + const TTree* tr = fESDTree; // go the the real ESD tree + while (tr->GetTree() && tr->GetTree()!=tr) tr = tr->GetTree(); + // + const TList* userInfo = const_cast(tr)->GetUserInfo(); + TMap* cdbMap = (TMap*)userInfo->FindObject("cdbMap"); + TList* cdbList = (TList*)userInfo->FindObject("cdbList"); + // + if (!cdbMap || !cdbList) { + userInfo->Print(); + AliFatal("Failed to extract cdbMap and cdbList from UserInfo list"); + } + // + return PreloadOCDB(fRunNumber,cdbMap,cdbList); +} + +//_________________________________________________________ +AliAlgDet* AliAlgSteer::GetDetectorByVolID(Int_t vid) const +{ + // get detector by sensor volid + for (int i=fNDet;i--;) if (fDetectors[i]->SensorOfDetector(vid)) return fDetectors[i]; + return 0; +} + +//____________________________________________ +void AliAlgSteer::Print(const Option_t *opt) const +{ + // print info + TString opts = opt; + opts.ToLower(); + printf("%5d DOFs in %d detectors",fNDOFs,fNDet); + if (!fConfMacroName.IsNull()) printf("(config: %s)",fConfMacroName.Data()); + printf("\n"); + if (GetMPAlignDone()) printf("ALIGNMENT FROM MILLEPEDE SOLUTION IS APPLIED\n"); + // + for (int idt=0;idtPrint(opt); + } + if (!opts.IsNull()) { + printf("\nSpecial sensor for Vertex Constraint\n"); + fVtxSens->Print(opt); + } + // + // event selection + printf("\n"); + printf("%-40s:\t", "Alowed event specii mask"); + PrintBits((ULong64_t)fSelEventSpecii,5); printf("\n"); + printf("%-40s:\t%d/%d\n", "Min points per collisions track (BOff/ON)", + fMinPoints[kColl][0],fMinPoints[kColl][1]); + printf("%-40s:\t%d/%d\n", "Min points per cosmic track leg (BOff/ON)", + fMinPoints[kCosm][0],fMinPoints[kCosm][1]); + printf("%-40s:\t%d\n", "Min detectots per collision track",fMinDetAcc[kColl]); + printf("%-40s:\t%d (%s)\n", "Min detectots per cosmic track/leg",fMinDetAcc[kCosm], + fCosmicSelStrict ? "STRICT":"SOFT"); + printf("%-40s:\t%d/%d\n", "Min/Max vertex contrib. to accept event",fVtxMinCont,fVtxMaxCont); + printf("%-40s:\t%d\n", "Min vertex contrib. for constraint",fVtxMinContVC); + printf("%-40s:\t%d\n", "Min Ncl ITS for vertex constraint",fMinITSClforVC); + printf("%-40s:\t%s\n", "SPD request for vertex constraint", + AliAlgDetITS::GetITSPattName(fITSPattforVC)); + printf("%-40s:\t%.4f/%.4f/%.2f\n","DCAr/DCAz/Chi2 cut for vertex constraint", + fMaxDCAforVC[0],fMaxDCAforVC[1],fMaxChi2forVC); + printf("Collision tracks: Min pT: %5.2f |etaMax|: %5.2f\n",fPtMin[kColl],fEtaMax[kColl]); + printf("Cosmic tracks: Min pT: %5.2f |etaMax|: %5.2f\n",fPtMin[kCosm],fEtaMax[kCosm]); + // + printf("%-40s:\t%s","Config. for reference OCDB",fRefOCDBConf.Data()); + if (fRefRunNumber>=0) printf("(%d)",fRefRunNumber); + printf("\n"); + printf("%-40s:\t%s\n","Config. for reco-time OCDB",fRecoOCDBConf.Data()); + // + printf("%-40s:\t%s\n","Output OCDB path",fOutCDBPath.Data()); + printf("%-40s:\t%s/%s\n","Output OCDB comment/responsible", + fOutCDBComment.Data(),fOutCDBResponsible.Data()); + printf("%-40s:\t%6d:%6d\n","Output OCDB run range",fOutCDBRunRange[0],fOutCDBRunRange[1]); + // + printf("%-40s:\t%s\n","Filename for MillePede steering",fMPSteerFileName.Data()); + printf("%-40s:\t%s\n","Filename for MillePede parameters",fMPParFileName.Data()); + printf("%-40s:\t%s\n","Filename for MillePede constraints",fMPConFileName.Data()); + printf("%-40s:\t%s\n","Filename for control residuals:",fResidFileName.Data()); + printf("%-40s:\t%.3f\n","Fraction of control tracks",fControlFrac); + printf("MPData output :\t"); + if (GetProduceMPData()) printf("%s%s ",fMPDatFileName.Data(),fgkMPDataExt); + if (GetProduceMPRecord()) printf("%s%s ",fMPDatFileName.Data(),".root"); + printf("\n"); + // + if (opts.Contains("stat")) PrintStatistics(); +} + +//________________________________________________________ +void AliAlgSteer::PrintStatistics() const +{ + // print processing stat + printf("\nProcessing Statistics\n"); + printf("Type: "); + for (int i=0;iClear(); + for (int idet=fNDet;idet--;) { + AliAlgDet* det = GetDetector(idet); + det->ResetPool(); // reset used alignment points + } +} + +//____________________________________________ +Bool_t AliAlgSteer::TestLocalSolution() +{ + // test track local solution + TVectorD rhs; + AliSymMatrix* mat = BuildMatrix(rhs); + if (!mat) return kFALSE; + // mat->Print("long data"); + // rhs.Print(); + TVectorD vsl(rhs); + if (!mat->SolveChol(rhs,vsl,kTRUE)) { + delete mat; + return kFALSE; + } + // + /* + // print solution vector + int nlocpar = fAlgTrack->GetNLocPar(); + int nlocparETP = fAlgTrack->GetNLocExtPar(); // parameters of external track param + printf("ETP Update: "); + for (int i=0;inlocparETP) printf("Mat.Corr. update:\n"); + for (int ip=fAlgTrack->GetNPoints();ip--;) { + AliAlgPoint* pnt = fAlgTrack->GetPoint(ip); + int npm = pnt->GetNMatPar(); + const float* expMatCov = pnt->GetMatCorrCov(); // its error + int offs = pnt->GetMaxLocVarID() - npm; + for (int ipar=0;ipar sig:%+.3e -> pull: %+.2e\n", + ip,ipar,parI,vsl[parI],Sqrt((*mat)(parI,parI)), err,vsl[parI]/err); + } + } + */ + // + // increment current params by new solution + rhs.SetElements(fAlgTrack->GetLocPars()); + vsl += rhs; + fAlgTrack->SetLocPars(vsl.GetMatrixArray()); + fAlgTrack->CalcResiduals(); + delete mat; + // + return kTRUE; +} + +//____________________________________________ +AliSymMatrix* AliAlgSteer::BuildMatrix(TVectorD &vec) +{ + // build matrix/vector for local track + int npnt = fAlgTrack->GetNPoints(); + int nlocpar = fAlgTrack->GetNLocPar(); + // + vec.ResizeTo(nlocpar); + memset(vec.GetMatrixArray(),0,nlocpar*sizeof(double)); + AliSymMatrix* matp = new AliSymMatrix(nlocpar); + AliSymMatrix& mat = *matp; + // + for (int ip=npnt;ip--;) { + AliAlgPoint* pnt = fAlgTrack->GetPoint(ip); + // + if (pnt->ContainsMeasurement()) { + // pnt->Print("meas"); + for (int idim=2;idim--;) { // each point has 2 position residuals + double sigma2 = pnt->GetErrDiag(idim); // residual error + double resid = fAlgTrack->GetResidual(idim,ip); // residual + double* deriv = fAlgTrack->GetDResDLoc(idim,ip); // array of Dresidual/Dparams + // + double sg2inv = 1./sigma2; + for (int parI=nlocpar;parI--;) { + vec[parI] -= deriv[parI]*resid*sg2inv; + // printf("%d %d %d %+e %+e %+e -> %+e\n",ip,idim,parI,sg2inv,deriv[parI],resid,vec[parI]); + // for (int parJ=nlocpar;parJ--;) { + for (int parJ=parI+1;parJ--;) { + mat(parI,parJ) += deriv[parI]*deriv[parJ]*sg2inv; + } + } + } // loop over 2 orthogonal measurements at the point + } // derivarives at measured points + // + // if the point contains material, consider its expected kinks, eloss + // as measurements + if (pnt->ContainsMaterial()) { + // at least 4 parameters: 2 spatial + 2 angular kinks with 0 expectaction + int npm = pnt->GetNMatPar(); + // const float* expMatCorr = pnt->GetMatCorrExp(); // expected correction (diagonalized) + const float* expMatCov = pnt->GetMatCorrCov(); // its error + int offs = pnt->GetMaxLocVarID() - npm; + for (int ipar=0;iparBranch("mprec","AliAlgMPRecord",&fMPRecord); + // +} + +//____________________________________________ +void AliAlgSteer::InitResidOutput() +{ + // prepare residual output + if (!fCResid) fCResid = new AliAlgRes(); + // + fResidFile = TFile::Open(fResidFileName.Data(),"recreate"); + if (!fResidFile) AliFatalF("Failed to create output file %s",fResidFileName.Data()); + // + fResidTree = new TTree("res","Control Residuals"); + fResidTree->Branch("t","AliAlgRes",&fCResid); + // +} + +//____________________________________________ +void AliAlgSteer::CloseMPRecOutput() +{ + // close output + if (!fMPRecFile) return; + AliInfoF("Closing %s",fMPRecFile->GetName()); + fMPRecFile->cd(); + fMPRecTree->Write(); + delete fMPRecTree; + fMPRecTree = 0; + fMPRecFile->Close(); + delete fMPRecFile; + fMPRecFile = 0; + delete fMPRecord; + fMPRecord = 0; +} + +//____________________________________________ +void AliAlgSteer::CloseResidOutput() +{ + // close output + if (!fResidFile) return; + AliInfoF("Closing %s",fResidFile->GetName()); + fResidFile->cd(); + fResidTree->Write(); + delete fResidTree; + fResidTree = 0; + fResidFile->Close(); + delete fResidFile; + fResidFile = 0; + delete fCResid; + fCResid = 0; +} + +//____________________________________________ +void AliAlgSteer::CloseMilleOutput() +{ + // close output + if (fMille ) AliInfoF("Closing %s%s",fMPDatFileName.Data(),fgkMPDataExt); + delete fMille; + fMille = 0; +} + +//____________________________________________ +void AliAlgSteer::SetMPDatFileName(const char* name) +{ + // set output file name + fMPDatFileName = name; + // strip root or mille extensions, they will be added automatically later + if (fMPDatFileName.EndsWith(fgkMPDataExt)) + fMPDatFileName.Remove(fMPDatFileName.Length()-strlen(fgkMPDataExt)); + else if (fMPDatFileName.EndsWith(".root")) + fMPDatFileName.Remove(fMPDatFileName.Length()-strlen(".root")); + // + if (fMPDatFileName.IsNull()) fMPDatFileName = "mpData"; + // +} + +//____________________________________________ +void AliAlgSteer::SetMPParFileName(const char* name) +{ + // set MP params output file name + fMPParFileName = name; + if (fMPParFileName.IsNull()) fMPParFileName = "mpParams.txt"; + // +} + +//____________________________________________ +void AliAlgSteer::SetMPConFileName(const char* name) +{ + // set MP constraints output file name + fMPConFileName = name; + if (fMPConFileName.IsNull()) fMPConFileName = "mpConstraints.txt"; + // +} + +//____________________________________________ +void AliAlgSteer::SetMPSteerFileName(const char* name) +{ + // set MP constraints output file name + fMPSteerFileName = name; + if (fMPSteerFileName.IsNull()) fMPSteerFileName = "mpConstraints.txt"; + // +} + +//____________________________________________ +void AliAlgSteer::SetResidFileName(const char* name) +{ + // set output file name + fResidFileName = name; + if (fResidFileName.IsNull()) fResidFileName = "mpControlRes.root"; + // +} + +//____________________________________________ +void AliAlgSteer::SetOutCDBPath(const char* name) +{ + // set output storage name + fOutCDBPath = name; + if (fOutCDBPath.IsNull()) fOutCDBPath = "local://outOCDB"; + // +} + +//____________________________________________ +void AliAlgSteer::SetObligatoryDetector(Int_t detID, Int_t trtype, Bool_t v) +{ + // mark detector presence obligatory in the track of given type + AliAlgDet* det = GetDetectorByDetID(detID); + if (!det) { + AliErrorF("Detector %d is not defined",detID); + } + if (v) fObligatoryDetPattern[trtype] |= 0x1<IsObligatory(trtype)!=v) det->SetObligatory(trtype,v); + // +} + +//____________________________________________ +Bool_t AliAlgSteer::AddVertexConstraint() +{ + // if vertex is set and if particle is primary, add vertex as a meared point + // + const AliESDtrack* esdTr = fESDTrack[0]; + if (!fVertex || !esdTr) return kFALSE; + // + if (esdTr->GetNcls(0)fMaxDCAforVC[0] || Abs(dz[1])>fMaxDCAforVC[1]) return kFALSE; + Double_t covar[6]; fVertex->GetCovMatrix(covar); + Double_t p[2] = {trc.GetParameter()[0]-dz[0],trc.GetParameter()[1]-dz[1]}; + Double_t c[3] = {0.5*(covar[0]+covar[2]),0.,covar[5]}; + Double_t chi2 = trc.GetPredictedChi2(p,c); + if (chi2>fMaxChi2forVC) return kFALSE; + // + // assing measured vertex rotated to VtxSens frame as reference point + double xyz[3],xyzT[3]; + fVertex->GetXYZ(xyz); + fVtxSens->SetAlpha(trc.GetAlpha()); + // usually translation from GLO to TRA frame should go via matrix T2G + // but for the VertexSensor Local and Global are the same frames + fVtxSens->ApplyCorrection(xyz); + fVtxSens->GetMatrixT2L().MasterToLocal(xyz,xyzT); + fRefPoint->SetSensor(fVtxSens); + fRefPoint->SetAlphaSens(fVtxSens->GetAlpTracking()); + fRefPoint->SetXYZTracking(xyzT); + fRefPoint->SetYZErrTracking(c); + fRefPoint->SetContainsMeasurement(kTRUE); + fRefPoint->Init(); + // + return kTRUE; +} + +//______________________________________________________ +void AliAlgSteer::WriteCalibrationResults() const +{ + // writes output calibration + CleanOCDB(); + AliCDBManager::Instance()->SetDefaultStorage(fOutCDBPath.Data()); + // + AliAlgDet* det; + for (int idet=0;idetIsDisabled()) continue; + det->WriteCalibrationResults(); + } + // +} + +//______________________________________________________ +void AliAlgSteer::SetOutCDBRunRange(int rmin,int rmax) +{ + // set output run range + fOutCDBRunRange[0] = rmin >=0 ? rmin : 0; + fOutCDBRunRange[1] = rmax>fOutCDBRunRange[0] ? rmax : AliCDBRunRange::Infinity(); +} + +//______________________________________________________ +Bool_t AliAlgSteer::LoadRefOCDB() +{ + // setup OCDB whose objects will be used as a reference with respect to which the + // alignment/calibration will prodice its corrections. + // Detectors which need some reference calibration data must use this one + // + // + AliInfo("Loading reference OCDB"); + CleanOCDB(); + AliCDBManager* man = AliCDBManager::Instance(); + // + if (!fRefOCDBConf.IsNull() && !gSystem->AccessPathName(fRefOCDBConf.Data(), kFileExists)) { + AliInfoF("Executing reference OCDB setup macro %s",fRefOCDBConf.Data()); + if (fRefRunNumber>0) gROOT->ProcessLine(Form(".x %s(%d)",fRefOCDBConf.Data(),fRefRunNumber)); + else gROOT->ProcessLine(Form(".x %s",fRefOCDBConf.Data())); + } + else { + AliWarningF("No reference OCDB config macro %s is found, assume raw:// with run %d", + fRefOCDBConf.Data(),AliCDBRunRange::Infinity()); + man->SetRaw(kTRUE); + man->SetRun(AliCDBRunRange::Infinity()); + } + // + if (AliGeomManager::GetGeometry()) { + AliInfo("Destroying current geometry before loading reference one"); + AliGeomManager::Destroy(); + } + AliGeomManager::LoadGeometry("geometry.root"); + if (!AliGeomManager::GetGeometry()) AliFatal("Failed to load geometry, cannot run"); + // + TString detList = ""; + for (int i=0;iOwnsDOFID(id)) return det; + } + return 0; +} + +//________________________________________________________ +AliAlgVol* AliAlgSteer::GetVolOfDOFID(int id) const +{ + // return volume owning DOF with this ID + for (int i=fNDet;i--;) { + AliAlgDet* det = GetDetector(i); + if (det->OwnsDOFID(id)) return det->GetVolOfDOFID(id); + } + if (fVtxSens && fVtxSens->OwnsDOFID(id)) return fVtxSens; + return 0; +} + +//________________________________________________________ +void AliAlgSteer::Terminate(Bool_t doStat) +{ + // finalize processing + if (fRunNumber>0) FillStatHisto( kRunDone ); + if (doStat) { + if (fDOFStat) delete fDOFStat; + fDOFStat = new AliAlgDOFStat(fNDOFs); + } + if (fVtxSens) fVtxSens->FillDOFStat(fDOFStat); + // + for (int i=fNDet;i--;) GetDetector(i)->Terminate(); + CloseMPRecOutput(); + CloseMilleOutput(); + CloseResidOutput(); + Print("stat"); + // +} + +//________________________________________________________ +Char_t* AliAlgSteer::GetDOFLabelTxt(int idf) const +{ + // get DOF full label + AliAlgVol* vol = GetVolOfDOFID(idf); + if (vol) return Form("%d_%s_%s",GetGloParLab(idf),vol->GetSymName(), + vol->GetDOFName(idf-vol->GetFirstParGloID())); + // + // this might be detector-specific calibration dof + AliAlgDet* det = GetDetOfDOFID(idf); + if (det) return Form("%d_%s_%s",GetGloParLab(idf),det->GetName(), + det->GetCalibDOFName(idf-det->GetFirstParGloID())); + return 0; +} + + +//********************* interaction with PEDE ********************** + +//______________________________________________________ +void AliAlgSteer::GenPedeSteerFile(const Option_t *opt) const +{ + // produce steering file template for PEDE + params and constraints + // + enum {kOff,kOn,kOnOn}; + const char* cmt[3] = {" ","! ","!!"}; + const char* kSolMeth[] = {"inversion","diagonalization","fullGMRES","sparseGMRES","cholesky","HIP"}; + const int kDefNIter = 3; // default number of iterations to ask + const float kDefDelta = 0.1; // def. delta to exit + TString opts = opt; + opts.ToLower(); + AliInfoF("Generating MP2 templates:\n" + "Steering :\t%s\n" + "Parameters :\t%s\n" + "Constraints:\t%s\n", + fMPSteerFileName.Data(),fMPParFileName.Data(),fMPConFileName.Data()); + // + FILE* parFl = fopen (fMPParFileName.Data(),"w+"); + FILE* strFl = fopen (fMPSteerFileName.Data(),"w+"); + // + // --- template of steering file + fprintf(strFl,"%-20s%s %s\n",fMPParFileName.Data(),cmt[kOnOn],"parameters template"); + fprintf(strFl,"%-20s%s %s\n",fMPConFileName.Data(),cmt[kOnOn],"constraints template"); + // + fprintf(strFl,"\n\n%s %s\n",cmt[kOnOn],"MUST uncomment 1 solving methods and tune it"); + // + int nm = sizeof(kSolMeth)/sizeof(char*); + for (int i=0;iWritePedeInfo(parFl,opt); + // + for (int idt=0;idtIsDisabled()) continue; + det->WritePedeInfo(parFl,opt); + // + } + // + WritePedeConstraints(); + // + fclose(strFl); + fclose(parFl); + // +} + +//___________________________________________________________ +Bool_t AliAlgSteer::ReadParameters(const char* parfile, Bool_t useErrors) +{ + // read parameters file (millepede output) + if (fNDOFs<1 || !fGloParVal || !fGloParErr) { + AliErrorF("Something is wrong in init: fNDOFs=%d fGloParVal=%p fGloParErr=%p", + fNDOFs,fGloParVal,fGloParErr); + } + ifstream inpf(parfile); + if (!inpf.good()) { + printf("Failed on input filename %s\n",parfile); + return kFALSE; + } + memset(fGloParVal,0,fNDOFs*sizeof(float)); + if (useErrors) memset(fGloParErr,0,fNDOFs*sizeof(float)); + int cnt = 0; + TString fline; + fline.ReadLine(inpf); + fline = fline.Strip(TString::kBoth,' '); + fline.ToLower(); + if (!fline.BeginsWith("parameter")) { + AliErrorF("First line is not parameter keyword:\n%s",fline.Data()); + return kFALSE; + } + double v0,v1,v2; + int lab,asg=0,asg0=0; + while (fline.ReadLine(inpf)) { + cnt++; + fline = fline.Strip(TString::kBoth,' '); + if (fline.BeginsWith("!") || fline.BeginsWith("*")) continue; // ignore comment + int nr = sscanf(fline.Data(),"%d%lf%lf%lf",&lab,&v0,&v1,&v2); + if (nr<3) { + AliErrorF("Expected to read at least 3 numbers, got %d, this is NOT milleped output",nr); + AliErrorF("line (%d) was:\n%s",cnt,fline.Data()); + return kFALSE; + } + if (nr==3) asg0++; + int parID = Label2ParID(lab); + if (parID<0 || parID>=fNDOFs) { + AliErrorF("Invalid label %d at line %d -> ParID=%d",lab,cnt,parID); + return kFALSE; + } + fGloParVal[parID] = -v0; + if (useErrors) fGloParErr[parID] = v1; + asg++; + // + }; + AliInfoF("Read %d lines, assigned %d values, %d dummy",cnt,asg,asg0); + // + return kTRUE; +} + +//______________________________________________________ +void AliAlgSteer::CheckConstraints(const char* params) +{ + // check how the constraints are satisfied with already uploaded or provided params + // + if (params && !ReadParameters(params)) { + AliErrorF("Failed to load parameters from %s",params); + return; + } + // + int ncon = GetNConstraints(); + for (int icon=0;iconCheckConstraint(); + } + // +} + +//___________________________________________________________ +void AliAlgSteer::MPRec2Mille(const char* mprecfile,const char* millefile,Bool_t bindata) +{ + // converts MPRecord tree to millepede binary format + TFile* flmpr = TFile::Open(mprecfile); + if (!flmpr) { + AliErrorClassF("Failed to open MPRecord file %s",mprecfile); + return; + } + TTree* mprTree = (TTree*)flmpr->Get("mpTree"); + if (!mprTree) { + AliErrorClassF("No mpTree in xMPRecord file %s",mprecfile); + return; + } + MPRec2Mille(mprTree,millefile,bindata); + delete mprTree; + flmpr->Close(); + delete flmpr; +} + +//___________________________________________________________ +void AliAlgSteer::MPRec2Mille(TTree* mprTree,const char* millefile,Bool_t bindata) +{ + // converts MPRecord tree to millepede binary format + // + TBranch* br = mprTree->GetBranch("mprec"); + if (!br) { + AliErrorClass("provided tree does not contain branch mprec"); + return; + } + AliAlgMPRecord* rec = new AliAlgMPRecord(); + br->SetAddress(&rec); + int nent = mprTree->GetEntries(); + TString mlname = millefile; + if (mlname.IsNull()) mlname = "mpRec2mpData"; + if (!mlname.EndsWith(fgkMPDataExt)) mlname += fgkMPDataExt; + Mille* mille = new Mille(mlname,bindata); + TArrayF buffDLoc; + for (int i=0;iGetEntry(i); + int nr = rec->GetNResid(); // number of residual records + int nloc = rec->GetNVarLoc(); + if (buffDLoc.GetSize()GetArrGlo(); + const float *recDLoc = rec->GetArrLoc(); + const short *recLabLoc = rec->GetArrLabLoc(); + const int *recLabGlo = rec->GetArrLabGlo(); + // + for (int ir=0;irGetNDGlo(ir); + int ndloc = rec->GetNDLoc(ir); + // fill 0-suppressed array from MPRecord to non-0-suppressed array of Mille + for (int l=ndloc;l--;) buffLocV[recLabLoc[l]] = recDLoc[l]; + // + mille->mille(nloc,buffLocV,ndglo,recDGlo,recLabGlo,rec->GetResid(ir),rec->GetResErr(ir)); + // + recLabGlo += ndglo; // next record + recDGlo += ndglo; + recLabLoc += ndloc; + recDLoc += ndloc; + } + mille->end(); + } + delete mille; + br->SetAddress(0); + delete rec; +} + +//____________________________________________________________ +void AliAlgSteer::FillStatHisto(int type, float w) +{ + if (!fHistoStat) CreateStatHisto(); + fHistoStat->Fill( (IsCosmic() ? kNHVars:0) + type, w); +} + +//____________________________________________________________ +void AliAlgSteer::CreateStatHisto() +{ + fHistoStat = new TH1F("stat","stat",2*kNHVars,-0.5,2*kNHVars-0.5); + fHistoStat->SetDirectory(0); + TAxis *xax = fHistoStat->GetXaxis(); + for (int j=0;j<2;j++) { + for (int i=0;iSetBinLabel(j*kNHVars+i+1, Form("%s.%s",j?"CSM":"COL",fgkHStatName[i])); + } + } +} + +//____________________________________________________________ +void AliAlgSteer::PrintLabels() const +{ + // print global IDs and Labels + for (int i=0;iIsDisabled()) continue; + det->AddAutoConstraints(); + } + AliInfoF("Added %d automatic constraints",GetNConstraints()); +} + +//____________________________________________________________ +void AliAlgSteer::WritePedeConstraints() const +{ + // write constraints file + FILE* conFl = fopen (fMPConFileName.Data(),"w+"); + // + int nconstr = GetNConstraints(); + for (int icon=0;iconWriteChildrenConstraints(conFl); + // + fclose(conFl); +} + +//____________________________________________________________ +void AliAlgSteer::FixLowStatFromDOFStat(Int_t thresh) +{ + // fix DOFs having stat below threshold + // + if (!fDOFStat) { + AliError("No object with DOFs statistics"); + return; + } + if (fNDOFs != fDOFStat->GetNDOFs()) { + AliErrorF("Discrepancy between NDOFs=%d of and statistics object: %d",fNDOFs,fDOFStat->GetNDOFs()); + return; + } + for (int parID=0;parIDGetStat(parID)>=thresh) continue; + fGloParErr[parID] = -999.; + } + // +} + +//____________________________________________________________ +void AliAlgSteer::LoadStat(const char* flname) +{ + // load statistics histos from external file produced by alignment task + TFile* fl = TFile::Open(flname); + // + TObject *hdfO=0,*hstO=0; + TList* lst = (TList*)fl->Get("clist"); + if (lst) { + hdfO = lst->FindObject("DOFstat"); + if (hdfO) lst->Remove(hdfO); + hstO = lst->FindObject("stat"); + if (hstO) lst->Remove(hstO); + delete lst; + } + else { + hdfO = fl->Get("DOFstat"); + hstO = fl->Get("stat"); + } + TH1F* hst = 0; + if (hstO && (hst=dynamic_cast(hstO))) hst->SetDirectory(0); + else AliWarning("did not find stat histo"); + // + AliAlgDOFStat* dofSt = 0; + if (!hdfO || !(dofSt=dynamic_cast(hdfO))) AliWarning("did not find DOFstat object"); + // + SetHistoStat(hst); + SetDOFStat(dofSt); + // + fl->Close(); + delete fl; +} + +//______________________________________________ +void AliAlgSteer::CheckSol(TTree* mpRecTree, Bool_t store, + Bool_t verbose, Bool_t loc, const char* outName) +{ + // do fast check of pede solution with MPRecord tree + AliAlgResFast* rLG = store ? new AliAlgResFast() : 0; + AliAlgResFast* rL = store&&loc ? new AliAlgResFast() : 0; + TTree *trLG=0,*trL=0; + TFile* outFile = 0; + if (store) { + TString outNS = outName; + if (outNS.IsNull()) outNS = "resFast"; + if (!outNS.EndsWith(".root")) outNS += ".root"; + outFile = TFile::Open(outNS.Data(),"recreate"); + trLG = new TTree("resFLG","Fast residuals with LG correction"); + trLG->Branch("rLG","AliAlgResFast",&rLG); + // + if (rL) { + trL = new TTree("resFL","Fast residuals with L correction"); + trL->Branch("rL","AliAlgResFast",&rL); + } + } + // + AliAlgMPRecord* rec = new AliAlgMPRecord(); + mpRecTree->SetBranchAddress("mprec",&rec); + int nrec = mpRecTree->GetEntriesFast(); + for (int irec=0;irecGetEntry(irec); + CheckSol(rec,rLG,rL,verbose,loc); + // store even in case of failure, to have the trees aligned with controlRes + if (trLG) trLG->Fill(); + if (trL) trL->Fill(); + } + // + // save + if (trLG) { + outFile->cd(); + trLG->Write(); + delete trLG; + if (trL) { + trL->Write(); + delete trL; + } + outFile->Close(); + delete outFile; + } + // +} + +//______________________________________________ +Bool_t AliAlgSteer::CheckSol(AliAlgMPRecord* rec, + AliAlgResFast *rLG, AliAlgResFast* rL, + Bool_t verbose, Bool_t loc) +{ + // Check pede solution using derivates, rather than updated geometry + // If loc==true, also produces residuals for current geometry, + // neglecting global corrections + // + if (rL) loc = kTRUE; // if local sol. tree asked, always evaluate it + // + int nres = rec->GetNResid(); + // + const float *recDGlo = rec->GetArrGlo(); + const float *recDLoc = rec->GetArrLoc(); + const short *recLabLoc = rec->GetArrLabLoc(); + const int *recLabGlo = rec->GetArrLabGlo(); + int nvloc = rec->GetNVarLoc(); + // + // count number of real measurement duplets and material correction fake 4-plets + int nPoints = 0; + int nMatCorr = 0; + for (int irs=0;irsGetNDGlo(irs)>0) { + if (irs==nres-1 || rec->GetNDGlo(irs+1)==0) + AliFatal("Real coordinate measurements must come in pairs"); + nPoints++; + irs++; // skip 2nd + continue; + } + else if (rec->GetResid(irs)==0 && rec->GetVolID(irs)==-1) { // material corrections have 0 residual + nMatCorr++; + } + else { // might be fixed parameter, global derivs are skept + nPoints++; + irs++; // skip 2nd + continue; + } + } + // + if (nMatCorr%4) AliWarningF("Error? NMatCorr=%d is not multiple of 4",nMatCorr); + // + if (rLG) { + rLG->Clear(); + rLG->SetNPoints(nPoints); + rLG->SetNMatSol(nMatCorr); + rLG->SetCosmic(rec->IsCosmic()); + } + if (rL) { + rL->Clear(); + rL->SetNPoints(nPoints); + rL->SetNMatSol(nMatCorr); + rL->SetCosmic(rec->IsCosmic()); + } + // + AliSymMatrix* matpG = new AliSymMatrix(nvloc); + TVectorD* vecp=0, *vecpG = new TVectorD(nvloc); + // + if (loc) vecp = new TVectorD(nvloc); + // + float chi2Ini=0,chi2L=0,chi2LG=0; + // + // residuals, accounting for global solution + double *resid = new Double_t[nres]; + int* volID = new Int_t[nres]; + for (int irs=0;irsGetResid(irs); + resid[irs] = resOr; + // + int ndglo = rec->GetNDGlo(irs); + int ndloc = rec->GetNDLoc(irs); + volID[irs]=0; + for (int ig=0;igGetVolID(); + else volID[irs] = -2; // calibration DOF !!! TODO + } + } + // + double sg2inv = rec->GetResErr(irs); + sg2inv = 1./(sg2inv*sg2inv); + // + chi2Ini += resid[irs]*resid[irs]*sg2inv; // chi accounting for global solution only + // + // Build matrix to solve local parameters + for (int il=0;ilSetChi2Ini(chi2Ini); + if (rLG) rLG->SetChi2Ini(chi2Ini); + // + TVectorD vecSol(nvloc); + TVectorD vecSolG(nvloc); + // + if (!matpG->SolveChol(*vecpG,vecSolG,kFALSE)) { + AliInfo("Failed to solve track corrected for globals\n"); + delete matpG; + matpG = 0; + } + else if (loc) { // solution with local correction only + if (!matpG->SolveChol(*vecp,vecSol,kFALSE)) { + AliInfo("Failed to solve track corrected for globals\n"); + delete matpG; + matpG = 0; + } + } + delete vecpG; + delete vecp; + if (!matpG) { // failed + delete[] resid; + delete[] volID; + if (rLG) rLG->Clear(); + if (rL) rL->Clear(); + return kFALSE; + } + // check + recDGlo = rec->GetArrGlo(); + recDLoc = rec->GetArrLoc(); + recLabLoc = rec->GetArrLabLoc(); + recLabGlo = rec->GetArrLabGlo(); + // + if (verbose) { + printf(loc ? "Sol L/LG:\n":"Sol LG:\n"); + int nExtP = (nvloc%4) ? 5:4; + for (int i=0;iGetResid(irs); + double resL = resOr; + double resLG = resid[irs]; + double sg = rec->GetResErr(irs); + double sg2Inv = 1/(sg*sg); + // + int ndglo = rec->GetNDGlo(irs); + int ndloc = rec->GetNDLoc(irs); + // + for (int il=0;il1) idMeas = 0; + if (idMeas==0) pntID++; // measurements come in pairs + int lbl = rec->GetVolID(irs); + lbl = ndglo ? recLabGlo[0] : 0; // TMP, until VolID is filled // RS!!!! + if (rLG) { + rLG->SetResSigMeas(pntID,idMeas,resLG,sg); + if (idMeas==0) rLG->SetLabel(pntID,lbl,volID[irs]); + } + if (rL) { + rL->SetResSigMeas(pntID,idMeas,resL,sg); + if (idMeas==0) rL->SetLabel(pntID,lbl,volID[irs]); + } + } + else { + matID++; // mat.correcitons come in 4-plets, but we fill each separately + // + if (rLG) rLG->SetMatCorr(matID,resLG,sg); + if (rL ) rL->SetMatCorr(matID,resL,sg); + } + // + if (verbose) { + int lbl = rec->GetVolID(irs); + lbl = ndglo ? recLabGlo[0] : (resOr==0 ? -1 : 0); // TMP, until VolID is filled // RS!!!! + if (loc) printf("%3d (%9d) %6.4f | [%+.2e:%+7.2f] [%+.2e:%+7.2f]\n", + irs,lbl,sg,resL,resL/sg,resLG,resLG/sg); + else printf("%3d (%9d) %6.4f | [%+.2e:%+7.2f]\n", + irs,lbl,sg,resLG,resLG/sg); + } + // + recLabGlo += ndglo; // prepare for next record + recDGlo += ndglo; + recLabLoc += ndloc; + recDLoc += ndloc; + } + if (rL) rL->SetChi2(chi2L); + if (rLG) rLG->SetChi2(chi2LG); + // + if (verbose) { + printf("Chi: G = %e | LG = %e",chi2Ini,chi2LG); + if (loc) printf(" | L = %e",chi2L); + printf("\n"); + } + // store track corrections + int nTrCor = nvloc - matID - 1; + for (int i=0;iGetTrCor()[i] = vecSolG[i]; + if (rL) rL->GetTrCor()[i] = vecSol[i]; + } + // + delete[] resid; + delete[] volID; + return kTRUE; +} + +//______________________________________________ +void AliAlgSteer::ApplyAlignmentFromMPSol() +{ + // apply alignment from millepede solution array to reference alignment level + AliInfo("Applying alignment from Millepede solution"); + for (int idt=0;idtIsDisabled()) continue; + det->ApplyAlignmentFromMPSol(); + } + SetMPAlignDone(); + // +} diff --git a/Detectors/Align/AliAlgSteer.h b/Detectors/Align/AliAlgSteer.h new file mode 100644 index 0000000000000..31a6b3a79f168 --- /dev/null +++ b/Detectors/Align/AliAlgSteer.h @@ -0,0 +1,419 @@ +#ifndef ALIALGSTEER_H +#define ALIALGSTEER_H + +#include "AliGeomManager.h" +#include "AliAlgTrack.h" +#include "AliSymMatrix.h" + +#include +#include +#include +#include +#include +#include +#include +#include "AliAlgAux.h" + +class AliESDEvent; +class AliESDtrack; +class AliESDCosmicTrack; +class AliESDVertex; +class AliAlgDet; +class AliAlgVol; +class AliAlgVtx; +class AliAlgPoint; +class AliAlgMPRecord; +class AliAlgRes; +class AliAlgResFast; +class AliAlgConstraint; +class AliAlgDOFStat; +class TTree; +class TFile; +// +class Mille; + + +/*-------------------------------------------------------- + Steering class for the global alignment. Responsible for feeding the track data + to participating detectors and preparation of the millepede input. + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + + +class AliAlgSteer : public TObject +{ + public: + enum {kNLrSkip=4}; + enum {kITS,kTPC,kTRD,kTOF,kHMPID,kNDetectors, kUndefined}; + enum {kCosmLow,kCosmUp,kNCosmLegs}; + enum {kInpStat,kAccStat,kNStatCl}; + enum {kRun,kEventColl,kEventCosm,kTrackColl,kTrackCosm, kMaxStat}; + enum MPOut_t {kMille=BIT(0),kMPRec=BIT(1),kContR=BIT(2)}; + enum {kInitGeomDone=BIT(14),kInitDOFsDone=BIT(15),kMPAlignDone=BIT(16)}; + // + enum { // STAT histo entries + kRunDone // input runs + ,kEvInp // input events + ,kEvVtx // after vtx selection + ,kTrackInp // input tracks + ,kTrackFitInp // input to ini fit + ,kTrackFitInpVC // those with vertex constraint + ,kTrackProcMatInp// input to process materials + ,kTrackResDerInp // input to resid/deriv calculation + ,kTrackStore // stored tracks + ,kTrackAcc // tracks accepted + ,kTrackControl // control tracks filled + // + ,kNHVars + }; + + // + AliAlgSteer(const char* configMacro=0, int refRun=-1); + virtual ~AliAlgSteer(); + Bool_t LoadRefOCDB(); + Bool_t LoadRecoTimeOCDB(); + Bool_t GetUseRecoOCDB() const {return fUseRecoOCDB;} + void SetUseRecoOCDB(Bool_t v=kTRUE) {fUseRecoOCDB=v;} + + void InitDetectors(); + void InitDOFs(); + void Terminate(Bool_t dostat=kTRUE); + void SetStatHistoLabels(TH1* h) const; + // + void SetInitGeomDone() {SetBit(kInitGeomDone);} + Bool_t GetInitGeomDone() const {return TestBit(kInitGeomDone);} + // + void SetInitDOFsDone() {SetBit(kInitDOFsDone);} + Bool_t GetInitDOFsDone() const {return TestBit(kInitDOFsDone);} + // + void SetMPAlignDone() {SetBit(kMPAlignDone);} + Bool_t GetMPAlignDone() const {return TestBit(kMPAlignDone);} + + void AssignDOFs(); + // + void AddDetector(UInt_t id, AliAlgDet* det=0); + void AddDetector(AliAlgDet* det); + // + void AddConstraint(const AliAlgConstraint* cs) {fConstraints.AddLast((TObject*)cs);} + Int_t GetNConstraints() const {return fConstraints.GetEntriesFast();} + const TObjArray* GetConstraints() const {return &fConstraints;} + const AliAlgConstraint* GetConstraint(int i) const {return (AliAlgConstraint*)fConstraints[i];} + void AddAutoConstraints(); + // + void AcknowledgeNewRun(Int_t run); + void SetRunNumber(Int_t run); + Int_t GetRunNumber() const {return fRunNumber;} + Bool_t GetFieldOn() const {return fFieldOn;} + void SetFieldOn(Bool_t v=kTRUE) {fFieldOn = v;} + Int_t GetTracksType() const {return fTracksType;} + void SetTracksType(Int_t t=AliAlgAux::kColl) {fTracksType = t;} + Bool_t IsCosmic() const {return fTracksType==AliAlgAux::kCosm;} + Bool_t IsCollision() const {return fTracksType==AliAlgAux::kColl;} + void SetCosmic(Bool_t v=kTRUE) {fTracksType = v ? AliAlgAux::kCosm : AliAlgAux::kColl;} + Float_t GetStat(int cls, int tp) const {return fStat[cls][tp];} + // + void SetESDTree(const TTree* tr) {fESDTree = tr;} + const TTree* GetESDTree() const {return fESDTree;} + void SetESDEvent(const AliESDEvent* ev); + const AliESDEvent* GetESDEvent() const {return fESDEvent;} + void SetESDtrack(const AliESDtrack* tr, int i=0) {fESDTrack[i] = tr;} + const AliESDtrack* GetESDtrack(int i=0) const {return fESDTrack[i];} + // + // Track selection + void SetCosmicSelStrict(Bool_t v=kTRUE) {fCosmicSelStrict = v;} + Bool_t GetCosmicSelStrict() const {return fCosmicSelStrict;} + // + Int_t GetMinPoints() const {return fMinPoints[fTracksType][GetFieldOn()];} + Int_t GetMinPoints(Bool_t tp,Bool_t bON) const {return fMinPoints[tp][bON];} + void SetMinPoints(Bool_t tp,Bool_t bON,int n) {int mn=bON?4:3; fMinPoints[tp][bON]=n>mn?n:mn;} + void SetMinPointsColl(int vbOff=3,int vbOn=4); + void SetMinPointsCosm(int vbOff=3,int vbOn=4); + // + Double_t GetPtMin(Bool_t tp) const {return fPtMin[tp];} + void SetPtMin(Bool_t tp,double pt) {fPtMin[tp] = pt;} + void SetPtMinColl(double pt=0.7) {SetPtMin(AliAlgAux::kColl,pt);} + void SetPtMinCosm(double pt=1.0) {SetPtMin(AliAlgAux::kCosm,pt);} + // + Double_t GetEtaMax(Bool_t tp) const {return fEtaMax[tp];} + void SetEtaMax(Bool_t tp,double eta) {fEtaMax[tp]=eta;} + void SetEtaMaxColl(double eta=1.5) {SetEtaMax(AliAlgAux::kColl,eta);} + void SetEtaMaxCosm(double eta=1.5) {SetEtaMax(AliAlgAux::kCosm,eta);} + // + void SetDefPtBOffCosm(double pt=5.0) {fDefPtBOff[AliAlgAux::kCosm] = pt>0.3 ? pt:0.3;} + void SetDefPtBOffColl(double pt=0.6) {fDefPtBOff[AliAlgAux::kColl] = pt>0.3 ? pt:0.3;} + Double_t GetDefPtBOff(Bool_t tp) {return fDefPtBOff[tp];} + // + Int_t GetMinDetAcc(Bool_t tp) const {return fMinDetAcc[tp];} + void SetMinDetAcc(Bool_t tp, int n) {fMinDetAcc[tp] = n;} + void SetMinDetAccColl(int n=1) {SetMinDetAcc(AliAlgAux::kColl,n);} + void SetMinDetAccCosm(int n=1) {SetMinDetAcc(AliAlgAux::kCosm,n);} + // + Int_t GetVtxMinCont() const {return fVtxMinCont;} + void SetVtxMinCont(int n) {fVtxMinCont = n;} + Int_t GetVtxMaxCont() const {return fVtxMaxCont;} + void SetVtxMaxCont(int n) {fVtxMaxCont = n;} + Int_t GetVtxMinContVC() const {return fVtxMinContVC;} + void SetVtxMinContVC(int n) {fVtxMinContVC = n;} + // + Int_t GetMinITSClforVC() const {return fMinITSClforVC;} + void SetMinITSClforVC(int n) {fMinITSClforVC = n;} + Int_t GetITSPattforVC() const {return fITSPattforVC;} + void SetITSPattforVC(int p) {fITSPattforVC=p;} + Double_t GetMaxDCARforVC() const {return fMaxDCAforVC[0];} + Double_t GetMaxDCAZforVC() const {return fMaxDCAforVC[1];} + void SetMaxDCAforVC(double dr=0.1,double dz=0.6) {fMaxDCAforVC[0]=dr; fMaxDCAforVC[1]=dz;} + Double_t GetMaxChi2forVC() const {return fMaxChi2forVC;} + void SetMaxChi2forVC(double chi2=10) {fMaxChi2forVC = chi2;} + // + Bool_t CheckDetectorPattern(UInt_t patt) const; + Bool_t CheckDetectorPoints(const int* npsel) const; + void SetObligatoryDetector(Int_t detID, Int_t tp, Bool_t v=kTRUE); + void SetEventSpeciiSelection(UInt_t sel) {fSelEventSpecii = sel;} + UInt_t GetEventSpeciiSelection() const {return fSelEventSpecii;} + // + void SetVertex(const AliESDVertex* v) {fVertex = v;} + const AliESDVertex* GetVertex() const {return fVertex;} + // + //---------------------------------------- + Bool_t ReadParameters(const char* parfile="millepede.res", Bool_t useErrors=kTRUE); + Float_t* GetGloParVal() const {return (Float_t*)fGloParVal;} + Float_t* GetGloParErr() const {return (Float_t*)fGloParErr;} + Int_t* GetGloParLab() const {return (Int_t*)fGloParLab;} + Int_t GetGloParLab(int i) const {return (Int_t)fGloParLab[i];} + Int_t ParID2Label(int i) const {return GetGloParLab(i);} + Int_t Label2ParID(int lab) const; + AliAlgVol* GetVolOfDOFID(int id) const; + AliAlgDet* GetDetOfDOFID(int id) const; + // + AliAlgPoint* GetRefPoint() const {return (AliAlgPoint*)fRefPoint;} + // + AliAlgRes* GetContResid() const {return (AliAlgRes*)fCResid;} + AliAlgMPRecord* GetMPRecord() const {return (AliAlgMPRecord*)fMPRecord;} + TTree* GetMPRecTree() const {return fMPRecTree;} + AliAlgTrack* GetAlgTrack() const {return (AliAlgTrack*)fAlgTrack;} + Bool_t ProcessEvent(const AliESDEvent* esdEv); + Bool_t ProcessTrack(const AliESDtrack* esdTr); + Bool_t ProcessTrack(const AliESDCosmicTrack* esdCTr); + UInt_t AcceptTrack(const AliESDtrack* esdTr, Bool_t strict=kTRUE) const; + UInt_t AcceptTrackCosmic(const AliESDtrack* esdPairCosm[kNCosmLegs]) const; + Bool_t CheckSetVertex(const AliESDVertex* vtx); + Bool_t AddVertexConstraint(); + Int_t GetNDetectors() const {return fNDet;} + AliAlgDet* GetDetector(Int_t i) const {return fDetectors[i];} + AliAlgDet* GetDetectorByDetID(Int_t i) const {return fDetPos[i]<0 ? 0:fDetectors[fDetPos[i]];} + AliAlgDet* GetDetectorByVolID(Int_t id) const; + AliAlgVtx* GetVertexSensor() const {return fVtxSens;} + // + void ResetDetectors(); + Int_t GetNDOFs() const {return fNDOFs;} + // + const char* GetConfMacroName() const {return fConfMacroName.Data();} + //---------------------------------------- + // output related + void SetMPDatFileName(const char* name="mpData"); + void SetMPParFileName(const char* name="mpParams.txt"); + void SetMPConFileName(const char* name="mpConstraints.txt"); + void SetMPSteerFileName(const char* name="mpSteer.txt"); + void SetResidFileName(const char* name="mpControlRes.root"); + void SetOutCDBPath(const char* name="local://outOCDB"); + void SetOutCDBComment(const char* cm=0) {fOutCDBComment = cm;} + void SetOutCDBResponsible(const char* v=0) {fOutCDBResponsible = v;} + void SetOutCDBRunRange(int rmin=0,int rmax=999999999); + Int_t* GetOutCDBRunRange() const {return (int*)fOutCDBRunRange;} + Int_t GetOutCDBRunMin() const {return fOutCDBRunRange[0];} + Int_t GetOutCDBRunMax() const {return fOutCDBRunRange[1];} + Float_t GetControlFrac() const {return fControlFrac;} + void SetControlFrac(float v=1.) {fControlFrac = v;} + void WriteCalibrationResults() const; + void ApplyAlignmentFromMPSol(); + const char* GetOutCDBComment() const {return fOutCDBComment.Data();} + const char* GetOutCDBResponsible() const {return fOutCDBResponsible.Data();} + const char* GetOutCDBPath() const {return fOutCDBPath.Data();} + const char* GetMPDatFileName() const {return fMPDatFileName.Data();} + const char* GetResidFileName() const {return fResidFileName.Data();} + const char* GetMPParFileName() const {return fMPParFileName.Data();} + const char* GetMPConFileName() const {return fMPConFileName.Data();} + const char* GetMPSteerFileName() const {return fMPSteerFileName.Data();} + // + Bool_t FillMPRecData(); + Bool_t FillMilleData(); + Bool_t FillControlData(); + void SetDoKalmanResid(Bool_t v=kTRUE) {fDoKalmanResid = v;} + void SetMPOutType(Int_t t) {fMPOutType = t;} + void ProduceMPData(Bool_t v=kTRUE) {if (v) fMPOutType|=kMille; else fMPOutType&=~kMille;} + void ProduceMPRecord(Bool_t v=kTRUE) {if (v) fMPOutType|=kMPRec; else fMPOutType&=~kMPRec;} + void ProduceControlRes(Bool_t v=kTRUE) {if (v) fMPOutType|=kContR; else fMPOutType&=~kContR;} + Int_t GetMPOutType() const {return fMPOutType;} + Bool_t GetDoKalmanResid() const {return fDoKalmanResid;} + Bool_t GetProduceMPData() const {return fMPOutType&kMille;} + Bool_t GetProduceMPRecord() const {return fMPOutType&kMPRec;} + Bool_t GetProduceControlRes() const {return fMPOutType&kContR;} + void CloseMPRecOutput(); + void CloseMilleOutput(); + void CloseResidOutput(); + void InitMPRecOutput(); + void InitMIlleOutput(); + void InitResidOutput(); + Bool_t StoreProcessedTrack(Int_t what); + void PrintStatistics() const; + Bool_t GetMilleTXT() const {return !fMilleOutBin;} + void SetMilleTXT(Bool_t v=kTRUE) {fMilleOutBin = !v;} + // + void GenPedeSteerFile(const Option_t *opt="") const; + void WritePedeConstraints() const; + void CheckConstraints(const char* params=0); + AliAlgDOFStat* GetDOFStat() const {return fDOFStat;} + void SetDOFStat(AliAlgDOFStat* st) {fDOFStat = st;} + void DetachDOFStat() {SetDOFStat(0);} + TH1* GetHistoStat() const {return fHistoStat;} + void DetachHistoStat() {SetHistoStat(0);} + void SetHistoStat(TH1F* h) {fHistoStat = h;} + void FillStatHisto(int type, float w=1); + void CreateStatHisto(); + void FixLowStatFromDOFStat(Int_t thresh=40); + void LoadStat(const char* flname); + // + //---------------------------------------- + // + Int_t GetRefRunNumber() const {return fRefRunNumber;} + void SetRefRunNumber(int r=-1) {fRefRunNumber = r;} + // + void SetRefOCDBConfigMacro(const char* nm="configRefOCDB.C") {fRefOCDBConf = nm;} + const char* GetRefOCDBConfigMacro() const {return fRefOCDBConf.Data();} + void SetRecoOCDBConfigMacro(const char* nm="configRecoOCDB.C") {fRecoOCDBConf = nm;} + const char* GetRecoOCDBConfigMacro() const {return fRecoOCDBConf.Data();} + Int_t GetRefOCDBLoaded() const {return fRefOCDBLoaded;} + // + virtual void Print(const Option_t *opt="") const; + void PrintLabels() const; + Char_t* GetDOFLabelTxt(int idf) const; + // + static Char_t* GetDetNameByDetID(Int_t id) {return (Char_t*)fgkDetectorName[id];} + static void MPRec2Mille(const char* mprecfile,const char* millefile="mpData.mille",Bool_t bindata=kTRUE); + static void MPRec2Mille(TTree* mprTree,const char* millefile="mpData.mille",Bool_t bindata=kTRUE); + // + AliSymMatrix* BuildMatrix(TVectorD &vec); + Bool_t TestLocalSolution(); + // + // fast check of solution using derivatives + void CheckSol(TTree* mpRecTree, Bool_t store=kTRUE,Bool_t verbose=kFALSE,Bool_t loc=kTRUE, const char* outName="resFast"); + Bool_t CheckSol(AliAlgMPRecord* rec,AliAlgResFast *rLG=0, AliAlgResFast* rL=0,Bool_t verbose=kTRUE, Bool_t loc=kTRUE); + // + protected: + // + // --------- dummies ----------- + AliAlgSteer(const AliAlgSteer&); + AliAlgSteer& operator=(const AliAlgSteer&); + // + protected: + // + Int_t fNDet; // number of deectors participating in the alignment + Int_t fNDOFs; // number of degrees of freedom + Int_t fRunNumber; // current run number + Bool_t fFieldOn; // field on flag + Int_t fTracksType; // collision/cosmic event type + AliAlgTrack* fAlgTrack; // current alignment track + AliAlgDet* fDetectors[kNDetectors]; // detectors participating in the alignment + Int_t fDetPos[kNDetectors]; // entry of detector in the fDetectors array + AliAlgVtx* fVtxSens; // fake sensor for the vertex + TObjArray fConstraints; // array of constraints + // + // Track selection + UInt_t fSelEventSpecii; // consider only these event specii + UInt_t fObligatoryDetPattern[AliAlgAux::kNTrackTypes]; // pattern of obligatory detectors + Bool_t fCosmicSelStrict; // if true, each cosmic track leg selected like separate track + Int_t fMinPoints[AliAlgAux::kNTrackTypes][2]; // require min points per leg (case Boff,Bon) + Int_t fMinDetAcc[AliAlgAux::kNTrackTypes]; // min number of detector required in track + Double_t fDefPtBOff[AliAlgAux::kNTrackTypes]; // nominal pt for tracks in Boff run + Double_t fPtMin[AliAlgAux::kNTrackTypes]; // min pT of tracks to consider + Double_t fEtaMax[AliAlgAux::kNTrackTypes]; // eta cut on tracks + Int_t fVtxMinCont; // require min number of contributors in Vtx + Int_t fVtxMaxCont; // require max number of contributors in Vtx + Int_t fVtxMinContVC; // min number of contributors to use as constraint + // + Int_t fMinITSClforVC; // use vertex constraint for tracks with enough points + Int_t fITSPattforVC; // optional request on ITS hits to allow vertex constraint + Double_t fMaxDCAforVC[2]; // DCA cut in R,Z to allow vertex constraint + Double_t fMaxChi2forVC; // track-vertex chi2 cut to allow vertex constraint + // + // + Float_t* fGloParVal; //[fNDOFs] parameters for DOFs + Float_t* fGloParErr; //[fNDOFs] errors for DOFs + Int_t* fGloParLab; //[fNDOFs] labels for DOFs + Int_t* fOrderedLbl; //[fNDOFs] ordered labels + Int_t* fLbl2ID; //[fNDOFs] Label order in fOrderedLbl -> parID + // + AliAlgPoint* fRefPoint; // reference point for track definition + // + const TTree* fESDTree; //! externally set esdTree, needed to access UserInfo list + const AliESDEvent* fESDEvent; //! externally set event + const AliESDtrack* fESDTrack[kNCosmLegs]; //! externally set ESD tracks + const AliESDVertex* fVertex; //! event vertex + // + // statistics + Float_t fStat[kNStatCl][kMaxStat]; // processing statistics + static const Char_t* fgkStatClName[kNStatCl]; // stat classes names + static const Char_t* fgkStatName[kMaxStat]; // stat type names + // + // output related + Float_t fControlFrac; // fraction of tracks to process control residuals + Int_t fMPOutType; // What to store as an output, see StoreProcessedTrack + Mille* fMille; //! Mille interface + AliAlgMPRecord* fMPRecord; //! MP record + AliAlgRes* fCResid; //! control residuals + TTree* fMPRecTree; //! tree to store MP record + TTree* fResidTree; //! tree to store control residuals + TFile* fMPRecFile; //! file to store MP record tree + TFile* fResidFile; //! file to store control residuals tree + TArrayF fMilleDBuffer; //! buffer for Mille Derivatives output + TArrayI fMilleIBuffer; //! buffer for Mille Indecis output + TString fMPDatFileName; // file name for records binary data output + TString fMPParFileName; // file name for MP params + TString fMPConFileName; // file name for MP constraints + TString fMPSteerFileName; // file name for MP steering + TString fResidFileName; // file name for optional control residuals + Bool_t fMilleOutBin; // optionally text output for Mille debugging + Bool_t fDoKalmanResid; // calculate residuals with smoothed kalman in the ControlRes + // + TString fOutCDBPath; // output OCDB path + TString fOutCDBComment; // optional comment to add to output cdb objects + TString fOutCDBResponsible; // optional responsible for output metadata + Int_t fOutCDBRunRange[2]; // run range for output storage + // + AliAlgDOFStat* fDOFStat; // stat of entries per dof + TH1F* fHistoStat; // histo with general statistics + // + // input related + TString fConfMacroName; // optional configuration macro + TString fRecoOCDBConf; // optional macro name for reco-time OCDB setup: void fun(int run) + TString fRefOCDBConf; // optional macro name for prealignment OCDB setup: void fun() + Int_t fRefRunNumber; // optional run number used for reference + Int_t fRefOCDBLoaded; // flag/counter for ref.OCDB loading + Bool_t fUseRecoOCDB; // flag to preload reco-time calib objects + // + static const Int_t fgkSkipLayers[kNLrSkip]; // detector layers for which we don't need module matrices + static const Char_t* fgkDetectorName[kNDetectors]; // names of detectors + static const Char_t* fgkHStatName[kNHVars]; // names for stat.bins in the stat histo + static const Char_t* fgkMPDataExt; // extension for MP2 binary data + // + ClassDef(AliAlgSteer,2) +}; + +//__________________________________________________________ +inline void AliAlgSteer::SetMinPointsColl(int vbOff,int vbOn) +{ + // ask min number of points per track + SetMinPoints(AliAlgAux::kColl,kFALSE,vbOff); + SetMinPoints(AliAlgAux::kColl,kTRUE,vbOn); +} + +//__________________________________________________________ +inline void AliAlgSteer::SetMinPointsCosm(int vbOff,int vbOn) +{ + // ask min number of points per track + SetMinPoints(AliAlgAux::kCosm,kFALSE,vbOff); + SetMinPoints(AliAlgAux::kCosm,kTRUE,vbOn); +} + +#endif diff --git a/Detectors/Align/AliAlgTrack.cxx b/Detectors/Align/AliAlgTrack.cxx new file mode 100644 index 0000000000000..7bdbe8e6ea416 --- /dev/null +++ b/Detectors/Align/AliAlgTrack.cxx @@ -0,0 +1,1513 @@ +/************************************************************************** + * 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. * + **************************************************************************/ + +#include +#include "AliAlgTrack.h" +#include "AliTrackerBase.h" +#include "AliLog.h" +#include "AliAlgSens.h" +#include "AliAlgVol.h" +#include "AliAlgDet.h" +#include "AliAlgAux.h" +#include +#include +#include + +using namespace AliAlgAux; +using namespace TMath; + +// RS: this is not good: we define constants outside the class, but it is to +// bypass the CINT limitations on static arrays initializations +const Int_t kRichardsonOrd = 1; // Order of Richardson extrapolation for derivative (min=1) +const Int_t kRichardsonN = kRichardsonOrd+1; // N of 2-point symmetric derivatives needed for requested order +const Int_t kNRDClones = kRichardsonN*2 ;// number of variations for derivative of requested order + +//____________________________________________________________________________ +AliAlgTrack::AliAlgTrack() : + fNLocPar(0) + ,fNLocExtPar(0) + ,fNGloPar(0) + ,fNDF(0) + ,fInnerPointID(0) + // ,fMinX2X0Pt2Account(5/1.0) + ,fMinX2X0Pt2Account(0.5e-3/1.0) + ,fMass(0.14) + ,fChi2(0) + ,fChi2CosmUp(0) + ,fChi2CosmDn(0) + ,fChi2Ini(0) + ,fPoints(0) + ,fLocPar() + ,fGloParID(0) + ,fGloParIDA(0) + ,fLocParA(0) +{ + // def c-tor + for (int i=0;i<2;i++) { + // we start with 0 size buffers for derivatives, they will be expanded automatically + fResid[i].Set(0); + fDResDGlo[i].Set(0); + fDResDLoc[i].Set(0); + // + fResidA[i] = 0; + fDResDLocA[i] = 0; + fDResDGloA[i] = 0; + } + fNeedInv[0] = fNeedInv[1] = kFALSE; + // +} + +//____________________________________________________________________________ +AliAlgTrack::~AliAlgTrack() +{ + // d-tor +} + +//____________________________________________________________________________ +void AliAlgTrack::Clear(Option_t *) +{ + // reset the track + TObject::Clear(); + ResetBit(0xffffffff); + fPoints.Clear(); + fChi2 = fChi2CosmUp = fChi2CosmDn = fChi2Ini = 0; + fNDF = 0; + fInnerPointID = -1; + fNeedInv[0] = fNeedInv[1] = kFALSE; + fNLocPar = fNLocExtPar = fNGloPar = 0; + // +} + +//____________________________________________________________________________ +void AliAlgTrack::DefineDOFs() +{ + // define varied DOF's (local parameters) for the track: + // 1) kinematic params (5 or 4 depending on Bfield) + // 2) mult. scattering angles (2) + // 3) if requested by point: energy loss + // + fNLocPar = fNLocExtPar = GetFieldON() ? kNKinParBON : kNKinParBOFF; + int np = GetNPoints(); + // + // the points are sorted in order opposite to track direction -> outer points come 1st, + // but for the 2-leg cosmic track the innermost points are in the middle (1st lower leg, then upper one) + // + // start along track direction, i.e. last point in the ordered array + int minPar = fNLocPar; + for (int ip=GetInnerPointID()+1;ip--;) { // collision track or cosmic lower leg + AliAlgPoint* pnt = GetPoint(ip); + pnt->SetMinLocVarID(minPar); + if (pnt->ContainsMaterial()) fNLocPar += pnt->GetNMatPar(); + pnt->SetMaxLocVarID(fNLocPar); // flag up to which parameted ID this points depends on + } + // + if (IsCosmic()) { + minPar = fNLocPar; + for (int ip=GetInnerPointID()+1;ipSetMinLocVarID(minPar); + if (pnt->ContainsMaterial()) fNLocPar += pnt->GetNMatPar(); + pnt->SetMaxLocVarID(fNLocPar); // flag up to which parameted ID this points depends on + } + } + // + if (fLocPar.GetSize()3 + AliWarning("Failed on derivatives calculation 0"); +#endif + return kFALSE; + } + // + if (IsCosmic()) { // cosmic upper leg + if (!CalcResidDeriv(params,fNeedInv[1],GetInnerPointID()+1,np-1)) { +#if DEBUG>3 + AliWarning("Failed on derivatives calculation 0"); +#endif + } + } + // + SetDerivDone(); + return kTRUE; +} + +//______________________________________________________ +Bool_t AliAlgTrack::CalcResidDeriv(double *params,Bool_t invert,int pFrom,int pTo) +{ + // Calculate derivatives of residuals vs params for points pFrom to pT. For cosmic upper leg + // track parameter may require inversion. + // The 1st 4 or 5 elements of params vector should be the reference AliExternalTrackParam + // Then parameters of material corrections for each point + // marked as having materials should come (4 or 5 dependending if ELoss is varied or fixed). + // They correspond to kink parameters + // (AliExternalTrackParam_after_material - AliExternalTrackParam_before_material) + // rotated to frame where they error matrix is diagonal. Their conversion to AliExternalTrackParam + // increment will be done locally in the ApplyMatCorr routine. + // + // The derivatives are calculated using Richardson extrapolation + // (like http://root.cern.ch/root/html/ROOT__Math__RichardsonDerivator.html) + // + AliExternalTrackParam probD[kNRDClones]; // use this to vary supplied param for derivative calculation + double varDelta[kRichardsonN]; + const int kInvElem[kNKinParBON] = {-1,1,1,-1,-1}; + // + const double kDelta[kNKinParBON] = {0.02,0.02, 0.001,0.001, 0.01}; // variations for ExtTrackParam and material effects + // + double delta[kNKinParBON]; // variations of curvature term are relative + for (int i=kNKinParBOFF;i--;) delta[i] = kDelta[i]; + if (GetFieldON()) delta[kParQ2Pt] = kDelta[kParQ2Pt]*Abs(GetParameter()[kParQ2Pt]); + // + int pinc; + if (pTo>pFrom) { // fit in points decreasing order: cosmics upper leg + pTo++; + pinc = 1; + } + else { // fit in points increasing order: collision track or cosmics lower leg + pTo--; + pinc = -1; + } + // 1) derivative wrt AliExternalTrackParam parameters + for (int ipar=fNLocExtPar;ipar--;) { + SetParams(probD,kNRDClones, GetX(),GetAlpha(),params,kTRUE); + if (invert) for (int ic=kNRDClones;ic--;) probD[ic].Invert(); + double del = delta[ipar]; + // + for (int icl=0;iclContainsMaterial()) { // apply material corrections + if (!ApplyMatCorr(probD, kNRDClones, params, pnt)) return kFALSE; + // } + // + if (pnt->ContainsMeasurement()) { + int offsDer = ip*fNLocPar + ipar; + RichardsonDeriv(probD, varDelta, pnt, fDResDLocA[0][offsDer], fDResDLocA[1][offsDer]); // calculate derivatives + if (invert&&kInvElem[ipar]<0) { + fDResDLocA[0][offsDer] = -fDResDLocA[0][offsDer]; + fDResDLocA[1][offsDer] = -fDResDLocA[1][offsDer]; + } + } + } // loop over points + } // loop over ExtTrackParam parameters + // + // 2) now vary material effect related parameters: MS and eventually ELoss + // + for (int ip=pFrom;ip!=pTo;ip+=pinc) { // points are ordered against track direction + AliAlgPoint* pnt = GetPoint(ip); + // + // global derivatives at this point + if (pnt->ContainsMeasurement() && !CalcResidDerivGlo(pnt)) { + #if DEBUG>3 + AliWarningF("Failed on global derivatives calculation at point %d",ip); + pnt->Print("meas"); +#endif + return kFALSE; + } + // + if (!pnt->ContainsMaterial()) continue; + // + int nParFreeI = pnt->GetNMatPar(); + // + // array delta gives desired variation of parameters in AliExternalTrackParam definition, + // while the variation should be done for parameters in the frame where the vector + // of material corrections has diagonal cov. matrix -> rotate the delta to this frame + double deltaMatD[kNKinParBON]; + pnt->DiagMatCorr(delta,deltaMatD); + // + // printf("Vary %d [%+.3e %+.3e %+.3e %+.3e] ",ip,deltaMatD[0],deltaMatD[1],deltaMatD[2],deltaMatD[3]); pnt->Print(); + + int offsI = pnt->GetMaxLocVarID() - nParFreeI; // the parameters for this point start with this offset + // they are irrelevant for the points upstream + for (int ipar=0;iparGetXPoint(),pnt->GetAlphaSens(),pnt->GetTrParamWSB(),kFALSE); + // no need for eventual track inversion here: if needed, this is already done in ParamWSB + // + int offsIP = offsI+ipar; // parameter entry in the params array + // printf(" Var:%d (%d) %e\n",ipar,offsIP, del); + + for (int icl=0;iclContainsMeasurement()) { // calculate derivatives at the scattering point itself + int offsDerIP = ip*fNLocPar + offsIP; + RichardsonDeriv(probD, varDelta, pnt, fDResDLocA[0][offsDerIP], fDResDLocA[1][offsDerIP]); // calculate derivatives for ip + // printf("DR SELF: %e %e at %d (%d)\n",fDResDLocA[0][offsDerIP], fDResDLocA[1][offsDerIP],offsI, offsDerIP); + } + // + // loop over points whose residuals can be affected by the material effects on point ip + for (int jp=ip+pinc;jp!=pTo;jp+=pinc) { + AliAlgPoint* pntJ = GetPoint(jp); + + // printf(" DerFor:%d ",jp); pntJ->Print(); + + if ( !PropagateParamToPoint(probD, kNRDClones, pntJ) ) return kFALSE; + // + if (pntJ->ContainsMaterial()) { // apply material corrections + if (!ApplyMatCorr(probD,kNRDClones,params,pntJ)) return kFALSE; + } + // + if (pntJ->ContainsMeasurement()) { + int offsDerJ = jp*fNLocPar + offsIP; + // calculate derivatives + RichardsonDeriv(probD, varDelta, pntJ, fDResDLocA[0][offsDerJ], fDResDLocA[1][offsDerJ]); + } + // + } // << loop over points whose residuals can be affected by the material effects on point ip + } // << loop over DOFs related to MS and ELoss are point ip + } // << loop over all points of the track + // + return kTRUE; +} + +//______________________________________________________ +Bool_t AliAlgTrack::CalcResidDerivGlo(AliAlgPoint* pnt) +{ + // calculate residuals derivatives over point's sensor and its parents global params + double deriv[AliAlgVol::kNDOFGeom*3]; + // + const AliAlgSens* sens = pnt->GetSensor(); + const AliAlgVol* vol = sens; + // precalculated track parameters + double snp=pnt->GetTrParamWSA(kParSnp),tgl=pnt->GetTrParamWSA(kParTgl); + // precalculate track slopes to account tracking X veriation + // these are coeffs to translate deltaX of the point to deltaY and deltaZ of track + double cspi = 1./Sqrt((1-snp)*(1+snp)), slpY = snp*cspi, slpZ = tgl*cspi; + // + pnt->SetDGloOffs(fNGloPar); // mark 1st entry of derivatives + do { + // measurement residuals + int nfree = vol->GetNDOFFree(); + if (!nfree) continue; // no free parameters? + sens->DPosTraDParGeom(pnt,deriv,vol==sens ? 0:vol); + // + CheckExpandDerGloBuffer(fNGloPar+nfree); // if needed, expand derivatives buffer + // + for (int ip=0;ipIsFreeDOF(ip)) continue; + double* dXYZ = &deriv[ip*3]; // tracking XYZ derivatives over this parameter + // residual is defined as diagonalized track_estimate - measured Y,Z in tracking frame + // where the track is evaluated at measured X! + // -> take into account modified X using track parameterization at the point (paramWSA) + // Attention: small simplifications(to be checked if it is ok!!!): + // effect of changing X is accounted neglecting track curvature to preserve linearity + // + // store diagonalized residuals in track buffer + pnt->DiagonalizeResiduals((dXYZ[AliAlgPoint::kX]*slpY - dXYZ[AliAlgPoint::kY]), + (dXYZ[AliAlgPoint::kX]*slpZ - dXYZ[AliAlgPoint::kZ]), + fDResDGloA[0][fNGloPar],fDResDGloA[1][fNGloPar]); + // and register global ID of varied parameter + fGloParIDA[fNGloPar] = vol->GetParGloID(ip); + fNGloPar++; + } + // + } while( (vol=vol->GetParent()) ); + // + // eventual detector calibration parameters + const AliAlgDet* det = sens->GetDetector(); + int ndof=0; + if (det && (ndof=det->GetNCalibDOFs())) { + // if needed, expand derivatives buffer + CheckExpandDerGloBuffer(fNGloPar+det->GetNCalibDOFsFree()); + for (int idf=0;idfIsFreeDOF(idf)) continue; + sens->DPosTraDParCalib(pnt,deriv,idf,0); + pnt->DiagonalizeResiduals((deriv[AliAlgPoint::kX]*slpY - deriv[AliAlgPoint::kY]), + (deriv[AliAlgPoint::kX]*slpZ - deriv[AliAlgPoint::kZ]), + fDResDGloA[0][fNGloPar],fDResDGloA[1][fNGloPar]); + // and register global ID of varied parameter + fGloParIDA[fNGloPar] = det->GetParGloID(idf); + fNGloPar++; + } + } + // + pnt->SetNGloDOFs(fNGloPar-pnt->GetDGloOffs()); // mark number of global derivatives filled + // + return kTRUE; +} + +//______________________________________________________ +Bool_t AliAlgTrack::CalcResiduals(const double *params) +{ + // Propagate for given local params and calculate residuals + // The 1st 4 or 5 elements of params vector should be the reference AliExternalTrackParam + // Then parameters of material corrections for each point + // marked as having materials should come (4 or 5 dependending if ELoss is varied or fixed). + // They correspond to kink parameters + // (AliExternalTrackParam_after_material - AliExternalTrackParam_before_material) + // rotated to frame where they error matrix is diagonal. Their conversion to AliExternalTrackParam + // increment will be done locally in the ApplyMatCorr routine. + // + // If params are not provided, use internal params array + // + if (!params) params = fLocParA; + int np = GetNPoints(); + fChi2 = 0; + fNDF = 0; + // + // collision track or cosmic lower leg + if (!CalcResiduals(params,fNeedInv[0],GetInnerPointID(),0)) { +#if DEBUG>3 + AliWarning("Failed on residuals calculation 0"); +#endif + return kFALSE; + } + // + if (IsCosmic()) { // cosmic upper leg + if (!CalcResiduals(params,fNeedInv[1],GetInnerPointID()+1,np-1)) { +#if DEBUG>3 + AliWarning("Failed on residuals calculation 1"); +#endif + return kFALSE; + } + } + // + fNDF -= fNLocExtPar; + SetResidDone(); + return kTRUE; +} + +//______________________________________________________ +Bool_t AliAlgTrack::CalcResiduals(const double *params,Bool_t invert,int pFrom,int pTo) +{ + // Calculate residuals for the single leg from points pFrom to pT + // The 1st 4 or 5 elements of params vector should be corrections to + // the reference AliExternalTrackParam + // Then parameters of material corrections for each point + // marked as having materials should come (4 or 5 dependending if ELoss is varied or fixed). + // They correspond to kink parameters + // (AliExternalTrackParam_after_material - AliExternalTrackParam_before_material) + // rotated to frame where they error matrix is diagonal. Their conversion to AliExternalTrackParam + // increment will be done locally in the ApplyMatCorr routine. + // + AliExternalTrackParam probe; + SetParams(probe,GetX(),GetAlpha(),params,kTRUE); + if (invert) probe.Invert(); + int pinc; + if (pTo>pFrom) { // fit in points decreasing order: cosmics upper leg + pTo++; + pinc = 1; + } + else { // fit in points increasing order: collision track or cosmics lower leg + pTo--; + pinc = -1; + } + // + for (int ip=pFrom;ip!=pTo;ip+=pinc) { // points are ordered against track direction + AliAlgPoint* pnt = GetPoint(ip); + if (!PropagateParamToPoint(probe, pnt)) return kFALSE; + // + // store the current track kinematics at the point BEFORE applying eventual material + // corrections. This kinematics will be later varied around supplied parameters (in the CalcResidDeriv) + pnt->SetTrParamWSB(probe.GetParameter()); + // + // account for materials + // if (pnt->ContainsMaterial()) { // apply material corrections + if (!ApplyMatCorr(probe, params, pnt)) return kFALSE; + // } + pnt->SetTrParamWSA(probe.GetParameter()); + // + if (pnt->ContainsMeasurement()) { // need to calculate residuals in the frame where errors are orthogonal + pnt->GetResidualsDiag(probe.GetParameter(),fResidA[0][ip],fResidA[1][ip]); + fChi2 += fResidA[0][ip]*fResidA[0][ip]/pnt->GetErrDiag(0); + fChi2 += fResidA[1][ip]*fResidA[1][ip]/pnt->GetErrDiag(1); + fNDF += 2; + } + // + if (pnt->ContainsMaterial()) { + // material degrees of freedom do not contribute to NDF since they are constrained by 0 expectation + int nCorrPar = pnt->GetNMatPar(); + const double *corrDiag = &fLocParA[pnt->GetMaxLocVarID()-nCorrPar]; // corrections in diagonalized frame + float *corCov = pnt->GetMatCorrCov(); // correction diagonalized covariance + for (int i=0;i3 + AliErrorF("Failed on clone %d propagation",itr); + tr[itr].Print(); + pnt->Print("meas mat"); +#endif + return kFALSE; + } + } + return kTRUE; +} + +//______________________________________________________ +Bool_t AliAlgTrack::PropagateParamToPoint(AliExternalTrackParam &tr, const AliAlgPoint* pnt, double maxStep) +{ + // propagate tracks to the point (only parameters, no error matrix) + double xyz[3],bxyz[3]; + // + if (!tr.RotateParamOnly(pnt->GetAlphaSens())) { +#if DEBUG>3 + AliErrorF("Failed to rotate to alpha=%f",pnt->GetAlphaSens()); + tr.Print(); + pnt->Print(); +#endif + return kFALSE; + } + // + double xTgt = pnt->GetXPoint(); + double xBeg = tr.GetX(); + double dx = xTgt - xBeg; + int nstep = int(Abs(dx)/maxStep)+1; + dx/=nstep; + // + for (int ist=nstep;ist--;) { + // + double xToGo = xTgt - dx*ist; + tr.GetXYZ(xyz); + // + if (GetFieldON()) { + if (pnt->GetUseBzOnly()) { + if (!tr.PropagateParamOnlyTo(xToGo,AliTrackerBase::GetBz(xyz))) { +#if DEBUG>3 + AliErrorF("Failed to propagate(BZ) to X=%f",pnt->GetXPoint()); + tr.Print(); + pnt->Print(); +#endif + return kFALSE; + } + } + else { + AliTrackerBase::GetBxByBz(xyz,bxyz); + if (!tr.PropagateParamOnlyBxByBzTo(xToGo,bxyz)) { +#if DEBUG>3 + AliErrorF("Failed to propagate(BXYZ) to X=%f",pnt->GetXPoint()); + tr.Print(); + pnt->Print(); +#endif + return kFALSE; + } + } + } + else { // straigth line propagation + if ( !tr.PropagateParamOnlyTo(xToGo,0) ) { +#if DEBUG>3 + AliErrorF("Failed to propagate(B=0) to X=%f",pnt->GetXPoint()); + tr.Print(); + pnt->Print(); +#endif + return kFALSE; + } + } + } // steps + // + return kTRUE; +} + +//______________________________________________________ +Bool_t AliAlgTrack::PropagateToPoint(AliExternalTrackParam &tr, const AliAlgPoint* pnt, + int minNSteps, double maxStep, Bool_t matCor, double *matPar) +{ + // propagate tracks to the point. If matCor is true, then material corrections will be applied. + // if matPar pointer is provided, it will be filled by total x2x0 and signed xrho + if (!tr.Rotate(pnt->GetAlphaSens())) { +#if DEBUG>3 + AliWarning(Form("Failed to rotate to alpha=%f",pnt->GetAlphaSens())); + tr.Print(); +#endif + return kFALSE; + } + // + double xyz0[3],xyz1[3],bxyz[3],matarr[7]; + double xPoint=pnt->GetXPoint(),dx=xPoint-tr.GetX(),dxa=Abs(dx),step=dxa/minNSteps; + if (matPar) matPar[0]=matPar[1]=0; + if (dxamaxStep) step = maxStep; + int nstep = int(dxa/step); + step = dxa/nstep; + if (dx<0) step = -step; + // + // printf("-->will go from X:%e to X:%e in %d steps of %f\n",tr.GetX(),xPoint,nstep,step); + + // do we go along or against track direction + Bool_t alongTrackDir = (dx>0&&!pnt->IsInvDir()) || (dx<0&&pnt->IsInvDir()); + Bool_t queryXYZ = matCor||GetFieldON(); + if (queryXYZ) tr.GetXYZ(xyz0); + // + double x2X0Tot=0,xrhoTot=0; + for (int ist=nstep;ist--;) { // single propagation step >> + double xToGo = xPoint - step*ist; + // + if (GetFieldON()) { + if (pnt->GetUseBzOnly()) { + if (!tr.PropagateTo(xToGo,AliTrackerBase::GetBz(xyz0))) { +#if DEBUG>3 + AliWarningF("Failed to propagate(BZ) to X=%f",xToGo); + tr.Print(); +#endif + return kFALSE; + } + } + else { + AliTrackerBase::GetBxByBz(xyz0,bxyz); + if (!tr.PropagateToBxByBz(xToGo,bxyz)) { +#if DEBUG>3 + AliWarningF("Failed to propagate(BXYZ) to X=%f",xToGo); +#endif + return kFALSE; + } + } + } + else { // straigth line propagation + if ( !tr.PropagateTo(xToGo,0) ) { +#if DEBUG>3 + AliWarningF("Failed to propagate(B=0) to X=%f",xToGo); +#endif + return kFALSE; + } + } + // + if (queryXYZ) { + tr.GetXYZ(xyz1); + if (matCor) { + AliTrackerBase::MeanMaterialBudget(xyz0,xyz1,matarr); + Double_t xrho=matarr[0]*matarr[4], xx0=matarr[1]; + if (alongTrackDir) xrho = -xrho; // if we go along track direction, energy correction is negative + x2X0Tot += xx0; + xrhoTot += xrho; + // printf("MAT %+7.2f %+7.2f %+7.2f -> %+7.2f %+7.2f %+7.2f | %+e %+e | -> %+e %+e | %+e %+e %+e %+e %+e\n", + // xyz0[0],xyz0[1],xyz0[2], xyz1[0],xyz1[1],xyz1[2], tr.Phi(), tr.GetAlpha(), + // x2X0Tot,xrhoTot, matarr[0],matarr[1],matarr[2],matarr[3],matarr[4]); + if (!tr.CorrectForMeanMaterial(xx0,xrho,fMass)) { +#if DEBUG>3 + AliWarningF("Failed on CorrectForMeanMaterial(%f,%f,%f)",xx0,xrho,fMass); + tr.Print(); +#endif + return kFALSE; + } + } + for (int l=3;l--;) xyz0[l] = xyz1[l]; + } + } // single propagation step << + // + if (matPar) { + matPar[0] = x2X0Tot; + matPar[1] = xrhoTot; + } + return kTRUE; +} + +/* +//______________________________________________________ +Bool_t AliAlgTrack::ApplyMS(AliExternalTrackParam& trPar, double tms,double pms) +{ + //------------------------------------------------------------------------------ + // Modify track par (e.g. AliExternalTrackParam) in the tracking frame + // (dip angle lam, az. angle phi) + // by multiple scattering defined by polar and azumuthal scattering angles in + // the track collinear frame (tms and pms resp). + // The updated direction vector in the tracking frame becomes + // + // | Cos[lam]*Cos[phi] Cos[phi]*Sin[lam] -Sin[phi] | | Cos[tms] | + // | Cos[lam]*Sin[phi] Sin[lam]*Sin[phi] Cos[phi] | x | Cos[pms]*Sin[tms]| + // | Sin[lam] -Cos[lam] 0 | | Sin[pms]*Sin[tms]| + // + //------------------------------------------------------------------------------ + // + double *par = (double*) trPar.GetParameter(); + // + if (Abs(tms)<1e-7) return kTRUE; + // + double snTms = Sin(tms), csTms = Cos(tms); + double snPms = Sin(pms), csPms = Cos(pms); + double snPhi = par[2], csPhi = Sqrt((1.-snPhi)*(1.+snPhi)); + double csLam = 1./Sqrt(1.+par[3]*par[3]), snLam = csLam*par[3]; + // + double r00 = csLam*csPhi, r01 = snLam*csPhi, &r02 = snPhi; + double r10 = csLam*snPhi, r11 = snLam*snPhi, &r12 = csPhi; + double &r20 = snLam ,&r21 = csLam; + // + double &v0 = csTms, v1 = snTms*csPms, v2 = snTms*snPms; + // + double px = r00*v0 + r01*v1 - r02*v2; + double py = r10*v0 + r11*v1 + r12*v2; + double pz = r20*v0 - r21*v1; + // + double pt = Sqrt(px*px + py*py); + par[2] = py/pt; + par[3] = pz/pt; + par[4]*= csLam/pt; + // + return kTRUE; +} +*/ + +//______________________________________________________ +Bool_t AliAlgTrack::ApplyMatCorr(AliExternalTrackParam& trPar, const Double_t *corrPar, const AliAlgPoint* pnt) +{ + // Modify track param (e.g. AliExternalTrackParam) in the tracking frame + // by delta accounting for material effects + // Note: corrPar contains delta to track parameters rotated by the matrix + // DIAGONALIZING ITS COVARIANCE MATRIX! + // transform parameters from the frame diagonalizing the errors to track frame + double corr[kNKinParBON] = {0}; + if (pnt->ContainsMaterial()) { // are there free params from meterials? + int nCorrPar = pnt->GetNMatPar(); + const double *corrDiag = &corrPar[pnt->GetMaxLocVarID()-nCorrPar]; // material corrections for this point start here + pnt->UnDiagMatCorr(corrDiag, corr); // this is to account for MS and RANDOM Eloss (if varied) + } + // to this we should add expected parameters modification due to the deterministic eloss + float *detELoss = pnt->GetMatCorrExp(); + for (int i=kNKinParBON;i--;) corr[i] += detELoss[i]; + //corr[kParQ2Pt] += detELoss[kParQ2Pt]; + // printf("apply corr UD %+.3e %+.3e %+.3e %+.3e %+.3e\n",corr[0],corr[1],corr[2],corr[3],corr[4]); + // printf(" corr D %+.3e %+.3e %+.3e %+.3e\n",corrDiag[0],corrDiag[1],corrDiag[2],corrDiag[3]); + // printf("at point :"); pnt->Print(); + return ApplyMatCorr(trPar,corr); + // +} + +//______________________________________________________ +Bool_t AliAlgTrack::ApplyMatCorr(AliExternalTrackParam& trPar, const Double_t *corr) +{ + // Modify track param (e.g. AliExternalTrackParam) in the tracking frame + // by delta accounting for material effects + // Note: corr contains delta to track frame, NOT in diagonalized one + const double kMaxSnp = 0.95; + double* par = (double*)trPar.GetParameter(); + double snpNew = par[kParSnp]+corr[kParSnp]; + if (Abs(snpNew)>kMaxSnp) { +#if DEBUG>3 + AliErrorF("Snp is too large: %f",snpNew); + printf("DeltaPar: "); + for (int i=0;iContainsMaterial()) { // are there free params from meterials? + int nCorrPar = pnt->GetNMatPar(); + const double *corrDiagP = &corrDiag[pnt->GetMaxLocVarID()-nCorrPar]; // material corrections for this point start here + pnt->UnDiagMatCorr(corrDiagP, corr); + } + float *detELoss = pnt->GetMatCorrExp(); + for (int i=kNKinParBON;i--;) corr[i] += detELoss[i]; + // if (!pnt->GetELossVaried()) corr[kParQ2Pt] = pnt->GetMatCorrExp()[kParQ2Pt]; // fixed eloss expected effect + // printf("apply corr UD %+.3e %+.3e %+.3e %+.3e\n",corr[0],corr[1],corr[2],corr[3]); + // printf(" corr D %+.3e %+.3e %+.3e %+.3e\n",corrDiagP[0],corrDiagP[1],corrDiagP[2],corrDiagP[3]); + // printf("at point :"); pnt->Print(); + // + for (int itr=ntr;itr--;) { + if (!ApplyMatCorr(trSet[itr],corr)) { +#if DEBUG>3 + AliErrorF("Failed on clone %d materials",itr); + trSet[itr].Print(); +#endif + return kFALSE; + } + } + return kTRUE; +} + +//______________________________________________ +Double_t AliAlgTrack::RichardsonExtrap(double *val, int ord) +{ + // Calculate Richardson extrapolation of order ord (starting from 1) + // The array val should contain estimates ord+1 of derivatives with variations + // d, d/2 ... d/2^ord. + // The array val is overwritten + // + if (ord==1) return (4.*val[1] - val[0])*(1./3); + do {for (int i=0;iGetResidualsDiag(trSet[(icl<<1)+0].GetParameter(), resYVP, resZVP); // variation with +delta + pnt->GetResidualsDiag(trSet[(icl<<1)+1].GetParameter(), resYVN, resZVN); // variation with -delta + derRichY[icl] = 0.5*(resYVP-resYVN)/delta[icl]; // 2-point symmetric derivatives + derRichZ[icl] = 0.5*(resZVP-resZVN)/delta[icl]; + } + derY = RichardsonExtrap(derRichY,kRichardsonOrd); // dY/dPar + derZ = RichardsonExtrap(derRichZ,kRichardsonOrd); // dZ/dPar + // +} + +//______________________________________________ +void AliAlgTrack::Print(Option_t *opt) const +{ + // print track data + printf("%s ",IsCosmic() ? " Cosmic ":"Collision "); + AliExternalTrackParam::Print(); + printf("N Free Par: %d (Kinem: %d) | Npoints: %d (Inner:%d) | M : %.3f | Chi2Ini:%.1f Chi2: %.1f/%d", + fNLocPar,fNLocExtPar,GetNPoints(),GetInnerPointID(),fMass,fChi2Ini,fChi2,fNDF); + if (IsCosmic()) { + int npLow = GetInnerPointID(); + int npUp = GetNPoints() - npLow - 1; + printf(" [Low:%.1f/%d Up:%.1f/%d]",fChi2CosmDn,npLow, fChi2CosmUp,npUp); + } + printf("\n"); + // + TString optS = opt; + optS.ToLower(); + Bool_t res = optS.Contains("r") && GetResidDone(); + Bool_t der = optS.Contains("d") && GetDerivDone(); + Bool_t par = optS.Contains("lc"); // local param corrections + Bool_t paru = optS.Contains("lcu"); // local param corrections in track param frame + // + if (par) { + printf("Ref.track corr: "); for (int i=0;iPrint(opt); + // + if (res && pnt->ContainsMeasurement()) { + printf(" Residuals : %+.3e %+.3e -> Pulls: %+7.2f %+7.2f\n", + GetResidual(0,ip),GetResidual(1,ip), + GetResidual(0,ip)/sqrt(pnt->GetErrDiag(0)),GetResidual(1,ip)/sqrt(pnt->GetErrDiag(1))); + } + if (der && pnt->ContainsMeasurement()) { + for (int ipar=0;iparContainsMaterial()) { // material corrections + int nCorrPar = pnt->GetNMatPar(); + const double *corrDiag = &fLocParA[pnt->GetMaxLocVarID()-nCorrPar]; + printf(" Corr.Diag: "); + for (int i=0;iGetMatCorrCov(); // correction covariance + //float *corExp = pnt->GetMatCorrExp(); // correction expectation + for (int i=0;iUnDiagMatCorr(corrDiag, corr); + // if (!pnt->GetELossVaried()) corr[kParQ2Pt] = pnt->GetMatCorrExp()[kParQ2Pt]; // fixed eloss expected effect + printf(" Corr.Track: "); + for (int i=0;iContainsMeasurement()) continue; + pnt->DumpCoordinates(); + } +} + +//______________________________________________ +Bool_t AliAlgTrack::IniFit() +{ + // perform initial fit of the track + // + const int kMinNStep = 3; + const double kMaxDefStep = 3.0; + // + AliExternalTrackParam trc = *this; + // + if (!GetFieldON()) { // for field-off data impose nominal momentum + + } + fChi2 = fChi2CosmUp = fChi2CosmDn = 0; + // + // the points are ranged from outer to inner for collision tracks, + // and from outer point of lower leg to outer point of upper leg for the cosmic track + // + // the fit will always start from the outgoing track in inward direction + if (!FitLeg(trc,0,GetInnerPointID(),fNeedInv[0])) { +#if DEBUG>3 + AliWarning("Failed FitLeg 0"); + trc.Print(); +#endif + return kFALSE; // collision track or cosmic lower leg + } + // + // printf("Lower leg: %d %d\n",0,GetInnerPointID()); trc.Print(); + // + if (IsCosmic()) { + fChi2CosmDn = fChi2; + AliExternalTrackParam trcU = trc; + if (!FitLeg(trcU,GetNPoints()-1,GetInnerPointID()+1,fNeedInv[1])) { //fit upper leg of cosmic track +#if DEBUG>3 + AliWarning("Failed FitLeg 0"); + trc.Print(); +#endif + return kFALSE; // collision track or cosmic lower leg + } + // + // propagate to reference point, which is the inner point of lower leg + const AliAlgPoint* refP = GetPoint(GetInnerPointID()); + if (!PropagateToPoint(trcU,refP,kMinNStep,kMaxDefStep,kTRUE)) return kFALSE; + // + fChi2CosmUp = fChi2 - fChi2CosmDn; + // printf("Upper leg: %d %d\n",GetInnerPointID()+1,GetNPoints()-1); trcU.Print(); + // + if (!CombineTracks(trc,trcU)) return kFALSE; + //printf("Combined\n"); trc.Print(); + } + CopyFrom(&trc); + // + fChi2Ini = fChi2; + + return kTRUE; +} + +//______________________________________________ +Bool_t AliAlgTrack::CombineTracks(AliExternalTrackParam& trcL, const AliExternalTrackParam& trcU) +{ + // Assign to trcL the combined tracks (Kalman update of trcL by trcU) + // The trcL and trcU MUST be defined at same X,Alpha + // + // Update equations: tracks described by vectors vL and vU and coviriances CL and CU resp. + // then the gain matrix K = CL*(CL+CU)^-1 + // Updated vector and its covariance: + // CL' = CL - K*CL + // vL' = vL + K(vU-vL) + // + if (Abs(trcL.GetX()-trcU.GetX())>kTinyDist || Abs(trcL.GetAlpha()-trcU.GetAlpha())>kTinyDist) { + AliError("Tracks must be defined at same reference X and Alpha"); + trcL.Print(); + trcU.Print(); + return kFALSE; + } + // + const double* covU=trcU.GetCovariance(),*parU=trcU.GetParameter(); + double* covL=(double*)trcL.GetCovariance(),*parL=(double*)trcL.GetParameter(); + // + int mtSize = GetFieldON() ? kNKinParBON : kNKinParBOFF; + TMatrixD matCL(mtSize,mtSize),matCLplCU(mtSize,mtSize); + TVectorD vl(mtSize),vUmnvL(mtSize); + // + // trcL.Print(); + // trcU.Print(); + // + for (int i=mtSize;i--;) { + vUmnvL[i] = parU[i] - parL[i]; // y = residual of 2 tracks + vl[i] = parL[i]; + for (int j=i+1;j--;) { + int indIJ = ((i*(i+1))>>1)+j; // position of IJ cov element in the AliExternalTrackParam covariance array + matCL(i,j) = matCL(j,i) = covL[indIJ]; + matCLplCU(i,j) = matCLplCU(j,i) = covL[indIJ] + covU[indIJ]; + } + } + matCLplCU.Invert(); // S^-1 = (Cl + Cu)^-1 + if (!matCLplCU.IsValid()) { +#if DEBUG>3 + AliError("Failed to invert summed cov.matrix of cosmic track"); + matCLplCU.Print(); +#endif + return kFALSE; // inversion failed + } + TMatrixD matK(matCL,TMatrixD::kMult,matCLplCU); // gain K = Cl*(Cl+Cu)^-1 + TMatrixD matKdotCL(matK,TMatrixD::kMult,matCL); // K*Cl + TVectorD vlUp = matK*vUmnvL; // K*(vl - vu) + for (int i=mtSize;i--;) { + parL[i] += vlUp[i]; // updated param: vL' = vL + K(vU-vL) + for (int j=i+1;j--;) covL[((i*(i+1))>>1)+j] -= matKdotCL(i,j); // updated covariance: Cl' = Cl - K*Cl + } + // + // update chi2 + double chi2 = 0; + for (int i=mtSize;i--;) for (int j=mtSize;j--;) chi2 += matCLplCU(i,j)*vUmnvL[i]*vUmnvL[j]; + fChi2 += chi2; + // + // printf("Combined: Chi2Tot:%.2f ChiUp:%.2f ChiDn:%.2f ChiCmb:%.2f\n",fChi2,fChi2CosmUp,fChi2CosmDn, chi2); + + return kTRUE; +} + +//______________________________________________ +Bool_t AliAlgTrack::FitLeg(AliExternalTrackParam& trc, int pFrom,int pTo, Bool_t &inv) +{ + // perform initial fit of the track + // the fit will always start from the outgoing track in inward direction (i.e. if cosmics - bottom leg) + const int kMinNStep = 3; + const double kMaxDefStep = 3.0; + const double kErrSpace= 50.; + const double kErrAng = 0.7; + const double kErrRelPtI = 1.; + const double kIniErr[15] = { // initial error + kErrSpace*kErrSpace, + 0 , kErrSpace*kErrSpace, + 0 , 0, kErrAng*kErrAng, + 0 , 0, 0, kErrAng*kErrAng, + 0 , 0, 0, 0, kErrRelPtI*kErrRelPtI + }; + // + // prepare seed at outer point + AliAlgPoint* p0 = GetPoint(pFrom); + double phi = trc.Phi(),alp=p0->GetAlphaSens(); + BringTo02Pi(phi); + BringTo02Pi(alp); + double dphi = DeltaPhiSmall(phi,alp); // abs delta angle + if (dphi>Pi()/2.) { // need to invert the track to new frame + inv = kTRUE; + // printf("Fit in %d %d Delta: %.3f -> Inverting for\n",pFrom,pTo,dphi); + // p0->Print("meas"); + // printf("BeforeInv "); trc.Print(); + trc.Invert(); + // printf("After Inv "); trc.Print(); + } + if (!trc.RotateParamOnly(p0->GetAlphaSens())) { +#if DEBUG>3 + AliWarningF("Failed on RotateParamOnly to %f",p0->GetAlphaSens()); + trc.Print(); +#endif + return kFALSE; + } + if (!PropagateParamToPoint(trc,p0,30)) { + // if (!PropagateToPoint(trc,p0,5,30,kTRUE)) { + //trc.PropagateParamOnlyTo(p0->GetXPoint()+kOverShootX,AliTrackerBase::GetBz())) { +#if DEBUG>3 + AliWarningF("Failed on PropagateParamOnlyTo to %f",p0->GetXPoint()+kOverShootX); + trc.Print(); +#endif + return kFALSE; + } + double* cov = (double*)trc.GetCovariance(); + memcpy(cov,kIniErr,15*sizeof(double)); + cov[14] *= trc.GetSigned1Pt()*trc.GetSigned1Pt(); + // + int pinc; + if (pTo>pFrom) { // fit in points increasing order: collision track or cosmics lower leg + pTo++; + pinc = 1; + } + else { // fit in points decreasing order: cosmics upper leg + pTo--; + pinc = -1; + } + // + for (int ip=pFrom;ip!=pTo;ip+=pinc) { // inward fit from outer point + AliAlgPoint* pnt = GetPoint(ip); + // + // printf("*** FitLeg %d (%d %d)\n",ip,pFrom,pTo); + // printf("Before propagate: "); trc.Print(); + if (!PropagateToPoint(trc,pnt,kMinNStep, kMaxDefStep, kTRUE)) return kFALSE; + if (pnt->ContainsMeasurement()) { + if (pnt->GetNeedUpdateFromTrack()) pnt->UpdatePointByTrackInfo(&trc); + const double* yz = pnt->GetYZTracking(); + const double* errYZ = pnt->GetYZErrTracking(); + double chi = trc.GetPredictedChi2(yz,errYZ); + //printf("***>> fitleg-> Y: %+e %+e / Z: %+e %+e -> Chi2: %e | %+e %+e\n",yz[0],trc.GetY(),yz[1],trc.GetZ(),chi, + // trc.Phi(),trc.GetAlpha()); + // printf("Before update at %e %e\n",yz[0],yz[1]); trc.Print(); + if (!trc.Update(yz,errYZ)) { +#if DEBUG>3 + AliWarningF("Failed on Update %f,%f {%f,%f,%f}",yz[0],yz[1],errYZ[0],errYZ[1],errYZ[2]); + trc.Print(); +#endif + return kFALSE; + } + fChi2 += chi; + // printf("After update: (%f) -> %f\n",chi,fChi2); trc.Print(); + } + } + // + if (inv) { + // printf("Before inverting back "); trc.Print(); + trc.Invert(); + } + // + return kTRUE; +} + +//______________________________________________ +Bool_t AliAlgTrack::ResidKalman() +{ + // calculate residuals from bi-directional Kalman smoother + // ATTENTION: this method modifies workspaces of the points!!! + // + Bool_t inv = kFALSE; + const int kMinNStep = 3; + const double kMaxDefStep = 3.0; + const double kErrSpace=50.; + const double kErrAng = 0.7; + const double kErrRelPtI = 1.; + const double kIniErr[15] = { // initial error + kErrSpace*kErrSpace, + 0 , kErrSpace*kErrSpace, + 0 , 0, kErrAng*kErrAng, + 0 , 0, 0, kErrAng*kErrAng, + 0 , 0, 0, 0, kErrRelPtI*kErrRelPtI + }; + // const Double_t kOverShootX = 5; + // + AliExternalTrackParam trc = *this; + // + int pID=0, nPnt = GetNPoints();; + AliAlgPoint* pnt = 0; + // get 1st measured point + while ( pIDContainsMeasurement() ) pID++; + if (!pnt) return kFALSE; + double phi = trc.Phi(),alp=pnt->GetAlphaSens(); + BringTo02Pi(phi); + BringTo02Pi(alp); + double dphi = DeltaPhiSmall(phi,alp); + if (dphi>Pi()/2.) { // need to invert the track to new frame + inv = kTRUE; + trc.Invert(); + } + // prepare track seed at 1st valid point + if (!trc.RotateParamOnly(pnt->GetAlphaSens())) { +#if DEBUG>3 + AliWarningF("Failed on RotateParamOnly to %f",pnt->GetAlphaSens()); + trc.Print(); +#endif + return kFALSE; + } + if (!PropagateParamToPoint(trc,pnt,30)) { + //if (!trc.PropagateParamOnlyTo(pnt->GetXPoint()+kOverShootX,AliTrackerBase::GetBz())) { +#if DEBUG>3 + AliWarningF("Failed on PropagateParamOnlyTo to %f",pnt->GetXPoint()+kOverShootX); + trc.Print(); +#endif + return kFALSE; + } + // + double* cov = (double*)trc.GetCovariance(); + memcpy(cov,kIniErr,15*sizeof(double)); + cov[14] *= trc.GetSigned1Pt()*trc.GetSigned1Pt(); + // + double chifwd = 0, chibwd = 0; + // inward fit + for (int ip=0;ipIsInvDir()!=inv) { // crossing point where the track should be inverted? + trc.Invert(); + inv = !inv; + } + // printf("*** ResidKalm %d (%d %d)\n",ip,0,nPnt); + // printf("Before propagate: "); trc.Print(); + if (!PropagateToPoint(trc,pnt,kMinNStep, kMaxDefStep, kTRUE)) return kFALSE; + if (!pnt->ContainsMeasurement()) continue; + const double* yz = pnt->GetYZTracking(); + const double* errYZ = pnt->GetYZErrTracking(); + // store track position/errors before update in the point WorkSpace-A + double* ws = (double*)pnt->GetTrParamWSA(); + ws[0] = trc.GetY(); + ws[1] = trc.GetZ(); + ws[2] = trc.GetSigmaY2(); + ws[3] = trc.GetSigmaZY(); + ws[4] = trc.GetSigmaZ2(); + double chi = trc.GetPredictedChi2(yz,errYZ); + // printf(">> INV%d (%9d): %+.2e %+.2e | %+.2e %+.2e %+.2e %+.2e %+.2e | %.2e %d \n",ip,pnt->GetSensor()->GetInternalID(),yz[0],yz[1], ws[0],ws[1],ws[2],ws[3],ws[4],chi,inv); + // printf(">>Bef ");trc.Print(); + // printf("KLM Before update at %e %e\n",yz[0],yz[1]); trc.Print(); + if (!trc.Update(yz,errYZ)) { +#if DEBUG>3 + AliWarningF("Failed on Inward Update %f,%f {%f,%f,%f}",yz[0],yz[1],errYZ[0],errYZ[1],errYZ[2]); + trc.Print(); +#endif + return kFALSE; + } + // printf(">>Aft ");trc.Print(); + chifwd += chi; + //printf("KLM After update: (%f) -> %f\n",chi,chifwd); trc.Print(); + } + // + // outward fit + cov = (double*)trc.GetCovariance(); + memcpy(cov,kIniErr,15*sizeof(double)); + cov[14] *= trc.GetSigned1Pt()*trc.GetSigned1Pt(); + for (int ip=nPnt;ip--;) { + pnt = GetPoint(ip); + if (pnt->IsInvDir()!=inv) { // crossing point where the track should be inverted? + trc.Invert(); + inv = !inv; + } + if (!PropagateToPoint(trc,pnt,kMinNStep, kMaxDefStep, kTRUE)) return kFALSE; + if (!pnt->ContainsMeasurement()) continue; + const double* yz = pnt->GetYZTracking(); + const double* errYZ = pnt->GetYZErrTracking(); + // store track position/errors before update in the point WorkSpace-B + double* ws = (double*)pnt->GetTrParamWSB(); + ws[0] = trc.GetY(); + ws[1] = trc.GetZ(); + ws[2] = trc.GetSigmaY2(); + ws[3] = trc.GetSigmaZY(); + ws[4] = trc.GetSigmaZ2(); + double chi = trc.GetPredictedChi2(yz,errYZ); + // printf("<< OUT%d (%9d): %+.2e %+.2e | %+.2e %+.2e %+.2e %+.2e %+.2e | %.2e %d \n",ip,pnt->GetSensor()->GetInternalID(),yz[0],yz[1], ws[0],ws[1],ws[2],ws[3],ws[4],chi,inv); + // printf("<3 + AliWarningF("Failed on Outward Update %f,%f {%f,%f,%f}",yz[0],yz[1],errYZ[0],errYZ[1],errYZ[2]); + trc.Print(); +#endif + return kFALSE; + } + chibwd += chi; + // printf("<ContainsMeasurement()) continue; + double* wsA = (double*)pnt->GetTrParamWSA(); // inward measurement + double* wsB = (double*)pnt->GetTrParamWSB(); // outward measurement + double &yA=wsA[0],&zA=wsA[1],&sgAYY=wsA[2],&sgAYZ=wsA[3],&sgAZZ=wsA[4]; + double &yB=wsB[0],&zB=wsB[1],&sgBYY=wsB[2],&sgBYZ=wsB[3],&sgBZZ=wsB[4]; + // compute weighted average + double sgYY = sgAYY+sgBYY, sgYZ=sgAYZ+sgBYZ, sgZZ=sgAZZ+sgBZZ; + double detI = sgYY*sgZZ - sgYZ*sgYZ; + if (TMath::Abs(detI) < kAlmost0) return kFALSE; else detI = 1./detI; + double tmp = sgYY; + sgYY = sgZZ*detI; + sgZZ = tmp*detI; + sgYZ = -sgYZ*detI; + double dy=yB-yA, dz=zB-zA; + double k00=sgAYY*sgYY+sgAYZ*sgYZ, k01=sgAYY*sgYZ+sgAYZ*sgZZ; + double k10=sgAYZ*sgYY+sgAZZ*sgYZ, k11=sgAYZ*sgYZ+sgAZZ*sgZZ; + double sgAYZt=sgAYZ; + yA += dy*k00 + dz*k01; // these are smoothed predictions, stored in WSA + zA += dy*k10 + dz*k11; // + sgAYY -= k00*sgAYY + k01*sgAYZ; + sgAYZ -= k00*sgAYZt+ k01*sgAZZ; + sgAZZ -= k10*sgAYZt+ k11*sgAZZ; + // printf("|| WGH%d (%9d): | %+.2e %+.2e %+.2e %.2e %.2e\n",ip,pnt->GetSensor()->GetInternalID(), wsA[0],wsA[1],wsA[2],wsA[3],wsA[4]); + } + // + fChi2 = chifwd; + SetKalmanDone(kTRUE); + return kTRUE; +} + +//______________________________________________ +Bool_t AliAlgTrack::ProcessMaterials() +{ + // attach material effect info to alignment points + AliExternalTrackParam trc = *this; + + // collision track of cosmic lower leg: move along track direction from last (middle for cosmic lower leg) + // point (inner) to 1st one (outer) + if (fNeedInv[0]) trc.Invert(); // track needs to be inverted ? (should be for upper leg) + if (!ProcessMaterials(trc, GetInnerPointID(),0)) { +#if DEBUG>3 + AliError("Failed to process materials for leg along the track"); +#endif + return kFALSE; + } + if (IsCosmic()) { + // cosmic upper leg: move againg the track direction from middle point (inner) to last one (outer) + trc = *this; + if (fNeedInv[1]) trc.Invert(); // track needs to be inverted ? + if (!ProcessMaterials(trc, GetInnerPointID()+1,GetNPoints()-1)) { +#if DEBUG>3 + AliError("Failed to process materials for leg against the track"); +#endif + return kFALSE; + } + } + return kTRUE; +} + +//______________________________________________ +Bool_t AliAlgTrack::ProcessMaterials(AliExternalTrackParam& trc, int pFrom,int pTo) +{ + // attach material effect info to alignment points + const int kMinNStep = 3; + const double kMaxDefStep = 3.0; + const double kErrSpcT = 1e-6; + const double kErrAngT = 1e-6; + const double kErrPtIT = 1e-12; + const double kErrTiny[15] = { // initial tiny error + kErrSpcT*kErrSpcT, + 0 , kErrSpcT*kErrSpcT, + 0 , 0, kErrAngT*kErrAngT, + 0 , 0, 0, kErrAngT*kErrAngT, + 0 , 0, 0, 0, kErrPtIT*kErrPtIT + }; + /* + const double kErrSpcH = 10.0; + const double kErrAngH = 0.5; + const double kErrPtIH = 0.5; + const double kErrHuge[15] = { // initial tiny error + kErrSpcH*kErrSpcH, + 0 , kErrSpcH*kErrSpcH, + 0 , 0, kErrAngH*kErrAngH, + 0 , 0, 0, kErrAngH*kErrAngH, + 0 , 0, 0, 0, kErrPtIH*kErrPtIH + }; + */ + // + // 2 copies of the track, one will be propagated accounting for materials, other - w/o + AliExternalTrackParam tr0; + double x2X0xRho[2] = {0,0}; + double dpar[5]={0},dcov[15]={0}; + // + int pinc; + if (pTo>pFrom) { // fit in points decreasing order: cosmics upper leg + pTo++; + pinc = 1; + } + else { // fit in points increasing order: collision track or cosmics lower leg + pTo--; + pinc = -1; + } + // + for (int ip=pFrom;ip!=pTo;ip+=pinc) { // points are ordered against track direction + AliAlgPoint* pnt = GetPoint(ip); + memcpy((double*)trc.GetCovariance(),kErrTiny,15*sizeof(double)); // assign tiny errors to both tracks + tr0 = trc; + // + // printf("-> ProcMat %d (%d->%d)\n",ip,pFrom,pTo); + if (!PropagateToPoint(trc,pnt,kMinNStep, kMaxDefStep, kTRUE ,x2X0xRho)) { // with material corrections +#if DEBUG>3 + AliErrorF("Failed to take track to point %d (dir: %d -> %d) with mat.corr.",ip,pFrom,pTo); + trc.Print(); + pnt->Print("meas"); +#endif + return kFALSE; + } + // + // is there enough material to consider the point as a scatterer? + pnt->SetContainsMaterial( x2X0xRho[0]*Abs(trc.GetSigned1Pt()) > GetMinX2X0Pt2Account() ); + // + // printf("-> ProcMat000 %d (%d->%d)\n",ip,pFrom,pTo); + if (!PropagateToPoint(tr0,pnt,kMinNStep, kMaxDefStep, kFALSE,0)) { // no material corrections +#if DEBUG>3 + AliErrorF("Failed to take track to point %d (dir: %d -> %d) w/o mat.corr.",ip,pFrom,pTo); + tr0.Print(); + pnt->Print("meas"); +#endif + return kFALSE; + } + // the difference between the params, covariance of tracks with and w/o material accounting gives + // paramets and covariance of material correction. For params ONLY ELoss effect is revealed + double *cov0=(double*)tr0.GetCovariance(),*par0=(double*)tr0.GetParameter(); + double *cov1=(double*)trc.GetCovariance(),*par1=(double*)trc.GetParameter(); + for (int l=15;l--;) dcov[l] = cov1[l] - cov0[l]; + for (int l=kNKinParBON;l--;) dpar[l] = par1[l] - par0[l]; // eloss affects all parameters! + pnt->SetMatCorrExp(dpar); + //dpar[kParQ2Pt] = par1[kParQ2Pt] - par0[kParQ2Pt]; // only e-loss expectation is non-0 + // + if (pnt->ContainsMaterial()) { + // + // MP2 handles only scalar residuals hence correlated matrix of material effect need to be diagonalized + Bool_t eLossFree = pnt->GetELossVaried(); + int nParFree = eLossFree ? kNKinParBON : kNKinParBOFF; + TMatrixDSym matCov(nParFree); + for (int i=nParFree;i--;) for (int j=i+1;j--;) matCov(i,j)=matCov(j,i) = dcov[j+((i*(i+1))>>1)]; + // + TMatrixDSymEigen matDiag(matCov); // find eigenvectors + const TMatrixD& matEVec = matDiag.GetEigenVectors(); + if (!matEVec.IsValid()) { +#if DEBUG>3 + AliError("Failed to diagonalize covariance of material correction"); + matCov.Print(); + return kFALSE; +#endif + } + pnt->SetMatCovDiagonalizationMatrix(matEVec); // store diagonalization matrix + pnt->SetMatCovDiag(matDiag.GetEigenValues()); // store E.Values: diagonalized cov.matrix + if (!eLossFree) pnt->SetMatCovDiagElem(kParQ2Pt, dcov[14]); + // + //printf("Add mat%d %e %e\n",ip, x2X0xRho[0],x2X0xRho[1]); + pnt->SetX2X0(x2X0xRho[0]); + pnt->SetXTimesRho(x2X0xRho[1]); + // + } + if (pnt->ContainsMeasurement()) { // update track to have best possible kinematics + const double* yz = pnt->GetYZTracking(); + const double* errYZ = pnt->GetYZErrTracking(); + if (!trc.Update(yz,errYZ)) { +#if DEBUG>3 + AliWarningF("Failed on Update %f,%f {%f,%f,%f}",yz[0],yz[1],errYZ[0],errYZ[1],errYZ[2]); + trc.Print(); +#endif + return kFALSE; + } + // + } + // + } + // + return kTRUE; +} + +//______________________________________________ +void AliAlgTrack::SortPoints() +{ + // sort points in order against track direction: innermost point is last + // for collision tracks. + // For 2-leg cosmic tracks: 1st points of outgoing (lower) leg are added from large to + // small radii, then the points of incomint (upper) leg are added in increasing R direction + // + // The fInnerPointID will mark the id of the innermost point, i.e. the last one for collision-like + // tracks and in case of cosmics - the point of lower leg with smallest R + // + fPoints.Sort(); + int np = GetNPoints(); + fInnerPointID = np-1; + if (IsCosmic()) { + for (int ip=np;ip--;) { + AliAlgPoint* pnt = GetPoint(ip); + if (pnt->IsInvDir()) continue; // this is a point of upper leg + fInnerPointID = ip; + break; + } + } + // +} + +//______________________________________________ +void AliAlgTrack::SetLocPars(const double* pars) +{ + // store loc par corrections + memcpy(fLocParA,pars,fNLocPar*sizeof(double)); +} + +//______________________________________________ +void AliAlgTrack::CheckExpandDerGloBuffer(int minSize) +{ + // if needed, expand global derivatives buffer + if (fGloParID.GetSize() +#include +#include + +/*-------------------------------------------------------- + Track model for the alignment: AliExternalTrackParam for kinematics + proper with number of multiple scattering kinks. + Full support for derivatives and residuals calculation + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + +//#define DEBUG 4 + +class AliAlgTrack: public AliExternalTrackParam +{ + public: + + enum {kCosmicBit=BIT(14),kFieldONBit=BIT(15),kResidDoneBit=BIT(16), + kDerivDoneBit=BIT(17),kKalmanDoneBit=BIT(18)}; + enum {kNKinParBOFF=4 // N params for ExternalTrackParam part w/o field + ,kNKinParBON=5 // N params for ExternalTrackParam part with field + ,kParY = 0 // track parameters + ,kParZ + ,kParSnp + ,kParTgl + ,kParQ2Pt + }; + AliAlgTrack(); + virtual ~AliAlgTrack(); + void DefineDOFs(); + Double_t GetMass() const {return fMass;} + Double_t GetMinX2X0Pt2Account() const {return fMinX2X0Pt2Account;} + Int_t GetNPoints() const {return fPoints.GetEntriesFast();} + AliAlgPoint* GetPoint(int i) const {return (AliAlgPoint*)fPoints[i];} + void AddPoint(AliAlgPoint* p) {fPoints.AddLast(p);} + void SetMass(double m) {fMass = m;} + void SetMinX2X0Pt2Account(double v) {fMinX2X0Pt2Account = v;} + Int_t GetNLocPar() const {return fNLocPar;} + Int_t GetNLocExtPar() const {return fNLocExtPar;} + Int_t GetInnerPointID() const {return fInnerPointID;} + AliAlgPoint* GetInnerPoint() const {return GetPoint(fInnerPointID);} + // + virtual void Clear(Option_t *opt=""); + virtual void Print(Option_t *opt="") const; + virtual void DumpCoordinates() const; + // + Bool_t PropagateToPoint(AliExternalTrackParam& tr, const AliAlgPoint* pnt, + int minNSteps,double maxStep,Bool_t matCor, double* matPar=0); + Bool_t PropagateParamToPoint(AliExternalTrackParam& tr, const AliAlgPoint* pnt, double maxStep=3); // param only + Bool_t PropagateParamToPoint(AliExternalTrackParam* trSet, int nTr, const AliAlgPoint* pnt, double maxStep=3); // params only + // + Bool_t CalcResiduals(const double *params=0); + Bool_t CalcResidDeriv(double *params=0); + Bool_t CalcResidDerivGlo(AliAlgPoint* pnt); + // + Bool_t IsCosmic() const {return TestBit(kCosmicBit);} + void SetCosmic(Bool_t v=kTRUE) {SetBit(kCosmicBit,v);} + Bool_t GetFieldON() const {return TestBit(kFieldONBit);} + void SetFieldON(Bool_t v=kTRUE) {SetBit(kFieldONBit,v);} + Bool_t GetResidDone() const {return TestBit(kResidDoneBit);} + void SetResidDone(Bool_t v=kTRUE) {SetBit(kResidDoneBit,v);} + Bool_t GetDerivDone() const {return TestBit(kDerivDoneBit);} + void SetDerivDone(Bool_t v=kTRUE) {SetBit(kDerivDoneBit,v);} + Bool_t GetKalmanDone() const {return TestBit(kKalmanDoneBit);} + void SetKalmanDone(Bool_t v=kTRUE) {SetBit(kKalmanDoneBit,v);} + // + void SortPoints(); + Bool_t IniFit(); + Bool_t ResidKalman(); + Bool_t ProcessMaterials(); + Bool_t CombineTracks(AliExternalTrackParam& trcL, const AliExternalTrackParam& trcU); + // + void SetChi2(double c) {fChi2 = c;}; + Double_t GetChi2() const {return fChi2;} + void SetChi2Ini(double c) {fChi2Ini = c;}; + Double_t GetChi2Ini() const {return fChi2Ini;} + Double_t GetChi2CosmUp() const {return fChi2CosmUp;} + Double_t GetChi2CosmDn() const {return fChi2CosmDn;} + // + void ImposePtBOff(double pt) {fP[kParQ2Pt] = 1./pt;} + // propagation methods + void CopyFrom(const AliExternalTrackParam* etp); + Bool_t ApplyMatCorr(AliExternalTrackParam& trPar, const Double_t *corrDiag, const AliAlgPoint* pnt); + Bool_t ApplyMatCorr(AliExternalTrackParam* trSet, int ntr, const Double_t *corrDiaf,const AliAlgPoint* pnt); + Bool_t ApplyMatCorr(AliExternalTrackParam& trPar, const Double_t *corrpar); + // + Double_t GetResidual(int dim, int pntID) const {return fResidA[dim][pntID];} + Double_t *GetDResDLoc(int dim, int pntID) const {return &fDResDLocA[dim][pntID*fNLocPar];} + Double_t *GetDResDGlo(int dim, int id) const {return &fDResDGloA[dim][id];} + Int_t *GetGloParID() const {return fGloParIDA;} + // + void SetParams(AliExternalTrackParam& tr, double x, double alp, const double* par,Bool_t add); + void SetParams(AliExternalTrackParam* trSet, int ntr, double x, double alp, const double* par,Bool_t add); + void SetParam(AliExternalTrackParam& tr, int par, double val); + void SetParam(AliExternalTrackParam* trSet, int ntr, int par, double val); + void ModParam(AliExternalTrackParam& tr, int par, double delta); + void ModParam(AliExternalTrackParam* trSet, int ntr, int par, double delta); + // + void RichardsonDeriv(const AliExternalTrackParam* trSet, const double *delta, + const AliAlgPoint* pnt, double& derY, double& derZ); + // + const Double_t* GetLocPars() const {return fLocParA;} + void SetLocPars(const double* pars); + // + protected: + // + Bool_t CalcResidDeriv(double *params,Bool_t invert,int pFrom,int pTo); + Bool_t CalcResiduals(const double *params,Bool_t invert,int pFrom,int pTo); + Bool_t FitLeg(AliExternalTrackParam& trc, int pFrom,int pTo, Bool_t &inv); + Bool_t ProcessMaterials(AliExternalTrackParam& trc, int pFrom,int pTo); + // + void CheckExpandDerGloBuffer(int minSize); + // + static Double_t RichardsonExtrap(double *val, int ord=1); + static Double_t RichardsonExtrap(const double *val, int ord=1); + // + // ---------- dummies ---------- + AliAlgTrack(const AliAlgTrack&); + AliAlgTrack& operator=(const AliAlgTrack&); + // + protected: + + // + Int_t fNLocPar; // number of local params + Int_t fNLocExtPar; // number of local params for the external track param + Int_t fNGloPar; // number of free global parameters the track depends on + Int_t fNDF; // number of degrees of freedom + Int_t fInnerPointID; // ID of inner point in sorted track. For 2-leg cosmics - innermost point of lower leg + Bool_t fNeedInv[2]; // set if one of cosmic legs need inversion + Double_t fMinX2X0Pt2Account; // minimum X2X0/pT accumulated between 2 points worth to account + Double_t fMass; // assumed mass + Double_t fChi2; // chi2 with current residuals + Double_t fChi2CosmUp; // chi2 for cosmic upper leg + Double_t fChi2CosmDn; // chi2 for cosmic down leg + Double_t fChi2Ini; // chi2 with current residuals + TObjArray fPoints; // alignment points + TArrayD fResid[2]; // residuals array + TArrayD fDResDLoc[2]; // array for derivatives over local params + TArrayD fDResDGlo[2]; // array for derivatives over global params + TArrayD fLocPar; // local parameters array + TArrayI fGloParID; // IDs of relevant global params + Double_t *fResidA[2]; //! fast access to residuals + Double_t *fDResDLocA[2]; //! fast access to local derivatives + Double_t *fDResDGloA[2]; //! fast access to global derivatives + Int_t *fGloParIDA; //! fast access to relevant global param IDs + Double_t *fLocParA; //! fast access to local params + // + ClassDef(AliAlgTrack,2) +}; + +//____________________________________________________________________________________________ +inline void AliAlgTrack::SetParams(AliExternalTrackParam& tr, double x, double alp, const double* par,Bool_t add) +{ + // set track params + const float kDefQ2PtCosm = 1., kDefG2PtColl = 1./0.6; + tr.SetParamOnly(x,alp,par); + double *parTr = (double*) tr.GetParameter(); + if (add) { // par is correction to reference params + for (int i=kNKinParBON;i--;) parTr[i] += GetParameter()[i]; + } + if (!GetFieldON()) parTr[4] = IsCosmic() ? kDefQ2PtCosm : kDefG2PtColl; // only 4 params are valid + // +} + +//____________________________________________________________________________________________ +inline void AliAlgTrack::SetParams(AliExternalTrackParam* trSet, int ntr, double x, double alp, const double* par,Bool_t add) +{ + // set parames for multiple tracks (VECTORIZE THIS) + if (!add) { // full parameter supplied + for (int itr=ntr;itr--;) SetParams(trSet[itr],x,alp,par,kFALSE); + return; + } + double partr[kNKinParBON]={0}; // par is a correction to reference parameter + for (int i=fNLocExtPar;i--;) partr[i] = GetParameter()[i] + par[i]; + for (int itr=ntr;itr--;) SetParams(trSet[itr],x,alp,partr,kFALSE); +} + +//____________________________________________________________________________________________ +inline void AliAlgTrack::SetParam(AliExternalTrackParam& tr, int par, double val) +{ + // set track parameter + ((double*)tr.GetParameter())[par] = val; +} + +//____________________________________________________________________________________________ +inline void AliAlgTrack::SetParam(AliExternalTrackParam* trSet, int ntr, int par, double val) +{ + // set parames for multiple tracks (VECTORIZE THIS) + for (int itr=ntr;itr--;) ((double*)trSet[itr].GetParameter())[par] = val; +} + +//____________________________________________________________________________________________ +inline void AliAlgTrack::ModParam(AliExternalTrackParam & tr, int par, double delta) +{ + // modify track parameter + ((double*)tr.GetParameter())[par] += delta; +} + +//____________________________________________________________________________________________ +inline void AliAlgTrack::ModParam(AliExternalTrackParam* trSet, int ntr, int par, double delta) +{ + // modify track parameter (VECTORIZE THOS) + for (int itr=ntr;itr--;) ModParam(trSet[itr],par,delta); +} + +//______________________________________________ +inline void AliAlgTrack::CopyFrom(const AliExternalTrackParam* etp) +{ + // assign kinematics + Set(etp->GetX(),etp->GetAlpha(),etp->GetParameter(),etp->GetCovariance()); +} + + +#endif diff --git a/Detectors/Align/AliAlgVol.cxx b/Detectors/Align/AliAlgVol.cxx new file mode 100644 index 0000000000000..f43354efaf52d --- /dev/null +++ b/Detectors/Align/AliAlgVol.cxx @@ -0,0 +1,837 @@ +/************************************************************************** + * 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. * + **************************************************************************/ + +/* + Alignment formalism: + + Vector l in the local frame of the volume_j (assuming hierarchy of nested volumes 0...J + from most coarse to the end volume) is transformed to master frame vector + g = G_j*l_j + Matrix G_j is Local2Global matrix (L2G in the code). If the volume has a parent + volume j-1, the global vector g can be transformed to the local volume of j-1 as + l_{j-1} = G^-1_{j-1}* g + Hence, the transormation from volume j to j-1 is + l_{j-1} = G^-1_{j-1}*G_j l_j = R_j*l_j + + The alignment corrections in general can be defined either as a + + 1) local delta: l'_j = delta_j * l_j + hence g' = G_j * delta_j = G'_j*l_j + or as + 2) global Delta: g' = Delta_j * G_j * l_j = G'_j*l_j + + Hence Delta and delta are linked as + Delta_j = G_j delta_j G^-1_j + delta_j = G^-1_j Delta_j G_j + + In case the whole chain of nested volumes is aligned, the corrections pile-up as: + + G_0*delta_0 ... G^-1_{j-2}*G_{j-1}*delta_{j-1}*G^-1_{j-1}*G_j*delta_j = + Delta_0 * Delta_{1} ... Delta_{j-1}*Delta_{j}... * G_j + + -> Delta_j = G'_{j-1} * G^-1_{j-1} * G_j * G'^-1_j + where G and G' are modified and original L2G matrices + + + From this by induction one gets relation between local and global deltas: + + Delta_j = Z_j * delta_j * Z^-1_j + + where Z_j = [ Prod_{k=0}^{j-1} (G_k * delta_k * G^-1_k) ] * G_j + + By convention, aliroot aligment framework stores global Deltas ! + + In case the geometry was already prealigned by PDelta_j matrices, the result + of the new incremental alignment Delta_j must be combined with PDelta_j to + resulting matrix TDelta_j before writing new alignment object. + + Derivation: if G_j and IG_j are final and ideal L2G matrices for level j, then + + G_j = TDelta_j * TDelta_{j-1} ... TDelta_0 * IG_j + = (Delta_j * Delta_{j-1} ... Delta_0) * (PDelta_j * PDelta_{j-1} ... PDelta_0) * IG_j + + Hence: + TDelta_j = [Prod_{i=j}^0 Delta_i ] * [Prod_{k=j}^0 PDelta_k ] * [Prod_{l=0}^{j-1} TDelta_l] + + By induction we get combination rule: + + TDelta_j = Delta_j * X_{j-1} * PDelta_j * X^-1_{j-1} + + where X_i = Delta_i * Delta_{i-1} ... Delta_0 + + --------------------------------- + + This alignment framework internally allows to find geometry corrections either in the + volume LOCAL frame or in its TRACKING frame. The latter is defined for sensors as + lab frame, rotated by the angle alpha in such a way that the X axis is normal to the + sensor plane (note, that for ITS the rotated X axis origin is also moved to the sensor) + For the non-sensor volumes the TRACKING frame is defined by rotation of the lab frame + with the alpha angle = average angle of centers of its children, seen from the origin. + + The TRACKING and IDEAL LOCAL (before misalignment) frames are related by the + tracking-to-local matrix (T2L in the code), i.e. the vectors in local and tracking frames + are related as + l = T2L * t + + The alignment can be done using both frames for different volumes of the same geometry + branch. + The alignments deltas in local and tracking frames are related as: + + l' = T2L * delta_t * t + l' = delta_l * T2L * t + -> delta_l = T2L * delta_t * T2L^-1 + + */ + + +#include "AliAlgVol.h" +#include "AliAlgDOFStat.h" +#include "AliAlgConstraint.h" +#include "AliAlignObjParams.h" +#include "AliGeomManager.h" +#include "AliAlgAux.h" +#include "AliLog.h" +#include +#include +#include +#include +#include +#include +#include + +ClassImp(AliAlgVol) + +using namespace TMath; +using namespace AliAlgAux; + +const char* AliAlgVol::fgkFrameName[AliAlgVol::kNVarFrames] = {"LOC","TRA"}; +// +UInt_t AliAlgVol::fgDefGeomFree = + kDOFBitTX | kDOFBitTY | kDOFBitTZ | kDOFBitPS | kDOFBitTH | kDOFBitPH; +// +const char* AliAlgVol::fgkDOFName[AliAlgVol::kNDOFGeom]={"TX","TY","TZ","PSI","THT","PHI"}; + +//_________________________________________________________ +AliAlgVol::AliAlgVol(const char* symname, int iid) : + TNamed(symname,"") + ,fVarFrame(kTRA) + ,fIntID(iid) + ,fX(0) + ,fAlp(0) + ,fNDOFs(0) + ,fDOF(0) + ,fNDOFGeomFree(0) + ,fNDOFFree(0) + ,fConstrChild(kDefChildConstr) + // + ,fParent(0) + ,fChildren(0) + // + ,fNProcPoints(0) + ,fFirstParGloID(-1) + ,fParVals(0) + ,fParErrs(0) + ,fParLabs(0) + // + ,fMatL2GReco() + ,fMatL2G() + ,fMatL2GIdeal() + ,fMatT2L() + ,fMatDeltaRefGlo() +{ + // def c-tor + SetVolID(0); // volumes have no VID, unless it is sensor + if (symname) { // real volumes have at least geometric degrees of freedom + SetNDOFs(kNDOFGeom); + } + SetFreeDOFPattern(fgDefGeomFree); +} + +//_________________________________________________________ +AliAlgVol::~AliAlgVol() +{ + // d-tor + delete fChildren; +} + +//_________________________________________________________ +void AliAlgVol::Delta2Matrix(TGeoHMatrix& deltaM, const Double_t *delta) const +{ + // prepare delta matrix for the volume from its + // local delta vector (AliAlignObj convension): dx,dy,dz,,theta,psi,phi + const double *tr=&delta[0],*rt=&delta[3]; // translation(cm) and rotation(degree) + AliAlignObjParams tempAlignObj; + tempAlignObj.SetRotation(rt[0],rt[1],rt[2]); + tempAlignObj.SetTranslation(tr[0],tr[1],tr[2]); + tempAlignObj.GetMatrix(deltaM); + // +} + + +//__________________________________________________________________ +void AliAlgVol::GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t *delta) const +{ + // prepare the variation matrix tau in volume TRACKING frame by applying + // local delta of modification of LOCAL frame: + // tra' = tau*tra = tau*T2L^-1*loc = T2L^-1*loc' = T2L^-1*delta*loc + // tau = T2L^-1*delta*T2L + Delta2Matrix(matMod, delta); + matMod.Multiply(&GetMatrixT2L()); + const TGeoHMatrix& t2li = GetMatrixT2L().Inverse(); + matMod.MultiplyLeft(&t2li); +} + +//__________________________________________________________________ +void AliAlgVol::GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t *delta, const TGeoHMatrix& relMat) const +{ + // prepare the variation matrix tau in volume TRACKING frame by applying + // local delta of modification of LOCAL frame of its PARENT; + // The relMat is matrix for transformation from child to parent frame: LOC = relMat*loc + // + // tra' = tau*tra = tau*T2L^-1*loc = T2L^-1*loc' = T2L^-1*relMat^-1*Delta*relMat*loc + // tau = (relMat*T2L)^-1*Delta*(relMat*T2L) + Delta2Matrix(matMod, delta); + TGeoHMatrix tmp = relMat; + tmp *= GetMatrixT2L(); + matMod.Multiply(&tmp); + const TGeoHMatrix& tmpi = tmp.Inverse(); + matMod.MultiplyLeft(&tmpi); +} + +//__________________________________________________________________ +void AliAlgVol::GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const Double_t *delta) const +{ + // prepare the variation matrix tau in volume TRACKING frame by applying + // local delta of modification of the same TRACKING frame: + // tra' = tau*tra + Delta2Matrix(matMod, delta); +} + +//__________________________________________________________________ +void AliAlgVol::GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const Double_t *delta, const TGeoHMatrix& relMat) const +{ + // prepare the variation matrix tau in volume TRACKING frame by applying + // local delta of modification of TRACKING frame of its PARENT; + // The relMat is matrix for transformation from child to parent frame: TRA = relMat*tra + // (see DPosTraDParGeomTRA) + // + // tra' = tau*tra = tau*relMat^-1*TRA = relMat^-1*TAU*TRA = relMat^-1*TAU*relMat*tra + // tau = relMat^-1*TAU*relMat + Delta2Matrix(matMod, delta); // TAU + matMod.Multiply(&relMat); + const TGeoHMatrix& reli = relMat.Inverse(); + matMod.MultiplyLeft(&reli); +} + +//_________________________________________________________ +Int_t AliAlgVol::CountParents() const +{ + // count parents in the chain + int cnt = 0; + const AliAlgVol* p = this; + while( (p=p->GetParent()) ) cnt++; + return cnt; +} + +//____________________________________________ +void AliAlgVol::Print(const Option_t *opt) const +{ + // print info + TString opts = opt; + opts.ToLower(); + printf("Lev:%2d IntID:%7d %s | %2d nodes | Effective X:%8.4f Alp:%+.4f | Used Points: %d\n", + CountParents(),GetInternalID(),GetSymName(),GetNChildren(),fX,fAlp,fNProcPoints); + printf(" DOFs: Tot: %d (offs: %5d) Free: %d Geom: %d {",fNDOFs,fFirstParGloID,fNDOFFree,fNDOFGeomFree); + for (int i=0;iGetAlignableEntry(path)) { + const TGeoHMatrix* l2g = AliGeomManager::GetMatrix(path); + if (!l2g) AliFatalF("Failed to find L2G matrix for alignable %s",path); + reco ? SetMatrixL2GReco(*l2g) : SetMatrixL2G(*l2g); + } + else { // extract from path + if (!gGeoManager->CheckPath(path)) AliFatalF("Volume path %s not valid!",path); + TGeoPhysicalNode* node = (TGeoPhysicalNode*)gGeoManager->GetListOfPhysicalNodes()->FindObject(path); + TGeoHMatrix l2g; + if (!node) { + AliWarningF("Attention: volume %s was not misaligned, extracting original matrix",path); + if (!AliGeomManager::GetOrigGlobalMatrix(path,l2g)) { + AliFatalF("Failed to find ideal L2G matrix for %s",path); + } + } + else { + l2g = *node->GetMatrix(); + } + reco ? SetMatrixL2GReco(l2g) : SetMatrixL2G(l2g); + } + // +} + +//____________________________________________ +void AliAlgVol::PrepareMatrixL2GIdeal() +{ + // extract from geometry ideal L2G matrix + TGeoHMatrix mtmp; + if (!AliGeomManager::GetOrigGlobalMatrix(GetSymName(),mtmp)) + AliFatalF("Failed to find ideal L2G matrix for %s",GetSymName()); + SetMatrixL2GIdeal(mtmp); + // +} + +//____________________________________________ +void AliAlgVol::PrepareMatrixT2L() +{ + // for non-sensors we define the fake tracking frame with the alpha angle being + // the average angle of centers of its children + // + double tot[3]={0,0,0},loc[3]={0,0,0},glo[3]; + int nch = GetNChildren(); + for (int ich=nch;ich--;) { + AliAlgVol* vol = GetChild(ich); + vol->GetMatrixL2GIdeal().LocalToMaster(loc,glo); + for (int j=3;j--;) tot[j] += glo[j]; + } + if (nch) for (int j=3;j--;) tot[j] /= nch; + // + fAlp = TMath::ATan2(tot[1],tot[0]); + AliAlgAux::BringToPiPM(fAlp); + // + fX = TMath::Sqrt(tot[0]*tot[0]+tot[1]*tot[1]); + // + // 1st create Tracking to Global matrix + fMatT2L.Clear(); + fMatT2L.SetDx(fX); + fMatT2L.RotateZ(fAlp*RadToDeg()); + // then convert it to Tracking to Local matrix + const TGeoHMatrix& l2gi = GetMatrixL2GIdeal().Inverse(); + fMatT2L.MultiplyLeft(&l2gi); + // +} + +//____________________________________________ +void AliAlgVol::SetMatrixT2L(const TGeoHMatrix& m) +{ + // set the T2L matrix and define tracking frame + // Note that this method is used for the externally set matrices + // (in case of sensors). For other volumes the tracking frame and matrix + // is defined in the PrepareMatrixT2L method + fMatT2L = m; + SetTrackingFrame(); +} + +//__________________________________________________________________ +void AliAlgVol::SetTrackingFrame() +{ + // Define tracking frame of the sensor + // This method should be implemented for sensors, which receive the T2L + // matrix from the geometry + AliErrorF("Volume %s was supposed to implement its own method",GetName()); +} + +//__________________________________________________________________ +void AliAlgVol::AssignDOFs(Int_t &cntDOFs, Float_t *pars, Float_t *errs, Int_t *labs) +{ + // Assigns offset of the DOFS of this volume in global array of DOFs, attaches arrays to volumes + // + fParVals = pars + cntDOFs; + fParErrs = errs + cntDOFs; + fParLabs = labs + cntDOFs; + SetFirstParGloID(cntDOFs); + for (int i=0;iAssignDOFs(cntDOFs,pars,errs,labs); + // + return; +} + +//__________________________________________________________________ +void AliAlgVol::InitDOFs() +{ + // initialize degrees of freedom + // + // Do we need this strict condition? + if (GetInitDOFsDone()) AliFatalF("Something is wrong, DOFs are already initialized for %s",GetName()); + for (int i=0;iSetOwner(kFALSE); + } + fChildren->AddLast(ch); +} + +//__________________________________________________________________ +void AliAlgVol::SetParVals(Int_t npar,Double_t *vl,Double_t *er) +{ + // set parameters + if (npar>fNDOFs) AliFatalF("Volume %s has %d dofs",GetName(),fNDOFs); + for (int i=0;iFinalizeStat(st); + } + if (st) FillDOFStat(st); + return fNProcPoints; +} + +//______________________________________________________ +void AliAlgVol::WritePedeInfo(FILE* parOut,const Option_t *opt) const +{ + // contribute to params template file for PEDE + enum {kOff,kOn,kOnOn}; + const char* comment[3] = {" ","! ","!!"}; + const char* kKeyParam = "parameter"; + TString opts = opt; + opts.ToLower(); + Bool_t showDef = opts.Contains("d"); // show free DOF even if not preconditioned + Bool_t showFix = opts.Contains("f"); // show DOF even if fixed + Bool_t showNam = opts.Contains("n"); // show volume name even if no nothing else is printable + // + // is there something to print ? + int nCond(0),nFix(0),nDef(0); + for (int i=0;i0 || nFix>0 ? kOff:kOn; // do we comment the "parameter" keyword for this volume + if (!nFix) showFix = kFALSE; + if (!nDef) showDef = kFALSE; + // + if (nCond || showDef || showFix || showNam) + fprintf(parOut,"%s%s %s\t\tDOF/Free: %d/%d (%s) %s\n",comment[cmt],kKeyParam,comment[kOnOn], + GetNDOFs(),GetNDOFFree(),fgkFrameName[fVarFrame],GetName()); + // + if (nCond || showDef || showFix) { + for (int i=0;iWritePedeInfo(parOut,opt); + // +} + +//_________________________________________________________________ +void AliAlgVol::CreateGloDeltaMatrix(TGeoHMatrix &deltaM) const +{ + // Create global matrix deltaM from fParVals array containing corrections. + // This deltaM does not account for eventual prealignment + // Volume knows if its variation was done in TRA or LOC frame + // + CreateLocDeltaMatrix(deltaM); + const TGeoHMatrix& l2g = GetMatrixL2G(); + const TGeoHMatrix& l2gi = l2g.Inverse(); + deltaM.Multiply(&l2gi); + deltaM.MultiplyLeft(&l2g); + // +} + +/* +//_________________________________________________________________ +void AliAlgVol::CreateGloDeltaMatrix(TGeoHMatrix &deltaM) const +{ + // Create global matrix deltaM from fParVals array containing corrections. + // This deltaM does not account for eventual prealignment + // Volume knows if its variation was done in TRA or LOC frame + // + // deltaM = Z * deltaL * Z^-1 + // where deltaL is local correction matrix and Z is matrix defined as + // Z = [ Prod_{k=0}^{j-1} G_k * deltaL_k * G^-1_k ] * G_j + // with j=being the level of the volume in the hierarchy + // + CreateLocDeltaMatrix(deltaM); + TGeoHMatrix zMat = GetMatrixL2G(); + const AliAlgVol* par = this; + while( (par=par->GetParent()) ) { + TGeoHMatrix locP; + par->CreateLocDeltaMatrix(locP); + locP.MultiplyLeft( &par->GetMatrixL2G() ); + locP.Multiply( &par->GetMatrixL2G().Inverse() ); + zMat.MultiplyLeft( &locP ); + } + deltaM.MultiplyLeft( &zMat ); + deltaM.Multiply( &zMat.Inverse() ); + // +} +*/ + +//_________________________________________________________________ +void AliAlgVol::CreatePreGloDeltaMatrix(TGeoHMatrix &deltaM) const +{ + // Create prealignment global matrix deltaM from prealigned G and + // original GO local-to-global matrices + // + // From G_j = Delta_j * Delta_{j-1} ... Delta_0 * GO_j + // where Delta_j is global prealignment matrix for volume at level j + // we get by induction + // Delta_j = G_j * GO^-1_j * GO_{j-1} * G^-1_{j-1} + // + deltaM = GetMatrixL2G(); + deltaM *= GetMatrixL2GIdeal().Inverse(); + const AliAlgVol* par = GetParent(); + if (par) { + deltaM *= par->GetMatrixL2GIdeal(); + deltaM *= par->GetMatrixL2G().Inverse(); + } + // +} + +/* + // this is an alternative lengthy way ! +//_________________________________________________________________ +void AliAlgVol::CreatePreGloDeltaMatrix(TGeoHMatrix &deltaM) const +{ + // Create prealignment global matrix deltaM from prealigned G and + // original GO local-to-global matrices + // + // From G_j = Delta_j * Delta_{j-1} ... Delta_0 * GO_j + // where Delta_j is global prealignment matrix for volume at level j + // we get by induction + // Delta_j = G_j * GO^-1_j * GO_{j-1} * G^-1_{j-1} + // + CreatePreLocDeltaMatrix(deltaM); + TGeoHMatrix zMat = GetMatrixL2GIdeal(); + const AliAlgVol* par = this; + while( (par=par->GetParent()) ) { + TGeoHMatrix locP; + par->CreatePreLocDeltaMatrix(locP); + locP.MultiplyLeft( &par->GetMatrixL2GIdeal() ); + locP.Multiply( &par->GetMatrixL2GIdeal().Inverse() ); + zMat.MultiplyLeft( &locP ); + } + deltaM.MultiplyLeft( &zMat ); + deltaM.Multiply( &zMat.Inverse() ); + // +} +*/ + +//_________________________________________________________________ +void AliAlgVol::CreatePreLocDeltaMatrix(TGeoHMatrix &deltaM) const +{ + // Create prealignment local matrix deltaM from prealigned G and + // original GO local-to-global matrices + // + // From G_j = GO_0 * delta_0 * GO^-1_0 * GO_1 * delta_1 ... GO^-1_{j-1}*GO_{j}*delta_j + // where delta_j is local prealignment matrix for volume at level j + // we get by induction + // delta_j = GO^-1_j * GO_{j-1} * G^-1_{j-1} * G^_{j} + // + const AliAlgVol* par = GetParent(); + deltaM = GetMatrixL2GIdeal().Inverse(); + if (par) { + deltaM *= par->GetMatrixL2GIdeal(); + deltaM *= par->GetMatrixL2G().Inverse(); + } + deltaM *= GetMatrixL2G(); + // +} + +//_________________________________________________________________ +void AliAlgVol::CreateLocDeltaMatrix(TGeoHMatrix &deltaM) const +{ + // Create local matrix deltaM from fParVals array containing corrections. + // This deltaM does not account for eventual prealignment + // Volume knows if its variation was done in TRA or LOC frame + double corr[kNDOFGeom]; + for (int i=kNDOFGeom;i--;) corr[i] = fParVals[i]; // we need doubles + Delta2Matrix(deltaM,corr); + if (IsFrameTRA()) { // we need corrections in local frame! + // l' = T2L * delta_t * t = T2L * delta_t * T2L^-1 * l = delta_l * l + // -> delta_l = T2L * delta_t * T2L^-1 + const TGeoHMatrix& t2l = GetMatrixT2L(); + const TGeoHMatrix& t2li = t2l.Inverse(); + deltaM.Multiply( &t2li ); + deltaM.MultiplyLeft( &t2l ); + } + // +} + +//_________________________________________________________________ +void AliAlgVol::CreateAlignmenMatrix(TGeoHMatrix& alg) const +{ + // create final alignment matrix, accounting for eventual prealignment + // + // if the correction for this volume at level j is TAU (global delta) then the combined + // correction (accounting for reference prealignment) is + // (Delta_0 * .. Delta_{j-1})^-1 * TAU ( Delta_0 * .. Delta_j) + // where Delta_i is prealigment global delta of volume i (0 is top) + // In principle, it can be obtained as: + // GIdeal_{j-1} * G_{j-1}^-1 * TAU * G_{j}^-1 * GIdeal_{j}^-1 + // where G_i is pre-misaligned reference L2G and GIdeal_i is L2GIdeal, + // but this creates precision problem. + // Therefore we use explicitly cached Deltas from prealignment object. + // + CreateGloDeltaMatrix(alg); + // + const AliAlgVol* par = GetParent(); + if (par) { + TGeoHMatrix dchain; + while (par) { + dchain.MultiplyLeft(&par->GetGlobalDeltaRef()); + par = par->GetParent(); + } + const TGeoHMatrix& dchaini = dchain.Inverse(); + alg.Multiply(&dchain); + alg.MultiplyLeft(&dchaini); + } + alg *= GetGlobalDeltaRef(); + + + /* // bad precision ? + alg.Multiply(&GetMatrixL2G()); + alg.Multiply(&GetMatrixL2GIdeal().Inverse()); + if (par) { + alg.MultiplyLeft(&par->GetMatrixL2G().Inverse()); + alg.MultiplyLeft(&par->GetMatrixL2GIdeal()); + } + */ + // +} + + /* +//_________________________________________________________________ +void AliAlgVol::CreateAlignmenMatrix(TGeoHMatrix& alg) const +{ + // create final alignment matrix, accounting for eventual prealignment + // + // deltaGlo_j * X_{j-1} * PdeltaGlo_j * X^-1_{j-1} + // + // where deltaGlo_j is global alignment matrix for this volume at level j + // of herarchy, obtained from CreateGloDeltaMatrix. + // PdeltaGlo_j is prealignment global matrix and + // X_i = deltaGlo_i * deltaGlo_{i-1} .. deltaGle_0 + // + TGeoHMatrix delGloPre,matX; + CreateGloDeltaMatrix(alg); + CreatePreGloDeltaMatrix(delGloPre); + const AliAlgVol* par = this; + while( (par=par->GetParent()) ) { + TGeoHMatrix parDelGlo; + par->CreateGloDeltaMatrix(parDelGlo); + matX *= parDelGlo; + } + alg *= matX; + alg *= delGloPre; + alg *= matX.Inverse(); + // +} +*/ + +//_________________________________________________________________ +void AliAlgVol::CreateAlignmentObjects(TClonesArray* arr) const +{ + // add to supplied array alignment object for itself and children + TClonesArray& parr = *arr; + TGeoHMatrix algM; + CreateAlignmenMatrix(algM); + new(parr[parr.GetEntriesFast()]) AliAlignObjParams(GetName(),GetVolID(),algM,kTRUE); + int nch = GetNChildren(); + for (int ich=0;ichCreateAlignmentObjects(arr); + // +} + +//_________________________________________________________________ +void AliAlgVol::UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix *cumulDelta) +{ + // recreate fMatL2GReco matrices from ideal L2G matrix and alignment objects + // used during data reconstruction. For the volume at level J we have + // L2G' = Delta_J * Delta_{J-1} *...* Delta_0 * L2GIdeal + // cumulDelta is Delta_{J-1} * ... * Delta_0, supplied by the parent + // + fMatL2GReco = fMatL2GIdeal; + // find alignment object for this volume + int nalg = algArr->GetEntriesFast(); + const AliAlignObjParams* par = 0; + for (int i=0;iAt(i); + if (!strcmp(par->GetSymName(),GetSymName())) break; + par = 0; + } + TGeoHMatrix delta; + if (!par) AliInfoF("Alignment for %s is absent in Reco-Time alignment object",GetSymName()); + else par->GetMatrix(delta); + if (cumulDelta) delta *= *cumulDelta; + // + fMatL2GReco.MultiplyLeft(&delta); + // propagate to children + for (int ich=GetNChildren();ich--;) GetChild(ich)->UpdateL2GRecoMatrices(algArr,&delta); + // +} + +//______________________________________________________ +Bool_t AliAlgVol::OwnsDOFID(Int_t id) const +{ + // check if DOF ID belongs to this volume or its children + if (id>=fFirstParGloID && idOwnsDOFID(id)) return kTRUE; + } + return kFALSE; +} + +//______________________________________________________ +AliAlgVol* AliAlgVol::GetVolOfDOFID(Int_t id) const +{ + // gets volume owning this DOF ID + if (id>=fFirstParGloID && idGetVolOfDOFID(id)) ) return vol; + } + return 0; +} + +//______________________________________________________ +const char* AliAlgVol::GetDOFName(int i) const +{ + // get name of DOF + return GetGeomDOFName(i); +} + +//______________________________________________________ +void AliAlgVol::FillDOFStat(AliAlgDOFStat* h) const +{ + // fill statistics info hist + if (!h) return; + int ndf = GetNDOFs(); + int dof0 = GetFirstParGloID(); + int stat = GetNProcessedPoints(); + for (int idf=0;idfAddStat(dof,stat); + } +} + +//________________________________________ +void AliAlgVol::AddAutoConstraints(TObjArray* constrArr) +{ + // adds automatic constraints + int nch = GetNChildren(); + // + if (HasChildrenConstraint()) { + AliAlgConstraint* constr = new AliAlgConstraint(); + constr->SetConstrainPattern(fConstrChild); + constr->SetParent(this); + for (int ich=nch;ich--;) { + AliAlgVol* child = GetChild(ich); + if (child->GetExcludeFromParentConstraint()) continue; + constr->AddChild(child); + } + if (constr->GetNChildren()) constrArr->Add(constr); + else delete constr; + } + // + for (int ich=0;ichAddAutoConstraints(constrArr); + // +} diff --git a/Detectors/Align/AliAlgVol.h b/Detectors/Align/AliAlgVol.h new file mode 100644 index 0000000000000..8ce0ea09adf55 --- /dev/null +++ b/Detectors/Align/AliAlgVol.h @@ -0,0 +1,214 @@ +#ifndef ALIALGVOL_H +#define ALIALGVOL_H + +#include +#include +#include +#include + +class TObjArray; +class TClonesArray; +class AliAlgDOFStat; +class TH1; + + +/*-------------------------------------------------------- + Base class of alignable volume. Has at least geometric + degrees of freedom + user defined calibration DOFs. + The name provided to constructor must be the SYMNAME which + AliGeomManager can trace to geometry. + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + + +class AliAlgVol : public TNamed +{ + public: + enum DOFGeom_t {kDOFTX,kDOFTY,kDOFTZ,kDOFPS,kDOFTH,kDOFPH,kNDOFGeom,kAllGeomDOF=0x3F}; + enum {kDOFBitTX=BIT(kDOFTX),kDOFBitTY=BIT(kDOFTY),kDOFBitTZ=BIT(kDOFTZ), + kDOFBitPS=BIT(kDOFPS),kDOFBitTH=BIT(kDOFTH),kDOFBitPH=BIT(kDOFPH)}; + enum {kNDOFMax=32}; + enum Frame_t {kLOC,kTRA,kNVarFrames}; // variation frames defined + enum {kInitDOFsDoneBit=BIT(14),kSkipBit=BIT(15),kExclFromParentConstraintBit=BIT(16)}; + enum {kDefChildConstr=0xff}; + // + AliAlgVol(const char* symname=0, int iid=0); + virtual ~AliAlgVol(); + // + const char* GetSymName() const {return GetName();} + // + Int_t GetVolID() const {return (Int_t)GetUniqueID();} + void SetVolID(Int_t v) {SetUniqueID(v);} + Int_t GetInternalID() const {return fIntID;} + void SetInternalID(Int_t v) {fIntID = v;} + // + // + void AssignDOFs(Int_t &cntDOFs, Float_t *pars, Float_t *errs, Int_t *labs); + void InitDOFs(); + // + Frame_t GetVarFrame() const {return fVarFrame;} + void SetVarFrame(Frame_t f) {fVarFrame = f;} + Bool_t IsFrameTRA() const {return fVarFrame == kTRA;} + Bool_t IsFrameLOC() const {return fVarFrame == kLOC;} + // + void SetFreeDOF(Int_t dof) {fDOF |= 0x1<AddChild(this);} + Int_t CountParents() const; + // + Int_t GetNChildren() const {return fChildren ? fChildren->GetEntriesFast():0;} + AliAlgVol* GetChild(int i) const {return fChildren ? (AliAlgVol*)fChildren->UncheckedAt(i):0;} + virtual void AddChild(AliAlgVol* ch); + // + Double_t GetXTracking() const {return fX;} + Double_t GetAlpTracking() const {return fAlp;} + // + Int_t GetNProcessedPoints() const {return fNProcPoints;} + virtual Int_t FinalizeStat(AliAlgDOFStat* h=0); + void FillDOFStat(AliAlgDOFStat* h) const; + // + Float_t* GetParVals() const {return fParVals;} + Double_t GetParVal(int par) const {return fParVals[par];} + Double_t GetParErr(int par) const {return fParErrs[par];} + Int_t GetParLab(int par) const {return fParLabs[par];} + void GetParValGeom(double* delta) const {for (int i=kNDOFGeom;i--;) delta[i]=fParVals[i];} + // + void SetParVals(Int_t npar,Double_t *vl,Double_t *er); + void SetParVal(Int_t par,Double_t v=0) {fParVals[par] = v;} + void SetParErr(Int_t par,Double_t e=0) {fParErrs[par] = e;} + // + Int_t GetNDOFs() const {return fNDOFs;} + Int_t GetNDOFFree() const {return fNDOFFree;} + Int_t GetNDOFGeomFree() const {return fNDOFGeomFree;} + Int_t GetFirstParGloID() const {return fFirstParGloID;} + Int_t GetParGloID(Int_t par) const {return fFirstParGloID+par;} + void SetFirstParGloID(Int_t id) {fFirstParGloID=id;} + // + virtual void PrepareMatrixT2L(); + virtual void SetTrackingFrame(); + // + const TGeoHMatrix& GetMatrixL2G() const {return fMatL2G;} + const TGeoHMatrix& GetMatrixL2GIdeal() const {return fMatL2GIdeal;} + const TGeoHMatrix& GetMatrixL2GReco() const {return fMatL2GReco;} + const TGeoHMatrix& GetGlobalDeltaRef() const {return fMatDeltaRefGlo;} + void SetMatrixL2G(const TGeoHMatrix& m) {fMatL2G = m;} + void SetMatrixL2GIdeal(const TGeoHMatrix& m) {fMatL2GIdeal = m;} + void SetMatrixL2GReco(const TGeoHMatrix& m) {fMatL2GReco = m;} + void SetGlobalDeltaRef(TGeoHMatrix& mat) {fMatDeltaRefGlo = mat;} + // + virtual void PrepareMatrixL2G(Bool_t reco=kFALSE); + virtual void PrepareMatrixL2GIdeal(); + virtual void UpdateL2GRecoMatrices(const TClonesArray* algArr,const TGeoHMatrix* cumulDelta); + // + void GetMatrixT2G(TGeoHMatrix& m) const; + // + const TGeoHMatrix& GetMatrixT2L() const {return fMatT2L;} + void SetMatrixT2L(const TGeoHMatrix& m); + // + void Delta2Matrix(TGeoHMatrix& deltaM, const Double_t *delta) const; + // + // preparation of variation matrices + void GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t *delta) const; + void GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const Double_t *delta) const; + void GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t *delta, const TGeoHMatrix& relMat) const; + void GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const Double_t *delta, const TGeoHMatrix& relMat) const; + // + // creation of global matrices for storage + void CreateGloDeltaMatrix(TGeoHMatrix& deltaM) const; + void CreateLocDeltaMatrix(TGeoHMatrix& deltaM) const; + void CreatePreGloDeltaMatrix(TGeoHMatrix &deltaM) const; + void CreatePreLocDeltaMatrix(TGeoHMatrix &deltaM) const; + void CreateAlignmenMatrix(TGeoHMatrix& alg) const; + void CreateAlignmentObjects(TClonesArray* arr) const; + // + void SetSkip(Bool_t v=kTRUE) {SetBit(kSkipBit,v);} + Bool_t GetSkip() const {return TestBit(kSkipBit);} + // + void ExcludeFromParentConstraint(Bool_t v=kTRUE) {SetBit(kExclFromParentConstraintBit,v);} + Bool_t GetExcludeFromParentConstraint() const {return TestBit(kExclFromParentConstraintBit);} + // + void SetInitDOFsDone() {SetBit(kInitDOFsDoneBit);} + Bool_t GetInitDOFsDone() const {return TestBit(kInitDOFsDoneBit);} + // + Bool_t OwnsDOFID(Int_t id) const; + AliAlgVol* GetVolOfDOFID(Int_t id) const; + // + virtual Bool_t IsSensor() const {return kFALSE;} + // + virtual const char* GetDOFName(int i) const; + virtual void Print(const Option_t *opt="") const; + virtual void WritePedeInfo(FILE* parOut, const Option_t *opt="") const; + // + static const char* GetGeomDOFName(int i) {return i + +using namespace TMath; + +ClassImp(AliAlgVtx) + +//_________________________________________________________ +AliAlgVtx::AliAlgVtx() : AliAlgSens("Vertex",0,1) +{ + // def c-tor + SetVarFrame(kLOC); + SetFreeDOFPattern( BIT(kDOFTX) | BIT(kDOFTY) | BIT(kDOFTZ) ); + // +} + +//____________________________________________ +void AliAlgVtx::PrepareMatrixT2L() +{ + // T2L matrix for vertex needs to be adjusted for every track + // in order to have X axis along the track direction. + // This method assumes that the fAlp was already set accordingly + // fX is fixed to 0 + // + fMatT2L.Clear(); + fMatT2L.RotateZ(fAlp*RadToDeg()); + // fMatT2L.MultiplyLeft(&GetMatrixL2GIdeal().Inverse()); L2G=I !!! + // +} + +//____________________________________________ +void AliAlgVtx::ApplyCorrection(double* vtx) const +{ + // apply eventual correction to supplied vertex position + vtx[kDOFTX] += GetParVal(kDOFTX); + vtx[kDOFTY] += GetParVal(kDOFTY); + vtx[kDOFTZ] += GetParVal(kDOFTZ); + // +} + +//____________________________________________ +AliAlgPoint* AliAlgVtx::TrackPoint2AlgPoint(int, const AliTrackPointArray*, const AliESDtrack*) +{ + // convert the pntId-th point to AliAlgPoint + static int cnt=0; + AliErrorF("This method shound not have been called, %d",cnt++); + return 0; +} diff --git a/Detectors/Align/AliAlgVtx.h b/Detectors/Align/AliAlgVtx.h new file mode 100644 index 0000000000000..26e4597e6cf95 --- /dev/null +++ b/Detectors/Align/AliAlgVtx.h @@ -0,0 +1,49 @@ +#ifndef ALIALGVTX_H +#define ALIALGVTX_H + +/*-------------------------------------------------------- + Special fake "sensor" for event vertex. + It is needed to allow adjustement of the global IP position + if the event event is used as a measured point. + Its degrees of freedom of LOCAL X,Y,Z, coinciding with + GLOBAL X,Y,Z. + Since the vertex added to the track as a mesured point must be + defined in the frame with X axis along the tracks, the T2L + matrix of this sensor need to be recalculated for each track! + -------------------------------------------------------*/ + +// Author: ruben.shahoyan@cern.ch + + +#include "AliAlgSens.h" +class AliTrackPointArray; +class AliESDtrack; +class AliAlgPoint; + + +class AliAlgVtx : public AliAlgSens +{ + public: + AliAlgVtx(); + // + void ApplyCorrection(double *vtx) const; + virtual Bool_t IsSensor() const {return kTRUE;} + // + void SetAlpha(double alp) {fAlp=alp; PrepareMatrixT2L();} + virtual void PrepareMatrixL2G(Bool_t=0) {fMatL2G.Clear();} // unit matrix + virtual void PrepareMatrixL2GIdeal() {fMatL2GIdeal.Clear();} // unit matrix + virtual void PrepareMatrixT2L(); + // + virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); + // + protected: + AliAlgVtx(const AliAlgVtx&); + AliAlgVtx& operator=(const AliAlgVtx&); + // + protected: + // + ClassDef(AliAlgVtx,1); +}; + + +#endif diff --git a/Detectors/Align/CMakeLists.txt b/Detectors/Align/CMakeLists.txt new file mode 100644 index 0000000000000..a7ab149ae1fb4 --- /dev/null +++ b/Detectors/Align/CMakeLists.txt @@ -0,0 +1,113 @@ +# ************************************************************************** +# * Copyright(c) 1998-2014, 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. * +# ************************************************************************** + +# Module +set(MODULE ALIGN) +add_definitions(-D_MODULE_="${MODULE}") + +# Module include folders +include_directories(${AliRoot_SOURCE_DIR}/${MODULE}) + +# Additional include directories - alphabetical order except ROOT +include_directories(SYSTEM ${ROOT_INCLUDE_DIR}) +include_directories(${AliRoot_SOURCE_DIR}/STEER/STEERBase + ${AliRoot_SOURCE_DIR}/STEER/STEER + ${AliRoot_SOURCE_DIR}/STEER/ESD + ${AliRoot_SOURCE_DIR}/STEER/CDB + ${AliRoot_SOURCE_DIR}/TRD/TRDbase + ${AliRoot_SOURCE_DIR}/ITS/ITSbase + ${AliRoot_SOURCE_DIR}/TOF/TOFbase + ${AliRoot_SOURCE_DIR}/HMPID/HMPIDbase + ) + +# Sources - alphabetical order +set(SRCS + AliAlgAux.cxx + AliAlgConstraint.cxx + AliAlgDet.cxx + AliAlgDetHMPID.cxx + AliAlgDetITS.cxx + AliAlgDetTOF.cxx + AliAlgDetTPC.cxx + AliAlgDetTRD.cxx + AliAlgDOFStat.cxx + AliAlgMPRecord.cxx + AliAlgPoint.cxx + AliAlgRes.cxx + AliAlgResFast.cxx + AliAlgSens.cxx + AliAlgSensHMPID.cxx + AliAlgSensITS.cxx + AliAlgSensTOF.cxx + AliAlgSensTPC.cxx + AliAlgSensTRD.cxx + AliAlgSteer.cxx + AliAlgTrack.cxx + AliAlgVol.cxx + AliAlgVtx.cxx + Mille.cxx + ) + +# Headers from sources +string(REPLACE ".cxx" ".h" HDRS "${SRCS}") + +# Generate the dictionary +# It will create G_ARG1.cxx and G_ARG1.h / ARG1 = function first argument +get_directory_property(incdirs INCLUDE_DIRECTORIES) +generate_dictionary("${MODULE}" "${MODULE}LinkDef.h" "${HDRS}" "${incdirs}") + +set(ROOT_DEPENDENCIES Core Geom Gpad Graf3d MathCore Matrix Hist RIO Tree) +set(ALIROOT_DEPENDENCIES STEERBase ESD CDB ITSbase TRDbase TOFbase) + +# Generate the ROOT map +# Dependecies +set(LIBDEPS ${ALIROOT_DEPENDENCIES} ${ROOT_DEPENDENCIES}) +generate_rootmap("${MODULE}" "${LIBDEPS}" "${CMAKE_CURRENT_SOURCE_DIR}/${MODULE}LinkDef.h") + +# Create an object to be reused in case of static libraries +# Otherwise the sources will be compiled twice +add_library(${MODULE}-object OBJECT ${SRCS} G__${MODULE}.cxx) +# Add a library to the project using the object +add_library(${MODULE} SHARED $) + +target_link_libraries(${MODULE} ${ALIROOT_DEPENDENCIES} ${ROOT_DEPENDENCIES}) + +# Public include folders that will be propagated to the dependecies +target_include_directories(${MODULE} PUBLIC ${incdirs}) + +# System dependent: Modify the way the library is build +if(${CMAKE_SYSTEM} MATCHES Darwin) + set(MODULE_LINK_FLAGS "-undefined dynamic_lookup ${MODULE_LINK_FLAGS}") +endif(${CMAKE_SYSTEM} MATCHES Darwin) + +# Aditional compile and link flags +set_target_properties(${MODULE}-object PROPERTIES COMPILE_FLAGS "${MODULE_COMPILE_FLAGS}") +set_target_properties(${MODULE} PROPERTIES LINK_FLAGS "${MODULE_LINK_FLAGS}") + +# Setting the correct headers for the object as gathered from the dependencies +# After all compilation flags are set +target_include_directories(${MODULE}-object PUBLIC $) +set_target_properties(${MODULE}-object PROPERTIES COMPILE_DEFINITIONS $) + +# Installation +install(TARGETS ${MODULE} + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib) + +# install macros +#install(DIRECTORY utils DESTINATION ALIGN) + +install(FILES ${HDRS} DESTINATION include) + diff --git a/Detectors/Align/Mille.cxx b/Detectors/Align/Mille.cxx new file mode 100644 index 0000000000000..ffd76992f9396 --- /dev/null +++ b/Detectors/Align/Mille.cxx @@ -0,0 +1,226 @@ +/** + * \file + * Create Millepede-II C-binary record. + * + * \author : Gero Flucke + * date : October 2006 + * $Revision: 1.3 $ + * $Date: 2007/04/16 17:47:38 $ + * (last update by $Author: flucke $) + */ + +/* + RS: original Mille.cc from http://svnsrv.desy.de/public/MillepedeII/tags/V04-02-03 + jeudi 30 avril 2015: renamed to cxx + jeudi 30 avril 2015: added automatic buffer expansion +*/ + +#include "Mille.h" + +#include +#include + +//___________________________________________________________________________ + +/// Opens outFileName (by default as binary file). +/** + * \param[in] outFileName file name + * \param[in] asBinary flag for binary + * \param[in] writeZero flag for keeping of zeros + */ +Mille::Mille(const char *outFileName, bool asBinary, bool writeZero) : + myOutFile(outFileName, + (asBinary ? (std::ios::binary | std::ios::out | std::ios::trunc) : (std::ios::out | std::ios::trunc ))), + myAsBinary(asBinary), myWriteZero(writeZero),myBufferSize(0), + myBufferInt(5000),myBufferFloat(5000), + myBufferPos(-1), myHasSpecial(false) +{ + // Instead myBufferPos(-1), myHasSpecial(false) and the following two lines + // we could call newSet() and kill()... + + if (!myOutFile.is_open()) { + std::cerr << "Mille::Mille: Could not open " << outFileName + << " as output file." << std::endl; + } +} + +//___________________________________________________________________________ +/// Closes file. +Mille::~Mille() +{ + myOutFile.close(); +} + +//___________________________________________________________________________ +/// Add measurement to buffer. +/** + * \param[in] NLC number of local derivatives + * \param[in] derLc local derivatives + * \param[in] NGL number of global derivatives + * \param[in] derGl global derivatives + * \param[in] label global labels + * \param[in] rMeas measurement (residuum) + * \param[in] sigma error + */ +void Mille::mille(int NLC, const float *derLc, + int NGL, const float *derGl, const int *label, + float rMeas, float sigma) +{ + if (sigma <= 0.) return; + if (myBufferPos == -1) this->newSet(); // start, e.g. new track + if (!this->checkBufferSize(NLC, NGL)) return; + + // first store measurement + ++myBufferPos; + float* bufferFloat = myBufferFloat.GetArray(); + int* bufferInt = myBufferInt.GetArray(); + bufferFloat[myBufferPos] = rMeas; + bufferInt [myBufferPos] = 0; + + // store local derivatives and local 'lables' 1,...,NLC + for (int i = 0; i < NLC; ++i) { + if (derLc[i] || myWriteZero) { // by default store only non-zero derivatives + ++myBufferPos; + bufferFloat[myBufferPos] = derLc[i]; // local derivatives + bufferInt [myBufferPos] = i+1; // index of local parameter + } + } + + // store uncertainty of measurement in between locals and globals + ++myBufferPos; + bufferFloat[myBufferPos] = sigma; + bufferInt [myBufferPos] = 0; + + // store global derivatives and their labels + for (int i = 0; i < NGL; ++i) { + if (derGl[i] || myWriteZero) { // by default store only non-zero derivatives + if ((label[i] > 0 || myWriteZero) && label[i] <= myMaxLabel) { // and for valid labels + ++myBufferPos; + bufferFloat[myBufferPos] = derGl[i]; // global derivatives + bufferInt [myBufferPos] = label[i]; // index of global parameter + } else { + std::cerr << "Mille::mille: Invalid label " << label[i] + << " <= 0 or > " << myMaxLabel << std::endl; + } + } + } +} + +//___________________________________________________________________________ +/// Add special data to buffer. +/** + * \param[in] nSpecial number of floats/ints + * \param[in] floatings floats + * \param[in] integers ints + */ +void Mille::special(int nSpecial, const float *floatings, const int *integers) +{ + if (nSpecial == 0) return; + if (myBufferPos == -1) this->newSet(); // start, e.g. new track + if (myHasSpecial) { + std::cerr << "Mille::special: Special values already stored for this record." + << std::endl; + return; + } + if (!this->checkBufferSize(nSpecial, 0)) return; + myHasSpecial = true; // after newSet() (Note: MILLSP sets to buffer position...) + + // myBufferFloat[.] | myBufferInt[.] + // ------------------------------------ + // 0.0 | 0 + // -float(nSpecial) | 0 + // The above indicates special data, following are nSpecial floating and nSpecial integer data. + // + float* bufferFloat = myBufferFloat.GetArray(); + int* bufferInt = myBufferInt.GetArray(); + // + ++myBufferPos; // zero pair + bufferFloat[myBufferPos] = 0.; + bufferInt [myBufferPos] = 0; + + ++myBufferPos; // nSpecial and zero + bufferFloat[myBufferPos] = -nSpecial; // automatic conversion to float + bufferInt [myBufferPos] = 0; + + for (int i = 0; i < nSpecial; ++i) { + ++myBufferPos; + bufferFloat[myBufferPos] = floatings[i]; + bufferInt [myBufferPos] = integers[i]; + } +} + +//___________________________________________________________________________ +/// Reset buffers, i.e. kill derivatives accumulated for current set. +void Mille::kill() +{ + myBufferPos = -1; +} + +//___________________________________________________________________________ +/// Write buffer (set of derivatives with same local parameters) to file. +int Mille::end() +{ + int wrote = 0; + if (myBufferPos > 0) { // only if anything stored... + const int numWordsToWrite = (myBufferPos + 1)*2; + float* bufferFloat = myBufferFloat.GetArray(); + int* bufferInt = myBufferInt.GetArray(); + + if (myAsBinary) { + myOutFile.write(reinterpret_cast(&numWordsToWrite), + sizeof(numWordsToWrite)); + myOutFile.write(reinterpret_cast(bufferFloat), + (myBufferPos+1) * sizeof(bufferFloat[0])); + myOutFile.write(reinterpret_cast(bufferInt), + (myBufferPos+1) * sizeof(bufferInt[0])); + } else { + myOutFile << numWordsToWrite << "\n"; + for (int i = 0; i < myBufferPos+1; ++i) { + myOutFile << bufferFloat[i] << " "; + } + myOutFile << "\n"; + + for (int i = 0; i < myBufferPos+1; ++i) { + myOutFile << bufferInt[i] << " "; + } + myOutFile << "\n"; + } + wrote = (myBufferPos+1)*(sizeof(bufferFloat[0])+sizeof(bufferInt[0]))+sizeof(int); + } + myBufferPos = -1; // reset buffer for next set of derivatives + return wrote; +} + +//___________________________________________________________________________ +/// Initialize for new set of locals, e.g. new track. +void Mille::newSet() +{ + myBufferPos = 0; + myHasSpecial = false; + myBufferFloat[0] = 0.0; + myBufferInt [0] = 0; // position 0 used as error counter +} + +//___________________________________________________________________________ +/// Enough space for next nLocal + nGlobal derivatives incl. measurement? +/** + * \param[in] nLocal number of local derivatives + * \param[in] nGlobal number of global derivatives + * \return true if sufficient space available (else false) + */ +bool Mille::checkBufferSize(int nLocal, int nGlobal) +{ + if (myBufferPos + nLocal + nGlobal + 2 >= myBufferInt.GetSize()) { + ++(myBufferInt[0]); // increase error count + std::cerr << "Mille::checkBufferSize: Buffer too short (" + << myBufferInt.GetSize() << ")," + << "\n need space for nLocal (" << nLocal<< ")" + << "/nGlobal (" << nGlobal << ") local/global derivatives, " + << myBufferPos + 1 << " already stored!" + << std::endl; + // return false; + myBufferInt.Set(myBufferPos + nLocal + nGlobal + 1000); + myBufferFloat.Set(myBufferPos + nLocal + nGlobal + 1000); + } + return true; +} diff --git a/Detectors/Align/Mille.h b/Detectors/Align/Mille.h new file mode 100644 index 0000000000000..9f4af02b3702f --- /dev/null +++ b/Detectors/Align/Mille.h @@ -0,0 +1,58 @@ +#ifndef MILLE_H +#define MILLE_H + +#include +#include +#include + +/** + * \class Mille + * + * Class to write a C binary (cf. below) file of a given name and to fill it + * with information used as input to **pede**. + * Use its member functions \c mille(), \c special(), \c kill() and \c end() + * as you would use the fortran \ref mille.f90 "MILLE" + * and its entry points \c MILLSP, \c KILLE and \c ENDLE. + * + * For debugging purposes constructor flags enable switching to text output and/or + * to write also derivatives and labels which are ==0. + * But note that **pede** will not be able to read text output and has not been tested with + * derivatives/labels ==0. + * + * \author : Gero Flucke + * date : October 2006 + * $Revision: 1.3 $ + * $Date: 2007/04/16 17:47:38 $ + * (last update by $Author: flucke $) + */ + +/// Class to write C binary file. +class Mille +{ + public: + Mille(const char *outFileName, bool asBinary = true, bool writeZero = false); + ~Mille(); + + void mille(int NLC, const float *derLc, int NGL, const float *derGl, + const int *label, float rMeas, float sigma); + void special(int nSpecial, const float *floatings, const int *integers); + void kill(); + int end(); + + private: + void newSet(); + bool checkBufferSize(int nLocal, int nGlobal); + + std::ofstream myOutFile; ///< C-binary for output + bool myAsBinary; ///< if false output as text + bool myWriteZero; ///< if true also write out derivatives/labels ==0 + /// buffer size for ints and floats + int myBufferSize; ///< buffer size for ints and floats + TArrayI myBufferInt; ///< to collect labels etc. + TArrayF myBufferFloat; ///< to collect derivatives etc. + int myBufferPos; ///< position in buffer + bool myHasSpecial; ///< if true, special(..) already called for this record + /// largest label allowed: 2^31 - 1 + enum {myMaxLabel = (0xFFFFFFFF - (1 << 31))}; +}; +#endif From ade2023978b2616808b7090cafd888616f6ba4cf Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Tue, 9 Feb 2021 16:45:52 +0100 Subject: [PATCH 191/770] [ALIGN] restructure source --- Detectors/Align/Readme.md | 2 ++ Detectors/Align/{ => include/Align}/AliAlgAux.h | 0 Detectors/Align/{ => include/Align}/AliAlgConstraint.h | 0 Detectors/Align/{ => include/Align}/AliAlgDOFStat.h | 0 Detectors/Align/{ => include/Align}/AliAlgDet.h | 0 Detectors/Align/{ => include/Align}/AliAlgDetHMPID.h | 0 Detectors/Align/{ => include/Align}/AliAlgDetITS.h | 0 Detectors/Align/{ => include/Align}/AliAlgDetTOF.h | 0 Detectors/Align/{ => include/Align}/AliAlgDetTPC.h | 0 Detectors/Align/{ => include/Align}/AliAlgDetTRD.h | 0 Detectors/Align/{ => include/Align}/AliAlgMPRecord.h | 0 Detectors/Align/{ => include/Align}/AliAlgPoint.h | 0 Detectors/Align/{ => include/Align}/AliAlgRes.h | 0 Detectors/Align/{ => include/Align}/AliAlgResFast.h | 0 Detectors/Align/{ => include/Align}/AliAlgSens.h | 0 Detectors/Align/{ => include/Align}/AliAlgSensHMPID.h | 0 Detectors/Align/{ => include/Align}/AliAlgSensITS.h | 0 Detectors/Align/{ => include/Align}/AliAlgSensTOF.h | 0 Detectors/Align/{ => include/Align}/AliAlgSensTPC.h | 0 Detectors/Align/{ => include/Align}/AliAlgSensTRD.h | 0 Detectors/Align/{ => include/Align}/AliAlgSteer.h | 0 Detectors/Align/{ => include/Align}/AliAlgTrack.h | 0 Detectors/Align/{ => include/Align}/AliAlgVol.h | 0 Detectors/Align/{ => include/Align}/AliAlgVtx.h | 0 Detectors/Align/{ => include/Align}/Mille.h | 0 Detectors/Align/{ => src}/ALIGNLinkDef.h | 0 Detectors/Align/{ => src}/AliAlgAux.cxx | 0 Detectors/Align/{ => src}/AliAlgConstraint.cxx | 0 Detectors/Align/{ => src}/AliAlgDOFStat.cxx | 0 Detectors/Align/{ => src}/AliAlgDet.cxx | 0 Detectors/Align/{ => src}/AliAlgDetHMPID.cxx | 0 Detectors/Align/{ => src}/AliAlgDetITS.cxx | 0 Detectors/Align/{ => src}/AliAlgDetTOF.cxx | 0 Detectors/Align/{ => src}/AliAlgDetTPC.cxx | 0 Detectors/Align/{ => src}/AliAlgDetTRD.cxx | 0 Detectors/Align/{ => src}/AliAlgMPRecord.cxx | 0 Detectors/Align/{ => src}/AliAlgPoint.cxx | 0 Detectors/Align/{ => src}/AliAlgRes.cxx | 0 Detectors/Align/{ => src}/AliAlgResFast.cxx | 0 Detectors/Align/{ => src}/AliAlgSens.cxx | 0 Detectors/Align/{ => src}/AliAlgSensHMPID.cxx | 0 Detectors/Align/{ => src}/AliAlgSensITS.cxx | 0 Detectors/Align/{ => src}/AliAlgSensTOF.cxx | 0 Detectors/Align/{ => src}/AliAlgSensTPC.cxx | 0 Detectors/Align/{ => src}/AliAlgSensTRD.cxx | 0 Detectors/Align/{ => src}/AliAlgSteer.cxx | 0 Detectors/Align/{ => src}/AliAlgTrack.cxx | 0 Detectors/Align/{ => src}/AliAlgVol.cxx | 0 Detectors/Align/{ => src}/AliAlgVtx.cxx | 0 Detectors/Align/{ => src}/Mille.cxx | 0 50 files changed, 2 insertions(+) create mode 100644 Detectors/Align/Readme.md rename Detectors/Align/{ => include/Align}/AliAlgAux.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgConstraint.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgDOFStat.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgDet.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgDetHMPID.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgDetITS.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgDetTOF.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgDetTPC.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgDetTRD.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgMPRecord.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgPoint.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgRes.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgResFast.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgSens.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgSensHMPID.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgSensITS.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgSensTOF.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgSensTPC.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgSensTRD.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgSteer.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgTrack.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgVol.h (100%) rename Detectors/Align/{ => include/Align}/AliAlgVtx.h (100%) rename Detectors/Align/{ => include/Align}/Mille.h (100%) rename Detectors/Align/{ => src}/ALIGNLinkDef.h (100%) rename Detectors/Align/{ => src}/AliAlgAux.cxx (100%) rename Detectors/Align/{ => src}/AliAlgConstraint.cxx (100%) rename Detectors/Align/{ => src}/AliAlgDOFStat.cxx (100%) rename Detectors/Align/{ => src}/AliAlgDet.cxx (100%) rename Detectors/Align/{ => src}/AliAlgDetHMPID.cxx (100%) rename Detectors/Align/{ => src}/AliAlgDetITS.cxx (100%) rename Detectors/Align/{ => src}/AliAlgDetTOF.cxx (100%) rename Detectors/Align/{ => src}/AliAlgDetTPC.cxx (100%) rename Detectors/Align/{ => src}/AliAlgDetTRD.cxx (100%) rename Detectors/Align/{ => src}/AliAlgMPRecord.cxx (100%) rename Detectors/Align/{ => src}/AliAlgPoint.cxx (100%) rename Detectors/Align/{ => src}/AliAlgRes.cxx (100%) rename Detectors/Align/{ => src}/AliAlgResFast.cxx (100%) rename Detectors/Align/{ => src}/AliAlgSens.cxx (100%) rename Detectors/Align/{ => src}/AliAlgSensHMPID.cxx (100%) rename Detectors/Align/{ => src}/AliAlgSensITS.cxx (100%) rename Detectors/Align/{ => src}/AliAlgSensTOF.cxx (100%) rename Detectors/Align/{ => src}/AliAlgSensTPC.cxx (100%) rename Detectors/Align/{ => src}/AliAlgSensTRD.cxx (100%) rename Detectors/Align/{ => src}/AliAlgSteer.cxx (100%) rename Detectors/Align/{ => src}/AliAlgTrack.cxx (100%) rename Detectors/Align/{ => src}/AliAlgVol.cxx (100%) rename Detectors/Align/{ => src}/AliAlgVtx.cxx (100%) rename Detectors/Align/{ => src}/Mille.cxx (100%) diff --git a/Detectors/Align/Readme.md b/Detectors/Align/Readme.md new file mode 100644 index 0000000000000..06ce970c6a4b2 --- /dev/null +++ b/Detectors/Align/Readme.md @@ -0,0 +1,2 @@ +#Align +This is a top page for the detector alignment documentation. \ No newline at end of file diff --git a/Detectors/Align/AliAlgAux.h b/Detectors/Align/include/Align/AliAlgAux.h similarity index 100% rename from Detectors/Align/AliAlgAux.h rename to Detectors/Align/include/Align/AliAlgAux.h diff --git a/Detectors/Align/AliAlgConstraint.h b/Detectors/Align/include/Align/AliAlgConstraint.h similarity index 100% rename from Detectors/Align/AliAlgConstraint.h rename to Detectors/Align/include/Align/AliAlgConstraint.h diff --git a/Detectors/Align/AliAlgDOFStat.h b/Detectors/Align/include/Align/AliAlgDOFStat.h similarity index 100% rename from Detectors/Align/AliAlgDOFStat.h rename to Detectors/Align/include/Align/AliAlgDOFStat.h diff --git a/Detectors/Align/AliAlgDet.h b/Detectors/Align/include/Align/AliAlgDet.h similarity index 100% rename from Detectors/Align/AliAlgDet.h rename to Detectors/Align/include/Align/AliAlgDet.h diff --git a/Detectors/Align/AliAlgDetHMPID.h b/Detectors/Align/include/Align/AliAlgDetHMPID.h similarity index 100% rename from Detectors/Align/AliAlgDetHMPID.h rename to Detectors/Align/include/Align/AliAlgDetHMPID.h diff --git a/Detectors/Align/AliAlgDetITS.h b/Detectors/Align/include/Align/AliAlgDetITS.h similarity index 100% rename from Detectors/Align/AliAlgDetITS.h rename to Detectors/Align/include/Align/AliAlgDetITS.h diff --git a/Detectors/Align/AliAlgDetTOF.h b/Detectors/Align/include/Align/AliAlgDetTOF.h similarity index 100% rename from Detectors/Align/AliAlgDetTOF.h rename to Detectors/Align/include/Align/AliAlgDetTOF.h diff --git a/Detectors/Align/AliAlgDetTPC.h b/Detectors/Align/include/Align/AliAlgDetTPC.h similarity index 100% rename from Detectors/Align/AliAlgDetTPC.h rename to Detectors/Align/include/Align/AliAlgDetTPC.h diff --git a/Detectors/Align/AliAlgDetTRD.h b/Detectors/Align/include/Align/AliAlgDetTRD.h similarity index 100% rename from Detectors/Align/AliAlgDetTRD.h rename to Detectors/Align/include/Align/AliAlgDetTRD.h diff --git a/Detectors/Align/AliAlgMPRecord.h b/Detectors/Align/include/Align/AliAlgMPRecord.h similarity index 100% rename from Detectors/Align/AliAlgMPRecord.h rename to Detectors/Align/include/Align/AliAlgMPRecord.h diff --git a/Detectors/Align/AliAlgPoint.h b/Detectors/Align/include/Align/AliAlgPoint.h similarity index 100% rename from Detectors/Align/AliAlgPoint.h rename to Detectors/Align/include/Align/AliAlgPoint.h diff --git a/Detectors/Align/AliAlgRes.h b/Detectors/Align/include/Align/AliAlgRes.h similarity index 100% rename from Detectors/Align/AliAlgRes.h rename to Detectors/Align/include/Align/AliAlgRes.h diff --git a/Detectors/Align/AliAlgResFast.h b/Detectors/Align/include/Align/AliAlgResFast.h similarity index 100% rename from Detectors/Align/AliAlgResFast.h rename to Detectors/Align/include/Align/AliAlgResFast.h diff --git a/Detectors/Align/AliAlgSens.h b/Detectors/Align/include/Align/AliAlgSens.h similarity index 100% rename from Detectors/Align/AliAlgSens.h rename to Detectors/Align/include/Align/AliAlgSens.h diff --git a/Detectors/Align/AliAlgSensHMPID.h b/Detectors/Align/include/Align/AliAlgSensHMPID.h similarity index 100% rename from Detectors/Align/AliAlgSensHMPID.h rename to Detectors/Align/include/Align/AliAlgSensHMPID.h diff --git a/Detectors/Align/AliAlgSensITS.h b/Detectors/Align/include/Align/AliAlgSensITS.h similarity index 100% rename from Detectors/Align/AliAlgSensITS.h rename to Detectors/Align/include/Align/AliAlgSensITS.h diff --git a/Detectors/Align/AliAlgSensTOF.h b/Detectors/Align/include/Align/AliAlgSensTOF.h similarity index 100% rename from Detectors/Align/AliAlgSensTOF.h rename to Detectors/Align/include/Align/AliAlgSensTOF.h diff --git a/Detectors/Align/AliAlgSensTPC.h b/Detectors/Align/include/Align/AliAlgSensTPC.h similarity index 100% rename from Detectors/Align/AliAlgSensTPC.h rename to Detectors/Align/include/Align/AliAlgSensTPC.h diff --git a/Detectors/Align/AliAlgSensTRD.h b/Detectors/Align/include/Align/AliAlgSensTRD.h similarity index 100% rename from Detectors/Align/AliAlgSensTRD.h rename to Detectors/Align/include/Align/AliAlgSensTRD.h diff --git a/Detectors/Align/AliAlgSteer.h b/Detectors/Align/include/Align/AliAlgSteer.h similarity index 100% rename from Detectors/Align/AliAlgSteer.h rename to Detectors/Align/include/Align/AliAlgSteer.h diff --git a/Detectors/Align/AliAlgTrack.h b/Detectors/Align/include/Align/AliAlgTrack.h similarity index 100% rename from Detectors/Align/AliAlgTrack.h rename to Detectors/Align/include/Align/AliAlgTrack.h diff --git a/Detectors/Align/AliAlgVol.h b/Detectors/Align/include/Align/AliAlgVol.h similarity index 100% rename from Detectors/Align/AliAlgVol.h rename to Detectors/Align/include/Align/AliAlgVol.h diff --git a/Detectors/Align/AliAlgVtx.h b/Detectors/Align/include/Align/AliAlgVtx.h similarity index 100% rename from Detectors/Align/AliAlgVtx.h rename to Detectors/Align/include/Align/AliAlgVtx.h diff --git a/Detectors/Align/Mille.h b/Detectors/Align/include/Align/Mille.h similarity index 100% rename from Detectors/Align/Mille.h rename to Detectors/Align/include/Align/Mille.h diff --git a/Detectors/Align/ALIGNLinkDef.h b/Detectors/Align/src/ALIGNLinkDef.h similarity index 100% rename from Detectors/Align/ALIGNLinkDef.h rename to Detectors/Align/src/ALIGNLinkDef.h diff --git a/Detectors/Align/AliAlgAux.cxx b/Detectors/Align/src/AliAlgAux.cxx similarity index 100% rename from Detectors/Align/AliAlgAux.cxx rename to Detectors/Align/src/AliAlgAux.cxx diff --git a/Detectors/Align/AliAlgConstraint.cxx b/Detectors/Align/src/AliAlgConstraint.cxx similarity index 100% rename from Detectors/Align/AliAlgConstraint.cxx rename to Detectors/Align/src/AliAlgConstraint.cxx diff --git a/Detectors/Align/AliAlgDOFStat.cxx b/Detectors/Align/src/AliAlgDOFStat.cxx similarity index 100% rename from Detectors/Align/AliAlgDOFStat.cxx rename to Detectors/Align/src/AliAlgDOFStat.cxx diff --git a/Detectors/Align/AliAlgDet.cxx b/Detectors/Align/src/AliAlgDet.cxx similarity index 100% rename from Detectors/Align/AliAlgDet.cxx rename to Detectors/Align/src/AliAlgDet.cxx diff --git a/Detectors/Align/AliAlgDetHMPID.cxx b/Detectors/Align/src/AliAlgDetHMPID.cxx similarity index 100% rename from Detectors/Align/AliAlgDetHMPID.cxx rename to Detectors/Align/src/AliAlgDetHMPID.cxx diff --git a/Detectors/Align/AliAlgDetITS.cxx b/Detectors/Align/src/AliAlgDetITS.cxx similarity index 100% rename from Detectors/Align/AliAlgDetITS.cxx rename to Detectors/Align/src/AliAlgDetITS.cxx diff --git a/Detectors/Align/AliAlgDetTOF.cxx b/Detectors/Align/src/AliAlgDetTOF.cxx similarity index 100% rename from Detectors/Align/AliAlgDetTOF.cxx rename to Detectors/Align/src/AliAlgDetTOF.cxx diff --git a/Detectors/Align/AliAlgDetTPC.cxx b/Detectors/Align/src/AliAlgDetTPC.cxx similarity index 100% rename from Detectors/Align/AliAlgDetTPC.cxx rename to Detectors/Align/src/AliAlgDetTPC.cxx diff --git a/Detectors/Align/AliAlgDetTRD.cxx b/Detectors/Align/src/AliAlgDetTRD.cxx similarity index 100% rename from Detectors/Align/AliAlgDetTRD.cxx rename to Detectors/Align/src/AliAlgDetTRD.cxx diff --git a/Detectors/Align/AliAlgMPRecord.cxx b/Detectors/Align/src/AliAlgMPRecord.cxx similarity index 100% rename from Detectors/Align/AliAlgMPRecord.cxx rename to Detectors/Align/src/AliAlgMPRecord.cxx diff --git a/Detectors/Align/AliAlgPoint.cxx b/Detectors/Align/src/AliAlgPoint.cxx similarity index 100% rename from Detectors/Align/AliAlgPoint.cxx rename to Detectors/Align/src/AliAlgPoint.cxx diff --git a/Detectors/Align/AliAlgRes.cxx b/Detectors/Align/src/AliAlgRes.cxx similarity index 100% rename from Detectors/Align/AliAlgRes.cxx rename to Detectors/Align/src/AliAlgRes.cxx diff --git a/Detectors/Align/AliAlgResFast.cxx b/Detectors/Align/src/AliAlgResFast.cxx similarity index 100% rename from Detectors/Align/AliAlgResFast.cxx rename to Detectors/Align/src/AliAlgResFast.cxx diff --git a/Detectors/Align/AliAlgSens.cxx b/Detectors/Align/src/AliAlgSens.cxx similarity index 100% rename from Detectors/Align/AliAlgSens.cxx rename to Detectors/Align/src/AliAlgSens.cxx diff --git a/Detectors/Align/AliAlgSensHMPID.cxx b/Detectors/Align/src/AliAlgSensHMPID.cxx similarity index 100% rename from Detectors/Align/AliAlgSensHMPID.cxx rename to Detectors/Align/src/AliAlgSensHMPID.cxx diff --git a/Detectors/Align/AliAlgSensITS.cxx b/Detectors/Align/src/AliAlgSensITS.cxx similarity index 100% rename from Detectors/Align/AliAlgSensITS.cxx rename to Detectors/Align/src/AliAlgSensITS.cxx diff --git a/Detectors/Align/AliAlgSensTOF.cxx b/Detectors/Align/src/AliAlgSensTOF.cxx similarity index 100% rename from Detectors/Align/AliAlgSensTOF.cxx rename to Detectors/Align/src/AliAlgSensTOF.cxx diff --git a/Detectors/Align/AliAlgSensTPC.cxx b/Detectors/Align/src/AliAlgSensTPC.cxx similarity index 100% rename from Detectors/Align/AliAlgSensTPC.cxx rename to Detectors/Align/src/AliAlgSensTPC.cxx diff --git a/Detectors/Align/AliAlgSensTRD.cxx b/Detectors/Align/src/AliAlgSensTRD.cxx similarity index 100% rename from Detectors/Align/AliAlgSensTRD.cxx rename to Detectors/Align/src/AliAlgSensTRD.cxx diff --git a/Detectors/Align/AliAlgSteer.cxx b/Detectors/Align/src/AliAlgSteer.cxx similarity index 100% rename from Detectors/Align/AliAlgSteer.cxx rename to Detectors/Align/src/AliAlgSteer.cxx diff --git a/Detectors/Align/AliAlgTrack.cxx b/Detectors/Align/src/AliAlgTrack.cxx similarity index 100% rename from Detectors/Align/AliAlgTrack.cxx rename to Detectors/Align/src/AliAlgTrack.cxx diff --git a/Detectors/Align/AliAlgVol.cxx b/Detectors/Align/src/AliAlgVol.cxx similarity index 100% rename from Detectors/Align/AliAlgVol.cxx rename to Detectors/Align/src/AliAlgVol.cxx diff --git a/Detectors/Align/AliAlgVtx.cxx b/Detectors/Align/src/AliAlgVtx.cxx similarity index 100% rename from Detectors/Align/AliAlgVtx.cxx rename to Detectors/Align/src/AliAlgVtx.cxx diff --git a/Detectors/Align/Mille.cxx b/Detectors/Align/src/Mille.cxx similarity index 100% rename from Detectors/Align/Mille.cxx rename to Detectors/Align/src/Mille.cxx From f30bcf3220dbca436041a5587860b2526f0e2650 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Tue, 9 Feb 2021 18:10:15 +0100 Subject: [PATCH 192/770] [ALIGN] o2 formatting and namespace --- Detectors/Align/include/Align/AliAlgAux.h | 208 +- .../Align/include/Align/AliAlgConstraint.h | 105 +- Detectors/Align/include/Align/AliAlgDOFStat.h | 57 +- Detectors/Align/include/Align/AliAlgDet.h | 342 ++-- .../Align/include/Align/AliAlgDetHMPID.h | 35 +- Detectors/Align/include/Align/AliAlgDetITS.h | 75 +- Detectors/Align/include/Align/AliAlgDetTOF.h | 36 +- Detectors/Align/include/Align/AliAlgDetTPC.h | 34 +- Detectors/Align/include/Align/AliAlgDetTRD.h | 80 +- .../Align/include/Align/AliAlgMPRecord.h | 162 +- Detectors/Align/include/Align/AliAlgPoint.h | 382 ++-- Detectors/Align/include/Align/AliAlgRes.h | 225 ++- Detectors/Align/include/Align/AliAlgResFast.h | 156 +- Detectors/Align/include/Align/AliAlgSens.h | 96 +- .../Align/include/Align/AliAlgSensHMPID.h | 35 +- Detectors/Align/include/Align/AliAlgSensITS.h | 35 +- Detectors/Align/include/Align/AliAlgSensTOF.h | 40 +- Detectors/Align/include/Align/AliAlgSensTPC.h | 41 +- Detectors/Align/include/Align/AliAlgSensTRD.h | 42 +- Detectors/Align/include/Align/AliAlgSteer.h | 727 +++---- Detectors/Align/include/Align/AliAlgTrack.h | 287 +-- Detectors/Align/include/Align/AliAlgVol.h | 356 ++-- Detectors/Align/include/Align/AliAlgVtx.h | 64 +- Detectors/Align/include/Align/Mille.h | 67 +- Detectors/Align/src/ALIGNLinkDef.h | 46 +- Detectors/Align/src/AliAlgAux.cxx | 129 +- Detectors/Align/src/AliAlgConstraint.cxx | 377 ++-- Detectors/Align/src/AliAlgDOFStat.cxx | 76 +- Detectors/Align/src/AliAlgDet.cxx | 461 +++-- Detectors/Align/src/AliAlgDetHMPID.cxx | 62 +- Detectors/Align/src/AliAlgDetITS.cxx | 333 ++-- Detectors/Align/src/AliAlgDetTOF.cxx | 71 +- Detectors/Align/src/AliAlgDetTPC.cxx | 92 +- Detectors/Align/src/AliAlgDetTRD.cxx | 129 +- Detectors/Align/src/AliAlgMPRecord.cxx | 305 ++- Detectors/Align/src/AliAlgPoint.cxx | 275 +-- Detectors/Align/src/AliAlgRes.cxx | 252 ++- Detectors/Align/src/AliAlgResFast.cxx | 130 +- Detectors/Align/src/AliAlgSens.cxx | 329 ++-- Detectors/Align/src/AliAlgSensHMPID.cxx | 85 +- Detectors/Align/src/AliAlgSensITS.cxx | 75 +- Detectors/Align/src/AliAlgSensTOF.cxx | 96 +- Detectors/Align/src/AliAlgSensTPC.cxx | 84 +- Detectors/Align/src/AliAlgSensTRD.cxx | 160 +- Detectors/Align/src/AliAlgSteer.cxx | 1696 +++++++++-------- Detectors/Align/src/AliAlgTrack.cxx | 1258 ++++++------ Detectors/Align/src/AliAlgVol.cxx | 463 +++-- Detectors/Align/src/AliAlgVtx.cxx | 48 +- Detectors/Align/src/Mille.cxx | 152 +- 49 files changed, 6019 insertions(+), 4852 deletions(-) diff --git a/Detectors/Align/include/Align/AliAlgAux.h b/Detectors/Align/include/Align/AliAlgAux.h index c7d21fd29fc31..ec45ca9438d40 100644 --- a/Detectors/Align/include/Align/AliAlgAux.h +++ b/Detectors/Align/include/Align/AliAlgAux.h @@ -1,3 +1,18 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgAux.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief Collection of auxillary methods + #ifndef ALIALGAUX_H #define ALIALGAUX_H @@ -9,106 +24,143 @@ class TList; using namespace TMath; -/*-------------------------------------------------------- - Collection of auxillary methods - -------------------------------------------------------*/ - -// Author: ruben.shahoyan@cern.ch - +namespace o2 +{ +namespace align +{ -namespace AliAlgAux { - const double kAlmostZeroD = 1e-15; - const float kAlmostZeroF = 1e-11; - const double kAlmostOneD = 1.-kAlmostZeroD; - const float kAlmostOneF = 1.-kAlmostZeroF; - const double kTinyDist = 1.e-7; // ignore distances less that this - // - enum {kColl,kCosm,kNTrackTypes}; - // - inline Double_t Sector2Alpha(int sect); - inline Int_t Phi2Sector(double alpha); - inline Double_t SectorDAlpha() {return Pi()/9;} - // - template void BringTo02Pi(F &phi); - template void BringToPiPM(F &phi); - template Bool_t OKforPhiMin(F phiMin,F phi); - template Bool_t OKforPhiMax(F phiMax,F phi); - template F MeanPhiSmall(F phi0, F phi1); - template F DeltaPhiSmall(F phi0, F phi1); - template Bool_t SmallerAbs(F d, F tolD) {return Abs(d) Bool_t Smaller(F d, F tolD) {return d +void BringTo02Pi(F& phi); +template +void BringToPiPM(F& phi); +template +Bool_t OKforPhiMin(F phiMin, F phi); +template +Bool_t OKforPhiMax(F phiMax, F phi); +template +F MeanPhiSmall(F phi0, F phi1); +template +F DeltaPhiSmall(F phi0, F phi1); +template +Bool_t SmallerAbs(F d, F tolD) +{ + return Abs(d) < tolD; } +template +Bool_t Smaller(F d, F tolD) +{ + return d < tolD; +} +// +inline Int_t NumberOfBitsSet(UInt_t x); +inline Bool_t IsZeroAbs(double d) { return SmallerAbs(d, kAlmostZeroD); } +inline Bool_t IsZeroAbs(float f) { return SmallerAbs(f, kAlmostZeroF); } +inline Bool_t IsZeroPos(double d) { return Smaller(d, kAlmostZeroD); } +inline Bool_t IsZeroPos(float f) { return Smaller(f, kAlmostZeroF); } +// +int FindKeyIndex(int key, const int* arr, int n); +// +void PrintBits(ULong64_t patt, Int_t maxBits); +// +// OCDB related stuff +void CleanOCDB(); +AliCDBId* FindCDBId(const TList* cdbList, const TString& key); +void RectifyOCDBUri(TString& inp); +Bool_t PreloadOCDB(int run, const TMap* cdbMap, const TList* cdbList); +} // namespace AliAlgAux //_________________________________________________________________________________ -template -inline void AliAlgAux::BringTo02Pi(F &phi) { +template +inline void AliAlgAux::BringTo02Pi(F& phi) +{ // bring phi to 0-2pi range - if (phi<0) phi+=TwoPi(); else if (phi>TwoPi()) phi-=TwoPi(); + if (phi < 0) + phi += TwoPi(); + else if (phi > TwoPi()) + phi -= TwoPi(); } //_________________________________________________________________________________ -template -inline void AliAlgAux::BringToPiPM(F &phi) { +template +inline void AliAlgAux::BringToPiPM(F& phi) +{ // bring phi to -pi:pi range - if (phi>Pi()) phi-=TwoPi(); + if (phi > Pi()) + phi -= TwoPi(); } //_________________________________________________________________________________ -template -inline Bool_t AliAlgAux::OKforPhiMin(F phiMin,F phi) { +template +inline Bool_t AliAlgAux::OKforPhiMin(F phiMin, F phi) +{ // check if phi is above the phiMin, phi's must be in 0-2pi range - F dphi = phi-phiMin; - return ((dphi>0 && dphi 0 && dphi < Pi()) || dphi < -Pi()) ? kTRUE : kFALSE; } //_________________________________________________________________________________ -template -inline Bool_t AliAlgAux::OKforPhiMax(F phiMax,F phi) { +template +inline Bool_t AliAlgAux::OKforPhiMax(F phiMax, F phi) +{ // check if phi is below the phiMax, phi's must be in 0-2pi range - F dphi = phi-phiMax; - return ((dphi<0 && dphi>-Pi()) || dphi>Pi()) ? kTRUE:kFALSE; + F dphi = phi - phiMax; + return ((dphi < 0 && dphi > -Pi()) || dphi > Pi()) ? kTRUE : kFALSE; } //_________________________________________________________________________________ -template -inline F AliAlgAux::MeanPhiSmall(F phi0, F phi1) { +template +inline F AliAlgAux::MeanPhiSmall(F phi0, F phi1) +{ // return mean phi, assume phis in 0:2pi F phi; - if (!OKforPhiMin(phi0,phi1)) {phi=phi0; phi0=phi1; phi1=phi;} - if (phi0>phi1) phi = (phi1 - (TwoPi()-phi0))/2; // wrap - else phi = (phi0+phi1)/2; + if (!OKforPhiMin(phi0, phi1)) { + phi = phi0; + phi0 = phi1; + phi1 = phi; + } + if (phi0 > phi1) + phi = (phi1 - (TwoPi() - phi0)) / 2; // wrap + else + phi = (phi0 + phi1) / 2; BringTo02Pi(phi); return phi; } //_________________________________________________________________________________ -template -inline F AliAlgAux::DeltaPhiSmall(F phi0, F phi1) { +template +inline F AliAlgAux::DeltaPhiSmall(F phi0, F phi1) +{ // return delta phi, assume phis in 0:2pi F del; - if (!OKforPhiMin(phi0,phi1)) {del=phi0; phi0=phi1; phi1=del;} + if (!OKforPhiMin(phi0, phi1)) { + del = phi0; + phi0 = phi1; + phi1 = del; + } del = phi1 - phi0; - if (del<0) del += TwoPi(); + if (del < 0) + del += TwoPi(); return del; } //_________________________________________________________________________________ -inline Int_t AliAlgAux::NumberOfBitsSet(UInt_t x) { +inline Int_t AliAlgAux::NumberOfBitsSet(UInt_t x) +{ // count number of non-0 bits in 32bit word x = x - ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); @@ -116,17 +168,23 @@ inline Int_t AliAlgAux::NumberOfBitsSet(UInt_t x) { } //_________________________________________________________________________________ -inline Double_t AliAlgAux::Sector2Alpha(int sect) { +inline Double_t AliAlgAux::Sector2Alpha(int sect) +{ // get barrel sector alpha in -pi:pi format - if (sect>8)sect-=18; return (sect+0.5)*SectorDAlpha(); -} + if (sect > 8) + sect -= 18; + return (sect + 0.5) * SectorDAlpha(); +} //_________________________________________________________________________________ -inline Int_t AliAlgAux::Phi2Sector(double phi) { +inline Int_t AliAlgAux::Phi2Sector(double phi) +{ // get barrel sector from phi in -pi:pi format - int sect = Nint( (phi*RadToDeg()-10)/20. ); - if (sect<0) sect+=18; + int sect = Nint((phi * RadToDeg() - 10) / 20.); + if (sect < 0) + sect += 18; return sect; -} - +} +} // namespace align +} // namespace o2 #endif diff --git a/Detectors/Align/include/Align/AliAlgConstraint.h b/Detectors/Align/include/Align/AliAlgConstraint.h index a59d61e3ec6a4..59430138e29e1 100644 --- a/Detectors/Align/include/Align/AliAlgConstraint.h +++ b/Detectors/Align/include/Align/AliAlgConstraint.h @@ -1,3 +1,28 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgConstraint.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief Descriptor of geometrical constraint + +/** + * Descriptor of geometrical constraint: the cumulative + * corrections of children for requested DOFs in the frame of + * parent (of LAB if parent is not defined) forced to be 0. + * The parent - child relationship need not to be real + * + * Constraint wil be quazi-exact (Lagrange multiplier) if + * corresponding sigma = 0, or of gaussian type is sigma>0 + */ + #ifndef ALIALGCONSTRAINT_H #define ALIALGCONSTRAINT_H @@ -6,66 +31,64 @@ #include #include "AliAlgVol.h" -/*-------------------------------------------------------- - Descriptor of geometrical constraint: the cumulative - corrections of children for requested DOFs in the frame of - parent (of LAB if parent is not defined) forced to be 0. - The parent - child relationship need not to be real - - Constraint wil be quazi-exact (Lagrange multiplier) if - corresponding sigma = 0, or of gaussian type is sigma>0 - -------------------------------------------------------*/ - -// Author: ruben.shahoyan@cern.ch - +namespace o2 +{ +namespace align +{ class AliAlgConstraint : public TNamed { public: - enum {kNDOFGeom=AliAlgVol::kNDOFGeom}; - enum {kNoJacobianBit=BIT(14)}; + enum { kNDOFGeom = AliAlgVol::kNDOFGeom }; + enum { kNoJacobianBit = BIT(14) }; // - AliAlgConstraint(const char* name=0,const char* title=0); + AliAlgConstraint(const char* name = 0, const char* title = 0); virtual ~AliAlgConstraint(); // - void SetParent(const AliAlgVol* par); - const AliAlgVol* GetParent() const {return fParent;} + void SetParent(const AliAlgVol* par); + const AliAlgVol* GetParent() const { return fParent; } // - Int_t GetNChildren() const {return fChildren.GetEntriesFast();} - AliAlgVol* GetChild(int i) const {return (AliAlgVol*)fChildren[i];} - void AddChild(const AliAlgVol* v) {if (v) fChildren.AddLast((AliAlgVol*)v);} + Int_t GetNChildren() const { return fChildren.GetEntriesFast(); } + AliAlgVol* GetChild(int i) const { return (AliAlgVol*)fChildren[i]; } + void AddChild(const AliAlgVol* v) + { + if (v) + fChildren.AddLast((AliAlgVol*)v); + } // - Bool_t IsDOFConstrained(Int_t dof) const {return fConstraint&0x1< class AliAlgSteer; class TH1F; class TCollection; +namespace o2 +{ +namespace align +{ + class AliAlgDOFStat : public TNamed { public: - AliAlgDOFStat(Int_t n=0); + AliAlgDOFStat(Int_t n = 0); virtual ~AliAlgDOFStat(); // - Int_t GetNDOFs() const {return fNDOFs;} - Int_t GetStat(int idf) const {return idf=fVolIDMin && vid<=fVolIDMax;} - void SetAddError(double y, double z); - const Double_t* GetAddError() const {return fAddError;} - // - Int_t GetNPoints() const {return fNPoints;} - // - void SetAlgSteer(AliAlgSteer* s) {fAlgSteer = s;} - AliAlgSens* GetSensor(Int_t id) const {return (AliAlgSens*)fSensors.UncheckedAt(id);} - AliAlgSens* GetSensorByVolId(Int_t vid) const {int sid=VolID2SID(vid); return sid<0 ? 0:GetSensor(sid);} - AliAlgSens* GetSensor(const char* symname) const {return (AliAlgSens*)fSensors.FindObject(symname);} - AliAlgVol* GetVolume(Int_t id) const {return (AliAlgVol*)fVolumes.UncheckedAt(id);} - AliAlgVol* GetVolume(const char* symname) const {return (AliAlgVol*)fVolumes.FindObject(symname);} - // - Bool_t OwnsDOFID(Int_t id) const; - AliAlgVol* GetVolOfDOFID(Int_t id) const; - // - Int_t GetDetLabel() const {return (GetDetID()+1)*1000000;} - void SetFreeDOF(Int_t dof); - void FixDOF(Int_t dof); - void SetFreeDOFPattern(ULong64_t pat) {fCalibDOF = pat; CalcFree();} - Bool_t IsFreeDOF(Int_t dof) const {return (fCalibDOF&(0x1<= fVolIDMin && vid <= fVolIDMax; } + void SetAddError(double y, double z); + const Double_t* GetAddError() const { return fAddError; } + // + Int_t GetNPoints() const { return fNPoints; } + // + void SetAlgSteer(AliAlgSteer* s) { fAlgSteer = s; } + AliAlgSens* GetSensor(Int_t id) const { return (AliAlgSens*)fSensors.UncheckedAt(id); } + AliAlgSens* GetSensorByVolId(Int_t vid) const + { + int sid = VolID2SID(vid); + return sid < 0 ? 0 : GetSensor(sid); + } + AliAlgSens* GetSensor(const char* symname) const { return (AliAlgSens*)fSensors.FindObject(symname); } + AliAlgVol* GetVolume(Int_t id) const { return (AliAlgVol*)fVolumes.UncheckedAt(id); } + AliAlgVol* GetVolume(const char* symname) const { return (AliAlgVol*)fVolumes.FindObject(symname); } + // + Bool_t OwnsDOFID(Int_t id) const; + AliAlgVol* GetVolOfDOFID(Int_t id) const; + // + Int_t GetDetLabel() const { return (GetDetID() + 1) * 1000000; } + void SetFreeDOF(Int_t dof); + void FixDOF(Int_t dof); + void SetFreeDOFPattern(ULong64_t pat) + { + fCalibDOF = pat; + CalcFree(); + } + Bool_t IsFreeDOF(Int_t dof) const { return (fCalibDOF & (0x1 << dof)) != 0; } + Bool_t IsCondDOF(Int_t dof) const; + ULong64_t GetFreeDOFPattern() const { return fCalibDOF; } + Int_t GetNProcessedPoints() const { return fNProcPoints; } + virtual const char* GetCalibDOFName(int) const { return 0; } + virtual Double_t GetCalibDOFVal(int) const { return 0; } + virtual Double_t GetCalibDOFValWithCal(int) const { return 0; } // virtual Int_t InitGeom(); virtual Int_t AssignDOFs(); - virtual void InitDOFs(); - virtual void Terminate(); - void FillDOFStat(AliAlgDOFStat* dofst=0) const; - virtual void AddVolume(AliAlgVol* vol); - virtual void DefineVolumes(); - virtual void DefineMatrices(); - virtual void Print(const Option_t *opt="") const; - virtual Int_t ProcessPoints(const AliESDtrack* esdTr, AliAlgTrack* algTrack,Bool_t inv=kFALSE); - virtual void UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const; - virtual void SetUseErrorParam(Int_t v=0); - Int_t GetUseErrorParam() const {return fUseErrorParam;} - // - virtual Bool_t AcceptTrack(const AliESDtrack* trc,Int_t trtype) const = 0; - Bool_t CheckFlags(const AliESDtrack* trc,Int_t trtype) const; + virtual void InitDOFs(); + virtual void Terminate(); + void FillDOFStat(AliAlgDOFStat* dofst = 0) const; + virtual void AddVolume(AliAlgVol* vol); + virtual void DefineVolumes(); + virtual void DefineMatrices(); + virtual void Print(const Option_t* opt = "") const; + virtual Int_t ProcessPoints(const AliESDtrack* esdTr, AliAlgTrack* algTrack, Bool_t inv = kFALSE); + virtual void UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const; + virtual void SetUseErrorParam(Int_t v = 0); + Int_t GetUseErrorParam() const { return fUseErrorParam; } + // + virtual Bool_t AcceptTrack(const AliESDtrack* trc, Int_t trtype) const = 0; + Bool_t CheckFlags(const AliESDtrack* trc, Int_t trtype) const; // virtual AliAlgPoint* GetPointFromPool(); virtual void ResetPool(); virtual void WriteSensorPositions(const char* outFName); // - void SetInitGeomDone() {SetBit(kInitGeomDone);} - Bool_t GetInitGeomDone() const {return TestBit(kInitGeomDone);} - // - void SetInitDOFsDone() {SetBit(kInitDOFsDone);} - Bool_t GetInitDOFsDone() const {return TestBit(kInitDOFsDone);} - void FixNonSensors(); - void SetFreeDOFPattern(UInt_t pat=0xffffffff, int lev=-1,const char* match=0); - void SetDOFCondition(int dof, float condErr, int lev=-1,const char* match=0); - int SelectVolumes(TObjArray* arr, int lev=-1,const char* match=0); - // - Int_t GetNDOFs() const {return fNDOFs;} - Int_t GetNCalibDOFs() const {return fNCalibDOF;} - Int_t GetNCalibDOFsFree() const {return fNCalibDOFFree;} - // - void SetDisabled(Int_t tp,Bool_t v) {fDisabled[tp]=v;SetObligatory(tp,!v);} - void SetDisabled() {SetDisabledColl();SetDisabledCosm();} - void SetDisabledColl(Bool_t v=kTRUE) {SetDisabled(AliAlgAux::kColl,v);} - void SetDisabledCosm(Bool_t v=kTRUE) {SetDisabled(AliAlgAux::kCosm,v);} - Bool_t IsDisabled(Int_t tp) const {return fDisabled[tp];} - Bool_t IsDisabled() const {return IsDisabledColl()&&IsDisabledCosm();} - Bool_t IsDisabledColl() const {return IsDisabled(AliAlgAux::kColl);} - Bool_t IsDisabledCosm() const {return IsDisabled(AliAlgAux::kCosm);} - // - void SetTrackFlagSel(Int_t tp,ULong_t f) {fTrackFlagSel[tp] = f;} - void SetTrackFlagSelColl(ULong_t f) {SetTrackFlagSel(AliAlgAux::kColl,f);} - void SetTrackFlagSelCosm(ULong_t f) {SetTrackFlagSel(AliAlgAux::kCosm,f);} - ULong_t GetTrackFlagSel(Int_t tp) const {return fTrackFlagSel[tp];} - ULong_t GetTrackFlagSelColl() const {return GetTrackFlagSel(AliAlgAux::kColl);} - ULong_t GetTrackFlagSelCosm() const {return GetTrackFlagSel(AliAlgAux::kCosm);} - // - void SetNPointsSel(Int_t tp,Int_t n) {fNPointsSel[tp] = n;} - void SetNPointsSelColl(Int_t n) {SetNPointsSel(AliAlgAux::kColl,n);} - void SetNPointsSelCosm(Int_t n) {SetNPointsSel(AliAlgAux::kCosm,n);} - Int_t GetNPointsSel(Int_t tp) const {return fNPointsSel[tp];} - Int_t GetNPointsSelColl() const {return GetNPointsSel(AliAlgAux::kColl);} - Int_t GetNPointsSelCosm() const {return GetNPointsSel(AliAlgAux::kCosm);} - // - // - Bool_t IsObligatory(Int_t tp) const {return fObligatory[tp];} - Bool_t IsObligatoryColl() const {return IsObligatory(AliAlgAux::kColl);} - Bool_t IsObligatoryCosm() const {return IsObligatory(AliAlgAux::kCosm);} - void SetObligatory(Int_t tp,Bool_t v=kTRUE); - void SetObligatoryColl(Bool_t v=kTRUE) {SetObligatory(AliAlgAux::kColl,v);} - void SetObligatoryCosm(Bool_t v=kTRUE) {SetObligatory(AliAlgAux::kCosm,v);} - // - void AddAutoConstraints() const; - void ConstrainOrphans(const double* sigma, const char* match=0); + void SetInitGeomDone() { SetBit(kInitGeomDone); } + Bool_t GetInitGeomDone() const { return TestBit(kInitGeomDone); } + // + void SetInitDOFsDone() { SetBit(kInitDOFsDone); } + Bool_t GetInitDOFsDone() const { return TestBit(kInitDOFsDone); } + void FixNonSensors(); + void SetFreeDOFPattern(UInt_t pat = 0xffffffff, int lev = -1, const char* match = 0); + void SetDOFCondition(int dof, float condErr, int lev = -1, const char* match = 0); + int SelectVolumes(TObjArray* arr, int lev = -1, const char* match = 0); + // + Int_t GetNDOFs() const { return fNDOFs; } + Int_t GetNCalibDOFs() const { return fNCalibDOF; } + Int_t GetNCalibDOFsFree() const { return fNCalibDOFFree; } + // + void SetDisabled(Int_t tp, Bool_t v) + { + fDisabled[tp] = v; + SetObligatory(tp, !v); + } + void SetDisabled() + { + SetDisabledColl(); + SetDisabledCosm(); + } + void SetDisabledColl(Bool_t v = kTRUE) { SetDisabled(AliAlgAux::kColl, v); } + void SetDisabledCosm(Bool_t v = kTRUE) { SetDisabled(AliAlgAux::kCosm, v); } + Bool_t IsDisabled(Int_t tp) const { return fDisabled[tp]; } + Bool_t IsDisabled() const { return IsDisabledColl() && IsDisabledCosm(); } + Bool_t IsDisabledColl() const { return IsDisabled(AliAlgAux::kColl); } + Bool_t IsDisabledCosm() const { return IsDisabled(AliAlgAux::kCosm); } + // + void SetTrackFlagSel(Int_t tp, ULong_t f) { fTrackFlagSel[tp] = f; } + void SetTrackFlagSelColl(ULong_t f) { SetTrackFlagSel(AliAlgAux::kColl, f); } + void SetTrackFlagSelCosm(ULong_t f) { SetTrackFlagSel(AliAlgAux::kCosm, f); } + ULong_t GetTrackFlagSel(Int_t tp) const { return fTrackFlagSel[tp]; } + ULong_t GetTrackFlagSelColl() const { return GetTrackFlagSel(AliAlgAux::kColl); } + ULong_t GetTrackFlagSelCosm() const { return GetTrackFlagSel(AliAlgAux::kCosm); } + // + void SetNPointsSel(Int_t tp, Int_t n) { fNPointsSel[tp] = n; } + void SetNPointsSelColl(Int_t n) { SetNPointsSel(AliAlgAux::kColl, n); } + void SetNPointsSelCosm(Int_t n) { SetNPointsSel(AliAlgAux::kCosm, n); } + Int_t GetNPointsSel(Int_t tp) const { return fNPointsSel[tp]; } + Int_t GetNPointsSelColl() const { return GetNPointsSel(AliAlgAux::kColl); } + Int_t GetNPointsSelCosm() const { return GetNPointsSel(AliAlgAux::kCosm); } + // + // + Bool_t IsObligatory(Int_t tp) const { return fObligatory[tp]; } + Bool_t IsObligatoryColl() const { return IsObligatory(AliAlgAux::kColl); } + Bool_t IsObligatoryCosm() const { return IsObligatory(AliAlgAux::kCosm); } + void SetObligatory(Int_t tp, Bool_t v = kTRUE); + void SetObligatoryColl(Bool_t v = kTRUE) { SetObligatory(AliAlgAux::kColl, v); } + void SetObligatoryCosm(Bool_t v = kTRUE) { SetObligatory(AliAlgAux::kCosm, v); } + // + void AddAutoConstraints() const; + void ConstrainOrphans(const double* sigma, const char* match = 0); - virtual void WritePedeInfo(FILE* parOut,const Option_t *opt="") const; - virtual void WriteCalibrationResults() const; - virtual void WriteAlignmentResults() const; + virtual void WritePedeInfo(FILE* parOut, const Option_t* opt = "") const; + virtual void WriteCalibrationResults() const; + virtual void WriteAlignmentResults() const; // - Float_t* GetParVals() const {return fParVals;} - Double_t GetParVal(int par) const {return fParVals ? fParVals[par] : 0;} - Double_t GetParErr(int par) const {return fParErrs ? fParErrs[par] : 0;} - Int_t GetParLab(int par) const {return fParLabs ? fParLabs[par] : 0;} + Float_t* GetParVals() const { return fParVals; } + Double_t GetParVal(int par) const { return fParVals ? fParVals[par] : 0; } + Double_t GetParErr(int par) const { return fParErrs ? fParErrs[par] : 0; } + Int_t GetParLab(int par) const { return fParLabs ? fParLabs[par] : 0; } // - void SetParVals(Int_t npar,Double_t *vl,Double_t *er); - void SetParVal(Int_t par,Double_t v=0) {fParVals[par] = v;} - void SetParErr(Int_t par,Double_t e=0) {fParErrs[par] = e;} + void SetParVals(Int_t npar, Double_t* vl, Double_t* er); + void SetParVal(Int_t par, Double_t v = 0) { fParVals[par] = v; } + void SetParErr(Int_t par, Double_t e = 0) { fParErrs[par] = e; } // - Int_t GetFirstParGloID() const {return fFirstParGloID;} - Int_t GetParGloID(Int_t par) const {return fFirstParGloID+par;} - void SetFirstParGloID(Int_t id) {fFirstParGloID=id;} + Int_t GetFirstParGloID() const { return fFirstParGloID; } + Int_t GetParGloID(Int_t par) const { return fFirstParGloID + par; } + void SetFirstParGloID(Int_t id) { fFirstParGloID = id; } // protected: - void SortSensors(); - void CalcFree(Bool_t condFree=kFALSE); + void SortSensors(); + void CalcFree(Bool_t condFree = kFALSE); // // ------- dummies --------- AliAlgDet(const AliAlgDet&); @@ -169,49 +200,50 @@ class AliAlgDet : public TNamed // protected: // - Int_t fNDOFs; // number of DOFs free - Int_t fVolIDMin; // min volID for this detector (for sensors only) - Int_t fVolIDMax; // max volID for this detector (for sensors only) - Int_t fNSensors; // number of sensors (i.e. volID's) - Int_t* fSID2VolID; //[fNSensors] table of conversion from VolID to sid - Int_t fNProcPoints; // total number of points processed + Int_t fNDOFs; // number of DOFs free + Int_t fVolIDMin; // min volID for this detector (for sensors only) + Int_t fVolIDMax; // max volID for this detector (for sensors only) + Int_t fNSensors; // number of sensors (i.e. volID's) + Int_t* fSID2VolID; //[fNSensors] table of conversion from VolID to sid + Int_t fNProcPoints; // total number of points processed // // Detector specific calibration degrees of freedom - Int_t fNCalibDOF; // number of calibDOFs for detector (preset) - Int_t fNCalibDOFFree; // number of calibDOFs for detector (preset) - ULong64_t fCalibDOF; // status of calib dof - Int_t fFirstParGloID; // ID of the 1st parameter in the global results array - Float_t* fParVals; //! values of the fitted params - Float_t* fParErrs; //! errors of the fitted params - Int_t* fParLabs; //! labels for parameters + Int_t fNCalibDOF; // number of calibDOFs for detector (preset) + Int_t fNCalibDOFFree; // number of calibDOFs for detector (preset) + ULong64_t fCalibDOF; // status of calib dof + Int_t fFirstParGloID; // ID of the 1st parameter in the global results array + Float_t* fParVals; //! values of the fitted params + Float_t* fParErrs; //! errors of the fitted params + Int_t* fParLabs; //! labels for parameters // // Track selection - Bool_t fDisabled[AliAlgAux::kNTrackTypes]; // detector disabled/enabled in the track - Bool_t fObligatory[AliAlgAux::kNTrackTypes]; // detector must be present in the track - ULong_t fTrackFlagSel[AliAlgAux::kNTrackTypes]; // flag for track selection - Int_t fNPointsSel[AliAlgAux::kNTrackTypes]; // min number of points to require + Bool_t fDisabled[AliAlgAux::kNTrackTypes]; // detector disabled/enabled in the track + Bool_t fObligatory[AliAlgAux::kNTrackTypes]; // detector must be present in the track + ULong_t fTrackFlagSel[AliAlgAux::kNTrackTypes]; // flag for track selection + Int_t fNPointsSel[AliAlgAux::kNTrackTypes]; // min number of points to require // - Int_t fUseErrorParam; // signal that points need to be updated using track info, 0 - no - Double_t fAddError[2]; // additional error increment for measurement - TObjArray fSensors; // all sensors of the detector - TObjArray fVolumes; // all volumes of the detector + Int_t fUseErrorParam; // signal that points need to be updated using track info, 0 - no + Double_t fAddError[2]; // additional error increment for measurement + TObjArray fSensors; // all sensors of the detector + TObjArray fVolumes; // all volumes of the detector // // this is transient info - Int_t fNPoints; //! number of points from this detector - Int_t fPoolNPoints; //! number of points in the pool - Int_t fPoolFreePointID; //! id of the last free point in the pool - TObjArray fPointsPool; //! pool of aligment points + Int_t fNPoints; //! number of points from this detector + Int_t fPoolNPoints; //! number of points in the pool + Int_t fPoolFreePointID; //! id of the last free point in the pool + TObjArray fPointsPool; //! pool of aligment points // - AliAlgSteer* fAlgSteer; // pointer to alignment steering object + AliAlgSteer* fAlgSteer; // pointer to alignment steering object // - ClassDef(AliAlgDet,1); // base class for detector global alignment + ClassDef(AliAlgDet, 1); // base class for detector global alignment }; //_____________________________________________________ -inline Bool_t AliAlgDet::CheckFlags(const AliESDtrack* trc,Int_t trtype) const +inline Bool_t AliAlgDet::CheckFlags(const AliESDtrack* trc, Int_t trtype) const { // check if flags are ok - return (trc->GetStatus()&fTrackFlagSel[trtype]) == fTrackFlagSel[trtype]; + return (trc->GetStatus() & fTrackFlagSel[trtype]) == fTrackFlagSel[trtype]; } - +} // namespace align +} // namespace o2 #endif diff --git a/Detectors/Align/include/Align/AliAlgDetHMPID.h b/Detectors/Align/include/Align/AliAlgDetHMPID.h index 2444fef0b6d08..01f3924907f57 100644 --- a/Detectors/Align/include/Align/AliAlgDetHMPID.h +++ b/Detectors/Align/include/Align/AliAlgDetHMPID.h @@ -1,21 +1,34 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgDetHMPID.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief HMPID detector wrapper + #ifndef ALIALGDETHMPID_H #define ALIALGDETHMPID_H #include "AliAlgDet.h" -/*-------------------------------------------------------- - HMPID detector wrapper - -------------------------------------------------------*/ - -// Author: ruben.shahoyan@cern.ch - +namespace o2 +{ +namespace align +{ class AliAlgDetHMPID : public AliAlgDet { public: - AliAlgDetHMPID(const char* title=""); + AliAlgDetHMPID(const char* title = ""); virtual ~AliAlgDetHMPID(); // - virtual void DefineVolumes(); + virtual void DefineVolumes(); // Bool_t AcceptTrack(const AliESDtrack* trc, Int_t trtype) const; // @@ -26,8 +39,8 @@ class AliAlgDetHMPID : public AliAlgDet AliAlgDetHMPID& operator=(const AliAlgDetHMPID&); // protected: - - ClassDef(AliAlgDetHMPID,1); + ClassDef(AliAlgDetHMPID, 1); }; - +} // namespace align +} // namespace o2 #endif diff --git a/Detectors/Align/include/Align/AliAlgDetITS.h b/Detectors/Align/include/Align/AliAlgDetITS.h index c450644fc4704..6b2985ef3fef7 100644 --- a/Detectors/Align/include/Align/AliAlgDetITS.h +++ b/Detectors/Align/include/Align/AliAlgDetITS.h @@ -1,50 +1,68 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgDetITS.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief ITS detector wrapper + #ifndef ALIALGDETITS_H #define ALIALGDETITS_H #include "AliAlgDet.h" #include "AliAlgAux.h" -/*-------------------------------------------------------- - ITS detector wrapper - -------------------------------------------------------*/ - -// Author: ruben.shahoyan@cern.ch - +namespace o2 +{ +namespace align +{ class AliAlgDetITS : public AliAlgDet { public: // - enum ITSSel_t {kSPDNoSel,kSPDBoth,kSPDAny,kSPD0,kSPD1,kNSPDSelTypes}; + enum ITSSel_t { kSPDNoSel, + kSPDBoth, + kSPDAny, + kSPD0, + kSPD1, + kNSPDSelTypes }; // - AliAlgDetITS(const char* title=""); + AliAlgDetITS(const char* title = ""); virtual ~AliAlgDetITS(); // - virtual void DefineVolumes(); + virtual void DefineVolumes(); // - Bool_t AcceptTrack(const AliESDtrack* trc,Int_t trtype) const; + Bool_t AcceptTrack(const AliESDtrack* trc, Int_t trtype) const; - void SetAddErrorLr(int ilr, double sigY, double sigZ); - void SetSkipLr(int ilr); - // - virtual void UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const; - virtual void SetUseErrorParam(Int_t v=1); - void SetITSSelPattern(Int_t trtype, ITSSel_t sel) {fITSPatt[trtype]=sel;} - void SetITSSelPatternColl(ITSSel_t sel=kSPDAny) {SetITSSelPattern(AliAlgAux::kColl,sel);} - void SetITSSelPatternCosm(ITSSel_t sel=kSPDNoSel) {SetITSSelPattern(AliAlgAux::kCosm,sel);} + void SetAddErrorLr(int ilr, double sigY, double sigZ); + void SetSkipLr(int ilr); + // + virtual void UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const; + virtual void SetUseErrorParam(Int_t v = 1); + void SetITSSelPattern(Int_t trtype, ITSSel_t sel) { fITSPatt[trtype] = sel; } + void SetITSSelPatternColl(ITSSel_t sel = kSPDAny) { SetITSSelPattern(AliAlgAux::kColl, sel); } + void SetITSSelPatternCosm(ITSSel_t sel = kSPDNoSel) { SetITSSelPattern(AliAlgAux::kCosm, sel); } - Int_t GetITSSelPattern(int tp) const {return fITSPatt[tp];} - Int_t GetITSSelPatternColl() const {return fITSPatt[AliAlgAux::kColl];} - Int_t GetITSSelPatternCosm() const {return fITSPatt[AliAlgAux::kCosm];} + Int_t GetITSSelPattern(int tp) const { return fITSPatt[tp]; } + Int_t GetITSSelPatternColl() const { return fITSPatt[AliAlgAux::kColl]; } + Int_t GetITSSelPatternCosm() const { return fITSPatt[AliAlgAux::kCosm]; } // - virtual void Print(const Option_t *opt="") const; + virtual void Print(const Option_t* opt = "") const; // static Bool_t CheckHitPattern(const AliESDtrack* trc, Int_t sel); - static const char* GetITSPattName(Int_t sel) {return sel class AliAlgTrack; -/*-------------------------------------------------------- - Millepede record in root format (can be converted to proper - pede binary format. - -------------------------------------------------------*/ - -// Author: ruben.shahoyan@cern.ch - +namespace o2 +{ +namespace align +{ class AliAlgMPRecord : public TObject { public: - enum {kCosmicBit=BIT(14)}; + enum { kCosmicBit = BIT(14) }; // AliAlgMPRecord(); virtual ~AliAlgMPRecord(); // - Int_t GetRun() const {return GetUniqueID();} - void SetRun(Int_t r) {SetUniqueID(r);} - UInt_t GetTimeStamp() const {return fTimeStamp;} - void SetTimeStamp(UInt_t t) {fTimeStamp = t;} - UInt_t GetTrackID() const {return fTrackID;} - void SetTrackID(UInt_t t) {fTrackID = t;} - Bool_t IsCosmic() const {return TestBit(kCosmicBit);} - void SetCosmic(Bool_t v=kTRUE) {SetBit(kCosmicBit,v);} - // - Int_t GetNVarGlo() const {return fNVarGlo;} - void SetNVarGlo(int n) {fNVarGlo = n;} - // - Int_t GetNResid() const {return fNResid;} - Int_t GetNVarLoc() const {return fNVarLoc;} - // - Int_t GetNDLoc(int id) const {return fNDLoc[id];} - Int_t GetNDGlo(int id) const {return fNDGlo[id];} - Int_t GetVolID(int id) const {return fVolID ? fVolID[id]-1:-1;} - Float_t GetResid(int id) const {return fResid[id];} - Float_t GetResErr(int id) const {return fResErr[id];} - // - Float_t GetChi2Ini() const {return fChi2Ini;} - Float_t GetQ2Pt() const {return fQ2Pt;} - Float_t GetTgl() const {return fTgl;} - Int_t GetNDLocTot() const {return fNDLocTot;} - Int_t GetNDGloTot() const {return fNDGloTot;} - const Float_t* GetArrGlo() const {return fDGlo;} - const Float_t* GetArrLoc() const {return fDLoc;} - const Short_t* GetArrLabLoc() const {return fIDLoc;} - const Int_t* GetArrLabGlo() const {return fIDGlo;} - // - Bool_t FillTrack(const AliAlgTrack* trc, const Int_t *id2Lab=0); - void DummyRecord(Float_t res, Float_t err, Float_t dGlo, Int_t labGlo); - // - void Resize(Int_t nresid, Int_t nloc, Int_t nglo); - // - virtual void Clear(const Option_t *opt=""); - virtual void Print(const Option_t *opt="") const; + Int_t GetRun() const { return GetUniqueID(); } + void SetRun(Int_t r) { SetUniqueID(r); } + UInt_t GetTimeStamp() const { return fTimeStamp; } + void SetTimeStamp(UInt_t t) { fTimeStamp = t; } + UInt_t GetTrackID() const { return fTrackID; } + void SetTrackID(UInt_t t) { fTrackID = t; } + Bool_t IsCosmic() const { return TestBit(kCosmicBit); } + void SetCosmic(Bool_t v = kTRUE) { SetBit(kCosmicBit, v); } + // + Int_t GetNVarGlo() const { return fNVarGlo; } + void SetNVarGlo(int n) { fNVarGlo = n; } + // + Int_t GetNResid() const { return fNResid; } + Int_t GetNVarLoc() const { return fNVarLoc; } + // + Int_t GetNDLoc(int id) const { return fNDLoc[id]; } + Int_t GetNDGlo(int id) const { return fNDGlo[id]; } + Int_t GetVolID(int id) const { return fVolID ? fVolID[id] - 1 : -1; } + Float_t GetResid(int id) const { return fResid[id]; } + Float_t GetResErr(int id) const { return fResErr[id]; } + // + Float_t GetChi2Ini() const { return fChi2Ini; } + Float_t GetQ2Pt() const { return fQ2Pt; } + Float_t GetTgl() const { return fTgl; } + Int_t GetNDLocTot() const { return fNDLocTot; } + Int_t GetNDGloTot() const { return fNDGloTot; } + const Float_t* GetArrGlo() const { return fDGlo; } + const Float_t* GetArrLoc() const { return fDLoc; } + const Short_t* GetArrLabLoc() const { return fIDLoc; } + const Int_t* GetArrLabGlo() const { return fIDGlo; } + // + Bool_t FillTrack(const AliAlgTrack* trc, const Int_t* id2Lab = 0); + void DummyRecord(Float_t res, Float_t err, Float_t dGlo, Int_t labGlo); + // + void Resize(Int_t nresid, Int_t nloc, Int_t nglo); + // + virtual void Clear(const Option_t* opt = ""); + virtual void Print(const Option_t* opt = "") const; // protected: // // ------- dummies -------- AliAlgMPRecord(const AliAlgMPRecord&); AliAlgMPRecord& operator=(const AliAlgMPRecord&); - // + // protected: // - UInt_t fTrackID; // track in the event - UInt_t fTimeStamp; // event time stamp - Int_t fNResid; // number of residuals for the track (=2 npoints) - Int_t fNVarLoc; // number of local variables for the track - Int_t fNVarGlo; // number of global variables defined - Int_t fNDLocTot; // total number of non-zero local derivatives - Int_t fNDGloTot; // total number of non-zero global derivatives - Int_t fNMeas; // number of measured points - Float_t fChi2Ini; // chi2 of initial kalman fit - Float_t fQ2Pt; // q/pt at ref point - Float_t fTgl; // dip angle at ref point - // - Short_t* fNDLoc; //[fNResid] number of non-0 local derivatives per residual - Int_t* fNDGlo; //[fNResid] number of non-0 global derivatives per residual - Int_t* fVolID; //[fNResid] volume id + 1 (0 - not a volume) - Float_t* fResid; //[fNResid] residuals - Float_t* fResErr; //[fNResid] error associated to residual - // - Short_t* fIDLoc; //[fNDLocTot] ID of local variables for non-0 local derivatives - Int_t* fIDGlo; //[fNDGloTot] ID of global variables for non-0 global derivatives - Float_t* fDLoc; //[fNDLocTot] non-0 local derivatives - Float_t* fDGlo; //[fNDGloTot] non-0 global derivatives + UInt_t fTrackID; // track in the event + UInt_t fTimeStamp; // event time stamp + Int_t fNResid; // number of residuals for the track (=2 npoints) + Int_t fNVarLoc; // number of local variables for the track + Int_t fNVarGlo; // number of global variables defined + Int_t fNDLocTot; // total number of non-zero local derivatives + Int_t fNDGloTot; // total number of non-zero global derivatives + Int_t fNMeas; // number of measured points + Float_t fChi2Ini; // chi2 of initial kalman fit + Float_t fQ2Pt; // q/pt at ref point + Float_t fTgl; // dip angle at ref point + // + Short_t* fNDLoc; //[fNResid] number of non-0 local derivatives per residual + Int_t* fNDGlo; //[fNResid] number of non-0 global derivatives per residual + Int_t* fVolID; //[fNResid] volume id + 1 (0 - not a volume) + Float_t* fResid; //[fNResid] residuals + Float_t* fResErr; //[fNResid] error associated to residual + // + Short_t* fIDLoc; //[fNDLocTot] ID of local variables for non-0 local derivatives + Int_t* fIDGlo; //[fNDGloTot] ID of global variables for non-0 global derivatives + Float_t* fDLoc; //[fNDLocTot] non-0 local derivatives + Float_t* fDGlo; //[fNDGloTot] non-0 global derivatives // // aux info - Int_t fNResidBook; //! number of slots booked for residuals - Int_t fNDLocTotBook; //! number of slots booked for local derivatives - Int_t fNDGloTotBook; //! number of slots booked for global derivatives + Int_t fNResidBook; //! number of slots booked for residuals + Int_t fNDLocTotBook; //! number of slots booked for local derivatives + Int_t fNDGloTotBook; //! number of slots booked for global derivatives // - ClassDef(AliAlgMPRecord,4); + ClassDef(AliAlgMPRecord, 4); }; - - +} // namespace align +} // namespace o2 #endif diff --git a/Detectors/Align/include/Align/AliAlgPoint.h b/Detectors/Align/include/Align/AliAlgPoint.h index ef12ea4d62833..07650e425cbe5 100644 --- a/Detectors/Align/include/Align/AliAlgPoint.h +++ b/Detectors/Align/include/Align/AliAlgPoint.h @@ -1,3 +1,25 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgPoint.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief Meausered point in the sensor. + +/** + * Meausered point in the sensor. + * The measurement is in the tracking frame. + * Apart from measurement may contain also material information. + * Cashes residuals and track positions at its reference X +*/ + #ifndef ALIALGPOINT_H #define ALIALGPOINT_H @@ -8,137 +30,163 @@ class AliExternalTrackParam; -/*-------------------------------------------------------- - Meausered point in the sensor. - The measurement is in the tracking frame. - Apart from measurement may contain also material information. - Cashes residuals and track positions at its reference X - -------------------------------------------------------*/ - -// Author: ruben.shahoyan@cern.ch - +namespace o2 +{ +namespace align +{ class AliAlgPoint : public TObject { public: - enum {kMaterialBit=BIT(14) // point contains material - ,kMeasurementBit=BIT(15) // point contains measurement - ,kUpdateFromTrackBit=BIT(16) // point needs to recalculate itself using track info - ,kVaryELossBit=BIT(17) // ELoss variation allowed - ,kUseBzOnly=BIT(18) // use only Bz component (ITS) - ,kInvDir=BIT(19) // propagation via this point is in decreasing X direction (upper cosmic leg) - ,kStatOK=BIT(20) // point is accounted in global statistics + enum { kMaterialBit = BIT(14) // point contains material + , + kMeasurementBit = BIT(15) // point contains measurement + , + kUpdateFromTrackBit = BIT(16) // point needs to recalculate itself using track info + , + kVaryELossBit = BIT(17) // ELoss variation allowed + , + kUseBzOnly = BIT(18) // use only Bz component (ITS) + , + kInvDir = BIT(19) // propagation via this point is in decreasing X direction (upper cosmic leg) + , + kStatOK = BIT(20) // point is accounted in global statistics }; - enum {kParY = 0 // track parameters - ,kParZ - ,kParSnp - ,kParTgl - ,kParQ2Pt, - kNMSPar=4,kNELossPar=1,kNMatDOFs=kNMSPar+kNELossPar}; - enum {kX,kY,kZ}; + enum { kParY = 0 // track parameters + , + kParZ, + kParSnp, + kParTgl, + kParQ2Pt, + kNMSPar = 4, + kNELossPar = 1, + kNMatDOFs = kNMSPar + kNELossPar }; + enum { kX, + kY, + kZ }; // AliAlgPoint(); - virtual ~AliAlgPoint() {} - // - void Init(); - void UpdatePointByTrackInfo(const AliExternalTrackParam* t); - // - Double_t GetAlphaSens() const {return fAlphaSens;} - Double_t GetXSens() const {return fXSens;} - Double_t GetXPoint() const {return fXSens + GetXTracking();} - Double_t GetXTracking() const {return fXYZTracking[0];} - Double_t GetYTracking() const {return fXYZTracking[1];} - Double_t GetZTracking() const {return fXYZTracking[2];} - const Double_t* GetYZTracking() const {return &fXYZTracking[1];} - const Double_t* GetXYZTracking() const {return fXYZTracking;} - const Double_t* GetYZErrTracking() const {return fErrYZTracking;} - // - const AliAlgSens* GetSensor() const {return fSensor;} - UInt_t GetVolID() const {return fSensor->GetVolID();} - void SetSensor(AliAlgSens* s) {fSensor = s;} - Int_t GetDetID() const {return fDetID;} - Int_t GetSID() const {return fSID;} - Int_t GetMinLocVarID() const {return fMinLocVarID;} - Int_t GetMaxLocVarID() const {return fMaxLocVarID;} - Int_t GetNMatPar() const; - Bool_t ContainsMaterial() const {return TestBit(kMaterialBit);} - Bool_t ContainsMeasurement() const {return TestBit(kMeasurementBit);} - Bool_t GetNeedUpdateFromTrack() const {return TestBit(kUpdateFromTrackBit);} - Bool_t GetELossVaried() const {return TestBit(kVaryELossBit);} - Bool_t GetUseBzOnly() const {return TestBit(kUseBzOnly);} - Bool_t IsInvDir() const {return TestBit(kInvDir);} - Bool_t IsStatOK() const {return TestBit(kStatOK);} - // - Double_t GetXTimesRho() const {return fXTimesRho;} - Double_t GetX2X0() const {return fX2X0;} - void SetXTimesRho(double v) {fXTimesRho = v;} - void SetX2X0(double v) {fX2X0 = v;} - // - void SetDetID(Int_t id) {fDetID = (Char_t)id;} - void SetSID(Int_t id) {fSID = (Short_t)id;} - // - void SetMinLocVarID(Int_t id) {fMinLocVarID = id;} - void SetMaxLocVarID(Int_t id) {fMaxLocVarID = id;} - void SetELossVaried(Bool_t v=kTRUE) {SetBit(kVaryELossBit,v);} - void SetContainsMaterial(Bool_t v=kTRUE) {SetBit(kMaterialBit,v);} - void SetContainsMeasurement(Bool_t v=kTRUE) {SetBit(kMeasurementBit,v);} - void SetNeedUpdateFromTrack(Bool_t v=kTRUE ) {SetBit(kUpdateFromTrackBit,v);} - void SetUseBzOnly(Bool_t v=kTRUE) {SetBit(kUseBzOnly,v);} - void SetInvDir(Bool_t v=kTRUE) {SetBit(kInvDir,v);} - void SetStatOK(Bool_t v=kTRUE) {SetBit(kStatOK,v);} - // - void GetResidualsDiag(const double* pos, double &resU, double &resV) const; - void DiagonalizeResiduals(double rY, double rZ, double &resU, double &resV) const; - // - void SetAlphaSens(double a) {fAlphaSens = a;} - void SetXSens(double x) {fXSens = x;} - void SetXYZTracking(const double r[3]) {for (int i=3;i--;) fXYZTracking[i]=r[i];} - void SetXYZTracking(double x,double y,double z); - void SetYZErrTracking(double sy2, double syz, double sz2); - void SetYZErrTracking(const double *err) {for (int i=3;i--;) fErrYZTracking[i]=err[i];} - Double_t GetErrDiag(int i) const {return fErrDiag[i];} - // - Double_t* GetTrParamWSA() const {return (Double_t*)fTrParamWSA;} - Double_t* GetTrParamWSB() const {return (Double_t*)fTrParamWSB;} - Double_t GetTrParamWSA(int ip) const {return fTrParamWSA[ip];} - Double_t GetTrParamWSB(int ip) const {return fTrParamWSB[ip];} - void GetTrWSA(AliExternalTrackParam& etp) const; - void GetTrWSB(AliExternalTrackParam& etp) const; - void SetTrParamWSA(const double* param) {for (int i=5;i--;) fTrParamWSA[i] = param[i];} - void SetTrParamWSB(const double* param) {for (int i=5;i--;) fTrParamWSB[i] = param[i];} - Double_t GetResidY() const {return GetTrParamWSA(kParY) - GetYTracking();} - Double_t GetResidZ() const {return GetTrParamWSA(kParZ) - GetZTracking();} - // - void SetMatCovDiagonalizationMatrix(const TMatrixD& d); - void SetMatCovDiag(const TVectorD& v); - void SetMatCovDiagElem(int i, double err2) {fMatCorrCov[i] = err2;} - void UnDiagMatCorr(const double* diag, double* nodiag) const; - void DiagMatCorr(const double* nodiag, double* diag) const; - void UnDiagMatCorr(const float* diag, float* nodiag) const; - void DiagMatCorr(const float* nodiag, float* diag) const; - // - void SetMatCorrExp(Double_t *p) {for (int i=5;i--;) fMatCorrExp[i] = p[i];} - Float_t* GetMatCorrExp() const {return (float*)fMatCorrExp;} - Float_t* GetMatCorrCov() const {return (float*)fMatCorrCov;} - // - void GetXYZGlo(Double_t r[3]) const; - Double_t GetPhiGlo() const; - Int_t GetAliceSector() const; - // - Int_t GetNGloDOFs() const {return fNGloDOFs;} - Int_t GetDGloOffs() const {return fDGloOffs;} - void SetNGloDOFs(int n) {fNGloDOFs = n;} - void SetDGloOffs(int n) {fDGloOffs = n;} - // - void IncrementStat(); - // - virtual void DumpCoordinates() const; + virtual ~AliAlgPoint() {} + // + void Init(); + void UpdatePointByTrackInfo(const AliExternalTrackParam* t); + // + Double_t GetAlphaSens() const { return fAlphaSens; } + Double_t GetXSens() const { return fXSens; } + Double_t GetXPoint() const { return fXSens + GetXTracking(); } + Double_t GetXTracking() const { return fXYZTracking[0]; } + Double_t GetYTracking() const { return fXYZTracking[1]; } + Double_t GetZTracking() const { return fXYZTracking[2]; } + const Double_t* GetYZTracking() const { return &fXYZTracking[1]; } + const Double_t* GetXYZTracking() const { return fXYZTracking; } + const Double_t* GetYZErrTracking() const { return fErrYZTracking; } + // + const AliAlgSens* GetSensor() const { return fSensor; } + UInt_t GetVolID() const { return fSensor->GetVolID(); } + void SetSensor(AliAlgSens* s) { fSensor = s; } + Int_t GetDetID() const { return fDetID; } + Int_t GetSID() const { return fSID; } + Int_t GetMinLocVarID() const { return fMinLocVarID; } + Int_t GetMaxLocVarID() const { return fMaxLocVarID; } + Int_t GetNMatPar() const; + Bool_t ContainsMaterial() const { return TestBit(kMaterialBit); } + Bool_t ContainsMeasurement() const { return TestBit(kMeasurementBit); } + Bool_t GetNeedUpdateFromTrack() const { return TestBit(kUpdateFromTrackBit); } + Bool_t GetELossVaried() const { return TestBit(kVaryELossBit); } + Bool_t GetUseBzOnly() const { return TestBit(kUseBzOnly); } + Bool_t IsInvDir() const { return TestBit(kInvDir); } + Bool_t IsStatOK() const { return TestBit(kStatOK); } + // + Double_t GetXTimesRho() const { return fXTimesRho; } + Double_t GetX2X0() const { return fX2X0; } + void SetXTimesRho(double v) { fXTimesRho = v; } + void SetX2X0(double v) { fX2X0 = v; } + // + void SetDetID(Int_t id) { fDetID = (Char_t)id; } + void SetSID(Int_t id) { fSID = (Short_t)id; } + // + void SetMinLocVarID(Int_t id) { fMinLocVarID = id; } + void SetMaxLocVarID(Int_t id) { fMaxLocVarID = id; } + void SetELossVaried(Bool_t v = kTRUE) { SetBit(kVaryELossBit, v); } + void SetContainsMaterial(Bool_t v = kTRUE) { SetBit(kMaterialBit, v); } + void SetContainsMeasurement(Bool_t v = kTRUE) { SetBit(kMeasurementBit, v); } + void SetNeedUpdateFromTrack(Bool_t v = kTRUE) { SetBit(kUpdateFromTrackBit, v); } + void SetUseBzOnly(Bool_t v = kTRUE) { SetBit(kUseBzOnly, v); } + void SetInvDir(Bool_t v = kTRUE) { SetBit(kInvDir, v); } + void SetStatOK(Bool_t v = kTRUE) { SetBit(kStatOK, v); } + // + void GetResidualsDiag(const double* pos, double& resU, double& resV) const; + void DiagonalizeResiduals(double rY, double rZ, double& resU, double& resV) const; + // + void SetAlphaSens(double a) { fAlphaSens = a; } + void SetXSens(double x) { fXSens = x; } + void SetXYZTracking(const double r[3]) + { + for (int i = 3; i--;) + fXYZTracking[i] = r[i]; + } + void SetXYZTracking(double x, double y, double z); + void SetYZErrTracking(double sy2, double syz, double sz2); + void SetYZErrTracking(const double* err) + { + for (int i = 3; i--;) + fErrYZTracking[i] = err[i]; + } + Double_t GetErrDiag(int i) const { return fErrDiag[i]; } + // + Double_t* GetTrParamWSA() const { return (Double_t*)fTrParamWSA; } + Double_t* GetTrParamWSB() const { return (Double_t*)fTrParamWSB; } + Double_t GetTrParamWSA(int ip) const { return fTrParamWSA[ip]; } + Double_t GetTrParamWSB(int ip) const { return fTrParamWSB[ip]; } + void GetTrWSA(AliExternalTrackParam& etp) const; + void GetTrWSB(AliExternalTrackParam& etp) const; + void SetTrParamWSA(const double* param) + { + for (int i = 5; i--;) + fTrParamWSA[i] = param[i]; + } + void SetTrParamWSB(const double* param) + { + for (int i = 5; i--;) + fTrParamWSB[i] = param[i]; + } + Double_t GetResidY() const { return GetTrParamWSA(kParY) - GetYTracking(); } + Double_t GetResidZ() const { return GetTrParamWSA(kParZ) - GetZTracking(); } + // + void SetMatCovDiagonalizationMatrix(const TMatrixD& d); + void SetMatCovDiag(const TVectorD& v); + void SetMatCovDiagElem(int i, double err2) { fMatCorrCov[i] = err2; } + void UnDiagMatCorr(const double* diag, double* nodiag) const; + void DiagMatCorr(const double* nodiag, double* diag) const; + void UnDiagMatCorr(const float* diag, float* nodiag) const; + void DiagMatCorr(const float* nodiag, float* diag) const; + // + void SetMatCorrExp(Double_t* p) + { + for (int i = 5; i--;) + fMatCorrExp[i] = p[i]; + } + Float_t* GetMatCorrExp() const { return (float*)fMatCorrExp; } + Float_t* GetMatCorrCov() const { return (float*)fMatCorrCov; } + // + void GetXYZGlo(Double_t r[3]) const; + Double_t GetPhiGlo() const; + Int_t GetAliceSector() const; + // + Int_t GetNGloDOFs() const { return fNGloDOFs; } + Int_t GetDGloOffs() const { return fDGloOffs; } + void SetNGloDOFs(int n) { fNGloDOFs = n; } + void SetDGloOffs(int n) { fDGloOffs = n; } + // + void IncrementStat(); + // + virtual void DumpCoordinates() const; virtual void Print(Option_t* option = "") const; virtual void Clear(Option_t* option = ""); // protected: - virtual Bool_t IsSortable() const {return kTRUE;} - virtual Int_t Compare(const TObject* a) const; + virtual Bool_t IsSortable() const { return kTRUE; } + virtual Int_t Compare(const TObject* a) const; // // ---------- dummies ---------- AliAlgPoint(const AliAlgPoint&); @@ -146,84 +194,88 @@ class AliAlgPoint : public TObject // protected: // - Int_t fMinLocVarID; // The residuals/derivatives depend on fNLocExtPar params - // and point params>=fMinLocVarID. - Int_t fMaxLocVarID; // The residuals/derivatives depend on fNLocExtPar params - // and point params=fMinLocVarID. + Int_t fMaxLocVarID; // The residuals/derivatives depend on fNLocExtPar params + // and point paramsIncrementStat(); SetStatOK(); } - - +} // namespace align +} // namespace o2 #endif diff --git a/Detectors/Align/include/Align/AliAlgRes.h b/Detectors/Align/include/Align/AliAlgRes.h index 55a1735ac9a39..e01a43862d230 100644 --- a/Detectors/Align/include/Align/AliAlgRes.h +++ b/Detectors/Align/include/Align/AliAlgRes.h @@ -1,3 +1,18 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgRes.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief Container for control residuals + #ifndef ALIALGRES_H #define ALIALGRES_H @@ -5,85 +20,88 @@ #include class AliAlgTrack; -/*-------------------------------------------------------- - Container for control residuals - -------------------------------------------------------*/ - -// Author: ruben.shahoyan@cern.ch - - +namespace o2 +{ +namespace align +{ -class AliAlgRes: public TObject +class AliAlgRes : public TObject { public: - enum {kCosmicBit=BIT(14),kVertexBit=BIT(15),kKalmanDoneBit=BIT(16)}; + enum { kCosmicBit = BIT(14), + kVertexBit = BIT(15), + kKalmanDoneBit = BIT(16) }; // AliAlgRes(); virtual ~AliAlgRes(); // - void SetRun(int r) {fRun = r;} - void SetBz(float v) {fBz = v;} - void SetTimeStamp(UInt_t v) {fTimeStamp = v;} - void SetTrackID(UInt_t v) {fTrackID = v;} - void SetNPoints(Int_t n) {fNPoints=n; Resize(n);} - // - Bool_t IsCosmic() const {return TestBit(kCosmicBit);} - Bool_t HasVertex() const {return TestBit(kVertexBit);} - void SetCosmic(Bool_t v=kTRUE) {SetBit(kCosmicBit,v);} - void SetHasVertex(Bool_t v=kTRUE) {SetBit(kVertexBit,v);} - // - Bool_t GetKalmanDone() const {return TestBit(kKalmanDoneBit);} - void SetKalmanDone(Bool_t v=kTRUE) {SetBit(kKalmanDoneBit,v);} - // - Int_t GetRun() const {return fRun;} - Float_t GetBz() const {return fBz;} - UInt_t GetTimeStamp() const {return fTimeStamp;} - UInt_t GetTrackID() const {return fTrackID;} - Int_t GetNPoints() const {return fNPoints;} - Int_t GetNBook() const {return fNBook;} - Float_t GetChi2() const {return fChi2;} - Float_t GetChi2Ini() const {return fChi2Ini;} - Float_t GetChi2K() const {return fChi2K;} - Float_t GetQ2Pt() const {return fQ2Pt;} - Float_t GetX(int i) const {return fX[i];} - Float_t GetY(int i) const {return fY[i];} - Float_t GetZ(int i) const {return fZ[i];} - Float_t GetSnp(int i) const {return fSnp[i];} - Float_t GetTgl(int i) const {return fTgl[i];} - Float_t GetAlpha(int i) const {return fAlpha[i];} - Float_t GetDY(int i) const {return fDY[i];} - Float_t GetDZ(int i) const {return fDZ[i];} - Float_t GetDYK(int i) const {return fDYK[i];} - Float_t GetDZK(int i) const {return fDZK[i];} - // - Float_t GetSigY2K(int i) const {return fSigY2K[i];} - Float_t GetSigYZK(int i) const {return fSigYZK[i];} - Float_t GetSigZ2K(int i) const {return fSigZ2K[i];} - Float_t GetSigmaYK(int i) const {return TMath::Sqrt(fSigY2K[i]);} - Float_t GetSigmaZK(int i) const {return TMath::Sqrt(fSigZ2K[i]);} - // - Float_t GetSigY2(int i) const {return fSigY2[i];} - Float_t GetSigYZ(int i) const {return fSigYZ[i];} - Float_t GetSigZ2(int i) const {return fSigZ2[i];} - Float_t GetSigmaY(int i) const {return TMath::Sqrt(fSigY2[i]);} - Float_t GetSigmaZ(int i) const {return TMath::Sqrt(fSigZ2[i]);} - // - Float_t GetSigY2Tot(int i) const {return fSigY2K[i]+fSigY2[i];} - Float_t GetSigYZTot(int i) const {return fSigYZK[i]+fSigYZ[i];} - Float_t GetSigZ2Tot(int i) const {return fSigZ2K[i]+fSigZ2[i];} - Float_t GetSigmaYTot(int i) const {return TMath::Sqrt(GetSigY2Tot(i));} - Float_t GetSigmaZTot(int i) const {return TMath::Sqrt(GetSigZ2Tot(i));} - // - Int_t GetVolID(int i) const {return fVolID[i];} - // - Float_t GetXLab(int i) const; - Float_t GetYLab(int i) const; - Float_t GetZLab(int i) const; - // - Bool_t FillTrack(AliAlgTrack* trc, Bool_t doKalman=kTRUE); - void Resize(Int_t n); - virtual void Clear(const Option_t *opt=""); - virtual void Print(const Option_t *opt="re") const; + void SetRun(int r) { fRun = r; } + void SetBz(float v) { fBz = v; } + void SetTimeStamp(UInt_t v) { fTimeStamp = v; } + void SetTrackID(UInt_t v) { fTrackID = v; } + void SetNPoints(Int_t n) + { + fNPoints = n; + Resize(n); + } + // + Bool_t IsCosmic() const { return TestBit(kCosmicBit); } + Bool_t HasVertex() const { return TestBit(kVertexBit); } + void SetCosmic(Bool_t v = kTRUE) { SetBit(kCosmicBit, v); } + void SetHasVertex(Bool_t v = kTRUE) { SetBit(kVertexBit, v); } + // + Bool_t GetKalmanDone() const { return TestBit(kKalmanDoneBit); } + void SetKalmanDone(Bool_t v = kTRUE) { SetBit(kKalmanDoneBit, v); } + // + Int_t GetRun() const { return fRun; } + Float_t GetBz() const { return fBz; } + UInt_t GetTimeStamp() const { return fTimeStamp; } + UInt_t GetTrackID() const { return fTrackID; } + Int_t GetNPoints() const { return fNPoints; } + Int_t GetNBook() const { return fNBook; } + Float_t GetChi2() const { return fChi2; } + Float_t GetChi2Ini() const { return fChi2Ini; } + Float_t GetChi2K() const { return fChi2K; } + Float_t GetQ2Pt() const { return fQ2Pt; } + Float_t GetX(int i) const { return fX[i]; } + Float_t GetY(int i) const { return fY[i]; } + Float_t GetZ(int i) const { return fZ[i]; } + Float_t GetSnp(int i) const { return fSnp[i]; } + Float_t GetTgl(int i) const { return fTgl[i]; } + Float_t GetAlpha(int i) const { return fAlpha[i]; } + Float_t GetDY(int i) const { return fDY[i]; } + Float_t GetDZ(int i) const { return fDZ[i]; } + Float_t GetDYK(int i) const { return fDYK[i]; } + Float_t GetDZK(int i) const { return fDZK[i]; } + // + Float_t GetSigY2K(int i) const { return fSigY2K[i]; } + Float_t GetSigYZK(int i) const { return fSigYZK[i]; } + Float_t GetSigZ2K(int i) const { return fSigZ2K[i]; } + Float_t GetSigmaYK(int i) const { return TMath::Sqrt(fSigY2K[i]); } + Float_t GetSigmaZK(int i) const { return TMath::Sqrt(fSigZ2K[i]); } + // + Float_t GetSigY2(int i) const { return fSigY2[i]; } + Float_t GetSigYZ(int i) const { return fSigYZ[i]; } + Float_t GetSigZ2(int i) const { return fSigZ2[i]; } + Float_t GetSigmaY(int i) const { return TMath::Sqrt(fSigY2[i]); } + Float_t GetSigmaZ(int i) const { return TMath::Sqrt(fSigZ2[i]); } + // + Float_t GetSigY2Tot(int i) const { return fSigY2K[i] + fSigY2[i]; } + Float_t GetSigYZTot(int i) const { return fSigYZK[i] + fSigYZ[i]; } + Float_t GetSigZ2Tot(int i) const { return fSigZ2K[i] + fSigZ2[i]; } + Float_t GetSigmaYTot(int i) const { return TMath::Sqrt(GetSigY2Tot(i)); } + Float_t GetSigmaZTot(int i) const { return TMath::Sqrt(GetSigZ2Tot(i)); } + // + Int_t GetVolID(int i) const { return fVolID[i]; } + // + Float_t GetXLab(int i) const; + Float_t GetYLab(int i) const; + Float_t GetZLab(int i) const; + // + Bool_t FillTrack(AliAlgTrack* trc, Bool_t doKalman = kTRUE); + void Resize(Int_t n); + virtual void Clear(const Option_t* opt = ""); + virtual void Print(const Option_t* opt = "re") const; // protected: // @@ -93,36 +111,37 @@ class AliAlgRes: public TObject // protected: // - Int_t fRun; // run - Float_t fBz; // field - UInt_t fTimeStamp; // event time - UInt_t fTrackID; // track ID - Int_t fNPoints; // n meas points - Int_t fNBook; //! booked lenfth - Float_t fChi2; // chi2 after solution - Float_t fChi2Ini; // chi2 before solution - Float_t fChi2K; // chi2 from kalman - Float_t fQ2Pt; // Q/Pt at reference point - Float_t* fX; //[fNPoints] tracking X of cluster - Float_t* fY; //[fNPoints] tracking Y of cluster - Float_t* fZ; //[fNPoints] tracking Z of cluster - Float_t* fSnp; //[fNPoints] track Snp - Float_t* fTgl; //[fNPoints] track Tgl - Float_t* fAlpha; //[fNPoints] track alpha - Float_t* fDY; //[fNPoints] Y residual (track - meas) - Float_t* fDZ; //[fNPoints] Z residual (track - meas) - Float_t* fDYK; //[fNPoints] Y residual (track - meas) Kalman - Float_t* fDZK; //[fNPoints] Z residual (track - meas) Kalman - Float_t* fSigY2; //[fNPoints] Y err^2 - Float_t* fSigYZ; //[fNPoints] YZ err - Float_t* fSigZ2; //[fNPoints] Z err^2 - Float_t* fSigY2K; //[fNPoints] Y err^2 of Kalman track smoothing - Float_t* fSigYZK; //[fNPoints] YZ err of Kalman track smoothing - Float_t* fSigZ2K; //[fNPoints] Z err^2 of Kalman track smoothing - Int_t* fVolID; //[fNPoints] volume id (0 for vertex constraint) - Int_t* fLabel; //[fNPoints] label of the volume - // - ClassDef(AliAlgRes,2); + Int_t fRun; // run + Float_t fBz; // field + UInt_t fTimeStamp; // event time + UInt_t fTrackID; // track ID + Int_t fNPoints; // n meas points + Int_t fNBook; //! booked lenfth + Float_t fChi2; // chi2 after solution + Float_t fChi2Ini; // chi2 before solution + Float_t fChi2K; // chi2 from kalman + Float_t fQ2Pt; // Q/Pt at reference point + Float_t* fX; //[fNPoints] tracking X of cluster + Float_t* fY; //[fNPoints] tracking Y of cluster + Float_t* fZ; //[fNPoints] tracking Z of cluster + Float_t* fSnp; //[fNPoints] track Snp + Float_t* fTgl; //[fNPoints] track Tgl + Float_t* fAlpha; //[fNPoints] track alpha + Float_t* fDY; //[fNPoints] Y residual (track - meas) + Float_t* fDZ; //[fNPoints] Z residual (track - meas) + Float_t* fDYK; //[fNPoints] Y residual (track - meas) Kalman + Float_t* fDZK; //[fNPoints] Z residual (track - meas) Kalman + Float_t* fSigY2; //[fNPoints] Y err^2 + Float_t* fSigYZ; //[fNPoints] YZ err + Float_t* fSigZ2; //[fNPoints] Z err^2 + Float_t* fSigY2K; //[fNPoints] Y err^2 of Kalman track smoothing + Float_t* fSigYZK; //[fNPoints] YZ err of Kalman track smoothing + Float_t* fSigZ2K; //[fNPoints] Z err^2 of Kalman track smoothing + Int_t* fVolID; //[fNPoints] volume id (0 for vertex constraint) + Int_t* fLabel; //[fNPoints] label of the volume + // + ClassDef(AliAlgRes, 2); }; - +} // namespace align +} // namespace o2 #endif diff --git a/Detectors/Align/include/Align/AliAlgResFast.h b/Detectors/Align/include/Align/AliAlgResFast.h index e82e2f627d39e..b48d722662467 100644 --- a/Detectors/Align/include/Align/AliAlgResFast.h +++ b/Detectors/Align/include/Align/AliAlgResFast.h @@ -1,65 +1,82 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgResFast.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief Container for control fast residuals evaluated via derivatives + #ifndef ALIALGRESFAST_H #define ALIALGRESFAST_H #include -/*-------------------------------------------------------- - Container for control fast residuals evaluated via derivatives - -------------------------------------------------------*/ - -// Author: ruben.shahoyan@cern.ch - - +namespace o2 +{ +namespace align +{ -class AliAlgResFast: public TObject +class AliAlgResFast : public TObject { public: - enum {kCosmicBit=BIT(14),kVertexBit=BIT(15)}; + enum { kCosmicBit = BIT(14), + kVertexBit = BIT(15) }; // AliAlgResFast(); virtual ~AliAlgResFast(); // - void SetNPoints(Int_t n) {fNPoints=n; Resize(n);} - void SetNMatSol(Int_t n) {fNMatSol = n;} - // - void SetChi2(float v) {fChi2 = v;} - Float_t GetChi2() const {return fChi2;} - // - void SetChi2Ini(float v) {fChi2Ini = v;} - Float_t GetChi2Ini() const {return fChi2Ini;} - // - Bool_t IsCosmic() const {return TestBit(kCosmicBit);} - Bool_t HasVertex() const {return TestBit(kVertexBit);} - void SetCosmic(Bool_t v=kTRUE) {SetBit(kCosmicBit,v);} - void SetHasVertex(Bool_t v=kTRUE) {SetBit(kVertexBit,v);} - // - Int_t GetNPoints() const {return fNPoints;} - Int_t GetNMatSol() const {return fNMatSol;} - Int_t GetNBook() const {return fNBook;} - Float_t GetD0(int i) const {return fD0[i];} - Float_t GetD1(int i) const {return fD1[i];} - Float_t GetSig0(int i) const {return fSig0[i];} - Float_t GetSig1(int i) const {return fSig1[i];} - Int_t GetVolID(int i) const {return fVolID[i];} - Int_t GetLabel(int i) const {return fLabel[i];} - // - Float_t* GetTrCor() const {return (Float_t*)fTrCorr;} - Float_t* GetD0() const {return (Float_t*)fD0;} - Float_t* GetD1() const {return (Float_t*)fD1;} - Float_t* GetSig0() const {return (Float_t*)fSig0;} - Float_t* GetSig1() const {return (Float_t*)fSig1;} - Int_t* GetVolID() const {return (Int_t*)fVolID;} - Int_t* GetLaber() const {return (Int_t*)fLabel;} - Float_t* GetSolMat() const {return (Float_t*)fSolMat;} - Float_t* GetMatErr() const {return (Float_t*)fMatErr;} - // - void SetResSigMeas(int ip, int ord, float res, float sig); - void SetMatCorr(int id, float res, float sig); - void SetLabel(int ip, Int_t lab, Int_t vol); - // - void Resize(Int_t n); - virtual void Clear(const Option_t *opt=""); - virtual void Print(const Option_t *opt="") const; + void SetNPoints(Int_t n) + { + fNPoints = n; + Resize(n); + } + void SetNMatSol(Int_t n) { fNMatSol = n; } + // + void SetChi2(float v) { fChi2 = v; } + Float_t GetChi2() const { return fChi2; } + // + void SetChi2Ini(float v) { fChi2Ini = v; } + Float_t GetChi2Ini() const { return fChi2Ini; } + // + Bool_t IsCosmic() const { return TestBit(kCosmicBit); } + Bool_t HasVertex() const { return TestBit(kVertexBit); } + void SetCosmic(Bool_t v = kTRUE) { SetBit(kCosmicBit, v); } + void SetHasVertex(Bool_t v = kTRUE) { SetBit(kVertexBit, v); } + // + Int_t GetNPoints() const { return fNPoints; } + Int_t GetNMatSol() const { return fNMatSol; } + Int_t GetNBook() const { return fNBook; } + Float_t GetD0(int i) const { return fD0[i]; } + Float_t GetD1(int i) const { return fD1[i]; } + Float_t GetSig0(int i) const { return fSig0[i]; } + Float_t GetSig1(int i) const { return fSig1[i]; } + Int_t GetVolID(int i) const { return fVolID[i]; } + Int_t GetLabel(int i) const { return fLabel[i]; } + // + Float_t* GetTrCor() const { return (Float_t*)fTrCorr; } + Float_t* GetD0() const { return (Float_t*)fD0; } + Float_t* GetD1() const { return (Float_t*)fD1; } + Float_t* GetSig0() const { return (Float_t*)fSig0; } + Float_t* GetSig1() const { return (Float_t*)fSig1; } + Int_t* GetVolID() const { return (Int_t*)fVolID; } + Int_t* GetLaber() const { return (Int_t*)fLabel; } + Float_t* GetSolMat() const { return (Float_t*)fSolMat; } + Float_t* GetMatErr() const { return (Float_t*)fMatErr; } + // + void SetResSigMeas(int ip, int ord, float res, float sig); + void SetMatCorr(int id, float res, float sig); + void SetLabel(int ip, Int_t lab, Int_t vol); + // + void Resize(Int_t n); + virtual void Clear(const Option_t* opt = ""); + virtual void Print(const Option_t* opt = "") const; // protected: // @@ -69,24 +86,25 @@ class AliAlgResFast: public TObject // protected: // - Int_t fNPoints; // n meas points - Int_t fNMatSol; // n local params - ExtTrPar corrections - Int_t fNBook; //! booked lenfth - Float_t fChi2; // chi2 - Float_t fChi2Ini; // chi2 before local fit - // - Float_t fTrCorr[5]; // correction to ExternalTrackParam - Float_t* fD0; //[fNPoints] 1st residual (track - meas) - Float_t* fD1; //[fNPoints] 2ns residual (track - meas) - Float_t* fSig0; //[fNPoints] ort. error 0 - Float_t* fSig1; //[fNPoints] ort. errir 1 - Int_t* fVolID; //[fNPoints] volume id (0 for vertex constraint) - Int_t* fLabel; //[fNPoints] label of the volume - // - Float_t* fSolMat; //[fNMatSol] // material corrections - Float_t* fMatErr; //[fNMatSol] // material corrections errors - // - ClassDef(AliAlgResFast,1); + Int_t fNPoints; // n meas points + Int_t fNMatSol; // n local params - ExtTrPar corrections + Int_t fNBook; //! booked lenfth + Float_t fChi2; // chi2 + Float_t fChi2Ini; // chi2 before local fit + // + Float_t fTrCorr[5]; // correction to ExternalTrackParam + Float_t* fD0; //[fNPoints] 1st residual (track - meas) + Float_t* fD1; //[fNPoints] 2ns residual (track - meas) + Float_t* fSig0; //[fNPoints] ort. error 0 + Float_t* fSig1; //[fNPoints] ort. errir 1 + Int_t* fVolID; //[fNPoints] volume id (0 for vertex constraint) + Int_t* fLabel; //[fNPoints] label of the volume + // + Float_t* fSolMat; //[fNMatSol] // material corrections + Float_t* fMatErr; //[fNMatSol] // material corrections errors + // + ClassDef(AliAlgResFast, 1); }; - +} // namespace align +} // namespace o2 #endif diff --git a/Detectors/Align/include/Align/AliAlgSens.h b/Detectors/Align/include/Align/AliAlgSens.h index 865a0271c2645..80fe8e25879d7 100644 --- a/Detectors/Align/include/Align/AliAlgSens.h +++ b/Detectors/Align/include/Align/AliAlgSens.h @@ -1,3 +1,18 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgSens.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief End-chain alignment volume in detector branch, where the actual measurement is done. + #ifndef ALIALGSENS_H #define ALIALGSENS_H @@ -13,71 +28,73 @@ class AliExternalTrackParam; class AliAlgDOFStat; class TCloneArray; -/*-------------------------------------------------------- - End-chain alignment volume in detector branch, where the actual measurement is done. - -------------------------------------------------------*/ - -// Author: ruben.shahoyan@cern.ch - +namespace o2 +{ +namespace align +{ class AliAlgSens : public AliAlgVol { public: // - AliAlgSens(const char* name=0, Int_t vid=0, Int_t iid=0); + AliAlgSens(const char* name = 0, Int_t vid = 0, Int_t iid = 0); virtual ~AliAlgSens(); // virtual void AddChild(AliAlgVol*); // - void SetDetector(AliAlgDet* det) {fDet = det;} - AliAlgDet* GetDetector() const {return fDet;} + void SetDetector(AliAlgDet* det) { fDet = det; } + AliAlgDet* GetDetector() const { return fDet; } // - Int_t GetSID() const {return fSID;} - void SetSID(int s) {fSID = s;} + Int_t GetSID() const { return fSID; } + void SetSID(int s) { fSID = s; } // - void IncrementStat() {fNProcPoints++;} + void IncrementStat() { fNProcPoints++; } // // derivatives calculation - virtual void DPosTraDParCalib(const AliAlgPoint* pnt,double* deriv,int calibID,const AliAlgVol* parent=0) const; - virtual void DPosTraDParGeom(const AliAlgPoint* pnt, double* deriv,const AliAlgVol* parent=0) const; + virtual void DPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int calibID, const AliAlgVol* parent = 0) const; + virtual void DPosTraDParGeom(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent = 0) const; // virtual void DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv) const; virtual void DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv) const; virtual void DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const; virtual void DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const; // - void GetModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const Double_t *delta) const; - void GetModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const Double_t *delta) const; + void GetModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const Double_t* delta) const; + void GetModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const Double_t* delta) const; // virtual void ApplyAlignmentFromMPSol(); // - void SetAddError(double y, double z) {fAddError[0]=y;fAddError[1]=z;} - const Double_t* GetAddError() const {return fAddError;} + void SetAddError(double y, double z) + { + fAddError[0] = y; + fAddError[1] = z; + } + const Double_t* GetAddError() const { return fAddError; } // - virtual void PrepareMatrixT2L(); + virtual void PrepareMatrixT2L(); // - virtual void SetTrackingFrame(); - virtual Bool_t IsSensor() const {return kTRUE;} - virtual void Print(const Option_t *opt="") const; + virtual void SetTrackingFrame(); + virtual Bool_t IsSensor() const { return kTRUE; } + virtual void Print(const Option_t* opt = "") const; // - virtual void UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const; - virtual void UpdateL2GRecoMatrices(const TClonesArray* algArr,const TGeoHMatrix* cumulDelta); + virtual void UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const; + virtual void UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta); // - virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t) = 0; + virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t) = 0; // - virtual Int_t FinalizeStat(AliAlgDOFStat* h=0); + virtual Int_t FinalizeStat(AliAlgDOFStat* h = 0); // virtual void PrepareMatrixClAlg(); virtual void PrepareMatrixClAlgReco(); - const TGeoHMatrix& GetMatrixClAlg() const {return fMatClAlg;} - const TGeoHMatrix& GetMatrixClAlgReco() const {return fMatClAlgReco;} - void SetMatrixClAlg(const TGeoHMatrix& m) {fMatClAlg = m;} - void SetMatrixClAlgReco(const TGeoHMatrix& m) {fMatClAlgReco = m;} + const TGeoHMatrix& GetMatrixClAlg() const { return fMatClAlg; } + const TGeoHMatrix& GetMatrixClAlgReco() const { return fMatClAlgReco; } + void SetMatrixClAlg(const TGeoHMatrix& m) { fMatClAlg = m; } + void SetMatrixClAlgReco(const TGeoHMatrix& m) { fMatClAlgReco = m; } // protected: // - virtual Bool_t IsSortable() const {return kTRUE;} - virtual Int_t Compare(const TObject* a) const; + virtual Bool_t IsSortable() const { return kTRUE; } + virtual Int_t Compare(const TObject* a) const; // // --------- dummies ----------- AliAlgSens(const AliAlgSens&); @@ -85,15 +102,16 @@ class AliAlgSens : public AliAlgVol // protected: // - Int_t fSID; // sensor id in detector - Double_t fAddError[2]; // additional error increment for measurement - AliAlgDet* fDet; // pointer on detector - TGeoHMatrix fMatClAlg; // reference cluster alignment matrix in tracking frame - TGeoHMatrix fMatClAlgReco; // reco-time cluster alignment matrix in tracking frame + Int_t fSID; // sensor id in detector + Double_t fAddError[2]; // additional error increment for measurement + AliAlgDet* fDet; // pointer on detector + TGeoHMatrix fMatClAlg; // reference cluster alignment matrix in tracking frame + TGeoHMatrix fMatClAlgReco; // reco-time cluster alignment matrix in tracking frame // - ClassDef(AliAlgSens,1) + ClassDef(AliAlgSens, 1) }; - +} // namespace align +} // namespace o2 #endif diff --git a/Detectors/Align/include/Align/AliAlgSensHMPID.h b/Detectors/Align/include/Align/AliAlgSensHMPID.h index b562465da0d90..2868bba25d7ce 100644 --- a/Detectors/Align/include/Align/AliAlgSensHMPID.h +++ b/Detectors/Align/include/Align/AliAlgSensHMPID.h @@ -1,26 +1,37 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgSensHMPID.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief HMPID sensor (chamber) + #ifndef ALIALGSENSHMPID_H #define ALIALGSENSHMPID_H #include "AliAlgSens.h" - class TObjArray; class AliTrackPointArray; class AliESDtrack; class AliAlgPoint; - -/*-------------------------------------------------------- - HMPID sensor (chamber) - -------------------------------------------------------*/ - -// Author: ruben.shahoyan@cern.ch - +namespace o2 +{ +namespace align +{ class AliAlgSensHMPID : public AliAlgSens { public: - AliAlgSensHMPID(const char* name=0, Int_t vid=0, Int_t iid=0, Int_t isec=0); + AliAlgSensHMPID(const char* name = 0, Int_t vid = 0, Int_t iid = 0, Int_t isec = 0); virtual ~AliAlgSensHMPID(); // virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); @@ -29,8 +40,8 @@ class AliAlgSensHMPID : public AliAlgSens // protected: // - ClassDef(AliAlgSensHMPID,1) + ClassDef(AliAlgSensHMPID, 1) }; - - +} // namespace align +} // namespace o2 #endif diff --git a/Detectors/Align/include/Align/AliAlgSensITS.h b/Detectors/Align/include/Align/AliAlgSensITS.h index 0ee39e37e163b..bff2ca77f9071 100644 --- a/Detectors/Align/include/Align/AliAlgSensITS.h +++ b/Detectors/Align/include/Align/AliAlgSensITS.h @@ -1,26 +1,37 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgSensITS.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief ITS sensor + #ifndef ALIALGSENSITS_H #define ALIALGSENSITS_H #include "AliAlgSens.h" - class TObjArray; class AliTrackPointArray; class AliESDtrack; class AliAlgPoint; - -/*-------------------------------------------------------- - ITS sensor - -------------------------------------------------------*/ - -// Author: ruben.shahoyan@cern.ch - +namespace o2 +{ +namespace align +{ class AliAlgSensITS : public AliAlgSens { public: - AliAlgSensITS(const char* name=0, Int_t vid=0, Int_t iid=0); + AliAlgSensITS(const char* name = 0, Int_t vid = 0, Int_t iid = 0); virtual ~AliAlgSensITS(); // virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); @@ -29,8 +40,8 @@ class AliAlgSensITS : public AliAlgSens // protected: // - ClassDef(AliAlgSensITS,1) + ClassDef(AliAlgSensITS, 1) }; - - +} // namespace align +} // namespace o2 #endif diff --git a/Detectors/Align/include/Align/AliAlgSensTOF.h b/Detectors/Align/include/Align/AliAlgSensTOF.h index fab786a58da87..8fad11107e62c 100644 --- a/Detectors/Align/include/Align/AliAlgSensTOF.h +++ b/Detectors/Align/include/Align/AliAlgSensTOF.h @@ -1,3 +1,18 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgSensTOF.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief TOF sensor + #ifndef ALIALGSENSTOF_H #define ALIALGSENSTOF_H @@ -8,33 +23,30 @@ class AliESDtrack; class AliAlgPoint; class TObjArray; - -/*-------------------------------------------------------- - TOF sensor - -------------------------------------------------------*/ - -// Author: ruben.shahoyan@cern.ch - +namespace o2 +{ +namespace align +{ class AliAlgSensTOF : public AliAlgSens { public: - AliAlgSensTOF(const char* name=0, Int_t vid=0, Int_t iid=0, Int_t isec=0); + AliAlgSensTOF(const char* name = 0, Int_t vid = 0, Int_t iid = 0, Int_t isec = 0); virtual ~AliAlgSensTOF(); // virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); // virtual void SetTrackingFrame(); virtual void PrepareMatrixT2L(); // - Int_t GetSector() const {return fSector;} - void SetSector(UInt_t sc) {fSector = (UChar_t)sc;} + Int_t GetSector() const { return fSector; } + void SetSector(UInt_t sc) { fSector = (UChar_t)sc; } // protected: // - UChar_t fSector; // sector ID + UChar_t fSector; // sector ID // - ClassDef(AliAlgSensTOF,1) + ClassDef(AliAlgSensTOF, 1) }; - - +} // namespace align +} // namespace o2 #endif diff --git a/Detectors/Align/include/Align/AliAlgSensTPC.h b/Detectors/Align/include/Align/AliAlgSensTPC.h index ef8822ad61d13..c95f2a648f357 100644 --- a/Detectors/Align/include/Align/AliAlgSensTPC.h +++ b/Detectors/Align/include/Align/AliAlgSensTPC.h @@ -1,30 +1,41 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgSensTPC.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief TPC sensor (chamber) + #ifndef ALIALGSENSTPC_H #define ALIALGSENSTPC_H #include "AliAlgSens.h" - class TObjArray; class AliTrackPointArray; class AliESDtrack; class AliAlgPoint; - -/*-------------------------------------------------------- - TPC sensor (chamber) - -------------------------------------------------------*/ - -// Author: ruben.shahoyan@cern.ch - +namespace o2 +{ +namespace align +{ class AliAlgSensTPC : public AliAlgSens { public: - AliAlgSensTPC(const char* name=0, Int_t vid=0, Int_t iid=0, Int_t isec=0); + AliAlgSensTPC(const char* name = 0, Int_t vid = 0, Int_t iid = 0, Int_t isec = 0); virtual ~AliAlgSensTPC(); // - Int_t GetSector() const {return fSector;} - void SetSector(UInt_t sc) {fSector = (UChar_t)sc;} + Int_t GetSector() const { return fSector; } + void SetSector(UInt_t sc) { fSector = (UChar_t)sc; } // virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); // virtual void SetTrackingFrame(); @@ -32,10 +43,10 @@ class AliAlgSensTPC : public AliAlgSens // protected: // - UChar_t fSector; // sector ID + UChar_t fSector; // sector ID - ClassDef(AliAlgSensTPC,1) + ClassDef(AliAlgSensTPC, 1) }; - - +} // namespace align +} // namespace o2 #endif diff --git a/Detectors/Align/include/Align/AliAlgSensTRD.h b/Detectors/Align/include/Align/AliAlgSensTRD.h index d0c6d094a8416..09cc540e0f369 100644 --- a/Detectors/Align/include/Align/AliAlgSensTRD.h +++ b/Detectors/Align/include/Align/AliAlgSensTRD.h @@ -1,3 +1,18 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgSensTRD.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief TRD sensor + #ifndef ALIALGSENSTRD_H #define ALIALGSENSTRD_H @@ -7,36 +22,33 @@ class AliESDtrack; class AliAlgPoint; class TObjArray; - -/*-------------------------------------------------------- - TRD sensor - -------------------------------------------------------*/ - -// Author: ruben.shahoyan@cern.ch - +namespace o2 +{ +namespace align +{ class AliAlgSensTRD : public AliAlgSens { public: - AliAlgSensTRD(const char* name=0, Int_t vid=0, Int_t iid=0, Int_t isec=0); + AliAlgSensTRD(const char* name = 0, Int_t vid = 0, Int_t iid = 0, Int_t isec = 0); virtual ~AliAlgSensTRD(); // - Int_t GetSector() const {return fSector;} - void SetSector(UInt_t sc) {fSector = (UChar_t)sc;} + Int_t GetSector() const { return fSector; } + void SetSector(UInt_t sc) { fSector = (UChar_t)sc; } // virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); // - virtual void DPosTraDParCalib(const AliAlgPoint* pnt,double* deriv,int calibID,const AliAlgVol* parent=0) const; + virtual void DPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int calibID, const AliAlgVol* parent = 0) const; // // virtual void SetTrackingFrame(); virtual void PrepareMatrixT2L(); // protected: // - UChar_t fSector; // sector ID + UChar_t fSector; // sector ID - ClassDef(AliAlgSensTRD,1) + ClassDef(AliAlgSensTRD, 1) }; - - +} // namespace align +} // namespace o2 #endif diff --git a/Detectors/Align/include/Align/AliAlgSteer.h b/Detectors/Align/include/Align/AliAlgSteer.h index 31a6b3a79f168..e81c621d56136 100644 --- a/Detectors/Align/include/Align/AliAlgSteer.h +++ b/Detectors/Align/include/Align/AliAlgSteer.h @@ -1,3 +1,23 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgSteer.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief Steering class for the global alignment + +/** + * Steering class for the global alignment. Responsible for feeding the track data + * to participating detectors and preparation of the millepede input. + */ + #ifndef ALIALGSTEER_H #define ALIALGSTEER_H @@ -32,273 +52,325 @@ class TFile; // class Mille; - -/*-------------------------------------------------------- - Steering class for the global alignment. Responsible for feeding the track data - to participating detectors and preparation of the millepede input. - -------------------------------------------------------*/ - -// Author: ruben.shahoyan@cern.ch - +namespace o2 +{ +namespace align +{ class AliAlgSteer : public TObject { public: - enum {kNLrSkip=4}; - enum {kITS,kTPC,kTRD,kTOF,kHMPID,kNDetectors, kUndefined}; - enum {kCosmLow,kCosmUp,kNCosmLegs}; - enum {kInpStat,kAccStat,kNStatCl}; - enum {kRun,kEventColl,kEventCosm,kTrackColl,kTrackCosm, kMaxStat}; - enum MPOut_t {kMille=BIT(0),kMPRec=BIT(1),kContR=BIT(2)}; - enum {kInitGeomDone=BIT(14),kInitDOFsDone=BIT(15),kMPAlignDone=BIT(16)}; - // - enum { // STAT histo entries - kRunDone // input runs - ,kEvInp // input events - ,kEvVtx // after vtx selection - ,kTrackInp // input tracks - ,kTrackFitInp // input to ini fit - ,kTrackFitInpVC // those with vertex constraint - ,kTrackProcMatInp// input to process materials - ,kTrackResDerInp // input to resid/deriv calculation - ,kTrackStore // stored tracks - ,kTrackAcc // tracks accepted - ,kTrackControl // control tracks filled + enum { kNLrSkip = 4 }; + enum { kITS, + kTPC, + kTRD, + kTOF, + kHMPID, + kNDetectors, + kUndefined }; + enum { kCosmLow, + kCosmUp, + kNCosmLegs }; + enum { kInpStat, + kAccStat, + kNStatCl }; + enum { kRun, + kEventColl, + kEventCosm, + kTrackColl, + kTrackCosm, + kMaxStat }; + enum MPOut_t { kMille = BIT(0), + kMPRec = BIT(1), + kContR = BIT(2) }; + enum { kInitGeomDone = BIT(14), + kInitDOFsDone = BIT(15), + kMPAlignDone = BIT(16) }; + // + enum { // STAT histo entries + kRunDone // input runs + , + kEvInp // input events + , + kEvVtx // after vtx selection + , + kTrackInp // input tracks + , + kTrackFitInp // input to ini fit + , + kTrackFitInpVC // those with vertex constraint + , + kTrackProcMatInp // input to process materials + , + kTrackResDerInp // input to resid/deriv calculation + , + kTrackStore // stored tracks + , + kTrackAcc // tracks accepted + , + kTrackControl // control tracks filled // - ,kNHVars + , + kNHVars }; // - AliAlgSteer(const char* configMacro=0, int refRun=-1); + AliAlgSteer(const char* configMacro = 0, int refRun = -1); virtual ~AliAlgSteer(); - Bool_t LoadRefOCDB(); - Bool_t LoadRecoTimeOCDB(); - Bool_t GetUseRecoOCDB() const {return fUseRecoOCDB;} - void SetUseRecoOCDB(Bool_t v=kTRUE) {fUseRecoOCDB=v;} + Bool_t LoadRefOCDB(); + Bool_t LoadRecoTimeOCDB(); + Bool_t GetUseRecoOCDB() const { return fUseRecoOCDB; } + void SetUseRecoOCDB(Bool_t v = kTRUE) { fUseRecoOCDB = v; } - void InitDetectors(); - void InitDOFs(); - void Terminate(Bool_t dostat=kTRUE); - void SetStatHistoLabels(TH1* h) const; + void InitDetectors(); + void InitDOFs(); + void Terminate(Bool_t dostat = kTRUE); + void SetStatHistoLabels(TH1* h) const; // - void SetInitGeomDone() {SetBit(kInitGeomDone);} - Bool_t GetInitGeomDone() const {return TestBit(kInitGeomDone);} + void SetInitGeomDone() { SetBit(kInitGeomDone); } + Bool_t GetInitGeomDone() const { return TestBit(kInitGeomDone); } // - void SetInitDOFsDone() {SetBit(kInitDOFsDone);} - Bool_t GetInitDOFsDone() const {return TestBit(kInitDOFsDone);} + void SetInitDOFsDone() { SetBit(kInitDOFsDone); } + Bool_t GetInitDOFsDone() const { return TestBit(kInitDOFsDone); } // - void SetMPAlignDone() {SetBit(kMPAlignDone);} - Bool_t GetMPAlignDone() const {return TestBit(kMPAlignDone);} + void SetMPAlignDone() { SetBit(kMPAlignDone); } + Bool_t GetMPAlignDone() const { return TestBit(kMPAlignDone); } - void AssignDOFs(); - // - void AddDetector(UInt_t id, AliAlgDet* det=0); - void AddDetector(AliAlgDet* det); - // - void AddConstraint(const AliAlgConstraint* cs) {fConstraints.AddLast((TObject*)cs);} - Int_t GetNConstraints() const {return fConstraints.GetEntriesFast();} - const TObjArray* GetConstraints() const {return &fConstraints;} - const AliAlgConstraint* GetConstraint(int i) const {return (AliAlgConstraint*)fConstraints[i];} - void AddAutoConstraints(); - // - void AcknowledgeNewRun(Int_t run); - void SetRunNumber(Int_t run); - Int_t GetRunNumber() const {return fRunNumber;} - Bool_t GetFieldOn() const {return fFieldOn;} - void SetFieldOn(Bool_t v=kTRUE) {fFieldOn = v;} - Int_t GetTracksType() const {return fTracksType;} - void SetTracksType(Int_t t=AliAlgAux::kColl) {fTracksType = t;} - Bool_t IsCosmic() const {return fTracksType==AliAlgAux::kCosm;} - Bool_t IsCollision() const {return fTracksType==AliAlgAux::kColl;} - void SetCosmic(Bool_t v=kTRUE) {fTracksType = v ? AliAlgAux::kCosm : AliAlgAux::kColl;} - Float_t GetStat(int cls, int tp) const {return fStat[cls][tp];} - // - void SetESDTree(const TTree* tr) {fESDTree = tr;} - const TTree* GetESDTree() const {return fESDTree;} - void SetESDEvent(const AliESDEvent* ev); - const AliESDEvent* GetESDEvent() const {return fESDEvent;} - void SetESDtrack(const AliESDtrack* tr, int i=0) {fESDTrack[i] = tr;} - const AliESDtrack* GetESDtrack(int i=0) const {return fESDTrack[i];} + void AssignDOFs(); + // + void AddDetector(UInt_t id, AliAlgDet* det = 0); + void AddDetector(AliAlgDet* det); + // + void AddConstraint(const AliAlgConstraint* cs) { fConstraints.AddLast((TObject*)cs); } + Int_t GetNConstraints() const { return fConstraints.GetEntriesFast(); } + const TObjArray* GetConstraints() const { return &fConstraints; } + const AliAlgConstraint* GetConstraint(int i) const { return (AliAlgConstraint*)fConstraints[i]; } + void AddAutoConstraints(); + // + void AcknowledgeNewRun(Int_t run); + void SetRunNumber(Int_t run); + Int_t GetRunNumber() const { return fRunNumber; } + Bool_t GetFieldOn() const { return fFieldOn; } + void SetFieldOn(Bool_t v = kTRUE) { fFieldOn = v; } + Int_t GetTracksType() const { return fTracksType; } + void SetTracksType(Int_t t = AliAlgAux::kColl) { fTracksType = t; } + Bool_t IsCosmic() const { return fTracksType == AliAlgAux::kCosm; } + Bool_t IsCollision() const { return fTracksType == AliAlgAux::kColl; } + void SetCosmic(Bool_t v = kTRUE) { fTracksType = v ? AliAlgAux::kCosm : AliAlgAux::kColl; } + Float_t GetStat(int cls, int tp) const { return fStat[cls][tp]; } + // + void SetESDTree(const TTree* tr) { fESDTree = tr; } + const TTree* GetESDTree() const { return fESDTree; } + void SetESDEvent(const AliESDEvent* ev); + const AliESDEvent* GetESDEvent() const { return fESDEvent; } + void SetESDtrack(const AliESDtrack* tr, int i = 0) { fESDTrack[i] = tr; } + const AliESDtrack* GetESDtrack(int i = 0) const { return fESDTrack[i]; } // // Track selection - void SetCosmicSelStrict(Bool_t v=kTRUE) {fCosmicSelStrict = v;} - Bool_t GetCosmicSelStrict() const {return fCosmicSelStrict;} - // - Int_t GetMinPoints() const {return fMinPoints[fTracksType][GetFieldOn()];} - Int_t GetMinPoints(Bool_t tp,Bool_t bON) const {return fMinPoints[tp][bON];} - void SetMinPoints(Bool_t tp,Bool_t bON,int n) {int mn=bON?4:3; fMinPoints[tp][bON]=n>mn?n:mn;} - void SetMinPointsColl(int vbOff=3,int vbOn=4); - void SetMinPointsCosm(int vbOff=3,int vbOn=4); - // - Double_t GetPtMin(Bool_t tp) const {return fPtMin[tp];} - void SetPtMin(Bool_t tp,double pt) {fPtMin[tp] = pt;} - void SetPtMinColl(double pt=0.7) {SetPtMin(AliAlgAux::kColl,pt);} - void SetPtMinCosm(double pt=1.0) {SetPtMin(AliAlgAux::kCosm,pt);} - // - Double_t GetEtaMax(Bool_t tp) const {return fEtaMax[tp];} - void SetEtaMax(Bool_t tp,double eta) {fEtaMax[tp]=eta;} - void SetEtaMaxColl(double eta=1.5) {SetEtaMax(AliAlgAux::kColl,eta);} - void SetEtaMaxCosm(double eta=1.5) {SetEtaMax(AliAlgAux::kCosm,eta);} - // - void SetDefPtBOffCosm(double pt=5.0) {fDefPtBOff[AliAlgAux::kCosm] = pt>0.3 ? pt:0.3;} - void SetDefPtBOffColl(double pt=0.6) {fDefPtBOff[AliAlgAux::kColl] = pt>0.3 ? pt:0.3;} - Double_t GetDefPtBOff(Bool_t tp) {return fDefPtBOff[tp];} - // - Int_t GetMinDetAcc(Bool_t tp) const {return fMinDetAcc[tp];} - void SetMinDetAcc(Bool_t tp, int n) {fMinDetAcc[tp] = n;} - void SetMinDetAccColl(int n=1) {SetMinDetAcc(AliAlgAux::kColl,n);} - void SetMinDetAccCosm(int n=1) {SetMinDetAcc(AliAlgAux::kCosm,n);} - // - Int_t GetVtxMinCont() const {return fVtxMinCont;} - void SetVtxMinCont(int n) {fVtxMinCont = n;} - Int_t GetVtxMaxCont() const {return fVtxMaxCont;} - void SetVtxMaxCont(int n) {fVtxMaxCont = n;} - Int_t GetVtxMinContVC() const {return fVtxMinContVC;} - void SetVtxMinContVC(int n) {fVtxMinContVC = n;} - // - Int_t GetMinITSClforVC() const {return fMinITSClforVC;} - void SetMinITSClforVC(int n) {fMinITSClforVC = n;} - Int_t GetITSPattforVC() const {return fITSPattforVC;} - void SetITSPattforVC(int p) {fITSPattforVC=p;} - Double_t GetMaxDCARforVC() const {return fMaxDCAforVC[0];} - Double_t GetMaxDCAZforVC() const {return fMaxDCAforVC[1];} - void SetMaxDCAforVC(double dr=0.1,double dz=0.6) {fMaxDCAforVC[0]=dr; fMaxDCAforVC[1]=dz;} - Double_t GetMaxChi2forVC() const {return fMaxChi2forVC;} - void SetMaxChi2forVC(double chi2=10) {fMaxChi2forVC = chi2;} - // - Bool_t CheckDetectorPattern(UInt_t patt) const; - Bool_t CheckDetectorPoints(const int* npsel) const; - void SetObligatoryDetector(Int_t detID, Int_t tp, Bool_t v=kTRUE); - void SetEventSpeciiSelection(UInt_t sel) {fSelEventSpecii = sel;} - UInt_t GetEventSpeciiSelection() const {return fSelEventSpecii;} - // - void SetVertex(const AliESDVertex* v) {fVertex = v;} - const AliESDVertex* GetVertex() const {return fVertex;} + void SetCosmicSelStrict(Bool_t v = kTRUE) { fCosmicSelStrict = v; } + Bool_t GetCosmicSelStrict() const { return fCosmicSelStrict; } + // + Int_t GetMinPoints() const { return fMinPoints[fTracksType][GetFieldOn()]; } + Int_t GetMinPoints(Bool_t tp, Bool_t bON) const { return fMinPoints[tp][bON]; } + void SetMinPoints(Bool_t tp, Bool_t bON, int n) + { + int mn = bON ? 4 : 3; + fMinPoints[tp][bON] = n > mn ? n : mn; + } + void SetMinPointsColl(int vbOff = 3, int vbOn = 4); + void SetMinPointsCosm(int vbOff = 3, int vbOn = 4); + // + Double_t GetPtMin(Bool_t tp) const { return fPtMin[tp]; } + void SetPtMin(Bool_t tp, double pt) { fPtMin[tp] = pt; } + void SetPtMinColl(double pt = 0.7) { SetPtMin(AliAlgAux::kColl, pt); } + void SetPtMinCosm(double pt = 1.0) { SetPtMin(AliAlgAux::kCosm, pt); } + // + Double_t GetEtaMax(Bool_t tp) const { return fEtaMax[tp]; } + void SetEtaMax(Bool_t tp, double eta) { fEtaMax[tp] = eta; } + void SetEtaMaxColl(double eta = 1.5) { SetEtaMax(AliAlgAux::kColl, eta); } + void SetEtaMaxCosm(double eta = 1.5) { SetEtaMax(AliAlgAux::kCosm, eta); } + // + void SetDefPtBOffCosm(double pt = 5.0) { fDefPtBOff[AliAlgAux::kCosm] = pt > 0.3 ? pt : 0.3; } + void SetDefPtBOffColl(double pt = 0.6) { fDefPtBOff[AliAlgAux::kColl] = pt > 0.3 ? pt : 0.3; } + Double_t GetDefPtBOff(Bool_t tp) { return fDefPtBOff[tp]; } + // + Int_t GetMinDetAcc(Bool_t tp) const { return fMinDetAcc[tp]; } + void SetMinDetAcc(Bool_t tp, int n) { fMinDetAcc[tp] = n; } + void SetMinDetAccColl(int n = 1) { SetMinDetAcc(AliAlgAux::kColl, n); } + void SetMinDetAccCosm(int n = 1) { SetMinDetAcc(AliAlgAux::kCosm, n); } + // + Int_t GetVtxMinCont() const { return fVtxMinCont; } + void SetVtxMinCont(int n) { fVtxMinCont = n; } + Int_t GetVtxMaxCont() const { return fVtxMaxCont; } + void SetVtxMaxCont(int n) { fVtxMaxCont = n; } + Int_t GetVtxMinContVC() const { return fVtxMinContVC; } + void SetVtxMinContVC(int n) { fVtxMinContVC = n; } + // + Int_t GetMinITSClforVC() const { return fMinITSClforVC; } + void SetMinITSClforVC(int n) { fMinITSClforVC = n; } + Int_t GetITSPattforVC() const { return fITSPattforVC; } + void SetITSPattforVC(int p) { fITSPattforVC = p; } + Double_t GetMaxDCARforVC() const { return fMaxDCAforVC[0]; } + Double_t GetMaxDCAZforVC() const { return fMaxDCAforVC[1]; } + void SetMaxDCAforVC(double dr = 0.1, double dz = 0.6) + { + fMaxDCAforVC[0] = dr; + fMaxDCAforVC[1] = dz; + } + Double_t GetMaxChi2forVC() const { return fMaxChi2forVC; } + void SetMaxChi2forVC(double chi2 = 10) { fMaxChi2forVC = chi2; } + // + Bool_t CheckDetectorPattern(UInt_t patt) const; + Bool_t CheckDetectorPoints(const int* npsel) const; + void SetObligatoryDetector(Int_t detID, Int_t tp, Bool_t v = kTRUE); + void SetEventSpeciiSelection(UInt_t sel) { fSelEventSpecii = sel; } + UInt_t GetEventSpeciiSelection() const { return fSelEventSpecii; } + // + void SetVertex(const AliESDVertex* v) { fVertex = v; } + const AliESDVertex* GetVertex() const { return fVertex; } // //---------------------------------------- - Bool_t ReadParameters(const char* parfile="millepede.res", Bool_t useErrors=kTRUE); - Float_t* GetGloParVal() const {return (Float_t*)fGloParVal;} - Float_t* GetGloParErr() const {return (Float_t*)fGloParErr;} - Int_t* GetGloParLab() const {return (Int_t*)fGloParLab;} - Int_t GetGloParLab(int i) const {return (Int_t)fGloParLab[i];} - Int_t ParID2Label(int i) const {return GetGloParLab(i);} - Int_t Label2ParID(int lab) const; - AliAlgVol* GetVolOfDOFID(int id) const; - AliAlgDet* GetDetOfDOFID(int id) const; - // - AliAlgPoint* GetRefPoint() const {return (AliAlgPoint*)fRefPoint;} - // - AliAlgRes* GetContResid() const {return (AliAlgRes*)fCResid;} - AliAlgMPRecord* GetMPRecord() const {return (AliAlgMPRecord*)fMPRecord;} - TTree* GetMPRecTree() const {return fMPRecTree;} - AliAlgTrack* GetAlgTrack() const {return (AliAlgTrack*)fAlgTrack;} - Bool_t ProcessEvent(const AliESDEvent* esdEv); - Bool_t ProcessTrack(const AliESDtrack* esdTr); - Bool_t ProcessTrack(const AliESDCosmicTrack* esdCTr); - UInt_t AcceptTrack(const AliESDtrack* esdTr, Bool_t strict=kTRUE) const; - UInt_t AcceptTrackCosmic(const AliESDtrack* esdPairCosm[kNCosmLegs]) const; - Bool_t CheckSetVertex(const AliESDVertex* vtx); - Bool_t AddVertexConstraint(); - Int_t GetNDetectors() const {return fNDet;} - AliAlgDet* GetDetector(Int_t i) const {return fDetectors[i];} - AliAlgDet* GetDetectorByDetID(Int_t i) const {return fDetPos[i]<0 ? 0:fDetectors[fDetPos[i]];} - AliAlgDet* GetDetectorByVolID(Int_t id) const; - AliAlgVtx* GetVertexSensor() const {return fVtxSens;} - // - void ResetDetectors(); - Int_t GetNDOFs() const {return fNDOFs;} - // - const char* GetConfMacroName() const {return fConfMacroName.Data();} + Bool_t ReadParameters(const char* parfile = "millepede.res", Bool_t useErrors = kTRUE); + Float_t* GetGloParVal() const { return (Float_t*)fGloParVal; } + Float_t* GetGloParErr() const { return (Float_t*)fGloParErr; } + Int_t* GetGloParLab() const { return (Int_t*)fGloParLab; } + Int_t GetGloParLab(int i) const { return (Int_t)fGloParLab[i]; } + Int_t ParID2Label(int i) const { return GetGloParLab(i); } + Int_t Label2ParID(int lab) const; + AliAlgVol* GetVolOfDOFID(int id) const; + AliAlgDet* GetDetOfDOFID(int id) const; + // + AliAlgPoint* GetRefPoint() const { return (AliAlgPoint*)fRefPoint; } + // + AliAlgRes* GetContResid() const { return (AliAlgRes*)fCResid; } + AliAlgMPRecord* GetMPRecord() const { return (AliAlgMPRecord*)fMPRecord; } + TTree* GetMPRecTree() const { return fMPRecTree; } + AliAlgTrack* GetAlgTrack() const { return (AliAlgTrack*)fAlgTrack; } + Bool_t ProcessEvent(const AliESDEvent* esdEv); + Bool_t ProcessTrack(const AliESDtrack* esdTr); + Bool_t ProcessTrack(const AliESDCosmicTrack* esdCTr); + UInt_t AcceptTrack(const AliESDtrack* esdTr, Bool_t strict = kTRUE) const; + UInt_t AcceptTrackCosmic(const AliESDtrack* esdPairCosm[kNCosmLegs]) const; + Bool_t CheckSetVertex(const AliESDVertex* vtx); + Bool_t AddVertexConstraint(); + Int_t GetNDetectors() const { return fNDet; } + AliAlgDet* GetDetector(Int_t i) const { return fDetectors[i]; } + AliAlgDet* GetDetectorByDetID(Int_t i) const { return fDetPos[i] < 0 ? 0 : fDetectors[fDetPos[i]]; } + AliAlgDet* GetDetectorByVolID(Int_t id) const; + AliAlgVtx* GetVertexSensor() const { return fVtxSens; } + // + void ResetDetectors(); + Int_t GetNDOFs() const { return fNDOFs; } + // + const char* GetConfMacroName() const { return fConfMacroName.Data(); } //---------------------------------------- // output related - void SetMPDatFileName(const char* name="mpData"); - void SetMPParFileName(const char* name="mpParams.txt"); - void SetMPConFileName(const char* name="mpConstraints.txt"); - void SetMPSteerFileName(const char* name="mpSteer.txt"); - void SetResidFileName(const char* name="mpControlRes.root"); - void SetOutCDBPath(const char* name="local://outOCDB"); - void SetOutCDBComment(const char* cm=0) {fOutCDBComment = cm;} - void SetOutCDBResponsible(const char* v=0) {fOutCDBResponsible = v;} - void SetOutCDBRunRange(int rmin=0,int rmax=999999999); - Int_t* GetOutCDBRunRange() const {return (int*)fOutCDBRunRange;} - Int_t GetOutCDBRunMin() const {return fOutCDBRunRange[0];} - Int_t GetOutCDBRunMax() const {return fOutCDBRunRange[1];} - Float_t GetControlFrac() const {return fControlFrac;} - void SetControlFrac(float v=1.) {fControlFrac = v;} - void WriteCalibrationResults() const; - void ApplyAlignmentFromMPSol(); - const char* GetOutCDBComment() const {return fOutCDBComment.Data();} - const char* GetOutCDBResponsible() const {return fOutCDBResponsible.Data();} - const char* GetOutCDBPath() const {return fOutCDBPath.Data();} - const char* GetMPDatFileName() const {return fMPDatFileName.Data();} - const char* GetResidFileName() const {return fResidFileName.Data();} - const char* GetMPParFileName() const {return fMPParFileName.Data();} - const char* GetMPConFileName() const {return fMPConFileName.Data();} - const char* GetMPSteerFileName() const {return fMPSteerFileName.Data();} - // - Bool_t FillMPRecData(); - Bool_t FillMilleData(); - Bool_t FillControlData(); - void SetDoKalmanResid(Bool_t v=kTRUE) {fDoKalmanResid = v;} - void SetMPOutType(Int_t t) {fMPOutType = t;} - void ProduceMPData(Bool_t v=kTRUE) {if (v) fMPOutType|=kMille; else fMPOutType&=~kMille;} - void ProduceMPRecord(Bool_t v=kTRUE) {if (v) fMPOutType|=kMPRec; else fMPOutType&=~kMPRec;} - void ProduceControlRes(Bool_t v=kTRUE) {if (v) fMPOutType|=kContR; else fMPOutType&=~kContR;} - Int_t GetMPOutType() const {return fMPOutType;} - Bool_t GetDoKalmanResid() const {return fDoKalmanResid;} - Bool_t GetProduceMPData() const {return fMPOutType&kMille;} - Bool_t GetProduceMPRecord() const {return fMPOutType&kMPRec;} - Bool_t GetProduceControlRes() const {return fMPOutType&kContR;} - void CloseMPRecOutput(); - void CloseMilleOutput(); - void CloseResidOutput(); - void InitMPRecOutput(); - void InitMIlleOutput(); - void InitResidOutput(); - Bool_t StoreProcessedTrack(Int_t what); - void PrintStatistics() const; - Bool_t GetMilleTXT() const {return !fMilleOutBin;} - void SetMilleTXT(Bool_t v=kTRUE) {fMilleOutBin = !v;} - // - void GenPedeSteerFile(const Option_t *opt="") const; - void WritePedeConstraints() const; - void CheckConstraints(const char* params=0); - AliAlgDOFStat* GetDOFStat() const {return fDOFStat;} - void SetDOFStat(AliAlgDOFStat* st) {fDOFStat = st;} - void DetachDOFStat() {SetDOFStat(0);} - TH1* GetHistoStat() const {return fHistoStat;} - void DetachHistoStat() {SetHistoStat(0);} - void SetHistoStat(TH1F* h) {fHistoStat = h;} - void FillStatHisto(int type, float w=1); - void CreateStatHisto(); - void FixLowStatFromDOFStat(Int_t thresh=40); - void LoadStat(const char* flname); + void SetMPDatFileName(const char* name = "mpData"); + void SetMPParFileName(const char* name = "mpParams.txt"); + void SetMPConFileName(const char* name = "mpConstraints.txt"); + void SetMPSteerFileName(const char* name = "mpSteer.txt"); + void SetResidFileName(const char* name = "mpControlRes.root"); + void SetOutCDBPath(const char* name = "local://outOCDB"); + void SetOutCDBComment(const char* cm = 0) { fOutCDBComment = cm; } + void SetOutCDBResponsible(const char* v = 0) { fOutCDBResponsible = v; } + void SetOutCDBRunRange(int rmin = 0, int rmax = 999999999); + Int_t* GetOutCDBRunRange() const { return (int*)fOutCDBRunRange; } + Int_t GetOutCDBRunMin() const { return fOutCDBRunRange[0]; } + Int_t GetOutCDBRunMax() const { return fOutCDBRunRange[1]; } + Float_t GetControlFrac() const { return fControlFrac; } + void SetControlFrac(float v = 1.) { fControlFrac = v; } + void WriteCalibrationResults() const; + void ApplyAlignmentFromMPSol(); + const char* GetOutCDBComment() const { return fOutCDBComment.Data(); } + const char* GetOutCDBResponsible() const { return fOutCDBResponsible.Data(); } + const char* GetOutCDBPath() const { return fOutCDBPath.Data(); } + const char* GetMPDatFileName() const { return fMPDatFileName.Data(); } + const char* GetResidFileName() const { return fResidFileName.Data(); } + const char* GetMPParFileName() const { return fMPParFileName.Data(); } + const char* GetMPConFileName() const { return fMPConFileName.Data(); } + const char* GetMPSteerFileName() const { return fMPSteerFileName.Data(); } + // + Bool_t FillMPRecData(); + Bool_t FillMilleData(); + Bool_t FillControlData(); + void SetDoKalmanResid(Bool_t v = kTRUE) { fDoKalmanResid = v; } + void SetMPOutType(Int_t t) { fMPOutType = t; } + void ProduceMPData(Bool_t v = kTRUE) + { + if (v) + fMPOutType |= kMille; + else + fMPOutType &= ~kMille; + } + void ProduceMPRecord(Bool_t v = kTRUE) + { + if (v) + fMPOutType |= kMPRec; + else + fMPOutType &= ~kMPRec; + } + void ProduceControlRes(Bool_t v = kTRUE) + { + if (v) + fMPOutType |= kContR; + else + fMPOutType &= ~kContR; + } + Int_t GetMPOutType() const { return fMPOutType; } + Bool_t GetDoKalmanResid() const { return fDoKalmanResid; } + Bool_t GetProduceMPData() const { return fMPOutType & kMille; } + Bool_t GetProduceMPRecord() const { return fMPOutType & kMPRec; } + Bool_t GetProduceControlRes() const { return fMPOutType & kContR; } + void CloseMPRecOutput(); + void CloseMilleOutput(); + void CloseResidOutput(); + void InitMPRecOutput(); + void InitMIlleOutput(); + void InitResidOutput(); + Bool_t StoreProcessedTrack(Int_t what); + void PrintStatistics() const; + Bool_t GetMilleTXT() const { return !fMilleOutBin; } + void SetMilleTXT(Bool_t v = kTRUE) { fMilleOutBin = !v; } + // + void GenPedeSteerFile(const Option_t* opt = "") const; + void WritePedeConstraints() const; + void CheckConstraints(const char* params = 0); + AliAlgDOFStat* GetDOFStat() const { return fDOFStat; } + void SetDOFStat(AliAlgDOFStat* st) { fDOFStat = st; } + void DetachDOFStat() { SetDOFStat(0); } + TH1* GetHistoStat() const { return fHistoStat; } + void DetachHistoStat() { SetHistoStat(0); } + void SetHistoStat(TH1F* h) { fHistoStat = h; } + void FillStatHisto(int type, float w = 1); + void CreateStatHisto(); + void FixLowStatFromDOFStat(Int_t thresh = 40); + void LoadStat(const char* flname); // //---------------------------------------- // - Int_t GetRefRunNumber() const {return fRefRunNumber;} - void SetRefRunNumber(int r=-1) {fRefRunNumber = r;} + Int_t GetRefRunNumber() const { return fRefRunNumber; } + void SetRefRunNumber(int r = -1) { fRefRunNumber = r; } // - void SetRefOCDBConfigMacro(const char* nm="configRefOCDB.C") {fRefOCDBConf = nm;} - const char* GetRefOCDBConfigMacro() const {return fRefOCDBConf.Data();} - void SetRecoOCDBConfigMacro(const char* nm="configRecoOCDB.C") {fRecoOCDBConf = nm;} - const char* GetRecoOCDBConfigMacro() const {return fRecoOCDBConf.Data();} - Int_t GetRefOCDBLoaded() const {return fRefOCDBLoaded;} + void SetRefOCDBConfigMacro(const char* nm = "configRefOCDB.C") { fRefOCDBConf = nm; } + const char* GetRefOCDBConfigMacro() const { return fRefOCDBConf.Data(); } + void SetRecoOCDBConfigMacro(const char* nm = "configRecoOCDB.C") { fRecoOCDBConf = nm; } + const char* GetRecoOCDBConfigMacro() const { return fRecoOCDBConf.Data(); } + Int_t GetRefOCDBLoaded() const { return fRefOCDBLoaded; } // - virtual void Print(const Option_t *opt="") const; - void PrintLabels() const; - Char_t* GetDOFLabelTxt(int idf) const; + virtual void Print(const Option_t* opt = "") const; + void PrintLabels() const; + Char_t* GetDOFLabelTxt(int idf) const; // - static Char_t* GetDetNameByDetID(Int_t id) {return (Char_t*)fgkDetectorName[id];} - static void MPRec2Mille(const char* mprecfile,const char* millefile="mpData.mille",Bool_t bindata=kTRUE); - static void MPRec2Mille(TTree* mprTree,const char* millefile="mpData.mille",Bool_t bindata=kTRUE); + static Char_t* GetDetNameByDetID(Int_t id) { return (Char_t*)fgkDetectorName[id]; } + static void MPRec2Mille(const char* mprecfile, const char* millefile = "mpData.mille", Bool_t bindata = kTRUE); + static void MPRec2Mille(TTree* mprTree, const char* millefile = "mpData.mille", Bool_t bindata = kTRUE); // - AliSymMatrix* BuildMatrix(TVectorD &vec); - Bool_t TestLocalSolution(); + AliSymMatrix* BuildMatrix(TVectorD& vec); + Bool_t TestLocalSolution(); // // fast check of solution using derivatives - void CheckSol(TTree* mpRecTree, Bool_t store=kTRUE,Bool_t verbose=kFALSE,Bool_t loc=kTRUE, const char* outName="resFast"); - Bool_t CheckSol(AliAlgMPRecord* rec,AliAlgResFast *rLG=0, AliAlgResFast* rL=0,Bool_t verbose=kTRUE, Bool_t loc=kTRUE); + void CheckSol(TTree* mpRecTree, Bool_t store = kTRUE, Bool_t verbose = kFALSE, Bool_t loc = kTRUE, const char* outName = "resFast"); + Bool_t CheckSol(AliAlgMPRecord* rec, AliAlgResFast* rLG = 0, AliAlgResFast* rL = 0, Bool_t verbose = kTRUE, Bool_t loc = kTRUE); // protected: // @@ -308,112 +380,113 @@ class AliAlgSteer : public TObject // protected: // - Int_t fNDet; // number of deectors participating in the alignment - Int_t fNDOFs; // number of degrees of freedom - Int_t fRunNumber; // current run number - Bool_t fFieldOn; // field on flag - Int_t fTracksType; // collision/cosmic event type - AliAlgTrack* fAlgTrack; // current alignment track - AliAlgDet* fDetectors[kNDetectors]; // detectors participating in the alignment - Int_t fDetPos[kNDetectors]; // entry of detector in the fDetectors array - AliAlgVtx* fVtxSens; // fake sensor for the vertex - TObjArray fConstraints; // array of constraints + Int_t fNDet; // number of deectors participating in the alignment + Int_t fNDOFs; // number of degrees of freedom + Int_t fRunNumber; // current run number + Bool_t fFieldOn; // field on flag + Int_t fTracksType; // collision/cosmic event type + AliAlgTrack* fAlgTrack; // current alignment track + AliAlgDet* fDetectors[kNDetectors]; // detectors participating in the alignment + Int_t fDetPos[kNDetectors]; // entry of detector in the fDetectors array + AliAlgVtx* fVtxSens; // fake sensor for the vertex + TObjArray fConstraints; // array of constraints // // Track selection - UInt_t fSelEventSpecii; // consider only these event specii - UInt_t fObligatoryDetPattern[AliAlgAux::kNTrackTypes]; // pattern of obligatory detectors - Bool_t fCosmicSelStrict; // if true, each cosmic track leg selected like separate track - Int_t fMinPoints[AliAlgAux::kNTrackTypes][2]; // require min points per leg (case Boff,Bon) - Int_t fMinDetAcc[AliAlgAux::kNTrackTypes]; // min number of detector required in track - Double_t fDefPtBOff[AliAlgAux::kNTrackTypes]; // nominal pt for tracks in Boff run - Double_t fPtMin[AliAlgAux::kNTrackTypes]; // min pT of tracks to consider - Double_t fEtaMax[AliAlgAux::kNTrackTypes]; // eta cut on tracks - Int_t fVtxMinCont; // require min number of contributors in Vtx - Int_t fVtxMaxCont; // require max number of contributors in Vtx - Int_t fVtxMinContVC; // min number of contributors to use as constraint - // - Int_t fMinITSClforVC; // use vertex constraint for tracks with enough points - Int_t fITSPattforVC; // optional request on ITS hits to allow vertex constraint - Double_t fMaxDCAforVC[2]; // DCA cut in R,Z to allow vertex constraint - Double_t fMaxChi2forVC; // track-vertex chi2 cut to allow vertex constraint - // - // - Float_t* fGloParVal; //[fNDOFs] parameters for DOFs - Float_t* fGloParErr; //[fNDOFs] errors for DOFs - Int_t* fGloParLab; //[fNDOFs] labels for DOFs - Int_t* fOrderedLbl; //[fNDOFs] ordered labels - Int_t* fLbl2ID; //[fNDOFs] Label order in fOrderedLbl -> parID - // - AliAlgPoint* fRefPoint; // reference point for track definition - // - const TTree* fESDTree; //! externally set esdTree, needed to access UserInfo list - const AliESDEvent* fESDEvent; //! externally set event - const AliESDtrack* fESDTrack[kNCosmLegs]; //! externally set ESD tracks - const AliESDVertex* fVertex; //! event vertex + UInt_t fSelEventSpecii; // consider only these event specii + UInt_t fObligatoryDetPattern[AliAlgAux::kNTrackTypes]; // pattern of obligatory detectors + Bool_t fCosmicSelStrict; // if true, each cosmic track leg selected like separate track + Int_t fMinPoints[AliAlgAux::kNTrackTypes][2]; // require min points per leg (case Boff,Bon) + Int_t fMinDetAcc[AliAlgAux::kNTrackTypes]; // min number of detector required in track + Double_t fDefPtBOff[AliAlgAux::kNTrackTypes]; // nominal pt for tracks in Boff run + Double_t fPtMin[AliAlgAux::kNTrackTypes]; // min pT of tracks to consider + Double_t fEtaMax[AliAlgAux::kNTrackTypes]; // eta cut on tracks + Int_t fVtxMinCont; // require min number of contributors in Vtx + Int_t fVtxMaxCont; // require max number of contributors in Vtx + Int_t fVtxMinContVC; // min number of contributors to use as constraint + // + Int_t fMinITSClforVC; // use vertex constraint for tracks with enough points + Int_t fITSPattforVC; // optional request on ITS hits to allow vertex constraint + Double_t fMaxDCAforVC[2]; // DCA cut in R,Z to allow vertex constraint + Double_t fMaxChi2forVC; // track-vertex chi2 cut to allow vertex constraint + // + // + Float_t* fGloParVal; //[fNDOFs] parameters for DOFs + Float_t* fGloParErr; //[fNDOFs] errors for DOFs + Int_t* fGloParLab; //[fNDOFs] labels for DOFs + Int_t* fOrderedLbl; //[fNDOFs] ordered labels + Int_t* fLbl2ID; //[fNDOFs] Label order in fOrderedLbl -> parID + // + AliAlgPoint* fRefPoint; // reference point for track definition + // + const TTree* fESDTree; //! externally set esdTree, needed to access UserInfo list + const AliESDEvent* fESDEvent; //! externally set event + const AliESDtrack* fESDTrack[kNCosmLegs]; //! externally set ESD tracks + const AliESDVertex* fVertex; //! event vertex // // statistics - Float_t fStat[kNStatCl][kMaxStat]; // processing statistics - static const Char_t* fgkStatClName[kNStatCl]; // stat classes names - static const Char_t* fgkStatName[kMaxStat]; // stat type names + Float_t fStat[kNStatCl][kMaxStat]; // processing statistics + static const Char_t* fgkStatClName[kNStatCl]; // stat classes names + static const Char_t* fgkStatName[kMaxStat]; // stat type names // // output related - Float_t fControlFrac; // fraction of tracks to process control residuals - Int_t fMPOutType; // What to store as an output, see StoreProcessedTrack - Mille* fMille; //! Mille interface - AliAlgMPRecord* fMPRecord; //! MP record - AliAlgRes* fCResid; //! control residuals - TTree* fMPRecTree; //! tree to store MP record - TTree* fResidTree; //! tree to store control residuals - TFile* fMPRecFile; //! file to store MP record tree - TFile* fResidFile; //! file to store control residuals tree - TArrayF fMilleDBuffer; //! buffer for Mille Derivatives output - TArrayI fMilleIBuffer; //! buffer for Mille Indecis output - TString fMPDatFileName; // file name for records binary data output - TString fMPParFileName; // file name for MP params - TString fMPConFileName; // file name for MP constraints - TString fMPSteerFileName; // file name for MP steering - TString fResidFileName; // file name for optional control residuals - Bool_t fMilleOutBin; // optionally text output for Mille debugging - Bool_t fDoKalmanResid; // calculate residuals with smoothed kalman in the ControlRes - // - TString fOutCDBPath; // output OCDB path - TString fOutCDBComment; // optional comment to add to output cdb objects - TString fOutCDBResponsible; // optional responsible for output metadata - Int_t fOutCDBRunRange[2]; // run range for output storage - // - AliAlgDOFStat* fDOFStat; // stat of entries per dof - TH1F* fHistoStat; // histo with general statistics + Float_t fControlFrac; // fraction of tracks to process control residuals + Int_t fMPOutType; // What to store as an output, see StoreProcessedTrack + Mille* fMille; //! Mille interface + AliAlgMPRecord* fMPRecord; //! MP record + AliAlgRes* fCResid; //! control residuals + TTree* fMPRecTree; //! tree to store MP record + TTree* fResidTree; //! tree to store control residuals + TFile* fMPRecFile; //! file to store MP record tree + TFile* fResidFile; //! file to store control residuals tree + TArrayF fMilleDBuffer; //! buffer for Mille Derivatives output + TArrayI fMilleIBuffer; //! buffer for Mille Indecis output + TString fMPDatFileName; // file name for records binary data output + TString fMPParFileName; // file name for MP params + TString fMPConFileName; // file name for MP constraints + TString fMPSteerFileName; // file name for MP steering + TString fResidFileName; // file name for optional control residuals + Bool_t fMilleOutBin; // optionally text output for Mille debugging + Bool_t fDoKalmanResid; // calculate residuals with smoothed kalman in the ControlRes + // + TString fOutCDBPath; // output OCDB path + TString fOutCDBComment; // optional comment to add to output cdb objects + TString fOutCDBResponsible; // optional responsible for output metadata + Int_t fOutCDBRunRange[2]; // run range for output storage + // + AliAlgDOFStat* fDOFStat; // stat of entries per dof + TH1F* fHistoStat; // histo with general statistics // // input related - TString fConfMacroName; // optional configuration macro - TString fRecoOCDBConf; // optional macro name for reco-time OCDB setup: void fun(int run) - TString fRefOCDBConf; // optional macro name for prealignment OCDB setup: void fun() - Int_t fRefRunNumber; // optional run number used for reference - Int_t fRefOCDBLoaded; // flag/counter for ref.OCDB loading - Bool_t fUseRecoOCDB; // flag to preload reco-time calib objects - // - static const Int_t fgkSkipLayers[kNLrSkip]; // detector layers for which we don't need module matrices - static const Char_t* fgkDetectorName[kNDetectors]; // names of detectors - static const Char_t* fgkHStatName[kNHVars]; // names for stat.bins in the stat histo - static const Char_t* fgkMPDataExt; // extension for MP2 binary data - // - ClassDef(AliAlgSteer,2) + TString fConfMacroName; // optional configuration macro + TString fRecoOCDBConf; // optional macro name for reco-time OCDB setup: void fun(int run) + TString fRefOCDBConf; // optional macro name for prealignment OCDB setup: void fun() + Int_t fRefRunNumber; // optional run number used for reference + Int_t fRefOCDBLoaded; // flag/counter for ref.OCDB loading + Bool_t fUseRecoOCDB; // flag to preload reco-time calib objects + // + static const Int_t fgkSkipLayers[kNLrSkip]; // detector layers for which we don't need module matrices + static const Char_t* fgkDetectorName[kNDetectors]; // names of detectors + static const Char_t* fgkHStatName[kNHVars]; // names for stat.bins in the stat histo + static const Char_t* fgkMPDataExt; // extension for MP2 binary data + // + ClassDef(AliAlgSteer, 2) }; //__________________________________________________________ -inline void AliAlgSteer::SetMinPointsColl(int vbOff,int vbOn) +inline void AliAlgSteer::SetMinPointsColl(int vbOff, int vbOn) { // ask min number of points per track - SetMinPoints(AliAlgAux::kColl,kFALSE,vbOff); - SetMinPoints(AliAlgAux::kColl,kTRUE,vbOn); + SetMinPoints(AliAlgAux::kColl, kFALSE, vbOff); + SetMinPoints(AliAlgAux::kColl, kTRUE, vbOn); } //__________________________________________________________ -inline void AliAlgSteer::SetMinPointsCosm(int vbOff,int vbOn) +inline void AliAlgSteer::SetMinPointsCosm(int vbOff, int vbOn) { // ask min number of points per track - SetMinPoints(AliAlgAux::kCosm,kFALSE,vbOff); - SetMinPoints(AliAlgAux::kCosm,kTRUE,vbOn); + SetMinPoints(AliAlgAux::kCosm, kFALSE, vbOff); + SetMinPoints(AliAlgAux::kCosm, kTRUE, vbOn); } - +} // namespace align +} // namespace o2 #endif diff --git a/Detectors/Align/include/Align/AliAlgTrack.h b/Detectors/Align/include/Align/AliAlgTrack.h index 161bf8d5dc6dc..7a88da346ad6f 100644 --- a/Detectors/Align/include/Align/AliAlgTrack.h +++ b/Detectors/Align/include/Align/AliAlgTrack.h @@ -1,3 +1,24 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgTrack.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief Track model for the alignment + +/** + * Track model for the alignment: AliExternalTrackParam for kinematics + * proper with number of multiple scattering kinks. + * Full support for derivatives and residuals calculation + */ + #ifndef ALIALGTRACK_H #define ALIALGTRACK_H @@ -7,178 +28,182 @@ #include #include -/*-------------------------------------------------------- - Track model for the alignment: AliExternalTrackParam for kinematics - proper with number of multiple scattering kinks. - Full support for derivatives and residuals calculation - -------------------------------------------------------*/ - -// Author: ruben.shahoyan@cern.ch - -//#define DEBUG 4 +namespace o2 +{ +namespace align +{ -class AliAlgTrack: public AliExternalTrackParam +class AliAlgTrack : public AliExternalTrackParam { public: - - enum {kCosmicBit=BIT(14),kFieldONBit=BIT(15),kResidDoneBit=BIT(16), - kDerivDoneBit=BIT(17),kKalmanDoneBit=BIT(18)}; - enum {kNKinParBOFF=4 // N params for ExternalTrackParam part w/o field - ,kNKinParBON=5 // N params for ExternalTrackParam part with field - ,kParY = 0 // track parameters - ,kParZ - ,kParSnp - ,kParTgl - ,kParQ2Pt + enum { kCosmicBit = BIT(14), + kFieldONBit = BIT(15), + kResidDoneBit = BIT(16), + kDerivDoneBit = BIT(17), + kKalmanDoneBit = BIT(18) }; + enum { kNKinParBOFF = 4 // N params for ExternalTrackParam part w/o field + , + kNKinParBON = 5 // N params for ExternalTrackParam part with field + , + kParY = 0 // track parameters + , + kParZ, + kParSnp, + kParTgl, + kParQ2Pt }; AliAlgTrack(); virtual ~AliAlgTrack(); - void DefineDOFs(); - Double_t GetMass() const {return fMass;} - Double_t GetMinX2X0Pt2Account() const {return fMinX2X0Pt2Account;} - Int_t GetNPoints() const {return fPoints.GetEntriesFast();} - AliAlgPoint* GetPoint(int i) const {return (AliAlgPoint*)fPoints[i];} - void AddPoint(AliAlgPoint* p) {fPoints.AddLast(p);} - void SetMass(double m) {fMass = m;} - void SetMinX2X0Pt2Account(double v) {fMinX2X0Pt2Account = v;} - Int_t GetNLocPar() const {return fNLocPar;} - Int_t GetNLocExtPar() const {return fNLocExtPar;} - Int_t GetInnerPointID() const {return fInnerPointID;} - AliAlgPoint* GetInnerPoint() const {return GetPoint(fInnerPointID);} - // - virtual void Clear(Option_t *opt=""); - virtual void Print(Option_t *opt="") const; - virtual void DumpCoordinates() const; - // - Bool_t PropagateToPoint(AliExternalTrackParam& tr, const AliAlgPoint* pnt, - int minNSteps,double maxStep,Bool_t matCor, double* matPar=0); - Bool_t PropagateParamToPoint(AliExternalTrackParam& tr, const AliAlgPoint* pnt, double maxStep=3); // param only - Bool_t PropagateParamToPoint(AliExternalTrackParam* trSet, int nTr, const AliAlgPoint* pnt, double maxStep=3); // params only - // - Bool_t CalcResiduals(const double *params=0); - Bool_t CalcResidDeriv(double *params=0); + void DefineDOFs(); + Double_t GetMass() const { return fMass; } + Double_t GetMinX2X0Pt2Account() const { return fMinX2X0Pt2Account; } + Int_t GetNPoints() const { return fPoints.GetEntriesFast(); } + AliAlgPoint* GetPoint(int i) const { return (AliAlgPoint*)fPoints[i]; } + void AddPoint(AliAlgPoint* p) { fPoints.AddLast(p); } + void SetMass(double m) { fMass = m; } + void SetMinX2X0Pt2Account(double v) { fMinX2X0Pt2Account = v; } + Int_t GetNLocPar() const { return fNLocPar; } + Int_t GetNLocExtPar() const { return fNLocExtPar; } + Int_t GetInnerPointID() const { return fInnerPointID; } + AliAlgPoint* GetInnerPoint() const { return GetPoint(fInnerPointID); } + // + virtual void Clear(Option_t* opt = ""); + virtual void Print(Option_t* opt = "") const; + virtual void DumpCoordinates() const; + // + Bool_t PropagateToPoint(AliExternalTrackParam& tr, const AliAlgPoint* pnt, + int minNSteps, double maxStep, Bool_t matCor, double* matPar = 0); + Bool_t PropagateParamToPoint(AliExternalTrackParam& tr, const AliAlgPoint* pnt, double maxStep = 3); // param only + Bool_t PropagateParamToPoint(AliExternalTrackParam* trSet, int nTr, const AliAlgPoint* pnt, double maxStep = 3); // params only + // + Bool_t CalcResiduals(const double* params = 0); + Bool_t CalcResidDeriv(double* params = 0); Bool_t CalcResidDerivGlo(AliAlgPoint* pnt); // - Bool_t IsCosmic() const {return TestBit(kCosmicBit);} - void SetCosmic(Bool_t v=kTRUE) {SetBit(kCosmicBit,v);} - Bool_t GetFieldON() const {return TestBit(kFieldONBit);} - void SetFieldON(Bool_t v=kTRUE) {SetBit(kFieldONBit,v);} - Bool_t GetResidDone() const {return TestBit(kResidDoneBit);} - void SetResidDone(Bool_t v=kTRUE) {SetBit(kResidDoneBit,v);} - Bool_t GetDerivDone() const {return TestBit(kDerivDoneBit);} - void SetDerivDone(Bool_t v=kTRUE) {SetBit(kDerivDoneBit,v);} - Bool_t GetKalmanDone() const {return TestBit(kKalmanDoneBit);} - void SetKalmanDone(Bool_t v=kTRUE) {SetBit(kKalmanDoneBit,v);} - // - void SortPoints(); + Bool_t IsCosmic() const { return TestBit(kCosmicBit); } + void SetCosmic(Bool_t v = kTRUE) { SetBit(kCosmicBit, v); } + Bool_t GetFieldON() const { return TestBit(kFieldONBit); } + void SetFieldON(Bool_t v = kTRUE) { SetBit(kFieldONBit, v); } + Bool_t GetResidDone() const { return TestBit(kResidDoneBit); } + void SetResidDone(Bool_t v = kTRUE) { SetBit(kResidDoneBit, v); } + Bool_t GetDerivDone() const { return TestBit(kDerivDoneBit); } + void SetDerivDone(Bool_t v = kTRUE) { SetBit(kDerivDoneBit, v); } + Bool_t GetKalmanDone() const { return TestBit(kKalmanDoneBit); } + void SetKalmanDone(Bool_t v = kTRUE) { SetBit(kKalmanDoneBit, v); } + // + void SortPoints(); Bool_t IniFit(); Bool_t ResidKalman(); Bool_t ProcessMaterials(); Bool_t CombineTracks(AliExternalTrackParam& trcL, const AliExternalTrackParam& trcU); // - void SetChi2(double c) {fChi2 = c;}; - Double_t GetChi2() const {return fChi2;} - void SetChi2Ini(double c) {fChi2Ini = c;}; - Double_t GetChi2Ini() const {return fChi2Ini;} - Double_t GetChi2CosmUp() const {return fChi2CosmUp;} - Double_t GetChi2CosmDn() const {return fChi2CosmDn;} + void SetChi2(double c) { fChi2 = c; }; + Double_t GetChi2() const { return fChi2; } + void SetChi2Ini(double c) { fChi2Ini = c; }; + Double_t GetChi2Ini() const { return fChi2Ini; } + Double_t GetChi2CosmUp() const { return fChi2CosmUp; } + Double_t GetChi2CosmDn() const { return fChi2CosmDn; } // - void ImposePtBOff(double pt) {fP[kParQ2Pt] = 1./pt;} + void ImposePtBOff(double pt) { fP[kParQ2Pt] = 1. / pt; } // propagation methods - void CopyFrom(const AliExternalTrackParam* etp); - Bool_t ApplyMatCorr(AliExternalTrackParam& trPar, const Double_t *corrDiag, const AliAlgPoint* pnt); - Bool_t ApplyMatCorr(AliExternalTrackParam* trSet, int ntr, const Double_t *corrDiaf,const AliAlgPoint* pnt); - Bool_t ApplyMatCorr(AliExternalTrackParam& trPar, const Double_t *corrpar); - // - Double_t GetResidual(int dim, int pntID) const {return fResidA[dim][pntID];} - Double_t *GetDResDLoc(int dim, int pntID) const {return &fDResDLocA[dim][pntID*fNLocPar];} - Double_t *GetDResDGlo(int dim, int id) const {return &fDResDGloA[dim][id];} - Int_t *GetGloParID() const {return fGloParIDA;} - // - void SetParams(AliExternalTrackParam& tr, double x, double alp, const double* par,Bool_t add); - void SetParams(AliExternalTrackParam* trSet, int ntr, double x, double alp, const double* par,Bool_t add); + void CopyFrom(const AliExternalTrackParam* etp); + Bool_t ApplyMatCorr(AliExternalTrackParam& trPar, const Double_t* corrDiag, const AliAlgPoint* pnt); + Bool_t ApplyMatCorr(AliExternalTrackParam* trSet, int ntr, const Double_t* corrDiaf, const AliAlgPoint* pnt); + Bool_t ApplyMatCorr(AliExternalTrackParam& trPar, const Double_t* corrpar); + // + Double_t GetResidual(int dim, int pntID) const { return fResidA[dim][pntID]; } + Double_t* GetDResDLoc(int dim, int pntID) const { return &fDResDLocA[dim][pntID * fNLocPar]; } + Double_t* GetDResDGlo(int dim, int id) const { return &fDResDGloA[dim][id]; } + Int_t* GetGloParID() const { return fGloParIDA; } + // + void SetParams(AliExternalTrackParam& tr, double x, double alp, const double* par, Bool_t add); + void SetParams(AliExternalTrackParam* trSet, int ntr, double x, double alp, const double* par, Bool_t add); void SetParam(AliExternalTrackParam& tr, int par, double val); void SetParam(AliExternalTrackParam* trSet, int ntr, int par, double val); void ModParam(AliExternalTrackParam& tr, int par, double delta); void ModParam(AliExternalTrackParam* trSet, int ntr, int par, double delta); // - void RichardsonDeriv(const AliExternalTrackParam* trSet, const double *delta, - const AliAlgPoint* pnt, double& derY, double& derZ); + void RichardsonDeriv(const AliExternalTrackParam* trSet, const double* delta, + const AliAlgPoint* pnt, double& derY, double& derZ); // - const Double_t* GetLocPars() const {return fLocParA;} - void SetLocPars(const double* pars); + const Double_t* GetLocPars() const { return fLocParA; } + void SetLocPars(const double* pars); // - protected: + protected: // - Bool_t CalcResidDeriv(double *params,Bool_t invert,int pFrom,int pTo); - Bool_t CalcResiduals(const double *params,Bool_t invert,int pFrom,int pTo); - Bool_t FitLeg(AliExternalTrackParam& trc, int pFrom,int pTo, Bool_t &inv); - Bool_t ProcessMaterials(AliExternalTrackParam& trc, int pFrom,int pTo); + Bool_t CalcResidDeriv(double* params, Bool_t invert, int pFrom, int pTo); + Bool_t CalcResiduals(const double* params, Bool_t invert, int pFrom, int pTo); + Bool_t FitLeg(AliExternalTrackParam& trc, int pFrom, int pTo, Bool_t& inv); + Bool_t ProcessMaterials(AliExternalTrackParam& trc, int pFrom, int pTo); // - void CheckExpandDerGloBuffer(int minSize); + void CheckExpandDerGloBuffer(int minSize); // - static Double_t RichardsonExtrap(double *val, int ord=1); - static Double_t RichardsonExtrap(const double *val, int ord=1); + static Double_t RichardsonExtrap(double* val, int ord = 1); + static Double_t RichardsonExtrap(const double* val, int ord = 1); // // ---------- dummies ---------- AliAlgTrack(const AliAlgTrack&); AliAlgTrack& operator=(const AliAlgTrack&); // protected: - // - Int_t fNLocPar; // number of local params - Int_t fNLocExtPar; // number of local params for the external track param - Int_t fNGloPar; // number of free global parameters the track depends on - Int_t fNDF; // number of degrees of freedom - Int_t fInnerPointID; // ID of inner point in sorted track. For 2-leg cosmics - innermost point of lower leg - Bool_t fNeedInv[2]; // set if one of cosmic legs need inversion - Double_t fMinX2X0Pt2Account; // minimum X2X0/pT accumulated between 2 points worth to account - Double_t fMass; // assumed mass - Double_t fChi2; // chi2 with current residuals - Double_t fChi2CosmUp; // chi2 for cosmic upper leg - Double_t fChi2CosmDn; // chi2 for cosmic down leg - Double_t fChi2Ini; // chi2 with current residuals - TObjArray fPoints; // alignment points - TArrayD fResid[2]; // residuals array - TArrayD fDResDLoc[2]; // array for derivatives over local params - TArrayD fDResDGlo[2]; // array for derivatives over global params - TArrayD fLocPar; // local parameters array - TArrayI fGloParID; // IDs of relevant global params - Double_t *fResidA[2]; //! fast access to residuals - Double_t *fDResDLocA[2]; //! fast access to local derivatives - Double_t *fDResDGloA[2]; //! fast access to global derivatives - Int_t *fGloParIDA; //! fast access to relevant global param IDs - Double_t *fLocParA; //! fast access to local params - // - ClassDef(AliAlgTrack,2) + Int_t fNLocPar; // number of local params + Int_t fNLocExtPar; // number of local params for the external track param + Int_t fNGloPar; // number of free global parameters the track depends on + Int_t fNDF; // number of degrees of freedom + Int_t fInnerPointID; // ID of inner point in sorted track. For 2-leg cosmics - innermost point of lower leg + Bool_t fNeedInv[2]; // set if one of cosmic legs need inversion + Double_t fMinX2X0Pt2Account; // minimum X2X0/pT accumulated between 2 points worth to account + Double_t fMass; // assumed mass + Double_t fChi2; // chi2 with current residuals + Double_t fChi2CosmUp; // chi2 for cosmic upper leg + Double_t fChi2CosmDn; // chi2 for cosmic down leg + Double_t fChi2Ini; // chi2 with current residuals + TObjArray fPoints; // alignment points + TArrayD fResid[2]; // residuals array + TArrayD fDResDLoc[2]; // array for derivatives over local params + TArrayD fDResDGlo[2]; // array for derivatives over global params + TArrayD fLocPar; // local parameters array + TArrayI fGloParID; // IDs of relevant global params + Double_t* fResidA[2]; //! fast access to residuals + Double_t* fDResDLocA[2]; //! fast access to local derivatives + Double_t* fDResDGloA[2]; //! fast access to global derivatives + Int_t* fGloParIDA; //! fast access to relevant global param IDs + Double_t* fLocParA; //! fast access to local params + // + ClassDef(AliAlgTrack, 2) }; //____________________________________________________________________________________________ -inline void AliAlgTrack::SetParams(AliExternalTrackParam& tr, double x, double alp, const double* par,Bool_t add) +inline void AliAlgTrack::SetParams(AliExternalTrackParam& tr, double x, double alp, const double* par, Bool_t add) { // set track params - const float kDefQ2PtCosm = 1., kDefG2PtColl = 1./0.6; - tr.SetParamOnly(x,alp,par); - double *parTr = (double*) tr.GetParameter(); + const float kDefQ2PtCosm = 1., kDefG2PtColl = 1. / 0.6; + tr.SetParamOnly(x, alp, par); + double* parTr = (double*)tr.GetParameter(); if (add) { // par is correction to reference params - for (int i=kNKinParBON;i--;) parTr[i] += GetParameter()[i]; + for (int i = kNKinParBON; i--;) + parTr[i] += GetParameter()[i]; } - if (!GetFieldON()) parTr[4] = IsCosmic() ? kDefQ2PtCosm : kDefG2PtColl; // only 4 params are valid + if (!GetFieldON()) + parTr[4] = IsCosmic() ? kDefQ2PtCosm : kDefG2PtColl; // only 4 params are valid // } //____________________________________________________________________________________________ -inline void AliAlgTrack::SetParams(AliExternalTrackParam* trSet, int ntr, double x, double alp, const double* par,Bool_t add) +inline void AliAlgTrack::SetParams(AliExternalTrackParam* trSet, int ntr, double x, double alp, const double* par, Bool_t add) { // set parames for multiple tracks (VECTORIZE THIS) if (!add) { // full parameter supplied - for (int itr=ntr;itr--;) SetParams(trSet[itr],x,alp,par,kFALSE); + for (int itr = ntr; itr--;) + SetParams(trSet[itr], x, alp, par, kFALSE); return; } - double partr[kNKinParBON]={0}; // par is a correction to reference parameter - for (int i=fNLocExtPar;i--;) partr[i] = GetParameter()[i] + par[i]; - for (int itr=ntr;itr--;) SetParams(trSet[itr],x,alp,partr,kFALSE); + double partr[kNKinParBON] = {0}; // par is a correction to reference parameter + for (int i = fNLocExtPar; i--;) + partr[i] = GetParameter()[i] + par[i]; + for (int itr = ntr; itr--;) + SetParams(trSet[itr], x, alp, partr, kFALSE); } //____________________________________________________________________________________________ @@ -192,11 +217,12 @@ inline void AliAlgTrack::SetParam(AliExternalTrackParam& tr, int par, double val inline void AliAlgTrack::SetParam(AliExternalTrackParam* trSet, int ntr, int par, double val) { // set parames for multiple tracks (VECTORIZE THIS) - for (int itr=ntr;itr--;) ((double*)trSet[itr].GetParameter())[par] = val; + for (int itr = ntr; itr--;) + ((double*)trSet[itr].GetParameter())[par] = val; } //____________________________________________________________________________________________ -inline void AliAlgTrack::ModParam(AliExternalTrackParam & tr, int par, double delta) +inline void AliAlgTrack::ModParam(AliExternalTrackParam& tr, int par, double delta) { // modify track parameter ((double*)tr.GetParameter())[par] += delta; @@ -206,15 +232,16 @@ inline void AliAlgTrack::ModParam(AliExternalTrackParam & tr, int par, double de inline void AliAlgTrack::ModParam(AliExternalTrackParam* trSet, int ntr, int par, double delta) { // modify track parameter (VECTORIZE THOS) - for (int itr=ntr;itr--;) ModParam(trSet[itr],par,delta); + for (int itr = ntr; itr--;) + ModParam(trSet[itr], par, delta); } //______________________________________________ inline void AliAlgTrack::CopyFrom(const AliExternalTrackParam* etp) { // assign kinematics - Set(etp->GetX(),etp->GetAlpha(),etp->GetParameter(),etp->GetCovariance()); + Set(etp->GetX(), etp->GetAlpha(), etp->GetParameter(), etp->GetCovariance()); } - - +} // namespace align +} // namespace o2 #endif diff --git a/Detectors/Align/include/Align/AliAlgVol.h b/Detectors/Align/include/Align/AliAlgVol.h index 8ce0ea09adf55..2daea62225074 100644 --- a/Detectors/Align/include/Align/AliAlgVol.h +++ b/Detectors/Align/include/Align/AliAlgVol.h @@ -1,3 +1,25 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgVol.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief Base class of alignable volume + +/** + * Base class of alignable volume. Has at least geometric + * degrees of freedom + user defined calibration DOFs. + * The name provided to constructor must be the SYMNAME which + * AliGeomManager can trace to geometry. + */ + #ifndef ALIALGVOL_H #define ALIALGVOL_H @@ -11,157 +33,187 @@ class TClonesArray; class AliAlgDOFStat; class TH1; - -/*-------------------------------------------------------- - Base class of alignable volume. Has at least geometric - degrees of freedom + user defined calibration DOFs. - The name provided to constructor must be the SYMNAME which - AliGeomManager can trace to geometry. - -------------------------------------------------------*/ - -// Author: ruben.shahoyan@cern.ch - +namespace o2 +{ +namespace align +{ class AliAlgVol : public TNamed { public: - enum DOFGeom_t {kDOFTX,kDOFTY,kDOFTZ,kDOFPS,kDOFTH,kDOFPH,kNDOFGeom,kAllGeomDOF=0x3F}; - enum {kDOFBitTX=BIT(kDOFTX),kDOFBitTY=BIT(kDOFTY),kDOFBitTZ=BIT(kDOFTZ), - kDOFBitPS=BIT(kDOFPS),kDOFBitTH=BIT(kDOFTH),kDOFBitPH=BIT(kDOFPH)}; - enum {kNDOFMax=32}; - enum Frame_t {kLOC,kTRA,kNVarFrames}; // variation frames defined - enum {kInitDOFsDoneBit=BIT(14),kSkipBit=BIT(15),kExclFromParentConstraintBit=BIT(16)}; - enum {kDefChildConstr=0xff}; - // - AliAlgVol(const char* symname=0, int iid=0); + enum DOFGeom_t { kDOFTX, + kDOFTY, + kDOFTZ, + kDOFPS, + kDOFTH, + kDOFPH, + kNDOFGeom, + kAllGeomDOF = 0x3F }; + enum { kDOFBitTX = BIT(kDOFTX), + kDOFBitTY = BIT(kDOFTY), + kDOFBitTZ = BIT(kDOFTZ), + kDOFBitPS = BIT(kDOFPS), + kDOFBitTH = BIT(kDOFTH), + kDOFBitPH = BIT(kDOFPH) }; + enum { kNDOFMax = 32 }; + enum Frame_t { kLOC, + kTRA, + kNVarFrames }; // variation frames defined + enum { kInitDOFsDoneBit = BIT(14), + kSkipBit = BIT(15), + kExclFromParentConstraintBit = BIT(16) }; + enum { kDefChildConstr = 0xff }; + // + AliAlgVol(const char* symname = 0, int iid = 0); virtual ~AliAlgVol(); // - const char* GetSymName() const {return GetName();} - // - Int_t GetVolID() const {return (Int_t)GetUniqueID();} - void SetVolID(Int_t v) {SetUniqueID(v);} - Int_t GetInternalID() const {return fIntID;} - void SetInternalID(Int_t v) {fIntID = v;} - // - // - void AssignDOFs(Int_t &cntDOFs, Float_t *pars, Float_t *errs, Int_t *labs); - void InitDOFs(); - // - Frame_t GetVarFrame() const {return fVarFrame;} - void SetVarFrame(Frame_t f) {fVarFrame = f;} - Bool_t IsFrameTRA() const {return fVarFrame == kTRA;} - Bool_t IsFrameLOC() const {return fVarFrame == kLOC;} - // - void SetFreeDOF(Int_t dof) {fDOF |= 0x1<AddChild(this);} - Int_t CountParents() const; - // - Int_t GetNChildren() const {return fChildren ? fChildren->GetEntriesFast():0;} - AliAlgVol* GetChild(int i) const {return fChildren ? (AliAlgVol*)fChildren->UncheckedAt(i):0;} + const char* GetSymName() const { return GetName(); } + // + Int_t GetVolID() const { return (Int_t)GetUniqueID(); } + void SetVolID(Int_t v) { SetUniqueID(v); } + Int_t GetInternalID() const { return fIntID; } + void SetInternalID(Int_t v) { fIntID = v; } + // + // + void AssignDOFs(Int_t& cntDOFs, Float_t* pars, Float_t* errs, Int_t* labs); + void InitDOFs(); + // + Frame_t GetVarFrame() const { return fVarFrame; } + void SetVarFrame(Frame_t f) { fVarFrame = f; } + Bool_t IsFrameTRA() const { return fVarFrame == kTRA; } + Bool_t IsFrameLOC() const { return fVarFrame == kLOC; } + // + void SetFreeDOF(Int_t dof) + { + fDOF |= 0x1 << dof; + CalcFree(); + } + void FixDOF(Int_t dof) + { + fDOF &= ~(0x1 << dof); + CalcFree(); + } + void SetFreeDOFPattern(UInt_t pat) + { + fDOF = pat; + CalcFree(); + } + Bool_t IsFreeDOF(Int_t dof) const { return (fDOF & (0x1 << dof)) != 0; } + Bool_t IsCondDOF(Int_t dof) const; + UInt_t GetFreeDOFPattern() const { return fDOF; } + UInt_t GetFreeDOFGeomPattern() const { return fDOF & kAllGeomDOF; } + // + void AddAutoConstraints(TObjArray* constrArr); + Bool_t IsChildrenDOFConstrained(Int_t dof) const { return fConstrChild & 0x1 << dof; } + UChar_t GetChildrenConstraintPattern() const { return fConstrChild; } + void ConstrainChildrenDOF(Int_t dof) { fConstrChild |= 0x1 << dof; } + void UConstrainChildrenDOF(Int_t dof) { fConstrChild &= ~(0x1 << dof); } + void SetChildrenConstrainPattern(UInt_t pat) { fConstrChild = pat; } + Bool_t HasChildrenConstraint() const { return fConstrChild; } + // + AliAlgVol* GetParent() const { return fParent; } + void SetParent(AliAlgVol* par) + { + fParent = par; + if (par) + par->AddChild(this); + } + Int_t CountParents() const; + // + Int_t GetNChildren() const { return fChildren ? fChildren->GetEntriesFast() : 0; } + AliAlgVol* GetChild(int i) const { return fChildren ? (AliAlgVol*)fChildren->UncheckedAt(i) : 0; } virtual void AddChild(AliAlgVol* ch); // - Double_t GetXTracking() const {return fX;} - Double_t GetAlpTracking() const {return fAlp;} - // - Int_t GetNProcessedPoints() const {return fNProcPoints;} - virtual Int_t FinalizeStat(AliAlgDOFStat* h=0); - void FillDOFStat(AliAlgDOFStat* h) const; - // - Float_t* GetParVals() const {return fParVals;} - Double_t GetParVal(int par) const {return fParVals[par];} - Double_t GetParErr(int par) const {return fParErrs[par];} - Int_t GetParLab(int par) const {return fParLabs[par];} - void GetParValGeom(double* delta) const {for (int i=kNDOFGeom;i--;) delta[i]=fParVals[i];} - // - void SetParVals(Int_t npar,Double_t *vl,Double_t *er); - void SetParVal(Int_t par,Double_t v=0) {fParVals[par] = v;} - void SetParErr(Int_t par,Double_t e=0) {fParErrs[par] = e;} - // - Int_t GetNDOFs() const {return fNDOFs;} - Int_t GetNDOFFree() const {return fNDOFFree;} - Int_t GetNDOFGeomFree() const {return fNDOFGeomFree;} - Int_t GetFirstParGloID() const {return fFirstParGloID;} - Int_t GetParGloID(Int_t par) const {return fFirstParGloID+par;} - void SetFirstParGloID(Int_t id) {fFirstParGloID=id;} - // - virtual void PrepareMatrixT2L(); - virtual void SetTrackingFrame(); - // - const TGeoHMatrix& GetMatrixL2G() const {return fMatL2G;} - const TGeoHMatrix& GetMatrixL2GIdeal() const {return fMatL2GIdeal;} - const TGeoHMatrix& GetMatrixL2GReco() const {return fMatL2GReco;} - const TGeoHMatrix& GetGlobalDeltaRef() const {return fMatDeltaRefGlo;} - void SetMatrixL2G(const TGeoHMatrix& m) {fMatL2G = m;} - void SetMatrixL2GIdeal(const TGeoHMatrix& m) {fMatL2GIdeal = m;} - void SetMatrixL2GReco(const TGeoHMatrix& m) {fMatL2GReco = m;} - void SetGlobalDeltaRef(TGeoHMatrix& mat) {fMatDeltaRefGlo = mat;} - // - virtual void PrepareMatrixL2G(Bool_t reco=kFALSE); - virtual void PrepareMatrixL2GIdeal(); - virtual void UpdateL2GRecoMatrices(const TClonesArray* algArr,const TGeoHMatrix* cumulDelta); - // - void GetMatrixT2G(TGeoHMatrix& m) const; - // - const TGeoHMatrix& GetMatrixT2L() const {return fMatT2L;} - void SetMatrixT2L(const TGeoHMatrix& m); - // - void Delta2Matrix(TGeoHMatrix& deltaM, const Double_t *delta) const; + Double_t GetXTracking() const { return fX; } + Double_t GetAlpTracking() const { return fAlp; } + // + Int_t GetNProcessedPoints() const { return fNProcPoints; } + virtual Int_t FinalizeStat(AliAlgDOFStat* h = 0); + void FillDOFStat(AliAlgDOFStat* h) const; + // + Float_t* GetParVals() const { return fParVals; } + Double_t GetParVal(int par) const { return fParVals[par]; } + Double_t GetParErr(int par) const { return fParErrs[par]; } + Int_t GetParLab(int par) const { return fParLabs[par]; } + void GetParValGeom(double* delta) const + { + for (int i = kNDOFGeom; i--;) + delta[i] = fParVals[i]; + } + // + void SetParVals(Int_t npar, Double_t* vl, Double_t* er); + void SetParVal(Int_t par, Double_t v = 0) { fParVals[par] = v; } + void SetParErr(Int_t par, Double_t e = 0) { fParErrs[par] = e; } + // + Int_t GetNDOFs() const { return fNDOFs; } + Int_t GetNDOFFree() const { return fNDOFFree; } + Int_t GetNDOFGeomFree() const { return fNDOFGeomFree; } + Int_t GetFirstParGloID() const { return fFirstParGloID; } + Int_t GetParGloID(Int_t par) const { return fFirstParGloID + par; } + void SetFirstParGloID(Int_t id) { fFirstParGloID = id; } + // + virtual void PrepareMatrixT2L(); + virtual void SetTrackingFrame(); + // + const TGeoHMatrix& GetMatrixL2G() const { return fMatL2G; } + const TGeoHMatrix& GetMatrixL2GIdeal() const { return fMatL2GIdeal; } + const TGeoHMatrix& GetMatrixL2GReco() const { return fMatL2GReco; } + const TGeoHMatrix& GetGlobalDeltaRef() const { return fMatDeltaRefGlo; } + void SetMatrixL2G(const TGeoHMatrix& m) { fMatL2G = m; } + void SetMatrixL2GIdeal(const TGeoHMatrix& m) { fMatL2GIdeal = m; } + void SetMatrixL2GReco(const TGeoHMatrix& m) { fMatL2GReco = m; } + void SetGlobalDeltaRef(TGeoHMatrix& mat) { fMatDeltaRefGlo = mat; } + // + virtual void PrepareMatrixL2G(Bool_t reco = kFALSE); + virtual void PrepareMatrixL2GIdeal(); + virtual void UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta); + // + void GetMatrixT2G(TGeoHMatrix& m) const; + // + const TGeoHMatrix& GetMatrixT2L() const { return fMatT2L; } + void SetMatrixT2L(const TGeoHMatrix& m); + // + void Delta2Matrix(TGeoHMatrix& deltaM, const Double_t* delta) const; // // preparation of variation matrices - void GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t *delta) const; - void GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const Double_t *delta) const; - void GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t *delta, const TGeoHMatrix& relMat) const; - void GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const Double_t *delta, const TGeoHMatrix& relMat) const; + void GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t* delta) const; + void GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const Double_t* delta) const; + void GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t* delta, const TGeoHMatrix& relMat) const; + void GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const Double_t* delta, const TGeoHMatrix& relMat) const; // // creation of global matrices for storage void CreateGloDeltaMatrix(TGeoHMatrix& deltaM) const; void CreateLocDeltaMatrix(TGeoHMatrix& deltaM) const; - void CreatePreGloDeltaMatrix(TGeoHMatrix &deltaM) const; - void CreatePreLocDeltaMatrix(TGeoHMatrix &deltaM) const; + void CreatePreGloDeltaMatrix(TGeoHMatrix& deltaM) const; + void CreatePreLocDeltaMatrix(TGeoHMatrix& deltaM) const; void CreateAlignmenMatrix(TGeoHMatrix& alg) const; void CreateAlignmentObjects(TClonesArray* arr) const; // - void SetSkip(Bool_t v=kTRUE) {SetBit(kSkipBit,v);} - Bool_t GetSkip() const {return TestBit(kSkipBit);} + void SetSkip(Bool_t v = kTRUE) { SetBit(kSkipBit, v); } + Bool_t GetSkip() const { return TestBit(kSkipBit); } // - void ExcludeFromParentConstraint(Bool_t v=kTRUE) {SetBit(kExclFromParentConstraintBit,v);} - Bool_t GetExcludeFromParentConstraint() const {return TestBit(kExclFromParentConstraintBit);} - // - void SetInitDOFsDone() {SetBit(kInitDOFsDoneBit);} - Bool_t GetInitDOFsDone() const {return TestBit(kInitDOFsDoneBit);} + void ExcludeFromParentConstraint(Bool_t v = kTRUE) { SetBit(kExclFromParentConstraintBit, v); } + Bool_t GetExcludeFromParentConstraint() const { return TestBit(kExclFromParentConstraintBit); } // - Bool_t OwnsDOFID(Int_t id) const; - AliAlgVol* GetVolOfDOFID(Int_t id) const; + void SetInitDOFsDone() { SetBit(kInitDOFsDoneBit); } + Bool_t GetInitDOFsDone() const { return TestBit(kInitDOFsDoneBit); } // - virtual Bool_t IsSensor() const {return kFALSE;} + Bool_t OwnsDOFID(Int_t id) const; + AliAlgVol* GetVolOfDOFID(Int_t id) const; // - virtual const char* GetDOFName(int i) const; - virtual void Print(const Option_t *opt="") const; - virtual void WritePedeInfo(FILE* parOut, const Option_t *opt="") const; + virtual Bool_t IsSensor() const { return kFALSE; } // - static const char* GetGeomDOFName(int i) {return i -#include -#include +/// @file Mille.h +/// @author Gero Flucke, ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since October 2006 +/// @brief Class to write C binary file. /** - * \class Mille - * * Class to write a C binary (cf. below) file of a given name and to fill it * with information used as input to **pede**. * Use its member functions \c mille(), \c special(), \c kill() and \c end() @@ -18,26 +24,31 @@ * to write also derivatives and labels which are ==0. * But note that **pede** will not be able to read text output and has not been tested with * derivatives/labels ==0. - * - * \author : Gero Flucke - * date : October 2006 - * $Revision: 1.3 $ - * $Date: 2007/04/16 17:47:38 $ - * (last update by $Author: flucke $) */ -/// Class to write C binary file. -class Mille +#ifndef MILLE_H +#define MILLE_H + +#include +#include +#include + +namespace o2 +{ +namespace align +{ + +class Mille { public: - Mille(const char *outFileName, bool asBinary = true, bool writeZero = false); + Mille(const char* outFileName, bool asBinary = true, bool writeZero = false); ~Mille(); - void mille(int NLC, const float *derLc, int NGL, const float *derGl, - const int *label, float rMeas, float sigma); - void special(int nSpecial, const float *floatings, const int *integers); + void mille(int NLC, const float* derLc, int NGL, const float* derGl, + const int* label, float rMeas, float sigma); + void special(int nSpecial, const float* floatings, const int* integers); void kill(); - int end(); + int end(); private: void newSet(); @@ -47,12 +58,16 @@ class Mille bool myAsBinary; ///< if false output as text bool myWriteZero; ///< if true also write out derivatives/labels ==0 /// buffer size for ints and floats - int myBufferSize; ///< buffer size for ints and floats - TArrayI myBufferInt; ///< to collect labels etc. - TArrayF myBufferFloat; ///< to collect derivatives etc. - int myBufferPos; ///< position in buffer - bool myHasSpecial; ///< if true, special(..) already called for this record + int myBufferSize; ///< buffer size for ints and floats + TArrayI myBufferInt; ///< to collect labels etc. + TArrayF myBufferFloat; ///< to collect derivatives etc. + int myBufferPos; ///< position in buffer + bool myHasSpecial; ///< if true, special(..) already called for this record /// largest label allowed: 2^31 - 1 - enum {myMaxLabel = (0xFFFFFFFF - (1 << 31))}; + enum { myMaxLabel = (0xFFFFFFFF - (1 << 31)) }; }; + +} // namespace align +} // namespace o2 + #endif diff --git a/Detectors/Align/src/ALIGNLinkDef.h b/Detectors/Align/src/ALIGNLinkDef.h index 8b1a36a5b8ca5..05c252f10229d 100644 --- a/Detectors/Align/src/ALIGNLinkDef.h +++ b/Detectors/Align/src/ALIGNLinkDef.h @@ -5,28 +5,28 @@ #pragma link off all functions; //#pragma link C++ class AliAlgAux; -#pragma link C++ class AliAlgDet+; -#pragma link C++ class AliAlgDetITS+; -#pragma link C++ class AliAlgDetTOF+; -#pragma link C++ class AliAlgDetTPC+; -#pragma link C++ class AliAlgDetTRD+; -#pragma link C++ class AliAlgDetHMPID+; -#pragma link C++ class AliAlgMPRecord+; -#pragma link C++ class AliAlgPoint+; -#pragma link C++ class AliAlgSens+; -#pragma link C++ class AliAlgSensITS+; -#pragma link C++ class AliAlgSensTOF+; -#pragma link C++ class AliAlgSensTPC+; -#pragma link C++ class AliAlgSensTRD+; -#pragma link C++ class AliAlgSensHMPID+; -#pragma link C++ class AliAlgSteer+; -#pragma link C++ class AliAlgTrack+; -#pragma link C++ class AliAlgVol+; -#pragma link C++ class AliAlgVtx+; -#pragma link C++ class AliAlgRes+; -#pragma link C++ class AliAlgResFast+; -#pragma link C++ class AliAlgConstraint+; -#pragma link C++ class AliAlgDOFStat+; -#pragma link C++ class AliAlgAux; +#pragma link C++ class o2::align::AliAlgDet+; +#pragma link C++ class o2::align::AliAlgDetITS+; +#pragma link C++ class o2::align::AliAlgDetTOF+; +#pragma link C++ class o2::align::AliAlgDetTPC+; +#pragma link C++ class o2::align::AliAlgDetTRD+; +#pragma link C++ class o2::align::AliAlgDetHMPID+; +#pragma link C++ class o2::align::AliAlgMPRecord+; +#pragma link C++ class o2::align::AliAlgPoint+; +#pragma link C++ class o2::align::AliAlgSens+; +#pragma link C++ class o2::align::AliAlgSensITS+; +#pragma link C++ class o2::align::AliAlgSensTOF+; +#pragma link C++ class o2::align::AliAlgSensTPC+; +#pragma link C++ class o2::align::AliAlgSensTRD+; +#pragma link C++ class o2::align::AliAlgSensHMPID+; +#pragma link C++ class o2::align::AliAlgSteer+; +#pragma link C++ class o2::align::AliAlgTrack+; +#pragma link C++ class o2::align::AliAlgVol+; +#pragma link C++ class o2::align::AliAlgVtx+; +#pragma link C++ class o2::align::AliAlgRes+; +#pragma link C++ class o2::align::AliAlgResFast+; +#pragma link C++ class o2::align::AliAlgConstraint+; +#pragma link C++ class o2::align::AliAlgDOFStat+; +#pragma link C++ class o2::align::AliAlgAux; #endif diff --git a/Detectors/Align/src/AliAlgAux.cxx b/Detectors/Align/src/AliAlgAux.cxx index bcf2d697585d7..cb1951d782231 100644 --- a/Detectors/Align/src/AliAlgAux.cxx +++ b/Detectors/Align/src/AliAlgAux.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgAux.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief Collection of auxillary methods #include "AliAlgAux.h" #include "AliCDBId.h" @@ -24,23 +24,32 @@ #include #include +namespace o2 +{ +namespace align +{ + //_______________________________________________________________ void AliAlgAux::PrintBits(ULong64_t patt, Int_t maxBits) { // print maxBits of the pattern - maxBits = Min(64,maxBits); - for (int i=0;i>i)&0x1) ? '+':'-'); + maxBits = Min(64, maxBits); + for (int i = 0; i < maxBits; i++) + printf("%c", ((patt >> i) & 0x1) ? '+' : '-'); } //_______________________________________________________________ -AliCDBId* AliAlgAux::FindCDBId(const TList* cdbList,const TString& key) +AliCDBId* AliAlgAux::FindCDBId(const TList* cdbList, const TString& key) { // Find enty for the key in the cdbList and create its CDBId // User must take care of deleting created CDBId TIter next(cdbList); TObjString* entry; - while ( (entry=(TObjString*)next()) ) if (entry->GetString().Contains(key)) break; - if (!entry) return 0; + while ((entry = (TObjString*)next())) + if (entry->GetString().Contains(key)) + break; + if (!entry) + return 0; return AliCDBId::MakeFromString(entry->GetString()); // } @@ -53,17 +62,18 @@ void AliAlgAux::RectifyOCDBUri(TString& inp) int ind; if (inp.BeginsWith("alien:/")) { // alien folder TPRegexp fr("[Ff]older=/"); - if ( (ind=inp.Index(fr))>0 ) inp.Remove(0,ind); + if ((ind = inp.Index(fr)) > 0) + inp.Remove(0, ind); ind = inp.First('?'); - if (ind>0) inp.Resize(ind); + if (ind > 0) + inp.Resize(ind); inp.Prepend("alien://"); - } - else if (inp.BeginsWith("local:/")) { + } else if (inp.BeginsWith("local:/")) { ind = inp.First('?'); - if (ind>0) inp.Resize(ind); - } - else { - AliFatalGeneralF("::RectifyOCDBUri","Failed to extract OCDB URI from %s",inp.Data()); + if (ind > 0) + inp.Resize(ind); + } else { + AliFatalGeneralF("::RectifyOCDBUri", "Failed to extract OCDB URI from %s", inp.Data()); } // } @@ -73,41 +83,41 @@ Bool_t AliAlgAux::PreloadOCDB(int run, const TMap* cdbMap, const TList* cdbList) { // Load OCDB paths for given run from pair of cdbMap / cdbList // as they are usually stored in the UserInfo list of esdTree - // In order to avoid unnecessary uploads, the objects are not actually + // In order to avoid unnecessary uploads, the objects are not actually // loaded/cached but just added as specific paths with version - // - TObjString *ostr,*okey; - TString uriDef,uri,key; + // + TObjString *ostr, *okey; + TString uriDef, uri, key; // CleanOCDB(); // ostr = (TObjString*)cdbMap->GetValue("default"); - RectifyOCDBUri( uriDef=ostr->GetString() ); - AliInfoGeneralF("","Default storage %s",uriDef.Data()); + RectifyOCDBUri(uriDef = ostr->GetString()); + AliInfoGeneralF("", "Default storage %s", uriDef.Data()); // - AliCDBManager* man = AliCDBManager::Instance(); + AliCDBManager* man = AliCDBManager::Instance(); man->SetDefaultStorage(uriDef.Data()); man->SetRun(run); // TIter nextM(cdbMap); - while ( (okey=(TObjString*)nextM()) ) { - if ( (key=okey->GetString())=="default") continue; + while ((okey = (TObjString*)nextM())) { + if ((key = okey->GetString()) == "default") + continue; ostr = (TObjString*)cdbMap->GetValue(okey); - RectifyOCDBUri( uri=ostr->GetString() ); - // fetch object from the list - AliCDBId* cdbID = FindCDBId(cdbList,key); - int ver=-1,sver=-1; + RectifyOCDBUri(uri = ostr->GetString()); + // fetch object from the list + AliCDBId* cdbID = FindCDBId(cdbList, key); + int ver = -1, sver = -1; if (cdbID) { ver = cdbID->GetVersion(); - sver= cdbID->GetSubVersion(); + sver = cdbID->GetSubVersion(); delete cdbID; + } else { + AliWarningGeneralF("::PreloadOCDB", "Key %s has special storage %s but absent in the cdbList", + key.Data(), uri.Data()); } - else { - AliWarningGeneralF("::PreloadOCDB","Key %s has special storage %s but absent in the cdbList", - key.Data(),uri.Data()); - } - AliInfoGeneralF("::PreloadOCDB","Setting storage for %s to %s",key.Data(),uri.Data()); - man->SetSpecificStorage(key.Data(),uri.Data(),ver,sver); + AliInfoGeneralF("::PreloadOCDB", "Setting storage for %s to %s", key.Data(), uri.Data()); + man->SetSpecificStorage(key.Data(), uri.Data(), ver, sver); } // return kTRUE; @@ -117,21 +127,28 @@ Bool_t AliAlgAux::PreloadOCDB(int run, const TMap* cdbMap, const TList* cdbList) void AliAlgAux::CleanOCDB() { // brings OCDB to virgin state - Bool_t isGrid = gGrid!=0; + Bool_t isGrid = gGrid != 0; AliCDBManager::Destroy(); - if (isGrid && !gGrid) TGrid::Connect("alien://"); + if (isGrid && !gGrid) + TGrid::Connect("alien://"); } //__________________________________________ -int AliAlgAux::FindKeyIndex(int key, const int *arr, int n) +int AliAlgAux::FindKeyIndex(int key, const int* arr, int n) { // finds index of key in the array - int imn=0,imx=n-1; - while (imx>=imn) { - int mid = (imx+imn)>>1; - if (arr[mid]==key) return mid; - if (arr[mid]= imn) { + int mid = (imx + imn) >> 1; + if (arr[mid] == key) + return mid; + if (arr[mid] < key) + imn = mid + 1; + else + imx = mid - 1; } return -1; } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgConstraint.cxx b/Detectors/Align/src/AliAlgConstraint.cxx index 844fc7f66dcf8..9b04ce85a0d64 100644 --- a/Detectors/Align/src/AliAlgConstraint.cxx +++ b/Detectors/Align/src/AliAlgConstraint.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgConstraint.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief Descriptor of geometrical constraint #include "AliAlgConstraint.h" #include "AliAlignObjParams.h" @@ -21,20 +21,23 @@ #include #include -ClassImp(AliAlgConstraint); +ClassImp(o2::align::AliAlgConstraint); -using namespace AliAlgAux; +using namespace o2::align::AliAlgAux; using namespace TMath; +namespace o2 +{ +namespace align +{ + //___________________________________________________________________ -AliAlgConstraint::AliAlgConstraint(const char* name,const char* title) - :TNamed(name,title) - ,fConstraint(0) - ,fParent(0) - ,fChildren(2) +AliAlgConstraint::AliAlgConstraint(const char* name, const char* title) + : TNamed(name, title), fConstraint(0), fParent(0), fChildren(2) { // def. c-tor - for (int i=kNDOFGeom;i--;) fSigma[i] = 0; + for (int i = kNDOFGeom; i--;) + fSigma[i] = 0; } //___________________________________________________________________ @@ -45,109 +48,121 @@ AliAlgConstraint::~AliAlgConstraint() } //___________________________________________________________________ -void AliAlgConstraint::SetParent(const AliAlgVol* par) +void AliAlgConstraint::SetParent(const AliAlgVol* par) { fParent = par; TString nm = GetName(); if (nm.IsNull()) { - if (par) SetNameTitle(par->GetSymName(),"Automatic"); - else SetNameTitle("GLOBAL","Automatic"); + if (par) + SetNameTitle(par->GetSymName(), "Automatic"); + else + SetNameTitle("GLOBAL", "Automatic"); } } - //______________________________________________________ void AliAlgConstraint::WriteChildrenConstraints(FILE* conOut) const { // write for PEDE eventual constraints on children movement in parent frame // - enum {kOff,kOn,kOnOn}; - enum {kConstr,kMeas}; - const char* comment[3] = {" ","! ","!!"}; - const char* kKeyConstr[2] = {"constraint","measurement"}; + enum { kOff, + kOn, + kOnOn }; + enum { kConstr, + kMeas }; + const char* comment[3] = {" ", "! ", "!!"}; + const char* kKeyConstr[2] = {"constraint", "measurement"}; // Bool_t doJac = !GetNoJacobian(); // do we need jacobian evaluation? int nch = GetNChildren(); - float *cstrArr = new float[nch*kNDOFGeom*kNDOFGeom]; - memset(cstrArr,0,nch*kNDOFGeom*kNDOFGeom*sizeof(float)); - // we need for each children the matrix for vector transformation from children frame + float* cstrArr = new float[nch * kNDOFGeom * kNDOFGeom]; + memset(cstrArr, 0, nch * kNDOFGeom * kNDOFGeom * sizeof(float)); + // we need for each children the matrix for vector transformation from children frame // (in which its DOFs are defined, LOC or TRA) to this parent variation frame // matRel = mPar^-1*mChild TGeoHMatrix mPar; // - // in case of parent assigned use its matrix, - // otherwise Alice global frame is assumed to be the parent -> Unit matrix - if (fParent && doJac) { - if (fParent->IsFrameTRA()) fParent->GetMatrixT2G(mPar); // tracking to global - else mPar = fParent->GetMatrixL2GIdeal(); // local to global + // in case of parent assigned use its matrix, + // otherwise Alice global frame is assumed to be the parent -> Unit matrix + if (fParent && doJac) { + if (fParent->IsFrameTRA()) + fParent->GetMatrixT2G(mPar); // tracking to global + else + mPar = fParent->GetMatrixL2GIdeal(); // local to global mPar = mPar.Inverse(); } // - float *jac = cstrArr; + float* jac = cstrArr; int nContCh[kNDOFGeom] = {0}; // we need at least on contributing children DOF to constrain the parent DOF - for (int ich=0;ichIsFrameTRA()) child->GetMatrixT2G(matRel); // tracking to global - else matRel = child->GetMatrixL2GIdeal(); // local to global + if (child->IsFrameTRA()) + child->GetMatrixT2G(matRel); // tracking to global + else + matRel = child->GetMatrixL2GIdeal(); // local to global matRel.MultiplyLeft(&mPar); - ConstrCoefGeom(matRel,jac); + ConstrCoefGeom(matRel, jac); // - for (int ics=0;icsIsFreeDOF(ip) && child->GetParErr(ip)>=0) nContCh[ip]++; - } + for (int ics = 0; ics < kNDOFGeom; ics++) { // DOF of parent to be constrained + for (int ip = 0; ip < kNDOFGeom; ip++) { // count contributing DOFs + float jv = jac[ics * kNDOFGeom + ip]; + if (!IsZeroAbs(jv) && child->IsFreeDOF(ip) && child->GetParErr(ip) >= 0) + nContCh[ip]++; + } } - } - else { // simple constraint on the sum of requested DOF + } else { // simple constraint on the sum of requested DOF // - for (int ip=0;ipIsFreeDOF(ip) && child->GetParErr(ip)>=0) nContCh[ip]++; - jac[ip*kNDOFGeom+ip] = 1.; + for (int ip = 0; ip < kNDOFGeom; ip++) { + if (child->IsFreeDOF(ip) && child->GetParErr(ip) >= 0) + nContCh[ip]++; + jac[ip * kNDOFGeom + ip] = 1.; } } - jac += kNDOFGeom*kNDOFGeom; // matrix for next slot + jac += kNDOFGeom * kNDOFGeom; // matrix for next slot } // - for (int ics=0;ics0 ? kOff : kOn; // do we comment this constraint? + for (int ics = 0; ics < kNDOFGeom; ics++) { + if (!IsDOFConstrained(ics)) + continue; + int cmtStatus = nContCh[ics] > 0 ? kOff : kOn; // do we comment this constraint? // - if (cmtStatus) AliInfoF("No contributors to constraint of %3s of %s",GetDOFName(ics),GetName()); + if (cmtStatus) + AliInfoF("No contributors to constraint of %3s of %s", GetDOFName(ics), GetName()); // - if (fSigma[ics]>0) { - fprintf(conOut,"\n%s%s\t%e\t%e\t%s %s of %s %s\n",comment[cmtStatus],kKeyConstr[kMeas],0.0,fSigma[ics], - comment[kOnOn],GetDOFName(ics),GetName(),GetTitle()); - } - else { - fprintf(conOut,"\n%s%s\t%e\t%s %s of %s %s\n",comment[cmtStatus],kKeyConstr[kConstr],0.0, - comment[kOnOn],GetDOFName(ics),GetName(),GetTitle()); + if (fSigma[ics] > 0) { + fprintf(conOut, "\n%s%s\t%e\t%e\t%s %s of %s %s\n", comment[cmtStatus], kKeyConstr[kMeas], 0.0, fSigma[ics], + comment[kOnOn], GetDOFName(ics), GetName(), GetTitle()); + } else { + fprintf(conOut, "\n%s%s\t%e\t%s %s of %s %s\n", comment[cmtStatus], kKeyConstr[kConstr], 0.0, + comment[kOnOn], GetDOFName(ics), GetName(), GetTitle()); } - for (int ich=0;ichIsFreeDOF(ip)&&!IsZeroAbs(jv)&& child->GetParErr(ip)>=0) - fprintf(conOut,"%9d %+.3e\t",child->GetParLab(ip),jv); + for (int ip = 0; ip < kNDOFGeom; ip++) { + float jv = jac[ics * kNDOFGeom + ip]; + if (child->IsFreeDOF(ip) && !IsZeroAbs(jv) && child->GetParErr(ip) >= 0) + fprintf(conOut, "%9d %+.3e\t", child->GetParLab(ip), jv); } // loop over DOF's of children contributing to this constraint // now, after comment, write disabled constraints - fprintf(conOut,"%s ",comment[kOn]); + fprintf(conOut, "%s ", comment[kOn]); if (doJac) { - for (int ip=0;ipIsFreeDOF(ip)&&!IsZeroAbs(jv)&& child->GetParErr(ip)>=0) continue; - fprintf(conOut,"%9d %+.3e\t",child->GetParLab(ip),jv); - } // loop over DOF's of children contributing to this constraint + for (int ip = 0; ip < kNDOFGeom; ip++) { + float jv = jac[ics * kNDOFGeom + ip]; + if (child->IsFreeDOF(ip) && !IsZeroAbs(jv) && child->GetParErr(ip) >= 0) + continue; + fprintf(conOut, "%9d %+.3e\t", child->GetParLab(ip), jv); + } // loop over DOF's of children contributing to this constraint } - fprintf(conOut,"%s from %s\n",comment[kOnOn],child->GetName()); + fprintf(conOut, "%s from %s\n", comment[kOnOn], child->GetName()); } // loop over children - } // loop over constraints in parent volume + } // loop over constraints in parent volume // delete[] cstrArr; } @@ -158,98 +173,118 @@ void AliAlgConstraint::CheckConstraint() const // check how the constraints are satysfied // int nch = GetNChildren(); - if (!nch) return; + if (!nch) + return; // Bool_t doJac = !GetNoJacobian(); // do we need jacobian evaluation? - float *cstrArr = new float[nch*kNDOFGeom*kNDOFGeom]; - memset(cstrArr,0,nch*kNDOFGeom*kNDOFGeom*sizeof(float)); - // we need for each children the matrix for vector transformation from children frame + float* cstrArr = new float[nch * kNDOFGeom * kNDOFGeom]; + memset(cstrArr, 0, nch * kNDOFGeom * kNDOFGeom * sizeof(float)); + // we need for each children the matrix for vector transformation from children frame // (in which its DOFs are defined, LOC or TRA) to this parent variation frame // matRel = mPar^-1*mChild TGeoHMatrix mPar; - // in case of parent assigned use its matrix, - // otherwise Alice global frame is assumed to be the parent -> Unit matrix - if (fParent && doJac) { - if (fParent->IsFrameTRA()) fParent->GetMatrixT2G(mPar); // tracking to global - else mPar = fParent->GetMatrixL2GIdeal(); // local to global + // in case of parent assigned use its matrix, + // otherwise Alice global frame is assumed to be the parent -> Unit matrix + if (fParent && doJac) { + if (fParent->IsFrameTRA()) + fParent->GetMatrixT2G(mPar); // tracking to global + else + mPar = fParent->GetMatrixL2GIdeal(); // local to global mPar = mPar.Inverse(); } // - float *jac = cstrArr; + float* jac = cstrArr; double parsTotEx[kNDOFGeom] = {0}; // explicitly calculated total modification double parsTotAn[kNDOFGeom] = {0}; // analyticaly calculated total modification // - printf("\n\n ----- Constraints Validation for %s %s ------\n",GetName(),GetTitle()); + printf("\n\n ----- Constraints Validation for %s %s ------\n", GetName(), GetTitle()); printf(" chld| "); - for (int jp=0;jpGetParVal(jc); // child params in child frame - printf("#%3d | ",ich); + double parsC[kNDOFGeom] = {0}, parsPAn[kNDOFGeom] = {0}, parsPEx[kNDOFGeom] = {0}; + for (int jc = kNDOFGeom; jc--;) + parsC[jc] = child->GetParVal(jc); // child params in child frame + printf("#%3d | ", ich); // if (doJac) { TGeoHMatrix matRel; - if (child->IsFrameTRA()) child->GetMatrixT2G(matRel); // tracking to global - else matRel = child->GetMatrixL2GIdeal(); // local to global + if (child->IsFrameTRA()) + child->GetMatrixT2G(matRel); // tracking to global + else + matRel = child->GetMatrixL2GIdeal(); // local to global // matRel.MultiplyLeft(&mPar); - ConstrCoefGeom(matRel,jac); // Jacobian for analytical constraint used by MillePeded - // - TGeoHMatrix tau; - child->Delta2Matrix(tau,parsC); // child correction matrix in the child frame + ConstrCoefGeom(matRel, jac); // Jacobian for analytical constraint used by MillePeded + // + TGeoHMatrix tau; + child->Delta2Matrix(tau, parsC); // child correction matrix in the child frame const TGeoHMatrix& matreli = matRel.Inverse(); tau.Multiply(&matreli); - tau.MultiplyLeft(&matRel); // child correction matrix in the parent frame + tau.MultiplyLeft(&matRel); // child correction matrix in the parent frame AliAlignObjParams tmpPar; tmpPar.SetMatrix(tau); tmpPar.GetTranslation(&parsPEx[0]); - tmpPar.GetAngles(&parsPEx[3]); // explicitly calculated child params in parent frame + tmpPar.GetAngles(&parsPEx[3]); // explicitly calculated child params in parent frame // // analytically calculated child params in parent frame - for (int jp=0;jpIsFreeDOF(jc) && child->GetParErr(jc)>=0; - if (acc) { printf(" %+.3e ",parsC[jc]); parsTotAn[jc] += parsC[jc];} - else printf(" /* %+.3e */ ",parsC[jc]); // just for info, not in the constraint + jac += kNDOFGeom * kNDOFGeom; // matrix for next slot + } else { + for (int jc = 0; jc < kNDOFGeom; jc++) { + Bool_t acc = child->IsFreeDOF(jc) && child->GetParErr(jc) >= 0; + if (acc) { + printf(" %+.3e ", parsC[jc]); + parsTotAn[jc] += parsC[jc]; + } else + printf(" /* %+.3e */ ", parsC[jc]); // just for info, not in the constraint } } printf(" | "); - for (int jc=0;jcGetSymName()); } - // + // printf(" Tot | "); - for (int jp=0;jpGetParVal(jp)); // parent proper corrections - else printf(" no parent -> %s ",doJac ? "Global":"Simple"); - printf(" ! <----- %s\n",GetName()); + if (fParent) + for (int jp = 0; jp < kNDOFGeom; jp++) + printf("%+.1e ", fParent->GetParVal(jp)); // parent proper corrections + else + printf(" no parent -> %s ", doJac ? "Global" : "Simple"); + printf(" ! <----- %s\n", GetName()); // printf(" Sig | "); - for (int jp=0;jpX approximation... - const double cf[kNDOFGeom] = {1,1,1,DegToRad(),DegToRad(),DegToRad()}; - // + const double cf[kNDOFGeom] = {1, 1, 1, DegToRad(), DegToRad(), DegToRad()}; + // // since the TAU is supposed to convert local corrections in the child frame to corrections - // in the parent frame, we scale angular degrees of freedom back to degrees and assign the + // in the parent frame, we scale angular degrees of freedom back to degrees and assign the // sign of S in the S*sin(angle) in the matrix, so that the final correction has a correct // sign, due to the choice of euler angles in the AliAlignObj::AnglesToMatrix // costhe*cosphi; -costhe*sinphi; sinthe; // sinpsi*sinthe*cosphi + cospsi*sinphi; -sinpsi*sinthe*sinphi + cospsi*cosphi; -costhe*sinpsi; // -cospsi*sinthe*cosphi + sinpsi*sinphi; cospsi*sinthe*sinphi + sinpsi*cosphi; costhe*cospsi; // - const double kJTol = 1e-4; // treat derivatives below this threshold as 0 - const double sgc[kNDOFGeom] = {1.,1.,1.,-RadToDeg(),RadToDeg(),-RadToDeg()}; + const double kJTol = 1e-4; // treat derivatives below this threshold as 0 + const double sgc[kNDOFGeom] = {1., 1., 1., -RadToDeg(), RadToDeg(), -RadToDeg()}; // double dDPar[kNDOFGeom][4][4] = { - // dDX[4][4] - {{0,0,0,0},{0,0,0,0},{0,0,0,0},{rd[0],rd[3],rd[6],0}}, + // dDX[4][4] + {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {rd[0], rd[3], rd[6], 0}}, // dDY[4][4] - {{0,0,0,0},{0,0,0,0},{0,0,0,0},{rd[1],rd[4],rd[7],0}}, + {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {rd[1], rd[4], rd[7], 0}}, // dDZ[4][4] - {{0,0,0,0},{0,0,0,0},{0,0,0,0},{rd[2],rd[5],rd[8],0}}, + {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {rd[2], rd[5], rd[8], 0}}, // dDPSI[4][4] - {{rd[2]*ri[3]-rd[1]*ri[6],rd[2]*ri[4]-rd[1]*ri[7],rd[2]*ri[5]-rd[1]*ri[8],0}, - {rd[5]*ri[3]-rd[4]*ri[6],rd[5]*ri[4]-rd[4]*ri[7],rd[5]*ri[5]-rd[4]*ri[8],0}, - {rd[8]*ri[3]-rd[7]*ri[6],rd[8]*ri[4]-rd[7]*ri[7],rd[8]*ri[5]-rd[7]*ri[8],0}, - {rd[2]*ti[1]-rd[1]*ti[2],rd[5]*ti[1]-rd[4]*ti[2],rd[8]*ti[1]-rd[7]*ti[2],0}}, + {{rd[2] * ri[3] - rd[1] * ri[6], rd[2] * ri[4] - rd[1] * ri[7], rd[2] * ri[5] - rd[1] * ri[8], 0}, + {rd[5] * ri[3] - rd[4] * ri[6], rd[5] * ri[4] - rd[4] * ri[7], rd[5] * ri[5] - rd[4] * ri[8], 0}, + {rd[8] * ri[3] - rd[7] * ri[6], rd[8] * ri[4] - rd[7] * ri[7], rd[8] * ri[5] - rd[7] * ri[8], 0}, + {rd[2] * ti[1] - rd[1] * ti[2], rd[5] * ti[1] - rd[4] * ti[2], rd[8] * ti[1] - rd[7] * ti[2], 0}}, // dDTHT[4][4] - {{rd[0]*ri[6]-rd[2]*ri[0], rd[0]*ri[7]-rd[2]*ri[1], rd[0]*ri[8]-rd[2]*ri[2],0}, - {rd[3]*ri[6]-rd[5]*ri[0], rd[3]*ri[7]-rd[5]*ri[1], rd[3]*ri[8]-rd[5]*ri[2],0}, - {rd[6]*ri[6]-rd[8]*ri[0], rd[6]*ri[7]-rd[8]*ri[1], rd[6]*ri[8]-rd[8]*ri[2],0}, - {rd[0]*ti[2]-rd[2]*ti[0], rd[3]*ti[2]-rd[5]*ti[0], rd[6]*ti[2]-rd[8]*ti[0],0}}, + {{rd[0] * ri[6] - rd[2] * ri[0], rd[0] * ri[7] - rd[2] * ri[1], rd[0] * ri[8] - rd[2] * ri[2], 0}, + {rd[3] * ri[6] - rd[5] * ri[0], rd[3] * ri[7] - rd[5] * ri[1], rd[3] * ri[8] - rd[5] * ri[2], 0}, + {rd[6] * ri[6] - rd[8] * ri[0], rd[6] * ri[7] - rd[8] * ri[1], rd[6] * ri[8] - rd[8] * ri[2], 0}, + {rd[0] * ti[2] - rd[2] * ti[0], rd[3] * ti[2] - rd[5] * ti[0], rd[6] * ti[2] - rd[8] * ti[0], 0}}, // dDPHI[4][4] - {{rd[1]*ri[0]-rd[0]*ri[3],rd[1]*ri[1]-rd[0]*ri[4],rd[1]*ri[2]-rd[0]*ri[5],0}, - {rd[4]*ri[0]-rd[3]*ri[3],rd[4]*ri[1]-rd[3]*ri[4],rd[4]*ri[2]-rd[3]*ri[5],0}, - {rd[7]*ri[0]-rd[6]*ri[3],rd[7]*ri[1]-rd[6]*ri[4],rd[7]*ri[2]-rd[6]*ri[5],0}, - {rd[1]*ti[0]-rd[0]*ti[1],rd[4]*ti[0]-rd[3]*ti[1],rd[7]*ti[0]-rd[6]*ti[1],0}}, + {{rd[1] * ri[0] - rd[0] * ri[3], rd[1] * ri[1] - rd[0] * ri[4], rd[1] * ri[2] - rd[0] * ri[5], 0}, + {rd[4] * ri[0] - rd[3] * ri[3], rd[4] * ri[1] - rd[3] * ri[4], rd[4] * ri[2] - rd[3] * ri[5], 0}, + {rd[7] * ri[0] - rd[6] * ri[3], rd[7] * ri[1] - rd[6] * ri[4], rd[7] * ri[2] - rd[6] * ri[5], 0}, + {rd[1] * ti[0] - rd[0] * ti[1], rd[4] * ti[0] - rd[3] * ti[1], rd[7] * ti[0] - rd[6] * ti[1], 0}}, }; // - for (int cs=0;cskJTol) ? jval : 0; // [cs][ip] + for (int cs = 0; cs < kNDOFGeom; cs++) { + int i = ij[cs][0], j = ij[cs][1]; + for (int ip = 0; ip < kNDOFGeom; ip++) { + double jval = sgc[cs] * dDPar[ip][i][j] * cf[ip]; + jac[cs * kNDOFGeom + ip] = (Abs(jval) > kJTol) ? jval : 0; // [cs][ip] } } } //______________________________________________________ -void AliAlgConstraint::Print(const Option_t *) const +void AliAlgConstraint::Print(const Option_t*) const { // print info printf("Constraint on "); - for (int i=0;iGetName()); + printf("%3d %s\n", i, child->GetName()); } } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgDOFStat.cxx b/Detectors/Align/src/AliAlgDOFStat.cxx index 0de9efb6155f1..387b2c976e932 100644 --- a/Detectors/Align/src/AliAlgDOFStat.cxx +++ b/Detectors/Align/src/AliAlgDOFStat.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgDOFStat.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief Mergable bbject for statistics of points used by each DOF #include "AliAlgDOFStat.h" #include "AliAlgSteer.h" @@ -21,19 +21,21 @@ using namespace TMath; -ClassImp(AliAlgDOFStat) +ClassImp(o2::align::AliAlgDOFStat); + +namespace o2 +{ +namespace align +{ //_________________________________________________________ AliAlgDOFStat::AliAlgDOFStat(Int_t n) - : TNamed("DOFstat","DOF statistics") - ,fNDOFs(n) - ,fNMerges(1) - ,fStat(0) + : TNamed("DOFstat", "DOF statistics"), fNDOFs(n), fNMerges(1), fStat(0) { // def c-tor if (fNDOFs) { fStat = new Int_t[n]; - memset(fStat,0,fNDOFs*sizeof(Int_t)); + memset(fStat, 0, fNDOFs * sizeof(Int_t)); } // } @@ -45,12 +47,11 @@ AliAlgDOFStat::~AliAlgDOFStat() delete[] fStat; } - //____________________________________________ void AliAlgDOFStat::Print(Option_t*) const { // print info - printf("NDOFs: %d, NMerges: %d\n",fNDOFs,fNMerges); + printf("NDOFs: %d, NMerges: %d\n", fNDOFs, fNMerges); // } @@ -58,32 +59,39 @@ void AliAlgDOFStat::Print(Option_t*) const TH1F* AliAlgDOFStat::CreateHisto(AliAlgSteer* st) const { // create histo with stat. If steer object is supplied, build labels - if (!fNDOFs) return 0; - TH1F* h = new TH1F("DOFstat","statistics per DOF",fNDOFs,0,fNDOFs); - for (int i=fNDOFs;i--;) { - h->SetBinContent(i+1,fStat[i]); - if (st) h->GetXaxis()->SetBinLabel(i+1,st->GetDOFLabelTxt(i)); + if (!fNDOFs) + return 0; + TH1F* h = new TH1F("DOFstat", "statistics per DOF", fNDOFs, 0, fNDOFs); + for (int i = fNDOFs; i--;) { + h->SetBinContent(i + 1, fStat[i]); + if (st) + h->GetXaxis()->SetBinLabel(i + 1, st->GetDOFLabelTxt(i)); } return h; } //______________________________________________________________________________ -Long64_t AliAlgDOFStat::Merge(TCollection *list) +Long64_t AliAlgDOFStat::Merge(TCollection* list) { // merge statistics int nmerged = 0; TIter next(list); - TObject *obj; - while((obj=next())) { + TObject* obj; + while ((obj = next())) { AliAlgDOFStat* stAdd = dynamic_cast(obj); - if (!stAdd) continue; + if (!stAdd) + continue; if (fNDOFs != stAdd->fNDOFs) { - AliErrorF("Different NDOF: %d vs %d",fNDOFs,stAdd->fNDOFs); + AliErrorF("Different NDOF: %d vs %d", fNDOFs, stAdd->fNDOFs); return 0; - } - for (int i=fNDOFs;i--;) fStat[i]+=stAdd->fStat[i]; + } + for (int i = fNDOFs; i--;) + fStat[i] += stAdd->fStat[i]; fNMerges += stAdd->fNMerges; nmerged++; } return nmerged; } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgDet.cxx b/Detectors/Align/src/AliAlgDet.cxx index 0a7fb0ae7073f..08154a9611dba 100644 --- a/Detectors/Align/src/AliAlgDet.cxx +++ b/Detectors/Align/src/AliAlgDet.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgDet.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief Base class for detector: wrapper for set of volumes #include "AliAlgDet.h" #include "AliAlgSens.h" @@ -35,42 +35,45 @@ #include #include -ClassImp(AliAlgDet) +ClassImp(o2::align::AliAlgDet); -using namespace AliAlgAux; +using namespace o2::align::AliAlgAux; + +namespace o2 +{ +namespace align +{ //____________________________________________ AliAlgDet::AliAlgDet() -: fNDOFs(0) - ,fVolIDMin(-1) - ,fVolIDMax(-1) - ,fNSensors(0) - ,fSID2VolID(0) - ,fNProcPoints(0) - // - ,fNCalibDOF(0) - ,fNCalibDOFFree(0) - ,fCalibDOF(0) - ,fFirstParGloID(-1) - ,fParVals(0) - ,fParErrs(0) - ,fParLabs(0) - // - ,fUseErrorParam(0) - ,fSensors() - ,fVolumes() - // - ,fNPoints(0) - ,fPoolNPoints(0) - ,fPoolFreePointID(0) - ,fPointsPool() - ,fAlgSteer(0) + : fNDOFs(0), fVolIDMin(-1), fVolIDMax(-1), fNSensors(0), fSID2VolID(0), fNProcPoints(0) + // + , + fNCalibDOF(0), + fNCalibDOFFree(0), + fCalibDOF(0), + fFirstParGloID(-1), + fParVals(0), + fParErrs(0), + fParLabs(0) + // + , + fUseErrorParam(0), + fSensors(), + fVolumes() + // + , + fNPoints(0), + fPoolNPoints(0), + fPoolFreePointID(0), + fPointsPool(), + fAlgSteer(0) { // def c-tor SetUniqueID(AliAlgSteer::kUndefined); // derived detectors must override this fAddError[0] = fAddError[1] = 0; // - for (int i=0;iGetFriendTrack()); @@ -103,13 +105,16 @@ Int_t AliAlgDet::ProcessPoints(const AliESDtrack* esdTr, AliAlgTrack* algTrack, int np(trP->GetNPoints()); int npSel(0); AliAlgPoint* apnt(0); - for (int ip=0;ipGetVolumeID()[ip]; - if (!SensorOfDetector(vid)) continue; + if (!SensorOfDetector(vid)) + continue; apnt = GetSensorByVolId(vid)->TrackPoint2AlgPoint(ip, trP, esdTr); - if (!apnt) continue; + if (!apnt) + continue; algTrack->AddPoint(apnt); - if (inv) apnt->SetInvDir(); + if (inv) + apnt->SetInvDir(); npSel++; fNPoints++; } @@ -124,7 +129,6 @@ void AliAlgDet::AcknowledgeNewRun(Int_t run) // detector should be able to undo alignment/calibration used during the reco UpdateL2GRecoMatrices(); - } //_________________________________________________________ @@ -133,25 +137,26 @@ void AliAlgDet::UpdateL2GRecoMatrices() // Update L2G matrices used for data reconstruction // AliCDBManager* man = AliCDBManager::Instance(); - AliCDBEntry* ent = man->Get(Form("%s/Align/Data",GetName())); - const TClonesArray *algArr = (const TClonesArray*)ent->GetObject(); + AliCDBEntry* ent = man->Get(Form("%s/Align/Data", GetName())); + const TClonesArray* algArr = (const TClonesArray*)ent->GetObject(); // int nvol = GetNVolumes(); - for (int iv=0;ivGetParent()) vol->UpdateL2GRecoMatrices(algArr,0); + if (!vol->GetParent()) + vol->UpdateL2GRecoMatrices(algArr, 0); } // } - //_________________________________________________________ -void AliAlgDet::ApplyAlignmentFromMPSol() +void AliAlgDet::ApplyAlignmentFromMPSol() { // apply alignment from millepede solution array to reference alignment level AliInfo("Applying alignment from Millepede solution"); - for (int isn=GetNSensors();isn--;) GetSensor(isn)->ApplyAlignmentFromMPSol(); + for (int isn = GetNSensors(); isn--;) + GetSensor(isn)->ApplyAlignmentFromMPSol(); } //_________________________________________________________ @@ -161,30 +166,32 @@ void AliAlgDet::CacheReferenceOCDB() // // cache global deltas to avoid preicision problem AliCDBManager* man = AliCDBManager::Instance(); - AliCDBEntry* ent = man->Get(Form("%s/Align/Data",GetName())); + AliCDBEntry* ent = man->Get(Form("%s/Align/Data", GetName())); TObjArray* arr = (TObjArray*)ent->GetObject(); - for (int i=arr->GetEntriesFast();i--;) { + for (int i = arr->GetEntriesFast(); i--;) { const AliAlignObjParams* par = (const AliAlignObjParams*)arr->At(i); AliAlgVol* vol = GetVolume(par->GetSymName()); - if (!vol) {AliErrorF("Volume %s not found",par->GetSymName()); continue;} + if (!vol) { + AliErrorF("Volume %s not found", par->GetSymName()); + continue; + } TGeoHMatrix delta; par->GetMatrix(delta); vol->SetGlobalDeltaRef(delta); } } - //_________________________________________________________ AliAlgPoint* AliAlgDet::GetPointFromPool() { // fetch or create new free point from the pool. // detector may override this method to create its own points derived from AliAlgPoint // - if (fPoolFreePointID>=fPoolNPoints) { // expand pool + if (fPoolFreePointID >= fPoolNPoints) { // expand pool fPointsPool.AddAtAndExpand(new AliAlgPoint(), fPoolNPoints++); } // - AliAlgPoint* pnt = (AliAlgPoint*) fPointsPool.UncheckedAt(fPoolFreePointID++); + AliAlgPoint* pnt = (AliAlgPoint*)fPointsPool.UncheckedAt(fPoolFreePointID++); pnt->Clear(); return pnt; // @@ -197,7 +204,7 @@ void AliAlgDet::ResetPool() fPoolFreePointID = 0; fNPoints = 0; } - + //_________________________________________________________ void AliAlgDet::DefineVolumes() { @@ -210,15 +217,17 @@ void AliAlgDet::AddVolume(AliAlgVol* vol) { // add volume if (GetVolume(vol->GetSymName())) { - AliFatalF("Volume %s was already added to %s",vol->GetName(),GetName()); + AliFatalF("Volume %s was already added to %s", vol->GetName(), GetName()); } fVolumes.AddLast(vol); if (vol->IsSensor()) { fSensors.AddLast(vol); ((AliAlgSens*)vol)->SetDetector(this); Int_t vid = ((AliAlgSens*)vol)->GetVolID(); - if (fVolIDMin<0 || vidfVolIDMax) fVolIDMax = vid; + if (fVolIDMin < 0 || vid < fVolIDMin) + fVolIDMin = vid; + if (fVolIDMax < 0 || vid > fVolIDMax) + fVolIDMax = vid; } // } @@ -232,7 +241,7 @@ void AliAlgDet::DefineMatrices() // TIter next(&fVolumes); AliAlgVol* vol(0); - while ( (vol=(AliAlgVol*)next()) ) { + while ((vol = (AliAlgVol*)next())) { // modified global-local matrix vol->PrepareMatrixL2G(); // ideal global-local matrix @@ -245,9 +254,10 @@ void AliAlgDet::DefineMatrices() // is used for as the reference for the alignment parameters only, // see its definition in the AliAlgVol::PrepateMatrixT2L next.Reset(); - while ( (vol=(AliAlgVol*)next()) ) { + while ((vol = (AliAlgVol*)next())) { vol->PrepareMatrixT2L(); - if (vol->IsSensor()) ((AliAlgSens*)vol)->PrepareMatrixClAlg(); // alignment matrix + if (vol->IsSensor()) + ((AliAlgSens*)vol)->PrepareMatrixClAlg(); // alignment matrix } // } @@ -263,7 +273,7 @@ void AliAlgDet::SortSensors() } fSensors.Sort(); fSID2VolID = new Int_t[fNSensors]; // cash id's for fast binary search - for (int i=0;iGetVolID(); GetSensor(i)->SetSID(i); } @@ -274,17 +284,18 @@ void AliAlgDet::SortSensors() Int_t AliAlgDet::InitGeom() { // define hiearchy, initialize matrices, return number of global parameters - if (GetInitGeomDone()) return 0; + if (GetInitGeomDone()) + return 0; // DefineVolumes(); - SortSensors(); // VolID's must be in increasing order + SortSensors(); // VolID's must be in increasing order DefineMatrices(); // // calculate number of global parameters int nvol = GetNVolumes(); fNDOFs = 0; - for (int iv=0;ivGetNDOFs(); } // @@ -299,31 +310,33 @@ Int_t AliAlgDet::AssignDOFs() // assign DOFs IDs, parameters // int gloCount0(fAlgSteer->GetNDOFs()), gloCount(fAlgSteer->GetNDOFs()); - Float_t* pars = fAlgSteer->GetGloParVal(); - Float_t* errs = fAlgSteer->GetGloParErr(); - Int_t* labs = fAlgSteer->GetGloParLab(); + Float_t* pars = fAlgSteer->GetGloParVal(); + Float_t* errs = fAlgSteer->GetGloParErr(); + Int_t* labs = fAlgSteer->GetGloParLab(); // // assign calibration DOFs fFirstParGloID = gloCount; fParVals = pars + gloCount; fParErrs = errs + gloCount; fParLabs = labs + gloCount; - for (int icl=0;iclGetParent()) vol->AssignDOFs(gloCount,pars,errs,labs); + if (!vol->GetParent()) + vol->AssignDOFs(gloCount, pars, errs, labs); } // - if (fNDOFs != gloCount-gloCount0) AliFatalF("Mismatch between declared %d and initialized %d DOFs for %s", - fNDOFs,gloCount-gloCount0,GetName()); - + if (fNDOFs != gloCount - gloCount0) + AliFatalF("Mismatch between declared %d and initialized %d DOFs for %s", + fNDOFs, gloCount - gloCount0, GetName()); + return fNDOFs; } @@ -331,13 +344,17 @@ Int_t AliAlgDet::AssignDOFs() void AliAlgDet::InitDOFs() { // initialize free parameters - if (GetInitDOFsDone()) AliFatalF("Something is wrong, DOFs are already initialized for %s",GetName()); + if (GetInitDOFsDone()) + AliFatalF("Something is wrong, DOFs are already initialized for %s", GetName()); // // process calibration DOFs - for (int i=0;iInitDOFs(); + for (int iv = 0; iv < nvol; iv++) + GetVolume(iv)->InitDOFs(); // CalcFree(kTRUE); // @@ -346,60 +363,66 @@ void AliAlgDet::InitDOFs() } //_________________________________________________________ -Int_t AliAlgDet::VolID2SID(Int_t vid) const +Int_t AliAlgDet::VolID2SID(Int_t vid) const { // find SID corresponding to VolID - int mn(0),mx(fNSensors-1); - while (mx>=mn) { - int md( (mx+mn)>>1 ), vids(GetSensor(md)->GetVolID()); - if (vidvids) mn = md+1; - else return md; + int mn(0), mx(fNSensors - 1); + while (mx >= mn) { + int md((mx + mn) >> 1), vids(GetSensor(md)->GetVolID()); + if (vid < vids) + mx = md - 1; + else if (vid > vids) + mn = md + 1; + else + return md; } return -1; } //____________________________________________ -void AliAlgDet::Print(const Option_t *opt) const +void AliAlgDet::Print(const Option_t* opt) const { // print info TString opts = opt; opts.ToLower(); printf("\nDetector:%5s %5d volumes %5d sensors {VolID: %5d-%5d} Def.Sys.Err: %.4e %.4e | Stat:%d\n", - GetName(),GetNVolumes(),GetNSensors(),GetVolIDMin(), - GetVolIDMax(),fAddError[0],fAddError[1],fNProcPoints); + GetName(), GetNVolumes(), GetNSensors(), GetVolIDMin(), + GetVolIDMax(), fAddError[0], fAddError[1], fNProcPoints); // printf("Errors assignment: "); - if (fUseErrorParam) printf("param %d\n",fUseErrorParam); - else printf("from TrackPoints\n"); + if (fUseErrorParam) + printf("param %d\n", fUseErrorParam); + else + printf("from TrackPoints\n"); // printf("Allowed in Collisions: %7s | Cosmic: %7s\n", - IsDisabled(kColl) ? " NO ":" YES ",IsDisabled(kCosm) ? " NO ":" YES "); + IsDisabled(kColl) ? " NO " : " YES ", IsDisabled(kCosm) ? " NO " : " YES "); // printf("Obligatory in Collisions: %7s | Cosmic: %7s\n", - IsObligatory(kColl) ? " YES ":" NO ",IsObligatory(kCosm) ? " YES ":" NO "); + IsObligatory(kColl) ? " YES " : " NO ", IsObligatory(kCosm) ? " YES " : " NO "); // printf("Sel. flags in Collisions: 0x%05lx | Cosmic: 0x%05lx\n", - fTrackFlagSel[kColl],fTrackFlagSel[kCosm]); + fTrackFlagSel[kColl], fTrackFlagSel[kCosm]); // printf("Min.points in Collisions: %7d | Cosmic: %7d\n", - fNPointsSel[kColl],fNPointsSel[kCosm]); + fNPointsSel[kColl], fNPointsSel[kCosm]); // - if (!(IsDisabledColl()&&IsDisabledCosm()) && opts.Contains("long")) - for (int iv=0;ivPrint(opt); + if (!(IsDisabledColl() && IsDisabledCosm()) && opts.Contains("long")) + for (int iv = 0; iv < GetNVolumes(); iv++) + GetVolume(iv)->Print(opt); // - for (int i=0;i=AliAlgSteer::kNDetectors) AliFatalF("Detector typeID %d exceeds allowed range %d:%d", - tp,0,AliAlgSteer::kNDetectors-1); + if (tp >= AliAlgSteer::kNDetectors) + AliFatalF("Detector typeID %d exceeds allowed range %d:%d", + tp, 0, AliAlgSteer::kNDetectors - 1); SetUniqueID(tp); } @@ -407,19 +430,20 @@ void AliAlgDet::SetDetID(UInt_t tp) void AliAlgDet::SetAddError(double sigy, double sigz) { // add syst error to all sensors - AliInfoF("Adding sys.error %.4e %.4e to all sensors",sigy,sigz); + AliInfoF("Adding sys.error %.4e %.4e to all sensors", sigy, sigz); fAddError[0] = sigy; fAddError[1] = sigz; - for (int isn=GetNSensors();isn--;) GetSensor(isn)->SetAddError(sigy,sigz); + for (int isn = GetNSensors(); isn--;) + GetSensor(isn)->SetAddError(sigy, sigz); // } //____________________________________________ -void AliAlgDet::SetUseErrorParam(Int_t v) +void AliAlgDet::SetUseErrorParam(Int_t v) { // set type of points error parameterization AliFatal("UpdatePointByTrackInfo is not implemented for this detector"); - // + // } //____________________________________________ @@ -430,24 +454,25 @@ void AliAlgDet::UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackP } //____________________________________________ -void AliAlgDet::SetObligatory(Int_t tp,Bool_t v) +void AliAlgDet::SetObligatory(Int_t tp, Bool_t v) { // mark detector presence obligatory in the track fObligatory[tp] = v; - fAlgSteer->SetObligatoryDetector(GetDetID(),tp,v); + fAlgSteer->SetObligatoryDetector(GetDetID(), tp, v); } //______________________________________________________ -void AliAlgDet::WritePedeInfo(FILE* parOut, const Option_t *opt) const +void AliAlgDet::WritePedeInfo(FILE* parOut, const Option_t* opt) const { // contribute to params and constraints template files for PEDE - fprintf(parOut,"\n!!\t\tDetector:\t%s\tNDOFs: %d\n",GetName(),GetNDOFs()); + fprintf(parOut, "\n!!\t\tDetector:\t%s\tNDOFs: %d\n", GetName(), GetNDOFs()); // // parameters int nvol = GetNVolumes(); - for (int iv=0;ivGetParent()) vol->WritePedeInfo(parOut,opt); + for (int iv = 0; iv < nvol; iv++) { // call for root level volumes, they will take care of their children + AliAlgVol* vol = GetVolume(iv); + if (!vol->GetParent()) + vol->WritePedeInfo(parOut, opt); } // } @@ -457,7 +482,7 @@ void AliAlgDet::WriteCalibrationResults() const { // store calibration results WriteAlignmentResults(); - // + // // eventually we may write other calibrations } @@ -465,13 +490,14 @@ void AliAlgDet::WriteCalibrationResults() const void AliAlgDet::WriteAlignmentResults() const { // store updated alignment - TClonesArray* arr = new TClonesArray("AliAlignObjParams",10); + TClonesArray* arr = new TClonesArray("AliAlignObjParams", 10); // int nvol = GetNVolumes(); - for (int iv=0;ivGetParent()) vol->CreateAlignmentObjects(arr); + if (!vol->GetParent()) + vol->CreateAlignmentObjects(arr); } // AliCDBManager* man = AliCDBManager::Instance(); @@ -479,8 +505,8 @@ void AliAlgDet::WriteAlignmentResults() const md->SetResponsible(fAlgSteer->GetOutCDBResponsible()); md->SetComment(fAlgSteer->GetOutCDBResponsible()); // - AliCDBId id(Form("%s/Align/Data",GetName()),fAlgSteer->GetOutCDBRunMin(),fAlgSteer->GetOutCDBRunMax()); - man->Put(arr,id,md); + AliCDBId id(Form("%s/Align/Data", GetName()), fAlgSteer->GetOutCDBRunMin(), fAlgSteer->GetOutCDBRunMax()); + man->Put(arr, id, md); // delete arr; } @@ -489,12 +515,14 @@ void AliAlgDet::WriteAlignmentResults() const Bool_t AliAlgDet::OwnsDOFID(Int_t id) const { // check if DOF ID belongs to this detector - for (int iv=GetNVolumes();iv--;) { + for (int iv = GetNVolumes(); iv--;) { AliAlgVol* vol = GetVolume(iv); // check only top level volumes - if (!vol->GetParent() && vol->OwnsDOFID(id)) return kTRUE; + if (!vol->GetParent() && vol->OwnsDOFID(id)) + return kTRUE; } // calibration DOF? - if (id>=fFirstParGloID && id= fFirstParGloID && id < fFirstParGloID + fNCalibDOF) + return kTRUE; // return kFALSE; } @@ -503,10 +531,12 @@ Bool_t AliAlgDet::OwnsDOFID(Int_t id) const AliAlgVol* AliAlgDet::GetVolOfDOFID(Int_t id) const { // gets volume owning this DOF ID - for (int iv=GetNVolumes();iv--;) { + for (int iv = GetNVolumes(); iv--;) { AliAlgVol* vol = GetVolume(iv); - if (vol->GetParent()) continue; // check only top level volumes - if ( (vol=vol->GetVolOfDOFID(id)) ) return vol; + if (vol->GetParent()) + continue; // check only top level volumes + if ((vol = vol->GetVolOfDOFID(id))) + return vol; } return 0; } @@ -519,10 +549,11 @@ void AliAlgDet::Terminate() int nvol = GetNVolumes(); fNProcPoints = 0; AliAlgDOFStat* st = fAlgSteer->GetDOFStat(); - for (int iv=0;ivGetParent()) fNProcPoints += vol->FinalizeStat(st); + if (!vol->GetParent()) + fNProcPoints += vol->FinalizeStat(st); } FillDOFStat(st); // fill stat for calib dofs } @@ -532,9 +563,10 @@ void AliAlgDet::AddAutoConstraints() const { // adds automatic constraints int nvol = GetNVolumes(); - for (int iv=0;ivGetParent()) vol->AddAutoConstraints((TObjArray*)fAlgSteer->GetConstraints()); + for (int iv = 0; iv < nvol; iv++) { // call for root level volumes, they will take care of their children + AliAlgVol* vol = GetVolume(iv); + if (!vol->GetParent()) + vol->AddAutoConstraints((TObjArray*)fAlgSteer->GetConstraints()); } } @@ -542,9 +574,10 @@ void AliAlgDet::AddAutoConstraints() const void AliAlgDet::FixNonSensors() { // fix all non-sensor volumes - for (int i=GetNVolumes();i--;) { - AliAlgVol *vol = GetVolume(i); - if (vol->IsSensor()) continue; + for (int i = GetNVolumes(); i--;) { + AliAlgVol* vol = GetVolume(i); + if (vol->IsSensor()) + continue; vol->SetFreeDOFPattern(0); vol->SetChildrenConstrainPattern(0); } @@ -555,13 +588,16 @@ int AliAlgDet::SelectVolumes(TObjArray* arr, int lev, const char* match) { // select volumes matching to pattern and/or hierarchy level // - if (!arr) return 0; + if (!arr) + return 0; int nadd = 0; - TString mts=match, syms; - for (int i=GetNVolumes();i--;) { - AliAlgVol *vol = GetVolume(i); - if (lev>=0 && vol->CountParents()!=lev) continue; // wrong level - if (!mts.IsNull() && !(syms=vol->GetSymName()).Contains(mts)) continue; //wrong name + TString mts = match, syms; + for (int i = GetNVolumes(); i--;) { + AliAlgVol* vol = GetVolume(i); + if (lev >= 0 && vol->CountParents() != lev) + continue; // wrong level + if (!mts.IsNull() && !(syms = vol->GetSymName()).Contains(mts)) + continue; //wrong name arr->AddLast(vol); nadd++; } @@ -570,35 +606,41 @@ int AliAlgDet::SelectVolumes(TObjArray* arr, int lev, const char* match) } //________________________________________ -void AliAlgDet::SetFreeDOFPattern(UInt_t pat, int lev,const char* match) +void AliAlgDet::SetFreeDOFPattern(UInt_t pat, int lev, const char* match) { // set free DOFs to volumes matching either to hierarchy level or // whose name contains match // - TString mts=match, syms; - for (int i=GetNVolumes();i--;) { - AliAlgVol *vol = GetVolume(i); - if (lev>=0 && vol->CountParents()!=lev) continue; // wrong level - if (!mts.IsNull() && !(syms=vol->GetSymName()).Contains(mts)) continue; //wrong name + TString mts = match, syms; + for (int i = GetNVolumes(); i--;) { + AliAlgVol* vol = GetVolume(i); + if (lev >= 0 && vol->CountParents() != lev) + continue; // wrong level + if (!mts.IsNull() && !(syms = vol->GetSymName()).Contains(mts)) + continue; //wrong name vol->SetFreeDOFPattern(pat); } // } //________________________________________ -void AliAlgDet::SetDOFCondition(int dof, float condErr ,int lev,const char* match) +void AliAlgDet::SetDOFCondition(int dof, float condErr, int lev, const char* match) { // set condition for DOF of volumes matching either to hierarchy level or // whose name contains match // - TString mts=match, syms; - for (int i=GetNVolumes();i--;) { - AliAlgVol *vol = GetVolume(i); - if (lev>=0 && vol->CountParents()!=lev) continue; // wrong level - if (!mts.IsNull() && !(syms=vol->GetSymName()).Contains(mts)) continue; //wrong name - if (dof>=vol->GetNDOFs()) continue; + TString mts = match, syms; + for (int i = GetNVolumes(); i--;) { + AliAlgVol* vol = GetVolume(i); + if (lev >= 0 && vol->CountParents() != lev) + continue; // wrong level + if (!mts.IsNull() && !(syms = vol->GetSymName()).Contains(mts)) + continue; //wrong name + if (dof >= vol->GetNDOFs()) + continue; vol->SetParErr(dof, condErr); - if (condErr>=0 && !vol->IsFreeDOF(dof)) vol->SetFreeDOF(dof); + if (condErr >= 0 && !vol->IsFreeDOF(dof)) + vol->SetFreeDOF(dof); //if (condErr<0 && vol->IsFreeDOF(dof)) vol->FixDOF(dof); } // @@ -612,34 +654,40 @@ void AliAlgDet::ConstrainOrphans(const double* sigma, const char* match) // sigma=0 : dof constrained exactly (Lagrange multiplier) // sigma>0 : dof constrained by gaussian constraint // - TString mts=match, syms; + TString mts = match, syms; AliAlgConstraint* constr = new AliAlgConstraint(); - for (int i=0;i=0) constr->ConstrainDOF(i); - else constr->UnConstrainDOF(i); - constr->SetSigma(i,sigma[i]); - } - for (int i=GetNVolumes();i--;) { - AliAlgVol *vol = GetVolume(i); - if (vol->GetParent()) continue; // wrong level - if (!mts.IsNull() && !(syms=vol->GetSymName()).Contains(mts)) continue; //wrong name + for (int i = 0; i < AliAlgVol::kNDOFGeom; i++) { + if (sigma[i] >= 0) + constr->ConstrainDOF(i); + else + constr->UnConstrainDOF(i); + constr->SetSigma(i, sigma[i]); + } + for (int i = GetNVolumes(); i--;) { + AliAlgVol* vol = GetVolume(i); + if (vol->GetParent()) + continue; // wrong level + if (!mts.IsNull() && !(syms = vol->GetSymName()).Contains(mts)) + continue; //wrong name constr->AddChild(vol); } // if (!constr->GetNChildren()) { - AliInfoF("No volume passed filter %s",match); + AliInfoF("No volume passed filter %s", match); delete constr; - } - else ((TObjArray*)fAlgSteer->GetConstraints())->Add(constr); + } else + ((TObjArray*)fAlgSteer->GetConstraints())->Add(constr); // } //________________________________________ -void AliAlgDet::SetFreeDOF(Int_t dof) +void AliAlgDet::SetFreeDOF(Int_t dof) { // set detector free dof - if (dof>=kNMaxKalibDOF) {AliFatalF("Detector CalibDOFs limited to %d, requested %d",kNMaxKalibDOF,dof);} - fCalibDOF |= 0x1<= kNMaxKalibDOF) { + AliFatalF("Detector CalibDOFs limited to %d, requested %d", kNMaxKalibDOF, dof); + } + fCalibDOF |= 0x1 << dof; CalcFree(); } @@ -647,8 +695,10 @@ void AliAlgDet::SetFreeDOF(Int_t dof) void AliAlgDet::FixDOF(Int_t dof) { // fix detector dof - if (dof>=kNMaxKalibDOF) {AliFatalF("Detector CalibDOFs limited to %d, requested %d",kNMaxKalibDOF,dof);} - fCalibDOF &=~(0x1<= kNMaxKalibDOF) { + AliFatalF("Detector CalibDOFs limited to %d, requested %d", kNMaxKalibDOF, dof); + } + fCalibDOF &= ~(0x1 << dof); CalcFree(); } @@ -664,9 +714,10 @@ void AliAlgDet::CalcFree(Bool_t condFix) { // calculate free calib dofs. If condFix==true, condition parameter a la pede, i.e. error < 0 fNCalibDOFFree = 0; - for (int i=0;iAddStat(dof,stat); + for (int idf = 0; idf < ndf; idf++) { + int dof = idf + dof0; + st->AddStat(dof, stat); } // } @@ -694,28 +746,28 @@ void AliAlgDet::WriteSensorPositions(const char* outFName) { // create tree with sensors ideal, ref and reco positions int ns = GetNSensors(); - double loc[3]={0}; + double loc[3] = {0}; // ------- local container type for dumping sensor positions ------ typedef struct { - int volID; // volume id + int volID; // volume id double pId[3]; // ideal double pRf[3]; // reference double pRc[3]; // reco-time } snpos_t; - snpos_t spos; // - TFile* fl = TFile::Open(outFName,"recreate"); - TTree* tr = new TTree("snpos",Form("sensor poisitions for %s",GetName())); - tr->Branch("volID",&spos.volID,"volID/I"); - tr->Branch("pId",&spos.pId,"pId[3]/D"); - tr->Branch("pRf",&spos.pRf,"pRf[3]/D"); - tr->Branch("pRc",&spos.pRc,"pRc[3]/D"); - // - for (int isn=0;isnBranch("volID", &spos.volID, "volID/I"); + tr->Branch("pId", &spos.pId, "pId[3]/D"); + tr->Branch("pRf", &spos.pRf, "pRf[3]/D"); + tr->Branch("pRc", &spos.pRc, "pRc[3]/D"); + // + for (int isn = 0; isn < ns; isn++) { AliAlgSens* sens = GetSensor(isn); spos.volID = sens->GetVolID(); - sens->GetMatrixL2GIdeal().LocalToMaster(loc,spos.pId); - sens->GetMatrixL2G().LocalToMaster(loc,spos.pRf); - sens->GetMatrixL2GReco().LocalToMaster(loc,spos.pRc); + sens->GetMatrixL2GIdeal().LocalToMaster(loc, spos.pId); + sens->GetMatrixL2G().LocalToMaster(loc, spos.pRf); + sens->GetMatrixL2GReco().LocalToMaster(loc, spos.pRc); tr->Fill(); } tr->Write(); @@ -723,3 +775,6 @@ void AliAlgDet::WriteSensorPositions(const char* outFName) fl->Close(); delete fl; } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgDetHMPID.cxx b/Detectors/Align/src/AliAlgDetHMPID.cxx index b183110b29f72..dd73d3354500d 100644 --- a/Detectors/Align/src/AliAlgDetHMPID.cxx +++ b/Detectors/Align/src/AliAlgDetHMPID.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgDetHMPID.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief HMPID detector wrapper #include "AliAlgDetHMPID.h" #include "AliHMPIDParam.h" @@ -23,13 +23,18 @@ #include "AliLog.h" #include -ClassImp(AliAlgDetHMPID); +ClassImp(o2::align::AliAlgDetHMPID); + +namespace o2 +{ +namespace align +{ //____________________________________________ AliAlgDetHMPID::AliAlgDetHMPID(const char* title) { // default c-tor - SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kHMPID),title); + SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kHMPID), title); SetDetID(AliAlgSteer::kHMPID); } @@ -46,25 +51,30 @@ void AliAlgDetHMPID::DefineVolumes() // int labDet = GetDetLabel(); AliGeomManager::ELayerID idHMPID = AliGeomManager::kHMPID; - for(Int_t iCh=AliHMPIDParam::kMinCh;iCh<=AliHMPIDParam::kMaxCh;iCh++) { - const char *symname = Form("/HMPID/Chamber%i",iCh); + for (Int_t iCh = AliHMPIDParam::kMinCh; iCh <= AliHMPIDParam::kMaxCh; iCh++) { + const char* symname = Form("/HMPID/Chamber%i", iCh); if (!gGeoManager->GetAlignableEntry(symname)) { - AliErrorF("Did not find alignable %s",symname); + AliErrorF("Did not find alignable %s", symname); continue; } - UShort_t vid = AliGeomManager::LayerToVolUID(idHMPID,iCh); - int iid = labDet + (1+iCh)*10000; - AliAlgSensHMPID* sens = new AliAlgSensHMPID(symname,vid,iid); + UShort_t vid = AliGeomManager::LayerToVolUID(idHMPID, iCh); + int iid = labDet + (1 + iCh) * 10000; + AliAlgSensHMPID* sens = new AliAlgSensHMPID(symname, vid, iid); AddVolume(sens); - }//iCh loop + } //iCh loop // } //____________________________________________ -Bool_t AliAlgDetHMPID::AcceptTrack(const AliESDtrack* trc, Int_t trtype) const +Bool_t AliAlgDetHMPID::AcceptTrack(const AliESDtrack* trc, Int_t trtype) const { // test if detector had seed this track - if (!CheckFlags(trc,trtype)) return kFALSE; - if (trc->GetNcls(1)GetNcls(1) < fNPointsSel[trtype]) + return kFALSE; return kTRUE; } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgDetITS.cxx b/Detectors/Align/src/AliAlgDetITS.cxx index d69629eba3bc7..67111ed4a6c61 100644 --- a/Detectors/Align/src/AliAlgDetITS.cxx +++ b/Detectors/Align/src/AliAlgDetITS.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgDetITS.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief ITS detector wrapper #include "AliAlgDetITS.h" #include "AliAlgVol.h" @@ -25,19 +25,23 @@ #include using namespace TMath; -using namespace AliAlgAux; +using namespace o2::align::AliAlgAux; -ClassImp(AliAlgDetITS); +ClassImp(o2::align::AliAlgDetITS); -const Char_t* AliAlgDetITS::fgkHitsSel[AliAlgDetITS::kNSPDSelTypes] = - {"SPDNoSel","SPDBoth","SPDAny","SPD0","SPD1"}; +namespace o2 +{ +namespace align +{ +const Char_t* AliAlgDetITS::fgkHitsSel[AliAlgDetITS::kNSPDSelTypes] = + {"SPDNoSel", "SPDBoth", "SPDAny", "SPD0", "SPD1"}; //____________________________________________ AliAlgDetITS::AliAlgDetITS(const char* title) { // default c-tor - SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kITS),title); + SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kITS), title); SetDetID(AliAlgSteer::kITS); SetUseErrorParam(); SetITSSelPatternColl(); @@ -56,97 +60,101 @@ void AliAlgDetITS::DefineVolumes() // define ITS volumes // const int kNSPDSect = 10; - AliAlgVol *volITS=0,*hstave=0,*ladd=0; - AliAlgSensITS *sens=0; + AliAlgVol *volITS = 0, *hstave = 0, *ladd = 0; + AliAlgSensITS* sens = 0; // int labDet = GetDetLabel(); - AddVolume( volITS = new AliAlgVol("ITS",labDet) ); + AddVolume(volITS = new AliAlgVol("ITS", labDet)); // // SPD - AliAlgVol *sect[kNSPDSect] = {0}; - for (int isc=0;iscSetParent(volITS); } - for (int ilr=0;ilr<=1;ilr++) { // SPD layers + for (int ilr = 0; ilr <= 1; ilr++) { // SPD layers // - int cntVolID=0,staveCnt=0; - int nst = AliITSgeomTGeo::GetNLadders(ilr+1)/kNSPDSect; // 2 or 4 staves per sector - for (int isc=0;iscSetParent(sect[isc]); - hstave->SetInternalID(iid); - for (int isn=0;isn<2;isn++) { // "ladder" (sensor) - int iids = iid + (1+isn); - AddVolume( sens = - new AliAlgSensITS(Form("ITS/SPD%d/Sector%d/Stave%d/HalfStave%d/Ladder%d", - ilr,isc,ist,ihst,isn+ihst*2), - AliGeomManager::LayerToVolUID(ilr+1,cntVolID++), iids) ); - sens->SetParent(hstave); - } - } + int cntVolID = 0, staveCnt = 0; + int nst = AliITSgeomTGeo::GetNLadders(ilr + 1) / kNSPDSect; // 2 or 4 staves per sector + for (int isc = 0; isc < kNSPDSect; isc++) { // sectors + for (int ist = 0; ist < nst; ist++) { // staves of SPDi + for (int ihst = 0; ihst < 2; ihst++) { // halfstave + int iid = labDet + (1 + ilr) * 10000 + (1 + staveCnt) * 100; + staveCnt++; + AddVolume(hstave = new AliAlgVol(Form("ITS/SPD%d/Sector%d/Stave%d/HalfStave%d", + ilr, isc, ist, ihst), + iid)); + hstave->SetParent(sect[isc]); + hstave->SetInternalID(iid); + for (int isn = 0; isn < 2; isn++) { // "ladder" (sensor) + int iids = iid + (1 + isn); + AddVolume(sens = + new AliAlgSensITS(Form("ITS/SPD%d/Sector%d/Stave%d/HalfStave%d/Ladder%d", + ilr, isc, ist, ihst, isn + ihst * 2), + AliGeomManager::LayerToVolUID(ilr + 1, cntVolID++), iids)); + sens->SetParent(hstave); + } + } } // staves of SPDi - } // sectors - } // SPD layers + } // sectors + } // SPD layers // // SDD - for (int ilr=2;ilr<=3;ilr++) { // layer - int cntVolID=0, staveCnt=0; - for (int ist=0;istSetParent(volITS); - for (int isn=0;isnSetParent(ladd); + for (int isn = 0; isn < AliITSgeomTGeo::GetNDetectors(ilr + 1); isn++) { // sensor + int iids = iid + (1 + isn); + AddVolume(sens = new AliAlgSensITS(Form("ITS/SDD%d/Ladder%d/Sensor%d", ilr, ist, isn), + AliGeomManager::LayerToVolUID(ilr + 1, cntVolID++), iids)); + sens->SetParent(ladd); } } // ladder - } // layer + } // layer // // SSD - for (int ilr=4;ilr<=5;ilr++) { // layer - int cntVolID=0,staveCnt=0; - for (int ist=0;istSetParent(volITS); - for (int isn=0;isnSetParent(ladd); + for (int isn = 0; isn < AliITSgeomTGeo::GetNDetectors(ilr + 1); isn++) { // sensor + int iids = iid + (1 + isn); + AddVolume(sens = new AliAlgSensITS(Form("ITS/SSD%d/Ladder%d/Sensor%d", ilr, ist, isn), + AliGeomManager::LayerToVolUID(ilr + 1, cntVolID++), iids)); + sens->SetParent(ladd); } } // ladder - } // layer + } // layer // // } //____________________________________________ -void AliAlgDetITS::Print(const Option_t *opt) const +void AliAlgDetITS::Print(const Option_t* opt) const { AliAlgDet::Print(opt); printf("Sel.pattern Collisions: %7s | Cosmic: %7s\n", - GetITSPattName(fITSPatt[kColl]),GetITSPattName(fITSPatt[kCosm])); + GetITSPattName(fITSPatt[kColl]), GetITSPattName(fITSPatt[kCosm])); } //____________________________________________ -Bool_t AliAlgDetITS::AcceptTrack(const AliESDtrack* trc,Int_t trtype) const +Bool_t AliAlgDetITS::AcceptTrack(const AliESDtrack* trc, Int_t trtype) const { // test if detector had seed this track - if (!CheckFlags(trc,trtype)) return kFALSE; - if (trc->GetNcls(0)GetNcls(0) < fNPointsSel[trtype]) + return kFALSE; + if (!CheckHitPattern(trc, GetITSSelPattern(trtype))) + return kFALSE; // return kTRUE; } @@ -155,11 +163,12 @@ Bool_t AliAlgDetITS::AcceptTrack(const AliESDtrack* trc,Int_t trtype) const void AliAlgDetITS::SetAddErrorLr(int ilr, double sigY, double sigZ) { // set syst. errors for specific layer - for (int isn=GetNSensors();isn--;) { + for (int isn = GetNSensors(); isn--;) { AliAlgSensITS* sens = (AliAlgSensITS*)GetSensor(isn); int vid = sens->GetVolID(); int lrs = AliGeomManager::VolUIDToLayer(vid); - if ( (lrs-AliGeomManager::kSPD1) == ilr) sens->SetAddError(sigY,sigZ); + if ((lrs - AliGeomManager::kSPD1) == ilr) + sens->SetAddError(sigY, sigZ); } } @@ -167,39 +176,45 @@ void AliAlgDetITS::SetAddErrorLr(int ilr, double sigY, double sigZ) void AliAlgDetITS::SetSkipLr(int ilr) { // exclude sensor of the layer from alignment - for (int isn=GetNSensors();isn--;) { + for (int isn = GetNSensors(); isn--;) { AliAlgSensITS* sens = (AliAlgSensITS*)GetSensor(isn); int vid = sens->GetVolID(); int lrs = AliGeomManager::VolUIDToLayer(vid); - if ( (lrs-AliGeomManager::kSPD1) == ilr) sens->SetSkip(); + if ((lrs - AliGeomManager::kSPD1) == ilr) + sens->SetSkip(); } } //_________________________________________________ -void AliAlgDetITS::SetUseErrorParam(Int_t v) +void AliAlgDetITS::SetUseErrorParam(Int_t v) { // set type of points error parameterization fUseErrorParam = v; } //_________________________________________________ -Bool_t AliAlgDetITS::CheckHitPattern(const AliESDtrack* trc, Int_t sel) +Bool_t AliAlgDetITS::CheckHitPattern(const AliESDtrack* trc, Int_t sel) { // check if track hit pattern is ok switch (sel) { - case kSPDBoth: - if (!trc->HasPointOnITSLayer(0) || !trc->HasPointOnITSLayer(1)) return kFALSE; - break; - case kSPDAny: - if (!trc->HasPointOnITSLayer(0) && !trc->HasPointOnITSLayer(1)) return kFALSE; - break; - case kSPD0: - if (!trc->HasPointOnITSLayer(0)) return kFALSE; - break; - case kSPD1: - if (!trc->HasPointOnITSLayer(1)) return kFALSE; - break; - default: break; + case kSPDBoth: + if (!trc->HasPointOnITSLayer(0) || !trc->HasPointOnITSLayer(1)) + return kFALSE; + break; + case kSPDAny: + if (!trc->HasPointOnITSLayer(0) && !trc->HasPointOnITSLayer(1)) + return kFALSE; + break; + case kSPD0: + if (!trc->HasPointOnITSLayer(0)) + return kFALSE; + break; + case kSPD1: + if (!trc->HasPointOnITSLayer(1)) + return kFALSE; + break; + default: + break; } return kTRUE; } @@ -211,31 +226,31 @@ void AliAlgDetITS::UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTra // the track must be in the detector tracking frame const AliAlgSens* sens = pnt->GetSensor(); int vid = sens->GetVolID(); - int lr = AliGeomManager::VolUIDToLayer(vid)-1; + int lr = AliGeomManager::VolUIDToLayer(vid) - 1; double angPol = ATan(t->GetTgl()); - double angAz = ASin(t->GetSnp()); - double errY,errZ; - GetErrorParamAngle(lr,angPol,angAz,errY,errZ); - const double *sysE = sens->GetAddError(); // additional syst error + double angAz = ASin(t->GetSnp()); + double errY, errZ; + GetErrorParamAngle(lr, angPol, angAz, errY, errZ); + const double* sysE = sens->GetAddError(); // additional syst error // - pnt->SetYZErrTracking(errY*errY+sysE[0]*sysE[0],0,errZ*errZ+sysE[1]*sysE[1]); + pnt->SetYZErrTracking(errY * errY + sysE[0] * sysE[0], 0, errZ * errZ + sysE[1] * sysE[1]); pnt->Init(); // } //-------------------------------------------------------------------------- -void AliAlgDetITS::GetErrorParamAngle(int layer, double anglePol, double angleAzi, double &erry, double &errz) const +void AliAlgDetITS::GetErrorParamAngle(int layer, double anglePol, double angleAzi, double& erry, double& errz) const { // Modified version of AliITSClusterParam::GetErrorParamAngle // Calculate cluster position error (parametrization extracted from rp-hit // residuals, as a function of angle between track and det module plane. // Origin: M.Lunardon, S.Moretto) // - const int kNcfSPDResX = 21; - const float kCfSPDResX[kNcfSPDResX] = {+1.1201e+01,+2.0903e+00,-2.2909e-01,-2.6413e-01,+4.2135e-01,-3.7190e-01, - +4.2339e-01,+1.8679e-01,-5.1249e-01,+1.8421e-01,+4.8849e-02,-4.3127e-01, - -1.1148e-01,+3.1984e-03,-2.5743e-01,-6.6408e-02,+3.0756e-01,+2.6809e-01, - -5.0339e-03,-1.4964e-01,-1.1001e-01}; - const float kSPDazMax=56.000000; + const int kNcfSPDResX = 21; + const float kCfSPDResX[kNcfSPDResX] = {+1.1201e+01, +2.0903e+00, -2.2909e-01, -2.6413e-01, +4.2135e-01, -3.7190e-01, + +4.2339e-01, +1.8679e-01, -5.1249e-01, +1.8421e-01, +4.8849e-02, -4.3127e-01, + -1.1148e-01, +3.1984e-03, -2.5743e-01, -6.6408e-02, +3.0756e-01, +2.6809e-01, + -5.0339e-03, -1.4964e-01, -1.1001e-01}; + const float kSPDazMax = 56.000000; // /* const int kNcfSPDMeanX = 16; @@ -244,62 +259,80 @@ void AliAlgDetITS::GetErrorParamAngle(int layer, double anglePol, double angleAz -1.9451e-01,-4.9347e-02,-1.9186e-01,-1.9195e-01}; */ // - const int kNcfSPDResZ = 5; - const float kCfSPDResZ[kNcfSPDResZ] = {+9.2384e+01,+3.4352e-01,-2.7317e+01,-1.4642e-01,+2.0868e+00}; - const float kSPDpolMin=34.358002, kSPDpolMax=145.000000; + const int kNcfSPDResZ = 5; + const float kCfSPDResZ[kNcfSPDResZ] = {+9.2384e+01, +3.4352e-01, -2.7317e+01, -1.4642e-01, +2.0868e+00}; + const float kSPDpolMin = 34.358002, kSPDpolMax = 145.000000; + // + const Double_t kMaxSigmaSDDx = 100.; + const Double_t kMaxSigmaSDDz = 400.; + const Double_t kMaxSigmaSSDx = 100.; + const Double_t kMaxSigmaSSDz = 1000.; // - const Double_t kMaxSigmaSDDx=100.; - const Double_t kMaxSigmaSDDz=400.; - const Double_t kMaxSigmaSSDx=100.; - const Double_t kMaxSigmaSSDz=1000.; - // - const Double_t kParamSDDx[2]={30.93,0.059}; - const Double_t kParamSDDz[2]={33.09,0.011}; - const Double_t kParamSSDx[2]={18.64,-0.0046}; - const Double_t kParamSSDz[2]={784.4,-0.828}; - Double_t sigmax=1000.0,sigmaz=1000.0; + const Double_t kParamSDDx[2] = {30.93, 0.059}; + const Double_t kParamSDDz[2] = {33.09, 0.011}; + const Double_t kParamSSDx[2] = {18.64, -0.0046}; + const Double_t kParamSSDz[2] = {784.4, -0.828}; + Double_t sigmax = 1000.0, sigmaz = 1000.0; //Double_t biasx = 0.0; angleAzi = Abs(angleAzi); anglePol = Abs(anglePol); // - if(angleAzi>0.5*Pi()) angleAzi = Pi()-angleAzi; - if(anglePol>0.5*Pi()) anglePol = Pi()-anglePol; - Double_t angleAziDeg = angleAzi*RadToDeg(); - Double_t anglePolDeg = anglePol*RadToDeg(); + if (angleAzi > 0.5 * Pi()) + angleAzi = Pi() - angleAzi; + if (anglePol > 0.5 * Pi()) + anglePol = Pi() - anglePol; + Double_t angleAziDeg = angleAzi * RadToDeg(); + Double_t anglePolDeg = anglePol * RadToDeg(); // - if(layer==0 || layer==1) { // SPD + if (layer == 0 || layer == 1) { // SPD // - float phiInt = angleAziDeg/kSPDazMax; // mapped to -1:1 - if (phiInt>1) phiInt = 1; else if (phiInt<-1) phiInt = -1; - float phiAbsInt = (TMath::Abs(angleAziDeg+angleAziDeg) - kSPDazMax)/kSPDazMax; // mapped to -1:1 - if (phiAbsInt>1) phiAbsInt = 1; else if (phiAbsInt<-1) phiAbsInt = -1; - anglePolDeg += 90; // the parameterization was provided in polar angle (90 deg - normal to sensor) - float polInt = (anglePolDeg+anglePolDeg - (kSPDpolMax+kSPDpolMin))/(kSPDpolMax-kSPDpolMin); // mapped to -1:1 - if (polInt>1) polInt = 1; else if (polInt<-1) polInt = -1; + float phiInt = angleAziDeg / kSPDazMax; // mapped to -1:1 + if (phiInt > 1) + phiInt = 1; + else if (phiInt < -1) + phiInt = -1; + float phiAbsInt = (TMath::Abs(angleAziDeg + angleAziDeg) - kSPDazMax) / kSPDazMax; // mapped to -1:1 + if (phiAbsInt > 1) + phiAbsInt = 1; + else if (phiAbsInt < -1) + phiAbsInt = -1; + anglePolDeg += 90; // the parameterization was provided in polar angle (90 deg - normal to sensor) + float polInt = (anglePolDeg + anglePolDeg - (kSPDpolMax + kSPDpolMin)) / (kSPDpolMax - kSPDpolMin); // mapped to -1:1 + if (polInt > 1) + polInt = 1; + else if (polInt < -1) + polInt = -1; // - sigmax = AliCheb3DCalc::ChebEval1D(phiAbsInt, kCfSPDResX , kNcfSPDResX); + sigmax = AliCheb3DCalc::ChebEval1D(phiAbsInt, kCfSPDResX, kNcfSPDResX); //biasx = AliCheb3DCalc::ChebEval1D(phiInt , kCfSPDMeanX, kNcfSPDMeanX); - sigmaz = AliCheb3DCalc::ChebEval1D(polInt , kCfSPDResZ , kNcfSPDResZ); + sigmaz = AliCheb3DCalc::ChebEval1D(polInt, kCfSPDResZ, kNcfSPDResZ); // // for the moment for the SPD only, need to decide where to put it //biasx *= 1e-4; - - } else if(layer==2 || layer==3) { // SDD - sigmax = angleAziDeg*kParamSDDx[1]+kParamSDDx[0]; - sigmaz = kParamSDDz[0]+kParamSDDz[1]*anglePolDeg; - if(sigmax > kMaxSigmaSDDx) sigmax = kMaxSigmaSDDx; - if(sigmaz > kMaxSigmaSDDz) sigmax = kMaxSigmaSDDz; - - } else if(layer==4 || layer==5) { // SSD + } else if (layer == 2 || layer == 3) { // SDD - sigmax = angleAziDeg*kParamSSDx[1]+kParamSSDx[0]; - sigmaz = kParamSSDz[0]+kParamSSDz[1]*anglePolDeg; - if(sigmax > kMaxSigmaSSDx) sigmax = kMaxSigmaSSDx; - if(sigmaz > kMaxSigmaSSDz) sigmax = kMaxSigmaSSDz; + sigmax = angleAziDeg * kParamSDDx[1] + kParamSDDx[0]; + sigmaz = kParamSDDz[0] + kParamSDDz[1] * anglePolDeg; + if (sigmax > kMaxSigmaSDDx) + sigmax = kMaxSigmaSDDx; + if (sigmaz > kMaxSigmaSDDz) + sigmax = kMaxSigmaSDDz; + + } else if (layer == 4 || layer == 5) { // SSD + + sigmax = angleAziDeg * kParamSSDx[1] + kParamSSDx[0]; + sigmaz = kParamSSDz[0] + kParamSSDz[1] * anglePolDeg; + if (sigmax > kMaxSigmaSSDx) + sigmax = kMaxSigmaSSDx; + if (sigmaz > kMaxSigmaSSDz) + sigmax = kMaxSigmaSSDz; } // convert from micron to cm - erry = 1.e-4*sigmax; - errz = 1.e-4*sigmaz; + erry = 1.e-4 * sigmax; + errz = 1.e-4 * sigmaz; } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgDetTOF.cxx b/Detectors/Align/src/AliAlgDetTOF.cxx index 89a541d804fc7..7e025cdb0dd4f 100644 --- a/Detectors/Align/src/AliAlgDetTOF.cxx +++ b/Detectors/Align/src/AliAlgDetTOF.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgDetTOF.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief Wrapper for TOF detector #include "AliAlgDetTOF.h" #include "AliAlgVol.h" @@ -22,13 +22,18 @@ #include "AliESDtrack.h" #include -ClassImp(AliAlgDetTOF); +ClassImp(o2::align::AliAlgDetTOF); + +namespace o2 +{ +namespace align +{ //____________________________________________ AliAlgDetTOF::AliAlgDetTOF(const char* title) { // default c-tor - SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kTOF),title); + SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kTOF), title); SetDetID(AliAlgSteer::kTOF); } @@ -43,35 +48,39 @@ void AliAlgDetTOF::DefineVolumes() { // define TOF volumes // - const int kNSect = 18, kNStrips = AliTOFGeometry::NStripA()+2*AliTOFGeometry::NStripB()+2*AliTOFGeometry::NStripC(); + const int kNSect = 18, kNStrips = AliTOFGeometry::NStripA() + 2 * AliTOFGeometry::NStripB() + 2 * AliTOFGeometry::NStripC(); int labDet = GetDetLabel(); - AliAlgSensTOF *strip=0; + AliAlgSensTOF* strip = 0; // // AddVolume( volTOF = new AliAlgVol("TOF") ); // no main volume, why? - AliAlgVol *sect[kNSect] = {0}; + AliAlgVol* sect[kNSect] = {0}; // - for (int isc=0;iscGetAlignableEntry(symname)) continue; - AddVolume( strip=new AliAlgSensTOF(symname,vid,iid,isc) ); + const char* symname = Form("TOF/sm%02d/strip%02d", isc, istr); + if (!gGeoManager->GetAlignableEntry(symname)) + continue; + AddVolume(strip = new AliAlgSensTOF(symname, vid, iid, isc)); strip->SetParent(sect[isc]); } // strip - } // layer + } // layer // } //____________________________________________ -Bool_t AliAlgDetTOF::AcceptTrack(const AliESDtrack* trc,Int_t trtype) const +Bool_t AliAlgDetTOF::AcceptTrack(const AliESDtrack* trc, Int_t trtype) const { // test if detector had seed this track - return CheckFlags(trc,trtype); + return CheckFlags(trc, trtype); } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgDetTPC.cxx b/Detectors/Align/src/AliAlgDetTPC.cxx index c090d12b22f2f..a069fd5a9a266 100644 --- a/Detectors/Align/src/AliAlgDetTPC.cxx +++ b/Detectors/Align/src/AliAlgDetTPC.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgDetTPC.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief TPC detector wrapper #include "AliAlgDetTPC.h" #include "AliAlgVol.h" @@ -22,13 +22,18 @@ #include "AliLog.h" #include -ClassImp(AliAlgDetTPC); +ClassImp(o2::align::AliAlgDetTPC); + +namespace o2 +{ +namespace align +{ //____________________________________________ AliAlgDetTPC::AliAlgDetTPC(const char* title) { // default c-tor - SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kTPC),title); + SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kTPC), title); SetDetID(AliAlgSteer::kTPC); } @@ -43,41 +48,46 @@ void AliAlgDetTPC::DefineVolumes() { // define TPC volumes // - const int kNSect = 18, kAC=2, kIOROC=2; - const char* kSide[kAC] = {"A","C"}; - const char* kROC[kIOROC] = {"Inner","Outer"}; + const int kNSect = 18, kAC = 2, kIOROC = 2; + const char* kSide[kAC] = {"A", "C"}; + const char* kROC[kIOROC] = {"Inner", "Outer"}; // AliAlgSensTPC *chamb=0; // int labDet = GetDetLabel(); - AliAlgVol* volTPC = new AliAlgVol("ALIC_1/TPC_M_1",labDet); - AddVolume( volTPC ); + AliAlgVol* volTPC = new AliAlgVol("ALIC_1/TPC_M_1", labDet); + AddVolume(volTPC); // - - for (int roc=0;rocGetAlignableEntry(symname)) { - AliErrorF("Did not find alignable %s",symname); - continue; - } - Int_t iid = side*kNSect+isc; - UShort_t vid = AliGeomManager::LayerToVolUID(AliGeomManager::kTPC1+roc,iid); - iid = labDet + (1+side)*10000 + (1+isc)*100+(1+roc); - AliAlgSensTPC* sens = new AliAlgSensTPC(symname,vid,iid,isc); - sens->SetParent(volTPC); - AddVolume(sens); + + for (int roc = 0; roc < kIOROC; roc++) { // inner/outer + for (int side = 0; side < kAC; side++) { // A/C + for (int isc = 0; isc < kNSect; isc++) { // sector ID + const char* symname = Form("TPC/Endcap%s/Sector%d/%sChamber", kSide[side], isc + 1, kROC[roc]); + if (!gGeoManager->GetAlignableEntry(symname)) { + AliErrorF("Did not find alignable %s", symname); + continue; + } + Int_t iid = side * kNSect + isc; + UShort_t vid = AliGeomManager::LayerToVolUID(AliGeomManager::kTPC1 + roc, iid); + iid = labDet + (1 + side) * 10000 + (1 + isc) * 100 + (1 + roc); + AliAlgSensTPC* sens = new AliAlgSensTPC(symname, vid, iid, isc); + sens->SetParent(volTPC); + AddVolume(sens); } // sector ID - } // A/C - } // inner/outer + } // A/C + } // inner/outer // } //____________________________________________ -Bool_t AliAlgDetTPC::AcceptTrack(const AliESDtrack* trc, Int_t trtype) const +Bool_t AliAlgDetTPC::AcceptTrack(const AliESDtrack* trc, Int_t trtype) const { // test if detector had seed this track - if (!CheckFlags(trc,trtype)) return kFALSE; - if (trc->GetNcls(1)GetNcls(1) < fNPointsSel[trtype]) + return kFALSE; return kTRUE; } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgDetTRD.cxx b/Detectors/Align/src/AliAlgDetTRD.cxx index 1ae51cc1e8cb1..80c661dc12435 100644 --- a/Detectors/Align/src/AliAlgDetTRD.cxx +++ b/Detectors/Align/src/AliAlgDetTRD.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgDetTRD.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief TRD detector wrapper #include "AliAlgDetTRD.h" #include "AliAlgVol.h" @@ -25,18 +25,21 @@ using namespace TMath; -ClassImp(AliAlgDetTRD); +ClassImp(o2::align::AliAlgDetTRD); + +namespace o2 +{ +namespace align +{ -const char* AliAlgDetTRD::fgkCalibDOFName[AliAlgDetTRD::kNCalibParams]={"DZdTglNRC","DVDriftT"}; +const char* AliAlgDetTRD::fgkCalibDOFName[AliAlgDetTRD::kNCalibParams] = {"DZdTglNRC", "DVDriftT"}; //____________________________________________ AliAlgDetTRD::AliAlgDetTRD(const char* title) - : AliAlgDet() - ,fNonRCCorrDzDtgl(0) - ,fCorrDVT(0) + : AliAlgDet(), fNonRCCorrDzDtgl(0), fCorrDVT(0) { // default c-tor - SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kTRD),title); + SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kTRD), title); SetDetID(AliAlgSteer::kTRD); fExtraErrRC[0] = fExtraErrRC[1] = 0; // @@ -46,7 +49,6 @@ AliAlgDetTRD::AliAlgDetTRD(const char* title) fNCalibDOF = kNCalibParams; } - //____________________________________________ AliAlgDetTRD::~AliAlgDetTRD() { @@ -59,76 +61,83 @@ void AliAlgDetTRD::DefineVolumes() // define TRD volumes // const int kNSect = 18, kNStacks = 5, kNLayers = 6; - AliAlgSensTRD *chamb=0; + AliAlgSensTRD* chamb = 0; // int labDet = GetDetLabel(); // AddVolume( volTRD = new AliAlgVol("TRD") ); // no main volume, why? - AliAlgVol *sect[kNSect] = {0}; + AliAlgVol* sect[kNSect] = {0}; // - for (int ilr=0;ilrGetAlignableEntry(symname)) continue; - UShort_t vid = AliGeomManager::LayerToVolUID(AliGeomManager::kTRD1+ilr,ich); - AddVolume( chamb = new AliAlgSensTRD(symname,vid,iid/*lid*/,isector) ); - iid = labDet + (1+isector)*100; - if (!sect[isector]) sect[isector] = new AliAlgVol(Form("TRD/sm%02d",isector),iid); + int iid = labDet + (1 + ilr) * 10000 + (1 + isector) * 100 + (1 + istack); + const char* symname = Form("TRD/sm%02d/st%d/pl%d", isector, istack, ilr); + if (!gGeoManager->GetAlignableEntry(symname)) + continue; + UShort_t vid = AliGeomManager::LayerToVolUID(AliGeomManager::kTRD1 + ilr, ich); + AddVolume(chamb = new AliAlgSensTRD(symname, vid, iid /*lid*/, isector)); + iid = labDet + (1 + isector) * 100; + if (!sect[isector]) + sect[isector] = new AliAlgVol(Form("TRD/sm%02d", isector), iid); chamb->SetParent(sect[isector]); } // chamber - } // layer + } // layer // - for (int isc=0;iscGetTRDntracklets()GetTRDntracklets() < fNPointsSel[trtype]) + return kFALSE; return kTRUE; } //__________________________________________ //____________________________________________ -void AliAlgDetTRD::Print(const Option_t *opt) const +void AliAlgDetTRD::Print(const Option_t* opt) const { // print info AliAlgDet::Print(opt); - printf("Extra error for RC tracklets: Y:%e Z:%e\n",fExtraErrRC[0],fExtraErrRC[1]); + printf("Extra error for RC tracklets: Y:%e Z:%e\n", fExtraErrRC[0], fExtraErrRC[1]); } - + const char* AliAlgDetTRD::GetCalibDOFName(int i) const { // return calibration DOF name - return i #include - using namespace TMath; -using namespace AliAlgAux; +using namespace o2::align::AliAlgAux; + +namespace o2 +{ +namespace align +{ //_________________________________________________________ AliAlgMPRecord::AliAlgMPRecord() - :fTrackID(0) - ,fTimeStamp(0) - ,fNResid(0) - ,fNVarLoc(0) - ,fNVarGlo(0) - ,fNDLocTot(0) - ,fNDGloTot(0) - ,fNMeas(0) - ,fChi2Ini(0) - ,fQ2Pt(0) - ,fTgl(0) - ,fNDLoc(0) - ,fNDGlo(0) - ,fVolID(0) - ,fResid(0) - ,fResErr(0) - ,fIDLoc(0) - ,fIDGlo(0) - ,fDLoc(0) - ,fDGlo(0) - // - ,fNResidBook(0) - ,fNDLocTotBook(0) - ,fNDGloTotBook(0) + : fTrackID(0), fTimeStamp(0), fNResid(0), fNVarLoc(0), fNVarGlo(0), fNDLocTot(0), fNDGloTot(0), fNMeas(0), fChi2Ini(0), fQ2Pt(0), fTgl(0), fNDLoc(0), fNDGlo(0), fVolID(0), fResid(0), fResErr(0), fIDLoc(0), fIDGlo(0), fDLoc(0), fDGlo(0) + // + , + fNResidBook(0), + fNDLocTotBook(0), + fNDGloTotBook(0) { // def c-tor - } //_________________________________________________________ @@ -74,7 +59,8 @@ AliAlgMPRecord::~AliAlgMPRecord() void AliAlgMPRecord::DummyRecord(Float_t res, Float_t err, Float_t dGlo, Int_t labGlo) { // create dummy residuals record - if (!fNDGlo) Resize(1,1,1); + if (!fNDGlo) + Resize(1, 1, 1); fChi2Ini = 0; fNMeas = 1; fNResid = 1; @@ -96,7 +82,7 @@ void AliAlgMPRecord::DummyRecord(Float_t res, Float_t err, Float_t dGlo, Int_t l } //_________________________________________________________ -Bool_t AliAlgMPRecord::FillTrack(const AliAlgTrack* trc, const Int_t *id2Lab) +Bool_t AliAlgMPRecord::FillTrack(const AliAlgTrack* trc, const Int_t* id2Lab) { // fill track info, optionally substitutind glopar par ID by label // @@ -104,112 +90,116 @@ Bool_t AliAlgMPRecord::FillTrack(const AliAlgTrack* trc, const Int_t *id2Lab) AliError("Track derivatives are not yet evaluated"); return kFALSE; } - fNVarLoc = trc->GetNLocPar(); // number of local degrees of freedom in the track + fNVarLoc = trc->GetNLocPar(); // number of local degrees of freedom in the track fNResid = 0; fNDLocTot = 0; fNDGloTot = 0; fChi2Ini = trc->GetChi2Ini(); fQ2Pt = trc->GetSigned1Pt(); - fTgl = trc->GetTgl(); + fTgl = trc->GetTgl(); fNMeas = 0; SetCosmic(trc->IsCosmic()); // 1) check sizes for buffers, expand if needed int np = trc->GetNPoints(); - int nres = 0; + int nres = 0; int nlocd = 0; int nglod = 0; - for (int ip=np;ip--;) { + for (int ip = np; ip--;) { AliAlgPoint* pnt = trc->GetPoint(ip); - int ngl = pnt->GetNGloDOFs(); // number of DOF's this point depends on + int ngl = pnt->GetNGloDOFs(); // number of DOF's this point depends on if (pnt->ContainsMeasurement()) { - nres += 2; // every point has 2 residuals - nlocd += fNVarLoc+fNVarLoc; // each residual has max fNVarLoc local derivatives - nglod += ngl + ngl; // number of global derivatives + nres += 2; // every point has 2 residuals + nlocd += fNVarLoc + fNVarLoc; // each residual has max fNVarLoc local derivatives + nglod += ngl + ngl; // number of global derivatives fNMeas++; } if (pnt->ContainsMaterial()) { int nmatpar = pnt->GetNMatPar(); - nres += nmatpar; // each point with materials has nmatpar fake residuals - nlocd += nmatpar; // and nmatpar non-0 local derivatives (orthogonal) + nres += nmatpar; // each point with materials has nmatpar fake residuals + nlocd += nmatpar; // and nmatpar non-0 local derivatives (orthogonal) } } // - Resize(nres,nlocd,nglod); - int nParETP = trc->GetNLocExtPar(); // numnber of local parameters for reference track param + Resize(nres, nlocd, nglod); + int nParETP = trc->GetNLocExtPar(); // numnber of local parameters for reference track param // const int* gloParID = trc->GetGloParID(); // IDs of global DOFs this track depends on - for (int ip=0;ipGetPoint(ip); if (pnt->ContainsMeasurement()) { int gloOffs = pnt->GetDGloOffs(); // 1st entry of global derivatives for this point - int nDGlo = pnt->GetNGloDOFs(); // number of global derivatives (number of DOFs it depends on) - if (!pnt->IsStatOK()) pnt->IncrementStat(); + int nDGlo = pnt->GetNGloDOFs(); // number of global derivatives (number of DOFs it depends on) + if (!pnt->IsStatOK()) + pnt->IncrementStat(); // - for (int idim=0;idim<2;idim++) { // 2 dimensional orthogonal measurement - fNDGlo[fNResid] = 0; - fVolID[fNResid] = pnt->GetSensor()->GetVolID()+1; - // - // measured residual/error - fResid[ fNResid] = trc->GetResidual(idim,ip); - fResErr[fNResid] = Sqrt(pnt->GetErrDiag(idim)); - // - // derivatives over local params - const double* deriv = trc->GetDResDLoc(idim,ip); // array of Dresidual/Dparams_loc - int nnon0 = 0; - for (int j=0;jGetMinLocVarID(); // point may depend on material variables starting from this one - int lp1 = pnt->GetMaxLocVarID(); // and up to this one (exclusive) - for (int j=lp0;jGetDResDGlo(idim, gloOffs); - const int* gloIDP = gloParID + gloOffs; - for (int j=0;jGetSensor()->GetVolID() + 1; + // + // measured residual/error + fResid[fNResid] = trc->GetResidual(idim, ip); + fResErr[fNResid] = Sqrt(pnt->GetErrDiag(idim)); + // + // derivatives over local params + const double* deriv = trc->GetDResDLoc(idim, ip); // array of Dresidual/Dparams_loc + int nnon0 = 0; + for (int j = 0; j < nParETP; j++) { // derivatives over reference track parameters + if (IsZeroAbs(deriv[j])) + continue; + nnon0++; + fDLoc[fNDLocTot] = deriv[j]; // store non-0 derivative + fIDLoc[fNDLocTot] = j; // and variable id + fNDLocTot++; + } + int lp0 = pnt->GetMinLocVarID(); // point may depend on material variables starting from this one + int lp1 = pnt->GetMaxLocVarID(); // and up to this one (exclusive) + for (int j = lp0; j < lp1; j++) { // derivatives over material variables + if (IsZeroAbs(deriv[j])) + continue; + nnon0++; + fDLoc[fNDLocTot] = deriv[j]; // store non-0 derivative + fIDLoc[fNDLocTot] = j; // and variable id + fNDLocTot++; + } + // + fNDLoc[fNResid] = nnon0; // local derivatives done, store their number for this residual + // + // derivatives over global params + nnon0 = 0; + deriv = trc->GetDResDGlo(idim, gloOffs); + const int* gloIDP = gloParID + gloOffs; + for (int j = 0; j < nDGlo; j++) { + if (IsZeroAbs(deriv[j])) + continue; + nnon0++; + fDGlo[fNDGloTot] = deriv[j]; // value of derivative + fIDGlo[fNDGloTot] = id2Lab ? id2Lab[gloIDP[j]] : gloIDP[j] + 1; // global DOF ID + fNDGloTot++; + } + fNDGlo[fNResid] = nnon0; + // + fNResid++; } } if (pnt->ContainsMaterial()) { // material point can add 4 or 5 otrhogonal pseudo-measurements - int nmatpar = pnt->GetNMatPar(); // residuals (correction expectation value) + int nmatpar = pnt->GetNMatPar(); // residuals (correction expectation value) // const float* expMatCorr = pnt->GetMatCorrExp(); // expected corrections (diagonalized) - const float* expMatCov = pnt->GetMatCorrCov(); // their diagonalized error matrix - int offs = pnt->GetMaxLocVarID() - nmatpar; // start of material variables + const float* expMatCov = pnt->GetMatCorrCov(); // their diagonalized error matrix + int offs = pnt->GetMaxLocVarID() - nmatpar; // start of material variables // here all derivatives are 1 = dx/dx - for (int j=0;jfNResidBook) { + if (nresid > fNResidBook) { delete[] fNDLoc; delete[] fNDGlo; delete[] fVolID; @@ -231,38 +221,38 @@ void AliAlgMPRecord::Resize(Int_t nresid, Int_t nloc, Int_t nglo) fNDLoc = new Short_t[nresid]; fNDGlo = new Int_t[nresid]; fVolID = new Int_t[nresid]; - fResid = new Float_t[nresid]; - fResErr = new Float_t[nresid]; + fResid = new Float_t[nresid]; + fResErr = new Float_t[nresid]; fNResidBook = nresid; - memset(fNDLoc,0,nresid*sizeof(Short_t)); - memset(fNDGlo,0,nresid*sizeof(Int_t)); - memset(fVolID,0,nresid*sizeof(Int_t)); - memset(fResid,0,nresid*sizeof(Float_t)); - memset(fResErr,0,nresid*sizeof(Float_t)); + memset(fNDLoc, 0, nresid * sizeof(Short_t)); + memset(fNDGlo, 0, nresid * sizeof(Int_t)); + memset(fVolID, 0, nresid * sizeof(Int_t)); + memset(fResid, 0, nresid * sizeof(Float_t)); + memset(fResErr, 0, nresid * sizeof(Float_t)); } - if (nloc>fNDLocTotBook) { + if (nloc > fNDLocTotBook) { delete[] fIDLoc; delete[] fDLoc; fIDLoc = new Short_t[nloc]; - fDLoc = new Float_t[nloc]; + fDLoc = new Float_t[nloc]; fNDLocTotBook = nloc; - memset(fIDLoc,0,nloc*sizeof(Short_t)); - memset(fDLoc,0,nloc*sizeof(Float_t)); + memset(fIDLoc, 0, nloc * sizeof(Short_t)); + memset(fDLoc, 0, nloc * sizeof(Float_t)); } - if (nglo>fNDGloTotBook) { + if (nglo > fNDGloTotBook) { delete[] fIDGlo; delete[] fDGlo; fIDGlo = new Int_t[nglo]; - fDGlo = new Float_t[nglo]; + fDGlo = new Float_t[nglo]; fNDGloTotBook = nglo; - memset(fIDGlo,0,nglo*sizeof(Int_t)); - memset(fDGlo,0,nglo*sizeof(Float_t)); + memset(fIDGlo, 0, nglo * sizeof(Int_t)); + memset(fDGlo, 0, nglo * sizeof(Float_t)); } // } //____________________________________________ -void AliAlgMPRecord::Clear(const Option_t *) +void AliAlgMPRecord::Clear(const Option_t*) { // reset record TObject::Clear(); @@ -275,32 +265,36 @@ void AliAlgMPRecord::Clear(const Option_t *) } //____________________________________________ -void AliAlgMPRecord::Print(const Option_t *) const +void AliAlgMPRecord::Print(const Option_t*) const { // print info // printf("Track %d Event TimeStamp:%d Run:%d\n", - fTrackID,fTimeStamp,GetRun()); - printf("Nmeas:%3d Q/pt:%+.2e Tgl:%+.2e Chi2Ini:%.1f\n",fNMeas,fQ2Pt,fTgl,fChi2Ini); + fTrackID, fTimeStamp, GetRun()); + printf("Nmeas:%3d Q/pt:%+.2e Tgl:%+.2e Chi2Ini:%.1f\n", fNMeas, fQ2Pt, fTgl, fChi2Ini); printf("NRes: %3d NLoc: %3d NGlo:%3d | Stored: Loc:%3d Glo:%5d\n", - fNResid,fNVarLoc,fNVarGlo,fNDLocTot,fNDGloTot); + fNResid, fNVarLoc, fNVarGlo, fNDLocTot, fNDGloTot); // - int curLoc=0,curGlo=0; - const int kNColLoc=5; - for (int ir=0;irfIDGlo[jd]%100) {printf("\n");/* eolOK = kTRUE;*/} - printf("[%5d] %+.2e ",fIDGlo[jd],fDGlo[jd]); - // if (((id+1)%kNColGlo)==0) + if (prvID > fIDGlo[jd] % 100) { + printf("\n"); /* eolOK = kTRUE;*/ + } + printf("[%5d] %+.2e ", fIDGlo[jd], fDGlo[jd]); + // if (((id+1)%kNColGlo)==0) // else eolOK = kFALSE; - prvID=fIDGlo[jd]%100; + prvID = fIDGlo[jd] % 100; } // if (!eolOK) printf("\n"); printf("\n"); @@ -323,3 +319,6 @@ void AliAlgMPRecord::Print(const Option_t *) const // } } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgPoint.cxx b/Detectors/Align/src/AliAlgPoint.cxx index c469c209146a5..73631769ff4df 100644 --- a/Detectors/Align/src/AliAlgPoint.cxx +++ b/Detectors/Align/src/AliAlgPoint.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgPoint.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief Meausered point in the sensor. #include #include @@ -20,36 +20,29 @@ #include "AliAlgAux.h" #include "AliExternalTrackParam.h" -using namespace AliAlgAux; +using namespace o2::align::AliAlgAux; using namespace TMath; +namespace o2 +{ +namespace align +{ + //_____________________________________ AliAlgPoint::AliAlgPoint() - :fMinLocVarID(0) - ,fMaxLocVarID(0) - ,fDetID(-1) - ,fSID(-1) - ,fAlphaSens(0) - ,fXSens(0) - ,fCosDiagErr(0) - ,fSinDiagErr(0) - ,fX2X0(0) - ,fXTimesRho(0) - ,fNGloDOFs(0) - ,fDGloOffs(0) - ,fSensor(0) + : fMinLocVarID(0), fMaxLocVarID(0), fDetID(-1), fSID(-1), fAlphaSens(0), fXSens(0), fCosDiagErr(0), fSinDiagErr(0), fX2X0(0), fXTimesRho(0), fNGloDOFs(0), fDGloOffs(0), fSensor(0) { // def c-tor - for (int i=3;i--;) { + for (int i = 3; i--;) { fXYZTracking[i] = 0; fErrYZTracking[i] = 0; } - memset(fMatCorrExp,0,5*sizeof(float)); - memset(fMatCorrCov,0,5*sizeof(float)); - memset(fMatDiag,0,5*5*sizeof(float)); + memset(fMatCorrExp, 0, 5 * sizeof(float)); + memset(fMatCorrCov, 0, 5 * sizeof(float)); + memset(fMatDiag, 0, 5 * 5 * sizeof(float)); // - memset(fTrParamWSA,0,5*sizeof(double)); - memset(fTrParamWSB,0,5*sizeof(double)); + memset(fTrParamWSA, 0, 5 * sizeof(double)); + memset(fTrParamWSB, 0, 5 * sizeof(double)); // } @@ -58,24 +51,25 @@ void AliAlgPoint::Init() { // compute aux info const double kCorrToler = 1e-6; - const double kDiagToler = 1e-14; - // + const double kDiagToler = 1e-14; + // // compute parameters of tranformation to diagonal error matrix - if (!IsZeroPos(fErrYZTracking[0]+fErrYZTracking[2])) { + if (!IsZeroPos(fErrYZTracking[0] + fErrYZTracking[2])) { // // is there a correlation? - if (SmallerAbs(fErrYZTracking[1]*fErrYZTracking[1]/(fErrYZTracking[0]*fErrYZTracking[2]),kCorrToler)) { + if (SmallerAbs(fErrYZTracking[1] * fErrYZTracking[1] / (fErrYZTracking[0] * fErrYZTracking[2]), kCorrToler)) { fCosDiagErr = 1.; fSinDiagErr = 0.; fErrDiag[0] = fErrYZTracking[0]; fErrDiag[1] = fErrYZTracking[2]; - } - else { - double dfd = 0.5*(fErrYZTracking[2] - fErrYZTracking[0]); + } else { + double dfd = 0.5 * (fErrYZTracking[2] - fErrYZTracking[0]); double phi = 0; // special treatment if errors are equal - if (Abs(dfd)0 ? (Pi()*0.25) : (Pi()*0.75); - else phi = 0.5*ATan2(fErrYZTracking[1],dfd); + if (Abs(dfd) < kDiagToler) + phi = fErrYZTracking[1] > 0 ? (Pi() * 0.25) : (Pi() * 0.75); + else + phi = 0.5 * ATan2(fErrYZTracking[1], dfd); // fCosDiagErr = Cos(phi); fSinDiagErr = Sin(phi); @@ -85,11 +79,11 @@ void AliAlgPoint::Init() // double smd = 0.5*(fErrYZTracking[0] + fErrYZTracking[2]); // fErrDiag[0] = smd + det; // fErrDiag[1] = smd - det; - double xterm = 2*fCosDiagErr*fSinDiagErr*fErrYZTracking[1]; - double cc = fCosDiagErr*fCosDiagErr; - double ss = fSinDiagErr*fSinDiagErr; - fErrDiag[0] = fErrYZTracking[0]*cc + fErrYZTracking[2]*ss - xterm; - fErrDiag[1] = fErrYZTracking[0]*ss + fErrYZTracking[2]*cc + xterm; + double xterm = 2 * fCosDiagErr * fSinDiagErr * fErrYZTracking[1]; + double cc = fCosDiagErr * fCosDiagErr; + double ss = fSinDiagErr * fSinDiagErr; + fErrDiag[0] = fErrYZTracking[0] * cc + fErrYZTracking[2] * ss - xterm; + fErrDiag[1] = fErrYZTracking[0] * ss + fErrYZTracking[2] * cc + xterm; } } // @@ -108,63 +102,70 @@ void AliAlgPoint::Print(Option_t* opt) const // print TString opts = opt; opts.ToLower(); - printf("%cDet%d SID:%4d Alp:%+.3f X:%+9.4f Meas:%s Mat: ",IsInvDir() ? '*':' ', - GetDetID(),GetSID(),GetAlphaSens(),GetXSens(),ContainsMeasurement() ? "ON":"OFF"); - if (!ContainsMaterial()) printf("OFF\n"); - else printf("x2X0: %.4f x*rho: %.4f | pars:[%3d:%3d)\n",GetX2X0(),GetXTimesRho(),GetMinLocVarID(),GetMaxLocVarID()); + printf("%cDet%d SID:%4d Alp:%+.3f X:%+9.4f Meas:%s Mat: ", IsInvDir() ? '*' : ' ', + GetDetID(), GetSID(), GetAlphaSens(), GetXSens(), ContainsMeasurement() ? "ON" : "OFF"); + if (!ContainsMaterial()) + printf("OFF\n"); + else + printf("x2X0: %.4f x*rho: %.4f | pars:[%3d:%3d)\n", GetX2X0(), GetXTimesRho(), GetMinLocVarID(), GetMaxLocVarID()); // if (opts.Contains("meas") && ContainsMeasurement()) { printf(" MeasPnt: Xtr: %+9.4f Ytr: %+8.4f Ztr: %+9.4f | ErrYZ: %+e %+e %+e | %d DOFglo\n", - GetXTracking(),GetYTracking(),GetZTracking(), - fErrYZTracking[0],fErrYZTracking[1],fErrYZTracking[2],GetNGloDOFs()); + GetXTracking(), GetYTracking(), GetZTracking(), + fErrYZTracking[0], fErrYZTracking[1], fErrYZTracking[2], GetNGloDOFs()); printf(" DiagErr: %+e %+e\n", fErrDiag[0], fErrDiag[1]); } // if (opts.Contains("mat") && ContainsMaterial()) { - printf(" MatCorr Exp(ELOSS): %+.4e %+.4e %+.4e %+.4e %+.4e\n", - fMatCorrExp[0], fMatCorrExp[1], fMatCorrExp[2], fMatCorrExp[3], fMatCorrExp[4]); - printf(" MatCorr Cov (diag): %+.4e %+.4e %+.4e %+.4e %+.4e\n", - fMatCorrCov[0], fMatCorrCov[1], fMatCorrCov[2], fMatCorrCov[3], fMatCorrCov[4]); + printf(" MatCorr Exp(ELOSS): %+.4e %+.4e %+.4e %+.4e %+.4e\n", + fMatCorrExp[0], fMatCorrExp[1], fMatCorrExp[2], fMatCorrExp[3], fMatCorrExp[4]); + printf(" MatCorr Cov (diag): %+.4e %+.4e %+.4e %+.4e %+.4e\n", + fMatCorrCov[0], fMatCorrCov[1], fMatCorrCov[2], fMatCorrCov[3], fMatCorrCov[4]); // if (opts.Contains("umat")) { float covUndiag[15]; - memset(covUndiag,0,15*sizeof(float)); + memset(covUndiag, 0, 15 * sizeof(float)); int np = GetNMatPar(); - for (int i=0;iGetXPoint(); - if (!IsInvDir()) { // track propagates from low to large X via this point + if (!IsInvDir()) { // track propagates from low to large X via this point if (!pnt->IsInvDir()) { // via this one also - return x>xp ? -1:1; - } - else return -1; // range points of lower leg 1st - } - else { // this point is from upper cosmic leg: track propagates from large to low X + return x > xp ? -1 : 1; + } else + return -1; // range points of lower leg 1st + } else { // this point is from upper cosmic leg: track propagates from large to low X if (pnt->IsInvDir()) { // this one also - return x>xp ? 1:-1; - } - else return 1; // other point is from lower leg + return x > xp ? 1 : -1; + } else + return 1; // other point is from lower leg } // } @@ -243,11 +246,11 @@ Int_t AliAlgPoint::Compare(const TObject* b) const void AliAlgPoint::GetXYZGlo(Double_t r[3]) const { // position in lab frame - double cs=TMath::Cos(fAlphaSens); - double sn=TMath::Sin(fAlphaSens); - double x=GetXPoint(); - r[0] = x*cs - GetYTracking()*sn; - r[1] = x*sn + GetYTracking()*cs; + double cs = TMath::Cos(fAlphaSens); + double sn = TMath::Sin(fAlphaSens); + double x = GetXPoint(); + r[0] = x * cs - GetYTracking() * sn; + r[1] = x * sn + GetYTracking() * cs; r[2] = GetZTracking(); // } @@ -258,14 +261,14 @@ Double_t AliAlgPoint::GetPhiGlo() const // phi angle (-pi:pi) in global frame double xyz[3]; GetXYZGlo(xyz); - return ATan2(xyz[1],xyz[0]); + return ATan2(xyz[1], xyz[0]); } //__________________________________________________________________ Int_t AliAlgPoint::GetAliceSector() const { // get global sector ID corresponding to this point phi - return Phi2Sector(GetPhiGlo()); + return Phi2Sector(GetPhiGlo()); } //__________________________________________________________________ @@ -274,16 +277,19 @@ void AliAlgPoint::SetMatCovDiagonalizationMatrix(const TMatrixD& d) // save non-sym matrix for material corrections cov.matrix diagonalization // (actually, the eigenvectors are stored) int sz = d.GetNrows(); - for (int i=sz;i--;) for (int j=sz;j--;) fMatDiag[i][j] = d(i,j); + for (int i = sz; i--;) + for (int j = sz; j--;) + fMatDiag[i][j] = d(i, j); } //__________________________________________________________________ void AliAlgPoint::SetMatCovDiag(const TVectorD& v) { - // save material correction diagonalized matrix - // (actually, the eigenvalues are stored w/o reordering them to correspond to the + // save material correction diagonalized matrix + // (actually, the eigenvalues are stored w/o reordering them to correspond to the // AliExternalTrackParam variables) - for (int i=v.GetNrows();i--;) fMatCorrCov[i] = v(i); + for (int i = v.GetNrows(); i--;) + fMatCorrCov[i] = v(i); } //__________________________________________________________________ @@ -292,9 +298,10 @@ void AliAlgPoint::UnDiagMatCorr(const double* diag, double* nodiag) const // transform material corrections from the frame diagonalizing the errors to point frame // nodiag = fMatDiag * diag int np = GetNMatPar(); - for (int ip=np;ip--;) { + for (int ip = np; ip--;) { double v = 0; - for (int jp=np;jp--;) v += fMatDiag[ip][jp]*diag[jp]; + for (int jp = np; jp--;) + v += fMatDiag[ip][jp] * diag[jp]; nodiag[ip] = v; } // @@ -306,9 +313,10 @@ void AliAlgPoint::UnDiagMatCorr(const float* diag, float* nodiag) const // transform material corrections from the frame diagonalizing the errors to point frame // nodiag = fMatDiag * diag int np = GetNMatPar(); - for (int ip=np;ip--;) { + for (int ip = np; ip--;) { double v = 0; - for (int jp=np;jp--;) v += double(fMatDiag[ip][jp])*diag[jp]; + for (int jp = np; jp--;) + v += double(fMatDiag[ip][jp]) * diag[jp]; nodiag[ip] = v; } // @@ -321,9 +329,10 @@ void AliAlgPoint::DiagMatCorr(const double* nodiag, double* diag) const // the frame diagonalizing the errors // diag = fMatDiag^T * nodiag int np = GetNMatPar(); - for (int ip=np;ip--;) { + for (int ip = np; ip--;) { double v = 0; - for (int jp=np;jp--;) v += fMatDiag[jp][ip]*nodiag[jp]; + for (int jp = np; jp--;) + v += fMatDiag[jp][ip] * nodiag[jp]; diag[ip] = v; } // @@ -336,9 +345,10 @@ void AliAlgPoint::DiagMatCorr(const float* nodiag, float* diag) const // the frame diagonalizing the errors // diag = fMatDiag^T * nodiag int np = GetNMatPar(); - for (int ip=np;ip--;) { + for (int ip = np; ip--;) { double v = 0; - for (int jp=np;jp--;) v += double(fMatDiag[jp][ip])*nodiag[jp]; + for (int jp = np; jp--;) + v += double(fMatDiag[jp][ip]) * nodiag[jp]; diag[ip] = v; } // @@ -348,26 +358,27 @@ void AliAlgPoint::DiagMatCorr(const float* nodiag, float* diag) const void AliAlgPoint::GetTrWSA(AliExternalTrackParam& etp) const { // assign WSA (after material corrections) parameters to supplied track - double covDum[15]={ + double covDum[15] = { 1.e-4, - 0 ,1.e-4, - 0 , 0,1.e-4, - 0 , 0, 0,1.e-4, - 0 , 0, 0, 0,1e-4 - }; - etp.Set(GetXPoint(),GetAlphaSens(),fTrParamWSA,covDum); + 0, 1.e-4, + 0, 0, 1.e-4, + 0, 0, 0, 1.e-4, + 0, 0, 0, 0, 1e-4}; + etp.Set(GetXPoint(), GetAlphaSens(), fTrParamWSA, covDum); } //__________________________________________________________________ void AliAlgPoint::GetTrWSB(AliExternalTrackParam& etp) const { // assign WSB parameters (before material corrections) to supplied track - double covDum[15]={ + double covDum[15] = { 1.e-4, - 0 ,1.e-4, - 0 , 0,1.e-4, - 0 , 0, 0,1.e-4, - 0 , 0, 0, 0,1e-4 - }; - etp.Set(GetXPoint(),GetAlphaSens(),fTrParamWSB,covDum); + 0, 1.e-4, + 0, 0, 1.e-4, + 0, 0, 0, 1.e-4, + 0, 0, 0, 0, 1e-4}; + etp.Set(GetXPoint(), GetAlphaSens(), fTrParamWSB, covDum); } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgRes.cxx b/Detectors/Align/src/AliAlgRes.cxx index 79f1e75ba0f3b..219ebbca0c668 100644 --- a/Detectors/Align/src/AliAlgRes.cxx +++ b/Detectors/Align/src/AliAlgRes.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgRes.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief Container for control residuals #include "AliAlgRes.h" #include "AliAlgTrack.h" @@ -24,38 +24,16 @@ using namespace TMath; -ClassImp(AliAlgRes) +ClassImp(o2::align::AliAlgRes); + +namespace o2 +{ +namespace align +{ //____________________________________ -AliAlgRes::AliAlgRes() -: fRun(0) - ,fBz(0) - ,fTimeStamp(0) - ,fTrackID(0) - ,fNPoints(0) - ,fNBook(0) - ,fChi2(0) - ,fChi2Ini(0) - ,fChi2K(0) - ,fQ2Pt(0) - ,fX(0) - ,fY(0) - ,fZ(0) - ,fSnp(0) - ,fTgl(0) - ,fAlpha(0) - ,fDY(0) - ,fDZ(0) - ,fDYK(0) - ,fDZK(0) - ,fSigY2(0) - ,fSigYZ(0) - ,fSigZ2(0) - ,fSigY2K(0) - ,fSigYZK(0) - ,fSigZ2K(0) - ,fVolID(0) - ,fLabel(0) +AliAlgRes::AliAlgRes() + : fRun(0), fBz(0), fTimeStamp(0), fTrackID(0), fNPoints(0), fNBook(0), fChi2(0), fChi2Ini(0), fChi2K(0), fQ2Pt(0), fX(0), fY(0), fZ(0), fSnp(0), fTgl(0), fAlpha(0), fDY(0), fDZ(0), fDYK(0), fDZK(0), fSigY2(0), fSigYZ(0), fSigZ2(0), fSigY2K(0), fSigYZK(0), fSigZ2K(0), fVolID(0), fLabel(0) { // def c-tor } @@ -88,7 +66,7 @@ AliAlgRes::~AliAlgRes() void AliAlgRes::Resize(Int_t np) { // resize container - if (np>fNBook) { + if (np > fNBook) { delete[] fX; delete[] fY; delete[] fZ; @@ -108,50 +86,50 @@ void AliAlgRes::Resize(Int_t np) delete[] fVolID; delete[] fLabel; // - fNBook = 100+np; - fX = new Float_t[fNBook]; - fY = new Float_t[fNBook]; - fZ = new Float_t[fNBook]; - fSnp = new Float_t[fNBook]; - fTgl = new Float_t[fNBook]; - fAlpha = new Float_t[fNBook]; - fDY = new Float_t[fNBook]; - fDZ = new Float_t[fNBook]; - fSigY2 = new Float_t[fNBook]; - fSigYZ = new Float_t[fNBook]; - fSigZ2 = new Float_t[fNBook]; - fDYK = new Float_t[fNBook]; - fDZK = new Float_t[fNBook]; - fSigY2K = new Float_t[fNBook]; - fSigYZK = new Float_t[fNBook]; - fSigZ2K = new Float_t[fNBook]; - fVolID = new Int_t[fNBook]; - fLabel = new Int_t[fNBook]; + fNBook = 100 + np; + fX = new Float_t[fNBook]; + fY = new Float_t[fNBook]; + fZ = new Float_t[fNBook]; + fSnp = new Float_t[fNBook]; + fTgl = new Float_t[fNBook]; + fAlpha = new Float_t[fNBook]; + fDY = new Float_t[fNBook]; + fDZ = new Float_t[fNBook]; + fSigY2 = new Float_t[fNBook]; + fSigYZ = new Float_t[fNBook]; + fSigZ2 = new Float_t[fNBook]; + fDYK = new Float_t[fNBook]; + fDZK = new Float_t[fNBook]; + fSigY2K = new Float_t[fNBook]; + fSigYZK = new Float_t[fNBook]; + fSigZ2K = new Float_t[fNBook]; + fVolID = new Int_t[fNBook]; + fLabel = new Int_t[fNBook]; // - memset(fX , 0,fNBook*sizeof(Float_t)); - memset(fY , 0,fNBook*sizeof(Float_t)); - memset(fZ , 0,fNBook*sizeof(Float_t)); - memset(fSnp , 0,fNBook*sizeof(Float_t)); - memset(fTgl , 0,fNBook*sizeof(Float_t)); - memset(fAlpha, 0,fNBook*sizeof(Float_t)); - memset(fDY , 0,fNBook*sizeof(Float_t)); - memset(fDZ , 0,fNBook*sizeof(Float_t)); - memset(fSigY2, 0,fNBook*sizeof(Float_t)); - memset(fSigYZ, 0,fNBook*sizeof(Float_t)); - memset(fSigZ2, 0,fNBook*sizeof(Float_t)); - memset(fDYK , 0,fNBook*sizeof(Float_t)); - memset(fDZK , 0,fNBook*sizeof(Float_t)); - memset(fSigY2K,0,fNBook*sizeof(Float_t)); - memset(fSigYZK,0,fNBook*sizeof(Float_t)); - memset(fSigZ2K,0,fNBook*sizeof(Float_t)); - memset(fVolID, 0,fNBook*sizeof(Int_t)); - memset(fLabel, 0,fNBook*sizeof(Int_t)); + memset(fX, 0, fNBook * sizeof(Float_t)); + memset(fY, 0, fNBook * sizeof(Float_t)); + memset(fZ, 0, fNBook * sizeof(Float_t)); + memset(fSnp, 0, fNBook * sizeof(Float_t)); + memset(fTgl, 0, fNBook * sizeof(Float_t)); + memset(fAlpha, 0, fNBook * sizeof(Float_t)); + memset(fDY, 0, fNBook * sizeof(Float_t)); + memset(fDZ, 0, fNBook * sizeof(Float_t)); + memset(fSigY2, 0, fNBook * sizeof(Float_t)); + memset(fSigYZ, 0, fNBook * sizeof(Float_t)); + memset(fSigZ2, 0, fNBook * sizeof(Float_t)); + memset(fDYK, 0, fNBook * sizeof(Float_t)); + memset(fDZK, 0, fNBook * sizeof(Float_t)); + memset(fSigY2K, 0, fNBook * sizeof(Float_t)); + memset(fSigYZK, 0, fNBook * sizeof(Float_t)); + memset(fSigZ2K, 0, fNBook * sizeof(Float_t)); + memset(fVolID, 0, fNBook * sizeof(Int_t)); + memset(fLabel, 0, fNBook * sizeof(Int_t)); } // } //____________________________________________ -void AliAlgRes::Clear(const Option_t *) +void AliAlgRes::Clear(const Option_t*) { // reset record TObject::Clear(); @@ -161,45 +139,52 @@ void AliAlgRes::Clear(const Option_t *) fTimeStamp = 0; fTrackID = 0; fChi2 = 0; - fChi2K= 0; + fChi2K = 0; fQ2Pt = 0; // } //____________________________________________ -void AliAlgRes::Print(const Option_t *opt) const +void AliAlgRes::Print(const Option_t* opt) const { // print info - TString opts = opt; opts.ToLower(); + TString opts = opt; + opts.ToLower(); Bool_t lab = opts.Contains("l"); - printf("%5sTr.",IsCosmic() ? "Cosm.":"Coll."); - if (IsCosmic()) printf("%2d/%2d ",fTrackID>>16,fTrackID&0xffff); - else printf("%5d ",fTrackID); + printf("%5sTr.", IsCosmic() ? "Cosm." : "Coll."); + if (IsCosmic()) + printf("%2d/%2d ", fTrackID >> 16, fTrackID & 0xffff); + else + printf("%5d ", fTrackID); printf("Run:%6d Bz:%+4.1f Np: %3d q/Pt:%+.4f | Chi2: Ini: %6.1f LinSol:%6.1f Kalm:%6.1f |Vtx:%3s| TStamp:%d\n", - fRun,fBz,fNPoints,fQ2Pt,fChi2Ini,fChi2,fChi2K,HasVertex() ? "ON":"OFF",fTimeStamp); + fRun, fBz, fNPoints, fQ2Pt, fChi2Ini, fChi2, fChi2K, HasVertex() ? "ON" : "OFF", fTimeStamp); if (opts.Contains("r")) { Bool_t ers = opts.Contains("e"); printf("%5s %7s %s %7s %7s %7s %5s %5s %9s %9s", - " VID "," Label "," Alp "," X "," Y "," Z "," Snp "," Tgl "," DY "," DZ "); - if (ers) printf(" %8s %8s %8s"," pSgYY "," pSgYZ "," pSgZZ "); // cluster errors + " VID ", " Label ", " Alp ", " X ", " Y ", " Z ", " Snp ", " Tgl ", " DY ", " DZ "); + if (ers) + printf(" %8s %8s %8s", " pSgYY ", " pSgYZ ", " pSgZZ "); // cluster errors if (GetKalmanDone()) { - printf(" %9s %9s"," DYK "," DZK "); - if (ers) printf(" %8s %8s %8s"," tSgYY "," tSgYZ "," tSgZZ "); // track errors + printf(" %9s %9s", " DYK ", " DZK "); + if (ers) + printf(" %8s %8s %8s", " tSgYY ", " tSgYZ ", " tSgZZ "); // track errors } printf("\n"); - for (int i=0;iGetNPoints(); + int nps, np = trc->GetNPoints(); if (trc->GetInnerPoint()->ContainsMeasurement()) { SetHasVertex(); nps = np; - } - else nps = np-1; // ref point is dummy? - if (nps<0) return kTRUE; + } else + nps = np - 1; // ref point is dummy? + if (nps < 0) + return kTRUE; SetCosmic(trc->IsCosmic()); - // + // SetNPoints(nps); fQ2Pt = trc->GetSigned1Pt(); fChi2 = trc->GetChi2(); fChi2Ini = trc->GetChi2Ini(); int nfill = 0; - for (int i=0;iGetPoint(i); - int inv = pnt->IsInvDir() ? -1:1; // Flag invertion for cosmic upper leg - if (!pnt->ContainsMeasurement()) continue; - if (!pnt->IsStatOK()) pnt->IncrementStat(); + int inv = pnt->IsInvDir() ? -1 : 1; // Flag invertion for cosmic upper leg + if (!pnt->ContainsMeasurement()) + continue; + if (!pnt->IsStatOK()) + pnt->IncrementStat(); fVolID[nfill] = pnt->GetVolID(); fLabel[nfill] = pnt->GetSensor()->GetInternalID(); fAlpha[nfill] = pnt->GetAlphaSens(); - fX[nfill] = pnt->GetXPoint()*inv; - fY[nfill] = pnt->GetYTracking(); - fZ[nfill] = pnt->GetZTracking(); - fDY[nfill] = pnt->GetResidY(); - fDZ[nfill] = pnt->GetResidZ(); + fX[nfill] = pnt->GetXPoint() * inv; + fY[nfill] = pnt->GetYTracking(); + fZ[nfill] = pnt->GetZTracking(); + fDY[nfill] = pnt->GetResidY(); + fDZ[nfill] = pnt->GetResidZ(); fSigY2[nfill] = pnt->GetYZErrTracking()[0]; fSigYZ[nfill] = pnt->GetYZErrTracking()[1]; fSigZ2[nfill] = pnt->GetYZErrTracking()[2]; // - fSnp[nfill] = pnt->GetTrParamWSA()[AliAlgPoint::kParSnp]; - fTgl[nfill] = pnt->GetTrParamWSA()[AliAlgPoint::kParTgl]; + fSnp[nfill] = pnt->GetTrParamWSA()[AliAlgPoint::kParSnp]; + fTgl[nfill] = pnt->GetTrParamWSA()[AliAlgPoint::kParTgl]; // nfill++; } - if (nfill!=nps) { + if (nfill != nps) { trc->Print("p"); - AliFatalF("Something is wrong: %d residuals were stored instead of %d",nfill,nps); + AliFatalF("Something is wrong: %d residuals were stored instead of %d", nfill, nps); } // SetKalmanDone(kFALSE); - int nfilk=0; + int nfilk = 0; if (doKalman && trc->ResidKalman()) { - for (int i=0;iGetPoint(i); - if (!pnt->ContainsMeasurement()) continue; + if (!pnt->ContainsMeasurement()) + continue; if (fVolID[nfilk] != int(pnt->GetVolID())) { - AliFatalF("Mismatch in Kalman filling for point %d: filled VID:%d, point VID:%d", - i,fVolID[nfilk],pnt->GetVolID()); + AliFatalF("Mismatch in Kalman filling for point %d: filled VID:%d, point VID:%d", + i, fVolID[nfilk], pnt->GetVolID()); } const double* wsA = pnt->GetTrParamWSA(); - fDYK[nfilk] = pnt->GetResidY(); - fDZK[nfilk] = pnt->GetResidZ(); + fDYK[nfilk] = pnt->GetResidY(); + fDZK[nfilk] = pnt->GetResidZ(); fSigY2K[nfilk] = wsA[2]; fSigYZK[nfilk] = wsA[3]; fSigZ2K[nfilk] = wsA[4]; @@ -282,14 +271,14 @@ Bool_t AliAlgRes::FillTrack(AliAlgTrack* trc, Bool_t doKalman) Float_t AliAlgRes::GetXLab(int i) const { // cluster lab X - return Abs(fX[i])*Cos(fAlpha[i]) - fY[i]*Sin(fAlpha[i]); + return Abs(fX[i]) * Cos(fAlpha[i]) - fY[i] * Sin(fAlpha[i]); } //_________________________________________________ Float_t AliAlgRes::GetYLab(int i) const { // cluster lab Y - return Abs(fX[i])*Sin(fAlpha[i]) + fY[i]*Cos(fAlpha[i]); + return Abs(fX[i]) * Sin(fAlpha[i]) + fY[i] * Cos(fAlpha[i]); } //_________________________________________________ @@ -298,3 +287,6 @@ Float_t AliAlgRes::GetZLab(int i) const // cluster lab Z return fZ[i]; } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgResFast.cxx b/Detectors/Align/src/AliAlgResFast.cxx index dc48e6992c192..fd5790a9fd04b 100644 --- a/Detectors/Align/src/AliAlgResFast.cxx +++ b/Detectors/Align/src/AliAlgResFast.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgResFast.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief Container for control fast residuals evaluated via derivatives #include "AliAlgResFast.h" #include "AliAlgTrack.h" @@ -24,26 +24,20 @@ using namespace TMath; -ClassImp(AliAlgResFast) +ClassImp(o2::align::AliAlgResFast); + +namespace o2 +{ +namespace align +{ //____________________________________ -AliAlgResFast::AliAlgResFast() -: fNPoints(0) - ,fNMatSol(0) - ,fNBook(0) - ,fChi2(0) - ,fChi2Ini(0) - ,fD0(0) - ,fD1(0) - ,fSig0(0) - ,fSig1(0) - ,fVolID(0) - ,fLabel(0) - ,fSolMat(0) - ,fMatErr(0) +AliAlgResFast::AliAlgResFast() + : fNPoints(0), fNMatSol(0), fNBook(0), fChi2(0), fChi2Ini(0), fD0(0), fD1(0), fSig0(0), fSig1(0), fVolID(0), fLabel(0), fSolMat(0), fMatErr(0) { // def c-tor - for (int i=5;i--;) fTrCorr[i] = 0; + for (int i = 5; i--;) + fTrCorr[i] = 0; } //________________________________________________ @@ -64,7 +58,7 @@ AliAlgResFast::~AliAlgResFast() void AliAlgResFast::Resize(Int_t np) { // resize container - if (np>fNBook) { + if (np > fNBook) { delete[] fD0; delete[] fD1; delete[] fSig0; @@ -74,30 +68,30 @@ void AliAlgResFast::Resize(Int_t np) delete[] fSolMat; delete[] fMatErr; // - fNBook = 30+np; - fD0 = new Float_t[fNBook]; - fD1 = new Float_t[fNBook]; - fSig0 = new Float_t[fNBook]; - fSig1 = new Float_t[fNBook]; - fVolID = new Int_t[fNBook]; - fLabel = new Int_t[fNBook]; - fSolMat = new Float_t[fNBook*4]; // at most 4 material params per point - fMatErr = new Float_t[fNBook*4]; // at most 4 material params per point + fNBook = 30 + np; + fD0 = new Float_t[fNBook]; + fD1 = new Float_t[fNBook]; + fSig0 = new Float_t[fNBook]; + fSig1 = new Float_t[fNBook]; + fVolID = new Int_t[fNBook]; + fLabel = new Int_t[fNBook]; + fSolMat = new Float_t[fNBook * 4]; // at most 4 material params per point + fMatErr = new Float_t[fNBook * 4]; // at most 4 material params per point // - memset(fD0 , 0,fNBook*sizeof(Float_t)); - memset(fD1 , 0,fNBook*sizeof(Float_t)); - memset(fSig0, 0,fNBook*sizeof(Float_t)); - memset(fSig1, 0,fNBook*sizeof(Float_t)); - memset(fVolID, 0,fNBook*sizeof(Int_t)); - memset(fLabel, 0,fNBook*sizeof(Int_t)); - memset(fSolMat, 0,4*fNBook*sizeof(Int_t)); - memset(fMatErr, 0,4*fNBook*sizeof(Int_t)); + memset(fD0, 0, fNBook * sizeof(Float_t)); + memset(fD1, 0, fNBook * sizeof(Float_t)); + memset(fSig0, 0, fNBook * sizeof(Float_t)); + memset(fSig1, 0, fNBook * sizeof(Float_t)); + memset(fVolID, 0, fNBook * sizeof(Int_t)); + memset(fLabel, 0, fNBook * sizeof(Int_t)); + memset(fSolMat, 0, 4 * fNBook * sizeof(Int_t)); + memset(fMatErr, 0, 4 * fNBook * sizeof(Int_t)); } // } //____________________________________________ -void AliAlgResFast::Clear(const Option_t *) +void AliAlgResFast::Clear(const Option_t*) { // reset record fNPoints = 0; @@ -107,29 +101,31 @@ void AliAlgResFast::Clear(const Option_t *) } //____________________________________________ -void AliAlgResFast::Print(const Option_t */*opt*/) const +void AliAlgResFast::Print(const Option_t* /*opt*/) const { // print info - printf("%3s:%1s (%9s/%5s) %6s | [ %7s:%7s ]\n","Pnt","M","Label", - "VolID","Sigma","resid","pull/LG"); - for (int irs=0;irs0 ? fD0[irs]/fSig0[irs]:-99); + irs, 0, fLabel[irs], fVolID[irs], fSig0[irs], fD0[irs], + fSig0[irs] > 0 ? fD0[irs] / fSig0[irs] : -99); printf("%3d:%1d (%9d/%5d) %6.4f | [%+.2e:%+7.2f]\n", - irs,1, fLabel[irs],fVolID[irs],fSig1[irs],fD1[irs], - fSig1[irs]>0 ? fD1[irs]/fSig1[irs]:-99); + irs, 1, fLabel[irs], fVolID[irs], fSig1[irs], fD1[irs], + fSig1[irs] > 0 ? fD1[irs] / fSig1[irs] : -99); } // printf("CorrETP: "); - for (int i=0;i<5;i++) printf("%+.3f ",fTrCorr[i]); printf("\n"); + for (int i = 0; i < 5; i++) + printf("%+.3f ", fTrCorr[i]); + printf("\n"); printf("MatCorr (corr/sig:pull)\n"); - int nmp = fNMatSol/4; + int nmp = fNMatSol / 4; int cnt = 0; - for (int imp=0;imp0 ? fSolMat[cnt]/fMatErr[cnt] : -99); + for (int imp = 0; imp < nmp; imp++) { + for (int ic = 0; ic < 4; ic++) { + printf("%+.2e/%.2e:%+8.3f|", fSolMat[cnt], fMatErr[cnt], + fMatErr[cnt] > 0 ? fSolMat[cnt] / fMatErr[cnt] : -99); cnt++; } printf("\n"); @@ -141,11 +137,10 @@ void AliAlgResFast::Print(const Option_t */*opt*/) const void AliAlgResFast::SetResSigMeas(int ip, int ord, float res, float sig) { // assign residual and error for measurement - if (ord==0) { + if (ord == 0) { fD0[ip] = res; fSig0[ip] = sig; - } - else { + } else { fD1[ip] = res; fSig1[ip] = sig; } @@ -166,3 +161,6 @@ void AliAlgResFast::SetLabel(int ip, Int_t lab, Int_t vol) fVolID[ip] = vol; fLabel[ip] = lab; } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgSens.cxx b/Detectors/Align/src/AliAlgSens.cxx index 27667131ed6eb..b8973812a331c 100644 --- a/Detectors/Align/src/AliAlgSens.cxx +++ b/Detectors/Align/src/AliAlgSens.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgSens.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief End-chain alignment volume in detector branch, where the actual measurement is done. #include #include @@ -24,18 +24,19 @@ #include "AliAlgDet.h" #include "AliAlgDOFStat.h" -ClassImp(AliAlgSens) +ClassImp(AliAlgSens); -using namespace AliAlgAux; +using namespace o2::align::AliAlgAux; using namespace TMath; +namespace o2 +{ +namespace align +{ + //_________________________________________________________ -AliAlgSens::AliAlgSens(const char* name,Int_t vid, Int_t iid) - : AliAlgVol(name,iid) - ,fSID(0) - ,fDet(0) - ,fMatClAlg() - ,fMatClAlgReco() +AliAlgSens::AliAlgSens(const char* name, Int_t vid, Int_t iid) + : AliAlgVol(name, iid), fSID(0), fDet(0), fMatClAlg(), fMatClAlgReco() { // def c-tor SetVolID(vid); @@ -52,42 +53,44 @@ AliAlgSens::~AliAlgSens() //_________________________________________________________ void AliAlgSens::DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv) const { - // Jacobian of position in sensor tracking frame (tra) vs sensor LOCAL frame + // Jacobian of position in sensor tracking frame (tra) vs sensor LOCAL frame // parameters in TGeoHMatrix convention. - // Result is stored in array deriv as linearized matrix 6x3 - const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5}; - double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3]; + // Result is stored in array deriv as linearized matrix 6x3 + const double kDelta[kNDOFGeom] = {0.1, 0.1, 0.1, 0.5, 0.5, 0.5}; + double delta[kNDOFGeom], pos0[3], pos1[3], pos2[3], pos3[3]; TGeoHMatrix matMod; // - memset(delta,0,kNDOFGeom*sizeof(double)); - memset(deriv,0,kNDOFGeom*3*sizeof(double)); - const double *tra = pnt->GetXYZTracking(); + memset(delta, 0, kNDOFGeom * sizeof(double)); + memset(deriv, 0, kNDOFGeom * 3 * sizeof(double)); + const double* tra = pnt->GetXYZTracking(); // - for (int ip=kNDOFGeom;ip--;) { + for (int ip = kNDOFGeom; ip--;) { // - if (!IsFreeDOF(ip)) continue; + if (!IsFreeDOF(ip)) + continue; // double var = kDelta[ip]; delta[ip] -= var; // variation matrix in tracking frame for variation in sensor LOCAL frame - GetDeltaT2LmodLOC(matMod, delta); - matMod.LocalToMaster(tra,pos0); // varied position in tracking frame + GetDeltaT2LmodLOC(matMod, delta); + matMod.LocalToMaster(tra, pos0); // varied position in tracking frame // - delta[ip] += 0.5*var; - GetDeltaT2LmodLOC(matMod, delta); - matMod.LocalToMaster(tra,pos1); // varied position in tracking frame + delta[ip] += 0.5 * var; + GetDeltaT2LmodLOC(matMod, delta); + matMod.LocalToMaster(tra, pos1); // varied position in tracking frame // delta[ip] += var; - GetDeltaT2LmodLOC(matMod, delta); - matMod.LocalToMaster(tra,pos2); // varied position in tracking frame + GetDeltaT2LmodLOC(matMod, delta); + matMod.LocalToMaster(tra, pos2); // varied position in tracking frame // - delta[ip] += 0.5*var; - GetDeltaT2LmodLOC(matMod, delta); - matMod.LocalToMaster(tra,pos3); // varied position in tracking frame + delta[ip] += 0.5 * var; + GetDeltaT2LmodLOC(matMod, delta); + matMod.LocalToMaster(tra, pos3); // varied position in tracking frame // delta[ip] = 0; - double *curd = deriv + ip*3; - for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var; + double* curd = deriv + ip * 3; + for (int i = 3; i--;) + curd[i] = (8. * (pos2[i] - pos1[i]) - (pos3[i] - pos0[i])) / 6. / var; } // } @@ -97,42 +100,44 @@ void AliAlgSens::DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv, const { // Jacobian of position in sensor tracking frame (tra) vs parent volume LOCAL frame parameters. // NO check of parentship is done! - // Result is stored in array deriv as linearized matrix 6x3 - const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5}; - double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3]; + // Result is stored in array deriv as linearized matrix 6x3 + const double kDelta[kNDOFGeom] = {0.1, 0.1, 0.1, 0.5, 0.5, 0.5}; + double delta[kNDOFGeom], pos0[3], pos1[3], pos2[3], pos3[3]; TGeoHMatrix matMod; // this is the matrix for transition from sensor to parent volume local frames: LOC=matRel*loc - TGeoHMatrix matRel = parent->GetMatrixL2GIdeal().Inverse(); + TGeoHMatrix matRel = parent->GetMatrixL2GIdeal().Inverse(); matRel *= GetMatrixL2GIdeal(); // - memset(delta,0,kNDOFGeom*sizeof(double)); - memset(deriv,0,kNDOFGeom*3*sizeof(double)); - const double *tra = pnt->GetXYZTracking(); + memset(delta, 0, kNDOFGeom * sizeof(double)); + memset(deriv, 0, kNDOFGeom * 3 * sizeof(double)); + const double* tra = pnt->GetXYZTracking(); // - for (int ip=kNDOFGeom;ip--;) { + for (int ip = kNDOFGeom; ip--;) { // - if (!IsFreeDOF(ip)) continue; + if (!IsFreeDOF(ip)) + continue; // double var = kDelta[ip]; delta[ip] -= var; GetDeltaT2LmodLOC(matMod, delta, matRel); - matMod.LocalToMaster(tra,pos0); // varied position in tracking frame + matMod.LocalToMaster(tra, pos0); // varied position in tracking frame // - delta[ip] += 0.5*var; + delta[ip] += 0.5 * var; GetDeltaT2LmodLOC(matMod, delta, matRel); - matMod.LocalToMaster(tra,pos1); // varied position in tracking frame + matMod.LocalToMaster(tra, pos1); // varied position in tracking frame // delta[ip] += var; GetDeltaT2LmodLOC(matMod, delta, matRel); - matMod.LocalToMaster(tra,pos2); // varied position in tracking frame + matMod.LocalToMaster(tra, pos2); // varied position in tracking frame // - delta[ip] += 0.5*var; + delta[ip] += 0.5 * var; GetDeltaT2LmodLOC(matMod, delta, matRel); - matMod.LocalToMaster(tra,pos3); // varied position in tracking frame + matMod.LocalToMaster(tra, pos3); // varied position in tracking frame // delta[ip] = 0; - double *curd = deriv + ip*3; - for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var; + double* curd = deriv + ip * 3; + for (int i = 3; i--;) + curd[i] = (8. * (pos2[i] - pos1[i]) - (pos3[i] - pos0[i])) / 6. / var; } // } @@ -140,43 +145,45 @@ void AliAlgSens::DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv, const //_________________________________________________________ void AliAlgSens::DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv) const { - // Jacobian of position in sensor tracking frame (tra) vs sensor TRACKING + // Jacobian of position in sensor tracking frame (tra) vs sensor TRACKING // frame parameters in TGeoHMatrix convention, i.e. the modified parameter is // tra' = tau*tra // - // Result is stored in array deriv as linearized matrix 6x3 - const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5}; - double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3]; + // Result is stored in array deriv as linearized matrix 6x3 + const double kDelta[kNDOFGeom] = {0.1, 0.1, 0.1, 0.5, 0.5, 0.5}; + double delta[kNDOFGeom], pos0[3], pos1[3], pos2[3], pos3[3]; TGeoHMatrix matMod; // - memset(delta,0,kNDOFGeom*sizeof(double)); - memset(deriv,0,kNDOFGeom*3*sizeof(double)); - const double *tra = pnt->GetXYZTracking(); + memset(delta, 0, kNDOFGeom * sizeof(double)); + memset(deriv, 0, kNDOFGeom * 3 * sizeof(double)); + const double* tra = pnt->GetXYZTracking(); // - for (int ip=kNDOFGeom;ip--;) { + for (int ip = kNDOFGeom; ip--;) { // - if (!IsFreeDOF(ip)) continue; + if (!IsFreeDOF(ip)) + continue; // double var = kDelta[ip]; delta[ip] -= var; - GetDeltaT2LmodTRA(matMod,delta); - matMod.LocalToMaster(tra,pos0); // varied position in tracking frame + GetDeltaT2LmodTRA(matMod, delta); + matMod.LocalToMaster(tra, pos0); // varied position in tracking frame // - delta[ip] += 0.5*var; - GetDeltaT2LmodTRA(matMod,delta); - matMod.LocalToMaster(tra,pos1); // varied position in tracking frame + delta[ip] += 0.5 * var; + GetDeltaT2LmodTRA(matMod, delta); + matMod.LocalToMaster(tra, pos1); // varied position in tracking frame // delta[ip] += var; - GetDeltaT2LmodTRA(matMod,delta); - matMod.LocalToMaster(tra,pos2); // varied position in tracking frame + GetDeltaT2LmodTRA(matMod, delta); + matMod.LocalToMaster(tra, pos2); // varied position in tracking frame // - delta[ip] += 0.5*var; - GetDeltaT2LmodTRA(matMod,delta); - matMod.LocalToMaster(tra,pos3); // varied position in tracking frame + delta[ip] += 0.5 * var; + GetDeltaT2LmodTRA(matMod, delta); + matMod.LocalToMaster(tra, pos3); // varied position in tracking frame // delta[ip] = 0; - double *curd = deriv + ip*3; - for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var; + double* curd = deriv + ip * 3; + for (int i = 3; i--;) + curd[i] = (8. * (pos2[i] - pos1[i]) - (pos3[i] - pos0[i])) / 6. / var; } // } @@ -184,58 +191,60 @@ void AliAlgSens::DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv) const //_________________________________________________________ void AliAlgSens::DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const { - // Jacobian of position in sensor tracking frame (tra) vs sensor TRACKING + // Jacobian of position in sensor tracking frame (tra) vs sensor TRACKING // frame parameters in TGeoHMatrix convention, i.e. the modified parameter is // tra' = tau*tra // - // Result is stored in array deriv as linearized matrix 6x3 - const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5}; - double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3]; + // Result is stored in array deriv as linearized matrix 6x3 + const double kDelta[kNDOFGeom] = {0.1, 0.1, 0.1, 0.5, 0.5, 0.5}; + double delta[kNDOFGeom], pos0[3], pos1[3], pos2[3], pos3[3]; TGeoHMatrix matMod; // // 1st we need a matrix for transition between child and parent TRACKING frames // Let TRA,LOC are positions in tracking and local frame of parent, linked as LOC=T2L*TRA // and tra,loc are positions in tracking and local frame of child, linked as loc=t2l*tra - // The loc and LOC are linked as LOC=R*loc, where R = L2G^-1*l2g, with L2G and l2g + // The loc and LOC are linked as LOC=R*loc, where R = L2G^-1*l2g, with L2G and l2g // local2global matrices for parent and child // // Then, TRA = T2L^-1*LOC = T2L^-1*R*loc = T2L^-1*R*t2l*tra // -> TRA = matRel*tra, with matRel = T2L^-1*L2G^-1 * l2g*t2l // Note that l2g*t2l are tracking to global matrices - TGeoHMatrix matRel,t2gP; - GetMatrixT2G(matRel); // t2g matrix of child - parent->GetMatrixT2G(t2gP); // t2g matrix of parent + TGeoHMatrix matRel, t2gP; + GetMatrixT2G(matRel); // t2g matrix of child + parent->GetMatrixT2G(t2gP); // t2g matrix of parent const TGeoHMatrix& t2gpi = t2gP.Inverse(); matRel.MultiplyLeft(&t2gpi); // - memset(delta,0,kNDOFGeom*sizeof(double)); - memset(deriv,0,kNDOFGeom*3*sizeof(double)); - const double *tra = pnt->GetXYZTracking(); + memset(delta, 0, kNDOFGeom * sizeof(double)); + memset(deriv, 0, kNDOFGeom * 3 * sizeof(double)); + const double* tra = pnt->GetXYZTracking(); // - for (int ip=kNDOFGeom;ip--;) { + for (int ip = kNDOFGeom; ip--;) { // - if (!IsFreeDOF(ip)) continue; + if (!IsFreeDOF(ip)) + continue; // double var = kDelta[ip]; delta[ip] -= var; - GetDeltaT2LmodTRA(matMod,delta,matRel); - matMod.LocalToMaster(tra,pos0); // varied position in tracking frame + GetDeltaT2LmodTRA(matMod, delta, matRel); + matMod.LocalToMaster(tra, pos0); // varied position in tracking frame // - delta[ip] += 0.5*var; - GetDeltaT2LmodTRA(matMod,delta,matRel); - matMod.LocalToMaster(tra,pos1); // varied position in tracking frame + delta[ip] += 0.5 * var; + GetDeltaT2LmodTRA(matMod, delta, matRel); + matMod.LocalToMaster(tra, pos1); // varied position in tracking frame // delta[ip] += var; - GetDeltaT2LmodTRA(matMod,delta,matRel); - matMod.LocalToMaster(tra,pos2); // varied position in tracking frame + GetDeltaT2LmodTRA(matMod, delta, matRel); + matMod.LocalToMaster(tra, pos2); // varied position in tracking frame // - delta[ip] += 0.5*var; - GetDeltaT2LmodTRA(matMod,delta,matRel); - matMod.LocalToMaster(tra,pos3); // varied position in tracking frame + delta[ip] += 0.5 * var; + GetDeltaT2LmodTRA(matMod, delta, matRel); + matMod.LocalToMaster(tra, pos3); // varied position in tracking frame // delta[ip] = 0; - double *curd = deriv + ip*3; - for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var; + double* curd = deriv + ip * 3; + for (int i = 3; i--;) + curd[i] = (8. * (pos2[i] - pos1[i]) - (pos3[i] - pos0[i])) / 6. / var; } // } @@ -246,31 +255,33 @@ void AliAlgSens::DPosTraDParGeom(const AliAlgPoint* pnt, double* deriv, const Al // calculate point position derivatives in tracking frame of sensor // vs standard geometrical DOFs of its parent volume (if parent!=0) or sensor itself Frame_t frame = parent ? parent->GetVarFrame() : GetVarFrame(); - switch(frame) { - case kLOC : parent ? DPosTraDParGeomLOC(pnt,deriv,parent) : DPosTraDParGeomLOC(pnt,deriv); - break; - case kTRA : parent ? DPosTraDParGeomTRA(pnt,deriv,parent) : DPosTraDParGeomTRA(pnt,deriv); - break; - default : AliErrorF("Alignment frame %d is not implemented",parent->GetVarFrame()); - break; + switch (frame) { + case kLOC: + parent ? DPosTraDParGeomLOC(pnt, deriv, parent) : DPosTraDParGeomLOC(pnt, deriv); + break; + case kTRA: + parent ? DPosTraDParGeomTRA(pnt, deriv, parent) : DPosTraDParGeomTRA(pnt, deriv); + break; + default: + AliErrorF("Alignment frame %d is not implemented", parent->GetVarFrame()); + break; } } //__________________________________________________________________ -void AliAlgSens::GetModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const Double_t *delta) const +void AliAlgSens::GetModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const Double_t* delta) const { - // prepare the sensitive module tracking2local matrix from its current T2L matrix + // prepare the sensitive module tracking2local matrix from its current T2L matrix // by applying local delta of modification of LOCAL frame: // loc' = delta*loc = T2L'*tra = T2L'*T2L^-1*loc -> T2L' = delta*T2L Delta2Matrix(matMod, delta); matMod.Multiply(&GetMatrixT2L()); } - //__________________________________________________________________ -void AliAlgSens::GetModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const Double_t *delta) const +void AliAlgSens::GetModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const Double_t* delta) const { - // prepare the sensitive module tracking2local matrix from its current T2L matrix + // prepare the sensitive module tracking2local matrix from its current T2L matrix // by applying local delta of modification of TRACKING frame: // loc' = T2L'*tra = T2L*delta*tra -> T2L' = T2L*delta Delta2Matrix(matMod, delta); @@ -280,14 +291,14 @@ void AliAlgSens::GetModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const Double_t //__________________________________________________________________ void AliAlgSens::AddChild(AliAlgVol*) { - AliFatalF("Sensor volume cannot have childs: id=%d %s",GetVolID(),GetName()); + AliFatalF("Sensor volume cannot have childs: id=%d %s", GetVolID(), GetName()); } //__________________________________________________________________ Int_t AliAlgSens::Compare(const TObject* b) const { // compare VolIDs - return GetUniqueID()GetUniqueID() ? -1 : 1; + return GetUniqueID() < b->GetUniqueID() ? -1 : 1; } //__________________________________________________________________ @@ -295,49 +306,59 @@ void AliAlgSens::SetTrackingFrame() { // define tracking frame of the sensor // AliWarningF("Generic method called for %s",GetSymName()); - double tra[3]={0},glo[3]; + double tra[3] = {0}, glo[3]; TGeoHMatrix t2g; GetMatrixT2G(t2g); - t2g.LocalToMaster(tra,glo); - fX = Sqrt(glo[0]*glo[0]+glo[1]*glo[1]); - fAlp = ATan2(glo[1],glo[0]); + t2g.LocalToMaster(tra, glo); + fX = Sqrt(glo[0] * glo[0] + glo[1] * glo[1]); + fAlp = ATan2(glo[1], glo[0]); AliAlgAux::BringToPiPM(fAlp); // } //____________________________________________ -void AliAlgSens::Print(const Option_t *opt) const +void AliAlgSens::Print(const Option_t* opt) const { // print info TString opts = opt; opts.ToLower(); printf("Lev:%2d IntID:%7d %s VId:%6d X:%8.4f Alp:%+.4f | Err: %.4e %.4e | Used Points: %d\n", - CountParents(), GetInternalID(), GetSymName(), GetVolID(), fX, fAlp, - fAddError[0],fAddError[1],fNProcPoints); - printf(" DOFs: Tot: %d (offs: %5d) Free: %d Geom: %d {",fNDOFs,fFirstParGloID,fNDOFFree,fNDOFGeomFree); - for (int i=0;iUpdatePointByTrackInfo(pnt,t); + fDet->UpdatePointByTrackInfo(pnt, t); } //____________________________________________ -void AliAlgSens::DPosTraDParCalib(const AliAlgPoint* pnt,double* deriv,int calibID,const AliAlgVol* parent) const +void AliAlgSens::DPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int calibID, const AliAlgVol* parent) const { // calculate point position X,Y,Z derivatives wrt calibration parameter calibID of given parent - // parent=0 means top detector object calibration + // parent=0 means top detector object calibration // - deriv[0]=deriv[1]=deriv[2]=0; + deriv[0] = deriv[1] = deriv[2] = 0; } //______________________________________________________ Int_t AliAlgSens::FinalizeStat(AliAlgDOFStat* st) { // finalize statistics on processed points - if (st) FillDOFStat(st); + if (st) + FillDOFStat(st); return fNProcPoints; } //_________________________________________________________________ -void AliAlgSens::UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix *cumulDelta) +void AliAlgSens::UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta) { // recreate fMatL2GReco matrices from ideal L2G matrix and alignment objects - // used during data reconstruction. + // used during data reconstruction. // On top of what each volume does, also update misalignment matrix inverse // - AliAlgVol::UpdateL2GRecoMatrices(algArr,cumulDelta); + AliAlgVol::UpdateL2GRecoMatrices(algArr, cumulDelta); PrepareMatrixClAlgReco(); // } - + /* //_________________________________________________________________ AliAlgPoint* AliAlgSens::TrackPoint2AlgPoint(int, const AliTrackPointArray*, const AliESDtrack*) @@ -432,7 +454,7 @@ void AliAlgSens::ApplyAlignmentFromMPSol() TGeoHMatrix deltaG; // create global combined delta: // DeltaG = deltaG_0*...*deltaG_j, where delta_i is global delta of each member of hierarchy - while(vol) { + while (vol) { TGeoHMatrix deltaGJ; vol->CreateAlignmenMatrix(deltaGJ); deltaG.MultiplyLeft(&deltaGJ); @@ -461,7 +483,7 @@ void AliAlgSens::ApplyAlignmentFromMPSol() // sensor proper variation GetParValGeom(delta); IsFrameTRA() ? GetDeltaT2LmodTRA(matMod,delta) : GetDeltaT2LmodLOC(matMod,delta); - fMatClAlg.MultiplyLeft(&matMod); + fMatClAlg.MultiplyLeft(&matMod); // AliAlgVol* parent = this; while ((parent==parent->GetParent())) { @@ -475,7 +497,7 @@ void AliAlgSens::ApplyAlignmentFromMPSol() GetDeltaT2LmodTRA(matMod, delta, matRel); } else { - matRel = parent->GetMatrixL2GIdeal().Inverse(); + matRel = parent->GetMatrixL2GIdeal().Inverse(); matRel *= GetMatrixL2GIdeal(); GetDeltaT2LmodLOC(matMod, delta, matRel); } @@ -485,3 +507,6 @@ void AliAlgSens::ApplyAlignmentFromMPSol() } */ + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgSensHMPID.cxx b/Detectors/Align/src/AliAlgSensHMPID.cxx index e49439c3d7d49..be92393941590 100644 --- a/Detectors/Align/src/AliAlgSensHMPID.cxx +++ b/Detectors/Align/src/AliAlgSensHMPID.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgSensHMPID.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief HMPID sensor (chamber) #include "AliAlgSensHMPID.h" #include "AliAlgAux.h" @@ -21,14 +21,19 @@ #include "AliAlgPoint.h" #include "AliAlgDet.h" -ClassImp(AliAlgSensHMPID) +ClassImp(o2::align::AliAlgSensHMPID); -using namespace AliAlgAux; +using namespace o2::align::AliAlgAux; using namespace TMath; +namespace o2 +{ +namespace align +{ + //_________________________________________________________ -AliAlgSensHMPID::AliAlgSensHMPID(const char* name,Int_t vid, Int_t iid, Int_t isec) - :AliAlgSens(name,vid,iid) +AliAlgSensHMPID::AliAlgSensHMPID(const char* name, Int_t vid, Int_t iid, Int_t isec) + : AliAlgSens(name, vid, iid) { // def c-tor } @@ -52,13 +57,13 @@ void AliAlgSensHMPID::SetTrackingFrame() void AliAlgSensHMPID::PrepareMatrixT2L() { // creat T2L matrix - double loc[3]={0,0,0},glo[3]; - GetMatrixL2GIdeal().LocalToMaster(loc,glo); - double alp = ATan2(glo[1],glo[0]); - double x = Sqrt(glo[0]*glo[0]+glo[1]*glo[1]); + double loc[3] = {0, 0, 0}, glo[3]; + GetMatrixL2GIdeal().LocalToMaster(loc, glo); + double alp = ATan2(glo[1], glo[0]); + double x = Sqrt(glo[0] * glo[0] + glo[1] * glo[1]); TGeoHMatrix t2l; t2l.SetDx(x); - t2l.RotateZ(alp*RadToDeg()); + t2l.RotateZ(alp * RadToDeg()); const TGeoHMatrix& l2gi = GetMatrixL2GIdeal().Inverse(); t2l.MultiplyLeft(&l2gi); /* @@ -81,20 +86,20 @@ AliAlgPoint* AliAlgSensHMPID::TrackPoint2AlgPoint(int pntId, const AliTrackPoint AliAlgPoint* pnt = det->GetPointFromPool(); pnt->SetSensor(this); // - double tra[3],locId[3],loc[3], + double tra[3], locId[3], loc[3], glo[3] = {trpArr->GetX()[pntId], trpArr->GetY()[pntId], trpArr->GetZ()[pntId]}; const TGeoHMatrix& matL2Grec = GetMatrixL2GReco(); // local to global matrix used for reconstruction - const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation + const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation // // undo reco-time alignment - matL2Grec.MasterToLocal(glo,locId); // go to local frame using reco-time matrix, here we recover ideal measurement + matL2Grec.MasterToLocal(glo, locId); // go to local frame using reco-time matrix, here we recover ideal measurement // - GetMatrixClAlg().LocalToMaster(locId,loc); // apply alignment + GetMatrixClAlg().LocalToMaster(locId, loc); // apply alignment // - matT2L.MasterToLocal(loc,tra); // go to tracking frame + matT2L.MasterToLocal(loc, tra); // go to tracking frame // /* - double gloT[3]; + double gloT[3]; TGeoHMatrix t2g; GetMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); printf("\n%5d %s\n",GetVolID(), GetSymName()); @@ -109,7 +114,7 @@ AliAlgPoint* AliAlgSensHMPID::TrackPoint2AlgPoint(int pntId, const AliTrackPoint // convert error TGeoHMatrix hcov; Double_t hcovel[9]; - const Float_t *pntcov = trpArr->GetCov()+pntId*6; // 6 elements per error matrix + const Float_t* pntcov = trpArr->GetCov() + pntId * 6; // 6 elements per error matrix hcovel[0] = double(pntcov[0]); hcovel[1] = double(pntcov[1]); hcovel[2] = double(pntcov[2]); @@ -122,20 +127,19 @@ AliAlgPoint* AliAlgSensHMPID::TrackPoint2AlgPoint(int pntId, const AliTrackPoint hcov.SetRotation(hcovel); hcov.Multiply(&matL2Grec); const TGeoHMatrix& l2gi = matL2Grec.Inverse(); - hcov.MultiplyLeft(&l2gi); // errors in local frame + hcov.MultiplyLeft(&l2gi); // errors in local frame hcov.Multiply(&matT2L); const TGeoHMatrix& t2li = matT2L.Inverse(); - hcov.MultiplyLeft(&t2li); // errors in tracking frame + hcov.MultiplyLeft(&t2li); // errors in tracking frame // - Double_t *hcovscl = hcov.GetRotationMatrix(); - const double *sysE = GetAddError(); // additional syst error - pnt->SetYZErrTracking(hcovscl[4]+sysE[0]*sysE[0],hcovscl[5],hcovscl[8]+sysE[1]*sysE[1]); - } - else { // errors will be calculated just before using the point in the fit, using track info - pnt->SetYZErrTracking(0,0,0); + Double_t* hcovscl = hcov.GetRotationMatrix(); + const double* sysE = GetAddError(); // additional syst error + pnt->SetYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); + } else { // errors will be calculated just before using the point in the fit, using track info + pnt->SetYZErrTracking(0, 0, 0); pnt->SetNeedUpdateFromTrack(); } - pnt->SetXYZTracking(tra[0],tra[1],tra[2]); + pnt->SetXYZTracking(tra[0], tra[1], tra[2]); pnt->SetAlphaSens(GetAlpTracking()); pnt->SetXSens(GetXTracking()); pnt->SetDetID(det->GetDetID()); @@ -148,3 +152,6 @@ AliAlgPoint* AliAlgSensHMPID::TrackPoint2AlgPoint(int pntId, const AliTrackPoint return pnt; // } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgSensITS.cxx b/Detectors/Align/src/AliAlgSensITS.cxx index afeb08e3dc492..a9dceba9b4472 100644 --- a/Detectors/Align/src/AliAlgSensITS.cxx +++ b/Detectors/Align/src/AliAlgSensITS.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgSensITS.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief ITS sensor #include "AliAlgSensITS.h" #include "AliAlgAux.h" @@ -21,14 +21,19 @@ #include "AliAlgPoint.h" #include "AliAlgDet.h" -ClassImp(AliAlgSensITS) +ClassImp(o2::align::AliAlgSensITS); -using namespace AliAlgAux; +using namespace o2::align::AliAlgAux; using namespace TMath; +namespace o2 +{ +namespace align +{ + //_________________________________________________________ -AliAlgSensITS::AliAlgSensITS(const char* name,Int_t vid, Int_t iid) - : AliAlgSens(name,vid,iid) +AliAlgSensITS::AliAlgSensITS(const char* name, Int_t vid, Int_t iid) + : AliAlgSens(name, vid, iid) { // def c-tor } @@ -62,20 +67,20 @@ AliAlgPoint* AliAlgSensITS::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr AliAlgPoint* pnt = det->GetPointFromPool(); pnt->SetSensor(this); // - double tra[3],locId[3],loc[3], + double tra[3], locId[3], loc[3], glo[3] = {trpArr->GetX()[pntId], trpArr->GetY()[pntId], trpArr->GetZ()[pntId]}; const TGeoHMatrix& matL2Grec = GetMatrixL2GReco(); // local to global matrix used for reconstruction - const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation + const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation // // undo reco-time alignment - matL2Grec.MasterToLocal(glo,locId); // go to local frame using reco-time matrix, here we recover ideal measurement + matL2Grec.MasterToLocal(glo, locId); // go to local frame using reco-time matrix, here we recover ideal measurement // - GetMatrixClAlg().LocalToMaster(locId,loc); // apply alignment + GetMatrixClAlg().LocalToMaster(locId, loc); // apply alignment // - matT2L.MasterToLocal(loc,tra); // go to tracking frame + matT2L.MasterToLocal(loc, tra); // go to tracking frame // /* - double gloT[3]; + double gloT[3]; TGeoHMatrix t2g; GetMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); printf("\n%5d %s\n",GetVolID(), GetSymName()); @@ -90,7 +95,7 @@ AliAlgPoint* AliAlgSensITS::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr // convert error TGeoHMatrix hcov; Double_t hcovel[9]; - const Float_t *pntcov = trpArr->GetCov()+pntId*6; // 6 elements per error matrix + const Float_t* pntcov = trpArr->GetCov() + pntId * 6; // 6 elements per error matrix hcovel[0] = double(pntcov[0]); hcovel[1] = double(pntcov[1]); hcovel[2] = double(pntcov[2]); @@ -103,20 +108,19 @@ AliAlgPoint* AliAlgSensITS::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr hcov.SetRotation(hcovel); hcov.Multiply(&matL2Grec); const TGeoHMatrix& l2gi = matL2Grec.Inverse(); - hcov.MultiplyLeft(&l2gi); // errors in local frame + hcov.MultiplyLeft(&l2gi); // errors in local frame hcov.Multiply(&matT2L); const TGeoHMatrix& t2li = matT2L.Inverse(); - hcov.MultiplyLeft(&t2li); // errors in tracking frame + hcov.MultiplyLeft(&t2li); // errors in tracking frame // - Double_t *hcovscl = hcov.GetRotationMatrix(); - const double *sysE = GetAddError(); // additional syst error - pnt->SetYZErrTracking(hcovscl[4]+sysE[0]*sysE[0],hcovscl[5],hcovscl[8]+sysE[1]*sysE[1]); - } - else { // errors will be calculated just before using the point in the fit, using track info - pnt->SetYZErrTracking(0,0,0); + Double_t* hcovscl = hcov.GetRotationMatrix(); + const double* sysE = GetAddError(); // additional syst error + pnt->SetYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); + } else { // errors will be calculated just before using the point in the fit, using track info + pnt->SetYZErrTracking(0, 0, 0); pnt->SetNeedUpdateFromTrack(); } - pnt->SetXYZTracking(tra[0],tra[1],tra[2]); + pnt->SetXYZTracking(tra[0], tra[1], tra[2]); pnt->SetAlphaSens(GetAlpTracking()); pnt->SetXSens(GetXTracking()); pnt->SetDetID(det->GetDetID()); @@ -129,3 +133,6 @@ AliAlgPoint* AliAlgSensITS::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr return pnt; // } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgSensTOF.cxx b/Detectors/Align/src/AliAlgSensTOF.cxx index 07113440c9844..f04427d194faf 100644 --- a/Detectors/Align/src/AliAlgSensTOF.cxx +++ b/Detectors/Align/src/AliAlgSensTOF.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgSensTOF.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief TOF sensor #include "AliAlgSensTOF.h" #include "AliAlgAux.h" @@ -21,15 +21,19 @@ #include "AliTrackPointArray.h" #include "AliESDtrack.h" -ClassImp(AliAlgSensTOF) +ClassImp(o2::align::AliAlgSensTOF); -using namespace AliAlgAux; +using namespace o2::align::AliAlgAux; using namespace TMath; +namespace o2 +{ +namespace align +{ + //_________________________________________________________ -AliAlgSensTOF::AliAlgSensTOF(const char* name,Int_t vid, Int_t iid, Int_t isec) - :AliAlgSens(name,vid,iid) - ,fSector(isec) +AliAlgSensTOF::AliAlgSensTOF(const char* name, Int_t vid, Int_t iid, Int_t isec) + : AliAlgSens(name, vid, iid), fSector(isec) { // def c-tor } @@ -55,12 +59,12 @@ void AliAlgSensTOF::PrepareMatrixT2L() { // extract from geometry T2L matrix double alp = Sector2Alpha(fSector); - double loc[3]={0,0,0},glo[3]; - GetMatrixL2GIdeal().LocalToMaster(loc,glo); - double x = Sqrt(glo[0]*glo[0]+glo[1]*glo[1]); + double loc[3] = {0, 0, 0}, glo[3]; + GetMatrixL2GIdeal().LocalToMaster(loc, glo); + double x = Sqrt(glo[0] * glo[0] + glo[1] * glo[1]); TGeoHMatrix t2l; t2l.SetDx(x); - t2l.RotateZ(alp*RadToDeg()); + t2l.RotateZ(alp * RadToDeg()); const TGeoHMatrix& l2gi = GetMatrixL2GIdeal().Inverse(); t2l.MultiplyLeft(&l2gi); /* @@ -86,10 +90,10 @@ AliAlgPoint* AliAlgSensTOF::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr AliAlgPoint* pnt = det->GetPointFromPool(); pnt->SetSensor(this); // - double tra[3],locId[3],loc[3],traId[3], + double tra[3], locId[3], loc[3], traId[3], glo[3] = {trpArr->GetX()[pntId], trpArr->GetY()[pntId], trpArr->GetZ()[pntId]}; const TGeoHMatrix& matL2Grec = GetMatrixL2GReco(); // local to global matrix used for reconstruction - const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation + const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation // // >>>------------- here we fix the z by emulating Misalign action in the tracking frame ------>>> if (!trpArr->TestBit(AliTrackPointArray::kTOFBugFixed)) { @@ -101,26 +105,26 @@ AliAlgPoint* AliAlgSensTOF::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr mClAlgTrec.MultiplyLeft(&t2li); TGeoHMatrix mT2G; GetMatrixT2G(mT2G); - mT2G.MasterToLocal(glo,tra); // we are in tracking frame, with original wrong alignment - mClAlgTrec.MasterToLocal(tra,traId); // here we have almost ideal X,Y and wrong Z - const double *trans = mClAlgTrec.GetTranslation(); - const double *rotmt = mClAlgTrec.GetRotationMatrix(); - tra[2] = trans[2] + traId[0]*rotmt[6]+traId[1]*rotmt[7]+tra[2]*rotmt[8]; //we got misaligned Z - mT2G.LocalToMaster(tra,glo); + mT2G.MasterToLocal(glo, tra); // we are in tracking frame, with original wrong alignment + mClAlgTrec.MasterToLocal(tra, traId); // here we have almost ideal X,Y and wrong Z + const double* trans = mClAlgTrec.GetTranslation(); + const double* rotmt = mClAlgTrec.GetRotationMatrix(); + tra[2] = trans[2] + traId[0] * rotmt[6] + traId[1] * rotmt[7] + tra[2] * rotmt[8]; //we got misaligned Z + mT2G.LocalToMaster(tra, glo); // } // now continue as usual // <<<------------- here we fix the z by emulating Misalign action in the tracking frame ------<<< // // undo reco-time alignment - matL2Grec.MasterToLocal(glo,locId); // go to local frame using reco-time matrix, here we recover ideal measurement + matL2Grec.MasterToLocal(glo, locId); // go to local frame using reco-time matrix, here we recover ideal measurement // - GetMatrixClAlg().LocalToMaster(locId,loc); // apply alignment + GetMatrixClAlg().LocalToMaster(locId, loc); // apply alignment // - matT2L.MasterToLocal(loc,tra); // go to tracking frame + matT2L.MasterToLocal(loc, tra); // go to tracking frame // /* - double gloT[3]; + double gloT[3]; TGeoHMatrix t2g; GetMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); printf("\n%5d %s\n",GetVolID(), GetSymName()); @@ -135,7 +139,7 @@ AliAlgPoint* AliAlgSensTOF::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr // convert error TGeoHMatrix hcov; Double_t hcovel[9]; - const Float_t *pntcov = trpArr->GetCov()+pntId*6; // 6 elements per error matrix + const Float_t* pntcov = trpArr->GetCov() + pntId * 6; // 6 elements per error matrix hcovel[0] = double(pntcov[0]); hcovel[1] = double(pntcov[1]); hcovel[2] = double(pntcov[2]); @@ -148,20 +152,19 @@ AliAlgPoint* AliAlgSensTOF::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr hcov.SetRotation(hcovel); hcov.Multiply(&matL2Grec); const TGeoHMatrix& l2gi = matL2Grec.Inverse(); - hcov.MultiplyLeft(&l2gi); // errors in local frame + hcov.MultiplyLeft(&l2gi); // errors in local frame hcov.Multiply(&matT2L); const TGeoHMatrix& t2li = matT2L.Inverse(); - hcov.MultiplyLeft(&t2li); // errors in tracking frame + hcov.MultiplyLeft(&t2li); // errors in tracking frame // - Double_t *hcovscl = hcov.GetRotationMatrix(); - const double *sysE = GetAddError(); // additional syst error - pnt->SetYZErrTracking(hcovscl[4]+sysE[0]*sysE[0],hcovscl[5],hcovscl[8]+sysE[1]*sysE[1]); - } - else { // errors will be calculated just before using the point in the fit, using track info - pnt->SetYZErrTracking(0,0,0); + Double_t* hcovscl = hcov.GetRotationMatrix(); + const double* sysE = GetAddError(); // additional syst error + pnt->SetYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); + } else { // errors will be calculated just before using the point in the fit, using track info + pnt->SetYZErrTracking(0, 0, 0); pnt->SetNeedUpdateFromTrack(); } - pnt->SetXYZTracking(tra[0],tra[1],tra[2]); + pnt->SetXYZTracking(tra[0], tra[1], tra[2]); pnt->SetAlphaSens(GetAlpTracking()); pnt->SetXSens(GetXTracking()); pnt->SetDetID(det->GetDetID()); @@ -174,3 +177,6 @@ AliAlgPoint* AliAlgSensTOF::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr return pnt; // } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgSensTPC.cxx b/Detectors/Align/src/AliAlgSensTPC.cxx index e8ef91c9d2f23..07c062d2bdb00 100644 --- a/Detectors/Align/src/AliAlgSensTPC.cxx +++ b/Detectors/Align/src/AliAlgSensTPC.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgSensTPC.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief TPC sensor (chamber) #include "AliAlgSensTPC.h" #include "AliAlgAux.h" @@ -21,15 +21,19 @@ #include "AliAlgPoint.h" #include "AliAlgDet.h" -ClassImp(AliAlgSensTPC) +ClassImp(o2::align::AliAlgSensTPC) -using namespace AliAlgAux; + using namespace o2::align::AliAlgAux; using namespace TMath; +namespace o2 +{ +namespace align +{ + //_________________________________________________________ -AliAlgSensTPC::AliAlgSensTPC(const char* name,Int_t vid, Int_t iid, Int_t isec) - :AliAlgSens(name,vid,iid) - ,fSector(isec) +AliAlgSensTPC::AliAlgSensTPC(const char* name, Int_t vid, Int_t iid, Int_t isec) + : AliAlgSens(name, vid, iid), fSector(isec) { // def c-tor } @@ -54,12 +58,12 @@ void AliAlgSensTPC::PrepareMatrixT2L() { // extract from geometry T2L matrix double alp = Sector2Alpha(fSector); - double loc[3]={0,0,0},glo[3]; - GetMatrixL2GIdeal().LocalToMaster(loc,glo); - double x = Sqrt(glo[0]*glo[0]+glo[1]*glo[1]); + double loc[3] = {0, 0, 0}, glo[3]; + GetMatrixL2GIdeal().LocalToMaster(loc, glo); + double x = Sqrt(glo[0] * glo[0] + glo[1] * glo[1]); TGeoHMatrix t2l; t2l.SetDx(x); - t2l.RotateZ(alp*RadToDeg()); + t2l.RotateZ(alp * RadToDeg()); const TGeoHMatrix& l2gi = GetMatrixL2GIdeal().Inverse(); t2l.MultiplyLeft(&l2gi); /* @@ -82,20 +86,20 @@ AliAlgPoint* AliAlgSensTPC::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr AliAlgPoint* pnt = det->GetPointFromPool(); pnt->SetSensor(this); // - double tra[3],locId[3],loc[3], + double tra[3], locId[3], loc[3], glo[3] = {trpArr->GetX()[pntId], trpArr->GetY()[pntId], trpArr->GetZ()[pntId]}; const TGeoHMatrix& matL2Grec = GetMatrixL2GReco(); // local to global matrix used for reconstruction - const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation + const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation // // undo reco-time alignment - matL2Grec.MasterToLocal(glo,locId); // go to local frame using reco-time matrix, here we recover ideal measurement + matL2Grec.MasterToLocal(glo, locId); // go to local frame using reco-time matrix, here we recover ideal measurement // - GetMatrixClAlg().LocalToMaster(locId,loc); // apply alignment + GetMatrixClAlg().LocalToMaster(locId, loc); // apply alignment // - matT2L.MasterToLocal(loc,tra); // go to tracking frame + matT2L.MasterToLocal(loc, tra); // go to tracking frame // /* - double gloT[3]; + double gloT[3]; TGeoHMatrix t2g; GetMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); printf("\n%5d %s\n",GetVolID(), GetSymName()); @@ -110,7 +114,7 @@ AliAlgPoint* AliAlgSensTPC::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr // convert error TGeoHMatrix hcov; Double_t hcovel[9]; - const Float_t *pntcov = trpArr->GetCov()+pntId*6; // 6 elements per error matrix + const Float_t* pntcov = trpArr->GetCov() + pntId * 6; // 6 elements per error matrix hcovel[0] = double(pntcov[0]); hcovel[1] = double(pntcov[1]); hcovel[2] = double(pntcov[2]); @@ -123,20 +127,19 @@ AliAlgPoint* AliAlgSensTPC::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr hcov.SetRotation(hcovel); hcov.Multiply(&matL2Grec); const TGeoHMatrix& l2gi = matL2Grec.Inverse(); - hcov.MultiplyLeft(&l2gi); // errors in local frame + hcov.MultiplyLeft(&l2gi); // errors in local frame hcov.Multiply(&matT2L); const TGeoHMatrix& t2li = matT2L.Inverse(); - hcov.MultiplyLeft(&t2li); // errors in tracking frame + hcov.MultiplyLeft(&t2li); // errors in tracking frame // - Double_t *hcovscl = hcov.GetRotationMatrix(); - const double *sysE = GetAddError(); // additional syst error - pnt->SetYZErrTracking(hcovscl[4]+sysE[0]*sysE[0],hcovscl[5],hcovscl[8]+sysE[1]*sysE[1]); - } - else { // errors will be calculated just before using the point in the fit, using track info - pnt->SetYZErrTracking(0,0,0); + Double_t* hcovscl = hcov.GetRotationMatrix(); + const double* sysE = GetAddError(); // additional syst error + pnt->SetYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); + } else { // errors will be calculated just before using the point in the fit, using track info + pnt->SetYZErrTracking(0, 0, 0); pnt->SetNeedUpdateFromTrack(); } - pnt->SetXYZTracking(tra[0],tra[1],tra[2]); + pnt->SetXYZTracking(tra[0], tra[1], tra[2]); pnt->SetAlphaSens(GetAlpTracking()); pnt->SetXSens(GetXTracking()); pnt->SetDetID(det->GetDetID()); @@ -149,3 +152,6 @@ AliAlgPoint* AliAlgSensTPC::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr return pnt; // } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgSensTRD.cxx b/Detectors/Align/src/AliAlgSensTRD.cxx index 80764315d974a..9ccd7db502281 100644 --- a/Detectors/Align/src/AliAlgSensTRD.cxx +++ b/Detectors/Align/src/AliAlgSensTRD.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgSensTRD.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief TRD sensor #include "AliAlgSensTRD.h" #include "AliTRDgeometry.h" @@ -23,15 +23,19 @@ #include "AliESDtrack.h" #include "AliTrackerBase.h" -ClassImp(AliAlgSensTRD) +ClassImp(o2::align::AliAlgSensTRD) -using namespace AliAlgAux; + using namespace o2::align::AliAlgAux; using namespace TMath; +namespace o2 +{ +namespace align +{ + //_________________________________________________________ -AliAlgSensTRD::AliAlgSensTRD(const char* name,Int_t vid, Int_t iid, Int_t isec) - :AliAlgSens(name,vid,iid) - ,fSector(isec) +AliAlgSensTRD::AliAlgSensTRD(const char* name, Int_t vid, Int_t iid, Int_t isec) + : AliAlgSens(name, vid, iid), fSector(isec) { // def c-tor } @@ -56,12 +60,12 @@ void AliAlgSensTRD::PrepareMatrixT2L() { // extract from geometry T2L matrix double alp = Sector2Alpha(fSector); - double loc[3]={0,0,0},glo[3]; - GetMatrixL2GIdeal().LocalToMaster(loc,glo); - double x = Sqrt(glo[0]*glo[0]+glo[1]*glo[1]); + double loc[3] = {0, 0, 0}, glo[3]; + GetMatrixL2GIdeal().LocalToMaster(loc, glo); + double x = Sqrt(glo[0] * glo[0] + glo[1] * glo[1]); TGeoHMatrix t2l; t2l.SetDx(x); - t2l.RotateZ(alp*RadToDeg()); + t2l.RotateZ(alp * RadToDeg()); const TGeoHMatrix& l2gi = GetMatrixL2GIdeal().Inverse(); t2l.MultiplyLeft(&l2gi); /* @@ -76,37 +80,36 @@ void AliAlgSensTRD::PrepareMatrixT2L() } //____________________________________________ -void AliAlgSensTRD::DPosTraDParCalib(const AliAlgPoint* pnt,double* deriv,int calibID,const AliAlgVol* parent) const +void AliAlgSensTRD::DPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int calibID, const AliAlgVol* parent) const { // calculate point position X,Y,Z derivatives wrt calibration parameter calibID of given parent - // parent=0 means top detector object calibration + // parent=0 means top detector object calibration // - deriv[0]=deriv[1]=deriv[2]=0; + deriv[0] = deriv[1] = deriv[2] = 0; // if (!parent) { // TRD detector global calibration // switch (calibID) { - case AliAlgDetTRD::kCalibNRCCorrDzDtgl: - { // correction for Non-Crossing tracklets Z,Y shift: Z -> Z + calib*tgl, Y -> Y + calib*tgl*tilt*sign(tilt); - double sgYZ = pnt->GetYZErrTracking()[1]; // makes sense only for nonRC tracklets - if (Abs(sgYZ)>0.01) { - const double kTilt = 2.*TMath::DegToRad(); - deriv[2] = pnt->GetTrParamWSA()[AliAlgPoint::kParTgl]; - deriv[1] = deriv[2]*Sign(kTilt,sgYZ); - } - break; + case AliAlgDetTRD::kCalibNRCCorrDzDtgl: { // correction for Non-Crossing tracklets Z,Y shift: Z -> Z + calib*tgl, Y -> Y + calib*tgl*tilt*sign(tilt); + double sgYZ = pnt->GetYZErrTracking()[1]; // makes sense only for nonRC tracklets + if (Abs(sgYZ) > 0.01) { + const double kTilt = 2. * TMath::DegToRad(); + deriv[2] = pnt->GetTrParamWSA()[AliAlgPoint::kParTgl]; + deriv[1] = deriv[2] * Sign(kTilt, sgYZ); + } + break; } - // - case AliAlgDetTRD::kCalibDVT: - { // correction for bias in VdriftT - // error in VdriftT equivalent to shift in X at which Y measurement is evaluated - // Y -> Y + dVdriftT * tg_phi, where tg_phi is the slope of the track in YX plane - double snp=pnt->GetTrParamWSA(AliAlgPoint::kParSnp),slpY=snp/Sqrt((1-snp)*(1+snp)); - deriv[1] = slpY; - break; + // + case AliAlgDetTRD::kCalibDVT: { // correction for bias in VdriftT + // error in VdriftT equivalent to shift in X at which Y measurement is evaluated + // Y -> Y + dVdriftT * tg_phi, where tg_phi is the slope of the track in YX plane + double snp = pnt->GetTrParamWSA(AliAlgPoint::kParSnp), slpY = snp / Sqrt((1 - snp) * (1 + snp)); + deriv[1] = slpY; + break; } - default: break; + default: + break; }; } // @@ -121,20 +124,20 @@ AliAlgPoint* AliAlgSensTRD::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr AliAlgPoint* pnt = det->GetPointFromPool(); pnt->SetSensor(this); // - double tra[3],locId[3],loc[3], + double tra[3], locId[3], loc[3], glo[3] = {trpArr->GetX()[pntId], trpArr->GetY()[pntId], trpArr->GetZ()[pntId]}; const TGeoHMatrix& matL2Grec = GetMatrixL2GReco(); // local to global matrix used for reconstruction - const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation + const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation // // undo reco-time alignment - matL2Grec.MasterToLocal(glo,locId); // go to local frame using reco-time matrix, here we recover ideal measurement + matL2Grec.MasterToLocal(glo, locId); // go to local frame using reco-time matrix, here we recover ideal measurement // - GetMatrixClAlg().LocalToMaster(locId,loc); // apply alignment + GetMatrixClAlg().LocalToMaster(locId, loc); // apply alignment // - matT2L.MasterToLocal(loc,tra); // go to tracking frame + matT2L.MasterToLocal(loc, tra); // go to tracking frame // /* - double gloT[3]; + double gloT[3]; TGeoHMatrix t2g; GetMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); printf("\n%5d %s\n",GetVolID(), GetSymName()); @@ -149,7 +152,7 @@ AliAlgPoint* AliAlgSensTRD::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr // convert error TGeoHMatrix hcov; Double_t hcovel[9]; - const Float_t *pntcov = trpArr->GetCov()+pntId*6; // 6 elements per error matrix + const Float_t* pntcov = trpArr->GetCov() + pntId * 6; // 6 elements per error matrix hcovel[0] = double(pntcov[0]); hcovel[1] = double(pntcov[1]); hcovel[2] = double(pntcov[2]); @@ -162,20 +165,19 @@ AliAlgPoint* AliAlgSensTRD::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr hcov.SetRotation(hcovel); hcov.Multiply(&matL2Grec); const TGeoHMatrix& l2gi = matL2Grec; - hcov.MultiplyLeft(&l2gi); // errors in local frame + hcov.MultiplyLeft(&l2gi); // errors in local frame hcov.Multiply(&matT2L); const TGeoHMatrix& t2li = matT2L.Inverse(); - hcov.MultiplyLeft(&t2li); // errors in tracking frame + hcov.MultiplyLeft(&t2li); // errors in tracking frame // - Double_t *hcovscl = hcov.GetRotationMatrix(); - const double *sysE = GetAddError(); // additional syst error - pnt->SetYZErrTracking(hcovscl[4]+sysE[0]*sysE[0],hcovscl[5],hcovscl[8]+sysE[1]*sysE[1]); - } - else { // errors will be calculated just before using the point in the fit, using track info - pnt->SetYZErrTracking(0,0,0); + Double_t* hcovscl = hcov.GetRotationMatrix(); + const double* sysE = GetAddError(); // additional syst error + pnt->SetYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); + } else { // errors will be calculated just before using the point in the fit, using track info + pnt->SetYZErrTracking(0, 0, 0); pnt->SetNeedUpdateFromTrack(); } - pnt->SetXYZTracking(tra[0],tra[1],tra[2]); + pnt->SetXYZTracking(tra[0], tra[1], tra[2]); pnt->SetAlphaSens(GetAlpTracking()); pnt->SetXSens(GetXTracking()); pnt->SetDetID(det->GetDetID()); @@ -186,35 +188,36 @@ AliAlgPoint* AliAlgSensTRD::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr // Apply calibrations // Correction for NonRC points to account for most probable Z for non-crossing { - const double kTilt = 2.*TMath::DegToRad(); + const double kTilt = 2. * TMath::DegToRad(); // is it pad crrossing? - double* errYZ = (double*) pnt->GetYZErrTracking(); + double* errYZ = (double*)pnt->GetYZErrTracking(); double sgYZ = errYZ[1]; - if (TMath::Abs(sgYZ)<0.01) { // crossing - // increase errors since the error + if (TMath::Abs(sgYZ) < 0.01) { // crossing + // increase errors since the error const double* extraErrRC = det->GetExtraErrRC(); - errYZ[0] += extraErrRC[0]*extraErrRC[0]; - errYZ[2] += extraErrRC[1]*extraErrRC[1]; - } - else { // account for probability to not cross the row + errYZ[0] += extraErrRC[0] * extraErrRC[0]; + errYZ[2] += extraErrRC[1] * extraErrRC[1]; + } else { // account for probability to not cross the row double* pYZ = (double*)pnt->GetYZTracking(); - double corrZ = det->GetNonRCCorrDzDtglWithCal()*tr->GetTgl(); - pYZ[1] += corrZ; - pYZ[0] += corrZ*Sign(kTilt,sgYZ); // Y and Z are correlated + double corrZ = det->GetNonRCCorrDzDtglWithCal() * tr->GetTgl(); + pYZ[1] += corrZ; + pYZ[0] += corrZ * Sign(kTilt, sgYZ); // Y and Z are correlated } } // // Correction for DVT, equivalent to shift in X at which Y is evaluated: dY = tg_phi * dvt { double dvt = det->GetCorrDVTWithCal(); - if (Abs(dvt)>kAlmostZeroD) { + if (Abs(dvt) > kAlmostZeroD) { AliExternalTrackParam trc = *tr; - if (!trc.RotateParamOnly(GetAlpTracking())) return 0; - double snp = trc.GetSnpAt(pnt->GetXPoint(),AliTrackerBase::GetBz()); - if (Abs(snp)>kAlmostOneD) return 0; - double slpY = snp/Sqrt((1-snp)*(1+snp)); + if (!trc.RotateParamOnly(GetAlpTracking())) + return 0; + double snp = trc.GetSnpAt(pnt->GetXPoint(), AliTrackerBase::GetBz()); + if (Abs(snp) > kAlmostOneD) + return 0; + double slpY = snp / Sqrt((1 - snp) * (1 + snp)); double* pYZ = (double*)pnt->GetYZTracking(); - pYZ[0] += dvt*slpY; + pYZ[0] += dvt * slpY; } } // @@ -223,3 +226,6 @@ AliAlgPoint* AliAlgSensTRD::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr return pnt; // } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgSteer.cxx b/Detectors/Align/src/AliAlgSteer.cxx index 1097b8fbc3df4..7421e8f44a22d 100644 --- a/Detectors/Align/src/AliAlgSteer.cxx +++ b/Detectors/Align/src/AliAlgSteer.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgSteer.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief Steering class for the global alignment #include "AliAlgSteer.h" #include "AliLog.h" @@ -52,88 +52,80 @@ #include using namespace TMath; -using namespace AliAlgAux; +using namespace o2::align::AliAlgAux; using std::ifstream; -ClassImp(AliAlgSteer) +ClassImp(o2::align::AliAlgSteer); -const Char_t* AliAlgSteer::fgkMPDataExt = ".mille"; -const Char_t* AliAlgSteer::fgkDetectorName[AliAlgSteer::kNDetectors] = {"ITS", "TPC", "TRD", "TOF", "HMPID" }; -const Int_t AliAlgSteer::fgkSkipLayers[AliAlgSteer::kNLrSkip] = {AliGeomManager::kPHOS1,AliGeomManager::kPHOS2, - AliGeomManager::kMUON,AliGeomManager::kEMCAL}; +namespace o2 +{ +namespace align +{ -const Char_t* AliAlgSteer::fgkStatClName[AliAlgSteer::kNStatCl] = {"Inp: ","Acc: "}; -const Char_t* AliAlgSteer::fgkStatName[AliAlgSteer::kMaxStat] = - {"runs","Ev.Coll", "Ev.Cosm", "Trc.Coll", "Trc.Cosm"}; +const Char_t* AliAlgSteer::fgkMPDataExt = ".mille"; +const Char_t* AliAlgSteer::fgkDetectorName[AliAlgSteer::kNDetectors] = {"ITS", "TPC", "TRD", "TOF", "HMPID"}; +const Int_t AliAlgSteer::fgkSkipLayers[AliAlgSteer::kNLrSkip] = {AliGeomManager::kPHOS1, AliGeomManager::kPHOS2, + AliGeomManager::kMUON, AliGeomManager::kEMCAL}; +const Char_t* AliAlgSteer::fgkStatClName[AliAlgSteer::kNStatCl] = {"Inp: ", "Acc: "}; +const Char_t* AliAlgSteer::fgkStatName[AliAlgSteer::kMaxStat] = + {"runs", "Ev.Coll", "Ev.Cosm", "Trc.Coll", "Trc.Cosm"}; const Char_t* AliAlgSteer::fgkHStatName[AliAlgSteer::kNHVars] = { - "Runs","Ev.Inp","Ev.VtxOK","Tr.Inp","Tr.2Fit","Tr.2FitVC","Tr.2PrMat","Tr.2ResDer","Tr.Stored","Tr.Acc","Tr.ContRes"}; - + "Runs", "Ev.Inp", "Ev.VtxOK", "Tr.Inp", "Tr.2Fit", "Tr.2FitVC", "Tr.2PrMat", "Tr.2ResDer", "Tr.Stored", "Tr.Acc", "Tr.ContRes"}; //________________________________________________________________ AliAlgSteer::AliAlgSteer(const char* configMacro, int refRun) - :fNDet(0) - ,fNDOFs(0) - ,fRunNumber(-1) - ,fFieldOn(kFALSE) - ,fTracksType(kColl) - ,fAlgTrack(0) - ,fVtxSens(0) - ,fConstraints() - ,fSelEventSpecii(AliRecoParam::kCosmic|AliRecoParam::kLowMult|AliRecoParam::kHighMult|AliRecoParam::kDefault) - ,fCosmicSelStrict(kFALSE) - ,fVtxMinCont(-1) - ,fVtxMaxCont(-1) - ,fVtxMinContVC(10) - ,fMinITSClforVC(3) - ,fITSPattforVC(AliAlgDetITS::kSPDAny) - ,fMaxChi2forVC(10) - // - ,fGloParVal(0) - ,fGloParErr(0) - ,fGloParLab(0) - ,fOrderedLbl(0) - ,fLbl2ID(0) - ,fRefPoint(0) - ,fESDTree(0) - ,fESDEvent(0) - ,fVertex(0) - ,fControlFrac(1.0) - ,fMPOutType(kMille|kMPRec|kContR) - ,fMille(0) - ,fMPRecord(0) - ,fCResid(0) - ,fMPRecTree(0) - ,fResidTree(0) - ,fMPRecFile(0) - ,fResidFile(0) - ,fMilleDBuffer() - ,fMilleIBuffer() - ,fMPDatFileName("mpData") - ,fMPParFileName("mpParams.txt") - ,fMPConFileName("mpConstraints.txt") - ,fMPSteerFileName("mpSteer.txt") - ,fResidFileName("mpControlRes.root") - ,fMilleOutBin(kTRUE) - ,fDoKalmanResid(kTRUE) - // - ,fOutCDBPath("local://outOCDB") - ,fOutCDBComment("AliAlgSteer") - ,fOutCDBResponsible("") - // - ,fDOFStat(0) - ,fHistoStat(0) - // - ,fConfMacroName(configMacro) - ,fRecoOCDBConf("configRecoOCDB.C") - ,fRefOCDBConf("configRefOCDB.C") - ,fRefRunNumber(refRun) - ,fRefOCDBLoaded(0) - ,fUseRecoOCDB(kTRUE) + : fNDet(0), fNDOFs(0), fRunNumber(-1), fFieldOn(kFALSE), fTracksType(kColl), fAlgTrack(0), fVtxSens(0), fConstraints(), fSelEventSpecii(AliRecoParam::kCosmic | AliRecoParam::kLowMult | AliRecoParam::kHighMult | AliRecoParam::kDefault), fCosmicSelStrict(kFALSE), fVtxMinCont(-1), fVtxMaxCont(-1), fVtxMinContVC(10), fMinITSClforVC(3), fITSPattforVC(AliAlgDetITS::kSPDAny), fMaxChi2forVC(10) + // + , + fGloParVal(0), + fGloParErr(0), + fGloParLab(0), + fOrderedLbl(0), + fLbl2ID(0), + fRefPoint(0), + fESDTree(0), + fESDEvent(0), + fVertex(0), + fControlFrac(1.0), + fMPOutType(kMille | kMPRec | kContR), + fMille(0), + fMPRecord(0), + fCResid(0), + fMPRecTree(0), + fResidTree(0), + fMPRecFile(0), + fResidFile(0), + fMilleDBuffer(), + fMilleIBuffer(), + fMPDatFileName("mpData"), + fMPParFileName("mpParams.txt"), + fMPConFileName("mpConstraints.txt"), + fMPSteerFileName("mpSteer.txt"), + fResidFileName("mpControlRes.root"), + fMilleOutBin(kTRUE), + fDoKalmanResid(kTRUE) + // + , + fOutCDBPath("local://outOCDB"), + fOutCDBComment("AliAlgSteer"), + fOutCDBResponsible("") + // + , + fDOFStat(0), + fHistoStat(0) + // + , + fConfMacroName(configMacro), + fRecoOCDBConf("configRecoOCDB.C"), + fRefOCDBConf("configRefOCDB.C"), + fRefRunNumber(refRun), + fRefOCDBLoaded(0), + fUseRecoOCDB(kTRUE) { // def c-tor - for (int i=kNDetectors;i--;) { + for (int i = kNDetectors; i--;) { fDetectors[i] = 0; fDetPos[i] = -1; } @@ -143,15 +135,16 @@ AliAlgSteer::AliAlgSteer(const char* configMacro, int refRun) SetEtaMaxCosm(); SetMinDetAccColl(); SetMinDetAccCosm(); - for (int i=0;iProcessLine(Form(".x %s+g((AliAlgSteer*)%p)",fConfMacroName.Data(),this)); - if (!GetInitDOFsDone()) InitDOFs(); - if (!GetNDOFs()) AliFatalF("No DOFs found, initialization with %s failed", - fConfMacroName.Data()); - } - + gROOT->ProcessLine(Form(".x %s+g((AliAlgSteer*)%p)", fConfMacroName.Data(), this)); + if (!GetInitDOFsDone()) + InitDOFs(); + if (!GetNDOFs()) + AliFatalF("No DOFs found, initialization with %s failed", + fConfMacroName.Data()); + } } //________________________________________________________________ AliAlgSteer::~AliAlgSteer() { // d-tor - if (fMPRecFile) CloseMPRecOutput(); - if (fMille) CloseMilleOutput(); - if (fResidFile) CloseResidOutput(); + if (fMPRecFile) + CloseMPRecOutput(); + if (fMille) + CloseMilleOutput(); + if (fResidFile) + CloseResidOutput(); // delete fAlgTrack; delete[] fGloParVal; delete[] fGloParErr; delete[] fGloParLab; - for (int i=0;iPrepareMatrixL2GIdeal(); dofCnt += fVtxSens->GetNDOFs(); // - for (int i=0;iInitGeom(); - if (!dofCnt) AliFatal("No DOFs found"); + for (int i = 0; i < fNDet; i++) + dofCnt += fDetectors[i]->InitGeom(); + if (!dofCnt) + AliFatal("No DOFs found"); // // - for (int idt=0;idtIsDisabled()) continue; + if (!det || det->IsDisabled()) + continue; det->CacheReferenceOCDB(); } // fGloParVal = new Float_t[dofCnt]; fGloParErr = new Float_t[dofCnt]; - fGloParLab = new Int_t[dofCnt]; - fOrderedLbl = new Int_t[dofCnt]; - fLbl2ID = new Int_t[dofCnt]; - memset(fGloParVal,0,dofCnt*sizeof(Float_t)); - memset(fGloParErr,0,dofCnt*sizeof(Float_t)); - memset(fGloParLab,0,dofCnt*sizeof(Int_t)); - memset(fOrderedLbl,0,dofCnt*sizeof(Int_t)); - memset(fLbl2ID,0,dofCnt*sizeof(Int_t)); + fGloParLab = new Int_t[dofCnt]; + fOrderedLbl = new Int_t[dofCnt]; + fLbl2ID = new Int_t[dofCnt]; + memset(fGloParVal, 0, dofCnt * sizeof(Float_t)); + memset(fGloParErr, 0, dofCnt * sizeof(Float_t)); + memset(fGloParLab, 0, dofCnt * sizeof(Int_t)); + memset(fOrderedLbl, 0, dofCnt * sizeof(Int_t)); + memset(fLbl2ID, 0, dofCnt * sizeof(Int_t)); AssignDOFs(); - AliInfoF("Booked %d global parameters",dofCnt); + AliInfoF("Booked %d global parameters", dofCnt); // SetInitGeomDone(); // @@ -242,7 +244,7 @@ void AliAlgSteer::InitDOFs() // scan all free global parameters, link detectors to array of params // if (GetInitDOFsDone()) { - AliInfoF("InitDOFs was already done, just reassigning %d DOFs arrays/labels",fNDOFs); + AliInfoF("InitDOFs was already done, just reassigning %d DOFs arrays/labels", fNDOFs); AssignDOFs(); return; } @@ -253,18 +255,19 @@ void AliAlgSteer::InitDOFs() // int nact = 0; fVtxSens->InitDOFs(); - for (int i=0;iInitDOFs(); - if (det->IsDisabled()) continue; + if (det->IsDisabled()) + continue; nact++; ndfAct += det->GetNDOFs(); } - for (int i=0;i0) ndfOld = fNDOFs; + if (fNDOFs > 0) + ndfOld = fNDOFs; fNDOFs = 0; // - fVtxSens->AssignDOFs(fNDOFs,fGloParVal,fGloParErr,fGloParLab); + fVtxSens->AssignDOFs(fNDOFs, fGloParVal, fGloParErr, fGloParLab); // - for (int idt=0;idtIsDisabled()) continue; fNDOFs += det->AssignDOFs(); } - AliInfoF("Assigned parameters/labels arrays for %d DOFs",fNDOFs); - if (ndfOld>-1 && ndfOld != fNDOFs) AliErrorF("Recalculated NDOFs=%d not equal to saved NDOFs=%d",fNDOFs,ndfOld); + AliInfoF("Assigned parameters/labels arrays for %d DOFs", fNDOFs); + if (ndfOld > -1 && ndfOld != fNDOFs) + AliErrorF("Recalculated NDOFs=%d not equal to saved NDOFs=%d", fNDOFs, ndfOld); // // build Lbl <-> parID table - Sort(fNDOFs,fGloParLab,fLbl2ID,kFALSE); // sort in increasing order - for (int i=fNDOFs;i--;) fOrderedLbl[i] = fGloParLab[fLbl2ID[i]]; + Sort(fNDOFs, fGloParLab, fLbl2ID, kFALSE); // sort in increasing order + for (int i = fNDOFs; i--;) + fOrderedLbl[i] = fGloParLab[fLbl2ID[i]]; // } @@ -303,26 +310,40 @@ void AliAlgSteer::AddDetector(UInt_t id, AliAlgDet* det) { // add detector participating in the alignment, optionally constructed externally // - if (!fRefOCDBLoaded) LoadRefOCDB(); + if (!fRefOCDBLoaded) + LoadRefOCDB(); // - if (id>=kNDetectors) AliFatalF("Detector typeID %d exceeds allowed range %d:%d", - id,0,kNDetectors-1); + if (id >= kNDetectors) + AliFatalF("Detector typeID %d exceeds allowed range %d:%d", + id, 0, kNDetectors - 1); // - if (fDetPos[id]!=-1) AliFatalF("Detector %d was already added",id); + if (fDetPos[id] != -1) + AliFatalF("Detector %d was already added", id); if (!det) { - switch(id) { - case kITS: det = new AliAlgDetITS(GetDetNameByDetID(kITS)); break; - case kTPC: det = new AliAlgDetTPC(GetDetNameByDetID(kTPC)); break; - case kTRD: det = new AliAlgDetTRD(GetDetNameByDetID(kTRD)); break; - case kTOF: det = new AliAlgDetTOF(GetDetNameByDetID(kTOF)); break; - default: AliFatalF("%d not implemented yet",id); break; + switch (id) { + case kITS: + det = new AliAlgDetITS(GetDetNameByDetID(kITS)); + break; + case kTPC: + det = new AliAlgDetTPC(GetDetNameByDetID(kTPC)); + break; + case kTRD: + det = new AliAlgDetTRD(GetDetNameByDetID(kTRD)); + break; + case kTOF: + det = new AliAlgDetTOF(GetDetNameByDetID(kTOF)); + break; + default: + AliFatalF("%d not implemented yet", id); + break; }; } // fDetectors[fNDet] = det; fDetPos[id] = fNDet; det->SetAlgSteer(this); - for (int i=0;iIsObligatory(i)); + for (int i = 0; i < kNTrackTypes; i++) + SetObligatoryDetector(id, i, det->IsObligatory(i)); fNDet++; // } @@ -335,29 +356,31 @@ void AliAlgSteer::AddDetector(AliAlgDet* det) } //_________________________________________________________ -Bool_t AliAlgSteer::CheckDetectorPattern(UInt_t patt) const +Bool_t AliAlgSteer::CheckDetectorPattern(UInt_t patt) const { //validate detector pattern - return ((patt & fObligatoryDetPattern[fTracksType]) == - fObligatoryDetPattern[fTracksType]) && - NumberOfBitsSet(patt)>=fMinDetAcc[fTracksType]; + return ((patt & fObligatoryDetPattern[fTracksType]) == + fObligatoryDetPattern[fTracksType]) && + NumberOfBitsSet(patt) >= fMinDetAcc[fTracksType]; } //_________________________________________________________ -Bool_t AliAlgSteer::CheckDetectorPoints(const int* npsel) const +Bool_t AliAlgSteer::CheckDetectorPoints(const int* npsel) const { //validate detectors pattern according to number of selected points int ndOK = 0; - for (int idt=0;idtIsDisabled(fTracksType)) continue; - if (npsel[idt]GetNPointsSel(fTracksType)) { - if (det->IsObligatory(fTracksType)) return kFALSE; + if (!det || det->IsDisabled(fTracksType)) + continue; + if (npsel[idt] < det->GetNPointsSel(fTracksType)) { + if (det->IsObligatory(fTracksType)) + return kFALSE; continue; } ndOK++; } - return ndOK>=fMinDetAcc[fTracksType]; + return ndOK >= fMinDetAcc[fTracksType]; } //_________________________________________________________ @@ -366,19 +389,25 @@ UInt_t AliAlgSteer::AcceptTrack(const AliESDtrack* esdTr, Bool_t strict) const // decide if the track should be processed AliAlgDet* det = 0; UInt_t detAcc = 0; - if (fFieldOn && esdTr->Pt()Eta())>fEtaMax[fTracksType]) return 0; - // - for (int idet=0;idetIsDisabled(fTracksType)) continue; - if (!det->AcceptTrack(esdTr,fTracksType)) { - if (strict && det->IsObligatory(fTracksType)) return 0; - else continue; + if (fFieldOn && esdTr->Pt() < fPtMin[fTracksType]) + return 0; + if (Abs(esdTr->Eta()) > fEtaMax[fTracksType]) + return 0; + // + for (int idet = 0; idet < kNDetectors; idet++) { + if (!(det = GetDetectorByDetID(idet)) || det->IsDisabled(fTracksType)) + continue; + if (!det->AcceptTrack(esdTr, fTracksType)) { + if (strict && det->IsObligatory(fTracksType)) + return 0; + else + continue; } // - detAcc |= 0x1<GetField() || - !SmallerAbs(fESDEvent->GetMagneticField()-AliTrackerBase::GetBz(),5e-4)) ) { + if (fESDEvent && + (!TGeoGlobalMagField::Instance()->GetField() || + !SmallerAbs(fESDEvent->GetMagneticField() - AliTrackerBase::GetBz(), 5e-4))) { fESDEvent->InitMagneticField(); } } @@ -419,63 +451,65 @@ Bool_t AliAlgSteer::ProcessEvent(const AliESDEvent* esdEv) { // process event const int kProcStatFreq = 100; - static int evCount=0; - if (!(evCount%kProcStatFreq)) { + static int evCount = 0; + if (!(evCount % kProcStatFreq)) { ProcInfo_t procInfo; gSystem->GetProcInfo(&procInfo); AliInfoF("ProcStat: CPUusr: %6d CPUsys: %6d RMem:%6d VMem:%6d", - int(procInfo.fCpuUser), int(procInfo.fCpuSys), - int(procInfo.fMemResident/1024),int(procInfo.fMemVirtual/1024)); + int(procInfo.fCpuUser), int(procInfo.fCpuSys), + int(procInfo.fMemResident / 1024), int(procInfo.fMemVirtual / 1024)); } evCount++; // SetESDEvent(esdEv); // - if (esdEv->GetRunNumber() != GetRunNumber()) SetRunNumber(esdEv->GetRunNumber()); + if (esdEv->GetRunNumber() != GetRunNumber()) + SetRunNumber(esdEv->GetRunNumber()); // - if (!(esdEv->GetEventSpecie()&fSelEventSpecii)) { -#if DEBUG>2 - AliInfoF("Reject: specie does not match, allowed 0x%0x",fSelEventSpecii); + if (!(esdEv->GetEventSpecie() & fSelEventSpecii)) { +#if DEBUG > 2 + AliInfoF("Reject: specie does not match, allowed 0x%0x", fSelEventSpecii); #endif return kFALSE; } // - SetCosmic(esdEv->GetEventSpecie()==AliRecoParam::kCosmic || - (esdEv->GetNumberOfCosmicTracks()>0 && !esdEv->GetPrimaryVertexTracks()->GetStatus())); + SetCosmic(esdEv->GetEventSpecie() == AliRecoParam::kCosmic || + (esdEv->GetNumberOfCosmicTracks() > 0 && !esdEv->GetPrimaryVertexTracks()->GetStatus())); // - FillStatHisto( kEvInp ); + FillStatHisto(kEvInp); // -#if DEBUG>2 +#if DEBUG > 2 AliInfoF("Processing event %d of ev.specie %d -> Ntr: %4d NtrCosm: %d", - esdEv->GetEventNumberInFile(),esdEv->GetEventSpecie(), - esdEv->GetNumberOfTracks(),esdEv->GetNumberOfCosmicTracks()); + esdEv->GetEventNumberInFile(), esdEv->GetEventSpecie(), + esdEv->GetNumberOfTracks(), esdEv->GetNumberOfCosmicTracks()); #endif // - SetFieldOn(Abs(esdEv->GetMagneticField())>kAlmost0Field); - if (!IsCosmic() && !CheckSetVertex(esdEv->GetPrimaryVertexTracks())) return kFALSE; - FillStatHisto( kEvVtx ); + SetFieldOn(Abs(esdEv->GetMagneticField()) > kAlmost0Field); + if (!IsCosmic() && !CheckSetVertex(esdEv->GetPrimaryVertexTracks())) + return kFALSE; + FillStatHisto(kEvVtx); // - int ntr=0,accTr = 0; + int ntr = 0, accTr = 0; if (IsCosmic()) { fStat[kInpStat][kEventCosm]++; ntr = esdEv->GetNumberOfCosmicTracks(); - FillStatHisto( kTrackInp, ntr); - for (int itr=0;itrGetCosmicTrack(itr)); + FillStatHisto(kTrackInp, ntr); + for (int itr = 0; itr < ntr; itr++) { + accTr += ProcessTrack(esdEv->GetCosmicTrack(itr)); } - if (accTr) fStat[kAccStat][kEventCosm]++; - } - else { + if (accTr) + fStat[kAccStat][kEventCosm]++; + } else { fStat[kInpStat][kEventColl]++; ntr = esdEv->GetNumberOfTracks(); - FillStatHisto( kTrackInp, ntr); - for (int itr=0;itrGetTrack(itr)); + accTr += ProcessTrack(esdEv->GetTrack(itr)); /* if (accTr>accTrOld && fCResid) { int ndf = fCResid->GetNPoints()*2-5; - if (fCResid->GetChi2()/ndf>20 || !fCResid->GetKalmanDone() + if (fCResid->GetChi2()/ndf>20 || !fCResid->GetKalmanDone() || fCResid->GetChi2K()/ndf>20) { printf("BAD FIT for %d\n",itr); } @@ -483,14 +517,15 @@ Bool_t AliAlgSteer::ProcessEvent(const AliESDEvent* esdEv) } */ } - if (accTr) fStat[kAccStat][kEventColl]++; - } + if (accTr) + fStat[kAccStat][kEventColl]++; + } // - FillStatHisto( kTrackAcc, accTr); + FillStatHisto(kTrackAcc, accTr); // if (accTr) { AliInfoF("Processed event %d of ev.specie %d -> Accepted: %4d of %4d tracks", - esdEv->GetEventNumberInFile(),esdEv->GetEventSpecie(),accTr,ntr); + esdEv->GetEventNumberInFile(), esdEv->GetEventSpecie(), accTr, ntr); } return kTRUE; } @@ -506,73 +541,86 @@ Bool_t AliAlgSteer::ProcessTrack(const AliESDtrack* esdTr) // int nPnt = 0; const AliESDfriendTrack* trF = esdTr->GetFriendTrack(); - if (!trF) return kFALSE; + if (!trF) + return kFALSE; const AliTrackPointArray* trPoints = trF->GetTrackPointArray(); - if (!trPoints || (nPnt=trPoints->GetNPoints())<1) return kFALSE; + if (!trPoints || (nPnt = trPoints->GetNPoints()) < 1) + return kFALSE; // UInt_t detAcc = AcceptTrack(esdTr); - if (!detAcc) return kFALSE; + if (!detAcc) + return kFALSE; // ResetDetectors(); fAlgTrack->Clear(); // - // process the track points for each detector, + // process the track points for each detector, AliAlgDet* det = 0; - for (int idet=0;idetProcessPoints(esdTr, fAlgTrack) < det->GetNPointsSel(kColl)) { - detAcc &= ~(0x1<IsObligatory(kColl)) return kFALSE; + detAcc &= ~(0x1 << idet); // did not survive, suppress detector in the track + if (det->IsObligatory(kColl)) + return kFALSE; } - if (NumberOfBitsSet(detAcc)GetNPoints()GetNPoints() < GetMinPoints()) + return kFALSE; // fill needed points (tracking frame) in the fAlgTrack fRefPoint->SetContainsMeasurement(kFALSE); fRefPoint->SetContainsMaterial(kFALSE); fAlgTrack->AddPoint(fRefPoint); // reference point which the track will refer to // fAlgTrack->CopyFrom(esdTr); - if (!GetFieldOn()) fAlgTrack->ImposePtBOff(fDefPtBOff[AliAlgAux::kColl]); - fAlgTrack->SetFieldON( GetFieldOn() ); + if (!GetFieldOn()) + fAlgTrack->ImposePtBOff(fDefPtBOff[AliAlgAux::kColl]); + fAlgTrack->SetFieldON(GetFieldOn()); fAlgTrack->SortPoints(); // // at this stage the points are sorted from maxX to minX, the latter corresponding to // reference point (e.g. vertex) with X~0. The fAlgTrack->GetInnerPointID() points on it, - // hence fAlgTrack->GetInnerPointID() is the 1st really measured point. We will set the - // alpha of the reference point to alpha of the barrel sector corresponding to this + // hence fAlgTrack->GetInnerPointID() is the 1st really measured point. We will set the + // alpha of the reference point to alpha of the barrel sector corresponding to this // 1st measured point - int pntMeas = fAlgTrack->GetInnerPointID()-1; - if (pntMeas<0) { // this should not happen + int pntMeas = fAlgTrack->GetInnerPointID() - 1; + if (pntMeas < 0) { // this should not happen fAlgTrack->Print("p meas"); AliFatal("AliAlgTrack->GetInnerPointID() cannot be 0"); } // do we want to add the vertex as a measured point ? if (!AddVertexConstraint()) { // no constrain, just reference point w/o measurement - fRefPoint->SetXYZTracking(0,0,0); + fRefPoint->SetXYZTracking(0, 0, 0); fRefPoint->SetAlphaSens(Sector2Alpha(fAlgTrack->GetPoint(pntMeas)->GetAliceSector())); - } - else FillStatHisto( kTrackFitInpVC ); + } else + FillStatHisto(kTrackFitInpVC); // - FillStatHisto( kTrackFitInp ); - if (!fAlgTrack->IniFit()) return kFALSE; - FillStatHisto( kTrackProcMatInp ); - if (!fAlgTrack->ProcessMaterials()) return kFALSE; + FillStatHisto(kTrackFitInp); + if (!fAlgTrack->IniFit()) + return kFALSE; + FillStatHisto(kTrackProcMatInp); + if (!fAlgTrack->ProcessMaterials()) + return kFALSE; fAlgTrack->DefineDOFs(); // - FillStatHisto( kTrackResDerInp ); - if (!fAlgTrack->CalcResidDeriv()) return kFALSE; + FillStatHisto(kTrackResDerInp); + if (!fAlgTrack->CalcResidDeriv()) + return kFALSE; // - if (!StoreProcessedTrack( fMPOutType&~kContR )) return kFALSE; // store derivatives for MP + if (!StoreProcessedTrack(fMPOutType & ~kContR)) + return kFALSE; // store derivatives for MP // - if (GetProduceControlRes() && // need control residuals, ignore selection fraction if this is the - (fMPOutType==kContR || gRandom->Rndm()Rndm() < fControlFrac)) { // output requested + if (!TestLocalSolution() || !StoreProcessedTrack(kContR)) + return kFALSE; } // - FillStatHisto( kTrackStore ); + FillStatHisto(kTrackStore); // fStat[kAccStat][kTrackColl]++; // @@ -580,27 +628,27 @@ Bool_t AliAlgSteer::ProcessTrack(const AliESDtrack* esdTr) } //_________________________________________________________ -Bool_t AliAlgSteer::CheckSetVertex(const AliESDVertex *vtx) -{ +Bool_t AliAlgSteer::CheckSetVertex(const AliESDVertex* vtx) +{ // vertex selection/constraint check if (!vtx) { fVertex = 0; return kTRUE; } int ncont = vtx->GetNContributors(); - if (fVtxMinCont>0 && fVtxMinCont>ncont) { -#if DEBUG>2 - AliInfoF("Rejecting event with %d vertex contributors (min %d asked)",ncont,fVtxMinCont); + if (fVtxMinCont > 0 && fVtxMinCont > ncont) { +#if DEBUG > 2 + AliInfoF("Rejecting event with %d vertex contributors (min %d asked)", ncont, fVtxMinCont); #endif return kFALSE; } - if (fVtxMaxCont>0 && ncont>fVtxMaxCont) { -#if DEBUG>2 - AliInfoF("Rejecting event with %d vertex contributors (max %d asked)",ncont,fVtxMaxCont); + if (fVtxMaxCont > 0 && ncont > fVtxMaxCont) { +#if DEBUG > 2 + AliInfoF("Rejecting event with %d vertex contributors (max %d asked)", ncont, fVtxMaxCont); #endif return kFALSE; } - fVertex = (ncont>=fVtxMinContVC) ? vtx : 0; // use vertex as a constraint + fVertex = (ncont >= fVtxMinContVC) ? vtx : 0; // use vertex as a constraint return kTRUE; } @@ -614,85 +662,97 @@ Bool_t AliAlgSteer::ProcessTrack(const AliESDCosmicTrack* cosmTr) fESDTrack[0] = 0; fESDTrack[1] = 0; // - for (int leg=kNCosmLegs;leg--;) { - const AliESDtrack* esdTr = - fESDEvent->GetTrack(leg==kCosmLow ? - cosmTr->GetESDLowerTrackIndex():cosmTr->GetESDUpperTrackIndex()); + for (int leg = kNCosmLegs; leg--;) { + const AliESDtrack* esdTr = + fESDEvent->GetTrack(leg == kCosmLow ? cosmTr->GetESDLowerTrackIndex() : cosmTr->GetESDUpperTrackIndex()); const AliESDfriendTrack* trF = esdTr->GetFriendTrack(); - if (!trF) return kFALSE; + if (!trF) + return kFALSE; const AliTrackPointArray* trPoints = trF->GetTrackPointArray(); - if (!trPoints || (nPnt+=trPoints->GetNPoints())<1) return kFALSE; + if (!trPoints || (nPnt += trPoints->GetNPoints()) < 1) + return kFALSE; // fESDTrack[leg] = esdTr; } // UInt_t detAcc = AcceptTrackCosmic(fESDTrack); - if (!detAcc) return kFALSE; + if (!detAcc) + return kFALSE; // ResetDetectors(); fAlgTrack->Clear(); fAlgTrack->SetCosmic(kTRUE); // - // process the track points for each detector, + // process the track points for each detector, // fill needed points (tracking frame) in the fAlgTrack fRefPoint->SetContainsMeasurement(kFALSE); - fRefPoint->SetContainsMaterial(kFALSE); + fRefPoint->SetContainsMaterial(kFALSE); fAlgTrack->AddPoint(fRefPoint); // reference point which the track will refer to // AliAlgDet* det = 0; Int_t npsel[kNDetectors] = {0}; - for (int nPleg=0,leg=kNCosmLegs;leg--;) { - for (int idet=0;idetProcessPoints(fESDTrack[leg],fAlgTrack, leg==kCosmUp); - if (npGetNPointsSel(kCosm) && fCosmicSelStrict && - det->IsObligatory(kCosm)) return kFALSE; + int np = det->ProcessPoints(fESDTrack[leg], fAlgTrack, leg == kCosmUp); + if (np < det->GetNPointsSel(kCosm) && fCosmicSelStrict && + det->IsObligatory(kCosm)) + return kFALSE; npsel[idet] += np; nPleg += np; } - if (nPlegCopyFrom(cosmTr); - if (!GetFieldOn()) fAlgTrack->ImposePtBOff(fDefPtBOff[AliAlgAux::kCosm]); - fAlgTrack->SetFieldON( GetFieldOn() ); + if (!GetFieldOn()) + fAlgTrack->ImposePtBOff(fDefPtBOff[AliAlgAux::kCosm]); + fAlgTrack->SetFieldON(GetFieldOn()); fAlgTrack->SortPoints(); - // + // // at this stage the points are sorted from maxX to minX, the latter corresponding to // reference point (e.g. vertex) with X~0. The fAlgTrack->GetInnerPointID() points on it, - // hence fAlgTrack->GetInnerPointID() is the 1st really measured point. We will set the - // alpha of the reference point to alpha of the barrel sector corresponding to this + // hence fAlgTrack->GetInnerPointID() is the 1st really measured point. We will set the + // alpha of the reference point to alpha of the barrel sector corresponding to this // 1st measured point - int pntMeas = fAlgTrack->GetInnerPointID()-1; - if (pntMeas<0) { // this should not happen + int pntMeas = fAlgTrack->GetInnerPointID() - 1; + if (pntMeas < 0) { // this should not happen fAlgTrack->Print("p meas"); AliFatal("AliAlgTrack->GetInnerPointID() cannot be 0"); } fRefPoint->SetAlphaSens(Sector2Alpha(fAlgTrack->GetPoint(pntMeas)->GetAliceSector())); - // - FillStatHisto( kTrackFitInp ); - if (!fAlgTrack->IniFit()) return kFALSE; // - FillStatHisto( kTrackProcMatInp ); - if (!fAlgTrack->ProcessMaterials()) return kFALSE; + FillStatHisto(kTrackFitInp); + if (!fAlgTrack->IniFit()) + return kFALSE; + // + FillStatHisto(kTrackProcMatInp); + if (!fAlgTrack->ProcessMaterials()) + return kFALSE; fAlgTrack->DefineDOFs(); // - FillStatHisto( kTrackResDerInp ); - if (!fAlgTrack->CalcResidDeriv()) return kFALSE; + FillStatHisto(kTrackResDerInp); + if (!fAlgTrack->CalcResidDeriv()) + return kFALSE; // - if (!StoreProcessedTrack( fMPOutType&~kContR )) return kFALSE; // store derivatives for MP + if (!StoreProcessedTrack(fMPOutType & ~kContR)) + return kFALSE; // store derivatives for MP // - if (GetProduceControlRes() && // need control residuals, ignore selection fraction if this is the - (fMPOutType==kContR || gRandom->Rndm()Rndm() < fControlFrac)) { // output requested + if (!TestLocalSolution() || !StoreProcessedTrack(kContR)) + return kFALSE; } // - FillStatHisto( kTrackStore ); + FillStatHisto(kTrackStore); fStat[kAccStat][kTrackCosm]++; return kTRUE; } @@ -702,9 +762,12 @@ Bool_t AliAlgSteer::StoreProcessedTrack(Int_t what) { // write alignment track Bool_t res = kTRUE; - if ((what&kMille)) res &= FillMilleData(); - if ((what&kMPRec)) res &= FillMPRecData(); - if ((what&kContR)) res &= FillControlData(); + if ((what & kMille)) + res &= FillMilleData(); + if ((what & kMPRec)) + res &= FillMPRecData(); + if ((what & kContR)) + res &= FillControlData(); // return res; } @@ -714,81 +777,87 @@ Bool_t AliAlgSteer::FillMilleData() { // store MP2 data in Mille format if (!fMille) { - TString mo = Form("%s%s",fMPDatFileName.Data(),fgkMPDataExt); - fMille = new Mille(mo.Data(),fMilleOutBin); - if (!fMille) AliFatalF("Failed to create output file %s",mo.Data()); + TString mo = Form("%s%s", fMPDatFileName.Data(), fgkMPDataExt); + fMille = new Mille(mo.Data(), fMilleOutBin); + if (!fMille) + AliFatalF("Failed to create output file %s", mo.Data()); } // if (!fAlgTrack->GetDerivDone()) { AliError("Track derivatives are not yet evaluated"); return kFALSE; } - int np(fAlgTrack->GetNPoints()),nDGloTot(0); // total number global derivatives stored - int nParETP(fAlgTrack->GetNLocExtPar()); // numnber of local parameters for reference track param - int nVarLoc(fAlgTrack->GetNLocPar()); // number of local degrees of freedom in the track - float* buffDL(0),*buffDG(0); // faster acces arrays - int *buffI(0); + int np(fAlgTrack->GetNPoints()), nDGloTot(0); // total number global derivatives stored + int nParETP(fAlgTrack->GetNLocExtPar()); // numnber of local parameters for reference track param + int nVarLoc(fAlgTrack->GetNLocPar()); // number of local degrees of freedom in the track + float *buffDL(0), *buffDG(0); // faster acces arrays + int* buffI(0); // const int* gloParID(fAlgTrack->GetGloParID()); // IDs of global DOFs this track depends on - for (int ip=0;ipGetPoint(ip); if (pnt->ContainsMeasurement()) { int gloOffs = pnt->GetDGloOffs(); // 1st entry of global derivatives for this point - int nDGlo = pnt->GetNGloDOFs(); // number of global derivatives (number of DOFs it depends on) - if (!pnt->IsStatOK()) pnt->IncrementStat(); + int nDGlo = pnt->GetNGloDOFs(); // number of global derivatives (number of DOFs it depends on) + if (!pnt->IsStatOK()) + pnt->IncrementStat(); // check buffer sizes { - if (fMilleDBuffer.GetSize()GetDResDLoc(idim,ip); // array of Dresidual/Dparams_loc - // derivatives over reference track parameters - for (int j=0;jGetMinLocVarID(), lp1 = pnt->GetMaxLocVarID(); - for (int j=lp0;jGetDResDGlo(idim, gloOffs); - const int* gloIDP(gloParID + gloOffs); - for (int j=0;jmille(nVarLoc,buffDL, nGlo,buffDG, buffI, - fAlgTrack->GetResidual(idim,ip),Sqrt(pnt->GetErrDiag(idim))); - nDGloTot += nGlo; - // + for (int idim = 0; idim < 2; idim++) { // 2 dimensional orthogonal measurement + memset(buffDL, 0, nVarLoc * sizeof(float)); + const double* deriv = fAlgTrack->GetDResDLoc(idim, ip); // array of Dresidual/Dparams_loc + // derivatives over reference track parameters + for (int j = 0; j < nParETP; j++) + buffDL[j] = (IsZeroAbs(deriv[j])) ? 0 : deriv[j]; + // + // point may depend on material variables within these limits + int lp0 = pnt->GetMinLocVarID(), lp1 = pnt->GetMaxLocVarID(); + for (int j = lp0; j < lp1; j++) + buffDL[j] = (IsZeroAbs(deriv[j])) ? 0 : deriv[j]; + // + // derivatives over global params: this array can be 0-suppressed, no need to reset + int nGlo(0); + deriv = fAlgTrack->GetDResDGlo(idim, gloOffs); + const int* gloIDP(gloParID + gloOffs); + for (int j = 0; j < nDGlo; j++) { + if (!IsZeroAbs(deriv[j])) { + buffDG[nGlo] = deriv[j]; // value of derivative + buffI[nGlo++] = GetGloParLab(gloIDP[j]); // global DOF ID + 1 (Millepede needs positive labels) + } + } + fMille->mille(nVarLoc, buffDL, nGlo, buffDG, buffI, + fAlgTrack->GetResidual(idim, ip), Sqrt(pnt->GetErrDiag(idim))); + nDGloTot += nGlo; + // } } - if (pnt->ContainsMaterial()) { // material point can add 4 or 5 otrhogonal pseudo-measurements - memset(buffDL,0,nVarLoc*sizeof(float)); - int nmatpar = pnt->GetNMatPar(); // residuals (correction expectation value) + if (pnt->ContainsMaterial()) { // material point can add 4 or 5 otrhogonal pseudo-measurements + memset(buffDL, 0, nVarLoc * sizeof(float)); + int nmatpar = pnt->GetNMatPar(); // residuals (correction expectation value) // const float* expMatCorr = pnt->GetMatCorrExp(); // expected corrections (diagonalized) - const float* expMatCov = pnt->GetMatCorrCov(); // their diagonalized error matrix - int offs = pnt->GetMaxLocVarID() - nmatpar; // start of material variables + const float* expMatCov = pnt->GetMatCorrCov(); // their diagonalized error matrix + int offs = pnt->GetMaxLocVarID() - nmatpar; // start of material variables // here all derivatives are 1 = dx/dx - for (int j=0;jmille(nVarLoc,buffDL,0,buffDG,buffI,expMatCorr[j],Sqrt(expMatCov[j])); - // expectation for MS effect is 0 - fMille->mille(nVarLoc,buffDL,0,buffDG,buffI,0,Sqrt(expMatCov[j])); - buffDL[j1] = 0.0; // reset buffer + for (int j = 0; j < nmatpar; j++) { // mat. "measurements" don't depend on global params + int j1 = j + offs; + buffDL[j1] = 1.0; // only 1 non-0 derivative + //fMille->mille(nVarLoc,buffDL,0,buffDG,buffI,expMatCorr[j],Sqrt(expMatCov[j])); + // expectation for MS effect is 0 + fMille->mille(nVarLoc, buffDL, 0, buffDG, buffI, 0, Sqrt(expMatCov[j])); + buffDL[j1] = 0.0; // reset buffer } } // material "measurement" - } // loop over points + } // loop over points // if (!nDGloTot) { AliInfo("Track does not depend on free global parameters, discard"); @@ -803,14 +872,17 @@ Bool_t AliAlgSteer::FillMilleData() Bool_t AliAlgSteer::FillMPRecData() { // store MP2 in MPRecord format - if (!fMPRecord) InitMPRecOutput(); + if (!fMPRecord) + InitMPRecOutput(); // fMPRecord->Clear(); - if (!fMPRecord->FillTrack(fAlgTrack,fGloParLab)) return kFALSE; + if (!fMPRecord->FillTrack(fAlgTrack, fGloParLab)) + return kFALSE; fMPRecord->SetRun(fRunNumber); fMPRecord->SetTimeStamp(fESDEvent->GetTimeStamp()); UInt_t tID = 0xffff & UInt_t(fESDTrack[0]->GetID()); - if (IsCosmic()) tID |= (0xffff & UInt_t(fESDTrack[1]->GetID()))<<16; + if (IsCosmic()) + tID |= (0xffff & UInt_t(fESDTrack[1]->GetID())) << 16; fMPRecord->SetTrackID(tID); fMPRecTree->Fill(); return kTRUE; @@ -820,23 +892,27 @@ Bool_t AliAlgSteer::FillMPRecData() Bool_t AliAlgSteer::FillControlData() { // store control residuals - if (!fCResid) InitResidOutput(); + if (!fCResid) + InitResidOutput(); // - int nps,np = fAlgTrack->GetNPoints(); - nps = (!fRefPoint->ContainsMeasurement()) ? np-1 : np; // ref point is dummy? - if (nps<0) return kTRUE; + int nps, np = fAlgTrack->GetNPoints(); + nps = (!fRefPoint->ContainsMeasurement()) ? np - 1 : np; // ref point is dummy? + if (nps < 0) + return kTRUE; // fCResid->Clear(); - if (!fCResid->FillTrack(fAlgTrack, fDoKalmanResid)) return kFALSE; + if (!fCResid->FillTrack(fAlgTrack, fDoKalmanResid)) + return kFALSE; fCResid->SetRun(fRunNumber); fCResid->SetTimeStamp(fESDEvent->GetTimeStamp()); fCResid->SetBz(fESDEvent->GetMagneticField()); UInt_t tID = 0xffff & UInt_t(fESDTrack[0]->GetID()); - if (IsCosmic()) tID |= (0xffff & UInt_t(fESDTrack[1]->GetID()))<<16; + if (IsCosmic()) + tID |= (0xffff & UInt_t(fESDTrack[1]->GetID())) << 16; fCResid->SetTrackID(tID); // fResidTree->Fill(); - FillStatHisto( kTrackControl ); + FillStatHisto(kTrackControl); // return kTRUE; } @@ -844,27 +920,30 @@ Bool_t AliAlgSteer::FillControlData() //_________________________________________________________ void AliAlgSteer::SetRunNumber(Int_t run) { - if (run==fRunNumber) return; // nothing to do + if (run == fRunNumber) + return; // nothing to do // - AcknowledgeNewRun(run); + AcknowledgeNewRun(run); } //_________________________________________________________ void AliAlgSteer::AcknowledgeNewRun(Int_t run) { // load needed info for new run - if (run==fRunNumber) return; // nothing to do - if (run>0) { + if (run == fRunNumber) + return; // nothing to do + if (run > 0) { fStat[kAccStat][kRun]++; } - if (fRunNumber>0) FillStatHisto( kRunDone ); + if (fRunNumber > 0) + FillStatHisto(kRunDone); fRunNumber = run; - AliInfoF("Processing new run %d",fRunNumber); + AliInfoF("Processing new run %d", fRunNumber); // // setup magnetic field - if (fESDEvent && + if (fESDEvent && (!TGeoGlobalMagField::Instance()->GetField() || - !SmallerAbs(fESDEvent->GetMagneticField()-AliTrackerBase::GetBz(),5e-4)) ) { + !SmallerAbs(fESDEvent->GetMagneticField() - AliTrackerBase::GetBz(), 5e-4))) { fESDEvent->InitMagneticField(); } // @@ -874,9 +953,10 @@ void AliAlgSteer::AcknowledgeNewRun(Int_t run) } LoadRecoTimeOCDB(); // - for (int idet=0;idetIsDisabled()) det->AcknowledgeNewRun(run); + if (!det->IsDisabled()) + det->AcknowledgeNewRun(run); } // // bring to virgin state @@ -892,24 +972,27 @@ void AliAlgSteer::AcknowledgeNewRun(Int_t run) Bool_t AliAlgSteer::LoadRecoTimeOCDB() { // Load OCDB paths used for the reconstruction of data being processed - // In order to avoid unnecessary uploads, the objects are not actually + // In order to avoid unnecessary uploads, the objects are not actually // loaded/cached but just added as specific paths with version - AliInfoF("Preloading Reco-Time OCDB for run %d from ESD UserInfo list",fRunNumber); + AliInfoF("Preloading Reco-Time OCDB for run %d from ESD UserInfo list", fRunNumber); // CleanOCDB(); // if (!fRecoOCDBConf.IsNull() && !gSystem->AccessPathName(fRecoOCDBConf.Data(), kFileExists)) { - AliInfoF("Executing reco-time OCDB setup macro %s",fRecoOCDBConf.Data()); - gROOT->ProcessLine(Form(".x %s(%d)",fRecoOCDBConf.Data(),fRunNumber)); - if (AliCDBManager::Instance()->IsDefaultStorageSet()) return kTRUE; - AliFatalF("macro %s failed to configure reco-time OCDB",fRecoOCDBConf.Data()); - } - else AliWarningF("No reco-time OCDB config macro %s is found, will use ESD:UserInfo", - fRecoOCDBConf.Data()); - // - if (!fESDTree) AliFatal("Cannot preload Reco-Time OCDB since the ESD tree is not set"); - const TTree* tr = fESDTree; // go the the real ESD tree - while (tr->GetTree() && tr->GetTree()!=tr) tr = tr->GetTree(); + AliInfoF("Executing reco-time OCDB setup macro %s", fRecoOCDBConf.Data()); + gROOT->ProcessLine(Form(".x %s(%d)", fRecoOCDBConf.Data(), fRunNumber)); + if (AliCDBManager::Instance()->IsDefaultStorageSet()) + return kTRUE; + AliFatalF("macro %s failed to configure reco-time OCDB", fRecoOCDBConf.Data()); + } else + AliWarningF("No reco-time OCDB config macro %s is found, will use ESD:UserInfo", + fRecoOCDBConf.Data()); + // + if (!fESDTree) + AliFatal("Cannot preload Reco-Time OCDB since the ESD tree is not set"); + const TTree* tr = fESDTree; // go the the real ESD tree + while (tr->GetTree() && tr->GetTree() != tr) + tr = tr->GetTree(); // const TList* userInfo = const_cast(tr)->GetUserInfo(); TMap* cdbMap = (TMap*)userInfo->FindObject("cdbMap"); @@ -920,31 +1003,36 @@ Bool_t AliAlgSteer::LoadRecoTimeOCDB() AliFatal("Failed to extract cdbMap and cdbList from UserInfo list"); } // - return PreloadOCDB(fRunNumber,cdbMap,cdbList); + return PreloadOCDB(fRunNumber, cdbMap, cdbList); } //_________________________________________________________ AliAlgDet* AliAlgSteer::GetDetectorByVolID(Int_t vid) const { // get detector by sensor volid - for (int i=fNDet;i--;) if (fDetectors[i]->SensorOfDetector(vid)) return fDetectors[i]; + for (int i = fNDet; i--;) + if (fDetectors[i]->SensorOfDetector(vid)) + return fDetectors[i]; return 0; } //____________________________________________ -void AliAlgSteer::Print(const Option_t *opt) const +void AliAlgSteer::Print(const Option_t* opt) const { // print info - TString opts = opt; + TString opts = opt; opts.ToLower(); - printf("%5d DOFs in %d detectors",fNDOFs,fNDet); - if (!fConfMacroName.IsNull()) printf("(config: %s)",fConfMacroName.Data()); + printf("%5d DOFs in %d detectors", fNDOFs, fNDet); + if (!fConfMacroName.IsNull()) + printf("(config: %s)", fConfMacroName.Data()); printf("\n"); - if (GetMPAlignDone()) printf("ALIGNMENT FROM MILLEPEDE SOLUTION IS APPLIED\n"); + if (GetMPAlignDone()) + printf("ALIGNMENT FROM MILLEPEDE SOLUTION IS APPLIED\n"); // - for (int idt=0;idtPrint(opt); } if (!opts.IsNull()) { @@ -954,46 +1042,51 @@ void AliAlgSteer::Print(const Option_t *opt) const // // event selection printf("\n"); - printf("%-40s:\t", "Alowed event specii mask"); - PrintBits((ULong64_t)fSelEventSpecii,5); printf("\n"); + printf("%-40s:\t", "Alowed event specii mask"); + PrintBits((ULong64_t)fSelEventSpecii, 5); + printf("\n"); printf("%-40s:\t%d/%d\n", "Min points per collisions track (BOff/ON)", - fMinPoints[kColl][0],fMinPoints[kColl][1]); + fMinPoints[kColl][0], fMinPoints[kColl][1]); printf("%-40s:\t%d/%d\n", "Min points per cosmic track leg (BOff/ON)", - fMinPoints[kCosm][0],fMinPoints[kCosm][1]); - printf("%-40s:\t%d\n", "Min detectots per collision track",fMinDetAcc[kColl]); - printf("%-40s:\t%d (%s)\n", "Min detectots per cosmic track/leg",fMinDetAcc[kCosm], - fCosmicSelStrict ? "STRICT":"SOFT"); - printf("%-40s:\t%d/%d\n", "Min/Max vertex contrib. to accept event",fVtxMinCont,fVtxMaxCont); - printf("%-40s:\t%d\n", "Min vertex contrib. for constraint",fVtxMinContVC); - printf("%-40s:\t%d\n", "Min Ncl ITS for vertex constraint",fMinITSClforVC); - printf("%-40s:\t%s\n", "SPD request for vertex constraint", - AliAlgDetITS::GetITSPattName(fITSPattforVC)); - printf("%-40s:\t%.4f/%.4f/%.2f\n","DCAr/DCAz/Chi2 cut for vertex constraint", - fMaxDCAforVC[0],fMaxDCAforVC[1],fMaxChi2forVC); - printf("Collision tracks: Min pT: %5.2f |etaMax|: %5.2f\n",fPtMin[kColl],fEtaMax[kColl]); - printf("Cosmic tracks: Min pT: %5.2f |etaMax|: %5.2f\n",fPtMin[kCosm],fEtaMax[kCosm]); - // - printf("%-40s:\t%s","Config. for reference OCDB",fRefOCDBConf.Data()); - if (fRefRunNumber>=0) printf("(%d)",fRefRunNumber); + fMinPoints[kCosm][0], fMinPoints[kCosm][1]); + printf("%-40s:\t%d\n", "Min detectots per collision track", fMinDetAcc[kColl]); + printf("%-40s:\t%d (%s)\n", "Min detectots per cosmic track/leg", fMinDetAcc[kCosm], + fCosmicSelStrict ? "STRICT" : "SOFT"); + printf("%-40s:\t%d/%d\n", "Min/Max vertex contrib. to accept event", fVtxMinCont, fVtxMaxCont); + printf("%-40s:\t%d\n", "Min vertex contrib. for constraint", fVtxMinContVC); + printf("%-40s:\t%d\n", "Min Ncl ITS for vertex constraint", fMinITSClforVC); + printf("%-40s:\t%s\n", "SPD request for vertex constraint", + AliAlgDetITS::GetITSPattName(fITSPattforVC)); + printf("%-40s:\t%.4f/%.4f/%.2f\n", "DCAr/DCAz/Chi2 cut for vertex constraint", + fMaxDCAforVC[0], fMaxDCAforVC[1], fMaxChi2forVC); + printf("Collision tracks: Min pT: %5.2f |etaMax|: %5.2f\n", fPtMin[kColl], fEtaMax[kColl]); + printf("Cosmic tracks: Min pT: %5.2f |etaMax|: %5.2f\n", fPtMin[kCosm], fEtaMax[kCosm]); + // + printf("%-40s:\t%s", "Config. for reference OCDB", fRefOCDBConf.Data()); + if (fRefRunNumber >= 0) + printf("(%d)", fRefRunNumber); printf("\n"); - printf("%-40s:\t%s\n","Config. for reco-time OCDB",fRecoOCDBConf.Data()); - // - printf("%-40s:\t%s\n","Output OCDB path",fOutCDBPath.Data()); - printf("%-40s:\t%s/%s\n","Output OCDB comment/responsible", - fOutCDBComment.Data(),fOutCDBResponsible.Data()); - printf("%-40s:\t%6d:%6d\n","Output OCDB run range",fOutCDBRunRange[0],fOutCDBRunRange[1]); - // - printf("%-40s:\t%s\n","Filename for MillePede steering",fMPSteerFileName.Data()); - printf("%-40s:\t%s\n","Filename for MillePede parameters",fMPParFileName.Data()); - printf("%-40s:\t%s\n","Filename for MillePede constraints",fMPConFileName.Data()); - printf("%-40s:\t%s\n","Filename for control residuals:",fResidFileName.Data()); - printf("%-40s:\t%.3f\n","Fraction of control tracks",fControlFrac); + printf("%-40s:\t%s\n", "Config. for reco-time OCDB", fRecoOCDBConf.Data()); + // + printf("%-40s:\t%s\n", "Output OCDB path", fOutCDBPath.Data()); + printf("%-40s:\t%s/%s\n", "Output OCDB comment/responsible", + fOutCDBComment.Data(), fOutCDBResponsible.Data()); + printf("%-40s:\t%6d:%6d\n", "Output OCDB run range", fOutCDBRunRange[0], fOutCDBRunRange[1]); + // + printf("%-40s:\t%s\n", "Filename for MillePede steering", fMPSteerFileName.Data()); + printf("%-40s:\t%s\n", "Filename for MillePede parameters", fMPParFileName.Data()); + printf("%-40s:\t%s\n", "Filename for MillePede constraints", fMPConFileName.Data()); + printf("%-40s:\t%s\n", "Filename for control residuals:", fResidFileName.Data()); + printf("%-40s:\t%.3f\n", "Fraction of control tracks", fControlFrac); printf("MPData output :\t"); - if (GetProduceMPData()) printf("%s%s ",fMPDatFileName.Data(),fgkMPDataExt); - if (GetProduceMPRecord()) printf("%s%s ",fMPDatFileName.Data(),".root"); + if (GetProduceMPData()) + printf("%s%s ", fMPDatFileName.Data(), fgkMPDataExt); + if (GetProduceMPRecord()) + printf("%s%s ", fMPDatFileName.Data(), ".root"); printf("\n"); // - if (opts.Contains("stat")) PrintStatistics(); + if (opts.Contains("stat")) + PrintStatistics(); } //________________________________________________________ @@ -1002,10 +1095,14 @@ void AliAlgSteer::PrintStatistics() const // print processing stat printf("\nProcessing Statistics\n"); printf("Type: "); - for (int i=0;iClear(); - for (int idet=fNDet;idet--;) { + for (int idet = fNDet; idet--;) { AliAlgDet* det = GetDetector(idet); - det->ResetPool(); // reset used alignment points + det->ResetPool(); // reset used alignment points } } @@ -1026,13 +1123,14 @@ Bool_t AliAlgSteer::TestLocalSolution() // test track local solution TVectorD rhs; AliSymMatrix* mat = BuildMatrix(rhs); - if (!mat) return kFALSE; + if (!mat) + return kFALSE; // mat->Print("long data"); // rhs.Print(); TVectorD vsl(rhs); - if (!mat->SolveChol(rhs,vsl,kTRUE)) { - delete mat; - return kFALSE; + if (!mat->SolveChol(rhs, vsl, kTRUE)) { + delete mat; + return kFALSE; } // /* @@ -1068,53 +1166,53 @@ Bool_t AliAlgSteer::TestLocalSolution() } //____________________________________________ -AliSymMatrix* AliAlgSteer::BuildMatrix(TVectorD &vec) +AliSymMatrix* AliAlgSteer::BuildMatrix(TVectorD& vec) { // build matrix/vector for local track int npnt = fAlgTrack->GetNPoints(); int nlocpar = fAlgTrack->GetNLocPar(); // vec.ResizeTo(nlocpar); - memset(vec.GetMatrixArray(),0,nlocpar*sizeof(double)); + memset(vec.GetMatrixArray(), 0, nlocpar * sizeof(double)); AliSymMatrix* matp = new AliSymMatrix(nlocpar); AliSymMatrix& mat = *matp; // - for (int ip=npnt;ip--;) { + for (int ip = npnt; ip--;) { AliAlgPoint* pnt = fAlgTrack->GetPoint(ip); // if (pnt->ContainsMeasurement()) { // pnt->Print("meas"); - for (int idim=2;idim--;) { // each point has 2 position residuals - double sigma2 = pnt->GetErrDiag(idim); // residual error - double resid = fAlgTrack->GetResidual(idim,ip); // residual - double* deriv = fAlgTrack->GetDResDLoc(idim,ip); // array of Dresidual/Dparams - // - double sg2inv = 1./sigma2; - for (int parI=nlocpar;parI--;) { - vec[parI] -= deriv[parI]*resid*sg2inv; - // printf("%d %d %d %+e %+e %+e -> %+e\n",ip,idim,parI,sg2inv,deriv[parI],resid,vec[parI]); - // for (int parJ=nlocpar;parJ--;) { - for (int parJ=parI+1;parJ--;) { - mat(parI,parJ) += deriv[parI]*deriv[parJ]*sg2inv; - } - } - } // loop over 2 orthogonal measurements at the point - } // derivarives at measured points + for (int idim = 2; idim--;) { // each point has 2 position residuals + double sigma2 = pnt->GetErrDiag(idim); // residual error + double resid = fAlgTrack->GetResidual(idim, ip); // residual + double* deriv = fAlgTrack->GetDResDLoc(idim, ip); // array of Dresidual/Dparams + // + double sg2inv = 1. / sigma2; + for (int parI = nlocpar; parI--;) { + vec[parI] -= deriv[parI] * resid * sg2inv; + // printf("%d %d %d %+e %+e %+e -> %+e\n",ip,idim,parI,sg2inv,deriv[parI],resid,vec[parI]); + // for (int parJ=nlocpar;parJ--;) { + for (int parJ = parI + 1; parJ--;) { + mat(parI, parJ) += deriv[parI] * deriv[parJ] * sg2inv; + } + } + } // loop over 2 orthogonal measurements at the point + } // derivarives at measured points // - // if the point contains material, consider its expected kinks, eloss + // if the point contains material, consider its expected kinks, eloss // as measurements if (pnt->ContainsMaterial()) { // at least 4 parameters: 2 spatial + 2 angular kinks with 0 expectaction int npm = pnt->GetNMatPar(); // const float* expMatCorr = pnt->GetMatCorrExp(); // expected correction (diagonalized) - const float* expMatCov = pnt->GetMatCorrCov(); // its error - int offs = pnt->GetMaxLocVarID() - npm; - for (int ipar=0;iparGetMatCorrCov(); // its error + int offs = pnt->GetMaxLocVarID() - npm; + for (int ipar = 0; ipar < npm; ipar++) { + int parI = offs + ipar; + // expected + // vec[parI] -= expMatCorr[ipar]/expMatCov[ipar]; // consider expectation as measurement + mat(parI, parI) += 1. / expMatCov[ipar]; // this measurement is orthogonal to all others + //printf("Pnt:%3d MatVar:%d DOF %3d | ExpVal: %+e Cov: %+e\n",ip,ipar,parI, expMatCorr[ipar], expMatCov[ipar]); } } // material effect descripotion params // @@ -1127,14 +1225,16 @@ AliSymMatrix* AliAlgSteer::BuildMatrix(TVectorD &vec) void AliAlgSteer::InitMPRecOutput() { // prepare MP record output - if (!fMPRecord) fMPRecord = new AliAlgMPRecord(); + if (!fMPRecord) + fMPRecord = new AliAlgMPRecord(); // - TString mo = Form("%s%s",fMPDatFileName.Data(),".root"); - fMPRecFile = TFile::Open(mo.Data(),"recreate"); - if (!fMPRecFile) AliFatalF("Failed to create output file %s",mo.Data()); + TString mo = Form("%s%s", fMPDatFileName.Data(), ".root"); + fMPRecFile = TFile::Open(mo.Data(), "recreate"); + if (!fMPRecFile) + AliFatalF("Failed to create output file %s", mo.Data()); // - fMPRecTree = new TTree("mpTree","MPrecord Tree"); - fMPRecTree->Branch("mprec","AliAlgMPRecord",&fMPRecord); + fMPRecTree = new TTree("mpTree", "MPrecord Tree"); + fMPRecTree->Branch("mprec", "AliAlgMPRecord", &fMPRecord); // } @@ -1142,13 +1242,15 @@ void AliAlgSteer::InitMPRecOutput() void AliAlgSteer::InitResidOutput() { // prepare residual output - if (!fCResid) fCResid = new AliAlgRes(); + if (!fCResid) + fCResid = new AliAlgRes(); // - fResidFile = TFile::Open(fResidFileName.Data(),"recreate"); - if (!fResidFile) AliFatalF("Failed to create output file %s",fResidFileName.Data()); + fResidFile = TFile::Open(fResidFileName.Data(), "recreate"); + if (!fResidFile) + AliFatalF("Failed to create output file %s", fResidFileName.Data()); // - fResidTree = new TTree("res","Control Residuals"); - fResidTree->Branch("t","AliAlgRes",&fCResid); + fResidTree = new TTree("res", "Control Residuals"); + fResidTree->Branch("t", "AliAlgRes", &fCResid); // } @@ -1156,8 +1258,9 @@ void AliAlgSteer::InitResidOutput() void AliAlgSteer::CloseMPRecOutput() { // close output - if (!fMPRecFile) return; - AliInfoF("Closing %s",fMPRecFile->GetName()); + if (!fMPRecFile) + return; + AliInfoF("Closing %s", fMPRecFile->GetName()); fMPRecFile->cd(); fMPRecTree->Write(); delete fMPRecTree; @@ -1173,8 +1276,9 @@ void AliAlgSteer::CloseMPRecOutput() void AliAlgSteer::CloseResidOutput() { // close output - if (!fResidFile) return; - AliInfoF("Closing %s",fResidFile->GetName()); + if (!fResidFile) + return; + AliInfoF("Closing %s", fResidFile->GetName()); fResidFile->cd(); fResidTree->Write(); delete fResidTree; @@ -1190,59 +1294,65 @@ void AliAlgSteer::CloseResidOutput() void AliAlgSteer::CloseMilleOutput() { // close output - if (fMille ) AliInfoF("Closing %s%s",fMPDatFileName.Data(),fgkMPDataExt); + if (fMille) + AliInfoF("Closing %s%s", fMPDatFileName.Data(), fgkMPDataExt); delete fMille; fMille = 0; } //____________________________________________ -void AliAlgSteer::SetMPDatFileName(const char* name) +void AliAlgSteer::SetMPDatFileName(const char* name) { // set output file name fMPDatFileName = name; // strip root or mille extensions, they will be added automatically later - if (fMPDatFileName.EndsWith(fgkMPDataExt)) - fMPDatFileName.Remove(fMPDatFileName.Length()-strlen(fgkMPDataExt)); - else if (fMPDatFileName.EndsWith(".root")) - fMPDatFileName.Remove(fMPDatFileName.Length()-strlen(".root")); + if (fMPDatFileName.EndsWith(fgkMPDataExt)) + fMPDatFileName.Remove(fMPDatFileName.Length() - strlen(fgkMPDataExt)); + else if (fMPDatFileName.EndsWith(".root")) + fMPDatFileName.Remove(fMPDatFileName.Length() - strlen(".root")); // - if (fMPDatFileName.IsNull()) fMPDatFileName = "mpData"; + if (fMPDatFileName.IsNull()) + fMPDatFileName = "mpData"; // } //____________________________________________ -void AliAlgSteer::SetMPParFileName(const char* name) +void AliAlgSteer::SetMPParFileName(const char* name) { // set MP params output file name - fMPParFileName = name; - if (fMPParFileName.IsNull()) fMPParFileName = "mpParams.txt"; + fMPParFileName = name; + if (fMPParFileName.IsNull()) + fMPParFileName = "mpParams.txt"; // } //____________________________________________ -void AliAlgSteer::SetMPConFileName(const char* name) +void AliAlgSteer::SetMPConFileName(const char* name) { // set MP constraints output file name - fMPConFileName = name; - if (fMPConFileName.IsNull()) fMPConFileName = "mpConstraints.txt"; + fMPConFileName = name; + if (fMPConFileName.IsNull()) + fMPConFileName = "mpConstraints.txt"; // } //____________________________________________ -void AliAlgSteer::SetMPSteerFileName(const char* name) +void AliAlgSteer::SetMPSteerFileName(const char* name) { // set MP constraints output file name - fMPSteerFileName = name; - if (fMPSteerFileName.IsNull()) fMPSteerFileName = "mpConstraints.txt"; + fMPSteerFileName = name; + if (fMPSteerFileName.IsNull()) + fMPSteerFileName = "mpConstraints.txt"; // } //____________________________________________ -void AliAlgSteer::SetResidFileName(const char* name) +void AliAlgSteer::SetResidFileName(const char* name) { // set output file name - fResidFileName = name; - if (fResidFileName.IsNull()) fResidFileName = "mpControlRes.root"; + fResidFileName = name; + if (fResidFileName.IsNull()) + fResidFileName = "mpControlRes.root"; // } @@ -1250,8 +1360,9 @@ void AliAlgSteer::SetResidFileName(const char* name) void AliAlgSteer::SetOutCDBPath(const char* name) { // set output storage name - fOutCDBPath = name; - if (fOutCDBPath.IsNull()) fOutCDBPath = "local://outOCDB"; + fOutCDBPath = name; + if (fOutCDBPath.IsNull()) + fOutCDBPath = "local://outOCDB"; // } @@ -1261,11 +1372,14 @@ void AliAlgSteer::SetObligatoryDetector(Int_t detID, Int_t trtype, Bool_t v) // mark detector presence obligatory in the track of given type AliAlgDet* det = GetDetectorByDetID(detID); if (!det) { - AliErrorF("Detector %d is not defined",detID); + AliErrorF("Detector %d is not defined", detID); } - if (v) fObligatoryDetPattern[trtype] |= 0x1<IsObligatory(trtype)!=v) det->SetObligatory(trtype,v); + if (v) + fObligatoryDetPattern[trtype] |= 0x1 << detID; + else + fObligatoryDetPattern[trtype] &= ~(0x1 << detID); + if (det->IsObligatory(trtype) != v) + det->SetObligatory(trtype, v); // } @@ -1275,31 +1389,38 @@ Bool_t AliAlgSteer::AddVertexConstraint() // if vertex is set and if particle is primary, add vertex as a meared point // const AliESDtrack* esdTr = fESDTrack[0]; - if (!fVertex || !esdTr) return kFALSE; + if (!fVertex || !esdTr) + return kFALSE; // - if (esdTr->GetNcls(0)GetNcls(0) < fMinITSClforVC) + return kFALSE; // not enough ITS clusters + if (!AliAlgDetITS::CheckHitPattern(esdTr, fITSPattforVC)) + return kFALSE; // AliExternalTrackParam trc = *esdTr; - Double_t dz[2],dzCov[3]; - if (!trc.PropagateToDCA(fVertex,AliTrackerBase::GetBz(),2*fMaxDCAforVC[0],dz,dzCov)) return kFALSE; + Double_t dz[2], dzCov[3]; + if (!trc.PropagateToDCA(fVertex, AliTrackerBase::GetBz(), 2 * fMaxDCAforVC[0], dz, dzCov)) + return kFALSE; // // check if primary candidate - if (Abs(dz[0])>fMaxDCAforVC[0] || Abs(dz[1])>fMaxDCAforVC[1]) return kFALSE; - Double_t covar[6]; fVertex->GetCovMatrix(covar); - Double_t p[2] = {trc.GetParameter()[0]-dz[0],trc.GetParameter()[1]-dz[1]}; - Double_t c[3] = {0.5*(covar[0]+covar[2]),0.,covar[5]}; - Double_t chi2 = trc.GetPredictedChi2(p,c); - if (chi2>fMaxChi2forVC) return kFALSE; + if (Abs(dz[0]) > fMaxDCAforVC[0] || Abs(dz[1]) > fMaxDCAforVC[1]) + return kFALSE; + Double_t covar[6]; + fVertex->GetCovMatrix(covar); + Double_t p[2] = {trc.GetParameter()[0] - dz[0], trc.GetParameter()[1] - dz[1]}; + Double_t c[3] = {0.5 * (covar[0] + covar[2]), 0., covar[5]}; + Double_t chi2 = trc.GetPredictedChi2(p, c); + if (chi2 > fMaxChi2forVC) + return kFALSE; // // assing measured vertex rotated to VtxSens frame as reference point - double xyz[3],xyzT[3]; + double xyz[3], xyzT[3]; fVertex->GetXYZ(xyz); fVtxSens->SetAlpha(trc.GetAlpha()); // usually translation from GLO to TRA frame should go via matrix T2G // but for the VertexSensor Local and Global are the same frames fVtxSens->ApplyCorrection(xyz); - fVtxSens->GetMatrixT2L().MasterToLocal(xyz,xyzT); + fVtxSens->GetMatrixT2L().MasterToLocal(xyz, xyzT); fRefPoint->SetSensor(fVtxSens); fRefPoint->SetAlphaSens(fVtxSens->GetAlpTracking()); fRefPoint->SetXYZTracking(xyzT); @@ -1318,19 +1439,20 @@ void AliAlgSteer::WriteCalibrationResults() const AliCDBManager::Instance()->SetDefaultStorage(fOutCDBPath.Data()); // AliAlgDet* det; - for (int idet=0;idetIsDisabled()) continue; + for (int idet = 0; idet < kNDetectors; idet++) { + if (!(det = GetDetectorByDetID(idet)) || det->IsDisabled()) + continue; det->WriteCalibrationResults(); } // } //______________________________________________________ -void AliAlgSteer::SetOutCDBRunRange(int rmin,int rmax) +void AliAlgSteer::SetOutCDBRunRange(int rmin, int rmax) { // set output run range - fOutCDBRunRange[0] = rmin >=0 ? rmin : 0; - fOutCDBRunRange[1] = rmax>fOutCDBRunRange[0] ? rmax : AliCDBRunRange::Infinity(); + fOutCDBRunRange[0] = rmin >= 0 ? rmin : 0; + fOutCDBRunRange[1] = rmax > fOutCDBRunRange[0] ? rmax : AliCDBRunRange::Infinity(); } //______________________________________________________ @@ -1344,15 +1466,16 @@ Bool_t AliAlgSteer::LoadRefOCDB() AliInfo("Loading reference OCDB"); CleanOCDB(); AliCDBManager* man = AliCDBManager::Instance(); - // + // if (!fRefOCDBConf.IsNull() && !gSystem->AccessPathName(fRefOCDBConf.Data(), kFileExists)) { - AliInfoF("Executing reference OCDB setup macro %s",fRefOCDBConf.Data()); - if (fRefRunNumber>0) gROOT->ProcessLine(Form(".x %s(%d)",fRefOCDBConf.Data(),fRefRunNumber)); - else gROOT->ProcessLine(Form(".x %s",fRefOCDBConf.Data())); - } - else { + AliInfoF("Executing reference OCDB setup macro %s", fRefOCDBConf.Data()); + if (fRefRunNumber > 0) + gROOT->ProcessLine(Form(".x %s(%d)", fRefOCDBConf.Data(), fRefRunNumber)); + else + gROOT->ProcessLine(Form(".x %s", fRefOCDBConf.Data())); + } else { AliWarningF("No reference OCDB config macro %s is found, assume raw:// with run %d", - fRefOCDBConf.Data(),AliCDBRunRange::Infinity()); + fRefOCDBConf.Data(), AliCDBRunRange::Infinity()); man->SetRaw(kTRUE); man->SetRun(AliCDBRunRange::Infinity()); } @@ -1362,10 +1485,14 @@ Bool_t AliAlgSteer::LoadRefOCDB() AliGeomManager::Destroy(); } AliGeomManager::LoadGeometry("geometry.root"); - if (!AliGeomManager::GetGeometry()) AliFatal("Failed to load geometry, cannot run"); + if (!AliGeomManager::GetGeometry()) + AliFatal("Failed to load geometry, cannot run"); // TString detList = ""; - for (int i=0;iOwnsDOFID(id)) return det; + if (det->OwnsDOFID(id)) + return det; } return 0; } @@ -1388,11 +1516,13 @@ AliAlgDet* AliAlgSteer::GetDetOfDOFID(int id) const AliAlgVol* AliAlgSteer::GetVolOfDOFID(int id) const { // return volume owning DOF with this ID - for (int i=fNDet;i--;) { + for (int i = fNDet; i--;) { AliAlgDet* det = GetDetector(i); - if (det->OwnsDOFID(id)) return det->GetVolOfDOFID(id); + if (det->OwnsDOFID(id)) + return det->GetVolOfDOFID(id); } - if (fVtxSens && fVtxSens->OwnsDOFID(id)) return fVtxSens; + if (fVtxSens && fVtxSens->OwnsDOFID(id)) + return fVtxSens; return 0; } @@ -1400,14 +1530,18 @@ AliAlgVol* AliAlgSteer::GetVolOfDOFID(int id) const void AliAlgSteer::Terminate(Bool_t doStat) { // finalize processing - if (fRunNumber>0) FillStatHisto( kRunDone ); + if (fRunNumber > 0) + FillStatHisto(kRunDone); if (doStat) { - if (fDOFStat) delete fDOFStat; + if (fDOFStat) + delete fDOFStat; fDOFStat = new AliAlgDOFStat(fNDOFs); } - if (fVtxSens) fVtxSens->FillDOFStat(fDOFStat); + if (fVtxSens) + fVtxSens->FillDOFStat(fDOFStat); // - for (int i=fNDet;i--;) GetDetector(i)->Terminate(); + for (int i = fNDet; i--;) + GetDetector(i)->Terminate(); CloseMPRecOutput(); CloseMilleOutput(); CloseResidOutput(); @@ -1420,74 +1554,80 @@ Char_t* AliAlgSteer::GetDOFLabelTxt(int idf) const { // get DOF full label AliAlgVol* vol = GetVolOfDOFID(idf); - if (vol) return Form("%d_%s_%s",GetGloParLab(idf),vol->GetSymName(), - vol->GetDOFName(idf-vol->GetFirstParGloID())); + if (vol) + return Form("%d_%s_%s", GetGloParLab(idf), vol->GetSymName(), + vol->GetDOFName(idf - vol->GetFirstParGloID())); // // this might be detector-specific calibration dof AliAlgDet* det = GetDetOfDOFID(idf); - if (det) return Form("%d_%s_%s",GetGloParLab(idf),det->GetName(), - det->GetCalibDOFName(idf-det->GetFirstParGloID())); + if (det) + return Form("%d_%s_%s", GetGloParLab(idf), det->GetName(), + det->GetCalibDOFName(idf - det->GetFirstParGloID())); return 0; } - //********************* interaction with PEDE ********************** //______________________________________________________ -void AliAlgSteer::GenPedeSteerFile(const Option_t *opt) const +void AliAlgSteer::GenPedeSteerFile(const Option_t* opt) const { // produce steering file template for PEDE + params and constraints // - enum {kOff,kOn,kOnOn}; - const char* cmt[3] = {" ","! ","!!"}; - const char* kSolMeth[] = {"inversion","diagonalization","fullGMRES","sparseGMRES","cholesky","HIP"}; - const int kDefNIter = 3; // default number of iterations to ask + enum { kOff, + kOn, + kOnOn }; + const char* cmt[3] = {" ", "! ", "!!"}; + const char* kSolMeth[] = {"inversion", "diagonalization", "fullGMRES", "sparseGMRES", "cholesky", "HIP"}; + const int kDefNIter = 3; // default number of iterations to ask const float kDefDelta = 0.1; // def. delta to exit TString opts = opt; opts.ToLower(); - AliInfoF("Generating MP2 templates:\n" - "Steering :\t%s\n" - "Parameters :\t%s\n" - "Constraints:\t%s\n", - fMPSteerFileName.Data(),fMPParFileName.Data(),fMPConFileName.Data()); + AliInfoF( + "Generating MP2 templates:\n" + "Steering :\t%s\n" + "Parameters :\t%s\n" + "Constraints:\t%s\n", + fMPSteerFileName.Data(), fMPParFileName.Data(), fMPConFileName.Data()); // - FILE* parFl = fopen (fMPParFileName.Data(),"w+"); - FILE* strFl = fopen (fMPSteerFileName.Data(),"w+"); + FILE* parFl = fopen(fMPParFileName.Data(), "w+"); + FILE* strFl = fopen(fMPSteerFileName.Data(), "w+"); // // --- template of steering file - fprintf(strFl,"%-20s%s %s\n",fMPParFileName.Data(),cmt[kOnOn],"parameters template"); - fprintf(strFl,"%-20s%s %s\n",fMPConFileName.Data(),cmt[kOnOn],"constraints template"); + fprintf(strFl, "%-20s%s %s\n", fMPParFileName.Data(), cmt[kOnOn], "parameters template"); + fprintf(strFl, "%-20s%s %s\n", fMPConFileName.Data(), cmt[kOnOn], "constraints template"); // - fprintf(strFl,"\n\n%s %s\n",cmt[kOnOn],"MUST uncomment 1 solving methods and tune it"); + fprintf(strFl, "\n\n%s %s\n", cmt[kOnOn], "MUST uncomment 1 solving methods and tune it"); // - int nm = sizeof(kSolMeth)/sizeof(char*); - for (int i=0;iWritePedeInfo(parFl,opt); + if (fVtxSens) + fVtxSens->WritePedeInfo(parFl, opt); // - for (int idt=0;idtIsDisabled()) continue; - det->WritePedeInfo(parFl,opt); + if (!det || det->IsDisabled()) + continue; + det->WritePedeInfo(parFl, opt); // } // @@ -1502,50 +1642,54 @@ void AliAlgSteer::GenPedeSteerFile(const Option_t *opt) const Bool_t AliAlgSteer::ReadParameters(const char* parfile, Bool_t useErrors) { // read parameters file (millepede output) - if (fNDOFs<1 || !fGloParVal || !fGloParErr) { + if (fNDOFs < 1 || !fGloParVal || !fGloParErr) { AliErrorF("Something is wrong in init: fNDOFs=%d fGloParVal=%p fGloParErr=%p", - fNDOFs,fGloParVal,fGloParErr); + fNDOFs, fGloParVal, fGloParErr); } ifstream inpf(parfile); if (!inpf.good()) { - printf("Failed on input filename %s\n",parfile); + printf("Failed on input filename %s\n", parfile); return kFALSE; } - memset(fGloParVal,0,fNDOFs*sizeof(float)); - if (useErrors) memset(fGloParErr,0,fNDOFs*sizeof(float)); + memset(fGloParVal, 0, fNDOFs * sizeof(float)); + if (useErrors) + memset(fGloParErr, 0, fNDOFs * sizeof(float)); int cnt = 0; TString fline; fline.ReadLine(inpf); - fline = fline.Strip(TString::kBoth,' '); + fline = fline.Strip(TString::kBoth, ' '); fline.ToLower(); if (!fline.BeginsWith("parameter")) { - AliErrorF("First line is not parameter keyword:\n%s",fline.Data()); + AliErrorF("First line is not parameter keyword:\n%s", fline.Data()); return kFALSE; } - double v0,v1,v2; - int lab,asg=0,asg0=0; + double v0, v1, v2; + int lab, asg = 0, asg0 = 0; while (fline.ReadLine(inpf)) { cnt++; - fline = fline.Strip(TString::kBoth,' '); - if (fline.BeginsWith("!") || fline.BeginsWith("*")) continue; // ignore comment - int nr = sscanf(fline.Data(),"%d%lf%lf%lf",&lab,&v0,&v1,&v2); - if (nr<3) { - AliErrorF("Expected to read at least 3 numbers, got %d, this is NOT milleped output",nr); - AliErrorF("line (%d) was:\n%s",cnt,fline.Data()); + fline = fline.Strip(TString::kBoth, ' '); + if (fline.BeginsWith("!") || fline.BeginsWith("*")) + continue; // ignore comment + int nr = sscanf(fline.Data(), "%d%lf%lf%lf", &lab, &v0, &v1, &v2); + if (nr < 3) { + AliErrorF("Expected to read at least 3 numbers, got %d, this is NOT milleped output", nr); + AliErrorF("line (%d) was:\n%s", cnt, fline.Data()); return kFALSE; } - if (nr==3) asg0++; + if (nr == 3) + asg0++; int parID = Label2ParID(lab); - if (parID<0 || parID>=fNDOFs) { - AliErrorF("Invalid label %d at line %d -> ParID=%d",lab,cnt,parID); + if (parID < 0 || parID >= fNDOFs) { + AliErrorF("Invalid label %d at line %d -> ParID=%d", lab, cnt, parID); return kFALSE; } fGloParVal[parID] = -v0; - if (useErrors) fGloParErr[parID] = v1; + if (useErrors) + fGloParErr[parID] = v1; asg++; // }; - AliInfoF("Read %d lines, assigned %d values, %d dummy",cnt,asg,asg0); + AliInfoF("Read %d lines, assigned %d values, %d dummy", cnt, asg, asg0); // return kTRUE; } @@ -1556,12 +1700,12 @@ void AliAlgSteer::CheckConstraints(const char* params) // check how the constraints are satisfied with already uploaded or provided params // if (params && !ReadParameters(params)) { - AliErrorF("Failed to load parameters from %s",params); + AliErrorF("Failed to load parameters from %s", params); return; } // int ncon = GetNConstraints(); - for (int icon=0;iconCheckConstraint(); } @@ -1569,27 +1713,27 @@ void AliAlgSteer::CheckConstraints(const char* params) } //___________________________________________________________ -void AliAlgSteer::MPRec2Mille(const char* mprecfile,const char* millefile,Bool_t bindata) +void AliAlgSteer::MPRec2Mille(const char* mprecfile, const char* millefile, Bool_t bindata) { // converts MPRecord tree to millepede binary format TFile* flmpr = TFile::Open(mprecfile); if (!flmpr) { - AliErrorClassF("Failed to open MPRecord file %s",mprecfile); + AliErrorClassF("Failed to open MPRecord file %s", mprecfile); return; } TTree* mprTree = (TTree*)flmpr->Get("mpTree"); if (!mprTree) { - AliErrorClassF("No mpTree in xMPRecord file %s",mprecfile); + AliErrorClassF("No mpTree in xMPRecord file %s", mprecfile); return; } - MPRec2Mille(mprTree,millefile,bindata); + MPRec2Mille(mprTree, millefile, bindata); delete mprTree; flmpr->Close(); delete flmpr; } //___________________________________________________________ -void AliAlgSteer::MPRec2Mille(TTree* mprTree,const char* millefile,Bool_t bindata) +void AliAlgSteer::MPRec2Mille(TTree* mprTree, const char* millefile, Bool_t bindata) { // converts MPRecord tree to millepede binary format // @@ -1602,34 +1746,38 @@ void AliAlgSteer::MPRec2Mille(TTree* mprTree,const char* millefile,Bool_t bindat br->SetAddress(&rec); int nent = mprTree->GetEntries(); TString mlname = millefile; - if (mlname.IsNull()) mlname = "mpRec2mpData"; - if (!mlname.EndsWith(fgkMPDataExt)) mlname += fgkMPDataExt; - Mille* mille = new Mille(mlname,bindata); + if (mlname.IsNull()) + mlname = "mpRec2mpData"; + if (!mlname.EndsWith(fgkMPDataExt)) + mlname += fgkMPDataExt; + Mille* mille = new Mille(mlname, bindata); TArrayF buffDLoc; - for (int i=0;iGetEntry(i); int nr = rec->GetNResid(); // number of residual records int nloc = rec->GetNVarLoc(); - if (buffDLoc.GetSize()GetArrGlo(); - const float *recDLoc = rec->GetArrLoc(); - const short *recLabLoc = rec->GetArrLabLoc(); - const int *recLabGlo = rec->GetArrLabGlo(); + if (buffDLoc.GetSize() < nloc) + buffDLoc.Set(nloc + 100); + float* buffLocV = buffDLoc.GetArray(); + const float* recDGlo = rec->GetArrGlo(); + const float* recDLoc = rec->GetArrLoc(); + const short* recLabLoc = rec->GetArrLabLoc(); + const int* recLabGlo = rec->GetArrLabGlo(); // - for (int ir=0;irGetNDGlo(ir); int ndloc = rec->GetNDLoc(ir); // fill 0-suppressed array from MPRecord to non-0-suppressed array of Mille - for (int l=ndloc;l--;) buffLocV[recLabLoc[l]] = recDLoc[l]; + for (int l = ndloc; l--;) + buffLocV[recLabLoc[l]] = recDLoc[l]; // - mille->mille(nloc,buffLocV,ndglo,recDGlo,recLabGlo,rec->GetResid(ir),rec->GetResErr(ir)); + mille->mille(nloc, buffLocV, ndglo, recDGlo, recLabGlo, rec->GetResid(ir), rec->GetResErr(ir)); // recLabGlo += ndglo; // next record - recDGlo += ndglo; - recLabLoc += ndloc; - recDLoc += ndloc; + recDGlo += ndglo; + recLabLoc += ndloc; + recDLoc += ndloc; } mille->end(); } @@ -1641,19 +1789,20 @@ void AliAlgSteer::MPRec2Mille(TTree* mprTree,const char* millefile,Bool_t bindat //____________________________________________________________ void AliAlgSteer::FillStatHisto(int type, float w) { - if (!fHistoStat) CreateStatHisto(); - fHistoStat->Fill( (IsCosmic() ? kNHVars:0) + type, w); + if (!fHistoStat) + CreateStatHisto(); + fHistoStat->Fill((IsCosmic() ? kNHVars : 0) + type, w); } //____________________________________________________________ void AliAlgSteer::CreateStatHisto() { - fHistoStat = new TH1F("stat","stat",2*kNHVars,-0.5,2*kNHVars-0.5); + fHistoStat = new TH1F("stat", "stat", 2 * kNHVars, -0.5, 2 * kNHVars - 0.5); fHistoStat->SetDirectory(0); - TAxis *xax = fHistoStat->GetXaxis(); - for (int j=0;j<2;j++) { - for (int i=0;iSetBinLabel(j*kNHVars+i+1, Form("%s.%s",j?"CSM":"COL",fgkHStatName[i])); + TAxis* xax = fHistoStat->GetXaxis(); + for (int j = 0; j < 2; j++) { + for (int i = 0; i < kNHVars; i++) { + xax->SetBinLabel(j * kNHVars + i + 1, Form("%s.%s", j ? "CSM" : "COL", fgkHStatName[i])); } } } @@ -1662,15 +1811,17 @@ void AliAlgSteer::CreateStatHisto() void AliAlgSteer::PrintLabels() const { // print global IDs and Labels - for (int i=0;iIsDisabled()) continue; + if (det->IsDisabled()) + continue; det->AddAutoConstraints(); } - AliInfoF("Added %d automatic constraints",GetNConstraints()); + AliInfoF("Added %d automatic constraints", GetNConstraints()); } //____________________________________________________________ void AliAlgSteer::WritePedeConstraints() const { // write constraints file - FILE* conFl = fopen (fMPConFileName.Data(),"w+"); + FILE* conFl = fopen(fMPConFileName.Data(), "w+"); // int nconstr = GetNConstraints(); - for (int icon=0;iconWriteChildrenConstraints(conFl); + for (int icon = 0; icon < nconstr; icon++) + GetConstraint(icon)->WriteChildrenConstraints(conFl); // fclose(conFl); } @@ -1708,11 +1861,12 @@ void AliAlgSteer::FixLowStatFromDOFStat(Int_t thresh) return; } if (fNDOFs != fDOFStat->GetNDOFs()) { - AliErrorF("Discrepancy between NDOFs=%d of and statistics object: %d",fNDOFs,fDOFStat->GetNDOFs()); + AliErrorF("Discrepancy between NDOFs=%d of and statistics object: %d", fNDOFs, fDOFStat->GetNDOFs()); return; } - for (int parID=0;parIDGetStat(parID)>=thresh) continue; + for (int parID = 0; parID < fNDOFs; parID++) { + if (fDOFStat->GetStat(parID) >= thresh) + continue; fGloParErr[parID] = -999.; } // @@ -1724,25 +1878,29 @@ void AliAlgSteer::LoadStat(const char* flname) // load statistics histos from external file produced by alignment task TFile* fl = TFile::Open(flname); // - TObject *hdfO=0,*hstO=0; + TObject *hdfO = 0, *hstO = 0; TList* lst = (TList*)fl->Get("clist"); if (lst) { hdfO = lst->FindObject("DOFstat"); - if (hdfO) lst->Remove(hdfO); + if (hdfO) + lst->Remove(hdfO); hstO = lst->FindObject("stat"); - if (hstO) lst->Remove(hstO); + if (hstO) + lst->Remove(hstO); delete lst; - } - else { + } else { hdfO = fl->Get("DOFstat"); hstO = fl->Get("stat"); } TH1F* hst = 0; - if (hstO && (hst=dynamic_cast(hstO))) hst->SetDirectory(0); - else AliWarning("did not find stat histo"); + if (hstO && (hst = dynamic_cast(hstO))) + hst->SetDirectory(0); + else + AliWarning("did not find stat histo"); // AliAlgDOFStat* dofSt = 0; - if (!hdfO || !(dofSt=dynamic_cast(hdfO))) AliWarning("did not find DOFstat object"); + if (!hdfO || !(dofSt = dynamic_cast(hdfO))) + AliWarning("did not find DOFstat object"); // SetHistoStat(hst); SetDOFStat(dofSt); @@ -1752,37 +1910,41 @@ void AliAlgSteer::LoadStat(const char* flname) } //______________________________________________ -void AliAlgSteer::CheckSol(TTree* mpRecTree, Bool_t store, - Bool_t verbose, Bool_t loc, const char* outName) +void AliAlgSteer::CheckSol(TTree* mpRecTree, Bool_t store, + Bool_t verbose, Bool_t loc, const char* outName) { // do fast check of pede solution with MPRecord tree AliAlgResFast* rLG = store ? new AliAlgResFast() : 0; - AliAlgResFast* rL = store&&loc ? new AliAlgResFast() : 0; - TTree *trLG=0,*trL=0; + AliAlgResFast* rL = store && loc ? new AliAlgResFast() : 0; + TTree *trLG = 0, *trL = 0; TFile* outFile = 0; if (store) { TString outNS = outName; - if (outNS.IsNull()) outNS = "resFast"; - if (!outNS.EndsWith(".root")) outNS += ".root"; - outFile = TFile::Open(outNS.Data(),"recreate"); - trLG = new TTree("resFLG","Fast residuals with LG correction"); - trLG->Branch("rLG","AliAlgResFast",&rLG); + if (outNS.IsNull()) + outNS = "resFast"; + if (!outNS.EndsWith(".root")) + outNS += ".root"; + outFile = TFile::Open(outNS.Data(), "recreate"); + trLG = new TTree("resFLG", "Fast residuals with LG correction"); + trLG->Branch("rLG", "AliAlgResFast", &rLG); // if (rL) { - trL = new TTree("resFL","Fast residuals with L correction"); - trL->Branch("rL","AliAlgResFast",&rL); + trL = new TTree("resFL", "Fast residuals with L correction"); + trL->Branch("rL", "AliAlgResFast", &rL); } } // AliAlgMPRecord* rec = new AliAlgMPRecord(); - mpRecTree->SetBranchAddress("mprec",&rec); + mpRecTree->SetBranchAddress("mprec", &rec); int nrec = mpRecTree->GetEntriesFast(); - for (int irec=0;irecGetEntry(irec); - CheckSol(rec,rLG,rL,verbose,loc); + CheckSol(rec, rLG, rL, verbose, loc); // store even in case of failure, to have the trees aligned with controlRes - if (trLG) trLG->Fill(); - if (trL) trL->Fill(); + if (trLG) + trLG->Fill(); + if (trL) + trL->Fill(); } // // save @@ -1801,46 +1963,46 @@ void AliAlgSteer::CheckSol(TTree* mpRecTree, Bool_t store, } //______________________________________________ -Bool_t AliAlgSteer::CheckSol(AliAlgMPRecord* rec, - AliAlgResFast *rLG, AliAlgResFast* rL, - Bool_t verbose, Bool_t loc) +Bool_t AliAlgSteer::CheckSol(AliAlgMPRecord* rec, + AliAlgResFast* rLG, AliAlgResFast* rL, + Bool_t verbose, Bool_t loc) { // Check pede solution using derivates, rather than updated geometry - // If loc==true, also produces residuals for current geometry, + // If loc==true, also produces residuals for current geometry, // neglecting global corrections // - if (rL) loc = kTRUE; // if local sol. tree asked, always evaluate it + if (rL) + loc = kTRUE; // if local sol. tree asked, always evaluate it // int nres = rec->GetNResid(); - // - const float *recDGlo = rec->GetArrGlo(); - const float *recDLoc = rec->GetArrLoc(); - const short *recLabLoc = rec->GetArrLabLoc(); - const int *recLabGlo = rec->GetArrLabGlo(); + // + const float* recDGlo = rec->GetArrGlo(); + const float* recDLoc = rec->GetArrLoc(); + const short* recLabLoc = rec->GetArrLabLoc(); + const int* recLabGlo = rec->GetArrLabGlo(); int nvloc = rec->GetNVarLoc(); // // count number of real measurement duplets and material correction fake 4-plets int nPoints = 0; int nMatCorr = 0; - for (int irs=0;irsGetNDGlo(irs)>0) { - if (irs==nres-1 || rec->GetNDGlo(irs+1)==0) - AliFatal("Real coordinate measurements must come in pairs"); + for (int irs = 0; irs < nres; irs++) { + if (rec->GetNDGlo(irs) > 0) { + if (irs == nres - 1 || rec->GetNDGlo(irs + 1) == 0) + AliFatal("Real coordinate measurements must come in pairs"); nPoints++; - irs++; // skip 2nd + irs++; // skip 2nd continue; - } - else if (rec->GetResid(irs)==0 && rec->GetVolID(irs)==-1) { // material corrections have 0 residual - nMatCorr++; - } - else { // might be fixed parameter, global derivs are skept + } else if (rec->GetResid(irs) == 0 && rec->GetVolID(irs) == -1) { // material corrections have 0 residual + nMatCorr++; + } else { // might be fixed parameter, global derivs are skept nPoints++; - irs++; // skip 2nd - continue; + irs++; // skip 2nd + continue; } } // - if (nMatCorr%4) AliWarningF("Error? NMatCorr=%d is not multiple of 4",nMatCorr); + if (nMatCorr % 4) + AliWarningF("Error? NMatCorr=%d is not multiple of 4", nMatCorr); // if (rLG) { rLG->Clear(); @@ -1856,72 +2018,78 @@ Bool_t AliAlgSteer::CheckSol(AliAlgMPRecord* rec, } // AliSymMatrix* matpG = new AliSymMatrix(nvloc); - TVectorD* vecp=0, *vecpG = new TVectorD(nvloc); + TVectorD *vecp = 0, *vecpG = new TVectorD(nvloc); // - if (loc) vecp = new TVectorD(nvloc); + if (loc) + vecp = new TVectorD(nvloc); // - float chi2Ini=0,chi2L=0,chi2LG=0; + float chi2Ini = 0, chi2L = 0, chi2LG = 0; // // residuals, accounting for global solution - double *resid = new Double_t[nres]; + double* resid = new Double_t[nres]; int* volID = new Int_t[nres]; - for (int irs=0;irsGetResid(irs); resid[irs] = resOr; // int ndglo = rec->GetNDGlo(irs); int ndloc = rec->GetNDLoc(irs); - volID[irs]=0; - for (int ig=0;igGetVolID(); - else volID[irs] = -2; // calibration DOF !!! TODO + AliAlgVol* vol = GetVolOfDOFID(idP); + if (vol) + volID[irs] = vol->GetVolID(); + else + volID[irs] = -2; // calibration DOF !!! TODO } } // - double sg2inv = rec->GetResErr(irs); - sg2inv = 1./(sg2inv*sg2inv); + double sg2inv = rec->GetResErr(irs); + sg2inv = 1. / (sg2inv * sg2inv); // - chi2Ini += resid[irs]*resid[irs]*sg2inv; // chi accounting for global solution only + chi2Ini += resid[irs] * resid[irs] * sg2inv; // chi accounting for global solution only // // Build matrix to solve local parameters - for (int il=0;ilSetChi2Ini(chi2Ini); - if (rLG) rLG->SetChi2Ini(chi2Ini); + if (rL) + rL->SetChi2Ini(chi2Ini); + if (rLG) + rLG->SetChi2Ini(chi2Ini); // TVectorD vecSol(nvloc); TVectorD vecSolG(nvloc); // - if (!matpG->SolveChol(*vecpG,vecSolG,kFALSE)) { + if (!matpG->SolveChol(*vecpG, vecSolG, kFALSE)) { AliInfo("Failed to solve track corrected for globals\n"); delete matpG; matpG = 0; - } - else if (loc) { // solution with local correction only - if (!matpG->SolveChol(*vecp,vecSol,kFALSE)) { + } else if (loc) { // solution with local correction only + if (!matpG->SolveChol(*vecp, vecSol, kFALSE)) { AliInfo("Failed to solve track corrected for globals\n"); delete matpG; matpG = 0; @@ -1932,8 +2100,10 @@ Bool_t AliAlgSteer::CheckSol(AliAlgMPRecord* rec, if (!matpG) { // failed delete[] resid; delete[] volID; - if (rLG) rLG->Clear(); - if (rL) rL->Clear(); + if (rLG) + rLG->Clear(); + if (rL) + rL->Clear(); return kFALSE; } // check @@ -1943,93 +2113,111 @@ Bool_t AliAlgSteer::CheckSol(AliAlgMPRecord* rec, recLabGlo = rec->GetArrLabGlo(); // if (verbose) { - printf(loc ? "Sol L/LG:\n":"Sol LG:\n"); - int nExtP = (nvloc%4) ? 5:4; - for (int i=0;iGetResid(irs); double resL = resOr; double resLG = resid[irs]; - double sg = rec->GetResErr(irs); - double sg2Inv = 1/(sg*sg); + double sg = rec->GetResErr(irs); + double sg2Inv = 1 / (sg * sg); // int ndglo = rec->GetNDGlo(irs); int ndloc = rec->GetNDLoc(irs); // - for (int il=0;il1) idMeas = 0; - if (idMeas==0) pntID++; // measurements come in pairs + if (idMeas > 1) + idMeas = 0; + if (idMeas == 0) + pntID++; // measurements come in pairs int lbl = rec->GetVolID(irs); lbl = ndglo ? recLabGlo[0] : 0; // TMP, until VolID is filled // RS!!!! if (rLG) { - rLG->SetResSigMeas(pntID,idMeas,resLG,sg); - if (idMeas==0) rLG->SetLabel(pntID,lbl,volID[irs]); + rLG->SetResSigMeas(pntID, idMeas, resLG, sg); + if (idMeas == 0) + rLG->SetLabel(pntID, lbl, volID[irs]); } if (rL) { - rL->SetResSigMeas(pntID,idMeas,resL,sg); - if (idMeas==0) rL->SetLabel(pntID,lbl,volID[irs]); + rL->SetResSigMeas(pntID, idMeas, resL, sg); + if (idMeas == 0) + rL->SetLabel(pntID, lbl, volID[irs]); } - } - else { + } else { matID++; // mat.correcitons come in 4-plets, but we fill each separately - // - if (rLG) rLG->SetMatCorr(matID,resLG,sg); - if (rL ) rL->SetMatCorr(matID,resL,sg); + // + if (rLG) + rLG->SetMatCorr(matID, resLG, sg); + if (rL) + rL->SetMatCorr(matID, resL, sg); } // if (verbose) { - int lbl = rec->GetVolID(irs); - lbl = ndglo ? recLabGlo[0] : (resOr==0 ? -1 : 0); // TMP, until VolID is filled // RS!!!! - if (loc) printf("%3d (%9d) %6.4f | [%+.2e:%+7.2f] [%+.2e:%+7.2f]\n", - irs,lbl,sg,resL,resL/sg,resLG,resLG/sg); - else printf("%3d (%9d) %6.4f | [%+.2e:%+7.2f]\n", - irs,lbl,sg,resLG,resLG/sg); + int lbl = rec->GetVolID(irs); + lbl = ndglo ? recLabGlo[0] : (resOr == 0 ? -1 : 0); // TMP, until VolID is filled // RS!!!! + if (loc) + printf("%3d (%9d) %6.4f | [%+.2e:%+7.2f] [%+.2e:%+7.2f]\n", + irs, lbl, sg, resL, resL / sg, resLG, resLG / sg); + else + printf("%3d (%9d) %6.4f | [%+.2e:%+7.2f]\n", + irs, lbl, sg, resLG, resLG / sg); } // recLabGlo += ndglo; // prepare for next record - recDGlo += ndglo; + recDGlo += ndglo; recLabLoc += ndloc; - recDLoc += ndloc; + recDLoc += ndloc; } - if (rL) rL->SetChi2(chi2L); - if (rLG) rLG->SetChi2(chi2LG); + if (rL) + rL->SetChi2(chi2L); + if (rLG) + rLG->SetChi2(chi2LG); // if (verbose) { - printf("Chi: G = %e | LG = %e",chi2Ini,chi2LG); - if (loc) printf(" | L = %e",chi2L); + printf("Chi: G = %e | LG = %e", chi2Ini, chi2LG); + if (loc) + printf(" | L = %e", chi2L); printf("\n"); } // store track corrections int nTrCor = nvloc - matID - 1; - for (int i=0;iGetTrCor()[i] = vecSolG[i]; - if (rL) rL->GetTrCor()[i] = vecSol[i]; + for (int i = 0; i < nTrCor; i++) { + if (rLG) + rLG->GetTrCor()[i] = vecSolG[i]; + if (rL) + rL->GetTrCor()[i] = vecSol[i]; } // delete[] resid; @@ -2042,11 +2230,15 @@ void AliAlgSteer::ApplyAlignmentFromMPSol() { // apply alignment from millepede solution array to reference alignment level AliInfo("Applying alignment from Millepede solution"); - for (int idt=0;idtIsDisabled()) continue; + if (!det || det->IsDisabled()) + continue; det->ApplyAlignmentFromMPSol(); } SetMPAlignDone(); // } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgTrack.cxx b/Detectors/Align/src/AliAlgTrack.cxx index 7bdbe8e6ea416..8c78f8a1a8176 100644 --- a/Detectors/Align/src/AliAlgTrack.cxx +++ b/Detectors/Align/src/AliAlgTrack.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgTrack.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief Track model for the alignment #include #include "AliAlgTrack.h" @@ -25,43 +25,44 @@ #include #include -using namespace AliAlgAux; +using namespace o2::align::AliAlgAux; using namespace TMath; +namespace o2 +{ +namespace align +{ + // RS: this is not good: we define constants outside the class, but it is to -// bypass the CINT limitations on static arrays initializations -const Int_t kRichardsonOrd = 1; // Order of Richardson extrapolation for derivative (min=1) -const Int_t kRichardsonN = kRichardsonOrd+1; // N of 2-point symmetric derivatives needed for requested order -const Int_t kNRDClones = kRichardsonN*2 ;// number of variations for derivative of requested order +// bypass the CINT limitations on static arrays initializations +const Int_t kRichardsonOrd = 1; // Order of Richardson extrapolation for derivative (min=1) +const Int_t kRichardsonN = kRichardsonOrd + 1; // N of 2-point symmetric derivatives needed for requested order +const Int_t kNRDClones = kRichardsonN * 2; // number of variations for derivative of requested order //____________________________________________________________________________ -AliAlgTrack::AliAlgTrack() : - fNLocPar(0) - ,fNLocExtPar(0) - ,fNGloPar(0) - ,fNDF(0) - ,fInnerPointID(0) - // ,fMinX2X0Pt2Account(5/1.0) - ,fMinX2X0Pt2Account(0.5e-3/1.0) - ,fMass(0.14) - ,fChi2(0) - ,fChi2CosmUp(0) - ,fChi2CosmDn(0) - ,fChi2Ini(0) - ,fPoints(0) - ,fLocPar() - ,fGloParID(0) - ,fGloParIDA(0) - ,fLocParA(0) +AliAlgTrack::AliAlgTrack() : fNLocPar(0), fNLocExtPar(0), fNGloPar(0), fNDF(0), fInnerPointID(0) + // ,fMinX2X0Pt2Account(5/1.0) + , + fMinX2X0Pt2Account(0.5e-3 / 1.0), + fMass(0.14), + fChi2(0), + fChi2CosmUp(0), + fChi2CosmDn(0), + fChi2Ini(0), + fPoints(0), + fLocPar(), + fGloParID(0), + fGloParIDA(0), + fLocParA(0) { // def c-tor - for (int i=0;i<2;i++) { + for (int i = 0; i < 2; i++) { // we start with 0 size buffers for derivatives, they will be expanded automatically fResid[i].Set(0); fDResDGlo[i].Set(0); fDResDLoc[i].Set(0); // - fResidA[i] = 0; + fResidA[i] = 0; fDResDLocA[i] = 0; fDResDGloA[i] = 0; } @@ -76,7 +77,7 @@ AliAlgTrack::~AliAlgTrack() } //____________________________________________________________________________ -void AliAlgTrack::Clear(Option_t *) +void AliAlgTrack::Clear(Option_t*) { // reset the track TObject::Clear(); @@ -93,7 +94,7 @@ void AliAlgTrack::Clear(Option_t *) //____________________________________________________________________________ void AliAlgTrack::DefineDOFs() { - // define varied DOF's (local parameters) for the track: + // define varied DOF's (local parameters) for the track: // 1) kinematic params (5 or 4 depending on Bfield) // 2) mult. scattering angles (2) // 3) if requested by point: energy loss @@ -106,36 +107,39 @@ void AliAlgTrack::DefineDOFs() // // start along track direction, i.e. last point in the ordered array int minPar = fNLocPar; - for (int ip=GetInnerPointID()+1;ip--;) { // collision track or cosmic lower leg + for (int ip = GetInnerPointID() + 1; ip--;) { // collision track or cosmic lower leg AliAlgPoint* pnt = GetPoint(ip); pnt->SetMinLocVarID(minPar); - if (pnt->ContainsMaterial()) fNLocPar += pnt->GetNMatPar(); + if (pnt->ContainsMaterial()) + fNLocPar += pnt->GetNMatPar(); pnt->SetMaxLocVarID(fNLocPar); // flag up to which parameted ID this points depends on } // if (IsCosmic()) { minPar = fNLocPar; - for (int ip=GetInnerPointID()+1;ipSetMinLocVarID(minPar); - if (pnt->ContainsMaterial()) fNLocPar += pnt->GetNMatPar(); + if (pnt->ContainsMaterial()) + fNLocPar += pnt->GetNMatPar(); pnt->SetMaxLocVarID(fNLocPar); // flag up to which parameted ID this points depends on } } // - if (fLocPar.GetSize()3 + if (!CalcResidDeriv(params, fNeedInv[0], GetInnerPointID(), 0)) { +#if DEBUG > 3 AliWarning("Failed on derivatives calculation 0"); #endif return kFALSE; } // if (IsCosmic()) { // cosmic upper leg - if (!CalcResidDeriv(params,fNeedInv[1],GetInnerPointID()+1,np-1)) { -#if DEBUG>3 + if (!CalcResidDeriv(params, fNeedInv[1], GetInnerPointID() + 1, np - 1)) { +#if DEBUG > 3 AliWarning("Failed on derivatives calculation 0"); #endif } - } + } // SetDerivDone(); return kTRUE; } //______________________________________________________ -Bool_t AliAlgTrack::CalcResidDeriv(double *params,Bool_t invert,int pFrom,int pTo) +Bool_t AliAlgTrack::CalcResidDeriv(double* params, Bool_t invert, int pFrom, int pTo) { - // Calculate derivatives of residuals vs params for points pFrom to pT. For cosmic upper leg + // Calculate derivatives of residuals vs params for points pFrom to pT. For cosmic upper leg // track parameter may require inversion. - // The 1st 4 or 5 elements of params vector should be the reference AliExternalTrackParam + // The 1st 4 or 5 elements of params vector should be the reference AliExternalTrackParam // Then parameters of material corrections for each point // marked as having materials should come (4 or 5 dependending if ELoss is varied or fixed). // They correspond to kink parameters @@ -199,74 +205,80 @@ Bool_t AliAlgTrack::CalcResidDeriv(double *params,Bool_t invert,int pFrom,int pT // rotated to frame where they error matrix is diagonal. Their conversion to AliExternalTrackParam // increment will be done locally in the ApplyMatCorr routine. // - // The derivatives are calculated using Richardson extrapolation + // The derivatives are calculated using Richardson extrapolation // (like http://root.cern.ch/root/html/ROOT__Math__RichardsonDerivator.html) // - AliExternalTrackParam probD[kNRDClones]; // use this to vary supplied param for derivative calculation + AliExternalTrackParam probD[kNRDClones]; // use this to vary supplied param for derivative calculation double varDelta[kRichardsonN]; - const int kInvElem[kNKinParBON] = {-1,1,1,-1,-1}; + const int kInvElem[kNKinParBON] = {-1, 1, 1, -1, -1}; // - const double kDelta[kNKinParBON] = {0.02,0.02, 0.001,0.001, 0.01}; // variations for ExtTrackParam and material effects + const double kDelta[kNKinParBON] = {0.02, 0.02, 0.001, 0.001, 0.01}; // variations for ExtTrackParam and material effects // double delta[kNKinParBON]; // variations of curvature term are relative - for (int i=kNKinParBOFF;i--;) delta[i] = kDelta[i]; - if (GetFieldON()) delta[kParQ2Pt] = kDelta[kParQ2Pt]*Abs(GetParameter()[kParQ2Pt]); + for (int i = kNKinParBOFF; i--;) + delta[i] = kDelta[i]; + if (GetFieldON()) + delta[kParQ2Pt] = kDelta[kParQ2Pt] * Abs(GetParameter()[kParQ2Pt]); // int pinc; - if (pTo>pFrom) { // fit in points decreasing order: cosmics upper leg + if (pTo > pFrom) { // fit in points decreasing order: cosmics upper leg pTo++; pinc = 1; - } - else { // fit in points increasing order: collision track or cosmics lower leg + } else { // fit in points increasing order: collision track or cosmics lower leg pTo--; pinc = -1; } // 1) derivative wrt AliExternalTrackParam parameters - for (int ipar=fNLocExtPar;ipar--;) { - SetParams(probD,kNRDClones, GetX(),GetAlpha(),params,kTRUE); - if (invert) for (int ic=kNRDClones;ic--;) probD[ic].Invert(); + for (int ipar = fNLocExtPar; ipar--;) { + SetParams(probD, kNRDClones, GetX(), GetAlpha(), params, kTRUE); + if (invert) + for (int ic = kNRDClones; ic--;) + probD[ic].Invert(); double del = delta[ipar]; // - for (int icl=0;iclContainsMaterial()) { // apply material corrections - if (!ApplyMatCorr(probD, kNRDClones, params, pnt)) return kFALSE; - // } + if (!ApplyMatCorr(probD, kNRDClones, params, pnt)) + return kFALSE; + // } // - if (pnt->ContainsMeasurement()) { - int offsDer = ip*fNLocPar + ipar; - RichardsonDeriv(probD, varDelta, pnt, fDResDLocA[0][offsDer], fDResDLocA[1][offsDer]); // calculate derivatives - if (invert&&kInvElem[ipar]<0) { - fDResDLocA[0][offsDer] = -fDResDLocA[0][offsDer]; - fDResDLocA[1][offsDer] = -fDResDLocA[1][offsDer]; - } + if (pnt->ContainsMeasurement()) { + int offsDer = ip * fNLocPar + ipar; + RichardsonDeriv(probD, varDelta, pnt, fDResDLocA[0][offsDer], fDResDLocA[1][offsDer]); // calculate derivatives + if (invert && kInvElem[ipar] < 0) { + fDResDLocA[0][offsDer] = -fDResDLocA[0][offsDer]; + fDResDLocA[1][offsDer] = -fDResDLocA[1][offsDer]; + } } } // loop over points - } // loop over ExtTrackParam parameters + } // loop over ExtTrackParam parameters // // 2) now vary material effect related parameters: MS and eventually ELoss // - for (int ip=pFrom;ip!=pTo;ip+=pinc) { // points are ordered against track direction + for (int ip = pFrom; ip != pTo; ip += pinc) { // points are ordered against track direction AliAlgPoint* pnt = GetPoint(ip); // // global derivatives at this point if (pnt->ContainsMeasurement() && !CalcResidDerivGlo(pnt)) { - #if DEBUG>3 - AliWarningF("Failed on global derivatives calculation at point %d",ip); +#if DEBUG > 3 + AliWarningF("Failed on global derivatives calculation at point %d", ip); pnt->Print("meas"); -#endif - return kFALSE; +#endif + return kFALSE; } // - if (!pnt->ContainsMaterial()) continue; + if (!pnt->ContainsMaterial()) + continue; // int nParFreeI = pnt->GetNMatPar(); // @@ -274,67 +286,71 @@ Bool_t AliAlgTrack::CalcResidDeriv(double *params,Bool_t invert,int pFrom,int pT // while the variation should be done for parameters in the frame where the vector // of material corrections has diagonal cov. matrix -> rotate the delta to this frame double deltaMatD[kNKinParBON]; - pnt->DiagMatCorr(delta,deltaMatD); - // + pnt->DiagMatCorr(delta, deltaMatD); + // // printf("Vary %d [%+.3e %+.3e %+.3e %+.3e] ",ip,deltaMatD[0],deltaMatD[1],deltaMatD[2],deltaMatD[3]); pnt->Print(); - int offsI = pnt->GetMaxLocVarID() - nParFreeI; // the parameters for this point start with this offset - // they are irrelevant for the points upstream - for (int ipar=0;iparGetMaxLocVarID() - nParFreeI; // the parameters for this point start with this offset + // they are irrelevant for the points upstream + for (int ipar = 0; ipar < nParFreeI; ipar++) { // loop over DOFs related to MS and ELoss are point ip double del = deltaMatD[ipar]; // - // We will vary the tracks starting from the original parameters propagated to given point + // We will vary the tracks starting from the original parameters propagated to given point // and stored there (before applying material corrections for this point) - // - SetParams(probD,kNRDClones, pnt->GetXPoint(),pnt->GetAlphaSens(),pnt->GetTrParamWSB(),kFALSE); + // + SetParams(probD, kNRDClones, pnt->GetXPoint(), pnt->GetAlphaSens(), pnt->GetTrParamWSB(), kFALSE); // no need for eventual track inversion here: if needed, this is already done in ParamWSB // - int offsIP = offsI+ipar; // parameter entry in the params array - // printf(" Var:%d (%d) %e\n",ipar,offsIP, del); + int offsIP = offsI + ipar; // parameter entry in the params array + // printf(" Var:%d (%d) %e\n",ipar,offsIP, del); - for (int icl=0;iclContainsMeasurement()) { // calculate derivatives at the scattering point itself - int offsDerIP = ip*fNLocPar + offsIP; - RichardsonDeriv(probD, varDelta, pnt, fDResDLocA[0][offsDerIP], fDResDLocA[1][offsDerIP]); // calculate derivatives for ip - // printf("DR SELF: %e %e at %d (%d)\n",fDResDLocA[0][offsDerIP], fDResDLocA[1][offsDerIP],offsI, offsDerIP); + for (int icl = 0; icl < kRichardsonN; icl++) { // calculate kRichardsonN variations with del, del/2, del/4... + varDelta[icl] = del; + double parOrig = params[offsIP]; + params[offsIP] += del; + // + // apply varied material effects : incremented by delta + if (!ApplyMatCorr(probD[(icl << 1) + 0], params, pnt)) + return kFALSE; + // + // apply varied material effects : decremented by delta + params[offsIP] = parOrig - del; + if (!ApplyMatCorr(probD[(icl << 1) + 1], params, pnt)) + return kFALSE; + // + params[offsIP] = parOrig; + del *= 0.5; + } + if (pnt->ContainsMeasurement()) { // calculate derivatives at the scattering point itself + int offsDerIP = ip * fNLocPar + offsIP; + RichardsonDeriv(probD, varDelta, pnt, fDResDLocA[0][offsDerIP], fDResDLocA[1][offsDerIP]); // calculate derivatives for ip + // printf("DR SELF: %e %e at %d (%d)\n",fDResDLocA[0][offsDerIP], fDResDLocA[1][offsDerIP],offsI, offsDerIP); } // // loop over points whose residuals can be affected by the material effects on point ip - for (int jp=ip+pinc;jp!=pTo;jp+=pinc) { - AliAlgPoint* pntJ = GetPoint(jp); + for (int jp = ip + pinc; jp != pTo; jp += pinc) { + AliAlgPoint* pntJ = GetPoint(jp); - // printf(" DerFor:%d ",jp); pntJ->Print(); + // printf(" DerFor:%d ",jp); pntJ->Print(); - if ( !PropagateParamToPoint(probD, kNRDClones, pntJ) ) return kFALSE; - // - if (pntJ->ContainsMaterial()) { // apply material corrections - if (!ApplyMatCorr(probD,kNRDClones,params,pntJ)) return kFALSE; - } - // - if (pntJ->ContainsMeasurement()) { - int offsDerJ = jp*fNLocPar + offsIP; - // calculate derivatives - RichardsonDeriv(probD, varDelta, pntJ, fDResDLocA[0][offsDerJ], fDResDLocA[1][offsDerJ]); - } - // + if (!PropagateParamToPoint(probD, kNRDClones, pntJ)) + return kFALSE; + // + if (pntJ->ContainsMaterial()) { // apply material corrections + if (!ApplyMatCorr(probD, kNRDClones, params, pntJ)) + return kFALSE; + } + // + if (pntJ->ContainsMeasurement()) { + int offsDerJ = jp * fNLocPar + offsIP; + // calculate derivatives + RichardsonDeriv(probD, varDelta, pntJ, fDResDLocA[0][offsDerJ], fDResDLocA[1][offsDerJ]); + } + // } // << loop over points whose residuals can be affected by the material effects on point ip - } // << loop over DOFs related to MS and ELoss are point ip - } // << loop over all points of the track - // + } // << loop over DOFs related to MS and ELoss are point ip + } // << loop over all points of the track + // return kTRUE; } @@ -342,73 +358,76 @@ Bool_t AliAlgTrack::CalcResidDeriv(double *params,Bool_t invert,int pFrom,int pT Bool_t AliAlgTrack::CalcResidDerivGlo(AliAlgPoint* pnt) { // calculate residuals derivatives over point's sensor and its parents global params - double deriv[AliAlgVol::kNDOFGeom*3]; + double deriv[AliAlgVol::kNDOFGeom * 3]; // const AliAlgSens* sens = pnt->GetSensor(); const AliAlgVol* vol = sens; // precalculated track parameters - double snp=pnt->GetTrParamWSA(kParSnp),tgl=pnt->GetTrParamWSA(kParTgl); - // precalculate track slopes to account tracking X veriation + double snp = pnt->GetTrParamWSA(kParSnp), tgl = pnt->GetTrParamWSA(kParTgl); + // precalculate track slopes to account tracking X veriation // these are coeffs to translate deltaX of the point to deltaY and deltaZ of track - double cspi = 1./Sqrt((1-snp)*(1+snp)), slpY = snp*cspi, slpZ = tgl*cspi; + double cspi = 1. / Sqrt((1 - snp) * (1 + snp)), slpY = snp * cspi, slpZ = tgl * cspi; // - pnt->SetDGloOffs(fNGloPar); // mark 1st entry of derivatives + pnt->SetDGloOffs(fNGloPar); // mark 1st entry of derivatives do { // measurement residuals int nfree = vol->GetNDOFFree(); - if (!nfree) continue; // no free parameters? - sens->DPosTraDParGeom(pnt,deriv,vol==sens ? 0:vol); + if (!nfree) + continue; // no free parameters? + sens->DPosTraDParGeom(pnt, deriv, vol == sens ? 0 : vol); // - CheckExpandDerGloBuffer(fNGloPar+nfree); // if needed, expand derivatives buffer + CheckExpandDerGloBuffer(fNGloPar + nfree); // if needed, expand derivatives buffer // - for (int ip=0;ipIsFreeDOF(ip)) continue; - double* dXYZ = &deriv[ip*3]; // tracking XYZ derivatives over this parameter + for (int ip = 0; ip < AliAlgVol::kNDOFGeom; ip++) { // we need only free parameters + if (!vol->IsFreeDOF(ip)) + continue; + double* dXYZ = &deriv[ip * 3]; // tracking XYZ derivatives over this parameter // residual is defined as diagonalized track_estimate - measured Y,Z in tracking frame - // where the track is evaluated at measured X! + // where the track is evaluated at measured X! // -> take into account modified X using track parameterization at the point (paramWSA) - // Attention: small simplifications(to be checked if it is ok!!!): + // Attention: small simplifications(to be checked if it is ok!!!): // effect of changing X is accounted neglecting track curvature to preserve linearity // // store diagonalized residuals in track buffer - pnt->DiagonalizeResiduals((dXYZ[AliAlgPoint::kX]*slpY - dXYZ[AliAlgPoint::kY]), - (dXYZ[AliAlgPoint::kX]*slpZ - dXYZ[AliAlgPoint::kZ]), - fDResDGloA[0][fNGloPar],fDResDGloA[1][fNGloPar]); + pnt->DiagonalizeResiduals((dXYZ[AliAlgPoint::kX] * slpY - dXYZ[AliAlgPoint::kY]), + (dXYZ[AliAlgPoint::kX] * slpZ - dXYZ[AliAlgPoint::kZ]), + fDResDGloA[0][fNGloPar], fDResDGloA[1][fNGloPar]); // and register global ID of varied parameter fGloParIDA[fNGloPar] = vol->GetParGloID(ip); fNGloPar++; } // - } while( (vol=vol->GetParent()) ); + } while ((vol = vol->GetParent())); // // eventual detector calibration parameters const AliAlgDet* det = sens->GetDetector(); - int ndof=0; - if (det && (ndof=det->GetNCalibDOFs())) { + int ndof = 0; + if (det && (ndof = det->GetNCalibDOFs())) { // if needed, expand derivatives buffer - CheckExpandDerGloBuffer(fNGloPar+det->GetNCalibDOFsFree()); - for (int idf=0;idfIsFreeDOF(idf)) continue; - sens->DPosTraDParCalib(pnt,deriv,idf,0); - pnt->DiagonalizeResiduals((deriv[AliAlgPoint::kX]*slpY - deriv[AliAlgPoint::kY]), - (deriv[AliAlgPoint::kX]*slpZ - deriv[AliAlgPoint::kZ]), - fDResDGloA[0][fNGloPar],fDResDGloA[1][fNGloPar]); + CheckExpandDerGloBuffer(fNGloPar + det->GetNCalibDOFsFree()); + for (int idf = 0; idf < ndof; idf++) { + if (!det->IsFreeDOF(idf)) + continue; + sens->DPosTraDParCalib(pnt, deriv, idf, 0); + pnt->DiagonalizeResiduals((deriv[AliAlgPoint::kX] * slpY - deriv[AliAlgPoint::kY]), + (deriv[AliAlgPoint::kX] * slpZ - deriv[AliAlgPoint::kZ]), + fDResDGloA[0][fNGloPar], fDResDGloA[1][fNGloPar]); // and register global ID of varied parameter fGloParIDA[fNGloPar] = det->GetParGloID(idf); fNGloPar++; } - } + } // - pnt->SetNGloDOFs(fNGloPar-pnt->GetDGloOffs()); // mark number of global derivatives filled + pnt->SetNGloDOFs(fNGloPar - pnt->GetDGloOffs()); // mark number of global derivatives filled // return kTRUE; } //______________________________________________________ -Bool_t AliAlgTrack::CalcResiduals(const double *params) +Bool_t AliAlgTrack::CalcResiduals(const double* params) { // Propagate for given local params and calculate residuals - // The 1st 4 or 5 elements of params vector should be the reference AliExternalTrackParam + // The 1st 4 or 5 elements of params vector should be the reference AliExternalTrackParam // Then parameters of material corrections for each point // marked as having materials should come (4 or 5 dependending if ELoss is varied or fixed). // They correspond to kink parameters @@ -418,23 +437,24 @@ Bool_t AliAlgTrack::CalcResiduals(const double *params) // // If params are not provided, use internal params array // - if (!params) params = fLocParA; + if (!params) + params = fLocParA; int np = GetNPoints(); fChi2 = 0; fNDF = 0; // // collision track or cosmic lower leg - if (!CalcResiduals(params,fNeedInv[0],GetInnerPointID(),0)) { -#if DEBUG>3 + if (!CalcResiduals(params, fNeedInv[0], GetInnerPointID(), 0)) { +#if DEBUG > 3 AliWarning("Failed on residuals calculation 0"); #endif return kFALSE; } // if (IsCosmic()) { // cosmic upper leg - if (!CalcResiduals(params,fNeedInv[1],GetInnerPointID()+1,np-1)) { -#if DEBUG>3 - AliWarning("Failed on residuals calculation 1"); + if (!CalcResiduals(params, fNeedInv[1], GetInnerPointID() + 1, np - 1)) { +#if DEBUG > 3 + AliWarning("Failed on residuals calculation 1"); #endif return kFALSE; } @@ -446,11 +466,11 @@ Bool_t AliAlgTrack::CalcResiduals(const double *params) } //______________________________________________________ -Bool_t AliAlgTrack::CalcResiduals(const double *params,Bool_t invert,int pFrom,int pTo) +Bool_t AliAlgTrack::CalcResiduals(const double* params, Bool_t invert, int pFrom, int pTo) { // Calculate residuals for the single leg from points pFrom to pT - // The 1st 4 or 5 elements of params vector should be corrections to - // the reference AliExternalTrackParam + // The 1st 4 or 5 elements of params vector should be corrections to + // the reference AliExternalTrackParam // Then parameters of material corrections for each point // marked as having materials should come (4 or 5 dependending if ELoss is varied or fixed). // They correspond to kink parameters @@ -459,21 +479,22 @@ Bool_t AliAlgTrack::CalcResiduals(const double *params,Bool_t invert,int pFrom,i // increment will be done locally in the ApplyMatCorr routine. // AliExternalTrackParam probe; - SetParams(probe,GetX(),GetAlpha(),params,kTRUE); - if (invert) probe.Invert(); + SetParams(probe, GetX(), GetAlpha(), params, kTRUE); + if (invert) + probe.Invert(); int pinc; - if (pTo>pFrom) { // fit in points decreasing order: cosmics upper leg + if (pTo > pFrom) { // fit in points decreasing order: cosmics upper leg pTo++; pinc = 1; - } - else { // fit in points increasing order: collision track or cosmics lower leg + } else { // fit in points increasing order: collision track or cosmics lower leg pTo--; pinc = -1; } // - for (int ip=pFrom;ip!=pTo;ip+=pinc) { // points are ordered against track direction + for (int ip = pFrom; ip != pTo; ip += pinc) { // points are ordered against track direction AliAlgPoint* pnt = GetPoint(ip); - if (!PropagateParamToPoint(probe, pnt)) return kFALSE; + if (!PropagateParamToPoint(probe, pnt)) + return kFALSE; // // store the current track kinematics at the point BEFORE applying eventual material // corrections. This kinematics will be later varied around supplied parameters (in the CalcResidDeriv) @@ -481,23 +502,25 @@ Bool_t AliAlgTrack::CalcResiduals(const double *params,Bool_t invert,int pFrom,i // // account for materials // if (pnt->ContainsMaterial()) { // apply material corrections - if (!ApplyMatCorr(probe, params, pnt)) return kFALSE; + if (!ApplyMatCorr(probe, params, pnt)) + return kFALSE; // } pnt->SetTrParamWSA(probe.GetParameter()); // if (pnt->ContainsMeasurement()) { // need to calculate residuals in the frame where errors are orthogonal - pnt->GetResidualsDiag(probe.GetParameter(),fResidA[0][ip],fResidA[1][ip]); - fChi2 += fResidA[0][ip]*fResidA[0][ip]/pnt->GetErrDiag(0); - fChi2 += fResidA[1][ip]*fResidA[1][ip]/pnt->GetErrDiag(1); + pnt->GetResidualsDiag(probe.GetParameter(), fResidA[0][ip], fResidA[1][ip]); + fChi2 += fResidA[0][ip] * fResidA[0][ip] / pnt->GetErrDiag(0); + fChi2 += fResidA[1][ip] * fResidA[1][ip] / pnt->GetErrDiag(1); fNDF += 2; } // if (pnt->ContainsMaterial()) { // material degrees of freedom do not contribute to NDF since they are constrained by 0 expectation int nCorrPar = pnt->GetNMatPar(); - const double *corrDiag = &fLocParA[pnt->GetMaxLocVarID()-nCorrPar]; // corrections in diagonalized frame - float *corCov = pnt->GetMatCorrCov(); // correction diagonalized covariance - for (int i=0;iGetMaxLocVarID() - nCorrPar]; // corrections in diagonalized frame + float* corCov = pnt->GetMatCorrCov(); // correction diagonalized covariance + for (int i = 0; i < nCorrPar; i++) + fChi2 += corrDiag[i] * corrDiag[i] / corCov[i]; } } return kTRUE; @@ -509,10 +532,10 @@ Bool_t AliAlgTrack::PropagateParamToPoint(AliExternalTrackParam* tr, int nTr, co // Propagate set of tracks to the point (only parameters, no error matrix) // VECTORIZE this // - for (int itr=nTr;itr--;) { - if (!PropagateParamToPoint(tr[itr],pnt,maxStep)) { -#if DEBUG>3 - AliErrorF("Failed on clone %d propagation",itr); + for (int itr = nTr; itr--;) { + if (!PropagateParamToPoint(tr[itr], pnt, maxStep)) { +#if DEBUG > 3 + AliErrorF("Failed on clone %d propagation", itr); tr[itr].Print(); pnt->Print("meas mat"); #endif @@ -523,14 +546,14 @@ Bool_t AliAlgTrack::PropagateParamToPoint(AliExternalTrackParam* tr, int nTr, co } //______________________________________________________ -Bool_t AliAlgTrack::PropagateParamToPoint(AliExternalTrackParam &tr, const AliAlgPoint* pnt, double maxStep) +Bool_t AliAlgTrack::PropagateParamToPoint(AliExternalTrackParam& tr, const AliAlgPoint* pnt, double maxStep) { // propagate tracks to the point (only parameters, no error matrix) - double xyz[3],bxyz[3]; + double xyz[3], bxyz[3]; // if (!tr.RotateParamOnly(pnt->GetAlphaSens())) { -#if DEBUG>3 - AliErrorF("Failed to rotate to alpha=%f",pnt->GetAlphaSens()); +#if DEBUG > 3 + AliErrorF("Failed to rotate to alpha=%f", pnt->GetAlphaSens()); tr.Print(); pnt->Print(); #endif @@ -540,45 +563,43 @@ Bool_t AliAlgTrack::PropagateParamToPoint(AliExternalTrackParam &tr, const AliAl double xTgt = pnt->GetXPoint(); double xBeg = tr.GetX(); double dx = xTgt - xBeg; - int nstep = int(Abs(dx)/maxStep)+1; - dx/=nstep; + int nstep = int(Abs(dx) / maxStep) + 1; + dx /= nstep; // - for (int ist=nstep;ist--;) { + for (int ist = nstep; ist--;) { // - double xToGo = xTgt - dx*ist; + double xToGo = xTgt - dx * ist; tr.GetXYZ(xyz); // if (GetFieldON()) { if (pnt->GetUseBzOnly()) { - if (!tr.PropagateParamOnlyTo(xToGo,AliTrackerBase::GetBz(xyz))) { -#if DEBUG>3 - AliErrorF("Failed to propagate(BZ) to X=%f",pnt->GetXPoint()); - tr.Print(); - pnt->Print(); + if (!tr.PropagateParamOnlyTo(xToGo, AliTrackerBase::GetBz(xyz))) { +#if DEBUG > 3 + AliErrorF("Failed to propagate(BZ) to X=%f", pnt->GetXPoint()); + tr.Print(); + pnt->Print(); #endif - return kFALSE; - } - } - else { - AliTrackerBase::GetBxByBz(xyz,bxyz); - if (!tr.PropagateParamOnlyBxByBzTo(xToGo,bxyz)) { -#if DEBUG>3 - AliErrorF("Failed to propagate(BXYZ) to X=%f",pnt->GetXPoint()); - tr.Print(); - pnt->Print(); + return kFALSE; + } + } else { + AliTrackerBase::GetBxByBz(xyz, bxyz); + if (!tr.PropagateParamOnlyBxByBzTo(xToGo, bxyz)) { +#if DEBUG > 3 + AliErrorF("Failed to propagate(BXYZ) to X=%f", pnt->GetXPoint()); + tr.Print(); + pnt->Print(); #endif - return kFALSE; - } + return kFALSE; + } } - } - else { // straigth line propagation - if ( !tr.PropagateParamOnlyTo(xToGo,0) ) { -#if DEBUG>3 - AliErrorF("Failed to propagate(B=0) to X=%f",pnt->GetXPoint()); - tr.Print(); - pnt->Print(); + } else { // straigth line propagation + if (!tr.PropagateParamOnlyTo(xToGo, 0)) { +#if DEBUG > 3 + AliErrorF("Failed to propagate(B=0) to X=%f", pnt->GetXPoint()); + tr.Print(); + pnt->Print(); #endif - return kFALSE; + return kFALSE; } } } // steps @@ -587,88 +608,93 @@ Bool_t AliAlgTrack::PropagateParamToPoint(AliExternalTrackParam &tr, const AliAl } //______________________________________________________ -Bool_t AliAlgTrack::PropagateToPoint(AliExternalTrackParam &tr, const AliAlgPoint* pnt, - int minNSteps, double maxStep, Bool_t matCor, double *matPar) +Bool_t AliAlgTrack::PropagateToPoint(AliExternalTrackParam& tr, const AliAlgPoint* pnt, + int minNSteps, double maxStep, Bool_t matCor, double* matPar) { // propagate tracks to the point. If matCor is true, then material corrections will be applied. // if matPar pointer is provided, it will be filled by total x2x0 and signed xrho if (!tr.Rotate(pnt->GetAlphaSens())) { -#if DEBUG>3 - AliWarning(Form("Failed to rotate to alpha=%f",pnt->GetAlphaSens())); +#if DEBUG > 3 + AliWarning(Form("Failed to rotate to alpha=%f", pnt->GetAlphaSens())); tr.Print(); #endif return kFALSE; } // - double xyz0[3],xyz1[3],bxyz[3],matarr[7]; - double xPoint=pnt->GetXPoint(),dx=xPoint-tr.GetX(),dxa=Abs(dx),step=dxa/minNSteps; - if (matPar) matPar[0]=matPar[1]=0; - if (dxamaxStep) step = maxStep; - int nstep = int(dxa/step); - step = dxa/nstep; - if (dx<0) step = -step; + double xyz0[3], xyz1[3], bxyz[3], matarr[7]; + double xPoint = pnt->GetXPoint(), dx = xPoint - tr.GetX(), dxa = Abs(dx), step = dxa / minNSteps; + if (matPar) + matPar[0] = matPar[1] = 0; + if (dxa < kTinyDist) + return kTRUE; + if (step > maxStep) + step = maxStep; + int nstep = int(dxa / step); + step = dxa / nstep; + if (dx < 0) + step = -step; // // printf("-->will go from X:%e to X:%e in %d steps of %f\n",tr.GetX(),xPoint,nstep,step); // do we go along or against track direction - Bool_t alongTrackDir = (dx>0&&!pnt->IsInvDir()) || (dx<0&&pnt->IsInvDir()); - Bool_t queryXYZ = matCor||GetFieldON(); - if (queryXYZ) tr.GetXYZ(xyz0); - // - double x2X0Tot=0,xrhoTot=0; - for (int ist=nstep;ist--;) { // single propagation step >> - double xToGo = xPoint - step*ist; + Bool_t alongTrackDir = (dx > 0 && !pnt->IsInvDir()) || (dx < 0 && pnt->IsInvDir()); + Bool_t queryXYZ = matCor || GetFieldON(); + if (queryXYZ) + tr.GetXYZ(xyz0); + // + double x2X0Tot = 0, xrhoTot = 0; + for (int ist = nstep; ist--;) { // single propagation step >> + double xToGo = xPoint - step * ist; // if (GetFieldON()) { if (pnt->GetUseBzOnly()) { - if (!tr.PropagateTo(xToGo,AliTrackerBase::GetBz(xyz0))) { -#if DEBUG>3 - AliWarningF("Failed to propagate(BZ) to X=%f",xToGo); - tr.Print(); + if (!tr.PropagateTo(xToGo, AliTrackerBase::GetBz(xyz0))) { +#if DEBUG > 3 + AliWarningF("Failed to propagate(BZ) to X=%f", xToGo); + tr.Print(); #endif - return kFALSE; - } - } - else { - AliTrackerBase::GetBxByBz(xyz0,bxyz); - if (!tr.PropagateToBxByBz(xToGo,bxyz)) { -#if DEBUG>3 - AliWarningF("Failed to propagate(BXYZ) to X=%f",xToGo); + return kFALSE; + } + } else { + AliTrackerBase::GetBxByBz(xyz0, bxyz); + if (!tr.PropagateToBxByBz(xToGo, bxyz)) { +#if DEBUG > 3 + AliWarningF("Failed to propagate(BXYZ) to X=%f", xToGo); #endif - return kFALSE; - } + return kFALSE; + } } - } - else { // straigth line propagation - if ( !tr.PropagateTo(xToGo,0) ) { -#if DEBUG>3 - AliWarningF("Failed to propagate(B=0) to X=%f",xToGo); + } else { // straigth line propagation + if (!tr.PropagateTo(xToGo, 0)) { +#if DEBUG > 3 + AliWarningF("Failed to propagate(B=0) to X=%f", xToGo); #endif - return kFALSE; + return kFALSE; } } // if (queryXYZ) { tr.GetXYZ(xyz1); if (matCor) { - AliTrackerBase::MeanMaterialBudget(xyz0,xyz1,matarr); - Double_t xrho=matarr[0]*matarr[4], xx0=matarr[1]; - if (alongTrackDir) xrho = -xrho; // if we go along track direction, energy correction is negative - x2X0Tot += xx0; - xrhoTot += xrho; - // printf("MAT %+7.2f %+7.2f %+7.2f -> %+7.2f %+7.2f %+7.2f | %+e %+e | -> %+e %+e | %+e %+e %+e %+e %+e\n", - // xyz0[0],xyz0[1],xyz0[2], xyz1[0],xyz1[1],xyz1[2], tr.Phi(), tr.GetAlpha(), - // x2X0Tot,xrhoTot, matarr[0],matarr[1],matarr[2],matarr[3],matarr[4]); - if (!tr.CorrectForMeanMaterial(xx0,xrho,fMass)) { -#if DEBUG>3 - AliWarningF("Failed on CorrectForMeanMaterial(%f,%f,%f)",xx0,xrho,fMass); - tr.Print(); + AliTrackerBase::MeanMaterialBudget(xyz0, xyz1, matarr); + Double_t xrho = matarr[0] * matarr[4], xx0 = matarr[1]; + if (alongTrackDir) + xrho = -xrho; // if we go along track direction, energy correction is negative + x2X0Tot += xx0; + xrhoTot += xrho; + // printf("MAT %+7.2f %+7.2f %+7.2f -> %+7.2f %+7.2f %+7.2f | %+e %+e | -> %+e %+e | %+e %+e %+e %+e %+e\n", + // xyz0[0],xyz0[1],xyz0[2], xyz1[0],xyz1[1],xyz1[2], tr.Phi(), tr.GetAlpha(), + // x2X0Tot,xrhoTot, matarr[0],matarr[1],matarr[2],matarr[3],matarr[4]); + if (!tr.CorrectForMeanMaterial(xx0, xrho, fMass)) { +#if DEBUG > 3 + AliWarningF("Failed on CorrectForMeanMaterial(%f,%f,%f)", xx0, xrho, fMass); + tr.Print(); #endif - return kFALSE; - } + return kFALSE; + } } - for (int l=3;l--;) xyz0[l] = xyz1[l]; + for (int l = 3; l--;) + xyz0[l] = xyz1[l]; } } // single propagation step << // @@ -684,9 +710,9 @@ Bool_t AliAlgTrack::PropagateToPoint(AliExternalTrackParam &tr, const AliAlgPoin Bool_t AliAlgTrack::ApplyMS(AliExternalTrackParam& trPar, double tms,double pms) { //------------------------------------------------------------------------------ - // Modify track par (e.g. AliExternalTrackParam) in the tracking frame - // (dip angle lam, az. angle phi) - // by multiple scattering defined by polar and azumuthal scattering angles in + // Modify track par (e.g. AliExternalTrackParam) in the tracking frame + // (dip angle lam, az. angle phi) + // by multiple scattering defined by polar and azumuthal scattering angles in // the track collinear frame (tms and pms resp). // The updated direction vector in the tracking frame becomes // @@ -701,7 +727,7 @@ Bool_t AliAlgTrack::ApplyMS(AliExternalTrackParam& trPar, double tms,double pms) if (Abs(tms)<1e-7) return kTRUE; // double snTms = Sin(tms), csTms = Cos(tms); - double snPms = Sin(pms), csPms = Cos(pms); + double snPms = Sin(pms), csPms = Cos(pms); double snPhi = par[2], csPhi = Sqrt((1.-snPhi)*(1.+snPhi)); double csLam = 1./Sqrt(1.+par[3]*par[3]), snLam = csLam*par[3]; // @@ -725,83 +751,87 @@ Bool_t AliAlgTrack::ApplyMS(AliExternalTrackParam& trPar, double tms,double pms) */ //______________________________________________________ -Bool_t AliAlgTrack::ApplyMatCorr(AliExternalTrackParam& trPar, const Double_t *corrPar, const AliAlgPoint* pnt) +Bool_t AliAlgTrack::ApplyMatCorr(AliExternalTrackParam& trPar, const Double_t* corrPar, const AliAlgPoint* pnt) { - // Modify track param (e.g. AliExternalTrackParam) in the tracking frame + // Modify track param (e.g. AliExternalTrackParam) in the tracking frame // by delta accounting for material effects - // Note: corrPar contains delta to track parameters rotated by the matrix + // Note: corrPar contains delta to track parameters rotated by the matrix // DIAGONALIZING ITS COVARIANCE MATRIX! // transform parameters from the frame diagonalizing the errors to track frame double corr[kNKinParBON] = {0}; if (pnt->ContainsMaterial()) { // are there free params from meterials? int nCorrPar = pnt->GetNMatPar(); - const double *corrDiag = &corrPar[pnt->GetMaxLocVarID()-nCorrPar]; // material corrections for this point start here - pnt->UnDiagMatCorr(corrDiag, corr); // this is to account for MS and RANDOM Eloss (if varied) + const double* corrDiag = &corrPar[pnt->GetMaxLocVarID() - nCorrPar]; // material corrections for this point start here + pnt->UnDiagMatCorr(corrDiag, corr); // this is to account for MS and RANDOM Eloss (if varied) } // to this we should add expected parameters modification due to the deterministic eloss - float *detELoss = pnt->GetMatCorrExp(); - for (int i=kNKinParBON;i--;) corr[i] += detELoss[i]; + float* detELoss = pnt->GetMatCorrExp(); + for (int i = kNKinParBON; i--;) + corr[i] += detELoss[i]; //corr[kParQ2Pt] += detELoss[kParQ2Pt]; // printf("apply corr UD %+.3e %+.3e %+.3e %+.3e %+.3e\n",corr[0],corr[1],corr[2],corr[3],corr[4]); - // printf(" corr D %+.3e %+.3e %+.3e %+.3e\n",corrDiag[0],corrDiag[1],corrDiag[2],corrDiag[3]); + // printf(" corr D %+.3e %+.3e %+.3e %+.3e\n",corrDiag[0],corrDiag[1],corrDiag[2],corrDiag[3]); // printf("at point :"); pnt->Print(); - return ApplyMatCorr(trPar,corr); + return ApplyMatCorr(trPar, corr); // } //______________________________________________________ -Bool_t AliAlgTrack::ApplyMatCorr(AliExternalTrackParam& trPar, const Double_t *corr) +Bool_t AliAlgTrack::ApplyMatCorr(AliExternalTrackParam& trPar, const Double_t* corr) { - // Modify track param (e.g. AliExternalTrackParam) in the tracking frame + // Modify track param (e.g. AliExternalTrackParam) in the tracking frame // by delta accounting for material effects // Note: corr contains delta to track frame, NOT in diagonalized one const double kMaxSnp = 0.95; double* par = (double*)trPar.GetParameter(); - double snpNew = par[kParSnp]+corr[kParSnp]; - if (Abs(snpNew)>kMaxSnp) { -#if DEBUG>3 - AliErrorF("Snp is too large: %f",snpNew); - printf("DeltaPar: "); - for (int i=0;i kMaxSnp) { +#if DEBUG > 3 + AliErrorF("Snp is too large: %f", snpNew); + printf("DeltaPar: "); + for (int i = 0; i < kNKinParBON; i++) + printf("%+.3e ", corr[i]); + printf("\n"); + trPar.Print(); #endif return kFALSE; } - par[kParY] += corr[kParY]; - par[kParZ] += corr[kParZ]; - par[kParSnp] = snpNew; - par[kParTgl] += corr[kParTgl]; + par[kParY] += corr[kParY]; + par[kParZ] += corr[kParZ]; + par[kParSnp] = snpNew; + par[kParTgl] += corr[kParTgl]; par[kParQ2Pt] += corr[kParQ2Pt]; return kTRUE; } //______________________________________________________ -Bool_t AliAlgTrack::ApplyMatCorr(AliExternalTrackParam* trSet, int ntr, const Double_t *corrDiag, const AliAlgPoint* pnt) +Bool_t AliAlgTrack::ApplyMatCorr(AliExternalTrackParam* trSet, int ntr, const Double_t* corrDiag, const AliAlgPoint* pnt) { - // Modify set of track params (e.g. AliExternalTrackParam) in the tracking frame + // Modify set of track params (e.g. AliExternalTrackParam) in the tracking frame // by delta accounting for material effects - // Note: corrDiag contain delta to track parameters rotated by the matrix DIAGONALIZING ITS + // Note: corrDiag contain delta to track parameters rotated by the matrix DIAGONALIZING ITS // COVARIANCE MATRIX // transform parameters from the frame diagonalizing the errors to track frame double corr[kNKinParBON] = {0}; if (pnt->ContainsMaterial()) { // are there free params from meterials? int nCorrPar = pnt->GetNMatPar(); - const double *corrDiagP = &corrDiag[pnt->GetMaxLocVarID()-nCorrPar]; // material corrections for this point start here + const double* corrDiagP = &corrDiag[pnt->GetMaxLocVarID() - nCorrPar]; // material corrections for this point start here pnt->UnDiagMatCorr(corrDiagP, corr); } - float *detELoss = pnt->GetMatCorrExp(); - for (int i=kNKinParBON;i--;) corr[i] += detELoss[i]; + float* detELoss = pnt->GetMatCorrExp(); + for (int i = kNKinParBON; i--;) + corr[i] += detELoss[i]; // if (!pnt->GetELossVaried()) corr[kParQ2Pt] = pnt->GetMatCorrExp()[kParQ2Pt]; // fixed eloss expected effect // printf("apply corr UD %+.3e %+.3e %+.3e %+.3e\n",corr[0],corr[1],corr[2],corr[3]); - // printf(" corr D %+.3e %+.3e %+.3e %+.3e\n",corrDiagP[0],corrDiagP[1],corrDiagP[2],corrDiagP[3]); + // printf(" corr D %+.3e %+.3e %+.3e %+.3e\n",corrDiagP[0],corrDiagP[1],corrDiagP[2],corrDiagP[3]); // printf("at point :"); pnt->Print(); // - for (int itr=ntr;itr--;) { - if (!ApplyMatCorr(trSet[itr],corr)) { -#if DEBUG>3 - AliErrorF("Failed on clone %d materials",itr); + for (int itr = ntr; itr--;) { + if (!ApplyMatCorr(trSet[itr], corr)) { +#if DEBUG > 3 + AliErrorF("Failed on clone %d materials", itr); trSet[itr].Print(); -#endif +#endif return kFALSE; } } @@ -809,64 +839,72 @@ Bool_t AliAlgTrack::ApplyMatCorr(AliExternalTrackParam* trSet, int ntr, const Do } //______________________________________________ -Double_t AliAlgTrack::RichardsonExtrap(double *val, int ord) +Double_t AliAlgTrack::RichardsonExtrap(double* val, int ord) { // Calculate Richardson extrapolation of order ord (starting from 1) // The array val should contain estimates ord+1 of derivatives with variations // d, d/2 ... d/2^ord. // The array val is overwritten // - if (ord==1) return (4.*val[1] - val[0])*(1./3); - do {for (int i=0;iGetResidualsDiag(trSet[(icl<<1)+0].GetParameter(), resYVP, resZVP); // variation with +delta - pnt->GetResidualsDiag(trSet[(icl<<1)+1].GetParameter(), resYVN, resZVN); // variation with -delta - derRichY[icl] = 0.5*(resYVP-resYVN)/delta[icl]; // 2-point symmetric derivatives - derRichZ[icl] = 0.5*(resZVP-resZVN)/delta[icl]; + static double derRichY[kRichardsonN], derRichZ[kRichardsonN]; + // + for (int icl = 0; icl < kRichardsonN; icl++) { // calculate kRichardsonN variations with del, del/2, del/4... + double resYVP = 0, resYVN = 0, resZVP = 0, resZVN = 0; + pnt->GetResidualsDiag(trSet[(icl << 1) + 0].GetParameter(), resYVP, resZVP); // variation with +delta + pnt->GetResidualsDiag(trSet[(icl << 1) + 1].GetParameter(), resYVN, resZVN); // variation with -delta + derRichY[icl] = 0.5 * (resYVP - resYVN) / delta[icl]; // 2-point symmetric derivatives + derRichZ[icl] = 0.5 * (resZVP - resZVN) / delta[icl]; } - derY = RichardsonExtrap(derRichY,kRichardsonOrd); // dY/dPar - derZ = RichardsonExtrap(derRichZ,kRichardsonOrd); // dZ/dPar + derY = RichardsonExtrap(derRichY, kRichardsonOrd); // dY/dPar + derZ = RichardsonExtrap(derRichZ, kRichardsonOrd); // dZ/dPar // } //______________________________________________ -void AliAlgTrack::Print(Option_t *opt) const +void AliAlgTrack::Print(Option_t* opt) const { // print track data - printf("%s ",IsCosmic() ? " Cosmic ":"Collision "); + printf("%s ", IsCosmic() ? " Cosmic " : "Collision "); AliExternalTrackParam::Print(); printf("N Free Par: %d (Kinem: %d) | Npoints: %d (Inner:%d) | M : %.3f | Chi2Ini:%.1f Chi2: %.1f/%d", - fNLocPar,fNLocExtPar,GetNPoints(),GetInnerPointID(),fMass,fChi2Ini,fChi2,fNDF); + fNLocPar, fNLocExtPar, GetNPoints(), GetInnerPointID(), fMass, fChi2Ini, fChi2, fNDF); if (IsCosmic()) { int npLow = GetInnerPointID(); - int npUp = GetNPoints() - npLow - 1; - printf(" [Low:%.1f/%d Up:%.1f/%d]",fChi2CosmDn,npLow, fChi2CosmUp,npUp); + int npUp = GetNPoints() - npLow - 1; + printf(" [Low:%.1f/%d Up:%.1f/%d]", fChi2CosmDn, npLow, fChi2CosmUp, npUp); } printf("\n"); // @@ -874,46 +912,55 @@ void AliAlgTrack::Print(Option_t *opt) const optS.ToLower(); Bool_t res = optS.Contains("r") && GetResidDone(); Bool_t der = optS.Contains("d") && GetDerivDone(); - Bool_t par = optS.Contains("lc"); // local param corrections + Bool_t par = optS.Contains("lc"); // local param corrections Bool_t paru = optS.Contains("lcu"); // local param corrections in track param frame // if (par) { - printf("Ref.track corr: "); for (int i=0;iPrint(opt); + pnt->Print(opt); // if (res && pnt->ContainsMeasurement()) { - printf(" Residuals : %+.3e %+.3e -> Pulls: %+7.2f %+7.2f\n", - GetResidual(0,ip),GetResidual(1,ip), - GetResidual(0,ip)/sqrt(pnt->GetErrDiag(0)),GetResidual(1,ip)/sqrt(pnt->GetErrDiag(1))); + printf(" Residuals : %+.3e %+.3e -> Pulls: %+7.2f %+7.2f\n", + GetResidual(0, ip), GetResidual(1, ip), + GetResidual(0, ip) / sqrt(pnt->GetErrDiag(0)), GetResidual(1, ip) / sqrt(pnt->GetErrDiag(1))); } if (der && pnt->ContainsMeasurement()) { - for (int ipar=0;iparContainsMaterial()) { // material corrections - int nCorrPar = pnt->GetNMatPar(); - const double *corrDiag = &fLocParA[pnt->GetMaxLocVarID()-nCorrPar]; - printf(" Corr.Diag: "); - for (int i=0;iGetMatCorrCov(); // correction covariance - //float *corExp = pnt->GetMatCorrExp(); // correction expectation - for (int i=0;iUnDiagMatCorr(corrDiag, corr); - // if (!pnt->GetELossVaried()) corr[kParQ2Pt] = pnt->GetMatCorrExp()[kParQ2Pt]; // fixed eloss expected effect - printf(" Corr.Track: "); - for (int i=0;iGetNMatPar(); + const double* corrDiag = &fLocParA[pnt->GetMaxLocVarID() - nCorrPar]; + printf(" Corr.Diag: "); + for (int i = 0; i < nCorrPar; i++) + printf("%+.3e ", corrDiag[i]); + printf("\n"); + printf(" Corr.Pull: "); + float* corCov = pnt->GetMatCorrCov(); // correction covariance + //float *corExp = pnt->GetMatCorrExp(); // correction expectation + for (int i = 0; i < nCorrPar; i++) + printf("%+.3e ", (corrDiag[i] /* - corExp[i]*/) / Sqrt(corCov[i])); + printf("\n"); + if (paru) { // print also mat.corrections in track frame + double corr[5] = {0}; + pnt->UnDiagMatCorr(corrDiag, corr); + // if (!pnt->GetELossVaried()) corr[kParQ2Pt] = pnt->GetMatCorrExp()[kParQ2Pt]; // fixed eloss expected effect + printf(" Corr.Track: "); + for (int i = 0; i < kNKinParBON; i++) + printf("%+.3e ", corr[i]); + printf("\n"); + } } } } // print points @@ -924,34 +971,34 @@ void AliAlgTrack::DumpCoordinates() const { // print various coordinates for inspection printf("gpx/D:gpy/D:gpz/D:gtxb/D:gtyb/D:gtzb/D:gtxa/D:gtya/D:gtza/D:alp/D:px/D:py/D:pz/D:tyb/D:tzb/D:tya/D:tza/D:ey/D:ez/D\n"); - for (int ip=0;ipContainsMeasurement()) continue; + if (!pnt->ContainsMeasurement()) + continue; pnt->DumpCoordinates(); } } //______________________________________________ -Bool_t AliAlgTrack::IniFit() +Bool_t AliAlgTrack::IniFit() { // perform initial fit of the track // - const int kMinNStep = 3; - const double kMaxDefStep = 3.0; + const int kMinNStep = 3; + const double kMaxDefStep = 3.0; // AliExternalTrackParam trc = *this; // if (!GetFieldON()) { // for field-off data impose nominal momentum - } fChi2 = fChi2CosmUp = fChi2CosmDn = 0; // - // the points are ranged from outer to inner for collision tracks, - // and from outer point of lower leg to outer point of upper leg for the cosmic track + // the points are ranged from outer to inner for collision tracks, + // and from outer point of lower leg to outer point of upper leg for the cosmic track // // the fit will always start from the outgoing track in inward direction - if (!FitLeg(trc,0,GetInnerPointID(),fNeedInv[0])) { -#if DEBUG>3 + if (!FitLeg(trc, 0, GetInnerPointID(), fNeedInv[0])) { +#if DEBUG > 3 AliWarning("Failed FitLeg 0"); trc.Print(); #endif @@ -963,8 +1010,8 @@ Bool_t AliAlgTrack::IniFit() if (IsCosmic()) { fChi2CosmDn = fChi2; AliExternalTrackParam trcU = trc; - if (!FitLeg(trcU,GetNPoints()-1,GetInnerPointID()+1,fNeedInv[1])) { //fit upper leg of cosmic track -#if DEBUG>3 + if (!FitLeg(trcU, GetNPoints() - 1, GetInnerPointID() + 1, fNeedInv[1])) { //fit upper leg of cosmic track +#if DEBUG > 3 AliWarning("Failed FitLeg 0"); trc.Print(); #endif @@ -973,13 +1020,15 @@ Bool_t AliAlgTrack::IniFit() // // propagate to reference point, which is the inner point of lower leg const AliAlgPoint* refP = GetPoint(GetInnerPointID()); - if (!PropagateToPoint(trcU,refP,kMinNStep,kMaxDefStep,kTRUE)) return kFALSE; + if (!PropagateToPoint(trcU, refP, kMinNStep, kMaxDefStep, kTRUE)) + return kFALSE; // fChi2CosmUp = fChi2 - fChi2CosmDn; // printf("Upper leg: %d %d\n",GetInnerPointID()+1,GetNPoints()-1); trcU.Print(); // - if (!CombineTracks(trc,trcU)) return kFALSE; - //printf("Combined\n"); trc.Print(); + if (!CombineTracks(trc, trcU)) + return kFALSE; + //printf("Combined\n"); trc.Print(); } CopyFrom(&trc); // @@ -1000,140 +1049,143 @@ Bool_t AliAlgTrack::CombineTracks(AliExternalTrackParam& trcL, const AliExternal // CL' = CL - K*CL // vL' = vL + K(vU-vL) // - if (Abs(trcL.GetX()-trcU.GetX())>kTinyDist || Abs(trcL.GetAlpha()-trcU.GetAlpha())>kTinyDist) { + if (Abs(trcL.GetX() - trcU.GetX()) > kTinyDist || Abs(trcL.GetAlpha() - trcU.GetAlpha()) > kTinyDist) { AliError("Tracks must be defined at same reference X and Alpha"); trcL.Print(); trcU.Print(); return kFALSE; } // - const double* covU=trcU.GetCovariance(),*parU=trcU.GetParameter(); - double* covL=(double*)trcL.GetCovariance(),*parL=(double*)trcL.GetParameter(); + const double *covU = trcU.GetCovariance(), *parU = trcU.GetParameter(); + double *covL = (double*)trcL.GetCovariance(), *parL = (double*)trcL.GetParameter(); // int mtSize = GetFieldON() ? kNKinParBON : kNKinParBOFF; - TMatrixD matCL(mtSize,mtSize),matCLplCU(mtSize,mtSize); - TVectorD vl(mtSize),vUmnvL(mtSize); + TMatrixD matCL(mtSize, mtSize), matCLplCU(mtSize, mtSize); + TVectorD vl(mtSize), vUmnvL(mtSize); // // trcL.Print(); // trcU.Print(); // - for (int i=mtSize;i--;) { - vUmnvL[i] = parU[i] - parL[i]; // y = residual of 2 tracks - vl[i] = parL[i]; - for (int j=i+1;j--;) { - int indIJ = ((i*(i+1))>>1)+j; // position of IJ cov element in the AliExternalTrackParam covariance array - matCL(i,j) = matCL(j,i) = covL[indIJ]; - matCLplCU(i,j) = matCLplCU(j,i) = covL[indIJ] + covU[indIJ]; + for (int i = mtSize; i--;) { + vUmnvL[i] = parU[i] - parL[i]; // y = residual of 2 tracks + vl[i] = parL[i]; + for (int j = i + 1; j--;) { + int indIJ = ((i * (i + 1)) >> 1) + j; // position of IJ cov element in the AliExternalTrackParam covariance array + matCL(i, j) = matCL(j, i) = covL[indIJ]; + matCLplCU(i, j) = matCLplCU(j, i) = covL[indIJ] + covU[indIJ]; } } - matCLplCU.Invert(); // S^-1 = (Cl + Cu)^-1 - if (!matCLplCU.IsValid()) { -#if DEBUG>3 + matCLplCU.Invert(); // S^-1 = (Cl + Cu)^-1 + if (!matCLplCU.IsValid()) { +#if DEBUG > 3 AliError("Failed to invert summed cov.matrix of cosmic track"); matCLplCU.Print(); -#endif +#endif return kFALSE; // inversion failed } - TMatrixD matK(matCL,TMatrixD::kMult,matCLplCU); // gain K = Cl*(Cl+Cu)^-1 - TMatrixD matKdotCL(matK,TMatrixD::kMult,matCL); // K*Cl - TVectorD vlUp = matK*vUmnvL; // K*(vl - vu) - for (int i=mtSize;i--;) { - parL[i] += vlUp[i]; // updated param: vL' = vL + K(vU-vL) - for (int j=i+1;j--;) covL[((i*(i+1))>>1)+j] -= matKdotCL(i,j); // updated covariance: Cl' = Cl - K*Cl - } + TMatrixD matK(matCL, TMatrixD::kMult, matCLplCU); // gain K = Cl*(Cl+Cu)^-1 + TMatrixD matKdotCL(matK, TMatrixD::kMult, matCL); // K*Cl + TVectorD vlUp = matK * vUmnvL; // K*(vl - vu) + for (int i = mtSize; i--;) { + parL[i] += vlUp[i]; // updated param: vL' = vL + K(vU-vL) + for (int j = i + 1; j--;) + covL[((i * (i + 1)) >> 1) + j] -= matKdotCL(i, j); // updated covariance: Cl' = Cl - K*Cl + } // // update chi2 double chi2 = 0; - for (int i=mtSize;i--;) for (int j=mtSize;j--;) chi2 += matCLplCU(i,j)*vUmnvL[i]*vUmnvL[j]; + for (int i = mtSize; i--;) + for (int j = mtSize; j--;) + chi2 += matCLplCU(i, j) * vUmnvL[i] * vUmnvL[j]; fChi2 += chi2; // // printf("Combined: Chi2Tot:%.2f ChiUp:%.2f ChiDn:%.2f ChiCmb:%.2f\n",fChi2,fChi2CosmUp,fChi2CosmDn, chi2); - + return kTRUE; } //______________________________________________ -Bool_t AliAlgTrack::FitLeg(AliExternalTrackParam& trc, int pFrom,int pTo, Bool_t &inv) +Bool_t AliAlgTrack::FitLeg(AliExternalTrackParam& trc, int pFrom, int pTo, Bool_t& inv) { // perform initial fit of the track // the fit will always start from the outgoing track in inward direction (i.e. if cosmics - bottom leg) - const int kMinNStep = 3; - const double kMaxDefStep = 3.0; - const double kErrSpace= 50.; + const int kMinNStep = 3; + const double kMaxDefStep = 3.0; + const double kErrSpace = 50.; const double kErrAng = 0.7; const double kErrRelPtI = 1.; - const double kIniErr[15] = { // initial error - kErrSpace*kErrSpace, - 0 , kErrSpace*kErrSpace, - 0 , 0, kErrAng*kErrAng, - 0 , 0, 0, kErrAng*kErrAng, - 0 , 0, 0, 0, kErrRelPtI*kErrRelPtI - }; + const double kIniErr[15] = {// initial error + kErrSpace * kErrSpace, + 0, kErrSpace * kErrSpace, + 0, 0, kErrAng * kErrAng, + 0, 0, 0, kErrAng * kErrAng, + 0, 0, 0, 0, kErrRelPtI * kErrRelPtI}; // // prepare seed at outer point AliAlgPoint* p0 = GetPoint(pFrom); - double phi = trc.Phi(),alp=p0->GetAlphaSens(); + double phi = trc.Phi(), alp = p0->GetAlphaSens(); BringTo02Pi(phi); BringTo02Pi(alp); - double dphi = DeltaPhiSmall(phi,alp); // abs delta angle - if (dphi>Pi()/2.) { // need to invert the track to new frame + double dphi = DeltaPhiSmall(phi, alp); // abs delta angle + if (dphi > Pi() / 2.) { // need to invert the track to new frame inv = kTRUE; - // printf("Fit in %d %d Delta: %.3f -> Inverting for\n",pFrom,pTo,dphi); + // printf("Fit in %d %d Delta: %.3f -> Inverting for\n",pFrom,pTo,dphi); // p0->Print("meas"); // printf("BeforeInv "); trc.Print(); trc.Invert(); // printf("After Inv "); trc.Print(); } if (!trc.RotateParamOnly(p0->GetAlphaSens())) { -#if DEBUG>3 - AliWarningF("Failed on RotateParamOnly to %f",p0->GetAlphaSens()); +#if DEBUG > 3 + AliWarningF("Failed on RotateParamOnly to %f", p0->GetAlphaSens()); trc.Print(); #endif return kFALSE; } - if (!PropagateParamToPoint(trc,p0,30)) { + if (!PropagateParamToPoint(trc, p0, 30)) { // if (!PropagateToPoint(trc,p0,5,30,kTRUE)) { //trc.PropagateParamOnlyTo(p0->GetXPoint()+kOverShootX,AliTrackerBase::GetBz())) { -#if DEBUG>3 - AliWarningF("Failed on PropagateParamOnlyTo to %f",p0->GetXPoint()+kOverShootX); +#if DEBUG > 3 + AliWarningF("Failed on PropagateParamOnlyTo to %f", p0->GetXPoint() + kOverShootX); trc.Print(); #endif return kFALSE; } double* cov = (double*)trc.GetCovariance(); - memcpy(cov,kIniErr,15*sizeof(double)); - cov[14] *= trc.GetSigned1Pt()*trc.GetSigned1Pt(); + memcpy(cov, kIniErr, 15 * sizeof(double)); + cov[14] *= trc.GetSigned1Pt() * trc.GetSigned1Pt(); // int pinc; - if (pTo>pFrom) { // fit in points increasing order: collision track or cosmics lower leg + if (pTo > pFrom) { // fit in points increasing order: collision track or cosmics lower leg pTo++; pinc = 1; - } - else { // fit in points decreasing order: cosmics upper leg + } else { // fit in points decreasing order: cosmics upper leg pTo--; pinc = -1; } // - for (int ip=pFrom;ip!=pTo;ip+=pinc) { // inward fit from outer point + for (int ip = pFrom; ip != pTo; ip += pinc) { // inward fit from outer point AliAlgPoint* pnt = GetPoint(ip); // // printf("*** FitLeg %d (%d %d)\n",ip,pFrom,pTo); // printf("Before propagate: "); trc.Print(); - if (!PropagateToPoint(trc,pnt,kMinNStep, kMaxDefStep, kTRUE)) return kFALSE; + if (!PropagateToPoint(trc, pnt, kMinNStep, kMaxDefStep, kTRUE)) + return kFALSE; if (pnt->ContainsMeasurement()) { - if (pnt->GetNeedUpdateFromTrack()) pnt->UpdatePointByTrackInfo(&trc); - const double* yz = pnt->GetYZTracking(); + if (pnt->GetNeedUpdateFromTrack()) + pnt->UpdatePointByTrackInfo(&trc); + const double* yz = pnt->GetYZTracking(); const double* errYZ = pnt->GetYZErrTracking(); - double chi = trc.GetPredictedChi2(yz,errYZ); + double chi = trc.GetPredictedChi2(yz, errYZ); //printf("***>> fitleg-> Y: %+e %+e / Z: %+e %+e -> Chi2: %e | %+e %+e\n",yz[0],trc.GetY(),yz[1],trc.GetZ(),chi, // trc.Phi(),trc.GetAlpha()); // printf("Before update at %e %e\n",yz[0],yz[1]); trc.Print(); - if (!trc.Update(yz,errYZ)) { -#if DEBUG>3 - AliWarningF("Failed on Update %f,%f {%f,%f,%f}",yz[0],yz[1],errYZ[0],errYZ[1],errYZ[2]); - trc.Print(); + if (!trc.Update(yz, errYZ)) { +#if DEBUG > 3 + AliWarningF("Failed on Update %f,%f {%f,%f,%f}", yz[0], yz[1], errYZ[0], errYZ[1], errYZ[2]); + trc.Print(); #endif - return kFALSE; + return kFALSE; } fChi2 += chi; // printf("After update: (%f) -> %f\n",chi,fChi2); trc.Print(); @@ -1149,75 +1201,79 @@ Bool_t AliAlgTrack::FitLeg(AliExternalTrackParam& trc, int pFrom,int pTo, Bool_t } //______________________________________________ -Bool_t AliAlgTrack::ResidKalman() +Bool_t AliAlgTrack::ResidKalman() { // calculate residuals from bi-directional Kalman smoother // ATTENTION: this method modifies workspaces of the points!!! - // + // Bool_t inv = kFALSE; - const int kMinNStep = 3; - const double kMaxDefStep = 3.0; - const double kErrSpace=50.; + const int kMinNStep = 3; + const double kMaxDefStep = 3.0; + const double kErrSpace = 50.; const double kErrAng = 0.7; const double kErrRelPtI = 1.; - const double kIniErr[15] = { // initial error - kErrSpace*kErrSpace, - 0 , kErrSpace*kErrSpace, - 0 , 0, kErrAng*kErrAng, - 0 , 0, 0, kErrAng*kErrAng, - 0 , 0, 0, 0, kErrRelPtI*kErrRelPtI - }; + const double kIniErr[15] = {// initial error + kErrSpace * kErrSpace, + 0, kErrSpace * kErrSpace, + 0, 0, kErrAng * kErrAng, + 0, 0, 0, kErrAng * kErrAng, + 0, 0, 0, 0, kErrRelPtI * kErrRelPtI}; // const Double_t kOverShootX = 5; // AliExternalTrackParam trc = *this; // - int pID=0, nPnt = GetNPoints();; + int pID = 0, nPnt = GetNPoints(); + ; AliAlgPoint* pnt = 0; - // get 1st measured point - while ( pIDContainsMeasurement() ) pID++; - if (!pnt) return kFALSE; - double phi = trc.Phi(),alp=pnt->GetAlphaSens(); + // get 1st measured point + while (pID < nPnt && !(pnt = GetPoint(pID))->ContainsMeasurement()) + pID++; + if (!pnt) + return kFALSE; + double phi = trc.Phi(), alp = pnt->GetAlphaSens(); BringTo02Pi(phi); BringTo02Pi(alp); - double dphi = DeltaPhiSmall(phi,alp); - if (dphi>Pi()/2.) { // need to invert the track to new frame + double dphi = DeltaPhiSmall(phi, alp); + if (dphi > Pi() / 2.) { // need to invert the track to new frame inv = kTRUE; trc.Invert(); } // prepare track seed at 1st valid point if (!trc.RotateParamOnly(pnt->GetAlphaSens())) { -#if DEBUG>3 - AliWarningF("Failed on RotateParamOnly to %f",pnt->GetAlphaSens()); +#if DEBUG > 3 + AliWarningF("Failed on RotateParamOnly to %f", pnt->GetAlphaSens()); trc.Print(); #endif return kFALSE; } - if (!PropagateParamToPoint(trc,pnt,30)) { + if (!PropagateParamToPoint(trc, pnt, 30)) { //if (!trc.PropagateParamOnlyTo(pnt->GetXPoint()+kOverShootX,AliTrackerBase::GetBz())) { -#if DEBUG>3 - AliWarningF("Failed on PropagateParamOnlyTo to %f",pnt->GetXPoint()+kOverShootX); +#if DEBUG > 3 + AliWarningF("Failed on PropagateParamOnlyTo to %f", pnt->GetXPoint() + kOverShootX); trc.Print(); #endif return kFALSE; } // double* cov = (double*)trc.GetCovariance(); - memcpy(cov,kIniErr,15*sizeof(double)); - cov[14] *= trc.GetSigned1Pt()*trc.GetSigned1Pt(); + memcpy(cov, kIniErr, 15 * sizeof(double)); + cov[14] *= trc.GetSigned1Pt() * trc.GetSigned1Pt(); // double chifwd = 0, chibwd = 0; // inward fit - for (int ip=0;ipIsInvDir()!=inv) { // crossing point where the track should be inverted? + if (pnt->IsInvDir() != inv) { // crossing point where the track should be inverted? trc.Invert(); inv = !inv; } // printf("*** ResidKalm %d (%d %d)\n",ip,0,nPnt); // printf("Before propagate: "); trc.Print(); - if (!PropagateToPoint(trc,pnt,kMinNStep, kMaxDefStep, kTRUE)) return kFALSE; - if (!pnt->ContainsMeasurement()) continue; - const double* yz = pnt->GetYZTracking(); + if (!PropagateToPoint(trc, pnt, kMinNStep, kMaxDefStep, kTRUE)) + return kFALSE; + if (!pnt->ContainsMeasurement()) + continue; + const double* yz = pnt->GetYZTracking(); const double* errYZ = pnt->GetYZErrTracking(); // store track position/errors before update in the point WorkSpace-A double* ws = (double*)pnt->GetTrParamWSA(); @@ -1226,35 +1282,37 @@ Bool_t AliAlgTrack::ResidKalman() ws[2] = trc.GetSigmaY2(); ws[3] = trc.GetSigmaZY(); ws[4] = trc.GetSigmaZ2(); - double chi = trc.GetPredictedChi2(yz,errYZ); + double chi = trc.GetPredictedChi2(yz, errYZ); // printf(">> INV%d (%9d): %+.2e %+.2e | %+.2e %+.2e %+.2e %+.2e %+.2e | %.2e %d \n",ip,pnt->GetSensor()->GetInternalID(),yz[0],yz[1], ws[0],ws[1],ws[2],ws[3],ws[4],chi,inv); // printf(">>Bef ");trc.Print(); // printf("KLM Before update at %e %e\n",yz[0],yz[1]); trc.Print(); - if (!trc.Update(yz,errYZ)) { -#if DEBUG>3 - AliWarningF("Failed on Inward Update %f,%f {%f,%f,%f}",yz[0],yz[1],errYZ[0],errYZ[1],errYZ[2]); + if (!trc.Update(yz, errYZ)) { +#if DEBUG > 3 + AliWarningF("Failed on Inward Update %f,%f {%f,%f,%f}", yz[0], yz[1], errYZ[0], errYZ[1], errYZ[2]); trc.Print(); #endif return kFALSE; } // printf(">>Aft ");trc.Print(); - chifwd += chi; + chifwd += chi; //printf("KLM After update: (%f) -> %f\n",chi,chifwd); trc.Print(); } // // outward fit cov = (double*)trc.GetCovariance(); - memcpy(cov,kIniErr,15*sizeof(double)); - cov[14] *= trc.GetSigned1Pt()*trc.GetSigned1Pt(); - for (int ip=nPnt;ip--;) { + memcpy(cov, kIniErr, 15 * sizeof(double)); + cov[14] *= trc.GetSigned1Pt() * trc.GetSigned1Pt(); + for (int ip = nPnt; ip--;) { pnt = GetPoint(ip); - if (pnt->IsInvDir()!=inv) { // crossing point where the track should be inverted? + if (pnt->IsInvDir() != inv) { // crossing point where the track should be inverted? trc.Invert(); inv = !inv; } - if (!PropagateToPoint(trc,pnt,kMinNStep, kMaxDefStep, kTRUE)) return kFALSE; - if (!pnt->ContainsMeasurement()) continue; - const double* yz = pnt->GetYZTracking(); + if (!PropagateToPoint(trc, pnt, kMinNStep, kMaxDefStep, kTRUE)) + return kFALSE; + if (!pnt->ContainsMeasurement()) + continue; + const double* yz = pnt->GetYZTracking(); const double* errYZ = pnt->GetYZErrTracking(); // store track position/errors before update in the point WorkSpace-B double* ws = (double*)pnt->GetTrParamWSB(); @@ -1263,45 +1321,49 @@ Bool_t AliAlgTrack::ResidKalman() ws[2] = trc.GetSigmaY2(); ws[3] = trc.GetSigmaZY(); ws[4] = trc.GetSigmaZ2(); - double chi = trc.GetPredictedChi2(yz,errYZ); + double chi = trc.GetPredictedChi2(yz, errYZ); // printf("<< OUT%d (%9d): %+.2e %+.2e | %+.2e %+.2e %+.2e %+.2e %+.2e | %.2e %d \n",ip,pnt->GetSensor()->GetInternalID(),yz[0],yz[1], ws[0],ws[1],ws[2],ws[3],ws[4],chi,inv); // printf("<3 - AliWarningF("Failed on Outward Update %f,%f {%f,%f,%f}",yz[0],yz[1],errYZ[0],errYZ[1],errYZ[2]); + if (!trc.Update(yz, errYZ)) { +#if DEBUG > 3 + AliWarningF("Failed on Outward Update %f,%f {%f,%f,%f}", yz[0], yz[1], errYZ[0], errYZ[1], errYZ[2]); trc.Print(); #endif return kFALSE; } - chibwd += chi; + chibwd += chi; // printf("<ContainsMeasurement()) continue; + if (!pnt->ContainsMeasurement()) + continue; double* wsA = (double*)pnt->GetTrParamWSA(); // inward measurement double* wsB = (double*)pnt->GetTrParamWSB(); // outward measurement - double &yA=wsA[0],&zA=wsA[1],&sgAYY=wsA[2],&sgAYZ=wsA[3],&sgAZZ=wsA[4]; - double &yB=wsB[0],&zB=wsB[1],&sgBYY=wsB[2],&sgBYZ=wsB[3],&sgBZZ=wsB[4]; + double &yA = wsA[0], &zA = wsA[1], &sgAYY = wsA[2], &sgAYZ = wsA[3], &sgAZZ = wsA[4]; + double &yB = wsB[0], &zB = wsB[1], &sgBYY = wsB[2], &sgBYZ = wsB[3], &sgBZZ = wsB[4]; // compute weighted average - double sgYY = sgAYY+sgBYY, sgYZ=sgAYZ+sgBYZ, sgZZ=sgAZZ+sgBZZ; - double detI = sgYY*sgZZ - sgYZ*sgYZ; - if (TMath::Abs(detI) < kAlmost0) return kFALSE; else detI = 1./detI; - double tmp = sgYY; - sgYY = sgZZ*detI; - sgZZ = tmp*detI; - sgYZ = -sgYZ*detI; - double dy=yB-yA, dz=zB-zA; - double k00=sgAYY*sgYY+sgAYZ*sgYZ, k01=sgAYY*sgYZ+sgAYZ*sgZZ; - double k10=sgAYZ*sgYY+sgAZZ*sgYZ, k11=sgAYZ*sgYZ+sgAZZ*sgZZ; - double sgAYZt=sgAYZ; - yA += dy*k00 + dz*k01; // these are smoothed predictions, stored in WSA - zA += dy*k10 + dz*k11; // - sgAYY -= k00*sgAYY + k01*sgAYZ; - sgAYZ -= k00*sgAYZt+ k01*sgAZZ; - sgAZZ -= k10*sgAYZt+ k11*sgAZZ; + double sgYY = sgAYY + sgBYY, sgYZ = sgAYZ + sgBYZ, sgZZ = sgAZZ + sgBZZ; + double detI = sgYY * sgZZ - sgYZ * sgYZ; + if (TMath::Abs(detI) < kAlmost0) + return kFALSE; + else + detI = 1. / detI; + double tmp = sgYY; + sgYY = sgZZ * detI; + sgZZ = tmp * detI; + sgYZ = -sgYZ * detI; + double dy = yB - yA, dz = zB - zA; + double k00 = sgAYY * sgYY + sgAYZ * sgYZ, k01 = sgAYY * sgYZ + sgAYZ * sgZZ; + double k10 = sgAYZ * sgYY + sgAZZ * sgYZ, k11 = sgAYZ * sgYZ + sgAZZ * sgZZ; + double sgAYZt = sgAYZ; + yA += dy * k00 + dz * k01; // these are smoothed predictions, stored in WSA + zA += dy * k10 + dz * k11; // + sgAYY -= k00 * sgAYY + k01 * sgAYZ; + sgAYZ -= k00 * sgAYZt + k01 * sgAZZ; + sgAZZ -= k10 * sgAYZt + k11 * sgAZZ; // printf("|| WGH%d (%9d): | %+.2e %+.2e %+.2e %.2e %.2e\n",ip,pnt->GetSensor()->GetInternalID(), wsA[0],wsA[1],wsA[2],wsA[3],wsA[4]); } // @@ -1311,28 +1373,30 @@ Bool_t AliAlgTrack::ResidKalman() } //______________________________________________ -Bool_t AliAlgTrack::ProcessMaterials() +Bool_t AliAlgTrack::ProcessMaterials() { // attach material effect info to alignment points AliExternalTrackParam trc = *this; - // collision track of cosmic lower leg: move along track direction from last (middle for cosmic lower leg) + // collision track of cosmic lower leg: move along track direction from last (middle for cosmic lower leg) // point (inner) to 1st one (outer) - if (fNeedInv[0]) trc.Invert(); // track needs to be inverted ? (should be for upper leg) - if (!ProcessMaterials(trc, GetInnerPointID(),0)) { -#if DEBUG>3 + if (fNeedInv[0]) + trc.Invert(); // track needs to be inverted ? (should be for upper leg) + if (!ProcessMaterials(trc, GetInnerPointID(), 0)) { +#if DEBUG > 3 AliError("Failed to process materials for leg along the track"); -#endif +#endif return kFALSE; } if (IsCosmic()) { // cosmic upper leg: move againg the track direction from middle point (inner) to last one (outer) trc = *this; - if (fNeedInv[1]) trc.Invert(); // track needs to be inverted ? - if (!ProcessMaterials(trc, GetInnerPointID()+1,GetNPoints()-1)) { -#if DEBUG>3 + if (fNeedInv[1]) + trc.Invert(); // track needs to be inverted ? + if (!ProcessMaterials(trc, GetInnerPointID() + 1, GetNPoints() - 1)) { +#if DEBUG > 3 AliError("Failed to process materials for leg against the track"); -#endif +#endif return kFALSE; } } @@ -1340,25 +1404,24 @@ Bool_t AliAlgTrack::ProcessMaterials() } //______________________________________________ -Bool_t AliAlgTrack::ProcessMaterials(AliExternalTrackParam& trc, int pFrom,int pTo) +Bool_t AliAlgTrack::ProcessMaterials(AliExternalTrackParam& trc, int pFrom, int pTo) { // attach material effect info to alignment points - const int kMinNStep = 3; - const double kMaxDefStep = 3.0; + const int kMinNStep = 3; + const double kMaxDefStep = 3.0; const double kErrSpcT = 1e-6; const double kErrAngT = 1e-6; const double kErrPtIT = 1e-12; - const double kErrTiny[15] = { // initial tiny error - kErrSpcT*kErrSpcT, - 0 , kErrSpcT*kErrSpcT, - 0 , 0, kErrAngT*kErrAngT, - 0 , 0, 0, kErrAngT*kErrAngT, - 0 , 0, 0, 0, kErrPtIT*kErrPtIT - }; + const double kErrTiny[15] = {// initial tiny error + kErrSpcT * kErrSpcT, + 0, kErrSpcT * kErrSpcT, + 0, 0, kErrAngT * kErrAngT, + 0, 0, 0, kErrAngT * kErrAngT, + 0, 0, 0, 0, kErrPtIT * kErrPtIT}; /* const double kErrSpcH = 10.0; const double kErrAngH = 0.5; - const double kErrPtIH = 0.5; + const double kErrPtIH = 0.5; const double kErrHuge[15] = { // initial tiny error kErrSpcH*kErrSpcH, 0 , kErrSpcH*kErrSpcH, @@ -1370,92 +1433,96 @@ Bool_t AliAlgTrack::ProcessMaterials(AliExternalTrackParam& trc, int pFrom,int p // // 2 copies of the track, one will be propagated accounting for materials, other - w/o AliExternalTrackParam tr0; - double x2X0xRho[2] = {0,0}; - double dpar[5]={0},dcov[15]={0}; + double x2X0xRho[2] = {0, 0}; + double dpar[5] = {0}, dcov[15] = {0}; // int pinc; - if (pTo>pFrom) { // fit in points decreasing order: cosmics upper leg + if (pTo > pFrom) { // fit in points decreasing order: cosmics upper leg pTo++; pinc = 1; - } - else { // fit in points increasing order: collision track or cosmics lower leg + } else { // fit in points increasing order: collision track or cosmics lower leg pTo--; pinc = -1; } // - for (int ip=pFrom;ip!=pTo;ip+=pinc) { // points are ordered against track direction + for (int ip = pFrom; ip != pTo; ip += pinc) { // points are ordered against track direction AliAlgPoint* pnt = GetPoint(ip); - memcpy((double*)trc.GetCovariance(),kErrTiny,15*sizeof(double)); // assign tiny errors to both tracks + memcpy((double*)trc.GetCovariance(), kErrTiny, 15 * sizeof(double)); // assign tiny errors to both tracks tr0 = trc; // // printf("-> ProcMat %d (%d->%d)\n",ip,pFrom,pTo); - if (!PropagateToPoint(trc,pnt,kMinNStep, kMaxDefStep, kTRUE ,x2X0xRho)) { // with material corrections -#if DEBUG>3 - AliErrorF("Failed to take track to point %d (dir: %d -> %d) with mat.corr.",ip,pFrom,pTo); + if (!PropagateToPoint(trc, pnt, kMinNStep, kMaxDefStep, kTRUE, x2X0xRho)) { // with material corrections +#if DEBUG > 3 + AliErrorF("Failed to take track to point %d (dir: %d -> %d) with mat.corr.", ip, pFrom, pTo); trc.Print(); pnt->Print("meas"); -#endif +#endif return kFALSE; } // // is there enough material to consider the point as a scatterer? - pnt->SetContainsMaterial( x2X0xRho[0]*Abs(trc.GetSigned1Pt()) > GetMinX2X0Pt2Account() ); + pnt->SetContainsMaterial(x2X0xRho[0] * Abs(trc.GetSigned1Pt()) > GetMinX2X0Pt2Account()); // // printf("-> ProcMat000 %d (%d->%d)\n",ip,pFrom,pTo); - if (!PropagateToPoint(tr0,pnt,kMinNStep, kMaxDefStep, kFALSE,0)) { // no material corrections -#if DEBUG>3 - AliErrorF("Failed to take track to point %d (dir: %d -> %d) w/o mat.corr.",ip,pFrom,pTo); + if (!PropagateToPoint(tr0, pnt, kMinNStep, kMaxDefStep, kFALSE, 0)) { // no material corrections +#if DEBUG > 3 + AliErrorF("Failed to take track to point %d (dir: %d -> %d) w/o mat.corr.", ip, pFrom, pTo); tr0.Print(); pnt->Print("meas"); -#endif - return kFALSE; +#endif + return kFALSE; } // the difference between the params, covariance of tracks with and w/o material accounting gives // paramets and covariance of material correction. For params ONLY ELoss effect is revealed - double *cov0=(double*)tr0.GetCovariance(),*par0=(double*)tr0.GetParameter(); - double *cov1=(double*)trc.GetCovariance(),*par1=(double*)trc.GetParameter(); - for (int l=15;l--;) dcov[l] = cov1[l] - cov0[l]; - for (int l=kNKinParBON;l--;) dpar[l] = par1[l] - par0[l]; // eloss affects all parameters! + double *cov0 = (double*)tr0.GetCovariance(), *par0 = (double*)tr0.GetParameter(); + double *cov1 = (double*)trc.GetCovariance(), *par1 = (double*)trc.GetParameter(); + for (int l = 15; l--;) + dcov[l] = cov1[l] - cov0[l]; + for (int l = kNKinParBON; l--;) + dpar[l] = par1[l] - par0[l]; // eloss affects all parameters! pnt->SetMatCorrExp(dpar); //dpar[kParQ2Pt] = par1[kParQ2Pt] - par0[kParQ2Pt]; // only e-loss expectation is non-0 - // + // if (pnt->ContainsMaterial()) { // // MP2 handles only scalar residuals hence correlated matrix of material effect need to be diagonalized Bool_t eLossFree = pnt->GetELossVaried(); int nParFree = eLossFree ? kNKinParBON : kNKinParBOFF; TMatrixDSym matCov(nParFree); - for (int i=nParFree;i--;) for (int j=i+1;j--;) matCov(i,j)=matCov(j,i) = dcov[j+((i*(i+1))>>1)]; + for (int i = nParFree; i--;) + for (int j = i + 1; j--;) + matCov(i, j) = matCov(j, i) = dcov[j + ((i * (i + 1)) >> 1)]; // - TMatrixDSymEigen matDiag(matCov); // find eigenvectors + TMatrixDSymEigen matDiag(matCov); // find eigenvectors const TMatrixD& matEVec = matDiag.GetEigenVectors(); if (!matEVec.IsValid()) { -#if DEBUG>3 - AliError("Failed to diagonalize covariance of material correction"); - matCov.Print(); - return kFALSE; -#endif +#if DEBUG > 3 + AliError("Failed to diagonalize covariance of material correction"); + matCov.Print(); + return kFALSE; +#endif } pnt->SetMatCovDiagonalizationMatrix(matEVec); // store diagonalization matrix pnt->SetMatCovDiag(matDiag.GetEigenValues()); // store E.Values: diagonalized cov.matrix - if (!eLossFree) pnt->SetMatCovDiagElem(kParQ2Pt, dcov[14]); + if (!eLossFree) + pnt->SetMatCovDiagElem(kParQ2Pt, dcov[14]); // //printf("Add mat%d %e %e\n",ip, x2X0xRho[0],x2X0xRho[1]); pnt->SetX2X0(x2X0xRho[0]); - pnt->SetXTimesRho(x2X0xRho[1]); + pnt->SetXTimesRho(x2X0xRho[1]); // } if (pnt->ContainsMeasurement()) { // update track to have best possible kinematics - const double* yz = pnt->GetYZTracking(); + const double* yz = pnt->GetYZTracking(); const double* errYZ = pnt->GetYZErrTracking(); - if (!trc.Update(yz,errYZ)) { -#if DEBUG>3 - AliWarningF("Failed on Update %f,%f {%f,%f,%f}",yz[0],yz[1],errYZ[0],errYZ[1],errYZ[2]); - trc.Print(); + if (!trc.Update(yz, errYZ)) { +#if DEBUG > 3 + AliWarningF("Failed on Update %f,%f {%f,%f,%f}", yz[0], yz[1], errYZ[0], errYZ[1], errYZ[2]); + trc.Print(); #endif - return kFALSE; - } - // + return kFALSE; + } + // } // } @@ -1467,7 +1534,7 @@ Bool_t AliAlgTrack::ProcessMaterials(AliExternalTrackParam& trc, int pFrom,int p void AliAlgTrack::SortPoints() { // sort points in order against track direction: innermost point is last - // for collision tracks. + // for collision tracks. // For 2-leg cosmic tracks: 1st points of outgoing (lower) leg are added from large to // small radii, then the points of incomint (upper) leg are added in increasing R direction // @@ -1476,11 +1543,12 @@ void AliAlgTrack::SortPoints() // fPoints.Sort(); int np = GetNPoints(); - fInnerPointID = np-1; + fInnerPointID = np - 1; if (IsCosmic()) { - for (int ip=np;ip--;) { + for (int ip = np; ip--;) { AliAlgPoint* pnt = GetPoint(ip); - if (pnt->IsInvDir()) continue; // this is a point of upper leg + if (pnt->IsInvDir()) + continue; // this is a point of upper leg fInnerPointID = ip; break; } @@ -1492,22 +1560,24 @@ void AliAlgTrack::SortPoints() void AliAlgTrack::SetLocPars(const double* pars) { // store loc par corrections - memcpy(fLocParA,pars,fNLocPar*sizeof(double)); + memcpy(fLocParA, pars, fNLocPar * sizeof(double)); } //______________________________________________ void AliAlgTrack::CheckExpandDerGloBuffer(int minSize) { // if needed, expand global derivatives buffer - if (fGloParID.GetSize() Delta_j = G'_{j-1} * G^-1_{j-1} * G_j * G'^-1_j + -> Delta_j = G'_{j-1} * G^-1_{j-1} * G_j * G'^-1_j where G and G' are modified and original L2G matrices @@ -54,10 +54,10 @@ By convention, aliroot aligment framework stores global Deltas ! In case the geometry was already prealigned by PDelta_j matrices, the result - of the new incremental alignment Delta_j must be combined with PDelta_j to + of the new incremental alignment Delta_j must be combined with PDelta_j to resulting matrix TDelta_j before writing new alignment object. - Derivation: if G_j and IG_j are final and ideal L2G matrices for level j, then + Derivation: if G_j and IG_j are final and ideal L2G matrices for level j, then G_j = TDelta_j * TDelta_{j-1} ... TDelta_0 * IG_j = (Delta_j * Delta_{j-1} ... Delta_0) * (PDelta_j * PDelta_{j-1} ... PDelta_0) * IG_j @@ -68,7 +68,7 @@ By induction we get combination rule: TDelta_j = Delta_j * X_{j-1} * PDelta_j * X^-1_{j-1} - + where X_i = Delta_i * Delta_{i-1} ... Delta_0 --------------------------------- @@ -80,22 +80,21 @@ For the non-sensor volumes the TRACKING frame is defined by rotation of the lab frame with the alpha angle = average angle of centers of its children, seen from the origin. - The TRACKING and IDEAL LOCAL (before misalignment) frames are related by the + The TRACKING and IDEAL LOCAL (before misalignment) frames are related by the tracking-to-local matrix (T2L in the code), i.e. the vectors in local and tracking frames - are related as + are related as l = T2L * t The alignment can be done using both frames for different volumes of the same geometry - branch. + branch. The alignments deltas in local and tracking frames are related as: - l' = T2L * delta_t * t + l' = T2L * delta_t * t l' = delta_l * T2L * t -> delta_l = T2L * delta_t * T2L^-1 */ - #include "AliAlgVol.h" #include "AliAlgDOFStat.h" #include "AliAlgConstraint.h" @@ -111,48 +110,46 @@ #include #include -ClassImp(AliAlgVol) +ClassImp(o2::align::AliAlgVol) + + using namespace TMath; +using namespace o2::align::AliAlgAux; -using namespace TMath; -using namespace AliAlgAux; +namespace o2 +{ +namespace align +{ -const char* AliAlgVol::fgkFrameName[AliAlgVol::kNVarFrames] = {"LOC","TRA"}; +const char* AliAlgVol::fgkFrameName[AliAlgVol::kNVarFrames] = {"LOC", "TRA"}; // -UInt_t AliAlgVol::fgDefGeomFree = +UInt_t AliAlgVol::fgDefGeomFree = kDOFBitTX | kDOFBitTY | kDOFBitTZ | kDOFBitPS | kDOFBitTH | kDOFBitPH; // -const char* AliAlgVol::fgkDOFName[AliAlgVol::kNDOFGeom]={"TX","TY","TZ","PSI","THT","PHI"}; +const char* AliAlgVol::fgkDOFName[AliAlgVol::kNDOFGeom] = {"TX", "TY", "TZ", "PSI", "THT", "PHI"}; //_________________________________________________________ -AliAlgVol::AliAlgVol(const char* symname, int iid) : - TNamed(symname,"") - ,fVarFrame(kTRA) - ,fIntID(iid) - ,fX(0) - ,fAlp(0) - ,fNDOFs(0) - ,fDOF(0) - ,fNDOFGeomFree(0) - ,fNDOFFree(0) - ,fConstrChild(kDefChildConstr) - // - ,fParent(0) - ,fChildren(0) - // - ,fNProcPoints(0) - ,fFirstParGloID(-1) - ,fParVals(0) - ,fParErrs(0) - ,fParLabs(0) - // - ,fMatL2GReco() - ,fMatL2G() - ,fMatL2GIdeal() - ,fMatT2L() - ,fMatDeltaRefGlo() +AliAlgVol::AliAlgVol(const char* symname, int iid) : TNamed(symname, ""), fVarFrame(kTRA), fIntID(iid), fX(0), fAlp(0), fNDOFs(0), fDOF(0), fNDOFGeomFree(0), fNDOFFree(0), fConstrChild(kDefChildConstr) + // + , + fParent(0), + fChildren(0) + // + , + fNProcPoints(0), + fFirstParGloID(-1), + fParVals(0), + fParErrs(0), + fParLabs(0) + // + , + fMatL2GReco(), + fMatL2G(), + fMatL2GIdeal(), + fMatT2L(), + fMatDeltaRefGlo() { // def c-tor - SetVolID(0); // volumes have no VID, unless it is sensor + SetVolID(0); // volumes have no VID, unless it is sensor if (symname) { // real volumes have at least geometric degrees of freedom SetNDOFs(kNDOFGeom); } @@ -167,25 +164,24 @@ AliAlgVol::~AliAlgVol() } //_________________________________________________________ -void AliAlgVol::Delta2Matrix(TGeoHMatrix& deltaM, const Double_t *delta) const +void AliAlgVol::Delta2Matrix(TGeoHMatrix& deltaM, const Double_t* delta) const { // prepare delta matrix for the volume from its // local delta vector (AliAlignObj convension): dx,dy,dz,,theta,psi,phi - const double *tr=&delta[0],*rt=&delta[3]; // translation(cm) and rotation(degree) + const double *tr = &delta[0], *rt = &delta[3]; // translation(cm) and rotation(degree) AliAlignObjParams tempAlignObj; - tempAlignObj.SetRotation(rt[0],rt[1],rt[2]); - tempAlignObj.SetTranslation(tr[0],tr[1],tr[2]); + tempAlignObj.SetRotation(rt[0], rt[1], rt[2]); + tempAlignObj.SetTranslation(tr[0], tr[1], tr[2]); tempAlignObj.GetMatrix(deltaM); - // + // } - //__________________________________________________________________ -void AliAlgVol::GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t *delta) const +void AliAlgVol::GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t* delta) const { - // prepare the variation matrix tau in volume TRACKING frame by applying + // prepare the variation matrix tau in volume TRACKING frame by applying // local delta of modification of LOCAL frame: - // tra' = tau*tra = tau*T2L^-1*loc = T2L^-1*loc' = T2L^-1*delta*loc + // tra' = tau*tra = tau*T2L^-1*loc = T2L^-1*loc' = T2L^-1*delta*loc // tau = T2L^-1*delta*T2L Delta2Matrix(matMod, delta); matMod.Multiply(&GetMatrixT2L()); @@ -194,10 +190,10 @@ void AliAlgVol::GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t *delta) co } //__________________________________________________________________ -void AliAlgVol::GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t *delta, const TGeoHMatrix& relMat) const +void AliAlgVol::GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t* delta, const TGeoHMatrix& relMat) const { - // prepare the variation matrix tau in volume TRACKING frame by applying - // local delta of modification of LOCAL frame of its PARENT; + // prepare the variation matrix tau in volume TRACKING frame by applying + // local delta of modification of LOCAL frame of its PARENT; // The relMat is matrix for transformation from child to parent frame: LOC = relMat*loc // // tra' = tau*tra = tau*T2L^-1*loc = T2L^-1*loc' = T2L^-1*relMat^-1*Delta*relMat*loc @@ -211,19 +207,19 @@ void AliAlgVol::GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t *delta, co } //__________________________________________________________________ -void AliAlgVol::GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const Double_t *delta) const +void AliAlgVol::GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const Double_t* delta) const { - // prepare the variation matrix tau in volume TRACKING frame by applying + // prepare the variation matrix tau in volume TRACKING frame by applying // local delta of modification of the same TRACKING frame: // tra' = tau*tra Delta2Matrix(matMod, delta); } //__________________________________________________________________ -void AliAlgVol::GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const Double_t *delta, const TGeoHMatrix& relMat) const +void AliAlgVol::GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const Double_t* delta, const TGeoHMatrix& relMat) const { - // prepare the variation matrix tau in volume TRACKING frame by applying - // local delta of modification of TRACKING frame of its PARENT; + // prepare the variation matrix tau in volume TRACKING frame by applying + // local delta of modification of TRACKING frame of its PARENT; // The relMat is matrix for transformation from child to parent frame: TRA = relMat*tra // (see DPosTraDParGeomTRA) // @@ -241,45 +237,58 @@ Int_t AliAlgVol::CountParents() const // count parents in the chain int cnt = 0; const AliAlgVol* p = this; - while( (p=p->GetParent()) ) cnt++; + while ((p = p->GetParent())) + cnt++; return cnt; } //____________________________________________ -void AliAlgVol::Print(const Option_t *opt) const +void AliAlgVol::Print(const Option_t* opt) const { // print info TString opts = opt; opts.ToLower(); printf("Lev:%2d IntID:%7d %s | %2d nodes | Effective X:%8.4f Alp:%+.4f | Used Points: %d\n", - CountParents(),GetInternalID(),GetSymName(),GetNChildren(),fX,fAlp,fNProcPoints); - printf(" DOFs: Tot: %d (offs: %5d) Free: %d Geom: %d {",fNDOFs,fFirstParGloID,fNDOFFree,fNDOFGeomFree); - for (int i=0;iGetAlignableEntry(path)) { const TGeoHMatrix* l2g = AliGeomManager::GetMatrix(path); - if (!l2g) AliFatalF("Failed to find L2G matrix for alignable %s",path); + if (!l2g) + AliFatalF("Failed to find L2G matrix for alignable %s", path); reco ? SetMatrixL2GReco(*l2g) : SetMatrixL2G(*l2g); - } - else { // extract from path - if (!gGeoManager->CheckPath(path)) AliFatalF("Volume path %s not valid!",path); + } else { // extract from path + if (!gGeoManager->CheckPath(path)) + AliFatalF("Volume path %s not valid!", path); TGeoPhysicalNode* node = (TGeoPhysicalNode*)gGeoManager->GetListOfPhysicalNodes()->FindObject(path); TGeoHMatrix l2g; if (!node) { - AliWarningF("Attention: volume %s was not misaligned, extracting original matrix",path); - if (!AliGeomManager::GetOrigGlobalMatrix(path,l2g)) { - AliFatalF("Failed to find ideal L2G matrix for %s",path); - } - } - else { + AliWarningF("Attention: volume %s was not misaligned, extracting original matrix", path); + if (!AliGeomManager::GetOrigGlobalMatrix(path, l2g)) { + AliFatalF("Failed to find ideal L2G matrix for %s", path); + } + } else { l2g = *node->GetMatrix(); } reco ? SetMatrixL2GReco(l2g) : SetMatrixL2G(l2g); @@ -317,8 +326,8 @@ void AliAlgVol::PrepareMatrixL2GIdeal() { // extract from geometry ideal L2G matrix TGeoHMatrix mtmp; - if (!AliGeomManager::GetOrigGlobalMatrix(GetSymName(),mtmp)) - AliFatalF("Failed to find ideal L2G matrix for %s",GetSymName()); + if (!AliGeomManager::GetOrigGlobalMatrix(GetSymName(), mtmp)) + AliFatalF("Failed to find ideal L2G matrix for %s", GetSymName()); SetMatrixL2GIdeal(mtmp); // } @@ -329,24 +338,27 @@ void AliAlgVol::PrepareMatrixT2L() // for non-sensors we define the fake tracking frame with the alpha angle being // the average angle of centers of its children // - double tot[3]={0,0,0},loc[3]={0,0,0},glo[3]; + double tot[3] = {0, 0, 0}, loc[3] = {0, 0, 0}, glo[3]; int nch = GetNChildren(); - for (int ich=nch;ich--;) { + for (int ich = nch; ich--;) { AliAlgVol* vol = GetChild(ich); - vol->GetMatrixL2GIdeal().LocalToMaster(loc,glo); - for (int j=3;j--;) tot[j] += glo[j]; + vol->GetMatrixL2GIdeal().LocalToMaster(loc, glo); + for (int j = 3; j--;) + tot[j] += glo[j]; } - if (nch) for (int j=3;j--;) tot[j] /= nch; + if (nch) + for (int j = 3; j--;) + tot[j] /= nch; // - fAlp = TMath::ATan2(tot[1],tot[0]); + fAlp = TMath::ATan2(tot[1], tot[0]); AliAlgAux::BringToPiPM(fAlp); // - fX = TMath::Sqrt(tot[0]*tot[0]+tot[1]*tot[1]); + fX = TMath::Sqrt(tot[0] * tot[0] + tot[1] * tot[1]); // // 1st create Tracking to Global matrix fMatT2L.Clear(); fMatT2L.SetDx(fX); - fMatT2L.RotateZ(fAlp*RadToDeg()); + fMatT2L.RotateZ(fAlp * RadToDeg()); // then convert it to Tracking to Local matrix const TGeoHMatrix& l2gi = GetMatrixL2GIdeal().Inverse(); fMatT2L.MultiplyLeft(&l2gi); @@ -370,11 +382,11 @@ void AliAlgVol::SetTrackingFrame() // Define tracking frame of the sensor // This method should be implemented for sensors, which receive the T2L // matrix from the geometry - AliErrorF("Volume %s was supposed to implement its own method",GetName()); + AliErrorF("Volume %s was supposed to implement its own method", GetName()); } //__________________________________________________________________ -void AliAlgVol::AssignDOFs(Int_t &cntDOFs, Float_t *pars, Float_t *errs, Int_t *labs) +void AliAlgVol::AssignDOFs(Int_t& cntDOFs, Float_t* pars, Float_t* errs, Int_t* labs) { // Assigns offset of the DOFS of this volume in global array of DOFs, attaches arrays to volumes // @@ -382,11 +394,13 @@ void AliAlgVol::AssignDOFs(Int_t &cntDOFs, Float_t *pars, Float_t *errs, Int_t * fParErrs = errs + cntDOFs; fParLabs = labs + cntDOFs; SetFirstParGloID(cntDOFs); - for (int i=0;iAssignDOFs(cntDOFs,pars,errs,labs); + int nch = GetNChildren(); // go over childs + for (int ich = 0; ich < nch; ich++) + GetChild(ich)->AssignDOFs(cntDOFs, pars, errs, labs); // return; } @@ -397,8 +411,11 @@ void AliAlgVol::InitDOFs() // initialize degrees of freedom // // Do we need this strict condition? - if (GetInitDOFsDone()) AliFatalF("Something is wrong, DOFs are already initialized for %s",GetName()); - for (int i=0;iSetOwner(kFALSE); } fChildren->AddLast(ch); } //__________________________________________________________________ -void AliAlgVol::SetParVals(Int_t npar,Double_t *vl,Double_t *er) +void AliAlgVol::SetParVals(Int_t npar, Double_t* vl, Double_t* er) { // set parameters - if (npar>fNDOFs) AliFatalF("Volume %s has %d dofs",GetName(),fNDOFs); - for (int i=0;i fNDOFs) + AliFatalF("Volume %s has %d dofs", GetName(), fNDOFs); + for (int i = 0; i < npar; i++) { fParVals[i] = vl[i]; fParErrs[i] = er ? er[i] : 0; } @@ -463,20 +484,23 @@ Int_t AliAlgVol::FinalizeStat(AliAlgDOFStat* st) { // finalize statistics on processed points fNProcPoints = 0; - for (int ich=GetNChildren();ich--;) { + for (int ich = GetNChildren(); ich--;) { AliAlgVol* child = GetChild(ich); fNProcPoints += child->FinalizeStat(st); } - if (st) FillDOFStat(st); + if (st) + FillDOFStat(st); return fNProcPoints; } //______________________________________________________ -void AliAlgVol::WritePedeInfo(FILE* parOut,const Option_t *opt) const +void AliAlgVol::WritePedeInfo(FILE* parOut, const Option_t* opt) const { // contribute to params template file for PEDE - enum {kOff,kOn,kOnOn}; - const char* comment[3] = {" ","! ","!!"}; + enum { kOff, + kOn, + kOnOn }; + const char* comment[3] = {" ", "! ", "!!"}; const char* kKeyParam = "parameter"; TString opts = opt; opts.ToLower(); @@ -485,42 +509,53 @@ void AliAlgVol::WritePedeInfo(FILE* parOut,const Option_t *opt) const Bool_t showNam = opts.Contains("n"); // show volume name even if no nothing else is printable // // is there something to print ? - int nCond(0),nFix(0),nDef(0); - for (int i=0;i0 || nFix>0 ? kOff:kOn; // do we comment the "parameter" keyword for this volume - if (!nFix) showFix = kFALSE; - if (!nDef) showDef = kFALSE; + int cmt = nCond > 0 || nFix > 0 ? kOff : kOn; // do we comment the "parameter" keyword for this volume + if (!nFix) + showFix = kFALSE; + if (!nDef) + showDef = kFALSE; // - if (nCond || showDef || showFix || showNam) - fprintf(parOut,"%s%s %s\t\tDOF/Free: %d/%d (%s) %s\n",comment[cmt],kKeyParam,comment[kOnOn], - GetNDOFs(),GetNDOFFree(),fgkFrameName[fVarFrame],GetName()); + if (nCond || showDef || showFix || showNam) + fprintf(parOut, "%s%s %s\t\tDOF/Free: %d/%d (%s) %s\n", comment[cmt], kKeyParam, comment[kOnOn], + GetNDOFs(), GetNDOFFree(), fgkFrameName[fVarFrame], GetName()); // if (nCond || showDef || showFix) { - for (int i=0;iWritePedeInfo(parOut,opt); + for (int ich = 0; ich < nch; ich++) + GetChild(ich)->WritePedeInfo(parOut, opt); // } //_________________________________________________________________ -void AliAlgVol::CreateGloDeltaMatrix(TGeoHMatrix &deltaM) const +void AliAlgVol::CreateGloDeltaMatrix(TGeoHMatrix& deltaM) const { // Create global matrix deltaM from fParVals array containing corrections. // This deltaM does not account for eventual prealignment @@ -542,8 +577,8 @@ void AliAlgVol::CreateGloDeltaMatrix(TGeoHMatrix &deltaM) const // This deltaM does not account for eventual prealignment // Volume knows if its variation was done in TRA or LOC frame // - // deltaM = Z * deltaL * Z^-1 - // where deltaL is local correction matrix and Z is matrix defined as + // deltaM = Z * deltaL * Z^-1 + // where deltaL is local correction matrix and Z is matrix defined as // Z = [ Prod_{k=0}^{j-1} G_k * deltaL_k * G^-1_k ] * G_j // with j=being the level of the volume in the hierarchy // @@ -564,9 +599,9 @@ void AliAlgVol::CreateGloDeltaMatrix(TGeoHMatrix &deltaM) const */ //_________________________________________________________________ -void AliAlgVol::CreatePreGloDeltaMatrix(TGeoHMatrix &deltaM) const +void AliAlgVol::CreatePreGloDeltaMatrix(TGeoHMatrix& deltaM) const { - // Create prealignment global matrix deltaM from prealigned G and + // Create prealignment global matrix deltaM from prealigned G and // original GO local-to-global matrices // // From G_j = Delta_j * Delta_{j-1} ... Delta_0 * GO_j @@ -589,7 +624,7 @@ void AliAlgVol::CreatePreGloDeltaMatrix(TGeoHMatrix &deltaM) const //_________________________________________________________________ void AliAlgVol::CreatePreGloDeltaMatrix(TGeoHMatrix &deltaM) const { - // Create prealignment global matrix deltaM from prealigned G and + // Create prealignment global matrix deltaM from prealigned G and // original GO local-to-global matrices // // From G_j = Delta_j * Delta_{j-1} ... Delta_0 * GO_j @@ -614,9 +649,9 @@ void AliAlgVol::CreatePreGloDeltaMatrix(TGeoHMatrix &deltaM) const */ //_________________________________________________________________ -void AliAlgVol::CreatePreLocDeltaMatrix(TGeoHMatrix &deltaM) const +void AliAlgVol::CreatePreLocDeltaMatrix(TGeoHMatrix& deltaM) const { - // Create prealignment local matrix deltaM from prealigned G and + // Create prealignment local matrix deltaM from prealigned G and // original GO local-to-global matrices // // From G_j = GO_0 * delta_0 * GO^-1_0 * GO_1 * delta_1 ... GO^-1_{j-1}*GO_{j}*delta_j @@ -628,28 +663,29 @@ void AliAlgVol::CreatePreLocDeltaMatrix(TGeoHMatrix &deltaM) const deltaM = GetMatrixL2GIdeal().Inverse(); if (par) { deltaM *= par->GetMatrixL2GIdeal(); - deltaM *= par->GetMatrixL2G().Inverse(); + deltaM *= par->GetMatrixL2G().Inverse(); } deltaM *= GetMatrixL2G(); // } //_________________________________________________________________ -void AliAlgVol::CreateLocDeltaMatrix(TGeoHMatrix &deltaM) const +void AliAlgVol::CreateLocDeltaMatrix(TGeoHMatrix& deltaM) const { // Create local matrix deltaM from fParVals array containing corrections. // This deltaM does not account for eventual prealignment // Volume knows if its variation was done in TRA or LOC frame double corr[kNDOFGeom]; - for (int i=kNDOFGeom;i--;) corr[i] = fParVals[i]; // we need doubles - Delta2Matrix(deltaM,corr); + for (int i = kNDOFGeom; i--;) + corr[i] = fParVals[i]; // we need doubles + Delta2Matrix(deltaM, corr); if (IsFrameTRA()) { // we need corrections in local frame! // l' = T2L * delta_t * t = T2L * delta_t * T2L^-1 * l = delta_l * l // -> delta_l = T2L * delta_t * T2L^-1 const TGeoHMatrix& t2l = GetMatrixT2L(); const TGeoHMatrix& t2li = t2l.Inverse(); - deltaM.Multiply( &t2li ); - deltaM.MultiplyLeft( &t2l ); + deltaM.Multiply(&t2li); + deltaM.MultiplyLeft(&t2l); } // } @@ -660,13 +696,13 @@ void AliAlgVol::CreateAlignmenMatrix(TGeoHMatrix& alg) const // create final alignment matrix, accounting for eventual prealignment // // if the correction for this volume at level j is TAU (global delta) then the combined - // correction (accounting for reference prealignment) is + // correction (accounting for reference prealignment) is // (Delta_0 * .. Delta_{j-1})^-1 * TAU ( Delta_0 * .. Delta_j) // where Delta_i is prealigment global delta of volume i (0 is top) // In principle, it can be obtained as: // GIdeal_{j-1} * G_{j-1}^-1 * TAU * G_{j}^-1 * GIdeal_{j}^-1 // where G_i is pre-misaligned reference L2G and GIdeal_i is L2GIdeal, - // but this creates precision problem. + // but this creates precision problem. // Therefore we use explicitly cached Deltas from prealignment object. // CreateGloDeltaMatrix(alg); @@ -684,7 +720,6 @@ void AliAlgVol::CreateAlignmenMatrix(TGeoHMatrix& alg) const } alg *= GetGlobalDeltaRef(); - /* // bad precision ? alg.Multiply(&GetMatrixL2G()); alg.Multiply(&GetMatrixL2GIdeal().Inverse()); @@ -696,17 +731,17 @@ void AliAlgVol::CreateAlignmenMatrix(TGeoHMatrix& alg) const // } - /* +/* //_________________________________________________________________ void AliAlgVol::CreateAlignmenMatrix(TGeoHMatrix& alg) const { // create final alignment matrix, accounting for eventual prealignment // // deltaGlo_j * X_{j-1} * PdeltaGlo_j * X^-1_{j-1} - // + // // where deltaGlo_j is global alignment matrix for this volume at level j // of herarchy, obtained from CreateGloDeltaMatrix. - // PdeltaGlo_j is prealignment global matrix and + // PdeltaGlo_j is prealignment global matrix and // X_i = deltaGlo_i * deltaGlo_{i-1} .. deltaGle_0 // TGeoHMatrix delGloPre,matX; @@ -732,14 +767,15 @@ void AliAlgVol::CreateAlignmentObjects(TClonesArray* arr) const TClonesArray& parr = *arr; TGeoHMatrix algM; CreateAlignmenMatrix(algM); - new(parr[parr.GetEntriesFast()]) AliAlignObjParams(GetName(),GetVolID(),algM,kTRUE); + new (parr[parr.GetEntriesFast()]) AliAlignObjParams(GetName(), GetVolID(), algM, kTRUE); int nch = GetNChildren(); - for (int ich=0;ichCreateAlignmentObjects(arr); + for (int ich = 0; ich < nch; ich++) + GetChild(ich)->CreateAlignmentObjects(arr); // } //_________________________________________________________________ -void AliAlgVol::UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix *cumulDelta) +void AliAlgVol::UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta) { // recreate fMatL2GReco matrices from ideal L2G matrix and alignment objects // used during data reconstruction. For the volume at level J we have @@ -750,31 +786,38 @@ void AliAlgVol::UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMat // find alignment object for this volume int nalg = algArr->GetEntriesFast(); const AliAlignObjParams* par = 0; - for (int i=0;iAt(i); - if (!strcmp(par->GetSymName(),GetSymName())) break; + if (!strcmp(par->GetSymName(), GetSymName())) + break; par = 0; } TGeoHMatrix delta; - if (!par) AliInfoF("Alignment for %s is absent in Reco-Time alignment object",GetSymName()); - else par->GetMatrix(delta); - if (cumulDelta) delta *= *cumulDelta; + if (!par) + AliInfoF("Alignment for %s is absent in Reco-Time alignment object", GetSymName()); + else + par->GetMatrix(delta); + if (cumulDelta) + delta *= *cumulDelta; // fMatL2GReco.MultiplyLeft(&delta); // propagate to children - for (int ich=GetNChildren();ich--;) GetChild(ich)->UpdateL2GRecoMatrices(algArr,&delta); + for (int ich = GetNChildren(); ich--;) + GetChild(ich)->UpdateL2GRecoMatrices(algArr, &delta); // } - + //______________________________________________________ Bool_t AliAlgVol::OwnsDOFID(Int_t id) const { // check if DOF ID belongs to this volume or its children - if (id>=fFirstParGloID && id= fFirstParGloID && id < fFirstParGloID + fNDOFs) + return kTRUE; // - for (int iv=GetNChildren();iv--;) { + for (int iv = GetNChildren(); iv--;) { AliAlgVol* vol = GetChild(iv); - if (vol->OwnsDOFID(id)) return kTRUE; + if (vol->OwnsDOFID(id)) + return kTRUE; } return kFALSE; } @@ -783,11 +826,13 @@ Bool_t AliAlgVol::OwnsDOFID(Int_t id) const AliAlgVol* AliAlgVol::GetVolOfDOFID(Int_t id) const { // gets volume owning this DOF ID - if (id>=fFirstParGloID && id= fFirstParGloID && id < fFirstParGloID + fNDOFs) + return (AliAlgVol*)this; // - for (int iv=GetNChildren();iv--;) { + for (int iv = GetNChildren(); iv--;) { AliAlgVol* vol = GetChild(iv); - if ( (vol=vol->GetVolOfDOFID(id)) ) return vol; + if ((vol = vol->GetVolOfDOFID(id))) + return vol; } return 0; } @@ -803,13 +848,14 @@ const char* AliAlgVol::GetDOFName(int i) const void AliAlgVol::FillDOFStat(AliAlgDOFStat* h) const { // fill statistics info hist - if (!h) return; + if (!h) + return; int ndf = GetNDOFs(); int dof0 = GetFirstParGloID(); int stat = GetNProcessedPoints(); - for (int idf=0;idfAddStat(dof,stat); + for (int idf = 0; idf < ndf; idf++) { + int dof = idf + dof0; + h->AddStat(dof, stat); } } @@ -823,15 +869,22 @@ void AliAlgVol::AddAutoConstraints(TObjArray* constrArr) AliAlgConstraint* constr = new AliAlgConstraint(); constr->SetConstrainPattern(fConstrChild); constr->SetParent(this); - for (int ich=nch;ich--;) { + for (int ich = nch; ich--;) { AliAlgVol* child = GetChild(ich); - if (child->GetExcludeFromParentConstraint()) continue; + if (child->GetExcludeFromParentConstraint()) + continue; constr->AddChild(child); } - if (constr->GetNChildren()) constrArr->Add(constr); - else delete constr; + if (constr->GetNChildren()) + constrArr->Add(constr); + else + delete constr; } // - for (int ich=0;ichAddAutoConstraints(constrArr); + for (int ich = 0; ich < nch; ich++) + GetChild(ich)->AddAutoConstraints(constrArr); // } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/AliAlgVtx.cxx b/Detectors/Align/src/AliAlgVtx.cxx index f20533893f1f6..201076cdb3677 100644 --- a/Detectors/Align/src/AliAlgVtx.cxx +++ b/Detectors/Align/src/AliAlgVtx.cxx @@ -1,17 +1,17 @@ -/************************************************************************** - * 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. * - **************************************************************************/ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file AliAlgVtx.h +/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since 2021-02-01 +/// @brief Special fake "sensor" for event vertex. #include "AliAlgVtx.h" #include "AliTrackPointArray.h" @@ -23,14 +23,19 @@ using namespace TMath; -ClassImp(AliAlgVtx) +ClassImp(o2::align::AliAlgVtx); + +namespace o2 +{ +namespace align +{ //_________________________________________________________ -AliAlgVtx::AliAlgVtx() : AliAlgSens("Vertex",0,1) +AliAlgVtx::AliAlgVtx() : AliAlgSens("Vertex", 0, 1) { // def c-tor SetVarFrame(kLOC); - SetFreeDOFPattern( BIT(kDOFTX) | BIT(kDOFTY) | BIT(kDOFTZ) ); + SetFreeDOFPattern(BIT(kDOFTX) | BIT(kDOFTY) | BIT(kDOFTZ)); // } @@ -43,7 +48,7 @@ void AliAlgVtx::PrepareMatrixT2L() // fX is fixed to 0 // fMatT2L.Clear(); - fMatT2L.RotateZ(fAlp*RadToDeg()); + fMatT2L.RotateZ(fAlp * RadToDeg()); // fMatT2L.MultiplyLeft(&GetMatrixL2GIdeal().Inverse()); L2G=I !!! // } @@ -62,7 +67,10 @@ void AliAlgVtx::ApplyCorrection(double* vtx) const AliAlgPoint* AliAlgVtx::TrackPoint2AlgPoint(int, const AliTrackPointArray*, const AliESDtrack*) { // convert the pntId-th point to AliAlgPoint - static int cnt=0; - AliErrorF("This method shound not have been called, %d",cnt++); + static int cnt = 0; + AliErrorF("This method shound not have been called, %d", cnt++); return 0; } + +} // namespace align +} // namespace o2 diff --git a/Detectors/Align/src/Mille.cxx b/Detectors/Align/src/Mille.cxx index ffd76992f9396..18c25065cf642 100644 --- a/Detectors/Align/src/Mille.cxx +++ b/Detectors/Align/src/Mille.cxx @@ -1,18 +1,22 @@ -/** - * \file - * Create Millepede-II C-binary record. - * - * \author : Gero Flucke - * date : October 2006 - * $Revision: 1.3 $ - * $Date: 2007/04/16 17:47:38 $ - * (last update by $Author: flucke $) - */ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file Mille.h +/// @author Gero Flucke, ruben.shahoyan@cern.ch, michael.lettrich@cern.ch +/// @since October 2006 +/// @brief Class to write C binary file. /* RS: original Mille.cc from http://svnsrv.desy.de/public/MillepedeII/tags/V04-02-03 jeudi 30 avril 2015: renamed to cxx - jeudi 30 avril 2015: added automatic buffer expansion + jeudi 30 avril 2015: added automatic buffer expansion */ #include "Mille.h" @@ -20,6 +24,10 @@ #include #include +namespace o2 +{ +namespace align +{ //___________________________________________________________________________ /// Opens outFileName (by default as binary file). @@ -28,19 +36,22 @@ * \param[in] asBinary flag for binary * \param[in] writeZero flag for keeping of zeros */ -Mille::Mille(const char *outFileName, bool asBinary, bool writeZero) : - myOutFile(outFileName, - (asBinary ? (std::ios::binary | std::ios::out | std::ios::trunc) : (std::ios::out | std::ios::trunc ))), - myAsBinary(asBinary), myWriteZero(writeZero),myBufferSize(0), - myBufferInt(5000),myBufferFloat(5000), - myBufferPos(-1), myHasSpecial(false) +Mille::Mille(const char* outFileName, bool asBinary, bool writeZero) : myOutFile(outFileName, + (asBinary ? (std::ios::binary | std::ios::out | std::ios::trunc) : (std::ios::out | std::ios::trunc))), + myAsBinary(asBinary), + myWriteZero(writeZero), + myBufferSize(0), + myBufferInt(5000), + myBufferFloat(5000), + myBufferPos(-1), + myHasSpecial(false) { // Instead myBufferPos(-1), myHasSpecial(false) and the following two lines // we could call newSet() and kill()... if (!myOutFile.is_open()) { - std::cerr << "Mille::Mille: Could not open " << outFileName - << " as output file." << std::endl; + std::cerr << "Mille::Mille: Could not open " << outFileName + << " as output file." << std::endl; } } @@ -62,45 +73,48 @@ Mille::~Mille() * \param[in] rMeas measurement (residuum) * \param[in] sigma error */ -void Mille::mille(int NLC, const float *derLc, - int NGL, const float *derGl, const int *label, - float rMeas, float sigma) +void Mille::mille(int NLC, const float* derLc, + int NGL, const float* derGl, const int* label, + float rMeas, float sigma) { - if (sigma <= 0.) return; - if (myBufferPos == -1) this->newSet(); // start, e.g. new track - if (!this->checkBufferSize(NLC, NGL)) return; + if (sigma <= 0.) + return; + if (myBufferPos == -1) + this->newSet(); // start, e.g. new track + if (!this->checkBufferSize(NLC, NGL)) + return; // first store measurement ++myBufferPos; float* bufferFloat = myBufferFloat.GetArray(); - int* bufferInt = myBufferInt.GetArray(); + int* bufferInt = myBufferInt.GetArray(); bufferFloat[myBufferPos] = rMeas; - bufferInt [myBufferPos] = 0; + bufferInt[myBufferPos] = 0; // store local derivatives and local 'lables' 1,...,NLC for (int i = 0; i < NLC; ++i) { if (derLc[i] || myWriteZero) { // by default store only non-zero derivatives ++myBufferPos; bufferFloat[myBufferPos] = derLc[i]; // local derivatives - bufferInt [myBufferPos] = i+1; // index of local parameter + bufferInt[myBufferPos] = i + 1; // index of local parameter } } // store uncertainty of measurement in between locals and globals ++myBufferPos; bufferFloat[myBufferPos] = sigma; - bufferInt [myBufferPos] = 0; + bufferInt[myBufferPos] = 0; // store global derivatives and their labels for (int i = 0; i < NGL; ++i) { - if (derGl[i] || myWriteZero) { // by default store only non-zero derivatives + if (derGl[i] || myWriteZero) { // by default store only non-zero derivatives if ((label[i] > 0 || myWriteZero) && label[i] <= myMaxLabel) { // and for valid labels - ++myBufferPos; - bufferFloat[myBufferPos] = derGl[i]; // global derivatives - bufferInt [myBufferPos] = label[i]; // index of global parameter + ++myBufferPos; + bufferFloat[myBufferPos] = derGl[i]; // global derivatives + bufferInt[myBufferPos] = label[i]; // index of global parameter } else { - std::cerr << "Mille::mille: Invalid label " << label[i] - << " <= 0 or > " << myMaxLabel << std::endl; + std::cerr << "Mille::mille: Invalid label " << label[i] + << " <= 0 or > " << myMaxLabel << std::endl; } } } @@ -113,16 +127,19 @@ void Mille::mille(int NLC, const float *derLc, * \param[in] floatings floats * \param[in] integers ints */ -void Mille::special(int nSpecial, const float *floatings, const int *integers) +void Mille::special(int nSpecial, const float* floatings, const int* integers) { - if (nSpecial == 0) return; - if (myBufferPos == -1) this->newSet(); // start, e.g. new track + if (nSpecial == 0) + return; + if (myBufferPos == -1) + this->newSet(); // start, e.g. new track if (myHasSpecial) { std::cerr << "Mille::special: Special values already stored for this record." - << std::endl; + << std::endl; return; } - if (!this->checkBufferSize(nSpecial, 0)) return; + if (!this->checkBufferSize(nSpecial, 0)) + return; myHasSpecial = true; // after newSet() (Note: MILLSP sets to buffer position...) // myBufferFloat[.] | myBufferInt[.] @@ -132,20 +149,20 @@ void Mille::special(int nSpecial, const float *floatings, const int *integers) // The above indicates special data, following are nSpecial floating and nSpecial integer data. // float* bufferFloat = myBufferFloat.GetArray(); - int* bufferInt = myBufferInt.GetArray(); + int* bufferInt = myBufferInt.GetArray(); // ++myBufferPos; // zero pair bufferFloat[myBufferPos] = 0.; - bufferInt [myBufferPos] = 0; + bufferInt[myBufferPos] = 0; - ++myBufferPos; // nSpecial and zero + ++myBufferPos; // nSpecial and zero bufferFloat[myBufferPos] = -nSpecial; // automatic conversion to float - bufferInt [myBufferPos] = 0; + bufferInt[myBufferPos] = 0; for (int i = 0; i < nSpecial; ++i) { ++myBufferPos; bufferFloat[myBufferPos] = floatings[i]; - bufferInt [myBufferPos] = integers[i]; + bufferInt[myBufferPos] = integers[i]; } } @@ -162,30 +179,30 @@ int Mille::end() { int wrote = 0; if (myBufferPos > 0) { // only if anything stored... - const int numWordsToWrite = (myBufferPos + 1)*2; + const int numWordsToWrite = (myBufferPos + 1) * 2; float* bufferFloat = myBufferFloat.GetArray(); - int* bufferInt = myBufferInt.GetArray(); + int* bufferInt = myBufferInt.GetArray(); if (myAsBinary) { - myOutFile.write(reinterpret_cast(&numWordsToWrite), - sizeof(numWordsToWrite)); - myOutFile.write(reinterpret_cast(bufferFloat), - (myBufferPos+1) * sizeof(bufferFloat[0])); - myOutFile.write(reinterpret_cast(bufferInt), - (myBufferPos+1) * sizeof(bufferInt[0])); + myOutFile.write(reinterpret_cast(&numWordsToWrite), + sizeof(numWordsToWrite)); + myOutFile.write(reinterpret_cast(bufferFloat), + (myBufferPos + 1) * sizeof(bufferFloat[0])); + myOutFile.write(reinterpret_cast(bufferInt), + (myBufferPos + 1) * sizeof(bufferInt[0])); } else { myOutFile << numWordsToWrite << "\n"; - for (int i = 0; i < myBufferPos+1; ++i) { - myOutFile << bufferFloat[i] << " "; + for (int i = 0; i < myBufferPos + 1; ++i) { + myOutFile << bufferFloat[i] << " "; } myOutFile << "\n"; - - for (int i = 0; i < myBufferPos+1; ++i) { - myOutFile << bufferInt[i] << " "; + + for (int i = 0; i < myBufferPos + 1; ++i) { + myOutFile << bufferInt[i] << " "; } myOutFile << "\n"; } - wrote = (myBufferPos+1)*(sizeof(bufferFloat[0])+sizeof(bufferInt[0]))+sizeof(int); + wrote = (myBufferPos + 1) * (sizeof(bufferFloat[0]) + sizeof(bufferInt[0])) + sizeof(int); } myBufferPos = -1; // reset buffer for next set of derivatives return wrote; @@ -198,7 +215,7 @@ void Mille::newSet() myBufferPos = 0; myHasSpecial = false; myBufferFloat[0] = 0.0; - myBufferInt [0] = 0; // position 0 used as error counter + myBufferInt[0] = 0; // position 0 used as error counter } //___________________________________________________________________________ @@ -212,15 +229,18 @@ bool Mille::checkBufferSize(int nLocal, int nGlobal) { if (myBufferPos + nLocal + nGlobal + 2 >= myBufferInt.GetSize()) { ++(myBufferInt[0]); // increase error count - std::cerr << "Mille::checkBufferSize: Buffer too short (" - << myBufferInt.GetSize() << ")," - << "\n need space for nLocal (" << nLocal<< ")" - << "/nGlobal (" << nGlobal << ") local/global derivatives, " - << myBufferPos + 1 << " already stored!" - << std::endl; + std::cerr << "Mille::checkBufferSize: Buffer too short (" + << myBufferInt.GetSize() << ")," + << "\n need space for nLocal (" << nLocal << ")" + << "/nGlobal (" << nGlobal << ") local/global derivatives, " + << myBufferPos + 1 << " already stored!" + << std::endl; // return false; myBufferInt.Set(myBufferPos + nLocal + nGlobal + 1000); myBufferFloat.Set(myBufferPos + nLocal + nGlobal + 1000); } return true; } + +} // namespace align +} // namespace o2 From 350761271781b7749ab0060fad0d08d2f3e9d667 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Tue, 9 Feb 2021 18:43:58 +0100 Subject: [PATCH 193/770] [ALIGN] reorganize includes --- Detectors/Align/include/Align/AliAlgAux.h | 2 +- .../Align/include/Align/AliAlgConstraint.h | 2 +- Detectors/Align/include/Align/AliAlgDet.h | 8 +-- .../Align/include/Align/AliAlgDetHMPID.h | 2 +- Detectors/Align/include/Align/AliAlgDetITS.h | 4 +- Detectors/Align/include/Align/AliAlgDetTOF.h | 2 +- Detectors/Align/include/Align/AliAlgDetTPC.h | 2 +- Detectors/Align/include/Align/AliAlgDetTRD.h | 2 +- Detectors/Align/include/Align/AliAlgPoint.h | 4 +- Detectors/Align/include/Align/AliAlgSens.h | 8 +-- .../Align/include/Align/AliAlgSensHMPID.h | 6 +-- Detectors/Align/include/Align/AliAlgSensITS.h | 2 +- Detectors/Align/include/Align/AliAlgSensTOF.h | 6 +-- Detectors/Align/include/Align/AliAlgSensTPC.h | 6 +-- Detectors/Align/include/Align/AliAlgSensTRD.h | 6 +-- Detectors/Align/include/Align/AliAlgSteer.h | 16 +++--- Detectors/Align/include/Align/AliAlgTrack.h | 4 +- Detectors/Align/include/Align/AliAlgVtx.h | 2 +- Detectors/Align/src/AliAlgAux.cxx | 8 +-- Detectors/Align/src/AliAlgConstraint.cxx | 8 +-- Detectors/Align/src/AliAlgDOFStat.cxx | 6 +-- Detectors/Align/src/AliAlgDet.cxx | 32 ++++++------ Detectors/Align/src/AliAlgDetHMPID.cxx | 16 +++--- Detectors/Align/src/AliAlgDetITS.cxx | 16 +++--- Detectors/Align/src/AliAlgDetTOF.cxx | 14 ++--- Detectors/Align/src/AliAlgDetTPC.cxx | 14 ++--- Detectors/Align/src/AliAlgDetTRD.cxx | 14 ++--- Detectors/Align/src/AliAlgMPRecord.cxx | 8 +-- Detectors/Align/src/AliAlgPoint.cxx | 6 +-- Detectors/Align/src/AliAlgRes.cxx | 10 ++-- Detectors/Align/src/AliAlgResFast.cxx | 10 ++-- Detectors/Align/src/AliAlgSens.cxx | 16 +++--- Detectors/Align/src/AliAlgSensHMPID.cxx | 14 ++--- Detectors/Align/src/AliAlgSensITS.cxx | 14 ++--- Detectors/Align/src/AliAlgSensTOF.cxx | 14 ++--- Detectors/Align/src/AliAlgSensTPC.cxx | 14 ++--- Detectors/Align/src/AliAlgSensTRD.cxx | 18 +++---- Detectors/Align/src/AliAlgSteer.cxx | 52 +++++++++---------- Detectors/Align/src/AliAlgTrack.cxx | 14 ++--- Detectors/Align/src/AliAlgVol.cxx | 14 ++--- Detectors/Align/src/AliAlgVtx.cxx | 12 ++--- 41 files changed, 214 insertions(+), 214 deletions(-) diff --git a/Detectors/Align/include/Align/AliAlgAux.h b/Detectors/Align/include/Align/AliAlgAux.h index ec45ca9438d40..b50bdb7182aa1 100644 --- a/Detectors/Align/include/Align/AliAlgAux.h +++ b/Detectors/Align/include/Align/AliAlgAux.h @@ -18,7 +18,7 @@ #include #include -class AliCDBId; +// class AliCDBId; class TMap; class TList; diff --git a/Detectors/Align/include/Align/AliAlgConstraint.h b/Detectors/Align/include/Align/AliAlgConstraint.h index 59430138e29e1..f3858e7316bec 100644 --- a/Detectors/Align/include/Align/AliAlgConstraint.h +++ b/Detectors/Align/include/Align/AliAlgConstraint.h @@ -29,7 +29,7 @@ #include #include #include -#include "AliAlgVol.h" +#include "Align/AliAlgVol.h" namespace o2 { diff --git a/Detectors/Align/include/Align/AliAlgDet.h b/Detectors/Align/include/Align/AliAlgDet.h index 3a215c633c1b6..7834d9472ee6e 100644 --- a/Detectors/Align/include/Align/AliAlgDet.h +++ b/Detectors/Align/include/Align/AliAlgDet.h @@ -19,16 +19,16 @@ #include #include #include -#include "AliAlgAux.h" -#include "AliESDtrack.h" +#include "Align/AliAlgAux.h" +//#include "AliESDtrack.h" class AliAlgTrack; class AliAlgDOFStat; class AliAlgPoint; class AliAlgSens; class AliAlgVol; class AliAlgSteer; -class AliTrackPointArray; -class AliExternalTrackParam; +//class AliTrackPointArray; +//class AliExternalTrackParam; class TH1; namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgDetHMPID.h b/Detectors/Align/include/Align/AliAlgDetHMPID.h index 01f3924907f57..79f3422416a48 100644 --- a/Detectors/Align/include/Align/AliAlgDetHMPID.h +++ b/Detectors/Align/include/Align/AliAlgDetHMPID.h @@ -16,7 +16,7 @@ #ifndef ALIALGDETHMPID_H #define ALIALGDETHMPID_H -#include "AliAlgDet.h" +#include "Align/AliAlgDet.h" namespace o2 { diff --git a/Detectors/Align/include/Align/AliAlgDetITS.h b/Detectors/Align/include/Align/AliAlgDetITS.h index 6b2985ef3fef7..d8e0ea4c9c3fa 100644 --- a/Detectors/Align/include/Align/AliAlgDetITS.h +++ b/Detectors/Align/include/Align/AliAlgDetITS.h @@ -16,8 +16,8 @@ #ifndef ALIALGDETITS_H #define ALIALGDETITS_H -#include "AliAlgDet.h" -#include "AliAlgAux.h" +#include "Align/AliAlgDet.h" +#include "Align/AliAlgAux.h" namespace o2 { diff --git a/Detectors/Align/include/Align/AliAlgDetTOF.h b/Detectors/Align/include/Align/AliAlgDetTOF.h index 12f8077e8028c..5dff50371bb4c 100644 --- a/Detectors/Align/include/Align/AliAlgDetTOF.h +++ b/Detectors/Align/include/Align/AliAlgDetTOF.h @@ -16,7 +16,7 @@ #ifndef ALIALGDETTOF_H #define ALIALGDETTOF_H -#include "AliAlgDet.h" +#include "Align/AliAlgDet.h" namespace o2 { diff --git a/Detectors/Align/include/Align/AliAlgDetTPC.h b/Detectors/Align/include/Align/AliAlgDetTPC.h index d3342b78976af..58b1c952a4b8d 100644 --- a/Detectors/Align/include/Align/AliAlgDetTPC.h +++ b/Detectors/Align/include/Align/AliAlgDetTPC.h @@ -16,7 +16,7 @@ #ifndef ALIALGDETTPC_H #define ALIALGDETTPC_H -#include "AliAlgDet.h" +#include "Align/AliAlgDet.h" namespace o2 { diff --git a/Detectors/Align/include/Align/AliAlgDetTRD.h b/Detectors/Align/include/Align/AliAlgDetTRD.h index fce3e20ed193a..77be9481e6c71 100644 --- a/Detectors/Align/include/Align/AliAlgDetTRD.h +++ b/Detectors/Align/include/Align/AliAlgDetTRD.h @@ -16,7 +16,7 @@ #ifndef ALIALGDETTRD_H #define ALIALGDETTRD_H -#include "AliAlgDet.h" +#include "Align/AliAlgDet.h" namespace o2 { diff --git a/Detectors/Align/include/Align/AliAlgPoint.h b/Detectors/Align/include/Align/AliAlgPoint.h index 07650e425cbe5..ec8048012fb5e 100644 --- a/Detectors/Align/include/Align/AliAlgPoint.h +++ b/Detectors/Align/include/Align/AliAlgPoint.h @@ -26,9 +26,9 @@ #include #include #include -#include "AliAlgSens.h" +#include "Align/AliAlgSens.h" -class AliExternalTrackParam; +//class AliExternalTrackParam; namespace o2 { diff --git a/Detectors/Align/include/Align/AliAlgSens.h b/Detectors/Align/include/Align/AliAlgSens.h index 80fe8e25879d7..3c6a43f09aca4 100644 --- a/Detectors/Align/include/Align/AliAlgSens.h +++ b/Detectors/Align/include/Align/AliAlgSens.h @@ -16,15 +16,15 @@ #ifndef ALIALGSENS_H #define ALIALGSENS_H -#include "AliAlgVol.h" +#include "Align/AliAlgVol.h" #include -class AliTrackPointArray; -class AliESDtrack; +//class AliTrackPointArray; +//class AliESDtrack; class AliAlgDet; class AliAlgPoint; class TObjArray; -class AliExternalTrackParam; +//class AliExternalTrackParam; class AliAlgDOFStat; class TCloneArray; diff --git a/Detectors/Align/include/Align/AliAlgSensHMPID.h b/Detectors/Align/include/Align/AliAlgSensHMPID.h index 2868bba25d7ce..84b376bfc0ca8 100644 --- a/Detectors/Align/include/Align/AliAlgSensHMPID.h +++ b/Detectors/Align/include/Align/AliAlgSensHMPID.h @@ -16,11 +16,11 @@ #ifndef ALIALGSENSHMPID_H #define ALIALGSENSHMPID_H -#include "AliAlgSens.h" +#include "Align/AliAlgSens.h" class TObjArray; -class AliTrackPointArray; -class AliESDtrack; +//class AliTrackPointArray; +//class AliESDtrack; class AliAlgPoint; namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgSensITS.h b/Detectors/Align/include/Align/AliAlgSensITS.h index bff2ca77f9071..10e6e3bca7bb6 100644 --- a/Detectors/Align/include/Align/AliAlgSensITS.h +++ b/Detectors/Align/include/Align/AliAlgSensITS.h @@ -16,7 +16,7 @@ #ifndef ALIALGSENSITS_H #define ALIALGSENSITS_H -#include "AliAlgSens.h" +#include "Align/AliAlgSens.h" class TObjArray; class AliTrackPointArray; diff --git a/Detectors/Align/include/Align/AliAlgSensTOF.h b/Detectors/Align/include/Align/AliAlgSensTOF.h index 8fad11107e62c..dd5d2ea47a1dc 100644 --- a/Detectors/Align/include/Align/AliAlgSensTOF.h +++ b/Detectors/Align/include/Align/AliAlgSensTOF.h @@ -16,10 +16,10 @@ #ifndef ALIALGSENSTOF_H #define ALIALGSENSTOF_H -#include "AliAlgSens.h" +#include "Align/AliAlgSens.h" -class AliTrackPointArray; -class AliESDtrack; +//class AliTrackPointArray; +//class AliESDtrack; class AliAlgPoint; class TObjArray; diff --git a/Detectors/Align/include/Align/AliAlgSensTPC.h b/Detectors/Align/include/Align/AliAlgSensTPC.h index c95f2a648f357..2aa1465380ebb 100644 --- a/Detectors/Align/include/Align/AliAlgSensTPC.h +++ b/Detectors/Align/include/Align/AliAlgSensTPC.h @@ -16,11 +16,11 @@ #ifndef ALIALGSENSTPC_H #define ALIALGSENSTPC_H -#include "AliAlgSens.h" +#include "Align/AliAlgSens.h" class TObjArray; -class AliTrackPointArray; -class AliESDtrack; +//class AliTrackPointArray; +//class AliESDtrack; class AliAlgPoint; namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgSensTRD.h b/Detectors/Align/include/Align/AliAlgSensTRD.h index 09cc540e0f369..215ae410a8121 100644 --- a/Detectors/Align/include/Align/AliAlgSensTRD.h +++ b/Detectors/Align/include/Align/AliAlgSensTRD.h @@ -16,9 +16,9 @@ #ifndef ALIALGSENSTRD_H #define ALIALGSENSTRD_H -#include "AliAlgSens.h" -class AliTrackPointArray; -class AliESDtrack; +#include "Align/AliAlgSens.h" +//class AliTrackPointArray; +//class AliESDtrack; class AliAlgPoint; class TObjArray; diff --git a/Detectors/Align/include/Align/AliAlgSteer.h b/Detectors/Align/include/Align/AliAlgSteer.h index e81c621d56136..4387adcaf9151 100644 --- a/Detectors/Align/include/Align/AliAlgSteer.h +++ b/Detectors/Align/include/Align/AliAlgSteer.h @@ -21,9 +21,9 @@ #ifndef ALIALGSTEER_H #define ALIALGSTEER_H -#include "AliGeomManager.h" -#include "AliAlgTrack.h" -#include "AliSymMatrix.h" +// #include "AliGeomManager.h" +#include "Align/AliAlgTrack.h" +// #include "AliSymMatrix.h" #include #include @@ -32,12 +32,12 @@ #include #include #include -#include "AliAlgAux.h" +#include "Align/AliAlgAux.h" -class AliESDEvent; -class AliESDtrack; -class AliESDCosmicTrack; -class AliESDVertex; +//class AliESDEvent; +//class AliESDtrack; +//class AliESDCosmicTrack; +//class AliESDVertex; class AliAlgDet; class AliAlgVol; class AliAlgVtx; diff --git a/Detectors/Align/include/Align/AliAlgTrack.h b/Detectors/Align/include/Align/AliAlgTrack.h index 7a88da346ad6f..9ec676fbd960f 100644 --- a/Detectors/Align/include/Align/AliAlgTrack.h +++ b/Detectors/Align/include/Align/AliAlgTrack.h @@ -22,8 +22,8 @@ #ifndef ALIALGTRACK_H #define ALIALGTRACK_H -#include "AliExternalTrackParam.h" -#include "AliAlgPoint.h" +//#include "AliExternalTrackParam.h" +#include "Align/AliAlgPoint.h" #include #include #include diff --git a/Detectors/Align/include/Align/AliAlgVtx.h b/Detectors/Align/include/Align/AliAlgVtx.h index 4ef8dfb7a37b6..9b221d27638e9 100644 --- a/Detectors/Align/include/Align/AliAlgVtx.h +++ b/Detectors/Align/include/Align/AliAlgVtx.h @@ -27,7 +27,7 @@ #ifndef ALIALGVTX_H #define ALIALGVTX_H -#include "AliAlgSens.h" +#include "Align/AliAlgSens.h" class AliTrackPointArray; class AliESDtrack; class AliAlgPoint; diff --git a/Detectors/Align/src/AliAlgAux.cxx b/Detectors/Align/src/AliAlgAux.cxx index cb1951d782231..8d087df442a88 100644 --- a/Detectors/Align/src/AliAlgAux.cxx +++ b/Detectors/Align/src/AliAlgAux.cxx @@ -13,10 +13,10 @@ /// @since 2021-02-01 /// @brief Collection of auxillary methods -#include "AliAlgAux.h" -#include "AliCDBId.h" -#include "AliCDBManager.h" -#include "AliLog.h" +#include "Align/AliAlgAux.h" +// #include "AliCDBId.h" +// #include "AliCDBManager.h" +#include "Framework/Logger.h" #include #include #include diff --git a/Detectors/Align/src/AliAlgConstraint.cxx b/Detectors/Align/src/AliAlgConstraint.cxx index 9b04ce85a0d64..4b2fe61efa966 100644 --- a/Detectors/Align/src/AliAlgConstraint.cxx +++ b/Detectors/Align/src/AliAlgConstraint.cxx @@ -13,10 +13,10 @@ /// @since 2021-02-01 /// @brief Descriptor of geometrical constraint -#include "AliAlgConstraint.h" -#include "AliAlignObjParams.h" -#include "AliAlgAux.h" -#include "AliLog.h" +#include "Align/AliAlgConstraint.h" +//#include "AliAlignObjParams.h" +#include "Align/AliAlgAux.h" +#include "Framework/Logger.h" #include #include #include diff --git a/Detectors/Align/src/AliAlgDOFStat.cxx b/Detectors/Align/src/AliAlgDOFStat.cxx index 387b2c976e932..77761bea3ca8d 100644 --- a/Detectors/Align/src/AliAlgDOFStat.cxx +++ b/Detectors/Align/src/AliAlgDOFStat.cxx @@ -13,9 +13,9 @@ /// @since 2021-02-01 /// @brief Mergable bbject for statistics of points used by each DOF -#include "AliAlgDOFStat.h" -#include "AliAlgSteer.h" -#include "AliLog.h" +#include "Align/AliAlgDOFStat.h" +#include "Align/AliAlgSteer.h" +#include "Framework/Logger.h" #include #include diff --git a/Detectors/Align/src/AliAlgDet.cxx b/Detectors/Align/src/AliAlgDet.cxx index 08154a9611dba..e29db8b33fb41 100644 --- a/Detectors/Align/src/AliAlgDet.cxx +++ b/Detectors/Align/src/AliAlgDet.cxx @@ -13,22 +13,22 @@ /// @since 2021-02-01 /// @brief Base class for detector: wrapper for set of volumes -#include "AliAlgDet.h" -#include "AliAlgSens.h" -#include "AliAlgDet.h" -#include "AliAlgSteer.h" -#include "AliAlgTrack.h" -#include "AliAlgDOFStat.h" -#include "AliAlgConstraint.h" -#include "AliLog.h" -#include "AliGeomManager.h" -#include "AliCDBManager.h" -#include "AliCDBMetaData.h" -#include "AliCDBEntry.h" -#include "AliAlignObj.h" -#include "AliCDBId.h" -#include "AliExternalTrackParam.h" -#include "AliAlignObjParams.h" +#include "Align/AliAlgDet.h" +#include "Align/AliAlgSens.h" +#include "Align/AliAlgDet.h" +#include "Align/AliAlgSteer.h" +#include "Align/AliAlgTrack.h" +#include "Align/AliAlgDOFStat.h" +#include "Align/AliAlgConstraint.h" +#include "Framework/Logger.h" +//#include "AliGeomManager.h" +//#include "AliCDBManager.h" +//#include "AliCDBMetaData.h" +//#include "AliCDBEntry.h" +//#include "AliAlignObj.h" +//#include "AliCDBId.h" +//#include "AliExternalTrackParam.h" +//#include "AliAlignObjParams.h" #include #include #include diff --git a/Detectors/Align/src/AliAlgDetHMPID.cxx b/Detectors/Align/src/AliAlgDetHMPID.cxx index dd73d3354500d..7e1fbf0d0578f 100644 --- a/Detectors/Align/src/AliAlgDetHMPID.cxx +++ b/Detectors/Align/src/AliAlgDetHMPID.cxx @@ -13,14 +13,14 @@ /// @since 2021-02-01 /// @brief HMPID detector wrapper -#include "AliAlgDetHMPID.h" -#include "AliHMPIDParam.h" -#include "AliAlgVol.h" -#include "AliAlgSensHMPID.h" -#include "AliAlgSteer.h" -#include "AliGeomManager.h" -#include "AliESDtrack.h" -#include "AliLog.h" +#include "Align/AliAlgDetHMPID.h" +//#include "AliHMPIDParam.h" +#include "Align/AliAlgVol.h" +#include "Align/AliAlgSensHMPID.h" +#include "Align/AliAlgSteer.h" +//#include "AliGeomManager.h" +//#include "AliESDtrack.h" +#include "Framework/Logger.h" #include ClassImp(o2::align::AliAlgDetHMPID); diff --git a/Detectors/Align/src/AliAlgDetITS.cxx b/Detectors/Align/src/AliAlgDetITS.cxx index 67111ed4a6c61..4e7a7637a2413 100644 --- a/Detectors/Align/src/AliAlgDetITS.cxx +++ b/Detectors/Align/src/AliAlgDetITS.cxx @@ -13,14 +13,14 @@ /// @since 2021-02-01 /// @brief ITS detector wrapper -#include "AliAlgDetITS.h" -#include "AliAlgVol.h" -#include "AliAlgSensITS.h" -#include "AliAlgSteer.h" -#include "AliITSgeomTGeo.h" -#include "AliGeomManager.h" -#include "AliESDtrack.h" -#include "AliCheb3DCalc.h" +#include "Align/AliAlgDetITS.h" +#include "Align/AliAlgVol.h" +#include "Align/AliAlgSensITS.h" +#include "Align/AliAlgSteer.h" +//#include "AliITSgeomTGeo.h" +//#include "AliGeomManager.h" +//#include "AliESDtrack.h" +//#include "AliCheb3DCalc.h" #include #include diff --git a/Detectors/Align/src/AliAlgDetTOF.cxx b/Detectors/Align/src/AliAlgDetTOF.cxx index 7e025cdb0dd4f..393f3fea8c629 100644 --- a/Detectors/Align/src/AliAlgDetTOF.cxx +++ b/Detectors/Align/src/AliAlgDetTOF.cxx @@ -13,13 +13,13 @@ /// @since 2021-02-01 /// @brief Wrapper for TOF detector -#include "AliAlgDetTOF.h" -#include "AliAlgVol.h" -#include "AliAlgSensTOF.h" -#include "AliAlgSteer.h" -#include "AliGeomManager.h" -#include "AliTOFGeometry.h" -#include "AliESDtrack.h" +#include "Align/AliAlgDetTOF.h" +#include "Align/AliAlgVol.h" +#include "Align/AliAlgSensTOF.h" +#include "Align/AliAlgSteer.h" +//#include "AliGeomManager.h" +//#include "AliTOFGeometry.h" +//#include "AliESDtrack.h" #include ClassImp(o2::align::AliAlgDetTOF); diff --git a/Detectors/Align/src/AliAlgDetTPC.cxx b/Detectors/Align/src/AliAlgDetTPC.cxx index a069fd5a9a266..d28d834429dab 100644 --- a/Detectors/Align/src/AliAlgDetTPC.cxx +++ b/Detectors/Align/src/AliAlgDetTPC.cxx @@ -13,13 +13,13 @@ /// @since 2021-02-01 /// @brief TPC detector wrapper -#include "AliAlgDetTPC.h" -#include "AliAlgVol.h" -#include "AliAlgSensTPC.h" -#include "AliAlgSteer.h" -#include "AliGeomManager.h" -#include "AliESDtrack.h" -#include "AliLog.h" +#include "Align/AliAlgDetTPC.h" +#include "Align/AliAlgVol.h" +#include "Align/AliAlgSensTPC.h" +#include "Align/AliAlgSteer.h" +//#include "AliGeomManager.h" +//#include "AliESDtrack.h" +#include "Framework/Logger.h" #include ClassImp(o2::align::AliAlgDetTPC); diff --git a/Detectors/Align/src/AliAlgDetTRD.cxx b/Detectors/Align/src/AliAlgDetTRD.cxx index 80c661dc12435..19e162674cf31 100644 --- a/Detectors/Align/src/AliAlgDetTRD.cxx +++ b/Detectors/Align/src/AliAlgDetTRD.cxx @@ -13,13 +13,13 @@ /// @since 2021-02-01 /// @brief TRD detector wrapper -#include "AliAlgDetTRD.h" -#include "AliAlgVol.h" -#include "AliAlgSensTRD.h" -#include "AliAlgSteer.h" -#include "AliGeomManager.h" -#include "AliESDtrack.h" -#include "AliTRDgeometry.h" +#include "Align/AliAlgDetTRD.h" +#include "Align/AliAlgVol.h" +#include "Align/AliAlgSensTRD.h" +#include "Align/AliAlgSteer.h" +//#include "AliGeomManager.h" +//#include "AliESDtrack.h" +//#include "AliTRDgeometry.h" #include #include diff --git a/Detectors/Align/src/AliAlgMPRecord.cxx b/Detectors/Align/src/AliAlgMPRecord.cxx index 055607ede6c31..9eff33352dca9 100644 --- a/Detectors/Align/src/AliAlgMPRecord.cxx +++ b/Detectors/Align/src/AliAlgMPRecord.cxx @@ -13,10 +13,10 @@ /// @since 2021-02-01 /// @brief Millepede record in root format (can be converted to proper pede binary format. -#include "AliAlgMPRecord.h" -#include "AliAlgAux.h" -#include "AliAlgTrack.h" -#include "AliLog.h" +#include "Align/AliAlgMPRecord.h" +#include "Align/AliAlgAux.h" +#include "Align/AliAlgTrack.h" +#include "Framework/Logger.h" #include #include diff --git a/Detectors/Align/src/AliAlgPoint.cxx b/Detectors/Align/src/AliAlgPoint.cxx index 73631769ff4df..c66a304f818b1 100644 --- a/Detectors/Align/src/AliAlgPoint.cxx +++ b/Detectors/Align/src/AliAlgPoint.cxx @@ -16,9 +16,9 @@ #include #include #include -#include "AliAlgPoint.h" -#include "AliAlgAux.h" -#include "AliExternalTrackParam.h" +#include "Align/AliAlgPoint.h" +#include "Align/AliAlgAux.h" +//#include "AliExternalTrackParam.h" using namespace o2::align::AliAlgAux; using namespace TMath; diff --git a/Detectors/Align/src/AliAlgRes.cxx b/Detectors/Align/src/AliAlgRes.cxx index 219ebbca0c668..315dc521674db 100644 --- a/Detectors/Align/src/AliAlgRes.cxx +++ b/Detectors/Align/src/AliAlgRes.cxx @@ -13,11 +13,11 @@ /// @since 2021-02-01 /// @brief Container for control residuals -#include "AliAlgRes.h" -#include "AliAlgTrack.h" -#include "AliAlgPoint.h" -#include "AliAlgSens.h" -#include "AliLog.h" +#include "Align/AliAlgRes.h" +#include "Align/AliAlgTrack.h" +#include "Align/AliAlgPoint.h" +#include "Align/AliAlgSens.h" +#include "Framework/Logger.h" #include #include #include diff --git a/Detectors/Align/src/AliAlgResFast.cxx b/Detectors/Align/src/AliAlgResFast.cxx index fd5790a9fd04b..e654338e551d3 100644 --- a/Detectors/Align/src/AliAlgResFast.cxx +++ b/Detectors/Align/src/AliAlgResFast.cxx @@ -13,11 +13,11 @@ /// @since 2021-02-01 /// @brief Container for control fast residuals evaluated via derivatives -#include "AliAlgResFast.h" -#include "AliAlgTrack.h" -#include "AliAlgPoint.h" -#include "AliAlgSens.h" -#include "AliLog.h" +#include "Align/AliAlgResFast.h" +#include "Align/AliAlgTrack.h" +#include "Align/AliAlgPoint.h" +#include "Align/AliAlgSens.h" +#include "Framework/Logger.h" #include #include #include diff --git a/Detectors/Align/src/AliAlgSens.cxx b/Detectors/Align/src/AliAlgSens.cxx index b8973812a331c..dba69b8a9263e 100644 --- a/Detectors/Align/src/AliAlgSens.cxx +++ b/Detectors/Align/src/AliAlgSens.cxx @@ -15,14 +15,14 @@ #include #include -#include "AliAlgSens.h" -#include "AliAlgAux.h" -#include "AliLog.h" -#include "AliGeomManager.h" -#include "AliExternalTrackParam.h" -#include "AliAlgPoint.h" -#include "AliAlgDet.h" -#include "AliAlgDOFStat.h" +#include "Align/AliAlgSens.h" +#include "Align/AliAlgAux.h" +#include "Framework/Logger.h" +//#include "AliGeomManager.h" +//#include "AliExternalTrackParam.h" +#include "Align/AliAlgPoint.h" +#include "Align/AliAlgDet.h" +#include "Align/AliAlgDOFStat.h" ClassImp(AliAlgSens); diff --git a/Detectors/Align/src/AliAlgSensHMPID.cxx b/Detectors/Align/src/AliAlgSensHMPID.cxx index be92393941590..118553fd1e0bf 100644 --- a/Detectors/Align/src/AliAlgSensHMPID.cxx +++ b/Detectors/Align/src/AliAlgSensHMPID.cxx @@ -13,13 +13,13 @@ /// @since 2021-02-01 /// @brief HMPID sensor (chamber) -#include "AliAlgSensHMPID.h" -#include "AliAlgAux.h" -#include "AliLog.h" -#include "AliTrackPointArray.h" -#include "AliESDtrack.h" -#include "AliAlgPoint.h" -#include "AliAlgDet.h" +#include "Align/AliAlgSensHMPID.h" +#include "Align/AliAlgAux.h" +#include "Framework/Logger.h" +//#include "AliTrackPointArray.h" +//#include "AliESDtrack.h" +#include "Align/AliAlgPoint.h" +#include "Align/AliAlgDet.h" ClassImp(o2::align::AliAlgSensHMPID); diff --git a/Detectors/Align/src/AliAlgSensITS.cxx b/Detectors/Align/src/AliAlgSensITS.cxx index a9dceba9b4472..b9ecd021ce236 100644 --- a/Detectors/Align/src/AliAlgSensITS.cxx +++ b/Detectors/Align/src/AliAlgSensITS.cxx @@ -13,13 +13,13 @@ /// @since 2021-02-01 /// @brief ITS sensor -#include "AliAlgSensITS.h" -#include "AliAlgAux.h" -#include "AliLog.h" -#include "AliTrackPointArray.h" -#include "AliESDtrack.h" -#include "AliAlgPoint.h" -#include "AliAlgDet.h" +#include "Align/AliAlgSensITS.h" +#include "Align/AliAlgAux.h" +#include "Framework/Logger.h" +//#include "AliTrackPointArray.h" +//#include "AliESDtrack.h" +#include "Align/AliAlgPoint.h" +#include "Align/AliAlgDet.h" ClassImp(o2::align::AliAlgSensITS); diff --git a/Detectors/Align/src/AliAlgSensTOF.cxx b/Detectors/Align/src/AliAlgSensTOF.cxx index f04427d194faf..5ad13d9e1a9af 100644 --- a/Detectors/Align/src/AliAlgSensTOF.cxx +++ b/Detectors/Align/src/AliAlgSensTOF.cxx @@ -13,13 +13,13 @@ /// @since 2021-02-01 /// @brief TOF sensor -#include "AliAlgSensTOF.h" -#include "AliAlgAux.h" -#include "AliAlgDetTOF.h" -#include "AliLog.h" -#include "AliAlgPoint.h" -#include "AliTrackPointArray.h" -#include "AliESDtrack.h" +#include "Align/AliAlgSensTOF.h" +#include "Align/AliAlgAux.h" +#include "Align/AliAlgDetTOF.h" +#include "Framework/Logger.h" +#include "Align/AliAlgPoint.h" +//#include "AliTrackPointArray.h" +//#include "AliESDtrack.h" ClassImp(o2::align::AliAlgSensTOF); diff --git a/Detectors/Align/src/AliAlgSensTPC.cxx b/Detectors/Align/src/AliAlgSensTPC.cxx index 07c062d2bdb00..21fdbf68babd6 100644 --- a/Detectors/Align/src/AliAlgSensTPC.cxx +++ b/Detectors/Align/src/AliAlgSensTPC.cxx @@ -13,13 +13,13 @@ /// @since 2021-02-01 /// @brief TPC sensor (chamber) -#include "AliAlgSensTPC.h" -#include "AliAlgAux.h" -#include "AliLog.h" -#include "AliTrackPointArray.h" -#include "AliESDtrack.h" -#include "AliAlgPoint.h" -#include "AliAlgDet.h" +#include "Align/AliAlgSensTPC.h" +#include "Align/AliAlgAux.h" +#include "Framework/Logger.h" +//#include "AliTrackPointArray.h" +//#include "AliESDtrack.h" +#include "Align/AliAlgPoint.h" +#include "Align/AliAlgDet.h" ClassImp(o2::align::AliAlgSensTPC) diff --git a/Detectors/Align/src/AliAlgSensTRD.cxx b/Detectors/Align/src/AliAlgSensTRD.cxx index 9ccd7db502281..0910e29fbf7f4 100644 --- a/Detectors/Align/src/AliAlgSensTRD.cxx +++ b/Detectors/Align/src/AliAlgSensTRD.cxx @@ -13,15 +13,15 @@ /// @since 2021-02-01 /// @brief TRD sensor -#include "AliAlgSensTRD.h" -#include "AliTRDgeometry.h" -#include "AliAlgDetTRD.h" -#include "AliAlgAux.h" -#include "AliLog.h" -#include "AliAlgPoint.h" -#include "AliTrackPointArray.h" -#include "AliESDtrack.h" -#include "AliTrackerBase.h" +#include "Align/AliAlgSensTRD.h" +//#include "AliTRDgeometry.h" +#include "Align/AliAlgDetTRD.h" +#include "Align/AliAlgAux.h" +#include "Framework/Logger.h" +#include "Align/AliAlgPoint.h" +//#include "AliTrackPointArray.h" +//#include "AliESDtrack.h" +//#include "AliTrackerBase.h" ClassImp(o2::align::AliAlgSensTRD) diff --git a/Detectors/Align/src/AliAlgSteer.cxx b/Detectors/Align/src/AliAlgSteer.cxx index 7421e8f44a22d..03d413d04b827 100644 --- a/Detectors/Align/src/AliAlgSteer.cxx +++ b/Detectors/Align/src/AliAlgSteer.cxx @@ -13,32 +13,32 @@ /// @since 2021-02-01 /// @brief Steering class for the global alignment -#include "AliAlgSteer.h" -#include "AliLog.h" -#include "AliAlgAux.h" -#include "AliAlgPoint.h" -#include "AliAlgDet.h" -#include "AliAlgVol.h" -#include "AliAlgDetITS.h" -#include "AliAlgDetTPC.h" -#include "AliAlgDetTRD.h" -#include "AliAlgDetTOF.h" -#include "AliAlgVtx.h" -#include "AliAlgMPRecord.h" -#include "AliAlgRes.h" -#include "AliAlgResFast.h" -#include "AliAlgConstraint.h" -#include "AliAlgDOFStat.h" -#include "AliTrackerBase.h" -#include "AliESDCosmicTrack.h" -#include "AliESDtrack.h" -#include "AliESDEvent.h" -#include "AliESDVertex.h" -#include "AliRecoParam.h" -#include "AliCDBRunRange.h" -#include "AliCDBManager.h" -#include "AliCDBEntry.h" -#include "Mille.h" +#include "Align/AliAlgSteer.h" +#include "Framework/Logger.h" +#include "Align/AliAlgAux.h" +#include "Align/AliAlgPoint.h" +#include "Align/AliAlgDet.h" +#include "Align/AliAlgVol.h" +#include "Align/AliAlgDetITS.h" +#include "Align/AliAlgDetTPC.h" +#include "Align/AliAlgDetTRD.h" +#include "Align/AliAlgDetTOF.h" +#include "Align/AliAlgVtx.h" +#include "Align/AliAlgMPRecord.h" +#include "Align/AliAlgRes.h" +#include "Align/AliAlgResFast.h" +#include "Align/AliAlgConstraint.h" +#include "Align/AliAlgDOFStat.h" +//#include "AliTrackerBase.h" +//#include "AliESDCosmicTrack.h" +//#include "AliESDtrack.h" +//#include "AliESDEvent.h" +//#include "AliESDVertex.h" +//#include "AliRecoParam.h" +//#include "AliCDBRunRange.h" +//#include "AliCDBManager.h" +//#include "AliCDBEntry.h" +#include "Align/Mille.h" #include #include #include diff --git a/Detectors/Align/src/AliAlgTrack.cxx b/Detectors/Align/src/AliAlgTrack.cxx index 8c78f8a1a8176..0fb8646a5e976 100644 --- a/Detectors/Align/src/AliAlgTrack.cxx +++ b/Detectors/Align/src/AliAlgTrack.cxx @@ -14,13 +14,13 @@ /// @brief Track model for the alignment #include -#include "AliAlgTrack.h" -#include "AliTrackerBase.h" -#include "AliLog.h" -#include "AliAlgSens.h" -#include "AliAlgVol.h" -#include "AliAlgDet.h" -#include "AliAlgAux.h" +#include "Align/AliAlgTrack.h" +//#include "AliTrackerBase.h" +#include "Framework/Logger.h" +#include "Align/AliAlgSens.h" +#include "Align/AliAlgVol.h" +#include "Align/AliAlgDet.h" +#include "Align/AliAlgAux.h" #include #include #include diff --git a/Detectors/Align/src/AliAlgVol.cxx b/Detectors/Align/src/AliAlgVol.cxx index bb6b04985b976..e9319d7c014dd 100644 --- a/Detectors/Align/src/AliAlgVol.cxx +++ b/Detectors/Align/src/AliAlgVol.cxx @@ -95,13 +95,13 @@ */ -#include "AliAlgVol.h" -#include "AliAlgDOFStat.h" -#include "AliAlgConstraint.h" -#include "AliAlignObjParams.h" -#include "AliGeomManager.h" -#include "AliAlgAux.h" -#include "AliLog.h" +#include "Align/AliAlgVol.h" +#include "Align/AliAlgDOFStat.h" +#include "Align/AliAlgConstraint.h" +//#include "AliAlignObjParams.h" +//#include "AliGeomManager.h" +#include "Align/AliAlgAux.h" +#include "Framework/Logger.h" #include #include #include diff --git a/Detectors/Align/src/AliAlgVtx.cxx b/Detectors/Align/src/AliAlgVtx.cxx index 201076cdb3677..75255f5bb0746 100644 --- a/Detectors/Align/src/AliAlgVtx.cxx +++ b/Detectors/Align/src/AliAlgVtx.cxx @@ -13,12 +13,12 @@ /// @since 2021-02-01 /// @brief Special fake "sensor" for event vertex. -#include "AliAlgVtx.h" -#include "AliTrackPointArray.h" -#include "AliESDtrack.h" -#include "AliAlgPoint.h" -#include "AliAlgDet.h" -#include "AliLog.h" +#include "Align/AliAlgVtx.h" +//#include "AliTrackPointArray.h" +//#include "AliESDtrack.h" +#include "Align/AliAlgPoint.h" +#include "Align/AliAlgDet.h" +#include "Framework/Logger.h" #include using namespace TMath; From d91576bb6c14fe4316b111fb39b782df72b3c32b Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Tue, 9 Feb 2021 19:13:41 +0100 Subject: [PATCH 194/770] [ALIGN] integrate into CMake --- Detectors/Align/CMakeLists.txt | 185 +++++++++++------------------ Detectors/Align/src/ALIGNLinkDef.h | 46 +++---- Detectors/CMakeLists.txt | 2 + 3 files changed, 97 insertions(+), 136 deletions(-) diff --git a/Detectors/Align/CMakeLists.txt b/Detectors/Align/CMakeLists.txt index a7ab149ae1fb4..0b18c04682bf2 100644 --- a/Detectors/Align/CMakeLists.txt +++ b/Detectors/Align/CMakeLists.txt @@ -1,113 +1,72 @@ -# ************************************************************************** -# * Copyright(c) 1998-2014, 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. * -# ************************************************************************** - -# Module -set(MODULE ALIGN) -add_definitions(-D_MODULE_="${MODULE}") - -# Module include folders -include_directories(${AliRoot_SOURCE_DIR}/${MODULE}) - -# Additional include directories - alphabetical order except ROOT -include_directories(SYSTEM ${ROOT_INCLUDE_DIR}) -include_directories(${AliRoot_SOURCE_DIR}/STEER/STEERBase - ${AliRoot_SOURCE_DIR}/STEER/STEER - ${AliRoot_SOURCE_DIR}/STEER/ESD - ${AliRoot_SOURCE_DIR}/STEER/CDB - ${AliRoot_SOURCE_DIR}/TRD/TRDbase - ${AliRoot_SOURCE_DIR}/ITS/ITSbase - ${AliRoot_SOURCE_DIR}/TOF/TOFbase - ${AliRoot_SOURCE_DIR}/HMPID/HMPIDbase - ) - -# Sources - alphabetical order -set(SRCS - AliAlgAux.cxx - AliAlgConstraint.cxx - AliAlgDet.cxx - AliAlgDetHMPID.cxx - AliAlgDetITS.cxx - AliAlgDetTOF.cxx - AliAlgDetTPC.cxx - AliAlgDetTRD.cxx - AliAlgDOFStat.cxx - AliAlgMPRecord.cxx - AliAlgPoint.cxx - AliAlgRes.cxx - AliAlgResFast.cxx - AliAlgSens.cxx - AliAlgSensHMPID.cxx - AliAlgSensITS.cxx - AliAlgSensTOF.cxx - AliAlgSensTPC.cxx - AliAlgSensTRD.cxx - AliAlgSteer.cxx - AliAlgTrack.cxx - AliAlgVol.cxx - AliAlgVtx.cxx - Mille.cxx - ) - -# Headers from sources -string(REPLACE ".cxx" ".h" HDRS "${SRCS}") - -# Generate the dictionary -# It will create G_ARG1.cxx and G_ARG1.h / ARG1 = function first argument -get_directory_property(incdirs INCLUDE_DIRECTORIES) -generate_dictionary("${MODULE}" "${MODULE}LinkDef.h" "${HDRS}" "${incdirs}") - -set(ROOT_DEPENDENCIES Core Geom Gpad Graf3d MathCore Matrix Hist RIO Tree) -set(ALIROOT_DEPENDENCIES STEERBase ESD CDB ITSbase TRDbase TOFbase) - -# Generate the ROOT map -# Dependecies -set(LIBDEPS ${ALIROOT_DEPENDENCIES} ${ROOT_DEPENDENCIES}) -generate_rootmap("${MODULE}" "${LIBDEPS}" "${CMAKE_CURRENT_SOURCE_DIR}/${MODULE}LinkDef.h") - -# Create an object to be reused in case of static libraries -# Otherwise the sources will be compiled twice -add_library(${MODULE}-object OBJECT ${SRCS} G__${MODULE}.cxx) -# Add a library to the project using the object -add_library(${MODULE} SHARED $) - -target_link_libraries(${MODULE} ${ALIROOT_DEPENDENCIES} ${ROOT_DEPENDENCIES}) - -# Public include folders that will be propagated to the dependecies -target_include_directories(${MODULE} PUBLIC ${incdirs}) - -# System dependent: Modify the way the library is build -if(${CMAKE_SYSTEM} MATCHES Darwin) - set(MODULE_LINK_FLAGS "-undefined dynamic_lookup ${MODULE_LINK_FLAGS}") -endif(${CMAKE_SYSTEM} MATCHES Darwin) - -# Aditional compile and link flags -set_target_properties(${MODULE}-object PROPERTIES COMPILE_FLAGS "${MODULE_COMPILE_FLAGS}") -set_target_properties(${MODULE} PROPERTIES LINK_FLAGS "${MODULE_LINK_FLAGS}") - -# Setting the correct headers for the object as gathered from the dependencies -# After all compilation flags are set -target_include_directories(${MODULE}-object PUBLIC $) -set_target_properties(${MODULE}-object PROPERTIES COMPILE_DEFINITIONS $) - -# Installation -install(TARGETS ${MODULE} - ARCHIVE DESTINATION lib - LIBRARY DESTINATION lib) - -# install macros -#install(DIRECTORY utils DESTINATION ALIGN) - -install(FILES ${HDRS} DESTINATION include) - +# Copyright CERN and copyright holders of ALICE O2. This software is distributed +# under the terms of the GNU General Public License v3 (GPL Version 3), copied +# verbatim in the file "COPYING". +# +# See http://alice-o2.web.cern.ch/license for full licensing information. +# +# In applying this license CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization or +# submit itself to any jurisdiction. + +#o2_add_library(Align +# SOURCES #src/AliAlgAux.cxx +# #src/AliAlgConstraint.cxx +# #src/AliAlgDet.cxx +# #src/AliAlgDetHMPID.cxx +# #src/AliAlgDetITS.cxx +# #src/AliAlgDetTOF.cxx +# #src/AliAlgDetTPC.cxx +# #src/AliAlgDetTRD.cxx +# #src/AliAlgDOFStat.cxx +# #src/AliAlgMPRecord.cxx +# #src/AliAlgPoint.cxx +# #src/AliAlgRes.cxx +# #src/AliAlgResFast.cxx +# #src/AliAlgSens.cxx +# #src/AliAlgSensHMPID.cxx +# #src/AliAlgSensITS.cxx +# #src/AliAlgSensTOF.cxx +# #src/AliAlgSensTPC.cxx +# #src/AliAlgSensTRD.cxx +# #src/AliAlgSteer.cxx +# #src/AliAlgTrack.cxx +# #src/AliAlgVol.cxx +# #src/AliAlgVtx.cxx +# #src/Mille.cxx +# PUBLIC_LINK_LIBRARIES O2::FrameworkLogger +# ROOT::Core +# ROOT::Geom +# ROOT::Gpad +# ROOT::Graf3d +# ROOT::MathCore +# ROOT::Matrix +# ROOT::Hist +# ROOT::RIO +# ROOT::Tree) + +#o2_target_root_dictionary( +# ReconstructionDataFormats +# HEADERS #include/Align/AliAlgDet.h +# #include/Align/AliAlgDetITS.h +# #include/Align/AliAlgDetTOF.h +# #include/Align/AliAlgDetTPC.h +# #include/Align/AliAlgDetTRD.h +# #include/Align/AliAlgDetHMPID.h +# #include/Align/AliAlgMPRecord.h +# #include/Align/AliAlgPoint.h +# #include/Align/AliAlgSens.h +# #include/Align/AliAlgSensITS.h +# #include/Align/AliAlgSensTOF.h +# #include/Align/AliAlgSensTPC.h +# #include/Align/AliAlgSensTRD.h +# #include/Align/AliAlgSensHMPID.h +# #include/Align/AliAlgSteer.h +# #include/Align/AliAlgTrack.h +# #include/Align/AliAlgVol.h +# #include/Align/AliAlgVtx.h +# #include/Align/AliAlgRes.h +# #include/Align/AliAlgResFast.h +# #include/Align/AliAlgConstraint.h +# #include/Align/AliAlgDOFStat.h +# #include/Align/AliAlgAux.h +# ) diff --git a/Detectors/Align/src/ALIGNLinkDef.h b/Detectors/Align/src/ALIGNLinkDef.h index 05c252f10229d..49647d3efb3eb 100644 --- a/Detectors/Align/src/ALIGNLinkDef.h +++ b/Detectors/Align/src/ALIGNLinkDef.h @@ -1,32 +1,32 @@ -#ifdef __CINT__ +#ifdef __CLING__ #pragma link off all globals; #pragma link off all classes; #pragma link off all functions; //#pragma link C++ class AliAlgAux; -#pragma link C++ class o2::align::AliAlgDet+; -#pragma link C++ class o2::align::AliAlgDetITS+; -#pragma link C++ class o2::align::AliAlgDetTOF+; -#pragma link C++ class o2::align::AliAlgDetTPC+; -#pragma link C++ class o2::align::AliAlgDetTRD+; -#pragma link C++ class o2::align::AliAlgDetHMPID+; -#pragma link C++ class o2::align::AliAlgMPRecord+; -#pragma link C++ class o2::align::AliAlgPoint+; -#pragma link C++ class o2::align::AliAlgSens+; -#pragma link C++ class o2::align::AliAlgSensITS+; -#pragma link C++ class o2::align::AliAlgSensTOF+; -#pragma link C++ class o2::align::AliAlgSensTPC+; -#pragma link C++ class o2::align::AliAlgSensTRD+; -#pragma link C++ class o2::align::AliAlgSensHMPID+; -#pragma link C++ class o2::align::AliAlgSteer+; -#pragma link C++ class o2::align::AliAlgTrack+; -#pragma link C++ class o2::align::AliAlgVol+; -#pragma link C++ class o2::align::AliAlgVtx+; -#pragma link C++ class o2::align::AliAlgRes+; -#pragma link C++ class o2::align::AliAlgResFast+; -#pragma link C++ class o2::align::AliAlgConstraint+; -#pragma link C++ class o2::align::AliAlgDOFStat+; +#pragma link C++ class o2::align::AliAlgDet + ; +#pragma link C++ class o2::align::AliAlgDetITS + ; +#pragma link C++ class o2::align::AliAlgDetTOF + ; +#pragma link C++ class o2::align::AliAlgDetTPC + ; +#pragma link C++ class o2::align::AliAlgDetTRD + ; +#pragma link C++ class o2::align::AliAlgDetHMPID + ; +#pragma link C++ class o2::align::AliAlgMPRecord + ; +#pragma link C++ class o2::align::AliAlgPoint + ; +#pragma link C++ class o2::align::AliAlgSens + ; +#pragma link C++ class o2::align::AliAlgSensITS + ; +#pragma link C++ class o2::align::AliAlgSensTOF + ; +#pragma link C++ class o2::align::AliAlgSensTPC + ; +#pragma link C++ class o2::align::AliAlgSensTRD + ; +#pragma link C++ class o2::align::AliAlgSensHMPID + ; +#pragma link C++ class o2::align::AliAlgSteer + ; +#pragma link C++ class o2::align::AliAlgTrack + ; +#pragma link C++ class o2::align::AliAlgVol + ; +#pragma link C++ class o2::align::AliAlgVtx + ; +#pragma link C++ class o2::align::AliAlgRes + ; +#pragma link C++ class o2::align::AliAlgResFast + ; +#pragma link C++ class o2::align::AliAlgConstraint + ; +#pragma link C++ class o2::align::AliAlgDOFStat + ; #pragma link C++ class o2::align::AliAlgAux; #endif diff --git a/Detectors/CMakeLists.txt b/Detectors/CMakeLists.txt index 41a3e8a0da254..8a1d4a432a934 100644 --- a/Detectors/CMakeLists.txt +++ b/Detectors/CMakeLists.txt @@ -40,6 +40,8 @@ endif() add_subdirectory(Calibration) add_subdirectory(DCS) +add_subdirectory(Align) + if(BUILD_SIMULATION) add_subdirectory(gconfig) o2_data_file(COPY gconfig DESTINATION Detectors) From f3e3b4ae374f70ff28b641e5078872b56a1ca737 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Wed, 10 Feb 2021 11:21:19 +0100 Subject: [PATCH 195/770] [Align] port AliAlgAux --- Detectors/Align/CMakeLists.txt | 122 +++++++++++----------- Detectors/Align/include/Align/AliAlgAux.h | 7 +- Detectors/Align/src/ALIGNLinkDef.h | 32 ------ Detectors/Align/src/AliAlgAux.cxx | 97 +---------------- Detectors/Align/src/AlignLinkDef.h | 32 ++++++ 5 files changed, 95 insertions(+), 195 deletions(-) delete mode 100644 Detectors/Align/src/ALIGNLinkDef.h create mode 100644 Detectors/Align/src/AlignLinkDef.h diff --git a/Detectors/Align/CMakeLists.txt b/Detectors/Align/CMakeLists.txt index 0b18c04682bf2..d19ac7e66af34 100644 --- a/Detectors/Align/CMakeLists.txt +++ b/Detectors/Align/CMakeLists.txt @@ -8,65 +8,65 @@ # granted to it by virtue of its status as an Intergovernmental Organization or # submit itself to any jurisdiction. -#o2_add_library(Align -# SOURCES #src/AliAlgAux.cxx -# #src/AliAlgConstraint.cxx -# #src/AliAlgDet.cxx -# #src/AliAlgDetHMPID.cxx -# #src/AliAlgDetITS.cxx -# #src/AliAlgDetTOF.cxx -# #src/AliAlgDetTPC.cxx -# #src/AliAlgDetTRD.cxx -# #src/AliAlgDOFStat.cxx -# #src/AliAlgMPRecord.cxx -# #src/AliAlgPoint.cxx -# #src/AliAlgRes.cxx -# #src/AliAlgResFast.cxx -# #src/AliAlgSens.cxx -# #src/AliAlgSensHMPID.cxx -# #src/AliAlgSensITS.cxx -# #src/AliAlgSensTOF.cxx -# #src/AliAlgSensTPC.cxx -# #src/AliAlgSensTRD.cxx -# #src/AliAlgSteer.cxx -# #src/AliAlgTrack.cxx -# #src/AliAlgVol.cxx -# #src/AliAlgVtx.cxx -# #src/Mille.cxx -# PUBLIC_LINK_LIBRARIES O2::FrameworkLogger -# ROOT::Core -# ROOT::Geom -# ROOT::Gpad -# ROOT::Graf3d -# ROOT::MathCore -# ROOT::Matrix -# ROOT::Hist -# ROOT::RIO -# ROOT::Tree) +o2_add_library(Align + SOURCES src/AliAlgAux.cxx + #src/AliAlgConstraint.cxx + #src/AliAlgDet.cxx + #src/AliAlgDetHMPID.cxx + #src/AliAlgDetITS.cxx + #src/AliAlgDetTOF.cxx + #src/AliAlgDetTPC.cxx + #src/AliAlgDetTRD.cxx + #src/AliAlgDOFStat.cxx + #src/AliAlgMPRecord.cxx + #src/AliAlgPoint.cxx + #src/AliAlgRes.cxx + #src/AliAlgResFast.cxx + #src/AliAlgSens.cxx + #src/AliAlgSensHMPID.cxx + #src/AliAlgSensITS.cxx + #src/AliAlgSensTOF.cxx + #src/AliAlgSensTPC.cxx + #src/AliAlgSensTRD.cxx + #src/AliAlgSteer.cxx + #src/AliAlgTrack.cxx + #src/AliAlgVol.cxx + #src/AliAlgVtx.cxx + #src/Mille.cxx + PUBLIC_LINK_LIBRARIES O2::FrameworkLogger + ROOT::Core + ROOT::Geom + ROOT::Gpad + ROOT::Graf3d + ROOT::MathCore + ROOT::Matrix + ROOT::Hist + ROOT::RIO + ROOT::Tree) -#o2_target_root_dictionary( -# ReconstructionDataFormats -# HEADERS #include/Align/AliAlgDet.h -# #include/Align/AliAlgDetITS.h -# #include/Align/AliAlgDetTOF.h -# #include/Align/AliAlgDetTPC.h -# #include/Align/AliAlgDetTRD.h -# #include/Align/AliAlgDetHMPID.h -# #include/Align/AliAlgMPRecord.h -# #include/Align/AliAlgPoint.h -# #include/Align/AliAlgSens.h -# #include/Align/AliAlgSensITS.h -# #include/Align/AliAlgSensTOF.h -# #include/Align/AliAlgSensTPC.h -# #include/Align/AliAlgSensTRD.h -# #include/Align/AliAlgSensHMPID.h -# #include/Align/AliAlgSteer.h -# #include/Align/AliAlgTrack.h -# #include/Align/AliAlgVol.h -# #include/Align/AliAlgVtx.h -# #include/Align/AliAlgRes.h -# #include/Align/AliAlgResFast.h -# #include/Align/AliAlgConstraint.h -# #include/Align/AliAlgDOFStat.h -# #include/Align/AliAlgAux.h -# ) +o2_target_root_dictionary( + Align + HEADERS #include/Align/AliAlgDet.h + #include/Align/AliAlgDetITS.h + #include/Align/AliAlgDetTOF.h + #include/Align/AliAlgDetTPC.h + #include/Align/AliAlgDetTRD.h + #include/Align/AliAlgDetHMPID.h + #include/Align/AliAlgMPRecord.h + #include/Align/AliAlgPoint.h + #include/Align/AliAlgSens.h + #include/Align/AliAlgSensITS.h + #include/Align/AliAlgSensTOF.h + #include/Align/AliAlgSensTPC.h + #include/Align/AliAlgSensTRD.h + #include/Align/AliAlgSensHMPID.h + #include/Align/AliAlgSteer.h + #include/Align/AliAlgTrack.h + #include/Align/AliAlgVol.h + #include/Align/AliAlgVtx.h + #include/Align/AliAlgRes.h + #include/Align/AliAlgResFast.h + #include/Align/AliAlgConstraint.h + #include/Align/AliAlgDOFStat.h + include/Align/AliAlgAux.h + ) diff --git a/Detectors/Align/include/Align/AliAlgAux.h b/Detectors/Align/include/Align/AliAlgAux.h index b50bdb7182aa1..8d292458445aa 100644 --- a/Detectors/Align/include/Align/AliAlgAux.h +++ b/Detectors/Align/include/Align/AliAlgAux.h @@ -77,12 +77,7 @@ inline Bool_t IsZeroPos(float f) { return Smaller(f, kAlmostZeroF); } int FindKeyIndex(int key, const int* arr, int n); // void PrintBits(ULong64_t patt, Int_t maxBits); -// -// OCDB related stuff -void CleanOCDB(); -AliCDBId* FindCDBId(const TList* cdbList, const TString& key); -void RectifyOCDBUri(TString& inp); -Bool_t PreloadOCDB(int run, const TMap* cdbMap, const TList* cdbList); + } // namespace AliAlgAux //_________________________________________________________________________________ diff --git a/Detectors/Align/src/ALIGNLinkDef.h b/Detectors/Align/src/ALIGNLinkDef.h deleted file mode 100644 index 49647d3efb3eb..0000000000000 --- a/Detectors/Align/src/ALIGNLinkDef.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifdef __CLING__ - -#pragma link off all globals; -#pragma link off all classes; -#pragma link off all functions; - -//#pragma link C++ class AliAlgAux; -#pragma link C++ class o2::align::AliAlgDet + ; -#pragma link C++ class o2::align::AliAlgDetITS + ; -#pragma link C++ class o2::align::AliAlgDetTOF + ; -#pragma link C++ class o2::align::AliAlgDetTPC + ; -#pragma link C++ class o2::align::AliAlgDetTRD + ; -#pragma link C++ class o2::align::AliAlgDetHMPID + ; -#pragma link C++ class o2::align::AliAlgMPRecord + ; -#pragma link C++ class o2::align::AliAlgPoint + ; -#pragma link C++ class o2::align::AliAlgSens + ; -#pragma link C++ class o2::align::AliAlgSensITS + ; -#pragma link C++ class o2::align::AliAlgSensTOF + ; -#pragma link C++ class o2::align::AliAlgSensTPC + ; -#pragma link C++ class o2::align::AliAlgSensTRD + ; -#pragma link C++ class o2::align::AliAlgSensHMPID + ; -#pragma link C++ class o2::align::AliAlgSteer + ; -#pragma link C++ class o2::align::AliAlgTrack + ; -#pragma link C++ class o2::align::AliAlgVol + ; -#pragma link C++ class o2::align::AliAlgVtx + ; -#pragma link C++ class o2::align::AliAlgRes + ; -#pragma link C++ class o2::align::AliAlgResFast + ; -#pragma link C++ class o2::align::AliAlgConstraint + ; -#pragma link C++ class o2::align::AliAlgDOFStat + ; -#pragma link C++ class o2::align::AliAlgAux; - -#endif diff --git a/Detectors/Align/src/AliAlgAux.cxx b/Detectors/Align/src/AliAlgAux.cxx index 8d087df442a88..ea80079e04acb 100644 --- a/Detectors/Align/src/AliAlgAux.cxx +++ b/Detectors/Align/src/AliAlgAux.cxx @@ -22,7 +22,7 @@ #include #include #include -#include +#include namespace o2 { @@ -38,101 +38,6 @@ void AliAlgAux::PrintBits(ULong64_t patt, Int_t maxBits) printf("%c", ((patt >> i) & 0x1) ? '+' : '-'); } -//_______________________________________________________________ -AliCDBId* AliAlgAux::FindCDBId(const TList* cdbList, const TString& key) -{ - // Find enty for the key in the cdbList and create its CDBId - // User must take care of deleting created CDBId - TIter next(cdbList); - TObjString* entry; - while ((entry = (TObjString*)next())) - if (entry->GetString().Contains(key)) - break; - if (!entry) - return 0; - return AliCDBId::MakeFromString(entry->GetString()); - // -} - -//_________________________________________________________ -void AliAlgAux::RectifyOCDBUri(TString& inp) -{ - // render URI from cdbMap to usable form - TString uri = ""; - int ind; - if (inp.BeginsWith("alien:/")) { // alien folder - TPRegexp fr("[Ff]older=/"); - if ((ind = inp.Index(fr)) > 0) - inp.Remove(0, ind); - ind = inp.First('?'); - if (ind > 0) - inp.Resize(ind); - inp.Prepend("alien://"); - } else if (inp.BeginsWith("local:/")) { - ind = inp.First('?'); - if (ind > 0) - inp.Resize(ind); - } else { - AliFatalGeneralF("::RectifyOCDBUri", "Failed to extract OCDB URI from %s", inp.Data()); - } - // -} - -//_________________________________________________________ -Bool_t AliAlgAux::PreloadOCDB(int run, const TMap* cdbMap, const TList* cdbList) -{ - // Load OCDB paths for given run from pair of cdbMap / cdbList - // as they are usually stored in the UserInfo list of esdTree - // In order to avoid unnecessary uploads, the objects are not actually - // loaded/cached but just added as specific paths with version - // - TObjString *ostr, *okey; - TString uriDef, uri, key; - // - CleanOCDB(); - // - ostr = (TObjString*)cdbMap->GetValue("default"); - RectifyOCDBUri(uriDef = ostr->GetString()); - AliInfoGeneralF("", "Default storage %s", uriDef.Data()); - // - AliCDBManager* man = AliCDBManager::Instance(); - man->SetDefaultStorage(uriDef.Data()); - man->SetRun(run); - // - TIter nextM(cdbMap); - while ((okey = (TObjString*)nextM())) { - if ((key = okey->GetString()) == "default") - continue; - ostr = (TObjString*)cdbMap->GetValue(okey); - RectifyOCDBUri(uri = ostr->GetString()); - // fetch object from the list - AliCDBId* cdbID = FindCDBId(cdbList, key); - int ver = -1, sver = -1; - if (cdbID) { - ver = cdbID->GetVersion(); - sver = cdbID->GetSubVersion(); - delete cdbID; - } else { - AliWarningGeneralF("::PreloadOCDB", "Key %s has special storage %s but absent in the cdbList", - key.Data(), uri.Data()); - } - AliInfoGeneralF("::PreloadOCDB", "Setting storage for %s to %s", key.Data(), uri.Data()); - man->SetSpecificStorage(key.Data(), uri.Data(), ver, sver); - } - // - return kTRUE; -} - -//_________________________________________________________ -void AliAlgAux::CleanOCDB() -{ - // brings OCDB to virgin state - Bool_t isGrid = gGrid != 0; - AliCDBManager::Destroy(); - if (isGrid && !gGrid) - TGrid::Connect("alien://"); -} - //__________________________________________ int AliAlgAux::FindKeyIndex(int key, const int* arr, int n) { diff --git a/Detectors/Align/src/AlignLinkDef.h b/Detectors/Align/src/AlignLinkDef.h new file mode 100644 index 0000000000000..17b32e0a06015 --- /dev/null +++ b/Detectors/Align/src/AlignLinkDef.h @@ -0,0 +1,32 @@ +#ifdef __CLING__ + +#pragma link off all globals; +#pragma link off all classes; +#pragma link off all functions; + +//#pragma link C++ class AliAlgAux; +//#pragma link C++ class o2::align::AliAlgDet + ; +//#pragma link C++ class o2::align::AliAlgDetITS + ; +//#pragma link C++ class o2::align::AliAlgDetTOF + ; +//#pragma link C++ class o2::align::AliAlgDetTPC + ; +//#pragma link C++ class o2::align::AliAlgDetTRD + ; +//#pragma link C++ class o2::align::AliAlgDetHMPID + ; +//#pragma link C++ class o2::align::AliAlgMPRecord + ; +//#pragma link C++ class o2::align::AliAlgPoint + ; +//#pragma link C++ class o2::align::AliAlgSens + ; +//#pragma link C++ class o2::align::AliAlgSensITS + ; +//#pragma link C++ class o2::align::AliAlgSensTOF + ; +//#pragma link C++ class o2::align::AliAlgSensTPC + ; +//#pragma link C++ class o2::align::AliAlgSensTRD + ; +//#pragma link C++ class o2::align::AliAlgSensHMPID + ; +//#pragma link C++ class o2::align::AliAlgSteer + ; +//#pragma link C++ class o2::align::AliAlgTrack + ; +//#pragma link C++ class o2::align::AliAlgVol + ; +//#pragma link C++ class o2::align::AliAlgVtx + ; +//#pragma link C++ class o2::align::AliAlgRes + ; +//#pragma link C++ class o2::align::AliAlgResFast + ; +//#pragma link C++ class o2::align::AliAlgConstraint + ; +//#pragma link C++ class o2::align::AliAlgDOFStat + ; +#pragma link C++ class o2::align::AliAlgAux; + +#endif From 8f30ce0efe73268c8c7a36b6149a6666f9f42bef Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Wed, 10 Feb 2021 11:28:25 +0100 Subject: [PATCH 196/770] [ALIGN] port AliAlgDOFStat --- Detectors/Align/CMakeLists.txt | 4 +-- Detectors/Align/include/Align/AliAlgDOFStat.h | 6 ++-- Detectors/Align/src/AliAlgDOFStat.cxx | 33 ++++++++++--------- Detectors/Align/src/AlignLinkDef.h | 2 +- 4 files changed, 23 insertions(+), 22 deletions(-) diff --git a/Detectors/Align/CMakeLists.txt b/Detectors/Align/CMakeLists.txt index d19ac7e66af34..04ebb71b7b60c 100644 --- a/Detectors/Align/CMakeLists.txt +++ b/Detectors/Align/CMakeLists.txt @@ -17,7 +17,7 @@ o2_add_library(Align #src/AliAlgDetTOF.cxx #src/AliAlgDetTPC.cxx #src/AliAlgDetTRD.cxx - #src/AliAlgDOFStat.cxx + src/AliAlgDOFStat.cxx #src/AliAlgMPRecord.cxx #src/AliAlgPoint.cxx #src/AliAlgRes.cxx @@ -67,6 +67,6 @@ o2_target_root_dictionary( #include/Align/AliAlgRes.h #include/Align/AliAlgResFast.h #include/Align/AliAlgConstraint.h - #include/Align/AliAlgDOFStat.h + include/Align/AliAlgDOFStat.h include/Align/AliAlgAux.h ) diff --git a/Detectors/Align/include/Align/AliAlgDOFStat.h b/Detectors/Align/include/Align/AliAlgDOFStat.h index e2b51f8c5caee..1339eb10e4849 100644 --- a/Detectors/Align/include/Align/AliAlgDOFStat.h +++ b/Detectors/Align/include/Align/AliAlgDOFStat.h @@ -17,7 +17,7 @@ #define ALIALGDOFSTAT_H #include -class AliAlgSteer; +//class AliAlgSteer; class TH1F; class TCollection; @@ -38,8 +38,8 @@ class AliAlgDOFStat : public TNamed void SetStat(int idf, int v) { fStat[idf] = v; } void AddStat(int idf, int v) { fStat[idf] += v; } Int_t GetNMerges() const { return fNMerges; } - // - TH1F* CreateHisto(AliAlgSteer* st) const; + // FIXME(milettri): needs AliAlgSteer + // TH1F* CreateHisto(AliAlgSteer* st) const; virtual void Print(Option_t* opt) const; virtual Long64_t Merge(TCollection* list); // diff --git a/Detectors/Align/src/AliAlgDOFStat.cxx b/Detectors/Align/src/AliAlgDOFStat.cxx index 77761bea3ca8d..311cd1313fde4 100644 --- a/Detectors/Align/src/AliAlgDOFStat.cxx +++ b/Detectors/Align/src/AliAlgDOFStat.cxx @@ -14,7 +14,7 @@ /// @brief Mergable bbject for statistics of points used by each DOF #include "Align/AliAlgDOFStat.h" -#include "Align/AliAlgSteer.h" +//#include "Align/AliAlgSteer.h" FIXME(milettri): needs AliAlgSteer #include "Framework/Logger.h" #include #include @@ -55,20 +55,21 @@ void AliAlgDOFStat::Print(Option_t*) const // } -//____________________________________________ -TH1F* AliAlgDOFStat::CreateHisto(AliAlgSteer* st) const -{ - // create histo with stat. If steer object is supplied, build labels - if (!fNDOFs) - return 0; - TH1F* h = new TH1F("DOFstat", "statistics per DOF", fNDOFs, 0, fNDOFs); - for (int i = fNDOFs; i--;) { - h->SetBinContent(i + 1, fStat[i]); - if (st) - h->GetXaxis()->SetBinLabel(i + 1, st->GetDOFLabelTxt(i)); - } - return h; -} +//FIXME(milettri): needs AliAlgSteer +////____________________________________________ +//TH1F* AliAlgDOFStat::CreateHisto(AliAlgSteer* st) const +//{ +// // create histo with stat. If steer object is supplied, build labels +// if (!fNDOFs) +// return 0; +// TH1F* h = new TH1F("DOFstat", "statistics per DOF", fNDOFs, 0, fNDOFs); +// for (int i = fNDOFs; i--;) { +// h->SetBinContent(i + 1, fStat[i]); +// if (st) +// h->GetXaxis()->SetBinLabel(i + 1, st->GetDOFLabelTxt(i)); +// } +// return h; +//} //______________________________________________________________________________ Long64_t AliAlgDOFStat::Merge(TCollection* list) @@ -82,7 +83,7 @@ Long64_t AliAlgDOFStat::Merge(TCollection* list) if (!stAdd) continue; if (fNDOFs != stAdd->fNDOFs) { - AliErrorF("Different NDOF: %d vs %d", fNDOFs, stAdd->fNDOFs); + LOG(ERROR) << "Different NDOF: " << fNDOFs << " vs " << stAdd->fNDOFs << "."; return 0; } for (int i = fNDOFs; i--;) diff --git a/Detectors/Align/src/AlignLinkDef.h b/Detectors/Align/src/AlignLinkDef.h index 17b32e0a06015..f70fff3b10d0a 100644 --- a/Detectors/Align/src/AlignLinkDef.h +++ b/Detectors/Align/src/AlignLinkDef.h @@ -26,7 +26,7 @@ //#pragma link C++ class o2::align::AliAlgRes + ; //#pragma link C++ class o2::align::AliAlgResFast + ; //#pragma link C++ class o2::align::AliAlgConstraint + ; -//#pragma link C++ class o2::align::AliAlgDOFStat + ; +#pragma link C++ class o2::align::AliAlgDOFStat + ; #pragma link C++ class o2::align::AliAlgAux; #endif From 6822c423ae4e6ef90dce2c528c1d1c053c38de1b Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Wed, 10 Feb 2021 11:55:51 +0100 Subject: [PATCH 197/770] [ALIGN] port AliAlgVol --- Detectors/Align/CMakeLists.txt | 4 +- Detectors/Align/include/Align/AliAlgVol.h | 4 +- Detectors/Align/src/AliAlgVol.cxx | 212 +++++++++++----------- Detectors/Align/src/AlignLinkDef.h | 2 +- 4 files changed, 114 insertions(+), 108 deletions(-) diff --git a/Detectors/Align/CMakeLists.txt b/Detectors/Align/CMakeLists.txt index 04ebb71b7b60c..59865b3b09710 100644 --- a/Detectors/Align/CMakeLists.txt +++ b/Detectors/Align/CMakeLists.txt @@ -30,7 +30,7 @@ o2_add_library(Align #src/AliAlgSensTRD.cxx #src/AliAlgSteer.cxx #src/AliAlgTrack.cxx - #src/AliAlgVol.cxx + src/AliAlgVol.cxx #src/AliAlgVtx.cxx #src/Mille.cxx PUBLIC_LINK_LIBRARIES O2::FrameworkLogger @@ -62,7 +62,7 @@ o2_target_root_dictionary( #include/Align/AliAlgSensHMPID.h #include/Align/AliAlgSteer.h #include/Align/AliAlgTrack.h - #include/Align/AliAlgVol.h + include/Align/AliAlgVol.h #include/Align/AliAlgVtx.h #include/Align/AliAlgRes.h #include/Align/AliAlgResFast.h diff --git a/Detectors/Align/include/Align/AliAlgVol.h b/Detectors/Align/include/Align/AliAlgVol.h index 2daea62225074..616921e2774a8 100644 --- a/Detectors/Align/include/Align/AliAlgVol.h +++ b/Detectors/Align/include/Align/AliAlgVol.h @@ -26,11 +26,11 @@ #include #include #include -#include +#include +#include "Align/AliAlgDOFStat.h" class TObjArray; class TClonesArray; -class AliAlgDOFStat; class TH1; namespace o2 diff --git a/Detectors/Align/src/AliAlgVol.cxx b/Detectors/Align/src/AliAlgVol.cxx index e9319d7c014dd..a6ad3a91692b5 100644 --- a/Detectors/Align/src/AliAlgVol.cxx +++ b/Detectors/Align/src/AliAlgVol.cxx @@ -97,7 +97,7 @@ #include "Align/AliAlgVol.h" #include "Align/AliAlgDOFStat.h" -#include "Align/AliAlgConstraint.h" +//#include "Align/AliAlgConstraint.h" FIXME(milettri): needs AliAlgsConstraint //#include "AliAlignObjParams.h" //#include "AliGeomManager.h" #include "Align/AliAlgAux.h" @@ -110,9 +110,9 @@ #include #include -ClassImp(o2::align::AliAlgVol) +ClassImp(o2::align::AliAlgVol); - using namespace TMath; +using namespace TMath; using namespace o2::align::AliAlgAux; namespace o2 @@ -166,14 +166,16 @@ AliAlgVol::~AliAlgVol() //_________________________________________________________ void AliAlgVol::Delta2Matrix(TGeoHMatrix& deltaM, const Double_t* delta) const { - // prepare delta matrix for the volume from its - // local delta vector (AliAlignObj convension): dx,dy,dz,,theta,psi,phi - const double *tr = &delta[0], *rt = &delta[3]; // translation(cm) and rotation(degree) - AliAlignObjParams tempAlignObj; - tempAlignObj.SetRotation(rt[0], rt[1], rt[2]); - tempAlignObj.SetTranslation(tr[0], tr[1], tr[2]); - tempAlignObj.GetMatrix(deltaM); + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + //FIXME(milettri): needs AliAlignObj + // // prepare delta matrix for the volume from its + // // local delta vector (AliAlignObj convension): dx,dy,dz,,theta,psi,phi + // const double *tr = &delta[0], *rt = &delta[3]; // translation(cm) and rotation(degree) // + // AliAlignObjParams tempAlignObj; + // tempAlignObj.SetRotation(rt[0], rt[1], rt[2]); + // tempAlignObj.SetTranslation(tr[0], tr[1], tr[2]); + // tempAlignObj.GetMatrix(deltaM); } //__________________________________________________________________ @@ -295,41 +297,43 @@ void AliAlgVol::Print(const Option_t* opt) const //____________________________________________ void AliAlgVol::PrepareMatrixL2G(Bool_t reco) { - // extract from geometry L2G matrix, depending on reco flag, set it as a reco-time - // or current alignment matrix - const char* path = GetSymName(); - if (gGeoManager->GetAlignableEntry(path)) { - const TGeoHMatrix* l2g = AliGeomManager::GetMatrix(path); - if (!l2g) - AliFatalF("Failed to find L2G matrix for alignable %s", path); - reco ? SetMatrixL2GReco(*l2g) : SetMatrixL2G(*l2g); - } else { // extract from path - if (!gGeoManager->CheckPath(path)) - AliFatalF("Volume path %s not valid!", path); - TGeoPhysicalNode* node = (TGeoPhysicalNode*)gGeoManager->GetListOfPhysicalNodes()->FindObject(path); - TGeoHMatrix l2g; - if (!node) { - AliWarningF("Attention: volume %s was not misaligned, extracting original matrix", path); - if (!AliGeomManager::GetOrigGlobalMatrix(path, l2g)) { - AliFatalF("Failed to find ideal L2G matrix for %s", path); - } - } else { - l2g = *node->GetMatrix(); - } - reco ? SetMatrixL2GReco(l2g) : SetMatrixL2G(l2g); - } - // + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + // FIXME(milettri): needs AliGeomManager + // // extract from geometry L2G matrix, depending on reco flag, set it as a reco-time + // // or current alignment matrix + // const char* path = GetSymName(); + // if (gGeoManager->GetAlignableEntry(path)) { + // const TGeoHMatrix* l2g = AliGeomManager::GetMatrix(path); + // if (!l2g) + // LOG(FATAL) << "Failed to find L2G matrix for alignable " << path; + // reco ? SetMatrixL2GReco(*l2g) : SetMatrixL2G(*l2g); + // } else { // extract from path + // if (!gGeoManager->CheckPath(path)) + // LOG(FATAL) << "Volume path " << path << " is not valid!"; + // TGeoPhysicalNode* node = (TGeoPhysicalNode*)gGeoManager->GetListOfPhysicalNodes()->FindObject(path); + // TGeoHMatrix l2g; + // if (!node) { + // LOG(WARNING) << "volume " << path << " was not misaligned, extracting original matrix"; + // if (!AliGeomManager::GetOrigGlobalMatrix(path, l2g)) { + // LOG(FATAL) << "Failed to find ideal L2G matrix for " << path; + // } + // } else { + // l2g = *node->GetMatrix(); + // } + // reco ? SetMatrixL2GReco(l2g) : SetMatrixL2G(l2g); + // } } //____________________________________________ void AliAlgVol::PrepareMatrixL2GIdeal() { - // extract from geometry ideal L2G matrix - TGeoHMatrix mtmp; - if (!AliGeomManager::GetOrigGlobalMatrix(GetSymName(), mtmp)) - AliFatalF("Failed to find ideal L2G matrix for %s", GetSymName()); - SetMatrixL2GIdeal(mtmp); - // + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + // FIXME(milettri): needs AliGeomManager + // // extract from geometry ideal L2G matrix + // TGeoHMatrix mtmp; + // if (!AliGeomManager::GetOrigGlobalMatrix(GetSymName(), mtmp)) + // LOG(FATAL) << "Failed to find ideal L2G matrix for " << GetSymName(); + // SetMatrixL2GIdeal(mtmp); } //____________________________________________ @@ -382,7 +386,7 @@ void AliAlgVol::SetTrackingFrame() // Define tracking frame of the sensor // This method should be implemented for sensors, which receive the T2L // matrix from the geometry - AliErrorF("Volume %s was supposed to implement its own method", GetName()); + LOG(ERROR) << "Volume " << GetName() << " was supposed to implement its own method"; } //__________________________________________________________________ @@ -412,14 +416,12 @@ void AliAlgVol::InitDOFs() // // Do we need this strict condition? if (GetInitDOFsDone()) - AliFatalF("Something is wrong, DOFs are already initialized for %s", GetName()); + LOG(FATAL) << "DOFs are already initialized for " << GetName(); for (int i = 0; i < fNDOFs; i++) if (fParErrs[i] < -9999 && IsZeroAbs(fParVals[i])) FixDOF(i); CalcFree(kTRUE); - // SetInitDOFsDone(); - // } //__________________________________________________________________ @@ -465,7 +467,7 @@ void AliAlgVol::SetParVals(Int_t npar, Double_t* vl, Double_t* er) { // set parameters if (npar > fNDOFs) - AliFatalF("Volume %s has %d dofs", GetName(), fNDOFs); + LOG(FATAL) << "Volume " << GetName() << " has " << fNDOFs << " dofs"; for (int i = 0; i < npar; i++) { fParVals[i] = vl[i]; fParErrs[i] = er ? er[i] : 0; @@ -728,7 +730,6 @@ void AliAlgVol::CreateAlignmenMatrix(TGeoHMatrix& alg) const alg.MultiplyLeft(&par->GetMatrixL2GIdeal()); } */ - // } /* @@ -763,48 +764,52 @@ void AliAlgVol::CreateAlignmenMatrix(TGeoHMatrix& alg) const //_________________________________________________________________ void AliAlgVol::CreateAlignmentObjects(TClonesArray* arr) const { + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + // FIXME(milettri): needs AliAlignObjParams // add to supplied array alignment object for itself and children - TClonesArray& parr = *arr; - TGeoHMatrix algM; - CreateAlignmenMatrix(algM); - new (parr[parr.GetEntriesFast()]) AliAlignObjParams(GetName(), GetVolID(), algM, kTRUE); - int nch = GetNChildren(); - for (int ich = 0; ich < nch; ich++) - GetChild(ich)->CreateAlignmentObjects(arr); + // TClonesArray& parr = *arr; + // TGeoHMatrix algM; + // CreateAlignmenMatrix(algM); + // new (parr[parr.GetEntriesFast()]) AliAlignObjParams(GetName(), GetVolID(), algM, kTRUE); + // int nch = GetNChildren(); + // for (int ich = 0; ich < nch; ich++) + // GetChild(ich)->CreateAlignmentObjects(arr); // } //_________________________________________________________________ void AliAlgVol::UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta) { - // recreate fMatL2GReco matrices from ideal L2G matrix and alignment objects - // used during data reconstruction. For the volume at level J we have - // L2G' = Delta_J * Delta_{J-1} *...* Delta_0 * L2GIdeal - // cumulDelta is Delta_{J-1} * ... * Delta_0, supplied by the parent - // - fMatL2GReco = fMatL2GIdeal; - // find alignment object for this volume - int nalg = algArr->GetEntriesFast(); - const AliAlignObjParams* par = 0; - for (int i = 0; i < nalg; i++) { - par = (AliAlignObjParams*)algArr->At(i); - if (!strcmp(par->GetSymName(), GetSymName())) - break; - par = 0; - } - TGeoHMatrix delta; - if (!par) - AliInfoF("Alignment for %s is absent in Reco-Time alignment object", GetSymName()); - else - par->GetMatrix(delta); - if (cumulDelta) - delta *= *cumulDelta; - // - fMatL2GReco.MultiplyLeft(&delta); - // propagate to children - for (int ich = GetNChildren(); ich--;) - GetChild(ich)->UpdateL2GRecoMatrices(algArr, &delta); - // + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + // FIXME(milettri): needs AliAlignObjParams + // // recreate fMatL2GReco matrices from ideal L2G matrix and alignment objects + // // used during data reconstruction. For the volume at level J we have + // // L2G' = Delta_J * Delta_{J-1} *...* Delta_0 * L2GIdeal + // // cumulDelta is Delta_{J-1} * ... * Delta_0, supplied by the parent + // // + // fMatL2GReco = fMatL2GIdeal; + // // find alignment object for this volume + // int nalg = algArr->GetEntriesFast(); + // const AliAlignObjParams* par = 0; + // for (int i = 0; i < nalg; i++) { + // par = (AliAlignObjParams*)algArr->At(i); + // if (!strcmp(par->GetSymName(), GetSymName())) + // break; + // par = 0; + // } + // TGeoHMatrix delta; + // if (!par) + // LOG(INFO) << "Alignment for " << GetSymName() << " is absent in Reco-Time alignment object"; + // else + // par->GetMatrix(delta); + // if (cumulDelta) + // delta *= *cumulDelta; + // // + // fMatL2GReco.MultiplyLeft(&delta); + // // propagate to children + // for (int ich = GetNChildren(); ich--;) + // GetChild(ich)->UpdateL2GRecoMatrices(algArr, &delta); + // // } //______________________________________________________ @@ -862,28 +867,29 @@ void AliAlgVol::FillDOFStat(AliAlgDOFStat* h) const //________________________________________ void AliAlgVol::AddAutoConstraints(TObjArray* constrArr) { - // adds automatic constraints - int nch = GetNChildren(); - // - if (HasChildrenConstraint()) { - AliAlgConstraint* constr = new AliAlgConstraint(); - constr->SetConstrainPattern(fConstrChild); - constr->SetParent(this); - for (int ich = nch; ich--;) { - AliAlgVol* child = GetChild(ich); - if (child->GetExcludeFromParentConstraint()) - continue; - constr->AddChild(child); - } - if (constr->GetNChildren()) - constrArr->Add(constr); - else - delete constr; - } - // - for (int ich = 0; ich < nch; ich++) - GetChild(ich)->AddAutoConstraints(constrArr); - // + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + // FIXME(milettri): needs AliAlgConstraint + // // adds automatic constraints + // int nch = GetNChildren(); + // // + // if (HasChildrenConstraint()) { + // AliAlgConstraint* constr = new AliAlgConstraint(); + // constr->SetConstrainPattern(fConstrChild); + // constr->SetParent(this); + // for (int ich = nch; ich--;) { + // AliAlgVol* child = GetChild(ich); + // if (child->GetExcludeFromParentConstraint()) + // continue; + // constr->AddChild(child); + // } + // if (constr->GetNChildren()) + // constrArr->Add(constr); + // else + // delete constr; + // } + // for (int ich = 0; ich < nch; ich++) { + // GetChild(ich)->AddAutoConstraints(constrArr); + // } } } // namespace align diff --git a/Detectors/Align/src/AlignLinkDef.h b/Detectors/Align/src/AlignLinkDef.h index f70fff3b10d0a..60aa049ea2b88 100644 --- a/Detectors/Align/src/AlignLinkDef.h +++ b/Detectors/Align/src/AlignLinkDef.h @@ -21,7 +21,7 @@ //#pragma link C++ class o2::align::AliAlgSensHMPID + ; //#pragma link C++ class o2::align::AliAlgSteer + ; //#pragma link C++ class o2::align::AliAlgTrack + ; -//#pragma link C++ class o2::align::AliAlgVol + ; +#pragma link C++ class o2::align::AliAlgVol + ; //#pragma link C++ class o2::align::AliAlgVtx + ; //#pragma link C++ class o2::align::AliAlgRes + ; //#pragma link C++ class o2::align::AliAlgResFast + ; From 60ca59534169fdc559973fa9072885f58ef7938b Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Wed, 10 Feb 2021 12:32:56 +0100 Subject: [PATCH 198/770] [ALIGN] port AliAlgConstraint --- Detectors/Align/CMakeLists.txt | 4 +- Detectors/Align/src/AliAlgConstraint.cxx | 248 ++++++++++++----------- Detectors/Align/src/AliAlgVol.cxx | 46 ++--- Detectors/Align/src/AlignLinkDef.h | 2 +- 4 files changed, 150 insertions(+), 150 deletions(-) diff --git a/Detectors/Align/CMakeLists.txt b/Detectors/Align/CMakeLists.txt index 59865b3b09710..17baf59335a90 100644 --- a/Detectors/Align/CMakeLists.txt +++ b/Detectors/Align/CMakeLists.txt @@ -10,7 +10,7 @@ o2_add_library(Align SOURCES src/AliAlgAux.cxx - #src/AliAlgConstraint.cxx + src/AliAlgConstraint.cxx #src/AliAlgDet.cxx #src/AliAlgDetHMPID.cxx #src/AliAlgDetITS.cxx @@ -66,7 +66,7 @@ o2_target_root_dictionary( #include/Align/AliAlgVtx.h #include/Align/AliAlgRes.h #include/Align/AliAlgResFast.h - #include/Align/AliAlgConstraint.h + include/Align/AliAlgConstraint.h include/Align/AliAlgDOFStat.h include/Align/AliAlgAux.h ) diff --git a/Detectors/Align/src/AliAlgConstraint.cxx b/Detectors/Align/src/AliAlgConstraint.cxx index 4b2fe61efa966..311fda884494f 100644 --- a/Detectors/Align/src/AliAlgConstraint.cxx +++ b/Detectors/Align/src/AliAlgConstraint.cxx @@ -129,9 +129,9 @@ void AliAlgConstraint::WriteChildrenConstraints(FILE* conOut) const continue; int cmtStatus = nContCh[ics] > 0 ? kOff : kOn; // do we comment this constraint? // - if (cmtStatus) - AliInfoF("No contributors to constraint of %3s of %s", GetDOFName(ics), GetName()); - // + if (cmtStatus) { + LOG(INFO) << "No contributors to constraint of " << GetDOFName(ics) << " of " << GetName(); + } if (fSigma[ics] > 0) { fprintf(conOut, "\n%s%s\t%e\t%e\t%s %s of %s %s\n", comment[cmtStatus], kKeyConstr[kMeas], 0.0, fSigma[ics], comment[kOnOn], GetDOFName(ics), GetName(), GetTitle()); @@ -170,127 +170,129 @@ void AliAlgConstraint::WriteChildrenConstraints(FILE* conOut) const //______________________________________________________ void AliAlgConstraint::CheckConstraint() const { - // check how the constraints are satysfied - // - int nch = GetNChildren(); - if (!nch) - return; - // - Bool_t doJac = !GetNoJacobian(); // do we need jacobian evaluation? - float* cstrArr = new float[nch * kNDOFGeom * kNDOFGeom]; - memset(cstrArr, 0, nch * kNDOFGeom * kNDOFGeom * sizeof(float)); - // we need for each children the matrix for vector transformation from children frame - // (in which its DOFs are defined, LOC or TRA) to this parent variation frame - // matRel = mPar^-1*mChild - TGeoHMatrix mPar; - // in case of parent assigned use its matrix, - // otherwise Alice global frame is assumed to be the parent -> Unit matrix - if (fParent && doJac) { - if (fParent->IsFrameTRA()) - fParent->GetMatrixT2G(mPar); // tracking to global - else - mPar = fParent->GetMatrixL2GIdeal(); // local to global - mPar = mPar.Inverse(); - } - // - float* jac = cstrArr; - double parsTotEx[kNDOFGeom] = {0}; // explicitly calculated total modification - double parsTotAn[kNDOFGeom] = {0}; // analyticaly calculated total modification - // - printf("\n\n ----- Constraints Validation for %s %s ------\n", GetName(), GetTitle()); - printf(" chld| "); - for (int jp = 0; jp < kNDOFGeom; jp++) - printf(" %3s:%3s An/Ex |", GetDOFName(jp), IsDOFConstrained(jp) ? "ON " : "OFF"); - printf(" | "); - for (int jp = 0; jp < kNDOFGeom; jp++) - printf(" D%3s ", GetDOFName(jp)); - printf(" ! %s\n", GetName()); - for (int ich = 0; ich < nch; ich++) { - AliAlgVol* child = GetChild(ich); - double parsC[kNDOFGeom] = {0}, parsPAn[kNDOFGeom] = {0}, parsPEx[kNDOFGeom] = {0}; - for (int jc = kNDOFGeom; jc--;) - parsC[jc] = child->GetParVal(jc); // child params in child frame - printf("#%3d | ", ich); - // - if (doJac) { - TGeoHMatrix matRel; - if (child->IsFrameTRA()) - child->GetMatrixT2G(matRel); // tracking to global - else - matRel = child->GetMatrixL2GIdeal(); // local to global - // - matRel.MultiplyLeft(&mPar); - ConstrCoefGeom(matRel, jac); // Jacobian for analytical constraint used by MillePeded - // - TGeoHMatrix tau; - child->Delta2Matrix(tau, parsC); // child correction matrix in the child frame - const TGeoHMatrix& matreli = matRel.Inverse(); - tau.Multiply(&matreli); - tau.MultiplyLeft(&matRel); // child correction matrix in the parent frame - AliAlignObjParams tmpPar; - tmpPar.SetMatrix(tau); - tmpPar.GetTranslation(&parsPEx[0]); - tmpPar.GetAngles(&parsPEx[3]); // explicitly calculated child params in parent frame - // - // analytically calculated child params in parent frame - for (int jp = 0; jp < kNDOFGeom; jp++) { - for (int jc = 0; jc < kNDOFGeom; jc++) - parsPAn[jp] += jac[jp * kNDOFGeom + jc] * parsC[jc]; - parsTotAn[jp] += parsPAn[jp]; // analyticaly calculated total modification - parsTotEx[jp] += parsPEx[jp]; // explicitly calculated total modification - // - printf("%+.1e/%+.1e ", parsPAn[jp], parsPEx[jp]); - // - } - // - jac += kNDOFGeom * kNDOFGeom; // matrix for next slot - } else { - for (int jc = 0; jc < kNDOFGeom; jc++) { - Bool_t acc = child->IsFreeDOF(jc) && child->GetParErr(jc) >= 0; - if (acc) { - printf(" %+.3e ", parsC[jc]); - parsTotAn[jc] += parsC[jc]; - } else - printf(" /* %+.3e */ ", parsC[jc]); // just for info, not in the constraint - } - } - printf(" | "); - for (int jc = 0; jc < kNDOFGeom; jc++) - printf("%+.1e ", parsC[jc]); // child proper corrections - printf(" ! %s\n", child->GetSymName()); - } - // - printf(" Tot | "); - for (int jp = 0; jp < kNDOFGeom; jp++) { - if (doJac) - printf("%+.1e/%+.1e ", parsTotAn[jp], parsTotEx[jp]); - else { - if (IsDOFConstrained(jp)) - printf(" %+.3e ", parsTotAn[jp]); - else - printf(" /* %+.3e */ ", parsTotAn[jp]); - } - } - printf(" | "); - if (fParent) - for (int jp = 0; jp < kNDOFGeom; jp++) - printf("%+.1e ", fParent->GetParVal(jp)); // parent proper corrections - else - printf(" no parent -> %s ", doJac ? "Global" : "Simple"); - printf(" ! <----- %s\n", GetName()); - // - printf(" Sig | "); - for (int jp = 0; jp < kNDOFGeom; jp++) { - if (IsDOFConstrained(jp)) - printf(" %+.3e ", fSigma[jp]); - else - printf(" /* %+.3e */ ", fSigma[jp]); - } - printf(" ! <----- \n"); - - // - delete[] cstrArr; + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + //FIXME(milettri) needs AliAlignObjParams + // // check how the constraints are satysfied + // // + // int nch = GetNChildren(); + // if (!nch) + // return; + // // + // Bool_t doJac = !GetNoJacobian(); // do we need jacobian evaluation? + // float* cstrArr = new float[nch * kNDOFGeom * kNDOFGeom]; + // memset(cstrArr, 0, nch * kNDOFGeom * kNDOFGeom * sizeof(float)); + // // we need for each children the matrix for vector transformation from children frame + // // (in which its DOFs are defined, LOC or TRA) to this parent variation frame + // // matRel = mPar^-1*mChild + // TGeoHMatrix mPar; + // // in case of parent assigned use its matrix, + // // otherwise Alice global frame is assumed to be the parent -> Unit matrix + // if (fParent && doJac) { + // if (fParent->IsFrameTRA()) + // fParent->GetMatrixT2G(mPar); // tracking to global + // else + // mPar = fParent->GetMatrixL2GIdeal(); // local to global + // mPar = mPar.Inverse(); + // } + // // + // float* jac = cstrArr; + // double parsTotEx[kNDOFGeom] = {0}; // explicitly calculated total modification + // double parsTotAn[kNDOFGeom] = {0}; // analyticaly calculated total modification + // // + // printf("\n\n ----- Constraints Validation for %s %s ------\n", GetName(), GetTitle()); + // printf(" chld| "); + // for (int jp = 0; jp < kNDOFGeom; jp++) + // printf(" %3s:%3s An/Ex |", GetDOFName(jp), IsDOFConstrained(jp) ? "ON " : "OFF"); + // printf(" | "); + // for (int jp = 0; jp < kNDOFGeom; jp++) + // printf(" D%3s ", GetDOFName(jp)); + // printf(" ! %s\n", GetName()); + // for (int ich = 0; ich < nch; ich++) { + // AliAlgVol* child = GetChild(ich); + // double parsC[kNDOFGeom] = {0}, parsPAn[kNDOFGeom] = {0}, parsPEx[kNDOFGeom] = {0}; + // for (int jc = kNDOFGeom; jc--;) + // parsC[jc] = child->GetParVal(jc); // child params in child frame + // printf("#%3d | ", ich); + // // + // if (doJac) { + // TGeoHMatrix matRel; + // if (child->IsFrameTRA()) + // child->GetMatrixT2G(matRel); // tracking to global + // else + // matRel = child->GetMatrixL2GIdeal(); // local to global + // // + // matRel.MultiplyLeft(&mPar); + // ConstrCoefGeom(matRel, jac); // Jacobian for analytical constraint used by MillePeded + // // + // TGeoHMatrix tau; + // child->Delta2Matrix(tau, parsC); // child correction matrix in the child frame + // const TGeoHMatrix& matreli = matRel.Inverse(); + // tau.Multiply(&matreli); + // tau.MultiplyLeft(&matRel); // child correction matrix in the parent frame + // AliAlignObjParams tmpPar; + // tmpPar.SetMatrix(tau); + // tmpPar.GetTranslation(&parsPEx[0]); + // tmpPar.GetAngles(&parsPEx[3]); // explicitly calculated child params in parent frame + // // + // // analytically calculated child params in parent frame + // for (int jp = 0; jp < kNDOFGeom; jp++) { + // for (int jc = 0; jc < kNDOFGeom; jc++) + // parsPAn[jp] += jac[jp * kNDOFGeom + jc] * parsC[jc]; + // parsTotAn[jp] += parsPAn[jp]; // analyticaly calculated total modification + // parsTotEx[jp] += parsPEx[jp]; // explicitly calculated total modification + // // + // printf("%+.1e/%+.1e ", parsPAn[jp], parsPEx[jp]); + // // + // } + // // + // jac += kNDOFGeom * kNDOFGeom; // matrix for next slot + // } else { + // for (int jc = 0; jc < kNDOFGeom; jc++) { + // Bool_t acc = child->IsFreeDOF(jc) && child->GetParErr(jc) >= 0; + // if (acc) { + // printf(" %+.3e ", parsC[jc]); + // parsTotAn[jc] += parsC[jc]; + // } else + // printf(" /* %+.3e */ ", parsC[jc]); // just for info, not in the constraint + // } + // } + // printf(" | "); + // for (int jc = 0; jc < kNDOFGeom; jc++) + // printf("%+.1e ", parsC[jc]); // child proper corrections + // printf(" ! %s\n", child->GetSymName()); + // } + // // + // printf(" Tot | "); + // for (int jp = 0; jp < kNDOFGeom; jp++) { + // if (doJac) + // printf("%+.1e/%+.1e ", parsTotAn[jp], parsTotEx[jp]); + // else { + // if (IsDOFConstrained(jp)) + // printf(" %+.3e ", parsTotAn[jp]); + // else + // printf(" /* %+.3e */ ", parsTotAn[jp]); + // } + // } + // printf(" | "); + // if (fParent) + // for (int jp = 0; jp < kNDOFGeom; jp++) + // printf("%+.1e ", fParent->GetParVal(jp)); // parent proper corrections + // else + // printf(" no parent -> %s ", doJac ? "Global" : "Simple"); + // printf(" ! <----- %s\n", GetName()); + // // + // printf(" Sig | "); + // for (int jp = 0; jp < kNDOFGeom; jp++) { + // if (IsDOFConstrained(jp)) + // printf(" %+.3e ", fSigma[jp]); + // else + // printf(" /* %+.3e */ ", fSigma[jp]); + // } + // printf(" ! <----- \n"); // + // // + // delete[] cstrArr; + // // } //_________________________________________________________________ diff --git a/Detectors/Align/src/AliAlgVol.cxx b/Detectors/Align/src/AliAlgVol.cxx index a6ad3a91692b5..ae35ed232cbb4 100644 --- a/Detectors/Align/src/AliAlgVol.cxx +++ b/Detectors/Align/src/AliAlgVol.cxx @@ -97,7 +97,7 @@ #include "Align/AliAlgVol.h" #include "Align/AliAlgDOFStat.h" -//#include "Align/AliAlgConstraint.h" FIXME(milettri): needs AliAlgsConstraint +#include "Align/AliAlgConstraint.h" //#include "AliAlignObjParams.h" //#include "AliGeomManager.h" #include "Align/AliAlgAux.h" @@ -867,29 +867,27 @@ void AliAlgVol::FillDOFStat(AliAlgDOFStat* h) const //________________________________________ void AliAlgVol::AddAutoConstraints(TObjArray* constrArr) { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; - // FIXME(milettri): needs AliAlgConstraint - // // adds automatic constraints - // int nch = GetNChildren(); - // // - // if (HasChildrenConstraint()) { - // AliAlgConstraint* constr = new AliAlgConstraint(); - // constr->SetConstrainPattern(fConstrChild); - // constr->SetParent(this); - // for (int ich = nch; ich--;) { - // AliAlgVol* child = GetChild(ich); - // if (child->GetExcludeFromParentConstraint()) - // continue; - // constr->AddChild(child); - // } - // if (constr->GetNChildren()) - // constrArr->Add(constr); - // else - // delete constr; - // } - // for (int ich = 0; ich < nch; ich++) { - // GetChild(ich)->AddAutoConstraints(constrArr); - // } + // adds automatic constraints + int nch = GetNChildren(); + // + if (HasChildrenConstraint()) { + AliAlgConstraint* constr = new AliAlgConstraint(); + constr->SetConstrainPattern(fConstrChild); + constr->SetParent(this); + for (int ich = nch; ich--;) { + AliAlgVol* child = GetChild(ich); + if (child->GetExcludeFromParentConstraint()) + continue; + constr->AddChild(child); + } + if (constr->GetNChildren()) + constrArr->Add(constr); + else + delete constr; + } + for (int ich = 0; ich < nch; ich++) { + GetChild(ich)->AddAutoConstraints(constrArr); + } } } // namespace align diff --git a/Detectors/Align/src/AlignLinkDef.h b/Detectors/Align/src/AlignLinkDef.h index 60aa049ea2b88..3c0331febb9bb 100644 --- a/Detectors/Align/src/AlignLinkDef.h +++ b/Detectors/Align/src/AlignLinkDef.h @@ -25,7 +25,7 @@ //#pragma link C++ class o2::align::AliAlgVtx + ; //#pragma link C++ class o2::align::AliAlgRes + ; //#pragma link C++ class o2::align::AliAlgResFast + ; -//#pragma link C++ class o2::align::AliAlgConstraint + ; +#pragma link C++ class o2::align::AliAlgConstraint + ; #pragma link C++ class o2::align::AliAlgDOFStat + ; #pragma link C++ class o2::align::AliAlgAux; From e6d7ab258d809c6c8b200d8d20a58cc4e58cd103 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Wed, 10 Feb 2021 18:24:38 +0100 Subject: [PATCH 199/770] [ALIGN] port AliAlgPoint --- Detectors/Align/CMakeLists.txt | 5 +- Detectors/Align/include/Align/AliAlgAux.h | 8 +++ Detectors/Align/include/Align/AliAlgPoint.h | 49 +++++++------- Detectors/Align/src/AliAlgPoint.cxx | 71 ++++++++++++--------- Detectors/Align/src/AlignLinkDef.h | 2 +- 5 files changed, 76 insertions(+), 59 deletions(-) diff --git a/Detectors/Align/CMakeLists.txt b/Detectors/Align/CMakeLists.txt index 17baf59335a90..110ab7d3aed6b 100644 --- a/Detectors/Align/CMakeLists.txt +++ b/Detectors/Align/CMakeLists.txt @@ -19,7 +19,7 @@ o2_add_library(Align #src/AliAlgDetTRD.cxx src/AliAlgDOFStat.cxx #src/AliAlgMPRecord.cxx - #src/AliAlgPoint.cxx + src/AliAlgPoint.cxx #src/AliAlgRes.cxx #src/AliAlgResFast.cxx #src/AliAlgSens.cxx @@ -34,6 +34,7 @@ o2_add_library(Align #src/AliAlgVtx.cxx #src/Mille.cxx PUBLIC_LINK_LIBRARIES O2::FrameworkLogger + O2::ReconstructionDataFormats ROOT::Core ROOT::Geom ROOT::Gpad @@ -53,7 +54,7 @@ o2_target_root_dictionary( #include/Align/AliAlgDetTRD.h #include/Align/AliAlgDetHMPID.h #include/Align/AliAlgMPRecord.h - #include/Align/AliAlgPoint.h + include/Align/AliAlgPoint.h #include/Align/AliAlgSens.h #include/Align/AliAlgSensITS.h #include/Align/AliAlgSensTOF.h diff --git a/Detectors/Align/include/Align/AliAlgAux.h b/Detectors/Align/include/Align/AliAlgAux.h index 8d292458445aa..36fea8ba84acb 100644 --- a/Detectors/Align/include/Align/AliAlgAux.h +++ b/Detectors/Align/include/Align/AliAlgAux.h @@ -18,6 +18,7 @@ #include #include +#include "ReconstructionDataFormats/Track.h" // class AliCDBId; class TMap; class TList; @@ -29,6 +30,13 @@ namespace o2 namespace align { +using trackParam_t = typename track::TrackParametrizationWithError; +using value_t = typename trackParam_t::value_t; +using dim2_t = typename trackParam_t::dim2_t; +using dim3_t = typename trackParam_t::dim3_t; +using params_t = typename trackParam_t::params_t; +using covMat_t = typename trackParam_t::covMat_t; + namespace AliAlgAux { const double kAlmostZeroD = 1e-15; diff --git a/Detectors/Align/include/Align/AliAlgPoint.h b/Detectors/Align/include/Align/AliAlgPoint.h index ec8048012fb5e..5a6166b9e31a2 100644 --- a/Detectors/Align/include/Align/AliAlgPoint.h +++ b/Detectors/Align/include/Align/AliAlgPoint.h @@ -26,9 +26,10 @@ #include #include #include -#include "Align/AliAlgSens.h" - -//class AliExternalTrackParam; +//#include "Align/AliAlgSens.h" +#include "ReconstructionDataFormats/Track.h" +#include "Framework/Logger.h" +#include "Align/AliAlgAux.h" namespace o2 { @@ -38,19 +39,13 @@ namespace align class AliAlgPoint : public TObject { public: - enum { kMaterialBit = BIT(14) // point contains material - , - kMeasurementBit = BIT(15) // point contains measurement - , - kUpdateFromTrackBit = BIT(16) // point needs to recalculate itself using track info - , - kVaryELossBit = BIT(17) // ELoss variation allowed - , - kUseBzOnly = BIT(18) // use only Bz component (ITS) - , - kInvDir = BIT(19) // propagation via this point is in decreasing X direction (upper cosmic leg) - , - kStatOK = BIT(20) // point is accounted in global statistics + enum { kMaterialBit = BIT(14), // point contains material + kMeasurementBit = BIT(15), // point contains measurement + kUpdateFromTrackBit = BIT(16), // point needs to recalculate itself using track info + kVaryELossBit = BIT(17), // ELoss variation allowed + kUseBzOnly = BIT(18), // use only Bz component (ITS) + kInvDir = BIT(19), // propagation via this point is in decreasing X direction (upper cosmic leg) + kStatOK = BIT(20) // point is accounted in global statistics }; enum { kParY = 0 // track parameters , @@ -69,7 +64,7 @@ class AliAlgPoint : public TObject virtual ~AliAlgPoint() {} // void Init(); - void UpdatePointByTrackInfo(const AliExternalTrackParam* t); + void UpdatePointByTrackInfo(const trackParam_t* t); // Double_t GetAlphaSens() const { return fAlphaSens; } Double_t GetXSens() const { return fXSens; } @@ -81,9 +76,9 @@ class AliAlgPoint : public TObject const Double_t* GetXYZTracking() const { return fXYZTracking; } const Double_t* GetYZErrTracking() const { return fErrYZTracking; } // - const AliAlgSens* GetSensor() const { return fSensor; } - UInt_t GetVolID() const { return fSensor->GetVolID(); } - void SetSensor(AliAlgSens* s) { fSensor = s; } + // const AliAlgSens* GetSensor() const { return fSensor; } FIXME(milettri): needs AliAlgSens + // UInt_t GetVolID() const { return fSensor->GetVolID(); } FIXME(milettri): needs AliAlgSens + // void SetSensor(AliAlgSens* s) { fSensor = s; } FIXME(milettri): needs AliAlgSens Int_t GetDetID() const { return fDetID; } Int_t GetSID() const { return fSID; } Int_t GetMinLocVarID() const { return fMinLocVarID; } @@ -138,8 +133,8 @@ class AliAlgPoint : public TObject Double_t* GetTrParamWSB() const { return (Double_t*)fTrParamWSB; } Double_t GetTrParamWSA(int ip) const { return fTrParamWSA[ip]; } Double_t GetTrParamWSB(int ip) const { return fTrParamWSB[ip]; } - void GetTrWSA(AliExternalTrackParam& etp) const; - void GetTrWSB(AliExternalTrackParam& etp) const; + void GetTrWSA(trackParam_t& etp) const; + void GetTrWSB(trackParam_t& etp) const; void SetTrParamWSA(const double* param) { for (int i = 5; i--;) @@ -222,7 +217,7 @@ class AliAlgPoint : public TObject Double_t fTrParamWSA[kNMatDOFs]; // workspace for tracks params at this point AFTER material correction Double_t fTrParamWSB[kNMatDOFs]; // workspace for tracks params at this point BEFORE material correction // - AliAlgSens* fSensor; // sensor of this point + // AliAlgSens* fSensor; // sensor of this point FIXME(milettri): Needs AliAlgSens // ClassDef(AliAlgPoint, 1) }; @@ -272,9 +267,11 @@ inline void AliAlgPoint::GetResidualsDiag(const double* pos, double& resU, doubl //__________________________________________________________________ inline void AliAlgPoint::IncrementStat() { - // increment statistics for detectors this point depends on - fSensor->IncrementStat(); - SetStatOK(); + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + // FIXME(milettri): needs AliAlgSens + // // increment statistics for detectors this point depends on + // fSensor->IncrementStat(); + // SetStatOK(); } } // namespace align } // namespace o2 diff --git a/Detectors/Align/src/AliAlgPoint.cxx b/Detectors/Align/src/AliAlgPoint.cxx index c66a304f818b1..f180b5a532eb2 100644 --- a/Detectors/Align/src/AliAlgPoint.cxx +++ b/Detectors/Align/src/AliAlgPoint.cxx @@ -13,12 +13,10 @@ /// @since 2021-02-01 /// @brief Meausered point in the sensor. -#include +#include #include #include #include "Align/AliAlgPoint.h" -#include "Align/AliAlgAux.h" -//#include "AliExternalTrackParam.h" using namespace o2::align::AliAlgAux; using namespace TMath; @@ -30,7 +28,7 @@ namespace align //_____________________________________ AliAlgPoint::AliAlgPoint() - : fMinLocVarID(0), fMaxLocVarID(0), fDetID(-1), fSID(-1), fAlphaSens(0), fXSens(0), fCosDiagErr(0), fSinDiagErr(0), fX2X0(0), fXTimesRho(0), fNGloDOFs(0), fDGloOffs(0), fSensor(0) + : fMinLocVarID(0), fMaxLocVarID(0), fDetID(-1), fSID(-1), fAlphaSens(0), fXSens(0), fCosDiagErr(0), fSinDiagErr(0), fX2X0(0), fXTimesRho(0), fNGloDOFs(0), fDGloOffs(0) //, fSensor(0) FIXME(milettri): Needs AliAlgSens { // def c-tor for (int i = 3; i--;) { @@ -90,10 +88,12 @@ void AliAlgPoint::Init() } //_____________________________________ -void AliAlgPoint::UpdatePointByTrackInfo(const AliExternalTrackParam* t) +void AliAlgPoint::UpdatePointByTrackInfo(const trackParam_t* t) { - // recalculate point errors using info about the track in the sensor tracking frame - fSensor->UpdatePointByTrackInfo(this, t); + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + //FIXME(milettri): needs AliAlgSens + // // recalculate point errors using info about the track in the sensor tracking frame + // fSensor->UpdatePointByTrackInfo(this, t); } //_____________________________________ @@ -176,29 +176,34 @@ void AliAlgPoint::DumpCoordinates() const { // dump various corrdinates for inspection // global xyz - double xyz[3]; - GetXYZGlo(xyz); - for (int i = 0; i < 3; i++) - printf("%+.4e ", xyz[i]); - // - AliExternalTrackParam wsb; - AliExternalTrackParam wsa; + dim3_t xyz; + GetXYZGlo(xyz.data()); + + auto print3d = [](dim3_t& xyz) { + for (auto i : xyz) { + printf("%+.4e ", i); + } + }; + + print3d(xyz); + trackParam_t wsb; + trackParam_t wsa; GetTrWSB(wsb); GetTrWSA(wsa); - wsb.GetXYZ(xyz); - for (int i = 0; i < 3; i++) - printf("%+.4e ", xyz[i]); // track before mat corr - wsa.GetXYZ(xyz); - for (int i = 0; i < 3; i++) - printf("%+.4e ", xyz[i]); // track after mat corr - // + + wsb.getXYZGlo(xyz); + print3d(xyz); // track before mat corr + + wsa.getXYZGlo(xyz); + print3d(xyz); // track after mat corr + printf("%+.4f ", fAlphaSens); printf("%+.4e ", GetXPoint()); printf("%+.4e ", GetYTracking()); printf("%+.4e ", GetZTracking()); // - printf("%+.4e %.4e ", wsb.GetY(), wsb.GetZ()); - printf("%+.4e %.4e ", wsa.GetY(), wsa.GetZ()); + printf("%+.4e %.4e ", wsb.getY(), wsb.getZ()); + printf("%+.4e %.4e ", wsa.getY(), wsa.getZ()); // printf("%4e %4e", Sqrt(fErrYZTracking[0]), Sqrt(fErrYZTracking[2])); printf("\n"); @@ -215,7 +220,7 @@ void AliAlgPoint::Clear(Option_t*) fNGloDOFs = 0; fDGloOffs = 0; // - fSensor = 0; + // fSensor = 0; FIXME(milettri): needs AliAlgSens } //__________________________________________________________________ @@ -355,29 +360,35 @@ void AliAlgPoint::DiagMatCorr(const float* nodiag, float* diag) const } //__________________________________________________________________ -void AliAlgPoint::GetTrWSA(AliExternalTrackParam& etp) const +void AliAlgPoint::GetTrWSA(trackParam_t& etp) const { // assign WSA (after material corrections) parameters to supplied track - double covDum[15] = { + const trackParam_t::covMat_t covDum{ 1.e-4, 0, 1.e-4, 0, 0, 1.e-4, 0, 0, 0, 1.e-4, 0, 0, 0, 0, 1e-4}; - etp.Set(GetXPoint(), GetAlphaSens(), fTrParamWSA, covDum); + params_t tmp; + std::copy(std::begin(fTrParamWSA), std::end(fTrParamWSA), std::begin(tmp)); + + etp.set(GetXPoint(), GetAlphaSens(), tmp, covDum); } //__________________________________________________________________ -void AliAlgPoint::GetTrWSB(AliExternalTrackParam& etp) const +void AliAlgPoint::GetTrWSB(trackParam_t& etp) const { // assign WSB parameters (before material corrections) to supplied track - double covDum[15] = { + const trackParam_t::covMat_t covDum{ 1.e-4, 0, 1.e-4, 0, 0, 1.e-4, 0, 0, 0, 1.e-4, 0, 0, 0, 0, 1e-4}; - etp.Set(GetXPoint(), GetAlphaSens(), fTrParamWSB, covDum); + params_t tmp; + std::copy(std::begin(fTrParamWSB), std::end(fTrParamWSB), std::begin(tmp)); + + etp.set(GetXPoint(), GetAlphaSens(), tmp, covDum); } } // namespace align diff --git a/Detectors/Align/src/AlignLinkDef.h b/Detectors/Align/src/AlignLinkDef.h index 3c0331febb9bb..5afbe5c5cfa10 100644 --- a/Detectors/Align/src/AlignLinkDef.h +++ b/Detectors/Align/src/AlignLinkDef.h @@ -12,7 +12,7 @@ //#pragma link C++ class o2::align::AliAlgDetTRD + ; //#pragma link C++ class o2::align::AliAlgDetHMPID + ; //#pragma link C++ class o2::align::AliAlgMPRecord + ; -//#pragma link C++ class o2::align::AliAlgPoint + ; +#pragma link C++ class o2::align::AliAlgPoint + ; //#pragma link C++ class o2::align::AliAlgSens + ; //#pragma link C++ class o2::align::AliAlgSensITS + ; //#pragma link C++ class o2::align::AliAlgSensTOF + ; From a507c50d6dc055cff62521b711d4f9845d9ddda2 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Wed, 10 Feb 2021 18:57:56 +0100 Subject: [PATCH 200/770] [ALIGN] port AliAlgSens --- Detectors/Align/CMakeLists.txt | 4 +- Detectors/Align/include/Align/AliAlgPoint.h | 25 ++++++------ Detectors/Align/include/Align/AliAlgSens.h | 23 +++++------ Detectors/Align/src/AliAlgPoint.cxx | 9 ++--- Detectors/Align/src/AliAlgSens.cxx | 42 ++++++++++----------- Detectors/Align/src/AlignLinkDef.h | 3 +- 6 files changed, 51 insertions(+), 55 deletions(-) diff --git a/Detectors/Align/CMakeLists.txt b/Detectors/Align/CMakeLists.txt index 110ab7d3aed6b..6713f97f90408 100644 --- a/Detectors/Align/CMakeLists.txt +++ b/Detectors/Align/CMakeLists.txt @@ -22,7 +22,7 @@ o2_add_library(Align src/AliAlgPoint.cxx #src/AliAlgRes.cxx #src/AliAlgResFast.cxx - #src/AliAlgSens.cxx + src/AliAlgSens.cxx #src/AliAlgSensHMPID.cxx #src/AliAlgSensITS.cxx #src/AliAlgSensTOF.cxx @@ -55,7 +55,7 @@ o2_target_root_dictionary( #include/Align/AliAlgDetHMPID.h #include/Align/AliAlgMPRecord.h include/Align/AliAlgPoint.h - #include/Align/AliAlgSens.h + include/Align/AliAlgSens.h #include/Align/AliAlgSensITS.h #include/Align/AliAlgSensTOF.h #include/Align/AliAlgSensTPC.h diff --git a/Detectors/Align/include/Align/AliAlgPoint.h b/Detectors/Align/include/Align/AliAlgPoint.h index 5a6166b9e31a2..ff8064c90fd17 100644 --- a/Detectors/Align/include/Align/AliAlgPoint.h +++ b/Detectors/Align/include/Align/AliAlgPoint.h @@ -26,7 +26,7 @@ #include #include #include -//#include "Align/AliAlgSens.h" +#include "Align/AliAlgSens.h" #include "ReconstructionDataFormats/Track.h" #include "Framework/Logger.h" #include "Align/AliAlgAux.h" @@ -75,10 +75,11 @@ class AliAlgPoint : public TObject const Double_t* GetYZTracking() const { return &fXYZTracking[1]; } const Double_t* GetXYZTracking() const { return fXYZTracking; } const Double_t* GetYZErrTracking() const { return fErrYZTracking; } - // - // const AliAlgSens* GetSensor() const { return fSensor; } FIXME(milettri): needs AliAlgSens - // UInt_t GetVolID() const { return fSensor->GetVolID(); } FIXME(milettri): needs AliAlgSens - // void SetSensor(AliAlgSens* s) { fSensor = s; } FIXME(milettri): needs AliAlgSens + + const AliAlgSens* GetSensor() const { return fSensor; } + UInt_t GetVolID() const { return fSensor->GetVolID(); } + void SetSensor(AliAlgSens* s) { fSensor = s; } + Int_t GetDetID() const { return fDetID; } Int_t GetSID() const { return fSID; } Int_t GetMinLocVarID() const { return fMinLocVarID; } @@ -216,9 +217,9 @@ class AliAlgPoint : public TObject // Double_t fTrParamWSA[kNMatDOFs]; // workspace for tracks params at this point AFTER material correction Double_t fTrParamWSB[kNMatDOFs]; // workspace for tracks params at this point BEFORE material correction - // - // AliAlgSens* fSensor; // sensor of this point FIXME(milettri): Needs AliAlgSens - // + + AliAlgSens* fSensor; // sensor of this point + ClassDef(AliAlgPoint, 1) }; @@ -267,11 +268,9 @@ inline void AliAlgPoint::GetResidualsDiag(const double* pos, double& resU, doubl //__________________________________________________________________ inline void AliAlgPoint::IncrementStat() { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; - // FIXME(milettri): needs AliAlgSens - // // increment statistics for detectors this point depends on - // fSensor->IncrementStat(); - // SetStatOK(); + // increment statistics for detectors this point depends on + fSensor->IncrementStat(); + SetStatOK(); } } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgSens.h b/Detectors/Align/include/Align/AliAlgSens.h index 3c6a43f09aca4..35dbd117053fd 100644 --- a/Detectors/Align/include/Align/AliAlgSens.h +++ b/Detectors/Align/include/Align/AliAlgSens.h @@ -16,16 +16,17 @@ #ifndef ALIALGSENS_H #define ALIALGSENS_H -#include "Align/AliAlgVol.h" #include +#include + +#include "Align/AliAlgVol.h" +//#include "Align/AliAlgDet.h" FIXME(milettri) needs AliAlgDet; +#include "Align/AliAlgPoint.h" +#include "Align/AliAlgDOFStat.h" +#include "ReconstructionDataFormats/Track.h" //class AliTrackPointArray; //class AliESDtrack; -class AliAlgDet; -class AliAlgPoint; -class TObjArray; -//class AliExternalTrackParam; -class AliAlgDOFStat; class TCloneArray; namespace o2 @@ -42,8 +43,8 @@ class AliAlgSens : public AliAlgVol // virtual void AddChild(AliAlgVol*); // - void SetDetector(AliAlgDet* det) { fDet = det; } - AliAlgDet* GetDetector() const { return fDet; } + // void SetDetector(AliAlgDet* det) { fDet = det; } FIXME(milettri) needs AliAlgDet; + // AliAlgDet* GetDetector() const { return fDet; } FIXME(milettri) needs AliAlgDet; // Int_t GetSID() const { return fSID; } void SetSID(int s) { fSID = s; } @@ -77,10 +78,10 @@ class AliAlgSens : public AliAlgVol virtual Bool_t IsSensor() const { return kTRUE; } virtual void Print(const Option_t* opt = "") const; // - virtual void UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const; + virtual void UpdatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) const; virtual void UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta); // - virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t) = 0; + // virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t) = 0; TODO(milettri): needs AliTrackPointArray AliESDtrack // virtual Int_t FinalizeStat(AliAlgDOFStat* h = 0); // @@ -104,7 +105,7 @@ class AliAlgSens : public AliAlgVol // Int_t fSID; // sensor id in detector Double_t fAddError[2]; // additional error increment for measurement - AliAlgDet* fDet; // pointer on detector + // AliAlgDet* fDet; // pointer on detector FIXME(milettri) needs AliAlgDet; TGeoHMatrix fMatClAlg; // reference cluster alignment matrix in tracking frame TGeoHMatrix fMatClAlgReco; // reco-time cluster alignment matrix in tracking frame diff --git a/Detectors/Align/src/AliAlgPoint.cxx b/Detectors/Align/src/AliAlgPoint.cxx index f180b5a532eb2..14b46baff0a6e 100644 --- a/Detectors/Align/src/AliAlgPoint.cxx +++ b/Detectors/Align/src/AliAlgPoint.cxx @@ -28,7 +28,7 @@ namespace align //_____________________________________ AliAlgPoint::AliAlgPoint() - : fMinLocVarID(0), fMaxLocVarID(0), fDetID(-1), fSID(-1), fAlphaSens(0), fXSens(0), fCosDiagErr(0), fSinDiagErr(0), fX2X0(0), fXTimesRho(0), fNGloDOFs(0), fDGloOffs(0) //, fSensor(0) FIXME(milettri): Needs AliAlgSens + : fMinLocVarID(0), fMaxLocVarID(0), fDetID(-1), fSID(-1), fAlphaSens(0), fXSens(0), fCosDiagErr(0), fSinDiagErr(0), fX2X0(0), fXTimesRho(0), fNGloDOFs(0), fDGloOffs(0), fSensor(0) { // def c-tor for (int i = 3; i--;) { @@ -90,10 +90,8 @@ void AliAlgPoint::Init() //_____________________________________ void AliAlgPoint::UpdatePointByTrackInfo(const trackParam_t* t) { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; - //FIXME(milettri): needs AliAlgSens // // recalculate point errors using info about the track in the sensor tracking frame - // fSensor->UpdatePointByTrackInfo(this, t); + fSensor->UpdatePointByTrackInfo(this, t); } //_____________________________________ @@ -219,8 +217,7 @@ void AliAlgPoint::Clear(Option_t*) fSID = -1; fNGloDOFs = 0; fDGloOffs = 0; - // - // fSensor = 0; FIXME(milettri): needs AliAlgSens + fSensor = 0; } //__________________________________________________________________ diff --git a/Detectors/Align/src/AliAlgSens.cxx b/Detectors/Align/src/AliAlgSens.cxx index dba69b8a9263e..d930360723e20 100644 --- a/Detectors/Align/src/AliAlgSens.cxx +++ b/Detectors/Align/src/AliAlgSens.cxx @@ -13,18 +13,14 @@ /// @since 2021-02-01 /// @brief End-chain alignment volume in detector branch, where the actual measurement is done. -#include +#include #include + #include "Align/AliAlgSens.h" -#include "Align/AliAlgAux.h" #include "Framework/Logger.h" //#include "AliGeomManager.h" -//#include "AliExternalTrackParam.h" -#include "Align/AliAlgPoint.h" -#include "Align/AliAlgDet.h" -#include "Align/AliAlgDOFStat.h" -ClassImp(AliAlgSens); +ClassImp(o2::align::AliAlgSens); using namespace o2::align::AliAlgAux; using namespace TMath; @@ -36,7 +32,7 @@ namespace align //_________________________________________________________ AliAlgSens::AliAlgSens(const char* name, Int_t vid, Int_t iid) - : AliAlgVol(name, iid), fSID(0), fDet(0), fMatClAlg(), fMatClAlgReco() + : AliAlgVol(name, iid), fSID(0), /*fDet(0), */ fMatClAlg(), fMatClAlgReco() // FIXME(milettri): needs AliAlgDet { // def c-tor SetVolID(vid); @@ -263,7 +259,7 @@ void AliAlgSens::DPosTraDParGeom(const AliAlgPoint* pnt, double* deriv, const Al parent ? DPosTraDParGeomTRA(pnt, deriv, parent) : DPosTraDParGeomTRA(pnt, deriv); break; default: - AliErrorF("Alignment frame %d is not implemented", parent->GetVarFrame()); + LOG(ERROR) << "Alignment frame " << parent->GetVarFrame() << " is not implemented"; break; } } @@ -291,7 +287,7 @@ void AliAlgSens::GetModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const Double_t* //__________________________________________________________________ void AliAlgSens::AddChild(AliAlgVol*) { - AliFatalF("Sensor volume cannot have childs: id=%d %s", GetVolID(), GetName()); + LOG(FATAL) << "Sensor volume cannot have children: id=" << GetVolID() << " " << GetName(); } //__________________________________________________________________ @@ -367,14 +363,16 @@ void AliAlgSens::Print(const Option_t* opt) const //____________________________________________ void AliAlgSens::PrepareMatrixT2L() { - // extract from geometry T2L matrix - const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(GetVolID()); - if (!t2l) { - Print("long"); - AliFatalF("Failed to find T2L matrix for VID:%d %s", GetVolID(), GetSymName()); - } - SetMatrixT2L(*t2l); - // + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + // TODO(milettri): depends on AliGeomManager; + // // extract from geometry T2L matrix + // const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(GetVolID()); + // if (!t2l) { + // Print("long"); + // AliFatalF("Failed to find T2L matrix for VID:%d %s", GetVolID(), GetSymName()); + // } + // SetMatrixT2L(*t2l); + // // } //____________________________________________ @@ -398,10 +396,12 @@ void AliAlgSens::PrepareMatrixClAlgReco() } //____________________________________________ -void AliAlgSens::UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const +void AliAlgSens::UpdatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) const { - // update - fDet->UpdatePointByTrackInfo(pnt, t); + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + // FIXME(milettri) needs AliAlgDet; + // // update + // fDet->UpdatePointByTrackInfo(pnt, t); } //____________________________________________ diff --git a/Detectors/Align/src/AlignLinkDef.h b/Detectors/Align/src/AlignLinkDef.h index 5afbe5c5cfa10..af4a2d6c74ccc 100644 --- a/Detectors/Align/src/AlignLinkDef.h +++ b/Detectors/Align/src/AlignLinkDef.h @@ -4,7 +4,6 @@ #pragma link off all classes; #pragma link off all functions; -//#pragma link C++ class AliAlgAux; //#pragma link C++ class o2::align::AliAlgDet + ; //#pragma link C++ class o2::align::AliAlgDetITS + ; //#pragma link C++ class o2::align::AliAlgDetTOF + ; @@ -13,7 +12,7 @@ //#pragma link C++ class o2::align::AliAlgDetHMPID + ; //#pragma link C++ class o2::align::AliAlgMPRecord + ; #pragma link C++ class o2::align::AliAlgPoint + ; -//#pragma link C++ class o2::align::AliAlgSens + ; +#pragma link C++ class o2::align::AliAlgSens + ; //#pragma link C++ class o2::align::AliAlgSensITS + ; //#pragma link C++ class o2::align::AliAlgSensTOF + ; //#pragma link C++ class o2::align::AliAlgSensTPC + ; From 922725bc14b2c17b4ac80ec16822a2aa6d407343 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Wed, 10 Feb 2021 21:25:43 +0100 Subject: [PATCH 201/770] [ALIGN] port AliAlgDet --- Detectors/Align/CMakeLists.txt | 4 +- Detectors/Align/include/Align/AliAlgDet.h | 41 +-- Detectors/Align/include/Align/AliAlgSens.h | 13 +- Detectors/Align/src/AliAlgDet.cxx | 327 +++++++++++---------- Detectors/Align/src/AliAlgSens.cxx | 10 +- Detectors/Align/src/AlignLinkDef.h | 2 +- 6 files changed, 208 insertions(+), 189 deletions(-) diff --git a/Detectors/Align/CMakeLists.txt b/Detectors/Align/CMakeLists.txt index 6713f97f90408..3479529bd3a83 100644 --- a/Detectors/Align/CMakeLists.txt +++ b/Detectors/Align/CMakeLists.txt @@ -11,7 +11,7 @@ o2_add_library(Align SOURCES src/AliAlgAux.cxx src/AliAlgConstraint.cxx - #src/AliAlgDet.cxx + src/AliAlgDet.cxx #src/AliAlgDetHMPID.cxx #src/AliAlgDetITS.cxx #src/AliAlgDetTOF.cxx @@ -47,7 +47,7 @@ o2_add_library(Align o2_target_root_dictionary( Align - HEADERS #include/Align/AliAlgDet.h + HEADERS include/Align/AliAlgDet.h #include/Align/AliAlgDetITS.h #include/Align/AliAlgDetTOF.h #include/Align/AliAlgDetTPC.h diff --git a/Detectors/Align/include/Align/AliAlgDet.h b/Detectors/Align/include/Align/AliAlgDet.h index 7834d9472ee6e..a521649325790 100644 --- a/Detectors/Align/include/Align/AliAlgDet.h +++ b/Detectors/Align/include/Align/AliAlgDet.h @@ -20,15 +20,15 @@ #include #include #include "Align/AliAlgAux.h" +//#include "Align/AliAlgTrack.h" FIXME(milettri): needs AliAlgTrack +#include "Align/AliAlgDOFStat.h" +#include "Align/AliAlgPoint.h" +#include "Align/AliAlgSens.h" +#include "Align/AliAlgVol.h" +//#include "Align/AliAlgSteer.h" FIXME(milettri): needs AliAlgSteer //#include "AliESDtrack.h" -class AliAlgTrack; -class AliAlgDOFStat; -class AliAlgPoint; -class AliAlgSens; -class AliAlgVol; -class AliAlgSteer; //class AliTrackPointArray; -//class AliExternalTrackParam; + class TH1; namespace o2 @@ -44,7 +44,7 @@ class AliAlgDet : public TNamed enum { kNMaxKalibDOF = 64 }; // AliAlgDet(); - AliAlgDet(const char* name, const char* title = ""); + AliAlgDet(const char* name, const char* title = "") : TNamed(name, title) {} virtual ~AliAlgDet(); Int_t GetDetID() const { return GetUniqueID(); } void SetDetID(UInt_t tp); @@ -66,7 +66,7 @@ class AliAlgDet : public TNamed // Int_t GetNPoints() const { return fNPoints; } // - void SetAlgSteer(AliAlgSteer* s) { fAlgSteer = s; } + // void SetAlgSteer(AliAlgSteer* s) { fAlgSteer = s; } FIXME(milettri): needs AliAlgSteer AliAlgSens* GetSensor(Int_t id) const { return (AliAlgSens*)fSensors.UncheckedAt(id); } AliAlgSens* GetSensorByVolId(Int_t vid) const { @@ -105,13 +105,13 @@ class AliAlgDet : public TNamed virtual void DefineVolumes(); virtual void DefineMatrices(); virtual void Print(const Option_t* opt = "") const; - virtual Int_t ProcessPoints(const AliESDtrack* esdTr, AliAlgTrack* algTrack, Bool_t inv = kFALSE); - virtual void UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const; + // virtual Int_t ProcessPoints(const AliESDtrack* esdTr, AliAlgTrack* algTrack, Bool_t inv = kFALSE); FIXME(milettri): needs AliESDtrack + virtual void UpdatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) const; virtual void SetUseErrorParam(Int_t v = 0); Int_t GetUseErrorParam() const { return fUseErrorParam; } // - virtual Bool_t AcceptTrack(const AliESDtrack* trc, Int_t trtype) const = 0; - Bool_t CheckFlags(const AliESDtrack* trc, Int_t trtype) const; + // virtual Bool_t AcceptTrack(const AliESDtrack* trc, Int_t trtype) const = 0; FIXME(milettri): needs AliESDtrack + // Bool_t CheckFlags(const AliESDtrack* trc, Int_t trtype) const; FIXME(milettri): needs AliESDtrack // virtual AliAlgPoint* GetPointFromPool(); virtual void ResetPool(); @@ -233,17 +233,18 @@ class AliAlgDet : public TNamed Int_t fPoolFreePointID; //! id of the last free point in the pool TObjArray fPointsPool; //! pool of aligment points // - AliAlgSteer* fAlgSteer; // pointer to alignment steering object + // AliAlgSteer* fAlgSteer; // pointer to alignment steering object FIXME(milettri): needs AliAlgSteer // ClassDef(AliAlgDet, 1); // base class for detector global alignment }; -//_____________________________________________________ -inline Bool_t AliAlgDet::CheckFlags(const AliESDtrack* trc, Int_t trtype) const -{ - // check if flags are ok - return (trc->GetStatus() & fTrackFlagSel[trtype]) == fTrackFlagSel[trtype]; -} +//FIXME(milettri): needs AliESDtrack +////_____________________________________________________ +//inline Bool_t AliAlgDet::CheckFlags(const AliESDtrack* trc, Int_t trtype) const +//{ +// // check if flags are ok +// return (trc->GetStatus() & fTrackFlagSel[trtype]) == fTrackFlagSel[trtype]; +//} } // namespace align } // namespace o2 #endif diff --git a/Detectors/Align/include/Align/AliAlgSens.h b/Detectors/Align/include/Align/AliAlgSens.h index 35dbd117053fd..918147dd46347 100644 --- a/Detectors/Align/include/Align/AliAlgSens.h +++ b/Detectors/Align/include/Align/AliAlgSens.h @@ -20,10 +20,8 @@ #include #include "Align/AliAlgVol.h" -//#include "Align/AliAlgDet.h" FIXME(milettri) needs AliAlgDet; -#include "Align/AliAlgPoint.h" #include "Align/AliAlgDOFStat.h" -#include "ReconstructionDataFormats/Track.h" +#include "Align/AliAlgAux.h" //class AliTrackPointArray; //class AliESDtrack; @@ -34,6 +32,9 @@ namespace o2 namespace align { +class AliAlgDet; +class AliAlgPoint; + class AliAlgSens : public AliAlgVol { public: @@ -43,8 +44,8 @@ class AliAlgSens : public AliAlgVol // virtual void AddChild(AliAlgVol*); // - // void SetDetector(AliAlgDet* det) { fDet = det; } FIXME(milettri) needs AliAlgDet; - // AliAlgDet* GetDetector() const { return fDet; } FIXME(milettri) needs AliAlgDet; + void SetDetector(AliAlgDet* det) { fDet = det; } + AliAlgDet* GetDetector() const { return fDet; } // Int_t GetSID() const { return fSID; } void SetSID(int s) { fSID = s; } @@ -105,7 +106,7 @@ class AliAlgSens : public AliAlgVol // Int_t fSID; // sensor id in detector Double_t fAddError[2]; // additional error increment for measurement - // AliAlgDet* fDet; // pointer on detector FIXME(milettri) needs AliAlgDet; + AliAlgDet* fDet; // pointer on detector TGeoHMatrix fMatClAlg; // reference cluster alignment matrix in tracking frame TGeoHMatrix fMatClAlgReco; // reco-time cluster alignment matrix in tracking frame diff --git a/Detectors/Align/src/AliAlgDet.cxx b/Detectors/Align/src/AliAlgDet.cxx index e29db8b33fb41..b9bfcfc2099f3 100644 --- a/Detectors/Align/src/AliAlgDet.cxx +++ b/Detectors/Align/src/AliAlgDet.cxx @@ -16,8 +16,8 @@ #include "Align/AliAlgDet.h" #include "Align/AliAlgSens.h" #include "Align/AliAlgDet.h" -#include "Align/AliAlgSteer.h" -#include "Align/AliAlgTrack.h" +//#include "Align/AliAlgSteer.h" FIXME(milettri): needs AliAlgSteer +//#include "Align/AliAlgTrack.h" FIXME(milettri): needs AliAlgTrack #include "Align/AliAlgDOFStat.h" #include "Align/AliAlgConstraint.h" #include "Framework/Logger.h" @@ -66,11 +66,12 @@ AliAlgDet::AliAlgDet() fNPoints(0), fPoolNPoints(0), fPoolFreePointID(0), - fPointsPool(), - fAlgSteer(0) + fPointsPool() //, +// fAlgSteer(0) FIXME(milettri): needs AliAlgSteer { // def c-tor - SetUniqueID(AliAlgSteer::kUndefined); // derived detectors must override this + // SetUniqueID(AliAlgSteer::kUndefined); // derived detectors must override this FIXME(milettri): needs AliAlgSteer; + SetUniqueID(6); fAddError[0] = fAddError[1] = 0; // for (int i = 0; i < kNTrackTypes; i++) { @@ -91,36 +92,37 @@ AliAlgDet::~AliAlgDet() fPointsPool.Delete(); } -//____________________________________________ -Int_t AliAlgDet::ProcessPoints(const AliESDtrack* esdTr, AliAlgTrack* algTrack, Bool_t inv) -{ - // Extract the points corresponding to this detector, recalibrate/realign them to the - // level of the "starting point" for the alignment/calibration session. - // If inv==true, the track propagates in direction of decreasing tracking X - // (i.e. upper leg of cosmic track) - // - const AliESDfriendTrack* trF(esdTr->GetFriendTrack()); - const AliTrackPointArray* trP(trF->GetTrackPointArray()); - // - int np(trP->GetNPoints()); - int npSel(0); - AliAlgPoint* apnt(0); - for (int ip = 0; ip < np; ip++) { - int vid = trP->GetVolumeID()[ip]; - if (!SensorOfDetector(vid)) - continue; - apnt = GetSensorByVolId(vid)->TrackPoint2AlgPoint(ip, trP, esdTr); - if (!apnt) - continue; - algTrack->AddPoint(apnt); - if (inv) - apnt->SetInvDir(); - npSel++; - fNPoints++; - } - // - return npSel; -} +//FIXME(milettri): needs AliESDtrack +////____________________________________________ +//Int_t AliAlgDet::ProcessPoints(const AliESDtrack* esdTr, AliAlgTrack* algTrack, Bool_t inv) +//{ +// // Extract the points corresponding to this detector, recalibrate/realign them to the +// // level of the "starting point" for the alignment/calibration session. +// // If inv==true, the track propagates in direction of decreasing tracking X +// // (i.e. upper leg of cosmic track) +// // +// const AliESDfriendTrack* trF(esdTr->GetFriendTrack()); +// const AliTrackPointArray* trP(trF->GetTrackPointArray()); +// // +// int np(trP->GetNPoints()); +// int npSel(0); +// AliAlgPoint* apnt(0); +// for (int ip = 0; ip < np; ip++) { +// int vid = trP->GetVolumeID()[ip]; +// if (!SensorOfDetector(vid)) +// continue; +// apnt = GetSensorByVolId(vid)->TrackPoint2AlgPoint(ip, trP, esdTr); +// if (!apnt) +// continue; +// algTrack->AddPoint(apnt); +// if (inv) +// apnt->SetInvDir(); +// npSel++; +// fNPoints++; +// } +// // +// return npSel; +//} //_________________________________________________________ void AliAlgDet::AcknowledgeNewRun(Int_t run) @@ -134,27 +136,29 @@ void AliAlgDet::AcknowledgeNewRun(Int_t run) //_________________________________________________________ void AliAlgDet::UpdateL2GRecoMatrices() { - // Update L2G matrices used for data reconstruction - // - AliCDBManager* man = AliCDBManager::Instance(); - AliCDBEntry* ent = man->Get(Form("%s/Align/Data", GetName())); - const TClonesArray* algArr = (const TClonesArray*)ent->GetObject(); - // - int nvol = GetNVolumes(); - for (int iv = 0; iv < nvol; iv++) { - AliAlgVol* vol = GetVolume(iv); - // call init for root level volumes, they will take care of their children - if (!vol->GetParent()) - vol->UpdateL2GRecoMatrices(algArr, 0); - } - // + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + //FIXME(milettri): needs OCDB + // // Update L2G matrices used for data reconstruction + // // + // AliCDBManager* man = AliCDBManager::Instance(); + // AliCDBEntry* ent = man->Get(Form("%s/Align/Data", GetName())); + // const TClonesArray* algArr = (const TClonesArray*)ent->GetObject(); + // // + // int nvol = GetNVolumes(); + // for (int iv = 0; iv < nvol; iv++) { + // AliAlgVol* vol = GetVolume(iv); + // // call init for root level volumes, they will take care of their children + // if (!vol->GetParent()) + // vol->UpdateL2GRecoMatrices(algArr, 0); + // } + // // } //_________________________________________________________ void AliAlgDet::ApplyAlignmentFromMPSol() { // apply alignment from millepede solution array to reference alignment level - AliInfo("Applying alignment from Millepede solution"); + LOG(INFO) << "Applying alignment from Millepede solution"; for (int isn = GetNSensors(); isn--;) GetSensor(isn)->ApplyAlignmentFromMPSol(); } @@ -162,23 +166,25 @@ void AliAlgDet::ApplyAlignmentFromMPSol() //_________________________________________________________ void AliAlgDet::CacheReferenceOCDB() { - // if necessary, detector may fetch here some reference OCDB data - // - // cache global deltas to avoid preicision problem - AliCDBManager* man = AliCDBManager::Instance(); - AliCDBEntry* ent = man->Get(Form("%s/Align/Data", GetName())); - TObjArray* arr = (TObjArray*)ent->GetObject(); - for (int i = arr->GetEntriesFast(); i--;) { - const AliAlignObjParams* par = (const AliAlignObjParams*)arr->At(i); - AliAlgVol* vol = GetVolume(par->GetSymName()); - if (!vol) { - AliErrorF("Volume %s not found", par->GetSymName()); - continue; - } - TGeoHMatrix delta; - par->GetMatrix(delta); - vol->SetGlobalDeltaRef(delta); - } + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + //FIXME(milettri): needs OCDB + // // if necessary, detector may fetch here some reference OCDB data + // // + // // cache global deltas to avoid preicision problem + // AliCDBManager* man = AliCDBManager::Instance(); + // AliCDBEntry* ent = man->Get(Form("%s/Align/Data", GetName())); + // TObjArray* arr = (TObjArray*)ent->GetObject(); + // for (int i = arr->GetEntriesFast(); i--;) { + // const AliAlignObjParams* par = (const AliAlignObjParams*)arr->At(i); + // AliAlgVol* vol = GetVolume(par->GetSymName()); + // if (!vol) { + // AliErrorF("Volume %s not found", par->GetSymName()); + // continue; + // } + // TGeoHMatrix delta; + // par->GetMatrix(delta); + // vol->SetGlobalDeltaRef(delta); + // } } //_________________________________________________________ @@ -209,7 +215,7 @@ void AliAlgDet::ResetPool() void AliAlgDet::DefineVolumes() { // dummy method - AliError("This method must be implemented by specific detector"); + LOG(ERROR) << "This method must be implemented by specific detector"; } //_________________________________________________________ @@ -217,7 +223,7 @@ void AliAlgDet::AddVolume(AliAlgVol* vol) { // add volume if (GetVolume(vol->GetSymName())) { - AliFatalF("Volume %s was already added to %s", vol->GetName(), GetName()); + LOG(FATAL) << "Volume " << vol->GetName() << " was already added to " << GetName(); } fVolumes.AddLast(vol); if (vol->IsSensor()) { @@ -268,7 +274,7 @@ void AliAlgDet::SortSensors() // build local tables for internal numbering fNSensors = fSensors.GetEntriesFast(); if (!fNSensors) { - AliWarning("No sensors defined"); + LOG(WARNING) << "No sensors defined"; return; } fSensors.Sort(); @@ -307,36 +313,34 @@ Int_t AliAlgDet::InitGeom() //_________________________________________________________ Int_t AliAlgDet::AssignDOFs() { - // assign DOFs IDs, parameters - // - int gloCount0(fAlgSteer->GetNDOFs()), gloCount(fAlgSteer->GetNDOFs()); - Float_t* pars = fAlgSteer->GetGloParVal(); - Float_t* errs = fAlgSteer->GetGloParErr(); - Int_t* labs = fAlgSteer->GetGloParLab(); - // - // assign calibration DOFs - fFirstParGloID = gloCount; - fParVals = pars + gloCount; - fParErrs = errs + gloCount; - fParLabs = labs + gloCount; - for (int icl = 0; icl < fNCalibDOF; icl++) { - fParLabs[icl] = (GetDetLabel() + 10000) * 100 + icl; - gloCount++; - } - // - int nvol = GetNVolumes(); - for (int iv = 0; iv < nvol; iv++) { - AliAlgVol* vol = GetVolume(iv); - // call init for root level volumes, they will take care of their children - if (!vol->GetParent()) - vol->AssignDOFs(gloCount, pars, errs, labs); - } - // - - if (fNDOFs != gloCount - gloCount0) - AliFatalF("Mismatch between declared %d and initialized %d DOFs for %s", - fNDOFs, gloCount - gloCount0, GetName()); - + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + //FIXME(milettri): needs AliAlgSteer + // // assign DOFs IDs, parameters + // // + // int gloCount0(fAlgSteer->GetNDOFs()), gloCount(fAlgSteer->GetNDOFs()); + // Float_t* pars = fAlgSteer->GetGloParVal(); + // Float_t* errs = fAlgSteer->GetGloParErr(); + // Int_t* labs = fAlgSteer->GetGloParLab(); + // // + // // assign calibration DOFs + // fFirstParGloID = gloCount; + // fParVals = pars + gloCount; + // fParErrs = errs + gloCount; + // fParLabs = labs + gloCount; + // for (int icl = 0; icl < fNCalibDOF; icl++) { + // fParLabs[icl] = (GetDetLabel() + 10000) * 100 + icl; + // gloCount++; + // } + // // + // int nvol = GetNVolumes(); + // for (int iv = 0; iv < nvol; iv++) { + // AliAlgVol* vol = GetVolume(iv); + // // call init for root level volumes, they will take care of their children + // if (!vol->GetParent()) + // vol->AssignDOFs(gloCount, pars, errs, labs); + // } + // if (fNDOFs != gloCount - gloCount0) + // LOG(FATAL) << "Mismatch between declared " << fNDOFs << " and initialized " << (gloCount - gloCount0) << " DOFs for " << GetName(); return fNDOFs; } @@ -345,7 +349,7 @@ void AliAlgDet::InitDOFs() { // initialize free parameters if (GetInitDOFsDone()) - AliFatalF("Something is wrong, DOFs are already initialized for %s", GetName()); + LOG(FATAL) << "DOFs are already initialized for " << GetName(); // // process calibration DOFs for (int i = 0; i < fNCalibDOF; i++) @@ -420,9 +424,11 @@ void AliAlgDet::Print(const Option_t* opt) const void AliAlgDet::SetDetID(UInt_t tp) { // assign type - if (tp >= AliAlgSteer::kNDetectors) - AliFatalF("Detector typeID %d exceeds allowed range %d:%d", - tp, 0, AliAlgSteer::kNDetectors - 1); + //FIXME(milettri): needs AliAlgSteer + // if (tp >= AliAlgSteer::kNDetectors) + // LOG(FATAL) << "Detector typeID " << tp << "exceeds allowed range" << 0 << ":" << (AliAlgSteer::kNDetectors - 1); + if (tp >= 5) + LOG(FATAL) << "Detector typeID " << tp << "exceeds allowed range" << 0 << ":" << (5 - 1); SetUniqueID(tp); } @@ -430,7 +436,7 @@ void AliAlgDet::SetDetID(UInt_t tp) void AliAlgDet::SetAddError(double sigy, double sigz) { // add syst error to all sensors - AliInfoF("Adding sys.error %.4e %.4e to all sensors", sigy, sigz); + LOG(INFO) << "Adding sys.error " << std::fixed << std::setprecision(4) << sigy << " " << sigz << " to all sensors"; fAddError[0] = sigy; fAddError[1] = sigz; for (int isn = GetNSensors(); isn--;) @@ -442,23 +448,25 @@ void AliAlgDet::SetAddError(double sigy, double sigz) void AliAlgDet::SetUseErrorParam(Int_t v) { // set type of points error parameterization - AliFatal("UpdatePointByTrackInfo is not implemented for this detector"); + LOG(FATAL) << "UpdatePointByTrackInfo is not implemented for this detector"; // } //____________________________________________ -void AliAlgDet::UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const +void AliAlgDet::UpdatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) const { // update point using specific error parameterization - AliFatal("If needed, this method has to be implemented for specific detector"); + LOG(FATAL) << "If needed, this method has to be implemented for specific detector"; } //____________________________________________ void AliAlgDet::SetObligatory(Int_t tp, Bool_t v) { - // mark detector presence obligatory in the track - fObligatory[tp] = v; - fAlgSteer->SetObligatoryDetector(GetDetID(), tp, v); + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + //FIXME(lettrich): needs AliAlgSteer + // // mark detector presence obligatory in the track + // fObligatory[tp] = v; + // fAlgSteer->SetObligatoryDetector(GetDetID(), tp, v); } //______________________________________________________ @@ -489,26 +497,28 @@ void AliAlgDet::WriteCalibrationResults() const //______________________________________________________ void AliAlgDet::WriteAlignmentResults() const { - // store updated alignment - TClonesArray* arr = new TClonesArray("AliAlignObjParams", 10); - // - int nvol = GetNVolumes(); - for (int iv = 0; iv < nvol; iv++) { - AliAlgVol* vol = GetVolume(iv); - // call only for top level objects, they will take care of children - if (!vol->GetParent()) - vol->CreateAlignmentObjects(arr); - } - // - AliCDBManager* man = AliCDBManager::Instance(); - AliCDBMetaData* md = new AliCDBMetaData(); - md->SetResponsible(fAlgSteer->GetOutCDBResponsible()); - md->SetComment(fAlgSteer->GetOutCDBResponsible()); - // - AliCDBId id(Form("%s/Align/Data", GetName()), fAlgSteer->GetOutCDBRunMin(), fAlgSteer->GetOutCDBRunMax()); - man->Put(arr, id, md); - // - delete arr; + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + //FIXME(lettrich): needs OCDB + // // store updated alignment + // TClonesArray* arr = new TClonesArray("AliAlignObjParams", 10); + // // + // int nvol = GetNVolumes(); + // for (int iv = 0; iv < nvol; iv++) { + // AliAlgVol* vol = GetVolume(iv); + // // call only for top level objects, they will take care of children + // if (!vol->GetParent()) + // vol->CreateAlignmentObjects(arr); + // } + // // + // AliCDBManager* man = AliCDBManager::Instance(); + // AliCDBMetaData* md = new AliCDBMetaData(); + // md->SetResponsible(fAlgSteer->GetOutCDBResponsible()); + // md->SetComment(fAlgSteer->GetOutCDBResponsible()); + // // + // AliCDBId id(Form("%s/Align/Data", GetName()), fAlgSteer->GetOutCDBRunMin(), fAlgSteer->GetOutCDBRunMax()); + // man->Put(arr, id, md); + // // + // delete arr; } //______________________________________________________ @@ -544,30 +554,34 @@ AliAlgVol* AliAlgDet::GetVolOfDOFID(Int_t id) const //______________________________________________________ void AliAlgDet::Terminate() { - // called at the end of processing - // if (IsDisabled()) return; - int nvol = GetNVolumes(); - fNProcPoints = 0; - AliAlgDOFStat* st = fAlgSteer->GetDOFStat(); - for (int iv = 0; iv < nvol; iv++) { - AliAlgVol* vol = GetVolume(iv); - // call init for root level volumes, they will take care of their children - if (!vol->GetParent()) - fNProcPoints += vol->FinalizeStat(st); - } - FillDOFStat(st); // fill stat for calib dofs + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + //FIXME(lettrich): needs AliAlgSteer + // // called at the end of processing + // // if (IsDisabled()) return; + // int nvol = GetNVolumes(); + // fNProcPoints = 0; + // AliAlgDOFStat* st = fAlgSteer->GetDOFStat(); + // for (int iv = 0; iv < nvol; iv++) { + // AliAlgVol* vol = GetVolume(iv); + // // call init for root level volumes, they will take care of their children + // if (!vol->GetParent()) + // fNProcPoints += vol->FinalizeStat(st); + // } + // FillDOFStat(st); // fill stat for calib dofs } //________________________________________ void AliAlgDet::AddAutoConstraints() const { - // adds automatic constraints - int nvol = GetNVolumes(); - for (int iv = 0; iv < nvol; iv++) { // call for root level volumes, they will take care of their children - AliAlgVol* vol = GetVolume(iv); - if (!vol->GetParent()) - vol->AddAutoConstraints((TObjArray*)fAlgSteer->GetConstraints()); - } + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + //FIXME(lettrich): needs AliAlgSteer + // // adds automatic constraints + // int nvol = GetNVolumes(); + // for (int iv = 0; iv < nvol; iv++) { // call for root level volumes, they will take care of their children + // AliAlgVol* vol = GetVolume(iv); + // if (!vol->GetParent()) + // vol->AddAutoConstraints((TObjArray*)fAlgSteer->GetConstraints()); + //} } //________________________________________ @@ -673,10 +687,13 @@ void AliAlgDet::ConstrainOrphans(const double* sigma, const char* match) } // if (!constr->GetNChildren()) { - AliInfoF("No volume passed filter %s", match); + LOG(INFO) << "No volume passed filter " << match; delete constr; - } else - ((TObjArray*)fAlgSteer->GetConstraints())->Add(constr); + } else { + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + //FIXME(lettrich): needs AliAlgSteer + // ((TObjArray*)fAlgSteer->GetConstraints())->Add(constr); + } // } @@ -685,7 +702,7 @@ void AliAlgDet::SetFreeDOF(Int_t dof) { // set detector free dof if (dof >= kNMaxKalibDOF) { - AliFatalF("Detector CalibDOFs limited to %d, requested %d", kNMaxKalibDOF, dof); + LOG(FATAL) << "Detector CalibDOFs limited to " << kNMaxKalibDOF << ", requested " << dof; } fCalibDOF |= 0x1 << dof; CalcFree(); @@ -696,7 +713,7 @@ void AliAlgDet::FixDOF(Int_t dof) { // fix detector dof if (dof >= kNMaxKalibDOF) { - AliFatalF("Detector CalibDOFs limited to %d, requested %d", kNMaxKalibDOF, dof); + LOG(FATAL) << "Detector CalibDOFs limited to " << kNMaxKalibDOF << ", requested " << dof; } fCalibDOF &= ~(0x1 << dof); CalcFree(); diff --git a/Detectors/Align/src/AliAlgSens.cxx b/Detectors/Align/src/AliAlgSens.cxx index d930360723e20..d1d1df4e19b9c 100644 --- a/Detectors/Align/src/AliAlgSens.cxx +++ b/Detectors/Align/src/AliAlgSens.cxx @@ -18,6 +18,8 @@ #include "Align/AliAlgSens.h" #include "Framework/Logger.h" +#include "Align/AliAlgPoint.h" +#include "Align/AliAlgDet.h" //#include "AliGeomManager.h" ClassImp(o2::align::AliAlgSens); @@ -32,7 +34,7 @@ namespace align //_________________________________________________________ AliAlgSens::AliAlgSens(const char* name, Int_t vid, Int_t iid) - : AliAlgVol(name, iid), fSID(0), /*fDet(0), */ fMatClAlg(), fMatClAlgReco() // FIXME(milettri): needs AliAlgDet + : AliAlgVol(name, iid), fSID(0), fDet(0), fMatClAlg(), fMatClAlgReco() { // def c-tor SetVolID(vid); @@ -398,10 +400,8 @@ void AliAlgSens::PrepareMatrixClAlgReco() //____________________________________________ void AliAlgSens::UpdatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) const { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; - // FIXME(milettri) needs AliAlgDet; - // // update - // fDet->UpdatePointByTrackInfo(pnt, t); + // update + fDet->UpdatePointByTrackInfo(pnt, t); } //____________________________________________ diff --git a/Detectors/Align/src/AlignLinkDef.h b/Detectors/Align/src/AlignLinkDef.h index af4a2d6c74ccc..819f5e5b94d88 100644 --- a/Detectors/Align/src/AlignLinkDef.h +++ b/Detectors/Align/src/AlignLinkDef.h @@ -4,7 +4,7 @@ #pragma link off all classes; #pragma link off all functions; -//#pragma link C++ class o2::align::AliAlgDet + ; +#pragma link C++ class o2::align::AliAlgDet + ; //#pragma link C++ class o2::align::AliAlgDetITS + ; //#pragma link C++ class o2::align::AliAlgDetTOF + ; //#pragma link C++ class o2::align::AliAlgDetTPC + ; From aa04b7a48a550739cf3984381d6f2b6ff7095c68 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Wed, 7 Apr 2021 22:39:47 +0200 Subject: [PATCH 202/770] [ALIGN] port AliAlgTrack --- Detectors/Align/CMakeLists.txt | 4 +- Detectors/Align/include/Align/AliAlgDet.h | 2 +- Detectors/Align/include/Align/AliAlgTrack.h | 110 +-- Detectors/Align/src/AliAlgDet.cxx | 2 +- Detectors/Align/src/AliAlgTrack.cxx | 752 ++++++++++---------- Detectors/Align/src/AlignLinkDef.h | 2 +- 6 files changed, 451 insertions(+), 421 deletions(-) diff --git a/Detectors/Align/CMakeLists.txt b/Detectors/Align/CMakeLists.txt index 3479529bd3a83..5cdd7b87f4411 100644 --- a/Detectors/Align/CMakeLists.txt +++ b/Detectors/Align/CMakeLists.txt @@ -29,7 +29,7 @@ o2_add_library(Align #src/AliAlgSensTPC.cxx #src/AliAlgSensTRD.cxx #src/AliAlgSteer.cxx - #src/AliAlgTrack.cxx + src/AliAlgTrack.cxx src/AliAlgVol.cxx #src/AliAlgVtx.cxx #src/Mille.cxx @@ -62,7 +62,7 @@ o2_target_root_dictionary( #include/Align/AliAlgSensTRD.h #include/Align/AliAlgSensHMPID.h #include/Align/AliAlgSteer.h - #include/Align/AliAlgTrack.h + include/Align/AliAlgTrack.h include/Align/AliAlgVol.h #include/Align/AliAlgVtx.h #include/Align/AliAlgRes.h diff --git a/Detectors/Align/include/Align/AliAlgDet.h b/Detectors/Align/include/Align/AliAlgDet.h index a521649325790..ec740b52ee1b1 100644 --- a/Detectors/Align/include/Align/AliAlgDet.h +++ b/Detectors/Align/include/Align/AliAlgDet.h @@ -20,7 +20,7 @@ #include #include #include "Align/AliAlgAux.h" -//#include "Align/AliAlgTrack.h" FIXME(milettri): needs AliAlgTrack +#include "Align/AliAlgTrack.h" #include "Align/AliAlgDOFStat.h" #include "Align/AliAlgPoint.h" #include "Align/AliAlgSens.h" diff --git a/Detectors/Align/include/Align/AliAlgTrack.h b/Detectors/Align/include/Align/AliAlgTrack.h index 9ec676fbd960f..d3426dffbd4e6 100644 --- a/Detectors/Align/include/Align/AliAlgTrack.h +++ b/Detectors/Align/include/Align/AliAlgTrack.h @@ -14,7 +14,7 @@ /// @brief Track model for the alignment /** - * Track model for the alignment: AliExternalTrackParam for kinematics + * Track model for the alignment: trackParam_t for kinematics * proper with number of multiple scattering kinks. * Full support for derivatives and residuals calculation */ @@ -22,8 +22,8 @@ #ifndef ALIALGTRACK_H #define ALIALGTRACK_H -//#include "AliExternalTrackParam.h" #include "Align/AliAlgPoint.h" +#include "ReconstructionDataFormats/Track.h" #include #include #include @@ -33,7 +33,9 @@ namespace o2 namespace align { -class AliAlgTrack : public AliExternalTrackParam +using trackParam_t = o2::track::TrackParametrizationWithError; + +class AliAlgTrack : public trackParam_t, public TObject { public: enum { kCosmicBit = BIT(14), @@ -71,10 +73,10 @@ class AliAlgTrack : public AliExternalTrackParam virtual void Print(Option_t* opt = "") const; virtual void DumpCoordinates() const; // - Bool_t PropagateToPoint(AliExternalTrackParam& tr, const AliAlgPoint* pnt, + Bool_t PropagateToPoint(trackParam_t& tr, const AliAlgPoint* pnt, int minNSteps, double maxStep, Bool_t matCor, double* matPar = 0); - Bool_t PropagateParamToPoint(AliExternalTrackParam& tr, const AliAlgPoint* pnt, double maxStep = 3); // param only - Bool_t PropagateParamToPoint(AliExternalTrackParam* trSet, int nTr, const AliAlgPoint* pnt, double maxStep = 3); // params only + Bool_t PropagateParamToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep = 3); // param only + Bool_t PropagateParamToPoint(trackParam_t* trSet, int nTr, const AliAlgPoint* pnt, double maxStep = 3); // params only // Bool_t CalcResiduals(const double* params = 0); Bool_t CalcResidDeriv(double* params = 0); @@ -95,7 +97,7 @@ class AliAlgTrack : public AliExternalTrackParam Bool_t IniFit(); Bool_t ResidKalman(); Bool_t ProcessMaterials(); - Bool_t CombineTracks(AliExternalTrackParam& trcL, const AliExternalTrackParam& trcU); + Bool_t CombineTracks(trackParam_t& trcL, const trackParam_t& trcU); // void SetChi2(double c) { fChi2 = c; }; Double_t GetChi2() const { return fChi2; } @@ -104,26 +106,26 @@ class AliAlgTrack : public AliExternalTrackParam Double_t GetChi2CosmUp() const { return fChi2CosmUp; } Double_t GetChi2CosmDn() const { return fChi2CosmDn; } // - void ImposePtBOff(double pt) { fP[kParQ2Pt] = 1. / pt; } + void ImposePtBOff(double pt) { setQ2Pt(1. / pt); } // propagation methods - void CopyFrom(const AliExternalTrackParam* etp); - Bool_t ApplyMatCorr(AliExternalTrackParam& trPar, const Double_t* corrDiag, const AliAlgPoint* pnt); - Bool_t ApplyMatCorr(AliExternalTrackParam* trSet, int ntr, const Double_t* corrDiaf, const AliAlgPoint* pnt); - Bool_t ApplyMatCorr(AliExternalTrackParam& trPar, const Double_t* corrpar); + void CopyFrom(const trackParam_t* etp); + Bool_t ApplyMatCorr(trackParam_t& trPar, const Double_t* corrDiag, const AliAlgPoint* pnt); + Bool_t ApplyMatCorr(trackParam_t* trSet, int ntr, const Double_t* corrDiaf, const AliAlgPoint* pnt); + Bool_t ApplyMatCorr(trackParam_t& trPar, const Double_t* corrpar); // Double_t GetResidual(int dim, int pntID) const { return fResidA[dim][pntID]; } Double_t* GetDResDLoc(int dim, int pntID) const { return &fDResDLocA[dim][pntID * fNLocPar]; } Double_t* GetDResDGlo(int dim, int id) const { return &fDResDGloA[dim][id]; } Int_t* GetGloParID() const { return fGloParIDA; } // - void SetParams(AliExternalTrackParam& tr, double x, double alp, const double* par, Bool_t add); - void SetParams(AliExternalTrackParam* trSet, int ntr, double x, double alp, const double* par, Bool_t add); - void SetParam(AliExternalTrackParam& tr, int par, double val); - void SetParam(AliExternalTrackParam* trSet, int ntr, int par, double val); - void ModParam(AliExternalTrackParam& tr, int par, double delta); - void ModParam(AliExternalTrackParam* trSet, int ntr, int par, double delta); + void SetParams(trackParam_t& tr, double x, double alp, const double* par, Bool_t add); + void SetParams(trackParam_t* trSet, int ntr, double x, double alp, const double* par, Bool_t add); + void SetParam(trackParam_t& tr, int par, double val); + void SetParam(trackParam_t* trSet, int ntr, int par, double val); + void ModParam(trackParam_t& tr, int par, double delta); + void ModParam(trackParam_t* trSet, int ntr, int par, double delta); // - void RichardsonDeriv(const AliExternalTrackParam* trSet, const double* delta, + void RichardsonDeriv(const trackParam_t* trSet, const double* delta, const AliAlgPoint* pnt, double& derY, double& derZ); // const Double_t* GetLocPars() const { return fLocParA; } @@ -133,8 +135,8 @@ class AliAlgTrack : public AliExternalTrackParam // Bool_t CalcResidDeriv(double* params, Bool_t invert, int pFrom, int pTo); Bool_t CalcResiduals(const double* params, Bool_t invert, int pFrom, int pTo); - Bool_t FitLeg(AliExternalTrackParam& trc, int pFrom, int pTo, Bool_t& inv); - Bool_t ProcessMaterials(AliExternalTrackParam& trc, int pFrom, int pTo); + Bool_t FitLeg(trackParam_t& trc, int pFrom, int pTo, Bool_t& inv); + Bool_t ProcessMaterials(trackParam_t& trc, int pFrom, int pTo); // void CheckExpandDerGloBuffer(int minSize); // @@ -146,7 +148,7 @@ class AliAlgTrack : public AliExternalTrackParam AliAlgTrack& operator=(const AliAlgTrack&); // protected: - // + //trackParam_t Int_t fNLocPar; // number of local params Int_t fNLocExtPar; // number of local params for the external track param Int_t fNGloPar; // number of free global parameters the track depends on @@ -175,23 +177,34 @@ class AliAlgTrack : public AliExternalTrackParam }; //____________________________________________________________________________________________ -inline void AliAlgTrack::SetParams(AliExternalTrackParam& tr, double x, double alp, const double* par, Bool_t add) +inline void AliAlgTrack::SetParams(trackParam_t& tr, double x, double alp, const double* par, Bool_t add) { // set track params - const float kDefQ2PtCosm = 1., kDefG2PtColl = 1. / 0.6; - tr.SetParamOnly(x, alp, par); - double* parTr = (double*)tr.GetParameter(); + const double kDefQ2PtCosm = 1; + const double kDefG2PtColl = 1. / 0.6; + params_t tmp; + std::copy(par, par + kNKinParBON, std::begin(tmp)); + tr.set(x, alp, tmp); if (add) { // par is correction to reference params - for (int i = kNKinParBON; i--;) - parTr[i] += GetParameter()[i]; + for (size_t i = 0; i < kNKinParBON; ++i) { + const double val = tr.getParam(i) + this->getParam(i); + tr.setParam(val, i); + } + } + if (!GetFieldON()) { + const double val = [&]() { + if (this->IsCosmic()) { + return kDefQ2PtCosm; + } else { + return kDefG2PtColl; + } + }(); + tr.setQ2Pt(val); // only 4 params are valid } - if (!GetFieldON()) - parTr[4] = IsCosmic() ? kDefQ2PtCosm : kDefG2PtColl; // only 4 params are valid - // } //____________________________________________________________________________________________ -inline void AliAlgTrack::SetParams(AliExternalTrackParam* trSet, int ntr, double x, double alp, const double* par, Bool_t add) +inline void AliAlgTrack::SetParams(trackParam_t* trSet, int ntr, double x, double alp, const double* par, Bool_t add) { // set parames for multiple tracks (VECTORIZE THIS) if (!add) { // full parameter supplied @@ -199,48 +212,51 @@ inline void AliAlgTrack::SetParams(AliExternalTrackParam* trSet, int ntr, double SetParams(trSet[itr], x, alp, par, kFALSE); return; } - double partr[kNKinParBON] = {0}; // par is a correction to reference parameter + params_t partr{0}; // par is a correction to reference parameter for (int i = fNLocExtPar; i--;) - partr[i] = GetParameter()[i] + par[i]; + partr[i] = getParam(i) + par[i]; for (int itr = ntr; itr--;) - SetParams(trSet[itr], x, alp, partr, kFALSE); + SetParams(trSet[itr], x, alp, partr.data(), kFALSE); } //____________________________________________________________________________________________ -inline void AliAlgTrack::SetParam(AliExternalTrackParam& tr, int par, double val) +inline void AliAlgTrack::SetParam(trackParam_t& tr, int par, double val) { // set track parameter - ((double*)tr.GetParameter())[par] = val; + tr.setParam(val, par); } //____________________________________________________________________________________________ -inline void AliAlgTrack::SetParam(AliExternalTrackParam* trSet, int ntr, int par, double val) +inline void AliAlgTrack::SetParam(trackParam_t* trSet, int ntr, int par, double val) { // set parames for multiple tracks (VECTORIZE THIS) - for (int itr = ntr; itr--;) - ((double*)trSet[itr].GetParameter())[par] = val; + for (int i = 0; i < ntr; ++i) { + SetParam(trSet[i], par, val); + } } //____________________________________________________________________________________________ -inline void AliAlgTrack::ModParam(AliExternalTrackParam& tr, int par, double delta) +inline void AliAlgTrack::ModParam(trackParam_t& tr, int par, double delta) { // modify track parameter - ((double*)tr.GetParameter())[par] += delta; + const auto val = tr.getParam(par) + delta; + SetParam(tr, par, val); } //____________________________________________________________________________________________ -inline void AliAlgTrack::ModParam(AliExternalTrackParam* trSet, int ntr, int par, double delta) +inline void AliAlgTrack::ModParam(trackParam_t* trSet, int ntr, int par, double delta) { // modify track parameter (VECTORIZE THOS) - for (int itr = ntr; itr--;) - ModParam(trSet[itr], par, delta); + for (size_t i = 0; i < ntr; ++i) { + ModParam(trSet[i], par, delta); + } } //______________________________________________ -inline void AliAlgTrack::CopyFrom(const AliExternalTrackParam* etp) +inline void AliAlgTrack::CopyFrom(const trackParam_t* etp) { // assign kinematics - Set(etp->GetX(), etp->GetAlpha(), etp->GetParameter(), etp->GetCovariance()); + set(etp->getX(), etp->getAlpha(), etp->getParams(), etp->getCov().data()); } } // namespace align } // namespace o2 diff --git a/Detectors/Align/src/AliAlgDet.cxx b/Detectors/Align/src/AliAlgDet.cxx index b9bfcfc2099f3..6f2038a8ec129 100644 --- a/Detectors/Align/src/AliAlgDet.cxx +++ b/Detectors/Align/src/AliAlgDet.cxx @@ -17,7 +17,7 @@ #include "Align/AliAlgSens.h" #include "Align/AliAlgDet.h" //#include "Align/AliAlgSteer.h" FIXME(milettri): needs AliAlgSteer -//#include "Align/AliAlgTrack.h" FIXME(milettri): needs AliAlgTrack +#include "Align/AliAlgTrack.h" #include "Align/AliAlgDOFStat.h" #include "Align/AliAlgConstraint.h" #include "Framework/Logger.h" diff --git a/Detectors/Align/src/AliAlgTrack.cxx b/Detectors/Align/src/AliAlgTrack.cxx index 0fb8646a5e976..c2b51217e2c5d 100644 --- a/Detectors/Align/src/AliAlgTrack.cxx +++ b/Detectors/Align/src/AliAlgTrack.cxx @@ -40,7 +40,7 @@ const Int_t kRichardsonN = kRichardsonOrd + 1; // N of 2-point symmetric derivat const Int_t kNRDClones = kRichardsonN * 2; // number of variations for derivative of requested order //____________________________________________________________________________ -AliAlgTrack::AliAlgTrack() : fNLocPar(0), fNLocExtPar(0), fNGloPar(0), fNDF(0), fInnerPointID(0) +AliAlgTrack::AliAlgTrack() : TrackParametrizationWithError(), TObject(), fNLocPar(0), fNLocExtPar(0), fNGloPar(0), fNDF(0), fInnerPointID(0) // ,fMinX2X0Pt2Account(5/1.0) , fMinX2X0Pt2Account(0.5e-3 / 1.0), @@ -151,15 +151,15 @@ void AliAlgTrack::DefineDOFs() } //______________________________________________________ -Bool_t AliAlgTrack::CalcResidDeriv(double* params) +Bool_t AliAlgTrack::CalcResidDeriv(Double_t* params) { // Propagate for given local params and calculate residuals and their derivatives. - // The 1st 4 or 5 elements of params vector should be the reference AliExternalTrackParam + // The 1st 4 or 5 elements of params vector should be the reference trackParam_t // Then parameters of material corrections for each point // marked as having materials should come (4 or 5 dependending if ELoss is varied or fixed). // They correspond to kink parameters - // (AliExternalTrackParam_after_material - AliExternalTrackParam_before_material) - // rotated to frame where they error matrix is diagonal. Their conversion to AliExternalTrackParam + // (trackParam_t_after_material - trackParam_t_before_material) + // rotated to frame where they error matrix is diagonal. Their conversion to trackParam_t // increment will be done locally in the ApplyMatCorr routine. // // If params are not provided, use internal params array @@ -175,7 +175,7 @@ Bool_t AliAlgTrack::CalcResidDeriv(double* params) // collision track or cosmic lower leg if (!CalcResidDeriv(params, fNeedInv[0], GetInnerPointID(), 0)) { #if DEBUG > 3 - AliWarning("Failed on derivatives calculation 0"); + LOG(warn) << "Failed on derivatives calculation 0"; #endif return kFALSE; } @@ -183,7 +183,7 @@ Bool_t AliAlgTrack::CalcResidDeriv(double* params) if (IsCosmic()) { // cosmic upper leg if (!CalcResidDeriv(params, fNeedInv[1], GetInnerPointID() + 1, np - 1)) { #if DEBUG > 3 - AliWarning("Failed on derivatives calculation 0"); + LOG(warn) << "Failed on derivatives calculation 0"; #endif } } @@ -193,22 +193,22 @@ Bool_t AliAlgTrack::CalcResidDeriv(double* params) } //______________________________________________________ -Bool_t AliAlgTrack::CalcResidDeriv(double* params, Bool_t invert, int pFrom, int pTo) +Bool_t AliAlgTrack::CalcResidDeriv(double* extendedParams, Bool_t invert, int pFrom, int pTo) { // Calculate derivatives of residuals vs params for points pFrom to pT. For cosmic upper leg // track parameter may require inversion. - // The 1st 4 or 5 elements of params vector should be the reference AliExternalTrackParam + // The 1st 4 or 5 elements of params vector should be the reference trackParam_t // Then parameters of material corrections for each point // marked as having materials should come (4 or 5 dependending if ELoss is varied or fixed). // They correspond to kink parameters - // (AliExternalTrackParam_after_material - AliExternalTrackParam_before_material) - // rotated to frame where they error matrix is diagonal. Their conversion to AliExternalTrackParam + // (trackParam_t_after_material - trackParam_t_before_material) + // rotated to frame where they error matrix is diagonal. Their conversion to trackParam_t // increment will be done locally in the ApplyMatCorr routine. // // The derivatives are calculated using Richardson extrapolation // (like http://root.cern.ch/root/html/ROOT__Math__RichardsonDerivator.html) // - AliExternalTrackParam probD[kNRDClones]; // use this to vary supplied param for derivative calculation + trackParam_t probD[kNRDClones]; // use this to vary supplied param for derivative calculation double varDelta[kRichardsonN]; const int kInvElem[kNKinParBON] = {-1, 1, 1, -1, -1}; // @@ -218,7 +218,7 @@ Bool_t AliAlgTrack::CalcResidDeriv(double* params, Bool_t invert, int pFrom, int for (int i = kNKinParBOFF; i--;) delta[i] = kDelta[i]; if (GetFieldON()) - delta[kParQ2Pt] = kDelta[kParQ2Pt] * Abs(GetParameter()[kParQ2Pt]); + delta[kParQ2Pt] = kDelta[kParQ2Pt] * Abs(getQ2Pt()); // int pinc; if (pTo > pFrom) { // fit in points decreasing order: cosmics upper leg @@ -228,12 +228,14 @@ Bool_t AliAlgTrack::CalcResidDeriv(double* params, Bool_t invert, int pFrom, int pTo--; pinc = -1; } - // 1) derivative wrt AliExternalTrackParam parameters + + // 1) derivative wrt trackParam_t parameters for (int ipar = fNLocExtPar; ipar--;) { - SetParams(probD, kNRDClones, GetX(), GetAlpha(), params, kTRUE); + + SetParams(probD, kNRDClones, getX(), getAlpha(), extendedParams, kTRUE); if (invert) for (int ic = kNRDClones; ic--;) - probD[ic].Invert(); + probD[ic].invert(); double del = delta[ipar]; // for (int icl = 0; icl < kRichardsonN; icl++) { // calculate kRichardsonN variations with del, del/2, del/4... @@ -248,7 +250,7 @@ Bool_t AliAlgTrack::CalcResidDeriv(double* params, Bool_t invert, int pFrom, int if (!PropagateParamToPoint(probD, kNRDClones, pnt)) return kFALSE; // if (pnt->ContainsMaterial()) { // apply material corrections - if (!ApplyMatCorr(probD, kNRDClones, params, pnt)) + if (!ApplyMatCorr(probD, kNRDClones, extendedParams, pnt)) return kFALSE; // } // @@ -272,7 +274,7 @@ Bool_t AliAlgTrack::CalcResidDeriv(double* params, Bool_t invert, int pFrom, int if (pnt->ContainsMeasurement() && !CalcResidDerivGlo(pnt)) { #if DEBUG > 3 AliWarningF("Failed on global derivatives calculation at point %d", ip); - pnt->Print("meas"); + pnt->print("meas"); #endif return kFALSE; } @@ -282,13 +284,13 @@ Bool_t AliAlgTrack::CalcResidDeriv(double* params, Bool_t invert, int pFrom, int // int nParFreeI = pnt->GetNMatPar(); // - // array delta gives desired variation of parameters in AliExternalTrackParam definition, + // array delta gives desired variation of parameters in trackParam_t definition, // while the variation should be done for parameters in the frame where the vector // of material corrections has diagonal cov. matrix -> rotate the delta to this frame double deltaMatD[kNKinParBON]; pnt->DiagMatCorr(delta, deltaMatD); // - // printf("Vary %d [%+.3e %+.3e %+.3e %+.3e] ",ip,deltaMatD[0],deltaMatD[1],deltaMatD[2],deltaMatD[3]); pnt->Print(); + // printf("Vary %d [%+.3e %+.3e %+.3e %+.3e] ",ip,deltaMatD[0],deltaMatD[1],deltaMatD[2],deltaMatD[3]); pnt->print(); int offsI = pnt->GetMaxLocVarID() - nParFreeI; // the parameters for this point start with this offset // they are irrelevant for the points upstream @@ -301,24 +303,24 @@ Bool_t AliAlgTrack::CalcResidDeriv(double* params, Bool_t invert, int pFrom, int SetParams(probD, kNRDClones, pnt->GetXPoint(), pnt->GetAlphaSens(), pnt->GetTrParamWSB(), kFALSE); // no need for eventual track inversion here: if needed, this is already done in ParamWSB // - int offsIP = offsI + ipar; // parameter entry in the params array + int offsIP = offsI + ipar; // parameter entry in the extendedParams array // printf(" Var:%d (%d) %e\n",ipar,offsIP, del); for (int icl = 0; icl < kRichardsonN; icl++) { // calculate kRichardsonN variations with del, del/2, del/4... varDelta[icl] = del; - double parOrig = params[offsIP]; - params[offsIP] += del; + double parOrig = extendedParams[offsIP]; + extendedParams[offsIP] += del; // // apply varied material effects : incremented by delta - if (!ApplyMatCorr(probD[(icl << 1) + 0], params, pnt)) + if (!ApplyMatCorr(probD[(icl << 1) + 0], extendedParams, pnt)) return kFALSE; // // apply varied material effects : decremented by delta - params[offsIP] = parOrig - del; - if (!ApplyMatCorr(probD[(icl << 1) + 1], params, pnt)) + extendedParams[offsIP] = parOrig - del; + if (!ApplyMatCorr(probD[(icl << 1) + 1], extendedParams, pnt)) return kFALSE; // - params[offsIP] = parOrig; + extendedParams[offsIP] = parOrig; del *= 0.5; } if (pnt->ContainsMeasurement()) { // calculate derivatives at the scattering point itself @@ -331,13 +333,13 @@ Bool_t AliAlgTrack::CalcResidDeriv(double* params, Bool_t invert, int pFrom, int for (int jp = ip + pinc; jp != pTo; jp += pinc) { AliAlgPoint* pntJ = GetPoint(jp); - // printf(" DerFor:%d ",jp); pntJ->Print(); + // printf(" DerFor:%d ",jp); pntJ->print(); if (!PropagateParamToPoint(probD, kNRDClones, pntJ)) return kFALSE; // if (pntJ->ContainsMaterial()) { // apply material corrections - if (!ApplyMatCorr(probD, kNRDClones, params, pntJ)) + if (!ApplyMatCorr(probD, kNRDClones, extendedParams, pntJ)) return kFALSE; } // @@ -424,37 +426,37 @@ Bool_t AliAlgTrack::CalcResidDerivGlo(AliAlgPoint* pnt) } //______________________________________________________ -Bool_t AliAlgTrack::CalcResiduals(const double* params) +Bool_t AliAlgTrack::CalcResiduals(const double* extendedParams) { // Propagate for given local params and calculate residuals - // The 1st 4 or 5 elements of params vector should be the reference AliExternalTrackParam + // The 1st 4 or 5 elements of extendedParams vector should be the reference trackParam_t // Then parameters of material corrections for each point // marked as having materials should come (4 or 5 dependending if ELoss is varied or fixed). // They correspond to kink parameters - // (AliExternalTrackParam_after_material - AliExternalTrackParam_before_material) - // rotated to frame where they error matrix is diagonal. Their conversion to AliExternalTrackParam + // (trackParam_t_after_material - trackParam_t_before_material) + // rotated to frame where they error matrix is diagonal. Their conversion to trackParam_t // increment will be done locally in the ApplyMatCorr routine. // - // If params are not provided, use internal params array + // If extendedParams are not provided, use internal extendedParams array // - if (!params) - params = fLocParA; + if (!extendedParams) + extendedParams = fLocParA; int np = GetNPoints(); fChi2 = 0; fNDF = 0; // // collision track or cosmic lower leg - if (!CalcResiduals(params, fNeedInv[0], GetInnerPointID(), 0)) { + if (!CalcResiduals(extendedParams, fNeedInv[0], GetInnerPointID(), 0)) { #if DEBUG > 3 - AliWarning("Failed on residuals calculation 0"); + LOG(warn) << "Failed on residuals calculation 0"; #endif return kFALSE; } // if (IsCosmic()) { // cosmic upper leg - if (!CalcResiduals(params, fNeedInv[1], GetInnerPointID() + 1, np - 1)) { + if (!CalcResiduals(extendedParams, fNeedInv[1], GetInnerPointID() + 1, np - 1)) { #if DEBUG > 3 - AliWarning("Failed on residuals calculation 1"); + LOG(warn) << "Failed on residuals calculation 1"; #endif return kFALSE; } @@ -466,22 +468,22 @@ Bool_t AliAlgTrack::CalcResiduals(const double* params) } //______________________________________________________ -Bool_t AliAlgTrack::CalcResiduals(const double* params, Bool_t invert, int pFrom, int pTo) +Bool_t AliAlgTrack::CalcResiduals(const double* extendedParams, Bool_t invert, int pFrom, int pTo) { // Calculate residuals for the single leg from points pFrom to pT - // The 1st 4 or 5 elements of params vector should be corrections to - // the reference AliExternalTrackParam + // The 1st 4 or 5 elements of extendedParams vector should be corrections to + // the reference trackParam_t // Then parameters of material corrections for each point // marked as having materials should come (4 or 5 dependending if ELoss is varied or fixed). // They correspond to kink parameters - // (AliExternalTrackParam_after_material - AliExternalTrackParam_before_material) - // rotated to frame where they error matrix is diagonal. Their conversion to AliExternalTrackParam + // (trackParam_t_after_material - trackParam_t_before_material) + // rotated to frame where they error matrix is diagonal. Their conversion to trackParam_t // increment will be done locally in the ApplyMatCorr routine. // - AliExternalTrackParam probe; - SetParams(probe, GetX(), GetAlpha(), params, kTRUE); + trackParam_t probe; + SetParams(probe, getX(), getAlpha(), extendedParams, kTRUE); if (invert) - probe.Invert(); + probe.invert(); int pinc; if (pTo > pFrom) { // fit in points decreasing order: cosmics upper leg pTo++; @@ -498,17 +500,17 @@ Bool_t AliAlgTrack::CalcResiduals(const double* params, Bool_t invert, int pFrom // // store the current track kinematics at the point BEFORE applying eventual material // corrections. This kinematics will be later varied around supplied parameters (in the CalcResidDeriv) - pnt->SetTrParamWSB(probe.GetParameter()); + pnt->SetTrParamWSB(probe.getParams()); // // account for materials // if (pnt->ContainsMaterial()) { // apply material corrections - if (!ApplyMatCorr(probe, params, pnt)) + if (!ApplyMatCorr(probe, extendedParams, pnt)) return kFALSE; // } - pnt->SetTrParamWSA(probe.GetParameter()); + pnt->SetTrParamWSA(probe.getParams()); // if (pnt->ContainsMeasurement()) { // need to calculate residuals in the frame where errors are orthogonal - pnt->GetResidualsDiag(probe.GetParameter(), fResidA[0][ip], fResidA[1][ip]); + pnt->GetResidualsDiag(probe.getParams(), fResidA[0][ip], fResidA[1][ip]); fChi2 += fResidA[0][ip] * fResidA[0][ip] / pnt->GetErrDiag(0); fChi2 += fResidA[1][ip] * fResidA[1][ip] / pnt->GetErrDiag(1); fNDF += 2; @@ -527,190 +529,200 @@ Bool_t AliAlgTrack::CalcResiduals(const double* params, Bool_t invert, int pFrom } //______________________________________________________ -Bool_t AliAlgTrack::PropagateParamToPoint(AliExternalTrackParam* tr, int nTr, const AliAlgPoint* pnt, double maxStep) +Bool_t AliAlgTrack::PropagateParamToPoint(trackParam_t* tr, int nTr, const AliAlgPoint* pnt, double maxStep) { - // Propagate set of tracks to the point (only parameters, no error matrix) - // VECTORIZE this - // - for (int itr = nTr; itr--;) { - if (!PropagateParamToPoint(tr[itr], pnt, maxStep)) { -#if DEBUG > 3 - AliErrorF("Failed on clone %d propagation", itr); - tr[itr].Print(); - pnt->Print("meas mat"); -#endif - return kFALSE; - } - } + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + // FIXME(milettri): needs AliTrackerBase + // // Propagate set of tracks to the point (only parameters, no error matrix) + // // VECTORIZE this + // // + // for (int itr = nTr; itr--;) { + // if (!PropagateParamToPoint(tr[itr], pnt, maxStep)) { + //#if DEBUG > 3 + // LOG(fatal) << "Failed on clone %d propagation" << itr; + // tr[itr].print(); + // pnt->print("meas mat"); + //#endif + // return kFALSE; + // } + // } return kTRUE; } //______________________________________________________ -Bool_t AliAlgTrack::PropagateParamToPoint(AliExternalTrackParam& tr, const AliAlgPoint* pnt, double maxStep) +Bool_t AliAlgTrack::PropagateParamToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep) { - // propagate tracks to the point (only parameters, no error matrix) - double xyz[3], bxyz[3]; - // - if (!tr.RotateParamOnly(pnt->GetAlphaSens())) { -#if DEBUG > 3 - AliErrorF("Failed to rotate to alpha=%f", pnt->GetAlphaSens()); - tr.Print(); - pnt->Print(); -#endif - return kFALSE; - } - // - double xTgt = pnt->GetXPoint(); - double xBeg = tr.GetX(); - double dx = xTgt - xBeg; - int nstep = int(Abs(dx) / maxStep) + 1; - dx /= nstep; - // - for (int ist = nstep; ist--;) { - // - double xToGo = xTgt - dx * ist; - tr.GetXYZ(xyz); - // - if (GetFieldON()) { - if (pnt->GetUseBzOnly()) { - if (!tr.PropagateParamOnlyTo(xToGo, AliTrackerBase::GetBz(xyz))) { -#if DEBUG > 3 - AliErrorF("Failed to propagate(BZ) to X=%f", pnt->GetXPoint()); - tr.Print(); - pnt->Print(); -#endif - return kFALSE; - } - } else { - AliTrackerBase::GetBxByBz(xyz, bxyz); - if (!tr.PropagateParamOnlyBxByBzTo(xToGo, bxyz)) { -#if DEBUG > 3 - AliErrorF("Failed to propagate(BXYZ) to X=%f", pnt->GetXPoint()); - tr.Print(); - pnt->Print(); -#endif - return kFALSE; - } - } - } else { // straigth line propagation - if (!tr.PropagateParamOnlyTo(xToGo, 0)) { -#if DEBUG > 3 - AliErrorF("Failed to propagate(B=0) to X=%f", pnt->GetXPoint()); - tr.Print(); - pnt->Print(); -#endif - return kFALSE; - } - } - } // steps - // + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + // FIXME(milettri): needs AliTrackerBase + // // propagate tracks to the point (only parameters, no error matrix) + // dim3_t xyz; + // double bxyz[3]; + // // + // if (!tr.rotateParam(pnt->GetAlphaSens())) { + //#if DEBUG > 3 + // LOG(error) << "Failed to rotate to alpha=" << pnt->GetAlphaSens(); + // tr.Print(); + // pnt->Print(); + //#endif + // return kFALSE; + // } + // // + // double xTgt = pnt->GetXPoint(); + // double xBeg = tr.getX(); + // double dx = xTgt - xBeg; + // int nstep = int(Abs(dx) / maxStep) + 1; + // dx /= nstep; + // // + // for (int ist = nstep; ist--;) { + // // + // double xToGo = xTgt - dx * ist; + // tr.getXYZGlo(xyz); + // // + // if (GetFieldON()) { + // if (pnt->GetUseBzOnly()) { + // if (!tr.propagateParamTo(xToGo, AliTrackerBase::GetBz(xyz))) { + //#if DEBUG > 3 + // LOG(error) << "Failed to propagate(BZ) to X=%" << pnt->GetXPoint(); + // tr.Print(); + // pnt->Print(); + //#endif + // return kFALSE; + // } + // } else { + // AliTrackerBase::GetBxByBz(xyz, bxyz); + // if (!tr.propagateParamTo(xToGo, bxyz)) { + //#if DEBUG > 3 + // LOG(error) << "Failed to propagate(BXYZ) to X=" << pnt->GetXPoint(); + // tr.Print(); + // pnt->Print(); + //#endif + // return kFALSE; + // } + // } + // } else { // straigth line propagation + // if (!tr.propagateParamTo(xToGo, 0)) { + //#if DEBUG > 3 + // LOG(error) << "Failed to propagate(B=0) to X=" << pnt->GetXPoint(); + // tr.Print(); + // pnt->Print(); + //#endif + // return kFALSE; + // } + // } + // } // steps + // // return kTRUE; } //______________________________________________________ -Bool_t AliAlgTrack::PropagateToPoint(AliExternalTrackParam& tr, const AliAlgPoint* pnt, +Bool_t AliAlgTrack::PropagateToPoint(trackParam_t& tr, const AliAlgPoint* pnt, int minNSteps, double maxStep, Bool_t matCor, double* matPar) { - // propagate tracks to the point. If matCor is true, then material corrections will be applied. - // if matPar pointer is provided, it will be filled by total x2x0 and signed xrho - if (!tr.Rotate(pnt->GetAlphaSens())) { -#if DEBUG > 3 - AliWarning(Form("Failed to rotate to alpha=%f", pnt->GetAlphaSens())); - tr.Print(); -#endif - return kFALSE; - } - // - double xyz0[3], xyz1[3], bxyz[3], matarr[7]; - double xPoint = pnt->GetXPoint(), dx = xPoint - tr.GetX(), dxa = Abs(dx), step = dxa / minNSteps; - if (matPar) - matPar[0] = matPar[1] = 0; - if (dxa < kTinyDist) - return kTRUE; - if (step > maxStep) - step = maxStep; - int nstep = int(dxa / step); - step = dxa / nstep; - if (dx < 0) - step = -step; - // - // printf("-->will go from X:%e to X:%e in %d steps of %f\n",tr.GetX(),xPoint,nstep,step); - - // do we go along or against track direction - Bool_t alongTrackDir = (dx > 0 && !pnt->IsInvDir()) || (dx < 0 && pnt->IsInvDir()); - Bool_t queryXYZ = matCor || GetFieldON(); - if (queryXYZ) - tr.GetXYZ(xyz0); - // - double x2X0Tot = 0, xrhoTot = 0; - for (int ist = nstep; ist--;) { // single propagation step >> - double xToGo = xPoint - step * ist; - // - if (GetFieldON()) { - if (pnt->GetUseBzOnly()) { - if (!tr.PropagateTo(xToGo, AliTrackerBase::GetBz(xyz0))) { -#if DEBUG > 3 - AliWarningF("Failed to propagate(BZ) to X=%f", xToGo); - tr.Print(); -#endif - return kFALSE; - } - } else { - AliTrackerBase::GetBxByBz(xyz0, bxyz); - if (!tr.PropagateToBxByBz(xToGo, bxyz)) { -#if DEBUG > 3 - AliWarningF("Failed to propagate(BXYZ) to X=%f", xToGo); -#endif - return kFALSE; - } - } - } else { // straigth line propagation - if (!tr.PropagateTo(xToGo, 0)) { -#if DEBUG > 3 - AliWarningF("Failed to propagate(B=0) to X=%f", xToGo); -#endif - return kFALSE; - } - } - // - if (queryXYZ) { - tr.GetXYZ(xyz1); - if (matCor) { - AliTrackerBase::MeanMaterialBudget(xyz0, xyz1, matarr); - Double_t xrho = matarr[0] * matarr[4], xx0 = matarr[1]; - if (alongTrackDir) - xrho = -xrho; // if we go along track direction, energy correction is negative - x2X0Tot += xx0; - xrhoTot += xrho; - // printf("MAT %+7.2f %+7.2f %+7.2f -> %+7.2f %+7.2f %+7.2f | %+e %+e | -> %+e %+e | %+e %+e %+e %+e %+e\n", - // xyz0[0],xyz0[1],xyz0[2], xyz1[0],xyz1[1],xyz1[2], tr.Phi(), tr.GetAlpha(), - // x2X0Tot,xrhoTot, matarr[0],matarr[1],matarr[2],matarr[3],matarr[4]); - if (!tr.CorrectForMeanMaterial(xx0, xrho, fMass)) { -#if DEBUG > 3 - AliWarningF("Failed on CorrectForMeanMaterial(%f,%f,%f)", xx0, xrho, fMass); - tr.Print(); -#endif - return kFALSE; - } - } - for (int l = 3; l--;) - xyz0[l] = xyz1[l]; - } - } // single propagation step << - // - if (matPar) { - matPar[0] = x2X0Tot; - matPar[1] = xrhoTot; - } + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + // FIXME(milettri): needs AliTrackerBase + // // propagate tracks to the point. If matCor is true, then material corrections will be applied. + // // if matPar pointer is provided, it will be filled by total x2x0 and signed xrho + // if (!tr.rotate(pnt->GetAlphaSens())) { + //#if DEBUG > 3 + // LOG(WARNING) << "Failed to rotate to alpha=" << pnt->GetAlphaSens(); + // tr.print(); + //#endif + // return kFALSE; + // } + // // + // dim3_t xyz0{0}; + // dim3_t xyz1{0}; + // dim3_t bxyz{0}; + // double matarr[7]; + // double xPoint = pnt->GetXPoint(), dx = xPoint - tr.getX(), dxa = Abs(dx), step = dxa / minNSteps; + // if (matPar) + // matPar[0] = matPar[1] = 0; + // if (dxa < kTinyDist) + // return kTRUE; + // if (step > maxStep) + // step = maxStep; + // int nstep = int(dxa / step); + // step = dxa / nstep; + // if (dx < 0) + // step = -step; + // // + // // printf("-->will go from X:%e to X:%e in %d steps of %f\n",tr.GetX(),xPoint,nstep,step); + // + // // do we go along or against track direction + // Bool_t alongTrackDir = (dx > 0 && !pnt->IsInvDir()) || (dx < 0 && pnt->IsInvDir()); + // Bool_t queryXYZ = matCor || GetFieldON(); + // if (queryXYZ) + // tr.getXYZGlo(xyz0); + // // + // double x2X0Tot = 0, xrhoTot = 0; + // for (int ist = nstep; ist--;) { // single propagation step >> + // double xToGo = xPoint - step * ist; + // // + // if (GetFieldON()) { + // if (pnt->GetUseBzOnly()) { + // if (!tr.propagateParamTo(xToGo, AliTrackerBase::GetBz(xyz0))) { + //#if DEBUG > 3 + // LOG(WARNING) << "Failed to propagate(BZ) to X=" << xToGo; + // tr.print(); + //#endif + // return kFALSE; + // } + // } else { + // AliTrackerBase::GetBxByBz(xyz0, bxyz); + // if (!tr.propagateParamTo(xToGo, bxyz)) { + //#if DEBUG > 3 + // AliWarningF("Failed to propagate(BXYZ) to X=%f", xToGo); + //#endif + // return kFALSE; + // } + // } + // } else { // straigth line propagation + // if (!tr.propagateParamTo(xToGo, 0)) { + //#if DEBUG > 3 + // AliWarningF("Failed to propagate(B=0) to X=%f", xToGo); + //#endif + // return kFALSE; + // } + // } + // // + // if (queryXYZ) { + // tr.getXYZGlo(xyz1); + // if (matCor) { + // AliTrackerBase::MeanMaterialBudget(xyz0, xyz1, matarr); + // Double_t xrho = matarr[0] * matarr[4], xx0 = matarr[1]; + // if (alongTrackDir) + // xrho = -xrho; // if we go along track direction, energy correction is negative + // x2X0Tot += xx0; + // xrhoTot += xrho; + // // printf("MAT %+7.2f %+7.2f %+7.2f -> %+7.2f %+7.2f %+7.2f | %+e %+e | -> %+e %+e | %+e %+e %+e %+e %+e\n", + // // xyz0[0],xyz0[1],xyz0[g2], xyz1[0],xyz1[1],xyz1[2], tr.Phi(), tr.GetAlpha(), + // // x2X0Tot,xrhoTot, matarr[0],matarr[1],matarr[2],matarr[3],matarr[4]); + // if (!tr.correctForMaterial(xx0, xrho, fMass)) { + //#if DEBUG > 3 + // LOG(WARNING) << "Failed on CorrectForMeanMaterial(" << xx0 << "," << xrho << "," << fMass << ")"; + // tr.print(); + //#endif + // return kFALSE; + // } + // } + // for (int l = 3; l--;) + // xyz0[l] = xyz1[l]; + // } + // } // single propagation step << + // // + // if (matPar) { + // matPar[0] = x2X0Tot; + // matPar[1] = xrhoTot; + // } return kTRUE; } /* //______________________________________________________ -Bool_t AliAlgTrack::ApplyMS(AliExternalTrackParam& trPar, double tms,double pms) +Bool_t AliAlgTrack::ApplyMS(trackParam_t& trPar, double tms,double pms) { //------------------------------------------------------------------------------ - // Modify track par (e.g. AliExternalTrackParam) in the tracking frame + // Modify track par (e.g. trackParam_t) in the tracking frame // (dip angle lam, az. angle phi) // by multiple scattering defined by polar and azumuthal scattering angles in // the track collinear frame (tms and pms resp). @@ -751,9 +763,9 @@ Bool_t AliAlgTrack::ApplyMS(AliExternalTrackParam& trPar, double tms,double pms) */ //______________________________________________________ -Bool_t AliAlgTrack::ApplyMatCorr(AliExternalTrackParam& trPar, const Double_t* corrPar, const AliAlgPoint* pnt) +Bool_t AliAlgTrack::ApplyMatCorr(trackParam_t& trPar, const Double_t* corrPar, const AliAlgPoint* pnt) { - // Modify track param (e.g. AliExternalTrackParam) in the tracking frame + // Modify track param (e.g. trackParam_t) in the tracking frame // by delta accounting for material effects // Note: corrPar contains delta to track parameters rotated by the matrix // DIAGONALIZING ITS COVARIANCE MATRIX! @@ -771,43 +783,41 @@ Bool_t AliAlgTrack::ApplyMatCorr(AliExternalTrackParam& trPar, const Double_t* c //corr[kParQ2Pt] += detELoss[kParQ2Pt]; // printf("apply corr UD %+.3e %+.3e %+.3e %+.3e %+.3e\n",corr[0],corr[1],corr[2],corr[3],corr[4]); // printf(" corr D %+.3e %+.3e %+.3e %+.3e\n",corrDiag[0],corrDiag[1],corrDiag[2],corrDiag[3]); - // printf("at point :"); pnt->Print(); + // printf("at point :"); pnt->print(); return ApplyMatCorr(trPar, corr); // } //______________________________________________________ -Bool_t AliAlgTrack::ApplyMatCorr(AliExternalTrackParam& trPar, const Double_t* corr) +Bool_t AliAlgTrack::ApplyMatCorr(trackParam_t& trPar, const Double_t* corr) { - // Modify track param (e.g. AliExternalTrackParam) in the tracking frame + // Modify track param (e.g. trackParam_t) in the tracking frame // by delta accounting for material effects // Note: corr contains delta to track frame, NOT in diagonalized one const double kMaxSnp = 0.95; - double* par = (double*)trPar.GetParameter(); - double snpNew = par[kParSnp] + corr[kParSnp]; - if (Abs(snpNew) > kMaxSnp) { + + const double snp = trPar.getSnp() + corr[kParSnp]; + if (Abs(snp) > kMaxSnp) { #if DEBUG > 3 - AliErrorF("Snp is too large: %f", snpNew); + LOG(error) << "Snp is too large: " << snp; printf("DeltaPar: "); for (int i = 0; i < kNKinParBON; i++) printf("%+.3e ", corr[i]); printf("\n"); - trPar.Print(); + trPar.print(); #endif return kFALSE; } - par[kParY] += corr[kParY]; - par[kParZ] += corr[kParZ]; - par[kParSnp] = snpNew; - par[kParTgl] += corr[kParTgl]; - par[kParQ2Pt] += corr[kParQ2Pt]; + + trPar.updateParams(corr); + return kTRUE; } //______________________________________________________ -Bool_t AliAlgTrack::ApplyMatCorr(AliExternalTrackParam* trSet, int ntr, const Double_t* corrDiag, const AliAlgPoint* pnt) +Bool_t AliAlgTrack::ApplyMatCorr(trackParam_t* trSet, int ntr, const Double_t* corrDiag, const AliAlgPoint* pnt) { - // Modify set of track params (e.g. AliExternalTrackParam) in the tracking frame + // Modify set of track params (e.g. trackParam_t) in the tracking frame // by delta accounting for material effects // Note: corrDiag contain delta to track parameters rotated by the matrix DIAGONALIZING ITS // COVARIANCE MATRIX @@ -824,13 +834,13 @@ Bool_t AliAlgTrack::ApplyMatCorr(AliExternalTrackParam* trSet, int ntr, const Do // if (!pnt->GetELossVaried()) corr[kParQ2Pt] = pnt->GetMatCorrExp()[kParQ2Pt]; // fixed eloss expected effect // printf("apply corr UD %+.3e %+.3e %+.3e %+.3e\n",corr[0],corr[1],corr[2],corr[3]); // printf(" corr D %+.3e %+.3e %+.3e %+.3e\n",corrDiagP[0],corrDiagP[1],corrDiagP[2],corrDiagP[3]); - // printf("at point :"); pnt->Print(); + // printf("at point :"); pnt->print(); // for (int itr = ntr; itr--;) { if (!ApplyMatCorr(trSet[itr], corr)) { #if DEBUG > 3 - AliErrorF("Failed on clone %d materials", itr); - trSet[itr].Print(); + LOG(error) << "Failed on clone %d materials" << itr; + trSet[itr].print(); #endif return kFALSE; } @@ -875,7 +885,7 @@ Double_t AliAlgTrack::RichardsonExtrap(const double* val, int ord) } //______________________________________________ -void AliAlgTrack::RichardsonDeriv(const AliExternalTrackParam* trSet, const double* delta, const AliAlgPoint* pnt, double& derY, double& derZ) +void AliAlgTrack::RichardsonDeriv(const trackParam_t* trSet, const double* delta, const AliAlgPoint* pnt, double& derY, double& derZ) { // Calculate Richardson derivatives for diagonalized Y and Z from a set of kRichardsonN pairs // of tracks with same parameter of i-th pair varied by +-delta[i] @@ -883,9 +893,9 @@ void AliAlgTrack::RichardsonDeriv(const AliExternalTrackParam* trSet, const doub // for (int icl = 0; icl < kRichardsonN; icl++) { // calculate kRichardsonN variations with del, del/2, del/4... double resYVP = 0, resYVN = 0, resZVP = 0, resZVN = 0; - pnt->GetResidualsDiag(trSet[(icl << 1) + 0].GetParameter(), resYVP, resZVP); // variation with +delta - pnt->GetResidualsDiag(trSet[(icl << 1) + 1].GetParameter(), resYVN, resZVN); // variation with -delta - derRichY[icl] = 0.5 * (resYVP - resYVN) / delta[icl]; // 2-point symmetric derivatives + pnt->GetResidualsDiag(trSet[(icl << 1) + 0].getParams(), resYVP, resZVP); // variation with +delta + pnt->GetResidualsDiag(trSet[(icl << 1) + 1].getParams(), resYVN, resZVN); // variation with -delta + derRichY[icl] = 0.5 * (resYVP - resYVN) / delta[icl]; // 2-point symmetric derivatives derRichZ[icl] = 0.5 * (resZVP - resZVN) / delta[icl]; } derY = RichardsonExtrap(derRichY, kRichardsonOrd); // dY/dPar @@ -898,7 +908,7 @@ void AliAlgTrack::Print(Option_t* opt) const { // print track data printf("%s ", IsCosmic() ? " Cosmic " : "Collision "); - AliExternalTrackParam::Print(); + trackParam_t::print(); printf("N Free Par: %d (Kinem: %d) | Npoints: %d (Inner:%d) | M : %.3f | Chi2Ini:%.1f Chi2: %.1f/%d", fNLocPar, fNLocExtPar, GetNPoints(), GetInnerPointID(), fMass, fChi2Ini, fChi2, fNDF); if (IsCosmic()) { @@ -987,7 +997,7 @@ Bool_t AliAlgTrack::IniFit() const int kMinNStep = 3; const double kMaxDefStep = 3.0; // - AliExternalTrackParam trc = *this; + trackParam_t trc = *this; // if (!GetFieldON()) { // for field-off data impose nominal momentum } @@ -999,21 +1009,21 @@ Bool_t AliAlgTrack::IniFit() // the fit will always start from the outgoing track in inward direction if (!FitLeg(trc, 0, GetInnerPointID(), fNeedInv[0])) { #if DEBUG > 3 - AliWarning("Failed FitLeg 0"); - trc.Print(); + LOG(warn) << "Failed FitLeg 0"; + trc.print(); #endif return kFALSE; // collision track or cosmic lower leg } // - // printf("Lower leg: %d %d\n",0,GetInnerPointID()); trc.Print(); + // printf("Lower leg: %d %d\n",0,GetInnerPointID()); trc.print(); // if (IsCosmic()) { fChi2CosmDn = fChi2; - AliExternalTrackParam trcU = trc; + trackParam_t trcU = trc; if (!FitLeg(trcU, GetNPoints() - 1, GetInnerPointID() + 1, fNeedInv[1])) { //fit upper leg of cosmic track #if DEBUG > 3 - AliWarning("Failed FitLeg 0"); - trc.Print(); + LOG(warn) << "Failed FitLeg 0"; + trc.print(); #endif return kFALSE; // collision track or cosmic lower leg } @@ -1024,11 +1034,11 @@ Bool_t AliAlgTrack::IniFit() return kFALSE; // fChi2CosmUp = fChi2 - fChi2CosmDn; - // printf("Upper leg: %d %d\n",GetInnerPointID()+1,GetNPoints()-1); trcU.Print(); + // printf("Upper leg: %d %d\n",GetInnerPointID()+1,GetNPoints()-1); trcU.print(); // if (!CombineTracks(trc, trcU)) return kFALSE; - //printf("Combined\n"); trc.Print(); + //printf("Combined\n"); trc.print(); } CopyFrom(&trc); // @@ -1038,7 +1048,7 @@ Bool_t AliAlgTrack::IniFit() } //______________________________________________ -Bool_t AliAlgTrack::CombineTracks(AliExternalTrackParam& trcL, const AliExternalTrackParam& trcU) +Bool_t AliAlgTrack::CombineTracks(trackParam_t& trcL, const trackParam_t& trcU) { // Assign to trcL the combined tracks (Kalman update of trcL by trcU) // The trcL and trcU MUST be defined at same X,Alpha @@ -1049,37 +1059,37 @@ Bool_t AliAlgTrack::CombineTracks(AliExternalTrackParam& trcL, const AliExternal // CL' = CL - K*CL // vL' = vL + K(vU-vL) // - if (Abs(trcL.GetX() - trcU.GetX()) > kTinyDist || Abs(trcL.GetAlpha() - trcU.GetAlpha()) > kTinyDist) { - AliError("Tracks must be defined at same reference X and Alpha"); - trcL.Print(); - trcU.Print(); + if (Abs(trcL.getX() - trcU.getX()) > kTinyDist || Abs(trcL.getAlpha() - trcU.getAlpha()) > kTinyDist) { + LOG(error) << "Tracks must be defined at same reference X and Alpha"; + trcL.print(); + trcU.print(); return kFALSE; } // - const double *covU = trcU.GetCovariance(), *parU = trcU.GetParameter(); - double *covL = (double*)trcL.GetCovariance(), *parL = (double*)trcL.GetParameter(); + // const covMat_t& covU = trcU.getCov(); + // const covMat_t& covL = trcL.getCov(); // int mtSize = GetFieldON() ? kNKinParBON : kNKinParBOFF; TMatrixD matCL(mtSize, mtSize), matCLplCU(mtSize, mtSize); TVectorD vl(mtSize), vUmnvL(mtSize); // - // trcL.Print(); - // trcU.Print(); + // trcL.print(); + // trcU.print(); // for (int i = mtSize; i--;) { - vUmnvL[i] = parU[i] - parL[i]; // y = residual of 2 tracks - vl[i] = parL[i]; + vUmnvL[i] = trcU.getParam(i) - trcL.getParam(i); // y = residual of 2 tracks + vl[i] = trcL.getParam(i); for (int j = i + 1; j--;) { - int indIJ = ((i * (i + 1)) >> 1) + j; // position of IJ cov element in the AliExternalTrackParam covariance array - matCL(i, j) = matCL(j, i) = covL[indIJ]; - matCLplCU(i, j) = matCLplCU(j, i) = covL[indIJ] + covU[indIJ]; + int indIJ = ((i * (i + 1)) >> 1) + j; // position of IJ cov element in the trackParam_t covariance array + matCL(i, j) = matCL(j, i) = trcL.getCovarElem(i, j); + matCLplCU(i, j) = matCLplCU(j, i) = trcL.getCovarElem(i, j) + trcU.getCovarElem(i, j); } } matCLplCU.Invert(); // S^-1 = (Cl + Cu)^-1 if (!matCLplCU.IsValid()) { #if DEBUG > 3 - AliError("Failed to invert summed cov.matrix of cosmic track"); - matCLplCU.Print(); + LOG(error) << "Failed to invert summed cov.matrix of cosmic track"; + matCLplCU.print(); #endif return kFALSE; // inversion failed } @@ -1087,9 +1097,9 @@ Bool_t AliAlgTrack::CombineTracks(AliExternalTrackParam& trcL, const AliExternal TMatrixD matKdotCL(matK, TMatrixD::kMult, matCL); // K*Cl TVectorD vlUp = matK * vUmnvL; // K*(vl - vu) for (int i = mtSize; i--;) { - parL[i] += vlUp[i]; // updated param: vL' = vL + K(vU-vL) + trcL.updateParam(vlUp[i], i); // updated param: vL' = vL + K(vU-vL) for (int j = i + 1; j--;) - covL[((i * (i + 1)) >> 1) + j] -= matKdotCL(i, j); // updated covariance: Cl' = Cl - K*Cl + trcL.updateCov(-matKdotCL(i, j), i, j); // updated covariance: Cl' = Cl - K*Cl } // // update chi2 @@ -1105,7 +1115,7 @@ Bool_t AliAlgTrack::CombineTracks(AliExternalTrackParam& trcL, const AliExternal } //______________________________________________ -Bool_t AliAlgTrack::FitLeg(AliExternalTrackParam& trc, int pFrom, int pTo, Bool_t& inv) +Bool_t AliAlgTrack::FitLeg(trackParam_t& trc, int pFrom, int pTo, Bool_t& inv) { // perform initial fit of the track // the fit will always start from the outgoing track in inward direction (i.e. if cosmics - bottom leg) @@ -1114,31 +1124,31 @@ Bool_t AliAlgTrack::FitLeg(AliExternalTrackParam& trc, int pFrom, int pTo, Bool_ const double kErrSpace = 50.; const double kErrAng = 0.7; const double kErrRelPtI = 1.; - const double kIniErr[15] = {// initial error - kErrSpace * kErrSpace, - 0, kErrSpace * kErrSpace, - 0, 0, kErrAng * kErrAng, - 0, 0, 0, kErrAng * kErrAng, - 0, 0, 0, 0, kErrRelPtI * kErrRelPtI}; + const covMat_t kIniErr{// initial error + kErrSpace * kErrSpace, + 0, kErrSpace * kErrSpace, + 0, 0, kErrAng * kErrAng, + 0, 0, 0, kErrAng * kErrAng, + 0, 0, 0, 0, kErrRelPtI * kErrRelPtI}; // // prepare seed at outer point AliAlgPoint* p0 = GetPoint(pFrom); - double phi = trc.Phi(), alp = p0->GetAlphaSens(); + double phi = trc.getPhi(), alp = p0->GetAlphaSens(); BringTo02Pi(phi); BringTo02Pi(alp); double dphi = DeltaPhiSmall(phi, alp); // abs delta angle if (dphi > Pi() / 2.) { // need to invert the track to new frame inv = kTRUE; // printf("Fit in %d %d Delta: %.3f -> Inverting for\n",pFrom,pTo,dphi); - // p0->Print("meas"); - // printf("BeforeInv "); trc.Print(); - trc.Invert(); - // printf("After Inv "); trc.Print(); + // p0->print("meas"); + // printf("BeforeInv "); trc.print(); + trc.invert(); + // printf("After Inv "); trc.print(); } - if (!trc.RotateParamOnly(p0->GetAlphaSens())) { + if (!trc.rotateParam(p0->GetAlphaSens())) { #if DEBUG > 3 - AliWarningF("Failed on RotateParamOnly to %f", p0->GetAlphaSens()); - trc.Print(); + AliWarningF("Failed on rotateParam to %f", p0->GetAlphaSens()); + trc.print(); #endif return kFALSE; } @@ -1147,13 +1157,12 @@ Bool_t AliAlgTrack::FitLeg(AliExternalTrackParam& trc, int pFrom, int pTo, Bool_ //trc.PropagateParamOnlyTo(p0->GetXPoint()+kOverShootX,AliTrackerBase::GetBz())) { #if DEBUG > 3 AliWarningF("Failed on PropagateParamOnlyTo to %f", p0->GetXPoint() + kOverShootX); - trc.Print(); + trc.print(); #endif return kFALSE; } - double* cov = (double*)trc.GetCovariance(); - memcpy(cov, kIniErr, 15 * sizeof(double)); - cov[14] *= trc.GetSigned1Pt() * trc.GetSigned1Pt(); + trc.setCov(kIniErr); + trc.setCov(trc.getQ2Pt() * trc.getQ2Pt(), 4, 4); // lowest diagonal element (Q2Pt2) // int pinc; if (pTo > pFrom) { // fit in points increasing order: collision track or cosmics lower leg @@ -1168,7 +1177,7 @@ Bool_t AliAlgTrack::FitLeg(AliExternalTrackParam& trc, int pFrom, int pTo, Bool_ AliAlgPoint* pnt = GetPoint(ip); // // printf("*** FitLeg %d (%d %d)\n",ip,pFrom,pTo); - // printf("Before propagate: "); trc.Print(); + // printf("Before propagate: "); trc.print(); if (!PropagateToPoint(trc, pnt, kMinNStep, kMaxDefStep, kTRUE)) return kFALSE; if (pnt->ContainsMeasurement()) { @@ -1176,25 +1185,25 @@ Bool_t AliAlgTrack::FitLeg(AliExternalTrackParam& trc, int pFrom, int pTo, Bool_ pnt->UpdatePointByTrackInfo(&trc); const double* yz = pnt->GetYZTracking(); const double* errYZ = pnt->GetYZErrTracking(); - double chi = trc.GetPredictedChi2(yz, errYZ); + double chi = trc.getPredictedChi2(yz, errYZ); //printf("***>> fitleg-> Y: %+e %+e / Z: %+e %+e -> Chi2: %e | %+e %+e\n",yz[0],trc.GetY(),yz[1],trc.GetZ(),chi, // trc.Phi(),trc.GetAlpha()); - // printf("Before update at %e %e\n",yz[0],yz[1]); trc.Print(); - if (!trc.Update(yz, errYZ)) { + // printf("Before update at %e %e\n",yz[0],yz[1]); trc.print(); + if (!trc.update(yz, errYZ)) { #if DEBUG > 3 AliWarningF("Failed on Update %f,%f {%f,%f,%f}", yz[0], yz[1], errYZ[0], errYZ[1], errYZ[2]); - trc.Print(); + trc.print(); #endif return kFALSE; } fChi2 += chi; - // printf("After update: (%f) -> %f\n",chi,fChi2); trc.Print(); + // printf("After update: (%f) -> %f\n",chi,fChi2); trc.print(); } } // if (inv) { - // printf("Before inverting back "); trc.Print(); - trc.Invert(); + // printf("Before inverting back "); trc.print(); + trc.invert(); } // return kTRUE; @@ -1212,15 +1221,15 @@ Bool_t AliAlgTrack::ResidKalman() const double kErrSpace = 50.; const double kErrAng = 0.7; const double kErrRelPtI = 1.; - const double kIniErr[15] = {// initial error - kErrSpace * kErrSpace, - 0, kErrSpace * kErrSpace, - 0, 0, kErrAng * kErrAng, - 0, 0, 0, kErrAng * kErrAng, - 0, 0, 0, 0, kErrRelPtI * kErrRelPtI}; + const covMat_t kIniErr = {// initial error + kErrSpace * kErrSpace, + 0, kErrSpace * kErrSpace, + 0, 0, kErrAng * kErrAng, + 0, 0, 0, kErrAng * kErrAng, + 0, 0, 0, 0, kErrRelPtI * kErrRelPtI}; // const Double_t kOverShootX = 5; // - AliExternalTrackParam trc = *this; + trackParam_t trc = *this; // int pID = 0, nPnt = GetNPoints(); ; @@ -1230,19 +1239,19 @@ Bool_t AliAlgTrack::ResidKalman() pID++; if (!pnt) return kFALSE; - double phi = trc.Phi(), alp = pnt->GetAlphaSens(); + double phi = trc.getPhi(), alp = pnt->GetAlphaSens(); BringTo02Pi(phi); BringTo02Pi(alp); double dphi = DeltaPhiSmall(phi, alp); if (dphi > Pi() / 2.) { // need to invert the track to new frame inv = kTRUE; - trc.Invert(); + trc.invert(); } // prepare track seed at 1st valid point - if (!trc.RotateParamOnly(pnt->GetAlphaSens())) { + if (!trc.rotateParam(pnt->GetAlphaSens())) { #if DEBUG > 3 - AliWarningF("Failed on RotateParamOnly to %f", pnt->GetAlphaSens()); - trc.Print(); + AliWarningF("Failed on rotateParam to %f", pnt->GetAlphaSens()); + trc.print(); #endif return kFALSE; } @@ -1250,25 +1259,25 @@ Bool_t AliAlgTrack::ResidKalman() //if (!trc.PropagateParamOnlyTo(pnt->GetXPoint()+kOverShootX,AliTrackerBase::GetBz())) { #if DEBUG > 3 AliWarningF("Failed on PropagateParamOnlyTo to %f", pnt->GetXPoint() + kOverShootX); - trc.Print(); + trc.print(); #endif return kFALSE; } // - double* cov = (double*)trc.GetCovariance(); - memcpy(cov, kIniErr, 15 * sizeof(double)); - cov[14] *= trc.GetSigned1Pt() * trc.GetSigned1Pt(); + trc.setCov(kIniErr); + const double inwardQ2Pt2 = trc.getCovarElem(4, 4) * trc.getQ2Pt() * trc.getQ2Pt(); + trc.setCov(inwardQ2Pt2, 4, 4); // lowest diagonal element (Q2Pt2) // double chifwd = 0, chibwd = 0; // inward fit for (int ip = 0; ip < nPnt; ip++) { pnt = GetPoint(ip); if (pnt->IsInvDir() != inv) { // crossing point where the track should be inverted? - trc.Invert(); + trc.invert(); inv = !inv; } // printf("*** ResidKalm %d (%d %d)\n",ip,0,nPnt); - // printf("Before propagate: "); trc.Print(); + // printf("Before propagate: "); trc.print(); if (!PropagateToPoint(trc, pnt, kMinNStep, kMaxDefStep, kTRUE)) return kFALSE; if (!pnt->ContainsMeasurement()) @@ -1277,35 +1286,36 @@ Bool_t AliAlgTrack::ResidKalman() const double* errYZ = pnt->GetYZErrTracking(); // store track position/errors before update in the point WorkSpace-A double* ws = (double*)pnt->GetTrParamWSA(); - ws[0] = trc.GetY(); - ws[1] = trc.GetZ(); - ws[2] = trc.GetSigmaY2(); - ws[3] = trc.GetSigmaZY(); - ws[4] = trc.GetSigmaZ2(); - double chi = trc.GetPredictedChi2(yz, errYZ); + ws[0] = trc.getY(); + ws[1] = trc.getZ(); + ws[2] = trc.getSigmaY2(); + ws[3] = trc.getSigmaZY(); + ws[4] = trc.getSigmaZ2(); + double chi = trc.getPredictedChi2(yz, errYZ); // printf(">> INV%d (%9d): %+.2e %+.2e | %+.2e %+.2e %+.2e %+.2e %+.2e | %.2e %d \n",ip,pnt->GetSensor()->GetInternalID(),yz[0],yz[1], ws[0],ws[1],ws[2],ws[3],ws[4],chi,inv); - // printf(">>Bef ");trc.Print(); - // printf("KLM Before update at %e %e\n",yz[0],yz[1]); trc.Print(); - if (!trc.Update(yz, errYZ)) { + // printf(">>Bef ");trc.print(); + // printf("KLM Before update at %e %e\n",yz[0],yz[1]); trc.print(); + if (!trc.update(yz, errYZ)) { #if DEBUG > 3 AliWarningF("Failed on Inward Update %f,%f {%f,%f,%f}", yz[0], yz[1], errYZ[0], errYZ[1], errYZ[2]); - trc.Print(); + trc.print(); #endif return kFALSE; } - // printf(">>Aft ");trc.Print(); + // printf(">>Aft ");trc.print(); chifwd += chi; - //printf("KLM After update: (%f) -> %f\n",chi,chifwd); trc.Print(); + //printf("KLM After update: (%f) -> %f\n",chi,chifwd); trc.print(); } // // outward fit - cov = (double*)trc.GetCovariance(); - memcpy(cov, kIniErr, 15 * sizeof(double)); - cov[14] *= trc.GetSigned1Pt() * trc.GetSigned1Pt(); + trc.setCov(kIniErr); + const double outwardQ2Pt2 = trc.getCovarElem(4, 4) * trc.getQ2Pt() * trc.getQ2Pt(); + trc.setCov(outwardQ2Pt2, 4, 4); // lowest diagonal element (Q2Pt2) + for (int ip = nPnt; ip--;) { pnt = GetPoint(ip); if (pnt->IsInvDir() != inv) { // crossing point where the track should be inverted? - trc.Invert(); + trc.invert(); inv = !inv; } if (!PropagateToPoint(trc, pnt, kMinNStep, kMaxDefStep, kTRUE)) @@ -1316,23 +1326,23 @@ Bool_t AliAlgTrack::ResidKalman() const double* errYZ = pnt->GetYZErrTracking(); // store track position/errors before update in the point WorkSpace-B double* ws = (double*)pnt->GetTrParamWSB(); - ws[0] = trc.GetY(); - ws[1] = trc.GetZ(); - ws[2] = trc.GetSigmaY2(); - ws[3] = trc.GetSigmaZY(); - ws[4] = trc.GetSigmaZ2(); - double chi = trc.GetPredictedChi2(yz, errYZ); + ws[0] = trc.getY(); + ws[1] = trc.getZ(); + ws[2] = trc.getSigmaY2(); + ws[3] = trc.getSigmaZY(); + ws[4] = trc.getSigmaZ2(); + double chi = trc.getPredictedChi2(yz, errYZ); // printf("<< OUT%d (%9d): %+.2e %+.2e | %+.2e %+.2e %+.2e %+.2e %+.2e | %.2e %d \n",ip,pnt->GetSensor()->GetInternalID(),yz[0],yz[1], ws[0],ws[1],ws[2],ws[3],ws[4],chi,inv); - // printf("< 3 AliWarningF("Failed on Outward Update %f,%f {%f,%f,%f}", yz[0], yz[1], errYZ[0], errYZ[1], errYZ[2]); - trc.Print(); + trc.print(); #endif return kFALSE; } chibwd += chi; - // printf("< 3 - AliError("Failed to process materials for leg along the track"); + LOG(error) << "Failed to process materials for leg along the track"; #endif return kFALSE; } @@ -1392,10 +1402,10 @@ Bool_t AliAlgTrack::ProcessMaterials() // cosmic upper leg: move againg the track direction from middle point (inner) to last one (outer) trc = *this; if (fNeedInv[1]) - trc.Invert(); // track needs to be inverted ? + trc.invert(); // track needs to be inverted ? if (!ProcessMaterials(trc, GetInnerPointID() + 1, GetNPoints() - 1)) { #if DEBUG > 3 - AliError("Failed to process materials for leg against the track"); + LOG(error) << "Failed to process materials for leg against the track"; #endif return kFALSE; } @@ -1404,7 +1414,7 @@ Bool_t AliAlgTrack::ProcessMaterials() } //______________________________________________ -Bool_t AliAlgTrack::ProcessMaterials(AliExternalTrackParam& trc, int pFrom, int pTo) +Bool_t AliAlgTrack::ProcessMaterials(trackParam_t& trc, int pFrom, int pTo) { // attach material effect info to alignment points const int kMinNStep = 3; @@ -1412,12 +1422,12 @@ Bool_t AliAlgTrack::ProcessMaterials(AliExternalTrackParam& trc, int pFrom, int const double kErrSpcT = 1e-6; const double kErrAngT = 1e-6; const double kErrPtIT = 1e-12; - const double kErrTiny[15] = {// initial tiny error - kErrSpcT * kErrSpcT, - 0, kErrSpcT * kErrSpcT, - 0, 0, kErrAngT * kErrAngT, - 0, 0, 0, kErrAngT * kErrAngT, - 0, 0, 0, 0, kErrPtIT * kErrPtIT}; + const covMat_t kErrTiny = {// initial tiny error + kErrSpcT * kErrSpcT, + 0, kErrSpcT * kErrSpcT, + 0, 0, kErrAngT * kErrAngT, + 0, 0, 0, kErrAngT * kErrAngT, + 0, 0, 0, 0, kErrPtIT * kErrPtIT}; /* const double kErrSpcH = 10.0; const double kErrAngH = 0.5; @@ -1432,9 +1442,11 @@ Bool_t AliAlgTrack::ProcessMaterials(AliExternalTrackParam& trc, int pFrom, int */ // // 2 copies of the track, one will be propagated accounting for materials, other - w/o - AliExternalTrackParam tr0; + trackParam_t tr0; double x2X0xRho[2] = {0, 0}; - double dpar[5] = {0}, dcov[15] = {0}; + double dpar[5] = {0}; + covMat_t dcov{0}; + // int pinc; if (pTo > pFrom) { // fit in points decreasing order: cosmics upper leg @@ -1447,35 +1459,37 @@ Bool_t AliAlgTrack::ProcessMaterials(AliExternalTrackParam& trc, int pFrom, int // for (int ip = pFrom; ip != pTo; ip += pinc) { // points are ordered against track direction AliAlgPoint* pnt = GetPoint(ip); - memcpy((double*)trc.GetCovariance(), kErrTiny, 15 * sizeof(double)); // assign tiny errors to both tracks + trc.setCov(kErrTiny); // assign tiny errors to both tracks tr0 = trc; // // printf("-> ProcMat %d (%d->%d)\n",ip,pFrom,pTo); if (!PropagateToPoint(trc, pnt, kMinNStep, kMaxDefStep, kTRUE, x2X0xRho)) { // with material corrections #if DEBUG > 3 - AliErrorF("Failed to take track to point %d (dir: %d -> %d) with mat.corr.", ip, pFrom, pTo); - trc.Print(); - pnt->Print("meas"); + LOG(error) << "Failed to take track to point" << ip << " (dir: " << pFrom << "->" pTo << ") with mat.corr."; + trc.print(); + pnt->print("meas"); #endif return kFALSE; } // // is there enough material to consider the point as a scatterer? - pnt->SetContainsMaterial(x2X0xRho[0] * Abs(trc.GetSigned1Pt()) > GetMinX2X0Pt2Account()); + pnt->SetContainsMaterial(x2X0xRho[0] * Abs(trc.getQ2Pt()) > GetMinX2X0Pt2Account()); // // printf("-> ProcMat000 %d (%d->%d)\n",ip,pFrom,pTo); if (!PropagateToPoint(tr0, pnt, kMinNStep, kMaxDefStep, kFALSE, 0)) { // no material corrections #if DEBUG > 3 - AliErrorF("Failed to take track to point %d (dir: %d -> %d) w/o mat.corr.", ip, pFrom, pTo); - tr0.Print(); - pnt->Print("meas"); + LOG(error) << "Failed to take track to point" << ip << " (dir: " << pFrom << "->" pTo << ") with mat.corr."; + tr0.print(); + pnt->print("meas"); #endif return kFALSE; } // the difference between the params, covariance of tracks with and w/o material accounting gives // paramets and covariance of material correction. For params ONLY ELoss effect is revealed - double *cov0 = (double*)tr0.GetCovariance(), *par0 = (double*)tr0.GetParameter(); - double *cov1 = (double*)trc.GetCovariance(), *par1 = (double*)trc.GetParameter(); + const covMat_t& cov0 = tr0.getCov(); + double* par0 = (double*)tr0.getParams(); + const covMat_t& cov1 = trc.getCov(); + double* par1 = (double*)trc.getParams(); for (int l = 15; l--;) dcov[l] = cov1[l] - cov0[l]; for (int l = kNKinParBON; l--;) @@ -1497,8 +1511,8 @@ Bool_t AliAlgTrack::ProcessMaterials(AliExternalTrackParam& trc, int pFrom, int const TMatrixD& matEVec = matDiag.GetEigenVectors(); if (!matEVec.IsValid()) { #if DEBUG > 3 - AliError("Failed to diagonalize covariance of material correction"); - matCov.Print(); + LOG(error) << "Failed to diagonalize covariance of material correction"; + matCov.print(); return kFALSE; #endif } @@ -1515,10 +1529,10 @@ Bool_t AliAlgTrack::ProcessMaterials(AliExternalTrackParam& trc, int pFrom, int if (pnt->ContainsMeasurement()) { // update track to have best possible kinematics const double* yz = pnt->GetYZTracking(); const double* errYZ = pnt->GetYZErrTracking(); - if (!trc.Update(yz, errYZ)) { + if (!trc.update(yz, errYZ)) { #if DEBUG > 3 AliWarningF("Failed on Update %f,%f {%f,%f,%f}", yz[0], yz[1], errYZ[0], errYZ[1], errYZ[2]); - trc.Print(); + trc.print(); #endif return kFALSE; } diff --git a/Detectors/Align/src/AlignLinkDef.h b/Detectors/Align/src/AlignLinkDef.h index 819f5e5b94d88..eedd31f907110 100644 --- a/Detectors/Align/src/AlignLinkDef.h +++ b/Detectors/Align/src/AlignLinkDef.h @@ -19,7 +19,7 @@ //#pragma link C++ class o2::align::AliAlgSensTRD + ; //#pragma link C++ class o2::align::AliAlgSensHMPID + ; //#pragma link C++ class o2::align::AliAlgSteer + ; -//#pragma link C++ class o2::align::AliAlgTrack + ; +#pragma link C++ class o2::align::AliAlgTrack + ; #pragma link C++ class o2::align::AliAlgVol + ; //#pragma link C++ class o2::align::AliAlgVtx + ; //#pragma link C++ class o2::align::AliAlgRes + ; From 17c382686b5bce1fc5b75e977c7795bcb10e4431 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Mon, 15 Feb 2021 18:08:50 +0100 Subject: [PATCH 203/770] [ALIGN] port AliAlgVtx --- Detectors/Align/CMakeLists.txt | 4 ++-- Detectors/Align/include/Align/AliAlgVtx.h | 6 +++--- Detectors/Align/src/AliAlgVtx.cxx | 21 +++++++++++---------- Detectors/Align/src/AlignLinkDef.h | 2 +- 4 files changed, 17 insertions(+), 16 deletions(-) diff --git a/Detectors/Align/CMakeLists.txt b/Detectors/Align/CMakeLists.txt index 5cdd7b87f4411..c091678f2968e 100644 --- a/Detectors/Align/CMakeLists.txt +++ b/Detectors/Align/CMakeLists.txt @@ -31,7 +31,7 @@ o2_add_library(Align #src/AliAlgSteer.cxx src/AliAlgTrack.cxx src/AliAlgVol.cxx - #src/AliAlgVtx.cxx + src/AliAlgVtx.cxx #src/Mille.cxx PUBLIC_LINK_LIBRARIES O2::FrameworkLogger O2::ReconstructionDataFormats @@ -64,7 +64,7 @@ o2_target_root_dictionary( #include/Align/AliAlgSteer.h include/Align/AliAlgTrack.h include/Align/AliAlgVol.h - #include/Align/AliAlgVtx.h + include/Align/AliAlgVtx.h #include/Align/AliAlgRes.h #include/Align/AliAlgResFast.h include/Align/AliAlgConstraint.h diff --git a/Detectors/Align/include/Align/AliAlgVtx.h b/Detectors/Align/include/Align/AliAlgVtx.h index 9b221d27638e9..18b27a8c306a9 100644 --- a/Detectors/Align/include/Align/AliAlgVtx.h +++ b/Detectors/Align/include/Align/AliAlgVtx.h @@ -28,8 +28,8 @@ #define ALIALGVTX_H #include "Align/AliAlgSens.h" -class AliTrackPointArray; -class AliESDtrack; +// class AliTrackPointArray; FIXME(milettri): needs AliTrackPointArray +//class AliESDtrack; FIXME(milettri): needs AliESDtrack class AliAlgPoint; namespace o2 @@ -54,7 +54,7 @@ class AliAlgVtx : public AliAlgSens virtual void PrepareMatrixL2GIdeal() { fMatL2GIdeal.Clear(); } // unit matrix virtual void PrepareMatrixT2L(); // - virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); + // virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); FIXME(milettri): needs AliTrackPointArray, AliESDtrack // protected: AliAlgVtx(const AliAlgVtx&); diff --git a/Detectors/Align/src/AliAlgVtx.cxx b/Detectors/Align/src/AliAlgVtx.cxx index 75255f5bb0746..33cb108de5a5c 100644 --- a/Detectors/Align/src/AliAlgVtx.cxx +++ b/Detectors/Align/src/AliAlgVtx.cxx @@ -14,8 +14,8 @@ /// @brief Special fake "sensor" for event vertex. #include "Align/AliAlgVtx.h" -//#include "AliTrackPointArray.h" -//#include "AliESDtrack.h" +//#include "AliTrackPointArray.h" FIXME(milettri): needs AliTrackPointArray +//#include "AliESDtrack.h" FIXME(milettri): needs AliESDtrack #include "Align/AliAlgPoint.h" #include "Align/AliAlgDet.h" #include "Framework/Logger.h" @@ -63,14 +63,15 @@ void AliAlgVtx::ApplyCorrection(double* vtx) const // } -//____________________________________________ -AliAlgPoint* AliAlgVtx::TrackPoint2AlgPoint(int, const AliTrackPointArray*, const AliESDtrack*) -{ - // convert the pntId-th point to AliAlgPoint - static int cnt = 0; - AliErrorF("This method shound not have been called, %d", cnt++); - return 0; -} +//FIXME(milettri): needs AliTrackPointArray, AliESDtrack +////____________________________________________ +//AliAlgPoint* AliAlgVtx::TrackPoint2AlgPoint(int, const AliTrackPointArray*, const AliESDtrack*) +//{ +// // convert the pntId-th point to AliAlgPoint +// static int cnt = 0; +// LOG(ERROR) << "This method shound not have been called," << cnt++; +// return 0; +//} } // namespace align } // namespace o2 diff --git a/Detectors/Align/src/AlignLinkDef.h b/Detectors/Align/src/AlignLinkDef.h index eedd31f907110..209659c922276 100644 --- a/Detectors/Align/src/AlignLinkDef.h +++ b/Detectors/Align/src/AlignLinkDef.h @@ -21,7 +21,7 @@ //#pragma link C++ class o2::align::AliAlgSteer + ; #pragma link C++ class o2::align::AliAlgTrack + ; #pragma link C++ class o2::align::AliAlgVol + ; -//#pragma link C++ class o2::align::AliAlgVtx + ; +#pragma link C++ class o2::align::AliAlgVtx + ; //#pragma link C++ class o2::align::AliAlgRes + ; //#pragma link C++ class o2::align::AliAlgResFast + ; #pragma link C++ class o2::align::AliAlgConstraint + ; From 493aea1f37e18b8d2bce3f7d47ef69e0b28e1a56 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Mon, 15 Feb 2021 18:30:44 +0100 Subject: [PATCH 204/770] [ALIGN] port AliAlgRes --- Detectors/Align/CMakeLists.txt | 4 ++-- Detectors/Align/include/Align/AliAlgRes.h | 3 ++- Detectors/Align/src/AliAlgRes.cxx | 7 +++---- Detectors/Align/src/AlignLinkDef.h | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Detectors/Align/CMakeLists.txt b/Detectors/Align/CMakeLists.txt index c091678f2968e..03d1cc4056566 100644 --- a/Detectors/Align/CMakeLists.txt +++ b/Detectors/Align/CMakeLists.txt @@ -20,7 +20,7 @@ o2_add_library(Align src/AliAlgDOFStat.cxx #src/AliAlgMPRecord.cxx src/AliAlgPoint.cxx - #src/AliAlgRes.cxx + src/AliAlgRes.cxx #src/AliAlgResFast.cxx src/AliAlgSens.cxx #src/AliAlgSensHMPID.cxx @@ -65,7 +65,7 @@ o2_target_root_dictionary( include/Align/AliAlgTrack.h include/Align/AliAlgVol.h include/Align/AliAlgVtx.h - #include/Align/AliAlgRes.h + include/Align/AliAlgRes.h #include/Align/AliAlgResFast.h include/Align/AliAlgConstraint.h include/Align/AliAlgDOFStat.h diff --git a/Detectors/Align/include/Align/AliAlgRes.h b/Detectors/Align/include/Align/AliAlgRes.h index e01a43862d230..7222125621097 100644 --- a/Detectors/Align/include/Align/AliAlgRes.h +++ b/Detectors/Align/include/Align/AliAlgRes.h @@ -18,13 +18,14 @@ #include #include -class AliAlgTrack; namespace o2 { namespace align { +class AliAlgTrack; + class AliAlgRes : public TObject { public: diff --git a/Detectors/Align/src/AliAlgRes.cxx b/Detectors/Align/src/AliAlgRes.cxx index 315dc521674db..e49409bf3fad5 100644 --- a/Detectors/Align/src/AliAlgRes.cxx +++ b/Detectors/Align/src/AliAlgRes.cxx @@ -206,7 +206,7 @@ Bool_t AliAlgRes::FillTrack(AliAlgTrack* trc, Bool_t doKalman) SetCosmic(trc->IsCosmic()); // SetNPoints(nps); - fQ2Pt = trc->GetSigned1Pt(); + fQ2Pt = trc->getQ2Pt(); fChi2 = trc->GetChi2(); fChi2Ini = trc->GetChi2Ini(); int nfill = 0; @@ -236,7 +236,7 @@ Bool_t AliAlgRes::FillTrack(AliAlgTrack* trc, Bool_t doKalman) } if (nfill != nps) { trc->Print("p"); - AliFatalF("Something is wrong: %d residuals were stored instead of %d", nfill, nps); + LOG(FATAL) << nfill << " residuals were stored instead of " << nps; } // SetKalmanDone(kFALSE); @@ -247,8 +247,7 @@ Bool_t AliAlgRes::FillTrack(AliAlgTrack* trc, Bool_t doKalman) if (!pnt->ContainsMeasurement()) continue; if (fVolID[nfilk] != int(pnt->GetVolID())) { - AliFatalF("Mismatch in Kalman filling for point %d: filled VID:%d, point VID:%d", - i, fVolID[nfilk], pnt->GetVolID()); + LOG(FATAL) << "Mismatch in Kalman filling for point " << i << ": filled VID:" << fVolID[nfilk] << ", point VID:" << pnt->GetVolID(); } const double* wsA = pnt->GetTrParamWSA(); fDYK[nfilk] = pnt->GetResidY(); diff --git a/Detectors/Align/src/AlignLinkDef.h b/Detectors/Align/src/AlignLinkDef.h index 209659c922276..087dd13e840f0 100644 --- a/Detectors/Align/src/AlignLinkDef.h +++ b/Detectors/Align/src/AlignLinkDef.h @@ -22,7 +22,7 @@ #pragma link C++ class o2::align::AliAlgTrack + ; #pragma link C++ class o2::align::AliAlgVol + ; #pragma link C++ class o2::align::AliAlgVtx + ; -//#pragma link C++ class o2::align::AliAlgRes + ; +#pragma link C++ class o2::align::AliAlgRes + ; //#pragma link C++ class o2::align::AliAlgResFast + ; #pragma link C++ class o2::align::AliAlgConstraint + ; #pragma link C++ class o2::align::AliAlgDOFStat + ; From 5caee2139da33237bb8ece0eb268af11873f985c Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Mon, 15 Feb 2021 20:34:07 +0100 Subject: [PATCH 205/770] [ALIGN] port AliAlgResFast --- Detectors/Align/CMakeLists.txt | 4 ++-- Detectors/Align/src/AlignLinkDef.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Detectors/Align/CMakeLists.txt b/Detectors/Align/CMakeLists.txt index 03d1cc4056566..5eb530377bbb4 100644 --- a/Detectors/Align/CMakeLists.txt +++ b/Detectors/Align/CMakeLists.txt @@ -21,7 +21,7 @@ o2_add_library(Align #src/AliAlgMPRecord.cxx src/AliAlgPoint.cxx src/AliAlgRes.cxx - #src/AliAlgResFast.cxx + src/AliAlgResFast.cxx src/AliAlgSens.cxx #src/AliAlgSensHMPID.cxx #src/AliAlgSensITS.cxx @@ -66,7 +66,7 @@ o2_target_root_dictionary( include/Align/AliAlgVol.h include/Align/AliAlgVtx.h include/Align/AliAlgRes.h - #include/Align/AliAlgResFast.h + include/Align/AliAlgResFast.h include/Align/AliAlgConstraint.h include/Align/AliAlgDOFStat.h include/Align/AliAlgAux.h diff --git a/Detectors/Align/src/AlignLinkDef.h b/Detectors/Align/src/AlignLinkDef.h index 087dd13e840f0..fc50addefe8cc 100644 --- a/Detectors/Align/src/AlignLinkDef.h +++ b/Detectors/Align/src/AlignLinkDef.h @@ -23,7 +23,7 @@ #pragma link C++ class o2::align::AliAlgVol + ; #pragma link C++ class o2::align::AliAlgVtx + ; #pragma link C++ class o2::align::AliAlgRes + ; -//#pragma link C++ class o2::align::AliAlgResFast + ; +#pragma link C++ class o2::align::AliAlgResFast + ; #pragma link C++ class o2::align::AliAlgConstraint + ; #pragma link C++ class o2::align::AliAlgDOFStat + ; #pragma link C++ class o2::align::AliAlgAux; From b8c736e388eec7982b02533e2b65944ad21d4def Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Mon, 15 Feb 2021 20:40:25 +0100 Subject: [PATCH 206/770] [ALIGN] port AliAlgMPRecord --- Detectors/Align/CMakeLists.txt | 4 ++-- Detectors/Align/include/Align/AliAlgMPRecord.h | 3 ++- Detectors/Align/src/AliAlgMPRecord.cxx | 8 ++++---- Detectors/Align/src/AlignLinkDef.h | 2 +- 4 files changed, 9 insertions(+), 8 deletions(-) diff --git a/Detectors/Align/CMakeLists.txt b/Detectors/Align/CMakeLists.txt index 5eb530377bbb4..14d02ce688f4f 100644 --- a/Detectors/Align/CMakeLists.txt +++ b/Detectors/Align/CMakeLists.txt @@ -18,7 +18,7 @@ o2_add_library(Align #src/AliAlgDetTPC.cxx #src/AliAlgDetTRD.cxx src/AliAlgDOFStat.cxx - #src/AliAlgMPRecord.cxx + src/AliAlgMPRecord.cxx src/AliAlgPoint.cxx src/AliAlgRes.cxx src/AliAlgResFast.cxx @@ -53,7 +53,7 @@ o2_target_root_dictionary( #include/Align/AliAlgDetTPC.h #include/Align/AliAlgDetTRD.h #include/Align/AliAlgDetHMPID.h - #include/Align/AliAlgMPRecord.h + include/Align/AliAlgMPRecord.h include/Align/AliAlgPoint.h include/Align/AliAlgSens.h #include/Align/AliAlgSensITS.h diff --git a/Detectors/Align/include/Align/AliAlgMPRecord.h b/Detectors/Align/include/Align/AliAlgMPRecord.h index ec534c9bc8a9f..6a81028a21481 100644 --- a/Detectors/Align/include/Align/AliAlgMPRecord.h +++ b/Detectors/Align/include/Align/AliAlgMPRecord.h @@ -17,13 +17,14 @@ #define ALIALGMPRECORD_H #include -class AliAlgTrack; namespace o2 { namespace align { +class AliAlgTrack; + class AliAlgMPRecord : public TObject { public: diff --git a/Detectors/Align/src/AliAlgMPRecord.cxx b/Detectors/Align/src/AliAlgMPRecord.cxx index 9eff33352dca9..7de50b4bb35d7 100644 --- a/Detectors/Align/src/AliAlgMPRecord.cxx +++ b/Detectors/Align/src/AliAlgMPRecord.cxx @@ -87,7 +87,7 @@ Bool_t AliAlgMPRecord::FillTrack(const AliAlgTrack* trc, const Int_t* id2Lab) // fill track info, optionally substitutind glopar par ID by label // if (!trc->GetDerivDone()) { - AliError("Track derivatives are not yet evaluated"); + LOG(ERROR) << "Track derivatives are not yet evaluated"; return kFALSE; } fNVarLoc = trc->GetNLocPar(); // number of local degrees of freedom in the track @@ -95,8 +95,8 @@ Bool_t AliAlgMPRecord::FillTrack(const AliAlgTrack* trc, const Int_t* id2Lab) fNDLocTot = 0; fNDGloTot = 0; fChi2Ini = trc->GetChi2Ini(); - fQ2Pt = trc->GetSigned1Pt(); - fTgl = trc->GetTgl(); + fQ2Pt = trc->getQ2Pt(); + fTgl = trc->getTgl(); fNMeas = 0; SetCosmic(trc->IsCosmic()); // 1) check sizes for buffers, expand if needed @@ -202,7 +202,7 @@ Bool_t AliAlgMPRecord::FillTrack(const AliAlgTrack* trc, const Int_t* id2Lab) } // if (!fNDGloTot) { - AliInfo("Track does not depend on free global parameters, discard"); + LOG(INFO) << "Track does not depend on free global parameters, discard"; return kFALSE; } return kTRUE; diff --git a/Detectors/Align/src/AlignLinkDef.h b/Detectors/Align/src/AlignLinkDef.h index fc50addefe8cc..6fa11704e0baf 100644 --- a/Detectors/Align/src/AlignLinkDef.h +++ b/Detectors/Align/src/AlignLinkDef.h @@ -10,7 +10,7 @@ //#pragma link C++ class o2::align::AliAlgDetTPC + ; //#pragma link C++ class o2::align::AliAlgDetTRD + ; //#pragma link C++ class o2::align::AliAlgDetHMPID + ; -//#pragma link C++ class o2::align::AliAlgMPRecord + ; +#pragma link C++ class o2::align::AliAlgMPRecord + ; #pragma link C++ class o2::align::AliAlgPoint + ; #pragma link C++ class o2::align::AliAlgSens + ; //#pragma link C++ class o2::align::AliAlgSensITS + ; From 2a85bacf0bf64d2a4913ac4438dcc8eba76c6110 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Mon, 15 Feb 2021 20:44:27 +0100 Subject: [PATCH 207/770] [ALIGN] port Mille --- Detectors/Align/CMakeLists.txt | 2 +- Detectors/Align/src/Mille.cxx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Detectors/Align/CMakeLists.txt b/Detectors/Align/CMakeLists.txt index 14d02ce688f4f..9b56f8483fd6b 100644 --- a/Detectors/Align/CMakeLists.txt +++ b/Detectors/Align/CMakeLists.txt @@ -32,7 +32,7 @@ o2_add_library(Align src/AliAlgTrack.cxx src/AliAlgVol.cxx src/AliAlgVtx.cxx - #src/Mille.cxx + src/Mille.cxx PUBLIC_LINK_LIBRARIES O2::FrameworkLogger O2::ReconstructionDataFormats ROOT::Core diff --git a/Detectors/Align/src/Mille.cxx b/Detectors/Align/src/Mille.cxx index 18c25065cf642..b34d9b48590ef 100644 --- a/Detectors/Align/src/Mille.cxx +++ b/Detectors/Align/src/Mille.cxx @@ -19,7 +19,7 @@ jeudi 30 avril 2015: added automatic buffer expansion */ -#include "Mille.h" +#include "Align/Mille.h" #include #include From ca1c2e6d5e7c96903fbe53bff22c9697e171527a Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Mon, 15 Feb 2021 22:35:50 +0100 Subject: [PATCH 208/770] [ALIGN] port AliAlgSteer --- Detectors/Align/CMakeLists.txt | 4 +- Detectors/Align/include/Align/AliAlgDOFStat.h | 6 +- Detectors/Align/include/Align/AliAlgDet.h | 8 +- Detectors/Align/include/Align/AliAlgSteer.h | 75 +- Detectors/Align/src/AliAlgDOFStat.cxx | 31 +- Detectors/Align/src/AliAlgDet.cxx | 122 +- Detectors/Align/src/AliAlgSteer.cxx | 2066 +++++++++-------- Detectors/Align/src/AlignLinkDef.h | 2 +- 8 files changed, 1165 insertions(+), 1149 deletions(-) diff --git a/Detectors/Align/CMakeLists.txt b/Detectors/Align/CMakeLists.txt index 9b56f8483fd6b..6d3279f448fea 100644 --- a/Detectors/Align/CMakeLists.txt +++ b/Detectors/Align/CMakeLists.txt @@ -28,7 +28,7 @@ o2_add_library(Align #src/AliAlgSensTOF.cxx #src/AliAlgSensTPC.cxx #src/AliAlgSensTRD.cxx - #src/AliAlgSteer.cxx + src/AliAlgSteer.cxx src/AliAlgTrack.cxx src/AliAlgVol.cxx src/AliAlgVtx.cxx @@ -61,7 +61,7 @@ o2_target_root_dictionary( #include/Align/AliAlgSensTPC.h #include/Align/AliAlgSensTRD.h #include/Align/AliAlgSensHMPID.h - #include/Align/AliAlgSteer.h + include/Align/AliAlgSteer.h include/Align/AliAlgTrack.h include/Align/AliAlgVol.h include/Align/AliAlgVtx.h diff --git a/Detectors/Align/include/Align/AliAlgDOFStat.h b/Detectors/Align/include/Align/AliAlgDOFStat.h index 1339eb10e4849..ce29aba8d2fb3 100644 --- a/Detectors/Align/include/Align/AliAlgDOFStat.h +++ b/Detectors/Align/include/Align/AliAlgDOFStat.h @@ -17,7 +17,6 @@ #define ALIALGDOFSTAT_H #include -//class AliAlgSteer; class TH1F; class TCollection; @@ -26,6 +25,8 @@ namespace o2 namespace align { +class AliAlgSteer; + class AliAlgDOFStat : public TNamed { public: @@ -38,8 +39,7 @@ class AliAlgDOFStat : public TNamed void SetStat(int idf, int v) { fStat[idf] = v; } void AddStat(int idf, int v) { fStat[idf] += v; } Int_t GetNMerges() const { return fNMerges; } - // FIXME(milettri): needs AliAlgSteer - // TH1F* CreateHisto(AliAlgSteer* st) const; + TH1F* CreateHisto(AliAlgSteer* st) const; virtual void Print(Option_t* opt) const; virtual Long64_t Merge(TCollection* list); // diff --git a/Detectors/Align/include/Align/AliAlgDet.h b/Detectors/Align/include/Align/AliAlgDet.h index ec740b52ee1b1..e5ad1ccbbc8f9 100644 --- a/Detectors/Align/include/Align/AliAlgDet.h +++ b/Detectors/Align/include/Align/AliAlgDet.h @@ -25,7 +25,7 @@ #include "Align/AliAlgPoint.h" #include "Align/AliAlgSens.h" #include "Align/AliAlgVol.h" -//#include "Align/AliAlgSteer.h" FIXME(milettri): needs AliAlgSteer +#include "Align/AliAlgSteer.h" //#include "AliESDtrack.h" //class AliTrackPointArray; @@ -66,7 +66,7 @@ class AliAlgDet : public TNamed // Int_t GetNPoints() const { return fNPoints; } // - // void SetAlgSteer(AliAlgSteer* s) { fAlgSteer = s; } FIXME(milettri): needs AliAlgSteer + void SetAlgSteer(AliAlgSteer* s) { fAlgSteer = s; } AliAlgSens* GetSensor(Int_t id) const { return (AliAlgSens*)fSensors.UncheckedAt(id); } AliAlgSens* GetSensorByVolId(Int_t vid) const { @@ -232,8 +232,8 @@ class AliAlgDet : public TNamed Int_t fPoolNPoints; //! number of points in the pool Int_t fPoolFreePointID; //! id of the last free point in the pool TObjArray fPointsPool; //! pool of aligment points - // - // AliAlgSteer* fAlgSteer; // pointer to alignment steering object FIXME(milettri): needs AliAlgSteer + // + AliAlgSteer* fAlgSteer; // pointer to alignment steering object // ClassDef(AliAlgDet, 1); // base class for detector global alignment }; diff --git a/Detectors/Align/include/Align/AliAlgSteer.h b/Detectors/Align/include/Align/AliAlgSteer.h index 4387adcaf9151..4af107730681c 100644 --- a/Detectors/Align/include/Align/AliAlgSteer.h +++ b/Detectors/Align/include/Align/AliAlgSteer.h @@ -21,9 +21,9 @@ #ifndef ALIALGSTEER_H #define ALIALGSTEER_H -// #include "AliGeomManager.h" +// #include "AliGeomManager.h" FIXME(milettri): needs AliGeomManager #include "Align/AliAlgTrack.h" -// #include "AliSymMatrix.h" +// #include "AliSymMatrix.h" FIXME(milettri): needs AliSymMatrix #include #include @@ -34,10 +34,22 @@ #include #include "Align/AliAlgAux.h" -//class AliESDEvent; -//class AliESDtrack; -//class AliESDCosmicTrack; -//class AliESDVertex; +//class AliESDEvent; FIXME(milettri): needs AliESDEvent +//class AliESDtrack; FIXME(milettri): needs AliESDtrack +//class AliESDCosmicTrack; FIXME(milettri): needs AliESDCosmicTrack +//class AliESDVertex; FIXME(milettri): needs AliESDVertex + +class TTree; +class TFile; +// + +namespace o2 +{ +namespace align +{ + +class Mille; + class AliAlgDet; class AliAlgVol; class AliAlgVtx; @@ -47,15 +59,6 @@ class AliAlgRes; class AliAlgResFast; class AliAlgConstraint; class AliAlgDOFStat; -class TTree; -class TFile; -// -class Mille; - -namespace o2 -{ -namespace align -{ class AliAlgSteer : public TObject { @@ -117,8 +120,8 @@ class AliAlgSteer : public TObject // AliAlgSteer(const char* configMacro = 0, int refRun = -1); virtual ~AliAlgSteer(); - Bool_t LoadRefOCDB(); - Bool_t LoadRecoTimeOCDB(); + // Bool_t LoadRefOCDB(); FIXME(milettri): needs OCDB + // Bool_t LoadRecoTimeOCDB(); FIXME(milettri): needs OCDB Bool_t GetUseRecoOCDB() const { return fUseRecoOCDB; } void SetUseRecoOCDB(Bool_t v = kTRUE) { fUseRecoOCDB = v; } @@ -161,10 +164,10 @@ class AliAlgSteer : public TObject // void SetESDTree(const TTree* tr) { fESDTree = tr; } const TTree* GetESDTree() const { return fESDTree; } - void SetESDEvent(const AliESDEvent* ev); - const AliESDEvent* GetESDEvent() const { return fESDEvent; } - void SetESDtrack(const AliESDtrack* tr, int i = 0) { fESDTrack[i] = tr; } - const AliESDtrack* GetESDtrack(int i = 0) const { return fESDTrack[i]; } + // void SetESDEvent(const AliESDEvent* ev); FIXME(milettri): needs AliESDEvent + // const AliESDEvent* GetESDEvent() const { return fESDEvent; } FIXME(milettri): needs AliESDEvent + // void SetESDtrack(const AliESDtrack* tr, int i = 0) { fESDTrack[i] = tr; } FIXME(milettri): needs AliESDtrack + // const AliESDtrack* GetESDtrack(int i = 0) const { return fESDTrack[i]; } FIXME(milettri): needs AliESDtrack // // Track selection void SetCosmicSelStrict(Bool_t v = kTRUE) { fCosmicSelStrict = v; } @@ -226,8 +229,8 @@ class AliAlgSteer : public TObject void SetEventSpeciiSelection(UInt_t sel) { fSelEventSpecii = sel; } UInt_t GetEventSpeciiSelection() const { return fSelEventSpecii; } // - void SetVertex(const AliESDVertex* v) { fVertex = v; } - const AliESDVertex* GetVertex() const { return fVertex; } + // void SetVertex(const AliESDVertex* v) { fVertex = v; } FIXME(milettri): needs AliESDVertex + // const AliESDVertex* GetVertex() const { return fVertex; } FIXME(milettri): needs AliESDVertex // //---------------------------------------- Bool_t ReadParameters(const char* parfile = "millepede.res", Bool_t useErrors = kTRUE); @@ -246,12 +249,12 @@ class AliAlgSteer : public TObject AliAlgMPRecord* GetMPRecord() const { return (AliAlgMPRecord*)fMPRecord; } TTree* GetMPRecTree() const { return fMPRecTree; } AliAlgTrack* GetAlgTrack() const { return (AliAlgTrack*)fAlgTrack; } - Bool_t ProcessEvent(const AliESDEvent* esdEv); - Bool_t ProcessTrack(const AliESDtrack* esdTr); - Bool_t ProcessTrack(const AliESDCosmicTrack* esdCTr); - UInt_t AcceptTrack(const AliESDtrack* esdTr, Bool_t strict = kTRUE) const; - UInt_t AcceptTrackCosmic(const AliESDtrack* esdPairCosm[kNCosmLegs]) const; - Bool_t CheckSetVertex(const AliESDVertex* vtx); + // Bool_t ProcessEvent(const AliESDEvent* esdEv); FIXME(milettri): needs AliESDEvent + // Bool_t ProcessTrack(const AliESDtrack* esdTr); FIXME(milettri): needs AliESDtrack + // Bool_t ProcessTrack(const AliESDCosmicTrack* esdCTr); FIXME(milettri): needs AliESDCosmicTrack + // UInt_t AcceptTrack(const AliESDtrack* esdTr, Bool_t strict = kTRUE) const; FIXME(milettri): needs AliESDtrack + // UInt_t AcceptTrackCosmic(const AliESDtrack* esdPairCosm[kNCosmLegs]) const; FIXME(milettri): needs AliESDtrack + // Bool_t CheckSetVertex(const AliESDVertex* vtx); FIXME(milettri): needs AliESDVertex Bool_t AddVertexConstraint(); Int_t GetNDetectors() const { return fNDet; } AliAlgDet* GetDetector(Int_t i) const { return fDetectors[i]; } @@ -273,13 +276,13 @@ class AliAlgSteer : public TObject void SetOutCDBPath(const char* name = "local://outOCDB"); void SetOutCDBComment(const char* cm = 0) { fOutCDBComment = cm; } void SetOutCDBResponsible(const char* v = 0) { fOutCDBResponsible = v; } - void SetOutCDBRunRange(int rmin = 0, int rmax = 999999999); + // void SetOutCDBRunRange(int rmin = 0, int rmax = 999999999); FIXME(milettri): needs OCDB Int_t* GetOutCDBRunRange() const { return (int*)fOutCDBRunRange; } Int_t GetOutCDBRunMin() const { return fOutCDBRunRange[0]; } Int_t GetOutCDBRunMax() const { return fOutCDBRunRange[1]; } Float_t GetControlFrac() const { return fControlFrac; } void SetControlFrac(float v = 1.) { fControlFrac = v; } - void WriteCalibrationResults() const; + // void WriteCalibrationResults() const; FIXME(milettri): needs OCDB void ApplyAlignmentFromMPSol(); const char* GetOutCDBComment() const { return fOutCDBComment.Data(); } const char* GetOutCDBResponsible() const { return fOutCDBResponsible.Data(); } @@ -365,7 +368,7 @@ class AliAlgSteer : public TObject static void MPRec2Mille(const char* mprecfile, const char* millefile = "mpData.mille", Bool_t bindata = kTRUE); static void MPRec2Mille(TTree* mprTree, const char* millefile = "mpData.mille", Bool_t bindata = kTRUE); // - AliSymMatrix* BuildMatrix(TVectorD& vec); + // AliSymMatrix* BuildMatrix(TVectorD& vec); FIXME(milettri): needs AliSymMatrix Bool_t TestLocalSolution(); // // fast check of solution using derivatives @@ -418,10 +421,10 @@ class AliAlgSteer : public TObject // AliAlgPoint* fRefPoint; // reference point for track definition // - const TTree* fESDTree; //! externally set esdTree, needed to access UserInfo list - const AliESDEvent* fESDEvent; //! externally set event - const AliESDtrack* fESDTrack[kNCosmLegs]; //! externally set ESD tracks - const AliESDVertex* fVertex; //! event vertex + const TTree* fESDTree; //! externally set esdTree, needed to access UserInfo list + // const AliESDEvent* fESDEvent; //! externally set event FIXME(milettri): needs AliESDEvent + // const AliESDtrack* fESDTrack[kNCosmLegs]; //! externally set ESD tracks FIXME(milettri): needs AliESDtrack + // const AliESDVertex* fVertex; //! event vertex FIXME(milettri): needs AliESDVertex // // statistics Float_t fStat[kNStatCl][kMaxStat]; // processing statistics diff --git a/Detectors/Align/src/AliAlgDOFStat.cxx b/Detectors/Align/src/AliAlgDOFStat.cxx index 311cd1313fde4..d805e78f8ca29 100644 --- a/Detectors/Align/src/AliAlgDOFStat.cxx +++ b/Detectors/Align/src/AliAlgDOFStat.cxx @@ -14,7 +14,7 @@ /// @brief Mergable bbject for statistics of points used by each DOF #include "Align/AliAlgDOFStat.h" -//#include "Align/AliAlgSteer.h" FIXME(milettri): needs AliAlgSteer +#include "Align/AliAlgSteer.h" #include "Framework/Logger.h" #include #include @@ -55,21 +55,20 @@ void AliAlgDOFStat::Print(Option_t*) const // } -//FIXME(milettri): needs AliAlgSteer -////____________________________________________ -//TH1F* AliAlgDOFStat::CreateHisto(AliAlgSteer* st) const -//{ -// // create histo with stat. If steer object is supplied, build labels -// if (!fNDOFs) -// return 0; -// TH1F* h = new TH1F("DOFstat", "statistics per DOF", fNDOFs, 0, fNDOFs); -// for (int i = fNDOFs; i--;) { -// h->SetBinContent(i + 1, fStat[i]); -// if (st) -// h->GetXaxis()->SetBinLabel(i + 1, st->GetDOFLabelTxt(i)); -// } -// return h; -//} +//____________________________________________ +TH1F* AliAlgDOFStat::CreateHisto(AliAlgSteer* st) const +{ + // create histo with stat. If steer object is supplied, build labels + if (!fNDOFs) + return 0; + TH1F* h = new TH1F("DOFstat", "statistics per DOF", fNDOFs, 0, fNDOFs); + for (int i = fNDOFs; i--;) { + h->SetBinContent(i + 1, fStat[i]); + if (st) + h->GetXaxis()->SetBinLabel(i + 1, st->GetDOFLabelTxt(i)); + } + return h; +} //______________________________________________________________________________ Long64_t AliAlgDOFStat::Merge(TCollection* list) diff --git a/Detectors/Align/src/AliAlgDet.cxx b/Detectors/Align/src/AliAlgDet.cxx index 6f2038a8ec129..68023f2b25920 100644 --- a/Detectors/Align/src/AliAlgDet.cxx +++ b/Detectors/Align/src/AliAlgDet.cxx @@ -16,7 +16,7 @@ #include "Align/AliAlgDet.h" #include "Align/AliAlgSens.h" #include "Align/AliAlgDet.h" -//#include "Align/AliAlgSteer.h" FIXME(milettri): needs AliAlgSteer +#include "Align/AliAlgSteer.h" #include "Align/AliAlgTrack.h" #include "Align/AliAlgDOFStat.h" #include "Align/AliAlgConstraint.h" @@ -66,11 +66,11 @@ AliAlgDet::AliAlgDet() fNPoints(0), fPoolNPoints(0), fPoolFreePointID(0), - fPointsPool() //, -// fAlgSteer(0) FIXME(milettri): needs AliAlgSteer + fPointsPool(), + fAlgSteer(0) { // def c-tor - // SetUniqueID(AliAlgSteer::kUndefined); // derived detectors must override this FIXME(milettri): needs AliAlgSteer; + SetUniqueID(AliAlgSteer::kUndefined); // derived detectors must override this SetUniqueID(6); fAddError[0] = fAddError[1] = 0; // @@ -313,34 +313,32 @@ Int_t AliAlgDet::InitGeom() //_________________________________________________________ Int_t AliAlgDet::AssignDOFs() { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; - //FIXME(milettri): needs AliAlgSteer - // // assign DOFs IDs, parameters - // // - // int gloCount0(fAlgSteer->GetNDOFs()), gloCount(fAlgSteer->GetNDOFs()); - // Float_t* pars = fAlgSteer->GetGloParVal(); - // Float_t* errs = fAlgSteer->GetGloParErr(); - // Int_t* labs = fAlgSteer->GetGloParLab(); - // // - // // assign calibration DOFs - // fFirstParGloID = gloCount; - // fParVals = pars + gloCount; - // fParErrs = errs + gloCount; - // fParLabs = labs + gloCount; - // for (int icl = 0; icl < fNCalibDOF; icl++) { - // fParLabs[icl] = (GetDetLabel() + 10000) * 100 + icl; - // gloCount++; - // } - // // - // int nvol = GetNVolumes(); - // for (int iv = 0; iv < nvol; iv++) { - // AliAlgVol* vol = GetVolume(iv); - // // call init for root level volumes, they will take care of their children - // if (!vol->GetParent()) - // vol->AssignDOFs(gloCount, pars, errs, labs); - // } - // if (fNDOFs != gloCount - gloCount0) - // LOG(FATAL) << "Mismatch between declared " << fNDOFs << " and initialized " << (gloCount - gloCount0) << " DOFs for " << GetName(); + // assign DOFs IDs, parameters + // + int gloCount0(fAlgSteer->GetNDOFs()), gloCount(fAlgSteer->GetNDOFs()); + Float_t* pars = fAlgSteer->GetGloParVal(); + Float_t* errs = fAlgSteer->GetGloParErr(); + Int_t* labs = fAlgSteer->GetGloParLab(); + // + // assign calibration DOFs + fFirstParGloID = gloCount; + fParVals = pars + gloCount; + fParErrs = errs + gloCount; + fParLabs = labs + gloCount; + for (int icl = 0; icl < fNCalibDOF; icl++) { + fParLabs[icl] = (GetDetLabel() + 10000) * 100 + icl; + gloCount++; + } + // + int nvol = GetNVolumes(); + for (int iv = 0; iv < nvol; iv++) { + AliAlgVol* vol = GetVolume(iv); + // call init for root level volumes, they will take care of their children + if (!vol->GetParent()) + vol->AssignDOFs(gloCount, pars, errs, labs); + } + if (fNDOFs != gloCount - gloCount0) + LOG(FATAL) << "Mismatch between declared " << fNDOFs << " and initialized " << (gloCount - gloCount0) << " DOFs for " << GetName(); return fNDOFs; } @@ -424,9 +422,8 @@ void AliAlgDet::Print(const Option_t* opt) const void AliAlgDet::SetDetID(UInt_t tp) { // assign type - //FIXME(milettri): needs AliAlgSteer - // if (tp >= AliAlgSteer::kNDetectors) - // LOG(FATAL) << "Detector typeID " << tp << "exceeds allowed range" << 0 << ":" << (AliAlgSteer::kNDetectors - 1); + if (tp >= AliAlgSteer::kNDetectors) + LOG(FATAL) << "Detector typeID " << tp << "exceeds allowed range" << 0 << ":" << (AliAlgSteer::kNDetectors - 1); if (tp >= 5) LOG(FATAL) << "Detector typeID " << tp << "exceeds allowed range" << 0 << ":" << (5 - 1); SetUniqueID(tp); @@ -462,11 +459,9 @@ void AliAlgDet::UpdatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) //____________________________________________ void AliAlgDet::SetObligatory(Int_t tp, Bool_t v) { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; - //FIXME(lettrich): needs AliAlgSteer - // // mark detector presence obligatory in the track - // fObligatory[tp] = v; - // fAlgSteer->SetObligatoryDetector(GetDetID(), tp, v); + // mark detector presence obligatory in the track + fObligatory[tp] = v; + fAlgSteer->SetObligatoryDetector(GetDetID(), tp, v); } //______________________________________________________ @@ -554,34 +549,30 @@ AliAlgVol* AliAlgDet::GetVolOfDOFID(Int_t id) const //______________________________________________________ void AliAlgDet::Terminate() { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; - //FIXME(lettrich): needs AliAlgSteer - // // called at the end of processing - // // if (IsDisabled()) return; - // int nvol = GetNVolumes(); - // fNProcPoints = 0; - // AliAlgDOFStat* st = fAlgSteer->GetDOFStat(); - // for (int iv = 0; iv < nvol; iv++) { - // AliAlgVol* vol = GetVolume(iv); - // // call init for root level volumes, they will take care of their children - // if (!vol->GetParent()) - // fNProcPoints += vol->FinalizeStat(st); - // } - // FillDOFStat(st); // fill stat for calib dofs + // called at the end of processing + // if (IsDisabled()) return; + int nvol = GetNVolumes(); + fNProcPoints = 0; + AliAlgDOFStat* st = fAlgSteer->GetDOFStat(); + for (int iv = 0; iv < nvol; iv++) { + AliAlgVol* vol = GetVolume(iv); + // call init for root level volumes, they will take care of their children + if (!vol->GetParent()) + fNProcPoints += vol->FinalizeStat(st); + } + FillDOFStat(st); // fill stat for calib dofs } //________________________________________ void AliAlgDet::AddAutoConstraints() const { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; - //FIXME(lettrich): needs AliAlgSteer - // // adds automatic constraints - // int nvol = GetNVolumes(); - // for (int iv = 0; iv < nvol; iv++) { // call for root level volumes, they will take care of their children - // AliAlgVol* vol = GetVolume(iv); - // if (!vol->GetParent()) - // vol->AddAutoConstraints((TObjArray*)fAlgSteer->GetConstraints()); - //} + // adds automatic constraints + int nvol = GetNVolumes(); + for (int iv = 0; iv < nvol; iv++) { // call for root level volumes, they will take care of their children + AliAlgVol* vol = GetVolume(iv); + if (!vol->GetParent()) + vol->AddAutoConstraints((TObjArray*)fAlgSteer->GetConstraints()); + } } //________________________________________ @@ -690,11 +681,8 @@ void AliAlgDet::ConstrainOrphans(const double* sigma, const char* match) LOG(INFO) << "No volume passed filter " << match; delete constr; } else { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; - //FIXME(lettrich): needs AliAlgSteer - // ((TObjArray*)fAlgSteer->GetConstraints())->Add(constr); + ((TObjArray*)fAlgSteer->GetConstraints())->Add(constr); } - // } //________________________________________ diff --git a/Detectors/Align/src/AliAlgSteer.cxx b/Detectors/Align/src/AliAlgSteer.cxx index 03d413d04b827..369a477a806e6 100644 --- a/Detectors/Align/src/AliAlgSteer.cxx +++ b/Detectors/Align/src/AliAlgSteer.cxx @@ -19,10 +19,10 @@ #include "Align/AliAlgPoint.h" #include "Align/AliAlgDet.h" #include "Align/AliAlgVol.h" -#include "Align/AliAlgDetITS.h" -#include "Align/AliAlgDetTPC.h" -#include "Align/AliAlgDetTRD.h" -#include "Align/AliAlgDetTOF.h" +//#include "Align/AliAlgDetITS.h" +//#include "Align/AliAlgDetTPC.h" +//#include "Align/AliAlgDetTRD.h" +//#include "Align/AliAlgDetTOF.h" #include "Align/AliAlgVtx.h" #include "Align/AliAlgMPRecord.h" #include "Align/AliAlgRes.h" @@ -64,8 +64,9 @@ namespace align const Char_t* AliAlgSteer::fgkMPDataExt = ".mille"; const Char_t* AliAlgSteer::fgkDetectorName[AliAlgSteer::kNDetectors] = {"ITS", "TPC", "TRD", "TOF", "HMPID"}; -const Int_t AliAlgSteer::fgkSkipLayers[AliAlgSteer::kNLrSkip] = {AliGeomManager::kPHOS1, AliGeomManager::kPHOS2, - AliGeomManager::kMUON, AliGeomManager::kEMCAL}; +//const Int_t AliAlgSteer::fgkSkipLayers[AliAlgSteer::kNLrSkip] = {AliGeomManager::kPHOS1, AliGeomManager::kPHOS2, +// AliGeomManager::kMUON, AliGeomManager::kEMCAL}; FIXME(milettri): needs AliGeomManager +const Int_t AliAlgSteer::fgkSkipLayers[AliAlgSteer::kNLrSkip] = {0, 0, 0, 0}; // FIXME(milettri): needs AliGeomManager const Char_t* AliAlgSteer::fgkStatClName[AliAlgSteer::kNStatCl] = {"Inp: ", "Acc: "}; const Char_t* AliAlgSteer::fgkStatName[AliAlgSteer::kMaxStat] = @@ -76,7 +77,17 @@ const Char_t* AliAlgSteer::fgkHStatName[AliAlgSteer::kNHVars] = { //________________________________________________________________ AliAlgSteer::AliAlgSteer(const char* configMacro, int refRun) - : fNDet(0), fNDOFs(0), fRunNumber(-1), fFieldOn(kFALSE), fTracksType(kColl), fAlgTrack(0), fVtxSens(0), fConstraints(), fSelEventSpecii(AliRecoParam::kCosmic | AliRecoParam::kLowMult | AliRecoParam::kHighMult | AliRecoParam::kDefault), fCosmicSelStrict(kFALSE), fVtxMinCont(-1), fVtxMaxCont(-1), fVtxMinContVC(10), fMinITSClforVC(3), fITSPattforVC(AliAlgDetITS::kSPDAny), fMaxChi2forVC(10) + : fNDet(0), fNDOFs(0), fRunNumber(-1), fFieldOn(kFALSE), fTracksType(kColl), fAlgTrack(0), fVtxSens(0), fConstraints(), + // fSelEventSpecii(AliRecoParam::kCosmic | AliRecoParam::kLowMult | AliRecoParam::kHighMult | AliRecoParam::kDefault), FIXME(milettri): needs AliRecoParam + fSelEventSpecii(0), // FIXME(milettri): needs AliRecoParam + fCosmicSelStrict(kFALSE), + fVtxMinCont(-1), + fVtxMaxCont(-1), + fVtxMinContVC(10), + fMinITSClforVC(3), + // fITSPattforVC(AliAlgDetITS::kSPDAny), FIXME(milettri): needs AliAlgDetITS + fITSPattforVC(0), // FIXME(milettri): needs AliAlgDetITS + fMaxChi2forVC(10) // , fGloParVal(0), @@ -86,8 +97,8 @@ AliAlgSteer::AliAlgSteer(const char* configMacro, int refRun) fLbl2ID(0), fRefPoint(0), fESDTree(0), - fESDEvent(0), - fVertex(0), + // fESDEvent(0), FIXME(milettri): needs AliESDEvent + // fVertex(0), FIXME(milettri): needs AliESDVertex fControlFrac(1.0), fMPOutType(kMille | kMPRec | kContR), fMille(0), @@ -143,11 +154,11 @@ AliAlgSteer::AliAlgSteer(const char* configMacro, int refRun) SetMinPointsCosm(); // for (int i = kNCosmLegs; i--;) - fESDTrack[i] = 0; - memset(fStat, 0, kNStatCl * kMaxStat * sizeof(float)); + // fESDTrack[i] = 0; FIXME(milettri): needs AliESDtrack + memset(fStat, 0, kNStatCl * kMaxStat * sizeof(float)); SetMaxDCAforVC(); SetMaxChi2forVC(); - SetOutCDBRunRange(); + // SetOutCDBRunRange(); FIXME(milettri): needs OCDB SetDefPtBOffCosm(); SetDefPtBOffColl(); // @@ -157,8 +168,7 @@ AliAlgSteer::AliAlgSteer(const char* configMacro, int refRun) if (!GetInitDOFsDone()) InitDOFs(); if (!GetNDOFs()) - AliFatalF("No DOFs found, initialization with %s failed", - fConfMacroName.Data()); + LOG(FATAL) << "No DOFs found, initialization with " << fConfMacroName.Data() << " failed"; } } @@ -211,7 +221,7 @@ void AliAlgSteer::InitDetectors() for (int i = 0; i < fNDet; i++) dofCnt += fDetectors[i]->InitGeom(); if (!dofCnt) - AliFatal("No DOFs found"); + LOG(FATAL) << "No DOFs found"; // // for (int idt = 0; idt < kNDetectors; idt++) { @@ -232,7 +242,7 @@ void AliAlgSteer::InitDetectors() memset(fOrderedLbl, 0, dofCnt * sizeof(Int_t)); memset(fLbl2ID, 0, dofCnt * sizeof(Int_t)); AssignDOFs(); - AliInfoF("Booked %d global parameters", dofCnt); + LOG(INFO) << "Booked " << dofCnt << " global parameters"; // SetInitGeomDone(); // @@ -244,7 +254,7 @@ void AliAlgSteer::InitDOFs() // scan all free global parameters, link detectors to array of params // if (GetInitDOFsDone()) { - AliInfoF("InitDOFs was already done, just reassigning %d DOFs arrays/labels", fNDOFs); + LOG(INFO) << "InitDOFs was already done, just reassigning " << fNDOFs << "DOFs arrays/labels"; AssignDOFs(); return; } @@ -265,9 +275,9 @@ void AliAlgSteer::InitDOFs() } for (int i = 0; i < kNTrackTypes; i++) if (nact < fMinDetAcc[i]) - AliFatalF("%d detectors are active, while %d in track are asked", nact, fMinDetAcc[i]); + LOG(FATAL) << nact << " detectors are active, while " << fMinDetAcc[i] << " in track are asked"; // - AliInfoF("%d global parameters %d detectors, %d in %d active detectors", fNDOFs, fNDet, ndfAct, nact); + LOG(INFO) << fNDOFs << " global parameters " << fNDet << " detectors, " << ndfAct << " in " << nact << " active detectors"; // AddAutoConstraints(); // @@ -294,9 +304,9 @@ void AliAlgSteer::AssignDOFs() //if (det->IsDisabled()) continue; fNDOFs += det->AssignDOFs(); } - AliInfoF("Assigned parameters/labels arrays for %d DOFs", fNDOFs); + LOG(INFO) << "Assigned parameters/labels arrays for " << fNDOFs << " DOFs"; if (ndfOld > -1 && ndfOld != fNDOFs) - AliErrorF("Recalculated NDOFs=%d not equal to saved NDOFs=%d", fNDOFs, ndfOld); + LOG(ERROR) << "Recalculated NDOFs=" << fNDOFs << " not equal to saved NDOFs=" << ndfOld; // // build Lbl <-> parID table Sort(fNDOFs, fGloParLab, fLbl2ID, kFALSE); // sort in increasing order @@ -308,33 +318,33 @@ void AliAlgSteer::AssignDOFs() //________________________________________________________________ void AliAlgSteer::AddDetector(UInt_t id, AliAlgDet* det) { + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; // add detector participating in the alignment, optionally constructed externally // if (!fRefOCDBLoaded) - LoadRefOCDB(); - // - if (id >= kNDetectors) - AliFatalF("Detector typeID %d exceeds allowed range %d:%d", - id, 0, kNDetectors - 1); + // LoadRefOCDB(); FIXME(milettri): needs OCDB + // + if (id >= kNDetectors) + LOG(FATAL) << "Detector typeID " << id << " exceeds allowed range " << 0 << ":" << (kNDetectors - 1); // if (fDetPos[id] != -1) - AliFatalF("Detector %d was already added", id); + LOG(FATAL) << "Detector " << id << " was already added"; if (!det) { switch (id) { - case kITS: - det = new AliAlgDetITS(GetDetNameByDetID(kITS)); - break; - case kTPC: - det = new AliAlgDetTPC(GetDetNameByDetID(kTPC)); - break; - case kTRD: - det = new AliAlgDetTRD(GetDetNameByDetID(kTRD)); - break; - case kTOF: - det = new AliAlgDetTOF(GetDetNameByDetID(kTOF)); - break; + // case kITS: + // det = new AliAlgDetITS(GetDetNameByDetID(kITS)); FIXME(milettri): needs AliAlgDetITS + // break; + // case kTPC: + // det = new AliAlgDetTPC(GetDetNameByDetID(kTPC)); FIXME(milettri): needs AliAlgDetTPC + // break; + // case kTRD: + // det = new AliAlgDetTRD(GetDetNameByDetID(kTRD)); FIXME(milettri): needs AliAlgDetTRD + // break; + // case kTOF: + // det = new AliAlgDetTOF(GetDetNameByDetID(kTOF)); FIXME(milettri): needs AliAlgDetTOF + // break; default: - AliFatalF("%d not implemented yet", id); + LOG(FATAL) << id << " not implemented yet"; break; }; } @@ -383,379 +393,381 @@ Bool_t AliAlgSteer::CheckDetectorPoints(const int* npsel) const return ndOK >= fMinDetAcc[fTracksType]; } +//FIXME(milettri): needs AliESDtrack +////_________________________________________________________ +//UInt_t AliAlgSteer::AcceptTrack(const AliESDtrack* esdTr, Bool_t strict) const +//{ +// // decide if the track should be processed +// AliAlgDet* det = 0; +// UInt_t detAcc = 0; +// if (fFieldOn && esdTr->Pt() < fPtMin[fTracksType]) +// return 0; +// if (Abs(esdTr->Eta()) > fEtaMax[fTracksType]) +// return 0; +// // +// for (int idet = 0; idet < kNDetectors; idet++) { +// if (!(det = GetDetectorByDetID(idet)) || det->IsDisabled(fTracksType)) +// continue; +// if (!det->AcceptTrack(esdTr, fTracksType)) { +// if (strict && det->IsObligatory(fTracksType)) +// return 0; +// else +// continue; +// } +// // +// detAcc |= 0x1 << idet; +// } +// if (NumberOfBitsSet(detAcc) < fMinDetAcc[fTracksType]) +// return 0; +// return detAcc; +// // +//} + +//FIXME(milettri): needs AliESDtrack +////_________________________________________________________ +//UInt_t AliAlgSteer::AcceptTrackCosmic(const AliESDtrack* esdPairCosm[kNCosmLegs]) const +//{ +// // decide if the pair of tracks making cosmic track should be processed +// UInt_t detAcc = 0, detAccLeg; +// for (int i = kNCosmLegs; i--;) { +// detAccLeg = AcceptTrack(esdPairCosm[i], fCosmicSelStrict); // missing obligatory detectors in one leg might be allowed +// if (!detAccLeg) +// return 0; +// detAcc |= detAccLeg; +// } +// if (fCosmicSelStrict) +// return detAcc; +// // +// // for non-stric selection check convolution of detector presence +// if (!CheckDetectorPattern(detAcc)) +// return 0; +// return detAcc; +// // +//} + +//FIXME(milettri): needs AliESDEvent +////_________________________________________________________ +//void AliAlgSteer::SetESDEvent(const AliESDEvent* ev) +//{ +// // attach event to analyse +// fESDEvent = ev; +// // setup magnetic field if needed +// if (fESDEvent && +// (!TGeoGlobalMagField::Instance()->GetField() || +// !SmallerAbs(fESDEvent->GetMagneticField() - AliTrackerBase::GetBz(), 5e-4))) { +// fESDEvent->InitMagneticField(); +// } +//} + +//FIXME(milettri): needs AliESDEvent +////_________________________________________________________ +//Bool_t AliAlgSteer::ProcessEvent(const AliESDEvent* esdEv) +//{ +// // process event +// const int kProcStatFreq = 100; +// static int evCount = 0; +// if (!(evCount % kProcStatFreq)) { +// ProcInfo_t procInfo; +// gSystem->GetProcInfo(&procInfo); +// LOG(INFO) << "ProcStat: CPUusr:" << int(procInfo.fCpuUser) << " CPUsys:" << int(procInfo.fCpuSys) << " RMem:" << int(procInfo.fMemResident / 1024) << " VMem:" << int(procInfo.fMemVirtual / 1024); +// } +// evCount++; +// // +// SetESDEvent(esdEv); +// // +// if (esdEv->GetRunNumber() != GetRunNumber()) +// SetRunNumber(esdEv->GetRunNumber()); +// // +// if (!(esdEv->GetEventSpecie() & fSelEventSpecii)) { +//#if DEBUG > 2 +// LOG(INFO) << "Reject: specie does not match, allowed " << fSelEventSpecii; +//#endif +// return kFALSE; +// } +// // +// SetCosmic(esdEv->GetEventSpecie() == AliRecoParam::kCosmic || +// (esdEv->GetNumberOfCosmicTracks() > 0 && !esdEv->GetPrimaryVertexTracks()->GetStatus())); +// // +// FillStatHisto(kEvInp); +// // +//#if DEBUG > 2 +// LOG << "Processing event " << esdEv->GetEventNumberInFile() << " of ev.specie " << esdEv->GetEventSpecie() << " -> Ntr: " << esdEv->GetNumberOfTracks() << " NtrCosm: " << esdEv->GetNumberOfCosmicTracks(); +//#endif +// // +// SetFieldOn(Abs(esdEv->GetMagneticField()) > kAlmost0Field); +// if (!IsCosmic() && !CheckSetVertex(esdEv->GetPrimaryVertexTracks())) +// return kFALSE; +// FillStatHisto(kEvVtx); +// // +// int ntr = 0, accTr = 0; +// if (IsCosmic()) { +// fStat[kInpStat][kEventCosm]++; +// ntr = esdEv->GetNumberOfCosmicTracks(); +// FillStatHisto(kTrackInp, ntr); +// for (int itr = 0; itr < ntr; itr++) { +// accTr += ProcessTrack(esdEv->GetCosmicTrack(itr)); +// } +// if (accTr) +// fStat[kAccStat][kEventCosm]++; +// } else { +// fStat[kInpStat][kEventColl]++; +// ntr = esdEv->GetNumberOfTracks(); +// FillStatHisto(kTrackInp, ntr); +// for (int itr = 0; itr < ntr; itr++) { +// // int accTrOld = accTr; +// accTr += ProcessTrack(esdEv->GetTrack(itr)); +// /* +// if (accTr>accTrOld && fCResid) { +// int ndf = fCResid->GetNPoints()*2-5; +// if (fCResid->GetChi2()/ndf>20 || !fCResid->GetKalmanDone() +// || fCResid->GetChi2K()/ndf>20) { +// printf("BAD FIT for %d\n",itr); +// } +// fCResid->Print("er"); +// } +// */ +// } +// if (accTr) +// fStat[kAccStat][kEventColl]++; +// } +// // +// FillStatHisto(kTrackAcc, accTr); +// // +// if (accTr) { +// LOG(INFO) << "Processed event " << esdEv->GetEventNumberInFile() << " of ev.specie " << esdEv->GetEventSpecie() << " -> Accepted: " << accTr << " of " << ntr << " tracks"; +// } +// return kTRUE; +//} + +//FIXME(milettri): needs AliESDtrack //_________________________________________________________ -UInt_t AliAlgSteer::AcceptTrack(const AliESDtrack* esdTr, Bool_t strict) const -{ - // decide if the track should be processed - AliAlgDet* det = 0; - UInt_t detAcc = 0; - if (fFieldOn && esdTr->Pt() < fPtMin[fTracksType]) - return 0; - if (Abs(esdTr->Eta()) > fEtaMax[fTracksType]) - return 0; - // - for (int idet = 0; idet < kNDetectors; idet++) { - if (!(det = GetDetectorByDetID(idet)) || det->IsDisabled(fTracksType)) - continue; - if (!det->AcceptTrack(esdTr, fTracksType)) { - if (strict && det->IsObligatory(fTracksType)) - return 0; - else - continue; - } - // - detAcc |= 0x1 << idet; - } - if (NumberOfBitsSet(detAcc) < fMinDetAcc[fTracksType]) - return 0; - return detAcc; - // -} - -//_________________________________________________________ -UInt_t AliAlgSteer::AcceptTrackCosmic(const AliESDtrack* esdPairCosm[kNCosmLegs]) const -{ - // decide if the pair of tracks making cosmic track should be processed - UInt_t detAcc = 0, detAccLeg; - for (int i = kNCosmLegs; i--;) { - detAccLeg = AcceptTrack(esdPairCosm[i], fCosmicSelStrict); // missing obligatory detectors in one leg might be allowed - if (!detAccLeg) - return 0; - detAcc |= detAccLeg; - } - if (fCosmicSelStrict) - return detAcc; - // - // for non-stric selection check convolution of detector presence - if (!CheckDetectorPattern(detAcc)) - return 0; - return detAcc; - // -} - -//_________________________________________________________ -void AliAlgSteer::SetESDEvent(const AliESDEvent* ev) -{ - // attach event to analyse - fESDEvent = ev; - // setup magnetic field if needed - if (fESDEvent && - (!TGeoGlobalMagField::Instance()->GetField() || - !SmallerAbs(fESDEvent->GetMagneticField() - AliTrackerBase::GetBz(), 5e-4))) { - fESDEvent->InitMagneticField(); - } -} - -//_________________________________________________________ -Bool_t AliAlgSteer::ProcessEvent(const AliESDEvent* esdEv) -{ - // process event - const int kProcStatFreq = 100; - static int evCount = 0; - if (!(evCount % kProcStatFreq)) { - ProcInfo_t procInfo; - gSystem->GetProcInfo(&procInfo); - AliInfoF("ProcStat: CPUusr: %6d CPUsys: %6d RMem:%6d VMem:%6d", - int(procInfo.fCpuUser), int(procInfo.fCpuSys), - int(procInfo.fMemResident / 1024), int(procInfo.fMemVirtual / 1024)); - } - evCount++; - // - SetESDEvent(esdEv); - // - if (esdEv->GetRunNumber() != GetRunNumber()) - SetRunNumber(esdEv->GetRunNumber()); - // - if (!(esdEv->GetEventSpecie() & fSelEventSpecii)) { -#if DEBUG > 2 - AliInfoF("Reject: specie does not match, allowed 0x%0x", fSelEventSpecii); -#endif - return kFALSE; - } - // - SetCosmic(esdEv->GetEventSpecie() == AliRecoParam::kCosmic || - (esdEv->GetNumberOfCosmicTracks() > 0 && !esdEv->GetPrimaryVertexTracks()->GetStatus())); - // - FillStatHisto(kEvInp); - // -#if DEBUG > 2 - AliInfoF("Processing event %d of ev.specie %d -> Ntr: %4d NtrCosm: %d", - esdEv->GetEventNumberInFile(), esdEv->GetEventSpecie(), - esdEv->GetNumberOfTracks(), esdEv->GetNumberOfCosmicTracks()); -#endif - // - SetFieldOn(Abs(esdEv->GetMagneticField()) > kAlmost0Field); - if (!IsCosmic() && !CheckSetVertex(esdEv->GetPrimaryVertexTracks())) - return kFALSE; - FillStatHisto(kEvVtx); - // - int ntr = 0, accTr = 0; - if (IsCosmic()) { - fStat[kInpStat][kEventCosm]++; - ntr = esdEv->GetNumberOfCosmicTracks(); - FillStatHisto(kTrackInp, ntr); - for (int itr = 0; itr < ntr; itr++) { - accTr += ProcessTrack(esdEv->GetCosmicTrack(itr)); - } - if (accTr) - fStat[kAccStat][kEventCosm]++; - } else { - fStat[kInpStat][kEventColl]++; - ntr = esdEv->GetNumberOfTracks(); - FillStatHisto(kTrackInp, ntr); - for (int itr = 0; itr < ntr; itr++) { - // int accTrOld = accTr; - accTr += ProcessTrack(esdEv->GetTrack(itr)); - /* - if (accTr>accTrOld && fCResid) { - int ndf = fCResid->GetNPoints()*2-5; - if (fCResid->GetChi2()/ndf>20 || !fCResid->GetKalmanDone() - || fCResid->GetChi2K()/ndf>20) { - printf("BAD FIT for %d\n",itr); - } - fCResid->Print("er"); - } - */ - } - if (accTr) - fStat[kAccStat][kEventColl]++; - } - // - FillStatHisto(kTrackAcc, accTr); - // - if (accTr) { - AliInfoF("Processed event %d of ev.specie %d -> Accepted: %4d of %4d tracks", - esdEv->GetEventNumberInFile(), esdEv->GetEventSpecie(), accTr, ntr); - } - return kTRUE; -} - -//_________________________________________________________ -Bool_t AliAlgSteer::ProcessTrack(const AliESDtrack* esdTr) -{ - // process single track - // - fStat[kInpStat][kTrackColl]++; - fESDTrack[0] = esdTr; - fESDTrack[1] = 0; - // - int nPnt = 0; - const AliESDfriendTrack* trF = esdTr->GetFriendTrack(); - if (!trF) - return kFALSE; - const AliTrackPointArray* trPoints = trF->GetTrackPointArray(); - if (!trPoints || (nPnt = trPoints->GetNPoints()) < 1) - return kFALSE; - // - UInt_t detAcc = AcceptTrack(esdTr); - if (!detAcc) - return kFALSE; - // - ResetDetectors(); - fAlgTrack->Clear(); - // - // process the track points for each detector, - AliAlgDet* det = 0; - for (int idet = 0; idet < kNDetectors; idet++) { - if (!(detAcc & (0x1 << idet))) - continue; - det = GetDetectorByDetID(idet); - if (det->ProcessPoints(esdTr, fAlgTrack) < det->GetNPointsSel(kColl)) { - detAcc &= ~(0x1 << idet); // did not survive, suppress detector in the track - if (det->IsObligatory(kColl)) - return kFALSE; - } - if (NumberOfBitsSet(detAcc) < fMinDetAcc[kColl]) - return kFALSE; // abandon track - } - // - if (fAlgTrack->GetNPoints() < GetMinPoints()) - return kFALSE; - // fill needed points (tracking frame) in the fAlgTrack - fRefPoint->SetContainsMeasurement(kFALSE); - fRefPoint->SetContainsMaterial(kFALSE); - fAlgTrack->AddPoint(fRefPoint); // reference point which the track will refer to - // - fAlgTrack->CopyFrom(esdTr); - if (!GetFieldOn()) - fAlgTrack->ImposePtBOff(fDefPtBOff[AliAlgAux::kColl]); - fAlgTrack->SetFieldON(GetFieldOn()); - fAlgTrack->SortPoints(); - // - // at this stage the points are sorted from maxX to minX, the latter corresponding to - // reference point (e.g. vertex) with X~0. The fAlgTrack->GetInnerPointID() points on it, - // hence fAlgTrack->GetInnerPointID() is the 1st really measured point. We will set the - // alpha of the reference point to alpha of the barrel sector corresponding to this - // 1st measured point - int pntMeas = fAlgTrack->GetInnerPointID() - 1; - if (pntMeas < 0) { // this should not happen - fAlgTrack->Print("p meas"); - AliFatal("AliAlgTrack->GetInnerPointID() cannot be 0"); - } - // do we want to add the vertex as a measured point ? - if (!AddVertexConstraint()) { // no constrain, just reference point w/o measurement - fRefPoint->SetXYZTracking(0, 0, 0); - fRefPoint->SetAlphaSens(Sector2Alpha(fAlgTrack->GetPoint(pntMeas)->GetAliceSector())); - } else - FillStatHisto(kTrackFitInpVC); - // - FillStatHisto(kTrackFitInp); - if (!fAlgTrack->IniFit()) - return kFALSE; - FillStatHisto(kTrackProcMatInp); - if (!fAlgTrack->ProcessMaterials()) - return kFALSE; - fAlgTrack->DefineDOFs(); - // - FillStatHisto(kTrackResDerInp); - if (!fAlgTrack->CalcResidDeriv()) - return kFALSE; - // - if (!StoreProcessedTrack(fMPOutType & ~kContR)) - return kFALSE; // store derivatives for MP - // - if (GetProduceControlRes() && // need control residuals, ignore selection fraction if this is the - (fMPOutType == kContR || gRandom->Rndm() < fControlFrac)) { // output requested - if (!TestLocalSolution() || !StoreProcessedTrack(kContR)) - return kFALSE; - } - // - FillStatHisto(kTrackStore); - // - fStat[kAccStat][kTrackColl]++; - // - return kTRUE; -} - -//_________________________________________________________ -Bool_t AliAlgSteer::CheckSetVertex(const AliESDVertex* vtx) -{ - // vertex selection/constraint check - if (!vtx) { - fVertex = 0; - return kTRUE; - } - int ncont = vtx->GetNContributors(); - if (fVtxMinCont > 0 && fVtxMinCont > ncont) { -#if DEBUG > 2 - AliInfoF("Rejecting event with %d vertex contributors (min %d asked)", ncont, fVtxMinCont); -#endif - return kFALSE; - } - if (fVtxMaxCont > 0 && ncont > fVtxMaxCont) { -#if DEBUG > 2 - AliInfoF("Rejecting event with %d vertex contributors (max %d asked)", ncont, fVtxMaxCont); -#endif - return kFALSE; - } - fVertex = (ncont >= fVtxMinContVC) ? vtx : 0; // use vertex as a constraint - return kTRUE; -} - -//_________________________________________________________ -Bool_t AliAlgSteer::ProcessTrack(const AliESDCosmicTrack* cosmTr) -{ - // process single cosmic track - // - fStat[kInpStat][kTrackCosm]++; - int nPnt = 0; - fESDTrack[0] = 0; - fESDTrack[1] = 0; - // - for (int leg = kNCosmLegs; leg--;) { - const AliESDtrack* esdTr = - fESDEvent->GetTrack(leg == kCosmLow ? cosmTr->GetESDLowerTrackIndex() : cosmTr->GetESDUpperTrackIndex()); - const AliESDfriendTrack* trF = esdTr->GetFriendTrack(); - if (!trF) - return kFALSE; - const AliTrackPointArray* trPoints = trF->GetTrackPointArray(); - if (!trPoints || (nPnt += trPoints->GetNPoints()) < 1) - return kFALSE; - // - fESDTrack[leg] = esdTr; - } - // - UInt_t detAcc = AcceptTrackCosmic(fESDTrack); - if (!detAcc) - return kFALSE; - // - ResetDetectors(); - fAlgTrack->Clear(); - fAlgTrack->SetCosmic(kTRUE); - // - // process the track points for each detector, - // fill needed points (tracking frame) in the fAlgTrack - fRefPoint->SetContainsMeasurement(kFALSE); - fRefPoint->SetContainsMaterial(kFALSE); - fAlgTrack->AddPoint(fRefPoint); // reference point which the track will refer to - // - AliAlgDet* det = 0; - Int_t npsel[kNDetectors] = {0}; - for (int nPleg = 0, leg = kNCosmLegs; leg--;) { - for (int idet = 0; idet < kNDetectors; idet++) { - if (!(detAcc & (0x1 << idet))) - continue; - det = GetDetectorByDetID(idet); - // - // upper leg points marked as the track going in inverse direction - int np = det->ProcessPoints(fESDTrack[leg], fAlgTrack, leg == kCosmUp); - if (np < det->GetNPointsSel(kCosm) && fCosmicSelStrict && - det->IsObligatory(kCosm)) - return kFALSE; - npsel[idet] += np; - nPleg += np; - } - if (nPleg < GetMinPoints()) - return kFALSE; - } - // last check on legs-combined patter - if (!CheckDetectorPoints(npsel)) - return kFALSE; - // - fAlgTrack->CopyFrom(cosmTr); - if (!GetFieldOn()) - fAlgTrack->ImposePtBOff(fDefPtBOff[AliAlgAux::kCosm]); - fAlgTrack->SetFieldON(GetFieldOn()); - fAlgTrack->SortPoints(); - // - // at this stage the points are sorted from maxX to minX, the latter corresponding to - // reference point (e.g. vertex) with X~0. The fAlgTrack->GetInnerPointID() points on it, - // hence fAlgTrack->GetInnerPointID() is the 1st really measured point. We will set the - // alpha of the reference point to alpha of the barrel sector corresponding to this - // 1st measured point - int pntMeas = fAlgTrack->GetInnerPointID() - 1; - if (pntMeas < 0) { // this should not happen - fAlgTrack->Print("p meas"); - AliFatal("AliAlgTrack->GetInnerPointID() cannot be 0"); - } - fRefPoint->SetAlphaSens(Sector2Alpha(fAlgTrack->GetPoint(pntMeas)->GetAliceSector())); - // - FillStatHisto(kTrackFitInp); - if (!fAlgTrack->IniFit()) - return kFALSE; - // - FillStatHisto(kTrackProcMatInp); - if (!fAlgTrack->ProcessMaterials()) - return kFALSE; - fAlgTrack->DefineDOFs(); - // - FillStatHisto(kTrackResDerInp); - if (!fAlgTrack->CalcResidDeriv()) - return kFALSE; - // - if (!StoreProcessedTrack(fMPOutType & ~kContR)) - return kFALSE; // store derivatives for MP - // - if (GetProduceControlRes() && // need control residuals, ignore selection fraction if this is the - (fMPOutType == kContR || gRandom->Rndm() < fControlFrac)) { // output requested - if (!TestLocalSolution() || !StoreProcessedTrack(kContR)) - return kFALSE; - } - // - FillStatHisto(kTrackStore); - fStat[kAccStat][kTrackCosm]++; - return kTRUE; -} +//Bool_t AliAlgSteer::ProcessTrack(const AliESDtrack* esdTr) +//{ +// // process single track +// // +// fStat[kInpStat][kTrackColl]++; +// fESDTrack[0] = esdTr; +// fESDTrack[1] = 0; +// // +// int nPnt = 0; +// const AliESDfriendTrack* trF = esdTr->GetFriendTrack(); +// if (!trF) +// return kFALSE; +// const AliTrackPointArray* trPoints = trF->GetTrackPointArray(); +// if (!trPoints || (nPnt = trPoints->GetNPoints()) < 1) +// return kFALSE; +// // +// UInt_t detAcc = AcceptTrack(esdTr); +// if (!detAcc) +// return kFALSE; +// // +// ResetDetectors(); +// fAlgTrack->Clear(); +// // +// // process the track points for each detector, +// AliAlgDet* det = 0; +// for (int idet = 0; idet < kNDetectors; idet++) { +// if (!(detAcc & (0x1 << idet))) +// continue; +// det = GetDetectorByDetID(idet); +// if (det->ProcessPoints(esdTr, fAlgTrack) < det->GetNPointsSel(kColl)) { +// detAcc &= ~(0x1 << idet); // did not survive, suppress detector in the track +// if (det->IsObligatory(kColl)) +// return kFALSE; +// } +// if (NumberOfBitsSet(detAcc) < fMinDetAcc[kColl]) +// return kFALSE; // abandon track +// } +// // +// if (fAlgTrack->GetNPoints() < GetMinPoints()) +// return kFALSE; +// // fill needed points (tracking frame) in the fAlgTrack +// fRefPoint->SetContainsMeasurement(kFALSE); +// fRefPoint->SetContainsMaterial(kFALSE); +// fAlgTrack->AddPoint(fRefPoint); // reference point which the track will refer to +// // +// fAlgTrack->CopyFrom(esdTr); +// if (!GetFieldOn()) +// fAlgTrack->ImposePtBOff(fDefPtBOff[AliAlgAux::kColl]); +// fAlgTrack->SetFieldON(GetFieldOn()); +// fAlgTrack->SortPoints(); +// // +// // at this stage the points are sorted from maxX to minX, the latter corresponding to +// // reference point (e.g. vertex) with X~0. The fAlgTrack->GetInnerPointID() points on it, +// // hence fAlgTrack->GetInnerPointID() is the 1st really measured point. We will set the +// // alpha of the reference point to alpha of the barrel sector corresponding to this +// // 1st measured point +// int pntMeas = fAlgTrack->GetInnerPointID() - 1; +// if (pntMeas < 0) { // this should not happen +// fAlgTrack->Print("p meas"); +// LOG(FATAL) << "AliAlgTrack->GetInnerPointID() cannot be 0"; +// } +// // do we want to add the vertex as a measured point ? +// if (!AddVertexConstraint()) { // no constrain, just reference point w/o measurement +// fRefPoint->SetXYZTracking(0, 0, 0); +// fRefPoint->SetAlphaSens(Sector2Alpha(fAlgTrack->GetPoint(pntMeas)->GetAliceSector())); +// } else +// FillStatHisto(kTrackFitInpVC); +// // +// FillStatHisto(kTrackFitInp); +// if (!fAlgTrack->IniFit()) +// return kFALSE; +// FillStatHisto(kTrackProcMatInp); +// if (!fAlgTrack->ProcessMaterials()) +// return kFALSE; +// fAlgTrack->DefineDOFs(); +// // +// FillStatHisto(kTrackResDerInp); +// if (!fAlgTrack->CalcResidDeriv()) +// return kFALSE; +// // +// if (!StoreProcessedTrack(fMPOutType & ~kContR)) +// return kFALSE; // store derivatives for MP +// // +// if (GetProduceControlRes() && // need control residuals, ignore selection fraction if this is the +// (fMPOutType == kContR || gRandom->Rndm() < fControlFrac)) { // output requested +// if (!TestLocalSolution() || !StoreProcessedTrack(kContR)) +// return kFALSE; +// } +// // +// FillStatHisto(kTrackStore); +// // +// fStat[kAccStat][kTrackColl]++; +// // +// return kTRUE; +//} + +//FIXME(milettri): needs AliESDVertex +////_________________________________________________________ +//Bool_t AliAlgSteer::CheckSetVertex(const AliESDVertex* vtx) +//{ +// // vertex selection/constraint check +// if (!vtx) { +// fVertex = 0; +// return kTRUE; +// } +// int ncont = vtx->GetNContributors(); +// if (fVtxMinCont > 0 && fVtxMinCont > ncont) { +//#if DEBUG > 2 +// LOG(INFO) << "Rejecting event with " << % d << " vertex contributors (min " << % d << " asked)", ncont, fVtxMinCont); +//#endif +// return kFALSE; +// } +// if (fVtxMaxCont > 0 && ncont > fVtxMaxCont) { +//#if DEBUG > 2 +// LOG(INFO) << "Rejecting event with " << % d << " vertex contributors (max " << % d << " asked)", ncont, fVtxMaxCont); +//#endif +// return kFALSE; +// } +// fVertex = (ncont >= fVtxMinContVC) ? vtx : 0; // use vertex as a constraint +// return kTRUE; +//} + +//FIXME(milettri): needs AliESDCosmicTrack +////_________________________________________________________ +//Bool_t AliAlgSteer::ProcessTrack(const AliESDCosmicTrack* cosmTr) +//{ +// // process single cosmic track +// // +// fStat[kInpStat][kTrackCosm]++; +// int nPnt = 0; +// fESDTrack[0] = 0; +// fESDTrack[1] = 0; +// // +// for (int leg = kNCosmLegs; leg--;) { +// const AliESDtrack* esdTr = +// fESDEvent->GetTrack(leg == kCosmLow ? cosmTr->GetESDLowerTrackIndex() : cosmTr->GetESDUpperTrackIndex()); +// const AliESDfriendTrack* trF = esdTr->GetFriendTrack(); +// if (!trF) +// return kFALSE; +// const AliTrackPointArray* trPoints = trF->GetTrackPointArray(); +// if (!trPoints || (nPnt += trPoints->GetNPoints()) < 1) +// return kFALSE; +// // +// fESDTrack[leg] = esdTr; +// } +// // +// UInt_t detAcc = AcceptTrackCosmic(fESDTrack); +// if (!detAcc) +// return kFALSE; +// // +// ResetDetectors(); +// fAlgTrack->Clear(); +// fAlgTrack->SetCosmic(kTRUE); +// // +// // process the track points for each detector, +// // fill needed points (tracking frame) in the fAlgTrack +// fRefPoint->SetContainsMeasurement(kFALSE); +// fRefPoint->SetContainsMaterial(kFALSE); +// fAlgTrack->AddPoint(fRefPoint); // reference point which the track will refer to +// // +// AliAlgDet* det = 0; +// Int_t npsel[kNDetectors] = {0}; +// for (int nPleg = 0, leg = kNCosmLegs; leg--;) { +// for (int idet = 0; idet < kNDetectors; idet++) { +// if (!(detAcc & (0x1 << idet))) +// continue; +// det = GetDetectorByDetID(idet); +// // +// // upper leg points marked as the track going in inverse direction +// int np = det->ProcessPoints(fESDTrack[leg], fAlgTrack, leg == kCosmUp); +// if (np < det->GetNPointsSel(kCosm) && fCosmicSelStrict && +// det->IsObligatory(kCosm)) +// return kFALSE; +// npsel[idet] += np; +// nPleg += np; +// } +// if (nPleg < GetMinPoints()) +// return kFALSE; +// } +// // last check on legs-combined patter +// if (!CheckDetectorPoints(npsel)) +// return kFALSE; +// // +// fAlgTrack->CopyFrom(cosmTr); +// if (!GetFieldOn()) +// fAlgTrack->ImposePtBOff(fDefPtBOff[AliAlgAux::kCosm]); +// fAlgTrack->SetFieldON(GetFieldOn()); +// fAlgTrack->SortPoints(); +// // +// // at this stage the points are sorted from maxX to minX, the latter corresponding to +// // reference point (e.g. vertex) with X~0. The fAlgTrack->GetInnerPointID() points on it, +// // hence fAlgTrack->GetInnerPointID() is the 1st really measured point. We will set the +// // alpha of the reference point to alpha of the barrel sector corresponding to this +// // 1st measured point +// int pntMeas = fAlgTrack->GetInnerPointID() - 1; +// if (pntMeas < 0) { // this should not happen +// fAlgTrack->Print("p meas"); +// LOG(FATAL) << "AliAlgTrack->GetInnerPointID() cannot be 0"; +// } +// fRefPoint->SetAlphaSens(Sector2Alpha(fAlgTrack->GetPoint(pntMeas)->GetAliceSector())); +// // +// FillStatHisto(kTrackFitInp); +// if (!fAlgTrack->IniFit()) +// return kFALSE; +// // +// FillStatHisto(kTrackProcMatInp); +// if (!fAlgTrack->ProcessMaterials()) +// return kFALSE; +// fAlgTrack->DefineDOFs(); +// // +// FillStatHisto(kTrackResDerInp); +// if (!fAlgTrack->CalcResidDeriv()) +// return kFALSE; +// // +// if (!StoreProcessedTrack(fMPOutType & ~kContR)) +// return kFALSE; // store derivatives for MP +// // +// if (GetProduceControlRes() && // need control residuals, ignore selection fraction if this is the +// (fMPOutType == kContR || gRandom->Rndm() < fControlFrac)) { // output requested +// if (!TestLocalSolution() || !StoreProcessedTrack(kContR)) +// return kFALSE; +// } +// // +// FillStatHisto(kTrackStore); +// fStat[kAccStat][kTrackCosm]++; +// return kTRUE; +//} //_________________________________________________________ Bool_t AliAlgSteer::StoreProcessedTrack(Int_t what) @@ -780,11 +792,11 @@ Bool_t AliAlgSteer::FillMilleData() TString mo = Form("%s%s", fMPDatFileName.Data(), fgkMPDataExt); fMille = new Mille(mo.Data(), fMilleOutBin); if (!fMille) - AliFatalF("Failed to create output file %s", mo.Data()); + LOG(FATAL) << "Failed to create output file " << mo.Data(); } // if (!fAlgTrack->GetDerivDone()) { - AliError("Track derivatives are not yet evaluated"); + LOG(ERROR) << "Track derivatives are not yet evaluated"; return kFALSE; } int np(fAlgTrack->GetNPoints()), nDGloTot(0); // total number global derivatives stored @@ -860,7 +872,7 @@ Bool_t AliAlgSteer::FillMilleData() } // loop over points // if (!nDGloTot) { - AliInfo("Track does not depend on free global parameters, discard"); + LOG(INFO) << "Track does not depend on free global parameters, discard"; fMille->kill(); return kFALSE; } @@ -871,49 +883,53 @@ Bool_t AliAlgSteer::FillMilleData() //_________________________________________________________ Bool_t AliAlgSteer::FillMPRecData() { - // store MP2 in MPRecord format - if (!fMPRecord) - InitMPRecOutput(); - // - fMPRecord->Clear(); - if (!fMPRecord->FillTrack(fAlgTrack, fGloParLab)) - return kFALSE; - fMPRecord->SetRun(fRunNumber); - fMPRecord->SetTimeStamp(fESDEvent->GetTimeStamp()); - UInt_t tID = 0xffff & UInt_t(fESDTrack[0]->GetID()); - if (IsCosmic()) - tID |= (0xffff & UInt_t(fESDTrack[1]->GetID())) << 16; - fMPRecord->SetTrackID(tID); - fMPRecTree->Fill(); + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + //FIXME(milettri): needs AliESDEvent + // // store MP2 in MPRecord format + // if (!fMPRecord) + // InitMPRecOutput(); + // // + // fMPRecord->Clear(); + // if (!fMPRecord->FillTrack(fAlgTrack, fGloParLab)) + // return kFALSE; + // fMPRecord->SetRun(fRunNumber); + // fMPRecord->SetTimeStamp(fESDEvent->GetTimeStamp()); + // UInt_t tID = 0xffff & UInt_t(fESDTrack[0]->GetID()); + // if (IsCosmic()) + // tID |= (0xffff & UInt_t(fESDTrack[1]->GetID())) << 16; + // fMPRecord->SetTrackID(tID); + // fMPRecTree->Fill(); return kTRUE; } //_________________________________________________________ Bool_t AliAlgSteer::FillControlData() { - // store control residuals - if (!fCResid) - InitResidOutput(); - // - int nps, np = fAlgTrack->GetNPoints(); - nps = (!fRefPoint->ContainsMeasurement()) ? np - 1 : np; // ref point is dummy? - if (nps < 0) - return kTRUE; - // - fCResid->Clear(); - if (!fCResid->FillTrack(fAlgTrack, fDoKalmanResid)) - return kFALSE; - fCResid->SetRun(fRunNumber); - fCResid->SetTimeStamp(fESDEvent->GetTimeStamp()); - fCResid->SetBz(fESDEvent->GetMagneticField()); - UInt_t tID = 0xffff & UInt_t(fESDTrack[0]->GetID()); - if (IsCosmic()) - tID |= (0xffff & UInt_t(fESDTrack[1]->GetID())) << 16; - fCResid->SetTrackID(tID); - // - fResidTree->Fill(); - FillStatHisto(kTrackControl); - // + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + //FIXME(milettri): needs AliESDEvent + // // store control residuals + // if (!fCResid) + // InitResidOutput(); + // // + // int nps, np = fAlgTrack->GetNPoints(); + // nps = (!fRefPoint->ContainsMeasurement()) ? np - 1 : np; // ref point is dummy? + // if (nps < 0) + // return kTRUE; + // // + // fCResid->Clear(); + // if (!fCResid->FillTrack(fAlgTrack, fDoKalmanResid)) + // return kFALSE; + // fCResid->SetRun(fRunNumber); + // fCResid->SetTimeStamp(fESDEvent->GetTimeStamp()); + // fCResid->SetBz(fESDEvent->GetMagneticField()); + // UInt_t tID = 0xffff & UInt_t(fESDTrack[0]->GetID()); + // if (IsCosmic()) + // tID |= (0xffff & UInt_t(fESDTrack[1]->GetID())) << 16; + // fCResid->SetTrackID(tID); + // // + // fResidTree->Fill(); + // FillStatHisto(kTrackControl); + // // return kTRUE; } @@ -929,82 +945,84 @@ void AliAlgSteer::SetRunNumber(Int_t run) //_________________________________________________________ void AliAlgSteer::AcknowledgeNewRun(Int_t run) { - // load needed info for new run - if (run == fRunNumber) - return; // nothing to do - if (run > 0) { - fStat[kAccStat][kRun]++; - } - if (fRunNumber > 0) - FillStatHisto(kRunDone); - fRunNumber = run; - AliInfoF("Processing new run %d", fRunNumber); - // - // setup magnetic field - if (fESDEvent && - (!TGeoGlobalMagField::Instance()->GetField() || - !SmallerAbs(fESDEvent->GetMagneticField() - AliTrackerBase::GetBz(), 5e-4))) { - fESDEvent->InitMagneticField(); - } - // - if (!fUseRecoOCDB) { - AliWarning("Reco-time OCDB will NOT be preloaded"); - return; - } - LoadRecoTimeOCDB(); - // - for (int idet = 0; idet < fNDet; idet++) { - AliAlgDet* det = GetDetector(idet); - if (!det->IsDisabled()) - det->AcknowledgeNewRun(run); - } - // - // bring to virgin state - // CleanOCDB(); - // - // LoadRefOCDB(); //??? we need to get back reference OCDB ??? - // - fStat[kInpStat][kRun]++; - // -} - -//_________________________________________________________ -Bool_t AliAlgSteer::LoadRecoTimeOCDB() -{ - // Load OCDB paths used for the reconstruction of data being processed - // In order to avoid unnecessary uploads, the objects are not actually - // loaded/cached but just added as specific paths with version - AliInfoF("Preloading Reco-Time OCDB for run %d from ESD UserInfo list", fRunNumber); - // - CleanOCDB(); - // - if (!fRecoOCDBConf.IsNull() && !gSystem->AccessPathName(fRecoOCDBConf.Data(), kFileExists)) { - AliInfoF("Executing reco-time OCDB setup macro %s", fRecoOCDBConf.Data()); - gROOT->ProcessLine(Form(".x %s(%d)", fRecoOCDBConf.Data(), fRunNumber)); - if (AliCDBManager::Instance()->IsDefaultStorageSet()) - return kTRUE; - AliFatalF("macro %s failed to configure reco-time OCDB", fRecoOCDBConf.Data()); - } else - AliWarningF("No reco-time OCDB config macro %s is found, will use ESD:UserInfo", - fRecoOCDBConf.Data()); - // - if (!fESDTree) - AliFatal("Cannot preload Reco-Time OCDB since the ESD tree is not set"); - const TTree* tr = fESDTree; // go the the real ESD tree - while (tr->GetTree() && tr->GetTree() != tr) - tr = tr->GetTree(); - // - const TList* userInfo = const_cast(tr)->GetUserInfo(); - TMap* cdbMap = (TMap*)userInfo->FindObject("cdbMap"); - TList* cdbList = (TList*)userInfo->FindObject("cdbList"); - // - if (!cdbMap || !cdbList) { - userInfo->Print(); - AliFatal("Failed to extract cdbMap and cdbList from UserInfo list"); - } - // - return PreloadOCDB(fRunNumber, cdbMap, cdbList); -} + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + //FIXME(milettri): needs AliESDEvent + // // load needed info for new run + // if (run == fRunNumber) + // return; // nothing to do + // if (run > 0) { + // fStat[kAccStat][kRun]++; + // } + // if (fRunNumber > 0) + // FillStatHisto(kRunDone); + // fRunNumber = run; + // LOG(INFO) << "Processing new run " << fRunNumber; + // // + // // setup magnetic field + // if (fESDEvent && + // (!TGeoGlobalMagField::Instance()->GetField() || + // !SmallerAbs(fESDEvent->GetMagneticField() - AliTrackerBase::GetBz(), 5e-4))) { + // fESDEvent->InitMagneticField(); + // } + // // + // if (!fUseRecoOCDB) { + // LOG(WARNING) << "Reco-time OCDB will NOT be preloaded"; + // return; + // } + // LoadRecoTimeOCDB(); + // // + // for (int idet = 0; idet < fNDet; idet++) { + // AliAlgDet* det = GetDetector(idet); + // if (!det->IsDisabled()) + // det->AcknowledgeNewRun(run); + // } + // // + // // bring to virgin state + // // CleanOCDB(); + // // + // // LoadRefOCDB(); //??? we need to get back reference OCDB ??? + // // + // fStat[kInpStat][kRun]++; + // // +} + +// FIXME(milettri): needs OCDB +////_________________________________________________________ +//Bool_t AliAlgSteer::LoadRecoTimeOCDB() +//{ +// // Load OCDB paths used for the reconstruction of data being processed +// // In order to avoid unnecessary uploads, the objects are not actually +// // loaded/cached but just added as specific paths with version +// LOG(INFO) << "Preloading Reco-Time OCDB for run " << fRunNumber << " from ESD UserInfo list"; +// // +// CleanOCDB(); +// // +// if (!fRecoOCDBConf.IsNull() && !gSystem->AccessPathName(fRecoOCDBConf.Data(), kFileExists)) { +// LOG(INFO) << "Executing reco-time OCDB setup macro " << fRecoOCDBConf.Data(); +// gROOT->ProcessLine(Form(".x %s(%d)", fRecoOCDBConf.Data(), fRunNumber)); +// if (AliCDBManager::Instance()->IsDefaultStorageSet()) +// return kTRUE; +// LOG(FATAL) << "macro " << fRecoOCDBConf.Data() << " failed to configure reco-time OCDB"; +// } else +// LOG(WARNING) << "No reco-time OCDB config macro" << fRecoOCDBConf.Data() << " is found, will use ESD:UserInfo"; +// // +// if (!fESDTree) +// LOG(FATAL) << "Cannot preload Reco-Time OCDB since the ESD tree is not set"; +// const TTree* tr = fESDTree; // go the the real ESD tree +// while (tr->GetTree() && tr->GetTree() != tr) +// tr = tr->GetTree(); +// // +// const TList* userInfo = const_cast(tr)->GetUserInfo(); +// TMap* cdbMap = (TMap*)userInfo->FindObject("cdbMap"); +// TList* cdbList = (TList*)userInfo->FindObject("cdbList"); +// // +// if (!cdbMap || !cdbList) { +// userInfo->Print(); +// LOG(FATAL) << "Failed to extract cdbMap and cdbList from UserInfo list"; +// } +// // +// return PreloadOCDB(fRunNumber, cdbMap, cdbList); +//} //_________________________________________________________ AliAlgDet* AliAlgSteer::GetDetectorByVolID(Int_t vid) const @@ -1056,7 +1074,8 @@ void AliAlgSteer::Print(const Option_t* opt) const printf("%-40s:\t%d\n", "Min vertex contrib. for constraint", fVtxMinContVC); printf("%-40s:\t%d\n", "Min Ncl ITS for vertex constraint", fMinITSClforVC); printf("%-40s:\t%s\n", "SPD request for vertex constraint", - AliAlgDetITS::GetITSPattName(fITSPattforVC)); + // AliAlgDetITS::GetITSPattName(fITSPattforVC)); FIXME(milettri): needs AliAlgDetITS + "ITSNAME"); // FIXME(milettri): needs AliAlgDetITS printf("%-40s:\t%.4f/%.4f/%.2f\n", "DCAr/DCAz/Chi2 cut for vertex constraint", fMaxDCAforVC[0], fMaxDCAforVC[1], fMaxChi2forVC); printf("Collision tracks: Min pT: %5.2f |etaMax|: %5.2f\n", fPtMin[kColl], fEtaMax[kColl]); @@ -1120,106 +1139,109 @@ void AliAlgSteer::ResetDetectors() //____________________________________________ Bool_t AliAlgSteer::TestLocalSolution() { - // test track local solution - TVectorD rhs; - AliSymMatrix* mat = BuildMatrix(rhs); - if (!mat) - return kFALSE; - // mat->Print("long data"); - // rhs.Print(); - TVectorD vsl(rhs); - if (!mat->SolveChol(rhs, vsl, kTRUE)) { - delete mat; - return kFALSE; - } - // - /* - // print solution vector - int nlocpar = fAlgTrack->GetNLocPar(); - int nlocparETP = fAlgTrack->GetNLocExtPar(); // parameters of external track param - printf("ETP Update: "); - for (int i=0;inlocparETP) printf("Mat.Corr. update:\n"); - for (int ip=fAlgTrack->GetNPoints();ip--;) { - AliAlgPoint* pnt = fAlgTrack->GetPoint(ip); - int npm = pnt->GetNMatPar(); - const float* expMatCov = pnt->GetMatCorrCov(); // its error - int offs = pnt->GetMaxLocVarID() - npm; - for (int ipar=0;ipar sig:%+.3e -> pull: %+.2e\n", - ip,ipar,parI,vsl[parI],Sqrt((*mat)(parI,parI)), err,vsl[parI]/err); - } - } - */ - // - // increment current params by new solution - rhs.SetElements(fAlgTrack->GetLocPars()); - vsl += rhs; - fAlgTrack->SetLocPars(vsl.GetMatrixArray()); - fAlgTrack->CalcResiduals(); - delete mat; - // + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + //FIXME(milettri): needs AliSymMatrix + // // test track local solution + // TVectorD rhs; + // AliSymMatrix* mat = BuildMatrix(rhs); + // if (!mat) + // return kFALSE; + // // mat->Print("long data"); + // // rhs.Print(); + // TVectorD vsl(rhs); + // if (!mat->SolveChol(rhs, vsl, kTRUE)) { + // delete mat; + // return kFALSE; + // } + // // + // /* + // // print solution vector + // int nlocpar = fAlgTrack->GetNLocPar(); + // int nlocparETP = fAlgTrack->GetNLocExtPar(); // parameters of external track param + // printf("ETP Update: "); + // for (int i=0;inlocparETP) printf("Mat.Corr. update:\n"); + // for (int ip=fAlgTrack->GetNPoints();ip--;) { + // AliAlgPoint* pnt = fAlgTrack->GetPoint(ip); + // int npm = pnt->GetNMatPar(); + // const float* expMatCov = pnt->GetMatCorrCov(); // its error + // int offs = pnt->GetMaxLocVarID() - npm; + // for (int ipar=0;ipar sig:%+.3e -> pull: %+.2e\n", + // ip,ipar,parI,vsl[parI],Sqrt((*mat)(parI,parI)), err,vsl[parI]/err); + // } + // } + // */ + // // + // // increment current params by new solution + // rhs.SetElements(fAlgTrack->GetLocPars()); + // vsl += rhs; + // fAlgTrack->SetLocPars(vsl.GetMatrixArray()); + // fAlgTrack->CalcResiduals(); + // delete mat; + // // return kTRUE; } -//____________________________________________ -AliSymMatrix* AliAlgSteer::BuildMatrix(TVectorD& vec) -{ - // build matrix/vector for local track - int npnt = fAlgTrack->GetNPoints(); - int nlocpar = fAlgTrack->GetNLocPar(); - // - vec.ResizeTo(nlocpar); - memset(vec.GetMatrixArray(), 0, nlocpar * sizeof(double)); - AliSymMatrix* matp = new AliSymMatrix(nlocpar); - AliSymMatrix& mat = *matp; - // - for (int ip = npnt; ip--;) { - AliAlgPoint* pnt = fAlgTrack->GetPoint(ip); - // - if (pnt->ContainsMeasurement()) { - // pnt->Print("meas"); - for (int idim = 2; idim--;) { // each point has 2 position residuals - double sigma2 = pnt->GetErrDiag(idim); // residual error - double resid = fAlgTrack->GetResidual(idim, ip); // residual - double* deriv = fAlgTrack->GetDResDLoc(idim, ip); // array of Dresidual/Dparams - // - double sg2inv = 1. / sigma2; - for (int parI = nlocpar; parI--;) { - vec[parI] -= deriv[parI] * resid * sg2inv; - // printf("%d %d %d %+e %+e %+e -> %+e\n",ip,idim,parI,sg2inv,deriv[parI],resid,vec[parI]); - // for (int parJ=nlocpar;parJ--;) { - for (int parJ = parI + 1; parJ--;) { - mat(parI, parJ) += deriv[parI] * deriv[parJ] * sg2inv; - } - } - } // loop over 2 orthogonal measurements at the point - } // derivarives at measured points - // - // if the point contains material, consider its expected kinks, eloss - // as measurements - if (pnt->ContainsMaterial()) { - // at least 4 parameters: 2 spatial + 2 angular kinks with 0 expectaction - int npm = pnt->GetNMatPar(); - // const float* expMatCorr = pnt->GetMatCorrExp(); // expected correction (diagonalized) - const float* expMatCov = pnt->GetMatCorrCov(); // its error - int offs = pnt->GetMaxLocVarID() - npm; - for (int ipar = 0; ipar < npm; ipar++) { - int parI = offs + ipar; - // expected - // vec[parI] -= expMatCorr[ipar]/expMatCov[ipar]; // consider expectation as measurement - mat(parI, parI) += 1. / expMatCov[ipar]; // this measurement is orthogonal to all others - //printf("Pnt:%3d MatVar:%d DOF %3d | ExpVal: %+e Cov: %+e\n",ip,ipar,parI, expMatCorr[ipar], expMatCov[ipar]); - } - } // material effect descripotion params - // - } // loop over track points - // - return matp; -} +//FIXME(milettri): needs AliSymMatrix +////____________________________________________ +//AliSymMatrix* AliAlgSteer::BuildMatrix(TVectorD& vec) +//{ +// // build matrix/vector for local track +// int npnt = fAlgTrack->GetNPoints(); +// int nlocpar = fAlgTrack->GetNLocPar(); +// // +// vec.ResizeTo(nlocpar); +// memset(vec.GetMatrixArray(), 0, nlocpar * sizeof(double)); +// AliSymMatrix* matp = new AliSymMatrix(nlocpar); +// AliSymMatrix& mat = *matp; +// // +// for (int ip = npnt; ip--;) { +// AliAlgPoint* pnt = fAlgTrack->GetPoint(ip); +// // +// if (pnt->ContainsMeasurement()) { +// // pnt->Print("meas"); +// for (int idim = 2; idim--;) { // each point has 2 position residuals +// double sigma2 = pnt->GetErrDiag(idim); // residual error +// double resid = fAlgTrack->GetResidual(idim, ip); // residual +// double* deriv = fAlgTrack->GetDResDLoc(idim, ip); // array of Dresidual/Dparams +// // +// double sg2inv = 1. / sigma2; +// for (int parI = nlocpar; parI--;) { +// vec[parI] -= deriv[parI] * resid * sg2inv; +// // printf("%d %d %d %+e %+e %+e -> %+e\n",ip,idim,parI,sg2inv,deriv[parI],resid,vec[parI]); +// // for (int parJ=nlocpar;parJ--;) { +// for (int parJ = parI + 1; parJ--;) { +// mat(parI, parJ) += deriv[parI] * deriv[parJ] * sg2inv; +// } +// } +// } // loop over 2 orthogonal measurements at the point +// } // derivarives at measured points +// // +// // if the point contains material, consider its expected kinks, eloss +// // as measurements +// if (pnt->ContainsMaterial()) { +// // at least 4 parameters: 2 spatial + 2 angular kinks with 0 expectaction +// int npm = pnt->GetNMatPar(); +// // const float* expMatCorr = pnt->GetMatCorrExp(); // expected correction (diagonalized) +// const float* expMatCov = pnt->GetMatCorrCov(); // its error +// int offs = pnt->GetMaxLocVarID() - npm; +// for (int ipar = 0; ipar < npm; ipar++) { +// int parI = offs + ipar; +// // expected +// // vec[parI] -= expMatCorr[ipar]/expMatCov[ipar]; // consider expectation as measurement +// mat(parI, parI) += 1. / expMatCov[ipar]; // this measurement is orthogonal to all others +// //printf("Pnt:%3d MatVar:%d DOF %3d | ExpVal: %+e Cov: %+e\n",ip,ipar,parI, expMatCorr[ipar], expMatCov[ipar]); +// } +// } // material effect descripotion params +// // +// } // loop over track points +// // +// return matp; +//} //____________________________________________ void AliAlgSteer::InitMPRecOutput() @@ -1231,7 +1253,7 @@ void AliAlgSteer::InitMPRecOutput() TString mo = Form("%s%s", fMPDatFileName.Data(), ".root"); fMPRecFile = TFile::Open(mo.Data(), "recreate"); if (!fMPRecFile) - AliFatalF("Failed to create output file %s", mo.Data()); + LOG(FATAL) << "Failed to create output file " << mo.Data(); // fMPRecTree = new TTree("mpTree", "MPrecord Tree"); fMPRecTree->Branch("mprec", "AliAlgMPRecord", &fMPRecord); @@ -1247,7 +1269,7 @@ void AliAlgSteer::InitResidOutput() // fResidFile = TFile::Open(fResidFileName.Data(), "recreate"); if (!fResidFile) - AliFatalF("Failed to create output file %s", fResidFileName.Data()); + LOG(FATAL) << "Failed to create output file " << fResidFileName.Data(); // fResidTree = new TTree("res", "Control Residuals"); fResidTree->Branch("t", "AliAlgRes", &fCResid); @@ -1260,7 +1282,7 @@ void AliAlgSteer::CloseMPRecOutput() // close output if (!fMPRecFile) return; - AliInfoF("Closing %s", fMPRecFile->GetName()); + LOG(INFO) << "Closing " << fMPRecFile->GetName(); fMPRecFile->cd(); fMPRecTree->Write(); delete fMPRecTree; @@ -1278,7 +1300,7 @@ void AliAlgSteer::CloseResidOutput() // close output if (!fResidFile) return; - AliInfoF("Closing %s", fResidFile->GetName()); + LOG(INFO) << "Closing " << fResidFile->GetName(); fResidFile->cd(); fResidTree->Write(); delete fResidTree; @@ -1295,7 +1317,7 @@ void AliAlgSteer::CloseMilleOutput() { // close output if (fMille) - AliInfoF("Closing %s%s", fMPDatFileName.Data(), fgkMPDataExt); + LOG(INFO) << "Closing " << fMPDatFileName.Data() << fgkMPDataExt; delete fMille; fMille = 0; } @@ -1372,7 +1394,7 @@ void AliAlgSteer::SetObligatoryDetector(Int_t detID, Int_t trtype, Bool_t v) // mark detector presence obligatory in the track of given type AliAlgDet* det = GetDetectorByDetID(detID); if (!det) { - AliErrorF("Detector %d is not defined", detID); + LOG(ERROR) << "Detector " << detID << " is not defined"; } if (v) fObligatoryDetPattern[trtype] |= 0x1 << detID; @@ -1386,119 +1408,123 @@ void AliAlgSteer::SetObligatoryDetector(Int_t detID, Int_t trtype, Bool_t v) //____________________________________________ Bool_t AliAlgSteer::AddVertexConstraint() { - // if vertex is set and if particle is primary, add vertex as a meared point - // - const AliESDtrack* esdTr = fESDTrack[0]; - if (!fVertex || !esdTr) - return kFALSE; - // - if (esdTr->GetNcls(0) < fMinITSClforVC) - return kFALSE; // not enough ITS clusters - if (!AliAlgDetITS::CheckHitPattern(esdTr, fITSPattforVC)) - return kFALSE; - // - AliExternalTrackParam trc = *esdTr; - Double_t dz[2], dzCov[3]; - if (!trc.PropagateToDCA(fVertex, AliTrackerBase::GetBz(), 2 * fMaxDCAforVC[0], dz, dzCov)) - return kFALSE; - // - // check if primary candidate - if (Abs(dz[0]) > fMaxDCAforVC[0] || Abs(dz[1]) > fMaxDCAforVC[1]) - return kFALSE; - Double_t covar[6]; - fVertex->GetCovMatrix(covar); - Double_t p[2] = {trc.GetParameter()[0] - dz[0], trc.GetParameter()[1] - dz[1]}; - Double_t c[3] = {0.5 * (covar[0] + covar[2]), 0., covar[5]}; - Double_t chi2 = trc.GetPredictedChi2(p, c); - if (chi2 > fMaxChi2forVC) - return kFALSE; - // - // assing measured vertex rotated to VtxSens frame as reference point - double xyz[3], xyzT[3]; - fVertex->GetXYZ(xyz); - fVtxSens->SetAlpha(trc.GetAlpha()); - // usually translation from GLO to TRA frame should go via matrix T2G - // but for the VertexSensor Local and Global are the same frames - fVtxSens->ApplyCorrection(xyz); - fVtxSens->GetMatrixT2L().MasterToLocal(xyz, xyzT); - fRefPoint->SetSensor(fVtxSens); - fRefPoint->SetAlphaSens(fVtxSens->GetAlpTracking()); - fRefPoint->SetXYZTracking(xyzT); - fRefPoint->SetYZErrTracking(c); - fRefPoint->SetContainsMeasurement(kTRUE); - fRefPoint->Init(); - // + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + //FIXME(milettri): needs AliESDtrack + // // if vertex is set and if particle is primary, add vertex as a meared point + // // + // const AliESDtrack* esdTr = fESDTrack[0]; + // if (!fVertex || !esdTr) + // return kFALSE; + // // + // if (esdTr->GetNcls(0) < fMinITSClforVC) + // return kFALSE; // not enough ITS clusters + // if (!AliAlgDetITS::CheckHitPattern(esdTr, fITSPattforVC)) + // return kFALSE; + // // + // AliExternalTrackParam trc = *esdTr; + // Double_t dz[2], dzCov[3]; + // if (!trc.PropagateToDCA(fVertex, AliTrackerBase::GetBz(), 2 * fMaxDCAforVC[0], dz, dzCov)) + // return kFALSE; + // // + // // check if primary candidate + // if (Abs(dz[0]) > fMaxDCAforVC[0] || Abs(dz[1]) > fMaxDCAforVC[1]) + // return kFALSE; + // Double_t covar[6]; + // fVertex->GetCovMatrix(covar); + // Double_t p[2] = {trc.GetParameter()[0] - dz[0], trc.GetParameter()[1] - dz[1]}; + // Double_t c[3] = {0.5 * (covar[0] + covar[2]), 0., covar[5]}; + // Double_t chi2 = trc.GetPredictedChi2(p, c); + // if (chi2 > fMaxChi2forVC) + // return kFALSE; + // // + // // assing measured vertex rotated to VtxSens frame as reference point + // double xyz[3], xyzT[3]; + // fVertex->GetXYZ(xyz); + // fVtxSens->SetAlpha(trc.GetAlpha()); + // // usually translation from GLO to TRA frame should go via matrix T2G + // // but for the VertexSensor Local and Global are the same frames + // fVtxSens->ApplyCorrection(xyz); + // fVtxSens->GetMatrixT2L().MasterToLocal(xyz, xyzT); + // fRefPoint->SetSensor(fVtxSens); + // fRefPoint->SetAlphaSens(fVtxSens->GetAlpTracking()); + // fRefPoint->SetXYZTracking(xyzT); + // fRefPoint->SetYZErrTracking(c); + // fRefPoint->SetContainsMeasurement(kTRUE); + // fRefPoint->Init(); + // // return kTRUE; } -//______________________________________________________ -void AliAlgSteer::WriteCalibrationResults() const -{ - // writes output calibration - CleanOCDB(); - AliCDBManager::Instance()->SetDefaultStorage(fOutCDBPath.Data()); - // - AliAlgDet* det; - for (int idet = 0; idet < kNDetectors; idet++) { - if (!(det = GetDetectorByDetID(idet)) || det->IsDisabled()) - continue; - det->WriteCalibrationResults(); - } - // -} - -//______________________________________________________ -void AliAlgSteer::SetOutCDBRunRange(int rmin, int rmax) -{ - // set output run range - fOutCDBRunRange[0] = rmin >= 0 ? rmin : 0; - fOutCDBRunRange[1] = rmax > fOutCDBRunRange[0] ? rmax : AliCDBRunRange::Infinity(); -} - -//______________________________________________________ -Bool_t AliAlgSteer::LoadRefOCDB() -{ - // setup OCDB whose objects will be used as a reference with respect to which the - // alignment/calibration will prodice its corrections. - // Detectors which need some reference calibration data must use this one - // - // - AliInfo("Loading reference OCDB"); - CleanOCDB(); - AliCDBManager* man = AliCDBManager::Instance(); - // - if (!fRefOCDBConf.IsNull() && !gSystem->AccessPathName(fRefOCDBConf.Data(), kFileExists)) { - AliInfoF("Executing reference OCDB setup macro %s", fRefOCDBConf.Data()); - if (fRefRunNumber > 0) - gROOT->ProcessLine(Form(".x %s(%d)", fRefOCDBConf.Data(), fRefRunNumber)); - else - gROOT->ProcessLine(Form(".x %s", fRefOCDBConf.Data())); - } else { - AliWarningF("No reference OCDB config macro %s is found, assume raw:// with run %d", - fRefOCDBConf.Data(), AliCDBRunRange::Infinity()); - man->SetRaw(kTRUE); - man->SetRun(AliCDBRunRange::Infinity()); - } - // - if (AliGeomManager::GetGeometry()) { - AliInfo("Destroying current geometry before loading reference one"); - AliGeomManager::Destroy(); - } - AliGeomManager::LoadGeometry("geometry.root"); - if (!AliGeomManager::GetGeometry()) - AliFatal("Failed to load geometry, cannot run"); - // - TString detList = ""; - for (int i = 0; i < kNDetectors; i++) { - detList += GetDetNameByDetID(i); - detList += " "; - } - AliGeomManager::ApplyAlignObjsFromCDB(detList.Data()); - // - fRefOCDBLoaded++; - // - return kTRUE; -} +//FIXME(milettri): needs OCDB +////______________________________________________________ +//void AliAlgSteer::WriteCalibrationResults() const +//{ +// // writes output calibration +// CleanOCDB(); +// AliCDBManager::Instance()->SetDefaultStorage(fOutCDBPath.Data()); +// // +// AliAlgDet* det; +// for (int idet = 0; idet < kNDetectors; idet++) { +// if (!(det = GetDetectorByDetID(idet)) || det->IsDisabled()) +// continue; +// det->WriteCalibrationResults(); +// } +// // +//} + +//FIXME(milettri): needs OCDB +////______________________________________________________ +//void AliAlgSteer::SetOutCDBRunRange(int rmin, int rmax) +//{ +// // set output run range +// fOutCDBRunRange[0] = rmin >= 0 ? rmin : 0; +// fOutCDBRunRange[1] = rmax > fOutCDBRunRange[0] ? rmax : AliCDBRunRange::Infinity(); +//} + +//FIXME(milettri): needs OCDB +////______________________________________________________ +//Bool_t AliAlgSteer::LoadRefOCDB() +//{ +// // setup OCDB whose objects will be used as a reference with respect to which the +// // alignment/calibration will prodice its corrections. +// // Detectors which need some reference calibration data must use this one +// // +// // +// LOG(INFO) << "Loading reference OCDB"); +// CleanOCDB(); +// AliCDBManager* man = AliCDBManager::Instance(); +// // +// if (!fRefOCDBConf.IsNull() && !gSystem->AccessPathName(fRefOCDBConf.Data(), kFileExists)) { +// LOG(INFO) << "Executing reference OCDB setup macro %s", fRefOCDBConf.Data()); +// if (fRefRunNumber > 0) +// gROOT->ProcessLine(Form(".x %s(%d)", fRefOCDBConf.Data(), fRefRunNumber)); +// else +// gROOT->ProcessLine(Form(".x %s", fRefOCDBConf.Data())); +// } else { +// LOG(WARNING) << "No reference OCDB config macro "<SetRaw(kTRUE); +// man->SetRun(AliCDBRunRange::Infinity()); +// } +// // +// if (AliGeomManager::GetGeometry()) { +// LOG(INFO) << "Destroying current geometry before loading reference one"); +// AliGeomManager::Destroy(); +// } +// AliGeomManager::LoadGeometry("geometry.root"); +// if (!AliGeomManager::GetGeometry()) +// LOG(FATAL) << "Failed to load geometry, cannot run"); +// // +// TString detList = ""; +// for (int i = 0; i < kNDetectors; i++) { +// detList += GetDetNameByDetID(i); +// detList += " "; +// } +// AliGeomManager::ApplyAlignObjsFromCDB(detList.Data()); +// // +// fRefOCDBLoaded++; +// // +// return kTRUE; +//} //________________________________________________________ AliAlgDet* AliAlgSteer::GetDetOfDOFID(int id) const @@ -1582,12 +1608,10 @@ void AliAlgSteer::GenPedeSteerFile(const Option_t* opt) const const float kDefDelta = 0.1; // def. delta to exit TString opts = opt; opts.ToLower(); - AliInfoF( - "Generating MP2 templates:\n" - "Steering :\t%s\n" - "Parameters :\t%s\n" - "Constraints:\t%s\n", - fMPSteerFileName.Data(), fMPParFileName.Data(), fMPConFileName.Data()); + LOG(INFO) << "Generating MP2 templates:\n " + << "Steering :\t" << fMPSteerFileName.Data() << "\n" + << "Parameters :\t" << fMPParFileName.Data() << "\n" + << "Constraints:\t" << fMPConFileName.Data() << "\n"; // FILE* parFl = fopen(fMPParFileName.Data(), "w+"); FILE* strFl = fopen(fMPSteerFileName.Data(), "w+"); @@ -1643,8 +1667,7 @@ Bool_t AliAlgSteer::ReadParameters(const char* parfile, Bool_t useErrors) { // read parameters file (millepede output) if (fNDOFs < 1 || !fGloParVal || !fGloParErr) { - AliErrorF("Something is wrong in init: fNDOFs=%d fGloParVal=%p fGloParErr=%p", - fNDOFs, fGloParVal, fGloParErr); + LOG(ERROR) << "Something is wrong in init: fNDOFs=" << fNDOFs << " fGloParVal=" << fGloParVal << " fGloParErr=" << fGloParErr; } ifstream inpf(parfile); if (!inpf.good()) { @@ -1660,7 +1683,8 @@ Bool_t AliAlgSteer::ReadParameters(const char* parfile, Bool_t useErrors) fline = fline.Strip(TString::kBoth, ' '); fline.ToLower(); if (!fline.BeginsWith("parameter")) { - AliErrorF("First line is not parameter keyword:\n%s", fline.Data()); + LOG(ERROR) << "First line is not parameter keyword:\n" + << fline.Data(); return kFALSE; } double v0, v1, v2; @@ -1672,15 +1696,15 @@ Bool_t AliAlgSteer::ReadParameters(const char* parfile, Bool_t useErrors) continue; // ignore comment int nr = sscanf(fline.Data(), "%d%lf%lf%lf", &lab, &v0, &v1, &v2); if (nr < 3) { - AliErrorF("Expected to read at least 3 numbers, got %d, this is NOT milleped output", nr); - AliErrorF("line (%d) was:\n%s", cnt, fline.Data()); + LOG(ERROR) << "Expected to read at least 3 numbers, got " << nr << ", this is NOT milleped output"; + LOG(ERROR) << "line (" << cnt << ") was:\n " << fline.Data(); return kFALSE; } if (nr == 3) asg0++; int parID = Label2ParID(lab); if (parID < 0 || parID >= fNDOFs) { - AliErrorF("Invalid label %d at line %d -> ParID=%d", lab, cnt, parID); + LOG(ERROR) << "Invalid label " << lab << " at line " << cnt << " -> ParID=" << parID; return kFALSE; } fGloParVal[parID] = -v0; @@ -1689,7 +1713,7 @@ Bool_t AliAlgSteer::ReadParameters(const char* parfile, Bool_t useErrors) asg++; // }; - AliInfoF("Read %d lines, assigned %d values, %d dummy", cnt, asg, asg0); + LOG(INFO) << "Read " << cnt << " lines, assigned " << asg << " values, " << asg0 << " dummy"; // return kTRUE; } @@ -1700,7 +1724,7 @@ void AliAlgSteer::CheckConstraints(const char* params) // check how the constraints are satisfied with already uploaded or provided params // if (params && !ReadParameters(params)) { - AliErrorF("Failed to load parameters from %s", params); + LOG(ERROR) << "Failed to load parameters from " << params; return; } // @@ -1718,12 +1742,12 @@ void AliAlgSteer::MPRec2Mille(const char* mprecfile, const char* millefile, Bool // converts MPRecord tree to millepede binary format TFile* flmpr = TFile::Open(mprecfile); if (!flmpr) { - AliErrorClassF("Failed to open MPRecord file %s", mprecfile); + LOG(ERROR) << "Failed to open MPRecord file " << mprecfile; return; } TTree* mprTree = (TTree*)flmpr->Get("mpTree"); if (!mprTree) { - AliErrorClassF("No mpTree in xMPRecord file %s", mprecfile); + LOG(ERROR) << "No mpTree in xMPRecord file " << mprecfile; return; } MPRec2Mille(mprTree, millefile, bindata); @@ -1739,7 +1763,7 @@ void AliAlgSteer::MPRec2Mille(TTree* mprTree, const char* millefile, Bool_t bind // TBranch* br = mprTree->GetBranch("mprec"); if (!br) { - AliErrorClass("provided tree does not contain branch mprec"); + LOG(ERROR) << "provided tree does not contain branch mprec"; return; } AliAlgMPRecord* rec = new AliAlgMPRecord(); @@ -1835,7 +1859,7 @@ void AliAlgSteer::AddAutoConstraints() continue; det->AddAutoConstraints(); } - AliInfoF("Added %d automatic constraints", GetNConstraints()); + LOG(INFO) << "Added " << GetNConstraints() << " automatic constraints"; } //____________________________________________________________ @@ -1857,11 +1881,11 @@ void AliAlgSteer::FixLowStatFromDOFStat(Int_t thresh) // fix DOFs having stat below threshold // if (!fDOFStat) { - AliError("No object with DOFs statistics"); + LOG(ERROR) << "No object with DOFs statistics"; return; } if (fNDOFs != fDOFStat->GetNDOFs()) { - AliErrorF("Discrepancy between NDOFs=%d of and statistics object: %d", fNDOFs, fDOFStat->GetNDOFs()); + LOG(ERROR) << "Discrepancy between NDOFs=" << fNDOFs << " of and statistics object: " << fDOFStat->GetNDOFs(); return; } for (int parID = 0; parID < fNDOFs; parID++) { @@ -1896,11 +1920,11 @@ void AliAlgSteer::LoadStat(const char* flname) if (hstO && (hst = dynamic_cast(hstO))) hst->SetDirectory(0); else - AliWarning("did not find stat histo"); + LOG(WARNING) << "did not find stat histo"; // AliAlgDOFStat* dofSt = 0; if (!hdfO || !(dofSt = dynamic_cast(hdfO))) - AliWarning("did not find DOFstat object"); + LOG(WARNING) << "did not find DOFstat object"; // SetHistoStat(hst); SetDOFStat(dofSt); @@ -1967,261 +1991,263 @@ Bool_t AliAlgSteer::CheckSol(AliAlgMPRecord* rec, AliAlgResFast* rLG, AliAlgResFast* rL, Bool_t verbose, Bool_t loc) { - // Check pede solution using derivates, rather than updated geometry - // If loc==true, also produces residuals for current geometry, - // neglecting global corrections - // - if (rL) - loc = kTRUE; // if local sol. tree asked, always evaluate it - // - int nres = rec->GetNResid(); - // - const float* recDGlo = rec->GetArrGlo(); - const float* recDLoc = rec->GetArrLoc(); - const short* recLabLoc = rec->GetArrLabLoc(); - const int* recLabGlo = rec->GetArrLabGlo(); - int nvloc = rec->GetNVarLoc(); - // - // count number of real measurement duplets and material correction fake 4-plets - int nPoints = 0; - int nMatCorr = 0; - for (int irs = 0; irs < nres; irs++) { - if (rec->GetNDGlo(irs) > 0) { - if (irs == nres - 1 || rec->GetNDGlo(irs + 1) == 0) - AliFatal("Real coordinate measurements must come in pairs"); - nPoints++; - irs++; // skip 2nd - continue; - } else if (rec->GetResid(irs) == 0 && rec->GetVolID(irs) == -1) { // material corrections have 0 residual - nMatCorr++; - } else { // might be fixed parameter, global derivs are skept - nPoints++; - irs++; // skip 2nd - continue; - } - } - // - if (nMatCorr % 4) - AliWarningF("Error? NMatCorr=%d is not multiple of 4", nMatCorr); - // - if (rLG) { - rLG->Clear(); - rLG->SetNPoints(nPoints); - rLG->SetNMatSol(nMatCorr); - rLG->SetCosmic(rec->IsCosmic()); - } - if (rL) { - rL->Clear(); - rL->SetNPoints(nPoints); - rL->SetNMatSol(nMatCorr); - rL->SetCosmic(rec->IsCosmic()); - } - // - AliSymMatrix* matpG = new AliSymMatrix(nvloc); - TVectorD *vecp = 0, *vecpG = new TVectorD(nvloc); - // - if (loc) - vecp = new TVectorD(nvloc); - // - float chi2Ini = 0, chi2L = 0, chi2LG = 0; - // - // residuals, accounting for global solution - double* resid = new Double_t[nres]; - int* volID = new Int_t[nres]; - for (int irs = 0; irs < nres; irs++) { - double resOr = rec->GetResid(irs); - resid[irs] = resOr; - // - int ndglo = rec->GetNDGlo(irs); - int ndloc = rec->GetNDLoc(irs); - volID[irs] = 0; - for (int ig = 0; ig < ndglo; ig++) { - int lbI = recLabGlo[ig]; - int idP = Label2ParID(lbI); - if (idP < 0) - AliFatalF("Did not find parameted for label %d\n", lbI); - double parVal = GetGloParVal()[idP]; - // resid[irs] -= parVal*recDGlo[ig]; - resid[irs] += parVal * recDGlo[ig]; - if (!ig) { - AliAlgVol* vol = GetVolOfDOFID(idP); - if (vol) - volID[irs] = vol->GetVolID(); - else - volID[irs] = -2; // calibration DOF !!! TODO - } - } - // - double sg2inv = rec->GetResErr(irs); - sg2inv = 1. / (sg2inv * sg2inv); - // - chi2Ini += resid[irs] * resid[irs] * sg2inv; // chi accounting for global solution only - // - // Build matrix to solve local parameters - for (int il = 0; il < ndloc; il++) { - int lbLI = recLabLoc[il]; // id of local variable - (*vecpG)[lbLI] -= recDLoc[il] * resid[irs] * sg2inv; - if (loc) - (*vecp)[lbLI] -= recDLoc[il] * resOr * sg2inv; - for (int jl = il + 1; jl--;) { - int lbLJ = recLabLoc[jl]; // id of local variable - (*matpG)(lbLI, lbLJ) += recDLoc[il] * recDLoc[jl] * sg2inv; - } - } - // - recLabGlo += ndglo; // prepare for next record - recDGlo += ndglo; - recLabLoc += ndloc; - recDLoc += ndloc; - // - } - // - if (rL) - rL->SetChi2Ini(chi2Ini); - if (rLG) - rLG->SetChi2Ini(chi2Ini); - // - TVectorD vecSol(nvloc); - TVectorD vecSolG(nvloc); - // - if (!matpG->SolveChol(*vecpG, vecSolG, kFALSE)) { - AliInfo("Failed to solve track corrected for globals\n"); - delete matpG; - matpG = 0; - } else if (loc) { // solution with local correction only - if (!matpG->SolveChol(*vecp, vecSol, kFALSE)) { - AliInfo("Failed to solve track corrected for globals\n"); - delete matpG; - matpG = 0; - } - } - delete vecpG; - delete vecp; - if (!matpG) { // failed - delete[] resid; - delete[] volID; - if (rLG) - rLG->Clear(); - if (rL) - rL->Clear(); - return kFALSE; - } - // check - recDGlo = rec->GetArrGlo(); - recDLoc = rec->GetArrLoc(); - recLabLoc = rec->GetArrLabLoc(); - recLabGlo = rec->GetArrLabGlo(); - // - if (verbose) { - printf(loc ? "Sol L/LG:\n" : "Sol LG:\n"); - int nExtP = (nvloc % 4) ? 5 : 4; - for (int i = 0; i < nExtP; i++) - loc ? printf("%+.3e/%+.3e ", vecSol[i], vecSolG[i]) : printf("%+.3e ", vecSolG[i]); - printf("\n"); - Bool_t nln = kTRUE; - int cntL = 0; - for (int i = nExtP; i < nvloc; i++) { - nln = kTRUE; - loc ? printf("%+.3e/%+.3e ", vecSol[i], vecSolG[i]) : printf("%+.3e ", vecSolG[i]); - if (((++cntL) % 4) == 0) { - printf("\n"); - nln = kFALSE; - } - } - if (!nln) - printf("\n"); - if (loc) - printf("%3s (%9s) %6s | [ %7s:%7s ] [ %7s:%7s ]\n", "Pnt", "Label", - "Sigma", "resid", "pull/L ", "resid", "pull/LG"); - else - printf("%3s (%9s) %6s | [ %7s:%7s ]\n", "Pnt", "Label", - "Sigma", "resid", "pull/LG"); - } - int idMeas = -1, pntID = -1, matID = -1; - for (int irs = 0; irs < nres; irs++) { - double resOr = rec->GetResid(irs); - double resL = resOr; - double resLG = resid[irs]; - double sg = rec->GetResErr(irs); - double sg2Inv = 1 / (sg * sg); - // - int ndglo = rec->GetNDGlo(irs); - int ndloc = rec->GetNDLoc(irs); - // - for (int il = 0; il < ndloc; il++) { - int lbLI = recLabLoc[il]; // id of local variable - resL += recDLoc[il] * vecSol[lbLI]; - resLG += recDLoc[il] * vecSolG[lbLI]; - } - // - chi2L += resL * resL * sg2Inv; // chi accounting for global solution only - chi2LG += resLG * resLG * sg2Inv; // chi accounting for global solution only - // - if (ndglo || resOr != 0) { // real measurement - idMeas++; - if (idMeas > 1) - idMeas = 0; - if (idMeas == 0) - pntID++; // measurements come in pairs - int lbl = rec->GetVolID(irs); - lbl = ndglo ? recLabGlo[0] : 0; // TMP, until VolID is filled // RS!!!! - if (rLG) { - rLG->SetResSigMeas(pntID, idMeas, resLG, sg); - if (idMeas == 0) - rLG->SetLabel(pntID, lbl, volID[irs]); - } - if (rL) { - rL->SetResSigMeas(pntID, idMeas, resL, sg); - if (idMeas == 0) - rL->SetLabel(pntID, lbl, volID[irs]); - } - } else { - matID++; // mat.correcitons come in 4-plets, but we fill each separately - // - if (rLG) - rLG->SetMatCorr(matID, resLG, sg); - if (rL) - rL->SetMatCorr(matID, resL, sg); - } - // - if (verbose) { - int lbl = rec->GetVolID(irs); - lbl = ndglo ? recLabGlo[0] : (resOr == 0 ? -1 : 0); // TMP, until VolID is filled // RS!!!! - if (loc) - printf("%3d (%9d) %6.4f | [%+.2e:%+7.2f] [%+.2e:%+7.2f]\n", - irs, lbl, sg, resL, resL / sg, resLG, resLG / sg); - else - printf("%3d (%9d) %6.4f | [%+.2e:%+7.2f]\n", - irs, lbl, sg, resLG, resLG / sg); - } - // - recLabGlo += ndglo; // prepare for next record - recDGlo += ndglo; - recLabLoc += ndloc; - recDLoc += ndloc; - } - if (rL) - rL->SetChi2(chi2L); - if (rLG) - rLG->SetChi2(chi2LG); - // - if (verbose) { - printf("Chi: G = %e | LG = %e", chi2Ini, chi2LG); - if (loc) - printf(" | L = %e", chi2L); - printf("\n"); - } - // store track corrections - int nTrCor = nvloc - matID - 1; - for (int i = 0; i < nTrCor; i++) { - if (rLG) - rLG->GetTrCor()[i] = vecSolG[i]; - if (rL) - rL->GetTrCor()[i] = vecSol[i]; - } - // - delete[] resid; - delete[] volID; + LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + //FIXME(milettri): needs AliSymMatrix + // // Check pede solution using derivates, rather than updated geometry + // // If loc==true, also produces residuals for current geometry, + // // neglecting global corrections + // // + // if (rL) + // loc = kTRUE; // if local sol. tree asked, always evaluate it + // // + // int nres = rec->GetNResid(); + // // + // const float* recDGlo = rec->GetArrGlo(); + // const float* recDLoc = rec->GetArrLoc(); + // const short* recLabLoc = rec->GetArrLabLoc(); + // const int* recLabGlo = rec->GetArrLabGlo(); + // int nvloc = rec->GetNVarLoc(); + // // + // // count number of real measurement duplets and material correction fake 4-plets + // int nPoints = 0; + // int nMatCorr = 0; + // for (int irs = 0; irs < nres; irs++) { + // if (rec->GetNDGlo(irs) > 0) { + // if (irs == nres - 1 || rec->GetNDGlo(irs + 1) == 0) + // LOG(FATAL) << ("Real coordinate measurements must come in pairs"); + // nPoints++; + // irs++; // skip 2nd + // continue; + // } else if (rec->GetResid(irs) == 0 && rec->GetVolID(irs) == -1) { // material corrections have 0 residual + // nMatCorr++; + // } else { // might be fixed parameter, global derivs are skept + // nPoints++; + // irs++; // skip 2nd + // continue; + // } + // } + // // + // if (nMatCorr % 4) + // LOG(WARNING) << "Error? NMatCorr=" << nMatCorr << " is not multiple of 4"; + // // + // if (rLG) { + // rLG->Clear(); + // rLG->SetNPoints(nPoints); + // rLG->SetNMatSol(nMatCorr); + // rLG->SetCosmic(rec->IsCosmic()); + // } + // if (rL) { + // rL->Clear(); + // rL->SetNPoints(nPoints); + // rL->SetNMatSol(nMatCorr); + // rL->SetCosmic(rec->IsCosmic()); + // } + // // + // AliSymMatrix* matpG = new AliSymMatrix(nvloc); + // TVectorD *vecp = 0, *vecpG = new TVectorD(nvloc); + // // + // if (loc) + // vecp = new TVectorD(nvloc); + // // + // float chi2Ini = 0, chi2L = 0, chi2LG = 0; + // // + // // residuals, accounting for global solution + // double* resid = new Double_t[nres]; + // int* volID = new Int_t[nres]; + // for (int irs = 0; irs < nres; irs++) { + // double resOr = rec->GetResid(irs); + // resid[irs] = resOr; + // // + // int ndglo = rec->GetNDGlo(irs); + // int ndloc = rec->GetNDLoc(irs); + // volID[irs] = 0; + // for (int ig = 0; ig < ndglo; ig++) { + // int lbI = recLabGlo[ig]; + // int idP = Label2ParID(lbI); + // if (idP < 0) + // LOG(FATAL) << "Did not find parameted for label " << lbI; + // double parVal = GetGloParVal()[idP]; + // // resid[irs] -= parVal*recDGlo[ig]; + // resid[irs] += parVal * recDGlo[ig]; + // if (!ig) { + // AliAlgVol* vol = GetVolOfDOFID(idP); + // if (vol) + // volID[irs] = vol->GetVolID(); + // else + // volID[irs] = -2; // calibration DOF !!! TODO + // } + // } + // // + // double sg2inv = rec->GetResErr(irs); + // sg2inv = 1. / (sg2inv * sg2inv); + // // + // chi2Ini += resid[irs] * resid[irs] * sg2inv; // chi accounting for global solution only + // // + // // Build matrix to solve local parameters + // for (int il = 0; il < ndloc; il++) { + // int lbLI = recLabLoc[il]; // id of local variable + // (*vecpG)[lbLI] -= recDLoc[il] * resid[irs] * sg2inv; + // if (loc) + // (*vecp)[lbLI] -= recDLoc[il] * resOr * sg2inv; + // for (int jl = il + 1; jl--;) { + // int lbLJ = recLabLoc[jl]; // id of local variable + // (*matpG)(lbLI, lbLJ) += recDLoc[il] * recDLoc[jl] * sg2inv; + // } + // } + // // + // recLabGlo += ndglo; // prepare for next record + // recDGlo += ndglo; + // recLabLoc += ndloc; + // recDLoc += ndloc; + // // + // } + // // + // if (rL) + // rL->SetChi2Ini(chi2Ini); + // if (rLG) + // rLG->SetChi2Ini(chi2Ini); + // // + // TVectorD vecSol(nvloc); + // TVectorD vecSolG(nvloc); + // // + // if (!matpG->SolveChol(*vecpG, vecSolG, kFALSE)) { + // LOG(INFO) << "Failed to solve track corrected for globals"; + // delete matpG; + // matpG = 0; + // } else if (loc) { // solution with local correction only + // if (!matpG->SolveChol(*vecp, vecSol, kFALSE)) { + // LOG(INFO) << "Failed to solve track corrected for globals"; + // delete matpG; + // matpG = 0; + // } + // } + // delete vecpG; + // delete vecp; + // if (!matpG) { // failed + // delete[] resid; + // delete[] volID; + // if (rLG) + // rLG->Clear(); + // if (rL) + // rL->Clear(); + // return kFALSE; + // } + // // check + // recDGlo = rec->GetArrGlo(); + // recDLoc = rec->GetArrLoc(); + // recLabLoc = rec->GetArrLabLoc(); + // recLabGlo = rec->GetArrLabGlo(); + // // + // if (verbose) { + // printf(loc ? "Sol L/LG:\n" : "Sol LG:\n"); + // int nExtP = (nvloc % 4) ? 5 : 4; + // for (int i = 0; i < nExtP; i++) + // loc ? printf("%+.3e/%+.3e ", vecSol[i], vecSolG[i]) : printf("%+.3e ", vecSolG[i]); + // printf("\n"); + // Bool_t nln = kTRUE; + // int cntL = 0; + // for (int i = nExtP; i < nvloc; i++) { + // nln = kTRUE; + // loc ? printf("%+.3e/%+.3e ", vecSol[i], vecSolG[i]) : printf("%+.3e ", vecSolG[i]); + // if (((++cntL) % 4) == 0) { + // printf("\n"); + // nln = kFALSE; + // } + // } + // if (!nln) + // printf("\n"); + // if (loc) + // printf("%3s (%9s) %6s | [ %7s:%7s ] [ %7s:%7s ]\n", "Pnt", "Label", + // "Sigma", "resid", "pull/L ", "resid", "pull/LG"); + // else + // printf("%3s (%9s) %6s | [ %7s:%7s ]\n", "Pnt", "Label", + // "Sigma", "resid", "pull/LG"); + // } + // int idMeas = -1, pntID = -1, matID = -1; + // for (int irs = 0; irs < nres; irs++) { + // double resOr = rec->GetResid(irs); + // double resL = resOr; + // double resLG = resid[irs]; + // double sg = rec->GetResErr(irs); + // double sg2Inv = 1 / (sg * sg); + // // + // int ndglo = rec->GetNDGlo(irs); + // int ndloc = rec->GetNDLoc(irs); + // // + // for (int il = 0; il < ndloc; il++) { + // int lbLI = recLabLoc[il]; // id of local variable + // resL += recDLoc[il] * vecSol[lbLI]; + // resLG += recDLoc[il] * vecSolG[lbLI]; + // } + // // + // chi2L += resL * resL * sg2Inv; // chi accounting for global solution only + // chi2LG += resLG * resLG * sg2Inv; // chi accounting for global solution only + // // + // if (ndglo || resOr != 0) { // real measurement + // idMeas++; + // if (idMeas > 1) + // idMeas = 0; + // if (idMeas == 0) + // pntID++; // measurements come in pairs + // int lbl = rec->GetVolID(irs); + // lbl = ndglo ? recLabGlo[0] : 0; // TMP, until VolID is filled // RS!!!! + // if (rLG) { + // rLG->SetResSigMeas(pntID, idMeas, resLG, sg); + // if (idMeas == 0) + // rLG->SetLabel(pntID, lbl, volID[irs]); + // } + // if (rL) { + // rL->SetResSigMeas(pntID, idMeas, resL, sg); + // if (idMeas == 0) + // rL->SetLabel(pntID, lbl, volID[irs]); + // } + // } else { + // matID++; // mat.correcitons come in 4-plets, but we fill each separately + // // + // if (rLG) + // rLG->SetMatCorr(matID, resLG, sg); + // if (rL) + // rL->SetMatCorr(matID, resL, sg); + // } + // // + // if (verbose) { + // int lbl = rec->GetVolID(irs); + // lbl = ndglo ? recLabGlo[0] : (resOr == 0 ? -1 : 0); // TMP, until VolID is filled // RS!!!! + // if (loc) + // printf("%3d (%9d) %6.4f | [%+.2e:%+7.2f] [%+.2e:%+7.2f]\n", + // irs, lbl, sg, resL, resL / sg, resLG, resLG / sg); + // else + // printf("%3d (%9d) %6.4f | [%+.2e:%+7.2f]\n", + // irs, lbl, sg, resLG, resLG / sg); + // } + // // + // recLabGlo += ndglo; // prepare for next record + // recDGlo += ndglo; + // recLabLoc += ndloc; + // recDLoc += ndloc; + // } + // if (rL) + // rL->SetChi2(chi2L); + // if (rLG) + // rLG->SetChi2(chi2LG); + // // + // if (verbose) { + // printf("Chi: G = %e | LG = %e", chi2Ini, chi2LG); + // if (loc) + // printf(" | L = %e", chi2L); + // printf("\n"); + // } + // // store track corrections + // int nTrCor = nvloc - matID - 1; + // for (int i = 0; i < nTrCor; i++) { + // if (rLG) + // rLG->GetTrCor()[i] = vecSolG[i]; + // if (rL) + // rL->GetTrCor()[i] = vecSol[i]; + // } + // // + // delete[] resid; + // delete[] volID; return kTRUE; } @@ -2229,7 +2255,7 @@ Bool_t AliAlgSteer::CheckSol(AliAlgMPRecord* rec, void AliAlgSteer::ApplyAlignmentFromMPSol() { // apply alignment from millepede solution array to reference alignment level - AliInfo("Applying alignment from Millepede solution"); + LOG(INFO) << "Applying alignment from Millepede solution"; for (int idt = 0; idt < kNDetectors; idt++) { AliAlgDet* det = GetDetectorByDetID(idt); if (!det || det->IsDisabled()) diff --git a/Detectors/Align/src/AlignLinkDef.h b/Detectors/Align/src/AlignLinkDef.h index 6fa11704e0baf..010f54d85087b 100644 --- a/Detectors/Align/src/AlignLinkDef.h +++ b/Detectors/Align/src/AlignLinkDef.h @@ -18,7 +18,7 @@ //#pragma link C++ class o2::align::AliAlgSensTPC + ; //#pragma link C++ class o2::align::AliAlgSensTRD + ; //#pragma link C++ class o2::align::AliAlgSensHMPID + ; -//#pragma link C++ class o2::align::AliAlgSteer + ; +#pragma link C++ class o2::align::AliAlgSteer + ; #pragma link C++ class o2::align::AliAlgTrack + ; #pragma link C++ class o2::align::AliAlgVol + ; #pragma link C++ class o2::align::AliAlgVtx + ; From 28a1c0bcfe9dcaa40e0be318d100e40affb7c027 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Fri, 19 Feb 2021 16:12:07 +0100 Subject: [PATCH 209/770] [ALIGN] replace AliGeoManager --- Detectors/Align/CMakeLists.txt | 1 + Detectors/Align/include/Align/AliAlgDet.h | 5 +- Detectors/Align/include/Align/AliAlgSteer.h | 2 +- Detectors/Align/src/AliAlgDet.cxx | 9 +-- Detectors/Align/src/AliAlgSens.cxx | 17 ++++-- Detectors/Align/src/AliAlgSteer.cxx | 4 +- Detectors/Align/src/AliAlgVol.cxx | 62 ++++++++++----------- 7 files changed, 52 insertions(+), 48 deletions(-) diff --git a/Detectors/Align/CMakeLists.txt b/Detectors/Align/CMakeLists.txt index 6d3279f448fea..5a75a6d1a77d0 100644 --- a/Detectors/Align/CMakeLists.txt +++ b/Detectors/Align/CMakeLists.txt @@ -35,6 +35,7 @@ o2_add_library(Align src/Mille.cxx PUBLIC_LINK_LIBRARIES O2::FrameworkLogger O2::ReconstructionDataFormats + O2::DetectorsBase ROOT::Core ROOT::Geom ROOT::Gpad diff --git a/Detectors/Align/include/Align/AliAlgDet.h b/Detectors/Align/include/Align/AliAlgDet.h index e5ad1ccbbc8f9..cf54dff6167bf 100644 --- a/Detectors/Align/include/Align/AliAlgDet.h +++ b/Detectors/Align/include/Align/AliAlgDet.h @@ -36,6 +36,7 @@ namespace o2 namespace align { +//TODO(milettri) : fix possibly incompatible Detector IDs of O2 and AliROOT class AliAlgDet : public TNamed { public: @@ -44,10 +45,12 @@ class AliAlgDet : public TNamed enum { kNMaxKalibDOF = 64 }; // AliAlgDet(); - AliAlgDet(const char* name, const char* title = "") : TNamed(name, title) {} + AliAlgDet(const char* name, const char* title = "", Int_t id = -1) : TNamed(name, title) { SetUniqueID(id); }; virtual ~AliAlgDet(); Int_t GetDetID() const { return GetUniqueID(); } + detectors::DetID GetO2DetID() const { return detectors::DetID(GetUniqueID()); }; void SetDetID(UInt_t tp); + void SetDetID(detectors::DetID id) { SetUniqueID(id); } // virtual void CacheReferenceOCDB(); virtual void AcknowledgeNewRun(Int_t run); diff --git a/Detectors/Align/include/Align/AliAlgSteer.h b/Detectors/Align/include/Align/AliAlgSteer.h index 4af107730681c..10e155b562a96 100644 --- a/Detectors/Align/include/Align/AliAlgSteer.h +++ b/Detectors/Align/include/Align/AliAlgSteer.h @@ -21,7 +21,7 @@ #ifndef ALIALGSTEER_H #define ALIALGSTEER_H -// #include "AliGeomManager.h" FIXME(milettri): needs AliGeomManager +#include "DetectorsBase/GeometryManager.h" #include "Align/AliAlgTrack.h" // #include "AliSymMatrix.h" FIXME(milettri): needs AliSymMatrix diff --git a/Detectors/Align/src/AliAlgDet.cxx b/Detectors/Align/src/AliAlgDet.cxx index 68023f2b25920..96c26bbe77e2f 100644 --- a/Detectors/Align/src/AliAlgDet.cxx +++ b/Detectors/Align/src/AliAlgDet.cxx @@ -421,12 +421,9 @@ void AliAlgDet::Print(const Option_t* opt) const //____________________________________________ void AliAlgDet::SetDetID(UInt_t tp) { - // assign type - if (tp >= AliAlgSteer::kNDetectors) - LOG(FATAL) << "Detector typeID " << tp << "exceeds allowed range" << 0 << ":" << (AliAlgSteer::kNDetectors - 1); - if (tp >= 5) - LOG(FATAL) << "Detector typeID " << tp << "exceeds allowed range" << 0 << ":" << (5 - 1); - SetUniqueID(tp); + o2::detectors::DetID detID(tp); + SetUniqueID(detID); + LOG(WARNING) << __PRETTY_FUNCTION__ << "Possible discrepancies with o2 detector ID"; } //____________________________________________ diff --git a/Detectors/Align/src/AliAlgSens.cxx b/Detectors/Align/src/AliAlgSens.cxx index d1d1df4e19b9c..f38507cc761f0 100644 --- a/Detectors/Align/src/AliAlgSens.cxx +++ b/Detectors/Align/src/AliAlgSens.cxx @@ -365,13 +365,20 @@ void AliAlgSens::Print(const Option_t* opt) const //____________________________________________ void AliAlgSens::PrepareMatrixT2L() { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; - // TODO(milettri): depends on AliGeomManager; - // // extract from geometry T2L matrix + // extract geometry T2L matrix + TGeoHMatrix t2l; + t2l.Clear(); + t2l.RotateZ(fAlp * RadToDeg()); // rotate in direction of normal to the sensor plane + const TGeoHMatrix* matL2G = base::GeometryManager::getMatrix(fDet->GetO2DetID(), GetSID()); + const TGeoHMatrix& matL2Gi = matL2G->Inverse(); + t2l.MultiplyLeft(&matL2Gi); + SetMatrixT2L(t2l); + // const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(GetVolID()); - // if (!t2l) { + // const if (!t2l) + // { // Print("long"); - // AliFatalF("Failed to find T2L matrix for VID:%d %s", GetVolID(), GetSymName()); + // LOG(FATAL) << "Failed to find T2L matrix for VID: " << GetVolID() << ", " << GetSymName(); // } // SetMatrixT2L(*t2l); // // diff --git a/Detectors/Align/src/AliAlgSteer.cxx b/Detectors/Align/src/AliAlgSteer.cxx index 369a477a806e6..c1f1366918f43 100644 --- a/Detectors/Align/src/AliAlgSteer.cxx +++ b/Detectors/Align/src/AliAlgSteer.cxx @@ -65,8 +65,8 @@ namespace align const Char_t* AliAlgSteer::fgkMPDataExt = ".mille"; const Char_t* AliAlgSteer::fgkDetectorName[AliAlgSteer::kNDetectors] = {"ITS", "TPC", "TRD", "TOF", "HMPID"}; //const Int_t AliAlgSteer::fgkSkipLayers[AliAlgSteer::kNLrSkip] = {AliGeomManager::kPHOS1, AliGeomManager::kPHOS2, -// AliGeomManager::kMUON, AliGeomManager::kEMCAL}; FIXME(milettri): needs AliGeomManager -const Int_t AliAlgSteer::fgkSkipLayers[AliAlgSteer::kNLrSkip] = {0, 0, 0, 0}; // FIXME(milettri): needs AliGeomManager +// AliGeomManager::kMUON, AliGeomManager::kEMCAL}; TODO(milettri, shahoian): needs detector IDs previously stored in AliGeomManager +const Int_t AliAlgSteer::fgkSkipLayers[AliAlgSteer::kNLrSkip] = {0, 0, 0, 0}; // TODO(milettri, shahoian): needs AliGeomManager - remove this line after fix. const Char_t* AliAlgSteer::fgkStatClName[AliAlgSteer::kNStatCl] = {"Inp: ", "Acc: "}; const Char_t* AliAlgSteer::fgkStatName[AliAlgSteer::kMaxStat] = diff --git a/Detectors/Align/src/AliAlgVol.cxx b/Detectors/Align/src/AliAlgVol.cxx index ae35ed232cbb4..7107aca03d004 100644 --- a/Detectors/Align/src/AliAlgVol.cxx +++ b/Detectors/Align/src/AliAlgVol.cxx @@ -99,7 +99,7 @@ #include "Align/AliAlgDOFStat.h" #include "Align/AliAlgConstraint.h" //#include "AliAlignObjParams.h" -//#include "AliGeomManager.h" +#include "DetectorsBase/GeometryManager.h" #include "Align/AliAlgAux.h" #include "Framework/Logger.h" #include @@ -297,43 +297,39 @@ void AliAlgVol::Print(const Option_t* opt) const //____________________________________________ void AliAlgVol::PrepareMatrixL2G(Bool_t reco) { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; - // FIXME(milettri): needs AliGeomManager - // // extract from geometry L2G matrix, depending on reco flag, set it as a reco-time - // // or current alignment matrix - // const char* path = GetSymName(); - // if (gGeoManager->GetAlignableEntry(path)) { - // const TGeoHMatrix* l2g = AliGeomManager::GetMatrix(path); - // if (!l2g) - // LOG(FATAL) << "Failed to find L2G matrix for alignable " << path; - // reco ? SetMatrixL2GReco(*l2g) : SetMatrixL2G(*l2g); - // } else { // extract from path - // if (!gGeoManager->CheckPath(path)) - // LOG(FATAL) << "Volume path " << path << " is not valid!"; - // TGeoPhysicalNode* node = (TGeoPhysicalNode*)gGeoManager->GetListOfPhysicalNodes()->FindObject(path); - // TGeoHMatrix l2g; - // if (!node) { - // LOG(WARNING) << "volume " << path << " was not misaligned, extracting original matrix"; - // if (!AliGeomManager::GetOrigGlobalMatrix(path, l2g)) { - // LOG(FATAL) << "Failed to find ideal L2G matrix for " << path; - // } - // } else { - // l2g = *node->GetMatrix(); - // } - // reco ? SetMatrixL2GReco(l2g) : SetMatrixL2G(l2g); - // } + // extract from geometry L2G matrix, depending on reco flag, set it as a reco-time + // or current alignment matrix + const char* path = GetSymName(); + if (gGeoManager->GetAlignableEntry(path)) { + const TGeoHMatrix* l2g = base::GeometryManager::getMatrix(path); + if (!l2g) + LOG(FATAL) << "Failed to find L2G matrix for alignable " << path; + reco ? SetMatrixL2GReco(*l2g) : SetMatrixL2G(*l2g); + } else { // extract from path + if (!gGeoManager->CheckPath(path)) + LOG(FATAL) << "Volume path " << path << " is not valid!"; + TGeoPhysicalNode* node = (TGeoPhysicalNode*)gGeoManager->GetListOfPhysicalNodes()->FindObject(path); + TGeoHMatrix l2g; + if (!node) { + LOG(WARNING) << "volume " << path << " was not misaligned, extracting original matrix"; + if (!base::GeometryManager::getOriginalMatrix(path, l2g)) { + LOG(FATAL) << "Failed to find ideal L2G matrix for " << path; + } + } else { + l2g = *node->GetMatrix(); + } + reco ? SetMatrixL2GReco(l2g) : SetMatrixL2G(l2g); + } } //____________________________________________ void AliAlgVol::PrepareMatrixL2GIdeal() { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; - // FIXME(milettri): needs AliGeomManager - // // extract from geometry ideal L2G matrix - // TGeoHMatrix mtmp; - // if (!AliGeomManager::GetOrigGlobalMatrix(GetSymName(), mtmp)) - // LOG(FATAL) << "Failed to find ideal L2G matrix for " << GetSymName(); - // SetMatrixL2GIdeal(mtmp); + // extract from geometry ideal L2G matrix + TGeoHMatrix mtmp; + if (!base::GeometryManager::getOriginalMatrix(GetSymName(), mtmp)) + LOG(FATAL) << "Failed to find ideal L2G matrix for " << GetSymName(); + SetMatrixL2GIdeal(mtmp); } //____________________________________________ From b1a28c2ff6ce9955dbbe40096aef2bf611143b3e Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Mon, 22 Feb 2021 15:53:37 +0100 Subject: [PATCH 210/770] [ALIGN] replace AliAlignObjParams --- Detectors/Align/CMakeLists.txt | 3 +- Detectors/Align/src/AliAlgConstraint.cxx | 254 ++++++++++++----------- Detectors/Align/src/AliAlgVol.cxx | 102 ++++----- 3 files changed, 186 insertions(+), 173 deletions(-) diff --git a/Detectors/Align/CMakeLists.txt b/Detectors/Align/CMakeLists.txt index 5a75a6d1a77d0..766a1c77f30e9 100644 --- a/Detectors/Align/CMakeLists.txt +++ b/Detectors/Align/CMakeLists.txt @@ -35,7 +35,8 @@ o2_add_library(Align src/Mille.cxx PUBLIC_LINK_LIBRARIES O2::FrameworkLogger O2::ReconstructionDataFormats - O2::DetectorsBase + O2::DetectorsCommonDataFormats + O2::DetectorsBase ROOT::Core ROOT::Geom ROOT::Gpad diff --git a/Detectors/Align/src/AliAlgConstraint.cxx b/Detectors/Align/src/AliAlgConstraint.cxx index 311fda884494f..b55386acae1e5 100644 --- a/Detectors/Align/src/AliAlgConstraint.cxx +++ b/Detectors/Align/src/AliAlgConstraint.cxx @@ -14,7 +14,7 @@ /// @brief Descriptor of geometrical constraint #include "Align/AliAlgConstraint.h" -//#include "AliAlignObjParams.h" +#include "DetectorsCommonDataFormats/AlignParam.h" #include "Align/AliAlgAux.h" #include "Framework/Logger.h" #include @@ -170,129 +170,137 @@ void AliAlgConstraint::WriteChildrenConstraints(FILE* conOut) const //______________________________________________________ void AliAlgConstraint::CheckConstraint() const { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; - //FIXME(milettri) needs AliAlignObjParams - // // check how the constraints are satysfied - // // - // int nch = GetNChildren(); - // if (!nch) - // return; - // // - // Bool_t doJac = !GetNoJacobian(); // do we need jacobian evaluation? - // float* cstrArr = new float[nch * kNDOFGeom * kNDOFGeom]; - // memset(cstrArr, 0, nch * kNDOFGeom * kNDOFGeom * sizeof(float)); - // // we need for each children the matrix for vector transformation from children frame - // // (in which its DOFs are defined, LOC or TRA) to this parent variation frame - // // matRel = mPar^-1*mChild - // TGeoHMatrix mPar; - // // in case of parent assigned use its matrix, - // // otherwise Alice global frame is assumed to be the parent -> Unit matrix - // if (fParent && doJac) { - // if (fParent->IsFrameTRA()) - // fParent->GetMatrixT2G(mPar); // tracking to global - // else - // mPar = fParent->GetMatrixL2GIdeal(); // local to global - // mPar = mPar.Inverse(); - // } - // // - // float* jac = cstrArr; - // double parsTotEx[kNDOFGeom] = {0}; // explicitly calculated total modification - // double parsTotAn[kNDOFGeom] = {0}; // analyticaly calculated total modification - // // - // printf("\n\n ----- Constraints Validation for %s %s ------\n", GetName(), GetTitle()); - // printf(" chld| "); - // for (int jp = 0; jp < kNDOFGeom; jp++) - // printf(" %3s:%3s An/Ex |", GetDOFName(jp), IsDOFConstrained(jp) ? "ON " : "OFF"); - // printf(" | "); - // for (int jp = 0; jp < kNDOFGeom; jp++) - // printf(" D%3s ", GetDOFName(jp)); - // printf(" ! %s\n", GetName()); - // for (int ich = 0; ich < nch; ich++) { - // AliAlgVol* child = GetChild(ich); - // double parsC[kNDOFGeom] = {0}, parsPAn[kNDOFGeom] = {0}, parsPEx[kNDOFGeom] = {0}; - // for (int jc = kNDOFGeom; jc--;) - // parsC[jc] = child->GetParVal(jc); // child params in child frame - // printf("#%3d | ", ich); - // // - // if (doJac) { - // TGeoHMatrix matRel; - // if (child->IsFrameTRA()) - // child->GetMatrixT2G(matRel); // tracking to global - // else - // matRel = child->GetMatrixL2GIdeal(); // local to global - // // - // matRel.MultiplyLeft(&mPar); - // ConstrCoefGeom(matRel, jac); // Jacobian for analytical constraint used by MillePeded - // // - // TGeoHMatrix tau; - // child->Delta2Matrix(tau, parsC); // child correction matrix in the child frame - // const TGeoHMatrix& matreli = matRel.Inverse(); - // tau.Multiply(&matreli); - // tau.MultiplyLeft(&matRel); // child correction matrix in the parent frame - // AliAlignObjParams tmpPar; - // tmpPar.SetMatrix(tau); - // tmpPar.GetTranslation(&parsPEx[0]); - // tmpPar.GetAngles(&parsPEx[3]); // explicitly calculated child params in parent frame - // // - // // analytically calculated child params in parent frame - // for (int jp = 0; jp < kNDOFGeom; jp++) { - // for (int jc = 0; jc < kNDOFGeom; jc++) - // parsPAn[jp] += jac[jp * kNDOFGeom + jc] * parsC[jc]; - // parsTotAn[jp] += parsPAn[jp]; // analyticaly calculated total modification - // parsTotEx[jp] += parsPEx[jp]; // explicitly calculated total modification - // // - // printf("%+.1e/%+.1e ", parsPAn[jp], parsPEx[jp]); - // // - // } - // // - // jac += kNDOFGeom * kNDOFGeom; // matrix for next slot - // } else { - // for (int jc = 0; jc < kNDOFGeom; jc++) { - // Bool_t acc = child->IsFreeDOF(jc) && child->GetParErr(jc) >= 0; - // if (acc) { - // printf(" %+.3e ", parsC[jc]); - // parsTotAn[jc] += parsC[jc]; - // } else - // printf(" /* %+.3e */ ", parsC[jc]); // just for info, not in the constraint - // } - // } - // printf(" | "); - // for (int jc = 0; jc < kNDOFGeom; jc++) - // printf("%+.1e ", parsC[jc]); // child proper corrections - // printf(" ! %s\n", child->GetSymName()); - // } - // // - // printf(" Tot | "); - // for (int jp = 0; jp < kNDOFGeom; jp++) { - // if (doJac) - // printf("%+.1e/%+.1e ", parsTotAn[jp], parsTotEx[jp]); - // else { - // if (IsDOFConstrained(jp)) - // printf(" %+.3e ", parsTotAn[jp]); - // else - // printf(" /* %+.3e */ ", parsTotAn[jp]); - // } - // } - // printf(" | "); - // if (fParent) - // for (int jp = 0; jp < kNDOFGeom; jp++) - // printf("%+.1e ", fParent->GetParVal(jp)); // parent proper corrections - // else - // printf(" no parent -> %s ", doJac ? "Global" : "Simple"); - // printf(" ! <----- %s\n", GetName()); - // // - // printf(" Sig | "); - // for (int jp = 0; jp < kNDOFGeom; jp++) { - // if (IsDOFConstrained(jp)) - // printf(" %+.3e ", fSigma[jp]); - // else - // printf(" /* %+.3e */ ", fSigma[jp]); - // } - // printf(" ! <----- \n"); + // check how the constraints are satysfied + int nch = GetNChildren(); + if (!nch) + return; + // + Bool_t doJac = !GetNoJacobian(); // do we need jacobian evaluation? + float* cstrArr = new float[nch * kNDOFGeom * kNDOFGeom]; + memset(cstrArr, 0, nch * kNDOFGeom * kNDOFGeom * sizeof(float)); + // we need for each children the matrix for vector transformation from children frame + // (in which its DOFs are defined, LOC or TRA) to this parent variation frame + // matRel = mPar^-1*mChild + TGeoHMatrix mPar; + // in case of parent assigned use its matrix, + // otherwise Alice global frame is assumed to be the parent -> Unit matrix + if (fParent && doJac) { + if (fParent->IsFrameTRA()) + fParent->GetMatrixT2G(mPar); // tracking to global + else + mPar = fParent->GetMatrixL2GIdeal(); // local to global + mPar = mPar.Inverse(); + } + // + float* jac = cstrArr; + double parsTotEx[kNDOFGeom] = {0}; // explicitly calculated total modification + double parsTotAn[kNDOFGeom] = {0}; // analyticaly calculated total modification + // + printf("\n\n ----- Constraints Validation for %s %s ------\n", GetName(), GetTitle()); + printf(" chld| "); + for (int jp = 0; jp < kNDOFGeom; jp++) + printf(" %3s:%3s An/Ex |", GetDOFName(jp), IsDOFConstrained(jp) ? "ON " : "OFF"); + printf(" | "); + for (int jp = 0; jp < kNDOFGeom; jp++) + printf(" D%3s ", GetDOFName(jp)); + printf(" ! %s\n", GetName()); + for (int ich = 0; ich < nch; ich++) { + AliAlgVol* child = GetChild(ich); + double parsC[kNDOFGeom] = {0}, parsPAn[kNDOFGeom] = {0}, parsPEx[kNDOFGeom] = {0}; + for (int jc = kNDOFGeom; jc--;) + parsC[jc] = child->GetParVal(jc); // child params in child frame + printf("#%3d | ", ich); + // + if (doJac) { + TGeoHMatrix matRel; + if (child->IsFrameTRA()) + child->GetMatrixT2G(matRel); // tracking to global + else + matRel = child->GetMatrixL2GIdeal(); // local to global + // + matRel.MultiplyLeft(&mPar); + ConstrCoefGeom(matRel, jac); // Jacobian for analytical constraint used by MillePeded + // + TGeoHMatrix tau; + child->Delta2Matrix(tau, parsC); // child correction matrix in the child frame + const TGeoHMatrix& matreli = matRel.Inverse(); + tau.Multiply(&matreli); + tau.MultiplyLeft(&matRel); // child correction matrix in the parent frame + detectors::AlignParam tmpPar; + // tmpPar.SetMatrix(tau); + // SetMatrix does setTranslation and setRotation afterwars; + tmpPar.setTranslation(tau); + tmpPar.setRotation(tau); + //tmpPar.GetTranslation(&parsPEx[0]); + // get Translation gets x,y,z; + parsPEx[0] = tmpPar.getX(); + parsPEx[1] = tmpPar.getY(); + parsPEx[2] = tmpPar.getZ(); + //tmpPar.GetAngles(&parsPEx[3]); // explicitly calculated child params in parent frame + // gets angles + parsPEx[3] = tmpPar.getPsi(); + parsPEx[4] = tmpPar.getTheta(); + parsPEx[5] = tmpPar.getPhi(); + // + // analytically calculated child params in parent frame + for (int jp = 0; jp < kNDOFGeom; jp++) { + for (int jc = 0; jc < kNDOFGeom; jc++) + parsPAn[jp] += jac[jp * kNDOFGeom + jc] * parsC[jc]; + parsTotAn[jp] += parsPAn[jp]; // analyticaly calculated total modification + parsTotEx[jp] += parsPEx[jp]; // explicitly calculated total modification + // + printf("%+.1e/%+.1e ", parsPAn[jp], parsPEx[jp]); + // + } + // + jac += kNDOFGeom * kNDOFGeom; // matrix for next slot + } else { + for (int jc = 0; jc < kNDOFGeom; jc++) { + Bool_t acc = child->IsFreeDOF(jc) && child->GetParErr(jc) >= 0; + if (acc) { + printf(" %+.3e ", parsC[jc]); + parsTotAn[jc] += parsC[jc]; + } else + printf(" /* %+.3e */ ", parsC[jc]); // just for info, not in the constraint + } + } + printf(" | "); + for (int jc = 0; jc < kNDOFGeom; jc++) + printf("%+.1e ", parsC[jc]); // child proper corrections + printf(" ! %s\n", child->GetSymName()); + } + // + printf(" Tot | "); + for (int jp = 0; jp < kNDOFGeom; jp++) { + if (doJac) + printf("%+.1e/%+.1e ", parsTotAn[jp], parsTotEx[jp]); + else { + if (IsDOFConstrained(jp)) + printf(" %+.3e ", parsTotAn[jp]); + else + printf(" /* %+.3e */ ", parsTotAn[jp]); + } + } + printf(" | "); + if (fParent) + for (int jp = 0; jp < kNDOFGeom; jp++) + printf("%+.1e ", fParent->GetParVal(jp)); // parent proper corrections + else + printf(" no parent -> %s ", doJac ? "Global" : "Simple"); + printf(" ! <----- %s\n", GetName()); + // + printf(" Sig | "); + for (int jp = 0; jp < kNDOFGeom; jp++) { + if (IsDOFConstrained(jp)) + printf(" %+.3e ", fSigma[jp]); + else + printf(" /* %+.3e */ ", fSigma[jp]); + } + printf(" ! <----- \n"); + + // + delete[] cstrArr; // - // // - // delete[] cstrArr; - // // } //_________________________________________________________________ diff --git a/Detectors/Align/src/AliAlgVol.cxx b/Detectors/Align/src/AliAlgVol.cxx index 7107aca03d004..28963409cff2e 100644 --- a/Detectors/Align/src/AliAlgVol.cxx +++ b/Detectors/Align/src/AliAlgVol.cxx @@ -98,7 +98,7 @@ #include "Align/AliAlgVol.h" #include "Align/AliAlgDOFStat.h" #include "Align/AliAlgConstraint.h" -//#include "AliAlignObjParams.h" +#include "DetectorsCommonDataFormats/AlignParam.h" #include "DetectorsBase/GeometryManager.h" #include "Align/AliAlgAux.h" #include "Framework/Logger.h" @@ -166,16 +166,19 @@ AliAlgVol::~AliAlgVol() //_________________________________________________________ void AliAlgVol::Delta2Matrix(TGeoHMatrix& deltaM, const Double_t* delta) const { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; - //FIXME(milettri): needs AliAlignObj - // // prepare delta matrix for the volume from its - // // local delta vector (AliAlignObj convension): dx,dy,dz,,theta,psi,phi - // const double *tr = &delta[0], *rt = &delta[3]; // translation(cm) and rotation(degree) - // - // AliAlignObjParams tempAlignObj; - // tempAlignObj.SetRotation(rt[0], rt[1], rt[2]); - // tempAlignObj.SetTranslation(tr[0], tr[1], tr[2]); - // tempAlignObj.GetMatrix(deltaM); + // prepare delta matrix for the volume from its + // local delta vector (AliAlignObj convension): dx,dy,dz,,theta,psi,phi + const double *tr = &delta[0], *rt = &delta[3]; // translation(cm) and rotation(degree) + + // AliAlignObjParams tempAlignObj; + // tempAlignObj.SetRotation(rt[0], rt[1], rt[2]); + // tempAlignObj.SetTranslation(tr[0], tr[1], tr[2]); + // tempAlignObj.GetMatrix(deltaM); + + detectors::AlignParam tempAlignObj; + tempAlignObj.setRotation(rt[0], rt[1], rt[2]); + tempAlignObj.setTranslation(tr[0], tr[1], tr[2]); + deltaM = tempAlignObj.createMatrix(); } //__________________________________________________________________ @@ -760,52 +763,53 @@ void AliAlgVol::CreateAlignmenMatrix(TGeoHMatrix& alg) const //_________________________________________________________________ void AliAlgVol::CreateAlignmentObjects(TClonesArray* arr) const { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; - // FIXME(milettri): needs AliAlignObjParams // add to supplied array alignment object for itself and children - // TClonesArray& parr = *arr; - // TGeoHMatrix algM; - // CreateAlignmenMatrix(algM); + TClonesArray& parr = *arr; + TGeoHMatrix algM; + CreateAlignmenMatrix(algM); // new (parr[parr.GetEntriesFast()]) AliAlignObjParams(GetName(), GetVolID(), algM, kTRUE); - // int nch = GetNChildren(); - // for (int ich = 0; ich < nch; ich++) - // GetChild(ich)->CreateAlignmentObjects(arr); - // + const Double_t* translation = algM.GetTranslation(); + const Double_t* rotation = algM.GetRotationMatrix(); + new (parr[parr.GetEntriesFast()]) detectors::AlignParam(GetName(), GetVolID(), + translation[0], translation[1], translation[2], + rotation[0], rotation[1], rotation[2], kTRUE); + int nch = GetNChildren(); + for (int ich = 0; ich < nch; ich++) + GetChild(ich)->CreateAlignmentObjects(arr); } //_________________________________________________________________ void AliAlgVol::UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta) { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; - // FIXME(milettri): needs AliAlignObjParams - // // recreate fMatL2GReco matrices from ideal L2G matrix and alignment objects - // // used during data reconstruction. For the volume at level J we have - // // L2G' = Delta_J * Delta_{J-1} *...* Delta_0 * L2GIdeal - // // cumulDelta is Delta_{J-1} * ... * Delta_0, supplied by the parent - // // - // fMatL2GReco = fMatL2GIdeal; - // // find alignment object for this volume - // int nalg = algArr->GetEntriesFast(); - // const AliAlignObjParams* par = 0; - // for (int i = 0; i < nalg; i++) { - // par = (AliAlignObjParams*)algArr->At(i); - // if (!strcmp(par->GetSymName(), GetSymName())) - // break; - // par = 0; - // } - // TGeoHMatrix delta; - // if (!par) - // LOG(INFO) << "Alignment for " << GetSymName() << " is absent in Reco-Time alignment object"; - // else + // recreate fMatL2GReco matrices from ideal L2G matrix and alignment objects + // used during data reconstruction. For the volume at level J we have + // L2G' = Delta_J * Delta_{J-1} *...* Delta_0 * L2GIdeal + // cumulDelta is Delta_{J-1} * ... * Delta_0, supplied by the parent + // + fMatL2GReco = fMatL2GIdeal; + // find alignment object for this volume + int nalg = algArr->GetEntriesFast(); + const detectors::AlignParam* par = nullptr; + for (int i = 0; i < nalg; i++) { + par = (detectors::AlignParam*)algArr->At(i); + if (!strcmp(par->getSymName(), GetSymName())) + break; + par = 0; + } + TGeoHMatrix delta; + if (!par) + LOG(INFO) << "Alignment for " << GetSymName() << " is absent in Reco-Time alignment object"; + else + delta = par->createMatrix(); // par->GetMatrix(delta); - // if (cumulDelta) - // delta *= *cumulDelta; - // // - // fMatL2GReco.MultiplyLeft(&delta); - // // propagate to children - // for (int ich = GetNChildren(); ich--;) - // GetChild(ich)->UpdateL2GRecoMatrices(algArr, &delta); - // // + if (cumulDelta) + delta *= *cumulDelta; + // + fMatL2GReco.MultiplyLeft(&delta); + // propagate to children + for (int ich = GetNChildren(); ich--;) + GetChild(ich)->UpdateL2GRecoMatrices(algArr, &delta); + // } //______________________________________________________ From 4b49dfc4a29a1f08f98e7a26e999c5ff619386a6 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Fri, 26 Feb 2021 00:15:29 +0100 Subject: [PATCH 211/770] [ALIGN] replace AliTrackerBase --- Detectors/Align/src/AliAlgTrack.cxx | 359 +++++++++++++++------------- 1 file changed, 191 insertions(+), 168 deletions(-) diff --git a/Detectors/Align/src/AliAlgTrack.cxx b/Detectors/Align/src/AliAlgTrack.cxx index c2b51217e2c5d..69a59e3f5e9e6 100644 --- a/Detectors/Align/src/AliAlgTrack.cxx +++ b/Detectors/Align/src/AliAlgTrack.cxx @@ -15,6 +15,9 @@ #include #include "Align/AliAlgTrack.h" +#include "DetectorsBase/Propagator.h" +#include "DetectorsCommonDataFormats/NameConf.h" +#include "DataFormatsParameters/GRPObject.h" //#include "AliTrackerBase.h" #include "Framework/Logger.h" #include "Align/AliAlgSens.h" @@ -531,86 +534,94 @@ Bool_t AliAlgTrack::CalcResiduals(const double* extendedParams, Bool_t invert, i //______________________________________________________ Bool_t AliAlgTrack::PropagateParamToPoint(trackParam_t* tr, int nTr, const AliAlgPoint* pnt, double maxStep) { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; - // FIXME(milettri): needs AliTrackerBase - // // Propagate set of tracks to the point (only parameters, no error matrix) - // // VECTORIZE this - // // - // for (int itr = nTr; itr--;) { - // if (!PropagateParamToPoint(tr[itr], pnt, maxStep)) { - //#if DEBUG > 3 - // LOG(fatal) << "Failed on clone %d propagation" << itr; - // tr[itr].print(); - // pnt->print("meas mat"); - //#endif - // return kFALSE; - // } - // } + // Propagate set of tracks to the point (only parameters, no error matrix) + // VECTORIZE this + // + for (int itr = nTr; itr--;) { + if (!PropagateParamToPoint(tr[itr], pnt, maxStep)) { +#if DEBUG > 3 + LOG(fatal) << "Failed on clone " << itr << " propagation "; + tr[itr].print(); + pnt->print("meas mat"); +#endif + return kFALSE; + } + } return kTRUE; } //______________________________________________________ Bool_t AliAlgTrack::PropagateParamToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep) { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; - // FIXME(milettri): needs AliTrackerBase - // // propagate tracks to the point (only parameters, no error matrix) - // dim3_t xyz; - // double bxyz[3]; - // // - // if (!tr.rotateParam(pnt->GetAlphaSens())) { - //#if DEBUG > 3 - // LOG(error) << "Failed to rotate to alpha=" << pnt->GetAlphaSens(); - // tr.Print(); - // pnt->Print(); - //#endif - // return kFALSE; - // } - // // - // double xTgt = pnt->GetXPoint(); - // double xBeg = tr.getX(); - // double dx = xTgt - xBeg; - // int nstep = int(Abs(dx) / maxStep) + 1; - // dx /= nstep; - // // - // for (int ist = nstep; ist--;) { - // // - // double xToGo = xTgt - dx * ist; - // tr.getXYZGlo(xyz); - // // - // if (GetFieldON()) { - // if (pnt->GetUseBzOnly()) { - // if (!tr.propagateParamTo(xToGo, AliTrackerBase::GetBz(xyz))) { - //#if DEBUG > 3 - // LOG(error) << "Failed to propagate(BZ) to X=%" << pnt->GetXPoint(); - // tr.Print(); - // pnt->Print(); - //#endif - // return kFALSE; - // } - // } else { - // AliTrackerBase::GetBxByBz(xyz, bxyz); - // if (!tr.propagateParamTo(xToGo, bxyz)) { - //#if DEBUG > 3 - // LOG(error) << "Failed to propagate(BXYZ) to X=" << pnt->GetXPoint(); - // tr.Print(); - // pnt->Print(); - //#endif - // return kFALSE; - // } - // } - // } else { // straigth line propagation - // if (!tr.propagateParamTo(xToGo, 0)) { - //#if DEBUG > 3 - // LOG(error) << "Failed to propagate(B=0) to X=" << pnt->GetXPoint(); - // tr.Print(); - // pnt->Print(); - //#endif - // return kFALSE; - // } - // } - // } // steps - // // + // propagate tracks to the point (only parameters, no error matrix) + + dim3_t xyzD{}; + math_utils::Point3D xyzP; + dim3_t bxyzV{}; + float bxyzF[3]{0, 0, 0}; + + o2::base::GeometryManager::loadGeometry(); + o2::base::Propagator::initFieldFromGRP(o2::base::NameConf::getGRPFileName()); + std::unique_ptr grp{o2::parameters::GRPObject::loadFrom(o2::base::NameConf::getGRPFileName())}; + const auto* propagator = base::Propagator::Instance(); + // + if (!tr.rotateParam(pnt->GetAlphaSens())) { +#if DEBUG > 3 + LOG(error) << "Failed to rotate to alpha=" << pnt->GetAlphaSens(); + tr.Print(); + pnt->Print(); +#endif + return kFALSE; + } + // + double xTgt = pnt->GetXPoint(); + double xBeg = tr.getX(); + double dx = xTgt - xBeg; + int nstep = int(Abs(dx) / maxStep) + 1; + dx /= nstep; + // + for (int ist = nstep; ist--;) { + // + double xToGo = xTgt - dx * ist; + tr.getXYZGlo(xyzD); + xyzP.SetXYZ(xyzD[0], xyzD[1], xyzD[2]); + // + if (GetFieldON()) { + if (pnt->GetUseBzOnly()) { + // if (!tr.propagateParamTo(xToGo, AliTrackerBase::GetBz(xyz))) { //TODO(milettri, shahoian): is this correct? + if (!tr.propagateParamTo(xToGo, propagator->getNominalBz())) { +#if DEBUG > 3 + LOG(error) << "Failed to propagate(BZ) to X=%" << pnt->GetXPoint(); + tr.Print(); + pnt->Print(); +#endif + return kFALSE; + } + } else { + //AliTrackerBase::GetBxByBz(xyz, bxyz); + propagator->getFiedXYZ(xyzP, bxyzF); + std::copy(std::begin(bxyzF), std::end(bxyzF), std::begin(bxyzV)); + if (!tr.propagateParamTo(xToGo, bxyzV)) { +#if DEBUG > 3 + LOG(error) << "Failed to propagate(BXYZ) to X=" << pnt->GetXPoint(); + tr.Print(); + pnt->Print(); +#endif + return kFALSE; + } + } + } else { // straigth line propagation + if (!tr.propagateParamTo(xToGo, 0)) { +#if DEBUG > 3 + LOG(error) << "Failed to propagate(B=0) to X=" << pnt->GetXPoint(); + tr.Print(); + pnt->Print(); +#endif + return kFALSE; + } + } + } // steps + // return kTRUE; } @@ -620,100 +631,112 @@ Bool_t AliAlgTrack::PropagateToPoint(trackParam_t& tr, const AliAlgPoint* pnt, { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; // FIXME(milettri): needs AliTrackerBase - // // propagate tracks to the point. If matCor is true, then material corrections will be applied. - // // if matPar pointer is provided, it will be filled by total x2x0 and signed xrho - // if (!tr.rotate(pnt->GetAlphaSens())) { - //#if DEBUG > 3 - // LOG(WARNING) << "Failed to rotate to alpha=" << pnt->GetAlphaSens(); - // tr.print(); - //#endif - // return kFALSE; - // } - // // - // dim3_t xyz0{0}; - // dim3_t xyz1{0}; - // dim3_t bxyz{0}; - // double matarr[7]; - // double xPoint = pnt->GetXPoint(), dx = xPoint - tr.getX(), dxa = Abs(dx), step = dxa / minNSteps; - // if (matPar) - // matPar[0] = matPar[1] = 0; - // if (dxa < kTinyDist) - // return kTRUE; - // if (step > maxStep) - // step = maxStep; - // int nstep = int(dxa / step); - // step = dxa / nstep; - // if (dx < 0) - // step = -step; - // // - // // printf("-->will go from X:%e to X:%e in %d steps of %f\n",tr.GetX(),xPoint,nstep,step); - // - // // do we go along or against track direction - // Bool_t alongTrackDir = (dx > 0 && !pnt->IsInvDir()) || (dx < 0 && pnt->IsInvDir()); - // Bool_t queryXYZ = matCor || GetFieldON(); - // if (queryXYZ) - // tr.getXYZGlo(xyz0); - // // - // double x2X0Tot = 0, xrhoTot = 0; - // for (int ist = nstep; ist--;) { // single propagation step >> - // double xToGo = xPoint - step * ist; - // // - // if (GetFieldON()) { - // if (pnt->GetUseBzOnly()) { - // if (!tr.propagateParamTo(xToGo, AliTrackerBase::GetBz(xyz0))) { - //#if DEBUG > 3 - // LOG(WARNING) << "Failed to propagate(BZ) to X=" << xToGo; - // tr.print(); - //#endif - // return kFALSE; - // } - // } else { - // AliTrackerBase::GetBxByBz(xyz0, bxyz); - // if (!tr.propagateParamTo(xToGo, bxyz)) { - //#if DEBUG > 3 - // AliWarningF("Failed to propagate(BXYZ) to X=%f", xToGo); - //#endif - // return kFALSE; - // } - // } - // } else { // straigth line propagation - // if (!tr.propagateParamTo(xToGo, 0)) { - //#if DEBUG > 3 - // AliWarningF("Failed to propagate(B=0) to X=%f", xToGo); - //#endif - // return kFALSE; - // } - // } - // // - // if (queryXYZ) { - // tr.getXYZGlo(xyz1); - // if (matCor) { - // AliTrackerBase::MeanMaterialBudget(xyz0, xyz1, matarr); - // Double_t xrho = matarr[0] * matarr[4], xx0 = matarr[1]; - // if (alongTrackDir) - // xrho = -xrho; // if we go along track direction, energy correction is negative - // x2X0Tot += xx0; - // xrhoTot += xrho; - // // printf("MAT %+7.2f %+7.2f %+7.2f -> %+7.2f %+7.2f %+7.2f | %+e %+e | -> %+e %+e | %+e %+e %+e %+e %+e\n", - // // xyz0[0],xyz0[1],xyz0[g2], xyz1[0],xyz1[1],xyz1[2], tr.Phi(), tr.GetAlpha(), - // // x2X0Tot,xrhoTot, matarr[0],matarr[1],matarr[2],matarr[3],matarr[4]); - // if (!tr.correctForMaterial(xx0, xrho, fMass)) { - //#if DEBUG > 3 - // LOG(WARNING) << "Failed on CorrectForMeanMaterial(" << xx0 << "," << xrho << "," << fMass << ")"; - // tr.print(); - //#endif - // return kFALSE; - // } - // } - // for (int l = 3; l--;) - // xyz0[l] = xyz1[l]; - // } - // } // single propagation step << - // // - // if (matPar) { - // matPar[0] = x2X0Tot; - // matPar[1] = xrhoTot; - // } + // // propagate tracks to the point. If matCor is true, then material corrections will be applied. + // // if matPar pointer is provided, it will be filled by total x2x0 and signed xrho + if (!tr.rotate(pnt->GetAlphaSens())) { +#if DEBUG > 3 + LOG(WARNING) << "Failed to rotate to alpha=" << pnt->GetAlphaSens(); + tr.print(); +#endif + return kFALSE; + } + // + base::GeometryManager::loadGeometry(); + base::Propagator::initFieldFromGRP(base::NameConf::getGRPFileName()); + std::unique_ptr grp{parameters::GRPObject::loadFrom(base::NameConf::getGRPFileName())}; + const auto* propagator = base::Propagator::Instance(); + + dim3_t xyz0{0}; + dim3_t xyz1{0}; + dim3_t bxyzV{0}; + float bxyzF[3]{0, 0, 0}; + math_utils::Point3D xyzP; + + double matarr[7]; + double xPoint = pnt->GetXPoint(), dx = xPoint - tr.getX(), dxa = Abs(dx), step = dxa / minNSteps; + if (matPar) + matPar[0] = matPar[1] = 0; + if (dxa < kTinyDist) + return kTRUE; + if (step > maxStep) + step = maxStep; + int nstep = int(dxa / step); + step = dxa / nstep; + if (dx < 0) + step = -step; + // + // printf("-->will go from X:%e to X:%e in %d steps of %f\n",tr.GetX(),xPoint,nstep,step); + + // do we go along or against track direction + Bool_t alongTrackDir = (dx > 0 && !pnt->IsInvDir()) || (dx < 0 && pnt->IsInvDir()); + Bool_t queryXYZ = matCor || GetFieldON(); + if (queryXYZ) + tr.getXYZGlo(xyz0); + xyzP.SetXYZ(xyz0[0], xyz0[1], xyz0[2]); + // + double x2X0Tot = 0, xrhoTot = 0; + for (int ist = nstep; ist--;) { // single propagation step >> + double xToGo = xPoint - step * ist; + // + if (GetFieldON()) { + if (pnt->GetUseBzOnly()) { + // if (!tr.propagateParamTo(xToGo, AliTrackerBase::GetBz(xyz0))) { + if (!tr.propagateParamTo(xToGo, propagator->getNominalBz())) { //TODO(milettri, shahoian) - check correctness +#if DEBUG > 3 + LOG(WARNING) << "Failed to propagate(BZ) to X=" << xToGo; + tr.print(); +#endif + return kFALSE; + } + } else { + //AliTrackerBase::GetBxByBz(xyz0, bxyz); + propagator->getFiedXYZ(xyzP, bxyzF); + std::copy(std::begin(bxyzF), std::end(bxyzF), std::begin(bxyzV)); + if (!tr.propagateParamTo(xToGo, bxyzV)) { +#if DEBUG > 3 + AliWarningF("Failed to propagate(BXYZ) to X=%f", xToGo); +#endif + return kFALSE; + } + } + } else { // straigth line propagation + if (!tr.propagateParamTo(xToGo, 0)) { +#if DEBUG > 3 + AliWarningF("Failed to propagate(B=0) to X=%f", xToGo); +#endif + return kFALSE; + } + } + // + if (queryXYZ) { + tr.getXYZGlo(xyz1); + if (matCor) { + //AliTrackerBase::MeanMaterialBudget(xyz0, xyz1, matarr); //TODO(milettri, shahoian) - t + Double_t xrho = matarr[0] * matarr[4], xx0 = matarr[1]; + if (alongTrackDir) + xrho = -xrho; // if we go along track direction, energy correction is negative + x2X0Tot += xx0; + xrhoTot += xrho; + // printf("MAT %+7.2f %+7.2f %+7.2f -> %+7.2f %+7.2f %+7.2f | %+e %+e | -> %+e %+e | %+e %+e %+e %+e %+e\n", + // xyz0[0],xyz0[1],xyz0[g2], xyz1[0],xyz1[1],xyz1[2], tr.Phi(), tr.GetAlpha(), + // x2X0Tot,xrhoTot, matarr[0],matarr[1],matarr[2],matarr[3],matarr[4]); + if (!tr.correctForMaterial(xx0, xrho, fMass)) { +#if DEBUG > 3 + LOG(WARNING) << "Failed on CorrectForMeanMaterial(" << xx0 << "," << xrho << "," << fMass << ")"; + tr.print(); +#endif + return kFALSE; + } + } + for (int l = 3; l--;) + xyz0[l] = xyz1[l]; + } + } // single propagation step << + // + if (matPar) { + matPar[0] = x2X0Tot; + matPar[1] = xrhoTot; + } return kTRUE; } From b706bda185d75b3257a8f0e2b3fac04b66d9a826 Mon Sep 17 00:00:00 2001 From: shahoian Date: Tue, 23 Mar 2021 20:43:40 +0100 Subject: [PATCH 212/770] fixes in AliAlgTrack --- Detectors/Align/include/Align/AliAlgTrack.h | 18 +- Detectors/Align/src/AliAlgSteer.cxx | 9 +- Detectors/Align/src/AliAlgTrack.cxx | 210 +++----------------- 3 files changed, 44 insertions(+), 193 deletions(-) diff --git a/Detectors/Align/include/Align/AliAlgTrack.h b/Detectors/Align/include/Align/AliAlgTrack.h index d3426dffbd4e6..18cf2748dd973 100644 --- a/Detectors/Align/include/Align/AliAlgTrack.h +++ b/Detectors/Align/include/Align/AliAlgTrack.h @@ -27,17 +27,24 @@ #include #include #include +#include "DetectorsBase/Propagator.h" namespace o2 { namespace align { -using trackParam_t = o2::track::TrackParametrizationWithError; - class AliAlgTrack : public trackParam_t, public TObject { public: + using trackParam_t = o2::track::TrackParametrizationWithError; + using Propagator = o2::base::PropagatorImpl; + using MatCorrType = Propagator::MatCorrType; + + static constexpr double MaxDefStep = 3.0; + static constexpr double MaxDefSnp = 0.95; + static constexpr MatCorrType DefMatCorrType = MatCorrType::USEMatCorrLUT; + enum { kCosmicBit = BIT(14), kFieldONBit = BIT(15), kResidDoneBit = BIT(16), @@ -73,10 +80,9 @@ class AliAlgTrack : public trackParam_t, public TObject virtual void Print(Option_t* opt = "") const; virtual void DumpCoordinates() const; // - Bool_t PropagateToPoint(trackParam_t& tr, const AliAlgPoint* pnt, - int minNSteps, double maxStep, Bool_t matCor, double* matPar = 0); - Bool_t PropagateParamToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep = 3); // param only - Bool_t PropagateParamToPoint(trackParam_t* trSet, int nTr, const AliAlgPoint* pnt, double maxStep = 3); // params only + Bool_t PropagateToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT, track::TrackLTIntegral* tLT = nullptr); + Bool_t PropagateParamToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep = 3, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT); // param only + Bool_t PropagateParamToPoint(trackParam_t* trSet, int nTr, const AliAlgPoint* pnt, double maxStep = 3, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT); // params only // Bool_t CalcResiduals(const double* params = 0); Bool_t CalcResidDeriv(double* params = 0); diff --git a/Detectors/Align/src/AliAlgSteer.cxx b/Detectors/Align/src/AliAlgSteer.cxx index c1f1366918f43..86d4c2cf12ac5 100644 --- a/Detectors/Align/src/AliAlgSteer.cxx +++ b/Detectors/Align/src/AliAlgSteer.cxx @@ -50,6 +50,8 @@ #include #include #include +#include "DetectorsCommonDataFormats/NameConf.h" +#include "DataFormatsParameters/GRPObject.h" using namespace TMath; using namespace o2::align::AliAlgAux; @@ -945,7 +947,12 @@ void AliAlgSteer::SetRunNumber(Int_t run) //_________________________________________________________ void AliAlgSteer::AcknowledgeNewRun(Int_t run) { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; + LOG(WARNING) << __PRETTY_FUNCTION__ << " yet incomplete"; + + o2::base::GeometryManager::loadGeometry(); + o2::base::PropagatorImpl::initFieldFromGRP(o2::base::NameConf::getGRPFileName()); + std::unique_ptr grp{o2::parameters::GRPObject::loadFrom(o2::base::NameConf::getGRPFileName())}; + //FIXME(milettri): needs AliESDEvent // // load needed info for new run // if (run == fRunNumber) diff --git a/Detectors/Align/src/AliAlgTrack.cxx b/Detectors/Align/src/AliAlgTrack.cxx index 69a59e3f5e9e6..d8549eb272ac7 100644 --- a/Detectors/Align/src/AliAlgTrack.cxx +++ b/Detectors/Align/src/AliAlgTrack.cxx @@ -15,10 +15,6 @@ #include #include "Align/AliAlgTrack.h" -#include "DetectorsBase/Propagator.h" -#include "DetectorsCommonDataFormats/NameConf.h" -#include "DataFormatsParameters/GRPObject.h" -//#include "AliTrackerBase.h" #include "Framework/Logger.h" #include "Align/AliAlgSens.h" #include "Align/AliAlgVol.h" @@ -532,7 +528,7 @@ Bool_t AliAlgTrack::CalcResiduals(const double* extendedParams, Bool_t invert, i } //______________________________________________________ -Bool_t AliAlgTrack::PropagateParamToPoint(trackParam_t* tr, int nTr, const AliAlgPoint* pnt, double maxStep) +Bool_t AliAlgTrack::PropagateParamToPoint(trackParam_t* tr, int nTr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt) { // Propagate set of tracks to the point (only parameters, no error matrix) // VECTORIZE this @@ -551,19 +547,9 @@ Bool_t AliAlgTrack::PropagateParamToPoint(trackParam_t* tr, int nTr, const AliAl } //______________________________________________________ -Bool_t AliAlgTrack::PropagateParamToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep) +Bool_t AliAlgTrack::PropagateParamToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt) { // propagate tracks to the point (only parameters, no error matrix) - - dim3_t xyzD{}; - math_utils::Point3D xyzP; - dim3_t bxyzV{}; - float bxyzF[3]{0, 0, 0}; - - o2::base::GeometryManager::loadGeometry(); - o2::base::Propagator::initFieldFromGRP(o2::base::NameConf::getGRPFileName()); - std::unique_ptr grp{o2::parameters::GRPObject::loadFrom(o2::base::NameConf::getGRPFileName())}; - const auto* propagator = base::Propagator::Instance(); // if (!tr.rotateParam(pnt->GetAlphaSens())) { #if DEBUG > 3 @@ -573,64 +559,13 @@ Bool_t AliAlgTrack::PropagateParamToPoint(trackParam_t& tr, const AliAlgPoint* p #endif return kFALSE; } + return Propagator::Instance()->propagateTo(tr, pnt->GetXPoint(), pnt->GetUseBzOnly(), maxSnp, maxStep, mt); // - double xTgt = pnt->GetXPoint(); - double xBeg = tr.getX(); - double dx = xTgt - xBeg; - int nstep = int(Abs(dx) / maxStep) + 1; - dx /= nstep; - // - for (int ist = nstep; ist--;) { - // - double xToGo = xTgt - dx * ist; - tr.getXYZGlo(xyzD); - xyzP.SetXYZ(xyzD[0], xyzD[1], xyzD[2]); - // - if (GetFieldON()) { - if (pnt->GetUseBzOnly()) { - // if (!tr.propagateParamTo(xToGo, AliTrackerBase::GetBz(xyz))) { //TODO(milettri, shahoian): is this correct? - if (!tr.propagateParamTo(xToGo, propagator->getNominalBz())) { -#if DEBUG > 3 - LOG(error) << "Failed to propagate(BZ) to X=%" << pnt->GetXPoint(); - tr.Print(); - pnt->Print(); -#endif - return kFALSE; - } - } else { - //AliTrackerBase::GetBxByBz(xyz, bxyz); - propagator->getFiedXYZ(xyzP, bxyzF); - std::copy(std::begin(bxyzF), std::end(bxyzF), std::begin(bxyzV)); - if (!tr.propagateParamTo(xToGo, bxyzV)) { -#if DEBUG > 3 - LOG(error) << "Failed to propagate(BXYZ) to X=" << pnt->GetXPoint(); - tr.Print(); - pnt->Print(); -#endif - return kFALSE; - } - } - } else { // straigth line propagation - if (!tr.propagateParamTo(xToGo, 0)) { -#if DEBUG > 3 - LOG(error) << "Failed to propagate(B=0) to X=" << pnt->GetXPoint(); - tr.Print(); - pnt->Print(); -#endif - return kFALSE; - } - } - } // steps - // - return kTRUE; } //______________________________________________________ -Bool_t AliAlgTrack::PropagateToPoint(trackParam_t& tr, const AliAlgPoint* pnt, - int minNSteps, double maxStep, Bool_t matCor, double* matPar) +Bool_t AliAlgTrack::PropagateToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT) { - LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; - // FIXME(milettri): needs AliTrackerBase // // propagate tracks to the point. If matCor is true, then material corrections will be applied. // // if matPar pointer is provided, it will be filled by total x2x0 and signed xrho if (!tr.rotate(pnt->GetAlphaSens())) { @@ -640,104 +575,7 @@ Bool_t AliAlgTrack::PropagateToPoint(trackParam_t& tr, const AliAlgPoint* pnt, #endif return kFALSE; } - // - base::GeometryManager::loadGeometry(); - base::Propagator::initFieldFromGRP(base::NameConf::getGRPFileName()); - std::unique_ptr grp{parameters::GRPObject::loadFrom(base::NameConf::getGRPFileName())}; - const auto* propagator = base::Propagator::Instance(); - - dim3_t xyz0{0}; - dim3_t xyz1{0}; - dim3_t bxyzV{0}; - float bxyzF[3]{0, 0, 0}; - math_utils::Point3D xyzP; - - double matarr[7]; - double xPoint = pnt->GetXPoint(), dx = xPoint - tr.getX(), dxa = Abs(dx), step = dxa / minNSteps; - if (matPar) - matPar[0] = matPar[1] = 0; - if (dxa < kTinyDist) - return kTRUE; - if (step > maxStep) - step = maxStep; - int nstep = int(dxa / step); - step = dxa / nstep; - if (dx < 0) - step = -step; - // - // printf("-->will go from X:%e to X:%e in %d steps of %f\n",tr.GetX(),xPoint,nstep,step); - - // do we go along or against track direction - Bool_t alongTrackDir = (dx > 0 && !pnt->IsInvDir()) || (dx < 0 && pnt->IsInvDir()); - Bool_t queryXYZ = matCor || GetFieldON(); - if (queryXYZ) - tr.getXYZGlo(xyz0); - xyzP.SetXYZ(xyz0[0], xyz0[1], xyz0[2]); - // - double x2X0Tot = 0, xrhoTot = 0; - for (int ist = nstep; ist--;) { // single propagation step >> - double xToGo = xPoint - step * ist; - // - if (GetFieldON()) { - if (pnt->GetUseBzOnly()) { - // if (!tr.propagateParamTo(xToGo, AliTrackerBase::GetBz(xyz0))) { - if (!tr.propagateParamTo(xToGo, propagator->getNominalBz())) { //TODO(milettri, shahoian) - check correctness -#if DEBUG > 3 - LOG(WARNING) << "Failed to propagate(BZ) to X=" << xToGo; - tr.print(); -#endif - return kFALSE; - } - } else { - //AliTrackerBase::GetBxByBz(xyz0, bxyz); - propagator->getFiedXYZ(xyzP, bxyzF); - std::copy(std::begin(bxyzF), std::end(bxyzF), std::begin(bxyzV)); - if (!tr.propagateParamTo(xToGo, bxyzV)) { -#if DEBUG > 3 - AliWarningF("Failed to propagate(BXYZ) to X=%f", xToGo); -#endif - return kFALSE; - } - } - } else { // straigth line propagation - if (!tr.propagateParamTo(xToGo, 0)) { -#if DEBUG > 3 - AliWarningF("Failed to propagate(B=0) to X=%f", xToGo); -#endif - return kFALSE; - } - } - // - if (queryXYZ) { - tr.getXYZGlo(xyz1); - if (matCor) { - //AliTrackerBase::MeanMaterialBudget(xyz0, xyz1, matarr); //TODO(milettri, shahoian) - t - Double_t xrho = matarr[0] * matarr[4], xx0 = matarr[1]; - if (alongTrackDir) - xrho = -xrho; // if we go along track direction, energy correction is negative - x2X0Tot += xx0; - xrhoTot += xrho; - // printf("MAT %+7.2f %+7.2f %+7.2f -> %+7.2f %+7.2f %+7.2f | %+e %+e | -> %+e %+e | %+e %+e %+e %+e %+e\n", - // xyz0[0],xyz0[1],xyz0[g2], xyz1[0],xyz1[1],xyz1[2], tr.Phi(), tr.GetAlpha(), - // x2X0Tot,xrhoTot, matarr[0],matarr[1],matarr[2],matarr[3],matarr[4]); - if (!tr.correctForMaterial(xx0, xrho, fMass)) { -#if DEBUG > 3 - LOG(WARNING) << "Failed on CorrectForMeanMaterial(" << xx0 << "," << xrho << "," << fMass << ")"; - tr.print(); -#endif - return kFALSE; - } - } - for (int l = 3; l--;) - xyz0[l] = xyz1[l]; - } - } // single propagation step << - // - if (matPar) { - matPar[0] = x2X0Tot; - matPar[1] = xrhoTot; - } - return kTRUE; + return Propagator::Instance()->propagateTo(tr, pnt->GetXPoint(), pnt->GetUseBzOnly(), maxSnp, maxStep, mt, tLT); } /* @@ -1017,8 +855,6 @@ Bool_t AliAlgTrack::IniFit() { // perform initial fit of the track // - const int kMinNStep = 3; - const double kMaxDefStep = 3.0; // trackParam_t trc = *this; // @@ -1053,7 +889,7 @@ Bool_t AliAlgTrack::IniFit() // // propagate to reference point, which is the inner point of lower leg const AliAlgPoint* refP = GetPoint(GetInnerPointID()); - if (!PropagateToPoint(trcU, refP, kMinNStep, kMaxDefStep, kTRUE)) + if (!PropagateToPoint(trcU, refP, MaxDefStep, MaxDefSnp, DefMatCorrType)) return kFALSE; // fChi2CosmUp = fChi2 - fChi2CosmDn; @@ -1143,7 +979,7 @@ Bool_t AliAlgTrack::FitLeg(trackParam_t& trc, int pFrom, int pTo, Bool_t& inv) // perform initial fit of the track // the fit will always start from the outgoing track in inward direction (i.e. if cosmics - bottom leg) const int kMinNStep = 3; - const double kMaxDefStep = 3.0; + const double MaxDefStep = 3.0; const double kErrSpace = 50.; const double kErrAng = 0.7; const double kErrRelPtI = 1.; @@ -1175,7 +1011,7 @@ Bool_t AliAlgTrack::FitLeg(trackParam_t& trc, int pFrom, int pTo, Bool_t& inv) #endif return kFALSE; } - if (!PropagateParamToPoint(trc, p0, 30)) { + if (!PropagateParamToPoint(trc, p0, MaxDefStep)) { // if (!PropagateToPoint(trc,p0,5,30,kTRUE)) { //trc.PropagateParamOnlyTo(p0->GetXPoint()+kOverShootX,AliTrackerBase::GetBz())) { #if DEBUG > 3 @@ -1201,8 +1037,9 @@ Bool_t AliAlgTrack::FitLeg(trackParam_t& trc, int pFrom, int pTo, Bool_t& inv) // // printf("*** FitLeg %d (%d %d)\n",ip,pFrom,pTo); // printf("Before propagate: "); trc.print(); - if (!PropagateToPoint(trc, pnt, kMinNStep, kMaxDefStep, kTRUE)) + if (!PropagateToPoint(trc, pnt, MaxDefStep, MaxDefSnp, DefMatCorrType)) { return kFALSE; + } if (pnt->ContainsMeasurement()) { if (pnt->GetNeedUpdateFromTrack()) pnt->UpdatePointByTrackInfo(&trc); @@ -1240,7 +1077,7 @@ Bool_t AliAlgTrack::ResidKalman() // Bool_t inv = kFALSE; const int kMinNStep = 3; - const double kMaxDefStep = 3.0; + const double MaxDefStep = 3.0; const double kErrSpace = 50.; const double kErrAng = 0.7; const double kErrRelPtI = 1.; @@ -1278,7 +1115,7 @@ Bool_t AliAlgTrack::ResidKalman() #endif return kFALSE; } - if (!PropagateParamToPoint(trc, pnt, 30)) { + if (!PropagateParamToPoint(trc, pnt, MaxDefStep)) { //if (!trc.PropagateParamOnlyTo(pnt->GetXPoint()+kOverShootX,AliTrackerBase::GetBz())) { #if DEBUG > 3 AliWarningF("Failed on PropagateParamOnlyTo to %f", pnt->GetXPoint() + kOverShootX); @@ -1301,8 +1138,9 @@ Bool_t AliAlgTrack::ResidKalman() } // printf("*** ResidKalm %d (%d %d)\n",ip,0,nPnt); // printf("Before propagate: "); trc.print(); - if (!PropagateToPoint(trc, pnt, kMinNStep, kMaxDefStep, kTRUE)) + if (!PropagateToPoint(trc, pnt, MaxDefStep, MaxDefSnp, DefMatCorrType)) { return kFALSE; + } if (!pnt->ContainsMeasurement()) continue; const double* yz = pnt->GetYZTracking(); @@ -1341,8 +1179,9 @@ Bool_t AliAlgTrack::ResidKalman() trc.invert(); inv = !inv; } - if (!PropagateToPoint(trc, pnt, kMinNStep, kMaxDefStep, kTRUE)) + if (!PropagateToPoint(trc, pnt, MaxDefStep, MaxDefSnp, DefMatCorrType)) { return kFALSE; + } if (!pnt->ContainsMeasurement()) continue; const double* yz = pnt->GetYZTracking(); @@ -1441,7 +1280,7 @@ Bool_t AliAlgTrack::ProcessMaterials(trackParam_t& trc, int pFrom, int pTo) { // attach material effect info to alignment points const int kMinNStep = 3; - const double kMaxDefStep = 3.0; + const double MaxDefStep = 3.0; const double kErrSpcT = 1e-6; const double kErrAngT = 1e-6; const double kErrPtIT = 1e-12; @@ -1466,10 +1305,10 @@ Bool_t AliAlgTrack::ProcessMaterials(trackParam_t& trc, int pFrom, int pTo) // // 2 copies of the track, one will be propagated accounting for materials, other - w/o trackParam_t tr0; - double x2X0xRho[2] = {0, 0}; + track::TrackLTIntegral matTL; double dpar[5] = {0}; covMat_t dcov{0}; - + matTL.setTimeNotNeeded(); // int pinc; if (pTo > pFrom) { // fit in points decreasing order: cosmics upper leg @@ -1486,7 +1325,7 @@ Bool_t AliAlgTrack::ProcessMaterials(trackParam_t& trc, int pFrom, int pTo) tr0 = trc; // // printf("-> ProcMat %d (%d->%d)\n",ip,pFrom,pTo); - if (!PropagateToPoint(trc, pnt, kMinNStep, kMaxDefStep, kTRUE, x2X0xRho)) { // with material corrections + if (!PropagateToPoint(trc, pnt, MaxDefStep, MaxDefSnp, DefMatCorrType, &matTL)) { // with material corrections #if DEBUG > 3 LOG(error) << "Failed to take track to point" << ip << " (dir: " << pFrom << "->" pTo << ") with mat.corr."; trc.print(); @@ -1496,10 +1335,10 @@ Bool_t AliAlgTrack::ProcessMaterials(trackParam_t& trc, int pFrom, int pTo) } // // is there enough material to consider the point as a scatterer? - pnt->SetContainsMaterial(x2X0xRho[0] * Abs(trc.getQ2Pt()) > GetMinX2X0Pt2Account()); + pnt->SetContainsMaterial(matTL.getX2X0() * Abs(trc.getQ2Pt()) > GetMinX2X0Pt2Account()); // // printf("-> ProcMat000 %d (%d->%d)\n",ip,pFrom,pTo); - if (!PropagateToPoint(tr0, pnt, kMinNStep, kMaxDefStep, kFALSE, 0)) { // no material corrections + if (!PropagateToPoint(tr0, pnt, MaxDefStep, MaxDefSnp, MatCorrType::USEMatCorrNONE)) { // no material corrections #if DEBUG > 3 LOG(error) << "Failed to take track to point" << ip << " (dir: " << pFrom << "->" pTo << ") with mat.corr."; tr0.print(); @@ -1544,9 +1383,8 @@ Bool_t AliAlgTrack::ProcessMaterials(trackParam_t& trc, int pFrom, int pTo) if (!eLossFree) pnt->SetMatCovDiagElem(kParQ2Pt, dcov[14]); // - //printf("Add mat%d %e %e\n",ip, x2X0xRho[0],x2X0xRho[1]); - pnt->SetX2X0(x2X0xRho[0]); - pnt->SetXTimesRho(x2X0xRho[1]); + pnt->SetX2X0(matTL.getX2X0()); + pnt->SetXTimesRho(matTL.getXRho()); // } if (pnt->ContainsMeasurement()) { // update track to have best possible kinematics From c8b2a5fbb41dd812a2299c858b4ff2f6ec16fa8f Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Mon, 12 Apr 2021 19:39:44 +0200 Subject: [PATCH 213/770] [ALIGN] eloss correction in cosmics propagation --- Detectors/Align/include/Align/AliAlgTrack.h | 3 +- Detectors/Align/src/AliAlgTrack.cxx | 40 ++++++++++++--------- 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/Detectors/Align/include/Align/AliAlgTrack.h b/Detectors/Align/include/Align/AliAlgTrack.h index 18cf2748dd973..20083c2726813 100644 --- a/Detectors/Align/include/Align/AliAlgTrack.h +++ b/Detectors/Align/include/Align/AliAlgTrack.h @@ -154,7 +154,6 @@ class AliAlgTrack : public trackParam_t, public TObject AliAlgTrack& operator=(const AliAlgTrack&); // protected: - //trackParam_t Int_t fNLocPar; // number of local params Int_t fNLocExtPar; // number of local params for the external track param Int_t fNGloPar; // number of free global parameters the track depends on @@ -178,6 +177,8 @@ class AliAlgTrack : public trackParam_t, public TObject Double_t* fDResDGloA[2]; //! fast access to global derivatives Int_t* fGloParIDA; //! fast access to relevant global param IDs Double_t* fLocParA; //! fast access to local params + private: + Bool_t Propagate(trackParam_t& tr, const AliAlgPoint* pnt, Double_t maxStep, Double_t maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT); // ClassDef(AliAlgTrack, 2) }; diff --git a/Detectors/Align/src/AliAlgTrack.cxx b/Detectors/Align/src/AliAlgTrack.cxx index d8549eb272ac7..133bea32b9690 100644 --- a/Detectors/Align/src/AliAlgTrack.cxx +++ b/Detectors/Align/src/AliAlgTrack.cxx @@ -550,32 +550,40 @@ Bool_t AliAlgTrack::PropagateParamToPoint(trackParam_t* tr, int nTr, const AliAl Bool_t AliAlgTrack::PropagateParamToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt) { // propagate tracks to the point (only parameters, no error matrix) - // - if (!tr.rotateParam(pnt->GetAlphaSens())) { -#if DEBUG > 3 - LOG(error) << "Failed to rotate to alpha=" << pnt->GetAlphaSens(); - tr.Print(); - pnt->Print(); -#endif - return kFALSE; - } - return Propagator::Instance()->propagateTo(tr, pnt->GetXPoint(), pnt->GetUseBzOnly(), maxSnp, maxStep, mt); - // + return Propagate(tr, pnt, maxStep, maxSnp, mt, nullptr); } //______________________________________________________ Bool_t AliAlgTrack::PropagateToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT) { - // // propagate tracks to the point. If matCor is true, then material corrections will be applied. - // // if matPar pointer is provided, it will be filled by total x2x0 and signed xrho - if (!tr.rotate(pnt->GetAlphaSens())) { + // propagate tracks to the point. If matCor is true, then material corrections will be applied. + // if matPar pointer is provided, it will be filled by total x2x0 and signed xrho + return Propagate(tr, pnt, maxStep, maxSnp, mt, tLT); +} + +Bool_t AliAlgTrack::Propagate(trackParam_t& track, const AliAlgPoint* pnt, Double_t maxStep, Double_t maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT) +{ + if (!track.rotate(pnt->GetAlphaSens())) { #if DEBUG > 3 - LOG(WARNING) << "Failed to rotate to alpha=" << pnt->GetAlphaSens(); + LOG(error) << "Failed to rotate to alpha=" << pnt->GetAlphaSens(); tr.print(); + pnt->Print(); #endif return kFALSE; } - return Propagator::Instance()->propagateTo(tr, pnt->GetXPoint(), pnt->GetUseBzOnly(), maxSnp, maxStep, mt, tLT); + // calculate the sign of the energy loss correction and ensure the upper leg of cosmics is calculated correctly. + const Int_t signCorr = [this, &pnt, &track, maxStep] { + const Double_t dx = maxStep - track.getX(); + const Int_t dir = dx > 0.f ? 1 : -1; + if (pnt->IsInvDir()) { + // upper leg of a cosmic -> inward facing track + return dir; + } else { + // outward facing track + return -dir; + } + }(); + return Propagator::Instance()->propagateTo(track, pnt->GetXPoint(), pnt->GetUseBzOnly(), maxSnp, maxStep, mt, tLT, signCorr); } /* From 63489c5b681c7380ed25be675a872b59e57ec729 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Tue, 13 Apr 2021 11:25:54 +0200 Subject: [PATCH 214/770] [ALIGN] adapt C++ elementary types Use elementary C++ data types instead of ROOT ones. * Double_t -> double * Float_t -> float * UInt_t -> uint32_t * Int_t -> int * Bool_t -> bool * UChar_t -> uint8_t * Char_r -> char * UShort_t -> uint16_t * Short_t -> int16_t * ULong_t -> uint64_t * ULong64_t -> uint64_t * Long_t -> int64_t * Long64_t -> int64_t --- Detectors/Align/include/Align/AliAlgAux.h | 67 ++-- .../Align/include/Align/AliAlgConstraint.h | 28 +- Detectors/Align/include/Align/AliAlgDOFStat.h | 18 +- Detectors/Align/include/Align/AliAlgDet.h | 212 ++++++------- .../Align/include/Align/AliAlgDetHMPID.h | 2 +- Detectors/Align/include/Align/AliAlgDetITS.h | 20 +- Detectors/Align/include/Align/AliAlgDetTOF.h | 2 +- Detectors/Align/include/Align/AliAlgDetTPC.h | 2 +- Detectors/Align/include/Align/AliAlgDetTRD.h | 22 +- .../Align/include/Align/AliAlgMPRecord.h | 108 +++---- Detectors/Align/include/Align/AliAlgPoint.h | 154 ++++----- Detectors/Align/include/Align/AliAlgRes.h | 172 +++++----- Detectors/Align/include/Align/AliAlgResFast.h | 94 +++--- Detectors/Align/include/Align/AliAlgSens.h | 22 +- .../Align/include/Align/AliAlgSensHMPID.h | 2 +- Detectors/Align/include/Align/AliAlgSensITS.h | 2 +- Detectors/Align/include/Align/AliAlgSensTOF.h | 8 +- Detectors/Align/include/Align/AliAlgSensTPC.h | 8 +- Detectors/Align/include/Align/AliAlgSensTRD.h | 8 +- Detectors/Align/include/Align/AliAlgSteer.h | 286 ++++++++--------- Detectors/Align/include/Align/AliAlgTrack.h | 148 ++++----- Detectors/Align/include/Align/AliAlgVol.h | 142 ++++----- Detectors/Align/include/Align/AliAlgVtx.h | 4 +- Detectors/Align/src/AliAlgAux.cxx | 4 +- Detectors/Align/src/AliAlgConstraint.cxx | 6 +- Detectors/Align/src/AliAlgDOFStat.cxx | 8 +- Detectors/Align/src/AliAlgDet.cxx | 55 ++-- Detectors/Align/src/AliAlgDetHMPID.cxx | 12 +- Detectors/Align/src/AliAlgDetITS.cxx | 50 +-- Detectors/Align/src/AliAlgDetTOF.cxx | 2 +- Detectors/Align/src/AliAlgDetTPC.cxx | 12 +- Detectors/Align/src/AliAlgDetTRD.cxx | 20 +- Detectors/Align/src/AliAlgMPRecord.cxx | 62 ++-- Detectors/Align/src/AliAlgPoint.cxx | 10 +- Detectors/Align/src/AliAlgRes.cxx | 94 +++--- Detectors/Align/src/AliAlgResFast.cxx | 36 +-- Detectors/Align/src/AliAlgSens.cxx | 10 +- Detectors/Align/src/AliAlgSensHMPID.cxx | 8 +- Detectors/Align/src/AliAlgSensITS.cxx | 8 +- Detectors/Align/src/AliAlgSensTOF.cxx | 8 +- Detectors/Align/src/AliAlgSensTPC.cxx | 8 +- Detectors/Align/src/AliAlgSensTRD.cxx | 8 +- Detectors/Align/src/AliAlgSteer.cxx | 294 +++++++++--------- Detectors/Align/src/AliAlgTrack.cxx | 202 ++++++------ Detectors/Align/src/AliAlgVol.cxx | 60 ++-- 45 files changed, 1251 insertions(+), 1257 deletions(-) diff --git a/Detectors/Align/include/Align/AliAlgAux.h b/Detectors/Align/include/Align/AliAlgAux.h index 36fea8ba84acb..97532b3d887b9 100644 --- a/Detectors/Align/include/Align/AliAlgAux.h +++ b/Detectors/Align/include/Align/AliAlgAux.h @@ -16,14 +16,9 @@ #ifndef ALIALGAUX_H #define ALIALGAUX_H -#include -#include +#include "CommonConstants/MathConstants.h" +#include "MathUtils/Utils.h" #include "ReconstructionDataFormats/Track.h" -// class AliCDBId; -class TMap; -class TList; - -using namespace TMath; namespace o2 { @@ -49,42 +44,42 @@ enum { kColl, kCosm, kNTrackTypes }; // -inline Double_t Sector2Alpha(int sect); -inline Int_t Phi2Sector(double alpha); -inline Double_t SectorDAlpha() { return Pi() / 9; } +inline double Sector2Alpha(int sect); +inline int Phi2Sector(double alpha); +inline double SectorDAlpha() { return constants::math::PI / 9; } // template void BringTo02Pi(F& phi); template void BringToPiPM(F& phi); template -Bool_t OKforPhiMin(F phiMin, F phi); +bool OKforPhiMin(F phiMin, F phi); template -Bool_t OKforPhiMax(F phiMax, F phi); +bool OKforPhiMax(F phiMax, F phi); template F MeanPhiSmall(F phi0, F phi1); template F DeltaPhiSmall(F phi0, F phi1); template -Bool_t SmallerAbs(F d, F tolD) +bool SmallerAbs(F d, F tolD) { - return Abs(d) < tolD; + return std::abs(d) < tolD; } template -Bool_t Smaller(F d, F tolD) +bool Smaller(F d, F tolD) { return d < tolD; } // -inline Int_t NumberOfBitsSet(UInt_t x); -inline Bool_t IsZeroAbs(double d) { return SmallerAbs(d, kAlmostZeroD); } -inline Bool_t IsZeroAbs(float f) { return SmallerAbs(f, kAlmostZeroF); } -inline Bool_t IsZeroPos(double d) { return Smaller(d, kAlmostZeroD); } -inline Bool_t IsZeroPos(float f) { return Smaller(f, kAlmostZeroF); } +inline int NumberOfBitsSet(uint32_t x); +inline bool IsZeroAbs(double d) { return SmallerAbs(d, kAlmostZeroD); } +inline bool IsZeroAbs(float f) { return SmallerAbs(f, kAlmostZeroF); } +inline bool IsZeroPos(double d) { return Smaller(d, kAlmostZeroD); } +inline bool IsZeroPos(float f) { return Smaller(f, kAlmostZeroF); } // int FindKeyIndex(int key, const int* arr, int n); // -void PrintBits(ULong64_t patt, Int_t maxBits); +void PrintBits(size_t patt, int maxBits); } // namespace AliAlgAux @@ -94,9 +89,9 @@ inline void AliAlgAux::BringTo02Pi(F& phi) { // bring phi to 0-2pi range if (phi < 0) - phi += TwoPi(); - else if (phi > TwoPi()) - phi -= TwoPi(); + phi += constants::math::TwoPI; + else if (phi > constants::math::TwoPI) + phi -= constants::math::TwoPI; } //_________________________________________________________________________________ @@ -104,25 +99,25 @@ template inline void AliAlgAux::BringToPiPM(F& phi) { // bring phi to -pi:pi range - if (phi > Pi()) - phi -= TwoPi(); + if (phi > constants::math::PI) + phi -= constants::math::TwoPI; } //_________________________________________________________________________________ template -inline Bool_t AliAlgAux::OKforPhiMin(F phiMin, F phi) +inline bool AliAlgAux::OKforPhiMin(F phiMin, F phi) { // check if phi is above the phiMin, phi's must be in 0-2pi range F dphi = phi - phiMin; - return ((dphi > 0 && dphi < Pi()) || dphi < -Pi()) ? kTRUE : kFALSE; + return ((dphi > 0 && dphi < constants::math::PI) || dphi < -constants::math::PI) ? true : false; } //_________________________________________________________________________________ template -inline Bool_t AliAlgAux::OKforPhiMax(F phiMax, F phi) +inline bool AliAlgAux::OKforPhiMax(F phiMax, F phi) { // check if phi is below the phiMax, phi's must be in 0-2pi range F dphi = phi - phiMax; - return ((dphi < 0 && dphi > -Pi()) || dphi > Pi()) ? kTRUE : kFALSE; + return ((dphi < 0 && dphi > -constants::math::PI) || dphi > constants::math::PI) ? true : false; } //_________________________________________________________________________________ @@ -137,7 +132,7 @@ inline F AliAlgAux::MeanPhiSmall(F phi0, F phi1) phi1 = phi; } if (phi0 > phi1) - phi = (phi1 - (TwoPi() - phi0)) / 2; // wrap + phi = (phi1 - (constants::math::TwoPI - phi0)) / 2; // wrap else phi = (phi0 + phi1) / 2; BringTo02Pi(phi); @@ -157,12 +152,12 @@ inline F AliAlgAux::DeltaPhiSmall(F phi0, F phi1) } del = phi1 - phi0; if (del < 0) - del += TwoPi(); + del += constants::math::TwoPI; return del; } //_________________________________________________________________________________ -inline Int_t AliAlgAux::NumberOfBitsSet(UInt_t x) +inline int AliAlgAux::NumberOfBitsSet(uint32_t x) { // count number of non-0 bits in 32bit word x = x - ((x >> 1) & 0x55555555); @@ -171,7 +166,7 @@ inline Int_t AliAlgAux::NumberOfBitsSet(UInt_t x) } //_________________________________________________________________________________ -inline Double_t AliAlgAux::Sector2Alpha(int sect) +inline double AliAlgAux::Sector2Alpha(int sect) { // get barrel sector alpha in -pi:pi format if (sect > 8) @@ -180,10 +175,10 @@ inline Double_t AliAlgAux::Sector2Alpha(int sect) } //_________________________________________________________________________________ -inline Int_t AliAlgAux::Phi2Sector(double phi) +inline int AliAlgAux::Phi2Sector(double phi) { // get barrel sector from phi in -pi:pi format - int sect = Nint((phi * RadToDeg() - 10) / 20.); + int sect = math_utils::nintd((phi * constants::math::Rad2Deg - 10) / 20.); if (sect < 0) sect += 18; return sect; diff --git a/Detectors/Align/include/Align/AliAlgConstraint.h b/Detectors/Align/include/Align/AliAlgConstraint.h index f3858e7316bec..a65ba301cf7d7 100644 --- a/Detectors/Align/include/Align/AliAlgConstraint.h +++ b/Detectors/Align/include/Align/AliAlgConstraint.h @@ -48,7 +48,7 @@ class AliAlgConstraint : public TNamed void SetParent(const AliAlgVol* par); const AliAlgVol* GetParent() const { return fParent; } // - Int_t GetNChildren() const { return fChildren.GetEntriesFast(); } + int GetNChildren() const { return fChildren.GetEntriesFast(); } AliAlgVol* GetChild(int i) const { return (AliAlgVol*)fChildren[i]; } void AddChild(const AliAlgVol* v) { @@ -56,17 +56,17 @@ class AliAlgConstraint : public TNamed fChildren.AddLast((AliAlgVol*)v); } // - Bool_t IsDOFConstrained(Int_t dof) const { return fConstraint & 0x1 << dof; } - UChar_t GetConstraintPattern() const { return fConstraint; } - void ConstrainDOF(Int_t dof) { fConstraint |= 0x1 << dof; } - void UnConstrainDOF(Int_t dof) { fConstraint &= ~(0x1 << dof); } - void SetConstrainPattern(UInt_t pat) { fConstraint = pat; } - Bool_t HasConstraint() const { return fConstraint; } - Double_t GetSigma(int i) const { return fSigma[i]; } + bool IsDOFConstrained(int dof) const { return fConstraint & 0x1 << dof; } + uint8_t GetConstraintPattern() const { return fConstraint; } + void ConstrainDOF(int dof) { fConstraint |= 0x1 << dof; } + void UnConstrainDOF(int dof) { fConstraint &= ~(0x1 << dof); } + void SetConstrainPattern(uint32_t pat) { fConstraint = pat; } + bool HasConstraint() const { return fConstraint; } + double GetSigma(int i) const { return fSigma[i]; } void SetSigma(int i, double s = 0) { fSigma[i] = s; } // - void SetNoJacobian(Bool_t v = kTRUE) { SetBit(kNoJacobianBit, v); } - Bool_t GetNoJacobian() const { return TestBit(kNoJacobianBit); } + void SetNoJacobian(bool v = true) { SetBit(kNoJacobianBit, v); } + bool GetNoJacobian() const { return TestBit(kNoJacobianBit); } // void ConstrCoefGeom(const TGeoHMatrix& matRD, float* jac /*[kNDOFGeom][kNDOFGeom]*/) const; // @@ -81,10 +81,10 @@ class AliAlgConstraint : public TNamed AliAlgConstraint& operator=(const AliAlgConstraint&); // protected: - UInt_t fConstraint; // bit pattern of constraint - Double_t fSigma[kNDOFGeom]; // optional sigma if constraint is gaussian - const AliAlgVol* fParent; // parent volume for contraint, lab if 0 - TObjArray fChildren; // volumes subjected to constraints + uint32_t fConstraint; // bit pattern of constraint + double fSigma[kNDOFGeom]; // optional sigma if constraint is gaussian + const AliAlgVol* fParent; // parent volume for contraint, lab if 0 + TObjArray fChildren; // volumes subjected to constraints // ClassDef(AliAlgConstraint, 2); }; diff --git a/Detectors/Align/include/Align/AliAlgDOFStat.h b/Detectors/Align/include/Align/AliAlgDOFStat.h index ce29aba8d2fb3..ce2ee30f94e25 100644 --- a/Detectors/Align/include/Align/AliAlgDOFStat.h +++ b/Detectors/Align/include/Align/AliAlgDOFStat.h @@ -30,18 +30,18 @@ class AliAlgSteer; class AliAlgDOFStat : public TNamed { public: - AliAlgDOFStat(Int_t n = 0); + AliAlgDOFStat(int n = 0); virtual ~AliAlgDOFStat(); // - Int_t GetNDOFs() const { return fNDOFs; } - Int_t GetStat(int idf) const { return idf < fNDOFs ? fStat[idf] : 0; } - Int_t* GetStat() const { return (Int_t*)fStat; }; + int GetNDOFs() const { return fNDOFs; } + int GetStat(int idf) const { return idf < fNDOFs ? fStat[idf] : 0; } + int* GetStat() const { return (int*)fStat; }; void SetStat(int idf, int v) { fStat[idf] = v; } void AddStat(int idf, int v) { fStat[idf] += v; } - Int_t GetNMerges() const { return fNMerges; } + int GetNMerges() const { return fNMerges; } TH1F* CreateHisto(AliAlgSteer* st) const; virtual void Print(Option_t* opt) const; - virtual Long64_t Merge(TCollection* list); + virtual int64_t Merge(TCollection* list); // protected: // @@ -49,9 +49,9 @@ class AliAlgDOFStat : public TNamed AliAlgDOFStat& operator=(const AliAlgDOFStat&); // protected: - Int_t fNDOFs; // number of dofs defined - Int_t fNMerges; // number of merges - Int_t* fStat; //[fNDOFs] statistics per DOF + int fNDOFs; // number of dofs defined + int fNMerges; // number of merges + int* fStat; //[fNDOFs] statistics per DOF // ClassDef(AliAlgDOFStat, 1); }; diff --git a/Detectors/Align/include/Align/AliAlgDet.h b/Detectors/Align/include/Align/AliAlgDet.h index cf54dff6167bf..6f79737a5b8bd 100644 --- a/Detectors/Align/include/Align/AliAlgDet.h +++ b/Detectors/Align/include/Align/AliAlgDet.h @@ -45,62 +45,62 @@ class AliAlgDet : public TNamed enum { kNMaxKalibDOF = 64 }; // AliAlgDet(); - AliAlgDet(const char* name, const char* title = "", Int_t id = -1) : TNamed(name, title) { SetUniqueID(id); }; + AliAlgDet(const char* name, const char* title = "", int id = -1) : TNamed(name, title) { SetUniqueID(id); }; virtual ~AliAlgDet(); - Int_t GetDetID() const { return GetUniqueID(); } + int GetDetID() const { return GetUniqueID(); } detectors::DetID GetO2DetID() const { return detectors::DetID(GetUniqueID()); }; - void SetDetID(UInt_t tp); + void SetDetID(uint32_t tp); void SetDetID(detectors::DetID id) { SetUniqueID(id); } // virtual void CacheReferenceOCDB(); - virtual void AcknowledgeNewRun(Int_t run); + virtual void AcknowledgeNewRun(int run); virtual void UpdateL2GRecoMatrices(); virtual void ApplyAlignmentFromMPSol(); // - Int_t VolID2SID(Int_t vid) const; - Int_t SID2VolID(Int_t sid) const { return sid < GetNSensors() ? fSID2VolID[sid] : -1; } //todo - Int_t GetNSensors() const { return fSensors.GetEntriesFast(); } - Int_t GetNVolumes() const { return fVolumes.GetEntriesFast(); } - Int_t GetVolIDMin() const { return fVolIDMin; } - Int_t GetVolIDMax() const { return fVolIDMax; } - Bool_t SensorOfDetector(Int_t vid) const { return vid >= fVolIDMin && vid <= fVolIDMax; } + int VolID2SID(int vid) const; + int SID2VolID(int sid) const { return sid < GetNSensors() ? fSID2VolID[sid] : -1; } //todo + int GetNSensors() const { return fSensors.GetEntriesFast(); } + int GetNVolumes() const { return fVolumes.GetEntriesFast(); } + int GetVolIDMin() const { return fVolIDMin; } + int GetVolIDMax() const { return fVolIDMax; } + bool SensorOfDetector(int vid) const { return vid >= fVolIDMin && vid <= fVolIDMax; } void SetAddError(double y, double z); - const Double_t* GetAddError() const { return fAddError; } + const double* GetAddError() const { return fAddError; } // - Int_t GetNPoints() const { return fNPoints; } + int GetNPoints() const { return fNPoints; } // void SetAlgSteer(AliAlgSteer* s) { fAlgSteer = s; } - AliAlgSens* GetSensor(Int_t id) const { return (AliAlgSens*)fSensors.UncheckedAt(id); } - AliAlgSens* GetSensorByVolId(Int_t vid) const + AliAlgSens* GetSensor(int id) const { return (AliAlgSens*)fSensors.UncheckedAt(id); } + AliAlgSens* GetSensorByVolId(int vid) const { int sid = VolID2SID(vid); return sid < 0 ? 0 : GetSensor(sid); } AliAlgSens* GetSensor(const char* symname) const { return (AliAlgSens*)fSensors.FindObject(symname); } - AliAlgVol* GetVolume(Int_t id) const { return (AliAlgVol*)fVolumes.UncheckedAt(id); } + AliAlgVol* GetVolume(int id) const { return (AliAlgVol*)fVolumes.UncheckedAt(id); } AliAlgVol* GetVolume(const char* symname) const { return (AliAlgVol*)fVolumes.FindObject(symname); } // - Bool_t OwnsDOFID(Int_t id) const; - AliAlgVol* GetVolOfDOFID(Int_t id) const; + bool OwnsDOFID(int id) const; + AliAlgVol* GetVolOfDOFID(int id) const; // - Int_t GetDetLabel() const { return (GetDetID() + 1) * 1000000; } - void SetFreeDOF(Int_t dof); - void FixDOF(Int_t dof); - void SetFreeDOFPattern(ULong64_t pat) + int GetDetLabel() const { return (GetDetID() + 1) * 1000000; } + void SetFreeDOF(int dof); + void FixDOF(int dof); + void SetFreeDOFPattern(uint64_t pat) { fCalibDOF = pat; CalcFree(); } - Bool_t IsFreeDOF(Int_t dof) const { return (fCalibDOF & (0x1 << dof)) != 0; } - Bool_t IsCondDOF(Int_t dof) const; - ULong64_t GetFreeDOFPattern() const { return fCalibDOF; } - Int_t GetNProcessedPoints() const { return fNProcPoints; } + bool IsFreeDOF(int dof) const { return (fCalibDOF & (0x1 << dof)) != 0; } + bool IsCondDOF(int dof) const; + uint64_t GetFreeDOFPattern() const { return fCalibDOF; } + int GetNProcessedPoints() const { return fNProcPoints; } virtual const char* GetCalibDOFName(int) const { return 0; } - virtual Double_t GetCalibDOFVal(int) const { return 0; } - virtual Double_t GetCalibDOFValWithCal(int) const { return 0; } + virtual double GetCalibDOFVal(int) const { return 0; } + virtual double GetCalibDOFValWithCal(int) const { return 0; } // - virtual Int_t InitGeom(); - virtual Int_t AssignDOFs(); + virtual int InitGeom(); + virtual int AssignDOFs(); virtual void InitDOFs(); virtual void Terminate(); void FillDOFStat(AliAlgDOFStat* dofst = 0) const; @@ -108,33 +108,33 @@ class AliAlgDet : public TNamed virtual void DefineVolumes(); virtual void DefineMatrices(); virtual void Print(const Option_t* opt = "") const; - // virtual Int_t ProcessPoints(const AliESDtrack* esdTr, AliAlgTrack* algTrack, Bool_t inv = kFALSE); FIXME(milettri): needs AliESDtrack + // virtual int ProcessPoints(const AliESDtrack* esdTr, AliAlgTrack* algTrack, bool inv = false); FIXME(milettri): needs AliESDtrack virtual void UpdatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) const; - virtual void SetUseErrorParam(Int_t v = 0); - Int_t GetUseErrorParam() const { return fUseErrorParam; } + virtual void SetUseErrorParam(int v = 0); + int GetUseErrorParam() const { return fUseErrorParam; } // - // virtual Bool_t AcceptTrack(const AliESDtrack* trc, Int_t trtype) const = 0; FIXME(milettri): needs AliESDtrack - // Bool_t CheckFlags(const AliESDtrack* trc, Int_t trtype) const; FIXME(milettri): needs AliESDtrack + // virtual bool AcceptTrack(const AliESDtrack* trc, int trtype) const = 0; FIXME(milettri): needs AliESDtrack + // bool CheckFlags(const AliESDtrack* trc, int trtype) const; FIXME(milettri): needs AliESDtrack // virtual AliAlgPoint* GetPointFromPool(); virtual void ResetPool(); virtual void WriteSensorPositions(const char* outFName); // void SetInitGeomDone() { SetBit(kInitGeomDone); } - Bool_t GetInitGeomDone() const { return TestBit(kInitGeomDone); } + bool GetInitGeomDone() const { return TestBit(kInitGeomDone); } // void SetInitDOFsDone() { SetBit(kInitDOFsDone); } - Bool_t GetInitDOFsDone() const { return TestBit(kInitDOFsDone); } + bool GetInitDOFsDone() const { return TestBit(kInitDOFsDone); } void FixNonSensors(); - void SetFreeDOFPattern(UInt_t pat = 0xffffffff, int lev = -1, const char* match = 0); + void SetFreeDOFPattern(uint32_t pat = 0xffffffff, int lev = -1, const char* match = 0); void SetDOFCondition(int dof, float condErr, int lev = -1, const char* match = 0); int SelectVolumes(TObjArray* arr, int lev = -1, const char* match = 0); // - Int_t GetNDOFs() const { return fNDOFs; } - Int_t GetNCalibDOFs() const { return fNCalibDOF; } - Int_t GetNCalibDOFsFree() const { return fNCalibDOFFree; } + int GetNDOFs() const { return fNDOFs; } + int GetNCalibDOFs() const { return fNCalibDOF; } + int GetNCalibDOFsFree() const { return fNCalibDOFFree; } // - void SetDisabled(Int_t tp, Bool_t v) + void SetDisabled(int tp, bool v) { fDisabled[tp] = v; SetObligatory(tp, !v); @@ -144,34 +144,34 @@ class AliAlgDet : public TNamed SetDisabledColl(); SetDisabledCosm(); } - void SetDisabledColl(Bool_t v = kTRUE) { SetDisabled(AliAlgAux::kColl, v); } - void SetDisabledCosm(Bool_t v = kTRUE) { SetDisabled(AliAlgAux::kCosm, v); } - Bool_t IsDisabled(Int_t tp) const { return fDisabled[tp]; } - Bool_t IsDisabled() const { return IsDisabledColl() && IsDisabledCosm(); } - Bool_t IsDisabledColl() const { return IsDisabled(AliAlgAux::kColl); } - Bool_t IsDisabledCosm() const { return IsDisabled(AliAlgAux::kCosm); } - // - void SetTrackFlagSel(Int_t tp, ULong_t f) { fTrackFlagSel[tp] = f; } - void SetTrackFlagSelColl(ULong_t f) { SetTrackFlagSel(AliAlgAux::kColl, f); } - void SetTrackFlagSelCosm(ULong_t f) { SetTrackFlagSel(AliAlgAux::kCosm, f); } - ULong_t GetTrackFlagSel(Int_t tp) const { return fTrackFlagSel[tp]; } - ULong_t GetTrackFlagSelColl() const { return GetTrackFlagSel(AliAlgAux::kColl); } - ULong_t GetTrackFlagSelCosm() const { return GetTrackFlagSel(AliAlgAux::kCosm); } - // - void SetNPointsSel(Int_t tp, Int_t n) { fNPointsSel[tp] = n; } - void SetNPointsSelColl(Int_t n) { SetNPointsSel(AliAlgAux::kColl, n); } - void SetNPointsSelCosm(Int_t n) { SetNPointsSel(AliAlgAux::kCosm, n); } - Int_t GetNPointsSel(Int_t tp) const { return fNPointsSel[tp]; } - Int_t GetNPointsSelColl() const { return GetNPointsSel(AliAlgAux::kColl); } - Int_t GetNPointsSelCosm() const { return GetNPointsSel(AliAlgAux::kCosm); } - // - // - Bool_t IsObligatory(Int_t tp) const { return fObligatory[tp]; } - Bool_t IsObligatoryColl() const { return IsObligatory(AliAlgAux::kColl); } - Bool_t IsObligatoryCosm() const { return IsObligatory(AliAlgAux::kCosm); } - void SetObligatory(Int_t tp, Bool_t v = kTRUE); - void SetObligatoryColl(Bool_t v = kTRUE) { SetObligatory(AliAlgAux::kColl, v); } - void SetObligatoryCosm(Bool_t v = kTRUE) { SetObligatory(AliAlgAux::kCosm, v); } + void SetDisabledColl(bool v = true) { SetDisabled(AliAlgAux::kColl, v); } + void SetDisabledCosm(bool v = true) { SetDisabled(AliAlgAux::kCosm, v); } + bool IsDisabled(int tp) const { return fDisabled[tp]; } + bool IsDisabled() const { return IsDisabledColl() && IsDisabledCosm(); } + bool IsDisabledColl() const { return IsDisabled(AliAlgAux::kColl); } + bool IsDisabledCosm() const { return IsDisabled(AliAlgAux::kCosm); } + // + void SetTrackFlagSel(int tp, uint64_t f) { fTrackFlagSel[tp] = f; } + void SetTrackFlagSelColl(uint64_t f) { SetTrackFlagSel(AliAlgAux::kColl, f); } + void SetTrackFlagSelCosm(uint64_t f) { SetTrackFlagSel(AliAlgAux::kCosm, f); } + uint64_t GetTrackFlagSel(int tp) const { return fTrackFlagSel[tp]; } + uint64_t GetTrackFlagSelColl() const { return GetTrackFlagSel(AliAlgAux::kColl); } + uint64_t GetTrackFlagSelCosm() const { return GetTrackFlagSel(AliAlgAux::kCosm); } + // + void SetNPointsSel(int tp, int n) { fNPointsSel[tp] = n; } + void SetNPointsSelColl(int n) { SetNPointsSel(AliAlgAux::kColl, n); } + void SetNPointsSelCosm(int n) { SetNPointsSel(AliAlgAux::kCosm, n); } + int GetNPointsSel(int tp) const { return fNPointsSel[tp]; } + int GetNPointsSelColl() const { return GetNPointsSel(AliAlgAux::kColl); } + int GetNPointsSelCosm() const { return GetNPointsSel(AliAlgAux::kCosm); } + // + // + bool IsObligatory(int tp) const { return fObligatory[tp]; } + bool IsObligatoryColl() const { return IsObligatory(AliAlgAux::kColl); } + bool IsObligatoryCosm() const { return IsObligatory(AliAlgAux::kCosm); } + void SetObligatory(int tp, bool v = true); + void SetObligatoryColl(bool v = true) { SetObligatory(AliAlgAux::kColl, v); } + void SetObligatoryCosm(bool v = true) { SetObligatory(AliAlgAux::kCosm, v); } // void AddAutoConstraints() const; void ConstrainOrphans(const double* sigma, const char* match = 0); @@ -180,22 +180,22 @@ class AliAlgDet : public TNamed virtual void WriteCalibrationResults() const; virtual void WriteAlignmentResults() const; // - Float_t* GetParVals() const { return fParVals; } - Double_t GetParVal(int par) const { return fParVals ? fParVals[par] : 0; } - Double_t GetParErr(int par) const { return fParErrs ? fParErrs[par] : 0; } - Int_t GetParLab(int par) const { return fParLabs ? fParLabs[par] : 0; } + float* GetParVals() const { return fParVals; } + double GetParVal(int par) const { return fParVals ? fParVals[par] : 0; } + double GetParErr(int par) const { return fParErrs ? fParErrs[par] : 0; } + int GetParLab(int par) const { return fParLabs ? fParLabs[par] : 0; } // - void SetParVals(Int_t npar, Double_t* vl, Double_t* er); - void SetParVal(Int_t par, Double_t v = 0) { fParVals[par] = v; } - void SetParErr(Int_t par, Double_t e = 0) { fParErrs[par] = e; } + void SetParVals(int npar, double* vl, double* er); + void SetParVal(int par, double v = 0) { fParVals[par] = v; } + void SetParErr(int par, double e = 0) { fParErrs[par] = e; } // - Int_t GetFirstParGloID() const { return fFirstParGloID; } - Int_t GetParGloID(Int_t par) const { return fFirstParGloID + par; } - void SetFirstParGloID(Int_t id) { fFirstParGloID = id; } + int GetFirstParGloID() const { return fFirstParGloID; } + int GetParGloID(int par) const { return fFirstParGloID + par; } + void SetFirstParGloID(int id) { fFirstParGloID = id; } // protected: void SortSensors(); - void CalcFree(Bool_t condFree = kFALSE); + void CalcFree(bool condFree = false); // // ------- dummies --------- AliAlgDet(const AliAlgDet&); @@ -203,37 +203,37 @@ class AliAlgDet : public TNamed // protected: // - Int_t fNDOFs; // number of DOFs free - Int_t fVolIDMin; // min volID for this detector (for sensors only) - Int_t fVolIDMax; // max volID for this detector (for sensors only) - Int_t fNSensors; // number of sensors (i.e. volID's) - Int_t* fSID2VolID; //[fNSensors] table of conversion from VolID to sid - Int_t fNProcPoints; // total number of points processed + int fNDOFs; // number of DOFs free + int fVolIDMin; // min volID for this detector (for sensors only) + int fVolIDMax; // max volID for this detector (for sensors only) + int fNSensors; // number of sensors (i.e. volID's) + int* fSID2VolID; //[fNSensors] table of conversion from VolID to sid + int fNProcPoints; // total number of points processed // // Detector specific calibration degrees of freedom - Int_t fNCalibDOF; // number of calibDOFs for detector (preset) - Int_t fNCalibDOFFree; // number of calibDOFs for detector (preset) - ULong64_t fCalibDOF; // status of calib dof - Int_t fFirstParGloID; // ID of the 1st parameter in the global results array - Float_t* fParVals; //! values of the fitted params - Float_t* fParErrs; //! errors of the fitted params - Int_t* fParLabs; //! labels for parameters + int fNCalibDOF; // number of calibDOFs for detector (preset) + int fNCalibDOFFree; // number of calibDOFs for detector (preset) + uint64_t fCalibDOF; // status of calib dof + int fFirstParGloID; // ID of the 1st parameter in the global results array + float* fParVals; //! values of the fitted params + float* fParErrs; //! errors of the fitted params + int* fParLabs; //! labels for parameters // // Track selection - Bool_t fDisabled[AliAlgAux::kNTrackTypes]; // detector disabled/enabled in the track - Bool_t fObligatory[AliAlgAux::kNTrackTypes]; // detector must be present in the track - ULong_t fTrackFlagSel[AliAlgAux::kNTrackTypes]; // flag for track selection - Int_t fNPointsSel[AliAlgAux::kNTrackTypes]; // min number of points to require + bool fDisabled[AliAlgAux::kNTrackTypes]; // detector disabled/enabled in the track + bool fObligatory[AliAlgAux::kNTrackTypes]; // detector must be present in the track + uint64_t fTrackFlagSel[AliAlgAux::kNTrackTypes]; // flag for track selection + int fNPointsSel[AliAlgAux::kNTrackTypes]; // min number of points to require // - Int_t fUseErrorParam; // signal that points need to be updated using track info, 0 - no - Double_t fAddError[2]; // additional error increment for measurement - TObjArray fSensors; // all sensors of the detector - TObjArray fVolumes; // all volumes of the detector + int fUseErrorParam; // signal that points need to be updated using track info, 0 - no + double fAddError[2]; // additional error increment for measurement + TObjArray fSensors; // all sensors of the detector + TObjArray fVolumes; // all volumes of the detector // // this is transient info - Int_t fNPoints; //! number of points from this detector - Int_t fPoolNPoints; //! number of points in the pool - Int_t fPoolFreePointID; //! id of the last free point in the pool + int fNPoints; //! number of points from this detector + int fPoolNPoints; //! number of points in the pool + int fPoolFreePointID; //! id of the last free point in the pool TObjArray fPointsPool; //! pool of aligment points // AliAlgSteer* fAlgSteer; // pointer to alignment steering object @@ -243,7 +243,7 @@ class AliAlgDet : public TNamed //FIXME(milettri): needs AliESDtrack ////_____________________________________________________ -//inline Bool_t AliAlgDet::CheckFlags(const AliESDtrack* trc, Int_t trtype) const +//inline bool AliAlgDet::CheckFlags(const AliESDtrack* trc, int trtype) const //{ // // check if flags are ok // return (trc->GetStatus() & fTrackFlagSel[trtype]) == fTrackFlagSel[trtype]; diff --git a/Detectors/Align/include/Align/AliAlgDetHMPID.h b/Detectors/Align/include/Align/AliAlgDetHMPID.h index 79f3422416a48..684d2b2a6541f 100644 --- a/Detectors/Align/include/Align/AliAlgDetHMPID.h +++ b/Detectors/Align/include/Align/AliAlgDetHMPID.h @@ -30,7 +30,7 @@ class AliAlgDetHMPID : public AliAlgDet // virtual void DefineVolumes(); // - Bool_t AcceptTrack(const AliESDtrack* trc, Int_t trtype) const; + bool AcceptTrack(const AliESDtrack* trc, int trtype) const; // protected: // diff --git a/Detectors/Align/include/Align/AliAlgDetITS.h b/Detectors/Align/include/Align/AliAlgDetITS.h index d8e0ea4c9c3fa..e9221b3254696 100644 --- a/Detectors/Align/include/Align/AliAlgDetITS.h +++ b/Detectors/Align/include/Align/AliAlgDetITS.h @@ -40,25 +40,25 @@ class AliAlgDetITS : public AliAlgDet // virtual void DefineVolumes(); // - Bool_t AcceptTrack(const AliESDtrack* trc, Int_t trtype) const; + bool AcceptTrack(const AliESDtrack* trc, int trtype) const; void SetAddErrorLr(int ilr, double sigY, double sigZ); void SetSkipLr(int ilr); // virtual void UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const; - virtual void SetUseErrorParam(Int_t v = 1); - void SetITSSelPattern(Int_t trtype, ITSSel_t sel) { fITSPatt[trtype] = sel; } + virtual void SetUseErrorParam(int v = 1); + void SetITSSelPattern(int trtype, ITSSel_t sel) { fITSPatt[trtype] = sel; } void SetITSSelPatternColl(ITSSel_t sel = kSPDAny) { SetITSSelPattern(AliAlgAux::kColl, sel); } void SetITSSelPatternCosm(ITSSel_t sel = kSPDNoSel) { SetITSSelPattern(AliAlgAux::kCosm, sel); } - Int_t GetITSSelPattern(int tp) const { return fITSPatt[tp]; } - Int_t GetITSSelPatternColl() const { return fITSPatt[AliAlgAux::kColl]; } - Int_t GetITSSelPatternCosm() const { return fITSPatt[AliAlgAux::kCosm]; } + int GetITSSelPattern(int tp) const { return fITSPatt[tp]; } + int GetITSSelPatternColl() const { return fITSPatt[AliAlgAux::kColl]; } + int GetITSSelPatternCosm() const { return fITSPatt[AliAlgAux::kCosm]; } // virtual void Print(const Option_t* opt = "") const; // - static Bool_t CheckHitPattern(const AliESDtrack* trc, Int_t sel); - static const char* GetITSPattName(Int_t sel) { return sel < kNSPDSelTypes ? fgkHitsSel[sel] : 0; } + static bool CheckHitPattern(const AliESDtrack* trc, int sel); + static const char* GetITSPattName(int sel) { return sel < kNSPDSelTypes ? fgkHitsSel[sel] : 0; } // protected: // @@ -70,9 +70,9 @@ class AliAlgDetITS : public AliAlgDet // protected: // - Int_t fITSPatt[AliAlgAux::kNTrackTypes]; // ITS hits selection pattern for coll/cosm tracks + int fITSPatt[AliAlgAux::kNTrackTypes]; // ITS hits selection pattern for coll/cosm tracks // - static const Char_t* fgkHitsSel[kNSPDSelTypes]; // ITS selection names + static const char* fgkHitsSel[kNSPDSelTypes]; // ITS selection names // ClassDef(AliAlgDetITS, 1); }; diff --git a/Detectors/Align/include/Align/AliAlgDetTOF.h b/Detectors/Align/include/Align/AliAlgDetTOF.h index 5dff50371bb4c..2ae4186cd11b7 100644 --- a/Detectors/Align/include/Align/AliAlgDetTOF.h +++ b/Detectors/Align/include/Align/AliAlgDetTOF.h @@ -31,7 +31,7 @@ class AliAlgDetTOF : public AliAlgDet // virtual void DefineVolumes(); // - Bool_t AcceptTrack(const AliESDtrack* trc, Int_t trtype) const; + bool AcceptTrack(const AliESDtrack* trc, int trtype) const; // protected: // diff --git a/Detectors/Align/include/Align/AliAlgDetTPC.h b/Detectors/Align/include/Align/AliAlgDetTPC.h index 58b1c952a4b8d..da0854c071d0e 100644 --- a/Detectors/Align/include/Align/AliAlgDetTPC.h +++ b/Detectors/Align/include/Align/AliAlgDetTPC.h @@ -31,7 +31,7 @@ class AliAlgDetTPC : public AliAlgDet // virtual void DefineVolumes(); // - Bool_t AcceptTrack(const AliESDtrack* trc, Int_t trtype) const; + bool AcceptTrack(const AliESDtrack* trc, int trtype) const; // protected: // diff --git a/Detectors/Align/include/Align/AliAlgDetTRD.h b/Detectors/Align/include/Align/AliAlgDetTRD.h index 77be9481e6c71..28876444d83d1 100644 --- a/Detectors/Align/include/Align/AliAlgDetTRD.h +++ b/Detectors/Align/include/Align/AliAlgDetTRD.h @@ -37,24 +37,24 @@ class AliAlgDetTRD : public AliAlgDet virtual void DefineVolumes(); virtual void Print(const Option_t* opt = "") const; // - Bool_t AcceptTrack(const AliESDtrack* trc, Int_t trtype) const; + bool AcceptTrack(const AliESDtrack* trc, int trtype) const; // virtual const char* GetCalibDOFName(int i) const; // virtual void WritePedeInfo(FILE* parOut, const Option_t* opt = "") const; // void SetNonRCCorrDzDtgl(double v = 0) { fNonRCCorrDzDtgl = v; } - Double_t GetNonRCCorrDzDtgl() const { return fNonRCCorrDzDtgl; } - Double_t GetNonRCCorrDzDtglWithCal() const { return GetNonRCCorrDzDtgl() + GetParVal(kCalibNRCCorrDzDtgl); } + double GetNonRCCorrDzDtgl() const { return fNonRCCorrDzDtgl; } + double GetNonRCCorrDzDtglWithCal() const { return GetNonRCCorrDzDtgl() + GetParVal(kCalibNRCCorrDzDtgl); } // void SetCorrDVT(double v = 0) { fCorrDVT = 0; } - Double_t GetCorrDVT() const { return fCorrDVT; } - Double_t GetCorrDVTWithCal() const { return GetCorrDVT() + GetParVal(kCalibDVT); } + double GetCorrDVT() const { return fCorrDVT; } + double GetCorrDVTWithCal() const { return GetCorrDVT() + GetParVal(kCalibDVT); } // - virtual Double_t GetCalibDOFVal(int id) const; - virtual Double_t GetCalibDOFValWithCal(int id) const; + virtual double GetCalibDOFVal(int id) const; + virtual double GetCalibDOFValWithCal(int id) const; // - const Double_t* GetExtraErrRC() const { return fExtraErrRC; } + const double* GetExtraErrRC() const { return fExtraErrRC; } void SetExtraErrRC(double y = 0.2, double z = 1.0) { fExtraErrRC[0] = y; @@ -69,9 +69,9 @@ class AliAlgDetTRD : public AliAlgDet // protected: // - Double_t fNonRCCorrDzDtgl; // correction in Z for non-crossing tracklets - Double_t fCorrDVT; // correction to Vdrift*t - Double_t fExtraErrRC[2]; // extra errors for RC tracklets + double fNonRCCorrDzDtgl; // correction in Z for non-crossing tracklets + double fCorrDVT; // correction to Vdrift*t + double fExtraErrRC[2]; // extra errors for RC tracklets // static const char* fgkCalibDOFName[kNCalibParams]; // diff --git a/Detectors/Align/include/Align/AliAlgMPRecord.h b/Detectors/Align/include/Align/AliAlgMPRecord.h index 6a81028a21481..1565a6a8980f6 100644 --- a/Detectors/Align/include/Align/AliAlgMPRecord.h +++ b/Detectors/Align/include/Align/AliAlgMPRecord.h @@ -33,41 +33,41 @@ class AliAlgMPRecord : public TObject AliAlgMPRecord(); virtual ~AliAlgMPRecord(); // - Int_t GetRun() const { return GetUniqueID(); } - void SetRun(Int_t r) { SetUniqueID(r); } - UInt_t GetTimeStamp() const { return fTimeStamp; } - void SetTimeStamp(UInt_t t) { fTimeStamp = t; } - UInt_t GetTrackID() const { return fTrackID; } - void SetTrackID(UInt_t t) { fTrackID = t; } - Bool_t IsCosmic() const { return TestBit(kCosmicBit); } - void SetCosmic(Bool_t v = kTRUE) { SetBit(kCosmicBit, v); } - // - Int_t GetNVarGlo() const { return fNVarGlo; } + int GetRun() const { return GetUniqueID(); } + void SetRun(int r) { SetUniqueID(r); } + uint32_t GetTimeStamp() const { return fTimeStamp; } + void SetTimeStamp(uint32_t t) { fTimeStamp = t; } + uint32_t GetTrackID() const { return fTrackID; } + void SetTrackID(uint32_t t) { fTrackID = t; } + bool IsCosmic() const { return TestBit(kCosmicBit); } + void SetCosmic(bool v = true) { SetBit(kCosmicBit, v); } + // + int GetNVarGlo() const { return fNVarGlo; } void SetNVarGlo(int n) { fNVarGlo = n; } // - Int_t GetNResid() const { return fNResid; } - Int_t GetNVarLoc() const { return fNVarLoc; } + int GetNResid() const { return fNResid; } + int GetNVarLoc() const { return fNVarLoc; } // - Int_t GetNDLoc(int id) const { return fNDLoc[id]; } - Int_t GetNDGlo(int id) const { return fNDGlo[id]; } - Int_t GetVolID(int id) const { return fVolID ? fVolID[id] - 1 : -1; } - Float_t GetResid(int id) const { return fResid[id]; } - Float_t GetResErr(int id) const { return fResErr[id]; } + int GetNDLoc(int id) const { return fNDLoc[id]; } + int GetNDGlo(int id) const { return fNDGlo[id]; } + int GetVolID(int id) const { return fVolID ? fVolID[id] - 1 : -1; } + float GetResid(int id) const { return fResid[id]; } + float GetResErr(int id) const { return fResErr[id]; } // - Float_t GetChi2Ini() const { return fChi2Ini; } - Float_t GetQ2Pt() const { return fQ2Pt; } - Float_t GetTgl() const { return fTgl; } - Int_t GetNDLocTot() const { return fNDLocTot; } - Int_t GetNDGloTot() const { return fNDGloTot; } - const Float_t* GetArrGlo() const { return fDGlo; } - const Float_t* GetArrLoc() const { return fDLoc; } - const Short_t* GetArrLabLoc() const { return fIDLoc; } - const Int_t* GetArrLabGlo() const { return fIDGlo; } + float GetChi2Ini() const { return fChi2Ini; } + float GetQ2Pt() const { return fQ2Pt; } + float GetTgl() const { return fTgl; } + int GetNDLocTot() const { return fNDLocTot; } + int GetNDGloTot() const { return fNDGloTot; } + const float* GetArrGlo() const { return fDGlo; } + const float* GetArrLoc() const { return fDLoc; } + const int16_t* GetArrLabLoc() const { return fIDLoc; } + const int* GetArrLabGlo() const { return fIDGlo; } // - Bool_t FillTrack(const AliAlgTrack* trc, const Int_t* id2Lab = 0); - void DummyRecord(Float_t res, Float_t err, Float_t dGlo, Int_t labGlo); + bool FillTrack(const AliAlgTrack* trc, const int* id2Lab = 0); + void DummyRecord(float res, float err, float dGlo, int labGlo); // - void Resize(Int_t nresid, Int_t nloc, Int_t nglo); + void Resize(int nresid, int nloc, int nglo); // virtual void Clear(const Option_t* opt = ""); virtual void Print(const Option_t* opt = "") const; @@ -80,33 +80,33 @@ class AliAlgMPRecord : public TObject // protected: // - UInt_t fTrackID; // track in the event - UInt_t fTimeStamp; // event time stamp - Int_t fNResid; // number of residuals for the track (=2 npoints) - Int_t fNVarLoc; // number of local variables for the track - Int_t fNVarGlo; // number of global variables defined - Int_t fNDLocTot; // total number of non-zero local derivatives - Int_t fNDGloTot; // total number of non-zero global derivatives - Int_t fNMeas; // number of measured points - Float_t fChi2Ini; // chi2 of initial kalman fit - Float_t fQ2Pt; // q/pt at ref point - Float_t fTgl; // dip angle at ref point - // - Short_t* fNDLoc; //[fNResid] number of non-0 local derivatives per residual - Int_t* fNDGlo; //[fNResid] number of non-0 global derivatives per residual - Int_t* fVolID; //[fNResid] volume id + 1 (0 - not a volume) - Float_t* fResid; //[fNResid] residuals - Float_t* fResErr; //[fNResid] error associated to residual - // - Short_t* fIDLoc; //[fNDLocTot] ID of local variables for non-0 local derivatives - Int_t* fIDGlo; //[fNDGloTot] ID of global variables for non-0 global derivatives - Float_t* fDLoc; //[fNDLocTot] non-0 local derivatives - Float_t* fDGlo; //[fNDGloTot] non-0 global derivatives + uint32_t fTrackID; // track in the event + uint32_t fTimeStamp; // event time stamp + int fNResid; // number of residuals for the track (=2 npoints) + int fNVarLoc; // number of local variables for the track + int fNVarGlo; // number of global variables defined + int fNDLocTot; // total number of non-zero local derivatives + int fNDGloTot; // total number of non-zero global derivatives + int fNMeas; // number of measured points + float fChi2Ini; // chi2 of initial kalman fit + float fQ2Pt; // q/pt at ref point + float fTgl; // dip angle at ref point + // + int16_t* fNDLoc; //[fNResid] number of non-0 local derivatives per residual + int* fNDGlo; //[fNResid] number of non-0 global derivatives per residual + int* fVolID; //[fNResid] volume id + 1 (0 - not a volume) + float* fResid; //[fNResid] residuals + float* fResErr; //[fNResid] error associated to residual + // + int16_t* fIDLoc; //[fNDLocTot] ID of local variables for non-0 local derivatives + int* fIDGlo; //[fNDGloTot] ID of global variables for non-0 global derivatives + float* fDLoc; //[fNDLocTot] non-0 local derivatives + float* fDGlo; //[fNDGloTot] non-0 global derivatives // // aux info - Int_t fNResidBook; //! number of slots booked for residuals - Int_t fNDLocTotBook; //! number of slots booked for local derivatives - Int_t fNDGloTotBook; //! number of slots booked for global derivatives + int fNResidBook; //! number of slots booked for residuals + int fNDLocTotBook; //! number of slots booked for local derivatives + int fNDGloTotBook; //! number of slots booked for global derivatives // ClassDef(AliAlgMPRecord, 4); }; diff --git a/Detectors/Align/include/Align/AliAlgPoint.h b/Detectors/Align/include/Align/AliAlgPoint.h index ff8064c90fd17..fec0205a7a24f 100644 --- a/Detectors/Align/include/Align/AliAlgPoint.h +++ b/Detectors/Align/include/Align/AliAlgPoint.h @@ -66,50 +66,50 @@ class AliAlgPoint : public TObject void Init(); void UpdatePointByTrackInfo(const trackParam_t* t); // - Double_t GetAlphaSens() const { return fAlphaSens; } - Double_t GetXSens() const { return fXSens; } - Double_t GetXPoint() const { return fXSens + GetXTracking(); } - Double_t GetXTracking() const { return fXYZTracking[0]; } - Double_t GetYTracking() const { return fXYZTracking[1]; } - Double_t GetZTracking() const { return fXYZTracking[2]; } - const Double_t* GetYZTracking() const { return &fXYZTracking[1]; } - const Double_t* GetXYZTracking() const { return fXYZTracking; } - const Double_t* GetYZErrTracking() const { return fErrYZTracking; } + double GetAlphaSens() const { return fAlphaSens; } + double GetXSens() const { return fXSens; } + double GetXPoint() const { return fXSens + GetXTracking(); } + double GetXTracking() const { return fXYZTracking[0]; } + double GetYTracking() const { return fXYZTracking[1]; } + double GetZTracking() const { return fXYZTracking[2]; } + const double* GetYZTracking() const { return &fXYZTracking[1]; } + const double* GetXYZTracking() const { return fXYZTracking; } + const double* GetYZErrTracking() const { return fErrYZTracking; } const AliAlgSens* GetSensor() const { return fSensor; } - UInt_t GetVolID() const { return fSensor->GetVolID(); } + uint32_t GetVolID() const { return fSensor->GetVolID(); } void SetSensor(AliAlgSens* s) { fSensor = s; } - Int_t GetDetID() const { return fDetID; } - Int_t GetSID() const { return fSID; } - Int_t GetMinLocVarID() const { return fMinLocVarID; } - Int_t GetMaxLocVarID() const { return fMaxLocVarID; } - Int_t GetNMatPar() const; - Bool_t ContainsMaterial() const { return TestBit(kMaterialBit); } - Bool_t ContainsMeasurement() const { return TestBit(kMeasurementBit); } - Bool_t GetNeedUpdateFromTrack() const { return TestBit(kUpdateFromTrackBit); } - Bool_t GetELossVaried() const { return TestBit(kVaryELossBit); } - Bool_t GetUseBzOnly() const { return TestBit(kUseBzOnly); } - Bool_t IsInvDir() const { return TestBit(kInvDir); } - Bool_t IsStatOK() const { return TestBit(kStatOK); } + int GetDetID() const { return fDetID; } + int GetSID() const { return fSID; } + int GetMinLocVarID() const { return fMinLocVarID; } + int GetMaxLocVarID() const { return fMaxLocVarID; } + int GetNMatPar() const; + bool ContainsMaterial() const { return TestBit(kMaterialBit); } + bool ContainsMeasurement() const { return TestBit(kMeasurementBit); } + bool GetNeedUpdateFromTrack() const { return TestBit(kUpdateFromTrackBit); } + bool GetELossVaried() const { return TestBit(kVaryELossBit); } + bool GetUseBzOnly() const { return TestBit(kUseBzOnly); } + bool IsInvDir() const { return TestBit(kInvDir); } + bool IsStatOK() const { return TestBit(kStatOK); } // - Double_t GetXTimesRho() const { return fXTimesRho; } - Double_t GetX2X0() const { return fX2X0; } + double GetXTimesRho() const { return fXTimesRho; } + double GetX2X0() const { return fX2X0; } void SetXTimesRho(double v) { fXTimesRho = v; } void SetX2X0(double v) { fX2X0 = v; } // - void SetDetID(Int_t id) { fDetID = (Char_t)id; } - void SetSID(Int_t id) { fSID = (Short_t)id; } + void SetDetID(int id) { fDetID = (char)id; } + void SetSID(int id) { fSID = (int16_t)id; } // - void SetMinLocVarID(Int_t id) { fMinLocVarID = id; } - void SetMaxLocVarID(Int_t id) { fMaxLocVarID = id; } - void SetELossVaried(Bool_t v = kTRUE) { SetBit(kVaryELossBit, v); } - void SetContainsMaterial(Bool_t v = kTRUE) { SetBit(kMaterialBit, v); } - void SetContainsMeasurement(Bool_t v = kTRUE) { SetBit(kMeasurementBit, v); } - void SetNeedUpdateFromTrack(Bool_t v = kTRUE) { SetBit(kUpdateFromTrackBit, v); } - void SetUseBzOnly(Bool_t v = kTRUE) { SetBit(kUseBzOnly, v); } - void SetInvDir(Bool_t v = kTRUE) { SetBit(kInvDir, v); } - void SetStatOK(Bool_t v = kTRUE) { SetBit(kStatOK, v); } + void SetMinLocVarID(int id) { fMinLocVarID = id; } + void SetMaxLocVarID(int id) { fMaxLocVarID = id; } + void SetELossVaried(bool v = true) { SetBit(kVaryELossBit, v); } + void SetContainsMaterial(bool v = true) { SetBit(kMaterialBit, v); } + void SetContainsMeasurement(bool v = true) { SetBit(kMeasurementBit, v); } + void SetNeedUpdateFromTrack(bool v = true) { SetBit(kUpdateFromTrackBit, v); } + void SetUseBzOnly(bool v = true) { SetBit(kUseBzOnly, v); } + void SetInvDir(bool v = true) { SetBit(kInvDir, v); } + void SetStatOK(bool v = true) { SetBit(kStatOK, v); } // void GetResidualsDiag(const double* pos, double& resU, double& resV) const; void DiagonalizeResiduals(double rY, double rZ, double& resU, double& resV) const; @@ -128,12 +128,12 @@ class AliAlgPoint : public TObject for (int i = 3; i--;) fErrYZTracking[i] = err[i]; } - Double_t GetErrDiag(int i) const { return fErrDiag[i]; } + double GetErrDiag(int i) const { return fErrDiag[i]; } // - Double_t* GetTrParamWSA() const { return (Double_t*)fTrParamWSA; } - Double_t* GetTrParamWSB() const { return (Double_t*)fTrParamWSB; } - Double_t GetTrParamWSA(int ip) const { return fTrParamWSA[ip]; } - Double_t GetTrParamWSB(int ip) const { return fTrParamWSB[ip]; } + double* GetTrParamWSA() const { return (double*)fTrParamWSA; } + double* GetTrParamWSB() const { return (double*)fTrParamWSB; } + double GetTrParamWSA(int ip) const { return fTrParamWSA[ip]; } + double GetTrParamWSB(int ip) const { return fTrParamWSB[ip]; } void GetTrWSA(trackParam_t& etp) const; void GetTrWSB(trackParam_t& etp) const; void SetTrParamWSA(const double* param) @@ -146,8 +146,8 @@ class AliAlgPoint : public TObject for (int i = 5; i--;) fTrParamWSB[i] = param[i]; } - Double_t GetResidY() const { return GetTrParamWSA(kParY) - GetYTracking(); } - Double_t GetResidZ() const { return GetTrParamWSA(kParZ) - GetZTracking(); } + double GetResidY() const { return GetTrParamWSA(kParY) - GetYTracking(); } + double GetResidZ() const { return GetTrParamWSA(kParZ) - GetZTracking(); } // void SetMatCovDiagonalizationMatrix(const TMatrixD& d); void SetMatCovDiag(const TVectorD& v); @@ -157,20 +157,20 @@ class AliAlgPoint : public TObject void UnDiagMatCorr(const float* diag, float* nodiag) const; void DiagMatCorr(const float* nodiag, float* diag) const; // - void SetMatCorrExp(Double_t* p) + void SetMatCorrExp(double* p) { for (int i = 5; i--;) fMatCorrExp[i] = p[i]; } - Float_t* GetMatCorrExp() const { return (float*)fMatCorrExp; } - Float_t* GetMatCorrCov() const { return (float*)fMatCorrCov; } + float* GetMatCorrExp() const { return (float*)fMatCorrExp; } + float* GetMatCorrCov() const { return (float*)fMatCorrCov; } // - void GetXYZGlo(Double_t r[3]) const; - Double_t GetPhiGlo() const; - Int_t GetAliceSector() const; + void GetXYZGlo(double r[3]) const; + double GetPhiGlo() const; + int GetAliceSector() const; // - Int_t GetNGloDOFs() const { return fNGloDOFs; } - Int_t GetDGloOffs() const { return fDGloOffs; } + int GetNGloDOFs() const { return fNGloDOFs; } + int GetDGloOffs() const { return fDGloOffs; } void SetNGloDOFs(int n) { fNGloDOFs = n; } void SetDGloOffs(int n) { fDGloOffs = n; } // @@ -181,8 +181,8 @@ class AliAlgPoint : public TObject virtual void Clear(Option_t* option = ""); // protected: - virtual Bool_t IsSortable() const { return kTRUE; } - virtual Int_t Compare(const TObject* a) const; + virtual bool IsSortable() const { return true; } + virtual int Compare(const TObject* a) const; // // ---------- dummies ---------- AliAlgPoint(const AliAlgPoint&); @@ -190,33 +190,33 @@ class AliAlgPoint : public TObject // protected: // - Int_t fMinLocVarID; // The residuals/derivatives depend on fNLocExtPar params - // and point params>=fMinLocVarID. - Int_t fMaxLocVarID; // The residuals/derivatives depend on fNLocExtPar params - // and point params=fMinLocVarID. + int fMaxLocVarID; // The residuals/derivatives depend on fNLocExtPar params + // and point params mn ? n : mn; @@ -183,63 +183,63 @@ class AliAlgSteer : public TObject void SetMinPointsColl(int vbOff = 3, int vbOn = 4); void SetMinPointsCosm(int vbOff = 3, int vbOn = 4); // - Double_t GetPtMin(Bool_t tp) const { return fPtMin[tp]; } - void SetPtMin(Bool_t tp, double pt) { fPtMin[tp] = pt; } + double GetPtMin(bool tp) const { return fPtMin[tp]; } + void SetPtMin(bool tp, double pt) { fPtMin[tp] = pt; } void SetPtMinColl(double pt = 0.7) { SetPtMin(AliAlgAux::kColl, pt); } void SetPtMinCosm(double pt = 1.0) { SetPtMin(AliAlgAux::kCosm, pt); } // - Double_t GetEtaMax(Bool_t tp) const { return fEtaMax[tp]; } - void SetEtaMax(Bool_t tp, double eta) { fEtaMax[tp] = eta; } + double GetEtaMax(bool tp) const { return fEtaMax[tp]; } + void SetEtaMax(bool tp, double eta) { fEtaMax[tp] = eta; } void SetEtaMaxColl(double eta = 1.5) { SetEtaMax(AliAlgAux::kColl, eta); } void SetEtaMaxCosm(double eta = 1.5) { SetEtaMax(AliAlgAux::kCosm, eta); } // void SetDefPtBOffCosm(double pt = 5.0) { fDefPtBOff[AliAlgAux::kCosm] = pt > 0.3 ? pt : 0.3; } void SetDefPtBOffColl(double pt = 0.6) { fDefPtBOff[AliAlgAux::kColl] = pt > 0.3 ? pt : 0.3; } - Double_t GetDefPtBOff(Bool_t tp) { return fDefPtBOff[tp]; } + double GetDefPtBOff(bool tp) { return fDefPtBOff[tp]; } // - Int_t GetMinDetAcc(Bool_t tp) const { return fMinDetAcc[tp]; } - void SetMinDetAcc(Bool_t tp, int n) { fMinDetAcc[tp] = n; } + int GetMinDetAcc(bool tp) const { return fMinDetAcc[tp]; } + void SetMinDetAcc(bool tp, int n) { fMinDetAcc[tp] = n; } void SetMinDetAccColl(int n = 1) { SetMinDetAcc(AliAlgAux::kColl, n); } void SetMinDetAccCosm(int n = 1) { SetMinDetAcc(AliAlgAux::kCosm, n); } // - Int_t GetVtxMinCont() const { return fVtxMinCont; } + int GetVtxMinCont() const { return fVtxMinCont; } void SetVtxMinCont(int n) { fVtxMinCont = n; } - Int_t GetVtxMaxCont() const { return fVtxMaxCont; } + int GetVtxMaxCont() const { return fVtxMaxCont; } void SetVtxMaxCont(int n) { fVtxMaxCont = n; } - Int_t GetVtxMinContVC() const { return fVtxMinContVC; } + int GetVtxMinContVC() const { return fVtxMinContVC; } void SetVtxMinContVC(int n) { fVtxMinContVC = n; } // - Int_t GetMinITSClforVC() const { return fMinITSClforVC; } + int GetMinITSClforVC() const { return fMinITSClforVC; } void SetMinITSClforVC(int n) { fMinITSClforVC = n; } - Int_t GetITSPattforVC() const { return fITSPattforVC; } + int GetITSPattforVC() const { return fITSPattforVC; } void SetITSPattforVC(int p) { fITSPattforVC = p; } - Double_t GetMaxDCARforVC() const { return fMaxDCAforVC[0]; } - Double_t GetMaxDCAZforVC() const { return fMaxDCAforVC[1]; } + double GetMaxDCARforVC() const { return fMaxDCAforVC[0]; } + double GetMaxDCAZforVC() const { return fMaxDCAforVC[1]; } void SetMaxDCAforVC(double dr = 0.1, double dz = 0.6) { fMaxDCAforVC[0] = dr; fMaxDCAforVC[1] = dz; } - Double_t GetMaxChi2forVC() const { return fMaxChi2forVC; } + double GetMaxChi2forVC() const { return fMaxChi2forVC; } void SetMaxChi2forVC(double chi2 = 10) { fMaxChi2forVC = chi2; } // - Bool_t CheckDetectorPattern(UInt_t patt) const; - Bool_t CheckDetectorPoints(const int* npsel) const; - void SetObligatoryDetector(Int_t detID, Int_t tp, Bool_t v = kTRUE); - void SetEventSpeciiSelection(UInt_t sel) { fSelEventSpecii = sel; } - UInt_t GetEventSpeciiSelection() const { return fSelEventSpecii; } + bool CheckDetectorPattern(uint32_t patt) const; + bool CheckDetectorPoints(const int* npsel) const; + void SetObligatoryDetector(int detID, int tp, bool v = true); + void SetEventSpeciiSelection(uint32_t sel) { fSelEventSpecii = sel; } + uint32_t GetEventSpeciiSelection() const { return fSelEventSpecii; } // // void SetVertex(const AliESDVertex* v) { fVertex = v; } FIXME(milettri): needs AliESDVertex // const AliESDVertex* GetVertex() const { return fVertex; } FIXME(milettri): needs AliESDVertex // //---------------------------------------- - Bool_t ReadParameters(const char* parfile = "millepede.res", Bool_t useErrors = kTRUE); - Float_t* GetGloParVal() const { return (Float_t*)fGloParVal; } - Float_t* GetGloParErr() const { return (Float_t*)fGloParErr; } - Int_t* GetGloParLab() const { return (Int_t*)fGloParLab; } - Int_t GetGloParLab(int i) const { return (Int_t)fGloParLab[i]; } - Int_t ParID2Label(int i) const { return GetGloParLab(i); } - Int_t Label2ParID(int lab) const; + bool ReadParameters(const char* parfile = "millepede.res", bool useErrors = true); + float* GetGloParVal() const { return (float*)fGloParVal; } + float* GetGloParErr() const { return (float*)fGloParErr; } + int* GetGloParLab() const { return (int*)fGloParLab; } + int GetGloParLab(int i) const { return (int)fGloParLab[i]; } + int ParID2Label(int i) const { return GetGloParLab(i); } + int Label2ParID(int lab) const; AliAlgVol* GetVolOfDOFID(int id) const; AliAlgDet* GetDetOfDOFID(int id) const; // @@ -249,21 +249,21 @@ class AliAlgSteer : public TObject AliAlgMPRecord* GetMPRecord() const { return (AliAlgMPRecord*)fMPRecord; } TTree* GetMPRecTree() const { return fMPRecTree; } AliAlgTrack* GetAlgTrack() const { return (AliAlgTrack*)fAlgTrack; } - // Bool_t ProcessEvent(const AliESDEvent* esdEv); FIXME(milettri): needs AliESDEvent - // Bool_t ProcessTrack(const AliESDtrack* esdTr); FIXME(milettri): needs AliESDtrack - // Bool_t ProcessTrack(const AliESDCosmicTrack* esdCTr); FIXME(milettri): needs AliESDCosmicTrack - // UInt_t AcceptTrack(const AliESDtrack* esdTr, Bool_t strict = kTRUE) const; FIXME(milettri): needs AliESDtrack - // UInt_t AcceptTrackCosmic(const AliESDtrack* esdPairCosm[kNCosmLegs]) const; FIXME(milettri): needs AliESDtrack - // Bool_t CheckSetVertex(const AliESDVertex* vtx); FIXME(milettri): needs AliESDVertex - Bool_t AddVertexConstraint(); - Int_t GetNDetectors() const { return fNDet; } - AliAlgDet* GetDetector(Int_t i) const { return fDetectors[i]; } - AliAlgDet* GetDetectorByDetID(Int_t i) const { return fDetPos[i] < 0 ? 0 : fDetectors[fDetPos[i]]; } - AliAlgDet* GetDetectorByVolID(Int_t id) const; + // bool ProcessEvent(const AliESDEvent* esdEv); FIXME(milettri): needs AliESDEvent + // bool ProcessTrack(const AliESDtrack* esdTr); FIXME(milettri): needs AliESDtrack + // bool ProcessTrack(const AliESDCosmicTrack* esdCTr); FIXME(milettri): needs AliESDCosmicTrack + // uint32_t AcceptTrack(const AliESDtrack* esdTr, bool strict = true) const; FIXME(milettri): needs AliESDtrack + // uint32_t AcceptTrackCosmic(const AliESDtrack* esdPairCosm[kNCosmLegs]) const; FIXME(milettri): needs AliESDtrack + // bool CheckSetVertex(const AliESDVertex* vtx); FIXME(milettri): needs AliESDVertex + bool AddVertexConstraint(); + int GetNDetectors() const { return fNDet; } + AliAlgDet* GetDetector(int i) const { return fDetectors[i]; } + AliAlgDet* GetDetectorByDetID(int i) const { return fDetPos[i] < 0 ? 0 : fDetectors[fDetPos[i]]; } + AliAlgDet* GetDetectorByVolID(int id) const; AliAlgVtx* GetVertexSensor() const { return fVtxSens; } // void ResetDetectors(); - Int_t GetNDOFs() const { return fNDOFs; } + int GetNDOFs() const { return fNDOFs; } // const char* GetConfMacroName() const { return fConfMacroName.Data(); } //---------------------------------------- @@ -277,10 +277,10 @@ class AliAlgSteer : public TObject void SetOutCDBComment(const char* cm = 0) { fOutCDBComment = cm; } void SetOutCDBResponsible(const char* v = 0) { fOutCDBResponsible = v; } // void SetOutCDBRunRange(int rmin = 0, int rmax = 999999999); FIXME(milettri): needs OCDB - Int_t* GetOutCDBRunRange() const { return (int*)fOutCDBRunRange; } - Int_t GetOutCDBRunMin() const { return fOutCDBRunRange[0]; } - Int_t GetOutCDBRunMax() const { return fOutCDBRunRange[1]; } - Float_t GetControlFrac() const { return fControlFrac; } + int* GetOutCDBRunRange() const { return (int*)fOutCDBRunRange; } + int GetOutCDBRunMin() const { return fOutCDBRunRange[0]; } + int GetOutCDBRunMax() const { return fOutCDBRunRange[1]; } + float GetControlFrac() const { return fControlFrac; } void SetControlFrac(float v = 1.) { fControlFrac = v; } // void WriteCalibrationResults() const; FIXME(milettri): needs OCDB void ApplyAlignmentFromMPSol(); @@ -293,47 +293,47 @@ class AliAlgSteer : public TObject const char* GetMPConFileName() const { return fMPConFileName.Data(); } const char* GetMPSteerFileName() const { return fMPSteerFileName.Data(); } // - Bool_t FillMPRecData(); - Bool_t FillMilleData(); - Bool_t FillControlData(); - void SetDoKalmanResid(Bool_t v = kTRUE) { fDoKalmanResid = v; } - void SetMPOutType(Int_t t) { fMPOutType = t; } - void ProduceMPData(Bool_t v = kTRUE) + bool FillMPRecData(); + bool FillMilleData(); + bool FillControlData(); + void SetDoKalmanResid(bool v = true) { fDoKalmanResid = v; } + void SetMPOutType(int t) { fMPOutType = t; } + void ProduceMPData(bool v = true) { if (v) fMPOutType |= kMille; else fMPOutType &= ~kMille; } - void ProduceMPRecord(Bool_t v = kTRUE) + void ProduceMPRecord(bool v = true) { if (v) fMPOutType |= kMPRec; else fMPOutType &= ~kMPRec; } - void ProduceControlRes(Bool_t v = kTRUE) + void ProduceControlRes(bool v = true) { if (v) fMPOutType |= kContR; else fMPOutType &= ~kContR; } - Int_t GetMPOutType() const { return fMPOutType; } - Bool_t GetDoKalmanResid() const { return fDoKalmanResid; } - Bool_t GetProduceMPData() const { return fMPOutType & kMille; } - Bool_t GetProduceMPRecord() const { return fMPOutType & kMPRec; } - Bool_t GetProduceControlRes() const { return fMPOutType & kContR; } + int GetMPOutType() const { return fMPOutType; } + bool GetDoKalmanResid() const { return fDoKalmanResid; } + bool GetProduceMPData() const { return fMPOutType & kMille; } + bool GetProduceMPRecord() const { return fMPOutType & kMPRec; } + bool GetProduceControlRes() const { return fMPOutType & kContR; } void CloseMPRecOutput(); void CloseMilleOutput(); void CloseResidOutput(); void InitMPRecOutput(); void InitMIlleOutput(); void InitResidOutput(); - Bool_t StoreProcessedTrack(Int_t what); + bool StoreProcessedTrack(int what); void PrintStatistics() const; - Bool_t GetMilleTXT() const { return !fMilleOutBin; } - void SetMilleTXT(Bool_t v = kTRUE) { fMilleOutBin = !v; } + bool GetMilleTXT() const { return !fMilleOutBin; } + void SetMilleTXT(bool v = true) { fMilleOutBin = !v; } // void GenPedeSteerFile(const Option_t* opt = "") const; void WritePedeConstraints() const; @@ -346,34 +346,34 @@ class AliAlgSteer : public TObject void SetHistoStat(TH1F* h) { fHistoStat = h; } void FillStatHisto(int type, float w = 1); void CreateStatHisto(); - void FixLowStatFromDOFStat(Int_t thresh = 40); + void FixLowStatFromDOFStat(int thresh = 40); void LoadStat(const char* flname); // //---------------------------------------- // - Int_t GetRefRunNumber() const { return fRefRunNumber; } + int GetRefRunNumber() const { return fRefRunNumber; } void SetRefRunNumber(int r = -1) { fRefRunNumber = r; } // void SetRefOCDBConfigMacro(const char* nm = "configRefOCDB.C") { fRefOCDBConf = nm; } const char* GetRefOCDBConfigMacro() const { return fRefOCDBConf.Data(); } void SetRecoOCDBConfigMacro(const char* nm = "configRecoOCDB.C") { fRecoOCDBConf = nm; } const char* GetRecoOCDBConfigMacro() const { return fRecoOCDBConf.Data(); } - Int_t GetRefOCDBLoaded() const { return fRefOCDBLoaded; } + int GetRefOCDBLoaded() const { return fRefOCDBLoaded; } // virtual void Print(const Option_t* opt = "") const; void PrintLabels() const; - Char_t* GetDOFLabelTxt(int idf) const; + char* GetDOFLabelTxt(int idf) const; // - static Char_t* GetDetNameByDetID(Int_t id) { return (Char_t*)fgkDetectorName[id]; } - static void MPRec2Mille(const char* mprecfile, const char* millefile = "mpData.mille", Bool_t bindata = kTRUE); - static void MPRec2Mille(TTree* mprTree, const char* millefile = "mpData.mille", Bool_t bindata = kTRUE); + static char* GetDetNameByDetID(int id) { return (char*)fgkDetectorName[id]; } + static void MPRec2Mille(const char* mprecfile, const char* millefile = "mpData.mille", bool bindata = true); + static void MPRec2Mille(TTree* mprTree, const char* millefile = "mpData.mille", bool bindata = true); // // AliSymMatrix* BuildMatrix(TVectorD& vec); FIXME(milettri): needs AliSymMatrix - Bool_t TestLocalSolution(); + bool TestLocalSolution(); // // fast check of solution using derivatives - void CheckSol(TTree* mpRecTree, Bool_t store = kTRUE, Bool_t verbose = kFALSE, Bool_t loc = kTRUE, const char* outName = "resFast"); - Bool_t CheckSol(AliAlgMPRecord* rec, AliAlgResFast* rLG = 0, AliAlgResFast* rL = 0, Bool_t verbose = kTRUE, Bool_t loc = kTRUE); + void CheckSol(TTree* mpRecTree, bool store = true, bool verbose = false, bool loc = true, const char* outName = "resFast"); + bool CheckSol(AliAlgMPRecord* rec, AliAlgResFast* rLG = 0, AliAlgResFast* rL = 0, bool verbose = true, bool loc = true); // protected: // @@ -383,41 +383,41 @@ class AliAlgSteer : public TObject // protected: // - Int_t fNDet; // number of deectors participating in the alignment - Int_t fNDOFs; // number of degrees of freedom - Int_t fRunNumber; // current run number - Bool_t fFieldOn; // field on flag - Int_t fTracksType; // collision/cosmic event type + int fNDet; // number of deectors participating in the alignment + int fNDOFs; // number of degrees of freedom + int fRunNumber; // current run number + bool fFieldOn; // field on flag + int fTracksType; // collision/cosmic event type AliAlgTrack* fAlgTrack; // current alignment track AliAlgDet* fDetectors[kNDetectors]; // detectors participating in the alignment - Int_t fDetPos[kNDetectors]; // entry of detector in the fDetectors array + int fDetPos[kNDetectors]; // entry of detector in the fDetectors array AliAlgVtx* fVtxSens; // fake sensor for the vertex TObjArray fConstraints; // array of constraints // // Track selection - UInt_t fSelEventSpecii; // consider only these event specii - UInt_t fObligatoryDetPattern[AliAlgAux::kNTrackTypes]; // pattern of obligatory detectors - Bool_t fCosmicSelStrict; // if true, each cosmic track leg selected like separate track - Int_t fMinPoints[AliAlgAux::kNTrackTypes][2]; // require min points per leg (case Boff,Bon) - Int_t fMinDetAcc[AliAlgAux::kNTrackTypes]; // min number of detector required in track - Double_t fDefPtBOff[AliAlgAux::kNTrackTypes]; // nominal pt for tracks in Boff run - Double_t fPtMin[AliAlgAux::kNTrackTypes]; // min pT of tracks to consider - Double_t fEtaMax[AliAlgAux::kNTrackTypes]; // eta cut on tracks - Int_t fVtxMinCont; // require min number of contributors in Vtx - Int_t fVtxMaxCont; // require max number of contributors in Vtx - Int_t fVtxMinContVC; // min number of contributors to use as constraint - // - Int_t fMinITSClforVC; // use vertex constraint for tracks with enough points - Int_t fITSPattforVC; // optional request on ITS hits to allow vertex constraint - Double_t fMaxDCAforVC[2]; // DCA cut in R,Z to allow vertex constraint - Double_t fMaxChi2forVC; // track-vertex chi2 cut to allow vertex constraint - // - // - Float_t* fGloParVal; //[fNDOFs] parameters for DOFs - Float_t* fGloParErr; //[fNDOFs] errors for DOFs - Int_t* fGloParLab; //[fNDOFs] labels for DOFs - Int_t* fOrderedLbl; //[fNDOFs] ordered labels - Int_t* fLbl2ID; //[fNDOFs] Label order in fOrderedLbl -> parID + uint32_t fSelEventSpecii; // consider only these event specii + uint32_t fObligatoryDetPattern[AliAlgAux::kNTrackTypes]; // pattern of obligatory detectors + bool fCosmicSelStrict; // if true, each cosmic track leg selected like separate track + int fMinPoints[AliAlgAux::kNTrackTypes][2]; // require min points per leg (case Boff,Bon) + int fMinDetAcc[AliAlgAux::kNTrackTypes]; // min number of detector required in track + double fDefPtBOff[AliAlgAux::kNTrackTypes]; // nominal pt for tracks in Boff run + double fPtMin[AliAlgAux::kNTrackTypes]; // min pT of tracks to consider + double fEtaMax[AliAlgAux::kNTrackTypes]; // eta cut on tracks + int fVtxMinCont; // require min number of contributors in Vtx + int fVtxMaxCont; // require max number of contributors in Vtx + int fVtxMinContVC; // min number of contributors to use as constraint + // + int fMinITSClforVC; // use vertex constraint for tracks with enough points + int fITSPattforVC; // optional request on ITS hits to allow vertex constraint + double fMaxDCAforVC[2]; // DCA cut in R,Z to allow vertex constraint + double fMaxChi2forVC; // track-vertex chi2 cut to allow vertex constraint + // + // + float* fGloParVal; //[fNDOFs] parameters for DOFs + float* fGloParErr; //[fNDOFs] errors for DOFs + int* fGloParLab; //[fNDOFs] labels for DOFs + int* fOrderedLbl; //[fNDOFs] ordered labels + int* fLbl2ID; //[fNDOFs] Label order in fOrderedLbl -> parID // AliAlgPoint* fRefPoint; // reference point for track definition // @@ -427,13 +427,13 @@ class AliAlgSteer : public TObject // const AliESDVertex* fVertex; //! event vertex FIXME(milettri): needs AliESDVertex // // statistics - Float_t fStat[kNStatCl][kMaxStat]; // processing statistics - static const Char_t* fgkStatClName[kNStatCl]; // stat classes names - static const Char_t* fgkStatName[kMaxStat]; // stat type names + float fStat[kNStatCl][kMaxStat]; // processing statistics + static const char* fgkStatClName[kNStatCl]; // stat classes names + static const char* fgkStatName[kMaxStat]; // stat type names // // output related - Float_t fControlFrac; // fraction of tracks to process control residuals - Int_t fMPOutType; // What to store as an output, see StoreProcessedTrack + float fControlFrac; // fraction of tracks to process control residuals + int fMPOutType; // What to store as an output, see StoreProcessedTrack Mille* fMille; //! Mille interface AliAlgMPRecord* fMPRecord; //! MP record AliAlgRes* fCResid; //! control residuals @@ -448,13 +448,13 @@ class AliAlgSteer : public TObject TString fMPConFileName; // file name for MP constraints TString fMPSteerFileName; // file name for MP steering TString fResidFileName; // file name for optional control residuals - Bool_t fMilleOutBin; // optionally text output for Mille debugging - Bool_t fDoKalmanResid; // calculate residuals with smoothed kalman in the ControlRes + bool fMilleOutBin; // optionally text output for Mille debugging + bool fDoKalmanResid; // calculate residuals with smoothed kalman in the ControlRes // TString fOutCDBPath; // output OCDB path TString fOutCDBComment; // optional comment to add to output cdb objects TString fOutCDBResponsible; // optional responsible for output metadata - Int_t fOutCDBRunRange[2]; // run range for output storage + int fOutCDBRunRange[2]; // run range for output storage // AliAlgDOFStat* fDOFStat; // stat of entries per dof TH1F* fHistoStat; // histo with general statistics @@ -463,14 +463,14 @@ class AliAlgSteer : public TObject TString fConfMacroName; // optional configuration macro TString fRecoOCDBConf; // optional macro name for reco-time OCDB setup: void fun(int run) TString fRefOCDBConf; // optional macro name for prealignment OCDB setup: void fun() - Int_t fRefRunNumber; // optional run number used for reference - Int_t fRefOCDBLoaded; // flag/counter for ref.OCDB loading - Bool_t fUseRecoOCDB; // flag to preload reco-time calib objects + int fRefRunNumber; // optional run number used for reference + int fRefOCDBLoaded; // flag/counter for ref.OCDB loading + bool fUseRecoOCDB; // flag to preload reco-time calib objects // - static const Int_t fgkSkipLayers[kNLrSkip]; // detector layers for which we don't need module matrices - static const Char_t* fgkDetectorName[kNDetectors]; // names of detectors - static const Char_t* fgkHStatName[kNHVars]; // names for stat.bins in the stat histo - static const Char_t* fgkMPDataExt; // extension for MP2 binary data + static const int fgkSkipLayers[kNLrSkip]; // detector layers for which we don't need module matrices + static const char* fgkDetectorName[kNDetectors]; // names of detectors + static const char* fgkHStatName[kNHVars]; // names for stat.bins in the stat histo + static const char* fgkMPDataExt; // extension for MP2 binary data // ClassDef(AliAlgSteer, 2) }; @@ -479,16 +479,16 @@ class AliAlgSteer : public TObject inline void AliAlgSteer::SetMinPointsColl(int vbOff, int vbOn) { // ask min number of points per track - SetMinPoints(AliAlgAux::kColl, kFALSE, vbOff); - SetMinPoints(AliAlgAux::kColl, kTRUE, vbOn); + SetMinPoints(AliAlgAux::kColl, false, vbOff); + SetMinPoints(AliAlgAux::kColl, true, vbOn); } //__________________________________________________________ inline void AliAlgSteer::SetMinPointsCosm(int vbOff, int vbOn) { // ask min number of points per track - SetMinPoints(AliAlgAux::kCosm, kFALSE, vbOff); - SetMinPoints(AliAlgAux::kCosm, kTRUE, vbOn); + SetMinPoints(AliAlgAux::kCosm, false, vbOff); + SetMinPoints(AliAlgAux::kCosm, true, vbOn); } } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgTrack.h b/Detectors/Align/include/Align/AliAlgTrack.h index 20083c2726813..db1d09a3f2767 100644 --- a/Detectors/Align/include/Align/AliAlgTrack.h +++ b/Detectors/Align/include/Align/AliAlgTrack.h @@ -64,68 +64,68 @@ class AliAlgTrack : public trackParam_t, public TObject AliAlgTrack(); virtual ~AliAlgTrack(); void DefineDOFs(); - Double_t GetMass() const { return fMass; } - Double_t GetMinX2X0Pt2Account() const { return fMinX2X0Pt2Account; } - Int_t GetNPoints() const { return fPoints.GetEntriesFast(); } + double GetMass() const { return fMass; } + double GetMinX2X0Pt2Account() const { return fMinX2X0Pt2Account; } + int GetNPoints() const { return fPoints.GetEntriesFast(); } AliAlgPoint* GetPoint(int i) const { return (AliAlgPoint*)fPoints[i]; } void AddPoint(AliAlgPoint* p) { fPoints.AddLast(p); } void SetMass(double m) { fMass = m; } void SetMinX2X0Pt2Account(double v) { fMinX2X0Pt2Account = v; } - Int_t GetNLocPar() const { return fNLocPar; } - Int_t GetNLocExtPar() const { return fNLocExtPar; } - Int_t GetInnerPointID() const { return fInnerPointID; } + int GetNLocPar() const { return fNLocPar; } + int GetNLocExtPar() const { return fNLocExtPar; } + int GetInnerPointID() const { return fInnerPointID; } AliAlgPoint* GetInnerPoint() const { return GetPoint(fInnerPointID); } // virtual void Clear(Option_t* opt = ""); virtual void Print(Option_t* opt = "") const; virtual void DumpCoordinates() const; // - Bool_t PropagateToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT, track::TrackLTIntegral* tLT = nullptr); - Bool_t PropagateParamToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep = 3, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT); // param only - Bool_t PropagateParamToPoint(trackParam_t* trSet, int nTr, const AliAlgPoint* pnt, double maxStep = 3, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT); // params only + bool PropagateToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT, track::TrackLTIntegral* tLT = nullptr); + bool PropagateParamToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep = 3, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT); // param only + bool PropagateParamToPoint(trackParam_t* trSet, int nTr, const AliAlgPoint* pnt, double maxStep = 3, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT); // params only // - Bool_t CalcResiduals(const double* params = 0); - Bool_t CalcResidDeriv(double* params = 0); - Bool_t CalcResidDerivGlo(AliAlgPoint* pnt); + bool CalcResiduals(const double* params = 0); + bool CalcResidDeriv(double* params = 0); + bool CalcResidDerivGlo(AliAlgPoint* pnt); // - Bool_t IsCosmic() const { return TestBit(kCosmicBit); } - void SetCosmic(Bool_t v = kTRUE) { SetBit(kCosmicBit, v); } - Bool_t GetFieldON() const { return TestBit(kFieldONBit); } - void SetFieldON(Bool_t v = kTRUE) { SetBit(kFieldONBit, v); } - Bool_t GetResidDone() const { return TestBit(kResidDoneBit); } - void SetResidDone(Bool_t v = kTRUE) { SetBit(kResidDoneBit, v); } - Bool_t GetDerivDone() const { return TestBit(kDerivDoneBit); } - void SetDerivDone(Bool_t v = kTRUE) { SetBit(kDerivDoneBit, v); } - Bool_t GetKalmanDone() const { return TestBit(kKalmanDoneBit); } - void SetKalmanDone(Bool_t v = kTRUE) { SetBit(kKalmanDoneBit, v); } + bool IsCosmic() const { return TestBit(kCosmicBit); } + void SetCosmic(bool v = true) { SetBit(kCosmicBit, v); } + bool GetFieldON() const { return TestBit(kFieldONBit); } + void SetFieldON(bool v = true) { SetBit(kFieldONBit, v); } + bool GetResidDone() const { return TestBit(kResidDoneBit); } + void SetResidDone(bool v = true) { SetBit(kResidDoneBit, v); } + bool GetDerivDone() const { return TestBit(kDerivDoneBit); } + void SetDerivDone(bool v = true) { SetBit(kDerivDoneBit, v); } + bool GetKalmanDone() const { return TestBit(kKalmanDoneBit); } + void SetKalmanDone(bool v = true) { SetBit(kKalmanDoneBit, v); } // void SortPoints(); - Bool_t IniFit(); - Bool_t ResidKalman(); - Bool_t ProcessMaterials(); - Bool_t CombineTracks(trackParam_t& trcL, const trackParam_t& trcU); + bool IniFit(); + bool ResidKalman(); + bool ProcessMaterials(); + bool CombineTracks(trackParam_t& trcL, const trackParam_t& trcU); // void SetChi2(double c) { fChi2 = c; }; - Double_t GetChi2() const { return fChi2; } + double GetChi2() const { return fChi2; } void SetChi2Ini(double c) { fChi2Ini = c; }; - Double_t GetChi2Ini() const { return fChi2Ini; } - Double_t GetChi2CosmUp() const { return fChi2CosmUp; } - Double_t GetChi2CosmDn() const { return fChi2CosmDn; } + double GetChi2Ini() const { return fChi2Ini; } + double GetChi2CosmUp() const { return fChi2CosmUp; } + double GetChi2CosmDn() const { return fChi2CosmDn; } // void ImposePtBOff(double pt) { setQ2Pt(1. / pt); } // propagation methods void CopyFrom(const trackParam_t* etp); - Bool_t ApplyMatCorr(trackParam_t& trPar, const Double_t* corrDiag, const AliAlgPoint* pnt); - Bool_t ApplyMatCorr(trackParam_t* trSet, int ntr, const Double_t* corrDiaf, const AliAlgPoint* pnt); - Bool_t ApplyMatCorr(trackParam_t& trPar, const Double_t* corrpar); + bool ApplyMatCorr(trackParam_t& trPar, const double* corrDiag, const AliAlgPoint* pnt); + bool ApplyMatCorr(trackParam_t* trSet, int ntr, const double* corrDiaf, const AliAlgPoint* pnt); + bool ApplyMatCorr(trackParam_t& trPar, const double* corrpar); // - Double_t GetResidual(int dim, int pntID) const { return fResidA[dim][pntID]; } - Double_t* GetDResDLoc(int dim, int pntID) const { return &fDResDLocA[dim][pntID * fNLocPar]; } - Double_t* GetDResDGlo(int dim, int id) const { return &fDResDGloA[dim][id]; } - Int_t* GetGloParID() const { return fGloParIDA; } + double GetResidual(int dim, int pntID) const { return fResidA[dim][pntID]; } + double* GetDResDLoc(int dim, int pntID) const { return &fDResDLocA[dim][pntID * fNLocPar]; } + double* GetDResDGlo(int dim, int id) const { return &fDResDGloA[dim][id]; } + int* GetGloParID() const { return fGloParIDA; } // - void SetParams(trackParam_t& tr, double x, double alp, const double* par, Bool_t add); - void SetParams(trackParam_t* trSet, int ntr, double x, double alp, const double* par, Bool_t add); + void SetParams(trackParam_t& tr, double x, double alp, const double* par, bool add); + void SetParams(trackParam_t* trSet, int ntr, double x, double alp, const double* par, bool add); void SetParam(trackParam_t& tr, int par, double val); void SetParam(trackParam_t* trSet, int ntr, int par, double val); void ModParam(trackParam_t& tr, int par, double delta); @@ -134,57 +134,57 @@ class AliAlgTrack : public trackParam_t, public TObject void RichardsonDeriv(const trackParam_t* trSet, const double* delta, const AliAlgPoint* pnt, double& derY, double& derZ); // - const Double_t* GetLocPars() const { return fLocParA; } + const double* GetLocPars() const { return fLocParA; } void SetLocPars(const double* pars); // protected: // - Bool_t CalcResidDeriv(double* params, Bool_t invert, int pFrom, int pTo); - Bool_t CalcResiduals(const double* params, Bool_t invert, int pFrom, int pTo); - Bool_t FitLeg(trackParam_t& trc, int pFrom, int pTo, Bool_t& inv); - Bool_t ProcessMaterials(trackParam_t& trc, int pFrom, int pTo); + bool CalcResidDeriv(double* params, bool invert, int pFrom, int pTo); + bool CalcResiduals(const double* params, bool invert, int pFrom, int pTo); + bool FitLeg(trackParam_t& trc, int pFrom, int pTo, bool& inv); + bool ProcessMaterials(trackParam_t& trc, int pFrom, int pTo); // void CheckExpandDerGloBuffer(int minSize); // - static Double_t RichardsonExtrap(double* val, int ord = 1); - static Double_t RichardsonExtrap(const double* val, int ord = 1); + static double RichardsonExtrap(double* val, int ord = 1); + static double RichardsonExtrap(const double* val, int ord = 1); // // ---------- dummies ---------- AliAlgTrack(const AliAlgTrack&); AliAlgTrack& operator=(const AliAlgTrack&); // protected: - Int_t fNLocPar; // number of local params - Int_t fNLocExtPar; // number of local params for the external track param - Int_t fNGloPar; // number of free global parameters the track depends on - Int_t fNDF; // number of degrees of freedom - Int_t fInnerPointID; // ID of inner point in sorted track. For 2-leg cosmics - innermost point of lower leg - Bool_t fNeedInv[2]; // set if one of cosmic legs need inversion - Double_t fMinX2X0Pt2Account; // minimum X2X0/pT accumulated between 2 points worth to account - Double_t fMass; // assumed mass - Double_t fChi2; // chi2 with current residuals - Double_t fChi2CosmUp; // chi2 for cosmic upper leg - Double_t fChi2CosmDn; // chi2 for cosmic down leg - Double_t fChi2Ini; // chi2 with current residuals - TObjArray fPoints; // alignment points - TArrayD fResid[2]; // residuals array - TArrayD fDResDLoc[2]; // array for derivatives over local params - TArrayD fDResDGlo[2]; // array for derivatives over global params - TArrayD fLocPar; // local parameters array - TArrayI fGloParID; // IDs of relevant global params - Double_t* fResidA[2]; //! fast access to residuals - Double_t* fDResDLocA[2]; //! fast access to local derivatives - Double_t* fDResDGloA[2]; //! fast access to global derivatives - Int_t* fGloParIDA; //! fast access to relevant global param IDs - Double_t* fLocParA; //! fast access to local params + int fNLocPar; // number of local params + int fNLocExtPar; // number of local params for the external track param + int fNGloPar; // number of free global parameters the track depends on + int fNDF; // number of degrees of freedom + int fInnerPointID; // ID of inner point in sorted track. For 2-leg cosmics - innermost point of lower leg + bool fNeedInv[2]; // set if one of cosmic legs need inversion + double fMinX2X0Pt2Account; // minimum X2X0/pT accumulated between 2 points worth to account + double fMass; // assumed mass + double fChi2; // chi2 with current residuals + double fChi2CosmUp; // chi2 for cosmic upper leg + double fChi2CosmDn; // chi2 for cosmic down leg + double fChi2Ini; // chi2 with current residuals + TObjArray fPoints; // alignment points + TArrayD fResid[2]; // residuals array + TArrayD fDResDLoc[2]; // array for derivatives over local params + TArrayD fDResDGlo[2]; // array for derivatives over global params + TArrayD fLocPar; // local parameters array + TArrayI fGloParID; // IDs of relevant global params + double* fResidA[2]; //! fast access to residuals + double* fDResDLocA[2]; //! fast access to local derivatives + double* fDResDGloA[2]; //! fast access to global derivatives + int* fGloParIDA; //! fast access to relevant global param IDs + double* fLocParA; //! fast access to local params private: - Bool_t Propagate(trackParam_t& tr, const AliAlgPoint* pnt, Double_t maxStep, Double_t maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT); + bool Propagate(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT); // ClassDef(AliAlgTrack, 2) }; //____________________________________________________________________________________________ -inline void AliAlgTrack::SetParams(trackParam_t& tr, double x, double alp, const double* par, Bool_t add) +inline void AliAlgTrack::SetParams(trackParam_t& tr, double x, double alp, const double* par, bool add) { // set track params const double kDefQ2PtCosm = 1; @@ -211,19 +211,19 @@ inline void AliAlgTrack::SetParams(trackParam_t& tr, double x, double alp, const } //____________________________________________________________________________________________ -inline void AliAlgTrack::SetParams(trackParam_t* trSet, int ntr, double x, double alp, const double* par, Bool_t add) +inline void AliAlgTrack::SetParams(trackParam_t* trSet, int ntr, double x, double alp, const double* par, bool add) { // set parames for multiple tracks (VECTORIZE THIS) if (!add) { // full parameter supplied for (int itr = ntr; itr--;) - SetParams(trSet[itr], x, alp, par, kFALSE); + SetParams(trSet[itr], x, alp, par, false); return; } params_t partr{0}; // par is a correction to reference parameter for (int i = fNLocExtPar; i--;) partr[i] = getParam(i) + par[i]; for (int itr = ntr; itr--;) - SetParams(trSet[itr], x, alp, partr.data(), kFALSE); + SetParams(trSet[itr], x, alp, partr.data(), false); } //____________________________________________________________________________________________ diff --git a/Detectors/Align/include/Align/AliAlgVol.h b/Detectors/Align/include/Align/AliAlgVol.h index 616921e2774a8..75f67bea3a861 100644 --- a/Detectors/Align/include/Align/AliAlgVol.h +++ b/Detectors/Align/include/Align/AliAlgVol.h @@ -69,47 +69,47 @@ class AliAlgVol : public TNamed // const char* GetSymName() const { return GetName(); } // - Int_t GetVolID() const { return (Int_t)GetUniqueID(); } - void SetVolID(Int_t v) { SetUniqueID(v); } - Int_t GetInternalID() const { return fIntID; } - void SetInternalID(Int_t v) { fIntID = v; } + int GetVolID() const { return (int)GetUniqueID(); } + void SetVolID(int v) { SetUniqueID(v); } + int GetInternalID() const { return fIntID; } + void SetInternalID(int v) { fIntID = v; } // // - void AssignDOFs(Int_t& cntDOFs, Float_t* pars, Float_t* errs, Int_t* labs); + void AssignDOFs(int& cntDOFs, float* pars, float* errs, int* labs); void InitDOFs(); // Frame_t GetVarFrame() const { return fVarFrame; } void SetVarFrame(Frame_t f) { fVarFrame = f; } - Bool_t IsFrameTRA() const { return fVarFrame == kTRA; } - Bool_t IsFrameLOC() const { return fVarFrame == kLOC; } + bool IsFrameTRA() const { return fVarFrame == kTRA; } + bool IsFrameLOC() const { return fVarFrame == kLOC; } // - void SetFreeDOF(Int_t dof) + void SetFreeDOF(int dof) { fDOF |= 0x1 << dof; CalcFree(); } - void FixDOF(Int_t dof) + void FixDOF(int dof) { fDOF &= ~(0x1 << dof); CalcFree(); } - void SetFreeDOFPattern(UInt_t pat) + void SetFreeDOFPattern(uint32_t pat) { fDOF = pat; CalcFree(); } - Bool_t IsFreeDOF(Int_t dof) const { return (fDOF & (0x1 << dof)) != 0; } - Bool_t IsCondDOF(Int_t dof) const; - UInt_t GetFreeDOFPattern() const { return fDOF; } - UInt_t GetFreeDOFGeomPattern() const { return fDOF & kAllGeomDOF; } + bool IsFreeDOF(int dof) const { return (fDOF & (0x1 << dof)) != 0; } + bool IsCondDOF(int dof) const; + uint32_t GetFreeDOFPattern() const { return fDOF; } + uint32_t GetFreeDOFGeomPattern() const { return fDOF & kAllGeomDOF; } // void AddAutoConstraints(TObjArray* constrArr); - Bool_t IsChildrenDOFConstrained(Int_t dof) const { return fConstrChild & 0x1 << dof; } - UChar_t GetChildrenConstraintPattern() const { return fConstrChild; } - void ConstrainChildrenDOF(Int_t dof) { fConstrChild |= 0x1 << dof; } - void UConstrainChildrenDOF(Int_t dof) { fConstrChild &= ~(0x1 << dof); } - void SetChildrenConstrainPattern(UInt_t pat) { fConstrChild = pat; } - Bool_t HasChildrenConstraint() const { return fConstrChild; } + bool IsChildrenDOFConstrained(int dof) const { return fConstrChild & 0x1 << dof; } + uint8_t GetChildrenConstraintPattern() const { return fConstrChild; } + void ConstrainChildrenDOF(int dof) { fConstrChild |= 0x1 << dof; } + void UConstrainChildrenDOF(int dof) { fConstrChild &= ~(0x1 << dof); } + void SetChildrenConstrainPattern(uint32_t pat) { fConstrChild = pat; } + bool HasChildrenConstraint() const { return fConstrChild; } // AliAlgVol* GetParent() const { return fParent; } void SetParent(AliAlgVol* par) @@ -118,39 +118,39 @@ class AliAlgVol : public TNamed if (par) par->AddChild(this); } - Int_t CountParents() const; + int CountParents() const; // - Int_t GetNChildren() const { return fChildren ? fChildren->GetEntriesFast() : 0; } + int GetNChildren() const { return fChildren ? fChildren->GetEntriesFast() : 0; } AliAlgVol* GetChild(int i) const { return fChildren ? (AliAlgVol*)fChildren->UncheckedAt(i) : 0; } virtual void AddChild(AliAlgVol* ch); // - Double_t GetXTracking() const { return fX; } - Double_t GetAlpTracking() const { return fAlp; } + double GetXTracking() const { return fX; } + double GetAlpTracking() const { return fAlp; } // - Int_t GetNProcessedPoints() const { return fNProcPoints; } - virtual Int_t FinalizeStat(AliAlgDOFStat* h = 0); + int GetNProcessedPoints() const { return fNProcPoints; } + virtual int FinalizeStat(AliAlgDOFStat* h = 0); void FillDOFStat(AliAlgDOFStat* h) const; // - Float_t* GetParVals() const { return fParVals; } - Double_t GetParVal(int par) const { return fParVals[par]; } - Double_t GetParErr(int par) const { return fParErrs[par]; } - Int_t GetParLab(int par) const { return fParLabs[par]; } + float* GetParVals() const { return fParVals; } + double GetParVal(int par) const { return fParVals[par]; } + double GetParErr(int par) const { return fParErrs[par]; } + int GetParLab(int par) const { return fParLabs[par]; } void GetParValGeom(double* delta) const { for (int i = kNDOFGeom; i--;) delta[i] = fParVals[i]; } // - void SetParVals(Int_t npar, Double_t* vl, Double_t* er); - void SetParVal(Int_t par, Double_t v = 0) { fParVals[par] = v; } - void SetParErr(Int_t par, Double_t e = 0) { fParErrs[par] = e; } + void SetParVals(int npar, double* vl, double* er); + void SetParVal(int par, double v = 0) { fParVals[par] = v; } + void SetParErr(int par, double e = 0) { fParErrs[par] = e; } // - Int_t GetNDOFs() const { return fNDOFs; } - Int_t GetNDOFFree() const { return fNDOFFree; } - Int_t GetNDOFGeomFree() const { return fNDOFGeomFree; } - Int_t GetFirstParGloID() const { return fFirstParGloID; } - Int_t GetParGloID(Int_t par) const { return fFirstParGloID + par; } - void SetFirstParGloID(Int_t id) { fFirstParGloID = id; } + int GetNDOFs() const { return fNDOFs; } + int GetNDOFFree() const { return fNDOFFree; } + int GetNDOFGeomFree() const { return fNDOFGeomFree; } + int GetFirstParGloID() const { return fFirstParGloID; } + int GetParGloID(int par) const { return fFirstParGloID + par; } + void SetFirstParGloID(int id) { fFirstParGloID = id; } // virtual void PrepareMatrixT2L(); virtual void SetTrackingFrame(); @@ -164,7 +164,7 @@ class AliAlgVol : public TNamed void SetMatrixL2GReco(const TGeoHMatrix& m) { fMatL2GReco = m; } void SetGlobalDeltaRef(TGeoHMatrix& mat) { fMatDeltaRefGlo = mat; } // - virtual void PrepareMatrixL2G(Bool_t reco = kFALSE); + virtual void PrepareMatrixL2G(bool reco = false); virtual void PrepareMatrixL2GIdeal(); virtual void UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta); // @@ -173,13 +173,13 @@ class AliAlgVol : public TNamed const TGeoHMatrix& GetMatrixT2L() const { return fMatT2L; } void SetMatrixT2L(const TGeoHMatrix& m); // - void Delta2Matrix(TGeoHMatrix& deltaM, const Double_t* delta) const; + void Delta2Matrix(TGeoHMatrix& deltaM, const double* delta) const; // // preparation of variation matrices - void GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t* delta) const; - void GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const Double_t* delta) const; - void GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t* delta, const TGeoHMatrix& relMat) const; - void GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const Double_t* delta, const TGeoHMatrix& relMat) const; + void GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const double* delta) const; + void GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const double* delta) const; + void GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const double* delta, const TGeoHMatrix& relMat) const; + void GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const double* delta, const TGeoHMatrix& relMat) const; // // creation of global matrices for storage void CreateGloDeltaMatrix(TGeoHMatrix& deltaM) const; @@ -189,31 +189,31 @@ class AliAlgVol : public TNamed void CreateAlignmenMatrix(TGeoHMatrix& alg) const; void CreateAlignmentObjects(TClonesArray* arr) const; // - void SetSkip(Bool_t v = kTRUE) { SetBit(kSkipBit, v); } - Bool_t GetSkip() const { return TestBit(kSkipBit); } + void SetSkip(bool v = true) { SetBit(kSkipBit, v); } + bool GetSkip() const { return TestBit(kSkipBit); } // - void ExcludeFromParentConstraint(Bool_t v = kTRUE) { SetBit(kExclFromParentConstraintBit, v); } - Bool_t GetExcludeFromParentConstraint() const { return TestBit(kExclFromParentConstraintBit); } + void ExcludeFromParentConstraint(bool v = true) { SetBit(kExclFromParentConstraintBit, v); } + bool GetExcludeFromParentConstraint() const { return TestBit(kExclFromParentConstraintBit); } // void SetInitDOFsDone() { SetBit(kInitDOFsDoneBit); } - Bool_t GetInitDOFsDone() const { return TestBit(kInitDOFsDoneBit); } + bool GetInitDOFsDone() const { return TestBit(kInitDOFsDoneBit); } // - Bool_t OwnsDOFID(Int_t id) const; - AliAlgVol* GetVolOfDOFID(Int_t id) const; + bool OwnsDOFID(int id) const; + AliAlgVol* GetVolOfDOFID(int id) const; // - virtual Bool_t IsSensor() const { return kFALSE; } + virtual bool IsSensor() const { return false; } // virtual const char* GetDOFName(int i) const; virtual void Print(const Option_t* opt = "") const; virtual void WritePedeInfo(FILE* parOut, const Option_t* opt = "") const; // static const char* GetGeomDOFName(int i) { return i < kNDOFGeom ? fgkDOFName[i] : 0; } - static void SetDefGeomFree(UChar_t patt) { fgDefGeomFree = patt; } - static UChar_t GetDefGeomFree() { return fgDefGeomFree; } + static void SetDefGeomFree(uint8_t patt) { fgDefGeomFree = patt; } + static uint8_t GetDefGeomFree() { return fgDefGeomFree; } // protected: - void SetNDOFs(Int_t n = kNDOFGeom); - void CalcFree(Bool_t condFree = kFALSE); + void SetNDOFs(int n = kNDOFGeom); + void CalcFree(bool condFree = false); // // ------- dummies ------- AliAlgVol(const AliAlgVol&); @@ -222,24 +222,24 @@ class AliAlgVol : public TNamed protected: // Frame_t fVarFrame; // Variation frame for this volume - Int_t fIntID; // internal id within the detector - Double_t fX; // tracking frame X offset - Double_t fAlp; // tracking frame alpa + int fIntID; // internal id within the detector + double fX; // tracking frame X offset + double fAlp; // tracking frame alpa // - Char_t fNDOFs; // number of degrees of freedom, including fixed ones - UInt_t fDOF; // bitpattern degrees of freedom - Char_t fNDOFGeomFree; // number of free geom degrees of freedom - Char_t fNDOFFree; // number of all free degrees of freedom - UChar_t fConstrChild; // bitpattern for constraints on children corrections + char fNDOFs; // number of degrees of freedom, including fixed ones + uint32_t fDOF; // bitpattern degrees of freedom + char fNDOFGeomFree; // number of free geom degrees of freedom + char fNDOFFree; // number of all free degrees of freedom + uint8_t fConstrChild; // bitpattern for constraints on children corrections // AliAlgVol* fParent; // parent volume TObjArray* fChildren; // array of childrens // - Int_t fNProcPoints; // n of processed points - Int_t fFirstParGloID; // ID of the 1st parameter in the global results array - Float_t* fParVals; //! values of the fitted params - Float_t* fParErrs; //! errors of the fitted params - Int_t* fParLabs; //! labels for parameters + int fNProcPoints; // n of processed points + int fFirstParGloID; // ID of the 1st parameter in the global results array + float* fParVals; //! values of the fitted params + float* fParErrs; //! errors of the fitted params + int* fParLabs; //! labels for parameters // TGeoHMatrix fMatL2GReco; // local to global matrix used for reco of data being processed TGeoHMatrix fMatL2G; // local to global matrix, including current alignment @@ -249,7 +249,7 @@ class AliAlgVol : public TNamed // static const char* fgkDOFName[kNDOFGeom]; static const char* fgkFrameName[kNVarFrames]; - static UInt_t fgDefGeomFree; + static uint32_t fgDefGeomFree; // ClassDef(AliAlgVol, 2) }; diff --git a/Detectors/Align/include/Align/AliAlgVtx.h b/Detectors/Align/include/Align/AliAlgVtx.h index 18b27a8c306a9..b01790b2b88f2 100644 --- a/Detectors/Align/include/Align/AliAlgVtx.h +++ b/Detectors/Align/include/Align/AliAlgVtx.h @@ -43,14 +43,14 @@ class AliAlgVtx : public AliAlgSens AliAlgVtx(); // void ApplyCorrection(double* vtx) const; - virtual Bool_t IsSensor() const { return kTRUE; } + virtual bool IsSensor() const { return true; } // void SetAlpha(double alp) { fAlp = alp; PrepareMatrixT2L(); } - virtual void PrepareMatrixL2G(Bool_t = 0) { fMatL2G.Clear(); } // unit matrix + virtual void PrepareMatrixL2G(bool = 0) { fMatL2G.Clear(); } // unit matrix virtual void PrepareMatrixL2GIdeal() { fMatL2GIdeal.Clear(); } // unit matrix virtual void PrepareMatrixT2L(); // diff --git a/Detectors/Align/src/AliAlgAux.cxx b/Detectors/Align/src/AliAlgAux.cxx index ea80079e04acb..e51842ebb8bec 100644 --- a/Detectors/Align/src/AliAlgAux.cxx +++ b/Detectors/Align/src/AliAlgAux.cxx @@ -30,10 +30,10 @@ namespace align { //_______________________________________________________________ -void AliAlgAux::PrintBits(ULong64_t patt, Int_t maxBits) +void AliAlgAux::PrintBits(size_t patt, int maxBits) { // print maxBits of the pattern - maxBits = Min(64, maxBits); + maxBits = std::min(64, maxBits); for (int i = 0; i < maxBits; i++) printf("%c", ((patt >> i) & 0x1) ? '+' : '-'); } diff --git a/Detectors/Align/src/AliAlgConstraint.cxx b/Detectors/Align/src/AliAlgConstraint.cxx index b55386acae1e5..4f95a85eb0568 100644 --- a/Detectors/Align/src/AliAlgConstraint.cxx +++ b/Detectors/Align/src/AliAlgConstraint.cxx @@ -73,7 +73,7 @@ void AliAlgConstraint::WriteChildrenConstraints(FILE* conOut) const const char* comment[3] = {" ", "! ", "!!"}; const char* kKeyConstr[2] = {"constraint", "measurement"}; // - Bool_t doJac = !GetNoJacobian(); // do we need jacobian evaluation? + bool doJac = !GetNoJacobian(); // do we need jacobian evaluation? int nch = GetNChildren(); float* cstrArr = new float[nch * kNDOFGeom * kNDOFGeom]; memset(cstrArr, 0, nch * kNDOFGeom * kNDOFGeom * sizeof(float)); @@ -175,7 +175,7 @@ void AliAlgConstraint::CheckConstraint() const if (!nch) return; // - Bool_t doJac = !GetNoJacobian(); // do we need jacobian evaluation? + bool doJac = !GetNoJacobian(); // do we need jacobian evaluation? float* cstrArr = new float[nch * kNDOFGeom * kNDOFGeom]; memset(cstrArr, 0, nch * kNDOFGeom * kNDOFGeom * sizeof(float)); // we need for each children the matrix for vector transformation from children frame @@ -256,7 +256,7 @@ void AliAlgConstraint::CheckConstraint() const jac += kNDOFGeom * kNDOFGeom; // matrix for next slot } else { for (int jc = 0; jc < kNDOFGeom; jc++) { - Bool_t acc = child->IsFreeDOF(jc) && child->GetParErr(jc) >= 0; + bool acc = child->IsFreeDOF(jc) && child->GetParErr(jc) >= 0; if (acc) { printf(" %+.3e ", parsC[jc]); parsTotAn[jc] += parsC[jc]; diff --git a/Detectors/Align/src/AliAlgDOFStat.cxx b/Detectors/Align/src/AliAlgDOFStat.cxx index d805e78f8ca29..fe6d7f3285644 100644 --- a/Detectors/Align/src/AliAlgDOFStat.cxx +++ b/Detectors/Align/src/AliAlgDOFStat.cxx @@ -29,13 +29,13 @@ namespace align { //_________________________________________________________ -AliAlgDOFStat::AliAlgDOFStat(Int_t n) +AliAlgDOFStat::AliAlgDOFStat(int n) : TNamed("DOFstat", "DOF statistics"), fNDOFs(n), fNMerges(1), fStat(0) { // def c-tor if (fNDOFs) { - fStat = new Int_t[n]; - memset(fStat, 0, fNDOFs * sizeof(Int_t)); + fStat = new int[n]; + memset(fStat, 0, fNDOFs * sizeof(int)); } // } @@ -71,7 +71,7 @@ TH1F* AliAlgDOFStat::CreateHisto(AliAlgSteer* st) const } //______________________________________________________________________________ -Long64_t AliAlgDOFStat::Merge(TCollection* list) +int64_t AliAlgDOFStat::Merge(TCollection* list) { // merge statistics int nmerged = 0; diff --git a/Detectors/Align/src/AliAlgDet.cxx b/Detectors/Align/src/AliAlgDet.cxx index 96c26bbe77e2f..db056b40f51dc 100644 --- a/Detectors/Align/src/AliAlgDet.cxx +++ b/Detectors/Align/src/AliAlgDet.cxx @@ -75,8 +75,8 @@ AliAlgDet::AliAlgDet() fAddError[0] = fAddError[1] = 0; // for (int i = 0; i < kNTrackTypes; i++) { - fDisabled[i] = kFALSE; - fObligatory[i] = kFALSE; + fDisabled[i] = false; + fObligatory[i] = false; fTrackFlagSel[i] = 0; fNPointsSel[i] = 0; } @@ -94,7 +94,7 @@ AliAlgDet::~AliAlgDet() //FIXME(milettri): needs AliESDtrack ////____________________________________________ -//Int_t AliAlgDet::ProcessPoints(const AliESDtrack* esdTr, AliAlgTrack* algTrack, Bool_t inv) +//int AliAlgDet::ProcessPoints(const AliESDtrack* esdTr, AliAlgTrack* algTrack, bool inv) //{ // // Extract the points corresponding to this detector, recalibrate/realign them to the // // level of the "starting point" for the alignment/calibration session. @@ -125,7 +125,7 @@ AliAlgDet::~AliAlgDet() //} //_________________________________________________________ -void AliAlgDet::AcknowledgeNewRun(Int_t run) +void AliAlgDet::AcknowledgeNewRun(int run) { // update parameters needed to process this run @@ -229,7 +229,7 @@ void AliAlgDet::AddVolume(AliAlgVol* vol) if (vol->IsSensor()) { fSensors.AddLast(vol); ((AliAlgSens*)vol)->SetDetector(this); - Int_t vid = ((AliAlgSens*)vol)->GetVolID(); + int vid = ((AliAlgSens*)vol)->GetVolID(); if (fVolIDMin < 0 || vid < fVolIDMin) fVolIDMin = vid; if (fVolIDMax < 0 || vid > fVolIDMax) @@ -278,7 +278,7 @@ void AliAlgDet::SortSensors() return; } fSensors.Sort(); - fSID2VolID = new Int_t[fNSensors]; // cash id's for fast binary search + fSID2VolID = new int[fNSensors]; // cash id's for fast binary search for (int i = 0; i < fNSensors; i++) { fSID2VolID[i] = GetSensor(i)->GetVolID(); GetSensor(i)->SetSID(i); @@ -287,7 +287,7 @@ void AliAlgDet::SortSensors() } //_________________________________________________________ -Int_t AliAlgDet::InitGeom() +int AliAlgDet::InitGeom() { // define hiearchy, initialize matrices, return number of global parameters if (GetInitGeomDone()) @@ -311,14 +311,14 @@ Int_t AliAlgDet::InitGeom() } //_________________________________________________________ -Int_t AliAlgDet::AssignDOFs() +int AliAlgDet::AssignDOFs() { // assign DOFs IDs, parameters // int gloCount0(fAlgSteer->GetNDOFs()), gloCount(fAlgSteer->GetNDOFs()); - Float_t* pars = fAlgSteer->GetGloParVal(); - Float_t* errs = fAlgSteer->GetGloParErr(); - Int_t* labs = fAlgSteer->GetGloParLab(); + float* pars = fAlgSteer->GetGloParVal(); + float* errs = fAlgSteer->GetGloParErr(); + int* labs = fAlgSteer->GetGloParLab(); // // assign calibration DOFs fFirstParGloID = gloCount; @@ -358,14 +358,14 @@ void AliAlgDet::InitDOFs() for (int iv = 0; iv < nvol; iv++) GetVolume(iv)->InitDOFs(); // - CalcFree(kTRUE); + CalcFree(true); // SetInitDOFsDone(); return; } //_________________________________________________________ -Int_t AliAlgDet::VolID2SID(Int_t vid) const +int AliAlgDet::VolID2SID(int vid) const { // find SID corresponding to VolID int mn(0), mx(fNSensors - 1); @@ -403,8 +403,7 @@ void AliAlgDet::Print(const Option_t* opt) const printf("Obligatory in Collisions: %7s | Cosmic: %7s\n", IsObligatory(kColl) ? " YES " : " NO ", IsObligatory(kCosm) ? " YES " : " NO "); // - printf("Sel. flags in Collisions: 0x%05lx | Cosmic: 0x%05lx\n", - fTrackFlagSel[kColl], fTrackFlagSel[kCosm]); + fmt::printf("Sel. flags in Collisions: {:05#x}%05 | Cosmic: 0x{:05#x}%05\n", fTrackFlagSel[kColl], fTrackFlagSel[kCosm]); // printf("Min.points in Collisions: %7d | Cosmic: %7d\n", fNPointsSel[kColl], fNPointsSel[kCosm]); @@ -419,7 +418,7 @@ void AliAlgDet::Print(const Option_t* opt) const } //____________________________________________ -void AliAlgDet::SetDetID(UInt_t tp) +void AliAlgDet::SetDetID(uint32_t tp) { o2::detectors::DetID detID(tp); SetUniqueID(detID); @@ -439,7 +438,7 @@ void AliAlgDet::SetAddError(double sigy, double sigz) } //____________________________________________ -void AliAlgDet::SetUseErrorParam(Int_t v) +void AliAlgDet::SetUseErrorParam(int v) { // set type of points error parameterization LOG(FATAL) << "UpdatePointByTrackInfo is not implemented for this detector"; @@ -454,7 +453,7 @@ void AliAlgDet::UpdatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) } //____________________________________________ -void AliAlgDet::SetObligatory(Int_t tp, Bool_t v) +void AliAlgDet::SetObligatory(int tp, bool v) { // mark detector presence obligatory in the track fObligatory[tp] = v; @@ -514,23 +513,23 @@ void AliAlgDet::WriteAlignmentResults() const } //______________________________________________________ -Bool_t AliAlgDet::OwnsDOFID(Int_t id) const +bool AliAlgDet::OwnsDOFID(int id) const { // check if DOF ID belongs to this detector for (int iv = GetNVolumes(); iv--;) { AliAlgVol* vol = GetVolume(iv); // check only top level volumes if (!vol->GetParent() && vol->OwnsDOFID(id)) - return kTRUE; + return true; } // calibration DOF? if (id >= fFirstParGloID && id < fFirstParGloID + fNCalibDOF) - return kTRUE; + return true; // - return kFALSE; + return false; } //______________________________________________________ -AliAlgVol* AliAlgDet::GetVolOfDOFID(Int_t id) const +AliAlgVol* AliAlgDet::GetVolOfDOFID(int id) const { // gets volume owning this DOF ID for (int iv = GetNVolumes(); iv--;) { @@ -608,7 +607,7 @@ int AliAlgDet::SelectVolumes(TObjArray* arr, int lev, const char* match) } //________________________________________ -void AliAlgDet::SetFreeDOFPattern(UInt_t pat, int lev, const char* match) +void AliAlgDet::SetFreeDOFPattern(uint32_t pat, int lev, const char* match) { // set free DOFs to volumes matching either to hierarchy level or // whose name contains match @@ -683,7 +682,7 @@ void AliAlgDet::ConstrainOrphans(const double* sigma, const char* match) } //________________________________________ -void AliAlgDet::SetFreeDOF(Int_t dof) +void AliAlgDet::SetFreeDOF(int dof) { // set detector free dof if (dof >= kNMaxKalibDOF) { @@ -694,7 +693,7 @@ void AliAlgDet::SetFreeDOF(Int_t dof) } //________________________________________ -void AliAlgDet::FixDOF(Int_t dof) +void AliAlgDet::FixDOF(int dof) { // fix detector dof if (dof >= kNMaxKalibDOF) { @@ -705,14 +704,14 @@ void AliAlgDet::FixDOF(Int_t dof) } //__________________________________________________________________ -Bool_t AliAlgDet::IsCondDOF(Int_t i) const +bool AliAlgDet::IsCondDOF(int i) const { // is DOF free and conditioned? return (!IsZeroAbs(GetParVal(i)) || !IsZeroAbs(GetParErr(i))); } //__________________________________________________________________ -void AliAlgDet::CalcFree(Bool_t condFix) +void AliAlgDet::CalcFree(bool condFix) { // calculate free calib dofs. If condFix==true, condition parameter a la pede, i.e. error < 0 fNCalibDOFFree = 0; diff --git a/Detectors/Align/src/AliAlgDetHMPID.cxx b/Detectors/Align/src/AliAlgDetHMPID.cxx index 7e1fbf0d0578f..64a1a3e192b18 100644 --- a/Detectors/Align/src/AliAlgDetHMPID.cxx +++ b/Detectors/Align/src/AliAlgDetHMPID.cxx @@ -51,13 +51,13 @@ void AliAlgDetHMPID::DefineVolumes() // int labDet = GetDetLabel(); AliGeomManager::ELayerID idHMPID = AliGeomManager::kHMPID; - for (Int_t iCh = AliHMPIDParam::kMinCh; iCh <= AliHMPIDParam::kMaxCh; iCh++) { + for (int iCh = AliHMPIDParam::kMinCh; iCh <= AliHMPIDParam::kMaxCh; iCh++) { const char* symname = Form("/HMPID/Chamber%i", iCh); if (!gGeoManager->GetAlignableEntry(symname)) { AliErrorF("Did not find alignable %s", symname); continue; } - UShort_t vid = AliGeomManager::LayerToVolUID(idHMPID, iCh); + uint16_t vid = AliGeomManager::LayerToVolUID(idHMPID, iCh); int iid = labDet + (1 + iCh) * 10000; AliAlgSensHMPID* sens = new AliAlgSensHMPID(symname, vid, iid); AddVolume(sens); @@ -66,14 +66,14 @@ void AliAlgDetHMPID::DefineVolumes() } //____________________________________________ -Bool_t AliAlgDetHMPID::AcceptTrack(const AliESDtrack* trc, Int_t trtype) const +bool AliAlgDetHMPID::AcceptTrack(const AliESDtrack* trc, int trtype) const { // test if detector had seed this track if (!CheckFlags(trc, trtype)) - return kFALSE; + return false; if (trc->GetNcls(1) < fNPointsSel[trtype]) - return kFALSE; - return kTRUE; + return false; + return true; } } // namespace align diff --git a/Detectors/Align/src/AliAlgDetITS.cxx b/Detectors/Align/src/AliAlgDetITS.cxx index 4e7a7637a2413..99cd64bfad53c 100644 --- a/Detectors/Align/src/AliAlgDetITS.cxx +++ b/Detectors/Align/src/AliAlgDetITS.cxx @@ -34,7 +34,7 @@ namespace o2 namespace align { -const Char_t* AliAlgDetITS::fgkHitsSel[AliAlgDetITS::kNSPDSelTypes] = +const char* AliAlgDetITS::fgkHitsSel[AliAlgDetITS::kNSPDSelTypes] = {"SPDNoSel", "SPDBoth", "SPDAny", "SPD0", "SPD1"}; //____________________________________________ @@ -146,17 +146,17 @@ void AliAlgDetITS::Print(const Option_t* opt) const } //____________________________________________ -Bool_t AliAlgDetITS::AcceptTrack(const AliESDtrack* trc, Int_t trtype) const +bool AliAlgDetITS::AcceptTrack(const AliESDtrack* trc, int trtype) const { // test if detector had seed this track if (!CheckFlags(trc, trtype)) - return kFALSE; + return false; if (trc->GetNcls(0) < fNPointsSel[trtype]) - return kFALSE; + return false; if (!CheckHitPattern(trc, GetITSSelPattern(trtype))) - return kFALSE; + return false; // - return kTRUE; + return true; } //____________________________________________ @@ -186,37 +186,37 @@ void AliAlgDetITS::SetSkipLr(int ilr) } //_________________________________________________ -void AliAlgDetITS::SetUseErrorParam(Int_t v) +void AliAlgDetITS::SetUseErrorParam(int v) { // set type of points error parameterization fUseErrorParam = v; } //_________________________________________________ -Bool_t AliAlgDetITS::CheckHitPattern(const AliESDtrack* trc, Int_t sel) +bool AliAlgDetITS::CheckHitPattern(const AliESDtrack* trc, int sel) { // check if track hit pattern is ok switch (sel) { case kSPDBoth: if (!trc->HasPointOnITSLayer(0) || !trc->HasPointOnITSLayer(1)) - return kFALSE; + return false; break; case kSPDAny: if (!trc->HasPointOnITSLayer(0) && !trc->HasPointOnITSLayer(1)) - return kFALSE; + return false; break; case kSPD0: if (!trc->HasPointOnITSLayer(0)) - return kFALSE; + return false; break; case kSPD1: if (!trc->HasPointOnITSLayer(1)) - return kFALSE; + return false; break; default: break; } - return kTRUE; + return true; } //_________________________________________________ @@ -263,17 +263,17 @@ void AliAlgDetITS::GetErrorParamAngle(int layer, double anglePol, double angleAz const float kCfSPDResZ[kNcfSPDResZ] = {+9.2384e+01, +3.4352e-01, -2.7317e+01, -1.4642e-01, +2.0868e+00}; const float kSPDpolMin = 34.358002, kSPDpolMax = 145.000000; // - const Double_t kMaxSigmaSDDx = 100.; - const Double_t kMaxSigmaSDDz = 400.; - const Double_t kMaxSigmaSSDx = 100.; - const Double_t kMaxSigmaSSDz = 1000.; + const double kMaxSigmaSDDx = 100.; + const double kMaxSigmaSDDz = 400.; + const double kMaxSigmaSSDx = 100.; + const double kMaxSigmaSSDz = 1000.; // - const Double_t kParamSDDx[2] = {30.93, 0.059}; - const Double_t kParamSDDz[2] = {33.09, 0.011}; - const Double_t kParamSSDx[2] = {18.64, -0.0046}; - const Double_t kParamSSDz[2] = {784.4, -0.828}; - Double_t sigmax = 1000.0, sigmaz = 1000.0; - //Double_t biasx = 0.0; + const double kParamSDDx[2] = {30.93, 0.059}; + const double kParamSDDz[2] = {33.09, 0.011}; + const double kParamSSDx[2] = {18.64, -0.0046}; + const double kParamSSDz[2] = {784.4, -0.828}; + double sigmax = 1000.0, sigmaz = 1000.0; + //double biasx = 0.0; angleAzi = Abs(angleAzi); anglePol = Abs(anglePol); @@ -282,8 +282,8 @@ void AliAlgDetITS::GetErrorParamAngle(int layer, double anglePol, double angleAz angleAzi = Pi() - angleAzi; if (anglePol > 0.5 * Pi()) anglePol = Pi() - anglePol; - Double_t angleAziDeg = angleAzi * RadToDeg(); - Double_t anglePolDeg = anglePol * RadToDeg(); + double angleAziDeg = angleAzi * RadToDeg(); + double anglePolDeg = anglePol * RadToDeg(); // if (layer == 0 || layer == 1) { // SPD // diff --git a/Detectors/Align/src/AliAlgDetTOF.cxx b/Detectors/Align/src/AliAlgDetTOF.cxx index 393f3fea8c629..669ba57d0655c 100644 --- a/Detectors/Align/src/AliAlgDetTOF.cxx +++ b/Detectors/Align/src/AliAlgDetTOF.cxx @@ -76,7 +76,7 @@ void AliAlgDetTOF::DefineVolumes() } //____________________________________________ -Bool_t AliAlgDetTOF::AcceptTrack(const AliESDtrack* trc, Int_t trtype) const +bool AliAlgDetTOF::AcceptTrack(const AliESDtrack* trc, int trtype) const { // test if detector had seed this track return CheckFlags(trc, trtype); diff --git a/Detectors/Align/src/AliAlgDetTPC.cxx b/Detectors/Align/src/AliAlgDetTPC.cxx index d28d834429dab..9acc3ec91169a 100644 --- a/Detectors/Align/src/AliAlgDetTPC.cxx +++ b/Detectors/Align/src/AliAlgDetTPC.cxx @@ -66,8 +66,8 @@ void AliAlgDetTPC::DefineVolumes() AliErrorF("Did not find alignable %s", symname); continue; } - Int_t iid = side * kNSect + isc; - UShort_t vid = AliGeomManager::LayerToVolUID(AliGeomManager::kTPC1 + roc, iid); + int iid = side * kNSect + isc; + uint16_t vid = AliGeomManager::LayerToVolUID(AliGeomManager::kTPC1 + roc, iid); iid = labDet + (1 + side) * 10000 + (1 + isc) * 100 + (1 + roc); AliAlgSensTPC* sens = new AliAlgSensTPC(symname, vid, iid, isc); sens->SetParent(volTPC); @@ -79,14 +79,14 @@ void AliAlgDetTPC::DefineVolumes() } //____________________________________________ -Bool_t AliAlgDetTPC::AcceptTrack(const AliESDtrack* trc, Int_t trtype) const +bool AliAlgDetTPC::AcceptTrack(const AliESDtrack* trc, int trtype) const { // test if detector had seed this track if (!CheckFlags(trc, trtype)) - return kFALSE; + return false; if (trc->GetNcls(1) < fNPointsSel[trtype]) - return kFALSE; - return kTRUE; + return false; + return true; } } // namespace align diff --git a/Detectors/Align/src/AliAlgDetTRD.cxx b/Detectors/Align/src/AliAlgDetTRD.cxx index 19e162674cf31..e1a43ac0dde78 100644 --- a/Detectors/Align/src/AliAlgDetTRD.cxx +++ b/Detectors/Align/src/AliAlgDetTRD.cxx @@ -69,14 +69,14 @@ void AliAlgDetTRD::DefineVolumes() // for (int ilr = 0; ilr < kNLayers; ilr++) { // layer for (int ich = 0; ich < kNStacks * kNSect; ich++) { // chamber - Int_t isector = ich / AliTRDgeometry::Nstack(); - Int_t istack = ich % AliTRDgeometry::Nstack(); - //Int_t lid = AliTRDgeometry::GetDetector(ilr,istack,isector); + int isector = ich / AliTRDgeometry::Nstack(); + int istack = ich % AliTRDgeometry::Nstack(); + //int lid = AliTRDgeometry::GetDetector(ilr,istack,isector); int iid = labDet + (1 + ilr) * 10000 + (1 + isector) * 100 + (1 + istack); const char* symname = Form("TRD/sm%02d/st%d/pl%d", isector, istack, ilr); if (!gGeoManager->GetAlignableEntry(symname)) continue; - UShort_t vid = AliGeomManager::LayerToVolUID(AliGeomManager::kTRD1 + ilr, ich); + uint16_t vid = AliGeomManager::LayerToVolUID(AliGeomManager::kTRD1 + ilr, ich); AddVolume(chamb = new AliAlgSensTRD(symname, vid, iid /*lid*/, isector)); iid = labDet + (1 + isector) * 100; if (!sect[isector]) @@ -93,14 +93,14 @@ void AliAlgDetTRD::DefineVolumes() } //____________________________________________ -Bool_t AliAlgDetTRD::AcceptTrack(const AliESDtrack* trc, Int_t trtype) const +bool AliAlgDetTRD::AcceptTrack(const AliESDtrack* trc, int trtype) const { // test if detector had seed this track if (!CheckFlags(trc, trtype)) - return kFALSE; + return false; if (trc->GetTRDntracklets() < fNPointsSel[trtype]) - return kFALSE; - return kTRUE; + return false; + return true; } //__________________________________________ @@ -143,7 +143,7 @@ void AliAlgDetTRD::WritePedeInfo(FILE* parOut, const Option_t* opt) const } //_______________________________________________________ -Double_t AliAlgDetTRD::GetCalibDOFVal(int id) const +double AliAlgDetTRD::GetCalibDOFVal(int id) const { // return preset value of calibration dof double val = 0; @@ -161,7 +161,7 @@ Double_t AliAlgDetTRD::GetCalibDOFVal(int id) const } //_______________________________________________________ -Double_t AliAlgDetTRD::GetCalibDOFValWithCal(int id) const +double AliAlgDetTRD::GetCalibDOFValWithCal(int id) const { // return preset value of calibration dof + mp correction return GetCalibDOFVal(id) + GetParVal(id); diff --git a/Detectors/Align/src/AliAlgMPRecord.cxx b/Detectors/Align/src/AliAlgMPRecord.cxx index 7de50b4bb35d7..e710b6d64033d 100644 --- a/Detectors/Align/src/AliAlgMPRecord.cxx +++ b/Detectors/Align/src/AliAlgMPRecord.cxx @@ -56,7 +56,7 @@ AliAlgMPRecord::~AliAlgMPRecord() } //_________________________________________________________ -void AliAlgMPRecord::DummyRecord(Float_t res, Float_t err, Float_t dGlo, Int_t labGlo) +void AliAlgMPRecord::DummyRecord(float res, float err, float dGlo, int labGlo) { // create dummy residuals record if (!fNDGlo) @@ -82,13 +82,13 @@ void AliAlgMPRecord::DummyRecord(Float_t res, Float_t err, Float_t dGlo, Int_t l } //_________________________________________________________ -Bool_t AliAlgMPRecord::FillTrack(const AliAlgTrack* trc, const Int_t* id2Lab) +bool AliAlgMPRecord::FillTrack(const AliAlgTrack* trc, const int* id2Lab) { // fill track info, optionally substitutind glopar par ID by label // if (!trc->GetDerivDone()) { LOG(ERROR) << "Track derivatives are not yet evaluated"; - return kFALSE; + return false; } fNVarLoc = trc->GetNLocPar(); // number of local degrees of freedom in the track fNResid = 0; @@ -203,13 +203,13 @@ Bool_t AliAlgMPRecord::FillTrack(const AliAlgTrack* trc, const Int_t* id2Lab) // if (!fNDGloTot) { LOG(INFO) << "Track does not depend on free global parameters, discard"; - return kFALSE; + return false; } - return kTRUE; + return true; } //________________________________________________ -void AliAlgMPRecord::Resize(Int_t nresid, Int_t nloc, Int_t nglo) +void AliAlgMPRecord::Resize(int nresid, int nloc, int nglo) { // resize container if (nresid > fNResidBook) { @@ -218,35 +218,35 @@ void AliAlgMPRecord::Resize(Int_t nresid, Int_t nloc, Int_t nglo) delete[] fVolID; delete[] fResid; delete[] fResErr; - fNDLoc = new Short_t[nresid]; - fNDGlo = new Int_t[nresid]; - fVolID = new Int_t[nresid]; - fResid = new Float_t[nresid]; - fResErr = new Float_t[nresid]; + fNDLoc = new int16_t[nresid]; + fNDGlo = new int[nresid]; + fVolID = new int[nresid]; + fResid = new float[nresid]; + fResErr = new float[nresid]; fNResidBook = nresid; - memset(fNDLoc, 0, nresid * sizeof(Short_t)); - memset(fNDGlo, 0, nresid * sizeof(Int_t)); - memset(fVolID, 0, nresid * sizeof(Int_t)); - memset(fResid, 0, nresid * sizeof(Float_t)); - memset(fResErr, 0, nresid * sizeof(Float_t)); + memset(fNDLoc, 0, nresid * sizeof(int16_t)); + memset(fNDGlo, 0, nresid * sizeof(int)); + memset(fVolID, 0, nresid * sizeof(int)); + memset(fResid, 0, nresid * sizeof(float)); + memset(fResErr, 0, nresid * sizeof(float)); } if (nloc > fNDLocTotBook) { delete[] fIDLoc; delete[] fDLoc; - fIDLoc = new Short_t[nloc]; - fDLoc = new Float_t[nloc]; + fIDLoc = new int16_t[nloc]; + fDLoc = new float[nloc]; fNDLocTotBook = nloc; - memset(fIDLoc, 0, nloc * sizeof(Short_t)); - memset(fDLoc, 0, nloc * sizeof(Float_t)); + memset(fIDLoc, 0, nloc * sizeof(int16_t)); + memset(fDLoc, 0, nloc * sizeof(float)); } if (nglo > fNDGloTotBook) { delete[] fIDGlo; delete[] fDGlo; - fIDGlo = new Int_t[nglo]; - fDGlo = new Float_t[nglo]; + fIDGlo = new int[nglo]; + fDGlo = new float[nglo]; fNDGloTotBook = nglo; - memset(fIDGlo, 0, nglo * sizeof(Int_t)); - memset(fDGlo, 0, nglo * sizeof(Float_t)); + memset(fIDGlo, 0, nglo * sizeof(int)); + memset(fDGlo, 0, nglo * sizeof(float)); } // } @@ -283,15 +283,15 @@ void AliAlgMPRecord::Print(const Option_t*) const ir, fResid[ir], fResErr[ir], ndloc, ndglo, GetVolID(ir)); // printf("Local Derivatives:\n"); - Bool_t eolOK = kTRUE; + bool eolOK = true; for (int id = 0; id < ndloc; id++) { int jd = id + curLoc; printf("[%3d] %+.2e ", fIDLoc[jd], fDLoc[jd]); if (((id + 1) % kNColLoc) == 0) { printf("\n"); - eolOK = kTRUE; + eolOK = true; } else - eolOK = kFALSE; + eolOK = false; } if (!eolOK) printf("\n"); @@ -299,18 +299,18 @@ void AliAlgMPRecord::Print(const Option_t*) const // // printf("Global Derivatives:\n"); - // eolOK = kTRUE; + // eolOK = true; // const int kNColGlo=6; int prvID = -1; for (int id = 0; id < ndglo; id++) { int jd = id + curGlo; - // eolOK==kFALSE; + // eolOK==false; if (prvID > fIDGlo[jd] % 100) { - printf("\n"); /* eolOK = kTRUE;*/ + printf("\n"); /* eolOK = true;*/ } printf("[%5d] %+.2e ", fIDGlo[jd], fDGlo[jd]); // if (((id+1)%kNColGlo)==0) - // else eolOK = kFALSE; + // else eolOK = false; prvID = fIDGlo[jd] % 100; } // if (!eolOK) printf("\n"); diff --git a/Detectors/Align/src/AliAlgPoint.cxx b/Detectors/Align/src/AliAlgPoint.cxx index 14b46baff0a6e..a7409a3590a7f 100644 --- a/Detectors/Align/src/AliAlgPoint.cxx +++ b/Detectors/Align/src/AliAlgPoint.cxx @@ -221,11 +221,11 @@ void AliAlgPoint::Clear(Option_t*) } //__________________________________________________________________ -Int_t AliAlgPoint::Compare(const TObject* b) const +int AliAlgPoint::Compare(const TObject* b) const { // sort points in direction opposite to track propagation, i.e. // 1) for tracks from collision: range in decreasing tracking X - // 2) for cosmic tracks: upper leg (pnt->IsInvDir()==kTRUE) ranged in increasing X + // 2) for cosmic tracks: upper leg (pnt->IsInvDir()==true) ranged in increasing X // lower leg - in decreasing X AliAlgPoint* pnt = (AliAlgPoint*)b; double x = GetXPoint(); @@ -245,7 +245,7 @@ Int_t AliAlgPoint::Compare(const TObject* b) const } //__________________________________________________________________ -void AliAlgPoint::GetXYZGlo(Double_t r[3]) const +void AliAlgPoint::GetXYZGlo(double r[3]) const { // position in lab frame double cs = TMath::Cos(fAlphaSens); @@ -258,7 +258,7 @@ void AliAlgPoint::GetXYZGlo(Double_t r[3]) const } //__________________________________________________________________ -Double_t AliAlgPoint::GetPhiGlo() const +double AliAlgPoint::GetPhiGlo() const { // phi angle (-pi:pi) in global frame double xyz[3]; @@ -267,7 +267,7 @@ Double_t AliAlgPoint::GetPhiGlo() const } //__________________________________________________________________ -Int_t AliAlgPoint::GetAliceSector() const +int AliAlgPoint::GetAliceSector() const { // get global sector ID corresponding to this point phi return Phi2Sector(GetPhiGlo()); diff --git a/Detectors/Align/src/AliAlgRes.cxx b/Detectors/Align/src/AliAlgRes.cxx index e49409bf3fad5..35caa63e368e3 100644 --- a/Detectors/Align/src/AliAlgRes.cxx +++ b/Detectors/Align/src/AliAlgRes.cxx @@ -63,7 +63,7 @@ AliAlgRes::~AliAlgRes() } //________________________________________________ -void AliAlgRes::Resize(Int_t np) +void AliAlgRes::Resize(int np) { // resize container if (np > fNBook) { @@ -87,43 +87,43 @@ void AliAlgRes::Resize(Int_t np) delete[] fLabel; // fNBook = 100 + np; - fX = new Float_t[fNBook]; - fY = new Float_t[fNBook]; - fZ = new Float_t[fNBook]; - fSnp = new Float_t[fNBook]; - fTgl = new Float_t[fNBook]; - fAlpha = new Float_t[fNBook]; - fDY = new Float_t[fNBook]; - fDZ = new Float_t[fNBook]; - fSigY2 = new Float_t[fNBook]; - fSigYZ = new Float_t[fNBook]; - fSigZ2 = new Float_t[fNBook]; - fDYK = new Float_t[fNBook]; - fDZK = new Float_t[fNBook]; - fSigY2K = new Float_t[fNBook]; - fSigYZK = new Float_t[fNBook]; - fSigZ2K = new Float_t[fNBook]; - fVolID = new Int_t[fNBook]; - fLabel = new Int_t[fNBook]; + fX = new float[fNBook]; + fY = new float[fNBook]; + fZ = new float[fNBook]; + fSnp = new float[fNBook]; + fTgl = new float[fNBook]; + fAlpha = new float[fNBook]; + fDY = new float[fNBook]; + fDZ = new float[fNBook]; + fSigY2 = new float[fNBook]; + fSigYZ = new float[fNBook]; + fSigZ2 = new float[fNBook]; + fDYK = new float[fNBook]; + fDZK = new float[fNBook]; + fSigY2K = new float[fNBook]; + fSigYZK = new float[fNBook]; + fSigZ2K = new float[fNBook]; + fVolID = new int[fNBook]; + fLabel = new int[fNBook]; // - memset(fX, 0, fNBook * sizeof(Float_t)); - memset(fY, 0, fNBook * sizeof(Float_t)); - memset(fZ, 0, fNBook * sizeof(Float_t)); - memset(fSnp, 0, fNBook * sizeof(Float_t)); - memset(fTgl, 0, fNBook * sizeof(Float_t)); - memset(fAlpha, 0, fNBook * sizeof(Float_t)); - memset(fDY, 0, fNBook * sizeof(Float_t)); - memset(fDZ, 0, fNBook * sizeof(Float_t)); - memset(fSigY2, 0, fNBook * sizeof(Float_t)); - memset(fSigYZ, 0, fNBook * sizeof(Float_t)); - memset(fSigZ2, 0, fNBook * sizeof(Float_t)); - memset(fDYK, 0, fNBook * sizeof(Float_t)); - memset(fDZK, 0, fNBook * sizeof(Float_t)); - memset(fSigY2K, 0, fNBook * sizeof(Float_t)); - memset(fSigYZK, 0, fNBook * sizeof(Float_t)); - memset(fSigZ2K, 0, fNBook * sizeof(Float_t)); - memset(fVolID, 0, fNBook * sizeof(Int_t)); - memset(fLabel, 0, fNBook * sizeof(Int_t)); + memset(fX, 0, fNBook * sizeof(float)); + memset(fY, 0, fNBook * sizeof(float)); + memset(fZ, 0, fNBook * sizeof(float)); + memset(fSnp, 0, fNBook * sizeof(float)); + memset(fTgl, 0, fNBook * sizeof(float)); + memset(fAlpha, 0, fNBook * sizeof(float)); + memset(fDY, 0, fNBook * sizeof(float)); + memset(fDZ, 0, fNBook * sizeof(float)); + memset(fSigY2, 0, fNBook * sizeof(float)); + memset(fSigYZ, 0, fNBook * sizeof(float)); + memset(fSigZ2, 0, fNBook * sizeof(float)); + memset(fDYK, 0, fNBook * sizeof(float)); + memset(fDZK, 0, fNBook * sizeof(float)); + memset(fSigY2K, 0, fNBook * sizeof(float)); + memset(fSigYZK, 0, fNBook * sizeof(float)); + memset(fSigZ2K, 0, fNBook * sizeof(float)); + memset(fVolID, 0, fNBook * sizeof(int)); + memset(fLabel, 0, fNBook * sizeof(int)); } // } @@ -150,7 +150,7 @@ void AliAlgRes::Print(const Option_t* opt) const // print info TString opts = opt; opts.ToLower(); - Bool_t lab = opts.Contains("l"); + bool lab = opts.Contains("l"); printf("%5sTr.", IsCosmic() ? "Cosm." : "Coll."); if (IsCosmic()) printf("%2d/%2d ", fTrackID >> 16, fTrackID & 0xffff); @@ -159,7 +159,7 @@ void AliAlgRes::Print(const Option_t* opt) const printf("Run:%6d Bz:%+4.1f Np: %3d q/Pt:%+.4f | Chi2: Ini: %6.1f LinSol:%6.1f Kalm:%6.1f |Vtx:%3s| TStamp:%d\n", fRun, fBz, fNPoints, fQ2Pt, fChi2Ini, fChi2, fChi2K, HasVertex() ? "ON" : "OFF", fTimeStamp); if (opts.Contains("r")) { - Bool_t ers = opts.Contains("e"); + bool ers = opts.Contains("e"); printf("%5s %7s %s %7s %7s %7s %5s %5s %9s %9s", " VID ", " Label ", " Alp ", " X ", " Y ", " Z ", " Snp ", " Tgl ", " DY ", " DZ "); if (ers) @@ -192,7 +192,7 @@ void AliAlgRes::Print(const Option_t* opt) const } //____________________________________________________________ -Bool_t AliAlgRes::FillTrack(AliAlgTrack* trc, Bool_t doKalman) +bool AliAlgRes::FillTrack(AliAlgTrack* trc, bool doKalman) { // fill tracks residuals info int nps, np = trc->GetNPoints(); @@ -202,7 +202,7 @@ Bool_t AliAlgRes::FillTrack(AliAlgTrack* trc, Bool_t doKalman) } else nps = np - 1; // ref point is dummy? if (nps < 0) - return kTRUE; + return true; SetCosmic(trc->IsCosmic()); // SetNPoints(nps); @@ -239,7 +239,7 @@ Bool_t AliAlgRes::FillTrack(AliAlgTrack* trc, Bool_t doKalman) LOG(FATAL) << nfill << " residuals were stored instead of " << nps; } // - SetKalmanDone(kFALSE); + SetKalmanDone(false); int nfilk = 0; if (doKalman && trc->ResidKalman()) { for (int i = 0; i < np; i++) { @@ -260,28 +260,28 @@ Bool_t AliAlgRes::FillTrack(AliAlgTrack* trc, Bool_t doKalman) } // fChi2K = trc->GetChi2(); - SetKalmanDone(kTRUE); + SetKalmanDone(true); } - return kTRUE; + return true; } //_________________________________________________ -Float_t AliAlgRes::GetXLab(int i) const +float AliAlgRes::GetXLab(int i) const { // cluster lab X return Abs(fX[i]) * Cos(fAlpha[i]) - fY[i] * Sin(fAlpha[i]); } //_________________________________________________ -Float_t AliAlgRes::GetYLab(int i) const +float AliAlgRes::GetYLab(int i) const { // cluster lab Y return Abs(fX[i]) * Sin(fAlpha[i]) + fY[i] * Cos(fAlpha[i]); } //_________________________________________________ -Float_t AliAlgRes::GetZLab(int i) const +float AliAlgRes::GetZLab(int i) const { // cluster lab Z return fZ[i]; diff --git a/Detectors/Align/src/AliAlgResFast.cxx b/Detectors/Align/src/AliAlgResFast.cxx index e654338e551d3..d84db7c796559 100644 --- a/Detectors/Align/src/AliAlgResFast.cxx +++ b/Detectors/Align/src/AliAlgResFast.cxx @@ -55,7 +55,7 @@ AliAlgResFast::~AliAlgResFast() } //________________________________________________ -void AliAlgResFast::Resize(Int_t np) +void AliAlgResFast::Resize(int np) { // resize container if (np > fNBook) { @@ -69,23 +69,23 @@ void AliAlgResFast::Resize(Int_t np) delete[] fMatErr; // fNBook = 30 + np; - fD0 = new Float_t[fNBook]; - fD1 = new Float_t[fNBook]; - fSig0 = new Float_t[fNBook]; - fSig1 = new Float_t[fNBook]; - fVolID = new Int_t[fNBook]; - fLabel = new Int_t[fNBook]; - fSolMat = new Float_t[fNBook * 4]; // at most 4 material params per point - fMatErr = new Float_t[fNBook * 4]; // at most 4 material params per point + fD0 = new float[fNBook]; + fD1 = new float[fNBook]; + fSig0 = new float[fNBook]; + fSig1 = new float[fNBook]; + fVolID = new int[fNBook]; + fLabel = new int[fNBook]; + fSolMat = new float[fNBook * 4]; // at most 4 material params per point + fMatErr = new float[fNBook * 4]; // at most 4 material params per point // - memset(fD0, 0, fNBook * sizeof(Float_t)); - memset(fD1, 0, fNBook * sizeof(Float_t)); - memset(fSig0, 0, fNBook * sizeof(Float_t)); - memset(fSig1, 0, fNBook * sizeof(Float_t)); - memset(fVolID, 0, fNBook * sizeof(Int_t)); - memset(fLabel, 0, fNBook * sizeof(Int_t)); - memset(fSolMat, 0, 4 * fNBook * sizeof(Int_t)); - memset(fMatErr, 0, 4 * fNBook * sizeof(Int_t)); + memset(fD0, 0, fNBook * sizeof(float)); + memset(fD1, 0, fNBook * sizeof(float)); + memset(fSig0, 0, fNBook * sizeof(float)); + memset(fSig1, 0, fNBook * sizeof(float)); + memset(fVolID, 0, fNBook * sizeof(int)); + memset(fLabel, 0, fNBook * sizeof(int)); + memset(fSolMat, 0, 4 * fNBook * sizeof(int)); + memset(fMatErr, 0, 4 * fNBook * sizeof(int)); } // } @@ -155,7 +155,7 @@ void AliAlgResFast::SetMatCorr(int id, float res, float sig) } //____________________________________________ -void AliAlgResFast::SetLabel(int ip, Int_t lab, Int_t vol) +void AliAlgResFast::SetLabel(int ip, int lab, int vol) { // set label/volid of measured volume fVolID[ip] = vol; diff --git a/Detectors/Align/src/AliAlgSens.cxx b/Detectors/Align/src/AliAlgSens.cxx index f38507cc761f0..5a37fd33df079 100644 --- a/Detectors/Align/src/AliAlgSens.cxx +++ b/Detectors/Align/src/AliAlgSens.cxx @@ -33,7 +33,7 @@ namespace align { //_________________________________________________________ -AliAlgSens::AliAlgSens(const char* name, Int_t vid, Int_t iid) +AliAlgSens::AliAlgSens(const char* name, int vid, int iid) : AliAlgVol(name, iid), fSID(0), fDet(0), fMatClAlg(), fMatClAlgReco() { // def c-tor @@ -267,7 +267,7 @@ void AliAlgSens::DPosTraDParGeom(const AliAlgPoint* pnt, double* deriv, const Al } //__________________________________________________________________ -void AliAlgSens::GetModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const Double_t* delta) const +void AliAlgSens::GetModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const double* delta) const { // prepare the sensitive module tracking2local matrix from its current T2L matrix // by applying local delta of modification of LOCAL frame: @@ -277,7 +277,7 @@ void AliAlgSens::GetModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const Double_t* } //__________________________________________________________________ -void AliAlgSens::GetModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const Double_t* delta) const +void AliAlgSens::GetModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const double* delta) const { // prepare the sensitive module tracking2local matrix from its current T2L matrix // by applying local delta of modification of TRACKING frame: @@ -293,7 +293,7 @@ void AliAlgSens::AddChild(AliAlgVol*) } //__________________________________________________________________ -Int_t AliAlgSens::Compare(const TObject* b) const +int AliAlgSens::Compare(const TObject* b) const { // compare VolIDs return GetUniqueID() < b->GetUniqueID() ? -1 : 1; @@ -421,7 +421,7 @@ void AliAlgSens::DPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int cal } //______________________________________________________ -Int_t AliAlgSens::FinalizeStat(AliAlgDOFStat* st) +int AliAlgSens::FinalizeStat(AliAlgDOFStat* st) { // finalize statistics on processed points if (st) diff --git a/Detectors/Align/src/AliAlgSensHMPID.cxx b/Detectors/Align/src/AliAlgSensHMPID.cxx index 118553fd1e0bf..9d8dc74fd7f93 100644 --- a/Detectors/Align/src/AliAlgSensHMPID.cxx +++ b/Detectors/Align/src/AliAlgSensHMPID.cxx @@ -32,7 +32,7 @@ namespace align { //_________________________________________________________ -AliAlgSensHMPID::AliAlgSensHMPID(const char* name, Int_t vid, Int_t iid, Int_t isec) +AliAlgSensHMPID::AliAlgSensHMPID(const char* name, int vid, int iid, int isec) : AliAlgSens(name, vid, iid) { // def c-tor @@ -113,8 +113,8 @@ AliAlgPoint* AliAlgSensHMPID::TrackPoint2AlgPoint(int pntId, const AliTrackPoint if (!det->GetUseErrorParam()) { // convert error TGeoHMatrix hcov; - Double_t hcovel[9]; - const Float_t* pntcov = trpArr->GetCov() + pntId * 6; // 6 elements per error matrix + double hcovel[9]; + const float* pntcov = trpArr->GetCov() + pntId * 6; // 6 elements per error matrix hcovel[0] = double(pntcov[0]); hcovel[1] = double(pntcov[1]); hcovel[2] = double(pntcov[2]); @@ -132,7 +132,7 @@ AliAlgPoint* AliAlgSensHMPID::TrackPoint2AlgPoint(int pntId, const AliTrackPoint const TGeoHMatrix& t2li = matT2L.Inverse(); hcov.MultiplyLeft(&t2li); // errors in tracking frame // - Double_t* hcovscl = hcov.GetRotationMatrix(); + double* hcovscl = hcov.GetRotationMatrix(); const double* sysE = GetAddError(); // additional syst error pnt->SetYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); } else { // errors will be calculated just before using the point in the fit, using track info diff --git a/Detectors/Align/src/AliAlgSensITS.cxx b/Detectors/Align/src/AliAlgSensITS.cxx index b9ecd021ce236..434aee2e60112 100644 --- a/Detectors/Align/src/AliAlgSensITS.cxx +++ b/Detectors/Align/src/AliAlgSensITS.cxx @@ -32,7 +32,7 @@ namespace align { //_________________________________________________________ -AliAlgSensITS::AliAlgSensITS(const char* name, Int_t vid, Int_t iid) +AliAlgSensITS::AliAlgSensITS(const char* name, int vid, int iid) : AliAlgSens(name, vid, iid) { // def c-tor @@ -94,8 +94,8 @@ AliAlgPoint* AliAlgSensITS::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr if (!det->GetUseErrorParam()) { // convert error TGeoHMatrix hcov; - Double_t hcovel[9]; - const Float_t* pntcov = trpArr->GetCov() + pntId * 6; // 6 elements per error matrix + double hcovel[9]; + const float* pntcov = trpArr->GetCov() + pntId * 6; // 6 elements per error matrix hcovel[0] = double(pntcov[0]); hcovel[1] = double(pntcov[1]); hcovel[2] = double(pntcov[2]); @@ -113,7 +113,7 @@ AliAlgPoint* AliAlgSensITS::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr const TGeoHMatrix& t2li = matT2L.Inverse(); hcov.MultiplyLeft(&t2li); // errors in tracking frame // - Double_t* hcovscl = hcov.GetRotationMatrix(); + double* hcovscl = hcov.GetRotationMatrix(); const double* sysE = GetAddError(); // additional syst error pnt->SetYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); } else { // errors will be calculated just before using the point in the fit, using track info diff --git a/Detectors/Align/src/AliAlgSensTOF.cxx b/Detectors/Align/src/AliAlgSensTOF.cxx index 5ad13d9e1a9af..bd0e27d734321 100644 --- a/Detectors/Align/src/AliAlgSensTOF.cxx +++ b/Detectors/Align/src/AliAlgSensTOF.cxx @@ -32,7 +32,7 @@ namespace align { //_________________________________________________________ -AliAlgSensTOF::AliAlgSensTOF(const char* name, Int_t vid, Int_t iid, Int_t isec) +AliAlgSensTOF::AliAlgSensTOF(const char* name, int vid, int iid, int isec) : AliAlgSens(name, vid, iid), fSector(isec) { // def c-tor @@ -138,8 +138,8 @@ AliAlgPoint* AliAlgSensTOF::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr if (!det->GetUseErrorParam()) { // convert error TGeoHMatrix hcov; - Double_t hcovel[9]; - const Float_t* pntcov = trpArr->GetCov() + pntId * 6; // 6 elements per error matrix + double hcovel[9]; + const float* pntcov = trpArr->GetCov() + pntId * 6; // 6 elements per error matrix hcovel[0] = double(pntcov[0]); hcovel[1] = double(pntcov[1]); hcovel[2] = double(pntcov[2]); @@ -157,7 +157,7 @@ AliAlgPoint* AliAlgSensTOF::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr const TGeoHMatrix& t2li = matT2L.Inverse(); hcov.MultiplyLeft(&t2li); // errors in tracking frame // - Double_t* hcovscl = hcov.GetRotationMatrix(); + double* hcovscl = hcov.GetRotationMatrix(); const double* sysE = GetAddError(); // additional syst error pnt->SetYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); } else { // errors will be calculated just before using the point in the fit, using track info diff --git a/Detectors/Align/src/AliAlgSensTPC.cxx b/Detectors/Align/src/AliAlgSensTPC.cxx index 21fdbf68babd6..54cb8dd698259 100644 --- a/Detectors/Align/src/AliAlgSensTPC.cxx +++ b/Detectors/Align/src/AliAlgSensTPC.cxx @@ -32,7 +32,7 @@ namespace align { //_________________________________________________________ -AliAlgSensTPC::AliAlgSensTPC(const char* name, Int_t vid, Int_t iid, Int_t isec) +AliAlgSensTPC::AliAlgSensTPC(const char* name, int vid, int iid, int isec) : AliAlgSens(name, vid, iid), fSector(isec) { // def c-tor @@ -113,8 +113,8 @@ AliAlgPoint* AliAlgSensTPC::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr if (!det->GetUseErrorParam()) { // convert error TGeoHMatrix hcov; - Double_t hcovel[9]; - const Float_t* pntcov = trpArr->GetCov() + pntId * 6; // 6 elements per error matrix + double hcovel[9]; + const float* pntcov = trpArr->GetCov() + pntId * 6; // 6 elements per error matrix hcovel[0] = double(pntcov[0]); hcovel[1] = double(pntcov[1]); hcovel[2] = double(pntcov[2]); @@ -132,7 +132,7 @@ AliAlgPoint* AliAlgSensTPC::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr const TGeoHMatrix& t2li = matT2L.Inverse(); hcov.MultiplyLeft(&t2li); // errors in tracking frame // - Double_t* hcovscl = hcov.GetRotationMatrix(); + double* hcovscl = hcov.GetRotationMatrix(); const double* sysE = GetAddError(); // additional syst error pnt->SetYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); } else { // errors will be calculated just before using the point in the fit, using track info diff --git a/Detectors/Align/src/AliAlgSensTRD.cxx b/Detectors/Align/src/AliAlgSensTRD.cxx index 0910e29fbf7f4..68045914f18e1 100644 --- a/Detectors/Align/src/AliAlgSensTRD.cxx +++ b/Detectors/Align/src/AliAlgSensTRD.cxx @@ -34,7 +34,7 @@ namespace align { //_________________________________________________________ -AliAlgSensTRD::AliAlgSensTRD(const char* name, Int_t vid, Int_t iid, Int_t isec) +AliAlgSensTRD::AliAlgSensTRD(const char* name, int vid, int iid, int isec) : AliAlgSens(name, vid, iid), fSector(isec) { // def c-tor @@ -151,8 +151,8 @@ AliAlgPoint* AliAlgSensTRD::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr if (!det->GetUseErrorParam()) { // convert error TGeoHMatrix hcov; - Double_t hcovel[9]; - const Float_t* pntcov = trpArr->GetCov() + pntId * 6; // 6 elements per error matrix + double hcovel[9]; + const float* pntcov = trpArr->GetCov() + pntId * 6; // 6 elements per error matrix hcovel[0] = double(pntcov[0]); hcovel[1] = double(pntcov[1]); hcovel[2] = double(pntcov[2]); @@ -170,7 +170,7 @@ AliAlgPoint* AliAlgSensTRD::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr const TGeoHMatrix& t2li = matT2L.Inverse(); hcov.MultiplyLeft(&t2li); // errors in tracking frame // - Double_t* hcovscl = hcov.GetRotationMatrix(); + double* hcovscl = hcov.GetRotationMatrix(); const double* sysE = GetAddError(); // additional syst error pnt->SetYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); } else { // errors will be calculated just before using the point in the fit, using track info diff --git a/Detectors/Align/src/AliAlgSteer.cxx b/Detectors/Align/src/AliAlgSteer.cxx index 86d4c2cf12ac5..1d53997f25c6d 100644 --- a/Detectors/Align/src/AliAlgSteer.cxx +++ b/Detectors/Align/src/AliAlgSteer.cxx @@ -64,25 +64,25 @@ namespace o2 namespace align { -const Char_t* AliAlgSteer::fgkMPDataExt = ".mille"; -const Char_t* AliAlgSteer::fgkDetectorName[AliAlgSteer::kNDetectors] = {"ITS", "TPC", "TRD", "TOF", "HMPID"}; -//const Int_t AliAlgSteer::fgkSkipLayers[AliAlgSteer::kNLrSkip] = {AliGeomManager::kPHOS1, AliGeomManager::kPHOS2, +const char* AliAlgSteer::fgkMPDataExt = ".mille"; +const char* AliAlgSteer::fgkDetectorName[AliAlgSteer::kNDetectors] = {"ITS", "TPC", "TRD", "TOF", "HMPID"}; +//const int AliAlgSteer::fgkSkipLayers[AliAlgSteer::kNLrSkip] = {AliGeomManager::kPHOS1, AliGeomManager::kPHOS2, // AliGeomManager::kMUON, AliGeomManager::kEMCAL}; TODO(milettri, shahoian): needs detector IDs previously stored in AliGeomManager -const Int_t AliAlgSteer::fgkSkipLayers[AliAlgSteer::kNLrSkip] = {0, 0, 0, 0}; // TODO(milettri, shahoian): needs AliGeomManager - remove this line after fix. +const int AliAlgSteer::fgkSkipLayers[AliAlgSteer::kNLrSkip] = {0, 0, 0, 0}; // TODO(milettri, shahoian): needs AliGeomManager - remove this line after fix. -const Char_t* AliAlgSteer::fgkStatClName[AliAlgSteer::kNStatCl] = {"Inp: ", "Acc: "}; -const Char_t* AliAlgSteer::fgkStatName[AliAlgSteer::kMaxStat] = +const char* AliAlgSteer::fgkStatClName[AliAlgSteer::kNStatCl] = {"Inp: ", "Acc: "}; +const char* AliAlgSteer::fgkStatName[AliAlgSteer::kMaxStat] = {"runs", "Ev.Coll", "Ev.Cosm", "Trc.Coll", "Trc.Cosm"}; -const Char_t* AliAlgSteer::fgkHStatName[AliAlgSteer::kNHVars] = { +const char* AliAlgSteer::fgkHStatName[AliAlgSteer::kNHVars] = { "Runs", "Ev.Inp", "Ev.VtxOK", "Tr.Inp", "Tr.2Fit", "Tr.2FitVC", "Tr.2PrMat", "Tr.2ResDer", "Tr.Stored", "Tr.Acc", "Tr.ContRes"}; //________________________________________________________________ AliAlgSteer::AliAlgSteer(const char* configMacro, int refRun) - : fNDet(0), fNDOFs(0), fRunNumber(-1), fFieldOn(kFALSE), fTracksType(kColl), fAlgTrack(0), fVtxSens(0), fConstraints(), + : fNDet(0), fNDOFs(0), fRunNumber(-1), fFieldOn(false), fTracksType(kColl), fAlgTrack(0), fVtxSens(0), fConstraints(), // fSelEventSpecii(AliRecoParam::kCosmic | AliRecoParam::kLowMult | AliRecoParam::kHighMult | AliRecoParam::kDefault), FIXME(milettri): needs AliRecoParam fSelEventSpecii(0), // FIXME(milettri): needs AliRecoParam - fCosmicSelStrict(kFALSE), + fCosmicSelStrict(false), fVtxMinCont(-1), fVtxMaxCont(-1), fVtxMinContVC(10), @@ -117,8 +117,8 @@ AliAlgSteer::AliAlgSteer(const char* configMacro, int refRun) fMPConFileName("mpConstraints.txt"), fMPSteerFileName("mpSteer.txt"), fResidFileName("mpControlRes.root"), - fMilleOutBin(kTRUE), - fDoKalmanResid(kTRUE) + fMilleOutBin(true), + fDoKalmanResid(true) // , fOutCDBPath("local://outOCDB"), @@ -135,7 +135,7 @@ AliAlgSteer::AliAlgSteer(const char* configMacro, int refRun) fRefOCDBConf("configRefOCDB.C"), fRefRunNumber(refRun), fRefOCDBLoaded(0), - fUseRecoOCDB(kTRUE) + fUseRecoOCDB(true) { // def c-tor for (int i = kNDetectors; i--;) { @@ -233,16 +233,16 @@ void AliAlgSteer::InitDetectors() det->CacheReferenceOCDB(); } // - fGloParVal = new Float_t[dofCnt]; - fGloParErr = new Float_t[dofCnt]; - fGloParLab = new Int_t[dofCnt]; - fOrderedLbl = new Int_t[dofCnt]; - fLbl2ID = new Int_t[dofCnt]; - memset(fGloParVal, 0, dofCnt * sizeof(Float_t)); - memset(fGloParErr, 0, dofCnt * sizeof(Float_t)); - memset(fGloParLab, 0, dofCnt * sizeof(Int_t)); - memset(fOrderedLbl, 0, dofCnt * sizeof(Int_t)); - memset(fLbl2ID, 0, dofCnt * sizeof(Int_t)); + fGloParVal = new float[dofCnt]; + fGloParErr = new float[dofCnt]; + fGloParLab = new int[dofCnt]; + fOrderedLbl = new int[dofCnt]; + fLbl2ID = new int[dofCnt]; + memset(fGloParVal, 0, dofCnt * sizeof(float)); + memset(fGloParErr, 0, dofCnt * sizeof(float)); + memset(fGloParLab, 0, dofCnt * sizeof(int)); + memset(fOrderedLbl, 0, dofCnt * sizeof(int)); + memset(fLbl2ID, 0, dofCnt * sizeof(int)); AssignDOFs(); LOG(INFO) << "Booked " << dofCnt << " global parameters"; // @@ -311,14 +311,14 @@ void AliAlgSteer::AssignDOFs() LOG(ERROR) << "Recalculated NDOFs=" << fNDOFs << " not equal to saved NDOFs=" << ndfOld; // // build Lbl <-> parID table - Sort(fNDOFs, fGloParLab, fLbl2ID, kFALSE); // sort in increasing order + Sort(fNDOFs, fGloParLab, fLbl2ID, false); // sort in increasing order for (int i = fNDOFs; i--;) fOrderedLbl[i] = fGloParLab[fLbl2ID[i]]; // } //________________________________________________________________ -void AliAlgSteer::AddDetector(UInt_t id, AliAlgDet* det) +void AliAlgSteer::AddDetector(uint32_t id, AliAlgDet* det) { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; // add detector participating in the alignment, optionally constructed externally @@ -368,7 +368,7 @@ void AliAlgSteer::AddDetector(AliAlgDet* det) } //_________________________________________________________ -Bool_t AliAlgSteer::CheckDetectorPattern(UInt_t patt) const +bool AliAlgSteer::CheckDetectorPattern(uint32_t patt) const { //validate detector pattern return ((patt & fObligatoryDetPattern[fTracksType]) == @@ -377,7 +377,7 @@ Bool_t AliAlgSteer::CheckDetectorPattern(UInt_t patt) const } //_________________________________________________________ -Bool_t AliAlgSteer::CheckDetectorPoints(const int* npsel) const +bool AliAlgSteer::CheckDetectorPoints(const int* npsel) const { //validate detectors pattern according to number of selected points int ndOK = 0; @@ -387,7 +387,7 @@ Bool_t AliAlgSteer::CheckDetectorPoints(const int* npsel) const continue; if (npsel[idt] < det->GetNPointsSel(fTracksType)) { if (det->IsObligatory(fTracksType)) - return kFALSE; + return false; continue; } ndOK++; @@ -397,11 +397,11 @@ Bool_t AliAlgSteer::CheckDetectorPoints(const int* npsel) const //FIXME(milettri): needs AliESDtrack ////_________________________________________________________ -//UInt_t AliAlgSteer::AcceptTrack(const AliESDtrack* esdTr, Bool_t strict) const +//uint32_t AliAlgSteer::AcceptTrack(const AliESDtrack* esdTr, bool strict) const //{ // // decide if the track should be processed // AliAlgDet* det = 0; -// UInt_t detAcc = 0; +// uint32_t detAcc = 0; // if (fFieldOn && esdTr->Pt() < fPtMin[fTracksType]) // return 0; // if (Abs(esdTr->Eta()) > fEtaMax[fTracksType]) @@ -427,10 +427,10 @@ Bool_t AliAlgSteer::CheckDetectorPoints(const int* npsel) const //FIXME(milettri): needs AliESDtrack ////_________________________________________________________ -//UInt_t AliAlgSteer::AcceptTrackCosmic(const AliESDtrack* esdPairCosm[kNCosmLegs]) const +//uint32_t AliAlgSteer::AcceptTrackCosmic(const AliESDtrack* esdPairCosm[kNCosmLegs]) const //{ // // decide if the pair of tracks making cosmic track should be processed -// UInt_t detAcc = 0, detAccLeg; +// uint32_t detAcc = 0, detAccLeg; // for (int i = kNCosmLegs; i--;) { // detAccLeg = AcceptTrack(esdPairCosm[i], fCosmicSelStrict); // missing obligatory detectors in one leg might be allowed // if (!detAccLeg) @@ -463,7 +463,7 @@ Bool_t AliAlgSteer::CheckDetectorPoints(const int* npsel) const //FIXME(milettri): needs AliESDEvent ////_________________________________________________________ -//Bool_t AliAlgSteer::ProcessEvent(const AliESDEvent* esdEv) +//bool AliAlgSteer::ProcessEvent(const AliESDEvent* esdEv) //{ // // process event // const int kProcStatFreq = 100; @@ -484,7 +484,7 @@ Bool_t AliAlgSteer::CheckDetectorPoints(const int* npsel) const //#if DEBUG > 2 // LOG(INFO) << "Reject: specie does not match, allowed " << fSelEventSpecii; //#endif -// return kFALSE; +// return false; // } // // // SetCosmic(esdEv->GetEventSpecie() == AliRecoParam::kCosmic || @@ -498,7 +498,7 @@ Bool_t AliAlgSteer::CheckDetectorPoints(const int* npsel) const // // // SetFieldOn(Abs(esdEv->GetMagneticField()) > kAlmost0Field); // if (!IsCosmic() && !CheckSetVertex(esdEv->GetPrimaryVertexTracks())) -// return kFALSE; +// return false; // FillStatHisto(kEvVtx); // // // int ntr = 0, accTr = 0; @@ -538,12 +538,12 @@ Bool_t AliAlgSteer::CheckDetectorPoints(const int* npsel) const // if (accTr) { // LOG(INFO) << "Processed event " << esdEv->GetEventNumberInFile() << " of ev.specie " << esdEv->GetEventSpecie() << " -> Accepted: " << accTr << " of " << ntr << " tracks"; // } -// return kTRUE; +// return true; //} //FIXME(milettri): needs AliESDtrack //_________________________________________________________ -//Bool_t AliAlgSteer::ProcessTrack(const AliESDtrack* esdTr) +//bool AliAlgSteer::ProcessTrack(const AliESDtrack* esdTr) //{ // // process single track // // @@ -554,14 +554,14 @@ Bool_t AliAlgSteer::CheckDetectorPoints(const int* npsel) const // int nPnt = 0; // const AliESDfriendTrack* trF = esdTr->GetFriendTrack(); // if (!trF) -// return kFALSE; +// return false; // const AliTrackPointArray* trPoints = trF->GetTrackPointArray(); // if (!trPoints || (nPnt = trPoints->GetNPoints()) < 1) -// return kFALSE; +// return false; // // -// UInt_t detAcc = AcceptTrack(esdTr); +// uint32_t detAcc = AcceptTrack(esdTr); // if (!detAcc) -// return kFALSE; +// return false; // // // ResetDetectors(); // fAlgTrack->Clear(); @@ -575,17 +575,17 @@ Bool_t AliAlgSteer::CheckDetectorPoints(const int* npsel) const // if (det->ProcessPoints(esdTr, fAlgTrack) < det->GetNPointsSel(kColl)) { // detAcc &= ~(0x1 << idet); // did not survive, suppress detector in the track // if (det->IsObligatory(kColl)) -// return kFALSE; +// return false; // } // if (NumberOfBitsSet(detAcc) < fMinDetAcc[kColl]) -// return kFALSE; // abandon track +// return false; // abandon track // } // // // if (fAlgTrack->GetNPoints() < GetMinPoints()) -// return kFALSE; +// return false; // // fill needed points (tracking frame) in the fAlgTrack -// fRefPoint->SetContainsMeasurement(kFALSE); -// fRefPoint->SetContainsMaterial(kFALSE); +// fRefPoint->SetContainsMeasurement(false); +// fRefPoint->SetContainsMaterial(false); // fAlgTrack->AddPoint(fRefPoint); // reference point which the track will refer to // // // fAlgTrack->CopyFrom(esdTr); @@ -613,61 +613,61 @@ Bool_t AliAlgSteer::CheckDetectorPoints(const int* npsel) const // // // FillStatHisto(kTrackFitInp); // if (!fAlgTrack->IniFit()) -// return kFALSE; +// return false; // FillStatHisto(kTrackProcMatInp); // if (!fAlgTrack->ProcessMaterials()) -// return kFALSE; +// return false; // fAlgTrack->DefineDOFs(); // // // FillStatHisto(kTrackResDerInp); // if (!fAlgTrack->CalcResidDeriv()) -// return kFALSE; +// return false; // // // if (!StoreProcessedTrack(fMPOutType & ~kContR)) -// return kFALSE; // store derivatives for MP +// return false; // store derivatives for MP // // // if (GetProduceControlRes() && // need control residuals, ignore selection fraction if this is the // (fMPOutType == kContR || gRandom->Rndm() < fControlFrac)) { // output requested // if (!TestLocalSolution() || !StoreProcessedTrack(kContR)) -// return kFALSE; +// return false; // } // // // FillStatHisto(kTrackStore); // // // fStat[kAccStat][kTrackColl]++; // // -// return kTRUE; +// return true; //} //FIXME(milettri): needs AliESDVertex ////_________________________________________________________ -//Bool_t AliAlgSteer::CheckSetVertex(const AliESDVertex* vtx) +//bool AliAlgSteer::CheckSetVertex(const AliESDVertex* vtx) //{ // // vertex selection/constraint check // if (!vtx) { // fVertex = 0; -// return kTRUE; +// return true; // } // int ncont = vtx->GetNContributors(); // if (fVtxMinCont > 0 && fVtxMinCont > ncont) { //#if DEBUG > 2 // LOG(INFO) << "Rejecting event with " << % d << " vertex contributors (min " << % d << " asked)", ncont, fVtxMinCont); //#endif -// return kFALSE; +// return false; // } // if (fVtxMaxCont > 0 && ncont > fVtxMaxCont) { //#if DEBUG > 2 // LOG(INFO) << "Rejecting event with " << % d << " vertex contributors (max " << % d << " asked)", ncont, fVtxMaxCont); //#endif -// return kFALSE; +// return false; // } // fVertex = (ncont >= fVtxMinContVC) ? vtx : 0; // use vertex as a constraint -// return kTRUE; +// return true; //} //FIXME(milettri): needs AliESDCosmicTrack ////_________________________________________________________ -//Bool_t AliAlgSteer::ProcessTrack(const AliESDCosmicTrack* cosmTr) +//bool AliAlgSteer::ProcessTrack(const AliESDCosmicTrack* cosmTr) //{ // // process single cosmic track // // @@ -681,30 +681,30 @@ Bool_t AliAlgSteer::CheckDetectorPoints(const int* npsel) const // fESDEvent->GetTrack(leg == kCosmLow ? cosmTr->GetESDLowerTrackIndex() : cosmTr->GetESDUpperTrackIndex()); // const AliESDfriendTrack* trF = esdTr->GetFriendTrack(); // if (!trF) -// return kFALSE; +// return false; // const AliTrackPointArray* trPoints = trF->GetTrackPointArray(); // if (!trPoints || (nPnt += trPoints->GetNPoints()) < 1) -// return kFALSE; +// return false; // // // fESDTrack[leg] = esdTr; // } // // -// UInt_t detAcc = AcceptTrackCosmic(fESDTrack); +// uint32_t detAcc = AcceptTrackCosmic(fESDTrack); // if (!detAcc) -// return kFALSE; +// return false; // // // ResetDetectors(); // fAlgTrack->Clear(); -// fAlgTrack->SetCosmic(kTRUE); +// fAlgTrack->SetCosmic(true); // // // // process the track points for each detector, // // fill needed points (tracking frame) in the fAlgTrack -// fRefPoint->SetContainsMeasurement(kFALSE); -// fRefPoint->SetContainsMaterial(kFALSE); +// fRefPoint->SetContainsMeasurement(false); +// fRefPoint->SetContainsMaterial(false); // fAlgTrack->AddPoint(fRefPoint); // reference point which the track will refer to // // // AliAlgDet* det = 0; -// Int_t npsel[kNDetectors] = {0}; +// int npsel[kNDetectors] = {0}; // for (int nPleg = 0, leg = kNCosmLegs; leg--;) { // for (int idet = 0; idet < kNDetectors; idet++) { // if (!(detAcc & (0x1 << idet))) @@ -715,16 +715,16 @@ Bool_t AliAlgSteer::CheckDetectorPoints(const int* npsel) const // int np = det->ProcessPoints(fESDTrack[leg], fAlgTrack, leg == kCosmUp); // if (np < det->GetNPointsSel(kCosm) && fCosmicSelStrict && // det->IsObligatory(kCosm)) -// return kFALSE; +// return false; // npsel[idet] += np; // nPleg += np; // } // if (nPleg < GetMinPoints()) -// return kFALSE; +// return false; // } // // last check on legs-combined patter // if (!CheckDetectorPoints(npsel)) -// return kFALSE; +// return false; // // // fAlgTrack->CopyFrom(cosmTr); // if (!GetFieldOn()) @@ -746,36 +746,36 @@ Bool_t AliAlgSteer::CheckDetectorPoints(const int* npsel) const // // // FillStatHisto(kTrackFitInp); // if (!fAlgTrack->IniFit()) -// return kFALSE; +// return false; // // // FillStatHisto(kTrackProcMatInp); // if (!fAlgTrack->ProcessMaterials()) -// return kFALSE; +// return false; // fAlgTrack->DefineDOFs(); // // // FillStatHisto(kTrackResDerInp); // if (!fAlgTrack->CalcResidDeriv()) -// return kFALSE; +// return false; // // // if (!StoreProcessedTrack(fMPOutType & ~kContR)) -// return kFALSE; // store derivatives for MP +// return false; // store derivatives for MP // // // if (GetProduceControlRes() && // need control residuals, ignore selection fraction if this is the // (fMPOutType == kContR || gRandom->Rndm() < fControlFrac)) { // output requested // if (!TestLocalSolution() || !StoreProcessedTrack(kContR)) -// return kFALSE; +// return false; // } // // // FillStatHisto(kTrackStore); // fStat[kAccStat][kTrackCosm]++; -// return kTRUE; +// return true; //} //_________________________________________________________ -Bool_t AliAlgSteer::StoreProcessedTrack(Int_t what) +bool AliAlgSteer::StoreProcessedTrack(int what) { // write alignment track - Bool_t res = kTRUE; + bool res = true; if ((what & kMille)) res &= FillMilleData(); if ((what & kMPRec)) @@ -787,7 +787,7 @@ Bool_t AliAlgSteer::StoreProcessedTrack(Int_t what) } //_________________________________________________________ -Bool_t AliAlgSteer::FillMilleData() +bool AliAlgSteer::FillMilleData() { // store MP2 data in Mille format if (!fMille) { @@ -799,7 +799,7 @@ Bool_t AliAlgSteer::FillMilleData() // if (!fAlgTrack->GetDerivDone()) { LOG(ERROR) << "Track derivatives are not yet evaluated"; - return kFALSE; + return false; } int np(fAlgTrack->GetNPoints()), nDGloTot(0); // total number global derivatives stored int nParETP(fAlgTrack->GetNLocExtPar()); // numnber of local parameters for reference track param @@ -876,14 +876,14 @@ Bool_t AliAlgSteer::FillMilleData() if (!nDGloTot) { LOG(INFO) << "Track does not depend on free global parameters, discard"; fMille->kill(); - return kFALSE; + return false; } fMille->end(); // store the record - return kTRUE; + return true; } //_________________________________________________________ -Bool_t AliAlgSteer::FillMPRecData() +bool AliAlgSteer::FillMPRecData() { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs AliESDEvent @@ -893,19 +893,19 @@ Bool_t AliAlgSteer::FillMPRecData() // // // fMPRecord->Clear(); // if (!fMPRecord->FillTrack(fAlgTrack, fGloParLab)) - // return kFALSE; + // return false; // fMPRecord->SetRun(fRunNumber); // fMPRecord->SetTimeStamp(fESDEvent->GetTimeStamp()); - // UInt_t tID = 0xffff & UInt_t(fESDTrack[0]->GetID()); + // uint32_t tID = 0xffff & uint(fESDTrack[0]->GetID()); // if (IsCosmic()) - // tID |= (0xffff & UInt_t(fESDTrack[1]->GetID())) << 16; + // tID |= (0xffff & uint(fESDTrack[1]->GetID())) << 16; // fMPRecord->SetTrackID(tID); // fMPRecTree->Fill(); - return kTRUE; + return true; } //_________________________________________________________ -Bool_t AliAlgSteer::FillControlData() +bool AliAlgSteer::FillControlData() { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs AliESDEvent @@ -916,27 +916,27 @@ Bool_t AliAlgSteer::FillControlData() // int nps, np = fAlgTrack->GetNPoints(); // nps = (!fRefPoint->ContainsMeasurement()) ? np - 1 : np; // ref point is dummy? // if (nps < 0) - // return kTRUE; + // return true; // // // fCResid->Clear(); // if (!fCResid->FillTrack(fAlgTrack, fDoKalmanResid)) - // return kFALSE; + // return false; // fCResid->SetRun(fRunNumber); // fCResid->SetTimeStamp(fESDEvent->GetTimeStamp()); // fCResid->SetBz(fESDEvent->GetMagneticField()); - // UInt_t tID = 0xffff & UInt_t(fESDTrack[0]->GetID()); + // uint32_t tID = 0xffff & uint(fESDTrack[0]->GetID()); // if (IsCosmic()) - // tID |= (0xffff & UInt_t(fESDTrack[1]->GetID())) << 16; + // tID |= (0xffff & uint(fESDTrack[1]->GetID())) << 16; // fCResid->SetTrackID(tID); // // // fResidTree->Fill(); // FillStatHisto(kTrackControl); // // - return kTRUE; + return true; } //_________________________________________________________ -void AliAlgSteer::SetRunNumber(Int_t run) +void AliAlgSteer::SetRunNumber(int run) { if (run == fRunNumber) return; // nothing to do @@ -945,7 +945,7 @@ void AliAlgSteer::SetRunNumber(Int_t run) } //_________________________________________________________ -void AliAlgSteer::AcknowledgeNewRun(Int_t run) +void AliAlgSteer::AcknowledgeNewRun(int run) { LOG(WARNING) << __PRETTY_FUNCTION__ << " yet incomplete"; @@ -995,7 +995,7 @@ void AliAlgSteer::AcknowledgeNewRun(Int_t run) // FIXME(milettri): needs OCDB ////_________________________________________________________ -//Bool_t AliAlgSteer::LoadRecoTimeOCDB() +//bool AliAlgSteer::LoadRecoTimeOCDB() //{ // // Load OCDB paths used for the reconstruction of data being processed // // In order to avoid unnecessary uploads, the objects are not actually @@ -1008,7 +1008,7 @@ void AliAlgSteer::AcknowledgeNewRun(Int_t run) // LOG(INFO) << "Executing reco-time OCDB setup macro " << fRecoOCDBConf.Data(); // gROOT->ProcessLine(Form(".x %s(%d)", fRecoOCDBConf.Data(), fRunNumber)); // if (AliCDBManager::Instance()->IsDefaultStorageSet()) -// return kTRUE; +// return true; // LOG(FATAL) << "macro " << fRecoOCDBConf.Data() << " failed to configure reco-time OCDB"; // } else // LOG(WARNING) << "No reco-time OCDB config macro" << fRecoOCDBConf.Data() << " is found, will use ESD:UserInfo"; @@ -1032,7 +1032,7 @@ void AliAlgSteer::AcknowledgeNewRun(Int_t run) //} //_________________________________________________________ -AliAlgDet* AliAlgSteer::GetDetectorByVolID(Int_t vid) const +AliAlgDet* AliAlgSteer::GetDetectorByVolID(int vid) const { // get detector by sensor volid for (int i = fNDet; i--;) @@ -1068,7 +1068,7 @@ void AliAlgSteer::Print(const Option_t* opt) const // event selection printf("\n"); printf("%-40s:\t", "Alowed event specii mask"); - PrintBits((ULong64_t)fSelEventSpecii, 5); + PrintBits((uint64_t)fSelEventSpecii, 5); printf("\n"); printf("%-40s:\t%d/%d\n", "Min points per collisions track (BOff/ON)", fMinPoints[kColl][0], fMinPoints[kColl][1]); @@ -1144,7 +1144,7 @@ void AliAlgSteer::ResetDetectors() } //____________________________________________ -Bool_t AliAlgSteer::TestLocalSolution() +bool AliAlgSteer::TestLocalSolution() { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs AliSymMatrix @@ -1152,13 +1152,13 @@ Bool_t AliAlgSteer::TestLocalSolution() // TVectorD rhs; // AliSymMatrix* mat = BuildMatrix(rhs); // if (!mat) - // return kFALSE; + // return false; // // mat->Print("long data"); // // rhs.Print(); // TVectorD vsl(rhs); - // if (!mat->SolveChol(rhs, vsl, kTRUE)) { + // if (!mat->SolveChol(rhs, vsl, true)) { // delete mat; - // return kFALSE; + // return false; // } // // // /* @@ -1190,7 +1190,7 @@ Bool_t AliAlgSteer::TestLocalSolution() // fAlgTrack->CalcResiduals(); // delete mat; // // - return kTRUE; + return true; } //FIXME(milettri): needs AliSymMatrix @@ -1396,7 +1396,7 @@ void AliAlgSteer::SetOutCDBPath(const char* name) } //____________________________________________ -void AliAlgSteer::SetObligatoryDetector(Int_t detID, Int_t trtype, Bool_t v) +void AliAlgSteer::SetObligatoryDetector(int detID, int trtype, bool v) { // mark detector presence obligatory in the track of given type AliAlgDet* det = GetDetectorByDetID(detID); @@ -1413,7 +1413,7 @@ void AliAlgSteer::SetObligatoryDetector(Int_t detID, Int_t trtype, Bool_t v) } //____________________________________________ -Bool_t AliAlgSteer::AddVertexConstraint() +bool AliAlgSteer::AddVertexConstraint() { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs AliESDtrack @@ -1421,28 +1421,28 @@ Bool_t AliAlgSteer::AddVertexConstraint() // // // const AliESDtrack* esdTr = fESDTrack[0]; // if (!fVertex || !esdTr) - // return kFALSE; + // return false; // // // if (esdTr->GetNcls(0) < fMinITSClforVC) - // return kFALSE; // not enough ITS clusters + // return false; // not enough ITS clusters // if (!AliAlgDetITS::CheckHitPattern(esdTr, fITSPattforVC)) - // return kFALSE; + // return false; // // // AliExternalTrackParam trc = *esdTr; - // Double_t dz[2], dzCov[3]; + // double dz[2], dzCov[3]; // if (!trc.PropagateToDCA(fVertex, AliTrackerBase::GetBz(), 2 * fMaxDCAforVC[0], dz, dzCov)) - // return kFALSE; + // return false; // // // // check if primary candidate // if (Abs(dz[0]) > fMaxDCAforVC[0] || Abs(dz[1]) > fMaxDCAforVC[1]) - // return kFALSE; - // Double_t covar[6]; + // return false; + // double covar[6]; // fVertex->GetCovMatrix(covar); - // Double_t p[2] = {trc.GetParameter()[0] - dz[0], trc.GetParameter()[1] - dz[1]}; - // Double_t c[3] = {0.5 * (covar[0] + covar[2]), 0., covar[5]}; - // Double_t chi2 = trc.GetPredictedChi2(p, c); + // double p[2] = {trc.GetParameter()[0] - dz[0], trc.GetParameter()[1] - dz[1]}; + // double c[3] = {0.5 * (covar[0] + covar[2]), 0., covar[5]}; + // double chi2 = trc.GetPredictedChi2(p, c); // if (chi2 > fMaxChi2forVC) - // return kFALSE; + // return false; // // // // assing measured vertex rotated to VtxSens frame as reference point // double xyz[3], xyzT[3]; @@ -1456,10 +1456,10 @@ Bool_t AliAlgSteer::AddVertexConstraint() // fRefPoint->SetAlphaSens(fVtxSens->GetAlpTracking()); // fRefPoint->SetXYZTracking(xyzT); // fRefPoint->SetYZErrTracking(c); - // fRefPoint->SetContainsMeasurement(kTRUE); + // fRefPoint->SetContainsMeasurement(true); // fRefPoint->Init(); // // - return kTRUE; + return true; } //FIXME(milettri): needs OCDB @@ -1490,7 +1490,7 @@ Bool_t AliAlgSteer::AddVertexConstraint() //FIXME(milettri): needs OCDB ////______________________________________________________ -//Bool_t AliAlgSteer::LoadRefOCDB() +//bool AliAlgSteer::LoadRefOCDB() //{ // // setup OCDB whose objects will be used as a reference with respect to which the // // alignment/calibration will prodice its corrections. @@ -1509,7 +1509,7 @@ Bool_t AliAlgSteer::AddVertexConstraint() // gROOT->ProcessLine(Form(".x %s", fRefOCDBConf.Data())); // } else { // LOG(WARNING) << "No reference OCDB config macro "<SetRaw(kTRUE); +// man->SetRaw(true); // man->SetRun(AliCDBRunRange::Infinity()); // } // // @@ -1530,7 +1530,7 @@ Bool_t AliAlgSteer::AddVertexConstraint() // // // fRefOCDBLoaded++; // // -// return kTRUE; +// return true; //} //________________________________________________________ @@ -1560,7 +1560,7 @@ AliAlgVol* AliAlgSteer::GetVolOfDOFID(int id) const } //________________________________________________________ -void AliAlgSteer::Terminate(Bool_t doStat) +void AliAlgSteer::Terminate(bool doStat) { // finalize processing if (fRunNumber > 0) @@ -1583,7 +1583,7 @@ void AliAlgSteer::Terminate(Bool_t doStat) } //________________________________________________________ -Char_t* AliAlgSteer::GetDOFLabelTxt(int idf) const +char* AliAlgSteer::GetDOFLabelTxt(int idf) const { // get DOF full label AliAlgVol* vol = GetVolOfDOFID(idf); @@ -1670,7 +1670,7 @@ void AliAlgSteer::GenPedeSteerFile(const Option_t* opt) const } //___________________________________________________________ -Bool_t AliAlgSteer::ReadParameters(const char* parfile, Bool_t useErrors) +bool AliAlgSteer::ReadParameters(const char* parfile, bool useErrors) { // read parameters file (millepede output) if (fNDOFs < 1 || !fGloParVal || !fGloParErr) { @@ -1679,7 +1679,7 @@ Bool_t AliAlgSteer::ReadParameters(const char* parfile, Bool_t useErrors) ifstream inpf(parfile); if (!inpf.good()) { printf("Failed on input filename %s\n", parfile); - return kFALSE; + return false; } memset(fGloParVal, 0, fNDOFs * sizeof(float)); if (useErrors) @@ -1692,7 +1692,7 @@ Bool_t AliAlgSteer::ReadParameters(const char* parfile, Bool_t useErrors) if (!fline.BeginsWith("parameter")) { LOG(ERROR) << "First line is not parameter keyword:\n" << fline.Data(); - return kFALSE; + return false; } double v0, v1, v2; int lab, asg = 0, asg0 = 0; @@ -1705,14 +1705,14 @@ Bool_t AliAlgSteer::ReadParameters(const char* parfile, Bool_t useErrors) if (nr < 3) { LOG(ERROR) << "Expected to read at least 3 numbers, got " << nr << ", this is NOT milleped output"; LOG(ERROR) << "line (" << cnt << ") was:\n " << fline.Data(); - return kFALSE; + return false; } if (nr == 3) asg0++; int parID = Label2ParID(lab); if (parID < 0 || parID >= fNDOFs) { LOG(ERROR) << "Invalid label " << lab << " at line " << cnt << " -> ParID=" << parID; - return kFALSE; + return false; } fGloParVal[parID] = -v0; if (useErrors) @@ -1722,7 +1722,7 @@ Bool_t AliAlgSteer::ReadParameters(const char* parfile, Bool_t useErrors) }; LOG(INFO) << "Read " << cnt << " lines, assigned " << asg << " values, " << asg0 << " dummy"; // - return kTRUE; + return true; } //______________________________________________________ @@ -1744,7 +1744,7 @@ void AliAlgSteer::CheckConstraints(const char* params) } //___________________________________________________________ -void AliAlgSteer::MPRec2Mille(const char* mprecfile, const char* millefile, Bool_t bindata) +void AliAlgSteer::MPRec2Mille(const char* mprecfile, const char* millefile, bool bindata) { // converts MPRecord tree to millepede binary format TFile* flmpr = TFile::Open(mprecfile); @@ -1764,7 +1764,7 @@ void AliAlgSteer::MPRec2Mille(const char* mprecfile, const char* millefile, Bool } //___________________________________________________________ -void AliAlgSteer::MPRec2Mille(TTree* mprTree, const char* millefile, Bool_t bindata) +void AliAlgSteer::MPRec2Mille(TTree* mprTree, const char* millefile, bool bindata) { // converts MPRecord tree to millepede binary format // @@ -1847,7 +1847,7 @@ void AliAlgSteer::PrintLabels() const } //____________________________________________________________ -Int_t AliAlgSteer::Label2ParID(int lab) const +int AliAlgSteer::Label2ParID(int lab) const { // convert Mille label to ParID (slow) int ind = FindKeyIndex(lab, fOrderedLbl, fNDOFs); @@ -1883,7 +1883,7 @@ void AliAlgSteer::WritePedeConstraints() const } //____________________________________________________________ -void AliAlgSteer::FixLowStatFromDOFStat(Int_t thresh) +void AliAlgSteer::FixLowStatFromDOFStat(int thresh) { // fix DOFs having stat below threshold // @@ -1941,8 +1941,8 @@ void AliAlgSteer::LoadStat(const char* flname) } //______________________________________________ -void AliAlgSteer::CheckSol(TTree* mpRecTree, Bool_t store, - Bool_t verbose, Bool_t loc, const char* outName) +void AliAlgSteer::CheckSol(TTree* mpRecTree, bool store, + bool verbose, bool loc, const char* outName) { // do fast check of pede solution with MPRecord tree AliAlgResFast* rLG = store ? new AliAlgResFast() : 0; @@ -1994,9 +1994,9 @@ void AliAlgSteer::CheckSol(TTree* mpRecTree, Bool_t store, } //______________________________________________ -Bool_t AliAlgSteer::CheckSol(AliAlgMPRecord* rec, - AliAlgResFast* rLG, AliAlgResFast* rL, - Bool_t verbose, Bool_t loc) +bool AliAlgSteer::CheckSol(AliAlgMPRecord* rec, + AliAlgResFast* rLG, AliAlgResFast* rL, + bool verbose, bool loc) { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs AliSymMatrix @@ -2005,7 +2005,7 @@ Bool_t AliAlgSteer::CheckSol(AliAlgMPRecord* rec, // // neglecting global corrections // // // if (rL) - // loc = kTRUE; // if local sol. tree asked, always evaluate it + // loc = true; // if local sol. tree asked, always evaluate it // // // int nres = rec->GetNResid(); // // @@ -2059,8 +2059,8 @@ Bool_t AliAlgSteer::CheckSol(AliAlgMPRecord* rec, // float chi2Ini = 0, chi2L = 0, chi2LG = 0; // // // // residuals, accounting for global solution - // double* resid = new Double_t[nres]; - // int* volID = new Int_t[nres]; + // double* resid = new double[nres]; + // int* volID = new int[nres]; // for (int irs = 0; irs < nres; irs++) { // double resOr = rec->GetResid(irs); // resid[irs] = resOr; @@ -2117,12 +2117,12 @@ Bool_t AliAlgSteer::CheckSol(AliAlgMPRecord* rec, // TVectorD vecSol(nvloc); // TVectorD vecSolG(nvloc); // // - // if (!matpG->SolveChol(*vecpG, vecSolG, kFALSE)) { + // if (!matpG->SolveChol(*vecpG, vecSolG, false)) { // LOG(INFO) << "Failed to solve track corrected for globals"; // delete matpG; // matpG = 0; // } else if (loc) { // solution with local correction only - // if (!matpG->SolveChol(*vecp, vecSol, kFALSE)) { + // if (!matpG->SolveChol(*vecp, vecSol, false)) { // LOG(INFO) << "Failed to solve track corrected for globals"; // delete matpG; // matpG = 0; @@ -2137,7 +2137,7 @@ Bool_t AliAlgSteer::CheckSol(AliAlgMPRecord* rec, // rLG->Clear(); // if (rL) // rL->Clear(); - // return kFALSE; + // return false; // } // // check // recDGlo = rec->GetArrGlo(); @@ -2151,14 +2151,14 @@ Bool_t AliAlgSteer::CheckSol(AliAlgMPRecord* rec, // for (int i = 0; i < nExtP; i++) // loc ? printf("%+.3e/%+.3e ", vecSol[i], vecSolG[i]) : printf("%+.3e ", vecSolG[i]); // printf("\n"); - // Bool_t nln = kTRUE; + // bool nln = true; // int cntL = 0; // for (int i = nExtP; i < nvloc; i++) { - // nln = kTRUE; + // nln = true; // loc ? printf("%+.3e/%+.3e ", vecSol[i], vecSolG[i]) : printf("%+.3e ", vecSolG[i]); // if (((++cntL) % 4) == 0) { // printf("\n"); - // nln = kFALSE; + // nln = false; // } // } // if (!nln) @@ -2255,7 +2255,7 @@ Bool_t AliAlgSteer::CheckSol(AliAlgMPRecord* rec, // // // delete[] resid; // delete[] volID; - return kTRUE; + return true; } //______________________________________________ diff --git a/Detectors/Align/src/AliAlgTrack.cxx b/Detectors/Align/src/AliAlgTrack.cxx index 133bea32b9690..74fbe7c699c65 100644 --- a/Detectors/Align/src/AliAlgTrack.cxx +++ b/Detectors/Align/src/AliAlgTrack.cxx @@ -34,9 +34,9 @@ namespace align // RS: this is not good: we define constants outside the class, but it is to // bypass the CINT limitations on static arrays initializations -const Int_t kRichardsonOrd = 1; // Order of Richardson extrapolation for derivative (min=1) -const Int_t kRichardsonN = kRichardsonOrd + 1; // N of 2-point symmetric derivatives needed for requested order -const Int_t kNRDClones = kRichardsonN * 2; // number of variations for derivative of requested order +const int kRichardsonOrd = 1; // Order of Richardson extrapolation for derivative (min=1) +const int kRichardsonN = kRichardsonOrd + 1; // N of 2-point symmetric derivatives needed for requested order +const int kNRDClones = kRichardsonN * 2; // number of variations for derivative of requested order //____________________________________________________________________________ AliAlgTrack::AliAlgTrack() : TrackParametrizationWithError(), TObject(), fNLocPar(0), fNLocExtPar(0), fNGloPar(0), fNDF(0), fInnerPointID(0) @@ -65,7 +65,7 @@ AliAlgTrack::AliAlgTrack() : TrackParametrizationWithError(), TObject(), fDResDLocA[i] = 0; fDResDGloA[i] = 0; } - fNeedInv[0] = fNeedInv[1] = kFALSE; + fNeedInv[0] = fNeedInv[1] = false; // } @@ -85,7 +85,7 @@ void AliAlgTrack::Clear(Option_t*) fChi2 = fChi2CosmUp = fChi2CosmDn = fChi2Ini = 0; fNDF = 0; fInnerPointID = -1; - fNeedInv[0] = fNeedInv[1] = kFALSE; + fNeedInv[0] = fNeedInv[1] = false; fNLocPar = fNLocExtPar = fNGloPar = 0; // } @@ -145,12 +145,12 @@ void AliAlgTrack::DefineDOFs() fDResDLocA[i] = fDResDLoc[i].GetArray(); } // - // memcpy(fLocParA,GetParameter(),fNLocExtPar*sizeof(Double_t)); - memset(fLocParA, 0, fNLocExtPar * sizeof(Double_t)); + // memcpy(fLocParA,GetParameter(),fNLocExtPar*sizeof(double)); + memset(fLocParA, 0, fNLocExtPar * sizeof(double)); } //______________________________________________________ -Bool_t AliAlgTrack::CalcResidDeriv(Double_t* params) +bool AliAlgTrack::CalcResidDeriv(double* params) { // Propagate for given local params and calculate residuals and their derivatives. // The 1st 4 or 5 elements of params vector should be the reference trackParam_t @@ -176,7 +176,7 @@ Bool_t AliAlgTrack::CalcResidDeriv(Double_t* params) #if DEBUG > 3 LOG(warn) << "Failed on derivatives calculation 0"; #endif - return kFALSE; + return false; } // if (IsCosmic()) { // cosmic upper leg @@ -188,11 +188,11 @@ Bool_t AliAlgTrack::CalcResidDeriv(Double_t* params) } // SetDerivDone(); - return kTRUE; + return true; } //______________________________________________________ -Bool_t AliAlgTrack::CalcResidDeriv(double* extendedParams, Bool_t invert, int pFrom, int pTo) +bool AliAlgTrack::CalcResidDeriv(double* extendedParams, bool invert, int pFrom, int pTo) { // Calculate derivatives of residuals vs params for points pFrom to pT. For cosmic upper leg // track parameter may require inversion. @@ -231,7 +231,7 @@ Bool_t AliAlgTrack::CalcResidDeriv(double* extendedParams, Bool_t invert, int pF // 1) derivative wrt trackParam_t parameters for (int ipar = fNLocExtPar; ipar--;) { - SetParams(probD, kNRDClones, getX(), getAlpha(), extendedParams, kTRUE); + SetParams(probD, kNRDClones, getX(), getAlpha(), extendedParams, true); if (invert) for (int ic = kNRDClones; ic--;) probD[ic].invert(); @@ -247,10 +247,10 @@ Bool_t AliAlgTrack::CalcResidDeriv(double* extendedParams, Bool_t invert, int pF for (int ip = pFrom; ip != pTo; ip += pinc) { // points are ordered against track direction AliAlgPoint* pnt = GetPoint(ip); if (!PropagateParamToPoint(probD, kNRDClones, pnt)) - return kFALSE; + return false; // if (pnt->ContainsMaterial()) { // apply material corrections if (!ApplyMatCorr(probD, kNRDClones, extendedParams, pnt)) - return kFALSE; + return false; // } // if (pnt->ContainsMeasurement()) { @@ -275,7 +275,7 @@ Bool_t AliAlgTrack::CalcResidDeriv(double* extendedParams, Bool_t invert, int pF AliWarningF("Failed on global derivatives calculation at point %d", ip); pnt->print("meas"); #endif - return kFALSE; + return false; } // if (!pnt->ContainsMaterial()) @@ -299,7 +299,7 @@ Bool_t AliAlgTrack::CalcResidDeriv(double* extendedParams, Bool_t invert, int pF // We will vary the tracks starting from the original parameters propagated to given point // and stored there (before applying material corrections for this point) // - SetParams(probD, kNRDClones, pnt->GetXPoint(), pnt->GetAlphaSens(), pnt->GetTrParamWSB(), kFALSE); + SetParams(probD, kNRDClones, pnt->GetXPoint(), pnt->GetAlphaSens(), pnt->GetTrParamWSB(), false); // no need for eventual track inversion here: if needed, this is already done in ParamWSB // int offsIP = offsI + ipar; // parameter entry in the extendedParams array @@ -312,12 +312,12 @@ Bool_t AliAlgTrack::CalcResidDeriv(double* extendedParams, Bool_t invert, int pF // // apply varied material effects : incremented by delta if (!ApplyMatCorr(probD[(icl << 1) + 0], extendedParams, pnt)) - return kFALSE; + return false; // // apply varied material effects : decremented by delta extendedParams[offsIP] = parOrig - del; if (!ApplyMatCorr(probD[(icl << 1) + 1], extendedParams, pnt)) - return kFALSE; + return false; // extendedParams[offsIP] = parOrig; del *= 0.5; @@ -335,11 +335,11 @@ Bool_t AliAlgTrack::CalcResidDeriv(double* extendedParams, Bool_t invert, int pF // printf(" DerFor:%d ",jp); pntJ->print(); if (!PropagateParamToPoint(probD, kNRDClones, pntJ)) - return kFALSE; + return false; // if (pntJ->ContainsMaterial()) { // apply material corrections if (!ApplyMatCorr(probD, kNRDClones, extendedParams, pntJ)) - return kFALSE; + return false; } // if (pntJ->ContainsMeasurement()) { @@ -352,11 +352,11 @@ Bool_t AliAlgTrack::CalcResidDeriv(double* extendedParams, Bool_t invert, int pF } // << loop over DOFs related to MS and ELoss are point ip } // << loop over all points of the track // - return kTRUE; + return true; } //______________________________________________________ -Bool_t AliAlgTrack::CalcResidDerivGlo(AliAlgPoint* pnt) +bool AliAlgTrack::CalcResidDerivGlo(AliAlgPoint* pnt) { // calculate residuals derivatives over point's sensor and its parents global params double deriv[AliAlgVol::kNDOFGeom * 3]; @@ -421,11 +421,11 @@ Bool_t AliAlgTrack::CalcResidDerivGlo(AliAlgPoint* pnt) // pnt->SetNGloDOFs(fNGloPar - pnt->GetDGloOffs()); // mark number of global derivatives filled // - return kTRUE; + return true; } //______________________________________________________ -Bool_t AliAlgTrack::CalcResiduals(const double* extendedParams) +bool AliAlgTrack::CalcResiduals(const double* extendedParams) { // Propagate for given local params and calculate residuals // The 1st 4 or 5 elements of extendedParams vector should be the reference trackParam_t @@ -449,7 +449,7 @@ Bool_t AliAlgTrack::CalcResiduals(const double* extendedParams) #if DEBUG > 3 LOG(warn) << "Failed on residuals calculation 0"; #endif - return kFALSE; + return false; } // if (IsCosmic()) { // cosmic upper leg @@ -457,17 +457,17 @@ Bool_t AliAlgTrack::CalcResiduals(const double* extendedParams) #if DEBUG > 3 LOG(warn) << "Failed on residuals calculation 1"; #endif - return kFALSE; + return false; } } // fNDF -= fNLocExtPar; SetResidDone(); - return kTRUE; + return true; } //______________________________________________________ -Bool_t AliAlgTrack::CalcResiduals(const double* extendedParams, Bool_t invert, int pFrom, int pTo) +bool AliAlgTrack::CalcResiduals(const double* extendedParams, bool invert, int pFrom, int pTo) { // Calculate residuals for the single leg from points pFrom to pT // The 1st 4 or 5 elements of extendedParams vector should be corrections to @@ -480,7 +480,7 @@ Bool_t AliAlgTrack::CalcResiduals(const double* extendedParams, Bool_t invert, i // increment will be done locally in the ApplyMatCorr routine. // trackParam_t probe; - SetParams(probe, getX(), getAlpha(), extendedParams, kTRUE); + SetParams(probe, getX(), getAlpha(), extendedParams, true); if (invert) probe.invert(); int pinc; @@ -495,7 +495,7 @@ Bool_t AliAlgTrack::CalcResiduals(const double* extendedParams, Bool_t invert, i for (int ip = pFrom; ip != pTo; ip += pinc) { // points are ordered against track direction AliAlgPoint* pnt = GetPoint(ip); if (!PropagateParamToPoint(probe, pnt)) - return kFALSE; + return false; // // store the current track kinematics at the point BEFORE applying eventual material // corrections. This kinematics will be later varied around supplied parameters (in the CalcResidDeriv) @@ -504,7 +504,7 @@ Bool_t AliAlgTrack::CalcResiduals(const double* extendedParams, Bool_t invert, i // account for materials // if (pnt->ContainsMaterial()) { // apply material corrections if (!ApplyMatCorr(probe, extendedParams, pnt)) - return kFALSE; + return false; // } pnt->SetTrParamWSA(probe.getParams()); // @@ -524,11 +524,11 @@ Bool_t AliAlgTrack::CalcResiduals(const double* extendedParams, Bool_t invert, i fChi2 += corrDiag[i] * corrDiag[i] / corCov[i]; } } - return kTRUE; + return true; } //______________________________________________________ -Bool_t AliAlgTrack::PropagateParamToPoint(trackParam_t* tr, int nTr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt) +bool AliAlgTrack::PropagateParamToPoint(trackParam_t* tr, int nTr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt) { // Propagate set of tracks to the point (only parameters, no error matrix) // VECTORIZE this @@ -540,28 +540,28 @@ Bool_t AliAlgTrack::PropagateParamToPoint(trackParam_t* tr, int nTr, const AliAl tr[itr].print(); pnt->print("meas mat"); #endif - return kFALSE; + return false; } } - return kTRUE; + return true; } //______________________________________________________ -Bool_t AliAlgTrack::PropagateParamToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt) +bool AliAlgTrack::PropagateParamToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt) { // propagate tracks to the point (only parameters, no error matrix) return Propagate(tr, pnt, maxStep, maxSnp, mt, nullptr); } //______________________________________________________ -Bool_t AliAlgTrack::PropagateToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT) +bool AliAlgTrack::PropagateToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT) { // propagate tracks to the point. If matCor is true, then material corrections will be applied. // if matPar pointer is provided, it will be filled by total x2x0 and signed xrho return Propagate(tr, pnt, maxStep, maxSnp, mt, tLT); } -Bool_t AliAlgTrack::Propagate(trackParam_t& track, const AliAlgPoint* pnt, Double_t maxStep, Double_t maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT) +bool AliAlgTrack::Propagate(trackParam_t& track, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT) { if (!track.rotate(pnt->GetAlphaSens())) { #if DEBUG > 3 @@ -569,12 +569,12 @@ Bool_t AliAlgTrack::Propagate(trackParam_t& track, const AliAlgPoint* pnt, Doubl tr.print(); pnt->Print(); #endif - return kFALSE; + return false; } // calculate the sign of the energy loss correction and ensure the upper leg of cosmics is calculated correctly. - const Int_t signCorr = [this, &pnt, &track, maxStep] { - const Double_t dx = maxStep - track.getX(); - const Int_t dir = dx > 0.f ? 1 : -1; + const int signCorr = [this, &pnt, &track, maxStep] { + const double dx = maxStep - track.getX(); + const int dir = dx > 0.f ? 1 : -1; if (pnt->IsInvDir()) { // upper leg of a cosmic -> inward facing track return dir; @@ -588,7 +588,7 @@ Bool_t AliAlgTrack::Propagate(trackParam_t& track, const AliAlgPoint* pnt, Doubl /* //______________________________________________________ -Bool_t AliAlgTrack::ApplyMS(trackParam_t& trPar, double tms,double pms) +bool AliAlgTrack::ApplyMS(trackParam_t& trPar, double tms,double pms) { //------------------------------------------------------------------------------ // Modify track par (e.g. trackParam_t) in the tracking frame @@ -605,7 +605,7 @@ Bool_t AliAlgTrack::ApplyMS(trackParam_t& trPar, double tms,double pms) // double *par = (double*) trPar.GetParameter(); // - if (Abs(tms)<1e-7) return kTRUE; + if (Abs(tms)<1e-7) return true; // double snTms = Sin(tms), csTms = Cos(tms); double snPms = Sin(pms), csPms = Cos(pms); @@ -627,12 +627,12 @@ Bool_t AliAlgTrack::ApplyMS(trackParam_t& trPar, double tms,double pms) par[3] = pz/pt; par[4]*= csLam/pt; // - return kTRUE; + return true; } */ //______________________________________________________ -Bool_t AliAlgTrack::ApplyMatCorr(trackParam_t& trPar, const Double_t* corrPar, const AliAlgPoint* pnt) +bool AliAlgTrack::ApplyMatCorr(trackParam_t& trPar, const double* corrPar, const AliAlgPoint* pnt) { // Modify track param (e.g. trackParam_t) in the tracking frame // by delta accounting for material effects @@ -658,7 +658,7 @@ Bool_t AliAlgTrack::ApplyMatCorr(trackParam_t& trPar, const Double_t* corrPar, c } //______________________________________________________ -Bool_t AliAlgTrack::ApplyMatCorr(trackParam_t& trPar, const Double_t* corr) +bool AliAlgTrack::ApplyMatCorr(trackParam_t& trPar, const double* corr) { // Modify track param (e.g. trackParam_t) in the tracking frame // by delta accounting for material effects @@ -675,16 +675,16 @@ Bool_t AliAlgTrack::ApplyMatCorr(trackParam_t& trPar, const Double_t* corr) printf("\n"); trPar.print(); #endif - return kFALSE; + return false; } trPar.updateParams(corr); - return kTRUE; + return true; } //______________________________________________________ -Bool_t AliAlgTrack::ApplyMatCorr(trackParam_t* trSet, int ntr, const Double_t* corrDiag, const AliAlgPoint* pnt) +bool AliAlgTrack::ApplyMatCorr(trackParam_t* trSet, int ntr, const double* corrDiag, const AliAlgPoint* pnt) { // Modify set of track params (e.g. trackParam_t) in the tracking frame // by delta accounting for material effects @@ -711,14 +711,14 @@ Bool_t AliAlgTrack::ApplyMatCorr(trackParam_t* trSet, int ntr, const Double_t* c LOG(error) << "Failed on clone %d materials" << itr; trSet[itr].print(); #endif - return kFALSE; + return false; } } - return kTRUE; + return true; } //______________________________________________ -Double_t AliAlgTrack::RichardsonExtrap(double* val, int ord) +double AliAlgTrack::RichardsonExtrap(double* val, int ord) { // Calculate Richardson extrapolation of order ord (starting from 1) // The array val should contain estimates ord+1 of derivatives with variations @@ -735,7 +735,7 @@ Double_t AliAlgTrack::RichardsonExtrap(double* val, int ord) } //______________________________________________ -Double_t AliAlgTrack::RichardsonExtrap(const double* val, int ord) +double AliAlgTrack::RichardsonExtrap(const double* val, int ord) { // Calculate Richardson extrapolation of order ord (starting from 1) // The array val should contain estimates ord+1 of derivatives with variations @@ -789,10 +789,10 @@ void AliAlgTrack::Print(Option_t* opt) const // TString optS = opt; optS.ToLower(); - Bool_t res = optS.Contains("r") && GetResidDone(); - Bool_t der = optS.Contains("d") && GetDerivDone(); - Bool_t par = optS.Contains("lc"); // local param corrections - Bool_t paru = optS.Contains("lcu"); // local param corrections in track param frame + bool res = optS.Contains("r") && GetResidDone(); + bool der = optS.Contains("d") && GetDerivDone(); + bool par = optS.Contains("lc"); // local param corrections + bool paru = optS.Contains("lcu"); // local param corrections in track param frame // if (par) { printf("Ref.track corr: "); @@ -859,7 +859,7 @@ void AliAlgTrack::DumpCoordinates() const } //______________________________________________ -Bool_t AliAlgTrack::IniFit() +bool AliAlgTrack::IniFit() { // perform initial fit of the track // @@ -879,7 +879,7 @@ Bool_t AliAlgTrack::IniFit() LOG(warn) << "Failed FitLeg 0"; trc.print(); #endif - return kFALSE; // collision track or cosmic lower leg + return false; // collision track or cosmic lower leg } // // printf("Lower leg: %d %d\n",0,GetInnerPointID()); trc.print(); @@ -892,30 +892,30 @@ Bool_t AliAlgTrack::IniFit() LOG(warn) << "Failed FitLeg 0"; trc.print(); #endif - return kFALSE; // collision track or cosmic lower leg + return false; // collision track or cosmic lower leg } // // propagate to reference point, which is the inner point of lower leg const AliAlgPoint* refP = GetPoint(GetInnerPointID()); if (!PropagateToPoint(trcU, refP, MaxDefStep, MaxDefSnp, DefMatCorrType)) - return kFALSE; + return false; // fChi2CosmUp = fChi2 - fChi2CosmDn; // printf("Upper leg: %d %d\n",GetInnerPointID()+1,GetNPoints()-1); trcU.print(); // if (!CombineTracks(trc, trcU)) - return kFALSE; + return false; //printf("Combined\n"); trc.print(); } CopyFrom(&trc); // fChi2Ini = fChi2; - return kTRUE; + return true; } //______________________________________________ -Bool_t AliAlgTrack::CombineTracks(trackParam_t& trcL, const trackParam_t& trcU) +bool AliAlgTrack::CombineTracks(trackParam_t& trcL, const trackParam_t& trcU) { // Assign to trcL the combined tracks (Kalman update of trcL by trcU) // The trcL and trcU MUST be defined at same X,Alpha @@ -930,7 +930,7 @@ Bool_t AliAlgTrack::CombineTracks(trackParam_t& trcL, const trackParam_t& trcU) LOG(error) << "Tracks must be defined at same reference X and Alpha"; trcL.print(); trcU.print(); - return kFALSE; + return false; } // // const covMat_t& covU = trcU.getCov(); @@ -958,7 +958,7 @@ Bool_t AliAlgTrack::CombineTracks(trackParam_t& trcL, const trackParam_t& trcU) LOG(error) << "Failed to invert summed cov.matrix of cosmic track"; matCLplCU.print(); #endif - return kFALSE; // inversion failed + return false; // inversion failed } TMatrixD matK(matCL, TMatrixD::kMult, matCLplCU); // gain K = Cl*(Cl+Cu)^-1 TMatrixD matKdotCL(matK, TMatrixD::kMult, matCL); // K*Cl @@ -978,11 +978,11 @@ Bool_t AliAlgTrack::CombineTracks(trackParam_t& trcL, const trackParam_t& trcU) // // printf("Combined: Chi2Tot:%.2f ChiUp:%.2f ChiDn:%.2f ChiCmb:%.2f\n",fChi2,fChi2CosmUp,fChi2CosmDn, chi2); - return kTRUE; + return true; } //______________________________________________ -Bool_t AliAlgTrack::FitLeg(trackParam_t& trc, int pFrom, int pTo, Bool_t& inv) +bool AliAlgTrack::FitLeg(trackParam_t& trc, int pFrom, int pTo, bool& inv) { // perform initial fit of the track // the fit will always start from the outgoing track in inward direction (i.e. if cosmics - bottom leg) @@ -1005,7 +1005,7 @@ Bool_t AliAlgTrack::FitLeg(trackParam_t& trc, int pFrom, int pTo, Bool_t& inv) BringTo02Pi(alp); double dphi = DeltaPhiSmall(phi, alp); // abs delta angle if (dphi > Pi() / 2.) { // need to invert the track to new frame - inv = kTRUE; + inv = true; // printf("Fit in %d %d Delta: %.3f -> Inverting for\n",pFrom,pTo,dphi); // p0->print("meas"); // printf("BeforeInv "); trc.print(); @@ -1017,16 +1017,16 @@ Bool_t AliAlgTrack::FitLeg(trackParam_t& trc, int pFrom, int pTo, Bool_t& inv) AliWarningF("Failed on rotateParam to %f", p0->GetAlphaSens()); trc.print(); #endif - return kFALSE; + return false; } if (!PropagateParamToPoint(trc, p0, MaxDefStep)) { - // if (!PropagateToPoint(trc,p0,5,30,kTRUE)) { + // if (!PropagateToPoint(trc,p0,5,30,true)) { //trc.PropagateParamOnlyTo(p0->GetXPoint()+kOverShootX,AliTrackerBase::GetBz())) { #if DEBUG > 3 AliWarningF("Failed on PropagateParamOnlyTo to %f", p0->GetXPoint() + kOverShootX); trc.print(); #endif - return kFALSE; + return false; } trc.setCov(kIniErr); trc.setCov(trc.getQ2Pt() * trc.getQ2Pt(), 4, 4); // lowest diagonal element (Q2Pt2) @@ -1046,7 +1046,7 @@ Bool_t AliAlgTrack::FitLeg(trackParam_t& trc, int pFrom, int pTo, Bool_t& inv) // printf("*** FitLeg %d (%d %d)\n",ip,pFrom,pTo); // printf("Before propagate: "); trc.print(); if (!PropagateToPoint(trc, pnt, MaxDefStep, MaxDefSnp, DefMatCorrType)) { - return kFALSE; + return false; } if (pnt->ContainsMeasurement()) { if (pnt->GetNeedUpdateFromTrack()) @@ -1062,7 +1062,7 @@ Bool_t AliAlgTrack::FitLeg(trackParam_t& trc, int pFrom, int pTo, Bool_t& inv) AliWarningF("Failed on Update %f,%f {%f,%f,%f}", yz[0], yz[1], errYZ[0], errYZ[1], errYZ[2]); trc.print(); #endif - return kFALSE; + return false; } fChi2 += chi; // printf("After update: (%f) -> %f\n",chi,fChi2); trc.print(); @@ -1074,16 +1074,16 @@ Bool_t AliAlgTrack::FitLeg(trackParam_t& trc, int pFrom, int pTo, Bool_t& inv) trc.invert(); } // - return kTRUE; + return true; } //______________________________________________ -Bool_t AliAlgTrack::ResidKalman() +bool AliAlgTrack::ResidKalman() { // calculate residuals from bi-directional Kalman smoother // ATTENTION: this method modifies workspaces of the points!!! // - Bool_t inv = kFALSE; + bool inv = false; const int kMinNStep = 3; const double MaxDefStep = 3.0; const double kErrSpace = 50.; @@ -1095,7 +1095,7 @@ Bool_t AliAlgTrack::ResidKalman() 0, 0, kErrAng * kErrAng, 0, 0, 0, kErrAng * kErrAng, 0, 0, 0, 0, kErrRelPtI * kErrRelPtI}; - // const Double_t kOverShootX = 5; + // const double kOverShootX = 5; // trackParam_t trc = *this; // @@ -1106,13 +1106,13 @@ Bool_t AliAlgTrack::ResidKalman() while (pID < nPnt && !(pnt = GetPoint(pID))->ContainsMeasurement()) pID++; if (!pnt) - return kFALSE; + return false; double phi = trc.getPhi(), alp = pnt->GetAlphaSens(); BringTo02Pi(phi); BringTo02Pi(alp); double dphi = DeltaPhiSmall(phi, alp); if (dphi > Pi() / 2.) { // need to invert the track to new frame - inv = kTRUE; + inv = true; trc.invert(); } // prepare track seed at 1st valid point @@ -1121,7 +1121,7 @@ Bool_t AliAlgTrack::ResidKalman() AliWarningF("Failed on rotateParam to %f", pnt->GetAlphaSens()); trc.print(); #endif - return kFALSE; + return false; } if (!PropagateParamToPoint(trc, pnt, MaxDefStep)) { //if (!trc.PropagateParamOnlyTo(pnt->GetXPoint()+kOverShootX,AliTrackerBase::GetBz())) { @@ -1129,7 +1129,7 @@ Bool_t AliAlgTrack::ResidKalman() AliWarningF("Failed on PropagateParamOnlyTo to %f", pnt->GetXPoint() + kOverShootX); trc.print(); #endif - return kFALSE; + return false; } // trc.setCov(kIniErr); @@ -1147,7 +1147,7 @@ Bool_t AliAlgTrack::ResidKalman() // printf("*** ResidKalm %d (%d %d)\n",ip,0,nPnt); // printf("Before propagate: "); trc.print(); if (!PropagateToPoint(trc, pnt, MaxDefStep, MaxDefSnp, DefMatCorrType)) { - return kFALSE; + return false; } if (!pnt->ContainsMeasurement()) continue; @@ -1169,7 +1169,7 @@ Bool_t AliAlgTrack::ResidKalman() AliWarningF("Failed on Inward Update %f,%f {%f,%f,%f}", yz[0], yz[1], errYZ[0], errYZ[1], errYZ[2]); trc.print(); #endif - return kFALSE; + return false; } // printf(">>Aft ");trc.print(); chifwd += chi; @@ -1188,7 +1188,7 @@ Bool_t AliAlgTrack::ResidKalman() inv = !inv; } if (!PropagateToPoint(trc, pnt, MaxDefStep, MaxDefSnp, DefMatCorrType)) { - return kFALSE; + return false; } if (!pnt->ContainsMeasurement()) continue; @@ -1209,7 +1209,7 @@ Bool_t AliAlgTrack::ResidKalman() AliWarningF("Failed on Outward Update %f,%f {%f,%f,%f}", yz[0], yz[1], errYZ[0], errYZ[1], errYZ[2]); trc.print(); #endif - return kFALSE; + return false; } chibwd += chi; // printf("< 3 LOG(error) << "Failed to process materials for leg along the track"; #endif - return kFALSE; + return false; } if (IsCosmic()) { // cosmic upper leg: move againg the track direction from middle point (inner) to last one (outer) @@ -1277,14 +1277,14 @@ Bool_t AliAlgTrack::ProcessMaterials() #if DEBUG > 3 LOG(error) << "Failed to process materials for leg against the track"; #endif - return kFALSE; + return false; } } - return kTRUE; + return true; } //______________________________________________ -Bool_t AliAlgTrack::ProcessMaterials(trackParam_t& trc, int pFrom, int pTo) +bool AliAlgTrack::ProcessMaterials(trackParam_t& trc, int pFrom, int pTo) { // attach material effect info to alignment points const int kMinNStep = 3; @@ -1339,7 +1339,7 @@ Bool_t AliAlgTrack::ProcessMaterials(trackParam_t& trc, int pFrom, int pTo) trc.print(); pnt->print("meas"); #endif - return kFALSE; + return false; } // // is there enough material to consider the point as a scatterer? @@ -1352,7 +1352,7 @@ Bool_t AliAlgTrack::ProcessMaterials(trackParam_t& trc, int pFrom, int pTo) tr0.print(); pnt->print("meas"); #endif - return kFALSE; + return false; } // the difference between the params, covariance of tracks with and w/o material accounting gives // paramets and covariance of material correction. For params ONLY ELoss effect is revealed @@ -1370,7 +1370,7 @@ Bool_t AliAlgTrack::ProcessMaterials(trackParam_t& trc, int pFrom, int pTo) if (pnt->ContainsMaterial()) { // // MP2 handles only scalar residuals hence correlated matrix of material effect need to be diagonalized - Bool_t eLossFree = pnt->GetELossVaried(); + bool eLossFree = pnt->GetELossVaried(); int nParFree = eLossFree ? kNKinParBON : kNKinParBOFF; TMatrixDSym matCov(nParFree); for (int i = nParFree; i--;) @@ -1383,7 +1383,7 @@ Bool_t AliAlgTrack::ProcessMaterials(trackParam_t& trc, int pFrom, int pTo) #if DEBUG > 3 LOG(error) << "Failed to diagonalize covariance of material correction"; matCov.print(); - return kFALSE; + return false; #endif } pnt->SetMatCovDiagonalizationMatrix(matEVec); // store diagonalization matrix @@ -1403,14 +1403,14 @@ Bool_t AliAlgTrack::ProcessMaterials(trackParam_t& trc, int pFrom, int pTo) AliWarningF("Failed on Update %f,%f {%f,%f,%f}", yz[0], yz[1], errYZ[0], errYZ[1], errYZ[2]); trc.print(); #endif - return kFALSE; + return false; } // } // } // - return kTRUE; + return true; } //______________________________________________ diff --git a/Detectors/Align/src/AliAlgVol.cxx b/Detectors/Align/src/AliAlgVol.cxx index 28963409cff2e..6b39462bf3ae0 100644 --- a/Detectors/Align/src/AliAlgVol.cxx +++ b/Detectors/Align/src/AliAlgVol.cxx @@ -122,7 +122,7 @@ namespace align const char* AliAlgVol::fgkFrameName[AliAlgVol::kNVarFrames] = {"LOC", "TRA"}; // -UInt_t AliAlgVol::fgDefGeomFree = +uint32_t AliAlgVol::fgDefGeomFree = kDOFBitTX | kDOFBitTY | kDOFBitTZ | kDOFBitPS | kDOFBitTH | kDOFBitPH; // const char* AliAlgVol::fgkDOFName[AliAlgVol::kNDOFGeom] = {"TX", "TY", "TZ", "PSI", "THT", "PHI"}; @@ -164,7 +164,7 @@ AliAlgVol::~AliAlgVol() } //_________________________________________________________ -void AliAlgVol::Delta2Matrix(TGeoHMatrix& deltaM, const Double_t* delta) const +void AliAlgVol::Delta2Matrix(TGeoHMatrix& deltaM, const double* delta) const { // prepare delta matrix for the volume from its // local delta vector (AliAlignObj convension): dx,dy,dz,,theta,psi,phi @@ -182,7 +182,7 @@ void AliAlgVol::Delta2Matrix(TGeoHMatrix& deltaM, const Double_t* delta) const } //__________________________________________________________________ -void AliAlgVol::GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t* delta) const +void AliAlgVol::GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const double* delta) const { // prepare the variation matrix tau in volume TRACKING frame by applying // local delta of modification of LOCAL frame: @@ -195,7 +195,7 @@ void AliAlgVol::GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t* delta) co } //__________________________________________________________________ -void AliAlgVol::GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t* delta, const TGeoHMatrix& relMat) const +void AliAlgVol::GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const double* delta, const TGeoHMatrix& relMat) const { // prepare the variation matrix tau in volume TRACKING frame by applying // local delta of modification of LOCAL frame of its PARENT; @@ -212,7 +212,7 @@ void AliAlgVol::GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const Double_t* delta, co } //__________________________________________________________________ -void AliAlgVol::GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const Double_t* delta) const +void AliAlgVol::GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const double* delta) const { // prepare the variation matrix tau in volume TRACKING frame by applying // local delta of modification of the same TRACKING frame: @@ -221,7 +221,7 @@ void AliAlgVol::GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const Double_t* delta) co } //__________________________________________________________________ -void AliAlgVol::GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const Double_t* delta, const TGeoHMatrix& relMat) const +void AliAlgVol::GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const double* delta, const TGeoHMatrix& relMat) const { // prepare the variation matrix tau in volume TRACKING frame by applying // local delta of modification of TRACKING frame of its PARENT; @@ -237,7 +237,7 @@ void AliAlgVol::GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const Double_t* delta, co } //_________________________________________________________ -Int_t AliAlgVol::CountParents() const +int AliAlgVol::CountParents() const { // count parents in the chain int cnt = 0; @@ -298,7 +298,7 @@ void AliAlgVol::Print(const Option_t* opt) const } //____________________________________________ -void AliAlgVol::PrepareMatrixL2G(Bool_t reco) +void AliAlgVol::PrepareMatrixL2G(bool reco) { // extract from geometry L2G matrix, depending on reco flag, set it as a reco-time // or current alignment matrix @@ -389,7 +389,7 @@ void AliAlgVol::SetTrackingFrame() } //__________________________________________________________________ -void AliAlgVol::AssignDOFs(Int_t& cntDOFs, Float_t* pars, Float_t* errs, Int_t* labs) +void AliAlgVol::AssignDOFs(int& cntDOFs, float* pars, float* errs, int* labs) { // Assigns offset of the DOFS of this volume in global array of DOFs, attaches arrays to volumes // @@ -419,12 +419,12 @@ void AliAlgVol::InitDOFs() for (int i = 0; i < fNDOFs; i++) if (fParErrs[i] < -9999 && IsZeroAbs(fParVals[i])) FixDOF(i); - CalcFree(kTRUE); + CalcFree(true); SetInitDOFsDone(); } //__________________________________________________________________ -void AliAlgVol::CalcFree(Bool_t condFix) +void AliAlgVol::CalcFree(bool condFix) { // calculate free dofs. If condFix==true, condition parameter a la pede, i.e. error < 0 fNDOFFree = fNDOFGeomFree = 0; @@ -442,7 +442,7 @@ void AliAlgVol::CalcFree(Bool_t condFix) } //__________________________________________________________________ -void AliAlgVol::SetNDOFs(Int_t n) +void AliAlgVol::SetNDOFs(int n) { // book global degrees of freedom if (n < kNDOFGeom) @@ -456,13 +456,13 @@ void AliAlgVol::AddChild(AliAlgVol* ch) // add child volume if (!fChildren) { fChildren = new TObjArray(); - fChildren->SetOwner(kFALSE); + fChildren->SetOwner(false); } fChildren->AddLast(ch); } //__________________________________________________________________ -void AliAlgVol::SetParVals(Int_t npar, Double_t* vl, Double_t* er) +void AliAlgVol::SetParVals(int npar, double* vl, double* er) { // set parameters if (npar > fNDOFs) @@ -474,14 +474,14 @@ void AliAlgVol::SetParVals(Int_t npar, Double_t* vl, Double_t* er) } //__________________________________________________________________ -Bool_t AliAlgVol::IsCondDOF(Int_t i) const +bool AliAlgVol::IsCondDOF(int i) const { // is DOF free and conditioned? return (!IsZeroAbs(GetParVal(i)) || !IsZeroAbs(GetParErr(i))); } //______________________________________________________ -Int_t AliAlgVol::FinalizeStat(AliAlgDOFStat* st) +int AliAlgVol::FinalizeStat(AliAlgDOFStat* st) { // finalize statistics on processed points fNProcPoints = 0; @@ -505,9 +505,9 @@ void AliAlgVol::WritePedeInfo(FILE* parOut, const Option_t* opt) const const char* kKeyParam = "parameter"; TString opts = opt; opts.ToLower(); - Bool_t showDef = opts.Contains("d"); // show free DOF even if not preconditioned - Bool_t showFix = opts.Contains("f"); // show DOF even if fixed - Bool_t showNam = opts.Contains("n"); // show volume name even if no nothing else is printable + bool showDef = opts.Contains("d"); // show free DOF even if not preconditioned + bool showFix = opts.Contains("f"); // show DOF even if fixed + bool showNam = opts.Contains("n"); // show volume name even if no nothing else is printable // // is there something to print ? int nCond(0), nFix(0), nDef(0); @@ -522,9 +522,9 @@ void AliAlgVol::WritePedeInfo(FILE* parOut, const Option_t* opt) const // int cmt = nCond > 0 || nFix > 0 ? kOff : kOn; // do we comment the "parameter" keyword for this volume if (!nFix) - showFix = kFALSE; + showFix = false; if (!nDef) - showDef = kFALSE; + showDef = false; // if (nCond || showDef || showFix || showNam) fprintf(parOut, "%s%s %s\t\tDOF/Free: %d/%d (%s) %s\n", comment[cmt], kKeyParam, comment[kOnOn], @@ -767,12 +767,12 @@ void AliAlgVol::CreateAlignmentObjects(TClonesArray* arr) const TClonesArray& parr = *arr; TGeoHMatrix algM; CreateAlignmenMatrix(algM); - // new (parr[parr.GetEntriesFast()]) AliAlignObjParams(GetName(), GetVolID(), algM, kTRUE); - const Double_t* translation = algM.GetTranslation(); - const Double_t* rotation = algM.GetRotationMatrix(); + // new (parr[parr.GetEntriesFast()]) AliAlignObjParams(GetName(), GetVolID(), algM, true); + const double* translation = algM.GetTranslation(); + const double* rotation = algM.GetRotationMatrix(); new (parr[parr.GetEntriesFast()]) detectors::AlignParam(GetName(), GetVolID(), translation[0], translation[1], translation[2], - rotation[0], rotation[1], rotation[2], kTRUE); + rotation[0], rotation[1], rotation[2], true); int nch = GetNChildren(); for (int ich = 0; ich < nch; ich++) GetChild(ich)->CreateAlignmentObjects(arr); @@ -813,22 +813,22 @@ void AliAlgVol::UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMat } //______________________________________________________ -Bool_t AliAlgVol::OwnsDOFID(Int_t id) const +bool AliAlgVol::OwnsDOFID(int id) const { // check if DOF ID belongs to this volume or its children if (id >= fFirstParGloID && id < fFirstParGloID + fNDOFs) - return kTRUE; + return true; // for (int iv = GetNChildren(); iv--;) { AliAlgVol* vol = GetChild(iv); if (vol->OwnsDOFID(id)) - return kTRUE; + return true; } - return kFALSE; + return false; } //______________________________________________________ -AliAlgVol* AliAlgVol::GetVolOfDOFID(Int_t id) const +AliAlgVol* AliAlgVol::GetVolOfDOFID(int id) const { // gets volume owning this DOF ID if (id >= fFirstParGloID && id < fFirstParGloID + fNDOFs) From fac7f09304e497a4a4a85f8be837893509c42e58 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Tue, 13 Apr 2021 16:52:17 +0200 Subject: [PATCH 215/770] [ALIGN] follow O2 naming guidelines * member functions start with lower case letters * member variables are prefixed with m or s instead of f --- Detectors/Align/include/Align/AliAlgAux.h | 62 +- .../Align/include/Align/AliAlgConstraint.h | 48 +- Detectors/Align/include/Align/AliAlgDOFStat.h | 22 +- Detectors/Align/include/Align/AliAlgDet.h | 296 ++-- .../Align/include/Align/AliAlgDetHMPID.h | 2 +- Detectors/Align/include/Align/AliAlgDetITS.h | 4 +- Detectors/Align/include/Align/AliAlgDetTOF.h | 2 +- Detectors/Align/include/Align/AliAlgDetTPC.h | 2 +- Detectors/Align/include/Align/AliAlgDetTRD.h | 14 +- .../Align/include/Align/AliAlgMPRecord.h | 120 +- Detectors/Align/include/Align/AliAlgPoint.h | 252 +-- Detectors/Align/include/Align/AliAlgRes.h | 180 +- Detectors/Align/include/Align/AliAlgResFast.h | 114 +- Detectors/Align/include/Align/AliAlgSens.h | 72 +- .../Align/include/Align/AliAlgSensHMPID.h | 4 +- Detectors/Align/include/Align/AliAlgSensITS.h | 2 +- Detectors/Align/include/Align/AliAlgSensTOF.h | 4 +- Detectors/Align/include/Align/AliAlgSensTPC.h | 4 +- Detectors/Align/include/Align/AliAlgSensTRD.h | 6 +- Detectors/Align/include/Align/AliAlgSteer.h | 560 +++---- Detectors/Align/include/Align/AliAlgTrack.h | 208 +-- Detectors/Align/include/Align/AliAlgVol.h | 262 +-- Detectors/Align/include/Align/AliAlgVtx.h | 16 +- Detectors/Align/src/AliAlgAux.cxx | 4 +- Detectors/Align/src/AliAlgConstraint.cxx | 122 +- Detectors/Align/src/AliAlgDOFStat.cxx | 36 +- Detectors/Align/src/AliAlgDet.cxx | 492 +++--- Detectors/Align/src/AliAlgDetHMPID.cxx | 12 +- Detectors/Align/src/AliAlgDetITS.cxx | 74 +- Detectors/Align/src/AliAlgDetTOF.cxx | 14 +- Detectors/Align/src/AliAlgDetTPC.cxx | 16 +- Detectors/Align/src/AliAlgDetTRD.cxx | 40 +- Detectors/Align/src/AliAlgMPRecord.cxx | 294 ++-- Detectors/Align/src/AliAlgPoint.cxx | 216 +-- Detectors/Align/src/AliAlgRes.cxx | 292 ++-- Detectors/Align/src/AliAlgResFast.cxx | 120 +- Detectors/Align/src/AliAlgSens.cxx | 236 +-- Detectors/Align/src/AliAlgSensHMPID.cxx | 56 +- Detectors/Align/src/AliAlgSensITS.cxx | 48 +- Detectors/Align/src/AliAlgSensTOF.cxx | 66 +- Detectors/Align/src/AliAlgSensTPC.cxx | 58 +- Detectors/Align/src/AliAlgSensTRD.cxx | 76 +- Detectors/Align/src/AliAlgSteer.cxx | 1448 ++++++++--------- Detectors/Align/src/AliAlgTrack.cxx | 684 ++++---- Detectors/Align/src/AliAlgVol.cxx | 458 +++--- Detectors/Align/src/AliAlgVtx.cxx | 22 +- 46 files changed, 3570 insertions(+), 3570 deletions(-) diff --git a/Detectors/Align/include/Align/AliAlgAux.h b/Detectors/Align/include/Align/AliAlgAux.h index 97532b3d887b9..0e102d87fc940 100644 --- a/Detectors/Align/include/Align/AliAlgAux.h +++ b/Detectors/Align/include/Align/AliAlgAux.h @@ -44,48 +44,48 @@ enum { kColl, kCosm, kNTrackTypes }; // -inline double Sector2Alpha(int sect); -inline int Phi2Sector(double alpha); -inline double SectorDAlpha() { return constants::math::PI / 9; } +inline double sector2Alpha(int sect); +inline int phi2Sector(double alpha); +inline double sectorDAlpha() { return constants::math::PI / 9; } // template -void BringTo02Pi(F& phi); +void bringTo02Pi(F& phi); template -void BringToPiPM(F& phi); +void bringToPiPM(F& phi); template -bool OKforPhiMin(F phiMin, F phi); +bool okForPhiMin(F phiMin, F phi); template -bool OKforPhiMax(F phiMax, F phi); +bool okForPhiMax(F phiMax, F phi); template -F MeanPhiSmall(F phi0, F phi1); +F meanPhiSmall(F phi0, F phi1); template -F DeltaPhiSmall(F phi0, F phi1); +F deltaPhiSmall(F phi0, F phi1); template -bool SmallerAbs(F d, F tolD) +bool smallerAbs(F d, F tolD) { return std::abs(d) < tolD; } template -bool Smaller(F d, F tolD) +bool smaller(F d, F tolD) { return d < tolD; } // -inline int NumberOfBitsSet(uint32_t x); -inline bool IsZeroAbs(double d) { return SmallerAbs(d, kAlmostZeroD); } -inline bool IsZeroAbs(float f) { return SmallerAbs(f, kAlmostZeroF); } -inline bool IsZeroPos(double d) { return Smaller(d, kAlmostZeroD); } -inline bool IsZeroPos(float f) { return Smaller(f, kAlmostZeroF); } +inline int numberOfBitsSet(uint32_t x); +inline bool isZeroAbs(double d) { return smallerAbs(d, kAlmostZeroD); } +inline bool isZeroAbs(float f) { return smallerAbs(f, kAlmostZeroF); } +inline bool isZeroPos(double d) { return smaller(d, kAlmostZeroD); } +inline bool isZeroPos(float f) { return smaller(f, kAlmostZeroF); } // -int FindKeyIndex(int key, const int* arr, int n); +int findKeyIndex(int key, const int* arr, int n); // -void PrintBits(size_t patt, int maxBits); +void printBits(size_t patt, int maxBits); } // namespace AliAlgAux //_________________________________________________________________________________ template -inline void AliAlgAux::BringTo02Pi(F& phi) +inline void AliAlgAux::bringTo02Pi(F& phi) { // bring phi to 0-2pi range if (phi < 0) @@ -96,7 +96,7 @@ inline void AliAlgAux::BringTo02Pi(F& phi) //_________________________________________________________________________________ template -inline void AliAlgAux::BringToPiPM(F& phi) +inline void AliAlgAux::bringToPiPM(F& phi) { // bring phi to -pi:pi range if (phi > constants::math::PI) @@ -104,7 +104,7 @@ inline void AliAlgAux::BringToPiPM(F& phi) } //_________________________________________________________________________________ template -inline bool AliAlgAux::OKforPhiMin(F phiMin, F phi) +inline bool AliAlgAux::okForPhiMin(F phiMin, F phi) { // check if phi is above the phiMin, phi's must be in 0-2pi range F dphi = phi - phiMin; @@ -113,7 +113,7 @@ inline bool AliAlgAux::OKforPhiMin(F phiMin, F phi) //_________________________________________________________________________________ template -inline bool AliAlgAux::OKforPhiMax(F phiMax, F phi) +inline bool AliAlgAux::okForPhiMax(F phiMax, F phi) { // check if phi is below the phiMax, phi's must be in 0-2pi range F dphi = phi - phiMax; @@ -122,11 +122,11 @@ inline bool AliAlgAux::OKforPhiMax(F phiMax, F phi) //_________________________________________________________________________________ template -inline F AliAlgAux::MeanPhiSmall(F phi0, F phi1) +inline F AliAlgAux::meanPhiSmall(F phi0, F phi1) { // return mean phi, assume phis in 0:2pi F phi; - if (!OKforPhiMin(phi0, phi1)) { + if (!okForPhiMin(phi0, phi1)) { phi = phi0; phi0 = phi1; phi1 = phi; @@ -135,17 +135,17 @@ inline F AliAlgAux::MeanPhiSmall(F phi0, F phi1) phi = (phi1 - (constants::math::TwoPI - phi0)) / 2; // wrap else phi = (phi0 + phi1) / 2; - BringTo02Pi(phi); + bringTo02Pi(phi); return phi; } //_________________________________________________________________________________ template -inline F AliAlgAux::DeltaPhiSmall(F phi0, F phi1) +inline F AliAlgAux::deltaPhiSmall(F phi0, F phi1) { // return delta phi, assume phis in 0:2pi F del; - if (!OKforPhiMin(phi0, phi1)) { + if (!okForPhiMin(phi0, phi1)) { del = phi0; phi0 = phi1; phi1 = del; @@ -157,7 +157,7 @@ inline F AliAlgAux::DeltaPhiSmall(F phi0, F phi1) } //_________________________________________________________________________________ -inline int AliAlgAux::NumberOfBitsSet(uint32_t x) +inline int AliAlgAux::numberOfBitsSet(uint32_t x) { // count number of non-0 bits in 32bit word x = x - ((x >> 1) & 0x55555555); @@ -166,16 +166,16 @@ inline int AliAlgAux::NumberOfBitsSet(uint32_t x) } //_________________________________________________________________________________ -inline double AliAlgAux::Sector2Alpha(int sect) +inline double AliAlgAux::sector2Alpha(int sect) { // get barrel sector alpha in -pi:pi format if (sect > 8) sect -= 18; - return (sect + 0.5) * SectorDAlpha(); + return (sect + 0.5) * sectorDAlpha(); } //_________________________________________________________________________________ -inline int AliAlgAux::Phi2Sector(double phi) +inline int AliAlgAux::phi2Sector(double phi) { // get barrel sector from phi in -pi:pi format int sect = math_utils::nintd((phi * constants::math::Rad2Deg - 10) / 20.); diff --git a/Detectors/Align/include/Align/AliAlgConstraint.h b/Detectors/Align/include/Align/AliAlgConstraint.h index a65ba301cf7d7..3e4c4cbe06265 100644 --- a/Detectors/Align/include/Align/AliAlgConstraint.h +++ b/Detectors/Align/include/Align/AliAlgConstraint.h @@ -45,35 +45,35 @@ class AliAlgConstraint : public TNamed AliAlgConstraint(const char* name = 0, const char* title = 0); virtual ~AliAlgConstraint(); // - void SetParent(const AliAlgVol* par); - const AliAlgVol* GetParent() const { return fParent; } + void setParent(const AliAlgVol* par); + const AliAlgVol* getParent() const { return mParent; } // - int GetNChildren() const { return fChildren.GetEntriesFast(); } - AliAlgVol* GetChild(int i) const { return (AliAlgVol*)fChildren[i]; } - void AddChild(const AliAlgVol* v) + int getNChildren() const { return mChildren.GetEntriesFast(); } + AliAlgVol* getChild(int i) const { return (AliAlgVol*)mChildren[i]; } + void addChild(const AliAlgVol* v) { if (v) - fChildren.AddLast((AliAlgVol*)v); + mChildren.AddLast((AliAlgVol*)v); } // - bool IsDOFConstrained(int dof) const { return fConstraint & 0x1 << dof; } - uint8_t GetConstraintPattern() const { return fConstraint; } - void ConstrainDOF(int dof) { fConstraint |= 0x1 << dof; } - void UnConstrainDOF(int dof) { fConstraint &= ~(0x1 << dof); } - void SetConstrainPattern(uint32_t pat) { fConstraint = pat; } - bool HasConstraint() const { return fConstraint; } - double GetSigma(int i) const { return fSigma[i]; } - void SetSigma(int i, double s = 0) { fSigma[i] = s; } + bool isDOFConstrained(int dof) const { return mConstraint & 0x1 << dof; } + uint8_t getConstraintPattern() const { return mConstraint; } + void constrainDOF(int dof) { mConstraint |= 0x1 << dof; } + void unConstrainDOF(int dof) { mConstraint &= ~(0x1 << dof); } + void setConstrainPattern(uint32_t pat) { mConstraint = pat; } + bool hasConstraint() const { return mConstraint; } + double getSigma(int i) const { return mSigma[i]; } + void setSigma(int i, double s = 0) { mSigma[i] = s; } // - void SetNoJacobian(bool v = true) { SetBit(kNoJacobianBit, v); } - bool GetNoJacobian() const { return TestBit(kNoJacobianBit); } + void setNoJacobian(bool v = true) { SetBit(kNoJacobianBit, v); } + bool getNoJacobian() const { return TestBit(kNoJacobianBit); } // - void ConstrCoefGeom(const TGeoHMatrix& matRD, float* jac /*[kNDOFGeom][kNDOFGeom]*/) const; + void constrCoefGeom(const TGeoHMatrix& matRD, float* jac /*[kNDOFGeom][kNDOFGeom]*/) const; // virtual void Print(const Option_t* opt = "") const; - virtual void WriteChildrenConstraints(FILE* conOut) const; - virtual void CheckConstraint() const; - virtual const char* GetDOFName(int i) const { return AliAlgVol::GetGeomDOFName(i); } + virtual void writeChildrenConstraints(FILE* conOut) const; + virtual void checkConstraint() const; + virtual const char* getDOFName(int i) const { return AliAlgVol::getGeomDOFName(i); } // protected: // ------- dummies ------- @@ -81,10 +81,10 @@ class AliAlgConstraint : public TNamed AliAlgConstraint& operator=(const AliAlgConstraint&); // protected: - uint32_t fConstraint; // bit pattern of constraint - double fSigma[kNDOFGeom]; // optional sigma if constraint is gaussian - const AliAlgVol* fParent; // parent volume for contraint, lab if 0 - TObjArray fChildren; // volumes subjected to constraints + uint32_t mConstraint; // bit pattern of constraint + double mSigma[kNDOFGeom]; // optional sigma if constraint is gaussian + const AliAlgVol* mParent; // parent volume for contraint, lab if 0 + TObjArray mChildren; // volumes subjected to constraints // ClassDef(AliAlgConstraint, 2); }; diff --git a/Detectors/Align/include/Align/AliAlgDOFStat.h b/Detectors/Align/include/Align/AliAlgDOFStat.h index ce2ee30f94e25..adb0f81604da5 100644 --- a/Detectors/Align/include/Align/AliAlgDOFStat.h +++ b/Detectors/Align/include/Align/AliAlgDOFStat.h @@ -33,15 +33,15 @@ class AliAlgDOFStat : public TNamed AliAlgDOFStat(int n = 0); virtual ~AliAlgDOFStat(); // - int GetNDOFs() const { return fNDOFs; } - int GetStat(int idf) const { return idf < fNDOFs ? fStat[idf] : 0; } - int* GetStat() const { return (int*)fStat; }; - void SetStat(int idf, int v) { fStat[idf] = v; } - void AddStat(int idf, int v) { fStat[idf] += v; } - int GetNMerges() const { return fNMerges; } - TH1F* CreateHisto(AliAlgSteer* st) const; + int getNDOFs() const { return mNDOFs; } + int getStat(int idf) const { return idf < mNDOFs ? mStat[idf] : 0; } + int* getStat() const { return (int*)mStat; }; + void setStat(int idf, int v) { mStat[idf] = v; } + void addStat(int idf, int v) { mStat[idf] += v; } + int getNMerges() const { return mNMerges; } + TH1F* createHisto(AliAlgSteer* st) const; virtual void Print(Option_t* opt) const; - virtual int64_t Merge(TCollection* list); + virtual int64_t merge(TCollection* list); // protected: // @@ -49,9 +49,9 @@ class AliAlgDOFStat : public TNamed AliAlgDOFStat& operator=(const AliAlgDOFStat&); // protected: - int fNDOFs; // number of dofs defined - int fNMerges; // number of merges - int* fStat; //[fNDOFs] statistics per DOF + int mNDOFs; // number of dofs defined + int mNMerges; // number of merges + int* mStat; //[mNDOFs] statistics per DOF // ClassDef(AliAlgDOFStat, 1); }; diff --git a/Detectors/Align/include/Align/AliAlgDet.h b/Detectors/Align/include/Align/AliAlgDet.h index 6f79737a5b8bd..735308f9773ab 100644 --- a/Detectors/Align/include/Align/AliAlgDet.h +++ b/Detectors/Align/include/Align/AliAlgDet.h @@ -47,155 +47,155 @@ class AliAlgDet : public TNamed AliAlgDet(); AliAlgDet(const char* name, const char* title = "", int id = -1) : TNamed(name, title) { SetUniqueID(id); }; virtual ~AliAlgDet(); - int GetDetID() const { return GetUniqueID(); } - detectors::DetID GetO2DetID() const { return detectors::DetID(GetUniqueID()); }; - void SetDetID(uint32_t tp); + int getDetID() const { return GetUniqueID(); } + detectors::DetID getO2DetID() const { return detectors::DetID(GetUniqueID()); }; + void setDetID(uint32_t tp); void SetDetID(detectors::DetID id) { SetUniqueID(id); } // - virtual void CacheReferenceOCDB(); - virtual void AcknowledgeNewRun(int run); - virtual void UpdateL2GRecoMatrices(); - virtual void ApplyAlignmentFromMPSol(); - // - int VolID2SID(int vid) const; - int SID2VolID(int sid) const { return sid < GetNSensors() ? fSID2VolID[sid] : -1; } //todo - int GetNSensors() const { return fSensors.GetEntriesFast(); } - int GetNVolumes() const { return fVolumes.GetEntriesFast(); } - int GetVolIDMin() const { return fVolIDMin; } - int GetVolIDMax() const { return fVolIDMax; } - bool SensorOfDetector(int vid) const { return vid >= fVolIDMin && vid <= fVolIDMax; } - void SetAddError(double y, double z); - const double* GetAddError() const { return fAddError; } - // - int GetNPoints() const { return fNPoints; } - // - void SetAlgSteer(AliAlgSteer* s) { fAlgSteer = s; } - AliAlgSens* GetSensor(int id) const { return (AliAlgSens*)fSensors.UncheckedAt(id); } - AliAlgSens* GetSensorByVolId(int vid) const + virtual void cacheReferenceOCDB(); + virtual void acknowledgeNewRun(int run); + virtual void updateL2GRecoMatrices(); + virtual void applyAlignmentFromMPSol(); + // + int volID2SID(int vid) const; + int sID2VolID(int sid) const { return sid < getNSensors() ? mSID2VolID[sid] : -1; } //todo + int getNSensors() const { return mSensors.GetEntriesFast(); } + int getNVolumes() const { return mVolumes.GetEntriesFast(); } + int getVolIDMin() const { return mVolIDMin; } + int getVolIDMax() const { return mVolIDMax; } + bool sensorOfDetector(int vid) const { return vid >= mVolIDMin && vid <= mVolIDMax; } + void setAddError(double y, double z); + const double* getAddError() const { return mAddError; } + // + int getNPoints() const { return mNPoints; } + // + void setAlgSteer(AliAlgSteer* s) { mAlgSteer = s; } + AliAlgSens* getSensor(int id) const { return (AliAlgSens*)mSensors.UncheckedAt(id); } + AliAlgSens* getSensorByVolId(int vid) const { - int sid = VolID2SID(vid); - return sid < 0 ? 0 : GetSensor(sid); + int sid = volID2SID(vid); + return sid < 0 ? 0 : getSensor(sid); } - AliAlgSens* GetSensor(const char* symname) const { return (AliAlgSens*)fSensors.FindObject(symname); } - AliAlgVol* GetVolume(int id) const { return (AliAlgVol*)fVolumes.UncheckedAt(id); } - AliAlgVol* GetVolume(const char* symname) const { return (AliAlgVol*)fVolumes.FindObject(symname); } + AliAlgSens* getSensor(const char* symname) const { return (AliAlgSens*)mSensors.FindObject(symname); } + AliAlgVol* getVolume(int id) const { return (AliAlgVol*)mVolumes.UncheckedAt(id); } + AliAlgVol* getVolume(const char* symname) const { return (AliAlgVol*)mVolumes.FindObject(symname); } // - bool OwnsDOFID(int id) const; - AliAlgVol* GetVolOfDOFID(int id) const; + bool ownsDOFID(int id) const; + AliAlgVol* getVolOfDOFID(int id) const; // - int GetDetLabel() const { return (GetDetID() + 1) * 1000000; } - void SetFreeDOF(int dof); - void FixDOF(int dof); - void SetFreeDOFPattern(uint64_t pat) + int getDetLabel() const { return (getDetID() + 1) * 1000000; } + void setFreeDOF(int dof); + void fixDOF(int dof); + void setFreeDOFPattern(uint64_t pat) { - fCalibDOF = pat; - CalcFree(); + mCalibDOF = pat; + calcFree(); } - bool IsFreeDOF(int dof) const { return (fCalibDOF & (0x1 << dof)) != 0; } - bool IsCondDOF(int dof) const; - uint64_t GetFreeDOFPattern() const { return fCalibDOF; } - int GetNProcessedPoints() const { return fNProcPoints; } - virtual const char* GetCalibDOFName(int) const { return 0; } - virtual double GetCalibDOFVal(int) const { return 0; } - virtual double GetCalibDOFValWithCal(int) const { return 0; } - // - virtual int InitGeom(); - virtual int AssignDOFs(); - virtual void InitDOFs(); - virtual void Terminate(); - void FillDOFStat(AliAlgDOFStat* dofst = 0) const; - virtual void AddVolume(AliAlgVol* vol); - virtual void DefineVolumes(); - virtual void DefineMatrices(); + bool isFreeDOF(int dof) const { return (mCalibDOF & (0x1 << dof)) != 0; } + bool isCondDOF(int dof) const; + uint64_t getFreeDOFPattern() const { return mCalibDOF; } + int getNProcessedPoints() const { return mNProcPoints; } + virtual const char* getCalibDOFName(int) const { return 0; } + virtual double getCalibDOFVal(int) const { return 0; } + virtual double getCalibDOFValWithCal(int) const { return 0; } + // + virtual int initGeom(); + virtual int assignDOFs(); + virtual void initDOFs(); + virtual void terminate(); + void fillDOFStat(AliAlgDOFStat* dofst = 0) const; + virtual void addVolume(AliAlgVol* vol); + virtual void defineVolumes(); + virtual void defineMatrices(); virtual void Print(const Option_t* opt = "") const; // virtual int ProcessPoints(const AliESDtrack* esdTr, AliAlgTrack* algTrack, bool inv = false); FIXME(milettri): needs AliESDtrack - virtual void UpdatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) const; - virtual void SetUseErrorParam(int v = 0); - int GetUseErrorParam() const { return fUseErrorParam; } + virtual void updatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) const; + virtual void setUseErrorParam(int v = 0); + int getUseErrorParam() const { return mUseErrorParam; } // // virtual bool AcceptTrack(const AliESDtrack* trc, int trtype) const = 0; FIXME(milettri): needs AliESDtrack // bool CheckFlags(const AliESDtrack* trc, int trtype) const; FIXME(milettri): needs AliESDtrack // - virtual AliAlgPoint* GetPointFromPool(); - virtual void ResetPool(); - virtual void WriteSensorPositions(const char* outFName); + virtual AliAlgPoint* getPointFromPool(); + virtual void resetPool(); + virtual void writeSensorPositions(const char* outFName); // - void SetInitGeomDone() { SetBit(kInitGeomDone); } - bool GetInitGeomDone() const { return TestBit(kInitGeomDone); } + void setInitGeomDone() { SetBit(kInitGeomDone); } + bool getInitGeomDone() const { return TestBit(kInitGeomDone); } // - void SetInitDOFsDone() { SetBit(kInitDOFsDone); } - bool GetInitDOFsDone() const { return TestBit(kInitDOFsDone); } - void FixNonSensors(); - void SetFreeDOFPattern(uint32_t pat = 0xffffffff, int lev = -1, const char* match = 0); - void SetDOFCondition(int dof, float condErr, int lev = -1, const char* match = 0); - int SelectVolumes(TObjArray* arr, int lev = -1, const char* match = 0); + void setInitDOFsDone() { SetBit(kInitDOFsDone); } + bool getInitDOFsDone() const { return TestBit(kInitDOFsDone); } + void fixNonSensors(); + void setFreeDOFPattern(uint32_t pat = 0xffffffff, int lev = -1, const char* match = 0); + void setDOFCondition(int dof, float condErr, int lev = -1, const char* match = 0); + int selectVolumes(TObjArray* arr, int lev = -1, const char* match = 0); // - int GetNDOFs() const { return fNDOFs; } - int GetNCalibDOFs() const { return fNCalibDOF; } - int GetNCalibDOFsFree() const { return fNCalibDOFFree; } + int getNDOFs() const { return mNDOFs; } + int getNCalibDOFs() const { return mNCalibDOF; } + int getNCalibDOFsFree() const { return mNCalibDOFFree; } // - void SetDisabled(int tp, bool v) + void setDisabled(int tp, bool v) { - fDisabled[tp] = v; - SetObligatory(tp, !v); + mDisabled[tp] = v; + setObligatory(tp, !v); } - void SetDisabled() + void setDisabled() { - SetDisabledColl(); - SetDisabledCosm(); + setDisabledColl(); + setDisabledCosm(); } - void SetDisabledColl(bool v = true) { SetDisabled(AliAlgAux::kColl, v); } - void SetDisabledCosm(bool v = true) { SetDisabled(AliAlgAux::kCosm, v); } - bool IsDisabled(int tp) const { return fDisabled[tp]; } - bool IsDisabled() const { return IsDisabledColl() && IsDisabledCosm(); } - bool IsDisabledColl() const { return IsDisabled(AliAlgAux::kColl); } - bool IsDisabledCosm() const { return IsDisabled(AliAlgAux::kCosm); } - // - void SetTrackFlagSel(int tp, uint64_t f) { fTrackFlagSel[tp] = f; } - void SetTrackFlagSelColl(uint64_t f) { SetTrackFlagSel(AliAlgAux::kColl, f); } - void SetTrackFlagSelCosm(uint64_t f) { SetTrackFlagSel(AliAlgAux::kCosm, f); } - uint64_t GetTrackFlagSel(int tp) const { return fTrackFlagSel[tp]; } - uint64_t GetTrackFlagSelColl() const { return GetTrackFlagSel(AliAlgAux::kColl); } - uint64_t GetTrackFlagSelCosm() const { return GetTrackFlagSel(AliAlgAux::kCosm); } - // - void SetNPointsSel(int tp, int n) { fNPointsSel[tp] = n; } - void SetNPointsSelColl(int n) { SetNPointsSel(AliAlgAux::kColl, n); } - void SetNPointsSelCosm(int n) { SetNPointsSel(AliAlgAux::kCosm, n); } - int GetNPointsSel(int tp) const { return fNPointsSel[tp]; } - int GetNPointsSelColl() const { return GetNPointsSel(AliAlgAux::kColl); } - int GetNPointsSelCosm() const { return GetNPointsSel(AliAlgAux::kCosm); } - // - // - bool IsObligatory(int tp) const { return fObligatory[tp]; } - bool IsObligatoryColl() const { return IsObligatory(AliAlgAux::kColl); } - bool IsObligatoryCosm() const { return IsObligatory(AliAlgAux::kCosm); } - void SetObligatory(int tp, bool v = true); - void SetObligatoryColl(bool v = true) { SetObligatory(AliAlgAux::kColl, v); } - void SetObligatoryCosm(bool v = true) { SetObligatory(AliAlgAux::kCosm, v); } - // - void AddAutoConstraints() const; - void ConstrainOrphans(const double* sigma, const char* match = 0); + void setDisabledColl(bool v = true) { setDisabled(AliAlgAux::kColl, v); } + void setDisabledCosm(bool v = true) { setDisabled(AliAlgAux::kCosm, v); } + bool isDisabled(int tp) const { return mDisabled[tp]; } + bool isDisabled() const { return IsDisabledColl() && IsDisabledCosm(); } + bool IsDisabledColl() const { return isDisabled(AliAlgAux::kColl); } + bool IsDisabledCosm() const { return isDisabled(AliAlgAux::kCosm); } + // + void setTrackFlagSel(int tp, uint64_t f) { mTrackFlagSel[tp] = f; } + void setTrackFlagSelColl(uint64_t f) { setTrackFlagSel(AliAlgAux::kColl, f); } + void setTrackFlagSelCosm(uint64_t f) { setTrackFlagSel(AliAlgAux::kCosm, f); } + uint64_t getTrackFlagSel(int tp) const { return mTrackFlagSel[tp]; } + uint64_t getTrackFlagSelColl() const { return getTrackFlagSel(AliAlgAux::kColl); } + uint64_t getTrackFlagSelCosm() const { return getTrackFlagSel(AliAlgAux::kCosm); } + // + void setNPointsSel(int tp, int n) { mNPointsSel[tp] = n; } + void setNPointsSelColl(int n) { setNPointsSel(AliAlgAux::kColl, n); } + void setNPointsSelCosm(int n) { setNPointsSel(AliAlgAux::kCosm, n); } + int getNPointsSel(int tp) const { return mNPointsSel[tp]; } + int getNPointsSelColl() const { return getNPointsSel(AliAlgAux::kColl); } + int getNPointsSelCosm() const { return getNPointsSel(AliAlgAux::kCosm); } + // + // + bool isObligatory(int tp) const { return mObligatory[tp]; } + bool isObligatoryColl() const { return isObligatory(AliAlgAux::kColl); } + bool isObligatoryCosm() const { return isObligatory(AliAlgAux::kCosm); } + void setObligatory(int tp, bool v = true); + void setObligatoryColl(bool v = true) { setObligatory(AliAlgAux::kColl, v); } + void setObligatoryCosm(bool v = true) { setObligatory(AliAlgAux::kCosm, v); } + // + void addAutoConstraints() const; + void constrainOrphans(const double* sigma, const char* match = 0); - virtual void WritePedeInfo(FILE* parOut, const Option_t* opt = "") const; - virtual void WriteCalibrationResults() const; - virtual void WriteAlignmentResults() const; + virtual void writePedeInfo(FILE* parOut, const Option_t* opt = "") const; + virtual void writeCalibrationResults() const; + virtual void writeAlignmentResults() const; // - float* GetParVals() const { return fParVals; } - double GetParVal(int par) const { return fParVals ? fParVals[par] : 0; } - double GetParErr(int par) const { return fParErrs ? fParErrs[par] : 0; } - int GetParLab(int par) const { return fParLabs ? fParLabs[par] : 0; } + float* getParVals() const { return mParVals; } + double getParVal(int par) const { return mParVals ? mParVals[par] : 0; } + double getParErr(int par) const { return mParErrs ? mParErrs[par] : 0; } + int getParLab(int par) const { return mParLabs ? mParLabs[par] : 0; } // - void SetParVals(int npar, double* vl, double* er); - void SetParVal(int par, double v = 0) { fParVals[par] = v; } - void SetParErr(int par, double e = 0) { fParErrs[par] = e; } + void setParVals(int npar, double* vl, double* er); + void setParVal(int par, double v = 0) { mParVals[par] = v; } + void setParErr(int par, double e = 0) { mParErrs[par] = e; } // - int GetFirstParGloID() const { return fFirstParGloID; } - int GetParGloID(int par) const { return fFirstParGloID + par; } - void SetFirstParGloID(int id) { fFirstParGloID = id; } + int getFirstParGloID() const { return mFirstParGloID; } + int getParGloID(int par) const { return mFirstParGloID + par; } + void setFirstParGloID(int id) { mFirstParGloID = id; } // protected: - void SortSensors(); - void CalcFree(bool condFree = false); + void sortSensors(); + void calcFree(bool condFree = false); // // ------- dummies --------- AliAlgDet(const AliAlgDet&); @@ -203,40 +203,40 @@ class AliAlgDet : public TNamed // protected: // - int fNDOFs; // number of DOFs free - int fVolIDMin; // min volID for this detector (for sensors only) - int fVolIDMax; // max volID for this detector (for sensors only) - int fNSensors; // number of sensors (i.e. volID's) - int* fSID2VolID; //[fNSensors] table of conversion from VolID to sid - int fNProcPoints; // total number of points processed + int mNDOFs; // number of DOFs free + int mVolIDMin; // min volID for this detector (for sensors only) + int mVolIDMax; // max volID for this detector (for sensors only) + int mNSensors; // number of sensors (i.e. volID's) + int* mSID2VolID; //[mNSensors] table of conversion from VolID to sid + int mNProcPoints; // total number of points processed // // Detector specific calibration degrees of freedom - int fNCalibDOF; // number of calibDOFs for detector (preset) - int fNCalibDOFFree; // number of calibDOFs for detector (preset) - uint64_t fCalibDOF; // status of calib dof - int fFirstParGloID; // ID of the 1st parameter in the global results array - float* fParVals; //! values of the fitted params - float* fParErrs; //! errors of the fitted params - int* fParLabs; //! labels for parameters + int mNCalibDOF; // number of calibDOFs for detector (preset) + int mNCalibDOFFree; // number of calibDOFs for detector (preset) + uint64_t mCalibDOF; // status of calib dof + int mFirstParGloID; // ID of the 1st parameter in the global results array + float* mParVals; //! values of the fitted params + float* mParErrs; //! errors of the fitted params + int* mParLabs; //! labels for parameters // // Track selection - bool fDisabled[AliAlgAux::kNTrackTypes]; // detector disabled/enabled in the track - bool fObligatory[AliAlgAux::kNTrackTypes]; // detector must be present in the track - uint64_t fTrackFlagSel[AliAlgAux::kNTrackTypes]; // flag for track selection - int fNPointsSel[AliAlgAux::kNTrackTypes]; // min number of points to require + bool mDisabled[AliAlgAux::kNTrackTypes]; // detector disabled/enabled in the track + bool mObligatory[AliAlgAux::kNTrackTypes]; // detector must be present in the track + uint64_t mTrackFlagSel[AliAlgAux::kNTrackTypes]; // flag for track selection + int mNPointsSel[AliAlgAux::kNTrackTypes]; // min number of points to require // - int fUseErrorParam; // signal that points need to be updated using track info, 0 - no - double fAddError[2]; // additional error increment for measurement - TObjArray fSensors; // all sensors of the detector - TObjArray fVolumes; // all volumes of the detector + int mUseErrorParam; // signal that points need to be updated using track info, 0 - no + double mAddError[2]; // additional error increment for measurement + TObjArray mSensors; // all sensors of the detector + TObjArray mVolumes; // all volumes of the detector // // this is transient info - int fNPoints; //! number of points from this detector - int fPoolNPoints; //! number of points in the pool - int fPoolFreePointID; //! id of the last free point in the pool - TObjArray fPointsPool; //! pool of aligment points + int mNPoints; //! number of points from this detector + int mPoolNPoints; //! number of points in the pool + int mPoolFreePointID; //! id of the last free point in the pool + TObjArray mPointsPool; //! pool of aligment points // - AliAlgSteer* fAlgSteer; // pointer to alignment steering object + AliAlgSteer* mAlgSteer; // pointer to alignment steering object // ClassDef(AliAlgDet, 1); // base class for detector global alignment }; @@ -246,7 +246,7 @@ class AliAlgDet : public TNamed //inline bool AliAlgDet::CheckFlags(const AliESDtrack* trc, int trtype) const //{ // // check if flags are ok -// return (trc->GetStatus() & fTrackFlagSel[trtype]) == fTrackFlagSel[trtype]; +// return (trc->GetStatus() & mTrackFlagSel[trtype]) == mTrackFlagSel[trtype]; //} } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgDetHMPID.h b/Detectors/Align/include/Align/AliAlgDetHMPID.h index 684d2b2a6541f..feb0b8c4361c3 100644 --- a/Detectors/Align/include/Align/AliAlgDetHMPID.h +++ b/Detectors/Align/include/Align/AliAlgDetHMPID.h @@ -28,7 +28,7 @@ class AliAlgDetHMPID : public AliAlgDet AliAlgDetHMPID(const char* title = ""); virtual ~AliAlgDetHMPID(); // - virtual void DefineVolumes(); + virtual void defineVolumes(); // bool AcceptTrack(const AliESDtrack* trc, int trtype) const; // diff --git a/Detectors/Align/include/Align/AliAlgDetITS.h b/Detectors/Align/include/Align/AliAlgDetITS.h index e9221b3254696..cf7207d31b89e 100644 --- a/Detectors/Align/include/Align/AliAlgDetITS.h +++ b/Detectors/Align/include/Align/AliAlgDetITS.h @@ -38,7 +38,7 @@ class AliAlgDetITS : public AliAlgDet AliAlgDetITS(const char* title = ""); virtual ~AliAlgDetITS(); // - virtual void DefineVolumes(); + virtual void defineVolumes(); // bool AcceptTrack(const AliESDtrack* trc, int trtype) const; @@ -46,7 +46,7 @@ class AliAlgDetITS : public AliAlgDet void SetSkipLr(int ilr); // virtual void UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const; - virtual void SetUseErrorParam(int v = 1); + virtual void setUseErrorParam(int v = 1); void SetITSSelPattern(int trtype, ITSSel_t sel) { fITSPatt[trtype] = sel; } void SetITSSelPatternColl(ITSSel_t sel = kSPDAny) { SetITSSelPattern(AliAlgAux::kColl, sel); } void SetITSSelPatternCosm(ITSSel_t sel = kSPDNoSel) { SetITSSelPattern(AliAlgAux::kCosm, sel); } diff --git a/Detectors/Align/include/Align/AliAlgDetTOF.h b/Detectors/Align/include/Align/AliAlgDetTOF.h index 2ae4186cd11b7..6cd982d5be0cd 100644 --- a/Detectors/Align/include/Align/AliAlgDetTOF.h +++ b/Detectors/Align/include/Align/AliAlgDetTOF.h @@ -29,7 +29,7 @@ class AliAlgDetTOF : public AliAlgDet AliAlgDetTOF(const char* title = ""); virtual ~AliAlgDetTOF(); // - virtual void DefineVolumes(); + virtual void defineVolumes(); // bool AcceptTrack(const AliESDtrack* trc, int trtype) const; // diff --git a/Detectors/Align/include/Align/AliAlgDetTPC.h b/Detectors/Align/include/Align/AliAlgDetTPC.h index da0854c071d0e..9f30ac5f41ee4 100644 --- a/Detectors/Align/include/Align/AliAlgDetTPC.h +++ b/Detectors/Align/include/Align/AliAlgDetTPC.h @@ -29,7 +29,7 @@ class AliAlgDetTPC : public AliAlgDet AliAlgDetTPC(const char* title = ""); virtual ~AliAlgDetTPC(); // - virtual void DefineVolumes(); + virtual void defineVolumes(); // bool AcceptTrack(const AliESDtrack* trc, int trtype) const; // diff --git a/Detectors/Align/include/Align/AliAlgDetTRD.h b/Detectors/Align/include/Align/AliAlgDetTRD.h index 28876444d83d1..2a22be8095b3b 100644 --- a/Detectors/Align/include/Align/AliAlgDetTRD.h +++ b/Detectors/Align/include/Align/AliAlgDetTRD.h @@ -34,25 +34,25 @@ class AliAlgDetTRD : public AliAlgDet AliAlgDetTRD(const char* title = ""); virtual ~AliAlgDetTRD(); // - virtual void DefineVolumes(); + virtual void defineVolumes(); virtual void Print(const Option_t* opt = "") const; // bool AcceptTrack(const AliESDtrack* trc, int trtype) const; // - virtual const char* GetCalibDOFName(int i) const; + virtual const char* getCalibDOFName(int i) const; // - virtual void WritePedeInfo(FILE* parOut, const Option_t* opt = "") const; + virtual void writePedeInfo(FILE* parOut, const Option_t* opt = "") const; // void SetNonRCCorrDzDtgl(double v = 0) { fNonRCCorrDzDtgl = v; } double GetNonRCCorrDzDtgl() const { return fNonRCCorrDzDtgl; } - double GetNonRCCorrDzDtglWithCal() const { return GetNonRCCorrDzDtgl() + GetParVal(kCalibNRCCorrDzDtgl); } + double GetNonRCCorrDzDtglWithCal() const { return GetNonRCCorrDzDtgl() + getParVal(kCalibNRCCorrDzDtgl); } // void SetCorrDVT(double v = 0) { fCorrDVT = 0; } double GetCorrDVT() const { return fCorrDVT; } - double GetCorrDVTWithCal() const { return GetCorrDVT() + GetParVal(kCalibDVT); } + double GetCorrDVTWithCal() const { return GetCorrDVT() + getParVal(kCalibDVT); } // - virtual double GetCalibDOFVal(int id) const; - virtual double GetCalibDOFValWithCal(int id) const; + virtual double getCalibDOFVal(int id) const; + virtual double getCalibDOFValWithCal(int id) const; // const double* GetExtraErrRC() const { return fExtraErrRC; } void SetExtraErrRC(double y = 0.2, double z = 1.0) diff --git a/Detectors/Align/include/Align/AliAlgMPRecord.h b/Detectors/Align/include/Align/AliAlgMPRecord.h index 1565a6a8980f6..9b8d55fd6d393 100644 --- a/Detectors/Align/include/Align/AliAlgMPRecord.h +++ b/Detectors/Align/include/Align/AliAlgMPRecord.h @@ -33,41 +33,41 @@ class AliAlgMPRecord : public TObject AliAlgMPRecord(); virtual ~AliAlgMPRecord(); // - int GetRun() const { return GetUniqueID(); } - void SetRun(int r) { SetUniqueID(r); } - uint32_t GetTimeStamp() const { return fTimeStamp; } - void SetTimeStamp(uint32_t t) { fTimeStamp = t; } - uint32_t GetTrackID() const { return fTrackID; } - void SetTrackID(uint32_t t) { fTrackID = t; } - bool IsCosmic() const { return TestBit(kCosmicBit); } - void SetCosmic(bool v = true) { SetBit(kCosmicBit, v); } - // - int GetNVarGlo() const { return fNVarGlo; } - void SetNVarGlo(int n) { fNVarGlo = n; } - // - int GetNResid() const { return fNResid; } - int GetNVarLoc() const { return fNVarLoc; } - // - int GetNDLoc(int id) const { return fNDLoc[id]; } - int GetNDGlo(int id) const { return fNDGlo[id]; } - int GetVolID(int id) const { return fVolID ? fVolID[id] - 1 : -1; } - float GetResid(int id) const { return fResid[id]; } - float GetResErr(int id) const { return fResErr[id]; } - // - float GetChi2Ini() const { return fChi2Ini; } - float GetQ2Pt() const { return fQ2Pt; } - float GetTgl() const { return fTgl; } - int GetNDLocTot() const { return fNDLocTot; } - int GetNDGloTot() const { return fNDGloTot; } - const float* GetArrGlo() const { return fDGlo; } - const float* GetArrLoc() const { return fDLoc; } - const int16_t* GetArrLabLoc() const { return fIDLoc; } - const int* GetArrLabGlo() const { return fIDGlo; } - // - bool FillTrack(const AliAlgTrack* trc, const int* id2Lab = 0); - void DummyRecord(float res, float err, float dGlo, int labGlo); - // - void Resize(int nresid, int nloc, int nglo); + int getRun() const { return GetUniqueID(); } + void setRun(int r) { SetUniqueID(r); } + uint32_t getTimeStamp() const { return mTimeStamp; } + void setTimeStamp(uint32_t t) { mTimeStamp = t; } + uint32_t getTrackID() const { return mTrackID; } + void setTrackID(uint32_t t) { mTrackID = t; } + bool isCosmic() const { return TestBit(kCosmicBit); } + void setCosmic(bool v = true) { SetBit(kCosmicBit, v); } + // + int getNVarGlo() const { return mNVarGlo; } + void setNVarGlo(int n) { mNVarGlo = n; } + // + int getNResid() const { return mNResid; } + int getNVarLoc() const { return mNVarLoc; } + // + int getNDLoc(int id) const { return mNDLoc[id]; } + int getNDGlo(int id) const { return mNDGlo[id]; } + int getVolID(int id) const { return mVolID ? mVolID[id] - 1 : -1; } + float getResid(int id) const { return mResid[id]; } + float getResErr(int id) const { return mResErr[id]; } + // + float getChi2Ini() const { return mChi2Ini; } + float getQ2Pt() const { return mQ2Pt; } + float getTgl() const { return mTgl; } + int getNDLocTot() const { return mNDLocTot; } + int getNDGloTot() const { return mNDGloTot; } + const float* getArrGlo() const { return mDGlo; } + const float* getArrLoc() const { return mDLoc; } + const int16_t* getArrLabLoc() const { return mIDLoc; } + const int* getArrLabGlo() const { return mIDGlo; } + // + bool fillTrack(const AliAlgTrack* trc, const int* id2Lab = 0); + void dummyRecord(float res, float err, float dGlo, int labGlo); + // + void resize(int nresid, int nloc, int nglo); // virtual void Clear(const Option_t* opt = ""); virtual void Print(const Option_t* opt = "") const; @@ -80,33 +80,33 @@ class AliAlgMPRecord : public TObject // protected: // - uint32_t fTrackID; // track in the event - uint32_t fTimeStamp; // event time stamp - int fNResid; // number of residuals for the track (=2 npoints) - int fNVarLoc; // number of local variables for the track - int fNVarGlo; // number of global variables defined - int fNDLocTot; // total number of non-zero local derivatives - int fNDGloTot; // total number of non-zero global derivatives - int fNMeas; // number of measured points - float fChi2Ini; // chi2 of initial kalman fit - float fQ2Pt; // q/pt at ref point - float fTgl; // dip angle at ref point - // - int16_t* fNDLoc; //[fNResid] number of non-0 local derivatives per residual - int* fNDGlo; //[fNResid] number of non-0 global derivatives per residual - int* fVolID; //[fNResid] volume id + 1 (0 - not a volume) - float* fResid; //[fNResid] residuals - float* fResErr; //[fNResid] error associated to residual - // - int16_t* fIDLoc; //[fNDLocTot] ID of local variables for non-0 local derivatives - int* fIDGlo; //[fNDGloTot] ID of global variables for non-0 global derivatives - float* fDLoc; //[fNDLocTot] non-0 local derivatives - float* fDGlo; //[fNDGloTot] non-0 global derivatives + uint32_t mTrackID; // track in the event + uint32_t mTimeStamp; // event time stamp + int mNResid; // number of residuals for the track (=2 npoints) + int mNVarLoc; // number of local variables for the track + int mNVarGlo; // number of global variables defined + int mNDLocTot; // total number of non-zero local derivatives + int mNDGloTot; // total number of non-zero global derivatives + int mNMeas; // number of measured points + float mChi2Ini; // chi2 of initial kalman fit + float mQ2Pt; // q/pt at ref point + float mTgl; // dip angle at ref point + // + int16_t* mNDLoc; //[mNResid] number of non-0 local derivatives per residual + int* mNDGlo; //[mNResid] number of non-0 global derivatives per residual + int* mVolID; //[mNResid] volume id + 1 (0 - not a volume) + float* mResid; //[mNResid] residuals + float* mResErr; //[mNResid] error associated to residual + // + int16_t* mIDLoc; //[mNDLocTot] ID of local variables for non-0 local derivatives + int* mIDGlo; //[mNDGloTot] ID of global variables for non-0 global derivatives + float* mDLoc; //[mNDLocTot] non-0 local derivatives + float* mDGlo; //[mNDGloTot] non-0 global derivatives // // aux info - int fNResidBook; //! number of slots booked for residuals - int fNDLocTotBook; //! number of slots booked for local derivatives - int fNDGloTotBook; //! number of slots booked for global derivatives + int mNResidBook; //! number of slots booked for residuals + int mNDLocTotBook; //! number of slots booked for local derivatives + int mNDGloTotBook; //! number of slots booked for global derivatives // ClassDef(AliAlgMPRecord, 4); }; diff --git a/Detectors/Align/include/Align/AliAlgPoint.h b/Detectors/Align/include/Align/AliAlgPoint.h index fec0205a7a24f..fe2606b678d5f 100644 --- a/Detectors/Align/include/Align/AliAlgPoint.h +++ b/Detectors/Align/include/Align/AliAlgPoint.h @@ -63,120 +63,120 @@ class AliAlgPoint : public TObject AliAlgPoint(); virtual ~AliAlgPoint() {} // - void Init(); - void UpdatePointByTrackInfo(const trackParam_t* t); + void init(); + void updatePointByTrackInfo(const trackParam_t* t); // - double GetAlphaSens() const { return fAlphaSens; } - double GetXSens() const { return fXSens; } - double GetXPoint() const { return fXSens + GetXTracking(); } - double GetXTracking() const { return fXYZTracking[0]; } - double GetYTracking() const { return fXYZTracking[1]; } - double GetZTracking() const { return fXYZTracking[2]; } - const double* GetYZTracking() const { return &fXYZTracking[1]; } - const double* GetXYZTracking() const { return fXYZTracking; } - const double* GetYZErrTracking() const { return fErrYZTracking; } + double getAlphaSens() const { return mAlphaSens; } + double getXSens() const { return mXSens; } + double getXPoint() const { return mXSens + getXTracking(); } + double getXTracking() const { return mXYZTracking[0]; } + double getYTracking() const { return mXYZTracking[1]; } + double getZTracking() const { return mXYZTracking[2]; } + const double* getYZTracking() const { return &mXYZTracking[1]; } + const double* getXYZTracking() const { return mXYZTracking; } + const double* getYZErrTracking() const { return mErrYZTracking; } - const AliAlgSens* GetSensor() const { return fSensor; } - uint32_t GetVolID() const { return fSensor->GetVolID(); } - void SetSensor(AliAlgSens* s) { fSensor = s; } + const AliAlgSens* getSensor() const { return mSensor; } + uint32_t getVolID() const { return mSensor->getVolID(); } + void setSensor(AliAlgSens* s) { mSensor = s; } - int GetDetID() const { return fDetID; } - int GetSID() const { return fSID; } - int GetMinLocVarID() const { return fMinLocVarID; } - int GetMaxLocVarID() const { return fMaxLocVarID; } - int GetNMatPar() const; - bool ContainsMaterial() const { return TestBit(kMaterialBit); } - bool ContainsMeasurement() const { return TestBit(kMeasurementBit); } - bool GetNeedUpdateFromTrack() const { return TestBit(kUpdateFromTrackBit); } - bool GetELossVaried() const { return TestBit(kVaryELossBit); } - bool GetUseBzOnly() const { return TestBit(kUseBzOnly); } - bool IsInvDir() const { return TestBit(kInvDir); } - bool IsStatOK() const { return TestBit(kStatOK); } + int getDetID() const { return mDetID; } + int getSID() const { return mSID; } + int getMinLocVarID() const { return mMinLocVarID; } + int getMaxLocVarID() const { return mMaxLocVarID; } + int getNMatPar() const; + bool containsMaterial() const { return TestBit(kMaterialBit); } + bool containsMeasurement() const { return TestBit(kMeasurementBit); } + bool getNeedUpdateFromTrack() const { return TestBit(kUpdateFromTrackBit); } + bool getELossVaried() const { return TestBit(kVaryELossBit); } + bool getUseBzOnly() const { return TestBit(kUseBzOnly); } + bool isInvDir() const { return TestBit(kInvDir); } + bool isStatOK() const { return TestBit(kStatOK); } // - double GetXTimesRho() const { return fXTimesRho; } - double GetX2X0() const { return fX2X0; } - void SetXTimesRho(double v) { fXTimesRho = v; } - void SetX2X0(double v) { fX2X0 = v; } + double getXTimesRho() const { return mXTimesRho; } + double getX2X0() const { return mX2X0; } + void setXTimesRho(double v) { mXTimesRho = v; } + void setX2X0(double v) { mX2X0 = v; } // - void SetDetID(int id) { fDetID = (char)id; } - void SetSID(int id) { fSID = (int16_t)id; } + void setDetID(int id) { mDetID = (char)id; } + void setSID(int id) { mSID = (int16_t)id; } // - void SetMinLocVarID(int id) { fMinLocVarID = id; } - void SetMaxLocVarID(int id) { fMaxLocVarID = id; } - void SetELossVaried(bool v = true) { SetBit(kVaryELossBit, v); } - void SetContainsMaterial(bool v = true) { SetBit(kMaterialBit, v); } - void SetContainsMeasurement(bool v = true) { SetBit(kMeasurementBit, v); } - void SetNeedUpdateFromTrack(bool v = true) { SetBit(kUpdateFromTrackBit, v); } - void SetUseBzOnly(bool v = true) { SetBit(kUseBzOnly, v); } - void SetInvDir(bool v = true) { SetBit(kInvDir, v); } - void SetStatOK(bool v = true) { SetBit(kStatOK, v); } + void setMinLocVarID(int id) { mMinLocVarID = id; } + void setMaxLocVarID(int id) { mMaxLocVarID = id; } + void setELossVaried(bool v = true) { SetBit(kVaryELossBit, v); } + void setContainsMaterial(bool v = true) { SetBit(kMaterialBit, v); } + void setContainsMeasurement(bool v = true) { SetBit(kMeasurementBit, v); } + void setNeedUpdateFromTrack(bool v = true) { SetBit(kUpdateFromTrackBit, v); } + void setUseBzOnly(bool v = true) { SetBit(kUseBzOnly, v); } + void setInvDir(bool v = true) { SetBit(kInvDir, v); } + void setStatOK(bool v = true) { SetBit(kStatOK, v); } // - void GetResidualsDiag(const double* pos, double& resU, double& resV) const; - void DiagonalizeResiduals(double rY, double rZ, double& resU, double& resV) const; + void getResidualsDiag(const double* pos, double& resU, double& resV) const; + void diagonalizeResiduals(double rY, double rZ, double& resU, double& resV) const; // - void SetAlphaSens(double a) { fAlphaSens = a; } - void SetXSens(double x) { fXSens = x; } - void SetXYZTracking(const double r[3]) + void setAlphaSens(double a) { mAlphaSens = a; } + void setXSens(double x) { mXSens = x; } + void setXYZTracking(const double r[3]) { for (int i = 3; i--;) - fXYZTracking[i] = r[i]; + mXYZTracking[i] = r[i]; } - void SetXYZTracking(double x, double y, double z); - void SetYZErrTracking(double sy2, double syz, double sz2); - void SetYZErrTracking(const double* err) + void setXYZTracking(double x, double y, double z); + void setYZErrTracking(double sy2, double syz, double sz2); + void setYZErrTracking(const double* err) { for (int i = 3; i--;) - fErrYZTracking[i] = err[i]; + mErrYZTracking[i] = err[i]; } - double GetErrDiag(int i) const { return fErrDiag[i]; } + double getErrDiag(int i) const { return mErrDiag[i]; } // - double* GetTrParamWSA() const { return (double*)fTrParamWSA; } - double* GetTrParamWSB() const { return (double*)fTrParamWSB; } - double GetTrParamWSA(int ip) const { return fTrParamWSA[ip]; } - double GetTrParamWSB(int ip) const { return fTrParamWSB[ip]; } - void GetTrWSA(trackParam_t& etp) const; - void GetTrWSB(trackParam_t& etp) const; - void SetTrParamWSA(const double* param) + double* getTrParamWSA() const { return (double*)mTrParamWSA; } + double* getTrParamWSB() const { return (double*)mTrParamWSB; } + double getTrParamWSA(int ip) const { return mTrParamWSA[ip]; } + double getTrParamWSB(int ip) const { return mTrParamWSB[ip]; } + void getTrWSA(trackParam_t& etp) const; + void getTrWSB(trackParam_t& etp) const; + void setTrParamWSA(const double* param) { for (int i = 5; i--;) - fTrParamWSA[i] = param[i]; + mTrParamWSA[i] = param[i]; } - void SetTrParamWSB(const double* param) + void setTrParamWSB(const double* param) { for (int i = 5; i--;) - fTrParamWSB[i] = param[i]; + mTrParamWSB[i] = param[i]; } - double GetResidY() const { return GetTrParamWSA(kParY) - GetYTracking(); } - double GetResidZ() const { return GetTrParamWSA(kParZ) - GetZTracking(); } + double getResidY() const { return getTrParamWSA(kParY) - getYTracking(); } + double getResidZ() const { return getTrParamWSA(kParZ) - getZTracking(); } // - void SetMatCovDiagonalizationMatrix(const TMatrixD& d); - void SetMatCovDiag(const TVectorD& v); - void SetMatCovDiagElem(int i, double err2) { fMatCorrCov[i] = err2; } - void UnDiagMatCorr(const double* diag, double* nodiag) const; - void DiagMatCorr(const double* nodiag, double* diag) const; - void UnDiagMatCorr(const float* diag, float* nodiag) const; - void DiagMatCorr(const float* nodiag, float* diag) const; + void setMatCovDiagonalizationMatrix(const TMatrixD& d); + void setMatCovDiag(const TVectorD& v); + void setMatCovDiagElem(int i, double err2) { mMatCorrCov[i] = err2; } + void unDiagMatCorr(const double* diag, double* nodiag) const; + void diagMatCorr(const double* nodiag, double* diag) const; + void unDiagMatCorr(const float* diag, float* nodiag) const; + void diagMatCorr(const float* nodiag, float* diag) const; // - void SetMatCorrExp(double* p) + void setMatCorrExp(double* p) { for (int i = 5; i--;) - fMatCorrExp[i] = p[i]; + mMatCorrExp[i] = p[i]; } - float* GetMatCorrExp() const { return (float*)fMatCorrExp; } - float* GetMatCorrCov() const { return (float*)fMatCorrCov; } + float* getMatCorrExp() const { return (float*)mMatCorrExp; } + float* getMatCorrCov() const { return (float*)mMatCorrCov; } // - void GetXYZGlo(double r[3]) const; - double GetPhiGlo() const; - int GetAliceSector() const; + void getXYZGlo(double r[3]) const; + double getPhiGlo() const; + int getAliceSector() const; // - int GetNGloDOFs() const { return fNGloDOFs; } - int GetDGloOffs() const { return fDGloOffs; } - void SetNGloDOFs(int n) { fNGloDOFs = n; } - void SetDGloOffs(int n) { fDGloOffs = n; } + int getNGloDOFs() const { return mNGloDOFs; } + int getDGloOffs() const { return mDGloOffs; } + void setNGloDOFs(int n) { mNGloDOFs = n; } + void setDGloOffs(int n) { mDGloOffs = n; } // - void IncrementStat(); + void incrementStat(); // - virtual void DumpCoordinates() const; + virtual void dumpCoordinates() const; virtual void Print(Option_t* option = "") const; virtual void Clear(Option_t* option = ""); // @@ -190,87 +190,87 @@ class AliAlgPoint : public TObject // protected: // - int fMinLocVarID; // The residuals/derivatives depend on fNLocExtPar params - // and point params>=fMinLocVarID. - int fMaxLocVarID; // The residuals/derivatives depend on fNLocExtPar params - // and point params=mMinLocVarID. + int mMaxLocVarID; // The residuals/derivatives depend on fNLocExtPar params + // and point paramsIncrementStat(); - SetStatOK(); + mSensor->incrementStat(); + setStatOK(); } } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgRes.h b/Detectors/Align/include/Align/AliAlgRes.h index c39a0fd934737..b4d37d512211f 100644 --- a/Detectors/Align/include/Align/AliAlgRes.h +++ b/Detectors/Align/include/Align/AliAlgRes.h @@ -36,71 +36,71 @@ class AliAlgRes : public TObject AliAlgRes(); virtual ~AliAlgRes(); // - void SetRun(int r) { fRun = r; } - void SetBz(float v) { fBz = v; } - void SetTimeStamp(uint32_t v) { fTimeStamp = v; } - void SetTrackID(uint32_t v) { fTrackID = v; } - void SetNPoints(int n) + void setRun(int r) { mRun = r; } + void setBz(float v) { mBz = v; } + void setTimeStamp(uint32_t v) { mTimeStamp = v; } + void setTrackID(uint32_t v) { mTrackID = v; } + void setNPoints(int n) { - fNPoints = n; - Resize(n); + mNPoints = n; + resize(n); } // - bool IsCosmic() const { return TestBit(kCosmicBit); } - bool HasVertex() const { return TestBit(kVertexBit); } - void SetCosmic(bool v = true) { SetBit(kCosmicBit, v); } - void SetHasVertex(bool v = true) { SetBit(kVertexBit, v); } - // - bool GetKalmanDone() const { return TestBit(kKalmanDoneBit); } - void SetKalmanDone(bool v = true) { SetBit(kKalmanDoneBit, v); } - // - int GetRun() const { return fRun; } - float GetBz() const { return fBz; } - uint32_t GetTimeStamp() const { return fTimeStamp; } - uint32_t GetTrackID() const { return fTrackID; } - int GetNPoints() const { return fNPoints; } - int GetNBook() const { return fNBook; } - float GetChi2() const { return fChi2; } - float GetChi2Ini() const { return fChi2Ini; } - float GetChi2K() const { return fChi2K; } - float GetQ2Pt() const { return fQ2Pt; } - float GetX(int i) const { return fX[i]; } - float GetY(int i) const { return fY[i]; } - float GetZ(int i) const { return fZ[i]; } - float GetSnp(int i) const { return fSnp[i]; } - float GetTgl(int i) const { return fTgl[i]; } - float GetAlpha(int i) const { return fAlpha[i]; } - float GetDY(int i) const { return fDY[i]; } - float GetDZ(int i) const { return fDZ[i]; } - float GetDYK(int i) const { return fDYK[i]; } - float GetDZK(int i) const { return fDZK[i]; } - // - float GetSigY2K(int i) const { return fSigY2K[i]; } - float GetSigYZK(int i) const { return fSigYZK[i]; } - float GetSigZ2K(int i) const { return fSigZ2K[i]; } - float GetSigmaYK(int i) const { return TMath::Sqrt(fSigY2K[i]); } - float GetSigmaZK(int i) const { return TMath::Sqrt(fSigZ2K[i]); } - // - float GetSigY2(int i) const { return fSigY2[i]; } - float GetSigYZ(int i) const { return fSigYZ[i]; } - float GetSigZ2(int i) const { return fSigZ2[i]; } - float GetSigmaY(int i) const { return TMath::Sqrt(fSigY2[i]); } - float GetSigmaZ(int i) const { return TMath::Sqrt(fSigZ2[i]); } - // - float GetSigY2Tot(int i) const { return fSigY2K[i] + fSigY2[i]; } - float GetSigYZTot(int i) const { return fSigYZK[i] + fSigYZ[i]; } - float GetSigZ2Tot(int i) const { return fSigZ2K[i] + fSigZ2[i]; } - float GetSigmaYTot(int i) const { return TMath::Sqrt(GetSigY2Tot(i)); } - float GetSigmaZTot(int i) const { return TMath::Sqrt(GetSigZ2Tot(i)); } - // - int GetVolID(int i) const { return fVolID[i]; } - // - float GetXLab(int i) const; - float GetYLab(int i) const; - float GetZLab(int i) const; - // - bool FillTrack(AliAlgTrack* trc, bool doKalman = true); - void Resize(int n); + bool isCosmic() const { return TestBit(kCosmicBit); } + bool hasVertex() const { return TestBit(kVertexBit); } + void setCosmic(bool v = kTRUE) { SetBit(kCosmicBit, v); } + void setHasVertex(bool v = kTRUE) { SetBit(kVertexBit, v); } + // + bool getKalmanDone() const { return TestBit(kKalmanDoneBit); } + void setKalmanDone(bool v = kTRUE) { SetBit(kKalmanDoneBit, v); } + // + int getRun() const { return mRun; } + float getBz() const { return mBz; } + uint32_t getTimeStamp() const { return mTimeStamp; } + uint32_t getTrackID() const { return mTrackID; } + int getNPoints() const { return mNPoints; } + int getNBook() const { return mNBook; } + float getChi2() const { return mChi2; } + float getChi2Ini() const { return mChi2Ini; } + float getChi2K() const { return mChi2K; } + float getQ2Pt() const { return mQ2Pt; } + float getX(int i) const { return mX[i]; } + float getY(int i) const { return mY[i]; } + float getZ(int i) const { return mZ[i]; } + float getSnp(int i) const { return mSnp[i]; } + float getTgl(int i) const { return mTgl[i]; } + float getAlpha(int i) const { return mAlpha[i]; } + float getDY(int i) const { return mDY[i]; } + float getDZ(int i) const { return mDZ[i]; } + float getDYK(int i) const { return mDYK[i]; } + float getDZK(int i) const { return mDZK[i]; } + // + float getSigY2K(int i) const { return mSigY2K[i]; } + float getSigYZK(int i) const { return mSigYZK[i]; } + float getSigZ2K(int i) const { return mSigZ2K[i]; } + float getSigmaYK(int i) const { return TMath::Sqrt(mSigY2K[i]); } + float getSigmaZK(int i) const { return TMath::Sqrt(mSigZ2K[i]); } + // + float getSigY2(int i) const { return mSigY2[i]; } + float getSigYZ(int i) const { return mSigYZ[i]; } + float getSigZ2(int i) const { return mSigZ2[i]; } + float getSigmaY(int i) const { return TMath::Sqrt(mSigY2[i]); } + float getSigmaZ(int i) const { return TMath::Sqrt(mSigZ2[i]); } + // + float getSigY2Tot(int i) const { return mSigY2K[i] + mSigY2[i]; } + float getSigYZTot(int i) const { return mSigYZK[i] + mSigYZ[i]; } + float getSigZ2Tot(int i) const { return mSigZ2K[i] + mSigZ2[i]; } + float getSigmaYTot(int i) const { return TMath::Sqrt(getSigY2Tot(i)); } + float getSigmaZTot(int i) const { return TMath::Sqrt(getSigZ2Tot(i)); } + // + int getVolID(int i) const { return mVolID[i]; } + // + float getXLab(int i) const; + float getYLab(int i) const; + float getZLab(int i) const; + // + bool fillTrack(AliAlgTrack* trc, bool doKalman = kTRUE); + void resize(int n); virtual void Clear(const Option_t* opt = ""); virtual void Print(const Option_t* opt = "re") const; // @@ -112,34 +112,34 @@ class AliAlgRes : public TObject // protected: // - int fRun; // run - float fBz; // field - uint32_t fTimeStamp; // event time - uint32_t fTrackID; // track ID - int fNPoints; // n meas points - int fNBook; //! booked lenfth - float fChi2; // chi2 after solution - float fChi2Ini; // chi2 before solution - float fChi2K; // chi2 from kalman - float fQ2Pt; // Q/Pt at reference point - float* fX; //[fNPoints] tracking X of cluster - float* fY; //[fNPoints] tracking Y of cluster - float* fZ; //[fNPoints] tracking Z of cluster - float* fSnp; //[fNPoints] track Snp - float* fTgl; //[fNPoints] track Tgl - float* fAlpha; //[fNPoints] track alpha - float* fDY; //[fNPoints] Y residual (track - meas) - float* fDZ; //[fNPoints] Z residual (track - meas) - float* fDYK; //[fNPoints] Y residual (track - meas) Kalman - float* fDZK; //[fNPoints] Z residual (track - meas) Kalman - float* fSigY2; //[fNPoints] Y err^2 - float* fSigYZ; //[fNPoints] YZ err - float* fSigZ2; //[fNPoints] Z err^2 - float* fSigY2K; //[fNPoints] Y err^2 of Kalman track smoothing - float* fSigYZK; //[fNPoints] YZ err of Kalman track smoothing - float* fSigZ2K; //[fNPoints] Z err^2 of Kalman track smoothing - int* fVolID; //[fNPoints] volume id (0 for vertex constraint) - int* fLabel; //[fNPoints] label of the volume + int mRun; // run + float mBz; // field + uint32_t mTimeStamp; // event time + uint32_t mTrackID; // track ID + int mNPoints; // n meas points + int mNBook; //! booked lenfth + float mChi2; // chi2 after solution + float mChi2Ini; // chi2 before solution + float mChi2K; // chi2 from kalman + float mQ2Pt; // Q/Pt at reference point + float* mX; //[mNPoints] tracking X of cluster + float* mY; //[mNPoints] tracking Y of cluster + float* mZ; //[mNPoints] tracking Z of cluster + float* mSnp; //[mNPoints] track Snp + float* mTgl; //[mNPoints] track Tgl + float* mAlpha; //[mNPoints] track alpha + float* mDY; //[mNPoints] Y residual (track - meas) + float* mDZ; //[mNPoints] Z residual (track - meas) + float* mDYK; //[mNPoints] Y residual (track - meas) Kalman + float* mDZK; //[mNPoints] Z residual (track - meas) Kalman + float* mSigY2; //[mNPoints] Y err^2 + float* mSigYZ; //[mNPoints] YZ err + float* mSigZ2; //[mNPoints] Z err^2 + float* mSigY2K; //[mNPoints] Y err^2 of Kalman track smoothing + float* mSigYZK; //[mNPoints] YZ err of Kalman track smoothing + float* mSigZ2K; //[mNPoints] Z err^2 of Kalman track smoothing + int* mVolID; //[mNPoints] volume id (0 for vertex constraint) + int* mLabel; //[mNPoints] label of the volume // ClassDef(AliAlgRes, 2); }; diff --git a/Detectors/Align/include/Align/AliAlgResFast.h b/Detectors/Align/include/Align/AliAlgResFast.h index 54b022b0c31d5..88e86a2c7e0cb 100644 --- a/Detectors/Align/include/Align/AliAlgResFast.h +++ b/Detectors/Align/include/Align/AliAlgResFast.h @@ -32,49 +32,49 @@ class AliAlgResFast : public TObject AliAlgResFast(); virtual ~AliAlgResFast(); // - void SetNPoints(int n) + void setNPoints(int n) { - fNPoints = n; - Resize(n); + mNPoints = n; + resize(n); } - void SetNMatSol(int n) { fNMatSol = n; } - // - void SetChi2(float v) { fChi2 = v; } - float GetChi2() const { return fChi2; } - // - void SetChi2Ini(float v) { fChi2Ini = v; } - float GetChi2Ini() const { return fChi2Ini; } - // - bool IsCosmic() const { return TestBit(kCosmicBit); } - bool HasVertex() const { return TestBit(kVertexBit); } - void SetCosmic(bool v = true) { SetBit(kCosmicBit, v); } - void SetHasVertex(bool v = true) { SetBit(kVertexBit, v); } - // - int GetNPoints() const { return fNPoints; } - int GetNMatSol() const { return fNMatSol; } - int GetNBook() const { return fNBook; } - float GetD0(int i) const { return fD0[i]; } - float GetD1(int i) const { return fD1[i]; } - float GetSig0(int i) const { return fSig0[i]; } - float GetSig1(int i) const { return fSig1[i]; } - int GetVolID(int i) const { return fVolID[i]; } - int GetLabel(int i) const { return fLabel[i]; } - // - float* GetTrCor() const { return (float*)fTrCorr; } - float* GetD0() const { return (float*)fD0; } - float* GetD1() const { return (float*)fD1; } - float* GetSig0() const { return (float*)fSig0; } - float* GetSig1() const { return (float*)fSig1; } - int* GetVolID() const { return (int*)fVolID; } - int* GetLaber() const { return (int*)fLabel; } - float* GetSolMat() const { return (float*)fSolMat; } - float* GetMatErr() const { return (float*)fMatErr; } - // - void SetResSigMeas(int ip, int ord, float res, float sig); - void SetMatCorr(int id, float res, float sig); - void SetLabel(int ip, int lab, int vol); - // - void Resize(int n); + void setNMatSol(int n) { mNMatSol = n; } + // + void setChi2(float v) { mChi2 = v; } + float getChi2() const { return mChi2; } + // + void setChi2Ini(float v) { mChi2Ini = v; } + float getChi2Ini() const { return mChi2Ini; } + // + bool isCosmic() const { return TestBit(kCosmicBit); } + bool hasVertex() const { return TestBit(kVertexBit); } + void setCosmic(bool v = true) { SetBit(kCosmicBit, v); } + void setHasVertex(bool v = true) { SetBit(kVertexBit, v); } + // + int getNPoints() const { return mNPoints; } + int getNMatSol() const { return mNMatSol; } + int getNBook() const { return mNBook; } + float getD0(int i) const { return mD0[i]; } + float getD1(int i) const { return mD1[i]; } + float getSig0(int i) const { return mSig0[i]; } + float getSig1(int i) const { return mSig1[i]; } + int getVolID(int i) const { return mVolID[i]; } + int getLabel(int i) const { return mLabel[i]; } + // + float* getTrCor() const { return (float*)mTrCorr; } + float* getD0() const { return (float*)mD0; } + float* getD1() const { return (float*)mD1; } + float* getSig0() const { return (float*)mSig0; } + float* getSig1() const { return (float*)mSig1; } + int* getVolID() const { return (int*)mVolID; } + int* getLaber() const { return (int*)mLabel; } + float* getSolMat() const { return (float*)mSolMat; } + float* getMatErr() const { return (float*)mMatErr; } + // + void setResSigMeas(int ip, int ord, float res, float sig); + void setMatCorr(int id, float res, float sig); + void setLabel(int ip, int lab, int vol); + // + void resize(int n); virtual void Clear(const Option_t* opt = ""); virtual void Print(const Option_t* opt = "") const; // @@ -86,22 +86,22 @@ class AliAlgResFast : public TObject // protected: // - int fNPoints; // n meas points - int fNMatSol; // n local params - ExtTrPar corrections - int fNBook; //! booked lenfth - float fChi2; // chi2 - float fChi2Ini; // chi2 before local fit - // - float fTrCorr[5]; // correction to ExternalTrackParam - float* fD0; //[fNPoints] 1st residual (track - meas) - float* fD1; //[fNPoints] 2ns residual (track - meas) - float* fSig0; //[fNPoints] ort. error 0 - float* fSig1; //[fNPoints] ort. errir 1 - int* fVolID; //[fNPoints] volume id (0 for vertex constraint) - int* fLabel; //[fNPoints] label of the volume - // - float* fSolMat; //[fNMatSol] // material corrections - float* fMatErr; //[fNMatSol] // material corrections errors + int mNPoints; // n meas points + int mNMatSol; // n local params - ExtTrPar corrections + int mNBook; //! booked lenfth + float mChi2; // chi2 + float mChi2Ini; // chi2 before local fit + // + float mTrCorr[5]; // correction to ExternalTrackParam + float* mD0; //[mNPoints] 1st residual (track - meas) + float* mD1; //[mNPoints] 2ns residual (track - meas) + float* mSig0; //[mNPoints] ort. error 0 + float* mSig1; //[mNPoints] ort. errir 1 + int* mVolID; //[mNPoints] volume id (0 for vertex constraint) + int* mLabel; //[mNPoints] label of the volume + // + float* mSolMat; //[mNMatSol] // material corrections + float* mMatErr; //[mNMatSol] // material corrections errors // ClassDef(AliAlgResFast, 1); }; diff --git a/Detectors/Align/include/Align/AliAlgSens.h b/Detectors/Align/include/Align/AliAlgSens.h index d11f05b44e072..16dcbbfc1bc30 100644 --- a/Detectors/Align/include/Align/AliAlgSens.h +++ b/Detectors/Align/include/Align/AliAlgSens.h @@ -42,56 +42,56 @@ class AliAlgSens : public AliAlgVol AliAlgSens(const char* name = 0, int vid = 0, int iid = 0); virtual ~AliAlgSens(); // - virtual void AddChild(AliAlgVol*); + virtual void addChild(AliAlgVol*); // - void SetDetector(AliAlgDet* det) { fDet = det; } - AliAlgDet* GetDetector() const { return fDet; } + void setDetector(AliAlgDet* det) { mDet = det; } + AliAlgDet* getDetector() const { return mDet; } // - int GetSID() const { return fSID; } - void SetSID(int s) { fSID = s; } + int getSID() const { return mSID; } + void setSID(int s) { mSID = s; } // - void IncrementStat() { fNProcPoints++; } + void incrementStat() { mNProcPoints++; } // // derivatives calculation - virtual void DPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int calibID, const AliAlgVol* parent = 0) const; - virtual void DPosTraDParGeom(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent = 0) const; + virtual void dPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int calibID, const AliAlgVol* parent = 0) const; + virtual void dPosTraDParGeom(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent = 0) const; // - virtual void DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv) const; - virtual void DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv) const; - virtual void DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const; - virtual void DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const; + virtual void dPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv) const; + virtual void dPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv) const; + virtual void dPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const; + virtual void dPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const; // - void GetModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const double* delta) const; - void GetModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const double* delta) const; + void getModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const double* delta) const; + void getModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const double* delta) const; // - virtual void ApplyAlignmentFromMPSol(); + virtual void applyAlignmentFromMPSol(); // - void SetAddError(double y, double z) + void setAddError(double y, double z) { - fAddError[0] = y; - fAddError[1] = z; + mAddError[0] = y; + mAddError[1] = z; } - const double* GetAddError() const { return fAddError; } + const double* getAddError() const { return mAddError; } // - virtual void PrepareMatrixT2L(); + virtual void prepareMatrixT2L(); // - virtual void SetTrackingFrame(); - virtual bool IsSensor() const { return true; } + virtual void setTrackingFrame(); + virtual bool isSensor() const { return true; } virtual void Print(const Option_t* opt = "") const; // - virtual void UpdatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) const; - virtual void UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta); + virtual void updatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) const; + virtual void updateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta); // // virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t) = 0; TODO(milettri): needs AliTrackPointArray AliESDtrack // - virtual int FinalizeStat(AliAlgDOFStat* h = 0); + virtual int finalizeStat(AliAlgDOFStat* h = 0); // - virtual void PrepareMatrixClAlg(); - virtual void PrepareMatrixClAlgReco(); - const TGeoHMatrix& GetMatrixClAlg() const { return fMatClAlg; } - const TGeoHMatrix& GetMatrixClAlgReco() const { return fMatClAlgReco; } - void SetMatrixClAlg(const TGeoHMatrix& m) { fMatClAlg = m; } - void SetMatrixClAlgReco(const TGeoHMatrix& m) { fMatClAlgReco = m; } + virtual void prepareMatrixClAlg(); + virtual void prepareMatrixClAlgReco(); + const TGeoHMatrix& getMatrixClAlg() const { return mMatClAlg; } + const TGeoHMatrix& getMatrixClAlgReco() const { return mMatClAlgReco; } + void setMatrixClAlg(const TGeoHMatrix& m) { mMatClAlg = m; } + void setMatrixClAlgReco(const TGeoHMatrix& m) { mMatClAlgReco = m; } // protected: // @@ -104,11 +104,11 @@ class AliAlgSens : public AliAlgVol // protected: // - int fSID; // sensor id in detector - double fAddError[2]; // additional error increment for measurement - AliAlgDet* fDet; // pointer on detector - TGeoHMatrix fMatClAlg; // reference cluster alignment matrix in tracking frame - TGeoHMatrix fMatClAlgReco; // reco-time cluster alignment matrix in tracking frame + int mSID; // sensor id in detector + double mAddError[2]; // additional error increment for measurement + AliAlgDet* mDet; // pointer on detector + TGeoHMatrix mMatClAlg; // reference cluster alignment matrix in tracking frame + TGeoHMatrix mMatClAlgReco; // reco-time cluster alignment matrix in tracking frame // ClassDef(AliAlgSens, 1) diff --git a/Detectors/Align/include/Align/AliAlgSensHMPID.h b/Detectors/Align/include/Align/AliAlgSensHMPID.h index 2248f978bcf78..d0c09700f8179 100644 --- a/Detectors/Align/include/Align/AliAlgSensHMPID.h +++ b/Detectors/Align/include/Align/AliAlgSensHMPID.h @@ -35,8 +35,8 @@ class AliAlgSensHMPID : public AliAlgSens virtual ~AliAlgSensHMPID(); // virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); - // virtual void SetTrackingFrame(); - virtual void PrepareMatrixT2L(); + // virtual void setTrackingFrame(); + virtual void prepareMatrixT2L(); // protected: // diff --git a/Detectors/Align/include/Align/AliAlgSensITS.h b/Detectors/Align/include/Align/AliAlgSensITS.h index 960e1d8d96d15..ba1fbef1b46a3 100644 --- a/Detectors/Align/include/Align/AliAlgSensITS.h +++ b/Detectors/Align/include/Align/AliAlgSensITS.h @@ -36,7 +36,7 @@ class AliAlgSensITS : public AliAlgSens // virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); - // virtual void SetTrackingFrame(); + // virtual void setTrackingFrame(); // protected: // diff --git a/Detectors/Align/include/Align/AliAlgSensTOF.h b/Detectors/Align/include/Align/AliAlgSensTOF.h index 0838abf622e6d..0dd8e7e2bc72d 100644 --- a/Detectors/Align/include/Align/AliAlgSensTOF.h +++ b/Detectors/Align/include/Align/AliAlgSensTOF.h @@ -35,8 +35,8 @@ class AliAlgSensTOF : public AliAlgSens virtual ~AliAlgSensTOF(); // virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); - // virtual void SetTrackingFrame(); - virtual void PrepareMatrixT2L(); + // virtual void setTrackingFrame(); + virtual void prepareMatrixT2L(); // int GetSector() const { return fSector; } void SetSector(uint32_t sc) { fSector = (uint8_t)sc; } diff --git a/Detectors/Align/include/Align/AliAlgSensTPC.h b/Detectors/Align/include/Align/AliAlgSensTPC.h index 77ffe5ba42180..7792b7a39dedf 100644 --- a/Detectors/Align/include/Align/AliAlgSensTPC.h +++ b/Detectors/Align/include/Align/AliAlgSensTPC.h @@ -38,8 +38,8 @@ class AliAlgSensTPC : public AliAlgSens void SetSector(uint32_t sc) { fSector = (uint8_t)sc; } // virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); - // virtual void SetTrackingFrame(); - virtual void PrepareMatrixT2L(); + // virtual void setTrackingFrame(); + virtual void prepareMatrixT2L(); // protected: // diff --git a/Detectors/Align/include/Align/AliAlgSensTRD.h b/Detectors/Align/include/Align/AliAlgSensTRD.h index 03b3daacac844..8550dd6f7eb8c 100644 --- a/Detectors/Align/include/Align/AliAlgSensTRD.h +++ b/Detectors/Align/include/Align/AliAlgSensTRD.h @@ -38,10 +38,10 @@ class AliAlgSensTRD : public AliAlgSens // virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); // - virtual void DPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int calibID, const AliAlgVol* parent = 0) const; + virtual void dPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int calibID, const AliAlgVol* parent = 0) const; // - // virtual void SetTrackingFrame(); - virtual void PrepareMatrixT2L(); + // virtual void setTrackingFrame(); + virtual void prepareMatrixT2L(); // protected: // diff --git a/Detectors/Align/include/Align/AliAlgSteer.h b/Detectors/Align/include/Align/AliAlgSteer.h index 4e10681d0d74a..7e575f957b8d6 100644 --- a/Detectors/Align/include/Align/AliAlgSteer.h +++ b/Detectors/Align/include/Align/AliAlgSteer.h @@ -122,258 +122,258 @@ class AliAlgSteer : public TObject virtual ~AliAlgSteer(); // bool LoadRefOCDB(); FIXME(milettri): needs OCDB // bool LoadRecoTimeOCDB(); FIXME(milettri): needs OCDB - bool GetUseRecoOCDB() const { return fUseRecoOCDB; } - void SetUseRecoOCDB(bool v = true) { fUseRecoOCDB = v; } + bool getUseRecoOCDB() const { return mUseRecoOCDB; } + void setUseRecoOCDB(bool v = true) { mUseRecoOCDB = v; } - void InitDetectors(); - void InitDOFs(); - void Terminate(bool dostat = true); - void SetStatHistoLabels(TH1* h) const; + void initDetectors(); + void initDOFs(); + void terminate(bool dostat = true); + void setStatHistoLabels(TH1* h) const; // - void SetInitGeomDone() { SetBit(kInitGeomDone); } - bool GetInitGeomDone() const { return TestBit(kInitGeomDone); } + void setInitGeomDone() { SetBit(kInitGeomDone); } + bool getInitGeomDone() const { return TestBit(kInitGeomDone); } // - void SetInitDOFsDone() { SetBit(kInitDOFsDone); } - bool GetInitDOFsDone() const { return TestBit(kInitDOFsDone); } + void setInitDOFsDone() { SetBit(kInitDOFsDone); } + bool getInitDOFsDone() const { return TestBit(kInitDOFsDone); } // - void SetMPAlignDone() { SetBit(kMPAlignDone); } - bool GetMPAlignDone() const { return TestBit(kMPAlignDone); } + void setMPAlignDone() { SetBit(kMPAlignDone); } + bool getMPAlignDone() const { return TestBit(kMPAlignDone); } - void AssignDOFs(); - // - void AddDetector(uint32_t id, AliAlgDet* det = 0); - void AddDetector(AliAlgDet* det); - // - void AddConstraint(const AliAlgConstraint* cs) { fConstraints.AddLast((TObject*)cs); } - int GetNConstraints() const { return fConstraints.GetEntriesFast(); } - const TObjArray* GetConstraints() const { return &fConstraints; } - const AliAlgConstraint* GetConstraint(int i) const { return (AliAlgConstraint*)fConstraints[i]; } - void AddAutoConstraints(); - // - void AcknowledgeNewRun(int run); - void SetRunNumber(int run); - int GetRunNumber() const { return fRunNumber; } - bool GetFieldOn() const { return fFieldOn; } - void SetFieldOn(bool v = true) { fFieldOn = v; } - int GetTracksType() const { return fTracksType; } - void SetTracksType(int t = AliAlgAux::kColl) { fTracksType = t; } - bool IsCosmic() const { return fTracksType == AliAlgAux::kCosm; } - bool IsCollision() const { return fTracksType == AliAlgAux::kColl; } - void SetCosmic(bool v = true) { fTracksType = v ? AliAlgAux::kCosm : AliAlgAux::kColl; } - float GetStat(int cls, int tp) const { return fStat[cls][tp]; } - // - void SetESDTree(const TTree* tr) { fESDTree = tr; } - const TTree* GetESDTree() const { return fESDTree; } + void assignDOFs(); + // + void addDetector(uint32_t id, AliAlgDet* det = 0); + void addDetector(AliAlgDet* det); + // + void addConstraint(const AliAlgConstraint* cs) { mConstraints.AddLast((TObject*)cs); } + int getNConstraints() const { return mConstraints.GetEntriesFast(); } + const TObjArray* getConstraints() const { return &mConstraints; } + const AliAlgConstraint* getConstraint(int i) const { return (AliAlgConstraint*)mConstraints[i]; } + void addAutoConstraints(); + // + void acknowledgeNewRun(int run); + void setRunNumber(int run); + int getRunNumber() const { return mRunNumber; } + bool getFieldOn() const { return mFieldOn; } + void setFieldOn(bool v = true) { mFieldOn = v; } + int getTracksType() const { return mTracksType; } + void setTracksType(int t = AliAlgAux::kColl) { mTracksType = t; } + bool isCosmic() const { return mTracksType == AliAlgAux::kCosm; } + bool isCollision() const { return mTracksType == AliAlgAux::kColl; } + void setCosmic(bool v = true) { mTracksType = v ? AliAlgAux::kCosm : AliAlgAux::kColl; } + float getStat(int cls, int tp) const { return mStat[cls][tp]; } + // + void setESDTree(const TTree* tr) { mESDTree = tr; } + const TTree* getESDTree() const { return mESDTree; } // void SetESDEvent(const AliESDEvent* ev); FIXME(milettri): needs AliESDEvent // const AliESDEvent* GetESDEvent() const { return fESDEvent; } FIXME(milettri): needs AliESDEvent // void SetESDtrack(const AliESDtrack* tr, int i = 0) { fESDTrack[i] = tr; } FIXME(milettri): needs AliESDtrack // const AliESDtrack* GetESDtrack(int i = 0) const { return fESDTrack[i]; } FIXME(milettri): needs AliESDtrack // // Track selection - void SetCosmicSelStrict(bool v = true) { fCosmicSelStrict = v; } - bool GetCosmicSelStrict() const { return fCosmicSelStrict; } + void setCosmicSelStrict(bool v = true) { mCosmicSelStrict = v; } + bool getCosmicSelStrict() const { return mCosmicSelStrict; } // - int GetMinPoints() const { return fMinPoints[fTracksType][GetFieldOn()]; } - int GetMinPoints(bool tp, bool bON) const { return fMinPoints[tp][bON]; } - void SetMinPoints(bool tp, bool bON, int n) + int getMinPoints() const { return mMinPoints[mTracksType][getFieldOn()]; } + int getMinPoints(bool tp, bool bON) const { return mMinPoints[tp][bON]; } + void setMinPoints(bool tp, bool bON, int n) { int mn = bON ? 4 : 3; - fMinPoints[tp][bON] = n > mn ? n : mn; + mMinPoints[tp][bON] = n > mn ? n : mn; } - void SetMinPointsColl(int vbOff = 3, int vbOn = 4); - void SetMinPointsCosm(int vbOff = 3, int vbOn = 4); - // - double GetPtMin(bool tp) const { return fPtMin[tp]; } - void SetPtMin(bool tp, double pt) { fPtMin[tp] = pt; } - void SetPtMinColl(double pt = 0.7) { SetPtMin(AliAlgAux::kColl, pt); } - void SetPtMinCosm(double pt = 1.0) { SetPtMin(AliAlgAux::kCosm, pt); } - // - double GetEtaMax(bool tp) const { return fEtaMax[tp]; } - void SetEtaMax(bool tp, double eta) { fEtaMax[tp] = eta; } - void SetEtaMaxColl(double eta = 1.5) { SetEtaMax(AliAlgAux::kColl, eta); } - void SetEtaMaxCosm(double eta = 1.5) { SetEtaMax(AliAlgAux::kCosm, eta); } - // - void SetDefPtBOffCosm(double pt = 5.0) { fDefPtBOff[AliAlgAux::kCosm] = pt > 0.3 ? pt : 0.3; } - void SetDefPtBOffColl(double pt = 0.6) { fDefPtBOff[AliAlgAux::kColl] = pt > 0.3 ? pt : 0.3; } - double GetDefPtBOff(bool tp) { return fDefPtBOff[tp]; } - // - int GetMinDetAcc(bool tp) const { return fMinDetAcc[tp]; } - void SetMinDetAcc(bool tp, int n) { fMinDetAcc[tp] = n; } - void SetMinDetAccColl(int n = 1) { SetMinDetAcc(AliAlgAux::kColl, n); } - void SetMinDetAccCosm(int n = 1) { SetMinDetAcc(AliAlgAux::kCosm, n); } - // - int GetVtxMinCont() const { return fVtxMinCont; } - void SetVtxMinCont(int n) { fVtxMinCont = n; } - int GetVtxMaxCont() const { return fVtxMaxCont; } - void SetVtxMaxCont(int n) { fVtxMaxCont = n; } - int GetVtxMinContVC() const { return fVtxMinContVC; } - void SetVtxMinContVC(int n) { fVtxMinContVC = n; } - // - int GetMinITSClforVC() const { return fMinITSClforVC; } - void SetMinITSClforVC(int n) { fMinITSClforVC = n; } - int GetITSPattforVC() const { return fITSPattforVC; } - void SetITSPattforVC(int p) { fITSPattforVC = p; } - double GetMaxDCARforVC() const { return fMaxDCAforVC[0]; } - double GetMaxDCAZforVC() const { return fMaxDCAforVC[1]; } - void SetMaxDCAforVC(double dr = 0.1, double dz = 0.6) + void setMinPointsColl(int vbOff = 3, int vbOn = 4); + void setMinPointsCosm(int vbOff = 3, int vbOn = 4); + // + double getPtMin(bool tp) const { return mPtMin[tp]; } + void setPtMin(bool tp, double pt) { mPtMin[tp] = pt; } + void setPtMinColl(double pt = 0.7) { setPtMin(AliAlgAux::kColl, pt); } + void setPtMinCosm(double pt = 1.0) { setPtMin(AliAlgAux::kCosm, pt); } + // + double getEtaMax(bool tp) const { return mEtaMax[tp]; } + void setEtaMax(bool tp, double eta) { mEtaMax[tp] = eta; } + void setEtaMaxColl(double eta = 1.5) { setEtaMax(AliAlgAux::kColl, eta); } + void setEtaMaxCosm(double eta = 1.5) { setEtaMax(AliAlgAux::kCosm, eta); } + // + void setDefPtBOffCosm(double pt = 5.0) { mDefPtBOff[AliAlgAux::kCosm] = pt > 0.3 ? pt : 0.3; } + void setDefPtBOffColl(double pt = 0.6) { mDefPtBOff[AliAlgAux::kColl] = pt > 0.3 ? pt : 0.3; } + double getDefPtBOff(bool tp) { return mDefPtBOff[tp]; } + // + int getMinDetAcc(bool tp) const { return mMinDetAcc[tp]; } + void setMinDetAcc(bool tp, int n) { mMinDetAcc[tp] = n; } + void setMinDetAccColl(int n = 1) { setMinDetAcc(AliAlgAux::kColl, n); } + void setMinDetAccCosm(int n = 1) { setMinDetAcc(AliAlgAux::kCosm, n); } + // + int getVtxMinCont() const { return mVtxMinCont; } + void setVtxMinCont(int n) { mVtxMinCont = n; } + int getVtxMaxCont() const { return mVtxMaxCont; } + void setVtxMaxCont(int n) { mVtxMaxCont = n; } + int getVtxMinContVC() const { return mVtxMinContVC; } + void setVtxMinContVC(int n) { mVtxMinContVC = n; } + // + int getMinITSClforVC() const { return mMinITSClforVC; } + void setMinITSClforVC(int n) { mMinITSClforVC = n; } + int getITSPattforVC() const { return mITSPattforVC; } + void setITSPattforVC(int p) { mITSPattforVC = p; } + double getMaxDCARforVC() const { return mMaxDCAforVC[0]; } + double getMaxDCAZforVC() const { return mMaxDCAforVC[1]; } + void setMaxDCAforVC(double dr = 0.1, double dz = 0.6) { - fMaxDCAforVC[0] = dr; - fMaxDCAforVC[1] = dz; + mMaxDCAforVC[0] = dr; + mMaxDCAforVC[1] = dz; } - double GetMaxChi2forVC() const { return fMaxChi2forVC; } - void SetMaxChi2forVC(double chi2 = 10) { fMaxChi2forVC = chi2; } + double getMaxChi2forVC() const { return mMaxChi2forVC; } + void setMaxChi2forVC(double chi2 = 10) { mMaxChi2forVC = chi2; } // - bool CheckDetectorPattern(uint32_t patt) const; - bool CheckDetectorPoints(const int* npsel) const; - void SetObligatoryDetector(int detID, int tp, bool v = true); - void SetEventSpeciiSelection(uint32_t sel) { fSelEventSpecii = sel; } - uint32_t GetEventSpeciiSelection() const { return fSelEventSpecii; } + bool checkDetectorPattern(uint32_t patt) const; + bool checkDetectorPoints(const int* npsel) const; + void setObligatoryDetector(int detID, int tp, bool v = true); + void setEventSpeciiSelection(uint32_t sel) { mSelEventSpecii = sel; } + uint32_t getEventSpeciiSelection() const { return mSelEventSpecii; } // // void SetVertex(const AliESDVertex* v) { fVertex = v; } FIXME(milettri): needs AliESDVertex // const AliESDVertex* GetVertex() const { return fVertex; } FIXME(milettri): needs AliESDVertex // //---------------------------------------- - bool ReadParameters(const char* parfile = "millepede.res", bool useErrors = true); - float* GetGloParVal() const { return (float*)fGloParVal; } - float* GetGloParErr() const { return (float*)fGloParErr; } - int* GetGloParLab() const { return (int*)fGloParLab; } - int GetGloParLab(int i) const { return (int)fGloParLab[i]; } - int ParID2Label(int i) const { return GetGloParLab(i); } - int Label2ParID(int lab) const; - AliAlgVol* GetVolOfDOFID(int id) const; - AliAlgDet* GetDetOfDOFID(int id) const; - // - AliAlgPoint* GetRefPoint() const { return (AliAlgPoint*)fRefPoint; } - // - AliAlgRes* GetContResid() const { return (AliAlgRes*)fCResid; } - AliAlgMPRecord* GetMPRecord() const { return (AliAlgMPRecord*)fMPRecord; } - TTree* GetMPRecTree() const { return fMPRecTree; } - AliAlgTrack* GetAlgTrack() const { return (AliAlgTrack*)fAlgTrack; } + bool readParameters(const char* parfile = "millepede.res", bool useErrors = true); + float* getGloParVal() const { return (float*)mGloParVal; } + float* getGloParErr() const { return (float*)mGloParErr; } + int* getGloParLab() const { return (int*)mGloParLab; } + int getGloParLab(int i) const { return (int)mGloParLab[i]; } + int parID2Label(int i) const { return getGloParLab(i); } + int label2ParID(int lab) const; + AliAlgVol* getVolOfDOFID(int id) const; + AliAlgDet* getDetOfDOFID(int id) const; + // + AliAlgPoint* getRefPoint() const { return (AliAlgPoint*)mRefPoint; } + // + AliAlgRes* getContResid() const { return (AliAlgRes*)mCResid; } + AliAlgMPRecord* getMPRecord() const { return (AliAlgMPRecord*)mMPRecord; } + TTree* getMPRecTree() const { return mMPRecTree; } + AliAlgTrack* getAlgTrack() const { return (AliAlgTrack*)mAlgTrack; } // bool ProcessEvent(const AliESDEvent* esdEv); FIXME(milettri): needs AliESDEvent // bool ProcessTrack(const AliESDtrack* esdTr); FIXME(milettri): needs AliESDtrack // bool ProcessTrack(const AliESDCosmicTrack* esdCTr); FIXME(milettri): needs AliESDCosmicTrack // uint32_t AcceptTrack(const AliESDtrack* esdTr, bool strict = true) const; FIXME(milettri): needs AliESDtrack // uint32_t AcceptTrackCosmic(const AliESDtrack* esdPairCosm[kNCosmLegs]) const; FIXME(milettri): needs AliESDtrack // bool CheckSetVertex(const AliESDVertex* vtx); FIXME(milettri): needs AliESDVertex - bool AddVertexConstraint(); - int GetNDetectors() const { return fNDet; } - AliAlgDet* GetDetector(int i) const { return fDetectors[i]; } - AliAlgDet* GetDetectorByDetID(int i) const { return fDetPos[i] < 0 ? 0 : fDetectors[fDetPos[i]]; } - AliAlgDet* GetDetectorByVolID(int id) const; - AliAlgVtx* GetVertexSensor() const { return fVtxSens; } + bool addVertexConstraint(); + int getNDetectors() const { return mNDet; } + AliAlgDet* getDetector(int i) const { return mDetectors[i]; } + AliAlgDet* getDetectorByDetID(int i) const { return mDetPos[i] < 0 ? 0 : mDetectors[mDetPos[i]]; } + AliAlgDet* getDetectorByVolID(int id) const; + AliAlgVtx* getVertexSensor() const { return mVtxSens; } // - void ResetDetectors(); - int GetNDOFs() const { return fNDOFs; } + void resetDetectors(); + int getNDOFs() const { return mNDOFs; } // - const char* GetConfMacroName() const { return fConfMacroName.Data(); } + const char* getConfMacroName() const { return mConfMacroName.Data(); } //---------------------------------------- // output related - void SetMPDatFileName(const char* name = "mpData"); - void SetMPParFileName(const char* name = "mpParams.txt"); - void SetMPConFileName(const char* name = "mpConstraints.txt"); - void SetMPSteerFileName(const char* name = "mpSteer.txt"); - void SetResidFileName(const char* name = "mpControlRes.root"); - void SetOutCDBPath(const char* name = "local://outOCDB"); - void SetOutCDBComment(const char* cm = 0) { fOutCDBComment = cm; } - void SetOutCDBResponsible(const char* v = 0) { fOutCDBResponsible = v; } + void setMPDatFileName(const char* name = "mpData"); + void setMPParFileName(const char* name = "mpParams.txt"); + void setMPConFileName(const char* name = "mpConstraints.txt"); + void setMPSteerFileName(const char* name = "mpSteer.txt"); + void setResidFileName(const char* name = "mpControlRes.root"); + void setOutCDBPath(const char* name = "local://outOCDB"); + void setOutCDBComment(const char* cm = 0) { mOutCDBComment = cm; } + void setOutCDBResponsible(const char* v = 0) { mOutCDBResponsible = v; } // void SetOutCDBRunRange(int rmin = 0, int rmax = 999999999); FIXME(milettri): needs OCDB - int* GetOutCDBRunRange() const { return (int*)fOutCDBRunRange; } - int GetOutCDBRunMin() const { return fOutCDBRunRange[0]; } - int GetOutCDBRunMax() const { return fOutCDBRunRange[1]; } - float GetControlFrac() const { return fControlFrac; } - void SetControlFrac(float v = 1.) { fControlFrac = v; } - // void WriteCalibrationResults() const; FIXME(milettri): needs OCDB - void ApplyAlignmentFromMPSol(); - const char* GetOutCDBComment() const { return fOutCDBComment.Data(); } - const char* GetOutCDBResponsible() const { return fOutCDBResponsible.Data(); } - const char* GetOutCDBPath() const { return fOutCDBPath.Data(); } - const char* GetMPDatFileName() const { return fMPDatFileName.Data(); } - const char* GetResidFileName() const { return fResidFileName.Data(); } - const char* GetMPParFileName() const { return fMPParFileName.Data(); } - const char* GetMPConFileName() const { return fMPConFileName.Data(); } - const char* GetMPSteerFileName() const { return fMPSteerFileName.Data(); } - // - bool FillMPRecData(); - bool FillMilleData(); - bool FillControlData(); - void SetDoKalmanResid(bool v = true) { fDoKalmanResid = v; } - void SetMPOutType(int t) { fMPOutType = t; } - void ProduceMPData(bool v = true) + int* getOutCDBRunRange() const { return (int*)mOutCDBRunRange; } + int getOutCDBRunMin() const { return mOutCDBRunRange[0]; } + int getOutCDBRunMax() const { return mOutCDBRunRange[1]; } + float getControlFrac() const { return mControlFrac; } + void setControlFrac(float v = 1.) { mControlFrac = v; } + // void writeCalibrationResults() const; FIXME(milettri): needs OCDB + void applyAlignmentFromMPSol(); + const char* getOutCDBComment() const { return mOutCDBComment.Data(); } + const char* getOutCDBResponsible() const { return mOutCDBResponsible.Data(); } + const char* getOutCDBPath() const { return mOutCDBPath.Data(); } + const char* getMPDatFileName() const { return mMPDatFileName.Data(); } + const char* getResidFileName() const { return mResidFileName.Data(); } + const char* getMPParFileName() const { return mMPParFileName.Data(); } + const char* getMPConFileName() const { return mMPConFileName.Data(); } + const char* getMPSteerFileName() const { return mMPSteerFileName.Data(); } + // + bool fillMPRecData(); + bool fillMilleData(); + bool fillControlData(); + void setDoKalmanResid(bool v = true) { mDoKalmanResid = v; } + void setMPOutType(int t) { mMPOutType = t; } + void produceMPData(bool v = true) { if (v) - fMPOutType |= kMille; + mMPOutType |= kMille; else - fMPOutType &= ~kMille; + mMPOutType &= ~kMille; } - void ProduceMPRecord(bool v = true) + void produceMPRecord(bool v = true) { if (v) - fMPOutType |= kMPRec; + mMPOutType |= kMPRec; else - fMPOutType &= ~kMPRec; + mMPOutType &= ~kMPRec; } - void ProduceControlRes(bool v = true) + void produceControlRes(bool v = true) { if (v) - fMPOutType |= kContR; + mMPOutType |= kContR; else - fMPOutType &= ~kContR; + mMPOutType &= ~kContR; } - int GetMPOutType() const { return fMPOutType; } - bool GetDoKalmanResid() const { return fDoKalmanResid; } - bool GetProduceMPData() const { return fMPOutType & kMille; } - bool GetProduceMPRecord() const { return fMPOutType & kMPRec; } - bool GetProduceControlRes() const { return fMPOutType & kContR; } - void CloseMPRecOutput(); - void CloseMilleOutput(); - void CloseResidOutput(); - void InitMPRecOutput(); - void InitMIlleOutput(); - void InitResidOutput(); - bool StoreProcessedTrack(int what); - void PrintStatistics() const; - bool GetMilleTXT() const { return !fMilleOutBin; } - void SetMilleTXT(bool v = true) { fMilleOutBin = !v; } - // - void GenPedeSteerFile(const Option_t* opt = "") const; - void WritePedeConstraints() const; - void CheckConstraints(const char* params = 0); - AliAlgDOFStat* GetDOFStat() const { return fDOFStat; } - void SetDOFStat(AliAlgDOFStat* st) { fDOFStat = st; } - void DetachDOFStat() { SetDOFStat(0); } - TH1* GetHistoStat() const { return fHistoStat; } - void DetachHistoStat() { SetHistoStat(0); } - void SetHistoStat(TH1F* h) { fHistoStat = h; } - void FillStatHisto(int type, float w = 1); - void CreateStatHisto(); - void FixLowStatFromDOFStat(int thresh = 40); - void LoadStat(const char* flname); + int getMPOutType() const { return mMPOutType; } + bool getDoKalmanResid() const { return mDoKalmanResid; } + bool getProduceMPData() const { return mMPOutType & kMille; } + bool getProduceMPRecord() const { return mMPOutType & kMPRec; } + bool getProduceControlRes() const { return mMPOutType & kContR; } + void closeMPRecOutput(); + void closeMilleOutput(); + void closeResidOutput(); + void initMPRecOutput(); + void initMIlleOutput(); + void initResidOutput(); + bool storeProcessedTrack(int what); + void printStatistics() const; + bool getMilleTXT() const { return !mMilleOutBin; } + void setMilleTXT(bool v = true) { mMilleOutBin = !v; } + // + void genPedeSteerFile(const Option_t* opt = "") const; + void writePedeConstraints() const; + void checkConstraints(const char* params = 0); + AliAlgDOFStat* GetDOFStat() const { return mDOFStat; } + void setDOFStat(AliAlgDOFStat* st) { mDOFStat = st; } + void detachDOFStat() { setDOFStat(0); } + TH1* getHistoStat() const { return mHistoStat; } + void detachHistoStat() { setHistoStat(0); } + void setHistoStat(TH1F* h) { mHistoStat = h; } + void fillStatHisto(int type, float w = 1); + void createStatHisto(); + void fixLowStatFromDOFStat(int thresh = 40); + void loadStat(const char* flname); // //---------------------------------------- // - int GetRefRunNumber() const { return fRefRunNumber; } - void SetRefRunNumber(int r = -1) { fRefRunNumber = r; } + int getRefRunNumber() const { return mRefRunNumber; } + void setRefRunNumber(int r = -1) { mRefRunNumber = r; } // - void SetRefOCDBConfigMacro(const char* nm = "configRefOCDB.C") { fRefOCDBConf = nm; } - const char* GetRefOCDBConfigMacro() const { return fRefOCDBConf.Data(); } - void SetRecoOCDBConfigMacro(const char* nm = "configRecoOCDB.C") { fRecoOCDBConf = nm; } - const char* GetRecoOCDBConfigMacro() const { return fRecoOCDBConf.Data(); } - int GetRefOCDBLoaded() const { return fRefOCDBLoaded; } + void setRefOCDBConfigMacro(const char* nm = "configRefOCDB.C") { mRefOCDBConf = nm; } + const char* getRefOCDBConfigMacro() const { return mRefOCDBConf.Data(); } + void setRecoOCDBConfigMacro(const char* nm = "configRecoOCDB.C") { mRecoOCDBConf = nm; } + const char* getRecoOCDBConfigMacro() const { return mRecoOCDBConf.Data(); } + int getRefOCDBLoaded() const { return mRefOCDBLoaded; } // virtual void Print(const Option_t* opt = "") const; - void PrintLabels() const; - char* GetDOFLabelTxt(int idf) const; + void printLabels() const; + Char_t* getDOFLabelTxt(int idf) const; // - static char* GetDetNameByDetID(int id) { return (char*)fgkDetectorName[id]; } - static void MPRec2Mille(const char* mprecfile, const char* millefile = "mpData.mille", bool bindata = true); - static void MPRec2Mille(TTree* mprTree, const char* millefile = "mpData.mille", bool bindata = true); + static Char_t* getDetNameByDetID(int id) { return (Char_t*)sDetectorName[id]; } + static void mPRec2Mille(const char* mprecfile, const char* millefile = "mpData.mille", bool bindata = true); + static void mPRec2Mille(TTree* mprTree, const char* millefile = "mpData.mille", bool bindata = true); // // AliSymMatrix* BuildMatrix(TVectorD& vec); FIXME(milettri): needs AliSymMatrix - bool TestLocalSolution(); + bool testLocalSolution(); // // fast check of solution using derivatives - void CheckSol(TTree* mpRecTree, bool store = true, bool verbose = false, bool loc = true, const char* outName = "resFast"); - bool CheckSol(AliAlgMPRecord* rec, AliAlgResFast* rLG = 0, AliAlgResFast* rL = 0, bool verbose = true, bool loc = true); + void checkSol(TTree* mpRecTree, bool store = true, bool verbose = false, bool loc = true, const char* outName = "resFast"); + bool checkSol(AliAlgMPRecord* rec, AliAlgResFast* rLG = 0, AliAlgResFast* rL = 0, bool verbose = true, bool loc = true); // protected: // @@ -383,112 +383,112 @@ class AliAlgSteer : public TObject // protected: // - int fNDet; // number of deectors participating in the alignment - int fNDOFs; // number of degrees of freedom - int fRunNumber; // current run number - bool fFieldOn; // field on flag - int fTracksType; // collision/cosmic event type - AliAlgTrack* fAlgTrack; // current alignment track - AliAlgDet* fDetectors[kNDetectors]; // detectors participating in the alignment - int fDetPos[kNDetectors]; // entry of detector in the fDetectors array - AliAlgVtx* fVtxSens; // fake sensor for the vertex - TObjArray fConstraints; // array of constraints + int mNDet; // number of deectors participating in the alignment + int mNDOFs; // number of degrees of freedom + int mRunNumber; // current run number + bool mFieldOn; // field on flag + int mTracksType; // collision/cosmic event type + AliAlgTrack* mAlgTrack; // current alignment track + AliAlgDet* mDetectors[kNDetectors]; // detectors participating in the alignment + int mDetPos[kNDetectors]; // entry of detector in the mDetectors array + AliAlgVtx* mVtxSens; // fake sensor for the vertex + TObjArray mConstraints; // array of constraints // // Track selection - uint32_t fSelEventSpecii; // consider only these event specii - uint32_t fObligatoryDetPattern[AliAlgAux::kNTrackTypes]; // pattern of obligatory detectors - bool fCosmicSelStrict; // if true, each cosmic track leg selected like separate track - int fMinPoints[AliAlgAux::kNTrackTypes][2]; // require min points per leg (case Boff,Bon) - int fMinDetAcc[AliAlgAux::kNTrackTypes]; // min number of detector required in track - double fDefPtBOff[AliAlgAux::kNTrackTypes]; // nominal pt for tracks in Boff run - double fPtMin[AliAlgAux::kNTrackTypes]; // min pT of tracks to consider - double fEtaMax[AliAlgAux::kNTrackTypes]; // eta cut on tracks - int fVtxMinCont; // require min number of contributors in Vtx - int fVtxMaxCont; // require max number of contributors in Vtx - int fVtxMinContVC; // min number of contributors to use as constraint - // - int fMinITSClforVC; // use vertex constraint for tracks with enough points - int fITSPattforVC; // optional request on ITS hits to allow vertex constraint - double fMaxDCAforVC[2]; // DCA cut in R,Z to allow vertex constraint - double fMaxChi2forVC; // track-vertex chi2 cut to allow vertex constraint - // - // - float* fGloParVal; //[fNDOFs] parameters for DOFs - float* fGloParErr; //[fNDOFs] errors for DOFs - int* fGloParLab; //[fNDOFs] labels for DOFs - int* fOrderedLbl; //[fNDOFs] ordered labels - int* fLbl2ID; //[fNDOFs] Label order in fOrderedLbl -> parID - // - AliAlgPoint* fRefPoint; // reference point for track definition - // - const TTree* fESDTree; //! externally set esdTree, needed to access UserInfo list + uint32_t mSelEventSpecii; // consider only these event specii + uint32_t mObligatoryDetPattern[AliAlgAux::kNTrackTypes]; // pattern of obligatory detectors + bool mCosmicSelStrict; // if true, each cosmic track leg selected like separate track + int mMinPoints[AliAlgAux::kNTrackTypes][2]; // require min points per leg (case Boff,Bon) + int mMinDetAcc[AliAlgAux::kNTrackTypes]; // min number of detector required in track + double mDefPtBOff[AliAlgAux::kNTrackTypes]; // nominal pt for tracks in Boff run + double mPtMin[AliAlgAux::kNTrackTypes]; // min pT of tracks to consider + double mEtaMax[AliAlgAux::kNTrackTypes]; // eta cut on tracks + int mVtxMinCont; // require min number of contributors in Vtx + int mVtxMaxCont; // require max number of contributors in Vtx + int mVtxMinContVC; // min number of contributors to use as constraint + // + int mMinITSClforVC; // use vertex constraint for tracks with enough points + int mITSPattforVC; // optional request on ITS hits to allow vertex constraint + double mMaxDCAforVC[2]; // DCA cut in R,Z to allow vertex constraint + double mMaxChi2forVC; // track-vertex chi2 cut to allow vertex constraint + // + // + float* mGloParVal; //[mNDOFs] parameters for DOFs + float* mGloParErr; //[mNDOFs] errors for DOFs + int* mGloParLab; //[mNDOFs] labels for DOFs + int* mOrderedLbl; //[mNDOFs] ordered labels + int* mLbl2ID; //[mNDOFs] Label order in mOrderedLbl -> parID + // + AliAlgPoint* mRefPoint; // reference point for track definition + // + const TTree* mESDTree; //! externally set esdTree, needed to access UserInfo list // const AliESDEvent* fESDEvent; //! externally set event FIXME(milettri): needs AliESDEvent // const AliESDtrack* fESDTrack[kNCosmLegs]; //! externally set ESD tracks FIXME(milettri): needs AliESDtrack // const AliESDVertex* fVertex; //! event vertex FIXME(milettri): needs AliESDVertex // // statistics - float fStat[kNStatCl][kMaxStat]; // processing statistics - static const char* fgkStatClName[kNStatCl]; // stat classes names - static const char* fgkStatName[kMaxStat]; // stat type names + float mStat[kNStatCl][kMaxStat]; // processing statistics + static const Char_t* sStatClName[kNStatCl]; // stat classes names + static const Char_t* sStatName[kMaxStat]; // stat type names // // output related - float fControlFrac; // fraction of tracks to process control residuals - int fMPOutType; // What to store as an output, see StoreProcessedTrack - Mille* fMille; //! Mille interface - AliAlgMPRecord* fMPRecord; //! MP record - AliAlgRes* fCResid; //! control residuals - TTree* fMPRecTree; //! tree to store MP record - TTree* fResidTree; //! tree to store control residuals - TFile* fMPRecFile; //! file to store MP record tree - TFile* fResidFile; //! file to store control residuals tree - TArrayF fMilleDBuffer; //! buffer for Mille Derivatives output - TArrayI fMilleIBuffer; //! buffer for Mille Indecis output - TString fMPDatFileName; // file name for records binary data output - TString fMPParFileName; // file name for MP params - TString fMPConFileName; // file name for MP constraints - TString fMPSteerFileName; // file name for MP steering - TString fResidFileName; // file name for optional control residuals - bool fMilleOutBin; // optionally text output for Mille debugging - bool fDoKalmanResid; // calculate residuals with smoothed kalman in the ControlRes - // - TString fOutCDBPath; // output OCDB path - TString fOutCDBComment; // optional comment to add to output cdb objects - TString fOutCDBResponsible; // optional responsible for output metadata - int fOutCDBRunRange[2]; // run range for output storage - // - AliAlgDOFStat* fDOFStat; // stat of entries per dof - TH1F* fHistoStat; // histo with general statistics + float mControlFrac; // fraction of tracks to process control residuals + int mMPOutType; // What to store as an output, see storeProcessedTrack + Mille* mMille; //! Mille interface + AliAlgMPRecord* mMPRecord; //! MP record + AliAlgRes* mCResid; //! control residuals + TTree* mMPRecTree; //! tree to store MP record + TTree* mResidTree; //! tree to store control residuals + TFile* mMPRecFile; //! file to store MP record tree + TFile* mResidFile; //! file to store control residuals tree + TArrayF mMilleDBuffer; //! buffer for Mille Derivatives output + TArrayI mMilleIBuffer; //! buffer for Mille Indecis output + TString mMPDatFileName; // file name for records binary data output + TString mMPParFileName; // file name for MP params + TString mMPConFileName; // file name for MP constraints + TString mMPSteerFileName; // file name for MP steering + TString mResidFileName; // file name for optional control residuals + bool mMilleOutBin; // optionally text output for Mille debugging + bool mDoKalmanResid; // calculate residuals with smoothed kalman in the ControlRes + // + TString mOutCDBPath; // output OCDB path + TString mOutCDBComment; // optional comment to add to output cdb objects + TString mOutCDBResponsible; // optional responsible for output metadata + int mOutCDBRunRange[2]; // run range for output storage + // + AliAlgDOFStat* mDOFStat; // stat of entries per dof + TH1F* mHistoStat; // histo with general statistics // // input related - TString fConfMacroName; // optional configuration macro - TString fRecoOCDBConf; // optional macro name for reco-time OCDB setup: void fun(int run) - TString fRefOCDBConf; // optional macro name for prealignment OCDB setup: void fun() - int fRefRunNumber; // optional run number used for reference - int fRefOCDBLoaded; // flag/counter for ref.OCDB loading - bool fUseRecoOCDB; // flag to preload reco-time calib objects - // - static const int fgkSkipLayers[kNLrSkip]; // detector layers for which we don't need module matrices - static const char* fgkDetectorName[kNDetectors]; // names of detectors - static const char* fgkHStatName[kNHVars]; // names for stat.bins in the stat histo - static const char* fgkMPDataExt; // extension for MP2 binary data - // - ClassDef(AliAlgSteer, 2) + TString mConfMacroName; // optional configuration macro + TString mRecoOCDBConf; // optional macro name for reco-time OCDB setup: void fun(int run) + TString mRefOCDBConf; // optional macro name for prealignment OCDB setup: void fun() + int mRefRunNumber; // optional run number used for reference + int mRefOCDBLoaded; // flag/counter for ref.OCDB loading + bool mUseRecoOCDB; // flag to preload reco-time calib objects + // + static const int sSkipLayers[kNLrSkip]; // detector layers for which we don't need module matrices + static const Char_t* sDetectorName[kNDetectors]; // names of detectors + static const Char_t* sHStatName[kNHVars]; // names for stat.bins in the stat histo + static const Char_t* sMPDataExt; // extension for MP2 binary data + // + ClassDef(AliAlgSteer, 3) }; //__________________________________________________________ -inline void AliAlgSteer::SetMinPointsColl(int vbOff, int vbOn) +inline void AliAlgSteer::setMinPointsColl(int vbOff, int vbOn) { // ask min number of points per track - SetMinPoints(AliAlgAux::kColl, false, vbOff); - SetMinPoints(AliAlgAux::kColl, true, vbOn); + setMinPoints(AliAlgAux::kColl, false, vbOff); + setMinPoints(AliAlgAux::kColl, true, vbOn); } //__________________________________________________________ -inline void AliAlgSteer::SetMinPointsCosm(int vbOff, int vbOn) +inline void AliAlgSteer::setMinPointsCosm(int vbOff, int vbOn) { // ask min number of points per track - SetMinPoints(AliAlgAux::kCosm, false, vbOff); - SetMinPoints(AliAlgAux::kCosm, true, vbOn); + setMinPoints(AliAlgAux::kCosm, false, vbOff); + setMinPoints(AliAlgAux::kCosm, true, vbOn); } } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgTrack.h b/Detectors/Align/include/Align/AliAlgTrack.h index db1d09a3f2767..cacfa995942a6 100644 --- a/Detectors/Align/include/Align/AliAlgTrack.h +++ b/Detectors/Align/include/Align/AliAlgTrack.h @@ -63,128 +63,128 @@ class AliAlgTrack : public trackParam_t, public TObject }; AliAlgTrack(); virtual ~AliAlgTrack(); - void DefineDOFs(); - double GetMass() const { return fMass; } - double GetMinX2X0Pt2Account() const { return fMinX2X0Pt2Account; } - int GetNPoints() const { return fPoints.GetEntriesFast(); } - AliAlgPoint* GetPoint(int i) const { return (AliAlgPoint*)fPoints[i]; } - void AddPoint(AliAlgPoint* p) { fPoints.AddLast(p); } - void SetMass(double m) { fMass = m; } - void SetMinX2X0Pt2Account(double v) { fMinX2X0Pt2Account = v; } - int GetNLocPar() const { return fNLocPar; } - int GetNLocExtPar() const { return fNLocExtPar; } - int GetInnerPointID() const { return fInnerPointID; } - AliAlgPoint* GetInnerPoint() const { return GetPoint(fInnerPointID); } + void defineDOFs(); + double getMass() const { return mMass; } + double getMinX2X0Pt2Account() const { return mMinX2X0Pt2Account; } + int getNPoints() const { return mPoints.GetEntriesFast(); } + AliAlgPoint* getPoint(int i) const { return (AliAlgPoint*)mPoints[i]; } + void addPoint(AliAlgPoint* p) { mPoints.AddLast(p); } + void setMass(double m) { mMass = m; } + void setMinX2X0Pt2Account(double v) { mMinX2X0Pt2Account = v; } + int getNLocPar() const { return mNLocPar; } + int getNLocExtPar() const { return mNLocExtPar; } + int getInnerPointID() const { return mInnerPointID; } + AliAlgPoint* getInnerPoint() const { return getPoint(mInnerPointID); } // virtual void Clear(Option_t* opt = ""); virtual void Print(Option_t* opt = "") const; - virtual void DumpCoordinates() const; + virtual void dumpCoordinates() const; // - bool PropagateToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT, track::TrackLTIntegral* tLT = nullptr); - bool PropagateParamToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep = 3, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT); // param only - bool PropagateParamToPoint(trackParam_t* trSet, int nTr, const AliAlgPoint* pnt, double maxStep = 3, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT); // params only + bool propagateToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT, track::TrackLTIntegral* tLT = nullptr); + bool propagateParamToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep = 3, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT); // param only + bool propagateParamToPoint(trackParam_t* trSet, int nTr, const AliAlgPoint* pnt, double maxStep = 3, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT); // params only // - bool CalcResiduals(const double* params = 0); - bool CalcResidDeriv(double* params = 0); - bool CalcResidDerivGlo(AliAlgPoint* pnt); + bool calcResiduals(const double* params = 0); + bool calcResidDeriv(double* params = 0); + bool calcResidDerivGlo(AliAlgPoint* pnt); // - bool IsCosmic() const { return TestBit(kCosmicBit); } - void SetCosmic(bool v = true) { SetBit(kCosmicBit, v); } - bool GetFieldON() const { return TestBit(kFieldONBit); } - void SetFieldON(bool v = true) { SetBit(kFieldONBit, v); } - bool GetResidDone() const { return TestBit(kResidDoneBit); } - void SetResidDone(bool v = true) { SetBit(kResidDoneBit, v); } - bool GetDerivDone() const { return TestBit(kDerivDoneBit); } - void SetDerivDone(bool v = true) { SetBit(kDerivDoneBit, v); } - bool GetKalmanDone() const { return TestBit(kKalmanDoneBit); } - void SetKalmanDone(bool v = true) { SetBit(kKalmanDoneBit, v); } + bool isCosmic() const { return TestBit(kCosmicBit); } + void setCosmic(bool v = true) { SetBit(kCosmicBit, v); } + bool getFieldON() const { return TestBit(kFieldONBit); } + void setFieldON(bool v = true) { SetBit(kFieldONBit, v); } + bool getResidDone() const { return TestBit(kResidDoneBit); } + void setResidDone(bool v = true) { SetBit(kResidDoneBit, v); } + bool getDerivDone() const { return TestBit(kDerivDoneBit); } + void setDerivDone(bool v = true) { SetBit(kDerivDoneBit, v); } + bool getKalmanDone() const { return TestBit(kKalmanDoneBit); } + void setKalmanDone(bool v = true) { SetBit(kKalmanDoneBit, v); } // - void SortPoints(); - bool IniFit(); - bool ResidKalman(); - bool ProcessMaterials(); - bool CombineTracks(trackParam_t& trcL, const trackParam_t& trcU); + void sortPoints(); + bool iniFit(); + bool residKalman(); + bool processMaterials(); + bool combineTracks(trackParam_t& trcL, const trackParam_t& trcU); // - void SetChi2(double c) { fChi2 = c; }; - double GetChi2() const { return fChi2; } - void SetChi2Ini(double c) { fChi2Ini = c; }; - double GetChi2Ini() const { return fChi2Ini; } - double GetChi2CosmUp() const { return fChi2CosmUp; } - double GetChi2CosmDn() const { return fChi2CosmDn; } + void setChi2(double c) { mChi2 = c; }; + double getChi2() const { return mChi2; } + void setChi2Ini(double c) { mChi2Ini = c; }; + double getChi2Ini() const { return mChi2Ini; } + double getChi2CosmUp() const { return mChi2CosmUp; } + double getChi2CosmDn() const { return mChi2CosmDn; } // - void ImposePtBOff(double pt) { setQ2Pt(1. / pt); } + void imposePtBOff(double pt) { setQ2Pt(1. / pt); } // propagation methods - void CopyFrom(const trackParam_t* etp); - bool ApplyMatCorr(trackParam_t& trPar, const double* corrDiag, const AliAlgPoint* pnt); - bool ApplyMatCorr(trackParam_t* trSet, int ntr, const double* corrDiaf, const AliAlgPoint* pnt); - bool ApplyMatCorr(trackParam_t& trPar, const double* corrpar); + void copyFrom(const trackParam_t* etp); + bool applyMatCorr(trackParam_t& trPar, const double* corrDiag, const AliAlgPoint* pnt); + bool applyMatCorr(trackParam_t* trSet, int ntr, const double* corrDiaf, const AliAlgPoint* pnt); + bool applyMatCorr(trackParam_t& trPar, const double* corrpar); // - double GetResidual(int dim, int pntID) const { return fResidA[dim][pntID]; } - double* GetDResDLoc(int dim, int pntID) const { return &fDResDLocA[dim][pntID * fNLocPar]; } - double* GetDResDGlo(int dim, int id) const { return &fDResDGloA[dim][id]; } - int* GetGloParID() const { return fGloParIDA; } + double getResidual(int dim, int pntID) const { return mResidA[dim][pntID]; } + double* getDResDLoc(int dim, int pntID) const { return &mDResDLocA[dim][pntID * mNLocPar]; } + double* getDResDGlo(int dim, int id) const { return &mDResDGloA[dim][id]; } + int* getGloParID() const { return mGloParIDA; } // - void SetParams(trackParam_t& tr, double x, double alp, const double* par, bool add); - void SetParams(trackParam_t* trSet, int ntr, double x, double alp, const double* par, bool add); - void SetParam(trackParam_t& tr, int par, double val); - void SetParam(trackParam_t* trSet, int ntr, int par, double val); - void ModParam(trackParam_t& tr, int par, double delta); - void ModParam(trackParam_t* trSet, int ntr, int par, double delta); + void setParams(trackParam_t& tr, double x, double alp, const double* par, bool add); + void setParams(trackParam_t* trSet, int ntr, double x, double alp, const double* par, bool add); + void setParam(trackParam_t& tr, int par, double val); + void setParam(trackParam_t* trSet, int ntr, int par, double val); + void modParam(trackParam_t& tr, int par, double delta); + void modParam(trackParam_t* trSet, int ntr, int par, double delta); // - void RichardsonDeriv(const trackParam_t* trSet, const double* delta, + void richardsonDeriv(const trackParam_t* trSet, const double* delta, const AliAlgPoint* pnt, double& derY, double& derZ); // - const double* GetLocPars() const { return fLocParA; } - void SetLocPars(const double* pars); + const double* getLocPars() const { return mLocParA; } + void setLocPars(const double* pars); // protected: // - bool CalcResidDeriv(double* params, bool invert, int pFrom, int pTo); - bool CalcResiduals(const double* params, bool invert, int pFrom, int pTo); - bool FitLeg(trackParam_t& trc, int pFrom, int pTo, bool& inv); - bool ProcessMaterials(trackParam_t& trc, int pFrom, int pTo); + bool calcResidDeriv(double* params, bool invert, int pFrom, int pTo); + bool calcResiduals(const double* params, bool invert, int pFrom, int pTo); + bool fitLeg(trackParam_t& trc, int pFrom, int pTo, bool& inv); + bool processMaterials(trackParam_t& trc, int pFrom, int pTo); // - void CheckExpandDerGloBuffer(int minSize); + void checkExpandDerGloBuffer(int minSize); // - static double RichardsonExtrap(double* val, int ord = 1); - static double RichardsonExtrap(const double* val, int ord = 1); + static double richardsonExtrap(double* val, int ord = 1); + static double richardsonExtrap(const double* val, int ord = 1); // // ---------- dummies ---------- AliAlgTrack(const AliAlgTrack&); AliAlgTrack& operator=(const AliAlgTrack&); // protected: - int fNLocPar; // number of local params - int fNLocExtPar; // number of local params for the external track param - int fNGloPar; // number of free global parameters the track depends on - int fNDF; // number of degrees of freedom - int fInnerPointID; // ID of inner point in sorted track. For 2-leg cosmics - innermost point of lower leg - bool fNeedInv[2]; // set if one of cosmic legs need inversion - double fMinX2X0Pt2Account; // minimum X2X0/pT accumulated between 2 points worth to account - double fMass; // assumed mass - double fChi2; // chi2 with current residuals - double fChi2CosmUp; // chi2 for cosmic upper leg - double fChi2CosmDn; // chi2 for cosmic down leg - double fChi2Ini; // chi2 with current residuals - TObjArray fPoints; // alignment points - TArrayD fResid[2]; // residuals array - TArrayD fDResDLoc[2]; // array for derivatives over local params - TArrayD fDResDGlo[2]; // array for derivatives over global params - TArrayD fLocPar; // local parameters array - TArrayI fGloParID; // IDs of relevant global params - double* fResidA[2]; //! fast access to residuals - double* fDResDLocA[2]; //! fast access to local derivatives - double* fDResDGloA[2]; //! fast access to global derivatives - int* fGloParIDA; //! fast access to relevant global param IDs - double* fLocParA; //! fast access to local params + int mNLocPar; // number of local params + int mNLocExtPar; // number of local params for the external track param + int mNGloPar; // number of free global parameters the track depends on + int mNDF; // number of degrees of freedom + int mInnerPointID; // ID of inner point in sorted track. For 2-leg cosmics - innermost point of lower leg + bool mNeedInv[2]; // set if one of cosmic legs need inversion + double mMinX2X0Pt2Account; // minimum X2X0/pT accumulated between 2 points worth to account + double mMass; // assumed mass + double mChi2; // chi2 with current residuals + double mChi2CosmUp; // chi2 for cosmic upper leg + double mChi2CosmDn; // chi2 for cosmic down leg + double mChi2Ini; // chi2 with current residuals + TObjArray mPoints; // alignment points + TArrayD mResid[2]; // residuals array + TArrayD mDResDLoc[2]; // array for derivatives over local params + TArrayD mDResDGlo[2]; // array for derivatives over global params + TArrayD mLocPar; // local parameters array + TArrayI mGloParID; // IDs of relevant global params + double* mResidA[2]; //! fast access to residuals + double* mDResDLocA[2]; //! fast access to local derivatives + double* mDResDGloA[2]; //! fast access to global derivatives + int* mGloParIDA; //! fast access to relevant global param IDs + double* mLocParA; //! fast access to local params private: - bool Propagate(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT); + bool propagate(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT); // ClassDef(AliAlgTrack, 2) }; //____________________________________________________________________________________________ -inline void AliAlgTrack::SetParams(trackParam_t& tr, double x, double alp, const double* par, bool add) +inline void AliAlgTrack::setParams(trackParam_t& tr, double x, double alp, const double* par, bool add) { // set track params const double kDefQ2PtCosm = 1; @@ -198,9 +198,9 @@ inline void AliAlgTrack::SetParams(trackParam_t& tr, double x, double alp, const tr.setParam(val, i); } } - if (!GetFieldON()) { + if (!getFieldON()) { const double val = [&]() { - if (this->IsCosmic()) { + if (this->isCosmic()) { return kDefQ2PtCosm; } else { return kDefG2PtColl; @@ -211,56 +211,56 @@ inline void AliAlgTrack::SetParams(trackParam_t& tr, double x, double alp, const } //____________________________________________________________________________________________ -inline void AliAlgTrack::SetParams(trackParam_t* trSet, int ntr, double x, double alp, const double* par, bool add) +inline void AliAlgTrack::setParams(trackParam_t* trSet, int ntr, double x, double alp, const double* par, bool add) { // set parames for multiple tracks (VECTORIZE THIS) if (!add) { // full parameter supplied for (int itr = ntr; itr--;) - SetParams(trSet[itr], x, alp, par, false); + setParams(trSet[itr], x, alp, par, false); return; } params_t partr{0}; // par is a correction to reference parameter - for (int i = fNLocExtPar; i--;) + for (int i = mNLocExtPar; i--;) partr[i] = getParam(i) + par[i]; for (int itr = ntr; itr--;) - SetParams(trSet[itr], x, alp, partr.data(), false); + setParams(trSet[itr], x, alp, partr.data(), false); } //____________________________________________________________________________________________ -inline void AliAlgTrack::SetParam(trackParam_t& tr, int par, double val) +inline void AliAlgTrack::setParam(trackParam_t& tr, int par, double val) { // set track parameter tr.setParam(val, par); } //____________________________________________________________________________________________ -inline void AliAlgTrack::SetParam(trackParam_t* trSet, int ntr, int par, double val) +inline void AliAlgTrack::setParam(trackParam_t* trSet, int ntr, int par, double val) { // set parames for multiple tracks (VECTORIZE THIS) for (int i = 0; i < ntr; ++i) { - SetParam(trSet[i], par, val); + setParam(trSet[i], par, val); } } //____________________________________________________________________________________________ -inline void AliAlgTrack::ModParam(trackParam_t& tr, int par, double delta) +inline void AliAlgTrack::modParam(trackParam_t& tr, int par, double delta) { // modify track parameter const auto val = tr.getParam(par) + delta; - SetParam(tr, par, val); + setParam(tr, par, val); } //____________________________________________________________________________________________ -inline void AliAlgTrack::ModParam(trackParam_t* trSet, int ntr, int par, double delta) +inline void AliAlgTrack::modParam(trackParam_t* trSet, int ntr, int par, double delta) { // modify track parameter (VECTORIZE THOS) for (size_t i = 0; i < ntr; ++i) { - ModParam(trSet[i], par, delta); + modParam(trSet[i], par, delta); } } //______________________________________________ -inline void AliAlgTrack::CopyFrom(const trackParam_t* etp) +inline void AliAlgTrack::copyFrom(const trackParam_t* etp) { // assign kinematics set(etp->getX(), etp->getAlpha(), etp->getParams(), etp->getCov().data()); diff --git a/Detectors/Align/include/Align/AliAlgVol.h b/Detectors/Align/include/Align/AliAlgVol.h index 75f67bea3a861..24315ed22a02d 100644 --- a/Detectors/Align/include/Align/AliAlgVol.h +++ b/Detectors/Align/include/Align/AliAlgVol.h @@ -67,153 +67,153 @@ class AliAlgVol : public TNamed AliAlgVol(const char* symname = 0, int iid = 0); virtual ~AliAlgVol(); // - const char* GetSymName() const { return GetName(); } + const char* getSymName() const { return GetName(); } // - int GetVolID() const { return (int)GetUniqueID(); } - void SetVolID(int v) { SetUniqueID(v); } - int GetInternalID() const { return fIntID; } - void SetInternalID(int v) { fIntID = v; } + int getVolID() const { return (int)GetUniqueID(); } + void setVolID(int v) { SetUniqueID(v); } + int getInternalID() const { return mIntID; } + void setInternalID(int v) { mIntID = v; } // // - void AssignDOFs(int& cntDOFs, float* pars, float* errs, int* labs); - void InitDOFs(); + void assignDOFs(int& cntDOFs, float* pars, float* errs, int* labs); + void initDOFs(); // - Frame_t GetVarFrame() const { return fVarFrame; } - void SetVarFrame(Frame_t f) { fVarFrame = f; } - bool IsFrameTRA() const { return fVarFrame == kTRA; } - bool IsFrameLOC() const { return fVarFrame == kLOC; } + Frame_t getVarFrame() const { return mVarFrame; } + void setVarFrame(Frame_t f) { mVarFrame = f; } + bool isFrameTRA() const { return mVarFrame == kTRA; } + bool isFrameLOC() const { return mVarFrame == kLOC; } // - void SetFreeDOF(int dof) + void setFreeDOF(int dof) { - fDOF |= 0x1 << dof; - CalcFree(); + mDOF |= 0x1 << dof; + calcFree(); } - void FixDOF(int dof) + void fixDOF(int dof) { - fDOF &= ~(0x1 << dof); - CalcFree(); + mDOF &= ~(0x1 << dof); + calcFree(); } - void SetFreeDOFPattern(uint32_t pat) + void setFreeDOFPattern(uint32_t pat) { - fDOF = pat; - CalcFree(); + mDOF = pat; + calcFree(); } - bool IsFreeDOF(int dof) const { return (fDOF & (0x1 << dof)) != 0; } - bool IsCondDOF(int dof) const; - uint32_t GetFreeDOFPattern() const { return fDOF; } - uint32_t GetFreeDOFGeomPattern() const { return fDOF & kAllGeomDOF; } - // - void AddAutoConstraints(TObjArray* constrArr); - bool IsChildrenDOFConstrained(int dof) const { return fConstrChild & 0x1 << dof; } - uint8_t GetChildrenConstraintPattern() const { return fConstrChild; } - void ConstrainChildrenDOF(int dof) { fConstrChild |= 0x1 << dof; } - void UConstrainChildrenDOF(int dof) { fConstrChild &= ~(0x1 << dof); } - void SetChildrenConstrainPattern(uint32_t pat) { fConstrChild = pat; } - bool HasChildrenConstraint() const { return fConstrChild; } - // - AliAlgVol* GetParent() const { return fParent; } - void SetParent(AliAlgVol* par) + bool isFreeDOF(int dof) const { return (mDOF & (0x1 << dof)) != 0; } + bool isCondDOF(int dof) const; + uint32_t getFreeDOFPattern() const { return mDOF; } + uint32_t getFreeDOFGeomPattern() const { return mDOF & kAllGeomDOF; } + // + void addAutoConstraints(TObjArray* constrArr); + bool isChildrenDOFConstrained(int dof) const { return mConstrChild & 0x1 << dof; } + uint8_t getChildrenConstraintPattern() const { return mConstrChild; } + void constrainChildrenDOF(int dof) { mConstrChild |= 0x1 << dof; } + void uConstrainChildrenDOF(int dof) { mConstrChild &= ~(0x1 << dof); } + void setChildrenConstrainPattern(uint32_t pat) { mConstrChild = pat; } + bool hasChildrenConstraint() const { return mConstrChild; } + // + AliAlgVol* getParent() const { return mParent; } + void setParent(AliAlgVol* par) { - fParent = par; + mParent = par; if (par) - par->AddChild(this); + par->addChild(this); } - int CountParents() const; + int countParents() const; // - int GetNChildren() const { return fChildren ? fChildren->GetEntriesFast() : 0; } - AliAlgVol* GetChild(int i) const { return fChildren ? (AliAlgVol*)fChildren->UncheckedAt(i) : 0; } - virtual void AddChild(AliAlgVol* ch); + int getNChildren() const { return mChildren ? mChildren->GetEntriesFast() : 0; } + AliAlgVol* getChild(int i) const { return mChildren ? (AliAlgVol*)mChildren->UncheckedAt(i) : 0; } + virtual void addChild(AliAlgVol* ch); // - double GetXTracking() const { return fX; } - double GetAlpTracking() const { return fAlp; } + double getXTracking() const { return mX; } + double getAlpTracking() const { return mAlp; } // - int GetNProcessedPoints() const { return fNProcPoints; } - virtual int FinalizeStat(AliAlgDOFStat* h = 0); - void FillDOFStat(AliAlgDOFStat* h) const; + int getNProcessedPoints() const { return mNProcPoints; } + virtual int finalizeStat(AliAlgDOFStat* h = 0); + void fillDOFStat(AliAlgDOFStat* h) const; // - float* GetParVals() const { return fParVals; } - double GetParVal(int par) const { return fParVals[par]; } - double GetParErr(int par) const { return fParErrs[par]; } - int GetParLab(int par) const { return fParLabs[par]; } - void GetParValGeom(double* delta) const + float* getParVals() const { return mParVals; } + double getParVal(int par) const { return mParVals[par]; } + double getParErr(int par) const { return mParErrs[par]; } + int getParLab(int par) const { return mParLabs[par]; } + void getParValGeom(double* delta) const { for (int i = kNDOFGeom; i--;) - delta[i] = fParVals[i]; + delta[i] = mParVals[i]; } // - void SetParVals(int npar, double* vl, double* er); - void SetParVal(int par, double v = 0) { fParVals[par] = v; } - void SetParErr(int par, double e = 0) { fParErrs[par] = e; } + void setParVals(int npar, double* vl, double* er); + void setParVal(int par, double v = 0) { mParVals[par] = v; } + void setParErr(int par, double e = 0) { mParErrs[par] = e; } // - int GetNDOFs() const { return fNDOFs; } - int GetNDOFFree() const { return fNDOFFree; } - int GetNDOFGeomFree() const { return fNDOFGeomFree; } - int GetFirstParGloID() const { return fFirstParGloID; } - int GetParGloID(int par) const { return fFirstParGloID + par; } - void SetFirstParGloID(int id) { fFirstParGloID = id; } + int getNDOFs() const { return mNDOFs; } + int getNDOFFree() const { return mNDOFFree; } + int getNDOFGeomFree() const { return mNDOFGeomFree; } + int getFirstParGloID() const { return mFirstParGloID; } + int getParGloID(int par) const { return mFirstParGloID + par; } + void setFirstParGloID(int id) { mFirstParGloID = id; } // - virtual void PrepareMatrixT2L(); - virtual void SetTrackingFrame(); + virtual void prepareMatrixT2L(); + virtual void setTrackingFrame(); // - const TGeoHMatrix& GetMatrixL2G() const { return fMatL2G; } - const TGeoHMatrix& GetMatrixL2GIdeal() const { return fMatL2GIdeal; } - const TGeoHMatrix& GetMatrixL2GReco() const { return fMatL2GReco; } - const TGeoHMatrix& GetGlobalDeltaRef() const { return fMatDeltaRefGlo; } - void SetMatrixL2G(const TGeoHMatrix& m) { fMatL2G = m; } - void SetMatrixL2GIdeal(const TGeoHMatrix& m) { fMatL2GIdeal = m; } - void SetMatrixL2GReco(const TGeoHMatrix& m) { fMatL2GReco = m; } - void SetGlobalDeltaRef(TGeoHMatrix& mat) { fMatDeltaRefGlo = mat; } + const TGeoHMatrix& getMatrixL2G() const { return mMatL2G; } + const TGeoHMatrix& getMatrixL2GIdeal() const { return mMatL2GIdeal; } + const TGeoHMatrix& getMatrixL2GReco() const { return mMatL2GReco; } + const TGeoHMatrix& getGlobalDeltaRef() const { return mMatDeltaRefGlo; } + void setMatrixL2G(const TGeoHMatrix& m) { mMatL2G = m; } + void setMatrixL2GIdeal(const TGeoHMatrix& m) { mMatL2GIdeal = m; } + void setMatrixL2GReco(const TGeoHMatrix& m) { mMatL2GReco = m; } + void setGlobalDeltaRef(TGeoHMatrix& mat) { mMatDeltaRefGlo = mat; } // - virtual void PrepareMatrixL2G(bool reco = false); - virtual void PrepareMatrixL2GIdeal(); - virtual void UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta); + virtual void prepareMatrixL2G(bool reco = false); + virtual void prepareMatrixL2GIdeal(); + virtual void updateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta); // - void GetMatrixT2G(TGeoHMatrix& m) const; + void getMatrixT2G(TGeoHMatrix& m) const; // - const TGeoHMatrix& GetMatrixT2L() const { return fMatT2L; } - void SetMatrixT2L(const TGeoHMatrix& m); + const TGeoHMatrix& getMatrixT2L() const { return mMatT2L; } + void setMatrixT2L(const TGeoHMatrix& m); // - void Delta2Matrix(TGeoHMatrix& deltaM, const double* delta) const; + void delta2Matrix(TGeoHMatrix& deltaM, const double* delta) const; // // preparation of variation matrices - void GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const double* delta) const; - void GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const double* delta) const; - void GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const double* delta, const TGeoHMatrix& relMat) const; - void GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const double* delta, const TGeoHMatrix& relMat) const; + void getDeltaT2LmodLOC(TGeoHMatrix& matMod, const double* delta) const; + void getDeltaT2LmodTRA(TGeoHMatrix& matMod, const double* delta) const; + void getDeltaT2LmodLOC(TGeoHMatrix& matMod, const double* delta, const TGeoHMatrix& relMat) const; + void getDeltaT2LmodTRA(TGeoHMatrix& matMod, const double* delta, const TGeoHMatrix& relMat) const; // // creation of global matrices for storage - void CreateGloDeltaMatrix(TGeoHMatrix& deltaM) const; - void CreateLocDeltaMatrix(TGeoHMatrix& deltaM) const; - void CreatePreGloDeltaMatrix(TGeoHMatrix& deltaM) const; - void CreatePreLocDeltaMatrix(TGeoHMatrix& deltaM) const; - void CreateAlignmenMatrix(TGeoHMatrix& alg) const; - void CreateAlignmentObjects(TClonesArray* arr) const; + void createGloDeltaMatrix(TGeoHMatrix& deltaM) const; + void createLocDeltaMatrix(TGeoHMatrix& deltaM) const; + void createPreGloDeltaMatrix(TGeoHMatrix& deltaM) const; + void createPreLocDeltaMatrix(TGeoHMatrix& deltaM) const; + void createAlignmenMatrix(TGeoHMatrix& alg) const; + void createAlignmentObjects(TClonesArray* arr) const; // - void SetSkip(bool v = true) { SetBit(kSkipBit, v); } - bool GetSkip() const { return TestBit(kSkipBit); } + void setSkip(bool v = true) { SetBit(kSkipBit, v); } + bool getSkip() const { return TestBit(kSkipBit); } // - void ExcludeFromParentConstraint(bool v = true) { SetBit(kExclFromParentConstraintBit, v); } - bool GetExcludeFromParentConstraint() const { return TestBit(kExclFromParentConstraintBit); } + void excludeFromParentConstraint(bool v = true) { SetBit(kExclFromParentConstraintBit, v); } + bool getExcludeFromParentConstraint() const { return TestBit(kExclFromParentConstraintBit); } // - void SetInitDOFsDone() { SetBit(kInitDOFsDoneBit); } - bool GetInitDOFsDone() const { return TestBit(kInitDOFsDoneBit); } + void setInitDOFsDone() { SetBit(kInitDOFsDoneBit); } + bool getInitDOFsDone() const { return TestBit(kInitDOFsDoneBit); } // - bool OwnsDOFID(int id) const; - AliAlgVol* GetVolOfDOFID(int id) const; + bool ownsDOFID(int id) const; + AliAlgVol* getVolOfDOFID(int id) const; // - virtual bool IsSensor() const { return false; } + virtual bool isSensor() const { return false; } // - virtual const char* GetDOFName(int i) const; + virtual const char* getDOFName(int i) const; virtual void Print(const Option_t* opt = "") const; - virtual void WritePedeInfo(FILE* parOut, const Option_t* opt = "") const; + virtual void writePedeInfo(FILE* parOut, const Option_t* opt = "") const; // - static const char* GetGeomDOFName(int i) { return i < kNDOFGeom ? fgkDOFName[i] : 0; } - static void SetDefGeomFree(uint8_t patt) { fgDefGeomFree = patt; } - static uint8_t GetDefGeomFree() { return fgDefGeomFree; } + static const char* getGeomDOFName(int i) { return i < kNDOFGeom ? sDOFName[i] : 0; } + static void setDefGeomFree(uint8_t patt) { sDefGeomFree = patt; } + static uint8_t getDefGeomFree() { return sDefGeomFree; } // protected: - void SetNDOFs(int n = kNDOFGeom); - void CalcFree(bool condFree = false); + void setNDOFs(int n = kNDOFGeom); + void calcFree(bool condFree = false); // // ------- dummies ------- AliAlgVol(const AliAlgVol&); @@ -221,45 +221,45 @@ class AliAlgVol : public TNamed // protected: // - Frame_t fVarFrame; // Variation frame for this volume - int fIntID; // internal id within the detector - double fX; // tracking frame X offset - double fAlp; // tracking frame alpa + Frame_t mVarFrame; // Variation frame for this volume + int mIntID; // internal id within the detector + double mX; // tracking frame X offset + double mAlp; // tracking frame alpa // - char fNDOFs; // number of degrees of freedom, including fixed ones - uint32_t fDOF; // bitpattern degrees of freedom - char fNDOFGeomFree; // number of free geom degrees of freedom - char fNDOFFree; // number of all free degrees of freedom - uint8_t fConstrChild; // bitpattern for constraints on children corrections + char mNDOFs; // number of degrees of freedom, including fixed ones + uint32_t mDOF; // bitpattern degrees of freedom + char mNDOFGeomFree; // number of free geom degrees of freedom + char mNDOFFree; // number of all free degrees of freedom + uint8_t mConstrChild; // bitpattern for constraints on children corrections // - AliAlgVol* fParent; // parent volume - TObjArray* fChildren; // array of childrens + AliAlgVol* mParent; // parent volume + TObjArray* mChildren; // array of childrens // - int fNProcPoints; // n of processed points - int fFirstParGloID; // ID of the 1st parameter in the global results array - float* fParVals; //! values of the fitted params - float* fParErrs; //! errors of the fitted params - int* fParLabs; //! labels for parameters + int mNProcPoints; // n of processed points + int mFirstParGloID; // ID of the 1st parameter in the global results array + float* mParVals; //! values of the fitted params + float* mParErrs; //! errors of the fitted params + int* mParLabs; //! labels for parameters // - TGeoHMatrix fMatL2GReco; // local to global matrix used for reco of data being processed - TGeoHMatrix fMatL2G; // local to global matrix, including current alignment - TGeoHMatrix fMatL2GIdeal; // local to global matrix, ideal - TGeoHMatrix fMatT2L; // tracking to local matrix (ideal) - TGeoHMatrix fMatDeltaRefGlo; // global reference delta from Align/Data + TGeoHMatrix mMatL2GReco; // local to global matrix used for reco of data being processed + TGeoHMatrix mMatL2G; // local to global matrix, including current alignment + TGeoHMatrix mMatL2GIdeal; // local to global matrix, ideal + TGeoHMatrix mMatT2L; // tracking to local matrix (ideal) + TGeoHMatrix mMatDeltaRefGlo; // global reference delta from Align/Data // - static const char* fgkDOFName[kNDOFGeom]; - static const char* fgkFrameName[kNVarFrames]; - static uint32_t fgDefGeomFree; + static const char* sDOFName[kNDOFGeom]; + static const char* sFrameName[kNVarFrames]; + static uint32_t sDefGeomFree; // ClassDef(AliAlgVol, 2) }; //___________________________________________________________ -inline void AliAlgVol::GetMatrixT2G(TGeoHMatrix& m) const +inline void AliAlgVol::getMatrixT2G(TGeoHMatrix& m) const { // compute tracking to global matrix, i.e. glo = T2G*tra = L2G*loc = L2G*T2L*tra - m = GetMatrixL2GIdeal(); - m *= GetMatrixT2L(); + m = getMatrixL2GIdeal(); + m *= getMatrixT2L(); } } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgVtx.h b/Detectors/Align/include/Align/AliAlgVtx.h index b01790b2b88f2..5dfaabddf71c0 100644 --- a/Detectors/Align/include/Align/AliAlgVtx.h +++ b/Detectors/Align/include/Align/AliAlgVtx.h @@ -42,17 +42,17 @@ class AliAlgVtx : public AliAlgSens public: AliAlgVtx(); // - void ApplyCorrection(double* vtx) const; - virtual bool IsSensor() const { return true; } + void applyCorrection(double* vtx) const; + virtual bool isSensor() const { return true; } // - void SetAlpha(double alp) + void setAlpha(double alp) { - fAlp = alp; - PrepareMatrixT2L(); + mAlp = alp; + prepareMatrixT2L(); } - virtual void PrepareMatrixL2G(bool = 0) { fMatL2G.Clear(); } // unit matrix - virtual void PrepareMatrixL2GIdeal() { fMatL2GIdeal.Clear(); } // unit matrix - virtual void PrepareMatrixT2L(); + virtual void prepareMatrixL2G(bool = 0) { mMatL2G.Clear(); } // unit matrix + virtual void prepareMatrixL2GIdeal() { mMatL2GIdeal.Clear(); } // unit matrix + virtual void prepareMatrixT2L(); // // virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); FIXME(milettri): needs AliTrackPointArray, AliESDtrack // diff --git a/Detectors/Align/src/AliAlgAux.cxx b/Detectors/Align/src/AliAlgAux.cxx index e51842ebb8bec..523d6da76662f 100644 --- a/Detectors/Align/src/AliAlgAux.cxx +++ b/Detectors/Align/src/AliAlgAux.cxx @@ -30,7 +30,7 @@ namespace align { //_______________________________________________________________ -void AliAlgAux::PrintBits(size_t patt, int maxBits) +void AliAlgAux::printBits(size_t patt, int maxBits) { // print maxBits of the pattern maxBits = std::min(64, maxBits); @@ -39,7 +39,7 @@ void AliAlgAux::PrintBits(size_t patt, int maxBits) } //__________________________________________ -int AliAlgAux::FindKeyIndex(int key, const int* arr, int n) +int AliAlgAux::findKeyIndex(int key, const int* arr, int n) { // finds index of key in the array int imn = 0, imx = n - 1; diff --git a/Detectors/Align/src/AliAlgConstraint.cxx b/Detectors/Align/src/AliAlgConstraint.cxx index 4f95a85eb0568..11d59abda2c02 100644 --- a/Detectors/Align/src/AliAlgConstraint.cxx +++ b/Detectors/Align/src/AliAlgConstraint.cxx @@ -33,35 +33,35 @@ namespace align //___________________________________________________________________ AliAlgConstraint::AliAlgConstraint(const char* name, const char* title) - : TNamed(name, title), fConstraint(0), fParent(0), fChildren(2) + : TNamed(name, title), mConstraint(0), mParent(0), mChildren(2) { // def. c-tor for (int i = kNDOFGeom; i--;) - fSigma[i] = 0; + mSigma[i] = 0; } //___________________________________________________________________ AliAlgConstraint::~AliAlgConstraint() { // d-tor - delete fParent; + delete mParent; } //___________________________________________________________________ -void AliAlgConstraint::SetParent(const AliAlgVol* par) +void AliAlgConstraint::setParent(const AliAlgVol* par) { - fParent = par; + mParent = par; TString nm = GetName(); if (nm.IsNull()) { if (par) - SetNameTitle(par->GetSymName(), "Automatic"); + SetNameTitle(par->getSymName(), "Automatic"); else SetNameTitle("GLOBAL", "Automatic"); } } //______________________________________________________ -void AliAlgConstraint::WriteChildrenConstraints(FILE* conOut) const +void AliAlgConstraint::writeChildrenConstraints(FILE* conOut) const { // write for PEDE eventual constraints on children movement in parent frame // @@ -73,8 +73,8 @@ void AliAlgConstraint::WriteChildrenConstraints(FILE* conOut) const const char* comment[3] = {" ", "! ", "!!"}; const char* kKeyConstr[2] = {"constraint", "measurement"}; // - bool doJac = !GetNoJacobian(); // do we need jacobian evaluation? - int nch = GetNChildren(); + bool doJac = !getNoJacobian(); // do we need jacobian evaluation? + int nch = getNChildren(); float* cstrArr = new float[nch * kNDOFGeom * kNDOFGeom]; memset(cstrArr, 0, nch * kNDOFGeom * kNDOFGeom * sizeof(float)); // we need for each children the matrix for vector transformation from children frame @@ -84,39 +84,39 @@ void AliAlgConstraint::WriteChildrenConstraints(FILE* conOut) const // // in case of parent assigned use its matrix, // otherwise Alice global frame is assumed to be the parent -> Unit matrix - if (fParent && doJac) { - if (fParent->IsFrameTRA()) - fParent->GetMatrixT2G(mPar); // tracking to global + if (mParent && doJac) { + if (mParent->isFrameTRA()) + mParent->getMatrixT2G(mPar); // tracking to global else - mPar = fParent->GetMatrixL2GIdeal(); // local to global + mPar = mParent->getMatrixL2GIdeal(); // local to global mPar = mPar.Inverse(); } // float* jac = cstrArr; int nContCh[kNDOFGeom] = {0}; // we need at least on contributing children DOF to constrain the parent DOF for (int ich = 0; ich < nch; ich++) { - AliAlgVol* child = GetChild(ich); + AliAlgVol* child = getChild(ich); // if (doJac) { // calculate jacobian TGeoHMatrix matRel; - if (child->IsFrameTRA()) - child->GetMatrixT2G(matRel); // tracking to global + if (child->isFrameTRA()) + child->getMatrixT2G(matRel); // tracking to global else - matRel = child->GetMatrixL2GIdeal(); // local to global + matRel = child->getMatrixL2GIdeal(); // local to global matRel.MultiplyLeft(&mPar); - ConstrCoefGeom(matRel, jac); + constrCoefGeom(matRel, jac); // for (int ics = 0; ics < kNDOFGeom; ics++) { // DOF of parent to be constrained for (int ip = 0; ip < kNDOFGeom; ip++) { // count contributing DOFs float jv = jac[ics * kNDOFGeom + ip]; - if (!IsZeroAbs(jv) && child->IsFreeDOF(ip) && child->GetParErr(ip) >= 0) + if (!isZeroAbs(jv) && child->isFreeDOF(ip) && child->getParErr(ip) >= 0) nContCh[ip]++; } } } else { // simple constraint on the sum of requested DOF // for (int ip = 0; ip < kNDOFGeom; ip++) { - if (child->IsFreeDOF(ip) && child->GetParErr(ip) >= 0) + if (child->isFreeDOF(ip) && child->getParErr(ip) >= 0) nContCh[ip]++; jac[ip * kNDOFGeom + ip] = 1.; } @@ -125,39 +125,39 @@ void AliAlgConstraint::WriteChildrenConstraints(FILE* conOut) const } // for (int ics = 0; ics < kNDOFGeom; ics++) { - if (!IsDOFConstrained(ics)) + if (!isDOFConstrained(ics)) continue; int cmtStatus = nContCh[ics] > 0 ? kOff : kOn; // do we comment this constraint? // if (cmtStatus) { - LOG(INFO) << "No contributors to constraint of " << GetDOFName(ics) << " of " << GetName(); + LOG(INFO) << "No contributors to constraint of " << getDOFName(ics) << " of " << GetName(); } - if (fSigma[ics] > 0) { - fprintf(conOut, "\n%s%s\t%e\t%e\t%s %s of %s %s\n", comment[cmtStatus], kKeyConstr[kMeas], 0.0, fSigma[ics], - comment[kOnOn], GetDOFName(ics), GetName(), GetTitle()); + if (mSigma[ics] > 0) { + fprintf(conOut, "\n%s%s\t%e\t%e\t%s %s of %s %s\n", comment[cmtStatus], kKeyConstr[kMeas], 0.0, mSigma[ics], + comment[kOnOn], getDOFName(ics), GetName(), GetTitle()); } else { fprintf(conOut, "\n%s%s\t%e\t%s %s of %s %s\n", comment[cmtStatus], kKeyConstr[kConstr], 0.0, - comment[kOnOn], GetDOFName(ics), GetName(), GetTitle()); + comment[kOnOn], getDOFName(ics), GetName(), GetTitle()); } for (int ich = 0; ich < nch; ich++) { // contribution from this children DOFs to constraint - AliAlgVol* child = GetChild(ich); + AliAlgVol* child = getChild(ich); jac = cstrArr + kNDOFGeom * kNDOFGeom * ich; if (cmtStatus) fprintf(conOut, "%s", comment[cmtStatus]); // comment out contribution // first write real constraints for (int ip = 0; ip < kNDOFGeom; ip++) { float jv = jac[ics * kNDOFGeom + ip]; - if (child->IsFreeDOF(ip) && !IsZeroAbs(jv) && child->GetParErr(ip) >= 0) - fprintf(conOut, "%9d %+.3e\t", child->GetParLab(ip), jv); + if (child->isFreeDOF(ip) && !isZeroAbs(jv) && child->getParErr(ip) >= 0) + fprintf(conOut, "%9d %+.3e\t", child->getParLab(ip), jv); } // loop over DOF's of children contributing to this constraint // now, after comment, write disabled constraints fprintf(conOut, "%s ", comment[kOn]); if (doJac) { for (int ip = 0; ip < kNDOFGeom; ip++) { float jv = jac[ics * kNDOFGeom + ip]; - if (child->IsFreeDOF(ip) && !IsZeroAbs(jv) && child->GetParErr(ip) >= 0) + if (child->isFreeDOF(ip) && !isZeroAbs(jv) && child->getParErr(ip) >= 0) continue; - fprintf(conOut, "%9d %+.3e\t", child->GetParLab(ip), jv); + fprintf(conOut, "%9d %+.3e\t", child->getParLab(ip), jv); } // loop over DOF's of children contributing to this constraint } fprintf(conOut, "%s from %s\n", comment[kOnOn], child->GetName()); @@ -168,14 +168,14 @@ void AliAlgConstraint::WriteChildrenConstraints(FILE* conOut) const } //______________________________________________________ -void AliAlgConstraint::CheckConstraint() const +void AliAlgConstraint::checkConstraint() const { // check how the constraints are satysfied - int nch = GetNChildren(); + int nch = getNChildren(); if (!nch) return; // - bool doJac = !GetNoJacobian(); // do we need jacobian evaluation? + bool doJac = !getNoJacobian(); // do we need jacobian evaluation? float* cstrArr = new float[nch * kNDOFGeom * kNDOFGeom]; memset(cstrArr, 0, nch * kNDOFGeom * kNDOFGeom * sizeof(float)); // we need for each children the matrix for vector transformation from children frame @@ -184,11 +184,11 @@ void AliAlgConstraint::CheckConstraint() const TGeoHMatrix mPar; // in case of parent assigned use its matrix, // otherwise Alice global frame is assumed to be the parent -> Unit matrix - if (fParent && doJac) { - if (fParent->IsFrameTRA()) - fParent->GetMatrixT2G(mPar); // tracking to global + if (mParent && doJac) { + if (mParent->isFrameTRA()) + mParent->getMatrixT2G(mPar); // tracking to global else - mPar = fParent->GetMatrixL2GIdeal(); // local to global + mPar = mParent->getMatrixL2GIdeal(); // local to global mPar = mPar.Inverse(); } // @@ -199,30 +199,30 @@ void AliAlgConstraint::CheckConstraint() const printf("\n\n ----- Constraints Validation for %s %s ------\n", GetName(), GetTitle()); printf(" chld| "); for (int jp = 0; jp < kNDOFGeom; jp++) - printf(" %3s:%3s An/Ex |", GetDOFName(jp), IsDOFConstrained(jp) ? "ON " : "OFF"); + printf(" %3s:%3s An/Ex |", getDOFName(jp), isDOFConstrained(jp) ? "ON " : "OFF"); printf(" | "); for (int jp = 0; jp < kNDOFGeom; jp++) - printf(" D%3s ", GetDOFName(jp)); + printf(" D%3s ", getDOFName(jp)); printf(" ! %s\n", GetName()); for (int ich = 0; ich < nch; ich++) { - AliAlgVol* child = GetChild(ich); + AliAlgVol* child = getChild(ich); double parsC[kNDOFGeom] = {0}, parsPAn[kNDOFGeom] = {0}, parsPEx[kNDOFGeom] = {0}; for (int jc = kNDOFGeom; jc--;) - parsC[jc] = child->GetParVal(jc); // child params in child frame + parsC[jc] = child->getParVal(jc); // child params in child frame printf("#%3d | ", ich); // if (doJac) { TGeoHMatrix matRel; - if (child->IsFrameTRA()) - child->GetMatrixT2G(matRel); // tracking to global + if (child->isFrameTRA()) + child->getMatrixT2G(matRel); // tracking to global else - matRel = child->GetMatrixL2GIdeal(); // local to global + matRel = child->getMatrixL2GIdeal(); // local to global // matRel.MultiplyLeft(&mPar); - ConstrCoefGeom(matRel, jac); // Jacobian for analytical constraint used by MillePeded + constrCoefGeom(matRel, jac); // Jacobian for analytical constraint used by MillePeded // TGeoHMatrix tau; - child->Delta2Matrix(tau, parsC); // child correction matrix in the child frame + child->delta2Matrix(tau, parsC); // child correction matrix in the child frame const TGeoHMatrix& matreli = matRel.Inverse(); tau.Multiply(&matreli); tau.MultiplyLeft(&matRel); // child correction matrix in the parent frame @@ -256,7 +256,7 @@ void AliAlgConstraint::CheckConstraint() const jac += kNDOFGeom * kNDOFGeom; // matrix for next slot } else { for (int jc = 0; jc < kNDOFGeom; jc++) { - bool acc = child->IsFreeDOF(jc) && child->GetParErr(jc) >= 0; + bool acc = child->isFreeDOF(jc) && child->getParErr(jc) >= 0; if (acc) { printf(" %+.3e ", parsC[jc]); parsTotAn[jc] += parsC[jc]; @@ -267,7 +267,7 @@ void AliAlgConstraint::CheckConstraint() const printf(" | "); for (int jc = 0; jc < kNDOFGeom; jc++) printf("%+.1e ", parsC[jc]); // child proper corrections - printf(" ! %s\n", child->GetSymName()); + printf(" ! %s\n", child->getSymName()); } // printf(" Tot | "); @@ -275,26 +275,26 @@ void AliAlgConstraint::CheckConstraint() const if (doJac) printf("%+.1e/%+.1e ", parsTotAn[jp], parsTotEx[jp]); else { - if (IsDOFConstrained(jp)) + if (isDOFConstrained(jp)) printf(" %+.3e ", parsTotAn[jp]); else printf(" /* %+.3e */ ", parsTotAn[jp]); } } printf(" | "); - if (fParent) + if (mParent) for (int jp = 0; jp < kNDOFGeom; jp++) - printf("%+.1e ", fParent->GetParVal(jp)); // parent proper corrections + printf("%+.1e ", mParent->getParVal(jp)); // parent proper corrections else printf(" no parent -> %s ", doJac ? "Global" : "Simple"); printf(" ! <----- %s\n", GetName()); // printf(" Sig | "); for (int jp = 0; jp < kNDOFGeom; jp++) { - if (IsDOFConstrained(jp)) - printf(" %+.3e ", fSigma[jp]); + if (isDOFConstrained(jp)) + printf(" %+.3e ", mSigma[jp]); else - printf(" /* %+.3e */ ", fSigma[jp]); + printf(" /* %+.3e */ ", mSigma[jp]); } printf(" ! <----- \n"); @@ -304,7 +304,7 @@ void AliAlgConstraint::CheckConstraint() const } //_________________________________________________________________ -void AliAlgConstraint::ConstrCoefGeom(const TGeoHMatrix& matRD, float* jac /*[kNDOFGeom][kNDOFGeom]*/) const +void AliAlgConstraint::constrCoefGeom(const TGeoHMatrix& matRD, float* jac /*[kNDOFGeom][kNDOFGeom]*/) const { // If the transformation R brings the vector from "local" frame to "master" frame as V=R*v // then application of the small LOCAL correction tau to vector v is equivalent to @@ -379,13 +379,13 @@ void AliAlgConstraint::Print(const Option_t*) const // print info printf("Constraint on "); for (int i = 0; i < kNDOFGeom; i++) - if (IsDOFConstrained(i)) - printf("%3s (Sig:%+e) ", GetDOFName(i), GetSigma(i)); + if (isDOFConstrained(i)) + printf("%3s (Sig:%+e) ", getDOFName(i), getSigma(i)); printf(" | %s %s\n", GetName(), GetTitle()); - if (GetNoJacobian()) + if (getNoJacobian()) printf("!!! This is explicit constraint on sum of DOFs (no Jacobian)!!!\n"); - for (int i = 0; i < GetNChildren(); i++) { - const AliAlgVol* child = GetChild(i); + for (int i = 0; i < getNChildren(); i++) { + const AliAlgVol* child = getChild(i); printf("%3d %s\n", i, child->GetName()); } } diff --git a/Detectors/Align/src/AliAlgDOFStat.cxx b/Detectors/Align/src/AliAlgDOFStat.cxx index fe6d7f3285644..739c6d414285f 100644 --- a/Detectors/Align/src/AliAlgDOFStat.cxx +++ b/Detectors/Align/src/AliAlgDOFStat.cxx @@ -30,12 +30,12 @@ namespace align //_________________________________________________________ AliAlgDOFStat::AliAlgDOFStat(int n) - : TNamed("DOFstat", "DOF statistics"), fNDOFs(n), fNMerges(1), fStat(0) + : TNamed("DOFstat", "DOF statistics"), mNDOFs(n), mNMerges(1), mStat(0) { // def c-tor - if (fNDOFs) { - fStat = new int[n]; - memset(fStat, 0, fNDOFs * sizeof(int)); + if (mNDOFs) { + mStat = new int[n]; + memset(mStat, 0, mNDOFs * sizeof(int)); } // } @@ -44,34 +44,34 @@ AliAlgDOFStat::AliAlgDOFStat(int n) AliAlgDOFStat::~AliAlgDOFStat() { // d-r - delete[] fStat; + delete[] mStat; } //____________________________________________ void AliAlgDOFStat::Print(Option_t*) const { // print info - printf("NDOFs: %d, NMerges: %d\n", fNDOFs, fNMerges); + printf("NDOFs: %d, NMerges: %d\n", mNDOFs, mNMerges); // } //____________________________________________ -TH1F* AliAlgDOFStat::CreateHisto(AliAlgSteer* st) const +TH1F* AliAlgDOFStat::createHisto(AliAlgSteer* st) const { // create histo with stat. If steer object is supplied, build labels - if (!fNDOFs) + if (!mNDOFs) return 0; - TH1F* h = new TH1F("DOFstat", "statistics per DOF", fNDOFs, 0, fNDOFs); - for (int i = fNDOFs; i--;) { - h->SetBinContent(i + 1, fStat[i]); + TH1F* h = new TH1F("DOFstat", "statistics per DOF", mNDOFs, 0, mNDOFs); + for (int i = mNDOFs; i--;) { + h->SetBinContent(i + 1, mStat[i]); if (st) - h->GetXaxis()->SetBinLabel(i + 1, st->GetDOFLabelTxt(i)); + h->GetXaxis()->SetBinLabel(i + 1, st->getDOFLabelTxt(i)); } return h; } //______________________________________________________________________________ -int64_t AliAlgDOFStat::Merge(TCollection* list) +int64_t AliAlgDOFStat::merge(TCollection* list) { // merge statistics int nmerged = 0; @@ -81,13 +81,13 @@ int64_t AliAlgDOFStat::Merge(TCollection* list) AliAlgDOFStat* stAdd = dynamic_cast(obj); if (!stAdd) continue; - if (fNDOFs != stAdd->fNDOFs) { - LOG(ERROR) << "Different NDOF: " << fNDOFs << " vs " << stAdd->fNDOFs << "."; + if (mNDOFs != stAdd->mNDOFs) { + LOG(ERROR) << "Different NDOF: " << mNDOFs << " vs " << stAdd->mNDOFs << "."; return 0; } - for (int i = fNDOFs; i--;) - fStat[i] += stAdd->fStat[i]; - fNMerges += stAdd->fNMerges; + for (int i = mNDOFs; i--;) + mStat[i] += stAdd->mStat[i]; + mNMerges += stAdd->mNMerges; nmerged++; } return nmerged; diff --git a/Detectors/Align/src/AliAlgDet.cxx b/Detectors/Align/src/AliAlgDet.cxx index db056b40f51dc..7531c81751305 100644 --- a/Detectors/Align/src/AliAlgDet.cxx +++ b/Detectors/Align/src/AliAlgDet.cxx @@ -46,39 +46,39 @@ namespace align //____________________________________________ AliAlgDet::AliAlgDet() - : fNDOFs(0), fVolIDMin(-1), fVolIDMax(-1), fNSensors(0), fSID2VolID(0), fNProcPoints(0) + : mNDOFs(0), mVolIDMin(-1), mVolIDMax(-1), mNSensors(0), mSID2VolID(0), mNProcPoints(0) // , - fNCalibDOF(0), - fNCalibDOFFree(0), - fCalibDOF(0), - fFirstParGloID(-1), - fParVals(0), - fParErrs(0), - fParLabs(0) + mNCalibDOF(0), + mNCalibDOFFree(0), + mCalibDOF(0), + mFirstParGloID(-1), + mParVals(0), + mParErrs(0), + mParLabs(0) // , - fUseErrorParam(0), - fSensors(), - fVolumes() + mUseErrorParam(0), + mSensors(), + mVolumes() // , - fNPoints(0), - fPoolNPoints(0), - fPoolFreePointID(0), - fPointsPool(), - fAlgSteer(0) + mNPoints(0), + mPoolNPoints(0), + mPoolFreePointID(0), + mPointsPool(), + mAlgSteer(0) { // def c-tor SetUniqueID(AliAlgSteer::kUndefined); // derived detectors must override this SetUniqueID(6); - fAddError[0] = fAddError[1] = 0; + mAddError[0] = mAddError[1] = 0; // for (int i = 0; i < kNTrackTypes; i++) { - fDisabled[i] = false; - fObligatory[i] = false; - fTrackFlagSel[i] = 0; - fNPointsSel[i] = 0; + mDisabled[i] = false; + mObligatory[i] = false; + mTrackFlagSel[i] = 0; + mNPointsSel[i] = 0; } // } @@ -87,9 +87,9 @@ AliAlgDet::AliAlgDet() AliAlgDet::~AliAlgDet() { // d-tor - fSensors.Clear(); // sensors are also attached as volumes, don't delete them here - fVolumes.Delete(); // here all is deleted - fPointsPool.Delete(); + mSensors.Clear(); // sensors are also attached as volumes, don't delete them here + mVolumes.Delete(); // here all is deleted + mPointsPool.Delete(); } //FIXME(milettri): needs AliESDtrack @@ -104,37 +104,37 @@ AliAlgDet::~AliAlgDet() // const AliESDfriendTrack* trF(esdTr->GetFriendTrack()); // const AliTrackPointArray* trP(trF->GetTrackPointArray()); // // -// int np(trP->GetNPoints()); +// int np(trP->getNPoints()); // int npSel(0); // AliAlgPoint* apnt(0); // for (int ip = 0; ip < np; ip++) { // int vid = trP->GetVolumeID()[ip]; -// if (!SensorOfDetector(vid)) +// if (!sensorOfDetector(vid)) // continue; -// apnt = GetSensorByVolId(vid)->TrackPoint2AlgPoint(ip, trP, esdTr); +// apnt = getSensorByVolId(vid)->TrackPoint2AlgPoint(ip, trP, esdTr); // if (!apnt) // continue; -// algTrack->AddPoint(apnt); +// algTrack->addPoint(apnt); // if (inv) -// apnt->SetInvDir(); +// apnt->setInvDir(); // npSel++; -// fNPoints++; +// mNPoints++; // } // // // return npSel; //} //_________________________________________________________ -void AliAlgDet::AcknowledgeNewRun(int run) +void AliAlgDet::acknowledgeNewRun(int run) { // update parameters needed to process this run // detector should be able to undo alignment/calibration used during the reco - UpdateL2GRecoMatrices(); + updateL2GRecoMatrices(); } //_________________________________________________________ -void AliAlgDet::UpdateL2GRecoMatrices() +void AliAlgDet::updateL2GRecoMatrices() { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs OCDB @@ -144,27 +144,27 @@ void AliAlgDet::UpdateL2GRecoMatrices() // AliCDBEntry* ent = man->Get(Form("%s/Align/Data", GetName())); // const TClonesArray* algArr = (const TClonesArray*)ent->GetObject(); // // - // int nvol = GetNVolumes(); + // int nvol = getNVolumes(); // for (int iv = 0; iv < nvol; iv++) { - // AliAlgVol* vol = GetVolume(iv); + // AliAlgVol* vol = getVolume(iv); // // call init for root level volumes, they will take care of their children - // if (!vol->GetParent()) - // vol->UpdateL2GRecoMatrices(algArr, 0); + // if (!vol->getParent()) + // vol->updateL2GRecoMatrices(algArr, 0); // } // // } //_________________________________________________________ -void AliAlgDet::ApplyAlignmentFromMPSol() +void AliAlgDet::applyAlignmentFromMPSol() { // apply alignment from millepede solution array to reference alignment level LOG(INFO) << "Applying alignment from Millepede solution"; - for (int isn = GetNSensors(); isn--;) - GetSensor(isn)->ApplyAlignmentFromMPSol(); + for (int isn = getNSensors(); isn--;) + getSensor(isn)->applyAlignmentFromMPSol(); } //_________________________________________________________ -void AliAlgDet::CacheReferenceOCDB() +void AliAlgDet::cacheReferenceOCDB() { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs OCDB @@ -176,82 +176,82 @@ void AliAlgDet::CacheReferenceOCDB() // TObjArray* arr = (TObjArray*)ent->GetObject(); // for (int i = arr->GetEntriesFast(); i--;) { // const AliAlignObjParams* par = (const AliAlignObjParams*)arr->At(i); - // AliAlgVol* vol = GetVolume(par->GetSymName()); + // AliAlgVol* vol = getVolume(par->GetSymName()); // if (!vol) { // AliErrorF("Volume %s not found", par->GetSymName()); // continue; // } // TGeoHMatrix delta; // par->GetMatrix(delta); - // vol->SetGlobalDeltaRef(delta); + // vol->setGlobalDeltaRef(delta); // } } //_________________________________________________________ -AliAlgPoint* AliAlgDet::GetPointFromPool() +AliAlgPoint* AliAlgDet::getPointFromPool() { // fetch or create new free point from the pool. // detector may override this method to create its own points derived from AliAlgPoint // - if (fPoolFreePointID >= fPoolNPoints) { // expand pool - fPointsPool.AddAtAndExpand(new AliAlgPoint(), fPoolNPoints++); + if (mPoolFreePointID >= mPoolNPoints) { // expand pool + mPointsPool.AddAtAndExpand(new AliAlgPoint(), mPoolNPoints++); } // - AliAlgPoint* pnt = (AliAlgPoint*)fPointsPool.UncheckedAt(fPoolFreePointID++); + AliAlgPoint* pnt = (AliAlgPoint*)mPointsPool.UncheckedAt(mPoolFreePointID++); pnt->Clear(); return pnt; // } //_________________________________________________________ -void AliAlgDet::ResetPool() +void AliAlgDet::resetPool() { // declare pool free - fPoolFreePointID = 0; - fNPoints = 0; + mPoolFreePointID = 0; + mNPoints = 0; } //_________________________________________________________ -void AliAlgDet::DefineVolumes() +void AliAlgDet::defineVolumes() { // dummy method LOG(ERROR) << "This method must be implemented by specific detector"; } //_________________________________________________________ -void AliAlgDet::AddVolume(AliAlgVol* vol) +void AliAlgDet::addVolume(AliAlgVol* vol) { // add volume - if (GetVolume(vol->GetSymName())) { + if (getVolume(vol->getSymName())) { LOG(FATAL) << "Volume " << vol->GetName() << " was already added to " << GetName(); } - fVolumes.AddLast(vol); - if (vol->IsSensor()) { - fSensors.AddLast(vol); - ((AliAlgSens*)vol)->SetDetector(this); - int vid = ((AliAlgSens*)vol)->GetVolID(); - if (fVolIDMin < 0 || vid < fVolIDMin) - fVolIDMin = vid; - if (fVolIDMax < 0 || vid > fVolIDMax) - fVolIDMax = vid; + mVolumes.AddLast(vol); + if (vol->isSensor()) { + mSensors.AddLast(vol); + ((AliAlgSens*)vol)->setDetector(this); + int vid = ((AliAlgSens*)vol)->getVolID(); + if (mVolIDMin < 0 || vid < mVolIDMin) + mVolIDMin = vid; + if (mVolIDMax < 0 || vid > mVolIDMax) + mVolIDMax = vid; } // } //_________________________________________________________ -void AliAlgDet::DefineMatrices() +void AliAlgDet::defineMatrices() { // define transformation matrices. Detectors may override this method // TGeoHMatrix mtmp; // - TIter next(&fVolumes); + TIter next(&mVolumes); AliAlgVol* vol(0); while ((vol = (AliAlgVol*)next())) { // modified global-local matrix - vol->PrepareMatrixL2G(); + vol->prepareMatrixL2G(); // ideal global-local matrix - vol->PrepareMatrixL2GIdeal(); + vol->prepareMatrixL2GIdeal(); // } // Now set tracking-local matrix (MUST be done after ALL L2G matrices are done!) @@ -261,116 +261,116 @@ void AliAlgDet::DefineMatrices() // see its definition in the AliAlgVol::PrepateMatrixT2L next.Reset(); while ((vol = (AliAlgVol*)next())) { - vol->PrepareMatrixT2L(); - if (vol->IsSensor()) - ((AliAlgSens*)vol)->PrepareMatrixClAlg(); // alignment matrix + vol->prepareMatrixT2L(); + if (vol->isSensor()) + ((AliAlgSens*)vol)->prepareMatrixClAlg(); // alignment matrix } // } //_________________________________________________________ -void AliAlgDet::SortSensors() +void AliAlgDet::sortSensors() { // build local tables for internal numbering - fNSensors = fSensors.GetEntriesFast(); - if (!fNSensors) { + mNSensors = mSensors.GetEntriesFast(); + if (!mNSensors) { LOG(WARNING) << "No sensors defined"; return; } - fSensors.Sort(); - fSID2VolID = new int[fNSensors]; // cash id's for fast binary search - for (int i = 0; i < fNSensors; i++) { - fSID2VolID[i] = GetSensor(i)->GetVolID(); - GetSensor(i)->SetSID(i); + mSensors.Sort(); + mSID2VolID = new int[mNSensors]; // cash id's for fast binary search + for (int i = 0; i < mNSensors; i++) { + mSID2VolID[i] = getSensor(i)->getVolID(); + getSensor(i)->setSID(i); } // } //_________________________________________________________ -int AliAlgDet::InitGeom() +int AliAlgDet::initGeom() { // define hiearchy, initialize matrices, return number of global parameters - if (GetInitGeomDone()) + if (getInitGeomDone()) return 0; // - DefineVolumes(); - SortSensors(); // VolID's must be in increasing order - DefineMatrices(); + defineVolumes(); + sortSensors(); // VolID's must be in increasing order + defineMatrices(); // // calculate number of global parameters - int nvol = GetNVolumes(); - fNDOFs = 0; + int nvol = getNVolumes(); + mNDOFs = 0; for (int iv = 0; iv < nvol; iv++) { - AliAlgVol* vol = GetVolume(iv); - fNDOFs += vol->GetNDOFs(); + AliAlgVol* vol = getVolume(iv); + mNDOFs += vol->getNDOFs(); } // - fNDOFs += fNCalibDOF; - SetInitGeomDone(); - return fNDOFs; + mNDOFs += mNCalibDOF; + setInitGeomDone(); + return mNDOFs; } //_________________________________________________________ -int AliAlgDet::AssignDOFs() +int AliAlgDet::assignDOFs() { // assign DOFs IDs, parameters // - int gloCount0(fAlgSteer->GetNDOFs()), gloCount(fAlgSteer->GetNDOFs()); - float* pars = fAlgSteer->GetGloParVal(); - float* errs = fAlgSteer->GetGloParErr(); - int* labs = fAlgSteer->GetGloParLab(); + int gloCount0(mAlgSteer->getNDOFs()), gloCount(mAlgSteer->getNDOFs()); + float* pars = mAlgSteer->getGloParVal(); + float* errs = mAlgSteer->getGloParErr(); + int* labs = mAlgSteer->getGloParLab(); // // assign calibration DOFs - fFirstParGloID = gloCount; - fParVals = pars + gloCount; - fParErrs = errs + gloCount; - fParLabs = labs + gloCount; - for (int icl = 0; icl < fNCalibDOF; icl++) { - fParLabs[icl] = (GetDetLabel() + 10000) * 100 + icl; + mFirstParGloID = gloCount; + mParVals = pars + gloCount; + mParErrs = errs + gloCount; + mParLabs = labs + gloCount; + for (int icl = 0; icl < mNCalibDOF; icl++) { + mParLabs[icl] = (getDetLabel() + 10000) * 100 + icl; gloCount++; } // - int nvol = GetNVolumes(); + int nvol = getNVolumes(); for (int iv = 0; iv < nvol; iv++) { - AliAlgVol* vol = GetVolume(iv); + AliAlgVol* vol = getVolume(iv); // call init for root level volumes, they will take care of their children - if (!vol->GetParent()) - vol->AssignDOFs(gloCount, pars, errs, labs); + if (!vol->getParent()) + vol->assignDOFs(gloCount, pars, errs, labs); } - if (fNDOFs != gloCount - gloCount0) - LOG(FATAL) << "Mismatch between declared " << fNDOFs << " and initialized " << (gloCount - gloCount0) << " DOFs for " << GetName(); - return fNDOFs; + if (mNDOFs != gloCount - gloCount0) + LOG(FATAL) << "Mismatch between declared " << mNDOFs << " and initialized " << (gloCount - gloCount0) << " DOFs for " << GetName(); + return mNDOFs; } //_________________________________________________________ -void AliAlgDet::InitDOFs() +void AliAlgDet::initDOFs() { // initialize free parameters - if (GetInitDOFsDone()) + if (getInitDOFsDone()) LOG(FATAL) << "DOFs are already initialized for " << GetName(); // // process calibration DOFs - for (int i = 0; i < fNCalibDOF; i++) - if (fParErrs[i] < -9999 && IsZeroAbs(fParVals[i])) - FixDOF(i); + for (int i = 0; i < mNCalibDOF; i++) + if (mParErrs[i] < -9999 && isZeroAbs(mParVals[i])) + fixDOF(i); // - int nvol = GetNVolumes(); + int nvol = getNVolumes(); for (int iv = 0; iv < nvol; iv++) - GetVolume(iv)->InitDOFs(); + getVolume(iv)->initDOFs(); // - CalcFree(true); + calcFree(true); // - SetInitDOFsDone(); + setInitDOFsDone(); return; } //_________________________________________________________ -int AliAlgDet::VolID2SID(int vid) const +int AliAlgDet::volID2SID(int vid) const { // find SID corresponding to VolID - int mn(0), mx(fNSensors - 1); + int mn(0), mx(mNSensors - 1); while (mx >= mn) { - int md((mx + mn) >> 1), vids(GetSensor(md)->GetVolID()); + int md((mx + mn) >> 1), vids(getSensor(md)->getVolID()); if (vid < vids) mx = md - 1; else if (vid > vids) @@ -388,37 +388,37 @@ void AliAlgDet::Print(const Option_t* opt) const TString opts = opt; opts.ToLower(); printf("\nDetector:%5s %5d volumes %5d sensors {VolID: %5d-%5d} Def.Sys.Err: %.4e %.4e | Stat:%d\n", - GetName(), GetNVolumes(), GetNSensors(), GetVolIDMin(), - GetVolIDMax(), fAddError[0], fAddError[1], fNProcPoints); + GetName(), getNVolumes(), getNSensors(), getVolIDMin(), + getVolIDMax(), mAddError[0], mAddError[1], mNProcPoints); // printf("Errors assignment: "); - if (fUseErrorParam) - printf("param %d\n", fUseErrorParam); + if (mUseErrorParam) + printf("param %d\n", mUseErrorParam); else printf("from TrackPoints\n"); // printf("Allowed in Collisions: %7s | Cosmic: %7s\n", - IsDisabled(kColl) ? " NO " : " YES ", IsDisabled(kCosm) ? " NO " : " YES "); + isDisabled(kColl) ? " NO " : " YES ", isDisabled(kCosm) ? " NO " : " YES "); // printf("Obligatory in Collisions: %7s | Cosmic: %7s\n", - IsObligatory(kColl) ? " YES " : " NO ", IsObligatory(kCosm) ? " YES " : " NO "); + isObligatory(kColl) ? " YES " : " NO ", isObligatory(kCosm) ? " YES " : " NO "); // - fmt::printf("Sel. flags in Collisions: {:05#x}%05 | Cosmic: 0x{:05#x}%05\n", fTrackFlagSel[kColl], fTrackFlagSel[kCosm]); + fmt::printf("Sel. flags in Collisions: {:05#x}%05 | Cosmic: 0x{:05#x}%05\n", mTrackFlagSel[kColl], mTrackFlagSel[kCosm]); // printf("Min.points in Collisions: %7d | Cosmic: %7d\n", - fNPointsSel[kColl], fNPointsSel[kCosm]); + mNPointsSel[kColl], mNPointsSel[kCosm]); // if (!(IsDisabledColl() && IsDisabledCosm()) && opts.Contains("long")) - for (int iv = 0; iv < GetNVolumes(); iv++) - GetVolume(iv)->Print(opt); + for (int iv = 0; iv < getNVolumes(); iv++) + getVolume(iv)->Print(opt); // - for (int i = 0; i < GetNCalibDOFs(); i++) { - printf("CalibDOF%2d: %-20s\t%e\n", i, GetCalibDOFName(i), GetCalibDOFValWithCal(i)); + for (int i = 0; i < getNCalibDOFs(); i++) { + printf("CalibDOF%2d: %-20s\t%e\n", i, getCalibDOFName(i), getCalibDOFValWithCal(i)); } } //____________________________________________ -void AliAlgDet::SetDetID(uint32_t tp) +void AliAlgDet::setDetID(uint32_t tp) { o2::detectors::DetID detID(tp); SetUniqueID(detID); @@ -426,19 +426,19 @@ void AliAlgDet::SetDetID(uint32_t tp) } //____________________________________________ -void AliAlgDet::SetAddError(double sigy, double sigz) +void AliAlgDet::setAddError(double sigy, double sigz) { // add syst error to all sensors LOG(INFO) << "Adding sys.error " << std::fixed << std::setprecision(4) << sigy << " " << sigz << " to all sensors"; - fAddError[0] = sigy; - fAddError[1] = sigz; - for (int isn = GetNSensors(); isn--;) - GetSensor(isn)->SetAddError(sigy, sigz); + mAddError[0] = sigy; + mAddError[1] = sigz; + for (int isn = getNSensors(); isn--;) + getSensor(isn)->setAddError(sigy, sigz); // } //____________________________________________ -void AliAlgDet::SetUseErrorParam(int v) +void AliAlgDet::setUseErrorParam(int v) { // set type of points error parameterization LOG(FATAL) << "UpdatePointByTrackInfo is not implemented for this detector"; @@ -446,146 +446,146 @@ void AliAlgDet::SetUseErrorParam(int v) } //____________________________________________ -void AliAlgDet::UpdatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) const +void AliAlgDet::updatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) const { // update point using specific error parameterization LOG(FATAL) << "If needed, this method has to be implemented for specific detector"; } //____________________________________________ -void AliAlgDet::SetObligatory(int tp, bool v) +void AliAlgDet::setObligatory(int tp, bool v) { // mark detector presence obligatory in the track - fObligatory[tp] = v; - fAlgSteer->SetObligatoryDetector(GetDetID(), tp, v); + mObligatory[tp] = v; + mAlgSteer->setObligatoryDetector(getDetID(), tp, v); } //______________________________________________________ -void AliAlgDet::WritePedeInfo(FILE* parOut, const Option_t* opt) const +void AliAlgDet::writePedeInfo(FILE* parOut, const Option_t* opt) const { // contribute to params and constraints template files for PEDE - fprintf(parOut, "\n!!\t\tDetector:\t%s\tNDOFs: %d\n", GetName(), GetNDOFs()); + fprintf(parOut, "\n!!\t\tDetector:\t%s\tNDOFs: %d\n", GetName(), getNDOFs()); // // parameters - int nvol = GetNVolumes(); + int nvol = getNVolumes(); for (int iv = 0; iv < nvol; iv++) { // call for root level volumes, they will take care of their children - AliAlgVol* vol = GetVolume(iv); - if (!vol->GetParent()) - vol->WritePedeInfo(parOut, opt); + AliAlgVol* vol = getVolume(iv); + if (!vol->getParent()) + vol->writePedeInfo(parOut, opt); } // } //______________________________________________________ -void AliAlgDet::WriteCalibrationResults() const +void AliAlgDet::writeCalibrationResults() const { // store calibration results - WriteAlignmentResults(); + writeAlignmentResults(); // // eventually we may write other calibrations } //______________________________________________________ -void AliAlgDet::WriteAlignmentResults() const +void AliAlgDet::writeAlignmentResults() const { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(lettrich): needs OCDB // // store updated alignment // TClonesArray* arr = new TClonesArray("AliAlignObjParams", 10); // // - // int nvol = GetNVolumes(); + // int nvol = getNVolumes(); // for (int iv = 0; iv < nvol; iv++) { - // AliAlgVol* vol = GetVolume(iv); + // AliAlgVol* vol = getVolume(iv); // // call only for top level objects, they will take care of children - // if (!vol->GetParent()) - // vol->CreateAlignmentObjects(arr); + // if (!vol->getParent()) + // vol->createAlignmentObjects(arr); // } // // // AliCDBManager* man = AliCDBManager::Instance(); // AliCDBMetaData* md = new AliCDBMetaData(); - // md->SetResponsible(fAlgSteer->GetOutCDBResponsible()); - // md->SetComment(fAlgSteer->GetOutCDBResponsible()); + // md->SetResponsible(mAlgSteer->getOutCDBResponsible()); + // md->SetComment(mAlgSteer->getOutCDBResponsible()); // // - // AliCDBId id(Form("%s/Align/Data", GetName()), fAlgSteer->GetOutCDBRunMin(), fAlgSteer->GetOutCDBRunMax()); + // AliCDBId id(Form("%s/Align/Data", GetName()), mAlgSteer->getOutCDBRunMin(), mAlgSteer->getOutCDBRunMax()); // man->Put(arr, id, md); // // // delete arr; } //______________________________________________________ -bool AliAlgDet::OwnsDOFID(int id) const +bool AliAlgDet::ownsDOFID(int id) const { // check if DOF ID belongs to this detector - for (int iv = GetNVolumes(); iv--;) { - AliAlgVol* vol = GetVolume(iv); // check only top level volumes - if (!vol->GetParent() && vol->OwnsDOFID(id)) + for (int iv = getNVolumes(); iv--;) { + AliAlgVol* vol = getVolume(iv); // check only top level volumes + if (!vol->getParent() && vol->ownsDOFID(id)) return true; } // calibration DOF? - if (id >= fFirstParGloID && id < fFirstParGloID + fNCalibDOF) + if (id >= mFirstParGloID && id < mFirstParGloID + mNCalibDOF) return true; // return false; } //______________________________________________________ -AliAlgVol* AliAlgDet::GetVolOfDOFID(int id) const +AliAlgVol* AliAlgDet::getVolOfDOFID(int id) const { // gets volume owning this DOF ID - for (int iv = GetNVolumes(); iv--;) { - AliAlgVol* vol = GetVolume(iv); - if (vol->GetParent()) + for (int iv = getNVolumes(); iv--;) { + AliAlgVol* vol = getVolume(iv); + if (vol->getParent()) continue; // check only top level volumes - if ((vol = vol->GetVolOfDOFID(id))) + if ((vol = vol->getVolOfDOFID(id))) return vol; } return 0; } //______________________________________________________ -void AliAlgDet::Terminate() +void AliAlgDet::terminate() { // called at the end of processing - // if (IsDisabled()) return; - int nvol = GetNVolumes(); - fNProcPoints = 0; - AliAlgDOFStat* st = fAlgSteer->GetDOFStat(); + // if (isDisabled()) return; + int nvol = getNVolumes(); + mNProcPoints = 0; + AliAlgDOFStat* st = mAlgSteer->GetDOFStat(); for (int iv = 0; iv < nvol; iv++) { - AliAlgVol* vol = GetVolume(iv); + AliAlgVol* vol = getVolume(iv); // call init for root level volumes, they will take care of their children - if (!vol->GetParent()) - fNProcPoints += vol->FinalizeStat(st); + if (!vol->getParent()) + mNProcPoints += vol->finalizeStat(st); } - FillDOFStat(st); // fill stat for calib dofs + fillDOFStat(st); // fill stat for calib dofs } //________________________________________ -void AliAlgDet::AddAutoConstraints() const +void AliAlgDet::addAutoConstraints() const { // adds automatic constraints - int nvol = GetNVolumes(); + int nvol = getNVolumes(); for (int iv = 0; iv < nvol; iv++) { // call for root level volumes, they will take care of their children - AliAlgVol* vol = GetVolume(iv); - if (!vol->GetParent()) - vol->AddAutoConstraints((TObjArray*)fAlgSteer->GetConstraints()); + AliAlgVol* vol = getVolume(iv); + if (!vol->getParent()) + vol->addAutoConstraints((TObjArray*)mAlgSteer->getConstraints()); } } //________________________________________ -void AliAlgDet::FixNonSensors() +void AliAlgDet::fixNonSensors() { // fix all non-sensor volumes - for (int i = GetNVolumes(); i--;) { - AliAlgVol* vol = GetVolume(i); - if (vol->IsSensor()) + for (int i = getNVolumes(); i--;) { + AliAlgVol* vol = getVolume(i); + if (vol->isSensor()) continue; - vol->SetFreeDOFPattern(0); - vol->SetChildrenConstrainPattern(0); + vol->setFreeDOFPattern(0); + vol->setChildrenConstrainPattern(0); } } //________________________________________ -int AliAlgDet::SelectVolumes(TObjArray* arr, int lev, const char* match) +int AliAlgDet::selectVolumes(TObjArray* arr, int lev, const char* match) { // select volumes matching to pattern and/or hierarchy level // @@ -593,11 +593,11 @@ int AliAlgDet::SelectVolumes(TObjArray* arr, int lev, const char* match) return 0; int nadd = 0; TString mts = match, syms; - for (int i = GetNVolumes(); i--;) { - AliAlgVol* vol = GetVolume(i); - if (lev >= 0 && vol->CountParents() != lev) + for (int i = getNVolumes(); i--;) { + AliAlgVol* vol = getVolume(i); + if (lev >= 0 && vol->countParents() != lev) continue; // wrong level - if (!mts.IsNull() && !(syms = vol->GetSymName()).Contains(mts)) + if (!mts.IsNull() && !(syms = vol->getSymName()).Contains(mts)) continue; //wrong name arr->AddLast(vol); nadd++; @@ -607,48 +607,48 @@ int AliAlgDet::SelectVolumes(TObjArray* arr, int lev, const char* match) } //________________________________________ -void AliAlgDet::SetFreeDOFPattern(uint32_t pat, int lev, const char* match) +void AliAlgDet::setFreeDOFPattern(uint32_t pat, int lev, const char* match) { // set free DOFs to volumes matching either to hierarchy level or // whose name contains match // TString mts = match, syms; - for (int i = GetNVolumes(); i--;) { - AliAlgVol* vol = GetVolume(i); - if (lev >= 0 && vol->CountParents() != lev) + for (int i = getNVolumes(); i--;) { + AliAlgVol* vol = getVolume(i); + if (lev >= 0 && vol->countParents() != lev) continue; // wrong level - if (!mts.IsNull() && !(syms = vol->GetSymName()).Contains(mts)) + if (!mts.IsNull() && !(syms = vol->getSymName()).Contains(mts)) continue; //wrong name - vol->SetFreeDOFPattern(pat); + vol->setFreeDOFPattern(pat); } // } //________________________________________ -void AliAlgDet::SetDOFCondition(int dof, float condErr, int lev, const char* match) +void AliAlgDet::setDOFCondition(int dof, float condErr, int lev, const char* match) { // set condition for DOF of volumes matching either to hierarchy level or // whose name contains match // TString mts = match, syms; - for (int i = GetNVolumes(); i--;) { - AliAlgVol* vol = GetVolume(i); - if (lev >= 0 && vol->CountParents() != lev) + for (int i = getNVolumes(); i--;) { + AliAlgVol* vol = getVolume(i); + if (lev >= 0 && vol->countParents() != lev) continue; // wrong level - if (!mts.IsNull() && !(syms = vol->GetSymName()).Contains(mts)) + if (!mts.IsNull() && !(syms = vol->getSymName()).Contains(mts)) continue; //wrong name - if (dof >= vol->GetNDOFs()) + if (dof >= vol->getNDOFs()) continue; - vol->SetParErr(dof, condErr); - if (condErr >= 0 && !vol->IsFreeDOF(dof)) - vol->SetFreeDOF(dof); - //if (condErr<0 && vol->IsFreeDOF(dof)) vol->FixDOF(dof); + vol->setParErr(dof, condErr); + if (condErr >= 0 && !vol->isFreeDOF(dof)) + vol->setFreeDOF(dof); + //if (condErr<0 && vol->isFreeDOF(dof)) vol->fixDOF(dof); } // } //________________________________________ -void AliAlgDet::ConstrainOrphans(const double* sigma, const char* match) +void AliAlgDet::constrainOrphans(const double* sigma, const char* match) { // additional constraint on volumes w/o parents (optionally containing "match" in symname) // sigma<0 : dof is not contrained @@ -659,94 +659,94 @@ void AliAlgDet::ConstrainOrphans(const double* sigma, const char* match) AliAlgConstraint* constr = new AliAlgConstraint(); for (int i = 0; i < AliAlgVol::kNDOFGeom; i++) { if (sigma[i] >= 0) - constr->ConstrainDOF(i); + constr->constrainDOF(i); else - constr->UnConstrainDOF(i); - constr->SetSigma(i, sigma[i]); + constr->unConstrainDOF(i); + constr->setSigma(i, sigma[i]); } - for (int i = GetNVolumes(); i--;) { - AliAlgVol* vol = GetVolume(i); - if (vol->GetParent()) + for (int i = getNVolumes(); i--;) { + AliAlgVol* vol = getVolume(i); + if (vol->getParent()) continue; // wrong level - if (!mts.IsNull() && !(syms = vol->GetSymName()).Contains(mts)) + if (!mts.IsNull() && !(syms = vol->getSymName()).Contains(mts)) continue; //wrong name - constr->AddChild(vol); + constr->addChild(vol); } // - if (!constr->GetNChildren()) { + if (!constr->getNChildren()) { LOG(INFO) << "No volume passed filter " << match; delete constr; } else { - ((TObjArray*)fAlgSteer->GetConstraints())->Add(constr); + ((TObjArray*)mAlgSteer->getConstraints())->Add(constr); } } //________________________________________ -void AliAlgDet::SetFreeDOF(int dof) +void AliAlgDet::setFreeDOF(int dof) { // set detector free dof if (dof >= kNMaxKalibDOF) { LOG(FATAL) << "Detector CalibDOFs limited to " << kNMaxKalibDOF << ", requested " << dof; } - fCalibDOF |= 0x1 << dof; - CalcFree(); + mCalibDOF |= 0x1 << dof; + calcFree(); } //________________________________________ -void AliAlgDet::FixDOF(int dof) +void AliAlgDet::fixDOF(int dof) { // fix detector dof if (dof >= kNMaxKalibDOF) { LOG(FATAL) << "Detector CalibDOFs limited to " << kNMaxKalibDOF << ", requested " << dof; } - fCalibDOF &= ~(0x1 << dof); - CalcFree(); + mCalibDOF &= ~(0x1 << dof); + calcFree(); } //__________________________________________________________________ -bool AliAlgDet::IsCondDOF(int i) const +bool AliAlgDet::isCondDOF(int i) const { // is DOF free and conditioned? - return (!IsZeroAbs(GetParVal(i)) || !IsZeroAbs(GetParErr(i))); + return (!isZeroAbs(getParVal(i)) || !isZeroAbs(getParErr(i))); } //__________________________________________________________________ -void AliAlgDet::CalcFree(bool condFix) +void AliAlgDet::calcFree(bool condFix) { // calculate free calib dofs. If condFix==true, condition parameter a la pede, i.e. error < 0 - fNCalibDOFFree = 0; - for (int i = 0; i < fNCalibDOF; i++) { - if (!IsFreeDOF(i)) { + mNCalibDOFFree = 0; + for (int i = 0; i < mNCalibDOF; i++) { + if (!isFreeDOF(i)) { if (condFix) - SetParErr(i, -999); + setParErr(i, -999); continue; } - fNCalibDOFFree++; + mNCalibDOFFree++; } // } //______________________________________________________ -void AliAlgDet::FillDOFStat(AliAlgDOFStat* st) const +void AliAlgDet::fillDOFStat(AliAlgDOFStat* st) const { // fill statistics info hist if (!st) return; - int ndf = GetNCalibDOFs(); - int dof0 = GetFirstParGloID(); - int stat = GetNProcessedPoints(); + int ndf = getNCalibDOFs(); + int dof0 = getFirstParGloID(); + int stat = getNProcessedPoints(); for (int idf = 0; idf < ndf; idf++) { int dof = idf + dof0; - st->AddStat(dof, stat); + st->addStat(dof, stat); } // } //______________________________________________________ -void AliAlgDet::WriteSensorPositions(const char* outFName) +void AliAlgDet::writeSensorPositions(const char* outFName) { // create tree with sensors ideal, ref and reco positions - int ns = GetNSensors(); + int ns = getNSensors(); double loc[3] = {0}; // ------- local container type for dumping sensor positions ------ typedef struct { @@ -764,11 +764,11 @@ void AliAlgDet::WriteSensorPositions(const char* outFName) tr->Branch("pRc", &spos.pRc, "pRc[3]/D"); // for (int isn = 0; isn < ns; isn++) { - AliAlgSens* sens = GetSensor(isn); - spos.volID = sens->GetVolID(); - sens->GetMatrixL2GIdeal().LocalToMaster(loc, spos.pId); - sens->GetMatrixL2G().LocalToMaster(loc, spos.pRf); - sens->GetMatrixL2GReco().LocalToMaster(loc, spos.pRc); + AliAlgSens* sens = getSensor(isn); + spos.volID = sens->getVolID(); + sens->getMatrixL2GIdeal().LocalToMaster(loc, spos.pId); + sens->getMatrixL2G().LocalToMaster(loc, spos.pRf); + sens->getMatrixL2GReco().LocalToMaster(loc, spos.pRc); tr->Fill(); } tr->Write(); diff --git a/Detectors/Align/src/AliAlgDetHMPID.cxx b/Detectors/Align/src/AliAlgDetHMPID.cxx index 64a1a3e192b18..e4c9a44cd2e08 100644 --- a/Detectors/Align/src/AliAlgDetHMPID.cxx +++ b/Detectors/Align/src/AliAlgDetHMPID.cxx @@ -34,8 +34,8 @@ namespace align AliAlgDetHMPID::AliAlgDetHMPID(const char* title) { // default c-tor - SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kHMPID), title); - SetDetID(AliAlgSteer::kHMPID); + SetNameTitle(AliAlgSteer::getDetNameByDetID(AliAlgSteer::kHMPID), title); + setDetID(AliAlgSteer::kHMPID); } //____________________________________________ @@ -45,11 +45,11 @@ AliAlgDetHMPID::~AliAlgDetHMPID() } //____________________________________________ -void AliAlgDetHMPID::DefineVolumes() +void AliAlgDetHMPID::defineVolumes() { // define HMPID volumes // - int labDet = GetDetLabel(); + int labDet = getDetLabel(); AliGeomManager::ELayerID idHMPID = AliGeomManager::kHMPID; for (int iCh = AliHMPIDParam::kMinCh; iCh <= AliHMPIDParam::kMaxCh; iCh++) { const char* symname = Form("/HMPID/Chamber%i", iCh); @@ -60,7 +60,7 @@ void AliAlgDetHMPID::DefineVolumes() uint16_t vid = AliGeomManager::LayerToVolUID(idHMPID, iCh); int iid = labDet + (1 + iCh) * 10000; AliAlgSensHMPID* sens = new AliAlgSensHMPID(symname, vid, iid); - AddVolume(sens); + addVolume(sens); } //iCh loop // } @@ -71,7 +71,7 @@ bool AliAlgDetHMPID::AcceptTrack(const AliESDtrack* trc, int trtype) const // test if detector had seed this track if (!CheckFlags(trc, trtype)) return false; - if (trc->GetNcls(1) < fNPointsSel[trtype]) + if (trc->GetNcls(1) < mNPointsSel[trtype]) return false; return true; } diff --git a/Detectors/Align/src/AliAlgDetITS.cxx b/Detectors/Align/src/AliAlgDetITS.cxx index 99cd64bfad53c..81aac175fe845 100644 --- a/Detectors/Align/src/AliAlgDetITS.cxx +++ b/Detectors/Align/src/AliAlgDetITS.cxx @@ -41,9 +41,9 @@ const char* AliAlgDetITS::fgkHitsSel[AliAlgDetITS::kNSPDSelTypes] = AliAlgDetITS::AliAlgDetITS(const char* title) { // default c-tor - SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kITS), title); - SetDetID(AliAlgSteer::kITS); - SetUseErrorParam(); + SetNameTitle(AliAlgSteer::getDetNameByDetID(AliAlgSteer::kITS), title); + setDetID(AliAlgSteer::kITS); + setUseErrorParam(); SetITSSelPatternColl(); SetITSSelPatternCosm(); } @@ -55,7 +55,7 @@ AliAlgDetITS::~AliAlgDetITS() } //____________________________________________ -void AliAlgDetITS::DefineVolumes() +void AliAlgDetITS::defineVolumes() { // define ITS volumes // @@ -63,15 +63,15 @@ void AliAlgDetITS::DefineVolumes() AliAlgVol *volITS = 0, *hstave = 0, *ladd = 0; AliAlgSensITS* sens = 0; // - int labDet = GetDetLabel(); - AddVolume(volITS = new AliAlgVol("ITS", labDet)); + int labDet = getDetLabel(); + addVolume(volITS = new AliAlgVol("ITS", labDet)); // // SPD AliAlgVol* sect[kNSPDSect] = {0}; for (int isc = 0; isc < kNSPDSect; isc++) { // sectors int iid = labDet + (10 + isc) * 10000; - AddVolume(sect[isc] = new AliAlgVol(Form("ITS/SPD0/Sector%d", isc), iid)); - sect[isc]->SetParent(volITS); + addVolume(sect[isc] = new AliAlgVol(Form("ITS/SPD0/Sector%d", isc), iid)); + sect[isc]->setParent(volITS); } for (int ilr = 0; ilr <= 1; ilr++) { // SPD layers // @@ -82,18 +82,18 @@ void AliAlgDetITS::DefineVolumes() for (int ihst = 0; ihst < 2; ihst++) { // halfstave int iid = labDet + (1 + ilr) * 10000 + (1 + staveCnt) * 100; staveCnt++; - AddVolume(hstave = new AliAlgVol(Form("ITS/SPD%d/Sector%d/Stave%d/HalfStave%d", + addVolume(hstave = new AliAlgVol(Form("ITS/SPD%d/Sector%d/Stave%d/HalfStave%d", ilr, isc, ist, ihst), iid)); - hstave->SetParent(sect[isc]); - hstave->SetInternalID(iid); + hstave->setParent(sect[isc]); + hstave->setInternalID(iid); for (int isn = 0; isn < 2; isn++) { // "ladder" (sensor) int iids = iid + (1 + isn); - AddVolume(sens = + addVolume(sens = new AliAlgSensITS(Form("ITS/SPD%d/Sector%d/Stave%d/HalfStave%d/Ladder%d", ilr, isc, ist, ihst, isn + ihst * 2), AliGeomManager::LayerToVolUID(ilr + 1, cntVolID++), iids)); - sens->SetParent(hstave); + sens->setParent(hstave); } } } // staves of SPDi @@ -106,13 +106,13 @@ void AliAlgDetITS::DefineVolumes() for (int ist = 0; ist < AliITSgeomTGeo::GetNLadders(ilr + 1); ist++) { // ladder int iid = labDet + (1 + ilr) * 10000 + (1 + staveCnt) * 100; staveCnt++; - AddVolume(ladd = new AliAlgVol(Form("ITS/SDD%d/Ladder%d", ilr, ist), iid)); - ladd->SetParent(volITS); + addVolume(ladd = new AliAlgVol(Form("ITS/SDD%d/Ladder%d", ilr, ist), iid)); + ladd->setParent(volITS); for (int isn = 0; isn < AliITSgeomTGeo::GetNDetectors(ilr + 1); isn++) { // sensor int iids = iid + (1 + isn); - AddVolume(sens = new AliAlgSensITS(Form("ITS/SDD%d/Ladder%d/Sensor%d", ilr, ist, isn), + addVolume(sens = new AliAlgSensITS(Form("ITS/SDD%d/Ladder%d/Sensor%d", ilr, ist, isn), AliGeomManager::LayerToVolUID(ilr + 1, cntVolID++), iids)); - sens->SetParent(ladd); + sens->setParent(ladd); } } // ladder } // layer @@ -123,13 +123,13 @@ void AliAlgDetITS::DefineVolumes() for (int ist = 0; ist < AliITSgeomTGeo::GetNLadders(ilr + 1); ist++) { // ladder int iid = labDet + (1 + ilr) * 10000 + (1 + staveCnt) * 100; staveCnt++; - AddVolume(ladd = new AliAlgVol(Form("ITS/SSD%d/Ladder%d", ilr, ist), iid)); - ladd->SetParent(volITS); + addVolume(ladd = new AliAlgVol(Form("ITS/SSD%d/Ladder%d", ilr, ist), iid)); + ladd->setParent(volITS); for (int isn = 0; isn < AliITSgeomTGeo::GetNDetectors(ilr + 1); isn++) { // sensor int iids = iid + (1 + isn); - AddVolume(sens = new AliAlgSensITS(Form("ITS/SSD%d/Ladder%d/Sensor%d", ilr, ist, isn), + addVolume(sens = new AliAlgSensITS(Form("ITS/SSD%d/Ladder%d/Sensor%d", ilr, ist, isn), AliGeomManager::LayerToVolUID(ilr + 1, cntVolID++), iids)); - sens->SetParent(ladd); + sens->setParent(ladd); } } // ladder } // layer @@ -151,7 +151,7 @@ bool AliAlgDetITS::AcceptTrack(const AliESDtrack* trc, int trtype) const // test if detector had seed this track if (!CheckFlags(trc, trtype)) return false; - if (trc->GetNcls(0) < fNPointsSel[trtype]) + if (trc->GetNcls(0) < mNPointsSel[trtype]) return false; if (!CheckHitPattern(trc, GetITSSelPattern(trtype))) return false; @@ -163,12 +163,12 @@ bool AliAlgDetITS::AcceptTrack(const AliESDtrack* trc, int trtype) const void AliAlgDetITS::SetAddErrorLr(int ilr, double sigY, double sigZ) { // set syst. errors for specific layer - for (int isn = GetNSensors(); isn--;) { - AliAlgSensITS* sens = (AliAlgSensITS*)GetSensor(isn); - int vid = sens->GetVolID(); + for (int isn = getNSensors(); isn--;) { + AliAlgSensITS* sens = (AliAlgSensITS*)getSensor(isn); + int vid = sens->getVolID(); int lrs = AliGeomManager::VolUIDToLayer(vid); if ((lrs - AliGeomManager::kSPD1) == ilr) - sens->SetAddError(sigY, sigZ); + sens->setAddError(sigY, sigZ); } } @@ -176,20 +176,20 @@ void AliAlgDetITS::SetAddErrorLr(int ilr, double sigY, double sigZ) void AliAlgDetITS::SetSkipLr(int ilr) { // exclude sensor of the layer from alignment - for (int isn = GetNSensors(); isn--;) { - AliAlgSensITS* sens = (AliAlgSensITS*)GetSensor(isn); - int vid = sens->GetVolID(); + for (int isn = getNSensors(); isn--;) { + AliAlgSensITS* sens = (AliAlgSensITS*)getSensor(isn); + int vid = sens->getVolID(); int lrs = AliGeomManager::VolUIDToLayer(vid); if ((lrs - AliGeomManager::kSPD1) == ilr) - sens->SetSkip(); + sens->setSkip(); } } //_________________________________________________ -void AliAlgDetITS::SetUseErrorParam(int v) +void AliAlgDetITS::setUseErrorParam(int v) { // set type of points error parameterization - fUseErrorParam = v; + mUseErrorParam = v; } //_________________________________________________ @@ -224,17 +224,17 @@ void AliAlgDetITS::UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTra { // update point using specific error parameterization // the track must be in the detector tracking frame - const AliAlgSens* sens = pnt->GetSensor(); - int vid = sens->GetVolID(); + const AliAlgSens* sens = pnt->getSensor(); + int vid = sens->getVolID(); int lr = AliGeomManager::VolUIDToLayer(vid) - 1; double angPol = ATan(t->GetTgl()); double angAz = ASin(t->GetSnp()); double errY, errZ; GetErrorParamAngle(lr, angPol, angAz, errY, errZ); - const double* sysE = sens->GetAddError(); // additional syst error + const double* sysE = sens->getAddError(); // additional syst error // - pnt->SetYZErrTracking(errY * errY + sysE[0] * sysE[0], 0, errZ * errZ + sysE[1] * sysE[1]); - pnt->Init(); + pnt->setYZErrTracking(errY * errY + sysE[0] * sysE[0], 0, errZ * errZ + sysE[1] * sysE[1]); + pnt->init(); // } //-------------------------------------------------------------------------- diff --git a/Detectors/Align/src/AliAlgDetTOF.cxx b/Detectors/Align/src/AliAlgDetTOF.cxx index 669ba57d0655c..62afb404194f0 100644 --- a/Detectors/Align/src/AliAlgDetTOF.cxx +++ b/Detectors/Align/src/AliAlgDetTOF.cxx @@ -33,8 +33,8 @@ namespace align AliAlgDetTOF::AliAlgDetTOF(const char* title) { // default c-tor - SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kTOF), title); - SetDetID(AliAlgSteer::kTOF); + SetNameTitle(AliAlgSteer::getDetNameByDetID(AliAlgSteer::kTOF), title); + setDetID(AliAlgSteer::kTOF); } //____________________________________________ @@ -44,12 +44,12 @@ AliAlgDetTOF::~AliAlgDetTOF() } //____________________________________________ -void AliAlgDetTOF::DefineVolumes() +void AliAlgDetTOF::defineVolumes() { // define TOF volumes // const int kNSect = 18, kNStrips = AliTOFGeometry::NStripA() + 2 * AliTOFGeometry::NStripB() + 2 * AliTOFGeometry::NStripC(); - int labDet = GetDetLabel(); + int labDet = getDetLabel(); AliAlgSensTOF* strip = 0; // // AddVolume( volTOF = new AliAlgVol("TOF") ); // no main volume, why? @@ -57,7 +57,7 @@ void AliAlgDetTOF::DefineVolumes() // for (int isc = 0; isc < kNSect; isc++) { int iid = labDet + (1 + isc) * 100; - AddVolume(sect[isc] = new AliAlgVol(Form("TOF/sm%02d", isc), iid)); + addVolume(sect[isc] = new AliAlgVol(Form("TOF/sm%02d", isc), iid)); } // int cnt = 0; @@ -68,8 +68,8 @@ void AliAlgDetTOF::DefineVolumes() const char* symname = Form("TOF/sm%02d/strip%02d", isc, istr); if (!gGeoManager->GetAlignableEntry(symname)) continue; - AddVolume(strip = new AliAlgSensTOF(symname, vid, iid, isc)); - strip->SetParent(sect[isc]); + addVolume(strip = new AliAlgSensTOF(symname, vid, iid, isc)); + strip->setParent(sect[isc]); } // strip } // layer // diff --git a/Detectors/Align/src/AliAlgDetTPC.cxx b/Detectors/Align/src/AliAlgDetTPC.cxx index 9acc3ec91169a..f705b239f0ddf 100644 --- a/Detectors/Align/src/AliAlgDetTPC.cxx +++ b/Detectors/Align/src/AliAlgDetTPC.cxx @@ -33,8 +33,8 @@ namespace align AliAlgDetTPC::AliAlgDetTPC(const char* title) { // default c-tor - SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kTPC), title); - SetDetID(AliAlgSteer::kTPC); + SetNameTitle(AliAlgSteer::getDetNameByDetID(AliAlgSteer::kTPC), title); + setDetID(AliAlgSteer::kTPC); } //____________________________________________ @@ -44,7 +44,7 @@ AliAlgDetTPC::~AliAlgDetTPC() } //____________________________________________ -void AliAlgDetTPC::DefineVolumes() +void AliAlgDetTPC::defineVolumes() { // define TPC volumes // @@ -53,9 +53,9 @@ void AliAlgDetTPC::DefineVolumes() const char* kROC[kIOROC] = {"Inner", "Outer"}; // AliAlgSensTPC *chamb=0; // - int labDet = GetDetLabel(); + int labDet = getDetLabel(); AliAlgVol* volTPC = new AliAlgVol("ALIC_1/TPC_M_1", labDet); - AddVolume(volTPC); + addVolume(volTPC); // for (int roc = 0; roc < kIOROC; roc++) { // inner/outer @@ -70,8 +70,8 @@ void AliAlgDetTPC::DefineVolumes() uint16_t vid = AliGeomManager::LayerToVolUID(AliGeomManager::kTPC1 + roc, iid); iid = labDet + (1 + side) * 10000 + (1 + isc) * 100 + (1 + roc); AliAlgSensTPC* sens = new AliAlgSensTPC(symname, vid, iid, isc); - sens->SetParent(volTPC); - AddVolume(sens); + sens->setParent(volTPC); + addVolume(sens); } // sector ID } // A/C } // inner/outer @@ -84,7 +84,7 @@ bool AliAlgDetTPC::AcceptTrack(const AliESDtrack* trc, int trtype) const // test if detector had seed this track if (!CheckFlags(trc, trtype)) return false; - if (trc->GetNcls(1) < fNPointsSel[trtype]) + if (trc->GetNcls(1) < mNPointsSel[trtype]) return false; return true; } diff --git a/Detectors/Align/src/AliAlgDetTRD.cxx b/Detectors/Align/src/AliAlgDetTRD.cxx index e1a43ac0dde78..a6542e936c4fd 100644 --- a/Detectors/Align/src/AliAlgDetTRD.cxx +++ b/Detectors/Align/src/AliAlgDetTRD.cxx @@ -39,14 +39,14 @@ AliAlgDetTRD::AliAlgDetTRD(const char* title) : AliAlgDet(), fNonRCCorrDzDtgl(0), fCorrDVT(0) { // default c-tor - SetNameTitle(AliAlgSteer::GetDetNameByDetID(AliAlgSteer::kTRD), title); - SetDetID(AliAlgSteer::kTRD); + SetNameTitle(AliAlgSteer::getDetNameByDetID(AliAlgSteer::kTRD), title); + setDetID(AliAlgSteer::kTRD); fExtraErrRC[0] = fExtraErrRC[1] = 0; // // ad hoc correction SetNonRCCorrDzDtgl(); SetExtraErrRC(); - fNCalibDOF = kNCalibParams; + mNCalibDOF = kNCalibParams; } //____________________________________________ @@ -56,14 +56,14 @@ AliAlgDetTRD::~AliAlgDetTRD() } //____________________________________________ -void AliAlgDetTRD::DefineVolumes() +void AliAlgDetTRD::defineVolumes() { // define TRD volumes // const int kNSect = 18, kNStacks = 5, kNLayers = 6; AliAlgSensTRD* chamb = 0; // - int labDet = GetDetLabel(); + int labDet = getDetLabel(); // AddVolume( volTRD = new AliAlgVol("TRD") ); // no main volume, why? AliAlgVol* sect[kNSect] = {0}; // @@ -77,17 +77,17 @@ void AliAlgDetTRD::DefineVolumes() if (!gGeoManager->GetAlignableEntry(symname)) continue; uint16_t vid = AliGeomManager::LayerToVolUID(AliGeomManager::kTRD1 + ilr, ich); - AddVolume(chamb = new AliAlgSensTRD(symname, vid, iid /*lid*/, isector)); + addVolume(chamb = new AliAlgSensTRD(symname, vid, iid /*lid*/, isector)); iid = labDet + (1 + isector) * 100; if (!sect[isector]) sect[isector] = new AliAlgVol(Form("TRD/sm%02d", isector), iid); - chamb->SetParent(sect[isector]); + chamb->setParent(sect[isector]); } // chamber } // layer // for (int isc = 0; isc < kNSect; isc++) { if (sect[isc]) - AddVolume(sect[isc]); + addVolume(sect[isc]); } // } @@ -98,7 +98,7 @@ bool AliAlgDetTRD::AcceptTrack(const AliESDtrack* trc, int trtype) const // test if detector had seed this track if (!CheckFlags(trc, trtype)) return false; - if (trc->GetTRDntracklets() < fNPointsSel[trtype]) + if (trc->GetTRDntracklets() < mNPointsSel[trtype]) return false; return true; } @@ -112,17 +112,17 @@ void AliAlgDetTRD::Print(const Option_t* opt) const printf("Extra error for RC tracklets: Y:%e Z:%e\n", fExtraErrRC[0], fExtraErrRC[1]); } -const char* AliAlgDetTRD::GetCalibDOFName(int i) const +const char* AliAlgDetTRD::getCalibDOFName(int i) const { // return calibration DOF name return i < kNCalibParams ? fgkCalibDOFName[i] : 0; } //______________________________________________________ -void AliAlgDetTRD::WritePedeInfo(FILE* parOut, const Option_t* opt) const +void AliAlgDetTRD::writePedeInfo(FILE* parOut, const Option_t* opt) const { // contribute to params and constraints template files for PEDE - AliAlgDet::WritePedeInfo(parOut, opt); + AliAlgDet::writePedeInfo(parOut, opt); // // write calibration parameters enum { kOff, @@ -132,18 +132,18 @@ void AliAlgDetTRD::WritePedeInfo(FILE* parOut, const Option_t* opt) const const char* kKeyParam = "parameter"; // fprintf(parOut, "%s%s %s\t %d calibraction params for %s\n", comment[kOff], kKeyParam, comment[kOnOn], - GetNCalibDOFs(), GetName()); + getNCalibDOFs(), GetName()); // - for (int ip = 0; ip < GetNCalibDOFs(); ip++) { - int cmt = IsCondDOF(ip) ? kOff : kOn; - fprintf(parOut, "%s %9d %+e %+e\t%s %s p%d\n", comment[cmt], GetParLab(ip), - GetParVal(ip), GetParErr(ip), comment[kOnOn], IsFreeDOF(ip) ? " " : "FX", ip); + for (int ip = 0; ip < getNCalibDOFs(); ip++) { + int cmt = isCondDOF(ip) ? kOff : kOn; + fprintf(parOut, "%s %9d %+e %+e\t%s %s p%d\n", comment[cmt], getParLab(ip), + getParVal(ip), getParErr(ip), comment[kOnOn], isFreeDOF(ip) ? " " : "FX", ip); } // } //_______________________________________________________ -double AliAlgDetTRD::GetCalibDOFVal(int id) const +double AliAlgDetTRD::getCalibDOFVal(int id) const { // return preset value of calibration dof double val = 0; @@ -161,10 +161,10 @@ double AliAlgDetTRD::GetCalibDOFVal(int id) const } //_______________________________________________________ -double AliAlgDetTRD::GetCalibDOFValWithCal(int id) const +double AliAlgDetTRD::getCalibDOFValWithCal(int id) const { // return preset value of calibration dof + mp correction - return GetCalibDOFVal(id) + GetParVal(id); + return getCalibDOFVal(id) + getParVal(id); } } // namespace align diff --git a/Detectors/Align/src/AliAlgMPRecord.cxx b/Detectors/Align/src/AliAlgMPRecord.cxx index e710b6d64033d..a824c9aa666b0 100644 --- a/Detectors/Align/src/AliAlgMPRecord.cxx +++ b/Detectors/Align/src/AliAlgMPRecord.cxx @@ -30,12 +30,12 @@ namespace align //_________________________________________________________ AliAlgMPRecord::AliAlgMPRecord() - : fTrackID(0), fTimeStamp(0), fNResid(0), fNVarLoc(0), fNVarGlo(0), fNDLocTot(0), fNDGloTot(0), fNMeas(0), fChi2Ini(0), fQ2Pt(0), fTgl(0), fNDLoc(0), fNDGlo(0), fVolID(0), fResid(0), fResErr(0), fIDLoc(0), fIDGlo(0), fDLoc(0), fDGlo(0) + : mTrackID(0), mTimeStamp(0), mNResid(0), mNVarLoc(0), mNVarGlo(0), mNDLocTot(0), mNDGloTot(0), mNMeas(0), mChi2Ini(0), mQ2Pt(0), mTgl(0), mNDLoc(0), mNDGlo(0), mVolID(0), mResid(0), mResErr(0), mIDLoc(0), mIDGlo(0), mDLoc(0), mDGlo(0) // , - fNResidBook(0), - fNDLocTotBook(0), - fNDGloTotBook(0) + mNResidBook(0), + mNDLocTotBook(0), + mNDGloTotBook(0) { // def c-tor } @@ -44,164 +44,164 @@ AliAlgMPRecord::AliAlgMPRecord() AliAlgMPRecord::~AliAlgMPRecord() { // d-tor - delete[] fNDLoc; - delete[] fNDGlo; - delete[] fVolID; - delete[] fResid; - delete[] fResErr; - delete[] fIDLoc; - delete[] fIDGlo; - delete[] fDLoc; - delete[] fDGlo; + delete[] mNDLoc; + delete[] mNDGlo; + delete[] mVolID; + delete[] mResid; + delete[] mResErr; + delete[] mIDLoc; + delete[] mIDGlo; + delete[] mDLoc; + delete[] mDGlo; } //_________________________________________________________ -void AliAlgMPRecord::DummyRecord(float res, float err, float dGlo, int labGlo) +void AliAlgMPRecord::dummyRecord(float res, float err, float dGlo, int labGlo) { // create dummy residuals record - if (!fNDGlo) - Resize(1, 1, 1); - fChi2Ini = 0; - fNMeas = 1; - fNResid = 1; - fNVarLoc = 0; - fNVarGlo = 1; - fIDGlo[0] = labGlo; - fDGlo[0] = dGlo; - fNDGlo[0] = 1; - fVolID[0] = -1; - fResid[0] = res; - fResErr[0] = err; + if (!mNDGlo) + resize(1, 1, 1); + mChi2Ini = 0; + mNMeas = 1; + mNResid = 1; + mNVarLoc = 0; + mNVarGlo = 1; + mIDGlo[0] = labGlo; + mDGlo[0] = dGlo; + mNDGlo[0] = 1; + mVolID[0] = -1; + mResid[0] = res; + mResErr[0] = err; // - fIDLoc[0] = 0; - fNDLoc[0] = 0; - fDLoc[0] = 0; - fNDGloTot = 1; - fNDLocTot = 0; + mIDLoc[0] = 0; + mNDLoc[0] = 0; + mDLoc[0] = 0; + mNDGloTot = 1; + mNDLocTot = 0; // } //_________________________________________________________ -bool AliAlgMPRecord::FillTrack(const AliAlgTrack* trc, const int* id2Lab) +bool AliAlgMPRecord::fillTrack(const AliAlgTrack* trc, const int* id2Lab) { // fill track info, optionally substitutind glopar par ID by label // - if (!trc->GetDerivDone()) { + if (!trc->getDerivDone()) { LOG(ERROR) << "Track derivatives are not yet evaluated"; return false; } - fNVarLoc = trc->GetNLocPar(); // number of local degrees of freedom in the track - fNResid = 0; - fNDLocTot = 0; - fNDGloTot = 0; - fChi2Ini = trc->GetChi2Ini(); - fQ2Pt = trc->getQ2Pt(); - fTgl = trc->getTgl(); - fNMeas = 0; - SetCosmic(trc->IsCosmic()); + mNVarLoc = trc->getNLocPar(); // number of local degrees of freedom in the track + mNResid = 0; + mNDLocTot = 0; + mNDGloTot = 0; + mChi2Ini = trc->getChi2Ini(); + mQ2Pt = trc->getQ2Pt(); + mTgl = trc->getTgl(); + mNMeas = 0; + setCosmic(trc->isCosmic()); // 1) check sizes for buffers, expand if needed - int np = trc->GetNPoints(); + int np = trc->getNPoints(); int nres = 0; int nlocd = 0; int nglod = 0; for (int ip = np; ip--;) { - AliAlgPoint* pnt = trc->GetPoint(ip); - int ngl = pnt->GetNGloDOFs(); // number of DOF's this point depends on - if (pnt->ContainsMeasurement()) { + AliAlgPoint* pnt = trc->getPoint(ip); + int ngl = pnt->getNGloDOFs(); // number of DOF's this point depends on + if (pnt->containsMeasurement()) { nres += 2; // every point has 2 residuals - nlocd += fNVarLoc + fNVarLoc; // each residual has max fNVarLoc local derivatives + nlocd += mNVarLoc + mNVarLoc; // each residual has max mNVarLoc local derivatives nglod += ngl + ngl; // number of global derivatives - fNMeas++; + mNMeas++; } - if (pnt->ContainsMaterial()) { - int nmatpar = pnt->GetNMatPar(); + if (pnt->containsMaterial()) { + int nmatpar = pnt->getNMatPar(); nres += nmatpar; // each point with materials has nmatpar fake residuals nlocd += nmatpar; // and nmatpar non-0 local derivatives (orthogonal) } } // - Resize(nres, nlocd, nglod); - int nParETP = trc->GetNLocExtPar(); // numnber of local parameters for reference track param + resize(nres, nlocd, nglod); + int nParETP = trc->getNLocExtPar(); // numnber of local parameters for reference track param // - const int* gloParID = trc->GetGloParID(); // IDs of global DOFs this track depends on + const int* gloParID = trc->getGloParID(); // IDs of global DOFs this track depends on for (int ip = 0; ip < np; ip++) { - AliAlgPoint* pnt = trc->GetPoint(ip); - if (pnt->ContainsMeasurement()) { - int gloOffs = pnt->GetDGloOffs(); // 1st entry of global derivatives for this point - int nDGlo = pnt->GetNGloDOFs(); // number of global derivatives (number of DOFs it depends on) - if (!pnt->IsStatOK()) - pnt->IncrementStat(); + AliAlgPoint* pnt = trc->getPoint(ip); + if (pnt->containsMeasurement()) { + int gloOffs = pnt->getDGloOffs(); // 1st entry of global derivatives for this point + int nDGlo = pnt->getNGloDOFs(); // number of global derivatives (number of DOFs it depends on) + if (!pnt->isStatOK()) + pnt->incrementStat(); // for (int idim = 0; idim < 2; idim++) { // 2 dimensional orthogonal measurement - fNDGlo[fNResid] = 0; - fVolID[fNResid] = pnt->GetSensor()->GetVolID() + 1; + mNDGlo[mNResid] = 0; + mVolID[mNResid] = pnt->getSensor()->getVolID() + 1; // // measured residual/error - fResid[fNResid] = trc->GetResidual(idim, ip); - fResErr[fNResid] = Sqrt(pnt->GetErrDiag(idim)); + mResid[mNResid] = trc->getResidual(idim, ip); + mResErr[mNResid] = Sqrt(pnt->getErrDiag(idim)); // // derivatives over local params - const double* deriv = trc->GetDResDLoc(idim, ip); // array of Dresidual/Dparams_loc + const double* deriv = trc->getDResDLoc(idim, ip); // array of Dresidual/Dparams_loc int nnon0 = 0; for (int j = 0; j < nParETP; j++) { // derivatives over reference track parameters - if (IsZeroAbs(deriv[j])) + if (isZeroAbs(deriv[j])) continue; nnon0++; - fDLoc[fNDLocTot] = deriv[j]; // store non-0 derivative - fIDLoc[fNDLocTot] = j; // and variable id - fNDLocTot++; + mDLoc[mNDLocTot] = deriv[j]; // store non-0 derivative + mIDLoc[mNDLocTot] = j; // and variable id + mNDLocTot++; } - int lp0 = pnt->GetMinLocVarID(); // point may depend on material variables starting from this one - int lp1 = pnt->GetMaxLocVarID(); // and up to this one (exclusive) + int lp0 = pnt->getMinLocVarID(); // point may depend on material variables starting from this one + int lp1 = pnt->getMaxLocVarID(); // and up to this one (exclusive) for (int j = lp0; j < lp1; j++) { // derivatives over material variables - if (IsZeroAbs(deriv[j])) + if (isZeroAbs(deriv[j])) continue; nnon0++; - fDLoc[fNDLocTot] = deriv[j]; // store non-0 derivative - fIDLoc[fNDLocTot] = j; // and variable id - fNDLocTot++; + mDLoc[mNDLocTot] = deriv[j]; // store non-0 derivative + mIDLoc[mNDLocTot] = j; // and variable id + mNDLocTot++; } // - fNDLoc[fNResid] = nnon0; // local derivatives done, store their number for this residual + mNDLoc[mNResid] = nnon0; // local derivatives done, store their number for this residual // // derivatives over global params nnon0 = 0; - deriv = trc->GetDResDGlo(idim, gloOffs); + deriv = trc->getDResDGlo(idim, gloOffs); const int* gloIDP = gloParID + gloOffs; for (int j = 0; j < nDGlo; j++) { - if (IsZeroAbs(deriv[j])) + if (isZeroAbs(deriv[j])) continue; nnon0++; - fDGlo[fNDGloTot] = deriv[j]; // value of derivative - fIDGlo[fNDGloTot] = id2Lab ? id2Lab[gloIDP[j]] : gloIDP[j] + 1; // global DOF ID - fNDGloTot++; + mDGlo[mNDGloTot] = deriv[j]; // value of derivative + mIDGlo[mNDGloTot] = id2Lab ? id2Lab[gloIDP[j]] : gloIDP[j] + 1; // global DOF ID + mNDGloTot++; } - fNDGlo[fNResid] = nnon0; + mNDGlo[mNResid] = nnon0; // - fNResid++; + mNResid++; } } - if (pnt->ContainsMaterial()) { // material point can add 4 or 5 otrhogonal pseudo-measurements - int nmatpar = pnt->GetNMatPar(); // residuals (correction expectation value) - // const float* expMatCorr = pnt->GetMatCorrExp(); // expected corrections (diagonalized) - const float* expMatCov = pnt->GetMatCorrCov(); // their diagonalized error matrix - int offs = pnt->GetMaxLocVarID() - nmatpar; // start of material variables + if (pnt->containsMaterial()) { // material point can add 4 or 5 otrhogonal pseudo-measurements + int nmatpar = pnt->getNMatPar(); // residuals (correction expectation value) + // const float* expMatCorr = pnt->getMatCorrExp(); // expected corrections (diagonalized) + const float* expMatCov = pnt->getMatCorrCov(); // their diagonalized error matrix + int offs = pnt->getMaxLocVarID() - nmatpar; // start of material variables // here all derivatives are 1 = dx/dx for (int j = 0; j < nmatpar; j++) { - fNDGlo[fNResid] = 0; // mat corrections don't depend on global params - fVolID[fNResid] = 0; // not associated to global parameter - fResid[fNResid] = 0; // expectation for MS effects is 0 - fResErr[fNResid] = Sqrt(expMatCov[j]); - fNDLoc[fNResid] = 1; // only 1 non-0 derivative - fDLoc[fNDLocTot] = 1.0; - fIDLoc[fNDLocTot] = offs + j; // variable id - fNDLocTot++; - fNResid++; + mNDGlo[mNResid] = 0; // mat corrections don't depend on global params + mVolID[mNResid] = 0; // not associated to global parameter + mResid[mNResid] = 0; // expectation for MS effects is 0 + mResErr[mNResid] = Sqrt(expMatCov[j]); + mNDLoc[mNResid] = 1; // only 1 non-0 derivative + mDLoc[mNDLocTot] = 1.0; + mIDLoc[mNDLocTot] = offs + j; // variable id + mNDLocTot++; + mNResid++; } } } // - if (!fNDGloTot) { + if (!mNDGloTot) { LOG(INFO) << "Track does not depend on free global parameters, discard"; return false; } @@ -209,44 +209,44 @@ bool AliAlgMPRecord::FillTrack(const AliAlgTrack* trc, const int* id2Lab) } //________________________________________________ -void AliAlgMPRecord::Resize(int nresid, int nloc, int nglo) +void AliAlgMPRecord::resize(int nresid, int nloc, int nglo) { // resize container - if (nresid > fNResidBook) { - delete[] fNDLoc; - delete[] fNDGlo; - delete[] fVolID; - delete[] fResid; - delete[] fResErr; - fNDLoc = new int16_t[nresid]; - fNDGlo = new int[nresid]; - fVolID = new int[nresid]; - fResid = new float[nresid]; - fResErr = new float[nresid]; - fNResidBook = nresid; - memset(fNDLoc, 0, nresid * sizeof(int16_t)); - memset(fNDGlo, 0, nresid * sizeof(int)); - memset(fVolID, 0, nresid * sizeof(int)); - memset(fResid, 0, nresid * sizeof(float)); - memset(fResErr, 0, nresid * sizeof(float)); + if (nresid > mNResidBook) { + delete[] mNDLoc; + delete[] mNDGlo; + delete[] mVolID; + delete[] mResid; + delete[] mResErr; + mNDLoc = new int16_t[nresid]; + mNDGlo = new int[nresid]; + mVolID = new int[nresid]; + mResid = new float[nresid]; + mResErr = new float[nresid]; + mNResidBook = nresid; + memset(mNDLoc, 0, nresid * sizeof(int16_t)); + memset(mNDGlo, 0, nresid * sizeof(int)); + memset(mVolID, 0, nresid * sizeof(int)); + memset(mResid, 0, nresid * sizeof(float)); + memset(mResErr, 0, nresid * sizeof(float)); } - if (nloc > fNDLocTotBook) { - delete[] fIDLoc; - delete[] fDLoc; - fIDLoc = new int16_t[nloc]; - fDLoc = new float[nloc]; - fNDLocTotBook = nloc; - memset(fIDLoc, 0, nloc * sizeof(int16_t)); - memset(fDLoc, 0, nloc * sizeof(float)); + if (nloc > mNDLocTotBook) { + delete[] mIDLoc; + delete[] mDLoc; + mIDLoc = new int16_t[nloc]; + mDLoc = new float[nloc]; + mNDLocTotBook = nloc; + memset(mIDLoc, 0, nloc * sizeof(int16_t)); + memset(mDLoc, 0, nloc * sizeof(float)); } - if (nglo > fNDGloTotBook) { - delete[] fIDGlo; - delete[] fDGlo; - fIDGlo = new int[nglo]; - fDGlo = new float[nglo]; - fNDGloTotBook = nglo; - memset(fIDGlo, 0, nglo * sizeof(int)); - memset(fDGlo, 0, nglo * sizeof(float)); + if (nglo > mNDGloTotBook) { + delete[] mIDGlo; + delete[] mDGlo; + mIDGlo = new int[nglo]; + mDGlo = new float[nglo]; + mNDGloTotBook = nglo; + memset(mIDGlo, 0, nglo * sizeof(int)); + memset(mDGlo, 0, nglo * sizeof(float)); } // } @@ -257,11 +257,11 @@ void AliAlgMPRecord::Clear(const Option_t*) // reset record TObject::Clear(); ResetBit(0xffffffff); - fNResid = 0; - fNVarLoc = 0; - fNVarGlo = 0; - fNDLocTot = 0; - fNDGloTot = 0; + mNResid = 0; + mNVarLoc = 0; + mNVarGlo = 0; + mNDLocTot = 0; + mNDGloTot = 0; } //____________________________________________ @@ -270,23 +270,23 @@ void AliAlgMPRecord::Print(const Option_t*) const // print info // printf("Track %d Event TimeStamp:%d Run:%d\n", - fTrackID, fTimeStamp, GetRun()); - printf("Nmeas:%3d Q/pt:%+.2e Tgl:%+.2e Chi2Ini:%.1f\n", fNMeas, fQ2Pt, fTgl, fChi2Ini); + mTrackID, mTimeStamp, getRun()); + printf("Nmeas:%3d Q/pt:%+.2e Tgl:%+.2e Chi2Ini:%.1f\n", mNMeas, mQ2Pt, mTgl, mChi2Ini); printf("NRes: %3d NLoc: %3d NGlo:%3d | Stored: Loc:%3d Glo:%5d\n", - fNResid, fNVarLoc, fNVarGlo, fNDLocTot, fNDGloTot); + mNResid, mNVarLoc, mNVarGlo, mNDLocTot, mNDGloTot); // int curLoc = 0, curGlo = 0; const int kNColLoc = 5; - for (int ir = 0; ir < fNResid; ir++) { - int ndloc = fNDLoc[ir], ndglo = fNDGlo[ir]; + for (int ir = 0; ir < mNResid; ir++) { + int ndloc = mNDLoc[ir], ndglo = mNDGlo[ir]; printf("Res:%3d %+e (%+e) | NDLoc:%3d NDGlo:%4d [VID:%5d]\n", - ir, fResid[ir], fResErr[ir], ndloc, ndglo, GetVolID(ir)); + ir, mResid[ir], mResErr[ir], ndloc, ndglo, getVolID(ir)); // printf("Local Derivatives:\n"); bool eolOK = true; for (int id = 0; id < ndloc; id++) { int jd = id + curLoc; - printf("[%3d] %+.2e ", fIDLoc[jd], fDLoc[jd]); + printf("[%3d] %+.2e ", mIDLoc[jd], mDLoc[jd]); if (((id + 1) % kNColLoc) == 0) { printf("\n"); eolOK = true; @@ -305,13 +305,13 @@ void AliAlgMPRecord::Print(const Option_t*) const for (int id = 0; id < ndglo; id++) { int jd = id + curGlo; // eolOK==false; - if (prvID > fIDGlo[jd] % 100) { + if (prvID > mIDGlo[jd] % 100) { printf("\n"); /* eolOK = true;*/ } - printf("[%5d] %+.2e ", fIDGlo[jd], fDGlo[jd]); + printf("[%5d] %+.2e ", mIDGlo[jd], mDGlo[jd]); // if (((id+1)%kNColGlo)==0) // else eolOK = false; - prvID = fIDGlo[jd] % 100; + prvID = mIDGlo[jd] % 100; } // if (!eolOK) printf("\n"); printf("\n"); diff --git a/Detectors/Align/src/AliAlgPoint.cxx b/Detectors/Align/src/AliAlgPoint.cxx index a7409a3590a7f..4dffba1748c84 100644 --- a/Detectors/Align/src/AliAlgPoint.cxx +++ b/Detectors/Align/src/AliAlgPoint.cxx @@ -28,70 +28,70 @@ namespace align //_____________________________________ AliAlgPoint::AliAlgPoint() - : fMinLocVarID(0), fMaxLocVarID(0), fDetID(-1), fSID(-1), fAlphaSens(0), fXSens(0), fCosDiagErr(0), fSinDiagErr(0), fX2X0(0), fXTimesRho(0), fNGloDOFs(0), fDGloOffs(0), fSensor(0) + : mMinLocVarID(0), mMaxLocVarID(0), mDetID(-1), mSID(-1), mAlphaSens(0), mXSens(0), mCosDiagErr(0), mSinDiagErr(0), mX2X0(0), mXTimesRho(0), mNGloDOFs(0), mDGloOffs(0), mSensor(0) { // def c-tor for (int i = 3; i--;) { - fXYZTracking[i] = 0; - fErrYZTracking[i] = 0; + mXYZTracking[i] = 0; + mErrYZTracking[i] = 0; } - memset(fMatCorrExp, 0, 5 * sizeof(float)); - memset(fMatCorrCov, 0, 5 * sizeof(float)); - memset(fMatDiag, 0, 5 * 5 * sizeof(float)); + memset(mMatCorrExp, 0, 5 * sizeof(float)); + memset(mMatCorrCov, 0, 5 * sizeof(float)); + memset(mMatDiag, 0, 5 * 5 * sizeof(float)); // - memset(fTrParamWSA, 0, 5 * sizeof(double)); - memset(fTrParamWSB, 0, 5 * sizeof(double)); + memset(mTrParamWSA, 0, 5 * sizeof(double)); + memset(mTrParamWSB, 0, 5 * sizeof(double)); // } //_____________________________________ -void AliAlgPoint::Init() +void AliAlgPoint::init() { // compute aux info const double kCorrToler = 1e-6; const double kDiagToler = 1e-14; // // compute parameters of tranformation to diagonal error matrix - if (!IsZeroPos(fErrYZTracking[0] + fErrYZTracking[2])) { + if (!isZeroPos(mErrYZTracking[0] + mErrYZTracking[2])) { // // is there a correlation? - if (SmallerAbs(fErrYZTracking[1] * fErrYZTracking[1] / (fErrYZTracking[0] * fErrYZTracking[2]), kCorrToler)) { - fCosDiagErr = 1.; - fSinDiagErr = 0.; - fErrDiag[0] = fErrYZTracking[0]; - fErrDiag[1] = fErrYZTracking[2]; + if (smallerAbs(mErrYZTracking[1] * mErrYZTracking[1] / (mErrYZTracking[0] * mErrYZTracking[2]), kCorrToler)) { + mCosDiagErr = 1.; + mSinDiagErr = 0.; + mErrDiag[0] = mErrYZTracking[0]; + mErrDiag[1] = mErrYZTracking[2]; } else { - double dfd = 0.5 * (fErrYZTracking[2] - fErrYZTracking[0]); + double dfd = 0.5 * (mErrYZTracking[2] - mErrYZTracking[0]); double phi = 0; // special treatment if errors are equal if (Abs(dfd) < kDiagToler) - phi = fErrYZTracking[1] > 0 ? (Pi() * 0.25) : (Pi() * 0.75); + phi = mErrYZTracking[1] > 0 ? (Pi() * 0.25) : (Pi() * 0.75); else - phi = 0.5 * ATan2(fErrYZTracking[1], dfd); + phi = 0.5 * ATan2(mErrYZTracking[1], dfd); // - fCosDiagErr = Cos(phi); - fSinDiagErr = Sin(phi); + mCosDiagErr = Cos(phi); + mSinDiagErr = Sin(phi); // - // double det = dfd*dfd + fErrYZTracking[1]*fErrYZTracking[1]; + // double det = dfd*dfd + mErrYZTracking[1]*mErrYZTracking[1]; // det = det>0 ? Sqrt(det) : 0; - // double smd = 0.5*(fErrYZTracking[0] + fErrYZTracking[2]); - // fErrDiag[0] = smd + det; - // fErrDiag[1] = smd - det; - double xterm = 2 * fCosDiagErr * fSinDiagErr * fErrYZTracking[1]; - double cc = fCosDiagErr * fCosDiagErr; - double ss = fSinDiagErr * fSinDiagErr; - fErrDiag[0] = fErrYZTracking[0] * cc + fErrYZTracking[2] * ss - xterm; - fErrDiag[1] = fErrYZTracking[0] * ss + fErrYZTracking[2] * cc + xterm; + // double smd = 0.5*(mErrYZTracking[0] + mErrYZTracking[2]); + // mErrDiag[0] = smd + det; + // mErrDiag[1] = smd - det; + double xterm = 2 * mCosDiagErr * mSinDiagErr * mErrYZTracking[1]; + double cc = mCosDiagErr * mCosDiagErr; + double ss = mSinDiagErr * mSinDiagErr; + mErrDiag[0] = mErrYZTracking[0] * cc + mErrYZTracking[2] * ss - xterm; + mErrDiag[1] = mErrYZTracking[0] * ss + mErrYZTracking[2] * cc + xterm; } } // } //_____________________________________ -void AliAlgPoint::UpdatePointByTrackInfo(const trackParam_t* t) +void AliAlgPoint::updatePointByTrackInfo(const trackParam_t* t) { // // recalculate point errors using info about the track in the sensor tracking frame - fSensor->UpdatePointByTrackInfo(this, t); + mSensor->updatePointByTrackInfo(this, t); } //_____________________________________ @@ -100,41 +100,41 @@ void AliAlgPoint::Print(Option_t* opt) const // print TString opts = opt; opts.ToLower(); - printf("%cDet%d SID:%4d Alp:%+.3f X:%+9.4f Meas:%s Mat: ", IsInvDir() ? '*' : ' ', - GetDetID(), GetSID(), GetAlphaSens(), GetXSens(), ContainsMeasurement() ? "ON" : "OFF"); - if (!ContainsMaterial()) + printf("%cDet%d SID:%4d Alp:%+.3f X:%+9.4f Meas:%s Mat: ", isInvDir() ? '*' : ' ', + getDetID(), getSID(), getAlphaSens(), getXSens(), containsMeasurement() ? "ON" : "OFF"); + if (!containsMaterial()) printf("OFF\n"); else - printf("x2X0: %.4f x*rho: %.4f | pars:[%3d:%3d)\n", GetX2X0(), GetXTimesRho(), GetMinLocVarID(), GetMaxLocVarID()); + printf("x2X0: %.4f x*rho: %.4f | pars:[%3d:%3d)\n", getX2X0(), getXTimesRho(), getMinLocVarID(), getMaxLocVarID()); // - if (opts.Contains("meas") && ContainsMeasurement()) { + if (opts.Contains("meas") && containsMeasurement()) { printf(" MeasPnt: Xtr: %+9.4f Ytr: %+8.4f Ztr: %+9.4f | ErrYZ: %+e %+e %+e | %d DOFglo\n", - GetXTracking(), GetYTracking(), GetZTracking(), - fErrYZTracking[0], fErrYZTracking[1], fErrYZTracking[2], GetNGloDOFs()); - printf(" DiagErr: %+e %+e\n", fErrDiag[0], fErrDiag[1]); + getXTracking(), getYTracking(), getZTracking(), + mErrYZTracking[0], mErrYZTracking[1], mErrYZTracking[2], getNGloDOFs()); + printf(" DiagErr: %+e %+e\n", mErrDiag[0], mErrDiag[1]); } // - if (opts.Contains("mat") && ContainsMaterial()) { + if (opts.Contains("mat") && containsMaterial()) { printf(" MatCorr Exp(ELOSS): %+.4e %+.4e %+.4e %+.4e %+.4e\n", - fMatCorrExp[0], fMatCorrExp[1], fMatCorrExp[2], fMatCorrExp[3], fMatCorrExp[4]); + mMatCorrExp[0], mMatCorrExp[1], mMatCorrExp[2], mMatCorrExp[3], mMatCorrExp[4]); printf(" MatCorr Cov (diag): %+.4e %+.4e %+.4e %+.4e %+.4e\n", - fMatCorrCov[0], fMatCorrCov[1], fMatCorrCov[2], fMatCorrCov[3], fMatCorrCov[4]); + mMatCorrCov[0], mMatCorrCov[1], mMatCorrCov[2], mMatCorrCov[3], mMatCorrCov[4]); // if (opts.Contains("umat")) { float covUndiag[15]; memset(covUndiag, 0, 15 * sizeof(float)); - int np = GetNMatPar(); + int np = getNMatPar(); for (int i = 0; i < np; i++) { for (int j = 0; j <= i; j++) { double val = 0; for (int k = np; k--;) - val += fMatDiag[i][k] * fMatDiag[j][k] * fMatCorrCov[k]; + val += mMatDiag[i][k] * mMatDiag[j][k] * mMatCorrCov[k]; int ij = (i * (i + 1) / 2) + j; covUndiag[ij] = val; } } if (np < kNMatDOFs) - covUndiag[14] = fMatCorrCov[4]; // eloss was fixed + covUndiag[14] = mMatCorrCov[4]; // eloss was fixed printf(" MatCorr Cov in normal form:\n"); printf(" %+e\n", covUndiag[0]); printf(" %+e %+e\n", covUndiag[1], covUndiag[2]); @@ -144,12 +144,12 @@ void AliAlgPoint::Print(Option_t* opt) const } } // - if (opts.Contains("diag") && ContainsMaterial()) { + if (opts.Contains("diag") && containsMaterial()) { printf(" Matrix for Mat.corr.errors diagonalization:\n"); - int npar = GetNMatPar(); + int npar = getNMatPar(); for (int i = 0; i < npar; i++) { for (int j = 0; j < npar; j++) - printf("%+.4e ", fMatDiag[i][j]); + printf("%+.4e ", mMatDiag[i][j]); printf("\n"); } } @@ -157,25 +157,25 @@ void AliAlgPoint::Print(Option_t* opt) const if (opts.Contains("wsa")) { // printf track state at this point stored during residuals calculation printf(" Local Track (A): "); for (int i = 0; i < 5; i++) - printf("%+.3e ", fTrParamWSA[i]); + printf("%+.3e ", mTrParamWSA[i]); printf("\n"); } if (opts.Contains("wsb")) { // printf track state at this point stored during residuals calculation printf(" Local Track (B): "); for (int i = 0; i < 5; i++) - printf("%+.3e ", fTrParamWSB[i]); + printf("%+.3e ", mTrParamWSB[i]); printf("\n"); } // } //_____________________________________ -void AliAlgPoint::DumpCoordinates() const +void AliAlgPoint::dumpCoordinates() const { // dump various corrdinates for inspection // global xyz dim3_t xyz; - GetXYZGlo(xyz.data()); + getXYZGlo(xyz.data()); auto print3d = [](dim3_t& xyz) { for (auto i : xyz) { @@ -186,8 +186,8 @@ void AliAlgPoint::DumpCoordinates() const print3d(xyz); trackParam_t wsb; trackParam_t wsa; - GetTrWSB(wsb); - GetTrWSA(wsa); + getTrWSB(wsb); + getTrWSA(wsa); wsb.getXYZGlo(xyz); print3d(xyz); // track before mat corr @@ -195,15 +195,15 @@ void AliAlgPoint::DumpCoordinates() const wsa.getXYZGlo(xyz); print3d(xyz); // track after mat corr - printf("%+.4f ", fAlphaSens); - printf("%+.4e ", GetXPoint()); - printf("%+.4e ", GetYTracking()); - printf("%+.4e ", GetZTracking()); + printf("%+.4f ", mAlphaSens); + printf("%+.4e ", getXPoint()); + printf("%+.4e ", getYTracking()); + printf("%+.4e ", getZTracking()); // printf("%+.4e %.4e ", wsb.getY(), wsb.getZ()); printf("%+.4e %.4e ", wsa.getY(), wsa.getZ()); // - printf("%4e %4e", Sqrt(fErrYZTracking[0]), Sqrt(fErrYZTracking[2])); + printf("%4e %4e", Sqrt(mErrYZTracking[0]), Sqrt(mErrYZTracking[2])); printf("\n"); } @@ -212,12 +212,12 @@ void AliAlgPoint::Clear(Option_t*) { // reset the point ResetBit(0xfffffff); - fMaxLocVarID = -1; - fDetID = -1; - fSID = -1; - fNGloDOFs = 0; - fDGloOffs = 0; - fSensor = 0; + mMaxLocVarID = -1; + mDetID = -1; + mSID = -1; + mNGloDOFs = 0; + mDGloOffs = 0; + mSensor = 0; } //__________________________________________________________________ @@ -225,18 +225,18 @@ int AliAlgPoint::Compare(const TObject* b) const { // sort points in direction opposite to track propagation, i.e. // 1) for tracks from collision: range in decreasing tracking X - // 2) for cosmic tracks: upper leg (pnt->IsInvDir()==true) ranged in increasing X + // 2) for cosmic tracks: upper leg (pnt->isInvDir()==true) ranged in increasing X // lower leg - in decreasing X AliAlgPoint* pnt = (AliAlgPoint*)b; - double x = GetXPoint(); - double xp = pnt->GetXPoint(); - if (!IsInvDir()) { // track propagates from low to large X via this point - if (!pnt->IsInvDir()) { // via this one also + double x = getXPoint(); + double xp = pnt->getXPoint(); + if (!isInvDir()) { // track propagates from low to large X via this point + if (!pnt->isInvDir()) { // via this one also return x > xp ? -1 : 1; } else return -1; // range points of lower leg 1st } else { // this point is from upper cosmic leg: track propagates from large to low X - if (pnt->IsInvDir()) { // this one also + if (pnt->isInvDir()) { // this one also return x > xp ? 1 : -1; } else return 1; // other point is from lower leg @@ -245,119 +245,119 @@ int AliAlgPoint::Compare(const TObject* b) const } //__________________________________________________________________ -void AliAlgPoint::GetXYZGlo(double r[3]) const +void AliAlgPoint::getXYZGlo(double r[3]) const { // position in lab frame - double cs = TMath::Cos(fAlphaSens); - double sn = TMath::Sin(fAlphaSens); - double x = GetXPoint(); - r[0] = x * cs - GetYTracking() * sn; - r[1] = x * sn + GetYTracking() * cs; - r[2] = GetZTracking(); + double cs = TMath::Cos(mAlphaSens); + double sn = TMath::Sin(mAlphaSens); + double x = getXPoint(); + r[0] = x * cs - getYTracking() * sn; + r[1] = x * sn + getYTracking() * cs; + r[2] = getZTracking(); // } //__________________________________________________________________ -double AliAlgPoint::GetPhiGlo() const +double AliAlgPoint::getPhiGlo() const { // phi angle (-pi:pi) in global frame double xyz[3]; - GetXYZGlo(xyz); + getXYZGlo(xyz); return ATan2(xyz[1], xyz[0]); } //__________________________________________________________________ -int AliAlgPoint::GetAliceSector() const +int AliAlgPoint::getAliceSector() const { // get global sector ID corresponding to this point phi - return Phi2Sector(GetPhiGlo()); + return phi2Sector(getPhiGlo()); } //__________________________________________________________________ -void AliAlgPoint::SetMatCovDiagonalizationMatrix(const TMatrixD& d) +void AliAlgPoint::setMatCovDiagonalizationMatrix(const TMatrixD& d) { // save non-sym matrix for material corrections cov.matrix diagonalization // (actually, the eigenvectors are stored) int sz = d.GetNrows(); for (int i = sz; i--;) for (int j = sz; j--;) - fMatDiag[i][j] = d(i, j); + mMatDiag[i][j] = d(i, j); } //__________________________________________________________________ -void AliAlgPoint::SetMatCovDiag(const TVectorD& v) +void AliAlgPoint::setMatCovDiag(const TVectorD& v) { // save material correction diagonalized matrix // (actually, the eigenvalues are stored w/o reordering them to correspond to the // AliExternalTrackParam variables) for (int i = v.GetNrows(); i--;) - fMatCorrCov[i] = v(i); + mMatCorrCov[i] = v(i); } //__________________________________________________________________ -void AliAlgPoint::UnDiagMatCorr(const double* diag, double* nodiag) const +void AliAlgPoint::unDiagMatCorr(const double* diag, double* nodiag) const { // transform material corrections from the frame diagonalizing the errors to point frame - // nodiag = fMatDiag * diag - int np = GetNMatPar(); + // nodiag = mMatDiag * diag + int np = getNMatPar(); for (int ip = np; ip--;) { double v = 0; for (int jp = np; jp--;) - v += fMatDiag[ip][jp] * diag[jp]; + v += mMatDiag[ip][jp] * diag[jp]; nodiag[ip] = v; } // } //__________________________________________________________________ -void AliAlgPoint::UnDiagMatCorr(const float* diag, float* nodiag) const +void AliAlgPoint::unDiagMatCorr(const float* diag, float* nodiag) const { // transform material corrections from the frame diagonalizing the errors to point frame - // nodiag = fMatDiag * diag - int np = GetNMatPar(); + // nodiag = mMatDiag * diag + int np = getNMatPar(); for (int ip = np; ip--;) { double v = 0; for (int jp = np; jp--;) - v += double(fMatDiag[ip][jp]) * diag[jp]; + v += double(mMatDiag[ip][jp]) * diag[jp]; nodiag[ip] = v; } // } //__________________________________________________________________ -void AliAlgPoint::DiagMatCorr(const double* nodiag, double* diag) const +void AliAlgPoint::diagMatCorr(const double* nodiag, double* diag) const { // transform material corrections from the AliExternalTrackParam frame to // the frame diagonalizing the errors - // diag = fMatDiag^T * nodiag - int np = GetNMatPar(); + // diag = mMatDiag^T * nodiag + int np = getNMatPar(); for (int ip = np; ip--;) { double v = 0; for (int jp = np; jp--;) - v += fMatDiag[jp][ip] * nodiag[jp]; + v += mMatDiag[jp][ip] * nodiag[jp]; diag[ip] = v; } // } //__________________________________________________________________ -void AliAlgPoint::DiagMatCorr(const float* nodiag, float* diag) const +void AliAlgPoint::diagMatCorr(const float* nodiag, float* diag) const { // transform material corrections from the AliExternalTrackParam frame to // the frame diagonalizing the errors - // diag = fMatDiag^T * nodiag - int np = GetNMatPar(); + // diag = mMatDiag^T * nodiag + int np = getNMatPar(); for (int ip = np; ip--;) { double v = 0; for (int jp = np; jp--;) - v += double(fMatDiag[jp][ip]) * nodiag[jp]; + v += double(mMatDiag[jp][ip]) * nodiag[jp]; diag[ip] = v; } // } //__________________________________________________________________ -void AliAlgPoint::GetTrWSA(trackParam_t& etp) const +void AliAlgPoint::getTrWSA(trackParam_t& etp) const { // assign WSA (after material corrections) parameters to supplied track const trackParam_t::covMat_t covDum{ @@ -367,13 +367,13 @@ void AliAlgPoint::GetTrWSA(trackParam_t& etp) const 0, 0, 0, 1.e-4, 0, 0, 0, 0, 1e-4}; params_t tmp; - std::copy(std::begin(fTrParamWSA), std::end(fTrParamWSA), std::begin(tmp)); + std::copy(std::begin(mTrParamWSA), std::end(mTrParamWSA), std::begin(tmp)); - etp.set(GetXPoint(), GetAlphaSens(), tmp, covDum); + etp.set(getXPoint(), getAlphaSens(), tmp, covDum); } //__________________________________________________________________ -void AliAlgPoint::GetTrWSB(trackParam_t& etp) const +void AliAlgPoint::getTrWSB(trackParam_t& etp) const { // assign WSB parameters (before material corrections) to supplied track const trackParam_t::covMat_t covDum{ @@ -383,9 +383,9 @@ void AliAlgPoint::GetTrWSB(trackParam_t& etp) const 0, 0, 0, 1.e-4, 0, 0, 0, 0, 1e-4}; params_t tmp; - std::copy(std::begin(fTrParamWSB), std::end(fTrParamWSB), std::begin(tmp)); + std::copy(std::begin(mTrParamWSB), std::end(mTrParamWSB), std::begin(tmp)); - etp.set(GetXPoint(), GetAlphaSens(), tmp, covDum); + etp.set(getXPoint(), getAlphaSens(), tmp, covDum); } } // namespace align diff --git a/Detectors/Align/src/AliAlgRes.cxx b/Detectors/Align/src/AliAlgRes.cxx index 35caa63e368e3..81807b445c2c0 100644 --- a/Detectors/Align/src/AliAlgRes.cxx +++ b/Detectors/Align/src/AliAlgRes.cxx @@ -33,7 +33,7 @@ namespace align //____________________________________ AliAlgRes::AliAlgRes() - : fRun(0), fBz(0), fTimeStamp(0), fTrackID(0), fNPoints(0), fNBook(0), fChi2(0), fChi2Ini(0), fChi2K(0), fQ2Pt(0), fX(0), fY(0), fZ(0), fSnp(0), fTgl(0), fAlpha(0), fDY(0), fDZ(0), fDYK(0), fDZK(0), fSigY2(0), fSigYZ(0), fSigZ2(0), fSigY2K(0), fSigYZK(0), fSigZ2K(0), fVolID(0), fLabel(0) + : mRun(0), mBz(0), mTimeStamp(0), mTrackID(0), mNPoints(0), mNBook(0), mChi2(0), mChi2Ini(0), mChi2K(0), mQ2Pt(0), mX(0), mY(0), mZ(0), mSnp(0), mTgl(0), mAlpha(0), mDY(0), mDZ(0), mDYK(0), mDZK(0), mSigY2(0), mSigYZ(0), mSigZ2(0), mSigY2K(0), mSigYZK(0), mSigZ2K(0), mVolID(0), mLabel(0) { // def c-tor } @@ -42,88 +42,88 @@ AliAlgRes::AliAlgRes() AliAlgRes::~AliAlgRes() { // d-tor - delete[] fX; - delete[] fY; - delete[] fZ; - delete[] fSnp; - delete[] fTgl; - delete[] fAlpha; - delete[] fDY; - delete[] fDZ; - delete[] fSigY2; - delete[] fSigYZ; - delete[] fSigZ2; - delete[] fDYK; - delete[] fDZK; - delete[] fSigY2K; - delete[] fSigYZK; - delete[] fSigZ2K; - delete[] fVolID; - delete[] fLabel; + delete[] mX; + delete[] mY; + delete[] mZ; + delete[] mSnp; + delete[] mTgl; + delete[] mAlpha; + delete[] mDY; + delete[] mDZ; + delete[] mSigY2; + delete[] mSigYZ; + delete[] mSigZ2; + delete[] mDYK; + delete[] mDZK; + delete[] mSigY2K; + delete[] mSigYZK; + delete[] mSigZ2K; + delete[] mVolID; + delete[] mLabel; } //________________________________________________ -void AliAlgRes::Resize(int np) +void AliAlgRes::resize(int np) { // resize container - if (np > fNBook) { - delete[] fX; - delete[] fY; - delete[] fZ; - delete[] fSnp; - delete[] fTgl; - delete[] fAlpha; - delete[] fDY; - delete[] fDZ; - delete[] fSigY2; - delete[] fSigYZ; - delete[] fSigZ2; - delete[] fDYK; - delete[] fDZK; - delete[] fSigY2K; - delete[] fSigYZK; - delete[] fSigZ2K; - delete[] fVolID; - delete[] fLabel; + if (np > mNBook) { + delete[] mX; + delete[] mY; + delete[] mZ; + delete[] mSnp; + delete[] mTgl; + delete[] mAlpha; + delete[] mDY; + delete[] mDZ; + delete[] mSigY2; + delete[] mSigYZ; + delete[] mSigZ2; + delete[] mDYK; + delete[] mDZK; + delete[] mSigY2K; + delete[] mSigYZK; + delete[] mSigZ2K; + delete[] mVolID; + delete[] mLabel; // - fNBook = 100 + np; - fX = new float[fNBook]; - fY = new float[fNBook]; - fZ = new float[fNBook]; - fSnp = new float[fNBook]; - fTgl = new float[fNBook]; - fAlpha = new float[fNBook]; - fDY = new float[fNBook]; - fDZ = new float[fNBook]; - fSigY2 = new float[fNBook]; - fSigYZ = new float[fNBook]; - fSigZ2 = new float[fNBook]; - fDYK = new float[fNBook]; - fDZK = new float[fNBook]; - fSigY2K = new float[fNBook]; - fSigYZK = new float[fNBook]; - fSigZ2K = new float[fNBook]; - fVolID = new int[fNBook]; - fLabel = new int[fNBook]; + mNBook = 100 + np; + mX = new float[mNBook]; + mY = new float[mNBook]; + mZ = new float[mNBook]; + mSnp = new float[mNBook]; + mTgl = new float[mNBook]; + mAlpha = new float[mNBook]; + mDY = new float[mNBook]; + mDZ = new float[mNBook]; + mSigY2 = new float[mNBook]; + mSigYZ = new float[mNBook]; + mSigZ2 = new float[mNBook]; + mDYK = new float[mNBook]; + mDZK = new float[mNBook]; + mSigY2K = new float[mNBook]; + mSigYZK = new float[mNBook]; + mSigZ2K = new float[mNBook]; + mVolID = new int[mNBook]; + mLabel = new int[mNBook]; // - memset(fX, 0, fNBook * sizeof(float)); - memset(fY, 0, fNBook * sizeof(float)); - memset(fZ, 0, fNBook * sizeof(float)); - memset(fSnp, 0, fNBook * sizeof(float)); - memset(fTgl, 0, fNBook * sizeof(float)); - memset(fAlpha, 0, fNBook * sizeof(float)); - memset(fDY, 0, fNBook * sizeof(float)); - memset(fDZ, 0, fNBook * sizeof(float)); - memset(fSigY2, 0, fNBook * sizeof(float)); - memset(fSigYZ, 0, fNBook * sizeof(float)); - memset(fSigZ2, 0, fNBook * sizeof(float)); - memset(fDYK, 0, fNBook * sizeof(float)); - memset(fDZK, 0, fNBook * sizeof(float)); - memset(fSigY2K, 0, fNBook * sizeof(float)); - memset(fSigYZK, 0, fNBook * sizeof(float)); - memset(fSigZ2K, 0, fNBook * sizeof(float)); - memset(fVolID, 0, fNBook * sizeof(int)); - memset(fLabel, 0, fNBook * sizeof(int)); + memset(mX, 0, mNBook * sizeof(float)); + memset(mY, 0, mNBook * sizeof(float)); + memset(mZ, 0, mNBook * sizeof(float)); + memset(mSnp, 0, mNBook * sizeof(float)); + memset(mTgl, 0, mNBook * sizeof(float)); + memset(mAlpha, 0, mNBook * sizeof(float)); + memset(mDY, 0, mNBook * sizeof(float)); + memset(mDZ, 0, mNBook * sizeof(float)); + memset(mSigY2, 0, mNBook * sizeof(float)); + memset(mSigYZ, 0, mNBook * sizeof(float)); + memset(mSigZ2, 0, mNBook * sizeof(float)); + memset(mDYK, 0, mNBook * sizeof(float)); + memset(mDZK, 0, mNBook * sizeof(float)); + memset(mSigY2K, 0, mNBook * sizeof(float)); + memset(mSigYZK, 0, mNBook * sizeof(float)); + memset(mSigZ2K, 0, mNBook * sizeof(float)); + memset(mVolID, 0, mNBook * sizeof(int)); + memset(mLabel, 0, mNBook * sizeof(int)); } // } @@ -134,13 +134,13 @@ void AliAlgRes::Clear(const Option_t*) // reset record TObject::Clear(); ResetBit(0xffffffff); - fNPoints = 0; - fRun = 0; - fTimeStamp = 0; - fTrackID = 0; - fChi2 = 0; - fChi2K = 0; - fQ2Pt = 0; + mNPoints = 0; + mRun = 0; + mTimeStamp = 0; + mTrackID = 0; + mChi2 = 0; + mChi2K = 0; + mQ2Pt = 0; // } @@ -151,40 +151,40 @@ void AliAlgRes::Print(const Option_t* opt) const TString opts = opt; opts.ToLower(); bool lab = opts.Contains("l"); - printf("%5sTr.", IsCosmic() ? "Cosm." : "Coll."); - if (IsCosmic()) - printf("%2d/%2d ", fTrackID >> 16, fTrackID & 0xffff); + printf("%5sTr.", isCosmic() ? "Cosm." : "Coll."); + if (isCosmic()) + printf("%2d/%2d ", mTrackID >> 16, mTrackID & 0xffff); else - printf("%5d ", fTrackID); + printf("%5d ", mTrackID); printf("Run:%6d Bz:%+4.1f Np: %3d q/Pt:%+.4f | Chi2: Ini: %6.1f LinSol:%6.1f Kalm:%6.1f |Vtx:%3s| TStamp:%d\n", - fRun, fBz, fNPoints, fQ2Pt, fChi2Ini, fChi2, fChi2K, HasVertex() ? "ON" : "OFF", fTimeStamp); + mRun, mBz, mNPoints, mQ2Pt, mChi2Ini, mChi2, mChi2K, hasVertex() ? "ON" : "OFF", mTimeStamp); if (opts.Contains("r")) { bool ers = opts.Contains("e"); printf("%5s %7s %s %7s %7s %7s %5s %5s %9s %9s", " VID ", " Label ", " Alp ", " X ", " Y ", " Z ", " Snp ", " Tgl ", " DY ", " DZ "); if (ers) printf(" %8s %8s %8s", " pSgYY ", " pSgYZ ", " pSgZZ "); // cluster errors - if (GetKalmanDone()) { + if (getKalmanDone()) { printf(" %9s %9s", " DYK ", " DZK "); if (ers) printf(" %8s %8s %8s", " tSgYY ", " tSgYZ ", " tSgZZ "); // track errors } printf("\n"); - for (int i = 0; i < fNPoints; i++) { - float x = fX[i], y = fY[i], z = fZ[i]; + for (int i = 0; i < mNPoints; i++) { + float x = mX[i], y = mY[i], z = mZ[i]; if (lab) { - x = GetXLab(i); - y = GetYLab(i); - z = GetZLab(i); + x = getXLab(i); + y = getYLab(i); + z = getZLab(i); } printf("%5d %7d %+5.2f %+7.2f %+7.2f %+7.2f %+5.2f %+5.2f %+9.2e %+9.2e", - fVolID[i], fLabel[i], fAlpha[i], x, y, z, fSnp[i], fTgl[i], fDY[i], fDZ[i]); + mVolID[i], mLabel[i], mAlpha[i], x, y, z, mSnp[i], mTgl[i], mDY[i], mDZ[i]); if (ers) - printf(" %.2e %+.1e %.2e", fSigY2[i], fSigYZ[i], fSigZ2[i]); - if (GetKalmanDone()) { - printf(" %+9.2e %+9.2e", fDYK[i], fDZK[i]); + printf(" %.2e %+.1e %.2e", mSigY2[i], mSigYZ[i], mSigZ2[i]); + if (getKalmanDone()) { + printf(" %+9.2e %+9.2e", mDYK[i], mDZK[i]); if (ers) - printf(" %.2e %+.1e %.2e", fSigY2K[i], fSigYZK[i], fSigZ2K[i]); + printf(" %.2e %+.1e %.2e", mSigY2K[i], mSigYZK[i], mSigZ2K[i]); } printf("\n"); } @@ -192,45 +192,45 @@ void AliAlgRes::Print(const Option_t* opt) const } //____________________________________________________________ -bool AliAlgRes::FillTrack(AliAlgTrack* trc, bool doKalman) +bool AliAlgRes::fillTrack(AliAlgTrack* trc, bool doKalman) { // fill tracks residuals info - int nps, np = trc->GetNPoints(); - if (trc->GetInnerPoint()->ContainsMeasurement()) { - SetHasVertex(); + int nps, np = trc->getNPoints(); + if (trc->getInnerPoint()->containsMeasurement()) { + setHasVertex(); nps = np; } else nps = np - 1; // ref point is dummy? if (nps < 0) return true; - SetCosmic(trc->IsCosmic()); + setCosmic(trc->isCosmic()); // - SetNPoints(nps); - fQ2Pt = trc->getQ2Pt(); - fChi2 = trc->GetChi2(); - fChi2Ini = trc->GetChi2Ini(); + setNPoints(nps); + mQ2Pt = trc->getQ2Pt(); + mChi2 = trc->getChi2(); + mChi2Ini = trc->getChi2Ini(); int nfill = 0; for (int i = 0; i < np; i++) { - AliAlgPoint* pnt = trc->GetPoint(i); - int inv = pnt->IsInvDir() ? -1 : 1; // Flag invertion for cosmic upper leg - if (!pnt->ContainsMeasurement()) + AliAlgPoint* pnt = trc->getPoint(i); + int inv = pnt->isInvDir() ? -1 : 1; // Flag invertion for cosmic upper leg + if (!pnt->containsMeasurement()) continue; - if (!pnt->IsStatOK()) - pnt->IncrementStat(); - fVolID[nfill] = pnt->GetVolID(); - fLabel[nfill] = pnt->GetSensor()->GetInternalID(); - fAlpha[nfill] = pnt->GetAlphaSens(); - fX[nfill] = pnt->GetXPoint() * inv; - fY[nfill] = pnt->GetYTracking(); - fZ[nfill] = pnt->GetZTracking(); - fDY[nfill] = pnt->GetResidY(); - fDZ[nfill] = pnt->GetResidZ(); - fSigY2[nfill] = pnt->GetYZErrTracking()[0]; - fSigYZ[nfill] = pnt->GetYZErrTracking()[1]; - fSigZ2[nfill] = pnt->GetYZErrTracking()[2]; + if (!pnt->isStatOK()) + pnt->incrementStat(); + mVolID[nfill] = pnt->getVolID(); + mLabel[nfill] = pnt->getSensor()->getInternalID(); + mAlpha[nfill] = pnt->getAlphaSens(); + mX[nfill] = pnt->getXPoint() * inv; + mY[nfill] = pnt->getYTracking(); + mZ[nfill] = pnt->getZTracking(); + mDY[nfill] = pnt->getResidY(); + mDZ[nfill] = pnt->getResidZ(); + mSigY2[nfill] = pnt->getYZErrTracking()[0]; + mSigYZ[nfill] = pnt->getYZErrTracking()[1]; + mSigZ2[nfill] = pnt->getYZErrTracking()[2]; // - fSnp[nfill] = pnt->GetTrParamWSA()[AliAlgPoint::kParSnp]; - fTgl[nfill] = pnt->GetTrParamWSA()[AliAlgPoint::kParTgl]; + mSnp[nfill] = pnt->getTrParamWSA()[AliAlgPoint::kParSnp]; + mTgl[nfill] = pnt->getTrParamWSA()[AliAlgPoint::kParTgl]; // nfill++; } @@ -239,52 +239,52 @@ bool AliAlgRes::FillTrack(AliAlgTrack* trc, bool doKalman) LOG(FATAL) << nfill << " residuals were stored instead of " << nps; } // - SetKalmanDone(false); + setKalmanDone(false); int nfilk = 0; - if (doKalman && trc->ResidKalman()) { + if (doKalman && trc->residKalman()) { for (int i = 0; i < np; i++) { - AliAlgPoint* pnt = trc->GetPoint(i); - if (!pnt->ContainsMeasurement()) + AliAlgPoint* pnt = trc->getPoint(i); + if (!pnt->containsMeasurement()) continue; - if (fVolID[nfilk] != int(pnt->GetVolID())) { - LOG(FATAL) << "Mismatch in Kalman filling for point " << i << ": filled VID:" << fVolID[nfilk] << ", point VID:" << pnt->GetVolID(); + if (mVolID[nfilk] != int(pnt->getVolID())) { + LOG(FATAL) << "Mismatch in Kalman filling for point " << i << ": filled VID:" << mVolID[nfilk] << ", point VID:" << pnt->getVolID(); } - const double* wsA = pnt->GetTrParamWSA(); - fDYK[nfilk] = pnt->GetResidY(); - fDZK[nfilk] = pnt->GetResidZ(); - fSigY2K[nfilk] = wsA[2]; - fSigYZK[nfilk] = wsA[3]; - fSigZ2K[nfilk] = wsA[4]; + const double* wsA = pnt->getTrParamWSA(); + mDYK[nfilk] = pnt->getResidY(); + mDZK[nfilk] = pnt->getResidZ(); + mSigY2K[nfilk] = wsA[2]; + mSigYZK[nfilk] = wsA[3]; + mSigZ2K[nfilk] = wsA[4]; // nfilk++; } // - fChi2K = trc->GetChi2(); - SetKalmanDone(true); + mChi2K = trc->getChi2(); + setKalmanDone(true); } return true; } //_________________________________________________ -float AliAlgRes::GetXLab(int i) const +float AliAlgRes::getXLab(int i) const { // cluster lab X - return Abs(fX[i]) * Cos(fAlpha[i]) - fY[i] * Sin(fAlpha[i]); + return Abs(mX[i]) * Cos(mAlpha[i]) - mY[i] * Sin(mAlpha[i]); } //_________________________________________________ -float AliAlgRes::GetYLab(int i) const +float AliAlgRes::getYLab(int i) const { // cluster lab Y - return Abs(fX[i]) * Sin(fAlpha[i]) + fY[i] * Cos(fAlpha[i]); + return Abs(mX[i]) * Sin(mAlpha[i]) + mY[i] * Cos(mAlpha[i]); } //_________________________________________________ -float AliAlgRes::GetZLab(int i) const +float AliAlgRes::getZLab(int i) const { // cluster lab Z - return fZ[i]; + return mZ[i]; } } // namespace align diff --git a/Detectors/Align/src/AliAlgResFast.cxx b/Detectors/Align/src/AliAlgResFast.cxx index d84db7c796559..ae16b1082085b 100644 --- a/Detectors/Align/src/AliAlgResFast.cxx +++ b/Detectors/Align/src/AliAlgResFast.cxx @@ -33,59 +33,59 @@ namespace align //____________________________________ AliAlgResFast::AliAlgResFast() - : fNPoints(0), fNMatSol(0), fNBook(0), fChi2(0), fChi2Ini(0), fD0(0), fD1(0), fSig0(0), fSig1(0), fVolID(0), fLabel(0), fSolMat(0), fMatErr(0) + : mNPoints(0), mNMatSol(0), mNBook(0), mChi2(0), mChi2Ini(0), mD0(0), mD1(0), mSig0(0), mSig1(0), mVolID(0), mLabel(0), mSolMat(0), mMatErr(0) { // def c-tor for (int i = 5; i--;) - fTrCorr[i] = 0; + mTrCorr[i] = 0; } //________________________________________________ AliAlgResFast::~AliAlgResFast() { // d-tor - delete[] fD0; - delete[] fD1; - delete[] fSig0; - delete[] fSig1; - delete[] fVolID; - delete[] fLabel; - delete[] fSolMat; - delete[] fMatErr; + delete[] mD0; + delete[] mD1; + delete[] mSig0; + delete[] mSig1; + delete[] mVolID; + delete[] mLabel; + delete[] mSolMat; + delete[] mMatErr; } //________________________________________________ -void AliAlgResFast::Resize(int np) +void AliAlgResFast::resize(int np) { // resize container - if (np > fNBook) { - delete[] fD0; - delete[] fD1; - delete[] fSig0; - delete[] fSig1; - delete[] fVolID; - delete[] fLabel; - delete[] fSolMat; - delete[] fMatErr; + if (np > mNBook) { + delete[] mD0; + delete[] mD1; + delete[] mSig0; + delete[] mSig1; + delete[] mVolID; + delete[] mLabel; + delete[] mSolMat; + delete[] mMatErr; // - fNBook = 30 + np; - fD0 = new float[fNBook]; - fD1 = new float[fNBook]; - fSig0 = new float[fNBook]; - fSig1 = new float[fNBook]; - fVolID = new int[fNBook]; - fLabel = new int[fNBook]; - fSolMat = new float[fNBook * 4]; // at most 4 material params per point - fMatErr = new float[fNBook * 4]; // at most 4 material params per point + mNBook = 30 + np; + mD0 = new float[mNBook]; + mD1 = new float[mNBook]; + mSig0 = new float[mNBook]; + mSig1 = new float[mNBook]; + mVolID = new int[mNBook]; + mLabel = new int[mNBook]; + mSolMat = new float[mNBook * 4]; // at most 4 material params per point + mMatErr = new float[mNBook * 4]; // at most 4 material params per point // - memset(fD0, 0, fNBook * sizeof(float)); - memset(fD1, 0, fNBook * sizeof(float)); - memset(fSig0, 0, fNBook * sizeof(float)); - memset(fSig1, 0, fNBook * sizeof(float)); - memset(fVolID, 0, fNBook * sizeof(int)); - memset(fLabel, 0, fNBook * sizeof(int)); - memset(fSolMat, 0, 4 * fNBook * sizeof(int)); - memset(fMatErr, 0, 4 * fNBook * sizeof(int)); + memset(mD0, 0, mNBook * sizeof(float)); + memset(mD1, 0, mNBook * sizeof(float)); + memset(mSig0, 0, mNBook * sizeof(float)); + memset(mSig1, 0, mNBook * sizeof(float)); + memset(mVolID, 0, mNBook * sizeof(int)); + memset(mLabel, 0, mNBook * sizeof(int)); + memset(mSolMat, 0, 4 * mNBook * sizeof(int)); + memset(mMatErr, 0, 4 * mNBook * sizeof(int)); } // } @@ -94,9 +94,9 @@ void AliAlgResFast::Resize(int np) void AliAlgResFast::Clear(const Option_t*) { // reset record - fNPoints = 0; - fNMatSol = 0; - fTrCorr[4] = 0; // rest will be 100% overwritten + mNPoints = 0; + mNMatSol = 0; + mTrCorr[4] = 0; // rest will be 100% overwritten // } @@ -106,26 +106,26 @@ void AliAlgResFast::Print(const Option_t* /*opt*/) const // print info printf("%3s:%1s (%9s/%5s) %6s | [ %7s:%7s ]\n", "Pnt", "M", "Label", "VolID", "Sigma", "resid", "pull/LG"); - for (int irs = 0; irs < fNPoints; irs++) { + for (int irs = 0; irs < mNPoints; irs++) { printf("%3d:%1d (%9d/%5d) %6.4f | [%+.2e:%+7.2f]\n", - irs, 0, fLabel[irs], fVolID[irs], fSig0[irs], fD0[irs], - fSig0[irs] > 0 ? fD0[irs] / fSig0[irs] : -99); + irs, 0, mLabel[irs], mVolID[irs], mSig0[irs], mD0[irs], + mSig0[irs] > 0 ? mD0[irs] / mSig0[irs] : -99); printf("%3d:%1d (%9d/%5d) %6.4f | [%+.2e:%+7.2f]\n", - irs, 1, fLabel[irs], fVolID[irs], fSig1[irs], fD1[irs], - fSig1[irs] > 0 ? fD1[irs] / fSig1[irs] : -99); + irs, 1, mLabel[irs], mVolID[irs], mSig1[irs], mD1[irs], + mSig1[irs] > 0 ? mD1[irs] / mSig1[irs] : -99); } // printf("CorrETP: "); for (int i = 0; i < 5; i++) - printf("%+.3f ", fTrCorr[i]); + printf("%+.3f ", mTrCorr[i]); printf("\n"); printf("MatCorr (corr/sig:pull)\n"); - int nmp = fNMatSol / 4; + int nmp = mNMatSol / 4; int cnt = 0; for (int imp = 0; imp < nmp; imp++) { for (int ic = 0; ic < 4; ic++) { - printf("%+.2e/%.2e:%+8.3f|", fSolMat[cnt], fMatErr[cnt], - fMatErr[cnt] > 0 ? fSolMat[cnt] / fMatErr[cnt] : -99); + printf("%+.2e/%.2e:%+8.3f|", mSolMat[cnt], mMatErr[cnt], + mMatErr[cnt] > 0 ? mSolMat[cnt] / mMatErr[cnt] : -99); cnt++; } printf("\n"); @@ -134,32 +134,32 @@ void AliAlgResFast::Print(const Option_t* /*opt*/) const } //____________________________________________ -void AliAlgResFast::SetResSigMeas(int ip, int ord, float res, float sig) +void AliAlgResFast::setResSigMeas(int ip, int ord, float res, float sig) { // assign residual and error for measurement if (ord == 0) { - fD0[ip] = res; - fSig0[ip] = sig; + mD0[ip] = res; + mSig0[ip] = sig; } else { - fD1[ip] = res; - fSig1[ip] = sig; + mD1[ip] = res; + mSig1[ip] = sig; } } //____________________________________________ -void AliAlgResFast::SetMatCorr(int id, float res, float sig) +void AliAlgResFast::setMatCorr(int id, float res, float sig) { // assign residual and error for material correction - fSolMat[id] = res; - fMatErr[id] = sig; + mSolMat[id] = res; + mMatErr[id] = sig; } //____________________________________________ -void AliAlgResFast::SetLabel(int ip, int lab, int vol) +void AliAlgResFast::setLabel(int ip, int lab, int vol) { // set label/volid of measured volume - fVolID[ip] = vol; - fLabel[ip] = lab; + mVolID[ip] = vol; + mLabel[ip] = lab; } } // namespace align diff --git a/Detectors/Align/src/AliAlgSens.cxx b/Detectors/Align/src/AliAlgSens.cxx index 5a37fd33df079..85c5f7c3251bf 100644 --- a/Detectors/Align/src/AliAlgSens.cxx +++ b/Detectors/Align/src/AliAlgSens.cxx @@ -34,12 +34,12 @@ namespace align //_________________________________________________________ AliAlgSens::AliAlgSens(const char* name, int vid, int iid) - : AliAlgVol(name, iid), fSID(0), fDet(0), fMatClAlg(), fMatClAlgReco() + : AliAlgVol(name, iid), mSID(0), mDet(0), mMatClAlg(), mMatClAlgReco() { // def c-tor - SetVolID(vid); - fAddError[0] = fAddError[1] = 0; - fConstrChild = 0; // sensors don't have children + setVolID(vid); + mAddError[0] = mAddError[1] = 0; + mConstrChild = 0; // sensors don't have children } //_________________________________________________________ @@ -49,7 +49,7 @@ AliAlgSens::~AliAlgSens() } //_________________________________________________________ -void AliAlgSens::DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv) const +void AliAlgSens::dPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv) const { // Jacobian of position in sensor tracking frame (tra) vs sensor LOCAL frame // parameters in TGeoHMatrix convention. @@ -60,29 +60,29 @@ void AliAlgSens::DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv) const // memset(delta, 0, kNDOFGeom * sizeof(double)); memset(deriv, 0, kNDOFGeom * 3 * sizeof(double)); - const double* tra = pnt->GetXYZTracking(); + const double* tra = pnt->getXYZTracking(); // for (int ip = kNDOFGeom; ip--;) { // - if (!IsFreeDOF(ip)) + if (!isFreeDOF(ip)) continue; // double var = kDelta[ip]; delta[ip] -= var; // variation matrix in tracking frame for variation in sensor LOCAL frame - GetDeltaT2LmodLOC(matMod, delta); + getDeltaT2LmodLOC(matMod, delta); matMod.LocalToMaster(tra, pos0); // varied position in tracking frame // delta[ip] += 0.5 * var; - GetDeltaT2LmodLOC(matMod, delta); + getDeltaT2LmodLOC(matMod, delta); matMod.LocalToMaster(tra, pos1); // varied position in tracking frame // delta[ip] += var; - GetDeltaT2LmodLOC(matMod, delta); + getDeltaT2LmodLOC(matMod, delta); matMod.LocalToMaster(tra, pos2); // varied position in tracking frame // delta[ip] += 0.5 * var; - GetDeltaT2LmodLOC(matMod, delta); + getDeltaT2LmodLOC(matMod, delta); matMod.LocalToMaster(tra, pos3); // varied position in tracking frame // delta[ip] = 0; @@ -94,7 +94,7 @@ void AliAlgSens::DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv) const } //_________________________________________________________ -void AliAlgSens::DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const +void AliAlgSens::dPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const { // Jacobian of position in sensor tracking frame (tra) vs parent volume LOCAL frame parameters. // NO check of parentship is done! @@ -103,33 +103,33 @@ void AliAlgSens::DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv, const double delta[kNDOFGeom], pos0[3], pos1[3], pos2[3], pos3[3]; TGeoHMatrix matMod; // this is the matrix for transition from sensor to parent volume local frames: LOC=matRel*loc - TGeoHMatrix matRel = parent->GetMatrixL2GIdeal().Inverse(); - matRel *= GetMatrixL2GIdeal(); + TGeoHMatrix matRel = parent->getMatrixL2GIdeal().Inverse(); + matRel *= getMatrixL2GIdeal(); // memset(delta, 0, kNDOFGeom * sizeof(double)); memset(deriv, 0, kNDOFGeom * 3 * sizeof(double)); - const double* tra = pnt->GetXYZTracking(); + const double* tra = pnt->getXYZTracking(); // for (int ip = kNDOFGeom; ip--;) { // - if (!IsFreeDOF(ip)) + if (!isFreeDOF(ip)) continue; // double var = kDelta[ip]; delta[ip] -= var; - GetDeltaT2LmodLOC(matMod, delta, matRel); + getDeltaT2LmodLOC(matMod, delta, matRel); matMod.LocalToMaster(tra, pos0); // varied position in tracking frame // delta[ip] += 0.5 * var; - GetDeltaT2LmodLOC(matMod, delta, matRel); + getDeltaT2LmodLOC(matMod, delta, matRel); matMod.LocalToMaster(tra, pos1); // varied position in tracking frame // delta[ip] += var; - GetDeltaT2LmodLOC(matMod, delta, matRel); + getDeltaT2LmodLOC(matMod, delta, matRel); matMod.LocalToMaster(tra, pos2); // varied position in tracking frame // delta[ip] += 0.5 * var; - GetDeltaT2LmodLOC(matMod, delta, matRel); + getDeltaT2LmodLOC(matMod, delta, matRel); matMod.LocalToMaster(tra, pos3); // varied position in tracking frame // delta[ip] = 0; @@ -141,7 +141,7 @@ void AliAlgSens::DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv, const } //_________________________________________________________ -void AliAlgSens::DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv) const +void AliAlgSens::dPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv) const { // Jacobian of position in sensor tracking frame (tra) vs sensor TRACKING // frame parameters in TGeoHMatrix convention, i.e. the modified parameter is @@ -154,28 +154,28 @@ void AliAlgSens::DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv) const // memset(delta, 0, kNDOFGeom * sizeof(double)); memset(deriv, 0, kNDOFGeom * 3 * sizeof(double)); - const double* tra = pnt->GetXYZTracking(); + const double* tra = pnt->getXYZTracking(); // for (int ip = kNDOFGeom; ip--;) { // - if (!IsFreeDOF(ip)) + if (!isFreeDOF(ip)) continue; // double var = kDelta[ip]; delta[ip] -= var; - GetDeltaT2LmodTRA(matMod, delta); + getDeltaT2LmodTRA(matMod, delta); matMod.LocalToMaster(tra, pos0); // varied position in tracking frame // delta[ip] += 0.5 * var; - GetDeltaT2LmodTRA(matMod, delta); + getDeltaT2LmodTRA(matMod, delta); matMod.LocalToMaster(tra, pos1); // varied position in tracking frame // delta[ip] += var; - GetDeltaT2LmodTRA(matMod, delta); + getDeltaT2LmodTRA(matMod, delta); matMod.LocalToMaster(tra, pos2); // varied position in tracking frame // delta[ip] += 0.5 * var; - GetDeltaT2LmodTRA(matMod, delta); + getDeltaT2LmodTRA(matMod, delta); matMod.LocalToMaster(tra, pos3); // varied position in tracking frame // delta[ip] = 0; @@ -187,7 +187,7 @@ void AliAlgSens::DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv) const } //_________________________________________________________ -void AliAlgSens::DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const +void AliAlgSens::dPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const { // Jacobian of position in sensor tracking frame (tra) vs sensor TRACKING // frame parameters in TGeoHMatrix convention, i.e. the modified parameter is @@ -208,35 +208,35 @@ void AliAlgSens::DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv, const // -> TRA = matRel*tra, with matRel = T2L^-1*L2G^-1 * l2g*t2l // Note that l2g*t2l are tracking to global matrices TGeoHMatrix matRel, t2gP; - GetMatrixT2G(matRel); // t2g matrix of child - parent->GetMatrixT2G(t2gP); // t2g matrix of parent + getMatrixT2G(matRel); // t2g matrix of child + parent->getMatrixT2G(t2gP); // t2g matrix of parent const TGeoHMatrix& t2gpi = t2gP.Inverse(); matRel.MultiplyLeft(&t2gpi); // memset(delta, 0, kNDOFGeom * sizeof(double)); memset(deriv, 0, kNDOFGeom * 3 * sizeof(double)); - const double* tra = pnt->GetXYZTracking(); + const double* tra = pnt->getXYZTracking(); // for (int ip = kNDOFGeom; ip--;) { // - if (!IsFreeDOF(ip)) + if (!isFreeDOF(ip)) continue; // double var = kDelta[ip]; delta[ip] -= var; - GetDeltaT2LmodTRA(matMod, delta, matRel); + getDeltaT2LmodTRA(matMod, delta, matRel); matMod.LocalToMaster(tra, pos0); // varied position in tracking frame // delta[ip] += 0.5 * var; - GetDeltaT2LmodTRA(matMod, delta, matRel); + getDeltaT2LmodTRA(matMod, delta, matRel); matMod.LocalToMaster(tra, pos1); // varied position in tracking frame // delta[ip] += var; - GetDeltaT2LmodTRA(matMod, delta, matRel); + getDeltaT2LmodTRA(matMod, delta, matRel); matMod.LocalToMaster(tra, pos2); // varied position in tracking frame // delta[ip] += 0.5 * var; - GetDeltaT2LmodTRA(matMod, delta, matRel); + getDeltaT2LmodTRA(matMod, delta, matRel); matMod.LocalToMaster(tra, pos3); // varied position in tracking frame // delta[ip] = 0; @@ -248,48 +248,48 @@ void AliAlgSens::DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv, const } //_________________________________________________________ -void AliAlgSens::DPosTraDParGeom(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const +void AliAlgSens::dPosTraDParGeom(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const { // calculate point position derivatives in tracking frame of sensor // vs standard geometrical DOFs of its parent volume (if parent!=0) or sensor itself - Frame_t frame = parent ? parent->GetVarFrame() : GetVarFrame(); + Frame_t frame = parent ? parent->getVarFrame() : getVarFrame(); switch (frame) { case kLOC: - parent ? DPosTraDParGeomLOC(pnt, deriv, parent) : DPosTraDParGeomLOC(pnt, deriv); + parent ? dPosTraDParGeomLOC(pnt, deriv, parent) : dPosTraDParGeomLOC(pnt, deriv); break; case kTRA: - parent ? DPosTraDParGeomTRA(pnt, deriv, parent) : DPosTraDParGeomTRA(pnt, deriv); + parent ? dPosTraDParGeomTRA(pnt, deriv, parent) : dPosTraDParGeomTRA(pnt, deriv); break; default: - LOG(ERROR) << "Alignment frame " << parent->GetVarFrame() << " is not implemented"; + LOG(ERROR) << "Alignment frame " << parent->getVarFrame() << " is not implemented"; break; } } //__________________________________________________________________ -void AliAlgSens::GetModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const double* delta) const +void AliAlgSens::getModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const double* delta) const { // prepare the sensitive module tracking2local matrix from its current T2L matrix // by applying local delta of modification of LOCAL frame: // loc' = delta*loc = T2L'*tra = T2L'*T2L^-1*loc -> T2L' = delta*T2L - Delta2Matrix(matMod, delta); - matMod.Multiply(&GetMatrixT2L()); + delta2Matrix(matMod, delta); + matMod.Multiply(&getMatrixT2L()); } //__________________________________________________________________ -void AliAlgSens::GetModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const double* delta) const +void AliAlgSens::getModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const double* delta) const { // prepare the sensitive module tracking2local matrix from its current T2L matrix // by applying local delta of modification of TRACKING frame: // loc' = T2L'*tra = T2L*delta*tra -> T2L' = T2L*delta - Delta2Matrix(matMod, delta); - matMod.MultiplyLeft(&GetMatrixT2L()); + delta2Matrix(matMod, delta); + matMod.MultiplyLeft(&getMatrixT2L()); } //__________________________________________________________________ -void AliAlgSens::AddChild(AliAlgVol*) +void AliAlgSens::addChild(AliAlgVol*) { - LOG(FATAL) << "Sensor volume cannot have children: id=" << GetVolID() << " " << GetName(); + LOG(FATAL) << "Sensor volume cannot have children: id=" << getVolID() << " " << GetName(); } //__________________________________________________________________ @@ -300,17 +300,17 @@ int AliAlgSens::Compare(const TObject* b) const } //__________________________________________________________________ -void AliAlgSens::SetTrackingFrame() +void AliAlgSens::setTrackingFrame() { // define tracking frame of the sensor - // AliWarningF("Generic method called for %s",GetSymName()); + // AliWarningF("Generic method called for %s",getSymName()); double tra[3] = {0}, glo[3]; TGeoHMatrix t2g; - GetMatrixT2G(t2g); + getMatrixT2G(t2g); t2g.LocalToMaster(tra, glo); - fX = Sqrt(glo[0] * glo[0] + glo[1] * glo[1]); - fAlp = ATan2(glo[1], glo[0]); - AliAlgAux::BringToPiPM(fAlp); + mX = Sqrt(glo[0] * glo[0] + glo[1] * glo[1]); + mAlp = ATan2(glo[1], glo[0]); + AliAlgAux::bringToPiPM(mAlp); // } @@ -321,98 +321,98 @@ void AliAlgSens::Print(const Option_t* opt) const TString opts = opt; opts.ToLower(); printf("Lev:%2d IntID:%7d %s VId:%6d X:%8.4f Alp:%+.4f | Err: %.4e %.4e | Used Points: %d\n", - CountParents(), GetInternalID(), GetSymName(), GetVolID(), fX, fAlp, - fAddError[0], fAddError[1], fNProcPoints); - printf(" DOFs: Tot: %d (offs: %5d) Free: %d Geom: %d {", fNDOFs, fFirstParGloID, fNDOFFree, fNDOFGeomFree); + countParents(), getInternalID(), getSymName(), getVolID(), mX, mAlp, + mAddError[0], mAddError[1], mNProcPoints); + printf(" DOFs: Tot: %d (offs: %5d) Free: %d Geom: %d {", mNDOFs, mFirstParGloID, mNDOFFree, mNDOFGeomFree); for (int i = 0; i < kNDOFGeom; i++) - printf("%d", IsFreeDOF(i) ? 1 : 0); - printf("} in %s frame\n", fgkFrameName[fVarFrame]); + printf("%d", isFreeDOF(i) ? 1 : 0); + printf("} in %s frame\n", sFrameName[mVarFrame]); // // // - if (opts.Contains("par") && fParVals) { + if (opts.Contains("par") && mParVals) { printf(" Lb: "); - for (int i = 0; i < fNDOFs; i++) - printf("%10d ", GetParLab(i)); + for (int i = 0; i < mNDOFs; i++) + printf("%10d ", getParLab(i)); printf("\n"); printf(" Vl: "); - for (int i = 0; i < fNDOFs; i++) - printf("%+9.3e ", GetParVal(i)); + for (int i = 0; i < mNDOFs; i++) + printf("%+9.3e ", getParVal(i)); printf("\n"); printf(" Er: "); - for (int i = 0; i < fNDOFs; i++) - printf("%+9.3e ", GetParErr(i)); + for (int i = 0; i < mNDOFs; i++) + printf("%+9.3e ", getParErr(i)); printf("\n"); } // if (opts.Contains("mat")) { // print matrices printf("L2G ideal : "); - GetMatrixL2GIdeal().Print(); + getMatrixL2GIdeal().Print(); printf("L2G misalign: "); - GetMatrixL2G().Print(); + getMatrixL2G().Print(); printf("L2G RecoTime: "); - GetMatrixL2GReco().Print(); + getMatrixL2GReco().Print(); printf("T2L : "); - GetMatrixT2L().Print(); + getMatrixT2L().Print(); printf("ClAlg : "); - GetMatrixClAlg().Print(); + getMatrixClAlg().Print(); printf("ClAlgReco: "); - GetMatrixClAlgReco().Print(); + getMatrixClAlgReco().Print(); } // } //____________________________________________ -void AliAlgSens::PrepareMatrixT2L() +void AliAlgSens::prepareMatrixT2L() { // extract geometry T2L matrix TGeoHMatrix t2l; t2l.Clear(); - t2l.RotateZ(fAlp * RadToDeg()); // rotate in direction of normal to the sensor plane - const TGeoHMatrix* matL2G = base::GeometryManager::getMatrix(fDet->GetO2DetID(), GetSID()); + t2l.RotateZ(mAlp * RadToDeg()); // rotate in direction of normal to the sensor plane + const TGeoHMatrix* matL2G = base::GeometryManager::getMatrix(mDet->getO2DetID(), getSID()); const TGeoHMatrix& matL2Gi = matL2G->Inverse(); t2l.MultiplyLeft(&matL2Gi); - SetMatrixT2L(t2l); + setMatrixT2L(t2l); - // const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(GetVolID()); + // const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(getVolID()); // const if (!t2l) // { // Print("long"); - // LOG(FATAL) << "Failed to find T2L matrix for VID: " << GetVolID() << ", " << GetSymName(); + // LOG(FATAL) << "Failed to find T2L matrix for VID: " << getVolID() << ", " << getSymName(); // } - // SetMatrixT2L(*t2l); + // setMatrixT2L(*t2l); // // } //____________________________________________ -void AliAlgSens::PrepareMatrixClAlg() +void AliAlgSens::prepareMatrixClAlg() { // prepare alignment matrix in the LOCAL frame: delta = Gideal^-1 * G - TGeoHMatrix ma = GetMatrixL2GIdeal().Inverse(); - ma *= GetMatrixL2G(); - SetMatrixClAlg(ma); + TGeoHMatrix ma = getMatrixL2GIdeal().Inverse(); + ma *= getMatrixL2G(); + setMatrixClAlg(ma); // } //____________________________________________ -void AliAlgSens::PrepareMatrixClAlgReco() +void AliAlgSens::prepareMatrixClAlgReco() { // prepare alignment matrix used at reco time - TGeoHMatrix ma = GetMatrixL2GIdeal().Inverse(); - ma *= GetMatrixL2GReco(); - SetMatrixClAlgReco(ma); + TGeoHMatrix ma = getMatrixL2GIdeal().Inverse(); + ma *= getMatrixL2GReco(); + setMatrixClAlgReco(ma); // } //____________________________________________ -void AliAlgSens::UpdatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) const +void AliAlgSens::updatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) const { // update - fDet->UpdatePointByTrackInfo(pnt, t); + mDet->updatePointByTrackInfo(pnt, t); } //____________________________________________ -void AliAlgSens::DPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int calibID, const AliAlgVol* parent) const +void AliAlgSens::dPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int calibID, const AliAlgVol* parent) const { // calculate point position X,Y,Z derivatives wrt calibration parameter calibID of given parent // parent=0 means top detector object calibration @@ -421,23 +421,23 @@ void AliAlgSens::DPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int cal } //______________________________________________________ -int AliAlgSens::FinalizeStat(AliAlgDOFStat* st) +int AliAlgSens::finalizeStat(AliAlgDOFStat* st) { // finalize statistics on processed points if (st) - FillDOFStat(st); - return fNProcPoints; + fillDOFStat(st); + return mNProcPoints; } //_________________________________________________________________ -void AliAlgSens::UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta) +void AliAlgSens::updateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta) { - // recreate fMatL2GReco matrices from ideal L2G matrix and alignment objects + // recreate mMatL2GReco matrices from ideal L2G matrix and alignment objects // used during data reconstruction. // On top of what each volume does, also update misalignment matrix inverse // - AliAlgVol::UpdateL2GRecoMatrices(algArr, cumulDelta); - PrepareMatrixClAlgReco(); + AliAlgVol::updateL2GRecoMatrices(algArr, cumulDelta); + prepareMatrixClAlgReco(); // } @@ -452,7 +452,7 @@ AliAlgPoint* AliAlgSens::TrackPoint2AlgPoint(int, const AliTrackPointArray*, con */ //_________________________________________________________________ -void AliAlgSens::ApplyAlignmentFromMPSol() +void AliAlgSens::applyAlignmentFromMPSol() { // apply to the tracking coordinates in the sensor frame the full chain // of alignments found by MP for this sensor and its parents @@ -463,23 +463,23 @@ void AliAlgSens::ApplyAlignmentFromMPSol() // DeltaG = deltaG_0*...*deltaG_j, where delta_i is global delta of each member of hierarchy while (vol) { TGeoHMatrix deltaGJ; - vol->CreateAlignmenMatrix(deltaGJ); + vol->createAlignmenMatrix(deltaGJ); deltaG.MultiplyLeft(&deltaGJ); - vol = vol->GetParent(); + vol = vol->getParent(); } // // update misaligned L2G matrix - deltaG *= GetMatrixL2GIdeal(); - SetMatrixL2G(deltaG); + deltaG *= getMatrixL2GIdeal(); + setMatrixL2G(deltaG); // // update local misalignment matrix - PrepareMatrixClAlg(); + prepareMatrixClAlg(); // } /* //_________________________________________________________________ -void AliAlgSens::ApplyAlignmentFromMPSol() +void AliAlgSens::applyAlignmentFromMPSol() { // apply to the tracking coordinates in the sensor frame the full chain // of alignments found by MP for this sensor and its parents @@ -488,27 +488,27 @@ void AliAlgSens::ApplyAlignmentFromMPSol() TGeoHMatrix matMod; // // sensor proper variation - GetParValGeom(delta); - IsFrameTRA() ? GetDeltaT2LmodTRA(matMod,delta) : GetDeltaT2LmodLOC(matMod,delta); - fMatClAlg.MultiplyLeft(&matMod); + getParValGeom(delta); + isFrameTRA() ? getDeltaT2LmodTRA(matMod,delta) : getDeltaT2LmodLOC(matMod,delta); + mMatClAlg.MultiplyLeft(&matMod); // AliAlgVol* parent = this; - while ((parent==parent->GetParent())) { + while ((parent==parent->getParent())) { // this is the matrix for transition from sensor to parent volume frame - parent->GetParValGeom(delta); + parent->getParValGeom(delta); TGeoHMatrix matRel,t2gP; - if (parent->IsFrameTRA()) { - GetMatrixT2G(matRel); // t2g matrix of child - parent->GetMatrixT2G(t2gP); // t2g matrix of parent + if (parent->isFrameTRA()) { + getMatrixT2G(matRel); // t2g matrix of child + parent->getMatrixT2G(t2gP); // t2g matrix of parent matRel.MultiplyLeft(&t2gP.Inverse()); - GetDeltaT2LmodTRA(matMod, delta, matRel); + getDeltaT2LmodTRA(matMod, delta, matRel); } else { - matRel = parent->GetMatrixL2GIdeal().Inverse(); - matRel *= GetMatrixL2GIdeal(); - GetDeltaT2LmodLOC(matMod, delta, matRel); + matRel = parent->getMatrixL2GIdeal().Inverse(); + matRel *= getMatrixL2GIdeal(); + getDeltaT2LmodLOC(matMod, delta, matRel); } - fMatClAlg.MultiplyLeft(&matMod); + mMatClAlg.MultiplyLeft(&matMod); } // } diff --git a/Detectors/Align/src/AliAlgSensHMPID.cxx b/Detectors/Align/src/AliAlgSensHMPID.cxx index 9d8dc74fd7f93..095ffccfb249d 100644 --- a/Detectors/Align/src/AliAlgSensHMPID.cxx +++ b/Detectors/Align/src/AliAlgSensHMPID.cxx @@ -45,35 +45,35 @@ AliAlgSensHMPID::~AliAlgSensHMPID() } /* //__________________________________________________________________ -void AliAlgSensHMPID::SetTrackingFrame() +void AliAlgSensHMPID::setTrackingFrame() { // define tracking frame of the sensor: just rotation by sector angle - fAlp = Sector2Alpha(fSector); + fAlp = sector2Alpha(fSector); fX = 0; } */ //____________________________________________ -void AliAlgSensHMPID::PrepareMatrixT2L() +void AliAlgSensHMPID::prepareMatrixT2L() { // creat T2L matrix double loc[3] = {0, 0, 0}, glo[3]; - GetMatrixL2GIdeal().LocalToMaster(loc, glo); + getMatrixL2GIdeal().LocalToMaster(loc, glo); double alp = ATan2(glo[1], glo[0]); double x = Sqrt(glo[0] * glo[0] + glo[1] * glo[1]); TGeoHMatrix t2l; t2l.SetDx(x); t2l.RotateZ(alp * RadToDeg()); - const TGeoHMatrix& l2gi = GetMatrixL2GIdeal().Inverse(); + const TGeoHMatrix& l2gi = getMatrixL2GIdeal().Inverse(); t2l.MultiplyLeft(&l2gi); /* - const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(GetVolID()); + const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(getVolID()); if (!t2l) { Print("long"); - AliFatalF("Failed to find T2L matrix for VID:%d %s",GetVolID(),GetSymName()); + AliFatalF("Failed to find T2L matrix for VID:%d %s",getVolID(),getSymName()); } */ - SetMatrixT2L(t2l); + setMatrixT2L(t2l); // } @@ -82,27 +82,27 @@ AliAlgPoint* AliAlgSensHMPID::TrackPoint2AlgPoint(int pntId, const AliTrackPoint { // convert the pntId-th point to AliAlgPoint // - AliAlgDet* det = GetDetector(); - AliAlgPoint* pnt = det->GetPointFromPool(); - pnt->SetSensor(this); + AliAlgDet* det = getDetector(); + AliAlgPoint* pnt = det->getPointFromPool(); + pnt->setSensor(this); // double tra[3], locId[3], loc[3], glo[3] = {trpArr->GetX()[pntId], trpArr->GetY()[pntId], trpArr->GetZ()[pntId]}; - const TGeoHMatrix& matL2Grec = GetMatrixL2GReco(); // local to global matrix used for reconstruction - const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation + const TGeoHMatrix& matL2Grec = getMatrixL2GReco(); // local to global matrix used for reconstruction + const TGeoHMatrix& matT2L = getMatrixT2L(); // matrix for tracking to local frame translation // // undo reco-time alignment matL2Grec.MasterToLocal(glo, locId); // go to local frame using reco-time matrix, here we recover ideal measurement // - GetMatrixClAlg().LocalToMaster(locId, loc); // apply alignment + getMatrixClAlg().LocalToMaster(locId, loc); // apply alignment // matT2L.MasterToLocal(loc, tra); // go to tracking frame // /* double gloT[3]; TGeoHMatrix t2g; - GetMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); - printf("\n%5d %s\n",GetVolID(), GetSymName()); + getMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); + printf("\n%5d %s\n",getVolID(), getSymName()); printf("GloOR: %+.4e %+.4e %+.4e\n",glo[0],glo[1],glo[2]); printf("LocID: %+.4e %+.4e %+.4e\n",locId[0],locId[1],locId[2]); printf("LocML: %+.4e %+.4e %+.4e\n",loc[0],loc[1],loc[2]); @@ -110,7 +110,7 @@ AliAlgPoint* AliAlgSensHMPID::TrackPoint2AlgPoint(int pntId, const AliTrackPoint printf("GloTR: %+.4e %+.4e %+.4e\n",gloT[0],gloT[1],gloT[2]); */ // - if (!det->GetUseErrorParam()) { + if (!det->getUseErrorParam()) { // convert error TGeoHMatrix hcov; double hcovel[9]; @@ -133,21 +133,21 @@ AliAlgPoint* AliAlgSensHMPID::TrackPoint2AlgPoint(int pntId, const AliTrackPoint hcov.MultiplyLeft(&t2li); // errors in tracking frame // double* hcovscl = hcov.GetRotationMatrix(); - const double* sysE = GetAddError(); // additional syst error - pnt->SetYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); + const double* sysE = getAddError(); // additional syst error + pnt->setYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); } else { // errors will be calculated just before using the point in the fit, using track info - pnt->SetYZErrTracking(0, 0, 0); - pnt->SetNeedUpdateFromTrack(); + pnt->setYZErrTracking(0, 0, 0); + pnt->setNeedUpdateFromTrack(); } - pnt->SetXYZTracking(tra[0], tra[1], tra[2]); - pnt->SetAlphaSens(GetAlpTracking()); - pnt->SetXSens(GetXTracking()); - pnt->SetDetID(det->GetDetID()); - pnt->SetSID(GetSID()); + pnt->setXYZTracking(tra[0], tra[1], tra[2]); + pnt->setAlphaSens(getAlpTracking()); + pnt->setXSens(getXTracking()); + pnt->setDetID(det->getDetID()); + pnt->setSID(getSID()); // - pnt->SetContainsMeasurement(); + pnt->setContainsMeasurement(); // - pnt->Init(); + pnt->init(); // return pnt; // diff --git a/Detectors/Align/src/AliAlgSensITS.cxx b/Detectors/Align/src/AliAlgSensITS.cxx index 434aee2e60112..977f1b3e840fa 100644 --- a/Detectors/Align/src/AliAlgSensITS.cxx +++ b/Detectors/Align/src/AliAlgSensITS.cxx @@ -45,16 +45,16 @@ AliAlgSensITS::~AliAlgSensITS() } /* //__________________________________________________________________ -void AliAlgSensITS::SetTrackingFrame() +void AliAlgSensITS::setTrackingFrame() { // define tracking frame of the sensor double tra[3]={0},loc[3],glo[3]; // ITS defines tracking frame with origin in sensor, others at 0 - GetMatrixT2L().LocalToMaster(tra,loc); - GetMatrixL2GIdeal().LocalToMaster(loc,glo); + getMatrixT2L().LocalToMaster(tra,loc); + getMatrixL2GIdeal().LocalToMaster(loc,glo); fX = Sqrt(glo[0]*glo[0]+glo[1]*glo[1]); fAlp = ATan2(glo[1],glo[0]); - AliAlgAux::BringToPiPM(fAlp); + AliAlgAux::bringToPiPM(fAlp); } */ @@ -63,27 +63,27 @@ AliAlgPoint* AliAlgSensITS::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr { // convert the pntId-th point to AliAlgPoint // - AliAlgDet* det = GetDetector(); - AliAlgPoint* pnt = det->GetPointFromPool(); - pnt->SetSensor(this); + AliAlgDet* det = getDetector(); + AliAlgPoint* pnt = det->getPointFromPool(); + pnt->setSensor(this); // double tra[3], locId[3], loc[3], glo[3] = {trpArr->GetX()[pntId], trpArr->GetY()[pntId], trpArr->GetZ()[pntId]}; - const TGeoHMatrix& matL2Grec = GetMatrixL2GReco(); // local to global matrix used for reconstruction - const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation + const TGeoHMatrix& matL2Grec = getMatrixL2GReco(); // local to global matrix used for reconstruction + const TGeoHMatrix& matT2L = getMatrixT2L(); // matrix for tracking to local frame translation // // undo reco-time alignment matL2Grec.MasterToLocal(glo, locId); // go to local frame using reco-time matrix, here we recover ideal measurement // - GetMatrixClAlg().LocalToMaster(locId, loc); // apply alignment + getMatrixClAlg().LocalToMaster(locId, loc); // apply alignment // matT2L.MasterToLocal(loc, tra); // go to tracking frame // /* double gloT[3]; TGeoHMatrix t2g; - GetMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); - printf("\n%5d %s\n",GetVolID(), GetSymName()); + getMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); + printf("\n%5d %s\n",getVolID(), getSymName()); printf("GloOR: %+.4e %+.4e %+.4e\n",glo[0],glo[1],glo[2]); printf("LocID: %+.4e %+.4e %+.4e\n",locId[0],locId[1],locId[2]); printf("LocML: %+.4e %+.4e %+.4e\n",loc[0],loc[1],loc[2]); @@ -91,7 +91,7 @@ AliAlgPoint* AliAlgSensITS::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr printf("GloTR: %+.4e %+.4e %+.4e\n",gloT[0],gloT[1],gloT[2]); */ // - if (!det->GetUseErrorParam()) { + if (!det->getUseErrorParam()) { // convert error TGeoHMatrix hcov; double hcovel[9]; @@ -114,21 +114,21 @@ AliAlgPoint* AliAlgSensITS::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr hcov.MultiplyLeft(&t2li); // errors in tracking frame // double* hcovscl = hcov.GetRotationMatrix(); - const double* sysE = GetAddError(); // additional syst error - pnt->SetYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); + const double* sysE = getAddError(); // additional syst error + pnt->setYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); } else { // errors will be calculated just before using the point in the fit, using track info - pnt->SetYZErrTracking(0, 0, 0); - pnt->SetNeedUpdateFromTrack(); + pnt->setYZErrTracking(0, 0, 0); + pnt->setNeedUpdateFromTrack(); } - pnt->SetXYZTracking(tra[0], tra[1], tra[2]); - pnt->SetAlphaSens(GetAlpTracking()); - pnt->SetXSens(GetXTracking()); - pnt->SetDetID(det->GetDetID()); - pnt->SetSID(GetSID()); + pnt->setXYZTracking(tra[0], tra[1], tra[2]); + pnt->setAlphaSens(getAlpTracking()); + pnt->setXSens(getXTracking()); + pnt->setDetID(det->getDetID()); + pnt->setSID(getSID()); // - pnt->SetContainsMeasurement(); + pnt->setContainsMeasurement(); // - pnt->Init(); + pnt->init(); // return pnt; // diff --git a/Detectors/Align/src/AliAlgSensTOF.cxx b/Detectors/Align/src/AliAlgSensTOF.cxx index bd0e27d734321..e43f797529d6b 100644 --- a/Detectors/Align/src/AliAlgSensTOF.cxx +++ b/Detectors/Align/src/AliAlgSensTOF.cxx @@ -46,35 +46,35 @@ AliAlgSensTOF::~AliAlgSensTOF() /* //__________________________________________________________________ -void AliAlgSensTOF::SetTrackingFrame() +void AliAlgSensTOF::setTrackingFrame() { // define tracking frame of the sensor: just rotation by sector angle - fAlp = Sector2Alpha(fSector); + fAlp = sector2Alpha(fSector); fX = 0; } */ //____________________________________________ -void AliAlgSensTOF::PrepareMatrixT2L() +void AliAlgSensTOF::prepareMatrixT2L() { // extract from geometry T2L matrix - double alp = Sector2Alpha(fSector); + double alp = sector2Alpha(fSector); double loc[3] = {0, 0, 0}, glo[3]; - GetMatrixL2GIdeal().LocalToMaster(loc, glo); + getMatrixL2GIdeal().LocalToMaster(loc, glo); double x = Sqrt(glo[0] * glo[0] + glo[1] * glo[1]); TGeoHMatrix t2l; t2l.SetDx(x); t2l.RotateZ(alp * RadToDeg()); - const TGeoHMatrix& l2gi = GetMatrixL2GIdeal().Inverse(); + const TGeoHMatrix& l2gi = getMatrixL2GIdeal().Inverse(); t2l.MultiplyLeft(&l2gi); /* - const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(GetVolID()); + const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(getVolID()); if (!t2l) { Print("long"); - AliFatalF("Failed to find T2L matrix for VID:%d %s",GetVolID(),GetSymName()); + AliFatalF("Failed to find T2L matrix for VID:%d %s",getVolID(),getSymName()); } */ - SetMatrixT2L(t2l); + setMatrixT2L(t2l); // } @@ -86,25 +86,25 @@ AliAlgPoint* AliAlgSensTOF::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr // TOF stores in the trackpoints X,Y with alignment applied but Z w/o alignment!!! // -> need special treatment unless data are already corrected // - AliAlgDetTOF* det = (AliAlgDetTOF*)GetDetector(); - AliAlgPoint* pnt = det->GetPointFromPool(); - pnt->SetSensor(this); + AliAlgDetTOF* det = (AliAlgDetTOF*)getDetector(); + AliAlgPoint* pnt = det->getPointFromPool(); + pnt->setSensor(this); // double tra[3], locId[3], loc[3], traId[3], glo[3] = {trpArr->GetX()[pntId], trpArr->GetY()[pntId], trpArr->GetZ()[pntId]}; - const TGeoHMatrix& matL2Grec = GetMatrixL2GReco(); // local to global matrix used for reconstruction - const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation + const TGeoHMatrix& matL2Grec = getMatrixL2GReco(); // local to global matrix used for reconstruction + const TGeoHMatrix& matT2L = getMatrixT2L(); // matrix for tracking to local frame translation // // >>>------------- here we fix the z by emulating Misalign action in the tracking frame ------>>> if (!trpArr->TestBit(AliTrackPointArray::kTOFBugFixed)) { // // we need reco-time alignment matrix in tracking frame, T^-1 * delta * T, where delta is local alignment matrix - TGeoHMatrix mClAlgTrec = GetMatrixClAlgReco(); - mClAlgTrec.Multiply(&GetMatrixT2L()); - const TGeoHMatrix& t2li = GetMatrixT2L().Inverse(); + TGeoHMatrix mClAlgTrec = getMatrixClAlgReco(); + mClAlgTrec.Multiply(&getMatrixT2L()); + const TGeoHMatrix& t2li = getMatrixT2L().Inverse(); mClAlgTrec.MultiplyLeft(&t2li); TGeoHMatrix mT2G; - GetMatrixT2G(mT2G); + getMatrixT2G(mT2G); mT2G.MasterToLocal(glo, tra); // we are in tracking frame, with original wrong alignment mClAlgTrec.MasterToLocal(tra, traId); // here we have almost ideal X,Y and wrong Z const double* trans = mClAlgTrec.GetTranslation(); @@ -119,15 +119,15 @@ AliAlgPoint* AliAlgSensTOF::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr // undo reco-time alignment matL2Grec.MasterToLocal(glo, locId); // go to local frame using reco-time matrix, here we recover ideal measurement // - GetMatrixClAlg().LocalToMaster(locId, loc); // apply alignment + getMatrixClAlg().LocalToMaster(locId, loc); // apply alignment // matT2L.MasterToLocal(loc, tra); // go to tracking frame // /* double gloT[3]; TGeoHMatrix t2g; - GetMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); - printf("\n%5d %s\n",GetVolID(), GetSymName()); + getMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); + printf("\n%5d %s\n",getVolID(), getSymName()); printf("GloOR: %+.4e %+.4e %+.4e\n",glo[0],glo[1],glo[2]); printf("LocID: %+.4e %+.4e %+.4e\n",locId[0],locId[1],locId[2]); printf("LocML: %+.4e %+.4e %+.4e\n",loc[0],loc[1],loc[2]); @@ -135,7 +135,7 @@ AliAlgPoint* AliAlgSensTOF::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr printf("GloTR: %+.4e %+.4e %+.4e\n",gloT[0],gloT[1],gloT[2]); */ // - if (!det->GetUseErrorParam()) { + if (!det->getUseErrorParam()) { // convert error TGeoHMatrix hcov; double hcovel[9]; @@ -158,21 +158,21 @@ AliAlgPoint* AliAlgSensTOF::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr hcov.MultiplyLeft(&t2li); // errors in tracking frame // double* hcovscl = hcov.GetRotationMatrix(); - const double* sysE = GetAddError(); // additional syst error - pnt->SetYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); + const double* sysE = getAddError(); // additional syst error + pnt->setYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); } else { // errors will be calculated just before using the point in the fit, using track info - pnt->SetYZErrTracking(0, 0, 0); - pnt->SetNeedUpdateFromTrack(); + pnt->setYZErrTracking(0, 0, 0); + pnt->setNeedUpdateFromTrack(); } - pnt->SetXYZTracking(tra[0], tra[1], tra[2]); - pnt->SetAlphaSens(GetAlpTracking()); - pnt->SetXSens(GetXTracking()); - pnt->SetDetID(det->GetDetID()); - pnt->SetSID(GetSID()); + pnt->setXYZTracking(tra[0], tra[1], tra[2]); + pnt->setAlphaSens(getAlpTracking()); + pnt->setXSens(getXTracking()); + pnt->setDetID(det->getDetID()); + pnt->setSID(getSID()); // - pnt->SetContainsMeasurement(); + pnt->setContainsMeasurement(); // - pnt->Init(); + pnt->init(); // return pnt; // diff --git a/Detectors/Align/src/AliAlgSensTPC.cxx b/Detectors/Align/src/AliAlgSensTPC.cxx index 54cb8dd698259..4362bbdabc707 100644 --- a/Detectors/Align/src/AliAlgSensTPC.cxx +++ b/Detectors/Align/src/AliAlgSensTPC.cxx @@ -45,35 +45,35 @@ AliAlgSensTPC::~AliAlgSensTPC() } /* //__________________________________________________________________ -void AliAlgSensTPC::SetTrackingFrame() +void AliAlgSensTPC::setTrackingFrame() { // define tracking frame of the sensor: just rotation by sector angle - fAlp = Sector2Alpha(fSector); + fAlp = sector2Alpha(fSector); fX = 0; } */ //____________________________________________ -void AliAlgSensTPC::PrepareMatrixT2L() +void AliAlgSensTPC::prepareMatrixT2L() { // extract from geometry T2L matrix - double alp = Sector2Alpha(fSector); + double alp = sector2Alpha(fSector); double loc[3] = {0, 0, 0}, glo[3]; - GetMatrixL2GIdeal().LocalToMaster(loc, glo); + getMatrixL2GIdeal().LocalToMaster(loc, glo); double x = Sqrt(glo[0] * glo[0] + glo[1] * glo[1]); TGeoHMatrix t2l; t2l.SetDx(x); t2l.RotateZ(alp * RadToDeg()); - const TGeoHMatrix& l2gi = GetMatrixL2GIdeal().Inverse(); + const TGeoHMatrix& l2gi = getMatrixL2GIdeal().Inverse(); t2l.MultiplyLeft(&l2gi); /* - const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(GetVolID()); + const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(getVolID()); if (!t2l) { Print("long"); - AliFatalF("Failed to find T2L matrix for VID:%d %s",GetVolID(),GetSymName()); + AliFatalF("Failed to find T2L matrix for VID:%d %s",getVolID(),getSymName()); } */ - SetMatrixT2L(t2l); + setMatrixT2L(t2l); // } @@ -82,27 +82,27 @@ AliAlgPoint* AliAlgSensTPC::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr { // convert the pntId-th point to AliAlgPoint // - AliAlgDet* det = GetDetector(); - AliAlgPoint* pnt = det->GetPointFromPool(); - pnt->SetSensor(this); + AliAlgDet* det = getDetector(); + AliAlgPoint* pnt = det->getPointFromPool(); + pnt->setSensor(this); // double tra[3], locId[3], loc[3], glo[3] = {trpArr->GetX()[pntId], trpArr->GetY()[pntId], trpArr->GetZ()[pntId]}; - const TGeoHMatrix& matL2Grec = GetMatrixL2GReco(); // local to global matrix used for reconstruction - const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation + const TGeoHMatrix& matL2Grec = getMatrixL2GReco(); // local to global matrix used for reconstruction + const TGeoHMatrix& matT2L = getMatrixT2L(); // matrix for tracking to local frame translation // // undo reco-time alignment matL2Grec.MasterToLocal(glo, locId); // go to local frame using reco-time matrix, here we recover ideal measurement // - GetMatrixClAlg().LocalToMaster(locId, loc); // apply alignment + getMatrixClAlg().LocalToMaster(locId, loc); // apply alignment // matT2L.MasterToLocal(loc, tra); // go to tracking frame // /* double gloT[3]; TGeoHMatrix t2g; - GetMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); - printf("\n%5d %s\n",GetVolID(), GetSymName()); + getMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); + printf("\n%5d %s\n",getVolID(), getSymName()); printf("GloOR: %+.4e %+.4e %+.4e\n",glo[0],glo[1],glo[2]); printf("LocID: %+.4e %+.4e %+.4e\n",locId[0],locId[1],locId[2]); printf("LocML: %+.4e %+.4e %+.4e\n",loc[0],loc[1],loc[2]); @@ -110,7 +110,7 @@ AliAlgPoint* AliAlgSensTPC::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr printf("GloTR: %+.4e %+.4e %+.4e\n",gloT[0],gloT[1],gloT[2]); */ // - if (!det->GetUseErrorParam()) { + if (!det->getUseErrorParam()) { // convert error TGeoHMatrix hcov; double hcovel[9]; @@ -133,21 +133,21 @@ AliAlgPoint* AliAlgSensTPC::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr hcov.MultiplyLeft(&t2li); // errors in tracking frame // double* hcovscl = hcov.GetRotationMatrix(); - const double* sysE = GetAddError(); // additional syst error - pnt->SetYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); + const double* sysE = getAddError(); // additional syst error + pnt->setYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); } else { // errors will be calculated just before using the point in the fit, using track info - pnt->SetYZErrTracking(0, 0, 0); - pnt->SetNeedUpdateFromTrack(); + pnt->setYZErrTracking(0, 0, 0); + pnt->setNeedUpdateFromTrack(); } - pnt->SetXYZTracking(tra[0], tra[1], tra[2]); - pnt->SetAlphaSens(GetAlpTracking()); - pnt->SetXSens(GetXTracking()); - pnt->SetDetID(det->GetDetID()); - pnt->SetSID(GetSID()); + pnt->setXYZTracking(tra[0], tra[1], tra[2]); + pnt->setAlphaSens(getAlpTracking()); + pnt->setXSens(getXTracking()); + pnt->setDetID(det->getDetID()); + pnt->setSID(getSID()); // - pnt->SetContainsMeasurement(); + pnt->setContainsMeasurement(); // - pnt->Init(); + pnt->init(); // return pnt; // diff --git a/Detectors/Align/src/AliAlgSensTRD.cxx b/Detectors/Align/src/AliAlgSensTRD.cxx index 68045914f18e1..a278e1a990c20 100644 --- a/Detectors/Align/src/AliAlgSensTRD.cxx +++ b/Detectors/Align/src/AliAlgSensTRD.cxx @@ -47,40 +47,40 @@ AliAlgSensTRD::~AliAlgSensTRD() } /* //__________________________________________________________________ -void AliAlgSensTRD::SetTrackingFrame() +void AliAlgSensTRD::setTrackingFrame() { // define tracking frame of the sensor: just rotation by sector angle - fAlp = Sector2Alpha(fSector); + fAlp = sector2Alpha(fSector); fX = 0; } */ //____________________________________________ -void AliAlgSensTRD::PrepareMatrixT2L() +void AliAlgSensTRD::prepareMatrixT2L() { // extract from geometry T2L matrix - double alp = Sector2Alpha(fSector); + double alp = sector2Alpha(fSector); double loc[3] = {0, 0, 0}, glo[3]; - GetMatrixL2GIdeal().LocalToMaster(loc, glo); + getMatrixL2GIdeal().LocalToMaster(loc, glo); double x = Sqrt(glo[0] * glo[0] + glo[1] * glo[1]); TGeoHMatrix t2l; t2l.SetDx(x); t2l.RotateZ(alp * RadToDeg()); - const TGeoHMatrix& l2gi = GetMatrixL2GIdeal().Inverse(); + const TGeoHMatrix& l2gi = getMatrixL2GIdeal().Inverse(); t2l.MultiplyLeft(&l2gi); /* - const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(GetVolID()); + const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(getVolID()); if (!t2l) { Print("long"); - AliFatalF("Failed to find T2L matrix for VID:%d %s",GetVolID(),GetSymName()); + AliFatalF("Failed to find T2L matrix for VID:%d %s",getVolID(),getSymName()); } */ - SetMatrixT2L(t2l); + setMatrixT2L(t2l); // } //____________________________________________ -void AliAlgSensTRD::DPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int calibID, const AliAlgVol* parent) const +void AliAlgSensTRD::dPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int calibID, const AliAlgVol* parent) const { // calculate point position X,Y,Z derivatives wrt calibration parameter calibID of given parent // parent=0 means top detector object calibration @@ -91,10 +91,10 @@ void AliAlgSensTRD::DPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int // switch (calibID) { case AliAlgDetTRD::kCalibNRCCorrDzDtgl: { // correction for Non-Crossing tracklets Z,Y shift: Z -> Z + calib*tgl, Y -> Y + calib*tgl*tilt*sign(tilt); - double sgYZ = pnt->GetYZErrTracking()[1]; // makes sense only for nonRC tracklets + double sgYZ = pnt->getYZErrTracking()[1]; // makes sense only for nonRC tracklets if (Abs(sgYZ) > 0.01) { const double kTilt = 2. * TMath::DegToRad(); - deriv[2] = pnt->GetTrParamWSA()[AliAlgPoint::kParTgl]; + deriv[2] = pnt->getTrParamWSA()[AliAlgPoint::kParTgl]; deriv[1] = deriv[2] * Sign(kTilt, sgYZ); } break; @@ -103,7 +103,7 @@ void AliAlgSensTRD::DPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int case AliAlgDetTRD::kCalibDVT: { // correction for bias in VdriftT // error in VdriftT equivalent to shift in X at which Y measurement is evaluated // Y -> Y + dVdriftT * tg_phi, where tg_phi is the slope of the track in YX plane - double snp = pnt->GetTrParamWSA(AliAlgPoint::kParSnp), slpY = snp / Sqrt((1 - snp) * (1 + snp)); + double snp = pnt->getTrParamWSA(AliAlgPoint::kParSnp), slpY = snp / Sqrt((1 - snp) * (1 + snp)); deriv[1] = slpY; break; } @@ -120,27 +120,27 @@ AliAlgPoint* AliAlgSensTRD::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr { // convert the pntId-th point to AliAlgPoint // - AliAlgDetTRD* det = (AliAlgDetTRD*)GetDetector(); - AliAlgPoint* pnt = det->GetPointFromPool(); - pnt->SetSensor(this); + AliAlgDetTRD* det = (AliAlgDetTRD*)getDetector(); + AliAlgPoint* pnt = det->getPointFromPool(); + pnt->setSensor(this); // double tra[3], locId[3], loc[3], glo[3] = {trpArr->GetX()[pntId], trpArr->GetY()[pntId], trpArr->GetZ()[pntId]}; - const TGeoHMatrix& matL2Grec = GetMatrixL2GReco(); // local to global matrix used for reconstruction - const TGeoHMatrix& matT2L = GetMatrixT2L(); // matrix for tracking to local frame translation + const TGeoHMatrix& matL2Grec = getMatrixL2GReco(); // local to global matrix used for reconstruction + const TGeoHMatrix& matT2L = getMatrixT2L(); // matrix for tracking to local frame translation // // undo reco-time alignment matL2Grec.MasterToLocal(glo, locId); // go to local frame using reco-time matrix, here we recover ideal measurement // - GetMatrixClAlg().LocalToMaster(locId, loc); // apply alignment + getMatrixClAlg().LocalToMaster(locId, loc); // apply alignment // matT2L.MasterToLocal(loc, tra); // go to tracking frame // /* double gloT[3]; TGeoHMatrix t2g; - GetMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); - printf("\n%5d %s\n",GetVolID(), GetSymName()); + getMatrixT2G(t2g); t2g.LocalToMaster(tra,gloT); + printf("\n%5d %s\n",getVolID(), getSymName()); printf("GloOR: %+.4e %+.4e %+.4e\n",glo[0],glo[1],glo[2]); printf("LocID: %+.4e %+.4e %+.4e\n",locId[0],locId[1],locId[2]); printf("LocML: %+.4e %+.4e %+.4e\n",loc[0],loc[1],loc[2]); @@ -148,7 +148,7 @@ AliAlgPoint* AliAlgSensTRD::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr printf("GloTR: %+.4e %+.4e %+.4e\n",gloT[0],gloT[1],gloT[2]); */ // - if (!det->GetUseErrorParam()) { + if (!det->getUseErrorParam()) { // convert error TGeoHMatrix hcov; double hcovel[9]; @@ -171,26 +171,26 @@ AliAlgPoint* AliAlgSensTRD::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr hcov.MultiplyLeft(&t2li); // errors in tracking frame // double* hcovscl = hcov.GetRotationMatrix(); - const double* sysE = GetAddError(); // additional syst error - pnt->SetYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); + const double* sysE = getAddError(); // additional syst error + pnt->setYZErrTracking(hcovscl[4] + sysE[0] * sysE[0], hcovscl[5], hcovscl[8] + sysE[1] * sysE[1]); } else { // errors will be calculated just before using the point in the fit, using track info - pnt->SetYZErrTracking(0, 0, 0); - pnt->SetNeedUpdateFromTrack(); + pnt->setYZErrTracking(0, 0, 0); + pnt->setNeedUpdateFromTrack(); } - pnt->SetXYZTracking(tra[0], tra[1], tra[2]); - pnt->SetAlphaSens(GetAlpTracking()); - pnt->SetXSens(GetXTracking()); - pnt->SetDetID(det->GetDetID()); - pnt->SetSID(GetSID()); + pnt->setXYZTracking(tra[0], tra[1], tra[2]); + pnt->setAlphaSens(getAlpTracking()); + pnt->setXSens(getXTracking()); + pnt->setDetID(det->getDetID()); + pnt->setSID(getSID()); // - pnt->SetContainsMeasurement(); + pnt->setContainsMeasurement(); // // Apply calibrations // Correction for NonRC points to account for most probable Z for non-crossing { const double kTilt = 2. * TMath::DegToRad(); // is it pad crrossing? - double* errYZ = (double*)pnt->GetYZErrTracking(); + double* errYZ = (double*)pnt->getYZErrTracking(); double sgYZ = errYZ[1]; if (TMath::Abs(sgYZ) < 0.01) { // crossing // increase errors since the error @@ -198,7 +198,7 @@ AliAlgPoint* AliAlgSensTRD::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr errYZ[0] += extraErrRC[0] * extraErrRC[0]; errYZ[2] += extraErrRC[1] * extraErrRC[1]; } else { // account for probability to not cross the row - double* pYZ = (double*)pnt->GetYZTracking(); + double* pYZ = (double*)pnt->getYZTracking(); double corrZ = det->GetNonRCCorrDzDtglWithCal() * tr->GetTgl(); pYZ[1] += corrZ; pYZ[0] += corrZ * Sign(kTilt, sgYZ); // Y and Z are correlated @@ -210,18 +210,18 @@ AliAlgPoint* AliAlgSensTRD::TrackPoint2AlgPoint(int pntId, const AliTrackPointAr double dvt = det->GetCorrDVTWithCal(); if (Abs(dvt) > kAlmostZeroD) { AliExternalTrackParam trc = *tr; - if (!trc.RotateParamOnly(GetAlpTracking())) + if (!trc.RotateParamOnly(getAlpTracking())) return 0; - double snp = trc.GetSnpAt(pnt->GetXPoint(), AliTrackerBase::GetBz()); + double snp = trc.GetSnpAt(pnt->getXPoint(), AliTrackerBase::GetBz()); if (Abs(snp) > kAlmostOneD) return 0; double slpY = snp / Sqrt((1 - snp) * (1 + snp)); - double* pYZ = (double*)pnt->GetYZTracking(); + double* pYZ = (double*)pnt->getYZTracking(); pYZ[0] += dvt * slpY; } } // - pnt->Init(); + pnt->init(); // return pnt; // diff --git a/Detectors/Align/src/AliAlgSteer.cxx b/Detectors/Align/src/AliAlgSteer.cxx index 1d53997f25c6d..4cd6fe7e84a40 100644 --- a/Detectors/Align/src/AliAlgSteer.cxx +++ b/Detectors/Align/src/AliAlgSteer.cxx @@ -64,113 +64,113 @@ namespace o2 namespace align { -const char* AliAlgSteer::fgkMPDataExt = ".mille"; -const char* AliAlgSteer::fgkDetectorName[AliAlgSteer::kNDetectors] = {"ITS", "TPC", "TRD", "TOF", "HMPID"}; -//const int AliAlgSteer::fgkSkipLayers[AliAlgSteer::kNLrSkip] = {AliGeomManager::kPHOS1, AliGeomManager::kPHOS2, +const Char_t* AliAlgSteer::sMPDataExt = ".mille"; +const Char_t* AliAlgSteer::sDetectorName[AliAlgSteer::kNDetectors] = {"ITS", "TPC", "TRD", "TOF", "HMPID"}; +//const int AliAlgSteer::mgkSkipLayers[AliAlgSteer::kNLrSkip] = {AliGeomManager::kPHOS1, AliGeomManager::kPHOS2, // AliGeomManager::kMUON, AliGeomManager::kEMCAL}; TODO(milettri, shahoian): needs detector IDs previously stored in AliGeomManager -const int AliAlgSteer::fgkSkipLayers[AliAlgSteer::kNLrSkip] = {0, 0, 0, 0}; // TODO(milettri, shahoian): needs AliGeomManager - remove this line after fix. +const int AliAlgSteer::sSkipLayers[AliAlgSteer::kNLrSkip] = {0, 0, 0, 0}; // TODO(milettri, shahoian): needs AliGeomManager - remove this line after fix. -const char* AliAlgSteer::fgkStatClName[AliAlgSteer::kNStatCl] = {"Inp: ", "Acc: "}; -const char* AliAlgSteer::fgkStatName[AliAlgSteer::kMaxStat] = +const Char_t* AliAlgSteer::sStatClName[AliAlgSteer::kNStatCl] = {"Inp: ", "Acc: "}; +const Char_t* AliAlgSteer::sStatName[AliAlgSteer::kMaxStat] = {"runs", "Ev.Coll", "Ev.Cosm", "Trc.Coll", "Trc.Cosm"}; -const char* AliAlgSteer::fgkHStatName[AliAlgSteer::kNHVars] = { +const Char_t* AliAlgSteer::sHStatName[AliAlgSteer::kNHVars] = { "Runs", "Ev.Inp", "Ev.VtxOK", "Tr.Inp", "Tr.2Fit", "Tr.2FitVC", "Tr.2PrMat", "Tr.2ResDer", "Tr.Stored", "Tr.Acc", "Tr.ContRes"}; //________________________________________________________________ AliAlgSteer::AliAlgSteer(const char* configMacro, int refRun) - : fNDet(0), fNDOFs(0), fRunNumber(-1), fFieldOn(false), fTracksType(kColl), fAlgTrack(0), fVtxSens(0), fConstraints(), + : mNDet(0), mNDOFs(0), mRunNumber(-1), mFieldOn(false), mTracksType(kColl), mAlgTrack(0), mVtxSens(0), mConstraints(), // fSelEventSpecii(AliRecoParam::kCosmic | AliRecoParam::kLowMult | AliRecoParam::kHighMult | AliRecoParam::kDefault), FIXME(milettri): needs AliRecoParam - fSelEventSpecii(0), // FIXME(milettri): needs AliRecoParam - fCosmicSelStrict(false), - fVtxMinCont(-1), - fVtxMaxCont(-1), - fVtxMinContVC(10), - fMinITSClforVC(3), - // fITSPattforVC(AliAlgDetITS::kSPDAny), FIXME(milettri): needs AliAlgDetITS - fITSPattforVC(0), // FIXME(milettri): needs AliAlgDetITS - fMaxChi2forVC(10) + mSelEventSpecii(0), // FIXME(milettri): needs AliRecoParam + mCosmicSelStrict(false), + mVtxMinCont(-1), + mVtxMaxCont(-1), + mVtxMinContVC(10), + mMinITSClforVC(3), + // mITSPattforVC(AliAlgDetITS::kSPDAny), FIXME(milettri): needs AliAlgDetITS + mITSPattforVC(0), // FIXME(milettri): needs AliAlgDetITS + mMaxChi2forVC(10) // , - fGloParVal(0), - fGloParErr(0), - fGloParLab(0), - fOrderedLbl(0), - fLbl2ID(0), - fRefPoint(0), - fESDTree(0), + mGloParVal(0), + mGloParErr(0), + mGloParLab(0), + mOrderedLbl(0), + mLbl2ID(0), + mRefPoint(0), + mESDTree(0), // fESDEvent(0), FIXME(milettri): needs AliESDEvent // fVertex(0), FIXME(milettri): needs AliESDVertex - fControlFrac(1.0), - fMPOutType(kMille | kMPRec | kContR), - fMille(0), - fMPRecord(0), - fCResid(0), - fMPRecTree(0), - fResidTree(0), - fMPRecFile(0), - fResidFile(0), - fMilleDBuffer(), - fMilleIBuffer(), - fMPDatFileName("mpData"), - fMPParFileName("mpParams.txt"), - fMPConFileName("mpConstraints.txt"), - fMPSteerFileName("mpSteer.txt"), - fResidFileName("mpControlRes.root"), - fMilleOutBin(true), - fDoKalmanResid(true) + mControlFrac(1.0), + mMPOutType(kMille | kMPRec | kContR), + mMille(0), + mMPRecord(0), + mCResid(0), + mMPRecTree(0), + mResidTree(0), + mMPRecFile(0), + mResidFile(0), + mMilleDBuffer(), + mMilleIBuffer(), + mMPDatFileName("mpData"), + mMPParFileName("mpParams.txt"), + mMPConFileName("mpConstraints.txt"), + mMPSteerFileName("mpSteer.txt"), + mResidFileName("mpControlRes.root"), + mMilleOutBin(true), + mDoKalmanResid(true) // , - fOutCDBPath("local://outOCDB"), - fOutCDBComment("AliAlgSteer"), - fOutCDBResponsible("") + mOutCDBPath("local://outOCDB"), + mOutCDBComment("AliAlgSteer"), + mOutCDBResponsible("") // , - fDOFStat(0), - fHistoStat(0) + mDOFStat(0), + mHistoStat(0) // , - fConfMacroName(configMacro), - fRecoOCDBConf("configRecoOCDB.C"), - fRefOCDBConf("configRefOCDB.C"), - fRefRunNumber(refRun), - fRefOCDBLoaded(0), - fUseRecoOCDB(true) + mConfMacroName(configMacro), + mRecoOCDBConf("configRecoOCDB.C"), + mRefOCDBConf("configRefOCDB.C"), + mRefRunNumber(refRun), + mRefOCDBLoaded(0), + mUseRecoOCDB(true) { // def c-tor for (int i = kNDetectors; i--;) { - fDetectors[i] = 0; - fDetPos[i] = -1; + mDetectors[i] = 0; + mDetPos[i] = -1; } - SetPtMinColl(); - SetPtMinCosm(); - SetEtaMaxColl(); - SetEtaMaxCosm(); - SetMinDetAccColl(); - SetMinDetAccCosm(); + setPtMinColl(); + setPtMinCosm(); + setEtaMaxColl(); + setEtaMaxCosm(); + setMinDetAccColl(); + setMinDetAccCosm(); for (int i = 0; i < kNTrackTypes; i++) { - fObligatoryDetPattern[i] = 0; + mObligatoryDetPattern[i] = 0; } // - SetMinPointsColl(); - SetMinPointsCosm(); + setMinPointsColl(); + setMinPointsCosm(); // for (int i = kNCosmLegs; i--;) // fESDTrack[i] = 0; FIXME(milettri): needs AliESDtrack - memset(fStat, 0, kNStatCl * kMaxStat * sizeof(float)); - SetMaxDCAforVC(); - SetMaxChi2forVC(); + memset(mStat, 0, kNStatCl * kMaxStat * sizeof(float)); + setMaxDCAforVC(); + setMaxChi2forVC(); // SetOutCDBRunRange(); FIXME(milettri): needs OCDB - SetDefPtBOffCosm(); - SetDefPtBOffColl(); + setDefPtBOffCosm(); + setDefPtBOffColl(); // // run config macro if provided - if (!fConfMacroName.IsNull()) { - gROOT->ProcessLine(Form(".x %s+g((AliAlgSteer*)%p)", fConfMacroName.Data(), this)); - if (!GetInitDOFsDone()) - InitDOFs(); - if (!GetNDOFs()) - LOG(FATAL) << "No DOFs found, initialization with " << fConfMacroName.Data() << " failed"; + if (!mConfMacroName.IsNull()) { + gROOT->ProcessLine(Form(".x %s+g((AliAlgSteer*)%p)", mConfMacroName.Data(), this)); + if (!getInitDOFsDone()) + initDOFs(); + if (!getNDOFs()) + LOG(FATAL) << "No DOFs found, initialization with " << mConfMacroName.Data() << " failed"; } } @@ -178,172 +178,172 @@ AliAlgSteer::AliAlgSteer(const char* configMacro, int refRun) AliAlgSteer::~AliAlgSteer() { // d-tor - if (fMPRecFile) - CloseMPRecOutput(); - if (fMille) - CloseMilleOutput(); - if (fResidFile) - CloseResidOutput(); - // - delete fAlgTrack; - delete[] fGloParVal; - delete[] fGloParErr; - delete[] fGloParLab; - for (int i = 0; i < fNDet; i++) - delete fDetectors[i]; - delete fVtxSens; - delete fRefPoint; - delete fDOFStat; - delete fHistoStat; + if (mMPRecFile) + closeMPRecOutput(); + if (mMille) + closeMilleOutput(); + if (mResidFile) + closeResidOutput(); + // + delete mAlgTrack; + delete[] mGloParVal; + delete[] mGloParErr; + delete[] mGloParLab; + for (int i = 0; i < mNDet; i++) + delete mDetectors[i]; + delete mVtxSens; + delete mRefPoint; + delete mDOFStat; + delete mHistoStat; // } //________________________________________________________________ -void AliAlgSteer::InitDetectors() +void AliAlgSteer::initDetectors() { // init all detectors geometry // - if (GetInitGeomDone()) + if (getInitGeomDone()) return; // // - fAlgTrack = new AliAlgTrack(); - fRefPoint = new AliAlgPoint(); + mAlgTrack = new AliAlgTrack(); + mRefPoint = new AliAlgPoint(); // int dofCnt = 0; // special fake sensor for vertex constraint point // it has special T2L matrix adjusted for each track, no need to init it here - fVtxSens = new AliAlgVtx(); - fVtxSens->SetInternalID(1); - fVtxSens->PrepareMatrixL2G(); - fVtxSens->PrepareMatrixL2GIdeal(); - dofCnt += fVtxSens->GetNDOFs(); - // - for (int i = 0; i < fNDet; i++) - dofCnt += fDetectors[i]->InitGeom(); + mVtxSens = new AliAlgVtx(); + mVtxSens->setInternalID(1); + mVtxSens->prepareMatrixL2G(); + mVtxSens->prepareMatrixL2GIdeal(); + dofCnt += mVtxSens->getNDOFs(); + // + for (int i = 0; i < mNDet; i++) + dofCnt += mDetectors[i]->initGeom(); if (!dofCnt) LOG(FATAL) << "No DOFs found"; // // for (int idt = 0; idt < kNDetectors; idt++) { - AliAlgDet* det = GetDetectorByDetID(idt); - if (!det || det->IsDisabled()) + AliAlgDet* det = getDetectorByDetID(idt); + if (!det || det->isDisabled()) continue; - det->CacheReferenceOCDB(); + det->cacheReferenceOCDB(); } // - fGloParVal = new float[dofCnt]; - fGloParErr = new float[dofCnt]; - fGloParLab = new int[dofCnt]; - fOrderedLbl = new int[dofCnt]; - fLbl2ID = new int[dofCnt]; - memset(fGloParVal, 0, dofCnt * sizeof(float)); - memset(fGloParErr, 0, dofCnt * sizeof(float)); - memset(fGloParLab, 0, dofCnt * sizeof(int)); - memset(fOrderedLbl, 0, dofCnt * sizeof(int)); - memset(fLbl2ID, 0, dofCnt * sizeof(int)); - AssignDOFs(); + mGloParVal = new float[dofCnt]; + mGloParErr = new float[dofCnt]; + mGloParLab = new int[dofCnt]; + mOrderedLbl = new int[dofCnt]; + mLbl2ID = new int[dofCnt]; + memset(mGloParVal, 0, dofCnt * sizeof(float)); + memset(mGloParErr, 0, dofCnt * sizeof(float)); + memset(mGloParLab, 0, dofCnt * sizeof(int)); + memset(mOrderedLbl, 0, dofCnt * sizeof(int)); + memset(mLbl2ID, 0, dofCnt * sizeof(int)); + assignDOFs(); LOG(INFO) << "Booked " << dofCnt << " global parameters"; // - SetInitGeomDone(); + setInitGeomDone(); // } //________________________________________________________________ -void AliAlgSteer::InitDOFs() +void AliAlgSteer::initDOFs() { // scan all free global parameters, link detectors to array of params // - if (GetInitDOFsDone()) { - LOG(INFO) << "InitDOFs was already done, just reassigning " << fNDOFs << "DOFs arrays/labels"; - AssignDOFs(); + if (getInitDOFsDone()) { + LOG(INFO) << "initDOFs was already done, just reassigning " << mNDOFs << "DOFs arrays/labels"; + assignDOFs(); return; } // - fNDOFs = 0; + mNDOFs = 0; int ndfAct = 0; - AssignDOFs(); + assignDOFs(); // int nact = 0; - fVtxSens->InitDOFs(); - for (int i = 0; i < fNDet; i++) { - AliAlgDet* det = GetDetector(i); - det->InitDOFs(); - if (det->IsDisabled()) + mVtxSens->initDOFs(); + for (int i = 0; i < mNDet; i++) { + AliAlgDet* det = getDetector(i); + det->initDOFs(); + if (det->isDisabled()) continue; nact++; - ndfAct += det->GetNDOFs(); + ndfAct += det->getNDOFs(); } for (int i = 0; i < kNTrackTypes; i++) - if (nact < fMinDetAcc[i]) - LOG(FATAL) << nact << " detectors are active, while " << fMinDetAcc[i] << " in track are asked"; + if (nact < mMinDetAcc[i]) + LOG(FATAL) << nact << " detectors are active, while " << mMinDetAcc[i] << " in track are asked"; // - LOG(INFO) << fNDOFs << " global parameters " << fNDet << " detectors, " << ndfAct << " in " << nact << " active detectors"; + LOG(INFO) << mNDOFs << " global parameters " << mNDet << " detectors, " << ndfAct << " in " << nact << " active detectors"; // - AddAutoConstraints(); + addAutoConstraints(); // - SetInitDOFsDone(); + setInitDOFsDone(); } //________________________________________________________________ -void AliAlgSteer::AssignDOFs() +void AliAlgSteer::assignDOFs() { // add parameters/labels arrays to volumes. If the AliAlgSteer is read from the file, this method need - // to be called (of InitDOFs should be called) + // to be called (of initDOFs should be called) // int ndfOld = -1; - if (fNDOFs > 0) - ndfOld = fNDOFs; - fNDOFs = 0; + if (mNDOFs > 0) + ndfOld = mNDOFs; + mNDOFs = 0; // - fVtxSens->AssignDOFs(fNDOFs, fGloParVal, fGloParErr, fGloParLab); + mVtxSens->assignDOFs(mNDOFs, mGloParVal, mGloParErr, mGloParLab); // for (int idt = 0; idt < kNDetectors; idt++) { - AliAlgDet* det = GetDetectorByDetID(idt); + AliAlgDet* det = getDetectorByDetID(idt); if (!det) continue; - //if (det->IsDisabled()) continue; - fNDOFs += det->AssignDOFs(); + //if (det->isDisabled()) continue; + mNDOFs += det->assignDOFs(); } - LOG(INFO) << "Assigned parameters/labels arrays for " << fNDOFs << " DOFs"; - if (ndfOld > -1 && ndfOld != fNDOFs) - LOG(ERROR) << "Recalculated NDOFs=" << fNDOFs << " not equal to saved NDOFs=" << ndfOld; + LOG(INFO) << "Assigned parameters/labels arrays for " << mNDOFs << " DOFs"; + if (ndfOld > -1 && ndfOld != mNDOFs) + LOG(ERROR) << "Recalculated NDOFs=" << mNDOFs << " not equal to saved NDOFs=" << ndfOld; // // build Lbl <-> parID table - Sort(fNDOFs, fGloParLab, fLbl2ID, false); // sort in increasing order - for (int i = fNDOFs; i--;) - fOrderedLbl[i] = fGloParLab[fLbl2ID[i]]; + Sort(mNDOFs, mGloParLab, mLbl2ID, false); // sort in increasing order + for (int i = mNDOFs; i--;) + mOrderedLbl[i] = mGloParLab[mLbl2ID[i]]; // } //________________________________________________________________ -void AliAlgSteer::AddDetector(uint32_t id, AliAlgDet* det) +void AliAlgSteer::addDetector(uint32_t id, AliAlgDet* det) { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; // add detector participating in the alignment, optionally constructed externally // - if (!fRefOCDBLoaded) + if (!mRefOCDBLoaded) // LoadRefOCDB(); FIXME(milettri): needs OCDB // if (id >= kNDetectors) LOG(FATAL) << "Detector typeID " << id << " exceeds allowed range " << 0 << ":" << (kNDetectors - 1); // - if (fDetPos[id] != -1) + if (mDetPos[id] != -1) LOG(FATAL) << "Detector " << id << " was already added"; if (!det) { switch (id) { // case kITS: - // det = new AliAlgDetITS(GetDetNameByDetID(kITS)); FIXME(milettri): needs AliAlgDetITS + // det = new AliAlgDetITS(getDetNameByDetID(kITS)); FIXME(milettri): needs AliAlgDetITS // break; // case kTPC: - // det = new AliAlgDetTPC(GetDetNameByDetID(kTPC)); FIXME(milettri): needs AliAlgDetTPC + // det = new AliAlgDetTPC(getDetNameByDetID(kTPC)); FIXME(milettri): needs AliAlgDetTPC // break; // case kTRD: - // det = new AliAlgDetTRD(GetDetNameByDetID(kTRD)); FIXME(milettri): needs AliAlgDetTRD + // det = new AliAlgDetTRD(getDetNameByDetID(kTRD)); FIXME(milettri): needs AliAlgDetTRD // break; // case kTOF: - // det = new AliAlgDetTOF(GetDetNameByDetID(kTOF)); FIXME(milettri): needs AliAlgDetTOF + // det = new AliAlgDetTOF(getDetNameByDetID(kTOF)); FIXME(milettri): needs AliAlgDetTOF // break; default: LOG(FATAL) << id << " not implemented yet"; @@ -351,48 +351,48 @@ void AliAlgSteer::AddDetector(uint32_t id, AliAlgDet* det) }; } // - fDetectors[fNDet] = det; - fDetPos[id] = fNDet; - det->SetAlgSteer(this); + mDetectors[mNDet] = det; + mDetPos[id] = mNDet; + det->setAlgSteer(this); for (int i = 0; i < kNTrackTypes; i++) - SetObligatoryDetector(id, i, det->IsObligatory(i)); - fNDet++; + setObligatoryDetector(id, i, det->isObligatory(i)); + mNDet++; // } //_________________________________________________________ -void AliAlgSteer::AddDetector(AliAlgDet* det) +void AliAlgSteer::addDetector(AliAlgDet* det) { // add detector constructed externally to alignment framework - AddDetector(det->GetDetID(), det); + addDetector(det->getDetID(), det); } //_________________________________________________________ -bool AliAlgSteer::CheckDetectorPattern(uint32_t patt) const +bool AliAlgSteer::checkDetectorPattern(uint32_t patt) const { //validate detector pattern - return ((patt & fObligatoryDetPattern[fTracksType]) == - fObligatoryDetPattern[fTracksType]) && - NumberOfBitsSet(patt) >= fMinDetAcc[fTracksType]; + return ((patt & mObligatoryDetPattern[mTracksType]) == + mObligatoryDetPattern[mTracksType]) && + numberOfBitsSet(patt) >= mMinDetAcc[mTracksType]; } //_________________________________________________________ -bool AliAlgSteer::CheckDetectorPoints(const int* npsel) const +bool AliAlgSteer::checkDetectorPoints(const int* npsel) const { //validate detectors pattern according to number of selected points int ndOK = 0; for (int idt = 0; idt < kNDetectors; idt++) { - AliAlgDet* det = GetDetectorByDetID(idt); - if (!det || det->IsDisabled(fTracksType)) + AliAlgDet* det = getDetectorByDetID(idt); + if (!det || det->isDisabled(mTracksType)) continue; - if (npsel[idt] < det->GetNPointsSel(fTracksType)) { - if (det->IsObligatory(fTracksType)) + if (npsel[idt] < det->getNPointsSel(mTracksType)) { + if (det->isObligatory(mTracksType)) return false; continue; } ndOK++; } - return ndOK >= fMinDetAcc[fTracksType]; + return ndOK >= mMinDetAcc[mTracksType]; } //FIXME(milettri): needs AliESDtrack @@ -402,16 +402,16 @@ bool AliAlgSteer::CheckDetectorPoints(const int* npsel) const // // decide if the track should be processed // AliAlgDet* det = 0; // uint32_t detAcc = 0; -// if (fFieldOn && esdTr->Pt() < fPtMin[fTracksType]) +// if (mFieldOn && esdTr->Pt() < mPtMin[mTracksType]) // return 0; -// if (Abs(esdTr->Eta()) > fEtaMax[fTracksType]) +// if (Abs(esdTr->Eta()) > mEtaMax[mTracksType]) // return 0; // // // for (int idet = 0; idet < kNDetectors; idet++) { -// if (!(det = GetDetectorByDetID(idet)) || det->IsDisabled(fTracksType)) +// if (!(det = getDetectorByDetID(idet)) || det->isDisabled(mTracksType)) // continue; -// if (!det->AcceptTrack(esdTr, fTracksType)) { -// if (strict && det->IsObligatory(fTracksType)) +// if (!det->AcceptTrack(esdTr, mTracksType)) { +// if (strict && det->isObligatory(mTracksType)) // return 0; // else // continue; @@ -419,7 +419,7 @@ bool AliAlgSteer::CheckDetectorPoints(const int* npsel) const // // // detAcc |= 0x1 << idet; // } -// if (NumberOfBitsSet(detAcc) < fMinDetAcc[fTracksType]) +// if (numberOfBitsSet(detAcc) < mMinDetAcc[mTracksType]) // return 0; // return detAcc; // // @@ -432,16 +432,16 @@ bool AliAlgSteer::CheckDetectorPoints(const int* npsel) const // // decide if the pair of tracks making cosmic track should be processed // uint32_t detAcc = 0, detAccLeg; // for (int i = kNCosmLegs; i--;) { -// detAccLeg = AcceptTrack(esdPairCosm[i], fCosmicSelStrict); // missing obligatory detectors in one leg might be allowed +// detAccLeg = AcceptTrack(esdPairCosm[i], mCosmicSelStrict); // missing obligatory detectors in one leg might be allowed // if (!detAccLeg) // return 0; // detAcc |= detAccLeg; // } -// if (fCosmicSelStrict) +// if (mCosmicSelStrict) // return detAcc; // // // // for non-stric selection check convolution of detector presence -// if (!CheckDetectorPattern(detAcc)) +// if (!checkDetectorPattern(detAcc)) // return 0; // return detAcc; // // @@ -456,7 +456,7 @@ bool AliAlgSteer::CheckDetectorPoints(const int* npsel) const // // setup magnetic field if needed // if (fESDEvent && // (!TGeoGlobalMagField::Instance()->GetField() || -// !SmallerAbs(fESDEvent->GetMagneticField() - AliTrackerBase::GetBz(), 5e-4))) { +// !smallerAbs(fESDEvent->GetMagneticField() - AliTrackerBase::GetBz(), 5e-4))) { // fESDEvent->InitMagneticField(); // } //} @@ -477,8 +477,8 @@ bool AliAlgSteer::CheckDetectorPoints(const int* npsel) const // // // SetESDEvent(esdEv); // // -// if (esdEv->GetRunNumber() != GetRunNumber()) -// SetRunNumber(esdEv->GetRunNumber()); +// if (esdEv->getRunNumber() != getRunNumber()) +// SetRunNumber(esdEv->getRunNumber()); // // // if (!(esdEv->GetEventSpecie() & fSelEventSpecii)) { //#if DEBUG > 2 @@ -487,53 +487,53 @@ bool AliAlgSteer::CheckDetectorPoints(const int* npsel) const // return false; // } // // -// SetCosmic(esdEv->GetEventSpecie() == AliRecoParam::kCosmic || +// setCosmic(esdEv->GetEventSpecie() == AliRecoParam::kCosmic || // (esdEv->GetNumberOfCosmicTracks() > 0 && !esdEv->GetPrimaryVertexTracks()->GetStatus())); // // -// FillStatHisto(kEvInp); +// fillStatHisto(kEvInp); // // //#if DEBUG > 2 // LOG << "Processing event " << esdEv->GetEventNumberInFile() << " of ev.specie " << esdEv->GetEventSpecie() << " -> Ntr: " << esdEv->GetNumberOfTracks() << " NtrCosm: " << esdEv->GetNumberOfCosmicTracks(); //#endif // // -// SetFieldOn(Abs(esdEv->GetMagneticField()) > kAlmost0Field); -// if (!IsCosmic() && !CheckSetVertex(esdEv->GetPrimaryVertexTracks())) +// setFieldOn(Abs(esdEv->GetMagneticField()) > kAlmost0Field); +// if (!isCosmic() && !CheckSetVertex(esdEv->GetPrimaryVertexTracks())) // return false; -// FillStatHisto(kEvVtx); +// fillStatHisto(kEvVtx); // // // int ntr = 0, accTr = 0; -// if (IsCosmic()) { -// fStat[kInpStat][kEventCosm]++; +// if (isCosmic()) { +// mStat[kInpStat][kEventCosm]++; // ntr = esdEv->GetNumberOfCosmicTracks(); -// FillStatHisto(kTrackInp, ntr); +// fillStatHisto(kTrackInp, ntr); // for (int itr = 0; itr < ntr; itr++) { // accTr += ProcessTrack(esdEv->GetCosmicTrack(itr)); // } // if (accTr) -// fStat[kAccStat][kEventCosm]++; +// mStat[kAccStat][kEventCosm]++; // } else { -// fStat[kInpStat][kEventColl]++; +// mStat[kInpStat][kEventColl]++; // ntr = esdEv->GetNumberOfTracks(); -// FillStatHisto(kTrackInp, ntr); +// fillStatHisto(kTrackInp, ntr); // for (int itr = 0; itr < ntr; itr++) { // // int accTrOld = accTr; // accTr += ProcessTrack(esdEv->GetTrack(itr)); // /* -// if (accTr>accTrOld && fCResid) { -// int ndf = fCResid->GetNPoints()*2-5; -// if (fCResid->GetChi2()/ndf>20 || !fCResid->GetKalmanDone() -// || fCResid->GetChi2K()/ndf>20) { +// if (accTr>accTrOld && mCResid) { +// int ndf = mCResid->getNPoints()*2-5; +// if (mCResid->getChi2()/ndf>20 || !mCResid->getKalmanDone() +// || mCResid->getChi2K()/ndf>20) { // printf("BAD FIT for %d\n",itr); // } -// fCResid->Print("er"); +// mCResid->Print("er"); // } // */ // } // if (accTr) -// fStat[kAccStat][kEventColl]++; +// mStat[kAccStat][kEventColl]++; // } // // -// FillStatHisto(kTrackAcc, accTr); +// fillStatHisto(kTrackAcc, accTr); // // // if (accTr) { // LOG(INFO) << "Processed event " << esdEv->GetEventNumberInFile() << " of ev.specie " << esdEv->GetEventSpecie() << " -> Accepted: " << accTr << " of " << ntr << " tracks"; @@ -547,7 +547,7 @@ bool AliAlgSteer::CheckDetectorPoints(const int* npsel) const //{ // // process single track // // -// fStat[kInpStat][kTrackColl]++; +// mStat[kInpStat][kTrackColl]++; // fESDTrack[0] = esdTr; // fESDTrack[1] = 0; // // @@ -563,78 +563,78 @@ bool AliAlgSteer::CheckDetectorPoints(const int* npsel) const // if (!detAcc) // return false; // // -// ResetDetectors(); -// fAlgTrack->Clear(); +// resetDetectors(); +// mAlgTrack->Clear(); // // // // process the track points for each detector, // AliAlgDet* det = 0; // for (int idet = 0; idet < kNDetectors; idet++) { // if (!(detAcc & (0x1 << idet))) // continue; -// det = GetDetectorByDetID(idet); -// if (det->ProcessPoints(esdTr, fAlgTrack) < det->GetNPointsSel(kColl)) { +// det = getDetectorByDetID(idet); +// if (det->ProcessPoints(esdTr, mAlgTrack) < det->getNPointsSel(kColl)) { // detAcc &= ~(0x1 << idet); // did not survive, suppress detector in the track -// if (det->IsObligatory(kColl)) +// if (det->isObligatory(kColl)) // return false; // } -// if (NumberOfBitsSet(detAcc) < fMinDetAcc[kColl]) +// if (numberOfBitsSet(detAcc) < mMinDetAcc[kColl]) // return false; // abandon track // } // // -// if (fAlgTrack->GetNPoints() < GetMinPoints()) +// if (mAlgTrack->getNPoints() < getMinPoints()) // return false; -// // fill needed points (tracking frame) in the fAlgTrack -// fRefPoint->SetContainsMeasurement(false); -// fRefPoint->SetContainsMaterial(false); -// fAlgTrack->AddPoint(fRefPoint); // reference point which the track will refer to +// // fill needed points (tracking frame) in the mAlgTrack +// mRefPoint->setContainsMeasurement(false); +// mRefPoint->setContainsMaterial(false); +// mAlgTrack->addPoint(mRefPoint); // reference point which the track will refer to // // -// fAlgTrack->CopyFrom(esdTr); -// if (!GetFieldOn()) -// fAlgTrack->ImposePtBOff(fDefPtBOff[AliAlgAux::kColl]); -// fAlgTrack->SetFieldON(GetFieldOn()); -// fAlgTrack->SortPoints(); +// mAlgTrack->copyFrom(esdTr); +// if (!getFieldOn()) +// mAlgTrack->imposePtBOff(mDefPtBOff[AliAlgAux::kColl]); +// mAlgTrack->setFieldON(getFieldOn()); +// mAlgTrack->sortPoints(); // // // // at this stage the points are sorted from maxX to minX, the latter corresponding to -// // reference point (e.g. vertex) with X~0. The fAlgTrack->GetInnerPointID() points on it, -// // hence fAlgTrack->GetInnerPointID() is the 1st really measured point. We will set the +// // reference point (e.g. vertex) with X~0. The mAlgTrack->getInnerPointID() points on it, +// // hence mAlgTrack->getInnerPointID() is the 1st really measured point. We will set the // // alpha of the reference point to alpha of the barrel sector corresponding to this // // 1st measured point -// int pntMeas = fAlgTrack->GetInnerPointID() - 1; +// int pntMeas = mAlgTrack->getInnerPointID() - 1; // if (pntMeas < 0) { // this should not happen -// fAlgTrack->Print("p meas"); -// LOG(FATAL) << "AliAlgTrack->GetInnerPointID() cannot be 0"; +// mAlgTrack->Print("p meas"); +// LOG(FATAL) << "AliAlgTrack->getInnerPointID() cannot be 0"; // } // // do we want to add the vertex as a measured point ? -// if (!AddVertexConstraint()) { // no constrain, just reference point w/o measurement -// fRefPoint->SetXYZTracking(0, 0, 0); -// fRefPoint->SetAlphaSens(Sector2Alpha(fAlgTrack->GetPoint(pntMeas)->GetAliceSector())); +// if (!addVertexConstraint()) { // no constrain, just reference point w/o measurement +// mRefPoint->setXYZTracking(0, 0, 0); +// mRefPoint->setAlphaSens(sector2Alpha(mAlgTrack->getPoint(pntMeas)->getAliceSector())); // } else -// FillStatHisto(kTrackFitInpVC); +// fillStatHisto(kTrackFitInpVC); // // -// FillStatHisto(kTrackFitInp); -// if (!fAlgTrack->IniFit()) +// fillStatHisto(kTrackFitInp); +// if (!mAlgTrack->iniFit()) // return false; -// FillStatHisto(kTrackProcMatInp); -// if (!fAlgTrack->ProcessMaterials()) +// fillStatHisto(kTrackProcMatInp); +// if (!mAlgTrack->processMaterials()) // return false; -// fAlgTrack->DefineDOFs(); +// mAlgTrack->defineDOFs(); // // -// FillStatHisto(kTrackResDerInp); -// if (!fAlgTrack->CalcResidDeriv()) +// fillStatHisto(kTrackResDerInp); +// if (!mAlgTrack->calcResidDeriv()) // return false; // // -// if (!StoreProcessedTrack(fMPOutType & ~kContR)) +// if (!storeProcessedTrack(mMPOutType & ~kContR)) // return false; // store derivatives for MP // // -// if (GetProduceControlRes() && // need control residuals, ignore selection fraction if this is the -// (fMPOutType == kContR || gRandom->Rndm() < fControlFrac)) { // output requested -// if (!TestLocalSolution() || !StoreProcessedTrack(kContR)) +// if (getProduceControlRes() && // need control residuals, ignore selection fraction if this is the +// (mMPOutType == kContR || gRandom->Rndm() < mControlFrac)) { // output requested +// if (!testLocalSolution() || !storeProcessedTrack(kContR)) // return false; // } // // -// FillStatHisto(kTrackStore); +// fillStatHisto(kTrackStore); // // -// fStat[kAccStat][kTrackColl]++; +// mStat[kAccStat][kTrackColl]++; // // // return true; //} @@ -649,19 +649,19 @@ bool AliAlgSteer::CheckDetectorPoints(const int* npsel) const // return true; // } // int ncont = vtx->GetNContributors(); -// if (fVtxMinCont > 0 && fVtxMinCont > ncont) { +// if (mVtxMinCont > 0 && mVtxMinCont > ncont) { //#if DEBUG > 2 -// LOG(INFO) << "Rejecting event with " << % d << " vertex contributors (min " << % d << " asked)", ncont, fVtxMinCont); +// LOG(INFO) << "Rejecting event with " << % d << " vertex contributors (min " << % d << " asked)", ncont, mVtxMinCont); //#endif // return false; // } -// if (fVtxMaxCont > 0 && ncont > fVtxMaxCont) { +// if (mVtxMaxCont > 0 && ncont > mVtxMaxCont) { //#if DEBUG > 2 -// LOG(INFO) << "Rejecting event with " << % d << " vertex contributors (max " << % d << " asked)", ncont, fVtxMaxCont); +// LOG(INFO) << "Rejecting event with " << % d << " vertex contributors (max " << % d << " asked)", ncont, mVtxMaxCont); //#endif // return false; // } -// fVertex = (ncont >= fVtxMinContVC) ? vtx : 0; // use vertex as a constraint +// fVertex = (ncont >= mVtxMinContVC) ? vtx : 0; // use vertex as a constraint // return true; //} @@ -671,7 +671,7 @@ bool AliAlgSteer::CheckDetectorPoints(const int* npsel) const //{ // // process single cosmic track // // -// fStat[kInpStat][kTrackCosm]++; +// mStat[kInpStat][kTrackCosm]++; // int nPnt = 0; // fESDTrack[0] = 0; // fESDTrack[1] = 0; @@ -693,15 +693,15 @@ bool AliAlgSteer::CheckDetectorPoints(const int* npsel) const // if (!detAcc) // return false; // // -// ResetDetectors(); -// fAlgTrack->Clear(); -// fAlgTrack->SetCosmic(true); +// resetDetectors(); +// mAlgTrack->Clear(); +// mAlgTrack->setCosmic(true); // // // // process the track points for each detector, -// // fill needed points (tracking frame) in the fAlgTrack -// fRefPoint->SetContainsMeasurement(false); -// fRefPoint->SetContainsMaterial(false); -// fAlgTrack->AddPoint(fRefPoint); // reference point which the track will refer to +// // fill needed points (tracking frame) in the mAlgTrack +// mRefPoint->setContainsMeasurement(false); +// mRefPoint->setContainsMaterial(false); +// mAlgTrack->addPoint(mRefPoint); // reference point which the track will refer to // // // AliAlgDet* det = 0; // int npsel[kNDetectors] = {0}; @@ -709,165 +709,165 @@ bool AliAlgSteer::CheckDetectorPoints(const int* npsel) const // for (int idet = 0; idet < kNDetectors; idet++) { // if (!(detAcc & (0x1 << idet))) // continue; -// det = GetDetectorByDetID(idet); +// det = getDetectorByDetID(idet); // // // // upper leg points marked as the track going in inverse direction -// int np = det->ProcessPoints(fESDTrack[leg], fAlgTrack, leg == kCosmUp); -// if (np < det->GetNPointsSel(kCosm) && fCosmicSelStrict && -// det->IsObligatory(kCosm)) +// int np = det->ProcessPoints(fESDTrack[leg], mAlgTrack, leg == kCosmUp); +// if (np < det->getNPointsSel(kCosm) && mCosmicSelStrict && +// det->isObligatory(kCosm)) // return false; // npsel[idet] += np; // nPleg += np; // } -// if (nPleg < GetMinPoints()) +// if (nPleg < getMinPoints()) // return false; // } // // last check on legs-combined patter -// if (!CheckDetectorPoints(npsel)) +// if (!checkDetectorPoints(npsel)) // return false; // // -// fAlgTrack->CopyFrom(cosmTr); -// if (!GetFieldOn()) -// fAlgTrack->ImposePtBOff(fDefPtBOff[AliAlgAux::kCosm]); -// fAlgTrack->SetFieldON(GetFieldOn()); -// fAlgTrack->SortPoints(); +// mAlgTrack->copyFrom(cosmTr); +// if (!getFieldOn()) +// mAlgTrack->imposePtBOff(mDefPtBOff[AliAlgAux::kCosm]); +// mAlgTrack->setFieldON(getFieldOn()); +// mAlgTrack->sortPoints(); // // // // at this stage the points are sorted from maxX to minX, the latter corresponding to -// // reference point (e.g. vertex) with X~0. The fAlgTrack->GetInnerPointID() points on it, -// // hence fAlgTrack->GetInnerPointID() is the 1st really measured point. We will set the +// // reference point (e.g. vertex) with X~0. The mAlgTrack->getInnerPointID() points on it, +// // hence mAlgTrack->getInnerPointID() is the 1st really measured point. We will set the // // alpha of the reference point to alpha of the barrel sector corresponding to this // // 1st measured point -// int pntMeas = fAlgTrack->GetInnerPointID() - 1; +// int pntMeas = mAlgTrack->getInnerPointID() - 1; // if (pntMeas < 0) { // this should not happen -// fAlgTrack->Print("p meas"); -// LOG(FATAL) << "AliAlgTrack->GetInnerPointID() cannot be 0"; +// mAlgTrack->Print("p meas"); +// LOG(FATAL) << "AliAlgTrack->getInnerPointID() cannot be 0"; // } -// fRefPoint->SetAlphaSens(Sector2Alpha(fAlgTrack->GetPoint(pntMeas)->GetAliceSector())); +// mRefPoint->setAlphaSens(sector2Alpha(mAlgTrack->getPoint(pntMeas)->getAliceSector())); // // -// FillStatHisto(kTrackFitInp); -// if (!fAlgTrack->IniFit()) +// fillStatHisto(kTrackFitInp); +// if (!mAlgTrack->iniFit()) // return false; // // -// FillStatHisto(kTrackProcMatInp); -// if (!fAlgTrack->ProcessMaterials()) +// fillStatHisto(kTrackProcMatInp); +// if (!mAlgTrack->processMaterials()) // return false; -// fAlgTrack->DefineDOFs(); +// mAlgTrack->defineDOFs(); // // -// FillStatHisto(kTrackResDerInp); -// if (!fAlgTrack->CalcResidDeriv()) +// fillStatHisto(kTrackResDerInp); +// if (!mAlgTrack->calcResidDeriv()) // return false; // // -// if (!StoreProcessedTrack(fMPOutType & ~kContR)) +// if (!storeProcessedTrack(mMPOutType & ~kContR)) // return false; // store derivatives for MP // // -// if (GetProduceControlRes() && // need control residuals, ignore selection fraction if this is the -// (fMPOutType == kContR || gRandom->Rndm() < fControlFrac)) { // output requested -// if (!TestLocalSolution() || !StoreProcessedTrack(kContR)) +// if (getProduceControlRes() && // need control residuals, ignore selection fraction if this is the +// (mMPOutType == kContR || gRandom->Rndm() < mControlFrac)) { // output requested +// if (!testLocalSolution() || !storeProcessedTrack(kContR)) // return false; // } // // -// FillStatHisto(kTrackStore); -// fStat[kAccStat][kTrackCosm]++; +// fillStatHisto(kTrackStore); +// mStat[kAccStat][kTrackCosm]++; // return true; //} //_________________________________________________________ -bool AliAlgSteer::StoreProcessedTrack(int what) +bool AliAlgSteer::storeProcessedTrack(int what) { // write alignment track bool res = true; if ((what & kMille)) - res &= FillMilleData(); + res &= fillMilleData(); if ((what & kMPRec)) - res &= FillMPRecData(); + res &= fillMPRecData(); if ((what & kContR)) - res &= FillControlData(); + res &= fillControlData(); // return res; } //_________________________________________________________ -bool AliAlgSteer::FillMilleData() +bool AliAlgSteer::fillMilleData() { // store MP2 data in Mille format - if (!fMille) { - TString mo = Form("%s%s", fMPDatFileName.Data(), fgkMPDataExt); - fMille = new Mille(mo.Data(), fMilleOutBin); - if (!fMille) + if (!mMille) { + TString mo = Form("%s%s", mMPDatFileName.Data(), sMPDataExt); + mMille = new Mille(mo.Data(), mMilleOutBin); + if (!mMille) LOG(FATAL) << "Failed to create output file " << mo.Data(); } // - if (!fAlgTrack->GetDerivDone()) { + if (!mAlgTrack->getDerivDone()) { LOG(ERROR) << "Track derivatives are not yet evaluated"; return false; } - int np(fAlgTrack->GetNPoints()), nDGloTot(0); // total number global derivatives stored - int nParETP(fAlgTrack->GetNLocExtPar()); // numnber of local parameters for reference track param - int nVarLoc(fAlgTrack->GetNLocPar()); // number of local degrees of freedom in the track + int np(mAlgTrack->getNPoints()), nDGloTot(0); // total number global derivatives stored + int nParETP(mAlgTrack->getNLocExtPar()); // numnber of local parameters for reference track param + int nVarLoc(mAlgTrack->getNLocPar()); // number of local degrees of freedom in the track float *buffDL(0), *buffDG(0); // faster acces arrays int* buffI(0); // - const int* gloParID(fAlgTrack->GetGloParID()); // IDs of global DOFs this track depends on + const int* gloParID(mAlgTrack->getGloParID()); // IDs of global DOFs this track depends on for (int ip = 0; ip < np; ip++) { - AliAlgPoint* pnt = fAlgTrack->GetPoint(ip); - if (pnt->ContainsMeasurement()) { - int gloOffs = pnt->GetDGloOffs(); // 1st entry of global derivatives for this point - int nDGlo = pnt->GetNGloDOFs(); // number of global derivatives (number of DOFs it depends on) - if (!pnt->IsStatOK()) - pnt->IncrementStat(); + AliAlgPoint* pnt = mAlgTrack->getPoint(ip); + if (pnt->containsMeasurement()) { + int gloOffs = pnt->getDGloOffs(); // 1st entry of global derivatives for this point + int nDGlo = pnt->getNGloDOFs(); // number of global derivatives (number of DOFs it depends on) + if (!pnt->isStatOK()) + pnt->incrementStat(); // check buffer sizes { - if (fMilleDBuffer.GetSize() < nVarLoc + nDGlo) - fMilleDBuffer.Set(100 + nVarLoc + nDGlo); - if (fMilleIBuffer.GetSize() < nDGlo) - fMilleIBuffer.Set(100 + nDGlo); - buffDL = fMilleDBuffer.GetArray(); // faster acces + if (mMilleDBuffer.GetSize() < nVarLoc + nDGlo) + mMilleDBuffer.Set(100 + nVarLoc + nDGlo); + if (mMilleIBuffer.GetSize() < nDGlo) + mMilleIBuffer.Set(100 + nDGlo); + buffDL = mMilleDBuffer.GetArray(); // faster acces buffDG = buffDL + nVarLoc; // faster acces - buffI = fMilleIBuffer.GetArray(); // faster acces + buffI = mMilleIBuffer.GetArray(); // faster acces } // local der. array cannot be 0-suppressed by Mille construction, need to reset all to 0 // for (int idim = 0; idim < 2; idim++) { // 2 dimensional orthogonal measurement memset(buffDL, 0, nVarLoc * sizeof(float)); - const double* deriv = fAlgTrack->GetDResDLoc(idim, ip); // array of Dresidual/Dparams_loc + const double* deriv = mAlgTrack->getDResDLoc(idim, ip); // array of Dresidual/Dparams_loc // derivatives over reference track parameters for (int j = 0; j < nParETP; j++) - buffDL[j] = (IsZeroAbs(deriv[j])) ? 0 : deriv[j]; + buffDL[j] = (isZeroAbs(deriv[j])) ? 0 : deriv[j]; // // point may depend on material variables within these limits - int lp0 = pnt->GetMinLocVarID(), lp1 = pnt->GetMaxLocVarID(); + int lp0 = pnt->getMinLocVarID(), lp1 = pnt->getMaxLocVarID(); for (int j = lp0; j < lp1; j++) - buffDL[j] = (IsZeroAbs(deriv[j])) ? 0 : deriv[j]; + buffDL[j] = (isZeroAbs(deriv[j])) ? 0 : deriv[j]; // // derivatives over global params: this array can be 0-suppressed, no need to reset int nGlo(0); - deriv = fAlgTrack->GetDResDGlo(idim, gloOffs); + deriv = mAlgTrack->getDResDGlo(idim, gloOffs); const int* gloIDP(gloParID + gloOffs); for (int j = 0; j < nDGlo; j++) { - if (!IsZeroAbs(deriv[j])) { + if (!isZeroAbs(deriv[j])) { buffDG[nGlo] = deriv[j]; // value of derivative - buffI[nGlo++] = GetGloParLab(gloIDP[j]); // global DOF ID + 1 (Millepede needs positive labels) + buffI[nGlo++] = getGloParLab(gloIDP[j]); // global DOF ID + 1 (Millepede needs positive labels) } } - fMille->mille(nVarLoc, buffDL, nGlo, buffDG, buffI, - fAlgTrack->GetResidual(idim, ip), Sqrt(pnt->GetErrDiag(idim))); + mMille->mille(nVarLoc, buffDL, nGlo, buffDG, buffI, + mAlgTrack->getResidual(idim, ip), Sqrt(pnt->getErrDiag(idim))); nDGloTot += nGlo; // } } - if (pnt->ContainsMaterial()) { // material point can add 4 or 5 otrhogonal pseudo-measurements + if (pnt->containsMaterial()) { // material point can add 4 or 5 otrhogonal pseudo-measurements memset(buffDL, 0, nVarLoc * sizeof(float)); - int nmatpar = pnt->GetNMatPar(); // residuals (correction expectation value) - // const float* expMatCorr = pnt->GetMatCorrExp(); // expected corrections (diagonalized) - const float* expMatCov = pnt->GetMatCorrCov(); // their diagonalized error matrix - int offs = pnt->GetMaxLocVarID() - nmatpar; // start of material variables + int nmatpar = pnt->getNMatPar(); // residuals (correction expectation value) + // const float* expMatCorr = pnt->getMatCorrExp(); // expected corrections (diagonalized) + const float* expMatCov = pnt->getMatCorrCov(); // their diagonalized error matrix + int offs = pnt->getMaxLocVarID() - nmatpar; // start of material variables // here all derivatives are 1 = dx/dx for (int j = 0; j < nmatpar; j++) { // mat. "measurements" don't depend on global params int j1 = j + offs; buffDL[j1] = 1.0; // only 1 non-0 derivative - //fMille->mille(nVarLoc,buffDL,0,buffDG,buffI,expMatCorr[j],Sqrt(expMatCov[j])); + //mMille->mille(nVarLoc,buffDL,0,buffDG,buffI,expMatCorr[j],Sqrt(expMatCov[j])); // expectation for MS effect is 0 - fMille->mille(nVarLoc, buffDL, 0, buffDG, buffI, 0, Sqrt(expMatCov[j])); + mMille->mille(nVarLoc, buffDL, 0, buffDG, buffI, 0, Sqrt(expMatCov[j])); buffDL[j1] = 0.0; // reset buffer } } // material "measurement" @@ -875,77 +875,77 @@ bool AliAlgSteer::FillMilleData() // if (!nDGloTot) { LOG(INFO) << "Track does not depend on free global parameters, discard"; - fMille->kill(); + mMille->kill(); return false; } - fMille->end(); // store the record + mMille->end(); // store the record return true; } //_________________________________________________________ -bool AliAlgSteer::FillMPRecData() +bool AliAlgSteer::fillMPRecData() { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs AliESDEvent // // store MP2 in MPRecord format - // if (!fMPRecord) - // InitMPRecOutput(); + // if (!mMPRecord) + // initMPRecOutput(); // // - // fMPRecord->Clear(); - // if (!fMPRecord->FillTrack(fAlgTrack, fGloParLab)) + // mMPRecord->Clear(); + // if (!mMPRecord->fillTrack(mAlgTrack, mGloParLab)) // return false; - // fMPRecord->SetRun(fRunNumber); - // fMPRecord->SetTimeStamp(fESDEvent->GetTimeStamp()); + // mMPRecord->SetRun(mRunNumber); + // mMPRecord->setTimeStamp(fESDEvent->GetTimeStamp()); // uint32_t tID = 0xffff & uint(fESDTrack[0]->GetID()); - // if (IsCosmic()) + // if (isCosmic()) // tID |= (0xffff & uint(fESDTrack[1]->GetID())) << 16; - // fMPRecord->SetTrackID(tID); - // fMPRecTree->Fill(); + // mMPRecord->setTrackID(tID); + // mMPRecTree->Fill(); return true; } //_________________________________________________________ -bool AliAlgSteer::FillControlData() +bool AliAlgSteer::fillControlData() { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs AliESDEvent // // store control residuals - // if (!fCResid) - // InitResidOutput(); + // if (!mCResid) + // initResidOutput(); // // - // int nps, np = fAlgTrack->GetNPoints(); - // nps = (!fRefPoint->ContainsMeasurement()) ? np - 1 : np; // ref point is dummy? + // int nps, np = mAlgTrack->getNPoints(); + // nps = (!mRefPoint->containsMeasurement()) ? np - 1 : np; // ref point is dummy? // if (nps < 0) // return true; // // - // fCResid->Clear(); - // if (!fCResid->FillTrack(fAlgTrack, fDoKalmanResid)) + // mCResid->Clear(); + // if (!mCResid->fillTrack(mAlgTrack, mDoKalmanResid)) // return false; - // fCResid->SetRun(fRunNumber); - // fCResid->SetTimeStamp(fESDEvent->GetTimeStamp()); - // fCResid->SetBz(fESDEvent->GetMagneticField()); + // mCResid->setRun(mRunNumber); + // mCResid->setTimeStamp(fESDEvent->GetTimeStamp()); + // mCResid->setBz(fESDEvent->GetMagneticField()); // uint32_t tID = 0xffff & uint(fESDTrack[0]->GetID()); - // if (IsCosmic()) + // if (isCosmic()) // tID |= (0xffff & uint(fESDTrack[1]->GetID())) << 16; - // fCResid->SetTrackID(tID); + // mCResid->setTrackID(tID); // // - // fResidTree->Fill(); - // FillStatHisto(kTrackControl); + // mResidTree->Fill(); + // fillStatHisto(kTrackControl); // // return true; } //_________________________________________________________ -void AliAlgSteer::SetRunNumber(int run) +void AliAlgSteer::setRunNumber(int run) { - if (run == fRunNumber) + if (run == mRunNumber) return; // nothing to do // - AcknowledgeNewRun(run); + acknowledgeNewRun(run); } //_________________________________________________________ -void AliAlgSteer::AcknowledgeNewRun(int run) +void AliAlgSteer::acknowledgeNewRun(int run) { LOG(WARNING) << __PRETTY_FUNCTION__ << " yet incomplete"; @@ -955,33 +955,33 @@ void AliAlgSteer::AcknowledgeNewRun(int run) //FIXME(milettri): needs AliESDEvent // // load needed info for new run - // if (run == fRunNumber) + // if (run == mRunNumber) // return; // nothing to do // if (run > 0) { - // fStat[kAccStat][kRun]++; + // mStat[kAccStat][kRun]++; // } - // if (fRunNumber > 0) - // FillStatHisto(kRunDone); - // fRunNumber = run; - // LOG(INFO) << "Processing new run " << fRunNumber; + // if (mRunNumber > 0) + // fillStatHisto(kRunDone); + // mRunNumber = run; + // LOG(INFO) << "Processing new run " << mRunNumber; // // // // setup magnetic field // if (fESDEvent && // (!TGeoGlobalMagField::Instance()->GetField() || - // !SmallerAbs(fESDEvent->GetMagneticField() - AliTrackerBase::GetBz(), 5e-4))) { + // !smallerAbs(fESDEvent->GetMagneticField() - AliTrackerBase::GetBz(), 5e-4))) { // fESDEvent->InitMagneticField(); // } // // - // if (!fUseRecoOCDB) { + // if (!mUseRecoOCDB) { // LOG(WARNING) << "Reco-time OCDB will NOT be preloaded"; // return; // } // LoadRecoTimeOCDB(); // // - // for (int idet = 0; idet < fNDet; idet++) { - // AliAlgDet* det = GetDetector(idet); - // if (!det->IsDisabled()) - // det->AcknowledgeNewRun(run); + // for (int idet = 0; idet < mNDet; idet++) { + // AliAlgDet* det = getDetector(idet); + // if (!det->isDisabled()) + // det->acknowledgeNewRun(run); // } // // // // bring to virgin state @@ -989,7 +989,7 @@ void AliAlgSteer::AcknowledgeNewRun(int run) // // // // LoadRefOCDB(); //??? we need to get back reference OCDB ??? // // - // fStat[kInpStat][kRun]++; + // mStat[kInpStat][kRun]++; // // } @@ -1000,22 +1000,22 @@ void AliAlgSteer::AcknowledgeNewRun(int run) // // Load OCDB paths used for the reconstruction of data being processed // // In order to avoid unnecessary uploads, the objects are not actually // // loaded/cached but just added as specific paths with version -// LOG(INFO) << "Preloading Reco-Time OCDB for run " << fRunNumber << " from ESD UserInfo list"; +// LOG(INFO) << "Preloading Reco-Time OCDB for run " << mRunNumber << " from ESD UserInfo list"; // // // CleanOCDB(); // // -// if (!fRecoOCDBConf.IsNull() && !gSystem->AccessPathName(fRecoOCDBConf.Data(), kFileExists)) { -// LOG(INFO) << "Executing reco-time OCDB setup macro " << fRecoOCDBConf.Data(); -// gROOT->ProcessLine(Form(".x %s(%d)", fRecoOCDBConf.Data(), fRunNumber)); +// if (!mRecoOCDBConf.IsNull() && !gSystem->AccessPathName(mRecoOCDBConf.Data(), kFileExists)) { +// LOG(INFO) << "Executing reco-time OCDB setup macro " << mRecoOCDBConf.Data(); +// gROOT->ProcessLine(Form(".x %s(%d)", mRecoOCDBConf.Data(), mRunNumber)); // if (AliCDBManager::Instance()->IsDefaultStorageSet()) // return true; -// LOG(FATAL) << "macro " << fRecoOCDBConf.Data() << " failed to configure reco-time OCDB"; +// LOG(FATAL) << "macro " << mRecoOCDBConf.Data() << " failed to configure reco-time OCDB"; // } else -// LOG(WARNING) << "No reco-time OCDB config macro" << fRecoOCDBConf.Data() << " is found, will use ESD:UserInfo"; +// LOG(WARNING) << "No reco-time OCDB config macro" << mRecoOCDBConf.Data() << " is found, will use ESD:UserInfo"; // // -// if (!fESDTree) +// if (!mESDTree) // LOG(FATAL) << "Cannot preload Reco-Time OCDB since the ESD tree is not set"; -// const TTree* tr = fESDTree; // go the the real ESD tree +// const TTree* tr = mESDTree; // go the the real ESD tree // while (tr->GetTree() && tr->GetTree() != tr) // tr = tr->GetTree(); // // @@ -1028,16 +1028,16 @@ void AliAlgSteer::AcknowledgeNewRun(int run) // LOG(FATAL) << "Failed to extract cdbMap and cdbList from UserInfo list"; // } // // -// return PreloadOCDB(fRunNumber, cdbMap, cdbList); +// return PreloadOCDB(mRunNumber, cdbMap, cdbList); //} //_________________________________________________________ -AliAlgDet* AliAlgSteer::GetDetectorByVolID(int vid) const +AliAlgDet* AliAlgSteer::getDetectorByVolID(int vid) const { // get detector by sensor volid - for (int i = fNDet; i--;) - if (fDetectors[i]->SensorOfDetector(vid)) - return fDetectors[i]; + for (int i = mNDet; i--;) + if (mDetectors[i]->sensorOfDetector(vid)) + return mDetectors[i]; return 0; } @@ -1047,104 +1047,104 @@ void AliAlgSteer::Print(const Option_t* opt) const // print info TString opts = opt; opts.ToLower(); - printf("%5d DOFs in %d detectors", fNDOFs, fNDet); - if (!fConfMacroName.IsNull()) - printf("(config: %s)", fConfMacroName.Data()); + printf("%5d DOFs in %d detectors", mNDOFs, mNDet); + if (!mConfMacroName.IsNull()) + printf("(config: %s)", mConfMacroName.Data()); printf("\n"); - if (GetMPAlignDone()) + if (getMPAlignDone()) printf("ALIGNMENT FROM MILLEPEDE SOLUTION IS APPLIED\n"); // for (int idt = 0; idt < kNDetectors; idt++) { - AliAlgDet* det = GetDetectorByDetID(idt); + AliAlgDet* det = getDetectorByDetID(idt); if (!det) continue; det->Print(opt); } if (!opts.IsNull()) { printf("\nSpecial sensor for Vertex Constraint\n"); - fVtxSens->Print(opt); + mVtxSens->Print(opt); } // // event selection printf("\n"); printf("%-40s:\t", "Alowed event specii mask"); - PrintBits((uint64_t)fSelEventSpecii, 5); + printBits((uint64_t)mSelEventSpecii, 5); printf("\n"); printf("%-40s:\t%d/%d\n", "Min points per collisions track (BOff/ON)", - fMinPoints[kColl][0], fMinPoints[kColl][1]); + mMinPoints[kColl][0], mMinPoints[kColl][1]); printf("%-40s:\t%d/%d\n", "Min points per cosmic track leg (BOff/ON)", - fMinPoints[kCosm][0], fMinPoints[kCosm][1]); - printf("%-40s:\t%d\n", "Min detectots per collision track", fMinDetAcc[kColl]); - printf("%-40s:\t%d (%s)\n", "Min detectots per cosmic track/leg", fMinDetAcc[kCosm], - fCosmicSelStrict ? "STRICT" : "SOFT"); - printf("%-40s:\t%d/%d\n", "Min/Max vertex contrib. to accept event", fVtxMinCont, fVtxMaxCont); - printf("%-40s:\t%d\n", "Min vertex contrib. for constraint", fVtxMinContVC); - printf("%-40s:\t%d\n", "Min Ncl ITS for vertex constraint", fMinITSClforVC); + mMinPoints[kCosm][0], mMinPoints[kCosm][1]); + printf("%-40s:\t%d\n", "Min detectots per collision track", mMinDetAcc[kColl]); + printf("%-40s:\t%d (%s)\n", "Min detectots per cosmic track/leg", mMinDetAcc[kCosm], + mCosmicSelStrict ? "STRICT" : "SOFT"); + printf("%-40s:\t%d/%d\n", "Min/Max vertex contrib. to accept event", mVtxMinCont, mVtxMaxCont); + printf("%-40s:\t%d\n", "Min vertex contrib. for constraint", mVtxMinContVC); + printf("%-40s:\t%d\n", "Min Ncl ITS for vertex constraint", mMinITSClforVC); printf("%-40s:\t%s\n", "SPD request for vertex constraint", - // AliAlgDetITS::GetITSPattName(fITSPattforVC)); FIXME(milettri): needs AliAlgDetITS + // AliAlgDetITS::GetITSPattName(mITSPattforVC)); FIXME(milettri): needs AliAlgDetITS "ITSNAME"); // FIXME(milettri): needs AliAlgDetITS printf("%-40s:\t%.4f/%.4f/%.2f\n", "DCAr/DCAz/Chi2 cut for vertex constraint", - fMaxDCAforVC[0], fMaxDCAforVC[1], fMaxChi2forVC); - printf("Collision tracks: Min pT: %5.2f |etaMax|: %5.2f\n", fPtMin[kColl], fEtaMax[kColl]); - printf("Cosmic tracks: Min pT: %5.2f |etaMax|: %5.2f\n", fPtMin[kCosm], fEtaMax[kCosm]); + mMaxDCAforVC[0], mMaxDCAforVC[1], mMaxChi2forVC); + printf("Collision tracks: Min pT: %5.2f |etaMax|: %5.2f\n", mPtMin[kColl], mEtaMax[kColl]); + printf("Cosmic tracks: Min pT: %5.2f |etaMax|: %5.2f\n", mPtMin[kCosm], mEtaMax[kCosm]); // - printf("%-40s:\t%s", "Config. for reference OCDB", fRefOCDBConf.Data()); - if (fRefRunNumber >= 0) - printf("(%d)", fRefRunNumber); + printf("%-40s:\t%s", "Config. for reference OCDB", mRefOCDBConf.Data()); + if (mRefRunNumber >= 0) + printf("(%d)", mRefRunNumber); printf("\n"); - printf("%-40s:\t%s\n", "Config. for reco-time OCDB", fRecoOCDBConf.Data()); + printf("%-40s:\t%s\n", "Config. for reco-time OCDB", mRecoOCDBConf.Data()); // - printf("%-40s:\t%s\n", "Output OCDB path", fOutCDBPath.Data()); + printf("%-40s:\t%s\n", "Output OCDB path", mOutCDBPath.Data()); printf("%-40s:\t%s/%s\n", "Output OCDB comment/responsible", - fOutCDBComment.Data(), fOutCDBResponsible.Data()); - printf("%-40s:\t%6d:%6d\n", "Output OCDB run range", fOutCDBRunRange[0], fOutCDBRunRange[1]); - // - printf("%-40s:\t%s\n", "Filename for MillePede steering", fMPSteerFileName.Data()); - printf("%-40s:\t%s\n", "Filename for MillePede parameters", fMPParFileName.Data()); - printf("%-40s:\t%s\n", "Filename for MillePede constraints", fMPConFileName.Data()); - printf("%-40s:\t%s\n", "Filename for control residuals:", fResidFileName.Data()); - printf("%-40s:\t%.3f\n", "Fraction of control tracks", fControlFrac); + mOutCDBComment.Data(), mOutCDBResponsible.Data()); + printf("%-40s:\t%6d:%6d\n", "Output OCDB run range", mOutCDBRunRange[0], mOutCDBRunRange[1]); + // + printf("%-40s:\t%s\n", "Filename for MillePede steering", mMPSteerFileName.Data()); + printf("%-40s:\t%s\n", "Filename for MillePede parameters", mMPParFileName.Data()); + printf("%-40s:\t%s\n", "Filename for MillePede constraints", mMPConFileName.Data()); + printf("%-40s:\t%s\n", "Filename for control residuals:", mResidFileName.Data()); + printf("%-40s:\t%.3f\n", "Fraction of control tracks", mControlFrac); printf("MPData output :\t"); - if (GetProduceMPData()) - printf("%s%s ", fMPDatFileName.Data(), fgkMPDataExt); - if (GetProduceMPRecord()) - printf("%s%s ", fMPDatFileName.Data(), ".root"); + if (getProduceMPData()) + printf("%s%s ", mMPDatFileName.Data(), sMPDataExt); + if (getProduceMPRecord()) + printf("%s%s ", mMPDatFileName.Data(), ".root"); printf("\n"); // if (opts.Contains("stat")) - PrintStatistics(); + printStatistics(); } //________________________________________________________ -void AliAlgSteer::PrintStatistics() const +void AliAlgSteer::printStatistics() const { // print processing stat printf("\nProcessing Statistics\n"); printf("Type: "); for (int i = 0; i < kMaxStat; i++) - printf("%s ", fgkStatName[i]); + printf("%s ", sStatName[i]); printf("\n"); for (int icl = 0; icl < kNStatCl; icl++) { - printf("%s ", fgkStatClName[icl]); + printf("%s ", sStatClName[icl]); for (int i = 0; i < kMaxStat; i++) - printf(Form("%%%dd ", (int)strlen(fgkStatName[i])), (int)fStat[icl][i]); + printf(Form("%%%dd ", (int)strlen(sStatName[i])), (int)mStat[icl][i]); printf("\n"); } } //________________________________________________________ -void AliAlgSteer::ResetDetectors() +void AliAlgSteer::resetDetectors() { // reset detectors for next track - fRefPoint->Clear(); - for (int idet = fNDet; idet--;) { - AliAlgDet* det = GetDetector(idet); - det->ResetPool(); // reset used alignment points + mRefPoint->Clear(); + for (int idet = mNDet; idet--;) { + AliAlgDet* det = getDetector(idet); + det->resetPool(); // reset used alignment points } } //____________________________________________ -bool AliAlgSteer::TestLocalSolution() +bool AliAlgSteer::testLocalSolution() { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs AliSymMatrix @@ -1163,17 +1163,17 @@ bool AliAlgSteer::TestLocalSolution() // // // /* // // print solution vector - // int nlocpar = fAlgTrack->GetNLocPar(); - // int nlocparETP = fAlgTrack->GetNLocExtPar(); // parameters of external track param + // int nlocpar = mAlgTrack->getNLocPar(); + // int nlocparETP = mAlgTrack->getNLocExtPar(); // parameters of external track param // printf("ETP Update: "); // for (int i=0;inlocparETP) printf("Mat.Corr. update:\n"); - // for (int ip=fAlgTrack->GetNPoints();ip--;) { - // AliAlgPoint* pnt = fAlgTrack->GetPoint(ip); - // int npm = pnt->GetNMatPar(); - // const float* expMatCov = pnt->GetMatCorrCov(); // its error - // int offs = pnt->GetMaxLocVarID() - npm; + // for (int ip=mAlgTrack->getNPoints();ip--;) { + // AliAlgPoint* pnt = mAlgTrack->getPoint(ip); + // int npm = pnt->getNMatPar(); + // const float* expMatCov = pnt->getMatCorrCov(); // its error + // int offs = pnt->getMaxLocVarID() - npm; // for (int ipar=0;iparGetLocPars()); + // rhs.SetElements(mAlgTrack->getLocPars()); // vsl += rhs; - // fAlgTrack->SetLocPars(vsl.GetMatrixArray()); - // fAlgTrack->CalcResiduals(); + // mAlgTrack->setLocPars(vsl.GetMatrixArray()); + // mAlgTrack->calcResiduals(); // delete mat; // // return true; @@ -1198,8 +1198,8 @@ bool AliAlgSteer::TestLocalSolution() //AliSymMatrix* AliAlgSteer::BuildMatrix(TVectorD& vec) //{ // // build matrix/vector for local track -// int npnt = fAlgTrack->GetNPoints(); -// int nlocpar = fAlgTrack->GetNLocPar(); +// int npnt = mAlgTrack->getNPoints(); +// int nlocpar = mAlgTrack->getNLocPar(); // // // vec.ResizeTo(nlocpar); // memset(vec.GetMatrixArray(), 0, nlocpar * sizeof(double)); @@ -1207,14 +1207,14 @@ bool AliAlgSteer::TestLocalSolution() // AliSymMatrix& mat = *matp; // // // for (int ip = npnt; ip--;) { -// AliAlgPoint* pnt = fAlgTrack->GetPoint(ip); +// AliAlgPoint* pnt = mAlgTrack->getPoint(ip); // // -// if (pnt->ContainsMeasurement()) { +// if (pnt->containsMeasurement()) { // // pnt->Print("meas"); // for (int idim = 2; idim--;) { // each point has 2 position residuals -// double sigma2 = pnt->GetErrDiag(idim); // residual error -// double resid = fAlgTrack->GetResidual(idim, ip); // residual -// double* deriv = fAlgTrack->GetDResDLoc(idim, ip); // array of Dresidual/Dparams +// double sigma2 = pnt->getErrDiag(idim); // residual error +// double resid = mAlgTrack->getResidual(idim, ip); // residual +// double* deriv = mAlgTrack->getDResDLoc(idim, ip); // array of Dresidual/Dparams // // // double sg2inv = 1. / sigma2; // for (int parI = nlocpar; parI--;) { @@ -1230,12 +1230,12 @@ bool AliAlgSteer::TestLocalSolution() // // // // if the point contains material, consider its expected kinks, eloss // // as measurements -// if (pnt->ContainsMaterial()) { +// if (pnt->containsMaterial()) { // // at least 4 parameters: 2 spatial + 2 angular kinks with 0 expectaction -// int npm = pnt->GetNMatPar(); -// // const float* expMatCorr = pnt->GetMatCorrExp(); // expected correction (diagonalized) -// const float* expMatCov = pnt->GetMatCorrCov(); // its error -// int offs = pnt->GetMaxLocVarID() - npm; +// int npm = pnt->getNMatPar(); +// // const float* expMatCorr = pnt->getMatCorrExp(); // expected correction (diagonalized) +// const float* expMatCov = pnt->getMatCorrCov(); // its error +// int offs = pnt->getMaxLocVarID() - npm; // for (int ipar = 0; ipar < npm; ipar++) { // int parI = offs + ipar; // // expected @@ -1251,169 +1251,169 @@ bool AliAlgSteer::TestLocalSolution() //} //____________________________________________ -void AliAlgSteer::InitMPRecOutput() +void AliAlgSteer::initMPRecOutput() { // prepare MP record output - if (!fMPRecord) - fMPRecord = new AliAlgMPRecord(); + if (!mMPRecord) + mMPRecord = new AliAlgMPRecord(); // - TString mo = Form("%s%s", fMPDatFileName.Data(), ".root"); - fMPRecFile = TFile::Open(mo.Data(), "recreate"); - if (!fMPRecFile) + TString mo = Form("%s%s", mMPDatFileName.Data(), ".root"); + mMPRecFile = TFile::Open(mo.Data(), "recreate"); + if (!mMPRecFile) LOG(FATAL) << "Failed to create output file " << mo.Data(); // - fMPRecTree = new TTree("mpTree", "MPrecord Tree"); - fMPRecTree->Branch("mprec", "AliAlgMPRecord", &fMPRecord); + mMPRecTree = new TTree("mpTree", "MPrecord Tree"); + mMPRecTree->Branch("mprec", "AliAlgMPRecord", &mMPRecord); // } //____________________________________________ -void AliAlgSteer::InitResidOutput() +void AliAlgSteer::initResidOutput() { // prepare residual output - if (!fCResid) - fCResid = new AliAlgRes(); + if (!mCResid) + mCResid = new AliAlgRes(); // - fResidFile = TFile::Open(fResidFileName.Data(), "recreate"); - if (!fResidFile) - LOG(FATAL) << "Failed to create output file " << fResidFileName.Data(); + mResidFile = TFile::Open(mResidFileName.Data(), "recreate"); + if (!mResidFile) + LOG(FATAL) << "Failed to create output file " << mResidFileName.Data(); // - fResidTree = new TTree("res", "Control Residuals"); - fResidTree->Branch("t", "AliAlgRes", &fCResid); + mResidTree = new TTree("res", "Control Residuals"); + mResidTree->Branch("t", "AliAlgRes", &mCResid); // } //____________________________________________ -void AliAlgSteer::CloseMPRecOutput() +void AliAlgSteer::closeMPRecOutput() { // close output - if (!fMPRecFile) + if (!mMPRecFile) return; - LOG(INFO) << "Closing " << fMPRecFile->GetName(); - fMPRecFile->cd(); - fMPRecTree->Write(); - delete fMPRecTree; - fMPRecTree = 0; - fMPRecFile->Close(); - delete fMPRecFile; - fMPRecFile = 0; - delete fMPRecord; - fMPRecord = 0; + LOG(INFO) << "Closing " << mMPRecFile->GetName(); + mMPRecFile->cd(); + mMPRecTree->Write(); + delete mMPRecTree; + mMPRecTree = 0; + mMPRecFile->Close(); + delete mMPRecFile; + mMPRecFile = 0; + delete mMPRecord; + mMPRecord = 0; } //____________________________________________ -void AliAlgSteer::CloseResidOutput() +void AliAlgSteer::closeResidOutput() { // close output - if (!fResidFile) + if (!mResidFile) return; - LOG(INFO) << "Closing " << fResidFile->GetName(); - fResidFile->cd(); - fResidTree->Write(); - delete fResidTree; - fResidTree = 0; - fResidFile->Close(); - delete fResidFile; - fResidFile = 0; - delete fCResid; - fCResid = 0; + LOG(INFO) << "Closing " << mResidFile->GetName(); + mResidFile->cd(); + mResidTree->Write(); + delete mResidTree; + mResidTree = 0; + mResidFile->Close(); + delete mResidFile; + mResidFile = 0; + delete mCResid; + mCResid = 0; } //____________________________________________ -void AliAlgSteer::CloseMilleOutput() +void AliAlgSteer::closeMilleOutput() { // close output - if (fMille) - LOG(INFO) << "Closing " << fMPDatFileName.Data() << fgkMPDataExt; - delete fMille; - fMille = 0; + if (mMille) + LOG(INFO) << "Closing " << mMPDatFileName.Data() << sMPDataExt; + delete mMille; + mMille = 0; } //____________________________________________ -void AliAlgSteer::SetMPDatFileName(const char* name) +void AliAlgSteer::setMPDatFileName(const char* name) { // set output file name - fMPDatFileName = name; + mMPDatFileName = name; // strip root or mille extensions, they will be added automatically later - if (fMPDatFileName.EndsWith(fgkMPDataExt)) - fMPDatFileName.Remove(fMPDatFileName.Length() - strlen(fgkMPDataExt)); - else if (fMPDatFileName.EndsWith(".root")) - fMPDatFileName.Remove(fMPDatFileName.Length() - strlen(".root")); + if (mMPDatFileName.EndsWith(sMPDataExt)) + mMPDatFileName.Remove(mMPDatFileName.Length() - strlen(sMPDataExt)); + else if (mMPDatFileName.EndsWith(".root")) + mMPDatFileName.Remove(mMPDatFileName.Length() - strlen(".root")); // - if (fMPDatFileName.IsNull()) - fMPDatFileName = "mpData"; + if (mMPDatFileName.IsNull()) + mMPDatFileName = "mpData"; // } //____________________________________________ -void AliAlgSteer::SetMPParFileName(const char* name) +void AliAlgSteer::setMPParFileName(const char* name) { // set MP params output file name - fMPParFileName = name; - if (fMPParFileName.IsNull()) - fMPParFileName = "mpParams.txt"; + mMPParFileName = name; + if (mMPParFileName.IsNull()) + mMPParFileName = "mpParams.txt"; // } //____________________________________________ -void AliAlgSteer::SetMPConFileName(const char* name) +void AliAlgSteer::setMPConFileName(const char* name) { // set MP constraints output file name - fMPConFileName = name; - if (fMPConFileName.IsNull()) - fMPConFileName = "mpConstraints.txt"; + mMPConFileName = name; + if (mMPConFileName.IsNull()) + mMPConFileName = "mpConstraints.txt"; // } //____________________________________________ -void AliAlgSteer::SetMPSteerFileName(const char* name) +void AliAlgSteer::setMPSteerFileName(const char* name) { // set MP constraints output file name - fMPSteerFileName = name; - if (fMPSteerFileName.IsNull()) - fMPSteerFileName = "mpConstraints.txt"; + mMPSteerFileName = name; + if (mMPSteerFileName.IsNull()) + mMPSteerFileName = "mpConstraints.txt"; // } //____________________________________________ -void AliAlgSteer::SetResidFileName(const char* name) +void AliAlgSteer::setResidFileName(const char* name) { // set output file name - fResidFileName = name; - if (fResidFileName.IsNull()) - fResidFileName = "mpControlRes.root"; + mResidFileName = name; + if (mResidFileName.IsNull()) + mResidFileName = "mpControlRes.root"; // } //____________________________________________ -void AliAlgSteer::SetOutCDBPath(const char* name) +void AliAlgSteer::setOutCDBPath(const char* name) { // set output storage name - fOutCDBPath = name; - if (fOutCDBPath.IsNull()) - fOutCDBPath = "local://outOCDB"; + mOutCDBPath = name; + if (mOutCDBPath.IsNull()) + mOutCDBPath = "local://outOCDB"; // } //____________________________________________ -void AliAlgSteer::SetObligatoryDetector(int detID, int trtype, bool v) +void AliAlgSteer::setObligatoryDetector(int detID, int trtype, bool v) { // mark detector presence obligatory in the track of given type - AliAlgDet* det = GetDetectorByDetID(detID); + AliAlgDet* det = getDetectorByDetID(detID); if (!det) { LOG(ERROR) << "Detector " << detID << " is not defined"; } if (v) - fObligatoryDetPattern[trtype] |= 0x1 << detID; + mObligatoryDetPattern[trtype] |= 0x1 << detID; else - fObligatoryDetPattern[trtype] &= ~(0x1 << detID); - if (det->IsObligatory(trtype) != v) - det->SetObligatory(trtype, v); + mObligatoryDetPattern[trtype] &= ~(0x1 << detID); + if (det->isObligatory(trtype) != v) + det->setObligatory(trtype, v); // } //____________________________________________ -bool AliAlgSteer::AddVertexConstraint() +bool AliAlgSteer::addVertexConstraint() { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs AliESDtrack @@ -1423,58 +1423,58 @@ bool AliAlgSteer::AddVertexConstraint() // if (!fVertex || !esdTr) // return false; // // - // if (esdTr->GetNcls(0) < fMinITSClforVC) + // if (esdTr->GetNcls(0) < mMinITSClforVC) // return false; // not enough ITS clusters - // if (!AliAlgDetITS::CheckHitPattern(esdTr, fITSPattforVC)) + // if (!AliAlgDetITS::CheckHitPattern(esdTr, mITSPattforVC)) // return false; // // // AliExternalTrackParam trc = *esdTr; // double dz[2], dzCov[3]; - // if (!trc.PropagateToDCA(fVertex, AliTrackerBase::GetBz(), 2 * fMaxDCAforVC[0], dz, dzCov)) + // if (!trc.PropagateToDCA(fVertex, AliTrackerBase::GetBz(), 2 * mMaxDCAforVC[0], dz, dzCov)) // return false; // // // // check if primary candidate - // if (Abs(dz[0]) > fMaxDCAforVC[0] || Abs(dz[1]) > fMaxDCAforVC[1]) + // if (Abs(dz[0]) > mMaxDCAforVC[0] || Abs(dz[1]) > mMaxDCAforVC[1]) // return false; // double covar[6]; // fVertex->GetCovMatrix(covar); // double p[2] = {trc.GetParameter()[0] - dz[0], trc.GetParameter()[1] - dz[1]}; // double c[3] = {0.5 * (covar[0] + covar[2]), 0., covar[5]}; // double chi2 = trc.GetPredictedChi2(p, c); - // if (chi2 > fMaxChi2forVC) + // if (chi2 > mMaxChi2forVC) // return false; // // // // assing measured vertex rotated to VtxSens frame as reference point // double xyz[3], xyzT[3]; // fVertex->GetXYZ(xyz); - // fVtxSens->SetAlpha(trc.GetAlpha()); + // mVtxSens->setAlpha(trc.GetAlpha()); // // usually translation from GLO to TRA frame should go via matrix T2G // // but for the VertexSensor Local and Global are the same frames - // fVtxSens->ApplyCorrection(xyz); - // fVtxSens->GetMatrixT2L().MasterToLocal(xyz, xyzT); - // fRefPoint->SetSensor(fVtxSens); - // fRefPoint->SetAlphaSens(fVtxSens->GetAlpTracking()); - // fRefPoint->SetXYZTracking(xyzT); - // fRefPoint->SetYZErrTracking(c); - // fRefPoint->SetContainsMeasurement(true); - // fRefPoint->Init(); + // mVtxSens->applyCorrection(xyz); + // mVtxSens->getMatrixT2L().MasterToLocal(xyz, xyzT); + // mRefPoint->setSensor(mVtxSens); + // mRefPoint->setAlphaSens(mVtxSens->getAlpTracking()); + // mRefPoint->setXYZTracking(xyzT); + // mRefPoint->setYZErrTracking(c); + // mRefPoint->setContainsMeasurement(true); + // mRefPoint->init(); // // return true; } //FIXME(milettri): needs OCDB ////______________________________________________________ -//void AliAlgSteer::WriteCalibrationResults() const +//void AliAlgSteer::writeCalibrationResults() const //{ // // writes output calibration // CleanOCDB(); -// AliCDBManager::Instance()->SetDefaultStorage(fOutCDBPath.Data()); +// AliCDBManager::Instance()->SetDefaultStorage(mOutCDBPath.Data()); // // // AliAlgDet* det; // for (int idet = 0; idet < kNDetectors; idet++) { -// if (!(det = GetDetectorByDetID(idet)) || det->IsDisabled()) +// if (!(det = getDetectorByDetID(idet)) || det->isDisabled()) // continue; -// det->WriteCalibrationResults(); +// det->writeCalibrationResults(); // } // // //} @@ -1484,8 +1484,8 @@ bool AliAlgSteer::AddVertexConstraint() //void AliAlgSteer::SetOutCDBRunRange(int rmin, int rmax) //{ // // set output run range -// fOutCDBRunRange[0] = rmin >= 0 ? rmin : 0; -// fOutCDBRunRange[1] = rmax > fOutCDBRunRange[0] ? rmax : AliCDBRunRange::Infinity(); +// mOutCDBRunRange[0] = rmin >= 0 ? rmin : 0; +// mOutCDBRunRange[1] = rmax > mOutCDBRunRange[0] ? rmax : AliCDBRunRange::Infinity(); //} //FIXME(milettri): needs OCDB @@ -1501,14 +1501,14 @@ bool AliAlgSteer::AddVertexConstraint() // CleanOCDB(); // AliCDBManager* man = AliCDBManager::Instance(); // // -// if (!fRefOCDBConf.IsNull() && !gSystem->AccessPathName(fRefOCDBConf.Data(), kFileExists)) { -// LOG(INFO) << "Executing reference OCDB setup macro %s", fRefOCDBConf.Data()); -// if (fRefRunNumber > 0) -// gROOT->ProcessLine(Form(".x %s(%d)", fRefOCDBConf.Data(), fRefRunNumber)); +// if (!mRefOCDBConf.IsNull() && !gSystem->AccessPathName(mRefOCDBConf.Data(), kFileExists)) { +// LOG(INFO) << "Executing reference OCDB setup macro %s", mRefOCDBConf.Data()); +// if (mRefRunNumber > 0) +// gROOT->ProcessLine(Form(".x %s(%d)", mRefOCDBConf.Data(), mRefRunNumber)); // else -// gROOT->ProcessLine(Form(".x %s", fRefOCDBConf.Data())); +// gROOT->ProcessLine(Form(".x %s", mRefOCDBConf.Data())); // } else { -// LOG(WARNING) << "No reference OCDB config macro "<SetRaw(true); // man->SetRun(AliCDBRunRange::Infinity()); // } @@ -1523,86 +1523,86 @@ bool AliAlgSteer::AddVertexConstraint() // // // TString detList = ""; // for (int i = 0; i < kNDetectors; i++) { -// detList += GetDetNameByDetID(i); +// detList += getDetNameByDetID(i); // detList += " "; // } // AliGeomManager::ApplyAlignObjsFromCDB(detList.Data()); // // -// fRefOCDBLoaded++; +// mRefOCDBLoaded++; // // // return true; //} //________________________________________________________ -AliAlgDet* AliAlgSteer::GetDetOfDOFID(int id) const +AliAlgDet* AliAlgSteer::getDetOfDOFID(int id) const { // return detector owning DOF with this ID - for (int i = fNDet; i--;) { - AliAlgDet* det = GetDetector(i); - if (det->OwnsDOFID(id)) + for (int i = mNDet; i--;) { + AliAlgDet* det = getDetector(i); + if (det->ownsDOFID(id)) return det; } return 0; } //________________________________________________________ -AliAlgVol* AliAlgSteer::GetVolOfDOFID(int id) const +AliAlgVol* AliAlgSteer::getVolOfDOFID(int id) const { // return volume owning DOF with this ID - for (int i = fNDet; i--;) { - AliAlgDet* det = GetDetector(i); - if (det->OwnsDOFID(id)) - return det->GetVolOfDOFID(id); + for (int i = mNDet; i--;) { + AliAlgDet* det = getDetector(i); + if (det->ownsDOFID(id)) + return det->getVolOfDOFID(id); } - if (fVtxSens && fVtxSens->OwnsDOFID(id)) - return fVtxSens; + if (mVtxSens && mVtxSens->ownsDOFID(id)) + return mVtxSens; return 0; } //________________________________________________________ -void AliAlgSteer::Terminate(bool doStat) +void AliAlgSteer::terminate(bool doStat) { // finalize processing - if (fRunNumber > 0) - FillStatHisto(kRunDone); + if (mRunNumber > 0) + fillStatHisto(kRunDone); if (doStat) { - if (fDOFStat) - delete fDOFStat; - fDOFStat = new AliAlgDOFStat(fNDOFs); + if (mDOFStat) + delete mDOFStat; + mDOFStat = new AliAlgDOFStat(mNDOFs); } - if (fVtxSens) - fVtxSens->FillDOFStat(fDOFStat); - // - for (int i = fNDet; i--;) - GetDetector(i)->Terminate(); - CloseMPRecOutput(); - CloseMilleOutput(); - CloseResidOutput(); + if (mVtxSens) + mVtxSens->fillDOFStat(mDOFStat); + // + for (int i = mNDet; i--;) + getDetector(i)->terminate(); + closeMPRecOutput(); + closeMilleOutput(); + closeResidOutput(); Print("stat"); // } //________________________________________________________ -char* AliAlgSteer::GetDOFLabelTxt(int idf) const +Char_t* AliAlgSteer::getDOFLabelTxt(int idf) const { // get DOF full label - AliAlgVol* vol = GetVolOfDOFID(idf); + AliAlgVol* vol = getVolOfDOFID(idf); if (vol) - return Form("%d_%s_%s", GetGloParLab(idf), vol->GetSymName(), - vol->GetDOFName(idf - vol->GetFirstParGloID())); + return Form("%d_%s_%s", getGloParLab(idf), vol->getSymName(), + vol->getDOFName(idf - vol->getFirstParGloID())); // // this might be detector-specific calibration dof - AliAlgDet* det = GetDetOfDOFID(idf); + AliAlgDet* det = getDetOfDOFID(idf); if (det) - return Form("%d_%s_%s", GetGloParLab(idf), det->GetName(), - det->GetCalibDOFName(idf - det->GetFirstParGloID())); + return Form("%d_%s_%s", getGloParLab(idf), det->GetName(), + det->getCalibDOFName(idf - det->getFirstParGloID())); return 0; } //********************* interaction with PEDE ********************** //______________________________________________________ -void AliAlgSteer::GenPedeSteerFile(const Option_t* opt) const +void AliAlgSteer::genPedeSteerFile(const Option_t* opt) const { // produce steering file template for PEDE + params and constraints // @@ -1616,16 +1616,16 @@ void AliAlgSteer::GenPedeSteerFile(const Option_t* opt) const TString opts = opt; opts.ToLower(); LOG(INFO) << "Generating MP2 templates:\n " - << "Steering :\t" << fMPSteerFileName.Data() << "\n" - << "Parameters :\t" << fMPParFileName.Data() << "\n" - << "Constraints:\t" << fMPConFileName.Data() << "\n"; + << "Steering :\t" << mMPSteerFileName.Data() << "\n" + << "Parameters :\t" << mMPParFileName.Data() << "\n" + << "Constraints:\t" << mMPConFileName.Data() << "\n"; // - FILE* parFl = fopen(fMPParFileName.Data(), "w+"); - FILE* strFl = fopen(fMPSteerFileName.Data(), "w+"); + FILE* parFl = fopen(mMPParFileName.Data(), "w+"); + FILE* strFl = fopen(mMPSteerFileName.Data(), "w+"); // // --- template of steering file - fprintf(strFl, "%-20s%s %s\n", fMPParFileName.Data(), cmt[kOnOn], "parameters template"); - fprintf(strFl, "%-20s%s %s\n", fMPConFileName.Data(), cmt[kOnOn], "constraints template"); + fprintf(strFl, "%-20s%s %s\n", mMPParFileName.Data(), cmt[kOnOn], "parameters template"); + fprintf(strFl, "%-20s%s %s\n", mMPConFileName.Data(), cmt[kOnOn], "constraints template"); // fprintf(strFl, "\n\n%s %s\n", cmt[kOnOn], "MUST uncomment 1 solving methods and tune it"); // @@ -1651,18 +1651,18 @@ void AliAlgSteer::GenPedeSteerFile(const Option_t* opt) const // fprintf(strFl, "\n\n\n%s%-20s %s %s\n\n\n", cmt[kOff], "CFiles", cmt[kOnOn], "put below *.mille files list"); // - if (fVtxSens) - fVtxSens->WritePedeInfo(parFl, opt); + if (mVtxSens) + mVtxSens->writePedeInfo(parFl, opt); // for (int idt = 0; idt < kNDetectors; idt++) { - AliAlgDet* det = GetDetectorByDetID(idt); - if (!det || det->IsDisabled()) + AliAlgDet* det = getDetectorByDetID(idt); + if (!det || det->isDisabled()) continue; - det->WritePedeInfo(parFl, opt); + det->writePedeInfo(parFl, opt); // } // - WritePedeConstraints(); + writePedeConstraints(); // fclose(strFl); fclose(parFl); @@ -1670,20 +1670,20 @@ void AliAlgSteer::GenPedeSteerFile(const Option_t* opt) const } //___________________________________________________________ -bool AliAlgSteer::ReadParameters(const char* parfile, bool useErrors) +bool AliAlgSteer::readParameters(const char* parfile, bool useErrors) { // read parameters file (millepede output) - if (fNDOFs < 1 || !fGloParVal || !fGloParErr) { - LOG(ERROR) << "Something is wrong in init: fNDOFs=" << fNDOFs << " fGloParVal=" << fGloParVal << " fGloParErr=" << fGloParErr; + if (mNDOFs < 1 || !mGloParVal || !mGloParErr) { + LOG(ERROR) << "Something is wrong in init: mNDOFs=" << mNDOFs << " mGloParVal=" << mGloParVal << " mGloParErr=" << mGloParErr; } ifstream inpf(parfile); if (!inpf.good()) { printf("Failed on input filename %s\n", parfile); return false; } - memset(fGloParVal, 0, fNDOFs * sizeof(float)); + memset(mGloParVal, 0, mNDOFs * sizeof(float)); if (useErrors) - memset(fGloParErr, 0, fNDOFs * sizeof(float)); + memset(mGloParErr, 0, mNDOFs * sizeof(float)); int cnt = 0; TString fline; fline.ReadLine(inpf); @@ -1709,14 +1709,14 @@ bool AliAlgSteer::ReadParameters(const char* parfile, bool useErrors) } if (nr == 3) asg0++; - int parID = Label2ParID(lab); - if (parID < 0 || parID >= fNDOFs) { + int parID = label2ParID(lab); + if (parID < 0 || parID >= mNDOFs) { LOG(ERROR) << "Invalid label " << lab << " at line " << cnt << " -> ParID=" << parID; return false; } - fGloParVal[parID] = -v0; + mGloParVal[parID] = -v0; if (useErrors) - fGloParErr[parID] = v1; + mGloParErr[parID] = v1; asg++; // }; @@ -1726,25 +1726,25 @@ bool AliAlgSteer::ReadParameters(const char* parfile, bool useErrors) } //______________________________________________________ -void AliAlgSteer::CheckConstraints(const char* params) +void AliAlgSteer::checkConstraints(const char* params) { // check how the constraints are satisfied with already uploaded or provided params // - if (params && !ReadParameters(params)) { + if (params && !readParameters(params)) { LOG(ERROR) << "Failed to load parameters from " << params; return; } // - int ncon = GetNConstraints(); + int ncon = getNConstraints(); for (int icon = 0; icon < ncon; icon++) { - const AliAlgConstraint* con = GetConstraint(icon); - con->CheckConstraint(); + const AliAlgConstraint* con = getConstraint(icon); + con->checkConstraint(); } // } //___________________________________________________________ -void AliAlgSteer::MPRec2Mille(const char* mprecfile, const char* millefile, bool bindata) +void AliAlgSteer::mPRec2Mille(const char* mprecfile, const char* millefile, bool bindata) { // converts MPRecord tree to millepede binary format TFile* flmpr = TFile::Open(mprecfile); @@ -1757,14 +1757,14 @@ void AliAlgSteer::MPRec2Mille(const char* mprecfile, const char* millefile, bool LOG(ERROR) << "No mpTree in xMPRecord file " << mprecfile; return; } - MPRec2Mille(mprTree, millefile, bindata); + mPRec2Mille(mprTree, millefile, bindata); delete mprTree; flmpr->Close(); delete flmpr; } //___________________________________________________________ -void AliAlgSteer::MPRec2Mille(TTree* mprTree, const char* millefile, bool bindata) +void AliAlgSteer::mPRec2Mille(TTree* mprTree, const char* millefile, bool bindata) { // converts MPRecord tree to millepede binary format // @@ -1779,31 +1779,31 @@ void AliAlgSteer::MPRec2Mille(TTree* mprTree, const char* millefile, bool bindat TString mlname = millefile; if (mlname.IsNull()) mlname = "mpRec2mpData"; - if (!mlname.EndsWith(fgkMPDataExt)) - mlname += fgkMPDataExt; + if (!mlname.EndsWith(sMPDataExt)) + mlname += sMPDataExt; Mille* mille = new Mille(mlname, bindata); TArrayF buffDLoc; for (int i = 0; i < nent; i++) { br->GetEntry(i); - int nr = rec->GetNResid(); // number of residual records - int nloc = rec->GetNVarLoc(); + int nr = rec->getNResid(); // number of residual records + int nloc = rec->getNVarLoc(); if (buffDLoc.GetSize() < nloc) buffDLoc.Set(nloc + 100); float* buffLocV = buffDLoc.GetArray(); - const float* recDGlo = rec->GetArrGlo(); - const float* recDLoc = rec->GetArrLoc(); - const short* recLabLoc = rec->GetArrLabLoc(); - const int* recLabGlo = rec->GetArrLabGlo(); + const float* recDGlo = rec->getArrGlo(); + const float* recDLoc = rec->getArrLoc(); + const short* recLabLoc = rec->getArrLabLoc(); + const int* recLabGlo = rec->getArrLabGlo(); // for (int ir = 0; ir < nr; ir++) { memset(buffLocV, 0, nloc * sizeof(float)); - int ndglo = rec->GetNDGlo(ir); - int ndloc = rec->GetNDLoc(ir); + int ndglo = rec->getNDGlo(ir); + int ndloc = rec->getNDLoc(ir); // fill 0-suppressed array from MPRecord to non-0-suppressed array of Mille for (int l = ndloc; l--;) buffLocV[recLabLoc[l]] = recDLoc[l]; // - mille->mille(nloc, buffLocV, ndglo, recDGlo, recLabGlo, rec->GetResid(ir), rec->GetResErr(ir)); + mille->mille(nloc, buffLocV, ndglo, recDGlo, recLabGlo, rec->getResid(ir), rec->getResErr(ir)); // recLabGlo += ndglo; // next record recDGlo += ndglo; @@ -1818,93 +1818,93 @@ void AliAlgSteer::MPRec2Mille(TTree* mprTree, const char* millefile, bool bindat } //____________________________________________________________ -void AliAlgSteer::FillStatHisto(int type, float w) +void AliAlgSteer::fillStatHisto(int type, float w) { - if (!fHistoStat) - CreateStatHisto(); - fHistoStat->Fill((IsCosmic() ? kNHVars : 0) + type, w); + if (!mHistoStat) + createStatHisto(); + mHistoStat->Fill((isCosmic() ? kNHVars : 0) + type, w); } //____________________________________________________________ -void AliAlgSteer::CreateStatHisto() +void AliAlgSteer::createStatHisto() { - fHistoStat = new TH1F("stat", "stat", 2 * kNHVars, -0.5, 2 * kNHVars - 0.5); - fHistoStat->SetDirectory(0); - TAxis* xax = fHistoStat->GetXaxis(); + mHistoStat = new TH1F("stat", "stat", 2 * kNHVars, -0.5, 2 * kNHVars - 0.5); + mHistoStat->SetDirectory(0); + TAxis* xax = mHistoStat->GetXaxis(); for (int j = 0; j < 2; j++) { for (int i = 0; i < kNHVars; i++) { - xax->SetBinLabel(j * kNHVars + i + 1, Form("%s.%s", j ? "CSM" : "COL", fgkHStatName[i])); + xax->SetBinLabel(j * kNHVars + i + 1, Form("%s.%s", j ? "CSM" : "COL", sHStatName[i])); } } } //____________________________________________________________ -void AliAlgSteer::PrintLabels() const +void AliAlgSteer::printLabels() const { // print global IDs and Labels - for (int i = 0; i < fNDOFs; i++) - printf("%5d %s\n", i, GetDOFLabelTxt(i)); + for (int i = 0; i < mNDOFs; i++) + printf("%5d %s\n", i, getDOFLabelTxt(i)); } //____________________________________________________________ -int AliAlgSteer::Label2ParID(int lab) const +int AliAlgSteer::label2ParID(int lab) const { // convert Mille label to ParID (slow) - int ind = FindKeyIndex(lab, fOrderedLbl, fNDOFs); + int ind = findKeyIndex(lab, mOrderedLbl, mNDOFs); if (ind < 0) return -1; - return fLbl2ID[ind]; + return mLbl2ID[ind]; } //____________________________________________________________ -void AliAlgSteer::AddAutoConstraints() +void AliAlgSteer::addAutoConstraints() { // add default constraints on children cumulative corrections within the volumes - for (int idet = 0; idet < fNDet; idet++) { - AliAlgDet* det = GetDetector(idet); - if (det->IsDisabled()) + for (int idet = 0; idet < mNDet; idet++) { + AliAlgDet* det = getDetector(idet); + if (det->isDisabled()) continue; - det->AddAutoConstraints(); + det->addAutoConstraints(); } - LOG(INFO) << "Added " << GetNConstraints() << " automatic constraints"; + LOG(INFO) << "Added " << getNConstraints() << " automatic constraints"; } //____________________________________________________________ -void AliAlgSteer::WritePedeConstraints() const +void AliAlgSteer::writePedeConstraints() const { // write constraints file - FILE* conFl = fopen(fMPConFileName.Data(), "w+"); + FILE* conFl = fopen(mMPConFileName.Data(), "w+"); // - int nconstr = GetNConstraints(); + int nconstr = getNConstraints(); for (int icon = 0; icon < nconstr; icon++) - GetConstraint(icon)->WriteChildrenConstraints(conFl); + getConstraint(icon)->writeChildrenConstraints(conFl); // fclose(conFl); } //____________________________________________________________ -void AliAlgSteer::FixLowStatFromDOFStat(int thresh) +void AliAlgSteer::fixLowStatFromDOFStat(int thresh) { // fix DOFs having stat below threshold // - if (!fDOFStat) { + if (!mDOFStat) { LOG(ERROR) << "No object with DOFs statistics"; return; } - if (fNDOFs != fDOFStat->GetNDOFs()) { - LOG(ERROR) << "Discrepancy between NDOFs=" << fNDOFs << " of and statistics object: " << fDOFStat->GetNDOFs(); + if (mNDOFs != mDOFStat->getNDOFs()) { + LOG(ERROR) << "Discrepancy between NDOFs=" << mNDOFs << " of and statistics object: " << mDOFStat->getNDOFs(); return; } - for (int parID = 0; parID < fNDOFs; parID++) { - if (fDOFStat->GetStat(parID) >= thresh) + for (int parID = 0; parID < mNDOFs; parID++) { + if (mDOFStat->getStat(parID) >= thresh) continue; - fGloParErr[parID] = -999.; + mGloParErr[parID] = -999.; } // } //____________________________________________________________ -void AliAlgSteer::LoadStat(const char* flname) +void AliAlgSteer::loadStat(const char* flname) { // load statistics histos from external file produced by alignment task TFile* fl = TFile::Open(flname); @@ -1933,15 +1933,15 @@ void AliAlgSteer::LoadStat(const char* flname) if (!hdfO || !(dofSt = dynamic_cast(hdfO))) LOG(WARNING) << "did not find DOFstat object"; // - SetHistoStat(hst); - SetDOFStat(dofSt); + setHistoStat(hst); + setDOFStat(dofSt); // fl->Close(); delete fl; } //______________________________________________ -void AliAlgSteer::CheckSol(TTree* mpRecTree, bool store, +void AliAlgSteer::checkSol(TTree* mpRecTree, bool store, bool verbose, bool loc, const char* outName) { // do fast check of pede solution with MPRecord tree @@ -1970,7 +1970,7 @@ void AliAlgSteer::CheckSol(TTree* mpRecTree, bool store, int nrec = mpRecTree->GetEntriesFast(); for (int irec = 0; irec < nrec; irec++) { mpRecTree->GetEntry(irec); - CheckSol(rec, rLG, rL, verbose, loc); + checkSol(rec, rLG, rL, verbose, loc); // store even in case of failure, to have the trees aligned with controlRes if (trLG) trLG->Fill(); @@ -1994,7 +1994,7 @@ void AliAlgSteer::CheckSol(TTree* mpRecTree, bool store, } //______________________________________________ -bool AliAlgSteer::CheckSol(AliAlgMPRecord* rec, +bool AliAlgSteer::checkSol(AliAlgMPRecord* rec, AliAlgResFast* rLG, AliAlgResFast* rL, bool verbose, bool loc) { @@ -2007,25 +2007,25 @@ bool AliAlgSteer::CheckSol(AliAlgMPRecord* rec, // if (rL) // loc = true; // if local sol. tree asked, always evaluate it // // - // int nres = rec->GetNResid(); + // int nres = rec->getNResid(); // // - // const float* recDGlo = rec->GetArrGlo(); - // const float* recDLoc = rec->GetArrLoc(); - // const short* recLabLoc = rec->GetArrLabLoc(); - // const int* recLabGlo = rec->GetArrLabGlo(); - // int nvloc = rec->GetNVarLoc(); + // const float* recDGlo = rec->getArrGlo(); + // const float* recDLoc = rec->getArrLoc(); + // const short* recLabLoc = rec->getArrLabLoc(); + // const int* recLabGlo = rec->getArrLabGlo(); + // int nvloc = rec->getNVarLoc(); // // // // count number of real measurement duplets and material correction fake 4-plets // int nPoints = 0; // int nMatCorr = 0; // for (int irs = 0; irs < nres; irs++) { - // if (rec->GetNDGlo(irs) > 0) { - // if (irs == nres - 1 || rec->GetNDGlo(irs + 1) == 0) + // if (rec->getNDGlo(irs) > 0) { + // if (irs == nres - 1 || rec->getNDGlo(irs + 1) == 0) // LOG(FATAL) << ("Real coordinate measurements must come in pairs"); // nPoints++; // irs++; // skip 2nd // continue; - // } else if (rec->GetResid(irs) == 0 && rec->GetVolID(irs) == -1) { // material corrections have 0 residual + // } else if (rec->getResid(irs) == 0 && rec->getVolID(irs) == -1) { // material corrections have 0 residual // nMatCorr++; // } else { // might be fixed parameter, global derivs are skept // nPoints++; @@ -2039,15 +2039,15 @@ bool AliAlgSteer::CheckSol(AliAlgMPRecord* rec, // // // if (rLG) { // rLG->Clear(); - // rLG->SetNPoints(nPoints); - // rLG->SetNMatSol(nMatCorr); - // rLG->SetCosmic(rec->IsCosmic()); + // rLG->setNPoints(nPoints); + // rLG->setNMatSol(nMatCorr); + // rLG->setCosmic(rec->isCosmic()); // } // if (rL) { // rL->Clear(); - // rL->SetNPoints(nPoints); - // rL->SetNMatSol(nMatCorr); - // rL->SetCosmic(rec->IsCosmic()); + // rL->setNPoints(nPoints); + // rL->setNMatSol(nMatCorr); + // rL->setCosmic(rec->isCosmic()); // } // // // AliSymMatrix* matpG = new AliSymMatrix(nvloc); @@ -2062,30 +2062,30 @@ bool AliAlgSteer::CheckSol(AliAlgMPRecord* rec, // double* resid = new double[nres]; // int* volID = new int[nres]; // for (int irs = 0; irs < nres; irs++) { - // double resOr = rec->GetResid(irs); + // double resOr = rec->getResid(irs); // resid[irs] = resOr; // // - // int ndglo = rec->GetNDGlo(irs); - // int ndloc = rec->GetNDLoc(irs); + // int ndglo = rec->getNDGlo(irs); + // int ndloc = rec->getNDLoc(irs); // volID[irs] = 0; // for (int ig = 0; ig < ndglo; ig++) { // int lbI = recLabGlo[ig]; - // int idP = Label2ParID(lbI); + // int idP = label2ParID(lbI); // if (idP < 0) // LOG(FATAL) << "Did not find parameted for label " << lbI; - // double parVal = GetGloParVal()[idP]; + // double parVal = getGloParVal()[idP]; // // resid[irs] -= parVal*recDGlo[ig]; // resid[irs] += parVal * recDGlo[ig]; // if (!ig) { - // AliAlgVol* vol = GetVolOfDOFID(idP); + // AliAlgVol* vol = getVolOfDOFID(idP); // if (vol) - // volID[irs] = vol->GetVolID(); + // volID[irs] = vol->getVolID(); // else // volID[irs] = -2; // calibration DOF !!! TODO // } // } // // - // double sg2inv = rec->GetResErr(irs); + // double sg2inv = rec->getResErr(irs); // sg2inv = 1. / (sg2inv * sg2inv); // // // chi2Ini += resid[irs] * resid[irs] * sg2inv; // chi accounting for global solution only @@ -2110,9 +2110,9 @@ bool AliAlgSteer::CheckSol(AliAlgMPRecord* rec, // } // // // if (rL) - // rL->SetChi2Ini(chi2Ini); + // rL->setChi2Ini(chi2Ini); // if (rLG) - // rLG->SetChi2Ini(chi2Ini); + // rLG->setChi2Ini(chi2Ini); // // // TVectorD vecSol(nvloc); // TVectorD vecSolG(nvloc); @@ -2140,10 +2140,10 @@ bool AliAlgSteer::CheckSol(AliAlgMPRecord* rec, // return false; // } // // check - // recDGlo = rec->GetArrGlo(); - // recDLoc = rec->GetArrLoc(); - // recLabLoc = rec->GetArrLabLoc(); - // recLabGlo = rec->GetArrLabGlo(); + // recDGlo = rec->getArrGlo(); + // recDLoc = rec->getArrLoc(); + // recLabLoc = rec->getArrLabLoc(); + // recLabGlo = rec->getArrLabGlo(); // // // if (verbose) { // printf(loc ? "Sol L/LG:\n" : "Sol LG:\n"); @@ -2172,14 +2172,14 @@ bool AliAlgSteer::CheckSol(AliAlgMPRecord* rec, // } // int idMeas = -1, pntID = -1, matID = -1; // for (int irs = 0; irs < nres; irs++) { - // double resOr = rec->GetResid(irs); + // double resOr = rec->getResid(irs); // double resL = resOr; // double resLG = resid[irs]; - // double sg = rec->GetResErr(irs); + // double sg = rec->getResErr(irs); // double sg2Inv = 1 / (sg * sg); // // - // int ndglo = rec->GetNDGlo(irs); - // int ndloc = rec->GetNDLoc(irs); + // int ndglo = rec->getNDGlo(irs); + // int ndloc = rec->getNDLoc(irs); // // // for (int il = 0; il < ndloc; il++) { // int lbLI = recLabLoc[il]; // id of local variable @@ -2196,29 +2196,29 @@ bool AliAlgSteer::CheckSol(AliAlgMPRecord* rec, // idMeas = 0; // if (idMeas == 0) // pntID++; // measurements come in pairs - // int lbl = rec->GetVolID(irs); + // int lbl = rec->getVolID(irs); // lbl = ndglo ? recLabGlo[0] : 0; // TMP, until VolID is filled // RS!!!! // if (rLG) { - // rLG->SetResSigMeas(pntID, idMeas, resLG, sg); + // rLG->setResSigMeas(pntID, idMeas, resLG, sg); // if (idMeas == 0) - // rLG->SetLabel(pntID, lbl, volID[irs]); + // rLG->setLabel(pntID, lbl, volID[irs]); // } // if (rL) { - // rL->SetResSigMeas(pntID, idMeas, resL, sg); + // rL->setResSigMeas(pntID, idMeas, resL, sg); // if (idMeas == 0) - // rL->SetLabel(pntID, lbl, volID[irs]); + // rL->setLabel(pntID, lbl, volID[irs]); // } // } else { // matID++; // mat.correcitons come in 4-plets, but we fill each separately // // // if (rLG) - // rLG->SetMatCorr(matID, resLG, sg); + // rLG->setMatCorr(matID, resLG, sg); // if (rL) - // rL->SetMatCorr(matID, resL, sg); + // rL->setMatCorr(matID, resL, sg); // } // // // if (verbose) { - // int lbl = rec->GetVolID(irs); + // int lbl = rec->getVolID(irs); // lbl = ndglo ? recLabGlo[0] : (resOr == 0 ? -1 : 0); // TMP, until VolID is filled // RS!!!! // if (loc) // printf("%3d (%9d) %6.4f | [%+.2e:%+7.2f] [%+.2e:%+7.2f]\n", @@ -2234,9 +2234,9 @@ bool AliAlgSteer::CheckSol(AliAlgMPRecord* rec, // recDLoc += ndloc; // } // if (rL) - // rL->SetChi2(chi2L); + // rL->setChi2(chi2L); // if (rLG) - // rLG->SetChi2(chi2LG); + // rLG->setChi2(chi2LG); // // // if (verbose) { // printf("Chi: G = %e | LG = %e", chi2Ini, chi2LG); @@ -2248,9 +2248,9 @@ bool AliAlgSteer::CheckSol(AliAlgMPRecord* rec, // int nTrCor = nvloc - matID - 1; // for (int i = 0; i < nTrCor; i++) { // if (rLG) - // rLG->GetTrCor()[i] = vecSolG[i]; + // rLG->getTrCor()[i] = vecSolG[i]; // if (rL) - // rL->GetTrCor()[i] = vecSol[i]; + // rL->getTrCor()[i] = vecSol[i]; // } // // // delete[] resid; @@ -2259,17 +2259,17 @@ bool AliAlgSteer::CheckSol(AliAlgMPRecord* rec, } //______________________________________________ -void AliAlgSteer::ApplyAlignmentFromMPSol() +void AliAlgSteer::applyAlignmentFromMPSol() { // apply alignment from millepede solution array to reference alignment level LOG(INFO) << "Applying alignment from Millepede solution"; for (int idt = 0; idt < kNDetectors; idt++) { - AliAlgDet* det = GetDetectorByDetID(idt); - if (!det || det->IsDisabled()) + AliAlgDet* det = getDetectorByDetID(idt); + if (!det || det->isDisabled()) continue; - det->ApplyAlignmentFromMPSol(); + det->applyAlignmentFromMPSol(); } - SetMPAlignDone(); + setMPAlignDone(); // } diff --git a/Detectors/Align/src/AliAlgTrack.cxx b/Detectors/Align/src/AliAlgTrack.cxx index 74fbe7c699c65..9fcbce3ccfc2f 100644 --- a/Detectors/Align/src/AliAlgTrack.cxx +++ b/Detectors/Align/src/AliAlgTrack.cxx @@ -39,33 +39,33 @@ const int kRichardsonN = kRichardsonOrd + 1; // N of 2-point symmetric derivativ const int kNRDClones = kRichardsonN * 2; // number of variations for derivative of requested order //____________________________________________________________________________ -AliAlgTrack::AliAlgTrack() : TrackParametrizationWithError(), TObject(), fNLocPar(0), fNLocExtPar(0), fNGloPar(0), fNDF(0), fInnerPointID(0) - // ,fMinX2X0Pt2Account(5/1.0) +AliAlgTrack::AliAlgTrack() : TrackParametrizationWithError(), TObject(), mNLocPar(0), mNLocExtPar(0), mNGloPar(0), mNDF(0), mInnerPointID(0) + // ,mMinX2X0Pt2Account(5/1.0) , - fMinX2X0Pt2Account(0.5e-3 / 1.0), - fMass(0.14), - fChi2(0), - fChi2CosmUp(0), - fChi2CosmDn(0), - fChi2Ini(0), - fPoints(0), - fLocPar(), - fGloParID(0), - fGloParIDA(0), - fLocParA(0) + mMinX2X0Pt2Account(0.5e-3 / 1.0), + mMass(0.14), + mChi2(0), + mChi2CosmUp(0), + mChi2CosmDn(0), + mChi2Ini(0), + mPoints(0), + mLocPar(), + mGloParID(0), + mGloParIDA(0), + mLocParA(0) { // def c-tor for (int i = 0; i < 2; i++) { // we start with 0 size buffers for derivatives, they will be expanded automatically - fResid[i].Set(0); - fDResDGlo[i].Set(0); - fDResDLoc[i].Set(0); + mResid[i].Set(0); + mDResDGlo[i].Set(0); + mDResDLoc[i].Set(0); // - fResidA[i] = 0; - fDResDLocA[i] = 0; - fDResDGloA[i] = 0; + mResidA[i] = 0; + mDResDLocA[i] = 0; + mDResDGloA[i] = 0; } - fNeedInv[0] = fNeedInv[1] = false; + mNeedInv[0] = mNeedInv[1] = false; // } @@ -81,76 +81,76 @@ void AliAlgTrack::Clear(Option_t*) // reset the track TObject::Clear(); ResetBit(0xffffffff); - fPoints.Clear(); - fChi2 = fChi2CosmUp = fChi2CosmDn = fChi2Ini = 0; - fNDF = 0; - fInnerPointID = -1; - fNeedInv[0] = fNeedInv[1] = false; - fNLocPar = fNLocExtPar = fNGloPar = 0; + mPoints.Clear(); + mChi2 = mChi2CosmUp = mChi2CosmDn = mChi2Ini = 0; + mNDF = 0; + mInnerPointID = -1; + mNeedInv[0] = mNeedInv[1] = false; + mNLocPar = mNLocExtPar = mNGloPar = 0; // } //____________________________________________________________________________ -void AliAlgTrack::DefineDOFs() +void AliAlgTrack::defineDOFs() { // define varied DOF's (local parameters) for the track: // 1) kinematic params (5 or 4 depending on Bfield) // 2) mult. scattering angles (2) // 3) if requested by point: energy loss // - fNLocPar = fNLocExtPar = GetFieldON() ? kNKinParBON : kNKinParBOFF; - int np = GetNPoints(); + mNLocPar = mNLocExtPar = getFieldON() ? kNKinParBON : kNKinParBOFF; + int np = getNPoints(); // // the points are sorted in order opposite to track direction -> outer points come 1st, // but for the 2-leg cosmic track the innermost points are in the middle (1st lower leg, then upper one) // // start along track direction, i.e. last point in the ordered array - int minPar = fNLocPar; - for (int ip = GetInnerPointID() + 1; ip--;) { // collision track or cosmic lower leg - AliAlgPoint* pnt = GetPoint(ip); - pnt->SetMinLocVarID(minPar); - if (pnt->ContainsMaterial()) - fNLocPar += pnt->GetNMatPar(); - pnt->SetMaxLocVarID(fNLocPar); // flag up to which parameted ID this points depends on + int minPar = mNLocPar; + for (int ip = getInnerPointID() + 1; ip--;) { // collision track or cosmic lower leg + AliAlgPoint* pnt = getPoint(ip); + pnt->setMinLocVarID(minPar); + if (pnt->containsMaterial()) + mNLocPar += pnt->getNMatPar(); + pnt->setMaxLocVarID(mNLocPar); // flag up to which parameted ID this points depends on } // - if (IsCosmic()) { - minPar = fNLocPar; - for (int ip = GetInnerPointID() + 1; ip < np; ip++) { // collision track or cosmic lower leg - AliAlgPoint* pnt = GetPoint(ip); - pnt->SetMinLocVarID(minPar); - if (pnt->ContainsMaterial()) - fNLocPar += pnt->GetNMatPar(); - pnt->SetMaxLocVarID(fNLocPar); // flag up to which parameted ID this points depends on + if (isCosmic()) { + minPar = mNLocPar; + for (int ip = getInnerPointID() + 1; ip < np; ip++) { // collision track or cosmic lower leg + AliAlgPoint* pnt = getPoint(ip); + pnt->setMinLocVarID(minPar); + if (pnt->containsMaterial()) + mNLocPar += pnt->getNMatPar(); + pnt->setMaxLocVarID(mNLocPar); // flag up to which parameted ID this points depends on } } // - if (fLocPar.GetSize() < fNLocPar) - fLocPar.Set(fNLocPar); - fLocPar.Reset(); - fLocParA = fLocPar.GetArray(); + if (mLocPar.GetSize() < mNLocPar) + mLocPar.Set(mNLocPar); + mLocPar.Reset(); + mLocParA = mLocPar.GetArray(); // - if (fResid[0].GetSize() < np) { - fResid[0].Set(np); - fResid[1].Set(np); + if (mResid[0].GetSize() < np) { + mResid[0].Set(np); + mResid[1].Set(np); } - if (fDResDLoc[0].GetSize() < fNLocPar * np) { - fDResDLoc[0].Set(fNLocPar * np); - fDResDLoc[1].Set(fNLocPar * np); + if (mDResDLoc[0].GetSize() < mNLocPar * np) { + mDResDLoc[0].Set(mNLocPar * np); + mDResDLoc[1].Set(mNLocPar * np); } for (int i = 2; i--;) { - fResid[i].Reset(); - fDResDLoc[i].Reset(); - fResidA[i] = fResid[i].GetArray(); - fDResDLocA[i] = fDResDLoc[i].GetArray(); + mResid[i].Reset(); + mDResDLoc[i].Reset(); + mResidA[i] = mResid[i].GetArray(); + mDResDLocA[i] = mDResDLoc[i].GetArray(); } // - // memcpy(fLocParA,GetParameter(),fNLocExtPar*sizeof(double)); - memset(fLocParA, 0, fNLocExtPar * sizeof(double)); + // memcpy(mLocParA,GetParameter(),mNLocExtPar*sizeof(double)); + memset(mLocParA, 0, mNLocExtPar * sizeof(double)); } //______________________________________________________ -bool AliAlgTrack::CalcResidDeriv(double* params) +bool AliAlgTrack::calcResidDeriv(double* params) { // Propagate for given local params and calculate residuals and their derivatives. // The 1st 4 or 5 elements of params vector should be the reference trackParam_t @@ -159,40 +159,40 @@ bool AliAlgTrack::CalcResidDeriv(double* params) // They correspond to kink parameters // (trackParam_t_after_material - trackParam_t_before_material) // rotated to frame where they error matrix is diagonal. Their conversion to trackParam_t - // increment will be done locally in the ApplyMatCorr routine. + // increment will be done locally in the applyMatCorr routine. // // If params are not provided, use internal params array // if (!params) - params = fLocParA; + params = mLocParA; // - if (!GetResidDone()) - CalcResiduals(params); + if (!getResidDone()) + calcResiduals(params); // - int np = GetNPoints(); + int np = getNPoints(); // // collision track or cosmic lower leg - if (!CalcResidDeriv(params, fNeedInv[0], GetInnerPointID(), 0)) { + if (!calcResidDeriv(params, mNeedInv[0], getInnerPointID(), 0)) { #if DEBUG > 3 LOG(warn) << "Failed on derivatives calculation 0"; #endif return false; } // - if (IsCosmic()) { // cosmic upper leg - if (!CalcResidDeriv(params, fNeedInv[1], GetInnerPointID() + 1, np - 1)) { + if (isCosmic()) { // cosmic upper leg + if (!calcResidDeriv(params, mNeedInv[1], getInnerPointID() + 1, np - 1)) { #if DEBUG > 3 LOG(warn) << "Failed on derivatives calculation 0"; #endif } } // - SetDerivDone(); + setDerivDone(); return true; } //______________________________________________________ -bool AliAlgTrack::CalcResidDeriv(double* extendedParams, bool invert, int pFrom, int pTo) +bool AliAlgTrack::calcResidDeriv(double* extendedParams, bool invert, int pFrom, int pTo) { // Calculate derivatives of residuals vs params for points pFrom to pT. For cosmic upper leg // track parameter may require inversion. @@ -202,7 +202,7 @@ bool AliAlgTrack::CalcResidDeriv(double* extendedParams, bool invert, int pFrom, // They correspond to kink parameters // (trackParam_t_after_material - trackParam_t_before_material) // rotated to frame where they error matrix is diagonal. Their conversion to trackParam_t - // increment will be done locally in the ApplyMatCorr routine. + // increment will be done locally in the applyMatCorr routine. // // The derivatives are calculated using Richardson extrapolation // (like http://root.cern.ch/root/html/ROOT__Math__RichardsonDerivator.html) @@ -216,7 +216,7 @@ bool AliAlgTrack::CalcResidDeriv(double* extendedParams, bool invert, int pFrom, double delta[kNKinParBON]; // variations of curvature term are relative for (int i = kNKinParBOFF; i--;) delta[i] = kDelta[i]; - if (GetFieldON()) + if (getFieldON()) delta[kParQ2Pt] = kDelta[kParQ2Pt] * Abs(getQ2Pt()); // int pinc; @@ -229,9 +229,9 @@ bool AliAlgTrack::CalcResidDeriv(double* extendedParams, bool invert, int pFrom, } // 1) derivative wrt trackParam_t parameters - for (int ipar = fNLocExtPar; ipar--;) { + for (int ipar = mNLocExtPar; ipar--;) { - SetParams(probD, kNRDClones, getX(), getAlpha(), extendedParams, true); + setParams(probD, kNRDClones, getX(), getAlpha(), extendedParams, true); if (invert) for (int ic = kNRDClones; ic--;) probD[ic].invert(); @@ -239,26 +239,26 @@ bool AliAlgTrack::CalcResidDeriv(double* extendedParams, bool invert, int pFrom, // for (int icl = 0; icl < kRichardsonN; icl++) { // calculate kRichardsonN variations with del, del/2, del/4... varDelta[icl] = del; - ModParam(probD[(icl << 1) + 0], ipar, del); - ModParam(probD[(icl << 1) + 1], ipar, -del); + modParam(probD[(icl << 1) + 0], ipar, del); + modParam(probD[(icl << 1) + 1], ipar, -del); del *= 0.5; } // propagate varied tracks to each point for (int ip = pFrom; ip != pTo; ip += pinc) { // points are ordered against track direction - AliAlgPoint* pnt = GetPoint(ip); - if (!PropagateParamToPoint(probD, kNRDClones, pnt)) + AliAlgPoint* pnt = getPoint(ip); + if (!propagateParamToPoint(probD, kNRDClones, pnt)) return false; - // if (pnt->ContainsMaterial()) { // apply material corrections - if (!ApplyMatCorr(probD, kNRDClones, extendedParams, pnt)) + // if (pnt->containsMaterial()) { // apply material corrections + if (!applyMatCorr(probD, kNRDClones, extendedParams, pnt)) return false; // } // - if (pnt->ContainsMeasurement()) { - int offsDer = ip * fNLocPar + ipar; - RichardsonDeriv(probD, varDelta, pnt, fDResDLocA[0][offsDer], fDResDLocA[1][offsDer]); // calculate derivatives + if (pnt->containsMeasurement()) { + int offsDer = ip * mNLocPar + ipar; + richardsonDeriv(probD, varDelta, pnt, mDResDLocA[0][offsDer], mDResDLocA[1][offsDer]); // calculate derivatives if (invert && kInvElem[ipar] < 0) { - fDResDLocA[0][offsDer] = -fDResDLocA[0][offsDer]; - fDResDLocA[1][offsDer] = -fDResDLocA[1][offsDer]; + mDResDLocA[0][offsDer] = -mDResDLocA[0][offsDer]; + mDResDLocA[1][offsDer] = -mDResDLocA[1][offsDer]; } } } // loop over points @@ -267,10 +267,10 @@ bool AliAlgTrack::CalcResidDeriv(double* extendedParams, bool invert, int pFrom, // 2) now vary material effect related parameters: MS and eventually ELoss // for (int ip = pFrom; ip != pTo; ip += pinc) { // points are ordered against track direction - AliAlgPoint* pnt = GetPoint(ip); + AliAlgPoint* pnt = getPoint(ip); // // global derivatives at this point - if (pnt->ContainsMeasurement() && !CalcResidDerivGlo(pnt)) { + if (pnt->containsMeasurement() && !calcResidDerivGlo(pnt)) { #if DEBUG > 3 AliWarningF("Failed on global derivatives calculation at point %d", ip); pnt->print("meas"); @@ -278,20 +278,20 @@ bool AliAlgTrack::CalcResidDeriv(double* extendedParams, bool invert, int pFrom, return false; } // - if (!pnt->ContainsMaterial()) + if (!pnt->containsMaterial()) continue; // - int nParFreeI = pnt->GetNMatPar(); + int nParFreeI = pnt->getNMatPar(); // // array delta gives desired variation of parameters in trackParam_t definition, // while the variation should be done for parameters in the frame where the vector // of material corrections has diagonal cov. matrix -> rotate the delta to this frame double deltaMatD[kNKinParBON]; - pnt->DiagMatCorr(delta, deltaMatD); + pnt->diagMatCorr(delta, deltaMatD); // // printf("Vary %d [%+.3e %+.3e %+.3e %+.3e] ",ip,deltaMatD[0],deltaMatD[1],deltaMatD[2],deltaMatD[3]); pnt->print(); - int offsI = pnt->GetMaxLocVarID() - nParFreeI; // the parameters for this point start with this offset + int offsI = pnt->getMaxLocVarID() - nParFreeI; // the parameters for this point start with this offset // they are irrelevant for the points upstream for (int ipar = 0; ipar < nParFreeI; ipar++) { // loop over DOFs related to MS and ELoss are point ip double del = deltaMatD[ipar]; @@ -299,7 +299,7 @@ bool AliAlgTrack::CalcResidDeriv(double* extendedParams, bool invert, int pFrom, // We will vary the tracks starting from the original parameters propagated to given point // and stored there (before applying material corrections for this point) // - SetParams(probD, kNRDClones, pnt->GetXPoint(), pnt->GetAlphaSens(), pnt->GetTrParamWSB(), false); + setParams(probD, kNRDClones, pnt->getXPoint(), pnt->getAlphaSens(), pnt->getTrParamWSB(), false); // no need for eventual track inversion here: if needed, this is already done in ParamWSB // int offsIP = offsI + ipar; // parameter entry in the extendedParams array @@ -311,41 +311,41 @@ bool AliAlgTrack::CalcResidDeriv(double* extendedParams, bool invert, int pFrom, extendedParams[offsIP] += del; // // apply varied material effects : incremented by delta - if (!ApplyMatCorr(probD[(icl << 1) + 0], extendedParams, pnt)) + if (!applyMatCorr(probD[(icl << 1) + 0], extendedParams, pnt)) return false; // // apply varied material effects : decremented by delta extendedParams[offsIP] = parOrig - del; - if (!ApplyMatCorr(probD[(icl << 1) + 1], extendedParams, pnt)) + if (!applyMatCorr(probD[(icl << 1) + 1], extendedParams, pnt)) return false; // extendedParams[offsIP] = parOrig; del *= 0.5; } - if (pnt->ContainsMeasurement()) { // calculate derivatives at the scattering point itself - int offsDerIP = ip * fNLocPar + offsIP; - RichardsonDeriv(probD, varDelta, pnt, fDResDLocA[0][offsDerIP], fDResDLocA[1][offsDerIP]); // calculate derivatives for ip - // printf("DR SELF: %e %e at %d (%d)\n",fDResDLocA[0][offsDerIP], fDResDLocA[1][offsDerIP],offsI, offsDerIP); + if (pnt->containsMeasurement()) { // calculate derivatives at the scattering point itself + int offsDerIP = ip * mNLocPar + offsIP; + richardsonDeriv(probD, varDelta, pnt, mDResDLocA[0][offsDerIP], mDResDLocA[1][offsDerIP]); // calculate derivatives for ip + // printf("DR SELF: %e %e at %d (%d)\n",mDResDLocA[0][offsDerIP], mDResDLocA[1][offsDerIP],offsI, offsDerIP); } // // loop over points whose residuals can be affected by the material effects on point ip for (int jp = ip + pinc; jp != pTo; jp += pinc) { - AliAlgPoint* pntJ = GetPoint(jp); + AliAlgPoint* pntJ = getPoint(jp); // printf(" DerFor:%d ",jp); pntJ->print(); - if (!PropagateParamToPoint(probD, kNRDClones, pntJ)) + if (!propagateParamToPoint(probD, kNRDClones, pntJ)) return false; // - if (pntJ->ContainsMaterial()) { // apply material corrections - if (!ApplyMatCorr(probD, kNRDClones, extendedParams, pntJ)) + if (pntJ->containsMaterial()) { // apply material corrections + if (!applyMatCorr(probD, kNRDClones, extendedParams, pntJ)) return false; } // - if (pntJ->ContainsMeasurement()) { - int offsDerJ = jp * fNLocPar + offsIP; + if (pntJ->containsMeasurement()) { + int offsDerJ = jp * mNLocPar + offsIP; // calculate derivatives - RichardsonDeriv(probD, varDelta, pntJ, fDResDLocA[0][offsDerJ], fDResDLocA[1][offsDerJ]); + richardsonDeriv(probD, varDelta, pntJ, mDResDLocA[0][offsDerJ], mDResDLocA[1][offsDerJ]); } // } // << loop over points whose residuals can be affected by the material effects on point ip @@ -356,31 +356,31 @@ bool AliAlgTrack::CalcResidDeriv(double* extendedParams, bool invert, int pFrom, } //______________________________________________________ -bool AliAlgTrack::CalcResidDerivGlo(AliAlgPoint* pnt) +bool AliAlgTrack::calcResidDerivGlo(AliAlgPoint* pnt) { // calculate residuals derivatives over point's sensor and its parents global params double deriv[AliAlgVol::kNDOFGeom * 3]; // - const AliAlgSens* sens = pnt->GetSensor(); + const AliAlgSens* sens = pnt->getSensor(); const AliAlgVol* vol = sens; // precalculated track parameters - double snp = pnt->GetTrParamWSA(kParSnp), tgl = pnt->GetTrParamWSA(kParTgl); + double snp = pnt->getTrParamWSA(kParSnp), tgl = pnt->getTrParamWSA(kParTgl); // precalculate track slopes to account tracking X veriation // these are coeffs to translate deltaX of the point to deltaY and deltaZ of track double cspi = 1. / Sqrt((1 - snp) * (1 + snp)), slpY = snp * cspi, slpZ = tgl * cspi; // - pnt->SetDGloOffs(fNGloPar); // mark 1st entry of derivatives + pnt->setDGloOffs(mNGloPar); // mark 1st entry of derivatives do { // measurement residuals - int nfree = vol->GetNDOFFree(); + int nfree = vol->getNDOFFree(); if (!nfree) continue; // no free parameters? - sens->DPosTraDParGeom(pnt, deriv, vol == sens ? 0 : vol); + sens->dPosTraDParGeom(pnt, deriv, vol == sens ? 0 : vol); // - CheckExpandDerGloBuffer(fNGloPar + nfree); // if needed, expand derivatives buffer + checkExpandDerGloBuffer(mNGloPar + nfree); // if needed, expand derivatives buffer // for (int ip = 0; ip < AliAlgVol::kNDOFGeom; ip++) { // we need only free parameters - if (!vol->IsFreeDOF(ip)) + if (!vol->isFreeDOF(ip)) continue; double* dXYZ = &deriv[ip * 3]; // tracking XYZ derivatives over this parameter // residual is defined as diagonalized track_estimate - measured Y,Z in tracking frame @@ -390,42 +390,42 @@ bool AliAlgTrack::CalcResidDerivGlo(AliAlgPoint* pnt) // effect of changing X is accounted neglecting track curvature to preserve linearity // // store diagonalized residuals in track buffer - pnt->DiagonalizeResiduals((dXYZ[AliAlgPoint::kX] * slpY - dXYZ[AliAlgPoint::kY]), + pnt->diagonalizeResiduals((dXYZ[AliAlgPoint::kX] * slpY - dXYZ[AliAlgPoint::kY]), (dXYZ[AliAlgPoint::kX] * slpZ - dXYZ[AliAlgPoint::kZ]), - fDResDGloA[0][fNGloPar], fDResDGloA[1][fNGloPar]); + mDResDGloA[0][mNGloPar], mDResDGloA[1][mNGloPar]); // and register global ID of varied parameter - fGloParIDA[fNGloPar] = vol->GetParGloID(ip); - fNGloPar++; + mGloParIDA[mNGloPar] = vol->getParGloID(ip); + mNGloPar++; } // - } while ((vol = vol->GetParent())); + } while ((vol = vol->getParent())); // // eventual detector calibration parameters - const AliAlgDet* det = sens->GetDetector(); + const AliAlgDet* det = sens->getDetector(); int ndof = 0; - if (det && (ndof = det->GetNCalibDOFs())) { + if (det && (ndof = det->getNCalibDOFs())) { // if needed, expand derivatives buffer - CheckExpandDerGloBuffer(fNGloPar + det->GetNCalibDOFsFree()); + checkExpandDerGloBuffer(mNGloPar + det->getNCalibDOFsFree()); for (int idf = 0; idf < ndof; idf++) { - if (!det->IsFreeDOF(idf)) + if (!det->isFreeDOF(idf)) continue; - sens->DPosTraDParCalib(pnt, deriv, idf, 0); - pnt->DiagonalizeResiduals((deriv[AliAlgPoint::kX] * slpY - deriv[AliAlgPoint::kY]), + sens->dPosTraDParCalib(pnt, deriv, idf, 0); + pnt->diagonalizeResiduals((deriv[AliAlgPoint::kX] * slpY - deriv[AliAlgPoint::kY]), (deriv[AliAlgPoint::kX] * slpZ - deriv[AliAlgPoint::kZ]), - fDResDGloA[0][fNGloPar], fDResDGloA[1][fNGloPar]); + mDResDGloA[0][mNGloPar], mDResDGloA[1][mNGloPar]); // and register global ID of varied parameter - fGloParIDA[fNGloPar] = det->GetParGloID(idf); - fNGloPar++; + mGloParIDA[mNGloPar] = det->getParGloID(idf); + mNGloPar++; } } // - pnt->SetNGloDOFs(fNGloPar - pnt->GetDGloOffs()); // mark number of global derivatives filled + pnt->setNGloDOFs(mNGloPar - pnt->getDGloOffs()); // mark number of global derivatives filled // return true; } //______________________________________________________ -bool AliAlgTrack::CalcResiduals(const double* extendedParams) +bool AliAlgTrack::calcResiduals(const double* extendedParams) { // Propagate for given local params and calculate residuals // The 1st 4 or 5 elements of extendedParams vector should be the reference trackParam_t @@ -434,26 +434,26 @@ bool AliAlgTrack::CalcResiduals(const double* extendedParams) // They correspond to kink parameters // (trackParam_t_after_material - trackParam_t_before_material) // rotated to frame where they error matrix is diagonal. Their conversion to trackParam_t - // increment will be done locally in the ApplyMatCorr routine. + // increment will be done locally in the applyMatCorr routine. // // If extendedParams are not provided, use internal extendedParams array // if (!extendedParams) - extendedParams = fLocParA; - int np = GetNPoints(); - fChi2 = 0; - fNDF = 0; + extendedParams = mLocParA; + int np = getNPoints(); + mChi2 = 0; + mNDF = 0; // // collision track or cosmic lower leg - if (!CalcResiduals(extendedParams, fNeedInv[0], GetInnerPointID(), 0)) { + if (!calcResiduals(extendedParams, mNeedInv[0], getInnerPointID(), 0)) { #if DEBUG > 3 LOG(warn) << "Failed on residuals calculation 0"; #endif return false; } // - if (IsCosmic()) { // cosmic upper leg - if (!CalcResiduals(extendedParams, fNeedInv[1], GetInnerPointID() + 1, np - 1)) { + if (isCosmic()) { // cosmic upper leg + if (!calcResiduals(extendedParams, mNeedInv[1], getInnerPointID() + 1, np - 1)) { #if DEBUG > 3 LOG(warn) << "Failed on residuals calculation 1"; #endif @@ -461,13 +461,13 @@ bool AliAlgTrack::CalcResiduals(const double* extendedParams) } } // - fNDF -= fNLocExtPar; - SetResidDone(); + mNDF -= mNLocExtPar; + setResidDone(); return true; } //______________________________________________________ -bool AliAlgTrack::CalcResiduals(const double* extendedParams, bool invert, int pFrom, int pTo) +bool AliAlgTrack::calcResiduals(const double* extendedParams, bool invert, int pFrom, int pTo) { // Calculate residuals for the single leg from points pFrom to pT // The 1st 4 or 5 elements of extendedParams vector should be corrections to @@ -477,10 +477,10 @@ bool AliAlgTrack::CalcResiduals(const double* extendedParams, bool invert, int p // They correspond to kink parameters // (trackParam_t_after_material - trackParam_t_before_material) // rotated to frame where they error matrix is diagonal. Their conversion to trackParam_t - // increment will be done locally in the ApplyMatCorr routine. + // increment will be done locally in the applyMatCorr routine. // trackParam_t probe; - SetParams(probe, getX(), getAlpha(), extendedParams, true); + setParams(probe, getX(), getAlpha(), extendedParams, true); if (invert) probe.invert(); int pinc; @@ -493,48 +493,48 @@ bool AliAlgTrack::CalcResiduals(const double* extendedParams, bool invert, int p } // for (int ip = pFrom; ip != pTo; ip += pinc) { // points are ordered against track direction - AliAlgPoint* pnt = GetPoint(ip); - if (!PropagateParamToPoint(probe, pnt)) + AliAlgPoint* pnt = getPoint(ip); + if (!propagateParamToPoint(probe, pnt)) return false; // // store the current track kinematics at the point BEFORE applying eventual material - // corrections. This kinematics will be later varied around supplied parameters (in the CalcResidDeriv) - pnt->SetTrParamWSB(probe.getParams()); + // corrections. This kinematics will be later varied around supplied parameters (in the calcResidDeriv) + pnt->setTrParamWSB(probe.getParams()); // // account for materials // if (pnt->ContainsMaterial()) { // apply material corrections - if (!ApplyMatCorr(probe, extendedParams, pnt)) + if (!applyMatCorr(probe, extendedParams, pnt)) return false; // } - pnt->SetTrParamWSA(probe.getParams()); + pnt->setTrParamWSA(probe.getParams()); // - if (pnt->ContainsMeasurement()) { // need to calculate residuals in the frame where errors are orthogonal - pnt->GetResidualsDiag(probe.getParams(), fResidA[0][ip], fResidA[1][ip]); - fChi2 += fResidA[0][ip] * fResidA[0][ip] / pnt->GetErrDiag(0); - fChi2 += fResidA[1][ip] * fResidA[1][ip] / pnt->GetErrDiag(1); - fNDF += 2; + if (pnt->containsMeasurement()) { // need to calculate residuals in the frame where errors are orthogonal + pnt->getResidualsDiag(probe.getParams(), mResidA[0][ip], mResidA[1][ip]); + mChi2 += mResidA[0][ip] * mResidA[0][ip] / pnt->getErrDiag(0); + mChi2 += mResidA[1][ip] * mResidA[1][ip] / pnt->getErrDiag(1); + mNDF += 2; } // - if (pnt->ContainsMaterial()) { + if (pnt->containsMaterial()) { // material degrees of freedom do not contribute to NDF since they are constrained by 0 expectation - int nCorrPar = pnt->GetNMatPar(); - const double* corrDiag = &fLocParA[pnt->GetMaxLocVarID() - nCorrPar]; // corrections in diagonalized frame - float* corCov = pnt->GetMatCorrCov(); // correction diagonalized covariance + int nCorrPar = pnt->getNMatPar(); + const double* corrDiag = &mLocParA[pnt->getMaxLocVarID() - nCorrPar]; // corrections in diagonalized frame + float* corCov = pnt->getMatCorrCov(); // correction diagonalized covariance for (int i = 0; i < nCorrPar; i++) - fChi2 += corrDiag[i] * corrDiag[i] / corCov[i]; + mChi2 += corrDiag[i] * corrDiag[i] / corCov[i]; } } return true; } //______________________________________________________ -bool AliAlgTrack::PropagateParamToPoint(trackParam_t* tr, int nTr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt) +bool AliAlgTrack::propagateParamToPoint(trackParam_t* tr, int nTr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt) { // Propagate set of tracks to the point (only parameters, no error matrix) // VECTORIZE this // for (int itr = nTr; itr--;) { - if (!PropagateParamToPoint(tr[itr], pnt, maxStep)) { + if (!propagateParamToPoint(tr[itr], pnt, maxStep)) { #if DEBUG > 3 LOG(fatal) << "Failed on clone " << itr << " propagation "; tr[itr].print(); @@ -547,25 +547,25 @@ bool AliAlgTrack::PropagateParamToPoint(trackParam_t* tr, int nTr, const AliAlgP } //______________________________________________________ -bool AliAlgTrack::PropagateParamToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt) +bool AliAlgTrack::propagateParamToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt) { // propagate tracks to the point (only parameters, no error matrix) - return Propagate(tr, pnt, maxStep, maxSnp, mt, nullptr); + return propagate(tr, pnt, maxStep, maxSnp, mt, nullptr); } //______________________________________________________ -bool AliAlgTrack::PropagateToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT) +bool AliAlgTrack::propagateToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT) { // propagate tracks to the point. If matCor is true, then material corrections will be applied. // if matPar pointer is provided, it will be filled by total x2x0 and signed xrho - return Propagate(tr, pnt, maxStep, maxSnp, mt, tLT); + return propagate(tr, pnt, maxStep, maxSnp, mt, tLT); } -bool AliAlgTrack::Propagate(trackParam_t& track, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT) +bool AliAlgTrack::propagate(trackParam_t& track, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT) { - if (!track.rotate(pnt->GetAlphaSens())) { + if (!track.rotate(pnt->getAlphaSens())) { #if DEBUG > 3 - LOG(error) << "Failed to rotate to alpha=" << pnt->GetAlphaSens(); + LOG(error) << "Failed to rotate to alpha=" << pnt->getAlphaSens(); tr.print(); pnt->Print(); #endif @@ -575,7 +575,7 @@ bool AliAlgTrack::Propagate(trackParam_t& track, const AliAlgPoint* pnt, double const int signCorr = [this, &pnt, &track, maxStep] { const double dx = maxStep - track.getX(); const int dir = dx > 0.f ? 1 : -1; - if (pnt->IsInvDir()) { + if (pnt->isInvDir()) { // upper leg of a cosmic -> inward facing track return dir; } else { @@ -583,7 +583,7 @@ bool AliAlgTrack::Propagate(trackParam_t& track, const AliAlgPoint* pnt, double return -dir; } }(); - return Propagator::Instance()->propagateTo(track, pnt->GetXPoint(), pnt->GetUseBzOnly(), maxSnp, maxStep, mt, tLT, signCorr); + return Propagator::Instance()->propagateTo(track, pnt->getXPoint(), pnt->getUseBzOnly(), maxSnp, maxStep, mt, tLT, signCorr); } /* @@ -632,7 +632,7 @@ bool AliAlgTrack::ApplyMS(trackParam_t& trPar, double tms,double pms) */ //______________________________________________________ -bool AliAlgTrack::ApplyMatCorr(trackParam_t& trPar, const double* corrPar, const AliAlgPoint* pnt) +bool AliAlgTrack::applyMatCorr(trackParam_t& trPar, const double* corrPar, const AliAlgPoint* pnt) { // Modify track param (e.g. trackParam_t) in the tracking frame // by delta accounting for material effects @@ -640,25 +640,25 @@ bool AliAlgTrack::ApplyMatCorr(trackParam_t& trPar, const double* corrPar, const // DIAGONALIZING ITS COVARIANCE MATRIX! // transform parameters from the frame diagonalizing the errors to track frame double corr[kNKinParBON] = {0}; - if (pnt->ContainsMaterial()) { // are there free params from meterials? - int nCorrPar = pnt->GetNMatPar(); - const double* corrDiag = &corrPar[pnt->GetMaxLocVarID() - nCorrPar]; // material corrections for this point start here - pnt->UnDiagMatCorr(corrDiag, corr); // this is to account for MS and RANDOM Eloss (if varied) + if (pnt->containsMaterial()) { // are there free params from meterials? + int nCorrPar = pnt->getNMatPar(); + const double* corrDiag = &corrPar[pnt->getMaxLocVarID() - nCorrPar]; // material corrections for this point start here + pnt->unDiagMatCorr(corrDiag, corr); // this is to account for MS and RANDOM Eloss (if varied) } // to this we should add expected parameters modification due to the deterministic eloss - float* detELoss = pnt->GetMatCorrExp(); + float* detELoss = pnt->getMatCorrExp(); for (int i = kNKinParBON; i--;) corr[i] += detELoss[i]; //corr[kParQ2Pt] += detELoss[kParQ2Pt]; // printf("apply corr UD %+.3e %+.3e %+.3e %+.3e %+.3e\n",corr[0],corr[1],corr[2],corr[3],corr[4]); // printf(" corr D %+.3e %+.3e %+.3e %+.3e\n",corrDiag[0],corrDiag[1],corrDiag[2],corrDiag[3]); // printf("at point :"); pnt->print(); - return ApplyMatCorr(trPar, corr); + return applyMatCorr(trPar, corr); // } //______________________________________________________ -bool AliAlgTrack::ApplyMatCorr(trackParam_t& trPar, const double* corr) +bool AliAlgTrack::applyMatCorr(trackParam_t& trPar, const double* corr) { // Modify track param (e.g. trackParam_t) in the tracking frame // by delta accounting for material effects @@ -684,7 +684,7 @@ bool AliAlgTrack::ApplyMatCorr(trackParam_t& trPar, const double* corr) } //______________________________________________________ -bool AliAlgTrack::ApplyMatCorr(trackParam_t* trSet, int ntr, const double* corrDiag, const AliAlgPoint* pnt) +bool AliAlgTrack::applyMatCorr(trackParam_t* trSet, int ntr, const double* corrDiag, const AliAlgPoint* pnt) { // Modify set of track params (e.g. trackParam_t) in the tracking frame // by delta accounting for material effects @@ -692,21 +692,21 @@ bool AliAlgTrack::ApplyMatCorr(trackParam_t* trSet, int ntr, const double* corrD // COVARIANCE MATRIX // transform parameters from the frame diagonalizing the errors to track frame double corr[kNKinParBON] = {0}; - if (pnt->ContainsMaterial()) { // are there free params from meterials? - int nCorrPar = pnt->GetNMatPar(); - const double* corrDiagP = &corrDiag[pnt->GetMaxLocVarID() - nCorrPar]; // material corrections for this point start here - pnt->UnDiagMatCorr(corrDiagP, corr); + if (pnt->containsMaterial()) { // are there free params from meterials? + int nCorrPar = pnt->getNMatPar(); + const double* corrDiagP = &corrDiag[pnt->getMaxLocVarID() - nCorrPar]; // material corrections for this point start here + pnt->unDiagMatCorr(corrDiagP, corr); } - float* detELoss = pnt->GetMatCorrExp(); + float* detELoss = pnt->getMatCorrExp(); for (int i = kNKinParBON; i--;) corr[i] += detELoss[i]; - // if (!pnt->GetELossVaried()) corr[kParQ2Pt] = pnt->GetMatCorrExp()[kParQ2Pt]; // fixed eloss expected effect + // if (!pnt->getELossVaried()) corr[kParQ2Pt] = pnt->getMatCorrExp()[kParQ2Pt]; // fixed eloss expected effect // printf("apply corr UD %+.3e %+.3e %+.3e %+.3e\n",corr[0],corr[1],corr[2],corr[3]); // printf(" corr D %+.3e %+.3e %+.3e %+.3e\n",corrDiagP[0],corrDiagP[1],corrDiagP[2],corrDiagP[3]); // printf("at point :"); pnt->print(); // for (int itr = ntr; itr--;) { - if (!ApplyMatCorr(trSet[itr], corr)) { + if (!applyMatCorr(trSet[itr], corr)) { #if DEBUG > 3 LOG(error) << "Failed on clone %d materials" << itr; trSet[itr].print(); @@ -718,7 +718,7 @@ bool AliAlgTrack::ApplyMatCorr(trackParam_t* trSet, int ntr, const double* corrD } //______________________________________________ -double AliAlgTrack::RichardsonExtrap(double* val, int ord) +double AliAlgTrack::richardsonExtrap(double* val, int ord) { // Calculate Richardson extrapolation of order ord (starting from 1) // The array val should contain estimates ord+1 of derivatives with variations @@ -735,7 +735,7 @@ double AliAlgTrack::RichardsonExtrap(double* val, int ord) } //______________________________________________ -double AliAlgTrack::RichardsonExtrap(const double* val, int ord) +double AliAlgTrack::richardsonExtrap(const double* val, int ord) { // Calculate Richardson extrapolation of order ord (starting from 1) // The array val should contain estimates ord+1 of derivatives with variations @@ -754,7 +754,7 @@ double AliAlgTrack::RichardsonExtrap(const double* val, int ord) } //______________________________________________ -void AliAlgTrack::RichardsonDeriv(const trackParam_t* trSet, const double* delta, const AliAlgPoint* pnt, double& derY, double& derZ) +void AliAlgTrack::richardsonDeriv(const trackParam_t* trSet, const double* delta, const AliAlgPoint* pnt, double& derY, double& derZ) { // Calculate Richardson derivatives for diagonalized Y and Z from a set of kRichardsonN pairs // of tracks with same parameter of i-th pair varied by +-delta[i] @@ -762,13 +762,13 @@ void AliAlgTrack::RichardsonDeriv(const trackParam_t* trSet, const double* delta // for (int icl = 0; icl < kRichardsonN; icl++) { // calculate kRichardsonN variations with del, del/2, del/4... double resYVP = 0, resYVN = 0, resZVP = 0, resZVN = 0; - pnt->GetResidualsDiag(trSet[(icl << 1) + 0].getParams(), resYVP, resZVP); // variation with +delta - pnt->GetResidualsDiag(trSet[(icl << 1) + 1].getParams(), resYVN, resZVN); // variation with -delta + pnt->getResidualsDiag(trSet[(icl << 1) + 0].getParams(), resYVP, resZVP); // variation with +delta + pnt->getResidualsDiag(trSet[(icl << 1) + 1].getParams(), resYVN, resZVN); // variation with -delta derRichY[icl] = 0.5 * (resYVP - resYVN) / delta[icl]; // 2-point symmetric derivatives derRichZ[icl] = 0.5 * (resZVP - resZVN) / delta[icl]; } - derY = RichardsonExtrap(derRichY, kRichardsonOrd); // dY/dPar - derZ = RichardsonExtrap(derRichZ, kRichardsonOrd); // dZ/dPar + derY = richardsonExtrap(derRichY, kRichardsonOrd); // dY/dPar + derZ = richardsonExtrap(derRichZ, kRichardsonOrd); // dZ/dPar // } @@ -776,65 +776,65 @@ void AliAlgTrack::RichardsonDeriv(const trackParam_t* trSet, const double* delta void AliAlgTrack::Print(Option_t* opt) const { // print track data - printf("%s ", IsCosmic() ? " Cosmic " : "Collision "); + printf("%s ", isCosmic() ? " Cosmic " : "Collision "); trackParam_t::print(); printf("N Free Par: %d (Kinem: %d) | Npoints: %d (Inner:%d) | M : %.3f | Chi2Ini:%.1f Chi2: %.1f/%d", - fNLocPar, fNLocExtPar, GetNPoints(), GetInnerPointID(), fMass, fChi2Ini, fChi2, fNDF); - if (IsCosmic()) { - int npLow = GetInnerPointID(); - int npUp = GetNPoints() - npLow - 1; - printf(" [Low:%.1f/%d Up:%.1f/%d]", fChi2CosmDn, npLow, fChi2CosmUp, npUp); + mNLocPar, mNLocExtPar, getNPoints(), getInnerPointID(), mMass, mChi2Ini, mChi2, mNDF); + if (isCosmic()) { + int npLow = getInnerPointID(); + int npUp = getNPoints() - npLow - 1; + printf(" [Low:%.1f/%d Up:%.1f/%d]", mChi2CosmDn, npLow, mChi2CosmUp, npUp); } printf("\n"); // TString optS = opt; optS.ToLower(); - bool res = optS.Contains("r") && GetResidDone(); - bool der = optS.Contains("d") && GetDerivDone(); + bool res = optS.Contains("r") && getResidDone(); + bool der = optS.Contains("d") && getDerivDone(); bool par = optS.Contains("lc"); // local param corrections bool paru = optS.Contains("lcu"); // local param corrections in track param frame // if (par) { printf("Ref.track corr: "); - for (int i = 0; i < fNLocExtPar; i++) - printf("%+.3e ", fLocParA[i]); + for (int i = 0; i < mNLocExtPar; i++) + printf("%+.3e ", mLocParA[i]); printf("\n"); } // if (optS.Contains("p") || res || der) { - for (int ip = 0; ip < GetNPoints(); ip++) { + for (int ip = 0; ip < getNPoints(); ip++) { printf("#%3d ", ip); - AliAlgPoint* pnt = GetPoint(ip); + AliAlgPoint* pnt = getPoint(ip); pnt->Print(opt); // - if (res && pnt->ContainsMeasurement()) { + if (res && pnt->containsMeasurement()) { printf(" Residuals : %+.3e %+.3e -> Pulls: %+7.2f %+7.2f\n", - GetResidual(0, ip), GetResidual(1, ip), - GetResidual(0, ip) / sqrt(pnt->GetErrDiag(0)), GetResidual(1, ip) / sqrt(pnt->GetErrDiag(1))); + getResidual(0, ip), getResidual(1, ip), + getResidual(0, ip) / sqrt(pnt->getErrDiag(0)), getResidual(1, ip) / sqrt(pnt->getErrDiag(1))); } - if (der && pnt->ContainsMeasurement()) { - for (int ipar = 0; ipar < fNLocPar; ipar++) { - printf(" Dres/dp%03d : %+.3e %+.3e\n", ipar, GetDResDLoc(0, ip)[ipar], GetDResDLoc(1, ip)[ipar]); + if (der && pnt->containsMeasurement()) { + for (int ipar = 0; ipar < mNLocPar; ipar++) { + printf(" Dres/dp%03d : %+.3e %+.3e\n", ipar, getDResDLoc(0, ip)[ipar], getDResDLoc(1, ip)[ipar]); } } // - if (par && pnt->ContainsMaterial()) { // material corrections - int nCorrPar = pnt->GetNMatPar(); - const double* corrDiag = &fLocParA[pnt->GetMaxLocVarID() - nCorrPar]; + if (par && pnt->containsMaterial()) { // material corrections + int nCorrPar = pnt->getNMatPar(); + const double* corrDiag = &mLocParA[pnt->getMaxLocVarID() - nCorrPar]; printf(" Corr.Diag: "); for (int i = 0; i < nCorrPar; i++) printf("%+.3e ", corrDiag[i]); printf("\n"); printf(" Corr.Pull: "); - float* corCov = pnt->GetMatCorrCov(); // correction covariance - //float *corExp = pnt->GetMatCorrExp(); // correction expectation + float* corCov = pnt->getMatCorrCov(); // correction covariance + //float *corExp = pnt->getMatCorrExp(); // correction expectation for (int i = 0; i < nCorrPar; i++) printf("%+.3e ", (corrDiag[i] /* - corExp[i]*/) / Sqrt(corCov[i])); printf("\n"); if (paru) { // print also mat.corrections in track frame double corr[5] = {0}; - pnt->UnDiagMatCorr(corrDiag, corr); - // if (!pnt->GetELossVaried()) corr[kParQ2Pt] = pnt->GetMatCorrExp()[kParQ2Pt]; // fixed eloss expected effect + pnt->unDiagMatCorr(corrDiag, corr); + // if (!pnt->getELossVaried()) corr[kParQ2Pt] = pnt->getMatCorrExp()[kParQ2Pt]; // fixed eloss expected effect printf(" Corr.Track: "); for (int i = 0; i < kNKinParBON; i++) printf("%+.3e ", corr[i]); @@ -846,76 +846,76 @@ void AliAlgTrack::Print(Option_t* opt) const } //______________________________________________ -void AliAlgTrack::DumpCoordinates() const +void AliAlgTrack::dumpCoordinates() const { // print various coordinates for inspection printf("gpx/D:gpy/D:gpz/D:gtxb/D:gtyb/D:gtzb/D:gtxa/D:gtya/D:gtza/D:alp/D:px/D:py/D:pz/D:tyb/D:tzb/D:tya/D:tza/D:ey/D:ez/D\n"); - for (int ip = 0; ip < GetNPoints(); ip++) { - AliAlgPoint* pnt = GetPoint(ip); - if (!pnt->ContainsMeasurement()) + for (int ip = 0; ip < getNPoints(); ip++) { + AliAlgPoint* pnt = getPoint(ip); + if (!pnt->containsMeasurement()) continue; - pnt->DumpCoordinates(); + pnt->dumpCoordinates(); } } //______________________________________________ -bool AliAlgTrack::IniFit() +bool AliAlgTrack::iniFit() { // perform initial fit of the track // // trackParam_t trc = *this; // - if (!GetFieldON()) { // for field-off data impose nominal momentum + if (!getFieldON()) { // for field-off data impose nominal momentum } - fChi2 = fChi2CosmUp = fChi2CosmDn = 0; + mChi2 = mChi2CosmUp = mChi2CosmDn = 0; // // the points are ranged from outer to inner for collision tracks, // and from outer point of lower leg to outer point of upper leg for the cosmic track // // the fit will always start from the outgoing track in inward direction - if (!FitLeg(trc, 0, GetInnerPointID(), fNeedInv[0])) { + if (!fitLeg(trc, 0, getInnerPointID(), mNeedInv[0])) { #if DEBUG > 3 - LOG(warn) << "Failed FitLeg 0"; + LOG(warn) << "Failed fitLeg 0"; trc.print(); #endif return false; // collision track or cosmic lower leg } // - // printf("Lower leg: %d %d\n",0,GetInnerPointID()); trc.print(); + // printf("Lower leg: %d %d\n",0,getInnerPointID()); trc.print(); // - if (IsCosmic()) { - fChi2CosmDn = fChi2; + if (isCosmic()) { + mChi2CosmDn = mChi2; trackParam_t trcU = trc; - if (!FitLeg(trcU, GetNPoints() - 1, GetInnerPointID() + 1, fNeedInv[1])) { //fit upper leg of cosmic track + if (!fitLeg(trcU, getNPoints() - 1, getInnerPointID() + 1, mNeedInv[1])) { //fit upper leg of cosmic track #if DEBUG > 3 - LOG(warn) << "Failed FitLeg 0"; + LOG(warn) << "Failed fitLeg 0"; trc.print(); #endif return false; // collision track or cosmic lower leg } // // propagate to reference point, which is the inner point of lower leg - const AliAlgPoint* refP = GetPoint(GetInnerPointID()); - if (!PropagateToPoint(trcU, refP, MaxDefStep, MaxDefSnp, DefMatCorrType)) + const AliAlgPoint* refP = getPoint(getInnerPointID()); + if (!propagateToPoint(trcU, refP, MaxDefStep, MaxDefSnp, DefMatCorrType)) return false; // - fChi2CosmUp = fChi2 - fChi2CosmDn; - // printf("Upper leg: %d %d\n",GetInnerPointID()+1,GetNPoints()-1); trcU.print(); + mChi2CosmUp = mChi2 - mChi2CosmDn; + // printf("Upper leg: %d %d\n",getInnerPointID()+1,getNPoints()-1); trcU.print(); // - if (!CombineTracks(trc, trcU)) + if (!combineTracks(trc, trcU)) return false; //printf("Combined\n"); trc.print(); } - CopyFrom(&trc); + copyFrom(&trc); // - fChi2Ini = fChi2; + mChi2Ini = mChi2; return true; } //______________________________________________ -bool AliAlgTrack::CombineTracks(trackParam_t& trcL, const trackParam_t& trcU) +bool AliAlgTrack::combineTracks(trackParam_t& trcL, const trackParam_t& trcU) { // Assign to trcL the combined tracks (Kalman update of trcL by trcU) // The trcL and trcU MUST be defined at same X,Alpha @@ -936,7 +936,7 @@ bool AliAlgTrack::CombineTracks(trackParam_t& trcL, const trackParam_t& trcU) // const covMat_t& covU = trcU.getCov(); // const covMat_t& covL = trcL.getCov(); // - int mtSize = GetFieldON() ? kNKinParBON : kNKinParBOFF; + int mtSize = getFieldON() ? kNKinParBON : kNKinParBOFF; TMatrixD matCL(mtSize, mtSize), matCLplCU(mtSize, mtSize); TVectorD vl(mtSize), vUmnvL(mtSize); // @@ -974,15 +974,15 @@ bool AliAlgTrack::CombineTracks(trackParam_t& trcL, const trackParam_t& trcU) for (int i = mtSize; i--;) for (int j = mtSize; j--;) chi2 += matCLplCU(i, j) * vUmnvL[i] * vUmnvL[j]; - fChi2 += chi2; + mChi2 += chi2; // - // printf("Combined: Chi2Tot:%.2f ChiUp:%.2f ChiDn:%.2f ChiCmb:%.2f\n",fChi2,fChi2CosmUp,fChi2CosmDn, chi2); + // printf("Combined: Chi2Tot:%.2f ChiUp:%.2f ChiDn:%.2f ChiCmb:%.2f\n",mChi2,mChi2CosmUp,mChi2CosmDn, chi2); return true; } //______________________________________________ -bool AliAlgTrack::FitLeg(trackParam_t& trc, int pFrom, int pTo, bool& inv) +bool AliAlgTrack::fitLeg(trackParam_t& trc, int pFrom, int pTo, bool& inv) { // perform initial fit of the track // the fit will always start from the outgoing track in inward direction (i.e. if cosmics - bottom leg) @@ -999,11 +999,11 @@ bool AliAlgTrack::FitLeg(trackParam_t& trc, int pFrom, int pTo, bool& inv) 0, 0, 0, 0, kErrRelPtI * kErrRelPtI}; // // prepare seed at outer point - AliAlgPoint* p0 = GetPoint(pFrom); - double phi = trc.getPhi(), alp = p0->GetAlphaSens(); - BringTo02Pi(phi); - BringTo02Pi(alp); - double dphi = DeltaPhiSmall(phi, alp); // abs delta angle + AliAlgPoint* p0 = getPoint(pFrom); + double phi = trc.getPhi(), alp = p0->getAlphaSens(); + bringTo02Pi(phi); + bringTo02Pi(alp); + double dphi = deltaPhiSmall(phi, alp); // abs delta angle if (dphi > Pi() / 2.) { // need to invert the track to new frame inv = true; // printf("Fit in %d %d Delta: %.3f -> Inverting for\n",pFrom,pTo,dphi); @@ -1012,18 +1012,18 @@ bool AliAlgTrack::FitLeg(trackParam_t& trc, int pFrom, int pTo, bool& inv) trc.invert(); // printf("After Inv "); trc.print(); } - if (!trc.rotateParam(p0->GetAlphaSens())) { + if (!trc.rotateParam(p0->getAlphaSens())) { #if DEBUG > 3 - AliWarningF("Failed on rotateParam to %f", p0->GetAlphaSens()); + AliWarningF("Failed on rotateParam to %f", p0->getAlphaSens()); trc.print(); #endif return false; } - if (!PropagateParamToPoint(trc, p0, MaxDefStep)) { - // if (!PropagateToPoint(trc,p0,5,30,true)) { - //trc.PropagateParamOnlyTo(p0->GetXPoint()+kOverShootX,AliTrackerBase::GetBz())) { + if (!propagateParamToPoint(trc, p0, MaxDefStep)) { + // if (!propagateToPoint(trc,p0,5,30,true)) { + //trc.PropagateParamOnlyTo(p0->getXPoint()+kOverShootX,AliTrackerBase::GetBz())) { #if DEBUG > 3 - AliWarningF("Failed on PropagateParamOnlyTo to %f", p0->GetXPoint() + kOverShootX); + AliWarningF("Failed on PropagateParamOnlyTo to %f", p0->getXPoint() + kOverShootX); trc.print(); #endif return false; @@ -1041,18 +1041,18 @@ bool AliAlgTrack::FitLeg(trackParam_t& trc, int pFrom, int pTo, bool& inv) } // for (int ip = pFrom; ip != pTo; ip += pinc) { // inward fit from outer point - AliAlgPoint* pnt = GetPoint(ip); + AliAlgPoint* pnt = getPoint(ip); // - // printf("*** FitLeg %d (%d %d)\n",ip,pFrom,pTo); + // printf("*** fitLeg %d (%d %d)\n",ip,pFrom,pTo); // printf("Before propagate: "); trc.print(); - if (!PropagateToPoint(trc, pnt, MaxDefStep, MaxDefSnp, DefMatCorrType)) { + if (!propagateToPoint(trc, pnt, MaxDefStep, MaxDefSnp, DefMatCorrType)) { return false; } - if (pnt->ContainsMeasurement()) { - if (pnt->GetNeedUpdateFromTrack()) - pnt->UpdatePointByTrackInfo(&trc); - const double* yz = pnt->GetYZTracking(); - const double* errYZ = pnt->GetYZErrTracking(); + if (pnt->containsMeasurement()) { + if (pnt->getNeedUpdateFromTrack()) + pnt->updatePointByTrackInfo(&trc); + const double* yz = pnt->getYZTracking(); + const double* errYZ = pnt->getYZErrTracking(); double chi = trc.getPredictedChi2(yz, errYZ); //printf("***>> fitleg-> Y: %+e %+e / Z: %+e %+e -> Chi2: %e | %+e %+e\n",yz[0],trc.GetY(),yz[1],trc.GetZ(),chi, // trc.Phi(),trc.GetAlpha()); @@ -1064,8 +1064,8 @@ bool AliAlgTrack::FitLeg(trackParam_t& trc, int pFrom, int pTo, bool& inv) #endif return false; } - fChi2 += chi; - // printf("After update: (%f) -> %f\n",chi,fChi2); trc.print(); + mChi2 += chi; + // printf("After update: (%f) -> %f\n",chi,mChi2); trc.print(); } } // @@ -1078,7 +1078,7 @@ bool AliAlgTrack::FitLeg(trackParam_t& trc, int pFrom, int pTo, bool& inv) } //______________________________________________ -bool AliAlgTrack::ResidKalman() +bool AliAlgTrack::residKalman() { // calculate residuals from bi-directional Kalman smoother // ATTENTION: this method modifies workspaces of the points!!! @@ -1099,34 +1099,34 @@ bool AliAlgTrack::ResidKalman() // trackParam_t trc = *this; // - int pID = 0, nPnt = GetNPoints(); + int pID = 0, nPnt = getNPoints(); ; AliAlgPoint* pnt = 0; // get 1st measured point - while (pID < nPnt && !(pnt = GetPoint(pID))->ContainsMeasurement()) + while (pID < nPnt && !(pnt = getPoint(pID))->containsMeasurement()) pID++; if (!pnt) return false; - double phi = trc.getPhi(), alp = pnt->GetAlphaSens(); - BringTo02Pi(phi); - BringTo02Pi(alp); - double dphi = DeltaPhiSmall(phi, alp); + double phi = trc.getPhi(), alp = pnt->getAlphaSens(); + bringTo02Pi(phi); + bringTo02Pi(alp); + double dphi = deltaPhiSmall(phi, alp); if (dphi > Pi() / 2.) { // need to invert the track to new frame inv = true; trc.invert(); } // prepare track seed at 1st valid point - if (!trc.rotateParam(pnt->GetAlphaSens())) { + if (!trc.rotateParam(pnt->getAlphaSens())) { #if DEBUG > 3 - AliWarningF("Failed on rotateParam to %f", pnt->GetAlphaSens()); + AliWarningF("Failed on rotateParam to %f", pnt->getAlphaSens()); trc.print(); #endif return false; } - if (!PropagateParamToPoint(trc, pnt, MaxDefStep)) { - //if (!trc.PropagateParamOnlyTo(pnt->GetXPoint()+kOverShootX,AliTrackerBase::GetBz())) { + if (!propagateParamToPoint(trc, pnt, MaxDefStep)) { + //if (!trc.PropagateParamOnlyTo(pnt->getXPoint()+kOverShootX,AliTrackerBase::GetBz())) { #if DEBUG > 3 - AliWarningF("Failed on PropagateParamOnlyTo to %f", pnt->GetXPoint() + kOverShootX); + AliWarningF("Failed on PropagateParamOnlyTo to %f", pnt->getXPoint() + kOverShootX); trc.print(); #endif return false; @@ -1139,29 +1139,29 @@ bool AliAlgTrack::ResidKalman() double chifwd = 0, chibwd = 0; // inward fit for (int ip = 0; ip < nPnt; ip++) { - pnt = GetPoint(ip); - if (pnt->IsInvDir() != inv) { // crossing point where the track should be inverted? + pnt = getPoint(ip); + if (pnt->isInvDir() != inv) { // crossing point where the track should be inverted? trc.invert(); inv = !inv; } // printf("*** ResidKalm %d (%d %d)\n",ip,0,nPnt); // printf("Before propagate: "); trc.print(); - if (!PropagateToPoint(trc, pnt, MaxDefStep, MaxDefSnp, DefMatCorrType)) { + if (!propagateToPoint(trc, pnt, MaxDefStep, MaxDefSnp, DefMatCorrType)) { return false; } - if (!pnt->ContainsMeasurement()) + if (!pnt->containsMeasurement()) continue; - const double* yz = pnt->GetYZTracking(); - const double* errYZ = pnt->GetYZErrTracking(); + const double* yz = pnt->getYZTracking(); + const double* errYZ = pnt->getYZErrTracking(); // store track position/errors before update in the point WorkSpace-A - double* ws = (double*)pnt->GetTrParamWSA(); + double* ws = (double*)pnt->getTrParamWSA(); ws[0] = trc.getY(); ws[1] = trc.getZ(); ws[2] = trc.getSigmaY2(); ws[3] = trc.getSigmaZY(); ws[4] = trc.getSigmaZ2(); double chi = trc.getPredictedChi2(yz, errYZ); - // printf(">> INV%d (%9d): %+.2e %+.2e | %+.2e %+.2e %+.2e %+.2e %+.2e | %.2e %d \n",ip,pnt->GetSensor()->GetInternalID(),yz[0],yz[1], ws[0],ws[1],ws[2],ws[3],ws[4],chi,inv); + // printf(">> INV%d (%9d): %+.2e %+.2e | %+.2e %+.2e %+.2e %+.2e %+.2e | %.2e %d \n",ip,pnt->getSensor()->getInternalID(),yz[0],yz[1], ws[0],ws[1],ws[2],ws[3],ws[4],chi,inv); // printf(">>Bef ");trc.print(); // printf("KLM Before update at %e %e\n",yz[0],yz[1]); trc.print(); if (!trc.update(yz, errYZ)) { @@ -1182,27 +1182,27 @@ bool AliAlgTrack::ResidKalman() trc.setCov(outwardQ2Pt2, 4, 4); // lowest diagonal element (Q2Pt2) for (int ip = nPnt; ip--;) { - pnt = GetPoint(ip); - if (pnt->IsInvDir() != inv) { // crossing point where the track should be inverted? + pnt = getPoint(ip); + if (pnt->isInvDir() != inv) { // crossing point where the track should be inverted? trc.invert(); inv = !inv; } - if (!PropagateToPoint(trc, pnt, MaxDefStep, MaxDefSnp, DefMatCorrType)) { + if (!propagateToPoint(trc, pnt, MaxDefStep, MaxDefSnp, DefMatCorrType)) { return false; } - if (!pnt->ContainsMeasurement()) + if (!pnt->containsMeasurement()) continue; - const double* yz = pnt->GetYZTracking(); - const double* errYZ = pnt->GetYZErrTracking(); + const double* yz = pnt->getYZTracking(); + const double* errYZ = pnt->getYZErrTracking(); // store track position/errors before update in the point WorkSpace-B - double* ws = (double*)pnt->GetTrParamWSB(); + double* ws = (double*)pnt->getTrParamWSB(); ws[0] = trc.getY(); ws[1] = trc.getZ(); ws[2] = trc.getSigmaY2(); ws[3] = trc.getSigmaZY(); ws[4] = trc.getSigmaZ2(); double chi = trc.getPredictedChi2(yz, errYZ); - // printf("<< OUT%d (%9d): %+.2e %+.2e | %+.2e %+.2e %+.2e %+.2e %+.2e | %.2e %d \n",ip,pnt->GetSensor()->GetInternalID(),yz[0],yz[1], ws[0],ws[1],ws[2],ws[3],ws[4],chi,inv); + // printf("<< OUT%d (%9d): %+.2e %+.2e | %+.2e %+.2e %+.2e %+.2e %+.2e | %.2e %d \n",ip,pnt->getSensor()->getInternalID(),yz[0],yz[1], ws[0],ws[1],ws[2],ws[3],ws[4],chi,inv); // printf("< 3 @@ -1217,11 +1217,11 @@ bool AliAlgTrack::ResidKalman() // // now compute smoothed prediction and residual for (int ip = 0; ip < nPnt; ip++) { - pnt = GetPoint(ip); - if (!pnt->ContainsMeasurement()) + pnt = getPoint(ip); + if (!pnt->containsMeasurement()) continue; - double* wsA = (double*)pnt->GetTrParamWSA(); // inward measurement - double* wsB = (double*)pnt->GetTrParamWSB(); // outward measurement + double* wsA = (double*)pnt->getTrParamWSA(); // inward measurement + double* wsB = (double*)pnt->getTrParamWSB(); // outward measurement double &yA = wsA[0], &zA = wsA[1], &sgAYY = wsA[2], &sgAYZ = wsA[3], &sgAZZ = wsA[4]; double &yB = wsB[0], &zB = wsB[1], &sgBYY = wsB[2], &sgBYZ = wsB[3], &sgBZZ = wsB[4]; // compute weighted average @@ -1244,36 +1244,36 @@ bool AliAlgTrack::ResidKalman() sgAYY -= k00 * sgAYY + k01 * sgAYZ; sgAYZ -= k00 * sgAYZt + k01 * sgAZZ; sgAZZ -= k10 * sgAYZt + k11 * sgAZZ; - // printf("|| WGH%d (%9d): | %+.2e %+.2e %+.2e %.2e %.2e\n",ip,pnt->GetSensor()->GetInternalID(), wsA[0],wsA[1],wsA[2],wsA[3],wsA[4]); + // printf("|| WGH%d (%9d): | %+.2e %+.2e %+.2e %.2e %.2e\n",ip,pnt->getSensor()->getInternalID(), wsA[0],wsA[1],wsA[2],wsA[3],wsA[4]); } // - fChi2 = chifwd; - SetKalmanDone(true); + mChi2 = chifwd; + setKalmanDone(true); return true; } //______________________________________________ -bool AliAlgTrack::ProcessMaterials() +bool AliAlgTrack::processMaterials() { // attach material effect info to alignment points trackParam_t trc = *this; // collision track of cosmic lower leg: move along track direction from last (middle for cosmic lower leg) // point (inner) to 1st one (outer) - if (fNeedInv[0]) + if (mNeedInv[0]) trc.invert(); // track needs to be inverted ? (should be for upper leg) - if (!ProcessMaterials(trc, GetInnerPointID(), 0)) { + if (!processMaterials(trc, getInnerPointID(), 0)) { #if DEBUG > 3 LOG(error) << "Failed to process materials for leg along the track"; #endif return false; } - if (IsCosmic()) { + if (isCosmic()) { // cosmic upper leg: move againg the track direction from middle point (inner) to last one (outer) trc = *this; - if (fNeedInv[1]) + if (mNeedInv[1]) trc.invert(); // track needs to be inverted ? - if (!ProcessMaterials(trc, GetInnerPointID() + 1, GetNPoints() - 1)) { + if (!processMaterials(trc, getInnerPointID() + 1, getNPoints() - 1)) { #if DEBUG > 3 LOG(error) << "Failed to process materials for leg against the track"; #endif @@ -1284,7 +1284,7 @@ bool AliAlgTrack::ProcessMaterials() } //______________________________________________ -bool AliAlgTrack::ProcessMaterials(trackParam_t& trc, int pFrom, int pTo) +bool AliAlgTrack::processMaterials(trackParam_t& trc, int pFrom, int pTo) { // attach material effect info to alignment points const int kMinNStep = 3; @@ -1328,12 +1328,12 @@ bool AliAlgTrack::ProcessMaterials(trackParam_t& trc, int pFrom, int pTo) } // for (int ip = pFrom; ip != pTo; ip += pinc) { // points are ordered against track direction - AliAlgPoint* pnt = GetPoint(ip); + AliAlgPoint* pnt = getPoint(ip); trc.setCov(kErrTiny); // assign tiny errors to both tracks tr0 = trc; // // printf("-> ProcMat %d (%d->%d)\n",ip,pFrom,pTo); - if (!PropagateToPoint(trc, pnt, MaxDefStep, MaxDefSnp, DefMatCorrType, &matTL)) { // with material corrections + if (!propagateToPoint(trc, pnt, MaxDefStep, MaxDefSnp, DefMatCorrType, &matTL)) { // with material corrections #if DEBUG > 3 LOG(error) << "Failed to take track to point" << ip << " (dir: " << pFrom << "->" pTo << ") with mat.corr."; trc.print(); @@ -1343,10 +1343,10 @@ bool AliAlgTrack::ProcessMaterials(trackParam_t& trc, int pFrom, int pTo) } // // is there enough material to consider the point as a scatterer? - pnt->SetContainsMaterial(matTL.getX2X0() * Abs(trc.getQ2Pt()) > GetMinX2X0Pt2Account()); + pnt->setContainsMaterial(matTL.getX2X0() * Abs(trc.getQ2Pt()) > getMinX2X0Pt2Account()); // // printf("-> ProcMat000 %d (%d->%d)\n",ip,pFrom,pTo); - if (!PropagateToPoint(tr0, pnt, MaxDefStep, MaxDefSnp, MatCorrType::USEMatCorrNONE)) { // no material corrections + if (!propagateToPoint(tr0, pnt, MaxDefStep, MaxDefSnp, MatCorrType::USEMatCorrNONE)) { // no material corrections #if DEBUG > 3 LOG(error) << "Failed to take track to point" << ip << " (dir: " << pFrom << "->" pTo << ") with mat.corr."; tr0.print(); @@ -1364,13 +1364,13 @@ bool AliAlgTrack::ProcessMaterials(trackParam_t& trc, int pFrom, int pTo) dcov[l] = cov1[l] - cov0[l]; for (int l = kNKinParBON; l--;) dpar[l] = par1[l] - par0[l]; // eloss affects all parameters! - pnt->SetMatCorrExp(dpar); + pnt->setMatCorrExp(dpar); //dpar[kParQ2Pt] = par1[kParQ2Pt] - par0[kParQ2Pt]; // only e-loss expectation is non-0 // - if (pnt->ContainsMaterial()) { + if (pnt->containsMaterial()) { // // MP2 handles only scalar residuals hence correlated matrix of material effect need to be diagonalized - bool eLossFree = pnt->GetELossVaried(); + bool eLossFree = pnt->getELossVaried(); int nParFree = eLossFree ? kNKinParBON : kNKinParBOFF; TMatrixDSym matCov(nParFree); for (int i = nParFree; i--;) @@ -1386,18 +1386,18 @@ bool AliAlgTrack::ProcessMaterials(trackParam_t& trc, int pFrom, int pTo) return false; #endif } - pnt->SetMatCovDiagonalizationMatrix(matEVec); // store diagonalization matrix - pnt->SetMatCovDiag(matDiag.GetEigenValues()); // store E.Values: diagonalized cov.matrix + pnt->setMatCovDiagonalizationMatrix(matEVec); // store diagonalization matrix + pnt->setMatCovDiag(matDiag.GetEigenValues()); // store E.Values: diagonalized cov.matrix if (!eLossFree) - pnt->SetMatCovDiagElem(kParQ2Pt, dcov[14]); + pnt->setMatCovDiagElem(kParQ2Pt, dcov[14]); // - pnt->SetX2X0(matTL.getX2X0()); - pnt->SetXTimesRho(matTL.getXRho()); + pnt->setX2X0(matTL.getX2X0()); + pnt->setXTimesRho(matTL.getXRho()); // } - if (pnt->ContainsMeasurement()) { // update track to have best possible kinematics - const double* yz = pnt->GetYZTracking(); - const double* errYZ = pnt->GetYZErrTracking(); + if (pnt->containsMeasurement()) { // update track to have best possible kinematics + const double* yz = pnt->getYZTracking(); + const double* errYZ = pnt->getYZErrTracking(); if (!trc.update(yz, errYZ)) { #if DEBUG > 3 AliWarningF("Failed on Update %f,%f {%f,%f,%f}", yz[0], yz[1], errYZ[0], errYZ[1], errYZ[2]); @@ -1414,25 +1414,25 @@ bool AliAlgTrack::ProcessMaterials(trackParam_t& trc, int pFrom, int pTo) } //______________________________________________ -void AliAlgTrack::SortPoints() +void AliAlgTrack::sortPoints() { // sort points in order against track direction: innermost point is last // for collision tracks. // For 2-leg cosmic tracks: 1st points of outgoing (lower) leg are added from large to // small radii, then the points of incomint (upper) leg are added in increasing R direction // - // The fInnerPointID will mark the id of the innermost point, i.e. the last one for collision-like + // The mInnerPointID will mark the id of the innermost point, i.e. the last one for collision-like // tracks and in case of cosmics - the point of lower leg with smallest R // - fPoints.Sort(); - int np = GetNPoints(); - fInnerPointID = np - 1; - if (IsCosmic()) { + mPoints.Sort(); + int np = getNPoints(); + mInnerPointID = np - 1; + if (isCosmic()) { for (int ip = np; ip--;) { - AliAlgPoint* pnt = GetPoint(ip); - if (pnt->IsInvDir()) + AliAlgPoint* pnt = getPoint(ip); + if (pnt->isInvDir()) continue; // this is a point of upper leg - fInnerPointID = ip; + mInnerPointID = ip; break; } } @@ -1440,25 +1440,25 @@ void AliAlgTrack::SortPoints() } //______________________________________________ -void AliAlgTrack::SetLocPars(const double* pars) +void AliAlgTrack::setLocPars(const double* pars) { // store loc par corrections - memcpy(fLocParA, pars, fNLocPar * sizeof(double)); + memcpy(mLocParA, pars, mNLocPar * sizeof(double)); } //______________________________________________ -void AliAlgTrack::CheckExpandDerGloBuffer(int minSize) +void AliAlgTrack::checkExpandDerGloBuffer(int minSize) { // if needed, expand global derivatives buffer - if (fGloParID.GetSize() < minSize) { - fGloParID.Set(minSize + 100); - fDResDGlo[0].Set(minSize + 100); - fDResDGlo[1].Set(minSize + 100); + if (mGloParID.GetSize() < minSize) { + mGloParID.Set(minSize + 100); + mDResDGlo[0].Set(minSize + 100); + mDResDGlo[1].Set(minSize + 100); // // reassign fast access arrays - fGloParIDA = fGloParID.GetArray(); - fDResDGloA[0] = fDResDGlo[0].GetArray(); - fDResDGloA[1] = fDResDGlo[1].GetArray(); + mGloParIDA = mGloParID.GetArray(); + mDResDGloA[0] = mDResDGlo[0].GetArray(); + mDResDGloA[1] = mDResDGlo[1].GetArray(); } } diff --git a/Detectors/Align/src/AliAlgVol.cxx b/Detectors/Align/src/AliAlgVol.cxx index 6b39462bf3ae0..36bff9808cf8f 100644 --- a/Detectors/Align/src/AliAlgVol.cxx +++ b/Detectors/Align/src/AliAlgVol.cxx @@ -120,51 +120,51 @@ namespace o2 namespace align { -const char* AliAlgVol::fgkFrameName[AliAlgVol::kNVarFrames] = {"LOC", "TRA"}; +const char* AliAlgVol::sFrameName[AliAlgVol::kNVarFrames] = {"LOC", "TRA"}; // -uint32_t AliAlgVol::fgDefGeomFree = +uint32_t AliAlgVol::sDefGeomFree = kDOFBitTX | kDOFBitTY | kDOFBitTZ | kDOFBitPS | kDOFBitTH | kDOFBitPH; // -const char* AliAlgVol::fgkDOFName[AliAlgVol::kNDOFGeom] = {"TX", "TY", "TZ", "PSI", "THT", "PHI"}; +const char* AliAlgVol::sDOFName[AliAlgVol::kNDOFGeom] = {"TX", "TY", "TZ", "PSI", "THT", "PHI"}; //_________________________________________________________ -AliAlgVol::AliAlgVol(const char* symname, int iid) : TNamed(symname, ""), fVarFrame(kTRA), fIntID(iid), fX(0), fAlp(0), fNDOFs(0), fDOF(0), fNDOFGeomFree(0), fNDOFFree(0), fConstrChild(kDefChildConstr) +AliAlgVol::AliAlgVol(const char* symname, int iid) : TNamed(symname, ""), mVarFrame(kTRA), mIntID(iid), mX(0), mAlp(0), mNDOFs(0), mDOF(0), mNDOFGeomFree(0), mNDOFFree(0), mConstrChild(kDefChildConstr) // , - fParent(0), - fChildren(0) + mParent(0), + mChildren(0) // , - fNProcPoints(0), - fFirstParGloID(-1), - fParVals(0), - fParErrs(0), - fParLabs(0) + mNProcPoints(0), + mFirstParGloID(-1), + mParVals(0), + mParErrs(0), + mParLabs(0) // , - fMatL2GReco(), - fMatL2G(), - fMatL2GIdeal(), - fMatT2L(), - fMatDeltaRefGlo() + mMatL2GReco(), + mMatL2G(), + mMatL2GIdeal(), + mMatT2L(), + mMatDeltaRefGlo() { // def c-tor - SetVolID(0); // volumes have no VID, unless it is sensor + setVolID(0); // volumes have no VID, unless it is sensor if (symname) { // real volumes have at least geometric degrees of freedom - SetNDOFs(kNDOFGeom); + setNDOFs(kNDOFGeom); } - SetFreeDOFPattern(fgDefGeomFree); + setFreeDOFPattern(sDefGeomFree); } //_________________________________________________________ AliAlgVol::~AliAlgVol() { // d-tor - delete fChildren; + delete mChildren; } //_________________________________________________________ -void AliAlgVol::Delta2Matrix(TGeoHMatrix& deltaM, const double* delta) const +void AliAlgVol::delta2Matrix(TGeoHMatrix& deltaM, const double* delta) const { // prepare delta matrix for the volume from its // local delta vector (AliAlignObj convension): dx,dy,dz,,theta,psi,phi @@ -182,20 +182,20 @@ void AliAlgVol::Delta2Matrix(TGeoHMatrix& deltaM, const double* delta) const } //__________________________________________________________________ -void AliAlgVol::GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const double* delta) const +void AliAlgVol::getDeltaT2LmodLOC(TGeoHMatrix& matMod, const double* delta) const { // prepare the variation matrix tau in volume TRACKING frame by applying // local delta of modification of LOCAL frame: // tra' = tau*tra = tau*T2L^-1*loc = T2L^-1*loc' = T2L^-1*delta*loc // tau = T2L^-1*delta*T2L - Delta2Matrix(matMod, delta); - matMod.Multiply(&GetMatrixT2L()); - const TGeoHMatrix& t2li = GetMatrixT2L().Inverse(); + delta2Matrix(matMod, delta); + matMod.Multiply(&getMatrixT2L()); + const TGeoHMatrix& t2li = getMatrixT2L().Inverse(); matMod.MultiplyLeft(&t2li); } //__________________________________________________________________ -void AliAlgVol::GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const double* delta, const TGeoHMatrix& relMat) const +void AliAlgVol::getDeltaT2LmodLOC(TGeoHMatrix& matMod, const double* delta, const TGeoHMatrix& relMat) const { // prepare the variation matrix tau in volume TRACKING frame by applying // local delta of modification of LOCAL frame of its PARENT; @@ -203,25 +203,25 @@ void AliAlgVol::GetDeltaT2LmodLOC(TGeoHMatrix& matMod, const double* delta, cons // // tra' = tau*tra = tau*T2L^-1*loc = T2L^-1*loc' = T2L^-1*relMat^-1*Delta*relMat*loc // tau = (relMat*T2L)^-1*Delta*(relMat*T2L) - Delta2Matrix(matMod, delta); + delta2Matrix(matMod, delta); TGeoHMatrix tmp = relMat; - tmp *= GetMatrixT2L(); + tmp *= getMatrixT2L(); matMod.Multiply(&tmp); const TGeoHMatrix& tmpi = tmp.Inverse(); matMod.MultiplyLeft(&tmpi); } //__________________________________________________________________ -void AliAlgVol::GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const double* delta) const +void AliAlgVol::getDeltaT2LmodTRA(TGeoHMatrix& matMod, const double* delta) const { // prepare the variation matrix tau in volume TRACKING frame by applying // local delta of modification of the same TRACKING frame: // tra' = tau*tra - Delta2Matrix(matMod, delta); + delta2Matrix(matMod, delta); } //__________________________________________________________________ -void AliAlgVol::GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const double* delta, const TGeoHMatrix& relMat) const +void AliAlgVol::getDeltaT2LmodTRA(TGeoHMatrix& matMod, const double* delta, const TGeoHMatrix& relMat) const { // prepare the variation matrix tau in volume TRACKING frame by applying // local delta of modification of TRACKING frame of its PARENT; @@ -230,19 +230,19 @@ void AliAlgVol::GetDeltaT2LmodTRA(TGeoHMatrix& matMod, const double* delta, cons // // tra' = tau*tra = tau*relMat^-1*TRA = relMat^-1*TAU*TRA = relMat^-1*TAU*relMat*tra // tau = relMat^-1*TAU*relMat - Delta2Matrix(matMod, delta); // TAU + delta2Matrix(matMod, delta); // TAU matMod.Multiply(&relMat); const TGeoHMatrix& reli = relMat.Inverse(); matMod.MultiplyLeft(&reli); } //_________________________________________________________ -int AliAlgVol::CountParents() const +int AliAlgVol::countParents() const { // count parents in the chain int cnt = 0; const AliAlgVol* p = this; - while ((p = p->GetParent())) + while ((p = p->getParent())) cnt++; return cnt; } @@ -254,60 +254,60 @@ void AliAlgVol::Print(const Option_t* opt) const TString opts = opt; opts.ToLower(); printf("Lev:%2d IntID:%7d %s | %2d nodes | Effective X:%8.4f Alp:%+.4f | Used Points: %d\n", - CountParents(), GetInternalID(), GetSymName(), GetNChildren(), fX, fAlp, fNProcPoints); - printf(" DOFs: Tot: %d (offs: %5d) Free: %d Geom: %d {", fNDOFs, fFirstParGloID, fNDOFFree, fNDOFGeomFree); + countParents(), getInternalID(), getSymName(), getNChildren(), mX, mAlp, mNProcPoints); + printf(" DOFs: Tot: %d (offs: %5d) Free: %d Geom: %d {", mNDOFs, mFirstParGloID, mNDOFFree, mNDOFGeomFree); for (int i = 0; i < kNDOFGeom; i++) - printf("%d", IsFreeDOF(i) ? 1 : 0); - printf("} in %s frame.", fgkFrameName[fVarFrame]); - if (GetNChildren()) { + printf("%d", isFreeDOF(i) ? 1 : 0); + printf("} in %s frame.", sFrameName[mVarFrame]); + if (getNChildren()) { printf(" Child.Constr: {"); for (int i = 0; i < kNDOFGeom; i++) - printf("%d", IsChildrenDOFConstrained(i) ? 1 : 0); + printf("%d", isChildrenDOFConstrained(i) ? 1 : 0); printf("}"); } - if (GetExcludeFromParentConstraint()) + if (getExcludeFromParentConstraint()) printf(" Excl.from parent constr."); printf("\n"); // - if (opts.Contains("par") && fParVals) { + if (opts.Contains("par") && mParVals) { printf(" Lb: "); - for (int i = 0; i < fNDOFs; i++) - printf("%10d ", GetParLab(i)); + for (int i = 0; i < mNDOFs; i++) + printf("%10d ", getParLab(i)); printf("\n"); printf(" Vl: "); - for (int i = 0; i < fNDOFs; i++) - printf("%+9.3e ", GetParVal(i)); + for (int i = 0; i < mNDOFs; i++) + printf("%+9.3e ", getParVal(i)); printf("\n"); printf(" Er: "); - for (int i = 0; i < fNDOFs; i++) - printf("%+9.3e ", GetParErr(i)); + for (int i = 0; i < mNDOFs; i++) + printf("%+9.3e ", getParErr(i)); printf("\n"); } if (opts.Contains("mat")) { // print matrices printf("L2G ideal : "); - GetMatrixL2GIdeal().Print(); + getMatrixL2GIdeal().Print(); printf("L2G misalign: "); - GetMatrixL2G().Print(); + getMatrixL2G().Print(); printf("L2G RecoTime: "); - GetMatrixL2GReco().Print(); + getMatrixL2GReco().Print(); printf("T2L (fake) : "); - GetMatrixT2L().Print(); + getMatrixT2L().Print(); } // } //____________________________________________ -void AliAlgVol::PrepareMatrixL2G(bool reco) +void AliAlgVol::prepareMatrixL2G(bool reco) { // extract from geometry L2G matrix, depending on reco flag, set it as a reco-time // or current alignment matrix - const char* path = GetSymName(); + const char* path = getSymName(); if (gGeoManager->GetAlignableEntry(path)) { const TGeoHMatrix* l2g = base::GeometryManager::getMatrix(path); if (!l2g) LOG(FATAL) << "Failed to find L2G matrix for alignable " << path; - reco ? SetMatrixL2GReco(*l2g) : SetMatrixL2G(*l2g); + reco ? setMatrixL2GReco(*l2g) : setMatrixL2G(*l2g); } else { // extract from path if (!gGeoManager->CheckPath(path)) LOG(FATAL) << "Volume path " << path << " is not valid!"; @@ -321,31 +321,31 @@ void AliAlgVol::PrepareMatrixL2G(bool reco) } else { l2g = *node->GetMatrix(); } - reco ? SetMatrixL2GReco(l2g) : SetMatrixL2G(l2g); + reco ? setMatrixL2GReco(l2g) : setMatrixL2G(l2g); } } //____________________________________________ -void AliAlgVol::PrepareMatrixL2GIdeal() +void AliAlgVol::prepareMatrixL2GIdeal() { // extract from geometry ideal L2G matrix TGeoHMatrix mtmp; - if (!base::GeometryManager::getOriginalMatrix(GetSymName(), mtmp)) - LOG(FATAL) << "Failed to find ideal L2G matrix for " << GetSymName(); - SetMatrixL2GIdeal(mtmp); + if (!base::GeometryManager::getOriginalMatrix(getSymName(), mtmp)) + LOG(FATAL) << "Failed to find ideal L2G matrix for " << getSymName(); + setMatrixL2GIdeal(mtmp); } //____________________________________________ -void AliAlgVol::PrepareMatrixT2L() +void AliAlgVol::prepareMatrixT2L() { // for non-sensors we define the fake tracking frame with the alpha angle being // the average angle of centers of its children // double tot[3] = {0, 0, 0}, loc[3] = {0, 0, 0}, glo[3]; - int nch = GetNChildren(); + int nch = getNChildren(); for (int ich = nch; ich--;) { - AliAlgVol* vol = GetChild(ich); - vol->GetMatrixL2GIdeal().LocalToMaster(loc, glo); + AliAlgVol* vol = getChild(ich); + vol->getMatrixL2GIdeal().LocalToMaster(loc, glo); for (int j = 3; j--;) tot[j] += glo[j]; } @@ -353,34 +353,34 @@ void AliAlgVol::PrepareMatrixT2L() for (int j = 3; j--;) tot[j] /= nch; // - fAlp = TMath::ATan2(tot[1], tot[0]); - AliAlgAux::BringToPiPM(fAlp); + mAlp = TMath::ATan2(tot[1], tot[0]); + AliAlgAux::bringToPiPM(mAlp); // - fX = TMath::Sqrt(tot[0] * tot[0] + tot[1] * tot[1]); + mX = TMath::Sqrt(tot[0] * tot[0] + tot[1] * tot[1]); // // 1st create Tracking to Global matrix - fMatT2L.Clear(); - fMatT2L.SetDx(fX); - fMatT2L.RotateZ(fAlp * RadToDeg()); + mMatT2L.Clear(); + mMatT2L.SetDx(mX); + mMatT2L.RotateZ(mAlp * RadToDeg()); // then convert it to Tracking to Local matrix - const TGeoHMatrix& l2gi = GetMatrixL2GIdeal().Inverse(); - fMatT2L.MultiplyLeft(&l2gi); + const TGeoHMatrix& l2gi = getMatrixL2GIdeal().Inverse(); + mMatT2L.MultiplyLeft(&l2gi); // } //____________________________________________ -void AliAlgVol::SetMatrixT2L(const TGeoHMatrix& m) +void AliAlgVol::setMatrixT2L(const TGeoHMatrix& m) { // set the T2L matrix and define tracking frame // Note that this method is used for the externally set matrices // (in case of sensors). For other volumes the tracking frame and matrix - // is defined in the PrepareMatrixT2L method - fMatT2L = m; - SetTrackingFrame(); + // is defined in the prepareMatrixT2L method + mMatT2L = m; + setTrackingFrame(); } //__________________________________________________________________ -void AliAlgVol::SetTrackingFrame() +void AliAlgVol::setTrackingFrame() { // Define tracking frame of the sensor // This method should be implemented for sensors, which receive the T2L @@ -389,113 +389,113 @@ void AliAlgVol::SetTrackingFrame() } //__________________________________________________________________ -void AliAlgVol::AssignDOFs(int& cntDOFs, float* pars, float* errs, int* labs) +void AliAlgVol::assignDOFs(int& cntDOFs, float* pars, float* errs, int* labs) { // Assigns offset of the DOFS of this volume in global array of DOFs, attaches arrays to volumes // - fParVals = pars + cntDOFs; - fParErrs = errs + cntDOFs; - fParLabs = labs + cntDOFs; - SetFirstParGloID(cntDOFs); - for (int i = 0; i < fNDOFs; i++) - fParLabs[i] = GetInternalID() * 100 + i; - cntDOFs += fNDOFs; // increment total DOFs count + mParVals = pars + cntDOFs; + mParErrs = errs + cntDOFs; + mParLabs = labs + cntDOFs; + setFirstParGloID(cntDOFs); + for (int i = 0; i < mNDOFs; i++) + mParLabs[i] = getInternalID() * 100 + i; + cntDOFs += mNDOFs; // increment total DOFs count // - int nch = GetNChildren(); // go over childs + int nch = getNChildren(); // go over childs for (int ich = 0; ich < nch; ich++) - GetChild(ich)->AssignDOFs(cntDOFs, pars, errs, labs); + getChild(ich)->assignDOFs(cntDOFs, pars, errs, labs); // return; } //__________________________________________________________________ -void AliAlgVol::InitDOFs() +void AliAlgVol::initDOFs() { // initialize degrees of freedom // // Do we need this strict condition? - if (GetInitDOFsDone()) + if (getInitDOFsDone()) LOG(FATAL) << "DOFs are already initialized for " << GetName(); - for (int i = 0; i < fNDOFs; i++) - if (fParErrs[i] < -9999 && IsZeroAbs(fParVals[i])) - FixDOF(i); - CalcFree(true); - SetInitDOFsDone(); + for (int i = 0; i < mNDOFs; i++) + if (mParErrs[i] < -9999 && isZeroAbs(mParVals[i])) + fixDOF(i); + calcFree(true); + setInitDOFsDone(); } //__________________________________________________________________ -void AliAlgVol::CalcFree(bool condFix) +void AliAlgVol::calcFree(bool condFix) { // calculate free dofs. If condFix==true, condition parameter a la pede, i.e. error < 0 - fNDOFFree = fNDOFGeomFree = 0; - for (int i = 0; i < fNDOFs; i++) { - if (!IsFreeDOF(i)) { + mNDOFFree = mNDOFGeomFree = 0; + for (int i = 0; i < mNDOFs; i++) { + if (!isFreeDOF(i)) { if (condFix) - SetParErr(i, -999); + setParErr(i, -999); continue; } - fNDOFFree++; + mNDOFFree++; if (i < kNDOFGeom) - fNDOFGeomFree++; + mNDOFGeomFree++; } // } //__________________________________________________________________ -void AliAlgVol::SetNDOFs(int n) +void AliAlgVol::setNDOFs(int n) { // book global degrees of freedom if (n < kNDOFGeom) n = kNDOFGeom; - fNDOFs = n; + mNDOFs = n; } //__________________________________________________________________ -void AliAlgVol::AddChild(AliAlgVol* ch) +void AliAlgVol::addChild(AliAlgVol* ch) { // add child volume - if (!fChildren) { - fChildren = new TObjArray(); - fChildren->SetOwner(false); + if (!mChildren) { + mChildren = new TObjArray(); + mChildren->SetOwner(false); } - fChildren->AddLast(ch); + mChildren->AddLast(ch); } //__________________________________________________________________ -void AliAlgVol::SetParVals(int npar, double* vl, double* er) +void AliAlgVol::setParVals(int npar, double* vl, double* er) { // set parameters - if (npar > fNDOFs) - LOG(FATAL) << "Volume " << GetName() << " has " << fNDOFs << " dofs"; + if (npar > mNDOFs) + LOG(FATAL) << "Volume " << GetName() << " has " << mNDOFs << " dofs"; for (int i = 0; i < npar; i++) { - fParVals[i] = vl[i]; - fParErrs[i] = er ? er[i] : 0; + mParVals[i] = vl[i]; + mParErrs[i] = er ? er[i] : 0; } } //__________________________________________________________________ -bool AliAlgVol::IsCondDOF(int i) const +bool AliAlgVol::isCondDOF(int i) const { // is DOF free and conditioned? - return (!IsZeroAbs(GetParVal(i)) || !IsZeroAbs(GetParErr(i))); + return (!isZeroAbs(getParVal(i)) || !isZeroAbs(getParErr(i))); } //______________________________________________________ -int AliAlgVol::FinalizeStat(AliAlgDOFStat* st) +int AliAlgVol::finalizeStat(AliAlgDOFStat* st) { // finalize statistics on processed points - fNProcPoints = 0; - for (int ich = GetNChildren(); ich--;) { - AliAlgVol* child = GetChild(ich); - fNProcPoints += child->FinalizeStat(st); + mNProcPoints = 0; + for (int ich = getNChildren(); ich--;) { + AliAlgVol* child = getChild(ich); + mNProcPoints += child->finalizeStat(st); } if (st) - FillDOFStat(st); - return fNProcPoints; + fillDOFStat(st); + return mNProcPoints; } //______________________________________________________ -void AliAlgVol::WritePedeInfo(FILE* parOut, const Option_t* opt) const +void AliAlgVol::writePedeInfo(FILE* parOut, const Option_t* opt) const { // contribute to params template file for PEDE enum { kOff, @@ -511,12 +511,12 @@ void AliAlgVol::WritePedeInfo(FILE* parOut, const Option_t* opt) const // // is there something to print ? int nCond(0), nFix(0), nDef(0); - for (int i = 0; i < fNDOFs; i++) { - if (!IsFreeDOF(i)) + for (int i = 0; i < mNDOFs; i++) { + if (!isFreeDOF(i)) nFix++; - if (IsCondDOF(i)) + if (isCondDOF(i)) nCond++; - if (!IsCondDOF(i) && IsFreeDOF(i)) + if (!isCondDOF(i) && isFreeDOF(i)) nDef++; } // @@ -528,42 +528,42 @@ void AliAlgVol::WritePedeInfo(FILE* parOut, const Option_t* opt) const // if (nCond || showDef || showFix || showNam) fprintf(parOut, "%s%s %s\t\tDOF/Free: %d/%d (%s) %s\n", comment[cmt], kKeyParam, comment[kOnOn], - GetNDOFs(), GetNDOFFree(), fgkFrameName[fVarFrame], GetName()); + getNDOFs(), getNDOFFree(), sFrameName[mVarFrame], GetName()); // if (nCond || showDef || showFix) { - for (int i = 0; i < fNDOFs; i++) { + for (int i = 0; i < mNDOFs; i++) { cmt = kOn; - if (IsCondDOF(i) || !IsFreeDOF(i)) + if (isCondDOF(i) || !isFreeDOF(i)) cmt = kOff; // free-conditioned : MUST print - else if (!IsFreeDOF(i)) { + else if (!isFreeDOF(i)) { if (!showFix) continue; } // Fixed: print commented if asked else if (!showDef) continue; // free-unconditioned: print commented if asked // - fprintf(parOut, "%s %9d %+e %+e\t%s %s p%d\n", comment[cmt], GetParLab(i), - GetParVal(i), GetParErr(i), comment[kOnOn], IsFreeDOF(i) ? " " : "FX", i); + fprintf(parOut, "%s %9d %+e %+e\t%s %s p%d\n", comment[cmt], getParLab(i), + getParVal(i), getParErr(i), comment[kOnOn], isFreeDOF(i) ? " " : "FX", i); } fprintf(parOut, "\n"); } // children volume - int nch = GetNChildren(); + int nch = getNChildren(); // for (int ich = 0; ich < nch; ich++) - GetChild(ich)->WritePedeInfo(parOut, opt); + getChild(ich)->writePedeInfo(parOut, opt); // } //_________________________________________________________________ -void AliAlgVol::CreateGloDeltaMatrix(TGeoHMatrix& deltaM) const +void AliAlgVol::createGloDeltaMatrix(TGeoHMatrix& deltaM) const { - // Create global matrix deltaM from fParVals array containing corrections. + // Create global matrix deltaM from mParVals array containing corrections. // This deltaM does not account for eventual prealignment // Volume knows if its variation was done in TRA or LOC frame // - CreateLocDeltaMatrix(deltaM); - const TGeoHMatrix& l2g = GetMatrixL2G(); + createLocDeltaMatrix(deltaM); + const TGeoHMatrix& l2g = getMatrixL2G(); const TGeoHMatrix& l2gi = l2g.Inverse(); deltaM.Multiply(&l2gi); deltaM.MultiplyLeft(&l2g); @@ -572,9 +572,9 @@ void AliAlgVol::CreateGloDeltaMatrix(TGeoHMatrix& deltaM) const /* //_________________________________________________________________ -void AliAlgVol::CreateGloDeltaMatrix(TGeoHMatrix &deltaM) const +void AliAlgVol::createGloDeltaMatrix(TGeoHMatrix &deltaM) const { - // Create global matrix deltaM from fParVals array containing corrections. + // Create global matrix deltaM from mParVals array containing corrections. // This deltaM does not account for eventual prealignment // Volume knows if its variation was done in TRA or LOC frame // @@ -583,14 +583,14 @@ void AliAlgVol::CreateGloDeltaMatrix(TGeoHMatrix &deltaM) const // Z = [ Prod_{k=0}^{j-1} G_k * deltaL_k * G^-1_k ] * G_j // with j=being the level of the volume in the hierarchy // - CreateLocDeltaMatrix(deltaM); - TGeoHMatrix zMat = GetMatrixL2G(); + createLocDeltaMatrix(deltaM); + TGeoHMatrix zMat = getMatrixL2G(); const AliAlgVol* par = this; - while( (par=par->GetParent()) ) { + while( (par=par->getParent()) ) { TGeoHMatrix locP; - par->CreateLocDeltaMatrix(locP); - locP.MultiplyLeft( &par->GetMatrixL2G() ); - locP.Multiply( &par->GetMatrixL2G().Inverse() ); + par->createLocDeltaMatrix(locP); + locP.MultiplyLeft( &par->getMatrixL2G() ); + locP.Multiply( &par->getMatrixL2G().Inverse() ); zMat.MultiplyLeft( &locP ); } deltaM.MultiplyLeft( &zMat ); @@ -600,7 +600,7 @@ void AliAlgVol::CreateGloDeltaMatrix(TGeoHMatrix &deltaM) const */ //_________________________________________________________________ -void AliAlgVol::CreatePreGloDeltaMatrix(TGeoHMatrix& deltaM) const +void AliAlgVol::createPreGloDeltaMatrix(TGeoHMatrix& deltaM) const { // Create prealignment global matrix deltaM from prealigned G and // original GO local-to-global matrices @@ -610,12 +610,12 @@ void AliAlgVol::CreatePreGloDeltaMatrix(TGeoHMatrix& deltaM) const // we get by induction // Delta_j = G_j * GO^-1_j * GO_{j-1} * G^-1_{j-1} // - deltaM = GetMatrixL2G(); - deltaM *= GetMatrixL2GIdeal().Inverse(); - const AliAlgVol* par = GetParent(); + deltaM = getMatrixL2G(); + deltaM *= getMatrixL2GIdeal().Inverse(); + const AliAlgVol* par = getParent(); if (par) { - deltaM *= par->GetMatrixL2GIdeal(); - deltaM *= par->GetMatrixL2G().Inverse(); + deltaM *= par->getMatrixL2GIdeal(); + deltaM *= par->getMatrixL2G().Inverse(); } // } @@ -623,7 +623,7 @@ void AliAlgVol::CreatePreGloDeltaMatrix(TGeoHMatrix& deltaM) const /* // this is an alternative lengthy way ! //_________________________________________________________________ -void AliAlgVol::CreatePreGloDeltaMatrix(TGeoHMatrix &deltaM) const +void AliAlgVol::createPreGloDeltaMatrix(TGeoHMatrix &deltaM) const { // Create prealignment global matrix deltaM from prealigned G and // original GO local-to-global matrices @@ -633,14 +633,14 @@ void AliAlgVol::CreatePreGloDeltaMatrix(TGeoHMatrix &deltaM) const // we get by induction // Delta_j = G_j * GO^-1_j * GO_{j-1} * G^-1_{j-1} // - CreatePreLocDeltaMatrix(deltaM); - TGeoHMatrix zMat = GetMatrixL2GIdeal(); + createPreLocDeltaMatrix(deltaM); + TGeoHMatrix zMat = getMatrixL2GIdeal(); const AliAlgVol* par = this; - while( (par=par->GetParent()) ) { + while( (par=par->getParent()) ) { TGeoHMatrix locP; - par->CreatePreLocDeltaMatrix(locP); - locP.MultiplyLeft( &par->GetMatrixL2GIdeal() ); - locP.Multiply( &par->GetMatrixL2GIdeal().Inverse() ); + par->createPreLocDeltaMatrix(locP); + locP.MultiplyLeft( &par->getMatrixL2GIdeal() ); + locP.Multiply( &par->getMatrixL2GIdeal().Inverse() ); zMat.MultiplyLeft( &locP ); } deltaM.MultiplyLeft( &zMat ); @@ -650,7 +650,7 @@ void AliAlgVol::CreatePreGloDeltaMatrix(TGeoHMatrix &deltaM) const */ //_________________________________________________________________ -void AliAlgVol::CreatePreLocDeltaMatrix(TGeoHMatrix& deltaM) const +void AliAlgVol::createPreLocDeltaMatrix(TGeoHMatrix& deltaM) const { // Create prealignment local matrix deltaM from prealigned G and // original GO local-to-global matrices @@ -660,30 +660,30 @@ void AliAlgVol::CreatePreLocDeltaMatrix(TGeoHMatrix& deltaM) const // we get by induction // delta_j = GO^-1_j * GO_{j-1} * G^-1_{j-1} * G^_{j} // - const AliAlgVol* par = GetParent(); - deltaM = GetMatrixL2GIdeal().Inverse(); + const AliAlgVol* par = getParent(); + deltaM = getMatrixL2GIdeal().Inverse(); if (par) { - deltaM *= par->GetMatrixL2GIdeal(); - deltaM *= par->GetMatrixL2G().Inverse(); + deltaM *= par->getMatrixL2GIdeal(); + deltaM *= par->getMatrixL2G().Inverse(); } - deltaM *= GetMatrixL2G(); + deltaM *= getMatrixL2G(); // } //_________________________________________________________________ -void AliAlgVol::CreateLocDeltaMatrix(TGeoHMatrix& deltaM) const +void AliAlgVol::createLocDeltaMatrix(TGeoHMatrix& deltaM) const { - // Create local matrix deltaM from fParVals array containing corrections. + // Create local matrix deltaM from mParVals array containing corrections. // This deltaM does not account for eventual prealignment // Volume knows if its variation was done in TRA or LOC frame double corr[kNDOFGeom]; for (int i = kNDOFGeom; i--;) - corr[i] = fParVals[i]; // we need doubles - Delta2Matrix(deltaM, corr); - if (IsFrameTRA()) { // we need corrections in local frame! + corr[i] = mParVals[i]; // we need doubles + delta2Matrix(deltaM, corr); + if (isFrameTRA()) { // we need corrections in local frame! // l' = T2L * delta_t * t = T2L * delta_t * T2L^-1 * l = delta_l * l // -> delta_l = T2L * delta_t * T2L^-1 - const TGeoHMatrix& t2l = GetMatrixT2L(); + const TGeoHMatrix& t2l = getMatrixT2L(); const TGeoHMatrix& t2li = t2l.Inverse(); deltaM.Multiply(&t2li); deltaM.MultiplyLeft(&t2l); @@ -692,7 +692,7 @@ void AliAlgVol::CreateLocDeltaMatrix(TGeoHMatrix& deltaM) const } //_________________________________________________________________ -void AliAlgVol::CreateAlignmenMatrix(TGeoHMatrix& alg) const +void AliAlgVol::createAlignmenMatrix(TGeoHMatrix& alg) const { // create final alignment matrix, accounting for eventual prealignment // @@ -706,51 +706,51 @@ void AliAlgVol::CreateAlignmenMatrix(TGeoHMatrix& alg) const // but this creates precision problem. // Therefore we use explicitly cached Deltas from prealignment object. // - CreateGloDeltaMatrix(alg); + createGloDeltaMatrix(alg); // - const AliAlgVol* par = GetParent(); + const AliAlgVol* par = getParent(); if (par) { TGeoHMatrix dchain; while (par) { - dchain.MultiplyLeft(&par->GetGlobalDeltaRef()); - par = par->GetParent(); + dchain.MultiplyLeft(&par->getGlobalDeltaRef()); + par = par->getParent(); } const TGeoHMatrix& dchaini = dchain.Inverse(); alg.Multiply(&dchain); alg.MultiplyLeft(&dchaini); } - alg *= GetGlobalDeltaRef(); + alg *= getGlobalDeltaRef(); /* // bad precision ? - alg.Multiply(&GetMatrixL2G()); - alg.Multiply(&GetMatrixL2GIdeal().Inverse()); + alg.Multiply(&getMatrixL2G()); + alg.Multiply(&getMatrixL2GIdeal().Inverse()); if (par) { - alg.MultiplyLeft(&par->GetMatrixL2G().Inverse()); - alg.MultiplyLeft(&par->GetMatrixL2GIdeal()); + alg.MultiplyLeft(&par->getMatrixL2G().Inverse()); + alg.MultiplyLeft(&par->getMatrixL2GIdeal()); } */ } /* //_________________________________________________________________ -void AliAlgVol::CreateAlignmenMatrix(TGeoHMatrix& alg) const +void AliAlgVol::createAlignmenMatrix(TGeoHMatrix& alg) const { // create final alignment matrix, accounting for eventual prealignment // // deltaGlo_j * X_{j-1} * PdeltaGlo_j * X^-1_{j-1} // // where deltaGlo_j is global alignment matrix for this volume at level j - // of herarchy, obtained from CreateGloDeltaMatrix. + // of herarchy, obtained from createGloDeltaMatrix. // PdeltaGlo_j is prealignment global matrix and // X_i = deltaGlo_i * deltaGlo_{i-1} .. deltaGle_0 // TGeoHMatrix delGloPre,matX; - CreateGloDeltaMatrix(alg); - CreatePreGloDeltaMatrix(delGloPre); + createGloDeltaMatrix(alg); + createPreGloDeltaMatrix(delGloPre); const AliAlgVol* par = this; - while( (par=par->GetParent()) ) { + while( (par=par->getParent()) ) { TGeoHMatrix parDelGlo; - par->CreateGloDeltaMatrix(parDelGlo); + par->createGloDeltaMatrix(parDelGlo); matX *= parDelGlo; } alg *= matX; @@ -761,132 +761,132 @@ void AliAlgVol::CreateAlignmenMatrix(TGeoHMatrix& alg) const */ //_________________________________________________________________ -void AliAlgVol::CreateAlignmentObjects(TClonesArray* arr) const +void AliAlgVol::createAlignmentObjects(TClonesArray* arr) const { // add to supplied array alignment object for itself and children TClonesArray& parr = *arr; TGeoHMatrix algM; - CreateAlignmenMatrix(algM); - // new (parr[parr.GetEntriesFast()]) AliAlignObjParams(GetName(), GetVolID(), algM, true); + createAlignmenMatrix(algM); + // new (parr[parr.GetEntriesFast()]) AliAlignObjParams(GetName(), getVolID(), algM, true); const double* translation = algM.GetTranslation(); const double* rotation = algM.GetRotationMatrix(); - new (parr[parr.GetEntriesFast()]) detectors::AlignParam(GetName(), GetVolID(), + new (parr[parr.GetEntriesFast()]) detectors::AlignParam(GetName(), getVolID(), translation[0], translation[1], translation[2], rotation[0], rotation[1], rotation[2], true); - int nch = GetNChildren(); + int nch = getNChildren(); for (int ich = 0; ich < nch; ich++) - GetChild(ich)->CreateAlignmentObjects(arr); + getChild(ich)->createAlignmentObjects(arr); } //_________________________________________________________________ -void AliAlgVol::UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta) +void AliAlgVol::updateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta) { - // recreate fMatL2GReco matrices from ideal L2G matrix and alignment objects + // recreate mMatL2GReco matrices from ideal L2G matrix and alignment objects // used during data reconstruction. For the volume at level J we have // L2G' = Delta_J * Delta_{J-1} *...* Delta_0 * L2GIdeal // cumulDelta is Delta_{J-1} * ... * Delta_0, supplied by the parent // - fMatL2GReco = fMatL2GIdeal; + mMatL2GReco = mMatL2GIdeal; // find alignment object for this volume int nalg = algArr->GetEntriesFast(); const detectors::AlignParam* par = nullptr; for (int i = 0; i < nalg; i++) { par = (detectors::AlignParam*)algArr->At(i); - if (!strcmp(par->getSymName(), GetSymName())) + if (!strcmp(par->getSymName(), getSymName())) break; par = 0; } TGeoHMatrix delta; if (!par) - LOG(INFO) << "Alignment for " << GetSymName() << " is absent in Reco-Time alignment object"; + LOG(INFO) << "Alignment for " << getSymName() << " is absent in Reco-Time alignment object"; else delta = par->createMatrix(); // par->GetMatrix(delta); if (cumulDelta) delta *= *cumulDelta; // - fMatL2GReco.MultiplyLeft(&delta); + mMatL2GReco.MultiplyLeft(&delta); // propagate to children - for (int ich = GetNChildren(); ich--;) - GetChild(ich)->UpdateL2GRecoMatrices(algArr, &delta); + for (int ich = getNChildren(); ich--;) + getChild(ich)->updateL2GRecoMatrices(algArr, &delta); // } //______________________________________________________ -bool AliAlgVol::OwnsDOFID(int id) const +bool AliAlgVol::ownsDOFID(int id) const { // check if DOF ID belongs to this volume or its children - if (id >= fFirstParGloID && id < fFirstParGloID + fNDOFs) + if (id >= mFirstParGloID && id < mFirstParGloID + mNDOFs) return true; // - for (int iv = GetNChildren(); iv--;) { - AliAlgVol* vol = GetChild(iv); - if (vol->OwnsDOFID(id)) + for (int iv = getNChildren(); iv--;) { + AliAlgVol* vol = getChild(iv); + if (vol->ownsDOFID(id)) return true; } return false; } //______________________________________________________ -AliAlgVol* AliAlgVol::GetVolOfDOFID(int id) const +AliAlgVol* AliAlgVol::getVolOfDOFID(int id) const { // gets volume owning this DOF ID - if (id >= fFirstParGloID && id < fFirstParGloID + fNDOFs) + if (id >= mFirstParGloID && id < mFirstParGloID + mNDOFs) return (AliAlgVol*)this; // - for (int iv = GetNChildren(); iv--;) { - AliAlgVol* vol = GetChild(iv); - if ((vol = vol->GetVolOfDOFID(id))) + for (int iv = getNChildren(); iv--;) { + AliAlgVol* vol = getChild(iv); + if ((vol = vol->getVolOfDOFID(id))) return vol; } return 0; } //______________________________________________________ -const char* AliAlgVol::GetDOFName(int i) const +const char* AliAlgVol::getDOFName(int i) const { // get name of DOF - return GetGeomDOFName(i); + return getGeomDOFName(i); } //______________________________________________________ -void AliAlgVol::FillDOFStat(AliAlgDOFStat* h) const +void AliAlgVol::fillDOFStat(AliAlgDOFStat* h) const { // fill statistics info hist if (!h) return; - int ndf = GetNDOFs(); - int dof0 = GetFirstParGloID(); - int stat = GetNProcessedPoints(); + int ndf = getNDOFs(); + int dof0 = getFirstParGloID(); + int stat = getNProcessedPoints(); for (int idf = 0; idf < ndf; idf++) { int dof = idf + dof0; - h->AddStat(dof, stat); + h->addStat(dof, stat); } } //________________________________________ -void AliAlgVol::AddAutoConstraints(TObjArray* constrArr) +void AliAlgVol::addAutoConstraints(TObjArray* constrArr) { // adds automatic constraints - int nch = GetNChildren(); + int nch = getNChildren(); // - if (HasChildrenConstraint()) { + if (hasChildrenConstraint()) { AliAlgConstraint* constr = new AliAlgConstraint(); - constr->SetConstrainPattern(fConstrChild); - constr->SetParent(this); + constr->setConstrainPattern(mConstrChild); + constr->setParent(this); for (int ich = nch; ich--;) { - AliAlgVol* child = GetChild(ich); - if (child->GetExcludeFromParentConstraint()) + AliAlgVol* child = getChild(ich); + if (child->getExcludeFromParentConstraint()) continue; - constr->AddChild(child); + constr->addChild(child); } - if (constr->GetNChildren()) + if (constr->getNChildren()) constrArr->Add(constr); else delete constr; } for (int ich = 0; ich < nch; ich++) { - GetChild(ich)->AddAutoConstraints(constrArr); + getChild(ich)->addAutoConstraints(constrArr); } } diff --git a/Detectors/Align/src/AliAlgVtx.cxx b/Detectors/Align/src/AliAlgVtx.cxx index 33cb108de5a5c..f2208d481720c 100644 --- a/Detectors/Align/src/AliAlgVtx.cxx +++ b/Detectors/Align/src/AliAlgVtx.cxx @@ -34,32 +34,32 @@ namespace align AliAlgVtx::AliAlgVtx() : AliAlgSens("Vertex", 0, 1) { // def c-tor - SetVarFrame(kLOC); - SetFreeDOFPattern(BIT(kDOFTX) | BIT(kDOFTY) | BIT(kDOFTZ)); + setVarFrame(kLOC); + setFreeDOFPattern(BIT(kDOFTX) | BIT(kDOFTY) | BIT(kDOFTZ)); // } //____________________________________________ -void AliAlgVtx::PrepareMatrixT2L() +void AliAlgVtx::prepareMatrixT2L() { // T2L matrix for vertex needs to be adjusted for every track // in order to have X axis along the track direction. - // This method assumes that the fAlp was already set accordingly + // This method assumes that the mAlp was already set accordingly // fX is fixed to 0 // - fMatT2L.Clear(); - fMatT2L.RotateZ(fAlp * RadToDeg()); - // fMatT2L.MultiplyLeft(&GetMatrixL2GIdeal().Inverse()); L2G=I !!! + mMatT2L.Clear(); + mMatT2L.RotateZ(mAlp * RadToDeg()); + // mMatT2L.MultiplyLeft(&getMatrixL2GIdeal().Inverse()); L2G=I !!! // } //____________________________________________ -void AliAlgVtx::ApplyCorrection(double* vtx) const +void AliAlgVtx::applyCorrection(double* vtx) const { // apply eventual correction to supplied vertex position - vtx[kDOFTX] += GetParVal(kDOFTX); - vtx[kDOFTY] += GetParVal(kDOFTY); - vtx[kDOFTZ] += GetParVal(kDOFTZ); + vtx[kDOFTX] += getParVal(kDOFTX); + vtx[kDOFTY] += getParVal(kDOFTY); + vtx[kDOFTZ] += getParVal(kDOFTZ); // } From d00180de4c8e0e94924adca7d66ce2544cf84461 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Wed, 14 Apr 2021 15:19:04 +0200 Subject: [PATCH 216/770] [ALIGN] rename alignment classes * AliAlgAux -> utils * AliAlgSteer -> Controller * AliAlgMPRecord -> Millepede2Record * AliAlgResFast -> ResidualsControllerFast * AliAlgRes -> ResidualsController * AliAlgVtx -> EventVertex * AliAlgTrack -> AlignmentTrack * AliAlgDet* -> AlignableDetector* * AliAlgSens* -> AlignableSensor* * AliAlgPoint -> AlignmentPoint * AliAlgVol -> AlignableVolume * AliAlgConstraint -> GeometricalConstraint * AliAlgDOFStat -> DOFStatistics --- Detectors/Align/CMakeLists.txt | 91 +++--- .../{AliAlgDet.h => AlignableDetector.h} | 114 +++---- ...AlgDetHMPID.h => AlignableDetectorHMPID.h} | 20 +- ...{AliAlgDetITS.h => AlignableDetectorITS.h} | 34 +- ...{AliAlgDetTOF.h => AlignableDetectorTOF.h} | 20 +- ...{AliAlgDetTPC.h => AlignableDetectorTPC.h} | 20 +- ...{AliAlgDetTRD.h => AlignableDetectorTRD.h} | 20 +- .../Align/{AliAlgSens.h => AlignableSensor.h} | 54 ++-- ...iAlgSensHMPID.h => AlignableSensorHMPID.h} | 20 +- .../{AliAlgSensITS.h => AlignableSensorITS.h} | 20 +- .../{AliAlgSensTOF.h => AlignableSensorTOF.h} | 20 +- .../{AliAlgSensTPC.h => AlignableSensorTPC.h} | 20 +- .../{AliAlgSensTRD.h => AlignableSensorTRD.h} | 22 +- .../Align/{AliAlgVol.h => AlignableVolume.h} | 40 +-- .../Align/{AliAlgPoint.h => AlignmentPoint.h} | 40 +-- .../Align/{AliAlgTrack.h => AlignmentTrack.h} | 56 ++-- .../Align/{AliAlgSteer.h => Controller.h} | 192 +++++------ .../{AliAlgDOFStat.h => DOFStatistics.h} | 24 +- .../Align/{AliAlgVtx.h => EventVertex.h} | 22 +- ...lgConstraint.h => GeometricalConstraint.h} | 42 +-- .../{AliAlgMPRecord.h => Millepede2Record.h} | 22 +- .../{AliAlgRes.h => ResidualsController.h} | 22 +- ...AlgResFast.h => ResidualsControllerFast.h} | 18 +- .../include/Align/{AliAlgAux.h => utils.h} | 55 +++- Detectors/Align/src/AliAlgAux.cxx | 59 ---- Detectors/Align/src/AlignLinkDef.h | 46 +-- .../{AliAlgDet.cxx => AlignableDetector.cxx} | 163 +++++----- ...etHMPID.cxx => AlignableDetectorHMPID.cxx} | 26 +- ...AlgDetITS.cxx => AlignableDetectorITS.cxx} | 84 ++--- ...AlgDetTOF.cxx => AlignableDetectorTOF.cxx} | 34 +- ...AlgDetTPC.cxx => AlignableDetectorTPC.cxx} | 30 +- ...AlgDetTRD.cxx => AlignableDetectorTRD.cxx} | 52 +-- .../{AliAlgSens.cxx => AlignableSensor.cxx} | 68 ++-- ...SensHMPID.cxx => AlignableSensorHMPID.cxx} | 32 +- ...iAlgSensITS.cxx => AlignableSensorITS.cxx} | 32 +- ...iAlgSensTOF.cxx => AlignableSensorTOF.cxx} | 32 +- ...iAlgSensTPC.cxx => AlignableSensorTPC.cxx} | 32 +- ...iAlgSensTRD.cxx => AlignableSensorTRD.cxx} | 44 +-- .../{AliAlgVol.cxx => AlignableVolume.cxx} | 162 +++++----- .../{AliAlgPoint.cxx => AlignmentPoint.cxx} | 44 +-- .../{AliAlgTrack.cxx => AlignmentTrack.cxx} | 148 ++++----- .../src/{AliAlgSteer.cxx => Controller.cxx} | 298 +++++++++--------- .../{AliAlgDOFStat.cxx => DOFStatistics.cxx} | 20 +- .../src/{AliAlgVtx.cxx => EventVertex.cxx} | 20 +- ...nstraint.cxx => GeometricalConstraint.cxx} | 32 +- ...liAlgMPRecord.cxx => Millepede2Record.cxx} | 28 +- ...{AliAlgRes.cxx => ResidualsController.cxx} | 38 +-- ...esFast.cxx => ResidualsControllerFast.cxx} | 28 +- 48 files changed, 1263 insertions(+), 1297 deletions(-) rename Detectors/Align/include/Align/{AliAlgDet.h => AlignableDetector.h} (68%) rename Detectors/Align/include/Align/{AliAlgDetHMPID.h => AlignableDetectorHMPID.h} (65%) rename Detectors/Align/include/Align/{AliAlgDetITS.h => AlignableDetectorITS.h} (69%) rename Detectors/Align/include/Align/{AliAlgDetTOF.h => AlignableDetectorTOF.h} (67%) rename Detectors/Align/include/Align/{AliAlgDetTPC.h => AlignableDetectorTPC.h} (67%) rename Detectors/Align/include/Align/{AliAlgDetTRD.h => AlignableDetectorTRD.h} (83%) rename Detectors/Align/include/Align/{AliAlgSens.h => AlignableSensor.h} (60%) rename Detectors/Align/include/Align/{AliAlgSensHMPID.h => AlignableSensorHMPID.h} (64%) rename Detectors/Align/include/Align/{AliAlgSensITS.h => AlignableSensorITS.h} (64%) rename Detectors/Align/include/Align/{AliAlgSensTOF.h => AlignableSensorTOF.h} (68%) rename Detectors/Align/include/Align/{AliAlgSensTPC.h => AlignableSensorTPC.h} (68%) rename Detectors/Align/include/Align/{AliAlgSensTRD.h => AlignableSensorTRD.h} (62%) rename Detectors/Align/include/Align/{AliAlgVol.h => AlignableVolume.h} (90%) rename Detectors/Align/include/Align/{AliAlgPoint.h => AlignmentPoint.h} (91%) rename Detectors/Align/include/Align/{AliAlgTrack.h => AlignmentTrack.h} (82%) rename Detectors/Align/include/Align/{AliAlgSteer.h => Controller.h} (71%) rename Detectors/Align/include/Align/{AliAlgDOFStat.h => DOFStatistics.h} (75%) rename Detectors/Align/include/Align/{AliAlgVtx.h => EventVertex.h} (78%) rename Detectors/Align/include/Align/{AliAlgConstraint.h => GeometricalConstraint.h} (65%) rename Detectors/Align/include/Align/{AliAlgMPRecord.h => Millepede2Record.h} (90%) rename Detectors/Align/include/Align/{AliAlgRes.h => ResidualsController.h} (92%) rename Detectors/Align/include/Align/{AliAlgResFast.h => ResidualsControllerFast.h} (89%) rename Detectors/Align/include/Align/{AliAlgAux.h => utils.h} (81%) delete mode 100644 Detectors/Align/src/AliAlgAux.cxx rename Detectors/Align/src/{AliAlgDet.cxx => AlignableDetector.cxx} (82%) rename Detectors/Align/src/{AliAlgDetHMPID.cxx => AlignableDetectorHMPID.cxx} (72%) rename Detectors/Align/src/{AliAlgDetITS.cxx => AlignableDetectorITS.cxx} (77%) rename Detectors/Align/src/{AliAlgDetTOF.cxx => AlignableDetectorTOF.cxx} (68%) rename Detectors/Align/src/{AliAlgDetTPC.cxx => AlignableDetectorTPC.cxx} (74%) rename Detectors/Align/src/{AliAlgDetTRD.cxx => AlignableDetectorTRD.cxx} (72%) rename Detectors/Align/src/{AliAlgSens.cxx => AlignableSensor.cxx} (87%) rename Detectors/Align/src/{AliAlgSensHMPID.cxx => AlignableSensorHMPID.cxx} (85%) rename Detectors/Align/src/{AliAlgSensITS.cxx => AlignableSensorITS.cxx} (84%) rename Detectors/Align/src/{AliAlgSensTOF.cxx => AlignableSensorTOF.cxx} (87%) rename Detectors/Align/src/{AliAlgSensTPC.cxx => AlignableSensorTPC.cxx} (85%) rename Detectors/Align/src/{AliAlgSensTRD.cxx => AlignableSensorTRD.cxx} (81%) rename Detectors/Align/src/{AliAlgVol.cxx => AlignableVolume.cxx} (83%) rename Detectors/Align/src/{AliAlgPoint.cxx => AlignmentPoint.cxx} (91%) rename Detectors/Align/src/{AliAlgTrack.cxx => AlignmentTrack.cxx} (91%) rename Detectors/Align/src/{AliAlgSteer.cxx => Controller.cxx} (89%) rename Detectors/Align/src/{AliAlgDOFStat.cxx => DOFStatistics.cxx} (84%) rename Detectors/Align/src/{AliAlgVtx.cxx => EventVertex.cxx} (80%) rename Detectors/Align/src/{AliAlgConstraint.cxx => GeometricalConstraint.cxx} (94%) rename Detectors/Align/src/{AliAlgMPRecord.cxx => Millepede2Record.cxx} (93%) rename Detectors/Align/src/{AliAlgRes.cxx => ResidualsController.cxx} (89%) rename Detectors/Align/src/{AliAlgResFast.cxx => ResidualsControllerFast.cxx} (84%) diff --git a/Detectors/Align/CMakeLists.txt b/Detectors/Align/CMakeLists.txt index 766a1c77f30e9..2e8b42cd55bf0 100644 --- a/Detectors/Align/CMakeLists.txt +++ b/Detectors/Align/CMakeLists.txt @@ -9,29 +9,28 @@ # submit itself to any jurisdiction. o2_add_library(Align - SOURCES src/AliAlgAux.cxx - src/AliAlgConstraint.cxx - src/AliAlgDet.cxx - #src/AliAlgDetHMPID.cxx - #src/AliAlgDetITS.cxx - #src/AliAlgDetTOF.cxx - #src/AliAlgDetTPC.cxx - #src/AliAlgDetTRD.cxx - src/AliAlgDOFStat.cxx - src/AliAlgMPRecord.cxx - src/AliAlgPoint.cxx - src/AliAlgRes.cxx - src/AliAlgResFast.cxx - src/AliAlgSens.cxx - #src/AliAlgSensHMPID.cxx - #src/AliAlgSensITS.cxx - #src/AliAlgSensTOF.cxx - #src/AliAlgSensTPC.cxx - #src/AliAlgSensTRD.cxx - src/AliAlgSteer.cxx - src/AliAlgTrack.cxx - src/AliAlgVol.cxx - src/AliAlgVtx.cxx + SOURCES src/GeometricalConstraint.cxx + src/AlignableDetector.cxx + #src/AlignableDetectorHMPID.cxx + #src/AlignableDetectorITS.cxx + #src/AlignableDetectorTOF.cxx + #src/AlignableDetectorTPC.cxx + #src/AlignableDetectorTRD.cxx + src/DOFStatistics.cxx + src/Millepede2Record.cxx + src/AlignmentPoint.cxx + src/ResidualsController.cxx + src/ResidualsControllerFast.cxx + src/AlignableSensor.cxx + #src/AlignableSensorHMPID.cxx + #src/AlignableSensorITS.cxx + #src/AlignableSensorTOF.cxx + #src/AlignableSensorTPC.cxx + #src/AlignableSensorTRD.cxx + src/Controller.cxx + src/AlignmentTrack.cxx + src/AlignableVolume.cxx + src/EventVertex.cxx src/Mille.cxx PUBLIC_LINK_LIBRARIES O2::FrameworkLogger O2::ReconstructionDataFormats @@ -49,27 +48,27 @@ o2_add_library(Align o2_target_root_dictionary( Align - HEADERS include/Align/AliAlgDet.h - #include/Align/AliAlgDetITS.h - #include/Align/AliAlgDetTOF.h - #include/Align/AliAlgDetTPC.h - #include/Align/AliAlgDetTRD.h - #include/Align/AliAlgDetHMPID.h - include/Align/AliAlgMPRecord.h - include/Align/AliAlgPoint.h - include/Align/AliAlgSens.h - #include/Align/AliAlgSensITS.h - #include/Align/AliAlgSensTOF.h - #include/Align/AliAlgSensTPC.h - #include/Align/AliAlgSensTRD.h - #include/Align/AliAlgSensHMPID.h - include/Align/AliAlgSteer.h - include/Align/AliAlgTrack.h - include/Align/AliAlgVol.h - include/Align/AliAlgVtx.h - include/Align/AliAlgRes.h - include/Align/AliAlgResFast.h - include/Align/AliAlgConstraint.h - include/Align/AliAlgDOFStat.h - include/Align/AliAlgAux.h + HEADERS include/Align/AlignableDetector.h + #include/Align/AlignableDetectorITS.h + #include/Align/AlignableDetectorTOF.h + #include/Align/AlignableDetectorTPC.h + #include/Align/AlignableDetectorTRD.h + #include/Align/AlignableDetectorHMPID.h + include/Align/Millepede2Record.h + include/Align/AlignmentPoint.h + include/Align/AlignableSensor.h + #include/Align/AlignableSensorITS.h + #include/Align/AlignableSensorTOF.h + #include/Align/AlignableSensorTPC.h + #include/Align/AlignableSensorTRD.h + #include/Align/AlignableSensorHMPID.h + include/Align/Controller.h + include/Align/AlignmentTrack.h + include/Align/AlignableVolume.h + include/Align/EventVertex.h + include/Align/ResidualsController.h + include/Align/ResidualsControllerFast.h + include/Align/GeometricalConstraint.h + include/Align/DOFStatistics.h + include/Align/utils.h ) diff --git a/Detectors/Align/include/Align/AliAlgDet.h b/Detectors/Align/include/Align/AlignableDetector.h similarity index 68% rename from Detectors/Align/include/Align/AliAlgDet.h rename to Detectors/Align/include/Align/AlignableDetector.h index 735308f9773ab..51a93598a276f 100644 --- a/Detectors/Align/include/Align/AliAlgDet.h +++ b/Detectors/Align/include/Align/AlignableDetector.h @@ -8,24 +8,24 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgDet.h +/// @file AlignableDetector.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Base class for detector: wrapper for set of volumes -#ifndef ALIALGDET_H -#define ALIALGDET_H +#ifndef ALIGNABLEDETECTOR_H +#define ALIGNABLEDETECTOR_H #include #include #include -#include "Align/AliAlgAux.h" -#include "Align/AliAlgTrack.h" -#include "Align/AliAlgDOFStat.h" -#include "Align/AliAlgPoint.h" -#include "Align/AliAlgSens.h" -#include "Align/AliAlgVol.h" -#include "Align/AliAlgSteer.h" +#include "Align/utils.h" +#include "Align/AlignmentTrack.h" +#include "Align/DOFStatistics.h" +#include "Align/AlignmentPoint.h" +#include "Align/AlignableSensor.h" +#include "Align/AlignableVolume.h" +#include "Align/Controller.h" //#include "AliESDtrack.h" //class AliTrackPointArray; @@ -37,16 +37,16 @@ namespace align { //TODO(milettri) : fix possibly incompatible Detector IDs of O2 and AliROOT -class AliAlgDet : public TNamed +class AlignableDetector : public TNamed { public: enum { kInitGeomDone = BIT(14), kInitDOFsDone = BIT(15) }; enum { kNMaxKalibDOF = 64 }; // - AliAlgDet(); - AliAlgDet(const char* name, const char* title = "", int id = -1) : TNamed(name, title) { SetUniqueID(id); }; - virtual ~AliAlgDet(); + AlignableDetector(); + AlignableDetector(const char* name, const char* title = "", int id = -1) : TNamed(name, title) { SetUniqueID(id); }; + virtual ~AlignableDetector(); int getDetID() const { return GetUniqueID(); } detectors::DetID getO2DetID() const { return detectors::DetID(GetUniqueID()); }; void setDetID(uint32_t tp); @@ -69,19 +69,19 @@ class AliAlgDet : public TNamed // int getNPoints() const { return mNPoints; } // - void setAlgSteer(AliAlgSteer* s) { mAlgSteer = s; } - AliAlgSens* getSensor(int id) const { return (AliAlgSens*)mSensors.UncheckedAt(id); } - AliAlgSens* getSensorByVolId(int vid) const + void setAlgSteer(Controller* s) { mAlgSteer = s; } + AlignableSensor* getSensor(int id) const { return (AlignableSensor*)mSensors.UncheckedAt(id); } + AlignableSensor* getSensorByVolId(int vid) const { int sid = volID2SID(vid); return sid < 0 ? 0 : getSensor(sid); } - AliAlgSens* getSensor(const char* symname) const { return (AliAlgSens*)mSensors.FindObject(symname); } - AliAlgVol* getVolume(int id) const { return (AliAlgVol*)mVolumes.UncheckedAt(id); } - AliAlgVol* getVolume(const char* symname) const { return (AliAlgVol*)mVolumes.FindObject(symname); } + AlignableSensor* getSensor(const char* symname) const { return (AlignableSensor*)mSensors.FindObject(symname); } + AlignableVolume* getVolume(int id) const { return (AlignableVolume*)mVolumes.UncheckedAt(id); } + AlignableVolume* getVolume(const char* symname) const { return (AlignableVolume*)mVolumes.FindObject(symname); } // bool ownsDOFID(int id) const; - AliAlgVol* getVolOfDOFID(int id) const; + AlignableVolume* getVolOfDOFID(int id) const; // int getDetLabel() const { return (getDetID() + 1) * 1000000; } void setFreeDOF(int dof); @@ -103,20 +103,20 @@ class AliAlgDet : public TNamed virtual int assignDOFs(); virtual void initDOFs(); virtual void terminate(); - void fillDOFStat(AliAlgDOFStat* dofst = 0) const; - virtual void addVolume(AliAlgVol* vol); + void fillDOFStat(DOFStatistics* dofst = 0) const; + virtual void addVolume(AlignableVolume* vol); virtual void defineVolumes(); virtual void defineMatrices(); virtual void Print(const Option_t* opt = "") const; - // virtual int ProcessPoints(const AliESDtrack* esdTr, AliAlgTrack* algTrack, bool inv = false); FIXME(milettri): needs AliESDtrack - virtual void updatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) const; + // virtual int ProcessPoints(const AliESDtrack* esdTr, AlignmentTrack* algTrack, bool inv = false); FIXME(milettri): needs AliESDtrack + virtual void updatePointByTrackInfo(AlignmentPoint* pnt, const trackParam_t* t) const; virtual void setUseErrorParam(int v = 0); int getUseErrorParam() const { return mUseErrorParam; } // // virtual bool AcceptTrack(const AliESDtrack* trc, int trtype) const = 0; FIXME(milettri): needs AliESDtrack // bool CheckFlags(const AliESDtrack* trc, int trtype) const; FIXME(milettri): needs AliESDtrack // - virtual AliAlgPoint* getPointFromPool(); + virtual AlignmentPoint* getPointFromPool(); virtual void resetPool(); virtual void writeSensorPositions(const char* outFName); // @@ -144,34 +144,34 @@ class AliAlgDet : public TNamed setDisabledColl(); setDisabledCosm(); } - void setDisabledColl(bool v = true) { setDisabled(AliAlgAux::kColl, v); } - void setDisabledCosm(bool v = true) { setDisabled(AliAlgAux::kCosm, v); } + void setDisabledColl(bool v = true) { setDisabled(utils::kColl, v); } + void setDisabledCosm(bool v = true) { setDisabled(utils::kCosm, v); } bool isDisabled(int tp) const { return mDisabled[tp]; } bool isDisabled() const { return IsDisabledColl() && IsDisabledCosm(); } - bool IsDisabledColl() const { return isDisabled(AliAlgAux::kColl); } - bool IsDisabledCosm() const { return isDisabled(AliAlgAux::kCosm); } + bool IsDisabledColl() const { return isDisabled(utils::kColl); } + bool IsDisabledCosm() const { return isDisabled(utils::kCosm); } // void setTrackFlagSel(int tp, uint64_t f) { mTrackFlagSel[tp] = f; } - void setTrackFlagSelColl(uint64_t f) { setTrackFlagSel(AliAlgAux::kColl, f); } - void setTrackFlagSelCosm(uint64_t f) { setTrackFlagSel(AliAlgAux::kCosm, f); } + void setTrackFlagSelColl(uint64_t f) { setTrackFlagSel(utils::kColl, f); } + void setTrackFlagSelCosm(uint64_t f) { setTrackFlagSel(utils::kCosm, f); } uint64_t getTrackFlagSel(int tp) const { return mTrackFlagSel[tp]; } - uint64_t getTrackFlagSelColl() const { return getTrackFlagSel(AliAlgAux::kColl); } - uint64_t getTrackFlagSelCosm() const { return getTrackFlagSel(AliAlgAux::kCosm); } + uint64_t getTrackFlagSelColl() const { return getTrackFlagSel(utils::kColl); } + uint64_t getTrackFlagSelCosm() const { return getTrackFlagSel(utils::kCosm); } // void setNPointsSel(int tp, int n) { mNPointsSel[tp] = n; } - void setNPointsSelColl(int n) { setNPointsSel(AliAlgAux::kColl, n); } - void setNPointsSelCosm(int n) { setNPointsSel(AliAlgAux::kCosm, n); } + void setNPointsSelColl(int n) { setNPointsSel(utils::kColl, n); } + void setNPointsSelCosm(int n) { setNPointsSel(utils::kCosm, n); } int getNPointsSel(int tp) const { return mNPointsSel[tp]; } - int getNPointsSelColl() const { return getNPointsSel(AliAlgAux::kColl); } - int getNPointsSelCosm() const { return getNPointsSel(AliAlgAux::kCosm); } + int getNPointsSelColl() const { return getNPointsSel(utils::kColl); } + int getNPointsSelCosm() const { return getNPointsSel(utils::kCosm); } // // bool isObligatory(int tp) const { return mObligatory[tp]; } - bool isObligatoryColl() const { return isObligatory(AliAlgAux::kColl); } - bool isObligatoryCosm() const { return isObligatory(AliAlgAux::kCosm); } + bool isObligatoryColl() const { return isObligatory(utils::kColl); } + bool isObligatoryCosm() const { return isObligatory(utils::kCosm); } void setObligatory(int tp, bool v = true); - void setObligatoryColl(bool v = true) { setObligatory(AliAlgAux::kColl, v); } - void setObligatoryCosm(bool v = true) { setObligatory(AliAlgAux::kCosm, v); } + void setObligatoryColl(bool v = true) { setObligatory(utils::kColl, v); } + void setObligatoryCosm(bool v = true) { setObligatory(utils::kCosm, v); } // void addAutoConstraints() const; void constrainOrphans(const double* sigma, const char* match = 0); @@ -198,8 +198,8 @@ class AliAlgDet : public TNamed void calcFree(bool condFree = false); // // ------- dummies --------- - AliAlgDet(const AliAlgDet&); - AliAlgDet& operator=(const AliAlgDet&); + AlignableDetector(const AlignableDetector&); + AlignableDetector& operator=(const AlignableDetector&); // protected: // @@ -220,10 +220,10 @@ class AliAlgDet : public TNamed int* mParLabs; //! labels for parameters // // Track selection - bool mDisabled[AliAlgAux::kNTrackTypes]; // detector disabled/enabled in the track - bool mObligatory[AliAlgAux::kNTrackTypes]; // detector must be present in the track - uint64_t mTrackFlagSel[AliAlgAux::kNTrackTypes]; // flag for track selection - int mNPointsSel[AliAlgAux::kNTrackTypes]; // min number of points to require + bool mDisabled[utils::kNTrackTypes]; // detector disabled/enabled in the track + bool mObligatory[utils::kNTrackTypes]; // detector must be present in the track + uint64_t mTrackFlagSel[utils::kNTrackTypes]; // flag for track selection + int mNPointsSel[utils::kNTrackTypes]; // min number of points to require // int mUseErrorParam; // signal that points need to be updated using track info, 0 - no double mAddError[2]; // additional error increment for measurement @@ -231,19 +231,19 @@ class AliAlgDet : public TNamed TObjArray mVolumes; // all volumes of the detector // // this is transient info - int mNPoints; //! number of points from this detector - int mPoolNPoints; //! number of points in the pool - int mPoolFreePointID; //! id of the last free point in the pool - TObjArray mPointsPool; //! pool of aligment points - // - AliAlgSteer* mAlgSteer; // pointer to alignment steering object - // - ClassDef(AliAlgDet, 1); // base class for detector global alignment + int mNPoints; //! number of points from this detector + int mPoolNPoints; //! number of points in the pool + int mPoolFreePointID; //! id of the last free point in the pool + TObjArray mPointsPool; //! pool of aligment points + // + Controller* mAlgSteer; // pointer to alignment steering object + // + ClassDef(AlignableDetector, 1); // base class for detector global alignment }; //FIXME(milettri): needs AliESDtrack ////_____________________________________________________ -//inline bool AliAlgDet::CheckFlags(const AliESDtrack* trc, int trtype) const +//inline bool AlignableDetector::CheckFlags(const AliESDtrack* trc, int trtype) const //{ // // check if flags are ok // return (trc->GetStatus() & mTrackFlagSel[trtype]) == mTrackFlagSel[trtype]; diff --git a/Detectors/Align/include/Align/AliAlgDetHMPID.h b/Detectors/Align/include/Align/AlignableDetectorHMPID.h similarity index 65% rename from Detectors/Align/include/Align/AliAlgDetHMPID.h rename to Detectors/Align/include/Align/AlignableDetectorHMPID.h index feb0b8c4361c3..0640f84aa3aee 100644 --- a/Detectors/Align/include/Align/AliAlgDetHMPID.h +++ b/Detectors/Align/include/Align/AlignableDetectorHMPID.h @@ -8,25 +8,25 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgDetHMPID.h +/// @file AlignableDetectorHMPID.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief HMPID detector wrapper -#ifndef ALIALGDETHMPID_H -#define ALIALGDETHMPID_H +#ifndef ALIGNABLEDETECTORHMPID_H +#define ALIGNABLEDETECTORHMPID_H -#include "Align/AliAlgDet.h" +#include "Align/AlignableDetector.h" namespace o2 { namespace align { -class AliAlgDetHMPID : public AliAlgDet +class AlignableDetectorHMPID : public AlignableDetector { public: - AliAlgDetHMPID(const char* title = ""); - virtual ~AliAlgDetHMPID(); + AlignableDetectorHMPID(const char* title = ""); + virtual ~AlignableDetectorHMPID(); // virtual void defineVolumes(); // @@ -35,11 +35,11 @@ class AliAlgDetHMPID : public AliAlgDet protected: // // -------- dummies -------- - AliAlgDetHMPID(const AliAlgDetHMPID&); - AliAlgDetHMPID& operator=(const AliAlgDetHMPID&); + AlignableDetectorHMPID(const AlignableDetectorHMPID&); + AlignableDetectorHMPID& operator=(const AlignableDetectorHMPID&); // protected: - ClassDef(AliAlgDetHMPID, 1); + ClassDef(AlignableDetectorHMPID, 1); }; } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgDetITS.h b/Detectors/Align/include/Align/AlignableDetectorITS.h similarity index 69% rename from Detectors/Align/include/Align/AliAlgDetITS.h rename to Detectors/Align/include/Align/AlignableDetectorITS.h index cf7207d31b89e..caa40fce1e44c 100644 --- a/Detectors/Align/include/Align/AliAlgDetITS.h +++ b/Detectors/Align/include/Align/AlignableDetectorITS.h @@ -8,23 +8,23 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgDetITS.h +/// @file AlignableDetectorITS.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief ITS detector wrapper -#ifndef ALIALGDETITS_H -#define ALIALGDETITS_H +#ifndef ALIGNABLEDETECTORITS_H +#define ALIGNABLEDETECTORITS_H -#include "Align/AliAlgDet.h" -#include "Align/AliAlgAux.h" +#include "Align/AlignableDetector.h" +#include "Align/utils.h" namespace o2 { namespace align { -class AliAlgDetITS : public AliAlgDet +class AlignableDetectorITS : public AlignableDetector { public: // @@ -35,8 +35,8 @@ class AliAlgDetITS : public AliAlgDet kSPD1, kNSPDSelTypes }; // - AliAlgDetITS(const char* title = ""); - virtual ~AliAlgDetITS(); + AlignableDetectorITS(const char* title = ""); + virtual ~AlignableDetectorITS(); // virtual void defineVolumes(); // @@ -45,15 +45,15 @@ class AliAlgDetITS : public AliAlgDet void SetAddErrorLr(int ilr, double sigY, double sigZ); void SetSkipLr(int ilr); // - virtual void UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const; + virtual void UpdatePointByTrackInfo(AlignmentPoint* pnt, const AliExternalTrackParam* t) const; virtual void setUseErrorParam(int v = 1); void SetITSSelPattern(int trtype, ITSSel_t sel) { fITSPatt[trtype] = sel; } - void SetITSSelPatternColl(ITSSel_t sel = kSPDAny) { SetITSSelPattern(AliAlgAux::kColl, sel); } - void SetITSSelPatternCosm(ITSSel_t sel = kSPDNoSel) { SetITSSelPattern(AliAlgAux::kCosm, sel); } + void SetITSSelPatternColl(ITSSel_t sel = kSPDAny) { SetITSSelPattern(utils::kColl, sel); } + void SetITSSelPatternCosm(ITSSel_t sel = kSPDNoSel) { SetITSSelPattern(utils::kCosm, sel); } int GetITSSelPattern(int tp) const { return fITSPatt[tp]; } - int GetITSSelPatternColl() const { return fITSPatt[AliAlgAux::kColl]; } - int GetITSSelPatternCosm() const { return fITSPatt[AliAlgAux::kCosm]; } + int GetITSSelPatternColl() const { return fITSPatt[utils::kColl]; } + int GetITSSelPatternCosm() const { return fITSPatt[utils::kCosm]; } // virtual void Print(const Option_t* opt = "") const; // @@ -65,16 +65,16 @@ class AliAlgDetITS : public AliAlgDet void GetErrorParamAngle(int layer, double tgl, double tgphitr, double& erry, double& errz) const; // // -------- dummies -------- - AliAlgDetITS(const AliAlgDetITS&); - AliAlgDetITS& operator=(const AliAlgDetITS&); + AlignableDetectorITS(const AlignableDetectorITS&); + AlignableDetectorITS& operator=(const AlignableDetectorITS&); // protected: // - int fITSPatt[AliAlgAux::kNTrackTypes]; // ITS hits selection pattern for coll/cosm tracks + int fITSPatt[utils::kNTrackTypes]; // ITS hits selection pattern for coll/cosm tracks // static const char* fgkHitsSel[kNSPDSelTypes]; // ITS selection names // - ClassDef(AliAlgDetITS, 1); + ClassDef(AlignableDetectorITS, 1); }; } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgDetTOF.h b/Detectors/Align/include/Align/AlignableDetectorTOF.h similarity index 67% rename from Detectors/Align/include/Align/AliAlgDetTOF.h rename to Detectors/Align/include/Align/AlignableDetectorTOF.h index 6cd982d5be0cd..9af6ee826534b 100644 --- a/Detectors/Align/include/Align/AliAlgDetTOF.h +++ b/Detectors/Align/include/Align/AlignableDetectorTOF.h @@ -8,26 +8,26 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgDetTOF.h +/// @file AlignableDetectorTOF.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Wrapper for TOF detector -#ifndef ALIALGDETTOF_H -#define ALIALGDETTOF_H +#ifndef ALIGNABLEDETECTORTOF_H +#define ALIGNABLEDETECTORTOF_H -#include "Align/AliAlgDet.h" +#include "Align/AlignableDetector.h" namespace o2 { namespace align { -class AliAlgDetTOF : public AliAlgDet +class AlignableDetectorTOF : public AlignableDetector { public: - AliAlgDetTOF(const char* title = ""); - virtual ~AliAlgDetTOF(); + AlignableDetectorTOF(const char* title = ""); + virtual ~AlignableDetectorTOF(); // virtual void defineVolumes(); // @@ -36,11 +36,11 @@ class AliAlgDetTOF : public AliAlgDet protected: // // -------- dummies -------- - AliAlgDetTOF(const AliAlgDetTOF&); - AliAlgDetTOF& operator=(const AliAlgDetTOF&); + AlignableDetectorTOF(const AlignableDetectorTOF&); + AlignableDetectorTOF& operator=(const AlignableDetectorTOF&); // protected: - ClassDef(AliAlgDetTOF, 1); + ClassDef(AlignableDetectorTOF, 1); }; } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgDetTPC.h b/Detectors/Align/include/Align/AlignableDetectorTPC.h similarity index 67% rename from Detectors/Align/include/Align/AliAlgDetTPC.h rename to Detectors/Align/include/Align/AlignableDetectorTPC.h index 9f30ac5f41ee4..bb2f0e103cdc0 100644 --- a/Detectors/Align/include/Align/AliAlgDetTPC.h +++ b/Detectors/Align/include/Align/AlignableDetectorTPC.h @@ -8,26 +8,26 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgDetTPC.h +/// @file AlignableDetectorTPC.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief TPC detector wrapper -#ifndef ALIALGDETTPC_H -#define ALIALGDETTPC_H +#ifndef ALIGNABLEDETECTORTPC_H +#define ALIGNABLEDETECTORTPC_H -#include "Align/AliAlgDet.h" +#include "Align/AlignableDetector.h" namespace o2 { namespace align { -class AliAlgDetTPC : public AliAlgDet +class AlignableDetectorTPC : public AlignableDetector { public: - AliAlgDetTPC(const char* title = ""); - virtual ~AliAlgDetTPC(); + AlignableDetectorTPC(const char* title = ""); + virtual ~AlignableDetectorTPC(); // virtual void defineVolumes(); // @@ -36,11 +36,11 @@ class AliAlgDetTPC : public AliAlgDet protected: // // -------- dummies -------- - AliAlgDetTPC(const AliAlgDetTPC&); - AliAlgDetTPC& operator=(const AliAlgDetTPC&); + AlignableDetectorTPC(const AlignableDetectorTPC&); + AlignableDetectorTPC& operator=(const AlignableDetectorTPC&); // protected: - ClassDef(AliAlgDetTPC, 1); + ClassDef(AlignableDetectorTPC, 1); }; } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgDetTRD.h b/Detectors/Align/include/Align/AlignableDetectorTRD.h similarity index 83% rename from Detectors/Align/include/Align/AliAlgDetTRD.h rename to Detectors/Align/include/Align/AlignableDetectorTRD.h index 2a22be8095b3b..3bdb998acc2dc 100644 --- a/Detectors/Align/include/Align/AliAlgDetTRD.h +++ b/Detectors/Align/include/Align/AlignableDetectorTRD.h @@ -8,22 +8,22 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgDetTRD.h +/// @file AlignableDetectorTRD.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief TRD detector wrapper -#ifndef ALIALGDETTRD_H -#define ALIALGDETTRD_H +#ifndef ALIGNABLEDETECTORTRD_H +#define ALIGNABLEDETECTORTRD_H -#include "Align/AliAlgDet.h" +#include "Align/AlignableDetector.h" namespace o2 { namespace align { -class AliAlgDetTRD : public AliAlgDet +class AlignableDetectorTRD : public AlignableDetector { public: // @@ -31,8 +31,8 @@ class AliAlgDetTRD : public AliAlgDet kCalibDVT, // global correction to Vdrift*t kNCalibParams }; // calibration parameters // - AliAlgDetTRD(const char* title = ""); - virtual ~AliAlgDetTRD(); + AlignableDetectorTRD(const char* title = ""); + virtual ~AlignableDetectorTRD(); // virtual void defineVolumes(); virtual void Print(const Option_t* opt = "") const; @@ -64,8 +64,8 @@ class AliAlgDetTRD : public AliAlgDet protected: // // -------- dummies -------- - AliAlgDetTRD(const AliAlgDetTRD&); - AliAlgDetTRD& operator=(const AliAlgDetTRD&); + AlignableDetectorTRD(const AlignableDetectorTRD&); + AlignableDetectorTRD& operator=(const AlignableDetectorTRD&); // protected: // @@ -75,7 +75,7 @@ class AliAlgDetTRD : public AliAlgDet // static const char* fgkCalibDOFName[kNCalibParams]; // - ClassDef(AliAlgDetTRD, 1); + ClassDef(AlignableDetectorTRD, 1); }; } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgSens.h b/Detectors/Align/include/Align/AlignableSensor.h similarity index 60% rename from Detectors/Align/include/Align/AliAlgSens.h rename to Detectors/Align/include/Align/AlignableSensor.h index 16dcbbfc1bc30..c2b868ecc8fbf 100644 --- a/Detectors/Align/include/Align/AliAlgSens.h +++ b/Detectors/Align/include/Align/AlignableSensor.h @@ -8,20 +8,20 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgSens.h +/// @file AlignableSensor.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief End-chain alignment volume in detector branch, where the actual measurement is done. -#ifndef ALIALGSENS_H -#define ALIALGSENS_H +#ifndef ALIGNABLESENSOR_H +#define ALIGNABLESENSOR_H #include #include -#include "Align/AliAlgVol.h" -#include "Align/AliAlgDOFStat.h" -#include "Align/AliAlgAux.h" +#include "Align/AlignableVolume.h" +#include "Align/DOFStatistics.h" +#include "Align/utils.h" //class AliTrackPointArray; //class AliESDtrack; @@ -32,20 +32,20 @@ namespace o2 namespace align { -class AliAlgDet; -class AliAlgPoint; +class AlignableDetector; +class AlignmentPoint; -class AliAlgSens : public AliAlgVol +class AlignableSensor : public AlignableVolume { public: // - AliAlgSens(const char* name = 0, int vid = 0, int iid = 0); - virtual ~AliAlgSens(); + AlignableSensor(const char* name = 0, int vid = 0, int iid = 0); + virtual ~AlignableSensor(); // - virtual void addChild(AliAlgVol*); + virtual void addChild(AlignableVolume*); // - void setDetector(AliAlgDet* det) { mDet = det; } - AliAlgDet* getDetector() const { return mDet; } + void setDetector(AlignableDetector* det) { mDet = det; } + AlignableDetector* getDetector() const { return mDet; } // int getSID() const { return mSID; } void setSID(int s) { mSID = s; } @@ -53,13 +53,13 @@ class AliAlgSens : public AliAlgVol void incrementStat() { mNProcPoints++; } // // derivatives calculation - virtual void dPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int calibID, const AliAlgVol* parent = 0) const; - virtual void dPosTraDParGeom(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent = 0) const; + virtual void dPosTraDParCalib(const AlignmentPoint* pnt, double* deriv, int calibID, const AlignableVolume* parent = 0) const; + virtual void dPosTraDParGeom(const AlignmentPoint* pnt, double* deriv, const AlignableVolume* parent = 0) const; // - virtual void dPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv) const; - virtual void dPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv) const; - virtual void dPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const; - virtual void dPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const; + virtual void dPosTraDParGeomLOC(const AlignmentPoint* pnt, double* deriv) const; + virtual void dPosTraDParGeomTRA(const AlignmentPoint* pnt, double* deriv) const; + virtual void dPosTraDParGeomLOC(const AlignmentPoint* pnt, double* deriv, const AlignableVolume* parent) const; + virtual void dPosTraDParGeomTRA(const AlignmentPoint* pnt, double* deriv, const AlignableVolume* parent) const; // void getModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const double* delta) const; void getModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const double* delta) const; @@ -79,12 +79,12 @@ class AliAlgSens : public AliAlgVol virtual bool isSensor() const { return true; } virtual void Print(const Option_t* opt = "") const; // - virtual void updatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) const; + virtual void updatePointByTrackInfo(AlignmentPoint* pnt, const trackParam_t* t) const; virtual void updateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta); // - // virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t) = 0; TODO(milettri): needs AliTrackPointArray AliESDtrack + // virtual AlignmentPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t) = 0; TODO(milettri): needs AliTrackPointArray AliESDtrack // - virtual int finalizeStat(AliAlgDOFStat* h = 0); + virtual int finalizeStat(DOFStatistics* h = 0); // virtual void prepareMatrixClAlg(); virtual void prepareMatrixClAlgReco(); @@ -99,19 +99,19 @@ class AliAlgSens : public AliAlgVol virtual int Compare(const TObject* a) const; // // --------- dummies ----------- - AliAlgSens(const AliAlgSens&); - AliAlgSens& operator=(const AliAlgSens&); + AlignableSensor(const AlignableSensor&); + AlignableSensor& operator=(const AlignableSensor&); // protected: // int mSID; // sensor id in detector double mAddError[2]; // additional error increment for measurement - AliAlgDet* mDet; // pointer on detector + AlignableDetector* mDet; // pointer on detector TGeoHMatrix mMatClAlg; // reference cluster alignment matrix in tracking frame TGeoHMatrix mMatClAlgReco; // reco-time cluster alignment matrix in tracking frame // - ClassDef(AliAlgSens, 1) + ClassDef(AlignableSensor, 1) }; } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgSensHMPID.h b/Detectors/Align/include/Align/AlignableSensorHMPID.h similarity index 64% rename from Detectors/Align/include/Align/AliAlgSensHMPID.h rename to Detectors/Align/include/Align/AlignableSensorHMPID.h index d0c09700f8179..95d833bc2beb3 100644 --- a/Detectors/Align/include/Align/AliAlgSensHMPID.h +++ b/Detectors/Align/include/Align/AlignableSensorHMPID.h @@ -8,39 +8,39 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgSensHMPID.h +/// @file AlignableSensorHMPID.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief HMPID sensor (chamber) -#ifndef ALIALGSENSHMPID_H -#define ALIALGSENSHMPID_H +#ifndef ALIGNABLESENSORHMPID_H +#define ALIGNABLESENSORHMPID_H -#include "Align/AliAlgSens.h" +#include "Align/AlignableSensor.h" class TObjArray; //class AliTrackPointArray; //class AliESDtrack; -class AliAlgPoint; +class AlignmentPoint; namespace o2 { namespace align { -class AliAlgSensHMPID : public AliAlgSens +class AlignableSensorHMPID : public AlignableSensor { public: - AliAlgSensHMPID(const char* name = 0, int vid = 0, int iid = 0, int isec = 0); - virtual ~AliAlgSensHMPID(); + AlignableSensorHMPID(const char* name = 0, int vid = 0, int iid = 0, int isec = 0); + virtual ~AlignableSensorHMPID(); // - virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); + virtual AlignmentPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); // virtual void setTrackingFrame(); virtual void prepareMatrixT2L(); // protected: // - ClassDef(AliAlgSensHMPID, 1) + ClassDef(AlignableSensorHMPID, 1) }; } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgSensITS.h b/Detectors/Align/include/Align/AlignableSensorITS.h similarity index 64% rename from Detectors/Align/include/Align/AliAlgSensITS.h rename to Detectors/Align/include/Align/AlignableSensorITS.h index ba1fbef1b46a3..c66885c53c154 100644 --- a/Detectors/Align/include/Align/AliAlgSensITS.h +++ b/Detectors/Align/include/Align/AlignableSensorITS.h @@ -8,39 +8,39 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgSensITS.h +/// @file AlignableSensorITS.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief ITS sensor -#ifndef ALIALGSENSITS_H -#define ALIALGSENSITS_H +#ifndef ALIGNABLESENSORITS_H +#define ALIGNABLESENSORITS_H -#include "Align/AliAlgSens.h" +#include "Align/AlignableSensor.h" class TObjArray; class AliTrackPointArray; class AliESDtrack; -class AliAlgPoint; +class AlignmentPoint; namespace o2 { namespace align { -class AliAlgSensITS : public AliAlgSens +class AlignableSensorITS : public AlignableSensor { public: - AliAlgSensITS(const char* name = 0, int vid = 0, int iid = 0); - virtual ~AliAlgSensITS(); + AlignableSensorITS(const char* name = 0, int vid = 0, int iid = 0); + virtual ~AlignableSensorITS(); // - virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); + virtual AlignmentPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); // virtual void setTrackingFrame(); // protected: // - ClassDef(AliAlgSensITS, 1) + ClassDef(AlignableSensorITS, 1) }; } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgSensTOF.h b/Detectors/Align/include/Align/AlignableSensorTOF.h similarity index 68% rename from Detectors/Align/include/Align/AliAlgSensTOF.h rename to Detectors/Align/include/Align/AlignableSensorTOF.h index 0dd8e7e2bc72d..9c0ceca513b11 100644 --- a/Detectors/Align/include/Align/AliAlgSensTOF.h +++ b/Detectors/Align/include/Align/AlignableSensorTOF.h @@ -8,19 +8,19 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgSensTOF.h +/// @file AlignableSensorTOF.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief TOF sensor -#ifndef ALIALGSENSTOF_H -#define ALIALGSENSTOF_H +#ifndef ALIGNABLESENSORTOF_H +#define ALIGNABLESENSORTOF_H -#include "Align/AliAlgSens.h" +#include "Align/AlignableSensor.h" //class AliTrackPointArray; //class AliESDtrack; -class AliAlgPoint; +class AlignmentPoint; class TObjArray; namespace o2 @@ -28,13 +28,13 @@ namespace o2 namespace align { -class AliAlgSensTOF : public AliAlgSens +class AlignableSensorTOF : public AlignableSensor { public: - AliAlgSensTOF(const char* name = 0, int vid = 0, int iid = 0, int isec = 0); - virtual ~AliAlgSensTOF(); + AlignableSensorTOF(const char* name = 0, int vid = 0, int iid = 0, int isec = 0); + virtual ~AlignableSensorTOF(); // - virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); + virtual AlignmentPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); // virtual void setTrackingFrame(); virtual void prepareMatrixT2L(); // @@ -45,7 +45,7 @@ class AliAlgSensTOF : public AliAlgSens // uint8_t fSector; // sector ID // - ClassDef(AliAlgSensTOF, 1) + ClassDef(AlignableSensorTOF, 1) }; } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgSensTPC.h b/Detectors/Align/include/Align/AlignableSensorTPC.h similarity index 68% rename from Detectors/Align/include/Align/AliAlgSensTPC.h rename to Detectors/Align/include/Align/AlignableSensorTPC.h index 7792b7a39dedf..b2218ebb0740b 100644 --- a/Detectors/Align/include/Align/AliAlgSensTPC.h +++ b/Detectors/Align/include/Align/AlignableSensorTPC.h @@ -8,36 +8,36 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgSensTPC.h +/// @file AlignableSensorTPC.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief TPC sensor (chamber) -#ifndef ALIALGSENSTPC_H -#define ALIALGSENSTPC_H +#ifndef ALIGNABLESENSORTPC_H +#define ALIGNABLESENSORTPC_H -#include "Align/AliAlgSens.h" +#include "Align/AlignableSensor.h" class TObjArray; //class AliTrackPointArray; //class AliESDtrack; -class AliAlgPoint; +class AlignmentPoint; namespace o2 { namespace align { -class AliAlgSensTPC : public AliAlgSens +class AlignableSensorTPC : public AlignableSensor { public: - AliAlgSensTPC(const char* name = 0, int vid = 0, int iid = 0, int isec = 0); - virtual ~AliAlgSensTPC(); + AlignableSensorTPC(const char* name = 0, int vid = 0, int iid = 0, int isec = 0); + virtual ~AlignableSensorTPC(); // int GetSector() const { return fSector; } void SetSector(uint32_t sc) { fSector = (uint8_t)sc; } // - virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); + virtual AlignmentPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); // virtual void setTrackingFrame(); virtual void prepareMatrixT2L(); // @@ -45,7 +45,7 @@ class AliAlgSensTPC : public AliAlgSens // uint8_t fSector; // sector ID - ClassDef(AliAlgSensTPC, 1) + ClassDef(AlignableSensorTPC, 1) }; } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgSensTRD.h b/Detectors/Align/include/Align/AlignableSensorTRD.h similarity index 62% rename from Detectors/Align/include/Align/AliAlgSensTRD.h rename to Detectors/Align/include/Align/AlignableSensorTRD.h index 8550dd6f7eb8c..80c9377d7aeb7 100644 --- a/Detectors/Align/include/Align/AliAlgSensTRD.h +++ b/Detectors/Align/include/Align/AlignableSensorTRD.h @@ -8,18 +8,18 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgSensTRD.h +/// @file AlignableSensorTRD.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief TRD sensor -#ifndef ALIALGSENSTRD_H -#define ALIALGSENSTRD_H +#ifndef ALIGNABLESENSORTRD_H +#define ALIGNABLESENSORTRD_H -#include "Align/AliAlgSens.h" +#include "Align/AlignableSensor.h" //class AliTrackPointArray; //class AliESDtrack; -class AliAlgPoint; +class AlignmentPoint; class TObjArray; namespace o2 @@ -27,18 +27,18 @@ namespace o2 namespace align { -class AliAlgSensTRD : public AliAlgSens +class AlignableSensorTRD : public AlignableSensor { public: - AliAlgSensTRD(const char* name = 0, int vid = 0, int iid = 0, int isec = 0); - virtual ~AliAlgSensTRD(); + AlignableSensorTRD(const char* name = 0, int vid = 0, int iid = 0, int isec = 0); + virtual ~AlignableSensorTRD(); // int GetSector() const { return fSector; } void SetSector(uint32_t sc) { fSector = (uint8_t)sc; } // - virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); + virtual AlignmentPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); // - virtual void dPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int calibID, const AliAlgVol* parent = 0) const; + virtual void dPosTraDParCalib(const AlignmentPoint* pnt, double* deriv, int calibID, const AlignableVolume* parent = 0) const; // // virtual void setTrackingFrame(); virtual void prepareMatrixT2L(); @@ -47,7 +47,7 @@ class AliAlgSensTRD : public AliAlgSens // uint8_t fSector; // sector ID - ClassDef(AliAlgSensTRD, 1) + ClassDef(AlignableSensorTRD, 1) }; } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgVol.h b/Detectors/Align/include/Align/AlignableVolume.h similarity index 90% rename from Detectors/Align/include/Align/AliAlgVol.h rename to Detectors/Align/include/Align/AlignableVolume.h index 24315ed22a02d..dd767a358fd59 100644 --- a/Detectors/Align/include/Align/AliAlgVol.h +++ b/Detectors/Align/include/Align/AlignableVolume.h @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgVol.h +/// @file AlignableVolume.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Base class of alignable volume @@ -20,14 +20,14 @@ * AliGeomManager can trace to geometry. */ -#ifndef ALIALGVOL_H -#define ALIALGVOL_H +#ifndef ALIGNABLEVOLUME_H +#define ALIGNABLEVOLUME_H #include #include #include #include -#include "Align/AliAlgDOFStat.h" +#include "Align/DOFStatistics.h" class TObjArray; class TClonesArray; @@ -38,7 +38,7 @@ namespace o2 namespace align { -class AliAlgVol : public TNamed +class AlignableVolume : public TNamed { public: enum DOFGeom_t { kDOFTX, @@ -64,8 +64,8 @@ class AliAlgVol : public TNamed kExclFromParentConstraintBit = BIT(16) }; enum { kDefChildConstr = 0xff }; // - AliAlgVol(const char* symname = 0, int iid = 0); - virtual ~AliAlgVol(); + AlignableVolume(const char* symname = 0, int iid = 0); + virtual ~AlignableVolume(); // const char* getSymName() const { return GetName(); } // @@ -111,8 +111,8 @@ class AliAlgVol : public TNamed void setChildrenConstrainPattern(uint32_t pat) { mConstrChild = pat; } bool hasChildrenConstraint() const { return mConstrChild; } // - AliAlgVol* getParent() const { return mParent; } - void setParent(AliAlgVol* par) + AlignableVolume* getParent() const { return mParent; } + void setParent(AlignableVolume* par) { mParent = par; if (par) @@ -121,15 +121,15 @@ class AliAlgVol : public TNamed int countParents() const; // int getNChildren() const { return mChildren ? mChildren->GetEntriesFast() : 0; } - AliAlgVol* getChild(int i) const { return mChildren ? (AliAlgVol*)mChildren->UncheckedAt(i) : 0; } - virtual void addChild(AliAlgVol* ch); + AlignableVolume* getChild(int i) const { return mChildren ? (AlignableVolume*)mChildren->UncheckedAt(i) : 0; } + virtual void addChild(AlignableVolume* ch); // double getXTracking() const { return mX; } double getAlpTracking() const { return mAlp; } // int getNProcessedPoints() const { return mNProcPoints; } - virtual int finalizeStat(AliAlgDOFStat* h = 0); - void fillDOFStat(AliAlgDOFStat* h) const; + virtual int finalizeStat(DOFStatistics* h = 0); + void fillDOFStat(DOFStatistics* h) const; // float* getParVals() const { return mParVals; } double getParVal(int par) const { return mParVals[par]; } @@ -199,7 +199,7 @@ class AliAlgVol : public TNamed bool getInitDOFsDone() const { return TestBit(kInitDOFsDoneBit); } // bool ownsDOFID(int id) const; - AliAlgVol* getVolOfDOFID(int id) const; + AlignableVolume* getVolOfDOFID(int id) const; // virtual bool isSensor() const { return false; } // @@ -216,8 +216,8 @@ class AliAlgVol : public TNamed void calcFree(bool condFree = false); // // ------- dummies ------- - AliAlgVol(const AliAlgVol&); - AliAlgVol& operator=(const AliAlgVol&); + AlignableVolume(const AlignableVolume&); + AlignableVolume& operator=(const AlignableVolume&); // protected: // @@ -232,8 +232,8 @@ class AliAlgVol : public TNamed char mNDOFFree; // number of all free degrees of freedom uint8_t mConstrChild; // bitpattern for constraints on children corrections // - AliAlgVol* mParent; // parent volume - TObjArray* mChildren; // array of childrens + AlignableVolume* mParent; // parent volume + TObjArray* mChildren; // array of childrens // int mNProcPoints; // n of processed points int mFirstParGloID; // ID of the 1st parameter in the global results array @@ -251,11 +251,11 @@ class AliAlgVol : public TNamed static const char* sFrameName[kNVarFrames]; static uint32_t sDefGeomFree; // - ClassDef(AliAlgVol, 2) + ClassDef(AlignableVolume, 2) }; //___________________________________________________________ -inline void AliAlgVol::getMatrixT2G(TGeoHMatrix& m) const +inline void AlignableVolume::getMatrixT2G(TGeoHMatrix& m) const { // compute tracking to global matrix, i.e. glo = T2G*tra = L2G*loc = L2G*T2L*tra m = getMatrixL2GIdeal(); diff --git a/Detectors/Align/include/Align/AliAlgPoint.h b/Detectors/Align/include/Align/AlignmentPoint.h similarity index 91% rename from Detectors/Align/include/Align/AliAlgPoint.h rename to Detectors/Align/include/Align/AlignmentPoint.h index fe2606b678d5f..1862baf74e034 100644 --- a/Detectors/Align/include/Align/AliAlgPoint.h +++ b/Detectors/Align/include/Align/AlignmentPoint.h @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgPoint.h +/// @file AlignmentPoint.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Meausered point in the sensor. @@ -20,23 +20,23 @@ * Cashes residuals and track positions at its reference X */ -#ifndef ALIALGPOINT_H -#define ALIALGPOINT_H +#ifndef ALIGNMENTPOINT_H +#define ALIGNMENTPOINT_H #include #include #include -#include "Align/AliAlgSens.h" +#include "Align/AlignableSensor.h" #include "ReconstructionDataFormats/Track.h" #include "Framework/Logger.h" -#include "Align/AliAlgAux.h" +#include "Align/utils.h" namespace o2 { namespace align { -class AliAlgPoint : public TObject +class AlignmentPoint : public TObject { public: enum { kMaterialBit = BIT(14), // point contains material @@ -60,8 +60,8 @@ class AliAlgPoint : public TObject kY, kZ }; // - AliAlgPoint(); - virtual ~AliAlgPoint() {} + AlignmentPoint(); + virtual ~AlignmentPoint() {} // void init(); void updatePointByTrackInfo(const trackParam_t* t); @@ -76,9 +76,9 @@ class AliAlgPoint : public TObject const double* getXYZTracking() const { return mXYZTracking; } const double* getYZErrTracking() const { return mErrYZTracking; } - const AliAlgSens* getSensor() const { return mSensor; } + const AlignableSensor* getSensor() const { return mSensor; } uint32_t getVolID() const { return mSensor->getVolID(); } - void setSensor(AliAlgSens* s) { mSensor = s; } + void setSensor(AlignableSensor* s) { mSensor = s; } int getDetID() const { return mDetID; } int getSID() const { return mSID; } @@ -185,8 +185,8 @@ class AliAlgPoint : public TObject virtual int Compare(const TObject* a) const; // // ---------- dummies ---------- - AliAlgPoint(const AliAlgPoint&); - AliAlgPoint& operator=(const AliAlgPoint&); + AlignmentPoint(const AlignmentPoint&); + AlignmentPoint& operator=(const AlignmentPoint&); // protected: // @@ -218,13 +218,13 @@ class AliAlgPoint : public TObject double mTrParamWSA[kNMatDOFs]; // workspace for tracks params at this point AFTER material correction double mTrParamWSB[kNMatDOFs]; // workspace for tracks params at this point BEFORE material correction - AliAlgSens* mSensor; // sensor of this point + AlignableSensor* mSensor; // sensor of this point - ClassDef(AliAlgPoint, 1) + ClassDef(AlignmentPoint, 1) }; //____________________________________________________ -inline void AliAlgPoint::setXYZTracking(double x, double y, double z) +inline void AlignmentPoint::setXYZTracking(double x, double y, double z) { // assign tracking coordinates mXYZTracking[0] = x; @@ -233,7 +233,7 @@ inline void AliAlgPoint::setXYZTracking(double x, double y, double z) } //____________________________________________________ -inline void AliAlgPoint::setYZErrTracking(double sy2, double syz, double sz2) +inline void AlignmentPoint::setYZErrTracking(double sy2, double syz, double sz2) { // assign tracking coordinates mErrYZTracking[0] = sy2; @@ -241,14 +241,14 @@ inline void AliAlgPoint::setYZErrTracking(double sy2, double syz, double sz2) mErrYZTracking[2] = sz2; } -inline int AliAlgPoint::getNMatPar() const +inline int AlignmentPoint::getNMatPar() const { // get number of free params for material descriptoin return containsMaterial() ? (getELossVaried() ? kNMSPar + kNELossPar : kNMSPar) : 0; } //_____________________________________ -inline void AliAlgPoint::diagonalizeResiduals(double rY, double rZ, double& resU, double& resV) const +inline void AlignmentPoint::diagonalizeResiduals(double rY, double rZ, double& resU, double& resV) const { // rotate residuals to frame where their error matrix is diagonal resU = mCosDiagErr * rY - mSinDiagErr * rZ; @@ -257,7 +257,7 @@ inline void AliAlgPoint::diagonalizeResiduals(double rY, double rZ, double& resU } //_____________________________________ -inline void AliAlgPoint::getResidualsDiag(const double* pos, double& resU, double& resV) const +inline void AlignmentPoint::getResidualsDiag(const double* pos, double& resU, double& resV) const { // calculate residuals in the frame where the errors are diagonal, given the position // of the track in the standard tracking frame @@ -266,7 +266,7 @@ inline void AliAlgPoint::getResidualsDiag(const double* pos, double& resU, doubl } //__________________________________________________________________ -inline void AliAlgPoint::incrementStat() +inline void AlignmentPoint::incrementStat() { // increment statistics for detectors this point depends on mSensor->incrementStat(); diff --git a/Detectors/Align/include/Align/AliAlgTrack.h b/Detectors/Align/include/Align/AlignmentTrack.h similarity index 82% rename from Detectors/Align/include/Align/AliAlgTrack.h rename to Detectors/Align/include/Align/AlignmentTrack.h index cacfa995942a6..d7b311139e9ea 100644 --- a/Detectors/Align/include/Align/AliAlgTrack.h +++ b/Detectors/Align/include/Align/AlignmentTrack.h @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgTrack.h +/// @file AlignmentTrack.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Track model for the alignment @@ -19,10 +19,10 @@ * Full support for derivatives and residuals calculation */ -#ifndef ALIALGTRACK_H -#define ALIALGTRACK_H +#ifndef ALIGNMENTTRACK_H +#define ALIGNMENTTRACK_H -#include "Align/AliAlgPoint.h" +#include "Align/AlignmentPoint.h" #include "ReconstructionDataFormats/Track.h" #include #include @@ -34,7 +34,7 @@ namespace o2 namespace align { -class AliAlgTrack : public trackParam_t, public TObject +class AlignmentTrack : public trackParam_t, public TObject { public: using trackParam_t = o2::track::TrackParametrizationWithError; @@ -61,32 +61,32 @@ class AliAlgTrack : public trackParam_t, public TObject kParTgl, kParQ2Pt }; - AliAlgTrack(); - virtual ~AliAlgTrack(); + AlignmentTrack(); + virtual ~AlignmentTrack(); void defineDOFs(); double getMass() const { return mMass; } double getMinX2X0Pt2Account() const { return mMinX2X0Pt2Account; } int getNPoints() const { return mPoints.GetEntriesFast(); } - AliAlgPoint* getPoint(int i) const { return (AliAlgPoint*)mPoints[i]; } - void addPoint(AliAlgPoint* p) { mPoints.AddLast(p); } + AlignmentPoint* getPoint(int i) const { return (AlignmentPoint*)mPoints[i]; } + void addPoint(AlignmentPoint* p) { mPoints.AddLast(p); } void setMass(double m) { mMass = m; } void setMinX2X0Pt2Account(double v) { mMinX2X0Pt2Account = v; } int getNLocPar() const { return mNLocPar; } int getNLocExtPar() const { return mNLocExtPar; } int getInnerPointID() const { return mInnerPointID; } - AliAlgPoint* getInnerPoint() const { return getPoint(mInnerPointID); } + AlignmentPoint* getInnerPoint() const { return getPoint(mInnerPointID); } // virtual void Clear(Option_t* opt = ""); virtual void Print(Option_t* opt = "") const; virtual void dumpCoordinates() const; // - bool propagateToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT, track::TrackLTIntegral* tLT = nullptr); - bool propagateParamToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep = 3, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT); // param only - bool propagateParamToPoint(trackParam_t* trSet, int nTr, const AliAlgPoint* pnt, double maxStep = 3, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT); // params only + bool propagateToPoint(trackParam_t& tr, const AlignmentPoint* pnt, double maxStep, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT, track::TrackLTIntegral* tLT = nullptr); + bool propagateParamToPoint(trackParam_t& tr, const AlignmentPoint* pnt, double maxStep = 3, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT); // param only + bool propagateParamToPoint(trackParam_t* trSet, int nTr, const AlignmentPoint* pnt, double maxStep = 3, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT); // params only // bool calcResiduals(const double* params = 0); bool calcResidDeriv(double* params = 0); - bool calcResidDerivGlo(AliAlgPoint* pnt); + bool calcResidDerivGlo(AlignmentPoint* pnt); // bool isCosmic() const { return TestBit(kCosmicBit); } void setCosmic(bool v = true) { SetBit(kCosmicBit, v); } @@ -115,8 +115,8 @@ class AliAlgTrack : public trackParam_t, public TObject void imposePtBOff(double pt) { setQ2Pt(1. / pt); } // propagation methods void copyFrom(const trackParam_t* etp); - bool applyMatCorr(trackParam_t& trPar, const double* corrDiag, const AliAlgPoint* pnt); - bool applyMatCorr(trackParam_t* trSet, int ntr, const double* corrDiaf, const AliAlgPoint* pnt); + bool applyMatCorr(trackParam_t& trPar, const double* corrDiag, const AlignmentPoint* pnt); + bool applyMatCorr(trackParam_t* trSet, int ntr, const double* corrDiaf, const AlignmentPoint* pnt); bool applyMatCorr(trackParam_t& trPar, const double* corrpar); // double getResidual(int dim, int pntID) const { return mResidA[dim][pntID]; } @@ -132,7 +132,7 @@ class AliAlgTrack : public trackParam_t, public TObject void modParam(trackParam_t* trSet, int ntr, int par, double delta); // void richardsonDeriv(const trackParam_t* trSet, const double* delta, - const AliAlgPoint* pnt, double& derY, double& derZ); + const AlignmentPoint* pnt, double& derY, double& derZ); // const double* getLocPars() const { return mLocParA; } void setLocPars(const double* pars); @@ -150,8 +150,8 @@ class AliAlgTrack : public trackParam_t, public TObject static double richardsonExtrap(const double* val, int ord = 1); // // ---------- dummies ---------- - AliAlgTrack(const AliAlgTrack&); - AliAlgTrack& operator=(const AliAlgTrack&); + AlignmentTrack(const AlignmentTrack&); + AlignmentTrack& operator=(const AlignmentTrack&); // protected: int mNLocPar; // number of local params @@ -178,13 +178,13 @@ class AliAlgTrack : public trackParam_t, public TObject int* mGloParIDA; //! fast access to relevant global param IDs double* mLocParA; //! fast access to local params private: - bool propagate(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT); + bool propagate(trackParam_t& tr, const AlignmentPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT); // - ClassDef(AliAlgTrack, 2) + ClassDef(AlignmentTrack, 2) }; //____________________________________________________________________________________________ -inline void AliAlgTrack::setParams(trackParam_t& tr, double x, double alp, const double* par, bool add) +inline void AlignmentTrack::setParams(trackParam_t& tr, double x, double alp, const double* par, bool add) { // set track params const double kDefQ2PtCosm = 1; @@ -211,7 +211,7 @@ inline void AliAlgTrack::setParams(trackParam_t& tr, double x, double alp, const } //____________________________________________________________________________________________ -inline void AliAlgTrack::setParams(trackParam_t* trSet, int ntr, double x, double alp, const double* par, bool add) +inline void AlignmentTrack::setParams(trackParam_t* trSet, int ntr, double x, double alp, const double* par, bool add) { // set parames for multiple tracks (VECTORIZE THIS) if (!add) { // full parameter supplied @@ -227,14 +227,14 @@ inline void AliAlgTrack::setParams(trackParam_t* trSet, int ntr, double x, doubl } //____________________________________________________________________________________________ -inline void AliAlgTrack::setParam(trackParam_t& tr, int par, double val) +inline void AlignmentTrack::setParam(trackParam_t& tr, int par, double val) { // set track parameter tr.setParam(val, par); } //____________________________________________________________________________________________ -inline void AliAlgTrack::setParam(trackParam_t* trSet, int ntr, int par, double val) +inline void AlignmentTrack::setParam(trackParam_t* trSet, int ntr, int par, double val) { // set parames for multiple tracks (VECTORIZE THIS) for (int i = 0; i < ntr; ++i) { @@ -243,7 +243,7 @@ inline void AliAlgTrack::setParam(trackParam_t* trSet, int ntr, int par, double } //____________________________________________________________________________________________ -inline void AliAlgTrack::modParam(trackParam_t& tr, int par, double delta) +inline void AlignmentTrack::modParam(trackParam_t& tr, int par, double delta) { // modify track parameter const auto val = tr.getParam(par) + delta; @@ -251,7 +251,7 @@ inline void AliAlgTrack::modParam(trackParam_t& tr, int par, double delta) } //____________________________________________________________________________________________ -inline void AliAlgTrack::modParam(trackParam_t* trSet, int ntr, int par, double delta) +inline void AlignmentTrack::modParam(trackParam_t* trSet, int ntr, int par, double delta) { // modify track parameter (VECTORIZE THOS) for (size_t i = 0; i < ntr; ++i) { @@ -260,7 +260,7 @@ inline void AliAlgTrack::modParam(trackParam_t* trSet, int ntr, int par, double } //______________________________________________ -inline void AliAlgTrack::copyFrom(const trackParam_t* etp) +inline void AlignmentTrack::copyFrom(const trackParam_t* etp) { // assign kinematics set(etp->getX(), etp->getAlpha(), etp->getParams(), etp->getCov().data()); diff --git a/Detectors/Align/include/Align/AliAlgSteer.h b/Detectors/Align/include/Align/Controller.h similarity index 71% rename from Detectors/Align/include/Align/AliAlgSteer.h rename to Detectors/Align/include/Align/Controller.h index 7e575f957b8d6..964eaca314213 100644 --- a/Detectors/Align/include/Align/AliAlgSteer.h +++ b/Detectors/Align/include/Align/Controller.h @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgSteer.h +/// @file Controller.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Steering class for the global alignment @@ -18,11 +18,11 @@ * to participating detectors and preparation of the millepede input. */ -#ifndef ALIALGSTEER_H -#define ALIALGSTEER_H +#ifndef CONTROLLER_H +#define CONTROLLER_H #include "DetectorsBase/GeometryManager.h" -#include "Align/AliAlgTrack.h" +#include "Align/AlignmentTrack.h" // #include "AliSymMatrix.h" FIXME(milettri): needs AliSymMatrix #include @@ -32,7 +32,7 @@ #include #include #include -#include "Align/AliAlgAux.h" +#include "Align/utils.h" //class AliESDEvent; FIXME(milettri): needs AliESDEvent //class AliESDtrack; FIXME(milettri): needs AliESDtrack @@ -50,17 +50,17 @@ namespace align class Mille; -class AliAlgDet; -class AliAlgVol; -class AliAlgVtx; -class AliAlgPoint; -class AliAlgMPRecord; -class AliAlgRes; -class AliAlgResFast; -class AliAlgConstraint; -class AliAlgDOFStat; +class AlignableDetector; +class AlignableVolume; +class EventVertex; +class AlignmentPoint; +class Millepede2Record; +class ResidualsController; +class ResidualsControllerFast; +class GeometricalConstraint; +class DOFStatistics; -class AliAlgSteer : public TObject +class Controller : public TObject { public: enum { kNLrSkip = 4 }; @@ -118,8 +118,8 @@ class AliAlgSteer : public TObject }; // - AliAlgSteer(const char* configMacro = 0, int refRun = -1); - virtual ~AliAlgSteer(); + Controller(const char* configMacro = 0, int refRun = -1); + virtual ~Controller(); // bool LoadRefOCDB(); FIXME(milettri): needs OCDB // bool LoadRecoTimeOCDB(); FIXME(milettri): needs OCDB bool getUseRecoOCDB() const { return mUseRecoOCDB; } @@ -141,13 +141,13 @@ class AliAlgSteer : public TObject void assignDOFs(); // - void addDetector(uint32_t id, AliAlgDet* det = 0); - void addDetector(AliAlgDet* det); + void addDetector(uint32_t id, AlignableDetector* det = 0); + void addDetector(AlignableDetector* det); // - void addConstraint(const AliAlgConstraint* cs) { mConstraints.AddLast((TObject*)cs); } + void addConstraint(const GeometricalConstraint* cs) { mConstraints.AddLast((TObject*)cs); } int getNConstraints() const { return mConstraints.GetEntriesFast(); } const TObjArray* getConstraints() const { return &mConstraints; } - const AliAlgConstraint* getConstraint(int i) const { return (AliAlgConstraint*)mConstraints[i]; } + const GeometricalConstraint* getConstraint(int i) const { return (GeometricalConstraint*)mConstraints[i]; } void addAutoConstraints(); // void acknowledgeNewRun(int run); @@ -156,10 +156,10 @@ class AliAlgSteer : public TObject bool getFieldOn() const { return mFieldOn; } void setFieldOn(bool v = true) { mFieldOn = v; } int getTracksType() const { return mTracksType; } - void setTracksType(int t = AliAlgAux::kColl) { mTracksType = t; } - bool isCosmic() const { return mTracksType == AliAlgAux::kCosm; } - bool isCollision() const { return mTracksType == AliAlgAux::kColl; } - void setCosmic(bool v = true) { mTracksType = v ? AliAlgAux::kCosm : AliAlgAux::kColl; } + void setTracksType(int t = utils::kColl) { mTracksType = t; } + bool isCosmic() const { return mTracksType == utils::kCosm; } + bool isCollision() const { return mTracksType == utils::kColl; } + void setCosmic(bool v = true) { mTracksType = v ? utils::kCosm : utils::kColl; } float getStat(int cls, int tp) const { return mStat[cls][tp]; } // void setESDTree(const TTree* tr) { mESDTree = tr; } @@ -185,22 +185,22 @@ class AliAlgSteer : public TObject // double getPtMin(bool tp) const { return mPtMin[tp]; } void setPtMin(bool tp, double pt) { mPtMin[tp] = pt; } - void setPtMinColl(double pt = 0.7) { setPtMin(AliAlgAux::kColl, pt); } - void setPtMinCosm(double pt = 1.0) { setPtMin(AliAlgAux::kCosm, pt); } + void setPtMinColl(double pt = 0.7) { setPtMin(utils::kColl, pt); } + void setPtMinCosm(double pt = 1.0) { setPtMin(utils::kCosm, pt); } // double getEtaMax(bool tp) const { return mEtaMax[tp]; } void setEtaMax(bool tp, double eta) { mEtaMax[tp] = eta; } - void setEtaMaxColl(double eta = 1.5) { setEtaMax(AliAlgAux::kColl, eta); } - void setEtaMaxCosm(double eta = 1.5) { setEtaMax(AliAlgAux::kCosm, eta); } + void setEtaMaxColl(double eta = 1.5) { setEtaMax(utils::kColl, eta); } + void setEtaMaxCosm(double eta = 1.5) { setEtaMax(utils::kCosm, eta); } // - void setDefPtBOffCosm(double pt = 5.0) { mDefPtBOff[AliAlgAux::kCosm] = pt > 0.3 ? pt : 0.3; } - void setDefPtBOffColl(double pt = 0.6) { mDefPtBOff[AliAlgAux::kColl] = pt > 0.3 ? pt : 0.3; } + void setDefPtBOffCosm(double pt = 5.0) { mDefPtBOff[utils::kCosm] = pt > 0.3 ? pt : 0.3; } + void setDefPtBOffColl(double pt = 0.6) { mDefPtBOff[utils::kColl] = pt > 0.3 ? pt : 0.3; } double getDefPtBOff(bool tp) { return mDefPtBOff[tp]; } // int getMinDetAcc(bool tp) const { return mMinDetAcc[tp]; } void setMinDetAcc(bool tp, int n) { mMinDetAcc[tp] = n; } - void setMinDetAccColl(int n = 1) { setMinDetAcc(AliAlgAux::kColl, n); } - void setMinDetAccCosm(int n = 1) { setMinDetAcc(AliAlgAux::kCosm, n); } + void setMinDetAccColl(int n = 1) { setMinDetAcc(utils::kColl, n); } + void setMinDetAccCosm(int n = 1) { setMinDetAcc(utils::kCosm, n); } // int getVtxMinCont() const { return mVtxMinCont; } void setVtxMinCont(int n) { mVtxMinCont = n; } @@ -240,15 +240,15 @@ class AliAlgSteer : public TObject int getGloParLab(int i) const { return (int)mGloParLab[i]; } int parID2Label(int i) const { return getGloParLab(i); } int label2ParID(int lab) const; - AliAlgVol* getVolOfDOFID(int id) const; - AliAlgDet* getDetOfDOFID(int id) const; + AlignableVolume* getVolOfDOFID(int id) const; + AlignableDetector* getDetOfDOFID(int id) const; // - AliAlgPoint* getRefPoint() const { return (AliAlgPoint*)mRefPoint; } + AlignmentPoint* getRefPoint() const { return (AlignmentPoint*)mRefPoint; } // - AliAlgRes* getContResid() const { return (AliAlgRes*)mCResid; } - AliAlgMPRecord* getMPRecord() const { return (AliAlgMPRecord*)mMPRecord; } + ResidualsController* getContResid() const { return (ResidualsController*)mCResid; } + Millepede2Record* getMPRecord() const { return (Millepede2Record*)mMPRecord; } TTree* getMPRecTree() const { return mMPRecTree; } - AliAlgTrack* getAlgTrack() const { return (AliAlgTrack*)mAlgTrack; } + AlignmentTrack* getAlgTrack() const { return (AlignmentTrack*)mAlgTrack; } // bool ProcessEvent(const AliESDEvent* esdEv); FIXME(milettri): needs AliESDEvent // bool ProcessTrack(const AliESDtrack* esdTr); FIXME(milettri): needs AliESDtrack // bool ProcessTrack(const AliESDCosmicTrack* esdCTr); FIXME(milettri): needs AliESDCosmicTrack @@ -257,10 +257,10 @@ class AliAlgSteer : public TObject // bool CheckSetVertex(const AliESDVertex* vtx); FIXME(milettri): needs AliESDVertex bool addVertexConstraint(); int getNDetectors() const { return mNDet; } - AliAlgDet* getDetector(int i) const { return mDetectors[i]; } - AliAlgDet* getDetectorByDetID(int i) const { return mDetPos[i] < 0 ? 0 : mDetectors[mDetPos[i]]; } - AliAlgDet* getDetectorByVolID(int id) const; - AliAlgVtx* getVertexSensor() const { return mVtxSens; } + AlignableDetector* getDetector(int i) const { return mDetectors[i]; } + AlignableDetector* getDetectorByDetID(int i) const { return mDetPos[i] < 0 ? 0 : mDetectors[mDetPos[i]]; } + AlignableDetector* getDetectorByVolID(int id) const; + EventVertex* getVertexSensor() const { return mVtxSens; } // void resetDetectors(); int getNDOFs() const { return mNDOFs; } @@ -338,8 +338,8 @@ class AliAlgSteer : public TObject void genPedeSteerFile(const Option_t* opt = "") const; void writePedeConstraints() const; void checkConstraints(const char* params = 0); - AliAlgDOFStat* GetDOFStat() const { return mDOFStat; } - void setDOFStat(AliAlgDOFStat* st) { mDOFStat = st; } + DOFStatistics* GetDOFStat() const { return mDOFStat; } + void setDOFStat(DOFStatistics* st) { mDOFStat = st; } void detachDOFStat() { setDOFStat(0); } TH1* getHistoStat() const { return mHistoStat; } void detachHistoStat() { setHistoStat(0); } @@ -373,39 +373,39 @@ class AliAlgSteer : public TObject // // fast check of solution using derivatives void checkSol(TTree* mpRecTree, bool store = true, bool verbose = false, bool loc = true, const char* outName = "resFast"); - bool checkSol(AliAlgMPRecord* rec, AliAlgResFast* rLG = 0, AliAlgResFast* rL = 0, bool verbose = true, bool loc = true); + bool checkSol(Millepede2Record* rec, ResidualsControllerFast* rLG = 0, ResidualsControllerFast* rL = 0, bool verbose = true, bool loc = true); // protected: // // --------- dummies ----------- - AliAlgSteer(const AliAlgSteer&); - AliAlgSteer& operator=(const AliAlgSteer&); + Controller(const Controller&); + Controller& operator=(const Controller&); // protected: // - int mNDet; // number of deectors participating in the alignment - int mNDOFs; // number of degrees of freedom - int mRunNumber; // current run number - bool mFieldOn; // field on flag - int mTracksType; // collision/cosmic event type - AliAlgTrack* mAlgTrack; // current alignment track - AliAlgDet* mDetectors[kNDetectors]; // detectors participating in the alignment - int mDetPos[kNDetectors]; // entry of detector in the mDetectors array - AliAlgVtx* mVtxSens; // fake sensor for the vertex - TObjArray mConstraints; // array of constraints + int mNDet; // number of deectors participating in the alignment + int mNDOFs; // number of degrees of freedom + int mRunNumber; // current run number + bool mFieldOn; // field on flag + int mTracksType; // collision/cosmic event type + AlignmentTrack* mAlgTrack; // current alignment track + AlignableDetector* mDetectors[kNDetectors]; // detectors participating in the alignment + int mDetPos[kNDetectors]; // entry of detector in the mDetectors array + EventVertex* mVtxSens; // fake sensor for the vertex + TObjArray mConstraints; // array of constraints // // Track selection - uint32_t mSelEventSpecii; // consider only these event specii - uint32_t mObligatoryDetPattern[AliAlgAux::kNTrackTypes]; // pattern of obligatory detectors - bool mCosmicSelStrict; // if true, each cosmic track leg selected like separate track - int mMinPoints[AliAlgAux::kNTrackTypes][2]; // require min points per leg (case Boff,Bon) - int mMinDetAcc[AliAlgAux::kNTrackTypes]; // min number of detector required in track - double mDefPtBOff[AliAlgAux::kNTrackTypes]; // nominal pt for tracks in Boff run - double mPtMin[AliAlgAux::kNTrackTypes]; // min pT of tracks to consider - double mEtaMax[AliAlgAux::kNTrackTypes]; // eta cut on tracks - int mVtxMinCont; // require min number of contributors in Vtx - int mVtxMaxCont; // require max number of contributors in Vtx - int mVtxMinContVC; // min number of contributors to use as constraint + uint32_t mSelEventSpecii; // consider only these event specii + uint32_t mObligatoryDetPattern[utils::kNTrackTypes]; // pattern of obligatory detectors + bool mCosmicSelStrict; // if true, each cosmic track leg selected like separate track + int mMinPoints[utils::kNTrackTypes][2]; // require min points per leg (case Boff,Bon) + int mMinDetAcc[utils::kNTrackTypes]; // min number of detector required in track + double mDefPtBOff[utils::kNTrackTypes]; // nominal pt for tracks in Boff run + double mPtMin[utils::kNTrackTypes]; // min pT of tracks to consider + double mEtaMax[utils::kNTrackTypes]; // eta cut on tracks + int mVtxMinCont; // require min number of contributors in Vtx + int mVtxMaxCont; // require max number of contributors in Vtx + int mVtxMinContVC; // min number of contributors to use as constraint // int mMinITSClforVC; // use vertex constraint for tracks with enough points int mITSPattforVC; // optional request on ITS hits to allow vertex constraint @@ -419,7 +419,7 @@ class AliAlgSteer : public TObject int* mOrderedLbl; //[mNDOFs] ordered labels int* mLbl2ID; //[mNDOFs] Label order in mOrderedLbl -> parID // - AliAlgPoint* mRefPoint; // reference point for track definition + AlignmentPoint* mRefPoint; // reference point for track definition // const TTree* mESDTree; //! externally set esdTree, needed to access UserInfo list // const AliESDEvent* fESDEvent; //! externally set event FIXME(milettri): needs AliESDEvent @@ -432,31 +432,31 @@ class AliAlgSteer : public TObject static const Char_t* sStatName[kMaxStat]; // stat type names // // output related - float mControlFrac; // fraction of tracks to process control residuals - int mMPOutType; // What to store as an output, see storeProcessedTrack - Mille* mMille; //! Mille interface - AliAlgMPRecord* mMPRecord; //! MP record - AliAlgRes* mCResid; //! control residuals - TTree* mMPRecTree; //! tree to store MP record - TTree* mResidTree; //! tree to store control residuals - TFile* mMPRecFile; //! file to store MP record tree - TFile* mResidFile; //! file to store control residuals tree - TArrayF mMilleDBuffer; //! buffer for Mille Derivatives output - TArrayI mMilleIBuffer; //! buffer for Mille Indecis output - TString mMPDatFileName; // file name for records binary data output - TString mMPParFileName; // file name for MP params - TString mMPConFileName; // file name for MP constraints - TString mMPSteerFileName; // file name for MP steering - TString mResidFileName; // file name for optional control residuals - bool mMilleOutBin; // optionally text output for Mille debugging - bool mDoKalmanResid; // calculate residuals with smoothed kalman in the ControlRes + float mControlFrac; // fraction of tracks to process control residuals + int mMPOutType; // What to store as an output, see storeProcessedTrack + Mille* mMille; //! Mille interface + Millepede2Record* mMPRecord; //! MP record + ResidualsController* mCResid; //! control residuals + TTree* mMPRecTree; //! tree to store MP record + TTree* mResidTree; //! tree to store control residuals + TFile* mMPRecFile; //! file to store MP record tree + TFile* mResidFile; //! file to store control residuals tree + TArrayF mMilleDBuffer; //! buffer for Mille Derivatives output + TArrayI mMilleIBuffer; //! buffer for Mille Indecis output + TString mMPDatFileName; // file name for records binary data output + TString mMPParFileName; // file name for MP params + TString mMPConFileName; // file name for MP constraints + TString mMPSteerFileName; // file name for MP steering + TString mResidFileName; // file name for optional control residuals + bool mMilleOutBin; // optionally text output for Mille debugging + bool mDoKalmanResid; // calculate residuals with smoothed kalman in the ControlRes // TString mOutCDBPath; // output OCDB path TString mOutCDBComment; // optional comment to add to output cdb objects TString mOutCDBResponsible; // optional responsible for output metadata int mOutCDBRunRange[2]; // run range for output storage // - AliAlgDOFStat* mDOFStat; // stat of entries per dof + DOFStatistics* mDOFStat; // stat of entries per dof TH1F* mHistoStat; // histo with general statistics // // input related @@ -472,23 +472,23 @@ class AliAlgSteer : public TObject static const Char_t* sHStatName[kNHVars]; // names for stat.bins in the stat histo static const Char_t* sMPDataExt; // extension for MP2 binary data // - ClassDef(AliAlgSteer, 3) + ClassDef(Controller, 3) }; //__________________________________________________________ -inline void AliAlgSteer::setMinPointsColl(int vbOff, int vbOn) +inline void Controller::setMinPointsColl(int vbOff, int vbOn) { // ask min number of points per track - setMinPoints(AliAlgAux::kColl, false, vbOff); - setMinPoints(AliAlgAux::kColl, true, vbOn); + setMinPoints(utils::kColl, false, vbOff); + setMinPoints(utils::kColl, true, vbOn); } //__________________________________________________________ -inline void AliAlgSteer::setMinPointsCosm(int vbOff, int vbOn) +inline void Controller::setMinPointsCosm(int vbOff, int vbOn) { // ask min number of points per track - setMinPoints(AliAlgAux::kCosm, false, vbOff); - setMinPoints(AliAlgAux::kCosm, true, vbOn); + setMinPoints(utils::kCosm, false, vbOff); + setMinPoints(utils::kCosm, true, vbOn); } } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgDOFStat.h b/Detectors/Align/include/Align/DOFStatistics.h similarity index 75% rename from Detectors/Align/include/Align/AliAlgDOFStat.h rename to Detectors/Align/include/Align/DOFStatistics.h index adb0f81604da5..734b8f6f386aa 100644 --- a/Detectors/Align/include/Align/AliAlgDOFStat.h +++ b/Detectors/Align/include/Align/DOFStatistics.h @@ -8,13 +8,13 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgDOFStat.h +/// @file DOFStatistics.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 -/// @brief Mergable bbject for statistics of points used by each DOF +/// @brief Mergable Object for statistics of points used by each DOF -#ifndef ALIALGDOFSTAT_H -#define ALIALGDOFSTAT_H +#ifndef DOFStatistics_H +#define DOFStatistics_H #include class TH1F; @@ -25,13 +25,13 @@ namespace o2 namespace align { -class AliAlgSteer; +class Controller; -class AliAlgDOFStat : public TNamed +class DOFStatistics : public TNamed { public: - AliAlgDOFStat(int n = 0); - virtual ~AliAlgDOFStat(); + DOFStatistics(int n = 0); + virtual ~DOFStatistics(); // int getNDOFs() const { return mNDOFs; } int getStat(int idf) const { return idf < mNDOFs ? mStat[idf] : 0; } @@ -39,21 +39,21 @@ class AliAlgDOFStat : public TNamed void setStat(int idf, int v) { mStat[idf] = v; } void addStat(int idf, int v) { mStat[idf] += v; } int getNMerges() const { return mNMerges; } - TH1F* createHisto(AliAlgSteer* st) const; + TH1F* createHisto(Controller* st) const; virtual void Print(Option_t* opt) const; virtual int64_t merge(TCollection* list); // protected: // - AliAlgDOFStat(const AliAlgDOFStat&); - AliAlgDOFStat& operator=(const AliAlgDOFStat&); + DOFStatistics(const DOFStatistics&); + DOFStatistics& operator=(const DOFStatistics&); // protected: int mNDOFs; // number of dofs defined int mNMerges; // number of merges int* mStat; //[mNDOFs] statistics per DOF // - ClassDef(AliAlgDOFStat, 1); + ClassDef(DOFStatistics, 1); }; } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgVtx.h b/Detectors/Align/include/Align/EventVertex.h similarity index 78% rename from Detectors/Align/include/Align/AliAlgVtx.h rename to Detectors/Align/include/Align/EventVertex.h index 5dfaabddf71c0..dc3e3f24181f7 100644 --- a/Detectors/Align/include/Align/AliAlgVtx.h +++ b/Detectors/Align/include/Align/EventVertex.h @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgVtx.h +/// @file EventVertex.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Special fake "sensor" for event vertex. @@ -24,23 +24,23 @@ * matrix of this sensor need to be recalculated for each track! */ -#ifndef ALIALGVTX_H -#define ALIALGVTX_H +#ifndef EVENTVERTEX_H +#define EventVertex_H -#include "Align/AliAlgSens.h" +#include "Align/AlignableSensor.h" // class AliTrackPointArray; FIXME(milettri): needs AliTrackPointArray //class AliESDtrack; FIXME(milettri): needs AliESDtrack -class AliAlgPoint; +class AlignmentPoint; namespace o2 { namespace align { -class AliAlgVtx : public AliAlgSens +class EventVertex : public AlignableSensor { public: - AliAlgVtx(); + EventVertex(); // void applyCorrection(double* vtx) const; virtual bool isSensor() const { return true; } @@ -54,15 +54,15 @@ class AliAlgVtx : public AliAlgSens virtual void prepareMatrixL2GIdeal() { mMatL2GIdeal.Clear(); } // unit matrix virtual void prepareMatrixT2L(); // - // virtual AliAlgPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); FIXME(milettri): needs AliTrackPointArray, AliESDtrack + // virtual AlignmentPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); FIXME(milettri): needs AliTrackPointArray, AliESDtrack // protected: - AliAlgVtx(const AliAlgVtx&); - AliAlgVtx& operator=(const AliAlgVtx&); + EventVertex(const EventVertex&); + EventVertex& operator=(const EventVertex&); // protected: // - ClassDef(AliAlgVtx, 1); + ClassDef(EventVertex, 1); }; } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgConstraint.h b/Detectors/Align/include/Align/GeometricalConstraint.h similarity index 65% rename from Detectors/Align/include/Align/AliAlgConstraint.h rename to Detectors/Align/include/Align/GeometricalConstraint.h index 3e4c4cbe06265..33294b0c8d89c 100644 --- a/Detectors/Align/include/Align/AliAlgConstraint.h +++ b/Detectors/Align/include/Align/GeometricalConstraint.h @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgConstraint.h +/// @file GeometricalConstraint.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Descriptor of geometrical constraint @@ -23,37 +23,37 @@ * corresponding sigma = 0, or of gaussian type is sigma>0 */ -#ifndef ALIALGCONSTRAINT_H -#define ALIALGCONSTRAINT_H +#ifndef GEOMETRICALCONSTRAINT_H +#define GEOMETRICALCONSTRAINT_H #include #include #include -#include "Align/AliAlgVol.h" +#include "Align/AlignableVolume.h" namespace o2 { namespace align { -class AliAlgConstraint : public TNamed +class GeometricalConstraint : public TNamed { public: - enum { kNDOFGeom = AliAlgVol::kNDOFGeom }; + enum { kNDOFGeom = AlignableVolume::kNDOFGeom }; enum { kNoJacobianBit = BIT(14) }; // - AliAlgConstraint(const char* name = 0, const char* title = 0); - virtual ~AliAlgConstraint(); + GeometricalConstraint(const char* name = 0, const char* title = 0); + virtual ~GeometricalConstraint(); // - void setParent(const AliAlgVol* par); - const AliAlgVol* getParent() const { return mParent; } + void setParent(const AlignableVolume* par); + const AlignableVolume* getParent() const { return mParent; } // int getNChildren() const { return mChildren.GetEntriesFast(); } - AliAlgVol* getChild(int i) const { return (AliAlgVol*)mChildren[i]; } - void addChild(const AliAlgVol* v) + AlignableVolume* getChild(int i) const { return (AlignableVolume*)mChildren[i]; } + void addChild(const AlignableVolume* v) { if (v) - mChildren.AddLast((AliAlgVol*)v); + mChildren.AddLast((AlignableVolume*)v); } // bool isDOFConstrained(int dof) const { return mConstraint & 0x1 << dof; } @@ -73,20 +73,20 @@ class AliAlgConstraint : public TNamed virtual void Print(const Option_t* opt = "") const; virtual void writeChildrenConstraints(FILE* conOut) const; virtual void checkConstraint() const; - virtual const char* getDOFName(int i) const { return AliAlgVol::getGeomDOFName(i); } + virtual const char* getDOFName(int i) const { return AlignableVolume::getGeomDOFName(i); } // protected: // ------- dummies ------- - AliAlgConstraint(const AliAlgConstraint&); - AliAlgConstraint& operator=(const AliAlgConstraint&); + GeometricalConstraint(const GeometricalConstraint&); + GeometricalConstraint& operator=(const GeometricalConstraint&); // protected: - uint32_t mConstraint; // bit pattern of constraint - double mSigma[kNDOFGeom]; // optional sigma if constraint is gaussian - const AliAlgVol* mParent; // parent volume for contraint, lab if 0 - TObjArray mChildren; // volumes subjected to constraints + uint32_t mConstraint; // bit pattern of constraint + double mSigma[kNDOFGeom]; // optional sigma if constraint is gaussian + const AlignableVolume* mParent; // parent volume for contraint, lab if 0 + TObjArray mChildren; // volumes subjected to constraints // - ClassDef(AliAlgConstraint, 2); + ClassDef(GeometricalConstraint, 2); }; } // namespace align diff --git a/Detectors/Align/include/Align/AliAlgMPRecord.h b/Detectors/Align/include/Align/Millepede2Record.h similarity index 90% rename from Detectors/Align/include/Align/AliAlgMPRecord.h rename to Detectors/Align/include/Align/Millepede2Record.h index 9b8d55fd6d393..a098a8bf7dcea 100644 --- a/Detectors/Align/include/Align/AliAlgMPRecord.h +++ b/Detectors/Align/include/Align/Millepede2Record.h @@ -8,13 +8,13 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgMPRecord.h +/// @file Millepede2Record.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Millepede record in root format (can be converted to proper pede binary format. -#ifndef ALIALGMPRECORD_H -#define ALIALGMPRECORD_H +#ifndef MILLEPEDE2RECORD_H +#define MILLEPEDE2RECORD_H #include @@ -23,15 +23,15 @@ namespace o2 namespace align { -class AliAlgTrack; +class AlignmentTrack; -class AliAlgMPRecord : public TObject +class Millepede2Record : public TObject { public: enum { kCosmicBit = BIT(14) }; // - AliAlgMPRecord(); - virtual ~AliAlgMPRecord(); + Millepede2Record(); + virtual ~Millepede2Record(); // int getRun() const { return GetUniqueID(); } void setRun(int r) { SetUniqueID(r); } @@ -64,7 +64,7 @@ class AliAlgMPRecord : public TObject const int16_t* getArrLabLoc() const { return mIDLoc; } const int* getArrLabGlo() const { return mIDGlo; } // - bool fillTrack(const AliAlgTrack* trc, const int* id2Lab = 0); + bool fillTrack(const AlignmentTrack* trc, const int* id2Lab = 0); void dummyRecord(float res, float err, float dGlo, int labGlo); // void resize(int nresid, int nloc, int nglo); @@ -75,8 +75,8 @@ class AliAlgMPRecord : public TObject protected: // // ------- dummies -------- - AliAlgMPRecord(const AliAlgMPRecord&); - AliAlgMPRecord& operator=(const AliAlgMPRecord&); + Millepede2Record(const Millepede2Record&); + Millepede2Record& operator=(const Millepede2Record&); // protected: // @@ -108,7 +108,7 @@ class AliAlgMPRecord : public TObject int mNDLocTotBook; //! number of slots booked for local derivatives int mNDGloTotBook; //! number of slots booked for global derivatives // - ClassDef(AliAlgMPRecord, 4); + ClassDef(Millepede2Record, 4); }; } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgRes.h b/Detectors/Align/include/Align/ResidualsController.h similarity index 92% rename from Detectors/Align/include/Align/AliAlgRes.h rename to Detectors/Align/include/Align/ResidualsController.h index b4d37d512211f..1c31058cb6df9 100644 --- a/Detectors/Align/include/Align/AliAlgRes.h +++ b/Detectors/Align/include/Align/ResidualsController.h @@ -8,13 +8,13 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgRes.h +/// @file ResidualsController.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Container for control residuals -#ifndef ALIALGRES_H -#define ALIALGRES_H +#ifndef RESIDUALSCONTROLLER_H +#define RESIDUALSCONTROLLER_H #include #include @@ -24,17 +24,17 @@ namespace o2 namespace align { -class AliAlgTrack; +class AlignmentTrack; -class AliAlgRes : public TObject +class ResidualsController : public TObject { public: enum { kCosmicBit = BIT(14), kVertexBit = BIT(15), kKalmanDoneBit = BIT(16) }; // - AliAlgRes(); - virtual ~AliAlgRes(); + ResidualsController(); + virtual ~ResidualsController(); // void setRun(int r) { mRun = r; } void setBz(float v) { mBz = v; } @@ -99,7 +99,7 @@ class AliAlgRes : public TObject float getYLab(int i) const; float getZLab(int i) const; // - bool fillTrack(AliAlgTrack* trc, bool doKalman = kTRUE); + bool fillTrack(AlignmentTrack* trc, bool doKalman = kTRUE); void resize(int n); virtual void Clear(const Option_t* opt = ""); virtual void Print(const Option_t* opt = "re") const; @@ -107,8 +107,8 @@ class AliAlgRes : public TObject protected: // // -------- dummies -------- - AliAlgRes(const AliAlgRes&); - AliAlgRes& operator=(const AliAlgRes&); + ResidualsController(const ResidualsController&); + ResidualsController& operator=(const ResidualsController&); // protected: // @@ -141,7 +141,7 @@ class AliAlgRes : public TObject int* mVolID; //[mNPoints] volume id (0 for vertex constraint) int* mLabel; //[mNPoints] label of the volume // - ClassDef(AliAlgRes, 2); + ClassDef(ResidualsController, 2); }; } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgResFast.h b/Detectors/Align/include/Align/ResidualsControllerFast.h similarity index 89% rename from Detectors/Align/include/Align/AliAlgResFast.h rename to Detectors/Align/include/Align/ResidualsControllerFast.h index 88e86a2c7e0cb..616cc7f183e4a 100644 --- a/Detectors/Align/include/Align/AliAlgResFast.h +++ b/Detectors/Align/include/Align/ResidualsControllerFast.h @@ -8,13 +8,13 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgResFast.h +/// @file ResidualsControllerFast.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Container for control fast residuals evaluated via derivatives -#ifndef ALIALGRESFAST_H -#define ALIALGRESFAST_H +#ifndef RESIDUALSCONTROLLERFAST_H +#define RESIDUALSCONTROLLERFAST_H #include @@ -23,14 +23,14 @@ namespace o2 namespace align { -class AliAlgResFast : public TObject +class ResidualsControllerFast : public TObject { public: enum { kCosmicBit = BIT(14), kVertexBit = BIT(15) }; // - AliAlgResFast(); - virtual ~AliAlgResFast(); + ResidualsControllerFast(); + virtual ~ResidualsControllerFast(); // void setNPoints(int n) { @@ -81,8 +81,8 @@ class AliAlgResFast : public TObject protected: // // -------- dummies -------- - AliAlgResFast(const AliAlgResFast&); - AliAlgResFast& operator=(const AliAlgResFast&); + ResidualsControllerFast(const ResidualsControllerFast&); + ResidualsControllerFast& operator=(const ResidualsControllerFast&); // protected: // @@ -103,7 +103,7 @@ class AliAlgResFast : public TObject float* mSolMat; //[mNMatSol] // material corrections float* mMatErr; //[mNMatSol] // material corrections errors // - ClassDef(AliAlgResFast, 1); + ClassDef(ResidualsControllerFast, 1); }; } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/AliAlgAux.h b/Detectors/Align/include/Align/utils.h similarity index 81% rename from Detectors/Align/include/Align/AliAlgAux.h rename to Detectors/Align/include/Align/utils.h index 0e102d87fc940..5852bfffadea4 100644 --- a/Detectors/Align/include/Align/AliAlgAux.h +++ b/Detectors/Align/include/Align/utils.h @@ -8,13 +8,13 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgAux.h +/// @file utils.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Collection of auxillary methods -#ifndef ALIALGAUX_H -#define ALIALGAUX_H +#ifndef UTILS_H +#define UTILS_H #include "CommonConstants/MathConstants.h" #include "MathUtils/Utils.h" @@ -32,7 +32,7 @@ using dim3_t = typename trackParam_t::dim3_t; using params_t = typename trackParam_t::params_t; using covMat_t = typename trackParam_t::covMat_t; -namespace AliAlgAux +namespace utils { const double kAlmostZeroD = 1e-15; const float kAlmostZeroF = 1e-11; @@ -81,11 +81,11 @@ int findKeyIndex(int key, const int* arr, int n); // void printBits(size_t patt, int maxBits); -} // namespace AliAlgAux +} // namespace utils //_________________________________________________________________________________ template -inline void AliAlgAux::bringTo02Pi(F& phi) +inline void utils::bringTo02Pi(F& phi) { // bring phi to 0-2pi range if (phi < 0) @@ -96,7 +96,7 @@ inline void AliAlgAux::bringTo02Pi(F& phi) //_________________________________________________________________________________ template -inline void AliAlgAux::bringToPiPM(F& phi) +inline void utils::bringToPiPM(F& phi) { // bring phi to -pi:pi range if (phi > constants::math::PI) @@ -104,7 +104,7 @@ inline void AliAlgAux::bringToPiPM(F& phi) } //_________________________________________________________________________________ template -inline bool AliAlgAux::okForPhiMin(F phiMin, F phi) +inline bool utils::okForPhiMin(F phiMin, F phi) { // check if phi is above the phiMin, phi's must be in 0-2pi range F dphi = phi - phiMin; @@ -113,7 +113,7 @@ inline bool AliAlgAux::okForPhiMin(F phiMin, F phi) //_________________________________________________________________________________ template -inline bool AliAlgAux::okForPhiMax(F phiMax, F phi) +inline bool utils::okForPhiMax(F phiMax, F phi) { // check if phi is below the phiMax, phi's must be in 0-2pi range F dphi = phi - phiMax; @@ -122,7 +122,7 @@ inline bool AliAlgAux::okForPhiMax(F phiMax, F phi) //_________________________________________________________________________________ template -inline F AliAlgAux::meanPhiSmall(F phi0, F phi1) +inline F utils::meanPhiSmall(F phi0, F phi1) { // return mean phi, assume phis in 0:2pi F phi; @@ -141,7 +141,7 @@ inline F AliAlgAux::meanPhiSmall(F phi0, F phi1) //_________________________________________________________________________________ template -inline F AliAlgAux::deltaPhiSmall(F phi0, F phi1) +inline F utils::deltaPhiSmall(F phi0, F phi1) { // return delta phi, assume phis in 0:2pi F del; @@ -157,7 +157,7 @@ inline F AliAlgAux::deltaPhiSmall(F phi0, F phi1) } //_________________________________________________________________________________ -inline int AliAlgAux::numberOfBitsSet(uint32_t x) +inline int utils::numberOfBitsSet(uint32_t x) { // count number of non-0 bits in 32bit word x = x - ((x >> 1) & 0x55555555); @@ -166,7 +166,7 @@ inline int AliAlgAux::numberOfBitsSet(uint32_t x) } //_________________________________________________________________________________ -inline double AliAlgAux::sector2Alpha(int sect) +inline double utils::sector2Alpha(int sect) { // get barrel sector alpha in -pi:pi format if (sect > 8) @@ -175,7 +175,7 @@ inline double AliAlgAux::sector2Alpha(int sect) } //_________________________________________________________________________________ -inline int AliAlgAux::phi2Sector(double phi) +inline int utils::phi2Sector(double phi) { // get barrel sector from phi in -pi:pi format int sect = math_utils::nintd((phi * constants::math::Rad2Deg - 10) / 20.); @@ -183,6 +183,33 @@ inline int AliAlgAux::phi2Sector(double phi) sect += 18; return sect; } + +//_______________________________________________________________ +inline void utils::printBits(size_t patt, int maxBits) +{ + // print maxBits of the pattern + maxBits = std::min(64, maxBits); + for (int i = 0; i < maxBits; i++) + printf("%c", ((patt >> i) & 0x1) ? '+' : '-'); +} + +//__________________________________________ +inline int utils::findKeyIndex(int key, const int* arr, int n) +{ + // finds index of key in the array + int imn = 0, imx = n - 1; + while (imx >= imn) { + int mid = (imx + imn) >> 1; + if (arr[mid] == key) + return mid; + if (arr[mid] < key) + imn = mid + 1; + else + imx = mid - 1; + } + return -1; +} + } // namespace align } // namespace o2 #endif diff --git a/Detectors/Align/src/AliAlgAux.cxx b/Detectors/Align/src/AliAlgAux.cxx deleted file mode 100644 index 523d6da76662f..0000000000000 --- a/Detectors/Align/src/AliAlgAux.cxx +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// @file AliAlgAux.h -/// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch -/// @since 2021-02-01 -/// @brief Collection of auxillary methods - -#include "Align/AliAlgAux.h" -// #include "AliCDBId.h" -// #include "AliCDBManager.h" -#include "Framework/Logger.h" -#include -#include -#include -#include -#include -#include - -namespace o2 -{ -namespace align -{ - -//_______________________________________________________________ -void AliAlgAux::printBits(size_t patt, int maxBits) -{ - // print maxBits of the pattern - maxBits = std::min(64, maxBits); - for (int i = 0; i < maxBits; i++) - printf("%c", ((patt >> i) & 0x1) ? '+' : '-'); -} - -//__________________________________________ -int AliAlgAux::findKeyIndex(int key, const int* arr, int n) -{ - // finds index of key in the array - int imn = 0, imx = n - 1; - while (imx >= imn) { - int mid = (imx + imn) >> 1; - if (arr[mid] == key) - return mid; - if (arr[mid] < key) - imn = mid + 1; - else - imx = mid - 1; - } - return -1; -} - -} // namespace align -} // namespace o2 diff --git a/Detectors/Align/src/AlignLinkDef.h b/Detectors/Align/src/AlignLinkDef.h index 010f54d85087b..4944006dbab1b 100644 --- a/Detectors/Align/src/AlignLinkDef.h +++ b/Detectors/Align/src/AlignLinkDef.h @@ -4,28 +4,28 @@ #pragma link off all classes; #pragma link off all functions; -#pragma link C++ class o2::align::AliAlgDet + ; -//#pragma link C++ class o2::align::AliAlgDetITS + ; -//#pragma link C++ class o2::align::AliAlgDetTOF + ; -//#pragma link C++ class o2::align::AliAlgDetTPC + ; -//#pragma link C++ class o2::align::AliAlgDetTRD + ; -//#pragma link C++ class o2::align::AliAlgDetHMPID + ; -#pragma link C++ class o2::align::AliAlgMPRecord + ; -#pragma link C++ class o2::align::AliAlgPoint + ; -#pragma link C++ class o2::align::AliAlgSens + ; -//#pragma link C++ class o2::align::AliAlgSensITS + ; -//#pragma link C++ class o2::align::AliAlgSensTOF + ; -//#pragma link C++ class o2::align::AliAlgSensTPC + ; -//#pragma link C++ class o2::align::AliAlgSensTRD + ; -//#pragma link C++ class o2::align::AliAlgSensHMPID + ; -#pragma link C++ class o2::align::AliAlgSteer + ; -#pragma link C++ class o2::align::AliAlgTrack + ; -#pragma link C++ class o2::align::AliAlgVol + ; -#pragma link C++ class o2::align::AliAlgVtx + ; -#pragma link C++ class o2::align::AliAlgRes + ; -#pragma link C++ class o2::align::AliAlgResFast + ; -#pragma link C++ class o2::align::AliAlgConstraint + ; -#pragma link C++ class o2::align::AliAlgDOFStat + ; -#pragma link C++ class o2::align::AliAlgAux; +#pragma link C++ class o2::align::AlignableDetector + ; +//#pragma link C++ class o2::align::AlignableDetectorITS + ; +//#pragma link C++ class o2::align::AlignableDetectorTOF + ; +//#pragma link C++ class o2::align::AlignableDetectorTPC + ; +//#pragma link C++ class o2::align::AlignableDetectorTRD + ; +//#pragma link C++ class o2::align::AlignableDetectorHMPID + ; +#pragma link C++ class o2::align::Millepede2Record + ; +#pragma link C++ class o2::align::AlignmentPoint + ; +#pragma link C++ class o2::align::AlignableSensor + ; +//#pragma link C++ class o2::align::AlignableSensorITS + ; +//#pragma link C++ class o2::align::AlignableSensorTOF + ; +//#pragma link C++ class o2::align::AlignableSensorTPC + ; +//#pragma link C++ class o2::align::AlignableSensorTRD + ; +//#pragma link C++ class o2::align::AlignableSensorHMPID + ; +#pragma link C++ class o2::align::Controller + ; +#pragma link C++ class o2::align::AlignmentTrack + ; +#pragma link C++ class o2::align::AlignableVolume + ; +#pragma link C++ class o2::align::EventVertex + ; +#pragma link C++ class o2::align::ResidualsController + ; +#pragma link C++ class o2::align::ResidualsControllerFast + ; +#pragma link C++ class o2::align::GeometricalConstraint + ; +#pragma link C++ class o2::align::DOFStatistics + ; +#pragma link C++ class o2::align::utils; #endif diff --git a/Detectors/Align/src/AliAlgDet.cxx b/Detectors/Align/src/AlignableDetector.cxx similarity index 82% rename from Detectors/Align/src/AliAlgDet.cxx rename to Detectors/Align/src/AlignableDetector.cxx index 7531c81751305..1b055acfff555 100644 --- a/Detectors/Align/src/AliAlgDet.cxx +++ b/Detectors/Align/src/AlignableDetector.cxx @@ -8,18 +8,17 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgDet.h +/// @file AlignableDetector.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Base class for detector: wrapper for set of volumes -#include "Align/AliAlgDet.h" -#include "Align/AliAlgSens.h" -#include "Align/AliAlgDet.h" -#include "Align/AliAlgSteer.h" -#include "Align/AliAlgTrack.h" -#include "Align/AliAlgDOFStat.h" -#include "Align/AliAlgConstraint.h" +#include "Align/AlignableDetector.h" +#include "Align/AlignableSensor.h" +#include "Align/Controller.h" +#include "Align/AlignmentTrack.h" +#include "Align/DOFStatistics.h" +#include "Align/GeometricalConstraint.h" #include "Framework/Logger.h" //#include "AliGeomManager.h" //#include "AliCDBManager.h" @@ -35,9 +34,9 @@ #include #include -ClassImp(o2::align::AliAlgDet); +ClassImp(o2::align::AlignableDetector); -using namespace o2::align::AliAlgAux; +using namespace o2::align::utils; namespace o2 { @@ -45,7 +44,7 @@ namespace align { //____________________________________________ -AliAlgDet::AliAlgDet() +AlignableDetector::AlignableDetector() : mNDOFs(0), mVolIDMin(-1), mVolIDMax(-1), mNSensors(0), mSID2VolID(0), mNProcPoints(0) // , @@ -70,7 +69,7 @@ AliAlgDet::AliAlgDet() mAlgSteer(0) { // def c-tor - SetUniqueID(AliAlgSteer::kUndefined); // derived detectors must override this + SetUniqueID(Controller::kUndefined); // derived detectors must override this SetUniqueID(6); mAddError[0] = mAddError[1] = 0; // @@ -84,7 +83,7 @@ AliAlgDet::AliAlgDet() } //____________________________________________ -AliAlgDet::~AliAlgDet() +AlignableDetector::~AlignableDetector() { // d-tor mSensors.Clear(); // sensors are also attached as volumes, don't delete them here @@ -94,7 +93,7 @@ AliAlgDet::~AliAlgDet() //FIXME(milettri): needs AliESDtrack ////____________________________________________ -//int AliAlgDet::ProcessPoints(const AliESDtrack* esdTr, AliAlgTrack* algTrack, bool inv) +//int AlignableDetector::ProcessPoints(const AliESDtrack* esdTr, AlignmentTrack* algTrack, bool inv) //{ // // Extract the points corresponding to this detector, recalibrate/realign them to the // // level of the "starting point" for the alignment/calibration session. @@ -106,7 +105,7 @@ AliAlgDet::~AliAlgDet() // // // int np(trP->getNPoints()); // int npSel(0); -// AliAlgPoint* apnt(0); +// AlignmentPoint* apnt(0); // for (int ip = 0; ip < np; ip++) { // int vid = trP->GetVolumeID()[ip]; // if (!sensorOfDetector(vid)) @@ -125,7 +124,7 @@ AliAlgDet::~AliAlgDet() //} //_________________________________________________________ -void AliAlgDet::acknowledgeNewRun(int run) +void AlignableDetector::acknowledgeNewRun(int run) { // update parameters needed to process this run @@ -134,7 +133,7 @@ void AliAlgDet::acknowledgeNewRun(int run) } //_________________________________________________________ -void AliAlgDet::updateL2GRecoMatrices() +void AlignableDetector::updateL2GRecoMatrices() { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs OCDB @@ -146,7 +145,7 @@ void AliAlgDet::updateL2GRecoMatrices() // // // int nvol = getNVolumes(); // for (int iv = 0; iv < nvol; iv++) { - // AliAlgVol* vol = getVolume(iv); + // AlignableVolume* vol = getVolume(iv); // // call init for root level volumes, they will take care of their children // if (!vol->getParent()) // vol->updateL2GRecoMatrices(algArr, 0); @@ -155,7 +154,7 @@ void AliAlgDet::updateL2GRecoMatrices() } //_________________________________________________________ -void AliAlgDet::applyAlignmentFromMPSol() +void AlignableDetector::applyAlignmentFromMPSol() { // apply alignment from millepede solution array to reference alignment level LOG(INFO) << "Applying alignment from Millepede solution"; @@ -164,7 +163,7 @@ void AliAlgDet::applyAlignmentFromMPSol() } //_________________________________________________________ -void AliAlgDet::cacheReferenceOCDB() +void AlignableDetector::cacheReferenceOCDB() { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs OCDB @@ -176,7 +175,7 @@ void AliAlgDet::cacheReferenceOCDB() // TObjArray* arr = (TObjArray*)ent->GetObject(); // for (int i = arr->GetEntriesFast(); i--;) { // const AliAlignObjParams* par = (const AliAlignObjParams*)arr->At(i); - // AliAlgVol* vol = getVolume(par->GetSymName()); + // AlignableVolume* vol = getVolume(par->GetSymName()); // if (!vol) { // AliErrorF("Volume %s not found", par->GetSymName()); // continue; @@ -188,23 +187,23 @@ void AliAlgDet::cacheReferenceOCDB() } //_________________________________________________________ -AliAlgPoint* AliAlgDet::getPointFromPool() +AlignmentPoint* AlignableDetector::getPointFromPool() { // fetch or create new free point from the pool. - // detector may override this method to create its own points derived from AliAlgPoint + // detector may override this method to create its own points derived from AlignmentPoint // if (mPoolFreePointID >= mPoolNPoints) { // expand pool - mPointsPool.AddAtAndExpand(new AliAlgPoint(), mPoolNPoints++); + mPointsPool.AddAtAndExpand(new AlignmentPoint(), mPoolNPoints++); } // - AliAlgPoint* pnt = (AliAlgPoint*)mPointsPool.UncheckedAt(mPoolFreePointID++); + AlignmentPoint* pnt = (AlignmentPoint*)mPointsPool.UncheckedAt(mPoolFreePointID++); pnt->Clear(); return pnt; // } //_________________________________________________________ -void AliAlgDet::resetPool() +void AlignableDetector::resetPool() { // declare pool free mPoolFreePointID = 0; @@ -212,14 +211,14 @@ void AliAlgDet::resetPool() } //_________________________________________________________ -void AliAlgDet::defineVolumes() +void AlignableDetector::defineVolumes() { // dummy method LOG(ERROR) << "This method must be implemented by specific detector"; } //_________________________________________________________ -void AliAlgDet::addVolume(AliAlgVol* vol) +void AlignableDetector::addVolume(AlignableVolume* vol) { // add volume if (getVolume(vol->getSymName())) { @@ -228,8 +227,8 @@ void AliAlgDet::addVolume(AliAlgVol* vol) mVolumes.AddLast(vol); if (vol->isSensor()) { mSensors.AddLast(vol); - ((AliAlgSens*)vol)->setDetector(this); - int vid = ((AliAlgSens*)vol)->getVolID(); + ((AlignableSensor*)vol)->setDetector(this); + int vid = ((AlignableSensor*)vol)->getVolID(); if (mVolIDMin < 0 || vid < mVolIDMin) mVolIDMin = vid; if (mVolIDMax < 0 || vid > mVolIDMax) @@ -239,15 +238,15 @@ void AliAlgDet::addVolume(AliAlgVol* vol) } //_________________________________________________________ -void AliAlgDet::defineMatrices() +void AlignableDetector::defineMatrices() { // define transformation matrices. Detectors may override this method // TGeoHMatrix mtmp; // TIter next(&mVolumes); - AliAlgVol* vol(0); - while ((vol = (AliAlgVol*)next())) { + AlignableVolume* vol(0); + while ((vol = (AlignableVolume*)next())) { // modified global-local matrix vol->prepareMatrixL2G(); // ideal global-local matrix @@ -258,18 +257,18 @@ void AliAlgDet::defineMatrices() // Attention: for sensor it is a real tracking matrix extracted from // the geometry but for container alignable volumes the tracking frame // is used for as the reference for the alignment parameters only, - // see its definition in the AliAlgVol::PrepateMatrixT2L + // see its definition in the AlignableVolume::PrepateMatrixT2L next.Reset(); - while ((vol = (AliAlgVol*)next())) { + while ((vol = (AlignableVolume*)next())) { vol->prepareMatrixT2L(); if (vol->isSensor()) - ((AliAlgSens*)vol)->prepareMatrixClAlg(); // alignment matrix + ((AlignableSensor*)vol)->prepareMatrixClAlg(); // alignment matrix } // } //_________________________________________________________ -void AliAlgDet::sortSensors() +void AlignableDetector::sortSensors() { // build local tables for internal numbering mNSensors = mSensors.GetEntriesFast(); @@ -287,7 +286,7 @@ void AliAlgDet::sortSensors() } //_________________________________________________________ -int AliAlgDet::initGeom() +int AlignableDetector::initGeom() { // define hiearchy, initialize matrices, return number of global parameters if (getInitGeomDone()) @@ -301,7 +300,7 @@ int AliAlgDet::initGeom() int nvol = getNVolumes(); mNDOFs = 0; for (int iv = 0; iv < nvol; iv++) { - AliAlgVol* vol = getVolume(iv); + AlignableVolume* vol = getVolume(iv); mNDOFs += vol->getNDOFs(); } // @@ -311,7 +310,7 @@ int AliAlgDet::initGeom() } //_________________________________________________________ -int AliAlgDet::assignDOFs() +int AlignableDetector::assignDOFs() { // assign DOFs IDs, parameters // @@ -332,7 +331,7 @@ int AliAlgDet::assignDOFs() // int nvol = getNVolumes(); for (int iv = 0; iv < nvol; iv++) { - AliAlgVol* vol = getVolume(iv); + AlignableVolume* vol = getVolume(iv); // call init for root level volumes, they will take care of their children if (!vol->getParent()) vol->assignDOFs(gloCount, pars, errs, labs); @@ -343,7 +342,7 @@ int AliAlgDet::assignDOFs() } //_________________________________________________________ -void AliAlgDet::initDOFs() +void AlignableDetector::initDOFs() { // initialize free parameters if (getInitDOFsDone()) @@ -365,7 +364,7 @@ void AliAlgDet::initDOFs() } //_________________________________________________________ -int AliAlgDet::volID2SID(int vid) const +int AlignableDetector::volID2SID(int vid) const { // find SID corresponding to VolID int mn(0), mx(mNSensors - 1); @@ -382,7 +381,7 @@ int AliAlgDet::volID2SID(int vid) const } //____________________________________________ -void AliAlgDet::Print(const Option_t* opt) const +void AlignableDetector::Print(const Option_t* opt) const { // print info TString opts = opt; @@ -418,7 +417,7 @@ void AliAlgDet::Print(const Option_t* opt) const } //____________________________________________ -void AliAlgDet::setDetID(uint32_t tp) +void AlignableDetector::setDetID(uint32_t tp) { o2::detectors::DetID detID(tp); SetUniqueID(detID); @@ -426,7 +425,7 @@ void AliAlgDet::setDetID(uint32_t tp) } //____________________________________________ -void AliAlgDet::setAddError(double sigy, double sigz) +void AlignableDetector::setAddError(double sigy, double sigz) { // add syst error to all sensors LOG(INFO) << "Adding sys.error " << std::fixed << std::setprecision(4) << sigy << " " << sigz << " to all sensors"; @@ -438,7 +437,7 @@ void AliAlgDet::setAddError(double sigy, double sigz) } //____________________________________________ -void AliAlgDet::setUseErrorParam(int v) +void AlignableDetector::setUseErrorParam(int v) { // set type of points error parameterization LOG(FATAL) << "UpdatePointByTrackInfo is not implemented for this detector"; @@ -446,14 +445,14 @@ void AliAlgDet::setUseErrorParam(int v) } //____________________________________________ -void AliAlgDet::updatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) const +void AlignableDetector::updatePointByTrackInfo(AlignmentPoint* pnt, const trackParam_t* t) const { // update point using specific error parameterization LOG(FATAL) << "If needed, this method has to be implemented for specific detector"; } //____________________________________________ -void AliAlgDet::setObligatory(int tp, bool v) +void AlignableDetector::setObligatory(int tp, bool v) { // mark detector presence obligatory in the track mObligatory[tp] = v; @@ -461,7 +460,7 @@ void AliAlgDet::setObligatory(int tp, bool v) } //______________________________________________________ -void AliAlgDet::writePedeInfo(FILE* parOut, const Option_t* opt) const +void AlignableDetector::writePedeInfo(FILE* parOut, const Option_t* opt) const { // contribute to params and constraints template files for PEDE fprintf(parOut, "\n!!\t\tDetector:\t%s\tNDOFs: %d\n", GetName(), getNDOFs()); @@ -469,7 +468,7 @@ void AliAlgDet::writePedeInfo(FILE* parOut, const Option_t* opt) const // parameters int nvol = getNVolumes(); for (int iv = 0; iv < nvol; iv++) { // call for root level volumes, they will take care of their children - AliAlgVol* vol = getVolume(iv); + AlignableVolume* vol = getVolume(iv); if (!vol->getParent()) vol->writePedeInfo(parOut, opt); } @@ -477,7 +476,7 @@ void AliAlgDet::writePedeInfo(FILE* parOut, const Option_t* opt) const } //______________________________________________________ -void AliAlgDet::writeCalibrationResults() const +void AlignableDetector::writeCalibrationResults() const { // store calibration results writeAlignmentResults(); @@ -486,7 +485,7 @@ void AliAlgDet::writeCalibrationResults() const } //______________________________________________________ -void AliAlgDet::writeAlignmentResults() const +void AlignableDetector::writeAlignmentResults() const { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(lettrich): needs OCDB @@ -495,7 +494,7 @@ void AliAlgDet::writeAlignmentResults() const // // // int nvol = getNVolumes(); // for (int iv = 0; iv < nvol; iv++) { - // AliAlgVol* vol = getVolume(iv); + // AlignableVolume* vol = getVolume(iv); // // call only for top level objects, they will take care of children // if (!vol->getParent()) // vol->createAlignmentObjects(arr); @@ -513,11 +512,11 @@ void AliAlgDet::writeAlignmentResults() const } //______________________________________________________ -bool AliAlgDet::ownsDOFID(int id) const +bool AlignableDetector::ownsDOFID(int id) const { // check if DOF ID belongs to this detector for (int iv = getNVolumes(); iv--;) { - AliAlgVol* vol = getVolume(iv); // check only top level volumes + AlignableVolume* vol = getVolume(iv); // check only top level volumes if (!vol->getParent() && vol->ownsDOFID(id)) return true; } @@ -529,11 +528,11 @@ bool AliAlgDet::ownsDOFID(int id) const } //______________________________________________________ -AliAlgVol* AliAlgDet::getVolOfDOFID(int id) const +AlignableVolume* AlignableDetector::getVolOfDOFID(int id) const { // gets volume owning this DOF ID for (int iv = getNVolumes(); iv--;) { - AliAlgVol* vol = getVolume(iv); + AlignableVolume* vol = getVolume(iv); if (vol->getParent()) continue; // check only top level volumes if ((vol = vol->getVolOfDOFID(id))) @@ -543,15 +542,15 @@ AliAlgVol* AliAlgDet::getVolOfDOFID(int id) const } //______________________________________________________ -void AliAlgDet::terminate() +void AlignableDetector::terminate() { // called at the end of processing // if (isDisabled()) return; int nvol = getNVolumes(); mNProcPoints = 0; - AliAlgDOFStat* st = mAlgSteer->GetDOFStat(); + DOFStatistics* st = mAlgSteer->GetDOFStat(); for (int iv = 0; iv < nvol; iv++) { - AliAlgVol* vol = getVolume(iv); + AlignableVolume* vol = getVolume(iv); // call init for root level volumes, they will take care of their children if (!vol->getParent()) mNProcPoints += vol->finalizeStat(st); @@ -560,23 +559,23 @@ void AliAlgDet::terminate() } //________________________________________ -void AliAlgDet::addAutoConstraints() const +void AlignableDetector::addAutoConstraints() const { // adds automatic constraints int nvol = getNVolumes(); for (int iv = 0; iv < nvol; iv++) { // call for root level volumes, they will take care of their children - AliAlgVol* vol = getVolume(iv); + AlignableVolume* vol = getVolume(iv); if (!vol->getParent()) vol->addAutoConstraints((TObjArray*)mAlgSteer->getConstraints()); } } //________________________________________ -void AliAlgDet::fixNonSensors() +void AlignableDetector::fixNonSensors() { // fix all non-sensor volumes for (int i = getNVolumes(); i--;) { - AliAlgVol* vol = getVolume(i); + AlignableVolume* vol = getVolume(i); if (vol->isSensor()) continue; vol->setFreeDOFPattern(0); @@ -585,7 +584,7 @@ void AliAlgDet::fixNonSensors() } //________________________________________ -int AliAlgDet::selectVolumes(TObjArray* arr, int lev, const char* match) +int AlignableDetector::selectVolumes(TObjArray* arr, int lev, const char* match) { // select volumes matching to pattern and/or hierarchy level // @@ -594,7 +593,7 @@ int AliAlgDet::selectVolumes(TObjArray* arr, int lev, const char* match) int nadd = 0; TString mts = match, syms; for (int i = getNVolumes(); i--;) { - AliAlgVol* vol = getVolume(i); + AlignableVolume* vol = getVolume(i); if (lev >= 0 && vol->countParents() != lev) continue; // wrong level if (!mts.IsNull() && !(syms = vol->getSymName()).Contains(mts)) @@ -607,14 +606,14 @@ int AliAlgDet::selectVolumes(TObjArray* arr, int lev, const char* match) } //________________________________________ -void AliAlgDet::setFreeDOFPattern(uint32_t pat, int lev, const char* match) +void AlignableDetector::setFreeDOFPattern(uint32_t pat, int lev, const char* match) { // set free DOFs to volumes matching either to hierarchy level or // whose name contains match // TString mts = match, syms; for (int i = getNVolumes(); i--;) { - AliAlgVol* vol = getVolume(i); + AlignableVolume* vol = getVolume(i); if (lev >= 0 && vol->countParents() != lev) continue; // wrong level if (!mts.IsNull() && !(syms = vol->getSymName()).Contains(mts)) @@ -625,14 +624,14 @@ void AliAlgDet::setFreeDOFPattern(uint32_t pat, int lev, const char* match) } //________________________________________ -void AliAlgDet::setDOFCondition(int dof, float condErr, int lev, const char* match) +void AlignableDetector::setDOFCondition(int dof, float condErr, int lev, const char* match) { // set condition for DOF of volumes matching either to hierarchy level or // whose name contains match // TString mts = match, syms; for (int i = getNVolumes(); i--;) { - AliAlgVol* vol = getVolume(i); + AlignableVolume* vol = getVolume(i); if (lev >= 0 && vol->countParents() != lev) continue; // wrong level if (!mts.IsNull() && !(syms = vol->getSymName()).Contains(mts)) @@ -648,7 +647,7 @@ void AliAlgDet::setDOFCondition(int dof, float condErr, int lev, const char* mat } //________________________________________ -void AliAlgDet::constrainOrphans(const double* sigma, const char* match) +void AlignableDetector::constrainOrphans(const double* sigma, const char* match) { // additional constraint on volumes w/o parents (optionally containing "match" in symname) // sigma<0 : dof is not contrained @@ -656,8 +655,8 @@ void AliAlgDet::constrainOrphans(const double* sigma, const char* match) // sigma>0 : dof constrained by gaussian constraint // TString mts = match, syms; - AliAlgConstraint* constr = new AliAlgConstraint(); - for (int i = 0; i < AliAlgVol::kNDOFGeom; i++) { + GeometricalConstraint* constr = new GeometricalConstraint(); + for (int i = 0; i < AlignableVolume::kNDOFGeom; i++) { if (sigma[i] >= 0) constr->constrainDOF(i); else @@ -665,7 +664,7 @@ void AliAlgDet::constrainOrphans(const double* sigma, const char* match) constr->setSigma(i, sigma[i]); } for (int i = getNVolumes(); i--;) { - AliAlgVol* vol = getVolume(i); + AlignableVolume* vol = getVolume(i); if (vol->getParent()) continue; // wrong level if (!mts.IsNull() && !(syms = vol->getSymName()).Contains(mts)) @@ -682,7 +681,7 @@ void AliAlgDet::constrainOrphans(const double* sigma, const char* match) } //________________________________________ -void AliAlgDet::setFreeDOF(int dof) +void AlignableDetector::setFreeDOF(int dof) { // set detector free dof if (dof >= kNMaxKalibDOF) { @@ -693,7 +692,7 @@ void AliAlgDet::setFreeDOF(int dof) } //________________________________________ -void AliAlgDet::fixDOF(int dof) +void AlignableDetector::fixDOF(int dof) { // fix detector dof if (dof >= kNMaxKalibDOF) { @@ -704,14 +703,14 @@ void AliAlgDet::fixDOF(int dof) } //__________________________________________________________________ -bool AliAlgDet::isCondDOF(int i) const +bool AlignableDetector::isCondDOF(int i) const { // is DOF free and conditioned? return (!isZeroAbs(getParVal(i)) || !isZeroAbs(getParErr(i))); } //__________________________________________________________________ -void AliAlgDet::calcFree(bool condFix) +void AlignableDetector::calcFree(bool condFix) { // calculate free calib dofs. If condFix==true, condition parameter a la pede, i.e. error < 0 mNCalibDOFFree = 0; @@ -727,7 +726,7 @@ void AliAlgDet::calcFree(bool condFix) } //______________________________________________________ -void AliAlgDet::fillDOFStat(AliAlgDOFStat* st) const +void AlignableDetector::fillDOFStat(DOFStatistics* st) const { // fill statistics info hist if (!st) @@ -743,7 +742,7 @@ void AliAlgDet::fillDOFStat(AliAlgDOFStat* st) const } //______________________________________________________ -void AliAlgDet::writeSensorPositions(const char* outFName) +void AlignableDetector::writeSensorPositions(const char* outFName) { // create tree with sensors ideal, ref and reco positions int ns = getNSensors(); @@ -764,7 +763,7 @@ void AliAlgDet::writeSensorPositions(const char* outFName) tr->Branch("pRc", &spos.pRc, "pRc[3]/D"); // for (int isn = 0; isn < ns; isn++) { - AliAlgSens* sens = getSensor(isn); + AlignableSensor* sens = getSensor(isn); spos.volID = sens->getVolID(); sens->getMatrixL2GIdeal().LocalToMaster(loc, spos.pId); sens->getMatrixL2G().LocalToMaster(loc, spos.pRf); diff --git a/Detectors/Align/src/AliAlgDetHMPID.cxx b/Detectors/Align/src/AlignableDetectorHMPID.cxx similarity index 72% rename from Detectors/Align/src/AliAlgDetHMPID.cxx rename to Detectors/Align/src/AlignableDetectorHMPID.cxx index e4c9a44cd2e08..74c7b69c6fbc9 100644 --- a/Detectors/Align/src/AliAlgDetHMPID.cxx +++ b/Detectors/Align/src/AlignableDetectorHMPID.cxx @@ -8,22 +8,22 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgDetHMPID.h +/// @file AlignableDetectorHMPID.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief HMPID detector wrapper -#include "Align/AliAlgDetHMPID.h" +#include "Align/AlignableDetectorHMPID.h" //#include "AliHMPIDParam.h" -#include "Align/AliAlgVol.h" -#include "Align/AliAlgSensHMPID.h" -#include "Align/AliAlgSteer.h" +#include "Align/AlignableVolume.h" +#include "Align/AlignableSensorHMPID.h" +#include "Align/Controller.h" //#include "AliGeomManager.h" //#include "AliESDtrack.h" #include "Framework/Logger.h" #include -ClassImp(o2::align::AliAlgDetHMPID); +ClassImp(o2::align::AlignableDetectorHMPID); namespace o2 { @@ -31,21 +31,21 @@ namespace align { //____________________________________________ -AliAlgDetHMPID::AliAlgDetHMPID(const char* title) +AlignableDetectorHMPID::AlignableDetectorHMPID(const char* title) { // default c-tor - SetNameTitle(AliAlgSteer::getDetNameByDetID(AliAlgSteer::kHMPID), title); - setDetID(AliAlgSteer::kHMPID); + SetNameTitle(Controller::getDetNameByDetID(Controller::kHMPID), title); + setDetID(Controller::kHMPID); } //____________________________________________ -AliAlgDetHMPID::~AliAlgDetHMPID() +AlignableDetectorHMPID::~AlignableDetectorHMPID() { // d-tor } //____________________________________________ -void AliAlgDetHMPID::defineVolumes() +void AlignableDetectorHMPID::defineVolumes() { // define HMPID volumes // @@ -59,14 +59,14 @@ void AliAlgDetHMPID::defineVolumes() } uint16_t vid = AliGeomManager::LayerToVolUID(idHMPID, iCh); int iid = labDet + (1 + iCh) * 10000; - AliAlgSensHMPID* sens = new AliAlgSensHMPID(symname, vid, iid); + AlignableSensorHMPID* sens = new AlignableSensorHMPID(symname, vid, iid); addVolume(sens); } //iCh loop // } //____________________________________________ -bool AliAlgDetHMPID::AcceptTrack(const AliESDtrack* trc, int trtype) const +bool AlignableDetectorHMPID::AcceptTrack(const AliESDtrack* trc, int trtype) const { // test if detector had seed this track if (!CheckFlags(trc, trtype)) diff --git a/Detectors/Align/src/AliAlgDetITS.cxx b/Detectors/Align/src/AlignableDetectorITS.cxx similarity index 77% rename from Detectors/Align/src/AliAlgDetITS.cxx rename to Detectors/Align/src/AlignableDetectorITS.cxx index 81aac175fe845..6691af387b4cc 100644 --- a/Detectors/Align/src/AliAlgDetITS.cxx +++ b/Detectors/Align/src/AlignableDetectorITS.cxx @@ -8,15 +8,15 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgDetITS.h +/// @file AlignableDetectorITS.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief ITS detector wrapper -#include "Align/AliAlgDetITS.h" -#include "Align/AliAlgVol.h" -#include "Align/AliAlgSensITS.h" -#include "Align/AliAlgSteer.h" +#include "Align/AlignableDetectorITS.h" +#include "Align/AlignableVolume.h" +#include "Align/AlignableSensorITS.h" +#include "Align/Controller.h" //#include "AliITSgeomTGeo.h" //#include "AliGeomManager.h" //#include "AliESDtrack.h" @@ -25,52 +25,52 @@ #include using namespace TMath; -using namespace o2::align::AliAlgAux; +using namespace o2::align::utils; -ClassImp(o2::align::AliAlgDetITS); +ClassImp(o2::align::AlignableDetectorITS); namespace o2 { namespace align { -const char* AliAlgDetITS::fgkHitsSel[AliAlgDetITS::kNSPDSelTypes] = +const char* AlignableDetectorITS::fgkHitsSel[AlignableDetectorITS::kNSPDSelTypes] = {"SPDNoSel", "SPDBoth", "SPDAny", "SPD0", "SPD1"}; //____________________________________________ -AliAlgDetITS::AliAlgDetITS(const char* title) +AlignableDetectorITS::AlignableDetectorITS(const char* title) { // default c-tor - SetNameTitle(AliAlgSteer::getDetNameByDetID(AliAlgSteer::kITS), title); - setDetID(AliAlgSteer::kITS); + SetNameTitle(Controller::getDetNameByDetID(Controller::kITS), title); + setDetID(Controller::kITS); setUseErrorParam(); SetITSSelPatternColl(); SetITSSelPatternCosm(); } //____________________________________________ -AliAlgDetITS::~AliAlgDetITS() +AlignableDetectorITS::~AlignableDetectorITS() { // d-tor } //____________________________________________ -void AliAlgDetITS::defineVolumes() +void AlignableDetectorITS::defineVolumes() { // define ITS volumes // const int kNSPDSect = 10; - AliAlgVol *volITS = 0, *hstave = 0, *ladd = 0; - AliAlgSensITS* sens = 0; + AlignableVolume *volITS = 0, *hstave = 0, *ladd = 0; + AlignableSensorITS* sens = 0; // int labDet = getDetLabel(); - addVolume(volITS = new AliAlgVol("ITS", labDet)); + addVolume(volITS = new AlignableVolume("ITS", labDet)); // // SPD - AliAlgVol* sect[kNSPDSect] = {0}; + AlignableVolume* sect[kNSPDSect] = {0}; for (int isc = 0; isc < kNSPDSect; isc++) { // sectors int iid = labDet + (10 + isc) * 10000; - addVolume(sect[isc] = new AliAlgVol(Form("ITS/SPD0/Sector%d", isc), iid)); + addVolume(sect[isc] = new AlignableVolume(Form("ITS/SPD0/Sector%d", isc), iid)); sect[isc]->setParent(volITS); } for (int ilr = 0; ilr <= 1; ilr++) { // SPD layers @@ -82,17 +82,17 @@ void AliAlgDetITS::defineVolumes() for (int ihst = 0; ihst < 2; ihst++) { // halfstave int iid = labDet + (1 + ilr) * 10000 + (1 + staveCnt) * 100; staveCnt++; - addVolume(hstave = new AliAlgVol(Form("ITS/SPD%d/Sector%d/Stave%d/HalfStave%d", - ilr, isc, ist, ihst), - iid)); + addVolume(hstave = new AlignableVolume(Form("ITS/SPD%d/Sector%d/Stave%d/HalfStave%d", + ilr, isc, ist, ihst), + iid)); hstave->setParent(sect[isc]); hstave->setInternalID(iid); for (int isn = 0; isn < 2; isn++) { // "ladder" (sensor) int iids = iid + (1 + isn); addVolume(sens = - new AliAlgSensITS(Form("ITS/SPD%d/Sector%d/Stave%d/HalfStave%d/Ladder%d", - ilr, isc, ist, ihst, isn + ihst * 2), - AliGeomManager::LayerToVolUID(ilr + 1, cntVolID++), iids)); + new AlignableSensorITS(Form("ITS/SPD%d/Sector%d/Stave%d/HalfStave%d/Ladder%d", + ilr, isc, ist, ihst, isn + ihst * 2), + AliGeomManager::LayerToVolUID(ilr + 1, cntVolID++), iids)); sens->setParent(hstave); } } @@ -106,12 +106,12 @@ void AliAlgDetITS::defineVolumes() for (int ist = 0; ist < AliITSgeomTGeo::GetNLadders(ilr + 1); ist++) { // ladder int iid = labDet + (1 + ilr) * 10000 + (1 + staveCnt) * 100; staveCnt++; - addVolume(ladd = new AliAlgVol(Form("ITS/SDD%d/Ladder%d", ilr, ist), iid)); + addVolume(ladd = new AlignableVolume(Form("ITS/SDD%d/Ladder%d", ilr, ist), iid)); ladd->setParent(volITS); for (int isn = 0; isn < AliITSgeomTGeo::GetNDetectors(ilr + 1); isn++) { // sensor int iids = iid + (1 + isn); - addVolume(sens = new AliAlgSensITS(Form("ITS/SDD%d/Ladder%d/Sensor%d", ilr, ist, isn), - AliGeomManager::LayerToVolUID(ilr + 1, cntVolID++), iids)); + addVolume(sens = new AlignableSensorITS(Form("ITS/SDD%d/Ladder%d/Sensor%d", ilr, ist, isn), + AliGeomManager::LayerToVolUID(ilr + 1, cntVolID++), iids)); sens->setParent(ladd); } } // ladder @@ -123,12 +123,12 @@ void AliAlgDetITS::defineVolumes() for (int ist = 0; ist < AliITSgeomTGeo::GetNLadders(ilr + 1); ist++) { // ladder int iid = labDet + (1 + ilr) * 10000 + (1 + staveCnt) * 100; staveCnt++; - addVolume(ladd = new AliAlgVol(Form("ITS/SSD%d/Ladder%d", ilr, ist), iid)); + addVolume(ladd = new AlignableVolume(Form("ITS/SSD%d/Ladder%d", ilr, ist), iid)); ladd->setParent(volITS); for (int isn = 0; isn < AliITSgeomTGeo::GetNDetectors(ilr + 1); isn++) { // sensor int iids = iid + (1 + isn); - addVolume(sens = new AliAlgSensITS(Form("ITS/SSD%d/Ladder%d/Sensor%d", ilr, ist, isn), - AliGeomManager::LayerToVolUID(ilr + 1, cntVolID++), iids)); + addVolume(sens = new AlignableSensorITS(Form("ITS/SSD%d/Ladder%d/Sensor%d", ilr, ist, isn), + AliGeomManager::LayerToVolUID(ilr + 1, cntVolID++), iids)); sens->setParent(ladd); } } // ladder @@ -138,15 +138,15 @@ void AliAlgDetITS::defineVolumes() } //____________________________________________ -void AliAlgDetITS::Print(const Option_t* opt) const +void AlignableDetectorITS::Print(const Option_t* opt) const { - AliAlgDet::Print(opt); + AlignableDetector::Print(opt); printf("Sel.pattern Collisions: %7s | Cosmic: %7s\n", GetITSPattName(fITSPatt[kColl]), GetITSPattName(fITSPatt[kCosm])); } //____________________________________________ -bool AliAlgDetITS::AcceptTrack(const AliESDtrack* trc, int trtype) const +bool AlignableDetectorITS::AcceptTrack(const AliESDtrack* trc, int trtype) const { // test if detector had seed this track if (!CheckFlags(trc, trtype)) @@ -160,11 +160,11 @@ bool AliAlgDetITS::AcceptTrack(const AliESDtrack* trc, int trtype) const } //____________________________________________ -void AliAlgDetITS::SetAddErrorLr(int ilr, double sigY, double sigZ) +void AlignableDetectorITS::SetAddErrorLr(int ilr, double sigY, double sigZ) { // set syst. errors for specific layer for (int isn = getNSensors(); isn--;) { - AliAlgSensITS* sens = (AliAlgSensITS*)getSensor(isn); + AlignableSensorITS* sens = (AlignableSensorITS*)getSensor(isn); int vid = sens->getVolID(); int lrs = AliGeomManager::VolUIDToLayer(vid); if ((lrs - AliGeomManager::kSPD1) == ilr) @@ -173,11 +173,11 @@ void AliAlgDetITS::SetAddErrorLr(int ilr, double sigY, double sigZ) } //____________________________________________ -void AliAlgDetITS::SetSkipLr(int ilr) +void AlignableDetectorITS::SetSkipLr(int ilr) { // exclude sensor of the layer from alignment for (int isn = getNSensors(); isn--;) { - AliAlgSensITS* sens = (AliAlgSensITS*)getSensor(isn); + AlignableSensorITS* sens = (AlignableSensorITS*)getSensor(isn); int vid = sens->getVolID(); int lrs = AliGeomManager::VolUIDToLayer(vid); if ((lrs - AliGeomManager::kSPD1) == ilr) @@ -186,14 +186,14 @@ void AliAlgDetITS::SetSkipLr(int ilr) } //_________________________________________________ -void AliAlgDetITS::setUseErrorParam(int v) +void AlignableDetectorITS::setUseErrorParam(int v) { // set type of points error parameterization mUseErrorParam = v; } //_________________________________________________ -bool AliAlgDetITS::CheckHitPattern(const AliESDtrack* trc, int sel) +bool AlignableDetectorITS::CheckHitPattern(const AliESDtrack* trc, int sel) { // check if track hit pattern is ok switch (sel) { @@ -220,11 +220,11 @@ bool AliAlgDetITS::CheckHitPattern(const AliESDtrack* trc, int sel) } //_________________________________________________ -void AliAlgDetITS::UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const +void AlignableDetectorITS::UpdatePointByTrackInfo(AlignmentPoint* pnt, const AliExternalTrackParam* t) const { // update point using specific error parameterization // the track must be in the detector tracking frame - const AliAlgSens* sens = pnt->getSensor(); + const AlignableSensor* sens = pnt->getSensor(); int vid = sens->getVolID(); int lr = AliGeomManager::VolUIDToLayer(vid) - 1; double angPol = ATan(t->GetTgl()); @@ -238,7 +238,7 @@ void AliAlgDetITS::UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTra // } //-------------------------------------------------------------------------- -void AliAlgDetITS::GetErrorParamAngle(int layer, double anglePol, double angleAzi, double& erry, double& errz) const +void AlignableDetectorITS::GetErrorParamAngle(int layer, double anglePol, double angleAzi, double& erry, double& errz) const { // Modified version of AliITSClusterParam::GetErrorParamAngle // Calculate cluster position error (parametrization extracted from rp-hit diff --git a/Detectors/Align/src/AliAlgDetTOF.cxx b/Detectors/Align/src/AlignableDetectorTOF.cxx similarity index 68% rename from Detectors/Align/src/AliAlgDetTOF.cxx rename to Detectors/Align/src/AlignableDetectorTOF.cxx index 62afb404194f0..d8ef959cef71d 100644 --- a/Detectors/Align/src/AliAlgDetTOF.cxx +++ b/Detectors/Align/src/AlignableDetectorTOF.cxx @@ -8,21 +8,21 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgDetTOF.h +/// @file AlignableDetectorTOF.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Wrapper for TOF detector -#include "Align/AliAlgDetTOF.h" -#include "Align/AliAlgVol.h" -#include "Align/AliAlgSensTOF.h" -#include "Align/AliAlgSteer.h" +#include "Align/AlignableDetectorTOF.h" +#include "Align/AlignableVolume.h" +#include "Align/AlignableSensorTOF.h" +#include "Align/Controller.h" //#include "AliGeomManager.h" //#include "AliTOFGeometry.h" //#include "AliESDtrack.h" #include -ClassImp(o2::align::AliAlgDetTOF); +ClassImp(o2::align::AlignableDetectorTOF); namespace o2 { @@ -30,34 +30,34 @@ namespace align { //____________________________________________ -AliAlgDetTOF::AliAlgDetTOF(const char* title) +AlignableDetectorTOF::AlignableDetectorTOF(const char* title) { // default c-tor - SetNameTitle(AliAlgSteer::getDetNameByDetID(AliAlgSteer::kTOF), title); - setDetID(AliAlgSteer::kTOF); + SetNameTitle(Controller::getDetNameByDetID(Controller::kTOF), title); + setDetID(Controller::kTOF); } //____________________________________________ -AliAlgDetTOF::~AliAlgDetTOF() +AlignableDetectorTOF::~AlignableDetectorTOF() { // d-tor } //____________________________________________ -void AliAlgDetTOF::defineVolumes() +void AlignableDetectorTOF::defineVolumes() { // define TOF volumes // const int kNSect = 18, kNStrips = AliTOFGeometry::NStripA() + 2 * AliTOFGeometry::NStripB() + 2 * AliTOFGeometry::NStripC(); int labDet = getDetLabel(); - AliAlgSensTOF* strip = 0; + AlignableSensorTOF* strip = 0; // - // AddVolume( volTOF = new AliAlgVol("TOF") ); // no main volume, why? - AliAlgVol* sect[kNSect] = {0}; + // AddVolume( volTOF = new AlignableVolume("TOF") ); // no main volume, why? + AlignableVolume* sect[kNSect] = {0}; // for (int isc = 0; isc < kNSect; isc++) { int iid = labDet + (1 + isc) * 100; - addVolume(sect[isc] = new AliAlgVol(Form("TOF/sm%02d", isc), iid)); + addVolume(sect[isc] = new AlignableVolume(Form("TOF/sm%02d", isc), iid)); } // int cnt = 0; @@ -68,7 +68,7 @@ void AliAlgDetTOF::defineVolumes() const char* symname = Form("TOF/sm%02d/strip%02d", isc, istr); if (!gGeoManager->GetAlignableEntry(symname)) continue; - addVolume(strip = new AliAlgSensTOF(symname, vid, iid, isc)); + addVolume(strip = new AlignableSensorTOF(symname, vid, iid, isc)); strip->setParent(sect[isc]); } // strip } // layer @@ -76,7 +76,7 @@ void AliAlgDetTOF::defineVolumes() } //____________________________________________ -bool AliAlgDetTOF::AcceptTrack(const AliESDtrack* trc, int trtype) const +bool AlignableDetectorTOF::AcceptTrack(const AliESDtrack* trc, int trtype) const { // test if detector had seed this track return CheckFlags(trc, trtype); diff --git a/Detectors/Align/src/AliAlgDetTPC.cxx b/Detectors/Align/src/AlignableDetectorTPC.cxx similarity index 74% rename from Detectors/Align/src/AliAlgDetTPC.cxx rename to Detectors/Align/src/AlignableDetectorTPC.cxx index f705b239f0ddf..b9ee9dea71647 100644 --- a/Detectors/Align/src/AliAlgDetTPC.cxx +++ b/Detectors/Align/src/AlignableDetectorTPC.cxx @@ -8,21 +8,21 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgDetTPC.h +/// @file AlignableDetectorTPC.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief TPC detector wrapper -#include "Align/AliAlgDetTPC.h" -#include "Align/AliAlgVol.h" -#include "Align/AliAlgSensTPC.h" -#include "Align/AliAlgSteer.h" +#include "Align/AlignableDetectorTPC.h" +#include "Align/AlignableVolume.h" +#include "Align/AlignableSensorTPC.h" +#include "Align/Controller.h" //#include "AliGeomManager.h" //#include "AliESDtrack.h" #include "Framework/Logger.h" #include -ClassImp(o2::align::AliAlgDetTPC); +ClassImp(o2::align::AlignableDetectorTPC); namespace o2 { @@ -30,31 +30,31 @@ namespace align { //____________________________________________ -AliAlgDetTPC::AliAlgDetTPC(const char* title) +AlignableDetectorTPC::AlignableDetectorTPC(const char* title) { // default c-tor - SetNameTitle(AliAlgSteer::getDetNameByDetID(AliAlgSteer::kTPC), title); - setDetID(AliAlgSteer::kTPC); + SetNameTitle(Controller::getDetNameByDetID(Controller::kTPC), title); + setDetID(Controller::kTPC); } //____________________________________________ -AliAlgDetTPC::~AliAlgDetTPC() +AlignableDetectorTPC::~AlignableDetectorTPC() { // d-tor } //____________________________________________ -void AliAlgDetTPC::defineVolumes() +void AlignableDetectorTPC::defineVolumes() { // define TPC volumes // const int kNSect = 18, kAC = 2, kIOROC = 2; const char* kSide[kAC] = {"A", "C"}; const char* kROC[kIOROC] = {"Inner", "Outer"}; - // AliAlgSensTPC *chamb=0; + // AlignableSensorTPC *chamb=0; // int labDet = getDetLabel(); - AliAlgVol* volTPC = new AliAlgVol("ALIC_1/TPC_M_1", labDet); + AlignableVolume* volTPC = new AlignableVolume("ALIC_1/TPC_M_1", labDet); addVolume(volTPC); // @@ -69,7 +69,7 @@ void AliAlgDetTPC::defineVolumes() int iid = side * kNSect + isc; uint16_t vid = AliGeomManager::LayerToVolUID(AliGeomManager::kTPC1 + roc, iid); iid = labDet + (1 + side) * 10000 + (1 + isc) * 100 + (1 + roc); - AliAlgSensTPC* sens = new AliAlgSensTPC(symname, vid, iid, isc); + AlignableSensorTPC* sens = new AlignableSensorTPC(symname, vid, iid, isc); sens->setParent(volTPC); addVolume(sens); } // sector ID @@ -79,7 +79,7 @@ void AliAlgDetTPC::defineVolumes() } //____________________________________________ -bool AliAlgDetTPC::AcceptTrack(const AliESDtrack* trc, int trtype) const +bool AlignableDetectorTPC::AcceptTrack(const AliESDtrack* trc, int trtype) const { // test if detector had seed this track if (!CheckFlags(trc, trtype)) diff --git a/Detectors/Align/src/AliAlgDetTRD.cxx b/Detectors/Align/src/AlignableDetectorTRD.cxx similarity index 72% rename from Detectors/Align/src/AliAlgDetTRD.cxx rename to Detectors/Align/src/AlignableDetectorTRD.cxx index a6542e936c4fd..24618f996528f 100644 --- a/Detectors/Align/src/AliAlgDetTRD.cxx +++ b/Detectors/Align/src/AlignableDetectorTRD.cxx @@ -8,15 +8,15 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgDetTRD.h +/// @file AlignableDetectorTRD.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief TRD detector wrapper -#include "Align/AliAlgDetTRD.h" -#include "Align/AliAlgVol.h" -#include "Align/AliAlgSensTRD.h" -#include "Align/AliAlgSteer.h" +#include "Align/AlignableDetectorTRD.h" +#include "Align/AlignableVolume.h" +#include "Align/AlignableSensorTRD.h" +#include "Align/Controller.h" //#include "AliGeomManager.h" //#include "AliESDtrack.h" //#include "AliTRDgeometry.h" @@ -25,22 +25,22 @@ using namespace TMath; -ClassImp(o2::align::AliAlgDetTRD); +ClassImp(o2::align::AlignableDetectorTRD); namespace o2 { namespace align { -const char* AliAlgDetTRD::fgkCalibDOFName[AliAlgDetTRD::kNCalibParams] = {"DZdTglNRC", "DVDriftT"}; +const char* AlignableDetectorTRD::fgkCalibDOFName[AlignableDetectorTRD::kNCalibParams] = {"DZdTglNRC", "DVDriftT"}; //____________________________________________ -AliAlgDetTRD::AliAlgDetTRD(const char* title) - : AliAlgDet(), fNonRCCorrDzDtgl(0), fCorrDVT(0) +AlignableDetectorTRD::AlignableDetectorTRD(const char* title) + : AlignableDetector(), fNonRCCorrDzDtgl(0), fCorrDVT(0) { // default c-tor - SetNameTitle(AliAlgSteer::getDetNameByDetID(AliAlgSteer::kTRD), title); - setDetID(AliAlgSteer::kTRD); + SetNameTitle(Controller::getDetNameByDetID(Controller::kTRD), title); + setDetID(Controller::kTRD); fExtraErrRC[0] = fExtraErrRC[1] = 0; // // ad hoc correction @@ -50,22 +50,22 @@ AliAlgDetTRD::AliAlgDetTRD(const char* title) } //____________________________________________ -AliAlgDetTRD::~AliAlgDetTRD() +AlignableDetectorTRD::~AlignableDetectorTRD() { // d-tor } //____________________________________________ -void AliAlgDetTRD::defineVolumes() +void AlignableDetectorTRD::defineVolumes() { // define TRD volumes // const int kNSect = 18, kNStacks = 5, kNLayers = 6; - AliAlgSensTRD* chamb = 0; + AlignableSensorTRD* chamb = 0; // int labDet = getDetLabel(); - // AddVolume( volTRD = new AliAlgVol("TRD") ); // no main volume, why? - AliAlgVol* sect[kNSect] = {0}; + // AddVolume( volTRD = new AlignableVolume("TRD") ); // no main volume, why? + AlignableVolume* sect[kNSect] = {0}; // for (int ilr = 0; ilr < kNLayers; ilr++) { // layer for (int ich = 0; ich < kNStacks * kNSect; ich++) { // chamber @@ -77,10 +77,10 @@ void AliAlgDetTRD::defineVolumes() if (!gGeoManager->GetAlignableEntry(symname)) continue; uint16_t vid = AliGeomManager::LayerToVolUID(AliGeomManager::kTRD1 + ilr, ich); - addVolume(chamb = new AliAlgSensTRD(symname, vid, iid /*lid*/, isector)); + addVolume(chamb = new AlignableSensorTRD(symname, vid, iid /*lid*/, isector)); iid = labDet + (1 + isector) * 100; if (!sect[isector]) - sect[isector] = new AliAlgVol(Form("TRD/sm%02d", isector), iid); + sect[isector] = new AlignableVolume(Form("TRD/sm%02d", isector), iid); chamb->setParent(sect[isector]); } // chamber } // layer @@ -93,7 +93,7 @@ void AliAlgDetTRD::defineVolumes() } //____________________________________________ -bool AliAlgDetTRD::AcceptTrack(const AliESDtrack* trc, int trtype) const +bool AlignableDetectorTRD::AcceptTrack(const AliESDtrack* trc, int trtype) const { // test if detector had seed this track if (!CheckFlags(trc, trtype)) @@ -105,24 +105,24 @@ bool AliAlgDetTRD::AcceptTrack(const AliESDtrack* trc, int trtype) const //__________________________________________ //____________________________________________ -void AliAlgDetTRD::Print(const Option_t* opt) const +void AlignableDetectorTRD::Print(const Option_t* opt) const { // print info - AliAlgDet::Print(opt); + AlignableDetector::Print(opt); printf("Extra error for RC tracklets: Y:%e Z:%e\n", fExtraErrRC[0], fExtraErrRC[1]); } -const char* AliAlgDetTRD::getCalibDOFName(int i) const +const char* AlignableDetectorTRD::getCalibDOFName(int i) const { // return calibration DOF name return i < kNCalibParams ? fgkCalibDOFName[i] : 0; } //______________________________________________________ -void AliAlgDetTRD::writePedeInfo(FILE* parOut, const Option_t* opt) const +void AlignableDetectorTRD::writePedeInfo(FILE* parOut, const Option_t* opt) const { // contribute to params and constraints template files for PEDE - AliAlgDet::writePedeInfo(parOut, opt); + AlignableDetector::writePedeInfo(parOut, opt); // // write calibration parameters enum { kOff, @@ -143,7 +143,7 @@ void AliAlgDetTRD::writePedeInfo(FILE* parOut, const Option_t* opt) const } //_______________________________________________________ -double AliAlgDetTRD::getCalibDOFVal(int id) const +double AlignableDetectorTRD::getCalibDOFVal(int id) const { // return preset value of calibration dof double val = 0; @@ -161,7 +161,7 @@ double AliAlgDetTRD::getCalibDOFVal(int id) const } //_______________________________________________________ -double AliAlgDetTRD::getCalibDOFValWithCal(int id) const +double AlignableDetectorTRD::getCalibDOFValWithCal(int id) const { // return preset value of calibration dof + mp correction return getCalibDOFVal(id) + getParVal(id); diff --git a/Detectors/Align/src/AliAlgSens.cxx b/Detectors/Align/src/AlignableSensor.cxx similarity index 87% rename from Detectors/Align/src/AliAlgSens.cxx rename to Detectors/Align/src/AlignableSensor.cxx index 85c5f7c3251bf..74a6cf5373279 100644 --- a/Detectors/Align/src/AliAlgSens.cxx +++ b/Detectors/Align/src/AlignableSensor.cxx @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgSens.h +/// @file AlignableSensor.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief End-chain alignment volume in detector branch, where the actual measurement is done. @@ -16,15 +16,15 @@ #include #include -#include "Align/AliAlgSens.h" +#include "Align/AlignableSensor.h" #include "Framework/Logger.h" -#include "Align/AliAlgPoint.h" -#include "Align/AliAlgDet.h" +#include "Align/AlignmentPoint.h" +#include "Align/AlignableDetector.h" //#include "AliGeomManager.h" -ClassImp(o2::align::AliAlgSens); +ClassImp(o2::align::AlignableSensor); -using namespace o2::align::AliAlgAux; +using namespace o2::align::utils; using namespace TMath; namespace o2 @@ -33,8 +33,8 @@ namespace align { //_________________________________________________________ -AliAlgSens::AliAlgSens(const char* name, int vid, int iid) - : AliAlgVol(name, iid), mSID(0), mDet(0), mMatClAlg(), mMatClAlgReco() +AlignableSensor::AlignableSensor(const char* name, int vid, int iid) + : AlignableVolume(name, iid), mSID(0), mDet(0), mMatClAlg(), mMatClAlgReco() { // def c-tor setVolID(vid); @@ -43,13 +43,13 @@ AliAlgSens::AliAlgSens(const char* name, int vid, int iid) } //_________________________________________________________ -AliAlgSens::~AliAlgSens() +AlignableSensor::~AlignableSensor() { // d-tor } //_________________________________________________________ -void AliAlgSens::dPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv) const +void AlignableSensor::dPosTraDParGeomLOC(const AlignmentPoint* pnt, double* deriv) const { // Jacobian of position in sensor tracking frame (tra) vs sensor LOCAL frame // parameters in TGeoHMatrix convention. @@ -94,7 +94,7 @@ void AliAlgSens::dPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv) const } //_________________________________________________________ -void AliAlgSens::dPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const +void AlignableSensor::dPosTraDParGeomLOC(const AlignmentPoint* pnt, double* deriv, const AlignableVolume* parent) const { // Jacobian of position in sensor tracking frame (tra) vs parent volume LOCAL frame parameters. // NO check of parentship is done! @@ -141,7 +141,7 @@ void AliAlgSens::dPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv, const } //_________________________________________________________ -void AliAlgSens::dPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv) const +void AlignableSensor::dPosTraDParGeomTRA(const AlignmentPoint* pnt, double* deriv) const { // Jacobian of position in sensor tracking frame (tra) vs sensor TRACKING // frame parameters in TGeoHMatrix convention, i.e. the modified parameter is @@ -187,7 +187,7 @@ void AliAlgSens::dPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv) const } //_________________________________________________________ -void AliAlgSens::dPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const +void AlignableSensor::dPosTraDParGeomTRA(const AlignmentPoint* pnt, double* deriv, const AlignableVolume* parent) const { // Jacobian of position in sensor tracking frame (tra) vs sensor TRACKING // frame parameters in TGeoHMatrix convention, i.e. the modified parameter is @@ -248,7 +248,7 @@ void AliAlgSens::dPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv, const } //_________________________________________________________ -void AliAlgSens::dPosTraDParGeom(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const +void AlignableSensor::dPosTraDParGeom(const AlignmentPoint* pnt, double* deriv, const AlignableVolume* parent) const { // calculate point position derivatives in tracking frame of sensor // vs standard geometrical DOFs of its parent volume (if parent!=0) or sensor itself @@ -267,7 +267,7 @@ void AliAlgSens::dPosTraDParGeom(const AliAlgPoint* pnt, double* deriv, const Al } //__________________________________________________________________ -void AliAlgSens::getModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const double* delta) const +void AlignableSensor::getModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const double* delta) const { // prepare the sensitive module tracking2local matrix from its current T2L matrix // by applying local delta of modification of LOCAL frame: @@ -277,7 +277,7 @@ void AliAlgSens::getModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const double* d } //__________________________________________________________________ -void AliAlgSens::getModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const double* delta) const +void AlignableSensor::getModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const double* delta) const { // prepare the sensitive module tracking2local matrix from its current T2L matrix // by applying local delta of modification of TRACKING frame: @@ -287,20 +287,20 @@ void AliAlgSens::getModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const double* d } //__________________________________________________________________ -void AliAlgSens::addChild(AliAlgVol*) +void AlignableSensor::addChild(AlignableVolume*) { LOG(FATAL) << "Sensor volume cannot have children: id=" << getVolID() << " " << GetName(); } //__________________________________________________________________ -int AliAlgSens::Compare(const TObject* b) const +int AlignableSensor::Compare(const TObject* b) const { // compare VolIDs return GetUniqueID() < b->GetUniqueID() ? -1 : 1; } //__________________________________________________________________ -void AliAlgSens::setTrackingFrame() +void AlignableSensor::setTrackingFrame() { // define tracking frame of the sensor // AliWarningF("Generic method called for %s",getSymName()); @@ -310,12 +310,12 @@ void AliAlgSens::setTrackingFrame() t2g.LocalToMaster(tra, glo); mX = Sqrt(glo[0] * glo[0] + glo[1] * glo[1]); mAlp = ATan2(glo[1], glo[0]); - AliAlgAux::bringToPiPM(mAlp); + utils::bringToPiPM(mAlp); // } //____________________________________________ -void AliAlgSens::Print(const Option_t* opt) const +void AlignableSensor::Print(const Option_t* opt) const { // print info TString opts = opt; @@ -363,7 +363,7 @@ void AliAlgSens::Print(const Option_t* opt) const } //____________________________________________ -void AliAlgSens::prepareMatrixT2L() +void AlignableSensor::prepareMatrixT2L() { // extract geometry T2L matrix TGeoHMatrix t2l; @@ -385,7 +385,7 @@ void AliAlgSens::prepareMatrixT2L() } //____________________________________________ -void AliAlgSens::prepareMatrixClAlg() +void AlignableSensor::prepareMatrixClAlg() { // prepare alignment matrix in the LOCAL frame: delta = Gideal^-1 * G TGeoHMatrix ma = getMatrixL2GIdeal().Inverse(); @@ -395,7 +395,7 @@ void AliAlgSens::prepareMatrixClAlg() } //____________________________________________ -void AliAlgSens::prepareMatrixClAlgReco() +void AlignableSensor::prepareMatrixClAlgReco() { // prepare alignment matrix used at reco time TGeoHMatrix ma = getMatrixL2GIdeal().Inverse(); @@ -405,14 +405,14 @@ void AliAlgSens::prepareMatrixClAlgReco() } //____________________________________________ -void AliAlgSens::updatePointByTrackInfo(AliAlgPoint* pnt, const trackParam_t* t) const +void AlignableSensor::updatePointByTrackInfo(AlignmentPoint* pnt, const trackParam_t* t) const { // update mDet->updatePointByTrackInfo(pnt, t); } //____________________________________________ -void AliAlgSens::dPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int calibID, const AliAlgVol* parent) const +void AlignableSensor::dPosTraDParCalib(const AlignmentPoint* pnt, double* deriv, int calibID, const AlignableVolume* parent) const { // calculate point position X,Y,Z derivatives wrt calibration parameter calibID of given parent // parent=0 means top detector object calibration @@ -421,7 +421,7 @@ void AliAlgSens::dPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int cal } //______________________________________________________ -int AliAlgSens::finalizeStat(AliAlgDOFStat* st) +int AlignableSensor::finalizeStat(DOFStatistics* st) { // finalize statistics on processed points if (st) @@ -430,20 +430,20 @@ int AliAlgSens::finalizeStat(AliAlgDOFStat* st) } //_________________________________________________________________ -void AliAlgSens::updateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta) +void AlignableSensor::updateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta) { // recreate mMatL2GReco matrices from ideal L2G matrix and alignment objects // used during data reconstruction. // On top of what each volume does, also update misalignment matrix inverse // - AliAlgVol::updateL2GRecoMatrices(algArr, cumulDelta); + AlignableVolume::updateL2GRecoMatrices(algArr, cumulDelta); prepareMatrixClAlgReco(); // } /* //_________________________________________________________________ -AliAlgPoint* AliAlgSens::TrackPoint2AlgPoint(int, const AliTrackPointArray*, const AliESDtrack*) +AlignmentPoint* AlignableSensor::TrackPoint2AlgPoint(int, const AliTrackPointArray*, const AliESDtrack*) { // dummy converter AliError("Generic method, must be implemented in specific sensor"); @@ -452,12 +452,12 @@ AliAlgPoint* AliAlgSens::TrackPoint2AlgPoint(int, const AliTrackPointArray*, con */ //_________________________________________________________________ -void AliAlgSens::applyAlignmentFromMPSol() +void AlignableSensor::applyAlignmentFromMPSol() { // apply to the tracking coordinates in the sensor frame the full chain // of alignments found by MP for this sensor and its parents // - const AliAlgVol* vol = this; + const AlignableVolume* vol = this; TGeoHMatrix deltaG; // create global combined delta: // DeltaG = deltaG_0*...*deltaG_j, where delta_i is global delta of each member of hierarchy @@ -479,7 +479,7 @@ void AliAlgSens::applyAlignmentFromMPSol() /* //_________________________________________________________________ -void AliAlgSens::applyAlignmentFromMPSol() +void AlignableSensor::applyAlignmentFromMPSol() { // apply to the tracking coordinates in the sensor frame the full chain // of alignments found by MP for this sensor and its parents @@ -492,7 +492,7 @@ void AliAlgSens::applyAlignmentFromMPSol() isFrameTRA() ? getDeltaT2LmodTRA(matMod,delta) : getDeltaT2LmodLOC(matMod,delta); mMatClAlg.MultiplyLeft(&matMod); // - AliAlgVol* parent = this; + AlignableVolume* parent = this; while ((parent==parent->getParent())) { // this is the matrix for transition from sensor to parent volume frame parent->getParValGeom(delta); diff --git a/Detectors/Align/src/AliAlgSensHMPID.cxx b/Detectors/Align/src/AlignableSensorHMPID.cxx similarity index 85% rename from Detectors/Align/src/AliAlgSensHMPID.cxx rename to Detectors/Align/src/AlignableSensorHMPID.cxx index 095ffccfb249d..cd186ef972556 100644 --- a/Detectors/Align/src/AliAlgSensHMPID.cxx +++ b/Detectors/Align/src/AlignableSensorHMPID.cxx @@ -8,22 +8,22 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgSensHMPID.h +/// @file AlignableSensorHMPID.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief HMPID sensor (chamber) -#include "Align/AliAlgSensHMPID.h" -#include "Align/AliAlgAux.h" +#include "Align/AlignableSensorHMPID.h" +#include "Align/utils.h" #include "Framework/Logger.h" //#include "AliTrackPointArray.h" //#include "AliESDtrack.h" -#include "Align/AliAlgPoint.h" -#include "Align/AliAlgDet.h" +#include "Align/AlignmentPoint.h" +#include "Align/AlignableDetector.h" -ClassImp(o2::align::AliAlgSensHMPID); +ClassImp(o2::align::AlignableSensorHMPID); -using namespace o2::align::AliAlgAux; +using namespace o2::align::utils; using namespace TMath; namespace o2 @@ -32,20 +32,20 @@ namespace align { //_________________________________________________________ -AliAlgSensHMPID::AliAlgSensHMPID(const char* name, int vid, int iid, int isec) - : AliAlgSens(name, vid, iid) +AlignableSensorHMPID::AlignableSensorHMPID(const char* name, int vid, int iid, int isec) + : AlignableSensor(name, vid, iid) { // def c-tor } //_________________________________________________________ -AliAlgSensHMPID::~AliAlgSensHMPID() +AlignableSensorHMPID::~AlignableSensorHMPID() { // d-tor } /* //__________________________________________________________________ -void AliAlgSensHMPID::setTrackingFrame() +void AlignableSensorHMPID::setTrackingFrame() { // define tracking frame of the sensor: just rotation by sector angle fAlp = sector2Alpha(fSector); @@ -54,7 +54,7 @@ void AliAlgSensHMPID::setTrackingFrame() */ //____________________________________________ -void AliAlgSensHMPID::prepareMatrixT2L() +void AlignableSensorHMPID::prepareMatrixT2L() { // creat T2L matrix double loc[3] = {0, 0, 0}, glo[3]; @@ -78,12 +78,12 @@ void AliAlgSensHMPID::prepareMatrixT2L() } //____________________________________________ -AliAlgPoint* AliAlgSensHMPID::TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack*) +AlignmentPoint* AlignableSensorHMPID::TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack*) { - // convert the pntId-th point to AliAlgPoint + // convert the pntId-th point to AlignmentPoint // - AliAlgDet* det = getDetector(); - AliAlgPoint* pnt = det->getPointFromPool(); + AlignableDetector* det = getDetector(); + AlignmentPoint* pnt = det->getPointFromPool(); pnt->setSensor(this); // double tra[3], locId[3], loc[3], diff --git a/Detectors/Align/src/AliAlgSensITS.cxx b/Detectors/Align/src/AlignableSensorITS.cxx similarity index 84% rename from Detectors/Align/src/AliAlgSensITS.cxx rename to Detectors/Align/src/AlignableSensorITS.cxx index 977f1b3e840fa..c1996e942b25f 100644 --- a/Detectors/Align/src/AliAlgSensITS.cxx +++ b/Detectors/Align/src/AlignableSensorITS.cxx @@ -8,22 +8,22 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgSensITS.h +/// @file AlignableSensorITS.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief ITS sensor -#include "Align/AliAlgSensITS.h" -#include "Align/AliAlgAux.h" +#include "Align/AlignableSensorITS.h" +#include "Align/utils.h" #include "Framework/Logger.h" //#include "AliTrackPointArray.h" //#include "AliESDtrack.h" -#include "Align/AliAlgPoint.h" -#include "Align/AliAlgDet.h" +#include "Align/AlignmentPoint.h" +#include "Align/AlignableDetector.h" -ClassImp(o2::align::AliAlgSensITS); +ClassImp(o2::align::AlignableSensorITS); -using namespace o2::align::AliAlgAux; +using namespace o2::align::utils; using namespace TMath; namespace o2 @@ -32,20 +32,20 @@ namespace align { //_________________________________________________________ -AliAlgSensITS::AliAlgSensITS(const char* name, int vid, int iid) - : AliAlgSens(name, vid, iid) +AlignableSensorITS::AlignableSensorITS(const char* name, int vid, int iid) + : AlignableSensor(name, vid, iid) { // def c-tor } //_________________________________________________________ -AliAlgSensITS::~AliAlgSensITS() +AlignableSensorITS::~AlignableSensorITS() { // d-tor } /* //__________________________________________________________________ -void AliAlgSensITS::setTrackingFrame() +void AlignableSensorITS::setTrackingFrame() { // define tracking frame of the sensor double tra[3]={0},loc[3],glo[3]; @@ -54,17 +54,17 @@ void AliAlgSensITS::setTrackingFrame() getMatrixL2GIdeal().LocalToMaster(loc,glo); fX = Sqrt(glo[0]*glo[0]+glo[1]*glo[1]); fAlp = ATan2(glo[1],glo[0]); - AliAlgAux::bringToPiPM(fAlp); + utils::bringToPiPM(fAlp); } */ //____________________________________________ -AliAlgPoint* AliAlgSensITS::TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack*) +AlignmentPoint* AlignableSensorITS::TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack*) { - // convert the pntId-th point to AliAlgPoint + // convert the pntId-th point to AlignmentPoint // - AliAlgDet* det = getDetector(); - AliAlgPoint* pnt = det->getPointFromPool(); + AlignableDetector* det = getDetector(); + AlignmentPoint* pnt = det->getPointFromPool(); pnt->setSensor(this); // double tra[3], locId[3], loc[3], diff --git a/Detectors/Align/src/AliAlgSensTOF.cxx b/Detectors/Align/src/AlignableSensorTOF.cxx similarity index 87% rename from Detectors/Align/src/AliAlgSensTOF.cxx rename to Detectors/Align/src/AlignableSensorTOF.cxx index e43f797529d6b..bd12f25fb54c9 100644 --- a/Detectors/Align/src/AliAlgSensTOF.cxx +++ b/Detectors/Align/src/AlignableSensorTOF.cxx @@ -8,22 +8,22 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgSensTOF.h +/// @file AlignableSensorTOF.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief TOF sensor -#include "Align/AliAlgSensTOF.h" -#include "Align/AliAlgAux.h" -#include "Align/AliAlgDetTOF.h" +#include "Align/AlignableSensorTOF.h" +#include "Align/utils.h" +#include "Align/AlignableDetectorTOF.h" #include "Framework/Logger.h" -#include "Align/AliAlgPoint.h" +#include "Align/AlignmentPoint.h" //#include "AliTrackPointArray.h" //#include "AliESDtrack.h" -ClassImp(o2::align::AliAlgSensTOF); +ClassImp(o2::align::AlignableSensorTOF); -using namespace o2::align::AliAlgAux; +using namespace o2::align::utils; using namespace TMath; namespace o2 @@ -32,21 +32,21 @@ namespace align { //_________________________________________________________ -AliAlgSensTOF::AliAlgSensTOF(const char* name, int vid, int iid, int isec) - : AliAlgSens(name, vid, iid), fSector(isec) +AlignableSensorTOF::AlignableSensorTOF(const char* name, int vid, int iid, int isec) + : AlignableSensor(name, vid, iid), fSector(isec) { // def c-tor } //_________________________________________________________ -AliAlgSensTOF::~AliAlgSensTOF() +AlignableSensorTOF::~AlignableSensorTOF() { // d-tor } /* //__________________________________________________________________ -void AliAlgSensTOF::setTrackingFrame() +void AlignableSensorTOF::setTrackingFrame() { // define tracking frame of the sensor: just rotation by sector angle fAlp = sector2Alpha(fSector); @@ -55,7 +55,7 @@ void AliAlgSensTOF::setTrackingFrame() */ //____________________________________________ -void AliAlgSensTOF::prepareMatrixT2L() +void AlignableSensorTOF::prepareMatrixT2L() { // extract from geometry T2L matrix double alp = sector2Alpha(fSector); @@ -79,15 +79,15 @@ void AliAlgSensTOF::prepareMatrixT2L() } //____________________________________________ -AliAlgPoint* AliAlgSensTOF::TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* tr) +AlignmentPoint* AlignableSensorTOF::TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* tr) { - // convert the pntId-th point to AliAlgPoint, detectors may override this method + // convert the pntId-th point to AlignmentPoint, detectors may override this method // // TOF stores in the trackpoints X,Y with alignment applied but Z w/o alignment!!! // -> need special treatment unless data are already corrected // - AliAlgDetTOF* det = (AliAlgDetTOF*)getDetector(); - AliAlgPoint* pnt = det->getPointFromPool(); + AlignableDetectorTOF* det = (AlignableDetectorTOF*)getDetector(); + AlignmentPoint* pnt = det->getPointFromPool(); pnt->setSensor(this); // double tra[3], locId[3], loc[3], traId[3], diff --git a/Detectors/Align/src/AliAlgSensTPC.cxx b/Detectors/Align/src/AlignableSensorTPC.cxx similarity index 85% rename from Detectors/Align/src/AliAlgSensTPC.cxx rename to Detectors/Align/src/AlignableSensorTPC.cxx index 4362bbdabc707..72170ad1cb831 100644 --- a/Detectors/Align/src/AliAlgSensTPC.cxx +++ b/Detectors/Align/src/AlignableSensorTPC.cxx @@ -8,22 +8,22 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgSensTPC.h +/// @file AlignableSensorTPC.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief TPC sensor (chamber) -#include "Align/AliAlgSensTPC.h" -#include "Align/AliAlgAux.h" +#include "Align/AlignableSensorTPC.h" +#include "Align/utils.h" #include "Framework/Logger.h" //#include "AliTrackPointArray.h" //#include "AliESDtrack.h" -#include "Align/AliAlgPoint.h" -#include "Align/AliAlgDet.h" +#include "Align/AlignmentPoint.h" +#include "Align/AlignableDetector.h" -ClassImp(o2::align::AliAlgSensTPC) +ClassImp(o2::align::AlignableSensorTPC) - using namespace o2::align::AliAlgAux; + using namespace o2::align::utils; using namespace TMath; namespace o2 @@ -32,20 +32,20 @@ namespace align { //_________________________________________________________ -AliAlgSensTPC::AliAlgSensTPC(const char* name, int vid, int iid, int isec) - : AliAlgSens(name, vid, iid), fSector(isec) +AlignableSensorTPC::AlignableSensorTPC(const char* name, int vid, int iid, int isec) + : AlignableSensor(name, vid, iid), fSector(isec) { // def c-tor } //_________________________________________________________ -AliAlgSensTPC::~AliAlgSensTPC() +AlignableSensorTPC::~AlignableSensorTPC() { // d-tor } /* //__________________________________________________________________ -void AliAlgSensTPC::setTrackingFrame() +void AlignableSensorTPC::setTrackingFrame() { // define tracking frame of the sensor: just rotation by sector angle fAlp = sector2Alpha(fSector); @@ -54,7 +54,7 @@ void AliAlgSensTPC::setTrackingFrame() */ //____________________________________________ -void AliAlgSensTPC::prepareMatrixT2L() +void AlignableSensorTPC::prepareMatrixT2L() { // extract from geometry T2L matrix double alp = sector2Alpha(fSector); @@ -78,12 +78,12 @@ void AliAlgSensTPC::prepareMatrixT2L() } //____________________________________________ -AliAlgPoint* AliAlgSensTPC::TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack*) +AlignmentPoint* AlignableSensorTPC::TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack*) { - // convert the pntId-th point to AliAlgPoint + // convert the pntId-th point to AlignmentPoint // - AliAlgDet* det = getDetector(); - AliAlgPoint* pnt = det->getPointFromPool(); + AlignableDetector* det = getDetector(); + AlignmentPoint* pnt = det->getPointFromPool(); pnt->setSensor(this); // double tra[3], locId[3], loc[3], diff --git a/Detectors/Align/src/AliAlgSensTRD.cxx b/Detectors/Align/src/AlignableSensorTRD.cxx similarity index 81% rename from Detectors/Align/src/AliAlgSensTRD.cxx rename to Detectors/Align/src/AlignableSensorTRD.cxx index a278e1a990c20..517d5f29dabc3 100644 --- a/Detectors/Align/src/AliAlgSensTRD.cxx +++ b/Detectors/Align/src/AlignableSensorTRD.cxx @@ -8,24 +8,24 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgSensTRD.h +/// @file AlignableSensorTRD.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief TRD sensor -#include "Align/AliAlgSensTRD.h" +#include "Align/AlignableSensorTRD.h" //#include "AliTRDgeometry.h" -#include "Align/AliAlgDetTRD.h" -#include "Align/AliAlgAux.h" +#include "Align/AlignableDetectorTRD.h" +#include "Align/utils.h" #include "Framework/Logger.h" -#include "Align/AliAlgPoint.h" +#include "Align/AlignmentPoint.h" //#include "AliTrackPointArray.h" //#include "AliESDtrack.h" //#include "AliTrackerBase.h" -ClassImp(o2::align::AliAlgSensTRD) +ClassImp(o2::align::AlignableSensorTRD) - using namespace o2::align::AliAlgAux; + using namespace o2::align::utils; using namespace TMath; namespace o2 @@ -34,20 +34,20 @@ namespace align { //_________________________________________________________ -AliAlgSensTRD::AliAlgSensTRD(const char* name, int vid, int iid, int isec) - : AliAlgSens(name, vid, iid), fSector(isec) +AlignableSensorTRD::AlignableSensorTRD(const char* name, int vid, int iid, int isec) + : AlignableSensor(name, vid, iid), fSector(isec) { // def c-tor } //_________________________________________________________ -AliAlgSensTRD::~AliAlgSensTRD() +AlignableSensorTRD::~AlignableSensorTRD() { // d-tor } /* //__________________________________________________________________ -void AliAlgSensTRD::setTrackingFrame() +void AlignableSensorTRD::setTrackingFrame() { // define tracking frame of the sensor: just rotation by sector angle fAlp = sector2Alpha(fSector); @@ -56,7 +56,7 @@ void AliAlgSensTRD::setTrackingFrame() */ //____________________________________________ -void AliAlgSensTRD::prepareMatrixT2L() +void AlignableSensorTRD::prepareMatrixT2L() { // extract from geometry T2L matrix double alp = sector2Alpha(fSector); @@ -80,7 +80,7 @@ void AliAlgSensTRD::prepareMatrixT2L() } //____________________________________________ -void AliAlgSensTRD::dPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int calibID, const AliAlgVol* parent) const +void AlignableSensorTRD::dPosTraDParCalib(const AlignmentPoint* pnt, double* deriv, int calibID, const AlignableVolume* parent) const { // calculate point position X,Y,Z derivatives wrt calibration parameter calibID of given parent // parent=0 means top detector object calibration @@ -90,20 +90,20 @@ void AliAlgSensTRD::dPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int if (!parent) { // TRD detector global calibration // switch (calibID) { - case AliAlgDetTRD::kCalibNRCCorrDzDtgl: { // correction for Non-Crossing tracklets Z,Y shift: Z -> Z + calib*tgl, Y -> Y + calib*tgl*tilt*sign(tilt); - double sgYZ = pnt->getYZErrTracking()[1]; // makes sense only for nonRC tracklets + case AlignableDetectorTRD::kCalibNRCCorrDzDtgl: { // correction for Non-Crossing tracklets Z,Y shift: Z -> Z + calib*tgl, Y -> Y + calib*tgl*tilt*sign(tilt); + double sgYZ = pnt->getYZErrTracking()[1]; // makes sense only for nonRC tracklets if (Abs(sgYZ) > 0.01) { const double kTilt = 2. * TMath::DegToRad(); - deriv[2] = pnt->getTrParamWSA()[AliAlgPoint::kParTgl]; + deriv[2] = pnt->getTrParamWSA()[AlignmentPoint::kParTgl]; deriv[1] = deriv[2] * Sign(kTilt, sgYZ); } break; } // - case AliAlgDetTRD::kCalibDVT: { // correction for bias in VdriftT + case AlignableDetectorTRD::kCalibDVT: { // correction for bias in VdriftT // error in VdriftT equivalent to shift in X at which Y measurement is evaluated // Y -> Y + dVdriftT * tg_phi, where tg_phi is the slope of the track in YX plane - double snp = pnt->getTrParamWSA(AliAlgPoint::kParSnp), slpY = snp / Sqrt((1 - snp) * (1 + snp)); + double snp = pnt->getTrParamWSA(AlignmentPoint::kParSnp), slpY = snp / Sqrt((1 - snp) * (1 + snp)); deriv[1] = slpY; break; } @@ -116,12 +116,12 @@ void AliAlgSensTRD::dPosTraDParCalib(const AliAlgPoint* pnt, double* deriv, int } //____________________________________________ -AliAlgPoint* AliAlgSensTRD::TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* tr) +AlignmentPoint* AlignableSensorTRD::TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* tr) { - // convert the pntId-th point to AliAlgPoint + // convert the pntId-th point to AlignmentPoint // - AliAlgDetTRD* det = (AliAlgDetTRD*)getDetector(); - AliAlgPoint* pnt = det->getPointFromPool(); + AlignableDetectorTRD* det = (AlignableDetectorTRD*)getDetector(); + AlignmentPoint* pnt = det->getPointFromPool(); pnt->setSensor(this); // double tra[3], locId[3], loc[3], diff --git a/Detectors/Align/src/AliAlgVol.cxx b/Detectors/Align/src/AlignableVolume.cxx similarity index 83% rename from Detectors/Align/src/AliAlgVol.cxx rename to Detectors/Align/src/AlignableVolume.cxx index 36bff9808cf8f..85023c192e3bc 100644 --- a/Detectors/Align/src/AliAlgVol.cxx +++ b/Detectors/Align/src/AlignableVolume.cxx @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgVol.h +/// @file AlignableVolume.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Base class of alignable volume @@ -95,12 +95,12 @@ */ -#include "Align/AliAlgVol.h" -#include "Align/AliAlgDOFStat.h" -#include "Align/AliAlgConstraint.h" +#include "Align/AlignableVolume.h" +#include "Align/DOFStatistics.h" +#include "Align/GeometricalConstraint.h" #include "DetectorsCommonDataFormats/AlignParam.h" #include "DetectorsBase/GeometryManager.h" -#include "Align/AliAlgAux.h" +#include "Align/utils.h" #include "Framework/Logger.h" #include #include @@ -110,43 +110,43 @@ #include #include -ClassImp(o2::align::AliAlgVol); +ClassImp(o2::align::AlignableVolume); using namespace TMath; -using namespace o2::align::AliAlgAux; +using namespace o2::align::utils; namespace o2 { namespace align { -const char* AliAlgVol::sFrameName[AliAlgVol::kNVarFrames] = {"LOC", "TRA"}; +const char* AlignableVolume::sFrameName[AlignableVolume::kNVarFrames] = {"LOC", "TRA"}; // -uint32_t AliAlgVol::sDefGeomFree = +uint32_t AlignableVolume::sDefGeomFree = kDOFBitTX | kDOFBitTY | kDOFBitTZ | kDOFBitPS | kDOFBitTH | kDOFBitPH; // -const char* AliAlgVol::sDOFName[AliAlgVol::kNDOFGeom] = {"TX", "TY", "TZ", "PSI", "THT", "PHI"}; +const char* AlignableVolume::sDOFName[AlignableVolume::kNDOFGeom] = {"TX", "TY", "TZ", "PSI", "THT", "PHI"}; //_________________________________________________________ -AliAlgVol::AliAlgVol(const char* symname, int iid) : TNamed(symname, ""), mVarFrame(kTRA), mIntID(iid), mX(0), mAlp(0), mNDOFs(0), mDOF(0), mNDOFGeomFree(0), mNDOFFree(0), mConstrChild(kDefChildConstr) - // - , - mParent(0), - mChildren(0) - // - , - mNProcPoints(0), - mFirstParGloID(-1), - mParVals(0), - mParErrs(0), - mParLabs(0) - // - , - mMatL2GReco(), - mMatL2G(), - mMatL2GIdeal(), - mMatT2L(), - mMatDeltaRefGlo() +AlignableVolume::AlignableVolume(const char* symname, int iid) : TNamed(symname, ""), mVarFrame(kTRA), mIntID(iid), mX(0), mAlp(0), mNDOFs(0), mDOF(0), mNDOFGeomFree(0), mNDOFFree(0), mConstrChild(kDefChildConstr) + // + , + mParent(0), + mChildren(0) + // + , + mNProcPoints(0), + mFirstParGloID(-1), + mParVals(0), + mParErrs(0), + mParLabs(0) + // + , + mMatL2GReco(), + mMatL2G(), + mMatL2GIdeal(), + mMatT2L(), + mMatDeltaRefGlo() { // def c-tor setVolID(0); // volumes have no VID, unless it is sensor @@ -157,14 +157,14 @@ AliAlgVol::AliAlgVol(const char* symname, int iid) : TNamed(symname, ""), mVarFr } //_________________________________________________________ -AliAlgVol::~AliAlgVol() +AlignableVolume::~AlignableVolume() { // d-tor delete mChildren; } //_________________________________________________________ -void AliAlgVol::delta2Matrix(TGeoHMatrix& deltaM, const double* delta) const +void AlignableVolume::delta2Matrix(TGeoHMatrix& deltaM, const double* delta) const { // prepare delta matrix for the volume from its // local delta vector (AliAlignObj convension): dx,dy,dz,,theta,psi,phi @@ -182,7 +182,7 @@ void AliAlgVol::delta2Matrix(TGeoHMatrix& deltaM, const double* delta) const } //__________________________________________________________________ -void AliAlgVol::getDeltaT2LmodLOC(TGeoHMatrix& matMod, const double* delta) const +void AlignableVolume::getDeltaT2LmodLOC(TGeoHMatrix& matMod, const double* delta) const { // prepare the variation matrix tau in volume TRACKING frame by applying // local delta of modification of LOCAL frame: @@ -195,7 +195,7 @@ void AliAlgVol::getDeltaT2LmodLOC(TGeoHMatrix& matMod, const double* delta) cons } //__________________________________________________________________ -void AliAlgVol::getDeltaT2LmodLOC(TGeoHMatrix& matMod, const double* delta, const TGeoHMatrix& relMat) const +void AlignableVolume::getDeltaT2LmodLOC(TGeoHMatrix& matMod, const double* delta, const TGeoHMatrix& relMat) const { // prepare the variation matrix tau in volume TRACKING frame by applying // local delta of modification of LOCAL frame of its PARENT; @@ -212,7 +212,7 @@ void AliAlgVol::getDeltaT2LmodLOC(TGeoHMatrix& matMod, const double* delta, cons } //__________________________________________________________________ -void AliAlgVol::getDeltaT2LmodTRA(TGeoHMatrix& matMod, const double* delta) const +void AlignableVolume::getDeltaT2LmodTRA(TGeoHMatrix& matMod, const double* delta) const { // prepare the variation matrix tau in volume TRACKING frame by applying // local delta of modification of the same TRACKING frame: @@ -221,7 +221,7 @@ void AliAlgVol::getDeltaT2LmodTRA(TGeoHMatrix& matMod, const double* delta) cons } //__________________________________________________________________ -void AliAlgVol::getDeltaT2LmodTRA(TGeoHMatrix& matMod, const double* delta, const TGeoHMatrix& relMat) const +void AlignableVolume::getDeltaT2LmodTRA(TGeoHMatrix& matMod, const double* delta, const TGeoHMatrix& relMat) const { // prepare the variation matrix tau in volume TRACKING frame by applying // local delta of modification of TRACKING frame of its PARENT; @@ -237,18 +237,18 @@ void AliAlgVol::getDeltaT2LmodTRA(TGeoHMatrix& matMod, const double* delta, cons } //_________________________________________________________ -int AliAlgVol::countParents() const +int AlignableVolume::countParents() const { // count parents in the chain int cnt = 0; - const AliAlgVol* p = this; + const AlignableVolume* p = this; while ((p = p->getParent())) cnt++; return cnt; } //____________________________________________ -void AliAlgVol::Print(const Option_t* opt) const +void AlignableVolume::Print(const Option_t* opt) const { // print info TString opts = opt; @@ -298,7 +298,7 @@ void AliAlgVol::Print(const Option_t* opt) const } //____________________________________________ -void AliAlgVol::prepareMatrixL2G(bool reco) +void AlignableVolume::prepareMatrixL2G(bool reco) { // extract from geometry L2G matrix, depending on reco flag, set it as a reco-time // or current alignment matrix @@ -326,7 +326,7 @@ void AliAlgVol::prepareMatrixL2G(bool reco) } //____________________________________________ -void AliAlgVol::prepareMatrixL2GIdeal() +void AlignableVolume::prepareMatrixL2GIdeal() { // extract from geometry ideal L2G matrix TGeoHMatrix mtmp; @@ -336,7 +336,7 @@ void AliAlgVol::prepareMatrixL2GIdeal() } //____________________________________________ -void AliAlgVol::prepareMatrixT2L() +void AlignableVolume::prepareMatrixT2L() { // for non-sensors we define the fake tracking frame with the alpha angle being // the average angle of centers of its children @@ -344,7 +344,7 @@ void AliAlgVol::prepareMatrixT2L() double tot[3] = {0, 0, 0}, loc[3] = {0, 0, 0}, glo[3]; int nch = getNChildren(); for (int ich = nch; ich--;) { - AliAlgVol* vol = getChild(ich); + AlignableVolume* vol = getChild(ich); vol->getMatrixL2GIdeal().LocalToMaster(loc, glo); for (int j = 3; j--;) tot[j] += glo[j]; @@ -354,7 +354,7 @@ void AliAlgVol::prepareMatrixT2L() tot[j] /= nch; // mAlp = TMath::ATan2(tot[1], tot[0]); - AliAlgAux::bringToPiPM(mAlp); + utils::bringToPiPM(mAlp); // mX = TMath::Sqrt(tot[0] * tot[0] + tot[1] * tot[1]); // @@ -369,7 +369,7 @@ void AliAlgVol::prepareMatrixT2L() } //____________________________________________ -void AliAlgVol::setMatrixT2L(const TGeoHMatrix& m) +void AlignableVolume::setMatrixT2L(const TGeoHMatrix& m) { // set the T2L matrix and define tracking frame // Note that this method is used for the externally set matrices @@ -380,7 +380,7 @@ void AliAlgVol::setMatrixT2L(const TGeoHMatrix& m) } //__________________________________________________________________ -void AliAlgVol::setTrackingFrame() +void AlignableVolume::setTrackingFrame() { // Define tracking frame of the sensor // This method should be implemented for sensors, which receive the T2L @@ -389,7 +389,7 @@ void AliAlgVol::setTrackingFrame() } //__________________________________________________________________ -void AliAlgVol::assignDOFs(int& cntDOFs, float* pars, float* errs, int* labs) +void AlignableVolume::assignDOFs(int& cntDOFs, float* pars, float* errs, int* labs) { // Assigns offset of the DOFS of this volume in global array of DOFs, attaches arrays to volumes // @@ -409,7 +409,7 @@ void AliAlgVol::assignDOFs(int& cntDOFs, float* pars, float* errs, int* labs) } //__________________________________________________________________ -void AliAlgVol::initDOFs() +void AlignableVolume::initDOFs() { // initialize degrees of freedom // @@ -424,7 +424,7 @@ void AliAlgVol::initDOFs() } //__________________________________________________________________ -void AliAlgVol::calcFree(bool condFix) +void AlignableVolume::calcFree(bool condFix) { // calculate free dofs. If condFix==true, condition parameter a la pede, i.e. error < 0 mNDOFFree = mNDOFGeomFree = 0; @@ -442,7 +442,7 @@ void AliAlgVol::calcFree(bool condFix) } //__________________________________________________________________ -void AliAlgVol::setNDOFs(int n) +void AlignableVolume::setNDOFs(int n) { // book global degrees of freedom if (n < kNDOFGeom) @@ -451,7 +451,7 @@ void AliAlgVol::setNDOFs(int n) } //__________________________________________________________________ -void AliAlgVol::addChild(AliAlgVol* ch) +void AlignableVolume::addChild(AlignableVolume* ch) { // add child volume if (!mChildren) { @@ -462,7 +462,7 @@ void AliAlgVol::addChild(AliAlgVol* ch) } //__________________________________________________________________ -void AliAlgVol::setParVals(int npar, double* vl, double* er) +void AlignableVolume::setParVals(int npar, double* vl, double* er) { // set parameters if (npar > mNDOFs) @@ -474,19 +474,19 @@ void AliAlgVol::setParVals(int npar, double* vl, double* er) } //__________________________________________________________________ -bool AliAlgVol::isCondDOF(int i) const +bool AlignableVolume::isCondDOF(int i) const { // is DOF free and conditioned? return (!isZeroAbs(getParVal(i)) || !isZeroAbs(getParErr(i))); } //______________________________________________________ -int AliAlgVol::finalizeStat(AliAlgDOFStat* st) +int AlignableVolume::finalizeStat(DOFStatistics* st) { // finalize statistics on processed points mNProcPoints = 0; for (int ich = getNChildren(); ich--;) { - AliAlgVol* child = getChild(ich); + AlignableVolume* child = getChild(ich); mNProcPoints += child->finalizeStat(st); } if (st) @@ -495,7 +495,7 @@ int AliAlgVol::finalizeStat(AliAlgDOFStat* st) } //______________________________________________________ -void AliAlgVol::writePedeInfo(FILE* parOut, const Option_t* opt) const +void AlignableVolume::writePedeInfo(FILE* parOut, const Option_t* opt) const { // contribute to params template file for PEDE enum { kOff, @@ -556,7 +556,7 @@ void AliAlgVol::writePedeInfo(FILE* parOut, const Option_t* opt) const } //_________________________________________________________________ -void AliAlgVol::createGloDeltaMatrix(TGeoHMatrix& deltaM) const +void AlignableVolume::createGloDeltaMatrix(TGeoHMatrix& deltaM) const { // Create global matrix deltaM from mParVals array containing corrections. // This deltaM does not account for eventual prealignment @@ -572,7 +572,7 @@ void AliAlgVol::createGloDeltaMatrix(TGeoHMatrix& deltaM) const /* //_________________________________________________________________ -void AliAlgVol::createGloDeltaMatrix(TGeoHMatrix &deltaM) const +void AlignableVolume::createGloDeltaMatrix(TGeoHMatrix &deltaM) const { // Create global matrix deltaM from mParVals array containing corrections. // This deltaM does not account for eventual prealignment @@ -585,7 +585,7 @@ void AliAlgVol::createGloDeltaMatrix(TGeoHMatrix &deltaM) const // createLocDeltaMatrix(deltaM); TGeoHMatrix zMat = getMatrixL2G(); - const AliAlgVol* par = this; + const AlignableVolume* par = this; while( (par=par->getParent()) ) { TGeoHMatrix locP; par->createLocDeltaMatrix(locP); @@ -600,7 +600,7 @@ void AliAlgVol::createGloDeltaMatrix(TGeoHMatrix &deltaM) const */ //_________________________________________________________________ -void AliAlgVol::createPreGloDeltaMatrix(TGeoHMatrix& deltaM) const +void AlignableVolume::createPreGloDeltaMatrix(TGeoHMatrix& deltaM) const { // Create prealignment global matrix deltaM from prealigned G and // original GO local-to-global matrices @@ -612,7 +612,7 @@ void AliAlgVol::createPreGloDeltaMatrix(TGeoHMatrix& deltaM) const // deltaM = getMatrixL2G(); deltaM *= getMatrixL2GIdeal().Inverse(); - const AliAlgVol* par = getParent(); + const AlignableVolume* par = getParent(); if (par) { deltaM *= par->getMatrixL2GIdeal(); deltaM *= par->getMatrixL2G().Inverse(); @@ -623,7 +623,7 @@ void AliAlgVol::createPreGloDeltaMatrix(TGeoHMatrix& deltaM) const /* // this is an alternative lengthy way ! //_________________________________________________________________ -void AliAlgVol::createPreGloDeltaMatrix(TGeoHMatrix &deltaM) const +void AlignableVolume::createPreGloDeltaMatrix(TGeoHMatrix &deltaM) const { // Create prealignment global matrix deltaM from prealigned G and // original GO local-to-global matrices @@ -635,7 +635,7 @@ void AliAlgVol::createPreGloDeltaMatrix(TGeoHMatrix &deltaM) const // createPreLocDeltaMatrix(deltaM); TGeoHMatrix zMat = getMatrixL2GIdeal(); - const AliAlgVol* par = this; + const AlignableVolume* par = this; while( (par=par->getParent()) ) { TGeoHMatrix locP; par->createPreLocDeltaMatrix(locP); @@ -650,7 +650,7 @@ void AliAlgVol::createPreGloDeltaMatrix(TGeoHMatrix &deltaM) const */ //_________________________________________________________________ -void AliAlgVol::createPreLocDeltaMatrix(TGeoHMatrix& deltaM) const +void AlignableVolume::createPreLocDeltaMatrix(TGeoHMatrix& deltaM) const { // Create prealignment local matrix deltaM from prealigned G and // original GO local-to-global matrices @@ -660,7 +660,7 @@ void AliAlgVol::createPreLocDeltaMatrix(TGeoHMatrix& deltaM) const // we get by induction // delta_j = GO^-1_j * GO_{j-1} * G^-1_{j-1} * G^_{j} // - const AliAlgVol* par = getParent(); + const AlignableVolume* par = getParent(); deltaM = getMatrixL2GIdeal().Inverse(); if (par) { deltaM *= par->getMatrixL2GIdeal(); @@ -671,7 +671,7 @@ void AliAlgVol::createPreLocDeltaMatrix(TGeoHMatrix& deltaM) const } //_________________________________________________________________ -void AliAlgVol::createLocDeltaMatrix(TGeoHMatrix& deltaM) const +void AlignableVolume::createLocDeltaMatrix(TGeoHMatrix& deltaM) const { // Create local matrix deltaM from mParVals array containing corrections. // This deltaM does not account for eventual prealignment @@ -692,7 +692,7 @@ void AliAlgVol::createLocDeltaMatrix(TGeoHMatrix& deltaM) const } //_________________________________________________________________ -void AliAlgVol::createAlignmenMatrix(TGeoHMatrix& alg) const +void AlignableVolume::createAlignmenMatrix(TGeoHMatrix& alg) const { // create final alignment matrix, accounting for eventual prealignment // @@ -708,7 +708,7 @@ void AliAlgVol::createAlignmenMatrix(TGeoHMatrix& alg) const // createGloDeltaMatrix(alg); // - const AliAlgVol* par = getParent(); + const AlignableVolume* par = getParent(); if (par) { TGeoHMatrix dchain; while (par) { @@ -733,7 +733,7 @@ void AliAlgVol::createAlignmenMatrix(TGeoHMatrix& alg) const /* //_________________________________________________________________ -void AliAlgVol::createAlignmenMatrix(TGeoHMatrix& alg) const +void AlignableVolume::createAlignmenMatrix(TGeoHMatrix& alg) const { // create final alignment matrix, accounting for eventual prealignment // @@ -747,7 +747,7 @@ void AliAlgVol::createAlignmenMatrix(TGeoHMatrix& alg) const TGeoHMatrix delGloPre,matX; createGloDeltaMatrix(alg); createPreGloDeltaMatrix(delGloPre); - const AliAlgVol* par = this; + const AlignableVolume* par = this; while( (par=par->getParent()) ) { TGeoHMatrix parDelGlo; par->createGloDeltaMatrix(parDelGlo); @@ -761,7 +761,7 @@ void AliAlgVol::createAlignmenMatrix(TGeoHMatrix& alg) const */ //_________________________________________________________________ -void AliAlgVol::createAlignmentObjects(TClonesArray* arr) const +void AlignableVolume::createAlignmentObjects(TClonesArray* arr) const { // add to supplied array alignment object for itself and children TClonesArray& parr = *arr; @@ -779,7 +779,7 @@ void AliAlgVol::createAlignmentObjects(TClonesArray* arr) const } //_________________________________________________________________ -void AliAlgVol::updateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta) +void AlignableVolume::updateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta) { // recreate mMatL2GReco matrices from ideal L2G matrix and alignment objects // used during data reconstruction. For the volume at level J we have @@ -813,14 +813,14 @@ void AliAlgVol::updateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMat } //______________________________________________________ -bool AliAlgVol::ownsDOFID(int id) const +bool AlignableVolume::ownsDOFID(int id) const { // check if DOF ID belongs to this volume or its children if (id >= mFirstParGloID && id < mFirstParGloID + mNDOFs) return true; // for (int iv = getNChildren(); iv--;) { - AliAlgVol* vol = getChild(iv); + AlignableVolume* vol = getChild(iv); if (vol->ownsDOFID(id)) return true; } @@ -828,14 +828,14 @@ bool AliAlgVol::ownsDOFID(int id) const } //______________________________________________________ -AliAlgVol* AliAlgVol::getVolOfDOFID(int id) const +AlignableVolume* AlignableVolume::getVolOfDOFID(int id) const { // gets volume owning this DOF ID if (id >= mFirstParGloID && id < mFirstParGloID + mNDOFs) - return (AliAlgVol*)this; + return (AlignableVolume*)this; // for (int iv = getNChildren(); iv--;) { - AliAlgVol* vol = getChild(iv); + AlignableVolume* vol = getChild(iv); if ((vol = vol->getVolOfDOFID(id))) return vol; } @@ -843,14 +843,14 @@ AliAlgVol* AliAlgVol::getVolOfDOFID(int id) const } //______________________________________________________ -const char* AliAlgVol::getDOFName(int i) const +const char* AlignableVolume::getDOFName(int i) const { // get name of DOF return getGeomDOFName(i); } //______________________________________________________ -void AliAlgVol::fillDOFStat(AliAlgDOFStat* h) const +void AlignableVolume::fillDOFStat(DOFStatistics* h) const { // fill statistics info hist if (!h) @@ -865,17 +865,17 @@ void AliAlgVol::fillDOFStat(AliAlgDOFStat* h) const } //________________________________________ -void AliAlgVol::addAutoConstraints(TObjArray* constrArr) +void AlignableVolume::addAutoConstraints(TObjArray* constrArr) { // adds automatic constraints int nch = getNChildren(); // if (hasChildrenConstraint()) { - AliAlgConstraint* constr = new AliAlgConstraint(); + GeometricalConstraint* constr = new GeometricalConstraint(); constr->setConstrainPattern(mConstrChild); constr->setParent(this); for (int ich = nch; ich--;) { - AliAlgVol* child = getChild(ich); + AlignableVolume* child = getChild(ich); if (child->getExcludeFromParentConstraint()) continue; constr->addChild(child); diff --git a/Detectors/Align/src/AliAlgPoint.cxx b/Detectors/Align/src/AlignmentPoint.cxx similarity index 91% rename from Detectors/Align/src/AliAlgPoint.cxx rename to Detectors/Align/src/AlignmentPoint.cxx index 4dffba1748c84..29af7a222d3bb 100644 --- a/Detectors/Align/src/AliAlgPoint.cxx +++ b/Detectors/Align/src/AlignmentPoint.cxx @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgPoint.h +/// @file AlignmentPoint.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Meausered point in the sensor. @@ -16,9 +16,9 @@ #include #include #include -#include "Align/AliAlgPoint.h" +#include "Align/AlignmentPoint.h" -using namespace o2::align::AliAlgAux; +using namespace o2::align::utils; using namespace TMath; namespace o2 @@ -27,7 +27,7 @@ namespace align { //_____________________________________ -AliAlgPoint::AliAlgPoint() +AlignmentPoint::AlignmentPoint() : mMinLocVarID(0), mMaxLocVarID(0), mDetID(-1), mSID(-1), mAlphaSens(0), mXSens(0), mCosDiagErr(0), mSinDiagErr(0), mX2X0(0), mXTimesRho(0), mNGloDOFs(0), mDGloOffs(0), mSensor(0) { // def c-tor @@ -45,7 +45,7 @@ AliAlgPoint::AliAlgPoint() } //_____________________________________ -void AliAlgPoint::init() +void AlignmentPoint::init() { // compute aux info const double kCorrToler = 1e-6; @@ -88,14 +88,14 @@ void AliAlgPoint::init() } //_____________________________________ -void AliAlgPoint::updatePointByTrackInfo(const trackParam_t* t) +void AlignmentPoint::updatePointByTrackInfo(const trackParam_t* t) { // // recalculate point errors using info about the track in the sensor tracking frame mSensor->updatePointByTrackInfo(this, t); } //_____________________________________ -void AliAlgPoint::Print(Option_t* opt) const +void AlignmentPoint::Print(Option_t* opt) const { // print TString opts = opt; @@ -170,7 +170,7 @@ void AliAlgPoint::Print(Option_t* opt) const } //_____________________________________ -void AliAlgPoint::dumpCoordinates() const +void AlignmentPoint::dumpCoordinates() const { // dump various corrdinates for inspection // global xyz @@ -208,7 +208,7 @@ void AliAlgPoint::dumpCoordinates() const } //_____________________________________ -void AliAlgPoint::Clear(Option_t*) +void AlignmentPoint::Clear(Option_t*) { // reset the point ResetBit(0xfffffff); @@ -221,13 +221,13 @@ void AliAlgPoint::Clear(Option_t*) } //__________________________________________________________________ -int AliAlgPoint::Compare(const TObject* b) const +int AlignmentPoint::Compare(const TObject* b) const { // sort points in direction opposite to track propagation, i.e. // 1) for tracks from collision: range in decreasing tracking X // 2) for cosmic tracks: upper leg (pnt->isInvDir()==true) ranged in increasing X // lower leg - in decreasing X - AliAlgPoint* pnt = (AliAlgPoint*)b; + AlignmentPoint* pnt = (AlignmentPoint*)b; double x = getXPoint(); double xp = pnt->getXPoint(); if (!isInvDir()) { // track propagates from low to large X via this point @@ -245,7 +245,7 @@ int AliAlgPoint::Compare(const TObject* b) const } //__________________________________________________________________ -void AliAlgPoint::getXYZGlo(double r[3]) const +void AlignmentPoint::getXYZGlo(double r[3]) const { // position in lab frame double cs = TMath::Cos(mAlphaSens); @@ -258,7 +258,7 @@ void AliAlgPoint::getXYZGlo(double r[3]) const } //__________________________________________________________________ -double AliAlgPoint::getPhiGlo() const +double AlignmentPoint::getPhiGlo() const { // phi angle (-pi:pi) in global frame double xyz[3]; @@ -267,14 +267,14 @@ double AliAlgPoint::getPhiGlo() const } //__________________________________________________________________ -int AliAlgPoint::getAliceSector() const +int AlignmentPoint::getAliceSector() const { // get global sector ID corresponding to this point phi return phi2Sector(getPhiGlo()); } //__________________________________________________________________ -void AliAlgPoint::setMatCovDiagonalizationMatrix(const TMatrixD& d) +void AlignmentPoint::setMatCovDiagonalizationMatrix(const TMatrixD& d) { // save non-sym matrix for material corrections cov.matrix diagonalization // (actually, the eigenvectors are stored) @@ -285,7 +285,7 @@ void AliAlgPoint::setMatCovDiagonalizationMatrix(const TMatrixD& d) } //__________________________________________________________________ -void AliAlgPoint::setMatCovDiag(const TVectorD& v) +void AlignmentPoint::setMatCovDiag(const TVectorD& v) { // save material correction diagonalized matrix // (actually, the eigenvalues are stored w/o reordering them to correspond to the @@ -295,7 +295,7 @@ void AliAlgPoint::setMatCovDiag(const TVectorD& v) } //__________________________________________________________________ -void AliAlgPoint::unDiagMatCorr(const double* diag, double* nodiag) const +void AlignmentPoint::unDiagMatCorr(const double* diag, double* nodiag) const { // transform material corrections from the frame diagonalizing the errors to point frame // nodiag = mMatDiag * diag @@ -310,7 +310,7 @@ void AliAlgPoint::unDiagMatCorr(const double* diag, double* nodiag) const } //__________________________________________________________________ -void AliAlgPoint::unDiagMatCorr(const float* diag, float* nodiag) const +void AlignmentPoint::unDiagMatCorr(const float* diag, float* nodiag) const { // transform material corrections from the frame diagonalizing the errors to point frame // nodiag = mMatDiag * diag @@ -325,7 +325,7 @@ void AliAlgPoint::unDiagMatCorr(const float* diag, float* nodiag) const } //__________________________________________________________________ -void AliAlgPoint::diagMatCorr(const double* nodiag, double* diag) const +void AlignmentPoint::diagMatCorr(const double* nodiag, double* diag) const { // transform material corrections from the AliExternalTrackParam frame to // the frame diagonalizing the errors @@ -341,7 +341,7 @@ void AliAlgPoint::diagMatCorr(const double* nodiag, double* diag) const } //__________________________________________________________________ -void AliAlgPoint::diagMatCorr(const float* nodiag, float* diag) const +void AlignmentPoint::diagMatCorr(const float* nodiag, float* diag) const { // transform material corrections from the AliExternalTrackParam frame to // the frame diagonalizing the errors @@ -357,7 +357,7 @@ void AliAlgPoint::diagMatCorr(const float* nodiag, float* diag) const } //__________________________________________________________________ -void AliAlgPoint::getTrWSA(trackParam_t& etp) const +void AlignmentPoint::getTrWSA(trackParam_t& etp) const { // assign WSA (after material corrections) parameters to supplied track const trackParam_t::covMat_t covDum{ @@ -373,7 +373,7 @@ void AliAlgPoint::getTrWSA(trackParam_t& etp) const } //__________________________________________________________________ -void AliAlgPoint::getTrWSB(trackParam_t& etp) const +void AlignmentPoint::getTrWSB(trackParam_t& etp) const { // assign WSB parameters (before material corrections) to supplied track const trackParam_t::covMat_t covDum{ diff --git a/Detectors/Align/src/AliAlgTrack.cxx b/Detectors/Align/src/AlignmentTrack.cxx similarity index 91% rename from Detectors/Align/src/AliAlgTrack.cxx rename to Detectors/Align/src/AlignmentTrack.cxx index 9fcbce3ccfc2f..2fc934de7380b 100644 --- a/Detectors/Align/src/AliAlgTrack.cxx +++ b/Detectors/Align/src/AlignmentTrack.cxx @@ -8,23 +8,23 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgTrack.h +/// @file AlignmentTrack.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Track model for the alignment #include -#include "Align/AliAlgTrack.h" +#include "Align/AlignmentTrack.h" #include "Framework/Logger.h" -#include "Align/AliAlgSens.h" -#include "Align/AliAlgVol.h" -#include "Align/AliAlgDet.h" -#include "Align/AliAlgAux.h" +#include "Align/AlignableSensor.h" +#include "Align/AlignableVolume.h" +#include "Align/AlignableDetector.h" +#include "Align/utils.h" #include #include #include -using namespace o2::align::AliAlgAux; +using namespace o2::align::utils; using namespace TMath; namespace o2 @@ -39,20 +39,20 @@ const int kRichardsonN = kRichardsonOrd + 1; // N of 2-point symmetric derivativ const int kNRDClones = kRichardsonN * 2; // number of variations for derivative of requested order //____________________________________________________________________________ -AliAlgTrack::AliAlgTrack() : TrackParametrizationWithError(), TObject(), mNLocPar(0), mNLocExtPar(0), mNGloPar(0), mNDF(0), mInnerPointID(0) - // ,mMinX2X0Pt2Account(5/1.0) - , - mMinX2X0Pt2Account(0.5e-3 / 1.0), - mMass(0.14), - mChi2(0), - mChi2CosmUp(0), - mChi2CosmDn(0), - mChi2Ini(0), - mPoints(0), - mLocPar(), - mGloParID(0), - mGloParIDA(0), - mLocParA(0) +AlignmentTrack::AlignmentTrack() : TrackParametrizationWithError(), TObject(), mNLocPar(0), mNLocExtPar(0), mNGloPar(0), mNDF(0), mInnerPointID(0) + // ,mMinX2X0Pt2Account(5/1.0) + , + mMinX2X0Pt2Account(0.5e-3 / 1.0), + mMass(0.14), + mChi2(0), + mChi2CosmUp(0), + mChi2CosmDn(0), + mChi2Ini(0), + mPoints(0), + mLocPar(), + mGloParID(0), + mGloParIDA(0), + mLocParA(0) { // def c-tor for (int i = 0; i < 2; i++) { @@ -70,13 +70,13 @@ AliAlgTrack::AliAlgTrack() : TrackParametrizationWithError(), TObject(), } //____________________________________________________________________________ -AliAlgTrack::~AliAlgTrack() +AlignmentTrack::~AlignmentTrack() { // d-tor } //____________________________________________________________________________ -void AliAlgTrack::Clear(Option_t*) +void AlignmentTrack::Clear(Option_t*) { // reset the track TObject::Clear(); @@ -91,7 +91,7 @@ void AliAlgTrack::Clear(Option_t*) } //____________________________________________________________________________ -void AliAlgTrack::defineDOFs() +void AlignmentTrack::defineDOFs() { // define varied DOF's (local parameters) for the track: // 1) kinematic params (5 or 4 depending on Bfield) @@ -107,7 +107,7 @@ void AliAlgTrack::defineDOFs() // start along track direction, i.e. last point in the ordered array int minPar = mNLocPar; for (int ip = getInnerPointID() + 1; ip--;) { // collision track or cosmic lower leg - AliAlgPoint* pnt = getPoint(ip); + AlignmentPoint* pnt = getPoint(ip); pnt->setMinLocVarID(minPar); if (pnt->containsMaterial()) mNLocPar += pnt->getNMatPar(); @@ -117,7 +117,7 @@ void AliAlgTrack::defineDOFs() if (isCosmic()) { minPar = mNLocPar; for (int ip = getInnerPointID() + 1; ip < np; ip++) { // collision track or cosmic lower leg - AliAlgPoint* pnt = getPoint(ip); + AlignmentPoint* pnt = getPoint(ip); pnt->setMinLocVarID(minPar); if (pnt->containsMaterial()) mNLocPar += pnt->getNMatPar(); @@ -150,7 +150,7 @@ void AliAlgTrack::defineDOFs() } //______________________________________________________ -bool AliAlgTrack::calcResidDeriv(double* params) +bool AlignmentTrack::calcResidDeriv(double* params) { // Propagate for given local params and calculate residuals and their derivatives. // The 1st 4 or 5 elements of params vector should be the reference trackParam_t @@ -192,7 +192,7 @@ bool AliAlgTrack::calcResidDeriv(double* params) } //______________________________________________________ -bool AliAlgTrack::calcResidDeriv(double* extendedParams, bool invert, int pFrom, int pTo) +bool AlignmentTrack::calcResidDeriv(double* extendedParams, bool invert, int pFrom, int pTo) { // Calculate derivatives of residuals vs params for points pFrom to pT. For cosmic upper leg // track parameter may require inversion. @@ -245,7 +245,7 @@ bool AliAlgTrack::calcResidDeriv(double* extendedParams, bool invert, int pFrom, } // propagate varied tracks to each point for (int ip = pFrom; ip != pTo; ip += pinc) { // points are ordered against track direction - AliAlgPoint* pnt = getPoint(ip); + AlignmentPoint* pnt = getPoint(ip); if (!propagateParamToPoint(probD, kNRDClones, pnt)) return false; // if (pnt->containsMaterial()) { // apply material corrections @@ -267,7 +267,7 @@ bool AliAlgTrack::calcResidDeriv(double* extendedParams, bool invert, int pFrom, // 2) now vary material effect related parameters: MS and eventually ELoss // for (int ip = pFrom; ip != pTo; ip += pinc) { // points are ordered against track direction - AliAlgPoint* pnt = getPoint(ip); + AlignmentPoint* pnt = getPoint(ip); // // global derivatives at this point if (pnt->containsMeasurement() && !calcResidDerivGlo(pnt)) { @@ -330,7 +330,7 @@ bool AliAlgTrack::calcResidDeriv(double* extendedParams, bool invert, int pFrom, // // loop over points whose residuals can be affected by the material effects on point ip for (int jp = ip + pinc; jp != pTo; jp += pinc) { - AliAlgPoint* pntJ = getPoint(jp); + AlignmentPoint* pntJ = getPoint(jp); // printf(" DerFor:%d ",jp); pntJ->print(); @@ -356,13 +356,13 @@ bool AliAlgTrack::calcResidDeriv(double* extendedParams, bool invert, int pFrom, } //______________________________________________________ -bool AliAlgTrack::calcResidDerivGlo(AliAlgPoint* pnt) +bool AlignmentTrack::calcResidDerivGlo(AlignmentPoint* pnt) { // calculate residuals derivatives over point's sensor and its parents global params - double deriv[AliAlgVol::kNDOFGeom * 3]; + double deriv[AlignableVolume::kNDOFGeom * 3]; // - const AliAlgSens* sens = pnt->getSensor(); - const AliAlgVol* vol = sens; + const AlignableSensor* sens = pnt->getSensor(); + const AlignableVolume* vol = sens; // precalculated track parameters double snp = pnt->getTrParamWSA(kParSnp), tgl = pnt->getTrParamWSA(kParTgl); // precalculate track slopes to account tracking X veriation @@ -379,7 +379,7 @@ bool AliAlgTrack::calcResidDerivGlo(AliAlgPoint* pnt) // checkExpandDerGloBuffer(mNGloPar + nfree); // if needed, expand derivatives buffer // - for (int ip = 0; ip < AliAlgVol::kNDOFGeom; ip++) { // we need only free parameters + for (int ip = 0; ip < AlignableVolume::kNDOFGeom; ip++) { // we need only free parameters if (!vol->isFreeDOF(ip)) continue; double* dXYZ = &deriv[ip * 3]; // tracking XYZ derivatives over this parameter @@ -390,8 +390,8 @@ bool AliAlgTrack::calcResidDerivGlo(AliAlgPoint* pnt) // effect of changing X is accounted neglecting track curvature to preserve linearity // // store diagonalized residuals in track buffer - pnt->diagonalizeResiduals((dXYZ[AliAlgPoint::kX] * slpY - dXYZ[AliAlgPoint::kY]), - (dXYZ[AliAlgPoint::kX] * slpZ - dXYZ[AliAlgPoint::kZ]), + pnt->diagonalizeResiduals((dXYZ[AlignmentPoint::kX] * slpY - dXYZ[AlignmentPoint::kY]), + (dXYZ[AlignmentPoint::kX] * slpZ - dXYZ[AlignmentPoint::kZ]), mDResDGloA[0][mNGloPar], mDResDGloA[1][mNGloPar]); // and register global ID of varied parameter mGloParIDA[mNGloPar] = vol->getParGloID(ip); @@ -401,7 +401,7 @@ bool AliAlgTrack::calcResidDerivGlo(AliAlgPoint* pnt) } while ((vol = vol->getParent())); // // eventual detector calibration parameters - const AliAlgDet* det = sens->getDetector(); + const AlignableDetector* det = sens->getDetector(); int ndof = 0; if (det && (ndof = det->getNCalibDOFs())) { // if needed, expand derivatives buffer @@ -410,8 +410,8 @@ bool AliAlgTrack::calcResidDerivGlo(AliAlgPoint* pnt) if (!det->isFreeDOF(idf)) continue; sens->dPosTraDParCalib(pnt, deriv, idf, 0); - pnt->diagonalizeResiduals((deriv[AliAlgPoint::kX] * slpY - deriv[AliAlgPoint::kY]), - (deriv[AliAlgPoint::kX] * slpZ - deriv[AliAlgPoint::kZ]), + pnt->diagonalizeResiduals((deriv[AlignmentPoint::kX] * slpY - deriv[AlignmentPoint::kY]), + (deriv[AlignmentPoint::kX] * slpZ - deriv[AlignmentPoint::kZ]), mDResDGloA[0][mNGloPar], mDResDGloA[1][mNGloPar]); // and register global ID of varied parameter mGloParIDA[mNGloPar] = det->getParGloID(idf); @@ -425,7 +425,7 @@ bool AliAlgTrack::calcResidDerivGlo(AliAlgPoint* pnt) } //______________________________________________________ -bool AliAlgTrack::calcResiduals(const double* extendedParams) +bool AlignmentTrack::calcResiduals(const double* extendedParams) { // Propagate for given local params and calculate residuals // The 1st 4 or 5 elements of extendedParams vector should be the reference trackParam_t @@ -467,7 +467,7 @@ bool AliAlgTrack::calcResiduals(const double* extendedParams) } //______________________________________________________ -bool AliAlgTrack::calcResiduals(const double* extendedParams, bool invert, int pFrom, int pTo) +bool AlignmentTrack::calcResiduals(const double* extendedParams, bool invert, int pFrom, int pTo) { // Calculate residuals for the single leg from points pFrom to pT // The 1st 4 or 5 elements of extendedParams vector should be corrections to @@ -493,7 +493,7 @@ bool AliAlgTrack::calcResiduals(const double* extendedParams, bool invert, int p } // for (int ip = pFrom; ip != pTo; ip += pinc) { // points are ordered against track direction - AliAlgPoint* pnt = getPoint(ip); + AlignmentPoint* pnt = getPoint(ip); if (!propagateParamToPoint(probe, pnt)) return false; // @@ -528,7 +528,7 @@ bool AliAlgTrack::calcResiduals(const double* extendedParams, bool invert, int p } //______________________________________________________ -bool AliAlgTrack::propagateParamToPoint(trackParam_t* tr, int nTr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt) +bool AlignmentTrack::propagateParamToPoint(trackParam_t* tr, int nTr, const AlignmentPoint* pnt, double maxStep, double maxSnp, MatCorrType mt) { // Propagate set of tracks to the point (only parameters, no error matrix) // VECTORIZE this @@ -547,21 +547,21 @@ bool AliAlgTrack::propagateParamToPoint(trackParam_t* tr, int nTr, const AliAlgP } //______________________________________________________ -bool AliAlgTrack::propagateParamToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt) +bool AlignmentTrack::propagateParamToPoint(trackParam_t& tr, const AlignmentPoint* pnt, double maxStep, double maxSnp, MatCorrType mt) { // propagate tracks to the point (only parameters, no error matrix) return propagate(tr, pnt, maxStep, maxSnp, mt, nullptr); } //______________________________________________________ -bool AliAlgTrack::propagateToPoint(trackParam_t& tr, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT) +bool AlignmentTrack::propagateToPoint(trackParam_t& tr, const AlignmentPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT) { // propagate tracks to the point. If matCor is true, then material corrections will be applied. // if matPar pointer is provided, it will be filled by total x2x0 and signed xrho return propagate(tr, pnt, maxStep, maxSnp, mt, tLT); } -bool AliAlgTrack::propagate(trackParam_t& track, const AliAlgPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT) +bool AlignmentTrack::propagate(trackParam_t& track, const AlignmentPoint* pnt, double maxStep, double maxSnp, MatCorrType mt, track::TrackLTIntegral* tLT) { if (!track.rotate(pnt->getAlphaSens())) { #if DEBUG > 3 @@ -588,7 +588,7 @@ bool AliAlgTrack::propagate(trackParam_t& track, const AliAlgPoint* pnt, double /* //______________________________________________________ -bool AliAlgTrack::ApplyMS(trackParam_t& trPar, double tms,double pms) +bool AlignmentTrack::ApplyMS(trackParam_t& trPar, double tms,double pms) { //------------------------------------------------------------------------------ // Modify track par (e.g. trackParam_t) in the tracking frame @@ -632,7 +632,7 @@ bool AliAlgTrack::ApplyMS(trackParam_t& trPar, double tms,double pms) */ //______________________________________________________ -bool AliAlgTrack::applyMatCorr(trackParam_t& trPar, const double* corrPar, const AliAlgPoint* pnt) +bool AlignmentTrack::applyMatCorr(trackParam_t& trPar, const double* corrPar, const AlignmentPoint* pnt) { // Modify track param (e.g. trackParam_t) in the tracking frame // by delta accounting for material effects @@ -658,7 +658,7 @@ bool AliAlgTrack::applyMatCorr(trackParam_t& trPar, const double* corrPar, const } //______________________________________________________ -bool AliAlgTrack::applyMatCorr(trackParam_t& trPar, const double* corr) +bool AlignmentTrack::applyMatCorr(trackParam_t& trPar, const double* corr) { // Modify track param (e.g. trackParam_t) in the tracking frame // by delta accounting for material effects @@ -684,7 +684,7 @@ bool AliAlgTrack::applyMatCorr(trackParam_t& trPar, const double* corr) } //______________________________________________________ -bool AliAlgTrack::applyMatCorr(trackParam_t* trSet, int ntr, const double* corrDiag, const AliAlgPoint* pnt) +bool AlignmentTrack::applyMatCorr(trackParam_t* trSet, int ntr, const double* corrDiag, const AlignmentPoint* pnt) { // Modify set of track params (e.g. trackParam_t) in the tracking frame // by delta accounting for material effects @@ -718,7 +718,7 @@ bool AliAlgTrack::applyMatCorr(trackParam_t* trSet, int ntr, const double* corrD } //______________________________________________ -double AliAlgTrack::richardsonExtrap(double* val, int ord) +double AlignmentTrack::richardsonExtrap(double* val, int ord) { // Calculate Richardson extrapolation of order ord (starting from 1) // The array val should contain estimates ord+1 of derivatives with variations @@ -735,7 +735,7 @@ double AliAlgTrack::richardsonExtrap(double* val, int ord) } //______________________________________________ -double AliAlgTrack::richardsonExtrap(const double* val, int ord) +double AlignmentTrack::richardsonExtrap(const double* val, int ord) { // Calculate Richardson extrapolation of order ord (starting from 1) // The array val should contain estimates ord+1 of derivatives with variations @@ -754,7 +754,7 @@ double AliAlgTrack::richardsonExtrap(const double* val, int ord) } //______________________________________________ -void AliAlgTrack::richardsonDeriv(const trackParam_t* trSet, const double* delta, const AliAlgPoint* pnt, double& derY, double& derZ) +void AlignmentTrack::richardsonDeriv(const trackParam_t* trSet, const double* delta, const AlignmentPoint* pnt, double& derY, double& derZ) { // Calculate Richardson derivatives for diagonalized Y and Z from a set of kRichardsonN pairs // of tracks with same parameter of i-th pair varied by +-delta[i] @@ -773,7 +773,7 @@ void AliAlgTrack::richardsonDeriv(const trackParam_t* trSet, const double* delta } //______________________________________________ -void AliAlgTrack::Print(Option_t* opt) const +void AlignmentTrack::Print(Option_t* opt) const { // print track data printf("%s ", isCosmic() ? " Cosmic " : "Collision "); @@ -804,7 +804,7 @@ void AliAlgTrack::Print(Option_t* opt) const if (optS.Contains("p") || res || der) { for (int ip = 0; ip < getNPoints(); ip++) { printf("#%3d ", ip); - AliAlgPoint* pnt = getPoint(ip); + AlignmentPoint* pnt = getPoint(ip); pnt->Print(opt); // if (res && pnt->containsMeasurement()) { @@ -846,12 +846,12 @@ void AliAlgTrack::Print(Option_t* opt) const } //______________________________________________ -void AliAlgTrack::dumpCoordinates() const +void AlignmentTrack::dumpCoordinates() const { // print various coordinates for inspection printf("gpx/D:gpy/D:gpz/D:gtxb/D:gtyb/D:gtzb/D:gtxa/D:gtya/D:gtza/D:alp/D:px/D:py/D:pz/D:tyb/D:tzb/D:tya/D:tza/D:ey/D:ez/D\n"); for (int ip = 0; ip < getNPoints(); ip++) { - AliAlgPoint* pnt = getPoint(ip); + AlignmentPoint* pnt = getPoint(ip); if (!pnt->containsMeasurement()) continue; pnt->dumpCoordinates(); @@ -859,7 +859,7 @@ void AliAlgTrack::dumpCoordinates() const } //______________________________________________ -bool AliAlgTrack::iniFit() +bool AlignmentTrack::iniFit() { // perform initial fit of the track // @@ -896,7 +896,7 @@ bool AliAlgTrack::iniFit() } // // propagate to reference point, which is the inner point of lower leg - const AliAlgPoint* refP = getPoint(getInnerPointID()); + const AlignmentPoint* refP = getPoint(getInnerPointID()); if (!propagateToPoint(trcU, refP, MaxDefStep, MaxDefSnp, DefMatCorrType)) return false; // @@ -915,7 +915,7 @@ bool AliAlgTrack::iniFit() } //______________________________________________ -bool AliAlgTrack::combineTracks(trackParam_t& trcL, const trackParam_t& trcU) +bool AlignmentTrack::combineTracks(trackParam_t& trcL, const trackParam_t& trcU) { // Assign to trcL the combined tracks (Kalman update of trcL by trcU) // The trcL and trcU MUST be defined at same X,Alpha @@ -982,7 +982,7 @@ bool AliAlgTrack::combineTracks(trackParam_t& trcL, const trackParam_t& trcU) } //______________________________________________ -bool AliAlgTrack::fitLeg(trackParam_t& trc, int pFrom, int pTo, bool& inv) +bool AlignmentTrack::fitLeg(trackParam_t& trc, int pFrom, int pTo, bool& inv) { // perform initial fit of the track // the fit will always start from the outgoing track in inward direction (i.e. if cosmics - bottom leg) @@ -999,7 +999,7 @@ bool AliAlgTrack::fitLeg(trackParam_t& trc, int pFrom, int pTo, bool& inv) 0, 0, 0, 0, kErrRelPtI * kErrRelPtI}; // // prepare seed at outer point - AliAlgPoint* p0 = getPoint(pFrom); + AlignmentPoint* p0 = getPoint(pFrom); double phi = trc.getPhi(), alp = p0->getAlphaSens(); bringTo02Pi(phi); bringTo02Pi(alp); @@ -1041,7 +1041,7 @@ bool AliAlgTrack::fitLeg(trackParam_t& trc, int pFrom, int pTo, bool& inv) } // for (int ip = pFrom; ip != pTo; ip += pinc) { // inward fit from outer point - AliAlgPoint* pnt = getPoint(ip); + AlignmentPoint* pnt = getPoint(ip); // // printf("*** fitLeg %d (%d %d)\n",ip,pFrom,pTo); // printf("Before propagate: "); trc.print(); @@ -1078,7 +1078,7 @@ bool AliAlgTrack::fitLeg(trackParam_t& trc, int pFrom, int pTo, bool& inv) } //______________________________________________ -bool AliAlgTrack::residKalman() +bool AlignmentTrack::residKalman() { // calculate residuals from bi-directional Kalman smoother // ATTENTION: this method modifies workspaces of the points!!! @@ -1101,7 +1101,7 @@ bool AliAlgTrack::residKalman() // int pID = 0, nPnt = getNPoints(); ; - AliAlgPoint* pnt = 0; + AlignmentPoint* pnt = 0; // get 1st measured point while (pID < nPnt && !(pnt = getPoint(pID))->containsMeasurement()) pID++; @@ -1253,7 +1253,7 @@ bool AliAlgTrack::residKalman() } //______________________________________________ -bool AliAlgTrack::processMaterials() +bool AlignmentTrack::processMaterials() { // attach material effect info to alignment points trackParam_t trc = *this; @@ -1284,7 +1284,7 @@ bool AliAlgTrack::processMaterials() } //______________________________________________ -bool AliAlgTrack::processMaterials(trackParam_t& trc, int pFrom, int pTo) +bool AlignmentTrack::processMaterials(trackParam_t& trc, int pFrom, int pTo) { // attach material effect info to alignment points const int kMinNStep = 3; @@ -1328,7 +1328,7 @@ bool AliAlgTrack::processMaterials(trackParam_t& trc, int pFrom, int pTo) } // for (int ip = pFrom; ip != pTo; ip += pinc) { // points are ordered against track direction - AliAlgPoint* pnt = getPoint(ip); + AlignmentPoint* pnt = getPoint(ip); trc.setCov(kErrTiny); // assign tiny errors to both tracks tr0 = trc; // @@ -1414,7 +1414,7 @@ bool AliAlgTrack::processMaterials(trackParam_t& trc, int pFrom, int pTo) } //______________________________________________ -void AliAlgTrack::sortPoints() +void AlignmentTrack::sortPoints() { // sort points in order against track direction: innermost point is last // for collision tracks. @@ -1429,7 +1429,7 @@ void AliAlgTrack::sortPoints() mInnerPointID = np - 1; if (isCosmic()) { for (int ip = np; ip--;) { - AliAlgPoint* pnt = getPoint(ip); + AlignmentPoint* pnt = getPoint(ip); if (pnt->isInvDir()) continue; // this is a point of upper leg mInnerPointID = ip; @@ -1440,14 +1440,14 @@ void AliAlgTrack::sortPoints() } //______________________________________________ -void AliAlgTrack::setLocPars(const double* pars) +void AlignmentTrack::setLocPars(const double* pars) { // store loc par corrections memcpy(mLocParA, pars, mNLocPar * sizeof(double)); } //______________________________________________ -void AliAlgTrack::checkExpandDerGloBuffer(int minSize) +void AlignmentTrack::checkExpandDerGloBuffer(int minSize) { // if needed, expand global derivatives buffer if (mGloParID.GetSize() < minSize) { diff --git a/Detectors/Align/src/AliAlgSteer.cxx b/Detectors/Align/src/Controller.cxx similarity index 89% rename from Detectors/Align/src/AliAlgSteer.cxx rename to Detectors/Align/src/Controller.cxx index 4cd6fe7e84a40..a9f5fd5ceae98 100644 --- a/Detectors/Align/src/AliAlgSteer.cxx +++ b/Detectors/Align/src/Controller.cxx @@ -8,27 +8,27 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgSteer.h +/// @file Controller.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Steering class for the global alignment -#include "Align/AliAlgSteer.h" +#include "Align/Controller.h" #include "Framework/Logger.h" -#include "Align/AliAlgAux.h" -#include "Align/AliAlgPoint.h" -#include "Align/AliAlgDet.h" -#include "Align/AliAlgVol.h" -//#include "Align/AliAlgDetITS.h" -//#include "Align/AliAlgDetTPC.h" -//#include "Align/AliAlgDetTRD.h" -//#include "Align/AliAlgDetTOF.h" -#include "Align/AliAlgVtx.h" -#include "Align/AliAlgMPRecord.h" -#include "Align/AliAlgRes.h" -#include "Align/AliAlgResFast.h" -#include "Align/AliAlgConstraint.h" -#include "Align/AliAlgDOFStat.h" +#include "Align/utils.h" +#include "Align/AlignmentPoint.h" +#include "Align/AlignableDetector.h" +#include "Align/AlignableVolume.h" +//#include "Align/AlignableDetectorITS.h" +//#include "Align/AlignableDetectorTPC.h" +//#include "Align/AlignableDetectorTRD.h" +//#include "Align/AlignableDetectorTOF.h" +#include "Align/EventVertex.h" +#include "Align/Millepede2Record.h" +#include "Align/ResidualsController.h" +#include "Align/ResidualsControllerFast.h" +#include "Align/GeometricalConstraint.h" +#include "Align/DOFStatistics.h" //#include "AliTrackerBase.h" //#include "AliESDCosmicTrack.h" //#include "AliESDtrack.h" @@ -54,31 +54,31 @@ #include "DataFormatsParameters/GRPObject.h" using namespace TMath; -using namespace o2::align::AliAlgAux; +using namespace o2::align::utils; using std::ifstream; -ClassImp(o2::align::AliAlgSteer); +ClassImp(o2::align::Controller); namespace o2 { namespace align { -const Char_t* AliAlgSteer::sMPDataExt = ".mille"; -const Char_t* AliAlgSteer::sDetectorName[AliAlgSteer::kNDetectors] = {"ITS", "TPC", "TRD", "TOF", "HMPID"}; -//const int AliAlgSteer::mgkSkipLayers[AliAlgSteer::kNLrSkip] = {AliGeomManager::kPHOS1, AliGeomManager::kPHOS2, +const Char_t* Controller::sMPDataExt = ".mille"; +const Char_t* Controller::sDetectorName[Controller::kNDetectors] = {"ITS", "TPC", "TRD", "TOF", "HMPID"}; +//const int Controller::mgkSkipLayers[Controller::kNLrSkip] = {AliGeomManager::kPHOS1, AliGeomManager::kPHOS2, // AliGeomManager::kMUON, AliGeomManager::kEMCAL}; TODO(milettri, shahoian): needs detector IDs previously stored in AliGeomManager -const int AliAlgSteer::sSkipLayers[AliAlgSteer::kNLrSkip] = {0, 0, 0, 0}; // TODO(milettri, shahoian): needs AliGeomManager - remove this line after fix. +const int Controller::sSkipLayers[Controller::kNLrSkip] = {0, 0, 0, 0}; // TODO(milettri, shahoian): needs AliGeomManager - remove this line after fix. -const Char_t* AliAlgSteer::sStatClName[AliAlgSteer::kNStatCl] = {"Inp: ", "Acc: "}; -const Char_t* AliAlgSteer::sStatName[AliAlgSteer::kMaxStat] = +const Char_t* Controller::sStatClName[Controller::kNStatCl] = {"Inp: ", "Acc: "}; +const Char_t* Controller::sStatName[Controller::kMaxStat] = {"runs", "Ev.Coll", "Ev.Cosm", "Trc.Coll", "Trc.Cosm"}; -const Char_t* AliAlgSteer::sHStatName[AliAlgSteer::kNHVars] = { +const Char_t* Controller::sHStatName[Controller::kNHVars] = { "Runs", "Ev.Inp", "Ev.VtxOK", "Tr.Inp", "Tr.2Fit", "Tr.2FitVC", "Tr.2PrMat", "Tr.2ResDer", "Tr.Stored", "Tr.Acc", "Tr.ContRes"}; //________________________________________________________________ -AliAlgSteer::AliAlgSteer(const char* configMacro, int refRun) +Controller::Controller(const char* configMacro, int refRun) : mNDet(0), mNDOFs(0), mRunNumber(-1), mFieldOn(false), mTracksType(kColl), mAlgTrack(0), mVtxSens(0), mConstraints(), // fSelEventSpecii(AliRecoParam::kCosmic | AliRecoParam::kLowMult | AliRecoParam::kHighMult | AliRecoParam::kDefault), FIXME(milettri): needs AliRecoParam mSelEventSpecii(0), // FIXME(milettri): needs AliRecoParam @@ -87,8 +87,8 @@ AliAlgSteer::AliAlgSteer(const char* configMacro, int refRun) mVtxMaxCont(-1), mVtxMinContVC(10), mMinITSClforVC(3), - // mITSPattforVC(AliAlgDetITS::kSPDAny), FIXME(milettri): needs AliAlgDetITS - mITSPattforVC(0), // FIXME(milettri): needs AliAlgDetITS + // mITSPattforVC(AlignableDetectorITS::kSPDAny), FIXME(milettri): needs AlignableDetectorITS + mITSPattforVC(0), // FIXME(milettri): needs AlignableDetectorITS mMaxChi2forVC(10) // , @@ -122,7 +122,7 @@ AliAlgSteer::AliAlgSteer(const char* configMacro, int refRun) // , mOutCDBPath("local://outOCDB"), - mOutCDBComment("AliAlgSteer"), + mOutCDBComment("Controller"), mOutCDBResponsible("") // , @@ -166,7 +166,7 @@ AliAlgSteer::AliAlgSteer(const char* configMacro, int refRun) // // run config macro if provided if (!mConfMacroName.IsNull()) { - gROOT->ProcessLine(Form(".x %s+g((AliAlgSteer*)%p)", mConfMacroName.Data(), this)); + gROOT->ProcessLine(Form(".x %s+g((Controller*)%p)", mConfMacroName.Data(), this)); if (!getInitDOFsDone()) initDOFs(); if (!getNDOFs()) @@ -175,7 +175,7 @@ AliAlgSteer::AliAlgSteer(const char* configMacro, int refRun) } //________________________________________________________________ -AliAlgSteer::~AliAlgSteer() +Controller::~Controller() { // d-tor if (mMPRecFile) @@ -199,7 +199,7 @@ AliAlgSteer::~AliAlgSteer() } //________________________________________________________________ -void AliAlgSteer::initDetectors() +void Controller::initDetectors() { // init all detectors geometry // @@ -208,13 +208,13 @@ void AliAlgSteer::initDetectors() // // - mAlgTrack = new AliAlgTrack(); - mRefPoint = new AliAlgPoint(); + mAlgTrack = new AlignmentTrack(); + mRefPoint = new AlignmentPoint(); // int dofCnt = 0; // special fake sensor for vertex constraint point // it has special T2L matrix adjusted for each track, no need to init it here - mVtxSens = new AliAlgVtx(); + mVtxSens = new EventVertex(); mVtxSens->setInternalID(1); mVtxSens->prepareMatrixL2G(); mVtxSens->prepareMatrixL2GIdeal(); @@ -227,7 +227,7 @@ void AliAlgSteer::initDetectors() // // for (int idt = 0; idt < kNDetectors; idt++) { - AliAlgDet* det = getDetectorByDetID(idt); + AlignableDetector* det = getDetectorByDetID(idt); if (!det || det->isDisabled()) continue; det->cacheReferenceOCDB(); @@ -251,7 +251,7 @@ void AliAlgSteer::initDetectors() } //________________________________________________________________ -void AliAlgSteer::initDOFs() +void Controller::initDOFs() { // scan all free global parameters, link detectors to array of params // @@ -268,7 +268,7 @@ void AliAlgSteer::initDOFs() int nact = 0; mVtxSens->initDOFs(); for (int i = 0; i < mNDet; i++) { - AliAlgDet* det = getDetector(i); + AlignableDetector* det = getDetector(i); det->initDOFs(); if (det->isDisabled()) continue; @@ -287,9 +287,9 @@ void AliAlgSteer::initDOFs() } //________________________________________________________________ -void AliAlgSteer::assignDOFs() +void Controller::assignDOFs() { - // add parameters/labels arrays to volumes. If the AliAlgSteer is read from the file, this method need + // add parameters/labels arrays to volumes. If the Controller is read from the file, this method need // to be called (of initDOFs should be called) // int ndfOld = -1; @@ -300,7 +300,7 @@ void AliAlgSteer::assignDOFs() mVtxSens->assignDOFs(mNDOFs, mGloParVal, mGloParErr, mGloParLab); // for (int idt = 0; idt < kNDetectors; idt++) { - AliAlgDet* det = getDetectorByDetID(idt); + AlignableDetector* det = getDetectorByDetID(idt); if (!det) continue; //if (det->isDisabled()) continue; @@ -318,7 +318,7 @@ void AliAlgSteer::assignDOFs() } //________________________________________________________________ -void AliAlgSteer::addDetector(uint32_t id, AliAlgDet* det) +void Controller::addDetector(uint32_t id, AlignableDetector* det) { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; // add detector participating in the alignment, optionally constructed externally @@ -334,16 +334,16 @@ void AliAlgSteer::addDetector(uint32_t id, AliAlgDet* det) if (!det) { switch (id) { // case kITS: - // det = new AliAlgDetITS(getDetNameByDetID(kITS)); FIXME(milettri): needs AliAlgDetITS + // det = new AlignableDetectorITS(getDetNameByDetID(kITS)); FIXME(milettri): needs AlignableDetectorITS // break; // case kTPC: - // det = new AliAlgDetTPC(getDetNameByDetID(kTPC)); FIXME(milettri): needs AliAlgDetTPC + // det = new AlignableDetectorTPC(getDetNameByDetID(kTPC)); FIXME(milettri): needs AlignableDetectorTPC // break; // case kTRD: - // det = new AliAlgDetTRD(getDetNameByDetID(kTRD)); FIXME(milettri): needs AliAlgDetTRD + // det = new AlignableDetectorTRD(getDetNameByDetID(kTRD)); FIXME(milettri): needs AlignableDetectorTRD // break; // case kTOF: - // det = new AliAlgDetTOF(getDetNameByDetID(kTOF)); FIXME(milettri): needs AliAlgDetTOF + // det = new AlignableDetectorTOF(getDetNameByDetID(kTOF)); FIXME(milettri): needs AlignableDetectorTOF // break; default: LOG(FATAL) << id << " not implemented yet"; @@ -361,14 +361,14 @@ void AliAlgSteer::addDetector(uint32_t id, AliAlgDet* det) } //_________________________________________________________ -void AliAlgSteer::addDetector(AliAlgDet* det) +void Controller::addDetector(AlignableDetector* det) { // add detector constructed externally to alignment framework addDetector(det->getDetID(), det); } //_________________________________________________________ -bool AliAlgSteer::checkDetectorPattern(uint32_t patt) const +bool Controller::checkDetectorPattern(uint32_t patt) const { //validate detector pattern return ((patt & mObligatoryDetPattern[mTracksType]) == @@ -377,12 +377,12 @@ bool AliAlgSteer::checkDetectorPattern(uint32_t patt) const } //_________________________________________________________ -bool AliAlgSteer::checkDetectorPoints(const int* npsel) const +bool Controller::checkDetectorPoints(const int* npsel) const { //validate detectors pattern according to number of selected points int ndOK = 0; for (int idt = 0; idt < kNDetectors; idt++) { - AliAlgDet* det = getDetectorByDetID(idt); + AlignableDetector* det = getDetectorByDetID(idt); if (!det || det->isDisabled(mTracksType)) continue; if (npsel[idt] < det->getNPointsSel(mTracksType)) { @@ -397,10 +397,10 @@ bool AliAlgSteer::checkDetectorPoints(const int* npsel) const //FIXME(milettri): needs AliESDtrack ////_________________________________________________________ -//uint32_t AliAlgSteer::AcceptTrack(const AliESDtrack* esdTr, bool strict) const +//uint32_t Controller::AcceptTrack(const AliESDtrack* esdTr, bool strict) const //{ // // decide if the track should be processed -// AliAlgDet* det = 0; +// AlignableDetector* det = 0; // uint32_t detAcc = 0; // if (mFieldOn && esdTr->Pt() < mPtMin[mTracksType]) // return 0; @@ -427,7 +427,7 @@ bool AliAlgSteer::checkDetectorPoints(const int* npsel) const //FIXME(milettri): needs AliESDtrack ////_________________________________________________________ -//uint32_t AliAlgSteer::AcceptTrackCosmic(const AliESDtrack* esdPairCosm[kNCosmLegs]) const +//uint32_t Controller::AcceptTrackCosmic(const AliESDtrack* esdPairCosm[kNCosmLegs]) const //{ // // decide if the pair of tracks making cosmic track should be processed // uint32_t detAcc = 0, detAccLeg; @@ -449,7 +449,7 @@ bool AliAlgSteer::checkDetectorPoints(const int* npsel) const //FIXME(milettri): needs AliESDEvent ////_________________________________________________________ -//void AliAlgSteer::SetESDEvent(const AliESDEvent* ev) +//void Controller::SetESDEvent(const AliESDEvent* ev) //{ // // attach event to analyse // fESDEvent = ev; @@ -463,7 +463,7 @@ bool AliAlgSteer::checkDetectorPoints(const int* npsel) const //FIXME(milettri): needs AliESDEvent ////_________________________________________________________ -//bool AliAlgSteer::ProcessEvent(const AliESDEvent* esdEv) +//bool Controller::ProcessEvent(const AliESDEvent* esdEv) //{ // // process event // const int kProcStatFreq = 100; @@ -543,7 +543,7 @@ bool AliAlgSteer::checkDetectorPoints(const int* npsel) const //FIXME(milettri): needs AliESDtrack //_________________________________________________________ -//bool AliAlgSteer::ProcessTrack(const AliESDtrack* esdTr) +//bool Controller::ProcessTrack(const AliESDtrack* esdTr) //{ // // process single track // // @@ -567,7 +567,7 @@ bool AliAlgSteer::checkDetectorPoints(const int* npsel) const // mAlgTrack->Clear(); // // // // process the track points for each detector, -// AliAlgDet* det = 0; +// AlignableDetector* det = 0; // for (int idet = 0; idet < kNDetectors; idet++) { // if (!(detAcc & (0x1 << idet))) // continue; @@ -590,7 +590,7 @@ bool AliAlgSteer::checkDetectorPoints(const int* npsel) const // // // mAlgTrack->copyFrom(esdTr); // if (!getFieldOn()) -// mAlgTrack->imposePtBOff(mDefPtBOff[AliAlgAux::kColl]); +// mAlgTrack->imposePtBOff(mDefPtBOff[utils::kColl]); // mAlgTrack->setFieldON(getFieldOn()); // mAlgTrack->sortPoints(); // // @@ -602,7 +602,7 @@ bool AliAlgSteer::checkDetectorPoints(const int* npsel) const // int pntMeas = mAlgTrack->getInnerPointID() - 1; // if (pntMeas < 0) { // this should not happen // mAlgTrack->Print("p meas"); -// LOG(FATAL) << "AliAlgTrack->getInnerPointID() cannot be 0"; +// LOG(FATAL) << "AlignmentTrack->getInnerPointID() cannot be 0"; // } // // do we want to add the vertex as a measured point ? // if (!addVertexConstraint()) { // no constrain, just reference point w/o measurement @@ -641,7 +641,7 @@ bool AliAlgSteer::checkDetectorPoints(const int* npsel) const //FIXME(milettri): needs AliESDVertex ////_________________________________________________________ -//bool AliAlgSteer::CheckSetVertex(const AliESDVertex* vtx) +//bool Controller::CheckSetVertex(const AliESDVertex* vtx) //{ // // vertex selection/constraint check // if (!vtx) { @@ -667,7 +667,7 @@ bool AliAlgSteer::checkDetectorPoints(const int* npsel) const //FIXME(milettri): needs AliESDCosmicTrack ////_________________________________________________________ -//bool AliAlgSteer::ProcessTrack(const AliESDCosmicTrack* cosmTr) +//bool Controller::ProcessTrack(const AliESDCosmicTrack* cosmTr) //{ // // process single cosmic track // // @@ -703,7 +703,7 @@ bool AliAlgSteer::checkDetectorPoints(const int* npsel) const // mRefPoint->setContainsMaterial(false); // mAlgTrack->addPoint(mRefPoint); // reference point which the track will refer to // // -// AliAlgDet* det = 0; +// AlignableDetector* det = 0; // int npsel[kNDetectors] = {0}; // for (int nPleg = 0, leg = kNCosmLegs; leg--;) { // for (int idet = 0; idet < kNDetectors; idet++) { @@ -728,7 +728,7 @@ bool AliAlgSteer::checkDetectorPoints(const int* npsel) const // // // mAlgTrack->copyFrom(cosmTr); // if (!getFieldOn()) -// mAlgTrack->imposePtBOff(mDefPtBOff[AliAlgAux::kCosm]); +// mAlgTrack->imposePtBOff(mDefPtBOff[utils::kCosm]); // mAlgTrack->setFieldON(getFieldOn()); // mAlgTrack->sortPoints(); // // @@ -740,7 +740,7 @@ bool AliAlgSteer::checkDetectorPoints(const int* npsel) const // int pntMeas = mAlgTrack->getInnerPointID() - 1; // if (pntMeas < 0) { // this should not happen // mAlgTrack->Print("p meas"); -// LOG(FATAL) << "AliAlgTrack->getInnerPointID() cannot be 0"; +// LOG(FATAL) << "AlignmentTrack->getInnerPointID() cannot be 0"; // } // mRefPoint->setAlphaSens(sector2Alpha(mAlgTrack->getPoint(pntMeas)->getAliceSector())); // // @@ -772,7 +772,7 @@ bool AliAlgSteer::checkDetectorPoints(const int* npsel) const //} //_________________________________________________________ -bool AliAlgSteer::storeProcessedTrack(int what) +bool Controller::storeProcessedTrack(int what) { // write alignment track bool res = true; @@ -787,7 +787,7 @@ bool AliAlgSteer::storeProcessedTrack(int what) } //_________________________________________________________ -bool AliAlgSteer::fillMilleData() +bool Controller::fillMilleData() { // store MP2 data in Mille format if (!mMille) { @@ -809,7 +809,7 @@ bool AliAlgSteer::fillMilleData() // const int* gloParID(mAlgTrack->getGloParID()); // IDs of global DOFs this track depends on for (int ip = 0; ip < np; ip++) { - AliAlgPoint* pnt = mAlgTrack->getPoint(ip); + AlignmentPoint* pnt = mAlgTrack->getPoint(ip); if (pnt->containsMeasurement()) { int gloOffs = pnt->getDGloOffs(); // 1st entry of global derivatives for this point int nDGlo = pnt->getNGloDOFs(); // number of global derivatives (number of DOFs it depends on) @@ -883,7 +883,7 @@ bool AliAlgSteer::fillMilleData() } //_________________________________________________________ -bool AliAlgSteer::fillMPRecData() +bool Controller::fillMPRecData() { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs AliESDEvent @@ -905,7 +905,7 @@ bool AliAlgSteer::fillMPRecData() } //_________________________________________________________ -bool AliAlgSteer::fillControlData() +bool Controller::fillControlData() { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs AliESDEvent @@ -936,7 +936,7 @@ bool AliAlgSteer::fillControlData() } //_________________________________________________________ -void AliAlgSteer::setRunNumber(int run) +void Controller::setRunNumber(int run) { if (run == mRunNumber) return; // nothing to do @@ -945,7 +945,7 @@ void AliAlgSteer::setRunNumber(int run) } //_________________________________________________________ -void AliAlgSteer::acknowledgeNewRun(int run) +void Controller::acknowledgeNewRun(int run) { LOG(WARNING) << __PRETTY_FUNCTION__ << " yet incomplete"; @@ -979,7 +979,7 @@ void AliAlgSteer::acknowledgeNewRun(int run) // LoadRecoTimeOCDB(); // // // for (int idet = 0; idet < mNDet; idet++) { - // AliAlgDet* det = getDetector(idet); + // AlignableDetector* det = getDetector(idet); // if (!det->isDisabled()) // det->acknowledgeNewRun(run); // } @@ -995,7 +995,7 @@ void AliAlgSteer::acknowledgeNewRun(int run) // FIXME(milettri): needs OCDB ////_________________________________________________________ -//bool AliAlgSteer::LoadRecoTimeOCDB() +//bool Controller::LoadRecoTimeOCDB() //{ // // Load OCDB paths used for the reconstruction of data being processed // // In order to avoid unnecessary uploads, the objects are not actually @@ -1032,7 +1032,7 @@ void AliAlgSteer::acknowledgeNewRun(int run) //} //_________________________________________________________ -AliAlgDet* AliAlgSteer::getDetectorByVolID(int vid) const +AlignableDetector* Controller::getDetectorByVolID(int vid) const { // get detector by sensor volid for (int i = mNDet; i--;) @@ -1042,7 +1042,7 @@ AliAlgDet* AliAlgSteer::getDetectorByVolID(int vid) const } //____________________________________________ -void AliAlgSteer::Print(const Option_t* opt) const +void Controller::Print(const Option_t* opt) const { // print info TString opts = opt; @@ -1055,7 +1055,7 @@ void AliAlgSteer::Print(const Option_t* opt) const printf("ALIGNMENT FROM MILLEPEDE SOLUTION IS APPLIED\n"); // for (int idt = 0; idt < kNDetectors; idt++) { - AliAlgDet* det = getDetectorByDetID(idt); + AlignableDetector* det = getDetectorByDetID(idt); if (!det) continue; det->Print(opt); @@ -1081,8 +1081,8 @@ void AliAlgSteer::Print(const Option_t* opt) const printf("%-40s:\t%d\n", "Min vertex contrib. for constraint", mVtxMinContVC); printf("%-40s:\t%d\n", "Min Ncl ITS for vertex constraint", mMinITSClforVC); printf("%-40s:\t%s\n", "SPD request for vertex constraint", - // AliAlgDetITS::GetITSPattName(mITSPattforVC)); FIXME(milettri): needs AliAlgDetITS - "ITSNAME"); // FIXME(milettri): needs AliAlgDetITS + // AlignableDetectorITS::GetITSPattName(mITSPattforVC)); FIXME(milettri): needs AlignableDetectorITS + "ITSNAME"); // FIXME(milettri): needs AlignableDetectorITS printf("%-40s:\t%.4f/%.4f/%.2f\n", "DCAr/DCAz/Chi2 cut for vertex constraint", mMaxDCAforVC[0], mMaxDCAforVC[1], mMaxChi2forVC); printf("Collision tracks: Min pT: %5.2f |etaMax|: %5.2f\n", mPtMin[kColl], mEtaMax[kColl]); @@ -1116,7 +1116,7 @@ void AliAlgSteer::Print(const Option_t* opt) const } //________________________________________________________ -void AliAlgSteer::printStatistics() const +void Controller::printStatistics() const { // print processing stat printf("\nProcessing Statistics\n"); @@ -1133,18 +1133,18 @@ void AliAlgSteer::printStatistics() const } //________________________________________________________ -void AliAlgSteer::resetDetectors() +void Controller::resetDetectors() { // reset detectors for next track mRefPoint->Clear(); for (int idet = mNDet; idet--;) { - AliAlgDet* det = getDetector(idet); + AlignableDetector* det = getDetector(idet); det->resetPool(); // reset used alignment points } } //____________________________________________ -bool AliAlgSteer::testLocalSolution() +bool Controller::testLocalSolution() { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs AliSymMatrix @@ -1170,7 +1170,7 @@ bool AliAlgSteer::testLocalSolution() // // // if (nlocpar>nlocparETP) printf("Mat.Corr. update:\n"); // for (int ip=mAlgTrack->getNPoints();ip--;) { - // AliAlgPoint* pnt = mAlgTrack->getPoint(ip); + // AlignmentPoint* pnt = mAlgTrack->getPoint(ip); // int npm = pnt->getNMatPar(); // const float* expMatCov = pnt->getMatCorrCov(); // its error // int offs = pnt->getMaxLocVarID() - npm; @@ -1195,7 +1195,7 @@ bool AliAlgSteer::testLocalSolution() //FIXME(milettri): needs AliSymMatrix ////____________________________________________ -//AliSymMatrix* AliAlgSteer::BuildMatrix(TVectorD& vec) +//AliSymMatrix* Controller::BuildMatrix(TVectorD& vec) //{ // // build matrix/vector for local track // int npnt = mAlgTrack->getNPoints(); @@ -1207,7 +1207,7 @@ bool AliAlgSteer::testLocalSolution() // AliSymMatrix& mat = *matp; // // // for (int ip = npnt; ip--;) { -// AliAlgPoint* pnt = mAlgTrack->getPoint(ip); +// AlignmentPoint* pnt = mAlgTrack->getPoint(ip); // // // if (pnt->containsMeasurement()) { // // pnt->Print("meas"); @@ -1251,11 +1251,11 @@ bool AliAlgSteer::testLocalSolution() //} //____________________________________________ -void AliAlgSteer::initMPRecOutput() +void Controller::initMPRecOutput() { // prepare MP record output if (!mMPRecord) - mMPRecord = new AliAlgMPRecord(); + mMPRecord = new Millepede2Record(); // TString mo = Form("%s%s", mMPDatFileName.Data(), ".root"); mMPRecFile = TFile::Open(mo.Data(), "recreate"); @@ -1263,28 +1263,28 @@ void AliAlgSteer::initMPRecOutput() LOG(FATAL) << "Failed to create output file " << mo.Data(); // mMPRecTree = new TTree("mpTree", "MPrecord Tree"); - mMPRecTree->Branch("mprec", "AliAlgMPRecord", &mMPRecord); + mMPRecTree->Branch("mprec", "Millepede2Record", &mMPRecord); // } //____________________________________________ -void AliAlgSteer::initResidOutput() +void Controller::initResidOutput() { // prepare residual output if (!mCResid) - mCResid = new AliAlgRes(); + mCResid = new ResidualsController(); // mResidFile = TFile::Open(mResidFileName.Data(), "recreate"); if (!mResidFile) LOG(FATAL) << "Failed to create output file " << mResidFileName.Data(); // mResidTree = new TTree("res", "Control Residuals"); - mResidTree->Branch("t", "AliAlgRes", &mCResid); + mResidTree->Branch("t", "ResidualsController", &mCResid); // } //____________________________________________ -void AliAlgSteer::closeMPRecOutput() +void Controller::closeMPRecOutput() { // close output if (!mMPRecFile) @@ -1302,7 +1302,7 @@ void AliAlgSteer::closeMPRecOutput() } //____________________________________________ -void AliAlgSteer::closeResidOutput() +void Controller::closeResidOutput() { // close output if (!mResidFile) @@ -1320,7 +1320,7 @@ void AliAlgSteer::closeResidOutput() } //____________________________________________ -void AliAlgSteer::closeMilleOutput() +void Controller::closeMilleOutput() { // close output if (mMille) @@ -1330,7 +1330,7 @@ void AliAlgSteer::closeMilleOutput() } //____________________________________________ -void AliAlgSteer::setMPDatFileName(const char* name) +void Controller::setMPDatFileName(const char* name) { // set output file name mMPDatFileName = name; @@ -1346,7 +1346,7 @@ void AliAlgSteer::setMPDatFileName(const char* name) } //____________________________________________ -void AliAlgSteer::setMPParFileName(const char* name) +void Controller::setMPParFileName(const char* name) { // set MP params output file name mMPParFileName = name; @@ -1356,7 +1356,7 @@ void AliAlgSteer::setMPParFileName(const char* name) } //____________________________________________ -void AliAlgSteer::setMPConFileName(const char* name) +void Controller::setMPConFileName(const char* name) { // set MP constraints output file name mMPConFileName = name; @@ -1366,7 +1366,7 @@ void AliAlgSteer::setMPConFileName(const char* name) } //____________________________________________ -void AliAlgSteer::setMPSteerFileName(const char* name) +void Controller::setMPSteerFileName(const char* name) { // set MP constraints output file name mMPSteerFileName = name; @@ -1376,7 +1376,7 @@ void AliAlgSteer::setMPSteerFileName(const char* name) } //____________________________________________ -void AliAlgSteer::setResidFileName(const char* name) +void Controller::setResidFileName(const char* name) { // set output file name mResidFileName = name; @@ -1386,7 +1386,7 @@ void AliAlgSteer::setResidFileName(const char* name) } //____________________________________________ -void AliAlgSteer::setOutCDBPath(const char* name) +void Controller::setOutCDBPath(const char* name) { // set output storage name mOutCDBPath = name; @@ -1396,10 +1396,10 @@ void AliAlgSteer::setOutCDBPath(const char* name) } //____________________________________________ -void AliAlgSteer::setObligatoryDetector(int detID, int trtype, bool v) +void Controller::setObligatoryDetector(int detID, int trtype, bool v) { // mark detector presence obligatory in the track of given type - AliAlgDet* det = getDetectorByDetID(detID); + AlignableDetector* det = getDetectorByDetID(detID); if (!det) { LOG(ERROR) << "Detector " << detID << " is not defined"; } @@ -1413,7 +1413,7 @@ void AliAlgSteer::setObligatoryDetector(int detID, int trtype, bool v) } //____________________________________________ -bool AliAlgSteer::addVertexConstraint() +bool Controller::addVertexConstraint() { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs AliESDtrack @@ -1425,7 +1425,7 @@ bool AliAlgSteer::addVertexConstraint() // // // if (esdTr->GetNcls(0) < mMinITSClforVC) // return false; // not enough ITS clusters - // if (!AliAlgDetITS::CheckHitPattern(esdTr, mITSPattforVC)) + // if (!AlignableDetectorITS::CheckHitPattern(esdTr, mITSPattforVC)) // return false; // // // AliExternalTrackParam trc = *esdTr; @@ -1464,13 +1464,13 @@ bool AliAlgSteer::addVertexConstraint() //FIXME(milettri): needs OCDB ////______________________________________________________ -//void AliAlgSteer::writeCalibrationResults() const +//void Controller::writeCalibrationResults() const //{ // // writes output calibration // CleanOCDB(); // AliCDBManager::Instance()->SetDefaultStorage(mOutCDBPath.Data()); // // -// AliAlgDet* det; +// AlignableDetector* det; // for (int idet = 0; idet < kNDetectors; idet++) { // if (!(det = getDetectorByDetID(idet)) || det->isDisabled()) // continue; @@ -1481,7 +1481,7 @@ bool AliAlgSteer::addVertexConstraint() //FIXME(milettri): needs OCDB ////______________________________________________________ -//void AliAlgSteer::SetOutCDBRunRange(int rmin, int rmax) +//void Controller::SetOutCDBRunRange(int rmin, int rmax) //{ // // set output run range // mOutCDBRunRange[0] = rmin >= 0 ? rmin : 0; @@ -1490,7 +1490,7 @@ bool AliAlgSteer::addVertexConstraint() //FIXME(milettri): needs OCDB ////______________________________________________________ -//bool AliAlgSteer::LoadRefOCDB() +//bool Controller::LoadRefOCDB() //{ // // setup OCDB whose objects will be used as a reference with respect to which the // // alignment/calibration will prodice its corrections. @@ -1534,11 +1534,11 @@ bool AliAlgSteer::addVertexConstraint() //} //________________________________________________________ -AliAlgDet* AliAlgSteer::getDetOfDOFID(int id) const +AlignableDetector* Controller::getDetOfDOFID(int id) const { // return detector owning DOF with this ID for (int i = mNDet; i--;) { - AliAlgDet* det = getDetector(i); + AlignableDetector* det = getDetector(i); if (det->ownsDOFID(id)) return det; } @@ -1546,11 +1546,11 @@ AliAlgDet* AliAlgSteer::getDetOfDOFID(int id) const } //________________________________________________________ -AliAlgVol* AliAlgSteer::getVolOfDOFID(int id) const +AlignableVolume* Controller::getVolOfDOFID(int id) const { // return volume owning DOF with this ID for (int i = mNDet; i--;) { - AliAlgDet* det = getDetector(i); + AlignableDetector* det = getDetector(i); if (det->ownsDOFID(id)) return det->getVolOfDOFID(id); } @@ -1560,7 +1560,7 @@ AliAlgVol* AliAlgSteer::getVolOfDOFID(int id) const } //________________________________________________________ -void AliAlgSteer::terminate(bool doStat) +void Controller::terminate(bool doStat) { // finalize processing if (mRunNumber > 0) @@ -1568,7 +1568,7 @@ void AliAlgSteer::terminate(bool doStat) if (doStat) { if (mDOFStat) delete mDOFStat; - mDOFStat = new AliAlgDOFStat(mNDOFs); + mDOFStat = new DOFStatistics(mNDOFs); } if (mVtxSens) mVtxSens->fillDOFStat(mDOFStat); @@ -1583,16 +1583,16 @@ void AliAlgSteer::terminate(bool doStat) } //________________________________________________________ -Char_t* AliAlgSteer::getDOFLabelTxt(int idf) const +Char_t* Controller::getDOFLabelTxt(int idf) const { // get DOF full label - AliAlgVol* vol = getVolOfDOFID(idf); + AlignableVolume* vol = getVolOfDOFID(idf); if (vol) return Form("%d_%s_%s", getGloParLab(idf), vol->getSymName(), vol->getDOFName(idf - vol->getFirstParGloID())); // // this might be detector-specific calibration dof - AliAlgDet* det = getDetOfDOFID(idf); + AlignableDetector* det = getDetOfDOFID(idf); if (det) return Form("%d_%s_%s", getGloParLab(idf), det->GetName(), det->getCalibDOFName(idf - det->getFirstParGloID())); @@ -1602,7 +1602,7 @@ Char_t* AliAlgSteer::getDOFLabelTxt(int idf) const //********************* interaction with PEDE ********************** //______________________________________________________ -void AliAlgSteer::genPedeSteerFile(const Option_t* opt) const +void Controller::genPedeSteerFile(const Option_t* opt) const { // produce steering file template for PEDE + params and constraints // @@ -1655,7 +1655,7 @@ void AliAlgSteer::genPedeSteerFile(const Option_t* opt) const mVtxSens->writePedeInfo(parFl, opt); // for (int idt = 0; idt < kNDetectors; idt++) { - AliAlgDet* det = getDetectorByDetID(idt); + AlignableDetector* det = getDetectorByDetID(idt); if (!det || det->isDisabled()) continue; det->writePedeInfo(parFl, opt); @@ -1670,7 +1670,7 @@ void AliAlgSteer::genPedeSteerFile(const Option_t* opt) const } //___________________________________________________________ -bool AliAlgSteer::readParameters(const char* parfile, bool useErrors) +bool Controller::readParameters(const char* parfile, bool useErrors) { // read parameters file (millepede output) if (mNDOFs < 1 || !mGloParVal || !mGloParErr) { @@ -1726,7 +1726,7 @@ bool AliAlgSteer::readParameters(const char* parfile, bool useErrors) } //______________________________________________________ -void AliAlgSteer::checkConstraints(const char* params) +void Controller::checkConstraints(const char* params) { // check how the constraints are satisfied with already uploaded or provided params // @@ -1737,14 +1737,14 @@ void AliAlgSteer::checkConstraints(const char* params) // int ncon = getNConstraints(); for (int icon = 0; icon < ncon; icon++) { - const AliAlgConstraint* con = getConstraint(icon); + const GeometricalConstraint* con = getConstraint(icon); con->checkConstraint(); } // } //___________________________________________________________ -void AliAlgSteer::mPRec2Mille(const char* mprecfile, const char* millefile, bool bindata) +void Controller::mPRec2Mille(const char* mprecfile, const char* millefile, bool bindata) { // converts MPRecord tree to millepede binary format TFile* flmpr = TFile::Open(mprecfile); @@ -1764,7 +1764,7 @@ void AliAlgSteer::mPRec2Mille(const char* mprecfile, const char* millefile, bool } //___________________________________________________________ -void AliAlgSteer::mPRec2Mille(TTree* mprTree, const char* millefile, bool bindata) +void Controller::mPRec2Mille(TTree* mprTree, const char* millefile, bool bindata) { // converts MPRecord tree to millepede binary format // @@ -1773,7 +1773,7 @@ void AliAlgSteer::mPRec2Mille(TTree* mprTree, const char* millefile, bool bindat LOG(ERROR) << "provided tree does not contain branch mprec"; return; } - AliAlgMPRecord* rec = new AliAlgMPRecord(); + Millepede2Record* rec = new Millepede2Record(); br->SetAddress(&rec); int nent = mprTree->GetEntries(); TString mlname = millefile; @@ -1818,7 +1818,7 @@ void AliAlgSteer::mPRec2Mille(TTree* mprTree, const char* millefile, bool bindat } //____________________________________________________________ -void AliAlgSteer::fillStatHisto(int type, float w) +void Controller::fillStatHisto(int type, float w) { if (!mHistoStat) createStatHisto(); @@ -1826,7 +1826,7 @@ void AliAlgSteer::fillStatHisto(int type, float w) } //____________________________________________________________ -void AliAlgSteer::createStatHisto() +void Controller::createStatHisto() { mHistoStat = new TH1F("stat", "stat", 2 * kNHVars, -0.5, 2 * kNHVars - 0.5); mHistoStat->SetDirectory(0); @@ -1839,7 +1839,7 @@ void AliAlgSteer::createStatHisto() } //____________________________________________________________ -void AliAlgSteer::printLabels() const +void Controller::printLabels() const { // print global IDs and Labels for (int i = 0; i < mNDOFs; i++) @@ -1847,7 +1847,7 @@ void AliAlgSteer::printLabels() const } //____________________________________________________________ -int AliAlgSteer::label2ParID(int lab) const +int Controller::label2ParID(int lab) const { // convert Mille label to ParID (slow) int ind = findKeyIndex(lab, mOrderedLbl, mNDOFs); @@ -1857,11 +1857,11 @@ int AliAlgSteer::label2ParID(int lab) const } //____________________________________________________________ -void AliAlgSteer::addAutoConstraints() +void Controller::addAutoConstraints() { // add default constraints on children cumulative corrections within the volumes for (int idet = 0; idet < mNDet; idet++) { - AliAlgDet* det = getDetector(idet); + AlignableDetector* det = getDetector(idet); if (det->isDisabled()) continue; det->addAutoConstraints(); @@ -1870,7 +1870,7 @@ void AliAlgSteer::addAutoConstraints() } //____________________________________________________________ -void AliAlgSteer::writePedeConstraints() const +void Controller::writePedeConstraints() const { // write constraints file FILE* conFl = fopen(mMPConFileName.Data(), "w+"); @@ -1883,7 +1883,7 @@ void AliAlgSteer::writePedeConstraints() const } //____________________________________________________________ -void AliAlgSteer::fixLowStatFromDOFStat(int thresh) +void Controller::fixLowStatFromDOFStat(int thresh) { // fix DOFs having stat below threshold // @@ -1904,7 +1904,7 @@ void AliAlgSteer::fixLowStatFromDOFStat(int thresh) } //____________________________________________________________ -void AliAlgSteer::loadStat(const char* flname) +void Controller::loadStat(const char* flname) { // load statistics histos from external file produced by alignment task TFile* fl = TFile::Open(flname); @@ -1929,8 +1929,8 @@ void AliAlgSteer::loadStat(const char* flname) else LOG(WARNING) << "did not find stat histo"; // - AliAlgDOFStat* dofSt = 0; - if (!hdfO || !(dofSt = dynamic_cast(hdfO))) + DOFStatistics* dofSt = 0; + if (!hdfO || !(dofSt = dynamic_cast(hdfO))) LOG(WARNING) << "did not find DOFstat object"; // setHistoStat(hst); @@ -1941,12 +1941,12 @@ void AliAlgSteer::loadStat(const char* flname) } //______________________________________________ -void AliAlgSteer::checkSol(TTree* mpRecTree, bool store, - bool verbose, bool loc, const char* outName) +void Controller::checkSol(TTree* mpRecTree, bool store, + bool verbose, bool loc, const char* outName) { // do fast check of pede solution with MPRecord tree - AliAlgResFast* rLG = store ? new AliAlgResFast() : 0; - AliAlgResFast* rL = store && loc ? new AliAlgResFast() : 0; + ResidualsControllerFast* rLG = store ? new ResidualsControllerFast() : 0; + ResidualsControllerFast* rL = store && loc ? new ResidualsControllerFast() : 0; TTree *trLG = 0, *trL = 0; TFile* outFile = 0; if (store) { @@ -1957,15 +1957,15 @@ void AliAlgSteer::checkSol(TTree* mpRecTree, bool store, outNS += ".root"; outFile = TFile::Open(outNS.Data(), "recreate"); trLG = new TTree("resFLG", "Fast residuals with LG correction"); - trLG->Branch("rLG", "AliAlgResFast", &rLG); + trLG->Branch("rLG", "ResidualsControllerFast", &rLG); // if (rL) { trL = new TTree("resFL", "Fast residuals with L correction"); - trL->Branch("rL", "AliAlgResFast", &rL); + trL->Branch("rL", "ResidualsControllerFast", &rL); } } // - AliAlgMPRecord* rec = new AliAlgMPRecord(); + Millepede2Record* rec = new Millepede2Record(); mpRecTree->SetBranchAddress("mprec", &rec); int nrec = mpRecTree->GetEntriesFast(); for (int irec = 0; irec < nrec; irec++) { @@ -1994,9 +1994,9 @@ void AliAlgSteer::checkSol(TTree* mpRecTree, bool store, } //______________________________________________ -bool AliAlgSteer::checkSol(AliAlgMPRecord* rec, - AliAlgResFast* rLG, AliAlgResFast* rL, - bool verbose, bool loc) +bool Controller::checkSol(Millepede2Record* rec, + ResidualsControllerFast* rLG, ResidualsControllerFast* rL, + bool verbose, bool loc) { LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs AliSymMatrix @@ -2077,7 +2077,7 @@ bool AliAlgSteer::checkSol(AliAlgMPRecord* rec, // // resid[irs] -= parVal*recDGlo[ig]; // resid[irs] += parVal * recDGlo[ig]; // if (!ig) { - // AliAlgVol* vol = getVolOfDOFID(idP); + // AlignableVolume* vol = getVolOfDOFID(idP); // if (vol) // volID[irs] = vol->getVolID(); // else @@ -2259,12 +2259,12 @@ bool AliAlgSteer::checkSol(AliAlgMPRecord* rec, } //______________________________________________ -void AliAlgSteer::applyAlignmentFromMPSol() +void Controller::applyAlignmentFromMPSol() { // apply alignment from millepede solution array to reference alignment level LOG(INFO) << "Applying alignment from Millepede solution"; for (int idt = 0; idt < kNDetectors; idt++) { - AliAlgDet* det = getDetectorByDetID(idt); + AlignableDetector* det = getDetectorByDetID(idt); if (!det || det->isDisabled()) continue; det->applyAlignmentFromMPSol(); diff --git a/Detectors/Align/src/AliAlgDOFStat.cxx b/Detectors/Align/src/DOFStatistics.cxx similarity index 84% rename from Detectors/Align/src/AliAlgDOFStat.cxx rename to Detectors/Align/src/DOFStatistics.cxx index 739c6d414285f..2ac696f5fc1ea 100644 --- a/Detectors/Align/src/AliAlgDOFStat.cxx +++ b/Detectors/Align/src/DOFStatistics.cxx @@ -8,20 +8,20 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgDOFStat.h +/// @file DOFStatistics.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Mergable bbject for statistics of points used by each DOF -#include "Align/AliAlgDOFStat.h" -#include "Align/AliAlgSteer.h" +#include "Align/DOFStatistics.h" +#include "Align/Controller.h" #include "Framework/Logger.h" #include #include using namespace TMath; -ClassImp(o2::align::AliAlgDOFStat); +ClassImp(o2::align::DOFStatistics); namespace o2 { @@ -29,7 +29,7 @@ namespace align { //_________________________________________________________ -AliAlgDOFStat::AliAlgDOFStat(int n) +DOFStatistics::DOFStatistics(int n) : TNamed("DOFstat", "DOF statistics"), mNDOFs(n), mNMerges(1), mStat(0) { // def c-tor @@ -41,14 +41,14 @@ AliAlgDOFStat::AliAlgDOFStat(int n) } //_________________________________________________________ -AliAlgDOFStat::~AliAlgDOFStat() +DOFStatistics::~DOFStatistics() { // d-r delete[] mStat; } //____________________________________________ -void AliAlgDOFStat::Print(Option_t*) const +void DOFStatistics::Print(Option_t*) const { // print info printf("NDOFs: %d, NMerges: %d\n", mNDOFs, mNMerges); @@ -56,7 +56,7 @@ void AliAlgDOFStat::Print(Option_t*) const } //____________________________________________ -TH1F* AliAlgDOFStat::createHisto(AliAlgSteer* st) const +TH1F* DOFStatistics::createHisto(Controller* st) const { // create histo with stat. If steer object is supplied, build labels if (!mNDOFs) @@ -71,14 +71,14 @@ TH1F* AliAlgDOFStat::createHisto(AliAlgSteer* st) const } //______________________________________________________________________________ -int64_t AliAlgDOFStat::merge(TCollection* list) +int64_t DOFStatistics::merge(TCollection* list) { // merge statistics int nmerged = 0; TIter next(list); TObject* obj; while ((obj = next())) { - AliAlgDOFStat* stAdd = dynamic_cast(obj); + DOFStatistics* stAdd = dynamic_cast(obj); if (!stAdd) continue; if (mNDOFs != stAdd->mNDOFs) { diff --git a/Detectors/Align/src/AliAlgVtx.cxx b/Detectors/Align/src/EventVertex.cxx similarity index 80% rename from Detectors/Align/src/AliAlgVtx.cxx rename to Detectors/Align/src/EventVertex.cxx index f2208d481720c..455a200745630 100644 --- a/Detectors/Align/src/AliAlgVtx.cxx +++ b/Detectors/Align/src/EventVertex.cxx @@ -8,22 +8,22 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgVtx.h +/// @file EventVertex.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Special fake "sensor" for event vertex. -#include "Align/AliAlgVtx.h" +#include "Align/EventVertex.h" //#include "AliTrackPointArray.h" FIXME(milettri): needs AliTrackPointArray //#include "AliESDtrack.h" FIXME(milettri): needs AliESDtrack -#include "Align/AliAlgPoint.h" -#include "Align/AliAlgDet.h" +#include "Align/AlignmentPoint.h" +#include "Align/AlignableDetector.h" #include "Framework/Logger.h" #include using namespace TMath; -ClassImp(o2::align::AliAlgVtx); +ClassImp(o2::align::EventVertex); namespace o2 { @@ -31,7 +31,7 @@ namespace align { //_________________________________________________________ -AliAlgVtx::AliAlgVtx() : AliAlgSens("Vertex", 0, 1) +EventVertex::EventVertex() : AlignableSensor("Vertex", 0, 1) { // def c-tor setVarFrame(kLOC); @@ -40,7 +40,7 @@ AliAlgVtx::AliAlgVtx() : AliAlgSens("Vertex", 0, 1) } //____________________________________________ -void AliAlgVtx::prepareMatrixT2L() +void EventVertex::prepareMatrixT2L() { // T2L matrix for vertex needs to be adjusted for every track // in order to have X axis along the track direction. @@ -54,7 +54,7 @@ void AliAlgVtx::prepareMatrixT2L() } //____________________________________________ -void AliAlgVtx::applyCorrection(double* vtx) const +void EventVertex::applyCorrection(double* vtx) const { // apply eventual correction to supplied vertex position vtx[kDOFTX] += getParVal(kDOFTX); @@ -65,9 +65,9 @@ void AliAlgVtx::applyCorrection(double* vtx) const //FIXME(milettri): needs AliTrackPointArray, AliESDtrack ////____________________________________________ -//AliAlgPoint* AliAlgVtx::TrackPoint2AlgPoint(int, const AliTrackPointArray*, const AliESDtrack*) +//AlignmentPoint* EventVertex::TrackPoint2AlgPoint(int, const AliTrackPointArray*, const AliESDtrack*) //{ -// // convert the pntId-th point to AliAlgPoint +// // convert the pntId-th point to AlignmentPoint // static int cnt = 0; // LOG(ERROR) << "This method shound not have been called," << cnt++; // return 0; diff --git a/Detectors/Align/src/AliAlgConstraint.cxx b/Detectors/Align/src/GeometricalConstraint.cxx similarity index 94% rename from Detectors/Align/src/AliAlgConstraint.cxx rename to Detectors/Align/src/GeometricalConstraint.cxx index 11d59abda2c02..9aa5891a5391f 100644 --- a/Detectors/Align/src/AliAlgConstraint.cxx +++ b/Detectors/Align/src/GeometricalConstraint.cxx @@ -8,22 +8,22 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgConstraint.h +/// @file GeometricalConstraint.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Descriptor of geometrical constraint -#include "Align/AliAlgConstraint.h" +#include "Align/GeometricalConstraint.h" #include "DetectorsCommonDataFormats/AlignParam.h" -#include "Align/AliAlgAux.h" +#include "Align/utils.h" #include "Framework/Logger.h" #include #include #include -ClassImp(o2::align::AliAlgConstraint); +ClassImp(o2::align::GeometricalConstraint); -using namespace o2::align::AliAlgAux; +using namespace o2::align::utils; using namespace TMath; namespace o2 @@ -32,7 +32,7 @@ namespace align { //___________________________________________________________________ -AliAlgConstraint::AliAlgConstraint(const char* name, const char* title) +GeometricalConstraint::GeometricalConstraint(const char* name, const char* title) : TNamed(name, title), mConstraint(0), mParent(0), mChildren(2) { // def. c-tor @@ -41,14 +41,14 @@ AliAlgConstraint::AliAlgConstraint(const char* name, const char* title) } //___________________________________________________________________ -AliAlgConstraint::~AliAlgConstraint() +GeometricalConstraint::~GeometricalConstraint() { // d-tor delete mParent; } //___________________________________________________________________ -void AliAlgConstraint::setParent(const AliAlgVol* par) +void GeometricalConstraint::setParent(const AlignableVolume* par) { mParent = par; TString nm = GetName(); @@ -61,7 +61,7 @@ void AliAlgConstraint::setParent(const AliAlgVol* par) } //______________________________________________________ -void AliAlgConstraint::writeChildrenConstraints(FILE* conOut) const +void GeometricalConstraint::writeChildrenConstraints(FILE* conOut) const { // write for PEDE eventual constraints on children movement in parent frame // @@ -95,7 +95,7 @@ void AliAlgConstraint::writeChildrenConstraints(FILE* conOut) const float* jac = cstrArr; int nContCh[kNDOFGeom] = {0}; // we need at least on contributing children DOF to constrain the parent DOF for (int ich = 0; ich < nch; ich++) { - AliAlgVol* child = getChild(ich); + AlignableVolume* child = getChild(ich); // if (doJac) { // calculate jacobian TGeoHMatrix matRel; @@ -140,7 +140,7 @@ void AliAlgConstraint::writeChildrenConstraints(FILE* conOut) const comment[kOnOn], getDOFName(ics), GetName(), GetTitle()); } for (int ich = 0; ich < nch; ich++) { // contribution from this children DOFs to constraint - AliAlgVol* child = getChild(ich); + AlignableVolume* child = getChild(ich); jac = cstrArr + kNDOFGeom * kNDOFGeom * ich; if (cmtStatus) fprintf(conOut, "%s", comment[cmtStatus]); // comment out contribution @@ -168,7 +168,7 @@ void AliAlgConstraint::writeChildrenConstraints(FILE* conOut) const } //______________________________________________________ -void AliAlgConstraint::checkConstraint() const +void GeometricalConstraint::checkConstraint() const { // check how the constraints are satysfied int nch = getNChildren(); @@ -205,7 +205,7 @@ void AliAlgConstraint::checkConstraint() const printf(" D%3s ", getDOFName(jp)); printf(" ! %s\n", GetName()); for (int ich = 0; ich < nch; ich++) { - AliAlgVol* child = getChild(ich); + AlignableVolume* child = getChild(ich); double parsC[kNDOFGeom] = {0}, parsPAn[kNDOFGeom] = {0}, parsPEx[kNDOFGeom] = {0}; for (int jc = kNDOFGeom; jc--;) parsC[jc] = child->getParVal(jc); // child params in child frame @@ -304,7 +304,7 @@ void AliAlgConstraint::checkConstraint() const } //_________________________________________________________________ -void AliAlgConstraint::constrCoefGeom(const TGeoHMatrix& matRD, float* jac /*[kNDOFGeom][kNDOFGeom]*/) const +void GeometricalConstraint::constrCoefGeom(const TGeoHMatrix& matRD, float* jac /*[kNDOFGeom][kNDOFGeom]*/) const { // If the transformation R brings the vector from "local" frame to "master" frame as V=R*v // then application of the small LOCAL correction tau to vector v is equivalent to @@ -374,7 +374,7 @@ void AliAlgConstraint::constrCoefGeom(const TGeoHMatrix& matRD, float* jac /*[kN } //______________________________________________________ -void AliAlgConstraint::Print(const Option_t*) const +void GeometricalConstraint::Print(const Option_t*) const { // print info printf("Constraint on "); @@ -385,7 +385,7 @@ void AliAlgConstraint::Print(const Option_t*) const if (getNoJacobian()) printf("!!! This is explicit constraint on sum of DOFs (no Jacobian)!!!\n"); for (int i = 0; i < getNChildren(); i++) { - const AliAlgVol* child = getChild(i); + const AlignableVolume* child = getChild(i); printf("%3d %s\n", i, child->GetName()); } } diff --git a/Detectors/Align/src/AliAlgMPRecord.cxx b/Detectors/Align/src/Millepede2Record.cxx similarity index 93% rename from Detectors/Align/src/AliAlgMPRecord.cxx rename to Detectors/Align/src/Millepede2Record.cxx index a824c9aa666b0..eba710ccdd66e 100644 --- a/Detectors/Align/src/AliAlgMPRecord.cxx +++ b/Detectors/Align/src/Millepede2Record.cxx @@ -8,20 +8,20 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgMPRecord.h +/// @file Millepede2Record.cxx /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Millepede record in root format (can be converted to proper pede binary format. -#include "Align/AliAlgMPRecord.h" -#include "Align/AliAlgAux.h" -#include "Align/AliAlgTrack.h" +#include "Align/Millepede2Record.h" +#include "Align/utils.h" +#include "Align/AlignmentTrack.h" #include "Framework/Logger.h" #include #include using namespace TMath; -using namespace o2::align::AliAlgAux; +using namespace o2::align::utils; namespace o2 { @@ -29,7 +29,7 @@ namespace align { //_________________________________________________________ -AliAlgMPRecord::AliAlgMPRecord() +Millepede2Record::Millepede2Record() : mTrackID(0), mTimeStamp(0), mNResid(0), mNVarLoc(0), mNVarGlo(0), mNDLocTot(0), mNDGloTot(0), mNMeas(0), mChi2Ini(0), mQ2Pt(0), mTgl(0), mNDLoc(0), mNDGlo(0), mVolID(0), mResid(0), mResErr(0), mIDLoc(0), mIDGlo(0), mDLoc(0), mDGlo(0) // , @@ -41,7 +41,7 @@ AliAlgMPRecord::AliAlgMPRecord() } //_________________________________________________________ -AliAlgMPRecord::~AliAlgMPRecord() +Millepede2Record::~Millepede2Record() { // d-tor delete[] mNDLoc; @@ -56,7 +56,7 @@ AliAlgMPRecord::~AliAlgMPRecord() } //_________________________________________________________ -void AliAlgMPRecord::dummyRecord(float res, float err, float dGlo, int labGlo) +void Millepede2Record::dummyRecord(float res, float err, float dGlo, int labGlo) { // create dummy residuals record if (!mNDGlo) @@ -82,7 +82,7 @@ void AliAlgMPRecord::dummyRecord(float res, float err, float dGlo, int labGlo) } //_________________________________________________________ -bool AliAlgMPRecord::fillTrack(const AliAlgTrack* trc, const int* id2Lab) +bool Millepede2Record::fillTrack(const AlignmentTrack* trc, const int* id2Lab) { // fill track info, optionally substitutind glopar par ID by label // @@ -105,7 +105,7 @@ bool AliAlgMPRecord::fillTrack(const AliAlgTrack* trc, const int* id2Lab) int nlocd = 0; int nglod = 0; for (int ip = np; ip--;) { - AliAlgPoint* pnt = trc->getPoint(ip); + AlignmentPoint* pnt = trc->getPoint(ip); int ngl = pnt->getNGloDOFs(); // number of DOF's this point depends on if (pnt->containsMeasurement()) { nres += 2; // every point has 2 residuals @@ -125,7 +125,7 @@ bool AliAlgMPRecord::fillTrack(const AliAlgTrack* trc, const int* id2Lab) // const int* gloParID = trc->getGloParID(); // IDs of global DOFs this track depends on for (int ip = 0; ip < np; ip++) { - AliAlgPoint* pnt = trc->getPoint(ip); + AlignmentPoint* pnt = trc->getPoint(ip); if (pnt->containsMeasurement()) { int gloOffs = pnt->getDGloOffs(); // 1st entry of global derivatives for this point int nDGlo = pnt->getNGloDOFs(); // number of global derivatives (number of DOFs it depends on) @@ -209,7 +209,7 @@ bool AliAlgMPRecord::fillTrack(const AliAlgTrack* trc, const int* id2Lab) } //________________________________________________ -void AliAlgMPRecord::resize(int nresid, int nloc, int nglo) +void Millepede2Record::resize(int nresid, int nloc, int nglo) { // resize container if (nresid > mNResidBook) { @@ -252,7 +252,7 @@ void AliAlgMPRecord::resize(int nresid, int nloc, int nglo) } //____________________________________________ -void AliAlgMPRecord::Clear(const Option_t*) +void Millepede2Record::Clear(const Option_t*) { // reset record TObject::Clear(); @@ -265,7 +265,7 @@ void AliAlgMPRecord::Clear(const Option_t*) } //____________________________________________ -void AliAlgMPRecord::Print(const Option_t*) const +void Millepede2Record::Print(const Option_t*) const { // print info // diff --git a/Detectors/Align/src/AliAlgRes.cxx b/Detectors/Align/src/ResidualsController.cxx similarity index 89% rename from Detectors/Align/src/AliAlgRes.cxx rename to Detectors/Align/src/ResidualsController.cxx index 81807b445c2c0..c7bf07fac7704 100644 --- a/Detectors/Align/src/AliAlgRes.cxx +++ b/Detectors/Align/src/ResidualsController.cxx @@ -8,15 +8,15 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgRes.h +/// @file ResidualsController.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Container for control residuals -#include "Align/AliAlgRes.h" -#include "Align/AliAlgTrack.h" -#include "Align/AliAlgPoint.h" -#include "Align/AliAlgSens.h" +#include "Align/ResidualsController.h" +#include "Align/AlignmentTrack.h" +#include "Align/AlignmentPoint.h" +#include "Align/AlignableSensor.h" #include "Framework/Logger.h" #include #include @@ -24,7 +24,7 @@ using namespace TMath; -ClassImp(o2::align::AliAlgRes); +ClassImp(o2::align::ResidualsController); namespace o2 { @@ -32,14 +32,14 @@ namespace align { //____________________________________ -AliAlgRes::AliAlgRes() +ResidualsController::ResidualsController() : mRun(0), mBz(0), mTimeStamp(0), mTrackID(0), mNPoints(0), mNBook(0), mChi2(0), mChi2Ini(0), mChi2K(0), mQ2Pt(0), mX(0), mY(0), mZ(0), mSnp(0), mTgl(0), mAlpha(0), mDY(0), mDZ(0), mDYK(0), mDZK(0), mSigY2(0), mSigYZ(0), mSigZ2(0), mSigY2K(0), mSigYZK(0), mSigZ2K(0), mVolID(0), mLabel(0) { // def c-tor } //________________________________________________ -AliAlgRes::~AliAlgRes() +ResidualsController::~ResidualsController() { // d-tor delete[] mX; @@ -63,7 +63,7 @@ AliAlgRes::~AliAlgRes() } //________________________________________________ -void AliAlgRes::resize(int np) +void ResidualsController::resize(int np) { // resize container if (np > mNBook) { @@ -129,7 +129,7 @@ void AliAlgRes::resize(int np) } //____________________________________________ -void AliAlgRes::Clear(const Option_t*) +void ResidualsController::Clear(const Option_t*) { // reset record TObject::Clear(); @@ -145,7 +145,7 @@ void AliAlgRes::Clear(const Option_t*) } //____________________________________________ -void AliAlgRes::Print(const Option_t* opt) const +void ResidualsController::Print(const Option_t* opt) const { // print info TString opts = opt; @@ -192,7 +192,7 @@ void AliAlgRes::Print(const Option_t* opt) const } //____________________________________________________________ -bool AliAlgRes::fillTrack(AliAlgTrack* trc, bool doKalman) +bool ResidualsController::fillTrack(AlignmentTrack* trc, bool doKalman) { // fill tracks residuals info int nps, np = trc->getNPoints(); @@ -211,7 +211,7 @@ bool AliAlgRes::fillTrack(AliAlgTrack* trc, bool doKalman) mChi2Ini = trc->getChi2Ini(); int nfill = 0; for (int i = 0; i < np; i++) { - AliAlgPoint* pnt = trc->getPoint(i); + AlignmentPoint* pnt = trc->getPoint(i); int inv = pnt->isInvDir() ? -1 : 1; // Flag invertion for cosmic upper leg if (!pnt->containsMeasurement()) continue; @@ -229,8 +229,8 @@ bool AliAlgRes::fillTrack(AliAlgTrack* trc, bool doKalman) mSigYZ[nfill] = pnt->getYZErrTracking()[1]; mSigZ2[nfill] = pnt->getYZErrTracking()[2]; // - mSnp[nfill] = pnt->getTrParamWSA()[AliAlgPoint::kParSnp]; - mTgl[nfill] = pnt->getTrParamWSA()[AliAlgPoint::kParTgl]; + mSnp[nfill] = pnt->getTrParamWSA()[AlignmentPoint::kParSnp]; + mTgl[nfill] = pnt->getTrParamWSA()[AlignmentPoint::kParTgl]; // nfill++; } @@ -243,7 +243,7 @@ bool AliAlgRes::fillTrack(AliAlgTrack* trc, bool doKalman) int nfilk = 0; if (doKalman && trc->residKalman()) { for (int i = 0; i < np; i++) { - AliAlgPoint* pnt = trc->getPoint(i); + AlignmentPoint* pnt = trc->getPoint(i); if (!pnt->containsMeasurement()) continue; if (mVolID[nfilk] != int(pnt->getVolID())) { @@ -267,21 +267,21 @@ bool AliAlgRes::fillTrack(AliAlgTrack* trc, bool doKalman) } //_________________________________________________ -float AliAlgRes::getXLab(int i) const +float ResidualsController::getXLab(int i) const { // cluster lab X return Abs(mX[i]) * Cos(mAlpha[i]) - mY[i] * Sin(mAlpha[i]); } //_________________________________________________ -float AliAlgRes::getYLab(int i) const +float ResidualsController::getYLab(int i) const { // cluster lab Y return Abs(mX[i]) * Sin(mAlpha[i]) + mY[i] * Cos(mAlpha[i]); } //_________________________________________________ -float AliAlgRes::getZLab(int i) const +float ResidualsController::getZLab(int i) const { // cluster lab Z return mZ[i]; diff --git a/Detectors/Align/src/AliAlgResFast.cxx b/Detectors/Align/src/ResidualsControllerFast.cxx similarity index 84% rename from Detectors/Align/src/AliAlgResFast.cxx rename to Detectors/Align/src/ResidualsControllerFast.cxx index ae16b1082085b..bc13d9e8bca34 100644 --- a/Detectors/Align/src/AliAlgResFast.cxx +++ b/Detectors/Align/src/ResidualsControllerFast.cxx @@ -8,15 +8,15 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file AliAlgResFast.h +/// @file ResidualsControllerFast.h /// @author ruben.shahoyan@cern.ch, michael.lettrich@cern.ch /// @since 2021-02-01 /// @brief Container for control fast residuals evaluated via derivatives -#include "Align/AliAlgResFast.h" -#include "Align/AliAlgTrack.h" -#include "Align/AliAlgPoint.h" -#include "Align/AliAlgSens.h" +#include "Align/ResidualsControllerFast.h" +#include "Align/AlignmentTrack.h" +#include "Align/AlignmentPoint.h" +#include "Align/AlignableSensor.h" #include "Framework/Logger.h" #include #include @@ -24,7 +24,7 @@ using namespace TMath; -ClassImp(o2::align::AliAlgResFast); +ClassImp(o2::align::ResidualsControllerFast); namespace o2 { @@ -32,7 +32,7 @@ namespace align { //____________________________________ -AliAlgResFast::AliAlgResFast() +ResidualsControllerFast::ResidualsControllerFast() : mNPoints(0), mNMatSol(0), mNBook(0), mChi2(0), mChi2Ini(0), mD0(0), mD1(0), mSig0(0), mSig1(0), mVolID(0), mLabel(0), mSolMat(0), mMatErr(0) { // def c-tor @@ -41,7 +41,7 @@ AliAlgResFast::AliAlgResFast() } //________________________________________________ -AliAlgResFast::~AliAlgResFast() +ResidualsControllerFast::~ResidualsControllerFast() { // d-tor delete[] mD0; @@ -55,7 +55,7 @@ AliAlgResFast::~AliAlgResFast() } //________________________________________________ -void AliAlgResFast::resize(int np) +void ResidualsControllerFast::resize(int np) { // resize container if (np > mNBook) { @@ -91,7 +91,7 @@ void AliAlgResFast::resize(int np) } //____________________________________________ -void AliAlgResFast::Clear(const Option_t*) +void ResidualsControllerFast::Clear(const Option_t*) { // reset record mNPoints = 0; @@ -101,7 +101,7 @@ void AliAlgResFast::Clear(const Option_t*) } //____________________________________________ -void AliAlgResFast::Print(const Option_t* /*opt*/) const +void ResidualsControllerFast::Print(const Option_t* /*opt*/) const { // print info printf("%3s:%1s (%9s/%5s) %6s | [ %7s:%7s ]\n", "Pnt", "M", "Label", @@ -134,7 +134,7 @@ void AliAlgResFast::Print(const Option_t* /*opt*/) const } //____________________________________________ -void AliAlgResFast::setResSigMeas(int ip, int ord, float res, float sig) +void ResidualsControllerFast::setResSigMeas(int ip, int ord, float res, float sig) { // assign residual and error for measurement if (ord == 0) { @@ -147,7 +147,7 @@ void AliAlgResFast::setResSigMeas(int ip, int ord, float res, float sig) } //____________________________________________ -void AliAlgResFast::setMatCorr(int id, float res, float sig) +void ResidualsControllerFast::setMatCorr(int id, float res, float sig) { // assign residual and error for material correction mSolMat[id] = res; @@ -155,7 +155,7 @@ void AliAlgResFast::setMatCorr(int id, float res, float sig) } //____________________________________________ -void AliAlgResFast::setLabel(int ip, int lab, int vol) +void ResidualsControllerFast::setLabel(int ip, int lab, int vol) { // set label/volid of measured volume mVolID[ip] = vol; From a7f46c75ca14b170fe687d280722682cd3093ed2 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Wed, 14 Apr 2021 19:03:53 +0200 Subject: [PATCH 217/770] [ALIGN] refactor utils --- .../Align/include/Align/AlignableDetector.h | 40 ++-- .../include/Align/AlignableDetectorITS.h | 10 +- Detectors/Align/include/Align/Controller.h | 54 ++--- Detectors/Align/include/Align/utils.h | 208 +++++++++--------- Detectors/Align/src/AlignableDetector.cxx | 10 +- Detectors/Align/src/AlignableDetectorITS.cxx | 2 +- Detectors/Align/src/AlignableSensorTRD.cxx | 4 +- Detectors/Align/src/AlignmentTrack.cxx | 2 +- Detectors/Align/src/Controller.cxx | 26 +-- 9 files changed, 182 insertions(+), 174 deletions(-) diff --git a/Detectors/Align/include/Align/AlignableDetector.h b/Detectors/Align/include/Align/AlignableDetector.h index 51a93598a276f..557eff28862ed 100644 --- a/Detectors/Align/include/Align/AlignableDetector.h +++ b/Detectors/Align/include/Align/AlignableDetector.h @@ -144,34 +144,34 @@ class AlignableDetector : public TNamed setDisabledColl(); setDisabledCosm(); } - void setDisabledColl(bool v = true) { setDisabled(utils::kColl, v); } - void setDisabledCosm(bool v = true) { setDisabled(utils::kCosm, v); } + void setDisabledColl(bool v = true) { setDisabled(utils::Coll, v); } + void setDisabledCosm(bool v = true) { setDisabled(utils::Cosm, v); } bool isDisabled(int tp) const { return mDisabled[tp]; } bool isDisabled() const { return IsDisabledColl() && IsDisabledCosm(); } - bool IsDisabledColl() const { return isDisabled(utils::kColl); } - bool IsDisabledCosm() const { return isDisabled(utils::kCosm); } + bool IsDisabledColl() const { return isDisabled(utils::Coll); } + bool IsDisabledCosm() const { return isDisabled(utils::Cosm); } // void setTrackFlagSel(int tp, uint64_t f) { mTrackFlagSel[tp] = f; } - void setTrackFlagSelColl(uint64_t f) { setTrackFlagSel(utils::kColl, f); } - void setTrackFlagSelCosm(uint64_t f) { setTrackFlagSel(utils::kCosm, f); } + void setTrackFlagSelColl(uint64_t f) { setTrackFlagSel(utils::Coll, f); } + void setTrackFlagSelCosm(uint64_t f) { setTrackFlagSel(utils::Cosm, f); } uint64_t getTrackFlagSel(int tp) const { return mTrackFlagSel[tp]; } - uint64_t getTrackFlagSelColl() const { return getTrackFlagSel(utils::kColl); } - uint64_t getTrackFlagSelCosm() const { return getTrackFlagSel(utils::kCosm); } + uint64_t getTrackFlagSelColl() const { return getTrackFlagSel(utils::Coll); } + uint64_t getTrackFlagSelCosm() const { return getTrackFlagSel(utils::Cosm); } // void setNPointsSel(int tp, int n) { mNPointsSel[tp] = n; } - void setNPointsSelColl(int n) { setNPointsSel(utils::kColl, n); } - void setNPointsSelCosm(int n) { setNPointsSel(utils::kCosm, n); } + void setNPointsSelColl(int n) { setNPointsSel(utils::Coll, n); } + void setNPointsSelCosm(int n) { setNPointsSel(utils::Cosm, n); } int getNPointsSel(int tp) const { return mNPointsSel[tp]; } - int getNPointsSelColl() const { return getNPointsSel(utils::kColl); } - int getNPointsSelCosm() const { return getNPointsSel(utils::kCosm); } + int getNPointsSelColl() const { return getNPointsSel(utils::Coll); } + int getNPointsSelCosm() const { return getNPointsSel(utils::Cosm); } // // bool isObligatory(int tp) const { return mObligatory[tp]; } - bool isObligatoryColl() const { return isObligatory(utils::kColl); } - bool isObligatoryCosm() const { return isObligatory(utils::kCosm); } + bool isObligatoryColl() const { return isObligatory(utils::Coll); } + bool isObligatoryCosm() const { return isObligatory(utils::Cosm); } void setObligatory(int tp, bool v = true); - void setObligatoryColl(bool v = true) { setObligatory(utils::kColl, v); } - void setObligatoryCosm(bool v = true) { setObligatory(utils::kCosm, v); } + void setObligatoryColl(bool v = true) { setObligatory(utils::Coll, v); } + void setObligatoryCosm(bool v = true) { setObligatory(utils::Cosm, v); } // void addAutoConstraints() const; void constrainOrphans(const double* sigma, const char* match = 0); @@ -220,10 +220,10 @@ class AlignableDetector : public TNamed int* mParLabs; //! labels for parameters // // Track selection - bool mDisabled[utils::kNTrackTypes]; // detector disabled/enabled in the track - bool mObligatory[utils::kNTrackTypes]; // detector must be present in the track - uint64_t mTrackFlagSel[utils::kNTrackTypes]; // flag for track selection - int mNPointsSel[utils::kNTrackTypes]; // min number of points to require + bool mDisabled[utils::NTrackTypes]; // detector disabled/enabled in the track + bool mObligatory[utils::NTrackTypes]; // detector must be present in the track + uint64_t mTrackFlagSel[utils::NTrackTypes]; // flag for track selection + int mNPointsSel[utils::NTrackTypes]; // min number of points to require // int mUseErrorParam; // signal that points need to be updated using track info, 0 - no double mAddError[2]; // additional error increment for measurement diff --git a/Detectors/Align/include/Align/AlignableDetectorITS.h b/Detectors/Align/include/Align/AlignableDetectorITS.h index caa40fce1e44c..50166d5d72d8a 100644 --- a/Detectors/Align/include/Align/AlignableDetectorITS.h +++ b/Detectors/Align/include/Align/AlignableDetectorITS.h @@ -48,12 +48,12 @@ class AlignableDetectorITS : public AlignableDetector virtual void UpdatePointByTrackInfo(AlignmentPoint* pnt, const AliExternalTrackParam* t) const; virtual void setUseErrorParam(int v = 1); void SetITSSelPattern(int trtype, ITSSel_t sel) { fITSPatt[trtype] = sel; } - void SetITSSelPatternColl(ITSSel_t sel = kSPDAny) { SetITSSelPattern(utils::kColl, sel); } - void SetITSSelPatternCosm(ITSSel_t sel = kSPDNoSel) { SetITSSelPattern(utils::kCosm, sel); } + void SetITSSelPatternColl(ITSSel_t sel = kSPDAny) { SetITSSelPattern(utils::Coll, sel); } + void SetITSSelPatternCosm(ITSSel_t sel = kSPDNoSel) { SetITSSelPattern(utils::Cosm, sel); } int GetITSSelPattern(int tp) const { return fITSPatt[tp]; } - int GetITSSelPatternColl() const { return fITSPatt[utils::kColl]; } - int GetITSSelPatternCosm() const { return fITSPatt[utils::kCosm]; } + int GetITSSelPatternColl() const { return fITSPatt[utils::Coll]; } + int GetITSSelPatternCosm() const { return fITSPatt[utils::Cosm]; } // virtual void Print(const Option_t* opt = "") const; // @@ -70,7 +70,7 @@ class AlignableDetectorITS : public AlignableDetector // protected: // - int fITSPatt[utils::kNTrackTypes]; // ITS hits selection pattern for coll/cosm tracks + int fITSPatt[utils::NTrackTypes]; // ITS hits selection pattern for coll/cosm tracks // static const char* fgkHitsSel[kNSPDSelTypes]; // ITS selection names // diff --git a/Detectors/Align/include/Align/Controller.h b/Detectors/Align/include/Align/Controller.h index 964eaca314213..d5f8cdfffbbef 100644 --- a/Detectors/Align/include/Align/Controller.h +++ b/Detectors/Align/include/Align/Controller.h @@ -156,10 +156,10 @@ class Controller : public TObject bool getFieldOn() const { return mFieldOn; } void setFieldOn(bool v = true) { mFieldOn = v; } int getTracksType() const { return mTracksType; } - void setTracksType(int t = utils::kColl) { mTracksType = t; } - bool isCosmic() const { return mTracksType == utils::kCosm; } - bool isCollision() const { return mTracksType == utils::kColl; } - void setCosmic(bool v = true) { mTracksType = v ? utils::kCosm : utils::kColl; } + void setTracksType(int t = utils::Coll) { mTracksType = t; } + bool isCosmic() const { return mTracksType == utils::Cosm; } + bool isCollision() const { return mTracksType == utils::Coll; } + void setCosmic(bool v = true) { mTracksType = v ? utils::Cosm : utils::Coll; } float getStat(int cls, int tp) const { return mStat[cls][tp]; } // void setESDTree(const TTree* tr) { mESDTree = tr; } @@ -185,22 +185,22 @@ class Controller : public TObject // double getPtMin(bool tp) const { return mPtMin[tp]; } void setPtMin(bool tp, double pt) { mPtMin[tp] = pt; } - void setPtMinColl(double pt = 0.7) { setPtMin(utils::kColl, pt); } - void setPtMinCosm(double pt = 1.0) { setPtMin(utils::kCosm, pt); } + void setPtMinColl(double pt = 0.7) { setPtMin(utils::Coll, pt); } + void setPtMinCosm(double pt = 1.0) { setPtMin(utils::Cosm, pt); } // double getEtaMax(bool tp) const { return mEtaMax[tp]; } void setEtaMax(bool tp, double eta) { mEtaMax[tp] = eta; } - void setEtaMaxColl(double eta = 1.5) { setEtaMax(utils::kColl, eta); } - void setEtaMaxCosm(double eta = 1.5) { setEtaMax(utils::kCosm, eta); } + void setEtaMaxColl(double eta = 1.5) { setEtaMax(utils::Coll, eta); } + void setEtaMaxCosm(double eta = 1.5) { setEtaMax(utils::Cosm, eta); } // - void setDefPtBOffCosm(double pt = 5.0) { mDefPtBOff[utils::kCosm] = pt > 0.3 ? pt : 0.3; } - void setDefPtBOffColl(double pt = 0.6) { mDefPtBOff[utils::kColl] = pt > 0.3 ? pt : 0.3; } + void setDefPtBOffCosm(double pt = 5.0) { mDefPtBOff[utils::Cosm] = pt > 0.3 ? pt : 0.3; } + void setDefPtBOffColl(double pt = 0.6) { mDefPtBOff[utils::Coll] = pt > 0.3 ? pt : 0.3; } double getDefPtBOff(bool tp) { return mDefPtBOff[tp]; } // int getMinDetAcc(bool tp) const { return mMinDetAcc[tp]; } void setMinDetAcc(bool tp, int n) { mMinDetAcc[tp] = n; } - void setMinDetAccColl(int n = 1) { setMinDetAcc(utils::kColl, n); } - void setMinDetAccCosm(int n = 1) { setMinDetAcc(utils::kCosm, n); } + void setMinDetAccColl(int n = 1) { setMinDetAcc(utils::Coll, n); } + void setMinDetAccCosm(int n = 1) { setMinDetAcc(utils::Cosm, n); } // int getVtxMinCont() const { return mVtxMinCont; } void setVtxMinCont(int n) { mVtxMinCont = n; } @@ -395,17 +395,17 @@ class Controller : public TObject TObjArray mConstraints; // array of constraints // // Track selection - uint32_t mSelEventSpecii; // consider only these event specii - uint32_t mObligatoryDetPattern[utils::kNTrackTypes]; // pattern of obligatory detectors - bool mCosmicSelStrict; // if true, each cosmic track leg selected like separate track - int mMinPoints[utils::kNTrackTypes][2]; // require min points per leg (case Boff,Bon) - int mMinDetAcc[utils::kNTrackTypes]; // min number of detector required in track - double mDefPtBOff[utils::kNTrackTypes]; // nominal pt for tracks in Boff run - double mPtMin[utils::kNTrackTypes]; // min pT of tracks to consider - double mEtaMax[utils::kNTrackTypes]; // eta cut on tracks - int mVtxMinCont; // require min number of contributors in Vtx - int mVtxMaxCont; // require max number of contributors in Vtx - int mVtxMinContVC; // min number of contributors to use as constraint + uint32_t mSelEventSpecii; // consider only these event specii + uint32_t mObligatoryDetPattern[utils::NTrackTypes]; // pattern of obligatory detectors + bool mCosmicSelStrict; // if true, each cosmic track leg selected like separate track + int mMinPoints[utils::NTrackTypes][2]; // require min points per leg (case Boff,Bon) + int mMinDetAcc[utils::NTrackTypes]; // min number of detector required in track + double mDefPtBOff[utils::NTrackTypes]; // nominal pt for tracks in Boff run + double mPtMin[utils::NTrackTypes]; // min pT of tracks to consider + double mEtaMax[utils::NTrackTypes]; // eta cut on tracks + int mVtxMinCont; // require min number of contributors in Vtx + int mVtxMaxCont; // require max number of contributors in Vtx + int mVtxMinContVC; // min number of contributors to use as constraint // int mMinITSClforVC; // use vertex constraint for tracks with enough points int mITSPattforVC; // optional request on ITS hits to allow vertex constraint @@ -479,16 +479,16 @@ class Controller : public TObject inline void Controller::setMinPointsColl(int vbOff, int vbOn) { // ask min number of points per track - setMinPoints(utils::kColl, false, vbOff); - setMinPoints(utils::kColl, true, vbOn); + setMinPoints(utils::Coll, false, vbOff); + setMinPoints(utils::Coll, true, vbOn); } //__________________________________________________________ inline void Controller::setMinPointsCosm(int vbOff, int vbOn) { // ask min number of points per track - setMinPoints(utils::kCosm, false, vbOff); - setMinPoints(utils::kCosm, true, vbOn); + setMinPoints(utils::Cosm, false, vbOff); + setMinPoints(utils::Cosm, true, vbOn); } } // namespace align } // namespace o2 diff --git a/Detectors/Align/include/Align/utils.h b/Detectors/Align/include/Align/utils.h index 5852bfffadea4..31a51d0166b9b 100644 --- a/Detectors/Align/include/Align/utils.h +++ b/Detectors/Align/include/Align/utils.h @@ -34,95 +34,95 @@ using covMat_t = typename trackParam_t::covMat_t; namespace utils { -const double kAlmostZeroD = 1e-15; -const float kAlmostZeroF = 1e-11; -const double kAlmostOneD = 1. - kAlmostZeroD; -const float kAlmostOneF = 1. - kAlmostZeroF; -const double kTinyDist = 1.e-7; // ignore distances less that this -// -enum { kColl, - kCosm, - kNTrackTypes }; -// -inline double sector2Alpha(int sect); -inline int phi2Sector(double alpha); -inline double sectorDAlpha() { return constants::math::PI / 9; } -// -template -void bringTo02Pi(F& phi); -template -void bringToPiPM(F& phi); -template -bool okForPhiMin(F phiMin, F phi); -template -bool okForPhiMax(F phiMax, F phi); -template -F meanPhiSmall(F phi0, F phi1); -template -F deltaPhiSmall(F phi0, F phi1); -template -bool smallerAbs(F d, F tolD) +constexpr double AlmostZeroD = 1e-15; +constexpr float AlmostZeroF = 1e-11; +constexpr double AlmostOneD = 1. - AlmostZeroD; +constexpr float AlmostOneF = 1. - AlmostZeroF; +constexpr double TinyDist = 1.e-7; // ignore distances less that this + +//_________________________________________________________________________________ +enum { Coll, + Cosm, + NTrackTypes }; + +//_________________________________________________________________________________ +inline constexpr double sectorDAlpha() noexcept { - return std::abs(d) < tolD; -} -template -bool smaller(F d, F tolD) + return constants::math::PI / 9; +}; + +//_________________________________________________________________________________ +inline constexpr double sector2Alpha(int sect) noexcept { - return d < tolD; -} -// -inline int numberOfBitsSet(uint32_t x); -inline bool isZeroAbs(double d) { return smallerAbs(d, kAlmostZeroD); } -inline bool isZeroAbs(float f) { return smallerAbs(f, kAlmostZeroF); } -inline bool isZeroPos(double d) { return smaller(d, kAlmostZeroD); } -inline bool isZeroPos(float f) { return smaller(f, kAlmostZeroF); } -// -int findKeyIndex(int key, const int* arr, int n); -// -void printBits(size_t patt, int maxBits); + // get barrel sector alpha in -pi:pi format + if (sect > 8) { + sect -= 18; + } + return (sect + 0.5) * sectorDAlpha(); +}; -} // namespace utils +//_________________________________________________________________________________ +inline int phi2Sector(double phi) +{ + // get barrel sector from phi in -pi:pi format + int sect = math_utils::nintd((phi * constants::math::Rad2Deg - 10) / 20.); + if (sect < 0) { + sect += 18; + } + return sect; +}; //_________________________________________________________________________________ template -inline void utils::bringTo02Pi(F& phi) +inline constexpr void bringTo02Pi(F& phi) noexcept { // bring phi to 0-2pi range - if (phi < 0) + if (phi < 0) { phi += constants::math::TwoPI; - else if (phi > constants::math::TwoPI) + } else if (phi > constants::math::TwoPI) { phi -= constants::math::TwoPI; -} + } +}; //_________________________________________________________________________________ template -inline void utils::bringToPiPM(F& phi) +inline constexpr void bringToPiPM(F& phi) noexcept { // bring phi to -pi:pi range - if (phi > constants::math::PI) + if (phi > constants::math::PI) { phi -= constants::math::TwoPI; -} + } +}; + //_________________________________________________________________________________ template -inline bool utils::okForPhiMin(F phiMin, F phi) +inline constexpr bool okForPhiMin(F phiMin, F phi) noexcept { // check if phi is above the phiMin, phi's must be in 0-2pi range - F dphi = phi - phiMin; - return ((dphi > 0 && dphi < constants::math::PI) || dphi < -constants::math::PI) ? true : false; -} + const F dphi = phi - phiMin; + if ((dphi > 0 && dphi < constants::math::PI) || dphi < -constants::math::PI) { + return true; + } else { + return false; + } +}; //_________________________________________________________________________________ template -inline bool utils::okForPhiMax(F phiMax, F phi) +inline constexpr bool okForPhiMax(F phiMax, F phi) noexcept { // check if phi is below the phiMax, phi's must be in 0-2pi range - F dphi = phi - phiMax; - return ((dphi < 0 && dphi > -constants::math::PI) || dphi > constants::math::PI) ? true : false; -} + const F dphi = phi - phiMax; + if ((dphi < 0 && dphi > -constants::math::PI) || dphi > constants::math::PI) { + return true; + } else { + return false; + } +}; //_________________________________________________________________________________ template -inline F utils::meanPhiSmall(F phi0, F phi1) +constexpr F meanPhiSmall(F phi0, F phi1) { // return mean phi, assume phis in 0:2pi F phi; @@ -131,19 +131,20 @@ inline F utils::meanPhiSmall(F phi0, F phi1) phi0 = phi1; phi1 = phi; } - if (phi0 > phi1) + if (phi0 > phi1) { phi = (phi1 - (constants::math::TwoPI - phi0)) / 2; // wrap - else + } else { phi = (phi0 + phi1) / 2; + } bringTo02Pi(phi); return phi; -} +}; //_________________________________________________________________________________ template -inline F utils::deltaPhiSmall(F phi0, F phi1) +constexpr F deltaPhiSmall(F phi0, F phi1) noexcept { - // return delta phi, assume phis in 0:2pi + // return delta phi, assume phi is in 0:2pi F del; if (!okForPhiMin(phi0, phi1)) { del = phi0; @@ -151,65 +152,72 @@ inline F utils::deltaPhiSmall(F phi0, F phi1) phi1 = del; } del = phi1 - phi0; - if (del < 0) + if (del < 0) { del += constants::math::TwoPI; + } return del; -} +}; //_________________________________________________________________________________ -inline int utils::numberOfBitsSet(uint32_t x) +template +inline constexpr bool smallerAbs(F d, F tolD) noexcept { - // count number of non-0 bits in 32bit word - x = x - ((x >> 1) & 0x55555555); - x = (x & 0x33333333) + ((x >> 2) & 0x33333333); - return (((x + (x >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; -} + return std::abs(d) < tolD; +}; //_________________________________________________________________________________ -inline double utils::sector2Alpha(int sect) +template +inline constexpr bool smaller(F d, F tolD) noexcept { - // get barrel sector alpha in -pi:pi format - if (sect > 8) - sect -= 18; - return (sect + 0.5) * sectorDAlpha(); + return d < tolD; } //_________________________________________________________________________________ -inline int utils::phi2Sector(double phi) +inline constexpr int numberOfBitsSet(uint32_t x) noexcept { - // get barrel sector from phi in -pi:pi format - int sect = math_utils::nintd((phi * constants::math::Rad2Deg - 10) / 20.); - if (sect < 0) - sect += 18; - return sect; -} + // count number of non-0 bits in 32bit word + x = x - ((x >> 1) & 0x55555555); + x = (x & 0x33333333) + ((x >> 2) & 0x33333333); + return (((x + (x >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; +}; -//_______________________________________________________________ -inline void utils::printBits(size_t patt, int maxBits) -{ - // print maxBits of the pattern - maxBits = std::min(64, maxBits); - for (int i = 0; i < maxBits; i++) - printf("%c", ((patt >> i) & 0x1) ? '+' : '-'); -} +inline constexpr bool isZeroAbs(double d) noexcept { return smallerAbs(d, AlmostZeroD); }; +inline constexpr bool isZeroAbs(float f) noexcept { return smallerAbs(f, AlmostZeroF); } +inline constexpr bool isZeroPos(double d) noexcept { return smaller(d, AlmostZeroD); } +inline constexpr bool isZeroPos(float f) noexcept { return smaller(f, AlmostZeroF); } //__________________________________________ -inline int utils::findKeyIndex(int key, const int* arr, int n) +inline constexpr int findKeyIndex(int key, const int* arr, int n) noexcept { // finds index of key in the array - int imn = 0, imx = n - 1; + int imn = 0; + int imx = n - 1; while (imx >= imn) { - int mid = (imx + imn) >> 1; - if (arr[mid] == key) + const int mid = (imx + imn) >> 1; + if (arr[mid] == key) { return mid; - if (arr[mid] < key) + } + + if (arr[mid] < key) { imn = mid + 1; - else + } else { imx = mid - 1; + } } return -1; } +//_______________________________________________________________ +inline void printBits(size_t patt, int maxBits) +{ + // print maxBits of the pattern + maxBits = std::min(64, maxBits); + for (int i = 0; i < maxBits; i++) { + printf("%c", ((patt >> i) & 0x1) ? '+' : '-'); + } +}; + +} // namespace utils } // namespace align } // namespace o2 #endif diff --git a/Detectors/Align/src/AlignableDetector.cxx b/Detectors/Align/src/AlignableDetector.cxx index 1b055acfff555..eac84388f3fa5 100644 --- a/Detectors/Align/src/AlignableDetector.cxx +++ b/Detectors/Align/src/AlignableDetector.cxx @@ -73,7 +73,7 @@ AlignableDetector::AlignableDetector() SetUniqueID(6); mAddError[0] = mAddError[1] = 0; // - for (int i = 0; i < kNTrackTypes; i++) { + for (int i = 0; i < NTrackTypes; i++) { mDisabled[i] = false; mObligatory[i] = false; mTrackFlagSel[i] = 0; @@ -397,15 +397,15 @@ void AlignableDetector::Print(const Option_t* opt) const printf("from TrackPoints\n"); // printf("Allowed in Collisions: %7s | Cosmic: %7s\n", - isDisabled(kColl) ? " NO " : " YES ", isDisabled(kCosm) ? " NO " : " YES "); + isDisabled(Coll) ? " NO " : " YES ", isDisabled(Cosm) ? " NO " : " YES "); // printf("Obligatory in Collisions: %7s | Cosmic: %7s\n", - isObligatory(kColl) ? " YES " : " NO ", isObligatory(kCosm) ? " YES " : " NO "); + isObligatory(Coll) ? " YES " : " NO ", isObligatory(Cosm) ? " YES " : " NO "); // - fmt::printf("Sel. flags in Collisions: {:05#x}%05 | Cosmic: 0x{:05#x}%05\n", mTrackFlagSel[kColl], mTrackFlagSel[kCosm]); + fmt::printf("Sel. flags in Collisions: {:05#x}%05 | Cosmic: 0x{:05#x}%05\n", mTrackFlagSel[Coll], mTrackFlagSel[Cosm]); // printf("Min.points in Collisions: %7d | Cosmic: %7d\n", - mNPointsSel[kColl], mNPointsSel[kCosm]); + mNPointsSel[Coll], mNPointsSel[Cosm]); // if (!(IsDisabledColl() && IsDisabledCosm()) && opts.Contains("long")) for (int iv = 0; iv < getNVolumes(); iv++) diff --git a/Detectors/Align/src/AlignableDetectorITS.cxx b/Detectors/Align/src/AlignableDetectorITS.cxx index 6691af387b4cc..cf02b0e16d193 100644 --- a/Detectors/Align/src/AlignableDetectorITS.cxx +++ b/Detectors/Align/src/AlignableDetectorITS.cxx @@ -142,7 +142,7 @@ void AlignableDetectorITS::Print(const Option_t* opt) const { AlignableDetector::Print(opt); printf("Sel.pattern Collisions: %7s | Cosmic: %7s\n", - GetITSPattName(fITSPatt[kColl]), GetITSPattName(fITSPatt[kCosm])); + GetITSPattName(fITSPatt[Coll]), GetITSPattName(fITSPatt[Cosm])); } //____________________________________________ diff --git a/Detectors/Align/src/AlignableSensorTRD.cxx b/Detectors/Align/src/AlignableSensorTRD.cxx index 517d5f29dabc3..f26d0df04e55f 100644 --- a/Detectors/Align/src/AlignableSensorTRD.cxx +++ b/Detectors/Align/src/AlignableSensorTRD.cxx @@ -208,12 +208,12 @@ AlignmentPoint* AlignableSensorTRD::TrackPoint2AlgPoint(int pntId, const AliTrac // Correction for DVT, equivalent to shift in X at which Y is evaluated: dY = tg_phi * dvt { double dvt = det->GetCorrDVTWithCal(); - if (Abs(dvt) > kAlmostZeroD) { + if (Abs(dvt) > AlmostZeroD) { AliExternalTrackParam trc = *tr; if (!trc.RotateParamOnly(getAlpTracking())) return 0; double snp = trc.GetSnpAt(pnt->getXPoint(), AliTrackerBase::GetBz()); - if (Abs(snp) > kAlmostOneD) + if (Abs(snp) > AlmostOneD) return 0; double slpY = snp / Sqrt((1 - snp) * (1 + snp)); double* pYZ = (double*)pnt->getYZTracking(); diff --git a/Detectors/Align/src/AlignmentTrack.cxx b/Detectors/Align/src/AlignmentTrack.cxx index 2fc934de7380b..bce0f36c8077d 100644 --- a/Detectors/Align/src/AlignmentTrack.cxx +++ b/Detectors/Align/src/AlignmentTrack.cxx @@ -926,7 +926,7 @@ bool AlignmentTrack::combineTracks(trackParam_t& trcL, const trackParam_t& trcU) // CL' = CL - K*CL // vL' = vL + K(vU-vL) // - if (Abs(trcL.getX() - trcU.getX()) > kTinyDist || Abs(trcL.getAlpha() - trcU.getAlpha()) > kTinyDist) { + if (Abs(trcL.getX() - trcU.getX()) > TinyDist || Abs(trcL.getAlpha() - trcU.getAlpha()) > TinyDist) { LOG(error) << "Tracks must be defined at same reference X and Alpha"; trcL.print(); trcU.print(); diff --git a/Detectors/Align/src/Controller.cxx b/Detectors/Align/src/Controller.cxx index a9f5fd5ceae98..12e2e54a2c0e8 100644 --- a/Detectors/Align/src/Controller.cxx +++ b/Detectors/Align/src/Controller.cxx @@ -79,7 +79,7 @@ const Char_t* Controller::sHStatName[Controller::kNHVars] = { //________________________________________________________________ Controller::Controller(const char* configMacro, int refRun) - : mNDet(0), mNDOFs(0), mRunNumber(-1), mFieldOn(false), mTracksType(kColl), mAlgTrack(0), mVtxSens(0), mConstraints(), + : mNDet(0), mNDOFs(0), mRunNumber(-1), mFieldOn(false), mTracksType(Coll), mAlgTrack(0), mVtxSens(0), mConstraints(), // fSelEventSpecii(AliRecoParam::kCosmic | AliRecoParam::kLowMult | AliRecoParam::kHighMult | AliRecoParam::kDefault), FIXME(milettri): needs AliRecoParam mSelEventSpecii(0), // FIXME(milettri): needs AliRecoParam mCosmicSelStrict(false), @@ -148,7 +148,7 @@ Controller::Controller(const char* configMacro, int refRun) setEtaMaxCosm(); setMinDetAccColl(); setMinDetAccCosm(); - for (int i = 0; i < kNTrackTypes; i++) { + for (int i = 0; i < NTrackTypes; i++) { mObligatoryDetPattern[i] = 0; } // @@ -275,7 +275,7 @@ void Controller::initDOFs() nact++; ndfAct += det->getNDOFs(); } - for (int i = 0; i < kNTrackTypes; i++) + for (int i = 0; i < NTrackTypes; i++) if (nact < mMinDetAcc[i]) LOG(FATAL) << nact << " detectors are active, while " << mMinDetAcc[i] << " in track are asked"; // @@ -354,7 +354,7 @@ void Controller::addDetector(uint32_t id, AlignableDetector* det) mDetectors[mNDet] = det; mDetPos[id] = mNDet; det->setAlgSteer(this); - for (int i = 0; i < kNTrackTypes; i++) + for (int i = 0; i < NTrackTypes; i++) setObligatoryDetector(id, i, det->isObligatory(i)); mNDet++; // @@ -713,8 +713,8 @@ bool Controller::checkDetectorPoints(const int* npsel) const // // // // upper leg points marked as the track going in inverse direction // int np = det->ProcessPoints(fESDTrack[leg], mAlgTrack, leg == kCosmUp); -// if (np < det->getNPointsSel(kCosm) && mCosmicSelStrict && -// det->isObligatory(kCosm)) +// if (np < det->getNPointsSel(Cosm) && mCosmicSelStrict && +// det->isObligatory(Cosm)) // return false; // npsel[idet] += np; // nPleg += np; @@ -728,7 +728,7 @@ bool Controller::checkDetectorPoints(const int* npsel) const // // // mAlgTrack->copyFrom(cosmTr); // if (!getFieldOn()) -// mAlgTrack->imposePtBOff(mDefPtBOff[utils::kCosm]); +// mAlgTrack->imposePtBOff(mDefPtBOff[utils::Cosm]); // mAlgTrack->setFieldON(getFieldOn()); // mAlgTrack->sortPoints(); // // @@ -1071,11 +1071,11 @@ void Controller::Print(const Option_t* opt) const printBits((uint64_t)mSelEventSpecii, 5); printf("\n"); printf("%-40s:\t%d/%d\n", "Min points per collisions track (BOff/ON)", - mMinPoints[kColl][0], mMinPoints[kColl][1]); + mMinPoints[Coll][0], mMinPoints[Coll][1]); printf("%-40s:\t%d/%d\n", "Min points per cosmic track leg (BOff/ON)", - mMinPoints[kCosm][0], mMinPoints[kCosm][1]); - printf("%-40s:\t%d\n", "Min detectots per collision track", mMinDetAcc[kColl]); - printf("%-40s:\t%d (%s)\n", "Min detectots per cosmic track/leg", mMinDetAcc[kCosm], + mMinPoints[Cosm][0], mMinPoints[Cosm][1]); + printf("%-40s:\t%d\n", "Min detectots per collision track", mMinDetAcc[Coll]); + printf("%-40s:\t%d (%s)\n", "Min detectots per cosmic track/leg", mMinDetAcc[Cosm], mCosmicSelStrict ? "STRICT" : "SOFT"); printf("%-40s:\t%d/%d\n", "Min/Max vertex contrib. to accept event", mVtxMinCont, mVtxMaxCont); printf("%-40s:\t%d\n", "Min vertex contrib. for constraint", mVtxMinContVC); @@ -1085,8 +1085,8 @@ void Controller::Print(const Option_t* opt) const "ITSNAME"); // FIXME(milettri): needs AlignableDetectorITS printf("%-40s:\t%.4f/%.4f/%.2f\n", "DCAr/DCAz/Chi2 cut for vertex constraint", mMaxDCAforVC[0], mMaxDCAforVC[1], mMaxChi2forVC); - printf("Collision tracks: Min pT: %5.2f |etaMax|: %5.2f\n", mPtMin[kColl], mEtaMax[kColl]); - printf("Cosmic tracks: Min pT: %5.2f |etaMax|: %5.2f\n", mPtMin[kCosm], mEtaMax[kCosm]); + printf("Collision tracks: Min pT: %5.2f |etaMax|: %5.2f\n", mPtMin[Coll], mEtaMax[Coll]); + printf("Cosmic tracks: Min pT: %5.2f |etaMax|: %5.2f\n", mPtMin[Cosm], mEtaMax[Cosm]); // printf("%-40s:\t%s", "Config. for reference OCDB", mRefOCDBConf.Data()); if (mRefRunNumber >= 0) From 0f634231f1f6fc7e23ba845bccb6ff6c8b4ce299 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Wed, 14 Apr 2021 20:07:10 +0200 Subject: [PATCH 218/770] [ALIGN] refactor DOFStatistics --- Detectors/Align/include/Align/DOFStatistics.h | 36 ++++----- Detectors/Align/src/DOFStatistics.cxx | 73 +++++-------------- 2 files changed, 38 insertions(+), 71 deletions(-) diff --git a/Detectors/Align/include/Align/DOFStatistics.h b/Detectors/Align/include/Align/DOFStatistics.h index 734b8f6f386aa..d683be8948734 100644 --- a/Detectors/Align/include/Align/DOFStatistics.h +++ b/Detectors/Align/include/Align/DOFStatistics.h @@ -16,7 +16,10 @@ #ifndef DOFStatistics_H #define DOFStatistics_H +#include #include +#include + class TH1F; class TCollection; @@ -30,29 +33,26 @@ class Controller; class DOFStatistics : public TNamed { public: - DOFStatistics(int n = 0); - virtual ~DOFStatistics(); - // - int getNDOFs() const { return mNDOFs; } - int getStat(int idf) const { return idf < mNDOFs ? mStat[idf] : 0; } - int* getStat() const { return (int*)mStat; }; - void setStat(int idf, int v) { mStat[idf] = v; } - void addStat(int idf, int v) { mStat[idf] += v; } - int getNMerges() const { return mNMerges; } - TH1F* createHisto(Controller* st) const; - virtual void Print(Option_t* opt) const; + explicit DOFStatistics(int n = 0) : TNamed("DOFStatistics", "DOF statistics"), mStat{n, 0} {}; + + inline int getNDOFs() const noexcept { return mStat.size(); } + inline int getStat(int idf) const noexcept { return idf < getNDOFs() ? mStat[idf] : 0; } + inline const int* getStat() const noexcept { return mStat.data(); }; + inline void setStat(int idf, int v) { mStat[idf] = v; } + inline void addStat(int idf, int v) { mStat[idf] += v; } + inline int getNMerges() const noexcept { return mNMerges; } + std::unique_ptr buildHistogram(Controller* st) const; + virtual void Print(Option_t* opt) const { std::cout << "NDOFs: " << mStat.size() << " NMerges: " << mNMerges << "\n"; }; virtual int64_t merge(TCollection* list); - // + protected: - // DOFStatistics(const DOFStatistics&); DOFStatistics& operator=(const DOFStatistics&); - // + protected: - int mNDOFs; // number of dofs defined - int mNMerges; // number of merges - int* mStat; //[mNDOFs] statistics per DOF - // + int mNMerges{1}; // number of merges + std::vector mStat; // statistics per DOF + ClassDef(DOFStatistics, 1); }; } // namespace align diff --git a/Detectors/Align/src/DOFStatistics.cxx b/Detectors/Align/src/DOFStatistics.cxx index 2ac696f5fc1ea..aedc7ae54efa6 100644 --- a/Detectors/Align/src/DOFStatistics.cxx +++ b/Detectors/Align/src/DOFStatistics.cxx @@ -16,11 +16,8 @@ #include "Align/DOFStatistics.h" #include "Align/Controller.h" #include "Framework/Logger.h" -#include #include -using namespace TMath; - ClassImp(o2::align::DOFStatistics); namespace o2 @@ -28,69 +25,39 @@ namespace o2 namespace align { -//_________________________________________________________ -DOFStatistics::DOFStatistics(int n) - : TNamed("DOFstat", "DOF statistics"), mNDOFs(n), mNMerges(1), mStat(0) -{ - // def c-tor - if (mNDOFs) { - mStat = new int[n]; - memset(mStat, 0, mNDOFs * sizeof(int)); - } - // -} - -//_________________________________________________________ -DOFStatistics::~DOFStatistics() -{ - // d-r - delete[] mStat; -} - -//____________________________________________ -void DOFStatistics::Print(Option_t*) const -{ - // print info - printf("NDOFs: %d, NMerges: %d\n", mNDOFs, mNMerges); - // -} - //____________________________________________ -TH1F* DOFStatistics::createHisto(Controller* st) const +std::unique_ptr DOFStatistics::buildHistogram(Controller* controller) const { // create histo with stat. If steer object is supplied, build labels - if (!mNDOFs) - return 0; - TH1F* h = new TH1F("DOFstat", "statistics per DOF", mNDOFs, 0, mNDOFs); - for (int i = mNDOFs; i--;) { - h->SetBinContent(i + 1, mStat[i]); - if (st) - h->GetXaxis()->SetBinLabel(i + 1, st->getDOFLabelTxt(i)); + auto histogram = std::make_unique("DOFstat", "statistics per DOF", getNDOFs(), 0, getNDOFs()); + for (size_t i = 0; i < getNDOFs(); ++i) { + // Bin 0 is underflow bin + histogram->SetBinContent(i + 1, mStat[i]); + if (controller != nullptr) { + histogram->GetXaxis()->SetBinLabel(i + 1, controller->getDOFLabelTxt(i)); + } } - return h; + return histogram; } //______________________________________________________________________________ int64_t DOFStatistics::merge(TCollection* list) { // merge statistics - int nmerged = 0; - TIter next(list); - TObject* obj; - while ((obj = next())) { - DOFStatistics* stAdd = dynamic_cast(obj); - if (!stAdd) + int nMerged = 0; + TIter next{list}; + TObject* obj = nullptr; + while ((obj = next()) != nullptr) { + DOFStatistics* otherStats = dynamic_cast(obj); + if (!otherStats) { continue; - if (mNDOFs != stAdd->mNDOFs) { - LOG(ERROR) << "Different NDOF: " << mNDOFs << " vs " << stAdd->mNDOFs << "."; - return 0; } - for (int i = mNDOFs; i--;) - mStat[i] += stAdd->mStat[i]; - mNMerges += stAdd->mNMerges; - nmerged++; + assert(getNDOFs() == otherStats->getNDOFs()); + std::transform(std::begin(otherStats->mStat), std::end(otherStats->mStat), std::begin(mStat), std::begin(mStat), std::plus<>{}); + mNMerges += otherStats->mNMerges; + nMerged++; } - return nmerged; + return nMerged; } } // namespace align From 624c84f77e17ec7faab9a742bc67c0b639b6ed30 Mon Sep 17 00:00:00 2001 From: Michael Lettrich Date: Tue, 20 Apr 2021 14:42:12 +0200 Subject: [PATCH 219/770] [ALIGN] obey O2 codechecker * 0 -> nullptr * virtual -> override/final * use default for default constructors/destructors * replace c-style includes with c++ style includes * braces for single line if-else, for, while, and do-while --- .../Align/include/Align/AlignableDetector.h | 20 +- .../Align/include/Align/AlignableSensor.h | 26 +- .../Align/include/Align/AlignableVolume.h | 18 +- .../Align/include/Align/AlignmentPoint.h | 25 +- .../Align/include/Align/AlignmentTrack.h | 19 +- Detectors/Align/include/Align/Controller.h | 44 +- Detectors/Align/include/Align/DOFStatistics.h | 4 +- Detectors/Align/include/Align/EventVertex.h | 10 +- .../include/Align/GeometricalConstraint.h | 11 +- .../Align/include/Align/Millepede2Record.h | 8 +- .../Align/include/Align/ResidualsController.h | 6 +- .../include/Align/ResidualsControllerFast.h | 6 +- Detectors/Align/src/AlignLinkDef.h | 10 + Detectors/Align/src/AlignableDetector.cxx | 178 +++-- Detectors/Align/src/AlignableSensor.cxx | 47 +- Detectors/Align/src/AlignableVolume.cxx | 164 ++-- Detectors/Align/src/AlignmentPoint.cxx | 62 +- Detectors/Align/src/AlignmentTrack.cxx | 211 +++-- Detectors/Align/src/Controller.cxx | 728 ++++++++++-------- Detectors/Align/src/GeometricalConstraint.cxx | 133 ++-- Detectors/Align/src/Mille.cxx | 22 +- Detectors/Align/src/Millepede2Record.cxx | 25 +- Detectors/Align/src/ResidualsController.cxx | 42 +- .../Align/src/ResidualsControllerFast.cxx | 10 +- 24 files changed, 1083 insertions(+), 746 deletions(-) diff --git a/Detectors/Align/include/Align/AlignableDetector.h b/Detectors/Align/include/Align/AlignableDetector.h index 557eff28862ed..650dae4607238 100644 --- a/Detectors/Align/include/Align/AlignableDetector.h +++ b/Detectors/Align/include/Align/AlignableDetector.h @@ -18,7 +18,7 @@ #include #include -#include +#include #include "Align/utils.h" #include "Align/AlignmentTrack.h" #include "Align/DOFStatistics.h" @@ -46,7 +46,7 @@ class AlignableDetector : public TNamed // AlignableDetector(); AlignableDetector(const char* name, const char* title = "", int id = -1) : TNamed(name, title) { SetUniqueID(id); }; - virtual ~AlignableDetector(); + ~AlignableDetector() override; int getDetID() const { return GetUniqueID(); } detectors::DetID getO2DetID() const { return detectors::DetID(GetUniqueID()); }; void setDetID(uint32_t tp); @@ -74,7 +74,7 @@ class AlignableDetector : public TNamed AlignableSensor* getSensorByVolId(int vid) const { int sid = volID2SID(vid); - return sid < 0 ? 0 : getSensor(sid); + return sid < 0 ? nullptr : getSensor(sid); } AlignableSensor* getSensor(const char* symname) const { return (AlignableSensor*)mSensors.FindObject(symname); } AlignableVolume* getVolume(int id) const { return (AlignableVolume*)mVolumes.UncheckedAt(id); } @@ -95,7 +95,7 @@ class AlignableDetector : public TNamed bool isCondDOF(int dof) const; uint64_t getFreeDOFPattern() const { return mCalibDOF; } int getNProcessedPoints() const { return mNProcPoints; } - virtual const char* getCalibDOFName(int) const { return 0; } + virtual const char* getCalibDOFName(int) const { return nullptr; } virtual double getCalibDOFVal(int) const { return 0; } virtual double getCalibDOFValWithCal(int) const { return 0; } // @@ -103,11 +103,11 @@ class AlignableDetector : public TNamed virtual int assignDOFs(); virtual void initDOFs(); virtual void terminate(); - void fillDOFStat(DOFStatistics* dofst = 0) const; + void fillDOFStat(DOFStatistics* dofst = nullptr) const; virtual void addVolume(AlignableVolume* vol); virtual void defineVolumes(); virtual void defineMatrices(); - virtual void Print(const Option_t* opt = "") const; + void Print(const Option_t* opt = "") const override; // virtual int ProcessPoints(const AliESDtrack* esdTr, AlignmentTrack* algTrack, bool inv = false); FIXME(milettri): needs AliESDtrack virtual void updatePointByTrackInfo(AlignmentPoint* pnt, const trackParam_t* t) const; virtual void setUseErrorParam(int v = 0); @@ -126,9 +126,9 @@ class AlignableDetector : public TNamed void setInitDOFsDone() { SetBit(kInitDOFsDone); } bool getInitDOFsDone() const { return TestBit(kInitDOFsDone); } void fixNonSensors(); - void setFreeDOFPattern(uint32_t pat = 0xffffffff, int lev = -1, const char* match = 0); - void setDOFCondition(int dof, float condErr, int lev = -1, const char* match = 0); - int selectVolumes(TObjArray* arr, int lev = -1, const char* match = 0); + void setFreeDOFPattern(uint32_t pat = 0xffffffff, int lev = -1, const char* match = nullptr); + void setDOFCondition(int dof, float condErr, int lev = -1, const char* match = nullptr); + int selectVolumes(TObjArray* arr, int lev = -1, const char* match = nullptr); // int getNDOFs() const { return mNDOFs; } int getNCalibDOFs() const { return mNCalibDOF; } @@ -174,7 +174,7 @@ class AlignableDetector : public TNamed void setObligatoryCosm(bool v = true) { setObligatory(utils::Cosm, v); } // void addAutoConstraints() const; - void constrainOrphans(const double* sigma, const char* match = 0); + void constrainOrphans(const double* sigma, const char* match = nullptr); virtual void writePedeInfo(FILE* parOut, const Option_t* opt = "") const; virtual void writeCalibrationResults() const; diff --git a/Detectors/Align/include/Align/AlignableSensor.h b/Detectors/Align/include/Align/AlignableSensor.h index c2b868ecc8fbf..045748e6c98c3 100644 --- a/Detectors/Align/include/Align/AlignableSensor.h +++ b/Detectors/Align/include/Align/AlignableSensor.h @@ -39,10 +39,10 @@ class AlignableSensor : public AlignableVolume { public: // - AlignableSensor(const char* name = 0, int vid = 0, int iid = 0); - virtual ~AlignableSensor(); + AlignableSensor(const char* name = nullptr, int vid = 0, int iid = 0); + ~AlignableSensor() override = default; // - virtual void addChild(AlignableVolume*); + void addChild(AlignableVolume*) override; // void setDetector(AlignableDetector* det) { mDet = det; } AlignableDetector* getDetector() const { return mDet; } @@ -53,8 +53,8 @@ class AlignableSensor : public AlignableVolume void incrementStat() { mNProcPoints++; } // // derivatives calculation - virtual void dPosTraDParCalib(const AlignmentPoint* pnt, double* deriv, int calibID, const AlignableVolume* parent = 0) const; - virtual void dPosTraDParGeom(const AlignmentPoint* pnt, double* deriv, const AlignableVolume* parent = 0) const; + virtual void dPosTraDParCalib(const AlignmentPoint* pnt, double* deriv, int calibID, const AlignableVolume* parent = nullptr) const; + virtual void dPosTraDParGeom(const AlignmentPoint* pnt, double* deriv, const AlignableVolume* parent = nullptr) const; // virtual void dPosTraDParGeomLOC(const AlignmentPoint* pnt, double* deriv) const; virtual void dPosTraDParGeomTRA(const AlignmentPoint* pnt, double* deriv) const; @@ -73,18 +73,18 @@ class AlignableSensor : public AlignableVolume } const double* getAddError() const { return mAddError; } // - virtual void prepareMatrixT2L(); + void prepareMatrixT2L() override; // - virtual void setTrackingFrame(); - virtual bool isSensor() const { return true; } - virtual void Print(const Option_t* opt = "") const; + void setTrackingFrame() override; + bool isSensor() const override { return true; } + void Print(const Option_t* opt = "") const override; // virtual void updatePointByTrackInfo(AlignmentPoint* pnt, const trackParam_t* t) const; - virtual void updateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta); + void updateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix* cumulDelta) override; // // virtual AlignmentPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t) = 0; TODO(milettri): needs AliTrackPointArray AliESDtrack // - virtual int finalizeStat(DOFStatistics* h = 0); + int finalizeStat(DOFStatistics* h = nullptr) override; // virtual void prepareMatrixClAlg(); virtual void prepareMatrixClAlgReco(); @@ -95,8 +95,8 @@ class AlignableSensor : public AlignableVolume // protected: // - virtual bool IsSortable() const { return true; } - virtual int Compare(const TObject* a) const; + bool IsSortable() const override { return true; } + int Compare(const TObject* a) const override; // // --------- dummies ----------- AlignableSensor(const AlignableSensor&); diff --git a/Detectors/Align/include/Align/AlignableVolume.h b/Detectors/Align/include/Align/AlignableVolume.h index dd767a358fd59..7bd066d26c850 100644 --- a/Detectors/Align/include/Align/AlignableVolume.h +++ b/Detectors/Align/include/Align/AlignableVolume.h @@ -64,8 +64,8 @@ class AlignableVolume : public TNamed kExclFromParentConstraintBit = BIT(16) }; enum { kDefChildConstr = 0xff }; // - AlignableVolume(const char* symname = 0, int iid = 0); - virtual ~AlignableVolume(); + AlignableVolume(const char* symname = nullptr, int iid = 0); + ~AlignableVolume() override; // const char* getSymName() const { return GetName(); } // @@ -115,20 +115,21 @@ class AlignableVolume : public TNamed void setParent(AlignableVolume* par) { mParent = par; - if (par) + if (par) { par->addChild(this); + } } int countParents() const; // int getNChildren() const { return mChildren ? mChildren->GetEntriesFast() : 0; } - AlignableVolume* getChild(int i) const { return mChildren ? (AlignableVolume*)mChildren->UncheckedAt(i) : 0; } + AlignableVolume* getChild(int i) const { return mChildren ? (AlignableVolume*)mChildren->UncheckedAt(i) : nullptr; } virtual void addChild(AlignableVolume* ch); // double getXTracking() const { return mX; } double getAlpTracking() const { return mAlp; } // int getNProcessedPoints() const { return mNProcPoints; } - virtual int finalizeStat(DOFStatistics* h = 0); + virtual int finalizeStat(DOFStatistics* h = nullptr); void fillDOFStat(DOFStatistics* h) const; // float* getParVals() const { return mParVals; } @@ -137,8 +138,9 @@ class AlignableVolume : public TNamed int getParLab(int par) const { return mParLabs[par]; } void getParValGeom(double* delta) const { - for (int i = kNDOFGeom; i--;) + for (int i = kNDOFGeom; i--;) { delta[i] = mParVals[i]; + } } // void setParVals(int npar, double* vl, double* er); @@ -204,10 +206,10 @@ class AlignableVolume : public TNamed virtual bool isSensor() const { return false; } // virtual const char* getDOFName(int i) const; - virtual void Print(const Option_t* opt = "") const; + void Print(const Option_t* opt = "") const override; virtual void writePedeInfo(FILE* parOut, const Option_t* opt = "") const; // - static const char* getGeomDOFName(int i) { return i < kNDOFGeom ? sDOFName[i] : 0; } + static const char* getGeomDOFName(int i) { return i < kNDOFGeom ? sDOFName[i] : nullptr; } static void setDefGeomFree(uint8_t patt) { sDefGeomFree = patt; } static uint8_t getDefGeomFree() { return sDefGeomFree; } // diff --git a/Detectors/Align/include/Align/AlignmentPoint.h b/Detectors/Align/include/Align/AlignmentPoint.h index 1862baf74e034..4b43ea7d0c51b 100644 --- a/Detectors/Align/include/Align/AlignmentPoint.h +++ b/Detectors/Align/include/Align/AlignmentPoint.h @@ -61,7 +61,7 @@ class AlignmentPoint : public TObject kZ }; // AlignmentPoint(); - virtual ~AlignmentPoint() {} + ~AlignmentPoint() override = default; // void init(); void updatePointByTrackInfo(const trackParam_t* t); @@ -118,15 +118,17 @@ class AlignmentPoint : public TObject void setXSens(double x) { mXSens = x; } void setXYZTracking(const double r[3]) { - for (int i = 3; i--;) + for (int i = 3; i--;) { mXYZTracking[i] = r[i]; + } } void setXYZTracking(double x, double y, double z); void setYZErrTracking(double sy2, double syz, double sz2); void setYZErrTracking(const double* err) { - for (int i = 3; i--;) + for (int i = 3; i--;) { mErrYZTracking[i] = err[i]; + } } double getErrDiag(int i) const { return mErrDiag[i]; } // @@ -138,13 +140,15 @@ class AlignmentPoint : public TObject void getTrWSB(trackParam_t& etp) const; void setTrParamWSA(const double* param) { - for (int i = 5; i--;) + for (int i = 5; i--;) { mTrParamWSA[i] = param[i]; + } } void setTrParamWSB(const double* param) { - for (int i = 5; i--;) + for (int i = 5; i--;) { mTrParamWSB[i] = param[i]; + } } double getResidY() const { return getTrParamWSA(kParY) - getYTracking(); } double getResidZ() const { return getTrParamWSA(kParZ) - getZTracking(); } @@ -159,8 +163,9 @@ class AlignmentPoint : public TObject // void setMatCorrExp(double* p) { - for (int i = 5; i--;) + for (int i = 5; i--;) { mMatCorrExp[i] = p[i]; + } } float* getMatCorrExp() const { return (float*)mMatCorrExp; } float* getMatCorrCov() const { return (float*)mMatCorrCov; } @@ -177,12 +182,12 @@ class AlignmentPoint : public TObject void incrementStat(); // virtual void dumpCoordinates() const; - virtual void Print(Option_t* option = "") const; - virtual void Clear(Option_t* option = ""); + void Print(Option_t* option = "") const final; + void Clear(Option_t* option = "") final; // protected: - virtual bool IsSortable() const { return true; } - virtual int Compare(const TObject* a) const; + bool IsSortable() const final { return true; } + int Compare(const TObject* a) const final; // // ---------- dummies ---------- AlignmentPoint(const AlignmentPoint&); diff --git a/Detectors/Align/include/Align/AlignmentTrack.h b/Detectors/Align/include/Align/AlignmentTrack.h index d7b311139e9ea..1b79001993063 100644 --- a/Detectors/Align/include/Align/AlignmentTrack.h +++ b/Detectors/Align/include/Align/AlignmentTrack.h @@ -62,7 +62,7 @@ class AlignmentTrack : public trackParam_t, public TObject kParQ2Pt }; AlignmentTrack(); - virtual ~AlignmentTrack(); + ~AlignmentTrack() override = default; void defineDOFs(); double getMass() const { return mMass; } double getMinX2X0Pt2Account() const { return mMinX2X0Pt2Account; } @@ -76,16 +76,16 @@ class AlignmentTrack : public trackParam_t, public TObject int getInnerPointID() const { return mInnerPointID; } AlignmentPoint* getInnerPoint() const { return getPoint(mInnerPointID); } // - virtual void Clear(Option_t* opt = ""); - virtual void Print(Option_t* opt = "") const; + void Clear(Option_t* opt = "") final; + void Print(Option_t* opt = "") const final; virtual void dumpCoordinates() const; // bool propagateToPoint(trackParam_t& tr, const AlignmentPoint* pnt, double maxStep, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT, track::TrackLTIntegral* tLT = nullptr); bool propagateParamToPoint(trackParam_t& tr, const AlignmentPoint* pnt, double maxStep = 3, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT); // param only bool propagateParamToPoint(trackParam_t* trSet, int nTr, const AlignmentPoint* pnt, double maxStep = 3, double maxSnp = 0.95, MatCorrType mt = MatCorrType::USEMatCorrLUT); // params only // - bool calcResiduals(const double* params = 0); - bool calcResidDeriv(double* params = 0); + bool calcResiduals(const double* params = nullptr); + bool calcResidDeriv(double* params = nullptr); bool calcResidDerivGlo(AlignmentPoint* pnt); // bool isCosmic() const { return TestBit(kCosmicBit); } @@ -215,15 +215,18 @@ inline void AlignmentTrack::setParams(trackParam_t* trSet, int ntr, double x, do { // set parames for multiple tracks (VECTORIZE THIS) if (!add) { // full parameter supplied - for (int itr = ntr; itr--;) + for (int itr = ntr; itr--;) { setParams(trSet[itr], x, alp, par, false); + } return; } params_t partr{0}; // par is a correction to reference parameter - for (int i = mNLocExtPar; i--;) + for (int i = mNLocExtPar; i--;) { partr[i] = getParam(i) + par[i]; - for (int itr = ntr; itr--;) + } + for (int itr = ntr; itr--;) { setParams(trSet[itr], x, alp, partr.data(), false); + } } //____________________________________________________________________________________________ diff --git a/Detectors/Align/include/Align/Controller.h b/Detectors/Align/include/Align/Controller.h index d5f8cdfffbbef..f7764d32c716f 100644 --- a/Detectors/Align/include/Align/Controller.h +++ b/Detectors/Align/include/Align/Controller.h @@ -118,8 +118,8 @@ class Controller : public TObject }; // - Controller(const char* configMacro = 0, int refRun = -1); - virtual ~Controller(); + Controller(const char* configMacro = nullptr, int refRun = -1); + ~Controller() final; // bool LoadRefOCDB(); FIXME(milettri): needs OCDB // bool LoadRecoTimeOCDB(); FIXME(milettri): needs OCDB bool getUseRecoOCDB() const { return mUseRecoOCDB; } @@ -141,7 +141,7 @@ class Controller : public TObject void assignDOFs(); // - void addDetector(uint32_t id, AlignableDetector* det = 0); + void addDetector(uint32_t id, AlignableDetector* det = nullptr); void addDetector(AlignableDetector* det); // void addConstraint(const GeometricalConstraint* cs) { mConstraints.AddLast((TObject*)cs); } @@ -258,7 +258,14 @@ class Controller : public TObject bool addVertexConstraint(); int getNDetectors() const { return mNDet; } AlignableDetector* getDetector(int i) const { return mDetectors[i]; } - AlignableDetector* getDetectorByDetID(int i) const { return mDetPos[i] < 0 ? 0 : mDetectors[mDetPos[i]]; } + AlignableDetector* getDetectorByDetID(int i) const + { + if (mDetPos[i] < 0) { + return nullptr; + } else { + return mDetectors[mDetPos[i]]; + } + } AlignableDetector* getDetectorByVolID(int id) const; EventVertex* getVertexSensor() const { return mVtxSens; } // @@ -274,8 +281,8 @@ class Controller : public TObject void setMPSteerFileName(const char* name = "mpSteer.txt"); void setResidFileName(const char* name = "mpControlRes.root"); void setOutCDBPath(const char* name = "local://outOCDB"); - void setOutCDBComment(const char* cm = 0) { mOutCDBComment = cm; } - void setOutCDBResponsible(const char* v = 0) { mOutCDBResponsible = v; } + void setOutCDBComment(const char* cm = nullptr) { mOutCDBComment = cm; } + void setOutCDBResponsible(const char* v = nullptr) { mOutCDBResponsible = v; } // void SetOutCDBRunRange(int rmin = 0, int rmax = 999999999); FIXME(milettri): needs OCDB int* getOutCDBRunRange() const { return (int*)mOutCDBRunRange; } int getOutCDBRunMin() const { return mOutCDBRunRange[0]; } @@ -300,24 +307,27 @@ class Controller : public TObject void setMPOutType(int t) { mMPOutType = t; } void produceMPData(bool v = true) { - if (v) + if (v) { mMPOutType |= kMille; - else + } else { mMPOutType &= ~kMille; + } } void produceMPRecord(bool v = true) { - if (v) + if (v) { mMPOutType |= kMPRec; - else + } else { mMPOutType &= ~kMPRec; + } } void produceControlRes(bool v = true) { - if (v) + if (v) { mMPOutType |= kContR; - else + } else { mMPOutType &= ~kContR; + } } int getMPOutType() const { return mMPOutType; } bool getDoKalmanResid() const { return mDoKalmanResid; } @@ -337,12 +347,12 @@ class Controller : public TObject // void genPedeSteerFile(const Option_t* opt = "") const; void writePedeConstraints() const; - void checkConstraints(const char* params = 0); + void checkConstraints(const char* params = nullptr); DOFStatistics* GetDOFStat() const { return mDOFStat; } void setDOFStat(DOFStatistics* st) { mDOFStat = st; } - void detachDOFStat() { setDOFStat(0); } + void detachDOFStat() { setDOFStat(nullptr); } TH1* getHistoStat() const { return mHistoStat; } - void detachHistoStat() { setHistoStat(0); } + void detachHistoStat() { setHistoStat(nullptr); } void setHistoStat(TH1F* h) { mHistoStat = h; } void fillStatHisto(int type, float w = 1); void createStatHisto(); @@ -360,7 +370,7 @@ class Controller : public TObject const char* getRecoOCDBConfigMacro() const { return mRecoOCDBConf.Data(); } int getRefOCDBLoaded() const { return mRefOCDBLoaded; } // - virtual void Print(const Option_t* opt = "") const; + void Print(const Option_t* opt = "") const final; void printLabels() const; Char_t* getDOFLabelTxt(int idf) const; // @@ -373,7 +383,7 @@ class Controller : public TObject // // fast check of solution using derivatives void checkSol(TTree* mpRecTree, bool store = true, bool verbose = false, bool loc = true, const char* outName = "resFast"); - bool checkSol(Millepede2Record* rec, ResidualsControllerFast* rLG = 0, ResidualsControllerFast* rL = 0, bool verbose = true, bool loc = true); + bool checkSol(Millepede2Record* rec, ResidualsControllerFast* rLG = nullptr, ResidualsControllerFast* rL = nullptr, bool verbose = true, bool loc = true); // protected: // diff --git a/Detectors/Align/include/Align/DOFStatistics.h b/Detectors/Align/include/Align/DOFStatistics.h index d683be8948734..3254e7574a217 100644 --- a/Detectors/Align/include/Align/DOFStatistics.h +++ b/Detectors/Align/include/Align/DOFStatistics.h @@ -42,8 +42,8 @@ class DOFStatistics : public TNamed inline void addStat(int idf, int v) { mStat[idf] += v; } inline int getNMerges() const noexcept { return mNMerges; } std::unique_ptr buildHistogram(Controller* st) const; - virtual void Print(Option_t* opt) const { std::cout << "NDOFs: " << mStat.size() << " NMerges: " << mNMerges << "\n"; }; - virtual int64_t merge(TCollection* list); + void Print(Option_t* opt) const final { std::cout << "NDOFs: " << mStat.size() << " NMerges: " << mNMerges << "\n"; }; + int64_t merge(TCollection* list); protected: DOFStatistics(const DOFStatistics&); diff --git a/Detectors/Align/include/Align/EventVertex.h b/Detectors/Align/include/Align/EventVertex.h index dc3e3f24181f7..58ab64868eab6 100644 --- a/Detectors/Align/include/Align/EventVertex.h +++ b/Detectors/Align/include/Align/EventVertex.h @@ -43,18 +43,18 @@ class EventVertex : public AlignableSensor EventVertex(); // void applyCorrection(double* vtx) const; - virtual bool isSensor() const { return true; } + bool isSensor() const final { return true; } // void setAlpha(double alp) { mAlp = alp; prepareMatrixT2L(); } - virtual void prepareMatrixL2G(bool = 0) { mMatL2G.Clear(); } // unit matrix - virtual void prepareMatrixL2GIdeal() { mMatL2GIdeal.Clear(); } // unit matrix - virtual void prepareMatrixT2L(); + void prepareMatrixL2G(bool = 0) final { mMatL2G.Clear(); } // unit matrix + void prepareMatrixL2GIdeal() final { mMatL2GIdeal.Clear(); } // unit matrix + void prepareMatrixT2L() final; // - // virtual AlignmentPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); FIXME(milettri): needs AliTrackPointArray, AliESDtrack + // AlignmentPoint* TrackPoint2AlgPoint(int pntId, const AliTrackPointArray* trpArr, const AliESDtrack* t); FIXME(milettri): needs AliTrackPointArray, AliESDtrack // protected: EventVertex(const EventVertex&); diff --git a/Detectors/Align/include/Align/GeometricalConstraint.h b/Detectors/Align/include/Align/GeometricalConstraint.h index 33294b0c8d89c..7ea1615c893ae 100644 --- a/Detectors/Align/include/Align/GeometricalConstraint.h +++ b/Detectors/Align/include/Align/GeometricalConstraint.h @@ -26,7 +26,7 @@ #ifndef GEOMETRICALCONSTRAINT_H #define GEOMETRICALCONSTRAINT_H -#include +#include #include #include #include "Align/AlignableVolume.h" @@ -42,8 +42,8 @@ class GeometricalConstraint : public TNamed enum { kNDOFGeom = AlignableVolume::kNDOFGeom }; enum { kNoJacobianBit = BIT(14) }; // - GeometricalConstraint(const char* name = 0, const char* title = 0); - virtual ~GeometricalConstraint(); + GeometricalConstraint(const char* name = nullptr, const char* title = nullptr); + ~GeometricalConstraint() override; // void setParent(const AlignableVolume* par); const AlignableVolume* getParent() const { return mParent; } @@ -52,8 +52,9 @@ class GeometricalConstraint : public TNamed AlignableVolume* getChild(int i) const { return (AlignableVolume*)mChildren[i]; } void addChild(const AlignableVolume* v) { - if (v) + if (v) { mChildren.AddLast((AlignableVolume*)v); + } } // bool isDOFConstrained(int dof) const { return mConstraint & 0x1 << dof; } @@ -70,7 +71,7 @@ class GeometricalConstraint : public TNamed // void constrCoefGeom(const TGeoHMatrix& matRD, float* jac /*[kNDOFGeom][kNDOFGeom]*/) const; // - virtual void Print(const Option_t* opt = "") const; + void Print(const Option_t* opt = "") const final; virtual void writeChildrenConstraints(FILE* conOut) const; virtual void checkConstraint() const; virtual const char* getDOFName(int i) const { return AlignableVolume::getGeomDOFName(i); } diff --git a/Detectors/Align/include/Align/Millepede2Record.h b/Detectors/Align/include/Align/Millepede2Record.h index a098a8bf7dcea..adb03c3e62474 100644 --- a/Detectors/Align/include/Align/Millepede2Record.h +++ b/Detectors/Align/include/Align/Millepede2Record.h @@ -31,7 +31,7 @@ class Millepede2Record : public TObject enum { kCosmicBit = BIT(14) }; // Millepede2Record(); - virtual ~Millepede2Record(); + ~Millepede2Record() final; // int getRun() const { return GetUniqueID(); } void setRun(int r) { SetUniqueID(r); } @@ -64,13 +64,13 @@ class Millepede2Record : public TObject const int16_t* getArrLabLoc() const { return mIDLoc; } const int* getArrLabGlo() const { return mIDGlo; } // - bool fillTrack(const AlignmentTrack* trc, const int* id2Lab = 0); + bool fillTrack(const AlignmentTrack* trc, const int* id2Lab = nullptr); void dummyRecord(float res, float err, float dGlo, int labGlo); // void resize(int nresid, int nloc, int nglo); // - virtual void Clear(const Option_t* opt = ""); - virtual void Print(const Option_t* opt = "") const; + void Clear(const Option_t* opt = "") final; + void Print(const Option_t* opt = "") const final; // protected: // diff --git a/Detectors/Align/include/Align/ResidualsController.h b/Detectors/Align/include/Align/ResidualsController.h index 1c31058cb6df9..90d748be6f081 100644 --- a/Detectors/Align/include/Align/ResidualsController.h +++ b/Detectors/Align/include/Align/ResidualsController.h @@ -34,7 +34,7 @@ class ResidualsController : public TObject kKalmanDoneBit = BIT(16) }; // ResidualsController(); - virtual ~ResidualsController(); + ~ResidualsController() final; // void setRun(int r) { mRun = r; } void setBz(float v) { mBz = v; } @@ -101,8 +101,8 @@ class ResidualsController : public TObject // bool fillTrack(AlignmentTrack* trc, bool doKalman = kTRUE); void resize(int n); - virtual void Clear(const Option_t* opt = ""); - virtual void Print(const Option_t* opt = "re") const; + void Clear(const Option_t* opt = "") final; + void Print(const Option_t* opt = "re") const final; // protected: // diff --git a/Detectors/Align/include/Align/ResidualsControllerFast.h b/Detectors/Align/include/Align/ResidualsControllerFast.h index 616cc7f183e4a..17c39428b5733 100644 --- a/Detectors/Align/include/Align/ResidualsControllerFast.h +++ b/Detectors/Align/include/Align/ResidualsControllerFast.h @@ -30,7 +30,7 @@ class ResidualsControllerFast : public TObject kVertexBit = BIT(15) }; // ResidualsControllerFast(); - virtual ~ResidualsControllerFast(); + ~ResidualsControllerFast() final; // void setNPoints(int n) { @@ -75,8 +75,8 @@ class ResidualsControllerFast : public TObject void setLabel(int ip, int lab, int vol); // void resize(int n); - virtual void Clear(const Option_t* opt = ""); - virtual void Print(const Option_t* opt = "") const; + void Clear(const Option_t* opt = "") final; + void Print(const Option_t* opt = "") const final; // protected: // diff --git a/Detectors/Align/src/AlignLinkDef.h b/Detectors/Align/src/AlignLinkDef.h index 4944006dbab1b..5eb9f43b4a726 100644 --- a/Detectors/Align/src/AlignLinkDef.h +++ b/Detectors/Align/src/AlignLinkDef.h @@ -1,3 +1,13 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + #ifdef __CLING__ #pragma link off all globals; diff --git a/Detectors/Align/src/AlignableDetector.cxx b/Detectors/Align/src/AlignableDetector.cxx index eac84388f3fa5..d7db75d44c2fb 100644 --- a/Detectors/Align/src/AlignableDetector.cxx +++ b/Detectors/Align/src/AlignableDetector.cxx @@ -32,7 +32,7 @@ #include #include #include -#include +#include ClassImp(o2::align::AlignableDetector); @@ -45,16 +45,16 @@ namespace align //____________________________________________ AlignableDetector::AlignableDetector() - : mNDOFs(0), mVolIDMin(-1), mVolIDMax(-1), mNSensors(0), mSID2VolID(0), mNProcPoints(0) + : mNDOFs(0), mVolIDMin(-1), mVolIDMax(-1), mNSensors(0), mSID2VolID(nullptr), mNProcPoints(0) // , mNCalibDOF(0), mNCalibDOFFree(0), mCalibDOF(0), mFirstParGloID(-1), - mParVals(0), - mParErrs(0), - mParLabs(0) + mParVals(nullptr), + mParErrs(nullptr), + mParLabs(nullptr) // , mUseErrorParam(0), @@ -66,7 +66,7 @@ AlignableDetector::AlignableDetector() mPoolNPoints(0), mPoolFreePointID(0), mPointsPool(), - mAlgSteer(0) + mAlgSteer(nullptr) { // def c-tor SetUniqueID(Controller::kUndefined); // derived detectors must override this @@ -108,14 +108,14 @@ AlignableDetector::~AlignableDetector() // AlignmentPoint* apnt(0); // for (int ip = 0; ip < np; ip++) { // int vid = trP->GetVolumeID()[ip]; -// if (!sensorOfDetector(vid)) -// continue; +// if (!sensorOfDetector(vid)){ +// continue;} // apnt = getSensorByVolId(vid)->TrackPoint2AlgPoint(ip, trP, esdTr); -// if (!apnt) -// continue; +// if (!apnt){ +// continue;} // algTrack->addPoint(apnt); -// if (inv) -// apnt->setInvDir(); +// if (inv){ +// apnt->setInvDir();} // npSel++; // mNPoints++; // } @@ -147,8 +147,8 @@ void AlignableDetector::updateL2GRecoMatrices() // for (int iv = 0; iv < nvol; iv++) { // AlignableVolume* vol = getVolume(iv); // // call init for root level volumes, they will take care of their children - // if (!vol->getParent()) - // vol->updateL2GRecoMatrices(algArr, 0); + // if (!vol->getParent()){ + // vol->updateL2GRecoMatrices(algArr, 0);} // } // // } @@ -158,8 +158,9 @@ void AlignableDetector::applyAlignmentFromMPSol() { // apply alignment from millepede solution array to reference alignment level LOG(INFO) << "Applying alignment from Millepede solution"; - for (int isn = getNSensors(); isn--;) + for (int isn = getNSensors(); isn--;) { getSensor(isn)->applyAlignmentFromMPSol(); + } } //_________________________________________________________ @@ -229,10 +230,12 @@ void AlignableDetector::addVolume(AlignableVolume* vol) mSensors.AddLast(vol); ((AlignableSensor*)vol)->setDetector(this); int vid = ((AlignableSensor*)vol)->getVolID(); - if (mVolIDMin < 0 || vid < mVolIDMin) + if (mVolIDMin < 0 || vid < mVolIDMin) { mVolIDMin = vid; - if (mVolIDMax < 0 || vid > mVolIDMax) + } + if (mVolIDMax < 0 || vid > mVolIDMax) { mVolIDMax = vid; + } } // } @@ -245,7 +248,7 @@ void AlignableDetector::defineMatrices() TGeoHMatrix mtmp; // TIter next(&mVolumes); - AlignableVolume* vol(0); + AlignableVolume* vol(nullptr); while ((vol = (AlignableVolume*)next())) { // modified global-local matrix vol->prepareMatrixL2G(); @@ -261,8 +264,9 @@ void AlignableDetector::defineMatrices() next.Reset(); while ((vol = (AlignableVolume*)next())) { vol->prepareMatrixT2L(); - if (vol->isSensor()) - ((AlignableSensor*)vol)->prepareMatrixClAlg(); // alignment matrix + if (vol->isSensor()) { + ((AlignableSensor*)vol)->prepareMatrixClAlg(); + } // alignment matrix } // } @@ -289,8 +293,9 @@ void AlignableDetector::sortSensors() int AlignableDetector::initGeom() { // define hiearchy, initialize matrices, return number of global parameters - if (getInitGeomDone()) + if (getInitGeomDone()) { return 0; + } // defineVolumes(); sortSensors(); // VolID's must be in increasing order @@ -333,11 +338,13 @@ int AlignableDetector::assignDOFs() for (int iv = 0; iv < nvol; iv++) { AlignableVolume* vol = getVolume(iv); // call init for root level volumes, they will take care of their children - if (!vol->getParent()) + if (!vol->getParent()) { vol->assignDOFs(gloCount, pars, errs, labs); + } } - if (mNDOFs != gloCount - gloCount0) + if (mNDOFs != gloCount - gloCount0) { LOG(FATAL) << "Mismatch between declared " << mNDOFs << " and initialized " << (gloCount - gloCount0) << " DOFs for " << GetName(); + } return mNDOFs; } @@ -345,17 +352,21 @@ int AlignableDetector::assignDOFs() void AlignableDetector::initDOFs() { // initialize free parameters - if (getInitDOFsDone()) + if (getInitDOFsDone()) { LOG(FATAL) << "DOFs are already initialized for " << GetName(); + } // // process calibration DOFs - for (int i = 0; i < mNCalibDOF; i++) - if (mParErrs[i] < -9999 && isZeroAbs(mParVals[i])) + for (int i = 0; i < mNCalibDOF; i++) { + if (mParErrs[i] < -9999 && isZeroAbs(mParVals[i])) { fixDOF(i); + } + } // int nvol = getNVolumes(); - for (int iv = 0; iv < nvol; iv++) + for (int iv = 0; iv < nvol; iv++) { getVolume(iv)->initDOFs(); + } // calcFree(true); // @@ -370,12 +381,13 @@ int AlignableDetector::volID2SID(int vid) const int mn(0), mx(mNSensors - 1); while (mx >= mn) { int md((mx + mn) >> 1), vids(getSensor(md)->getVolID()); - if (vid < vids) + if (vid < vids) { mx = md - 1; - else if (vid > vids) + } else if (vid > vids) { mn = md + 1; - else + } else { return md; + } } return -1; } @@ -391,10 +403,11 @@ void AlignableDetector::Print(const Option_t* opt) const getVolIDMax(), mAddError[0], mAddError[1], mNProcPoints); // printf("Errors assignment: "); - if (mUseErrorParam) + if (mUseErrorParam) { printf("param %d\n", mUseErrorParam); - else + } else { printf("from TrackPoints\n"); + } // printf("Allowed in Collisions: %7s | Cosmic: %7s\n", isDisabled(Coll) ? " NO " : " YES ", isDisabled(Cosm) ? " NO " : " YES "); @@ -407,9 +420,11 @@ void AlignableDetector::Print(const Option_t* opt) const printf("Min.points in Collisions: %7d | Cosmic: %7d\n", mNPointsSel[Coll], mNPointsSel[Cosm]); // - if (!(IsDisabledColl() && IsDisabledCosm()) && opts.Contains("long")) - for (int iv = 0; iv < getNVolumes(); iv++) + if (!(IsDisabledColl() && IsDisabledCosm()) && opts.Contains("long")) { + for (int iv = 0; iv < getNVolumes(); iv++) { getVolume(iv)->Print(opt); + } + } // for (int i = 0; i < getNCalibDOFs(); i++) { printf("CalibDOF%2d: %-20s\t%e\n", i, getCalibDOFName(i), getCalibDOFValWithCal(i)); @@ -431,8 +446,9 @@ void AlignableDetector::setAddError(double sigy, double sigz) LOG(INFO) << "Adding sys.error " << std::fixed << std::setprecision(4) << sigy << " " << sigz << " to all sensors"; mAddError[0] = sigy; mAddError[1] = sigz; - for (int isn = getNSensors(); isn--;) + for (int isn = getNSensors(); isn--;) { getSensor(isn)->setAddError(sigy, sigz); + } // } @@ -469,8 +485,9 @@ void AlignableDetector::writePedeInfo(FILE* parOut, const Option_t* opt) const int nvol = getNVolumes(); for (int iv = 0; iv < nvol; iv++) { // call for root level volumes, they will take care of their children AlignableVolume* vol = getVolume(iv); - if (!vol->getParent()) + if (!vol->getParent()) { vol->writePedeInfo(parOut, opt); + } } // } @@ -496,8 +513,8 @@ void AlignableDetector::writeAlignmentResults() const // for (int iv = 0; iv < nvol; iv++) { // AlignableVolume* vol = getVolume(iv); // // call only for top level objects, they will take care of children - // if (!vol->getParent()) - // vol->createAlignmentObjects(arr); + // if (!vol->getParent()){ + // vol->createAlignmentObjects(arr);} // } // // // AliCDBManager* man = AliCDBManager::Instance(); @@ -517,12 +534,14 @@ bool AlignableDetector::ownsDOFID(int id) const // check if DOF ID belongs to this detector for (int iv = getNVolumes(); iv--;) { AlignableVolume* vol = getVolume(iv); // check only top level volumes - if (!vol->getParent() && vol->ownsDOFID(id)) + if (!vol->getParent() && vol->ownsDOFID(id)) { return true; + } } // calibration DOF? - if (id >= mFirstParGloID && id < mFirstParGloID + mNCalibDOF) + if (id >= mFirstParGloID && id < mFirstParGloID + mNCalibDOF) { return true; + } // return false; } @@ -533,12 +552,14 @@ AlignableVolume* AlignableDetector::getVolOfDOFID(int id) const // gets volume owning this DOF ID for (int iv = getNVolumes(); iv--;) { AlignableVolume* vol = getVolume(iv); - if (vol->getParent()) - continue; // check only top level volumes - if ((vol = vol->getVolOfDOFID(id))) + if (vol->getParent()) { + continue; + } // check only top level volumes + if ((vol = vol->getVolOfDOFID(id))) { return vol; + } } - return 0; + return nullptr; } //______________________________________________________ @@ -552,8 +573,9 @@ void AlignableDetector::terminate() for (int iv = 0; iv < nvol; iv++) { AlignableVolume* vol = getVolume(iv); // call init for root level volumes, they will take care of their children - if (!vol->getParent()) + if (!vol->getParent()) { mNProcPoints += vol->finalizeStat(st); + } } fillDOFStat(st); // fill stat for calib dofs } @@ -565,8 +587,9 @@ void AlignableDetector::addAutoConstraints() const int nvol = getNVolumes(); for (int iv = 0; iv < nvol; iv++) { // call for root level volumes, they will take care of their children AlignableVolume* vol = getVolume(iv); - if (!vol->getParent()) + if (!vol->getParent()) { vol->addAutoConstraints((TObjArray*)mAlgSteer->getConstraints()); + } } } @@ -576,8 +599,9 @@ void AlignableDetector::fixNonSensors() // fix all non-sensor volumes for (int i = getNVolumes(); i--;) { AlignableVolume* vol = getVolume(i); - if (vol->isSensor()) + if (vol->isSensor()) { continue; + } vol->setFreeDOFPattern(0); vol->setChildrenConstrainPattern(0); } @@ -588,16 +612,19 @@ int AlignableDetector::selectVolumes(TObjArray* arr, int lev, const char* match) { // select volumes matching to pattern and/or hierarchy level // - if (!arr) + if (!arr) { return 0; + } int nadd = 0; TString mts = match, syms; for (int i = getNVolumes(); i--;) { AlignableVolume* vol = getVolume(i); - if (lev >= 0 && vol->countParents() != lev) - continue; // wrong level - if (!mts.IsNull() && !(syms = vol->getSymName()).Contains(mts)) - continue; //wrong name + if (lev >= 0 && vol->countParents() != lev) { + continue; + } // wrong level + if (!mts.IsNull() && !(syms = vol->getSymName()).Contains(mts)) { + continue; + } //wrong name arr->AddLast(vol); nadd++; } @@ -614,10 +641,12 @@ void AlignableDetector::setFreeDOFPattern(uint32_t pat, int lev, const char* mat TString mts = match, syms; for (int i = getNVolumes(); i--;) { AlignableVolume* vol = getVolume(i); - if (lev >= 0 && vol->countParents() != lev) - continue; // wrong level - if (!mts.IsNull() && !(syms = vol->getSymName()).Contains(mts)) - continue; //wrong name + if (lev >= 0 && vol->countParents() != lev) { + continue; + } // wrong level + if (!mts.IsNull() && !(syms = vol->getSymName()).Contains(mts)) { + continue; + } //wrong name vol->setFreeDOFPattern(pat); } // @@ -632,15 +661,19 @@ void AlignableDetector::setDOFCondition(int dof, float condErr, int lev, const c TString mts = match, syms; for (int i = getNVolumes(); i--;) { AlignableVolume* vol = getVolume(i); - if (lev >= 0 && vol->countParents() != lev) - continue; // wrong level - if (!mts.IsNull() && !(syms = vol->getSymName()).Contains(mts)) - continue; //wrong name - if (dof >= vol->getNDOFs()) + if (lev >= 0 && vol->countParents() != lev) { + continue; + } // wrong level + if (!mts.IsNull() && !(syms = vol->getSymName()).Contains(mts)) { + continue; + } //wrong name + if (dof >= vol->getNDOFs()) { continue; + } vol->setParErr(dof, condErr); - if (condErr >= 0 && !vol->isFreeDOF(dof)) + if (condErr >= 0 && !vol->isFreeDOF(dof)) { vol->setFreeDOF(dof); + } //if (condErr<0 && vol->isFreeDOF(dof)) vol->fixDOF(dof); } // @@ -657,18 +690,21 @@ void AlignableDetector::constrainOrphans(const double* sigma, const char* match) TString mts = match, syms; GeometricalConstraint* constr = new GeometricalConstraint(); for (int i = 0; i < AlignableVolume::kNDOFGeom; i++) { - if (sigma[i] >= 0) + if (sigma[i] >= 0) { constr->constrainDOF(i); - else + } else { constr->unConstrainDOF(i); + } constr->setSigma(i, sigma[i]); } for (int i = getNVolumes(); i--;) { AlignableVolume* vol = getVolume(i); - if (vol->getParent()) - continue; // wrong level - if (!mts.IsNull() && !(syms = vol->getSymName()).Contains(mts)) - continue; //wrong name + if (vol->getParent()) { + continue; + } // wrong level + if (!mts.IsNull() && !(syms = vol->getSymName()).Contains(mts)) { + continue; + } //wrong name constr->addChild(vol); } // @@ -716,8 +752,9 @@ void AlignableDetector::calcFree(bool condFix) mNCalibDOFFree = 0; for (int i = 0; i < mNCalibDOF; i++) { if (!isFreeDOF(i)) { - if (condFix) + if (condFix) { setParErr(i, -999); + } continue; } mNCalibDOFFree++; @@ -729,8 +766,9 @@ void AlignableDetector::calcFree(bool condFix) void AlignableDetector::fillDOFStat(DOFStatistics* st) const { // fill statistics info hist - if (!st) + if (!st) { return; + } int ndf = getNCalibDOFs(); int dof0 = getFirstParGloID(); int stat = getNProcessedPoints(); diff --git a/Detectors/Align/src/AlignableSensor.cxx b/Detectors/Align/src/AlignableSensor.cxx index 74a6cf5373279..3ca7ea6a02f40 100644 --- a/Detectors/Align/src/AlignableSensor.cxx +++ b/Detectors/Align/src/AlignableSensor.cxx @@ -34,7 +34,7 @@ namespace align //_________________________________________________________ AlignableSensor::AlignableSensor(const char* name, int vid, int iid) - : AlignableVolume(name, iid), mSID(0), mDet(0), mMatClAlg(), mMatClAlgReco() + : AlignableVolume(name, iid), mSID(0), mDet(nullptr), mMatClAlg(), mMatClAlgReco() { // def c-tor setVolID(vid); @@ -42,12 +42,6 @@ AlignableSensor::AlignableSensor(const char* name, int vid, int iid) mConstrChild = 0; // sensors don't have children } -//_________________________________________________________ -AlignableSensor::~AlignableSensor() -{ - // d-tor -} - //_________________________________________________________ void AlignableSensor::dPosTraDParGeomLOC(const AlignmentPoint* pnt, double* deriv) const { @@ -64,8 +58,9 @@ void AlignableSensor::dPosTraDParGeomLOC(const AlignmentPoint* pnt, double* deri // for (int ip = kNDOFGeom; ip--;) { // - if (!isFreeDOF(ip)) + if (!isFreeDOF(ip)) { continue; + } // double var = kDelta[ip]; delta[ip] -= var; @@ -87,8 +82,9 @@ void AlignableSensor::dPosTraDParGeomLOC(const AlignmentPoint* pnt, double* deri // delta[ip] = 0; double* curd = deriv + ip * 3; - for (int i = 3; i--;) + for (int i = 3; i--;) { curd[i] = (8. * (pos2[i] - pos1[i]) - (pos3[i] - pos0[i])) / 6. / var; + } } // } @@ -112,8 +108,9 @@ void AlignableSensor::dPosTraDParGeomLOC(const AlignmentPoint* pnt, double* deri // for (int ip = kNDOFGeom; ip--;) { // - if (!isFreeDOF(ip)) + if (!isFreeDOF(ip)) { continue; + } // double var = kDelta[ip]; delta[ip] -= var; @@ -134,8 +131,9 @@ void AlignableSensor::dPosTraDParGeomLOC(const AlignmentPoint* pnt, double* deri // delta[ip] = 0; double* curd = deriv + ip * 3; - for (int i = 3; i--;) + for (int i = 3; i--;) { curd[i] = (8. * (pos2[i] - pos1[i]) - (pos3[i] - pos0[i])) / 6. / var; + } } // } @@ -158,8 +156,9 @@ void AlignableSensor::dPosTraDParGeomTRA(const AlignmentPoint* pnt, double* deri // for (int ip = kNDOFGeom; ip--;) { // - if (!isFreeDOF(ip)) + if (!isFreeDOF(ip)) { continue; + } // double var = kDelta[ip]; delta[ip] -= var; @@ -180,8 +179,9 @@ void AlignableSensor::dPosTraDParGeomTRA(const AlignmentPoint* pnt, double* deri // delta[ip] = 0; double* curd = deriv + ip * 3; - for (int i = 3; i--;) + for (int i = 3; i--;) { curd[i] = (8. * (pos2[i] - pos1[i]) - (pos3[i] - pos0[i])) / 6. / var; + } } // } @@ -219,8 +219,9 @@ void AlignableSensor::dPosTraDParGeomTRA(const AlignmentPoint* pnt, double* deri // for (int ip = kNDOFGeom; ip--;) { // - if (!isFreeDOF(ip)) + if (!isFreeDOF(ip)) { continue; + } // double var = kDelta[ip]; delta[ip] -= var; @@ -241,8 +242,9 @@ void AlignableSensor::dPosTraDParGeomTRA(const AlignmentPoint* pnt, double* deri // delta[ip] = 0; double* curd = deriv + ip * 3; - for (int i = 3; i--;) + for (int i = 3; i--;) { curd[i] = (8. * (pos2[i] - pos1[i]) - (pos3[i] - pos0[i])) / 6. / var; + } } // } @@ -324,24 +326,28 @@ void AlignableSensor::Print(const Option_t* opt) const countParents(), getInternalID(), getSymName(), getVolID(), mX, mAlp, mAddError[0], mAddError[1], mNProcPoints); printf(" DOFs: Tot: %d (offs: %5d) Free: %d Geom: %d {", mNDOFs, mFirstParGloID, mNDOFFree, mNDOFGeomFree); - for (int i = 0; i < kNDOFGeom; i++) + for (int i = 0; i < kNDOFGeom; i++) { printf("%d", isFreeDOF(i) ? 1 : 0); + } printf("} in %s frame\n", sFrameName[mVarFrame]); // // // if (opts.Contains("par") && mParVals) { printf(" Lb: "); - for (int i = 0; i < mNDOFs; i++) + for (int i = 0; i < mNDOFs; i++) { printf("%10d ", getParLab(i)); + } printf("\n"); printf(" Vl: "); - for (int i = 0; i < mNDOFs; i++) + for (int i = 0; i < mNDOFs; i++) { printf("%+9.3e ", getParVal(i)); + } printf("\n"); printf(" Er: "); - for (int i = 0; i < mNDOFs; i++) + for (int i = 0; i < mNDOFs; i++) { printf("%+9.3e ", getParErr(i)); + } printf("\n"); } // @@ -424,8 +430,9 @@ void AlignableSensor::dPosTraDParCalib(const AlignmentPoint* pnt, double* deriv, int AlignableSensor::finalizeStat(DOFStatistics* st) { // finalize statistics on processed points - if (st) + if (st) { fillDOFStat(st); + } return mNProcPoints; } diff --git a/Detectors/Align/src/AlignableVolume.cxx b/Detectors/Align/src/AlignableVolume.cxx index 85023c192e3bc..8a8b62a09bec8 100644 --- a/Detectors/Align/src/AlignableVolume.cxx +++ b/Detectors/Align/src/AlignableVolume.cxx @@ -108,7 +108,7 @@ #include #include #include -#include +#include ClassImp(o2::align::AlignableVolume); @@ -131,15 +131,15 @@ const char* AlignableVolume::sDOFName[AlignableVolume::kNDOFGeom] = {"TX", "TY", AlignableVolume::AlignableVolume(const char* symname, int iid) : TNamed(symname, ""), mVarFrame(kTRA), mIntID(iid), mX(0), mAlp(0), mNDOFs(0), mDOF(0), mNDOFGeomFree(0), mNDOFFree(0), mConstrChild(kDefChildConstr) // , - mParent(0), - mChildren(0) + mParent(nullptr), + mChildren(nullptr) // , mNProcPoints(0), mFirstParGloID(-1), - mParVals(0), - mParErrs(0), - mParLabs(0) + mParVals(nullptr), + mParErrs(nullptr), + mParLabs(nullptr) // , mMatL2GReco(), @@ -242,8 +242,9 @@ int AlignableVolume::countParents() const // count parents in the chain int cnt = 0; const AlignableVolume* p = this; - while ((p = p->getParent())) + while ((p = p->getParent())) { cnt++; + } return cnt; } @@ -256,31 +257,37 @@ void AlignableVolume::Print(const Option_t* opt) const printf("Lev:%2d IntID:%7d %s | %2d nodes | Effective X:%8.4f Alp:%+.4f | Used Points: %d\n", countParents(), getInternalID(), getSymName(), getNChildren(), mX, mAlp, mNProcPoints); printf(" DOFs: Tot: %d (offs: %5d) Free: %d Geom: %d {", mNDOFs, mFirstParGloID, mNDOFFree, mNDOFGeomFree); - for (int i = 0; i < kNDOFGeom; i++) + for (int i = 0; i < kNDOFGeom; i++) { printf("%d", isFreeDOF(i) ? 1 : 0); + } printf("} in %s frame.", sFrameName[mVarFrame]); if (getNChildren()) { printf(" Child.Constr: {"); - for (int i = 0; i < kNDOFGeom; i++) + for (int i = 0; i < kNDOFGeom; i++) { printf("%d", isChildrenDOFConstrained(i) ? 1 : 0); + } printf("}"); } - if (getExcludeFromParentConstraint()) + if (getExcludeFromParentConstraint()) { printf(" Excl.from parent constr."); + } printf("\n"); // if (opts.Contains("par") && mParVals) { printf(" Lb: "); - for (int i = 0; i < mNDOFs; i++) + for (int i = 0; i < mNDOFs; i++) { printf("%10d ", getParLab(i)); + } printf("\n"); printf(" Vl: "); - for (int i = 0; i < mNDOFs; i++) + for (int i = 0; i < mNDOFs; i++) { printf("%+9.3e ", getParVal(i)); + } printf("\n"); printf(" Er: "); - for (int i = 0; i < mNDOFs; i++) + for (int i = 0; i < mNDOFs; i++) { printf("%+9.3e ", getParErr(i)); + } printf("\n"); } @@ -305,12 +312,14 @@ void AlignableVolume::prepareMatrixL2G(bool reco) const char* path = getSymName(); if (gGeoManager->GetAlignableEntry(path)) { const TGeoHMatrix* l2g = base::GeometryManager::getMatrix(path); - if (!l2g) + if (!l2g) { LOG(FATAL) << "Failed to find L2G matrix for alignable " << path; + } reco ? setMatrixL2GReco(*l2g) : setMatrixL2G(*l2g); } else { // extract from path - if (!gGeoManager->CheckPath(path)) + if (!gGeoManager->CheckPath(path)) { LOG(FATAL) << "Volume path " << path << " is not valid!"; + } TGeoPhysicalNode* node = (TGeoPhysicalNode*)gGeoManager->GetListOfPhysicalNodes()->FindObject(path); TGeoHMatrix l2g; if (!node) { @@ -330,8 +339,9 @@ void AlignableVolume::prepareMatrixL2GIdeal() { // extract from geometry ideal L2G matrix TGeoHMatrix mtmp; - if (!base::GeometryManager::getOriginalMatrix(getSymName(), mtmp)) + if (!base::GeometryManager::getOriginalMatrix(getSymName(), mtmp)) { LOG(FATAL) << "Failed to find ideal L2G matrix for " << getSymName(); + } setMatrixL2GIdeal(mtmp); } @@ -346,12 +356,15 @@ void AlignableVolume::prepareMatrixT2L() for (int ich = nch; ich--;) { AlignableVolume* vol = getChild(ich); vol->getMatrixL2GIdeal().LocalToMaster(loc, glo); - for (int j = 3; j--;) + for (int j = 3; j--;) { tot[j] += glo[j]; + } } - if (nch) - for (int j = 3; j--;) + if (nch) { + for (int j = 3; j--;) { tot[j] /= nch; + } + } // mAlp = TMath::ATan2(tot[1], tot[0]); utils::bringToPiPM(mAlp); @@ -397,13 +410,15 @@ void AlignableVolume::assignDOFs(int& cntDOFs, float* pars, float* errs, int* la mParErrs = errs + cntDOFs; mParLabs = labs + cntDOFs; setFirstParGloID(cntDOFs); - for (int i = 0; i < mNDOFs; i++) + for (int i = 0; i < mNDOFs; i++) { mParLabs[i] = getInternalID() * 100 + i; + } cntDOFs += mNDOFs; // increment total DOFs count // int nch = getNChildren(); // go over childs - for (int ich = 0; ich < nch; ich++) + for (int ich = 0; ich < nch; ich++) { getChild(ich)->assignDOFs(cntDOFs, pars, errs, labs); + } // return; } @@ -414,11 +429,14 @@ void AlignableVolume::initDOFs() // initialize degrees of freedom // // Do we need this strict condition? - if (getInitDOFsDone()) + if (getInitDOFsDone()) { LOG(FATAL) << "DOFs are already initialized for " << GetName(); - for (int i = 0; i < mNDOFs; i++) - if (mParErrs[i] < -9999 && isZeroAbs(mParVals[i])) + } + for (int i = 0; i < mNDOFs; i++) { + if (mParErrs[i] < -9999 && isZeroAbs(mParVals[i])) { fixDOF(i); + } + } calcFree(true); setInitDOFsDone(); } @@ -430,13 +448,15 @@ void AlignableVolume::calcFree(bool condFix) mNDOFFree = mNDOFGeomFree = 0; for (int i = 0; i < mNDOFs; i++) { if (!isFreeDOF(i)) { - if (condFix) + if (condFix) { setParErr(i, -999); + } continue; } mNDOFFree++; - if (i < kNDOFGeom) + if (i < kNDOFGeom) { mNDOFGeomFree++; + } } // } @@ -445,8 +465,9 @@ void AlignableVolume::calcFree(bool condFix) void AlignableVolume::setNDOFs(int n) { // book global degrees of freedom - if (n < kNDOFGeom) + if (n < kNDOFGeom) { n = kNDOFGeom; + } mNDOFs = n; } @@ -465,8 +486,9 @@ void AlignableVolume::addChild(AlignableVolume* ch) void AlignableVolume::setParVals(int npar, double* vl, double* er) { // set parameters - if (npar > mNDOFs) + if (npar > mNDOFs) { LOG(FATAL) << "Volume " << GetName() << " has " << mNDOFs << " dofs"; + } for (int i = 0; i < npar; i++) { mParVals[i] = vl[i]; mParErrs[i] = er ? er[i] : 0; @@ -489,8 +511,9 @@ int AlignableVolume::finalizeStat(DOFStatistics* st) AlignableVolume* child = getChild(ich); mNProcPoints += child->finalizeStat(st); } - if (st) + if (st) { fillDOFStat(st); + } return mNProcPoints; } @@ -512,35 +535,44 @@ void AlignableVolume::writePedeInfo(FILE* parOut, const Option_t* opt) const // is there something to print ? int nCond(0), nFix(0), nDef(0); for (int i = 0; i < mNDOFs; i++) { - if (!isFreeDOF(i)) + if (!isFreeDOF(i)) { nFix++; - if (isCondDOF(i)) + } + if (isCondDOF(i)) { nCond++; - if (!isCondDOF(i) && isFreeDOF(i)) + } + if (!isCondDOF(i) && isFreeDOF(i)) { nDef++; + } } // int cmt = nCond > 0 || nFix > 0 ? kOff : kOn; // do we comment the "parameter" keyword for this volume - if (!nFix) + if (!nFix) { showFix = false; - if (!nDef) + } + if (!nDef) { showDef = false; + } // - if (nCond || showDef || showFix || showNam) + if (nCond || showDef || showFix || showNam) { fprintf(parOut, "%s%s %s\t\tDOF/Free: %d/%d (%s) %s\n", comment[cmt], kKeyParam, comment[kOnOn], getNDOFs(), getNDOFFree(), sFrameName[mVarFrame], GetName()); + } // if (nCond || showDef || showFix) { for (int i = 0; i < mNDOFs; i++) { cmt = kOn; - if (isCondDOF(i) || !isFreeDOF(i)) - cmt = kOff; // free-conditioned : MUST print + if (isCondDOF(i) || !isFreeDOF(i)) { + cmt = kOff; + } // free-conditioned : MUST print else if (!isFreeDOF(i)) { - if (!showFix) + if (!showFix) { continue; + } } // Fixed: print commented if asked - else if (!showDef) - continue; // free-unconditioned: print commented if asked + else if (!showDef) { + continue; + } // free-unconditioned: print commented if asked // fprintf(parOut, "%s %9d %+e %+e\t%s %s p%d\n", comment[cmt], getParLab(i), getParVal(i), getParErr(i), comment[kOnOn], isFreeDOF(i) ? " " : "FX", i); @@ -550,8 +582,9 @@ void AlignableVolume::writePedeInfo(FILE* parOut, const Option_t* opt) const // children volume int nch = getNChildren(); // - for (int ich = 0; ich < nch; ich++) + for (int ich = 0; ich < nch; ich++) { getChild(ich)->writePedeInfo(parOut, opt); + } // } @@ -677,8 +710,9 @@ void AlignableVolume::createLocDeltaMatrix(TGeoHMatrix& deltaM) const // This deltaM does not account for eventual prealignment // Volume knows if its variation was done in TRA or LOC frame double corr[kNDOFGeom]; - for (int i = kNDOFGeom; i--;) - corr[i] = mParVals[i]; // we need doubles + for (int i = kNDOFGeom; i--;) { + corr[i] = mParVals[i]; + } // we need doubles delta2Matrix(deltaM, corr); if (isFrameTRA()) { // we need corrections in local frame! // l' = T2L * delta_t * t = T2L * delta_t * T2L^-1 * l = delta_l * l @@ -774,8 +808,9 @@ void AlignableVolume::createAlignmentObjects(TClonesArray* arr) const translation[0], translation[1], translation[2], rotation[0], rotation[1], rotation[2], true); int nch = getNChildren(); - for (int ich = 0; ich < nch; ich++) + for (int ich = 0; ich < nch; ich++) { getChild(ich)->createAlignmentObjects(arr); + } } //_________________________________________________________________ @@ -792,23 +827,27 @@ void AlignableVolume::updateL2GRecoMatrices(const TClonesArray* algArr, const TG const detectors::AlignParam* par = nullptr; for (int i = 0; i < nalg; i++) { par = (detectors::AlignParam*)algArr->At(i); - if (!strcmp(par->getSymName(), getSymName())) + if (!strcmp(par->getSymName(), getSymName())) { break; - par = 0; + } + par = nullptr; } TGeoHMatrix delta; - if (!par) + if (!par) { LOG(INFO) << "Alignment for " << getSymName() << " is absent in Reco-Time alignment object"; - else + } else { delta = par->createMatrix(); + } // par->GetMatrix(delta); - if (cumulDelta) + if (cumulDelta) { delta *= *cumulDelta; + } // mMatL2GReco.MultiplyLeft(&delta); // propagate to children - for (int ich = getNChildren(); ich--;) + for (int ich = getNChildren(); ich--;) { getChild(ich)->updateL2GRecoMatrices(algArr, &delta); + } // } @@ -816,13 +855,15 @@ void AlignableVolume::updateL2GRecoMatrices(const TClonesArray* algArr, const TG bool AlignableVolume::ownsDOFID(int id) const { // check if DOF ID belongs to this volume or its children - if (id >= mFirstParGloID && id < mFirstParGloID + mNDOFs) + if (id >= mFirstParGloID && id < mFirstParGloID + mNDOFs) { return true; + } // for (int iv = getNChildren(); iv--;) { AlignableVolume* vol = getChild(iv); - if (vol->ownsDOFID(id)) + if (vol->ownsDOFID(id)) { return true; + } } return false; } @@ -831,15 +872,17 @@ bool AlignableVolume::ownsDOFID(int id) const AlignableVolume* AlignableVolume::getVolOfDOFID(int id) const { // gets volume owning this DOF ID - if (id >= mFirstParGloID && id < mFirstParGloID + mNDOFs) + if (id >= mFirstParGloID && id < mFirstParGloID + mNDOFs) { return (AlignableVolume*)this; + } // for (int iv = getNChildren(); iv--;) { AlignableVolume* vol = getChild(iv); - if ((vol = vol->getVolOfDOFID(id))) + if ((vol = vol->getVolOfDOFID(id))) { return vol; + } } - return 0; + return nullptr; } //______________________________________________________ @@ -853,8 +896,9 @@ const char* AlignableVolume::getDOFName(int i) const void AlignableVolume::fillDOFStat(DOFStatistics* h) const { // fill statistics info hist - if (!h) + if (!h) { return; + } int ndf = getNDOFs(); int dof0 = getFirstParGloID(); int stat = getNProcessedPoints(); @@ -876,14 +920,16 @@ void AlignableVolume::addAutoConstraints(TObjArray* constrArr) constr->setParent(this); for (int ich = nch; ich--;) { AlignableVolume* child = getChild(ich); - if (child->getExcludeFromParentConstraint()) + if (child->getExcludeFromParentConstraint()) { continue; + } constr->addChild(child); } - if (constr->getNChildren()) + if (constr->getNChildren()) { constrArr->Add(constr); - else + } else { delete constr; + } } for (int ich = 0; ich < nch; ich++) { getChild(ich)->addAutoConstraints(constrArr); diff --git a/Detectors/Align/src/AlignmentPoint.cxx b/Detectors/Align/src/AlignmentPoint.cxx index 29af7a222d3bb..8b3b030ded1e3 100644 --- a/Detectors/Align/src/AlignmentPoint.cxx +++ b/Detectors/Align/src/AlignmentPoint.cxx @@ -28,7 +28,7 @@ namespace align //_____________________________________ AlignmentPoint::AlignmentPoint() - : mMinLocVarID(0), mMaxLocVarID(0), mDetID(-1), mSID(-1), mAlphaSens(0), mXSens(0), mCosDiagErr(0), mSinDiagErr(0), mX2X0(0), mXTimesRho(0), mNGloDOFs(0), mDGloOffs(0), mSensor(0) + : mMinLocVarID(0), mMaxLocVarID(0), mDetID(-1), mSID(-1), mAlphaSens(0), mXSens(0), mCosDiagErr(0), mSinDiagErr(0), mX2X0(0), mXTimesRho(0), mNGloDOFs(0), mDGloOffs(0), mSensor(nullptr) { // def c-tor for (int i = 3; i--;) { @@ -64,10 +64,11 @@ void AlignmentPoint::init() double dfd = 0.5 * (mErrYZTracking[2] - mErrYZTracking[0]); double phi = 0; // special treatment if errors are equal - if (Abs(dfd) < kDiagToler) + if (Abs(dfd) < kDiagToler) { phi = mErrYZTracking[1] > 0 ? (Pi() * 0.25) : (Pi() * 0.75); - else + } else { phi = 0.5 * ATan2(mErrYZTracking[1], dfd); + } // mCosDiagErr = Cos(phi); mSinDiagErr = Sin(phi); @@ -102,10 +103,11 @@ void AlignmentPoint::Print(Option_t* opt) const opts.ToLower(); printf("%cDet%d SID:%4d Alp:%+.3f X:%+9.4f Meas:%s Mat: ", isInvDir() ? '*' : ' ', getDetID(), getSID(), getAlphaSens(), getXSens(), containsMeasurement() ? "ON" : "OFF"); - if (!containsMaterial()) + if (!containsMaterial()) { printf("OFF\n"); - else + } else { printf("x2X0: %.4f x*rho: %.4f | pars:[%3d:%3d)\n", getX2X0(), getXTimesRho(), getMinLocVarID(), getMaxLocVarID()); + } // if (opts.Contains("meas") && containsMeasurement()) { printf(" MeasPnt: Xtr: %+9.4f Ytr: %+8.4f Ztr: %+9.4f | ErrYZ: %+e %+e %+e | %d DOFglo\n", @@ -127,14 +129,16 @@ void AlignmentPoint::Print(Option_t* opt) const for (int i = 0; i < np; i++) { for (int j = 0; j <= i; j++) { double val = 0; - for (int k = np; k--;) + for (int k = np; k--;) { val += mMatDiag[i][k] * mMatDiag[j][k] * mMatCorrCov[k]; + } int ij = (i * (i + 1) / 2) + j; covUndiag[ij] = val; } } - if (np < kNMatDOFs) - covUndiag[14] = mMatCorrCov[4]; // eloss was fixed + if (np < kNMatDOFs) { + covUndiag[14] = mMatCorrCov[4]; + } // eloss was fixed printf(" MatCorr Cov in normal form:\n"); printf(" %+e\n", covUndiag[0]); printf(" %+e %+e\n", covUndiag[1], covUndiag[2]); @@ -148,22 +152,25 @@ void AlignmentPoint::Print(Option_t* opt) const printf(" Matrix for Mat.corr.errors diagonalization:\n"); int npar = getNMatPar(); for (int i = 0; i < npar; i++) { - for (int j = 0; j < npar; j++) + for (int j = 0; j < npar; j++) { printf("%+.4e ", mMatDiag[i][j]); + } printf("\n"); } } // if (opts.Contains("wsa")) { // printf track state at this point stored during residuals calculation printf(" Local Track (A): "); - for (int i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) { printf("%+.3e ", mTrParamWSA[i]); + } printf("\n"); } if (opts.Contains("wsb")) { // printf track state at this point stored during residuals calculation printf(" Local Track (B): "); - for (int i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) { printf("%+.3e ", mTrParamWSB[i]); + } printf("\n"); } // @@ -217,7 +224,7 @@ void AlignmentPoint::Clear(Option_t*) mSID = -1; mNGloDOFs = 0; mDGloOffs = 0; - mSensor = 0; + mSensor = nullptr; } //__________________________________________________________________ @@ -233,13 +240,15 @@ int AlignmentPoint::Compare(const TObject* b) const if (!isInvDir()) { // track propagates from low to large X via this point if (!pnt->isInvDir()) { // via this one also return x > xp ? -1 : 1; - } else - return -1; // range points of lower leg 1st + } else { + return -1; + } // range points of lower leg 1st } else { // this point is from upper cosmic leg: track propagates from large to low X if (pnt->isInvDir()) { // this one also return x > xp ? 1 : -1; - } else - return 1; // other point is from lower leg + } else { + return 1; + } // other point is from lower leg } // } @@ -279,9 +288,11 @@ void AlignmentPoint::setMatCovDiagonalizationMatrix(const TMatrixD& d) // save non-sym matrix for material corrections cov.matrix diagonalization // (actually, the eigenvectors are stored) int sz = d.GetNrows(); - for (int i = sz; i--;) - for (int j = sz; j--;) + for (int i = sz; i--;) { + for (int j = sz; j--;) { mMatDiag[i][j] = d(i, j); + } + } } //__________________________________________________________________ @@ -290,8 +301,9 @@ void AlignmentPoint::setMatCovDiag(const TVectorD& v) // save material correction diagonalized matrix // (actually, the eigenvalues are stored w/o reordering them to correspond to the // AliExternalTrackParam variables) - for (int i = v.GetNrows(); i--;) + for (int i = v.GetNrows(); i--;) { mMatCorrCov[i] = v(i); + } } //__________________________________________________________________ @@ -302,8 +314,9 @@ void AlignmentPoint::unDiagMatCorr(const double* diag, double* nodiag) const int np = getNMatPar(); for (int ip = np; ip--;) { double v = 0; - for (int jp = np; jp--;) + for (int jp = np; jp--;) { v += mMatDiag[ip][jp] * diag[jp]; + } nodiag[ip] = v; } // @@ -317,8 +330,9 @@ void AlignmentPoint::unDiagMatCorr(const float* diag, float* nodiag) const int np = getNMatPar(); for (int ip = np; ip--;) { double v = 0; - for (int jp = np; jp--;) + for (int jp = np; jp--;) { v += double(mMatDiag[ip][jp]) * diag[jp]; + } nodiag[ip] = v; } // @@ -333,8 +347,9 @@ void AlignmentPoint::diagMatCorr(const double* nodiag, double* diag) const int np = getNMatPar(); for (int ip = np; ip--;) { double v = 0; - for (int jp = np; jp--;) + for (int jp = np; jp--;) { v += mMatDiag[jp][ip] * nodiag[jp]; + } diag[ip] = v; } // @@ -349,8 +364,9 @@ void AlignmentPoint::diagMatCorr(const float* nodiag, float* diag) const int np = getNMatPar(); for (int ip = np; ip--;) { double v = 0; - for (int jp = np; jp--;) + for (int jp = np; jp--;) { v += double(mMatDiag[jp][ip]) * nodiag[jp]; + } diag[ip] = v; } // diff --git a/Detectors/Align/src/AlignmentTrack.cxx b/Detectors/Align/src/AlignmentTrack.cxx index bce0f36c8077d..d1472f62b2550 100644 --- a/Detectors/Align/src/AlignmentTrack.cxx +++ b/Detectors/Align/src/AlignmentTrack.cxx @@ -13,7 +13,7 @@ /// @since 2021-02-01 /// @brief Track model for the alignment -#include +#include #include "Align/AlignmentTrack.h" #include "Framework/Logger.h" #include "Align/AlignableSensor.h" @@ -39,9 +39,8 @@ const int kRichardsonN = kRichardsonOrd + 1; // N of 2-point symmetric derivativ const int kNRDClones = kRichardsonN * 2; // number of variations for derivative of requested order //____________________________________________________________________________ -AlignmentTrack::AlignmentTrack() : TrackParametrizationWithError(), TObject(), mNLocPar(0), mNLocExtPar(0), mNGloPar(0), mNDF(0), mInnerPointID(0) - // ,mMinX2X0Pt2Account(5/1.0) - , +AlignmentTrack::AlignmentTrack() : TrackParametrizationWithError(), TObject(), mNLocPar(0), mNLocExtPar(0), mNGloPar(0), mNDF(0), mInnerPointID(0), + // ,mMinX2X0Pt2Account(5/1.0), mMinX2X0Pt2Account(0.5e-3 / 1.0), mMass(0.14), mChi2(0), @@ -51,8 +50,8 @@ AlignmentTrack::AlignmentTrack() : TrackParametrizationWithError(), TObj mPoints(0), mLocPar(), mGloParID(0), - mGloParIDA(0), - mLocParA(0) + mGloParIDA(nullptr), + mLocParA(nullptr) { // def c-tor for (int i = 0; i < 2; i++) { @@ -61,20 +60,14 @@ AlignmentTrack::AlignmentTrack() : TrackParametrizationWithError(), TObj mDResDGlo[i].Set(0); mDResDLoc[i].Set(0); // - mResidA[i] = 0; - mDResDLocA[i] = 0; - mDResDGloA[i] = 0; + mResidA[i] = nullptr; + mDResDLocA[i] = nullptr; + mDResDGloA[i] = nullptr; } mNeedInv[0] = mNeedInv[1] = false; // } -//____________________________________________________________________________ -AlignmentTrack::~AlignmentTrack() -{ - // d-tor -} - //____________________________________________________________________________ void AlignmentTrack::Clear(Option_t*) { @@ -109,8 +102,9 @@ void AlignmentTrack::defineDOFs() for (int ip = getInnerPointID() + 1; ip--;) { // collision track or cosmic lower leg AlignmentPoint* pnt = getPoint(ip); pnt->setMinLocVarID(minPar); - if (pnt->containsMaterial()) + if (pnt->containsMaterial()) { mNLocPar += pnt->getNMatPar(); + } pnt->setMaxLocVarID(mNLocPar); // flag up to which parameted ID this points depends on } // @@ -119,14 +113,16 @@ void AlignmentTrack::defineDOFs() for (int ip = getInnerPointID() + 1; ip < np; ip++) { // collision track or cosmic lower leg AlignmentPoint* pnt = getPoint(ip); pnt->setMinLocVarID(minPar); - if (pnt->containsMaterial()) + if (pnt->containsMaterial()) { mNLocPar += pnt->getNMatPar(); + } pnt->setMaxLocVarID(mNLocPar); // flag up to which parameted ID this points depends on } } // - if (mLocPar.GetSize() < mNLocPar) + if (mLocPar.GetSize() < mNLocPar) { mLocPar.Set(mNLocPar); + } mLocPar.Reset(); mLocParA = mLocPar.GetArray(); // @@ -163,11 +159,13 @@ bool AlignmentTrack::calcResidDeriv(double* params) // // If params are not provided, use internal params array // - if (!params) + if (!params) { params = mLocParA; + } // - if (!getResidDone()) + if (!getResidDone()) { calcResiduals(params); + } // int np = getNPoints(); // @@ -214,10 +212,12 @@ bool AlignmentTrack::calcResidDeriv(double* extendedParams, bool invert, int pFr const double kDelta[kNKinParBON] = {0.02, 0.02, 0.001, 0.001, 0.01}; // variations for ExtTrackParam and material effects // double delta[kNKinParBON]; // variations of curvature term are relative - for (int i = kNKinParBOFF; i--;) + for (int i = kNKinParBOFF; i--;) { delta[i] = kDelta[i]; - if (getFieldON()) + } + if (getFieldON()) { delta[kParQ2Pt] = kDelta[kParQ2Pt] * Abs(getQ2Pt()); + } // int pinc; if (pTo > pFrom) { // fit in points decreasing order: cosmics upper leg @@ -232,9 +232,11 @@ bool AlignmentTrack::calcResidDeriv(double* extendedParams, bool invert, int pFr for (int ipar = mNLocExtPar; ipar--;) { setParams(probD, kNRDClones, getX(), getAlpha(), extendedParams, true); - if (invert) - for (int ic = kNRDClones; ic--;) + if (invert) { + for (int ic = kNRDClones; ic--;) { probD[ic].invert(); + } + } double del = delta[ipar]; // for (int icl = 0; icl < kRichardsonN; icl++) { // calculate kRichardsonN variations with del, del/2, del/4... @@ -246,11 +248,13 @@ bool AlignmentTrack::calcResidDeriv(double* extendedParams, bool invert, int pFr // propagate varied tracks to each point for (int ip = pFrom; ip != pTo; ip += pinc) { // points are ordered against track direction AlignmentPoint* pnt = getPoint(ip); - if (!propagateParamToPoint(probD, kNRDClones, pnt)) + if (!propagateParamToPoint(probD, kNRDClones, pnt)) { return false; + } // if (pnt->containsMaterial()) { // apply material corrections - if (!applyMatCorr(probD, kNRDClones, extendedParams, pnt)) + if (!applyMatCorr(probD, kNRDClones, extendedParams, pnt)) { return false; + } // } // if (pnt->containsMeasurement()) { @@ -278,8 +282,9 @@ bool AlignmentTrack::calcResidDeriv(double* extendedParams, bool invert, int pFr return false; } // - if (!pnt->containsMaterial()) + if (!pnt->containsMaterial()) { continue; + } // int nParFreeI = pnt->getNMatPar(); // @@ -311,13 +316,15 @@ bool AlignmentTrack::calcResidDeriv(double* extendedParams, bool invert, int pFr extendedParams[offsIP] += del; // // apply varied material effects : incremented by delta - if (!applyMatCorr(probD[(icl << 1) + 0], extendedParams, pnt)) + if (!applyMatCorr(probD[(icl << 1) + 0], extendedParams, pnt)) { return false; + } // // apply varied material effects : decremented by delta extendedParams[offsIP] = parOrig - del; - if (!applyMatCorr(probD[(icl << 1) + 1], extendedParams, pnt)) + if (!applyMatCorr(probD[(icl << 1) + 1], extendedParams, pnt)) { return false; + } // extendedParams[offsIP] = parOrig; del *= 0.5; @@ -334,12 +341,14 @@ bool AlignmentTrack::calcResidDeriv(double* extendedParams, bool invert, int pFr // printf(" DerFor:%d ",jp); pntJ->print(); - if (!propagateParamToPoint(probD, kNRDClones, pntJ)) + if (!propagateParamToPoint(probD, kNRDClones, pntJ)) { return false; + } // if (pntJ->containsMaterial()) { // apply material corrections - if (!applyMatCorr(probD, kNRDClones, extendedParams, pntJ)) + if (!applyMatCorr(probD, kNRDClones, extendedParams, pntJ)) { return false; + } } // if (pntJ->containsMeasurement()) { @@ -373,15 +382,17 @@ bool AlignmentTrack::calcResidDerivGlo(AlignmentPoint* pnt) do { // measurement residuals int nfree = vol->getNDOFFree(); - if (!nfree) - continue; // no free parameters? - sens->dPosTraDParGeom(pnt, deriv, vol == sens ? 0 : vol); + if (!nfree) { + continue; + } // no free parameters? + sens->dPosTraDParGeom(pnt, deriv, vol == sens ? nullptr : vol); // checkExpandDerGloBuffer(mNGloPar + nfree); // if needed, expand derivatives buffer // for (int ip = 0; ip < AlignableVolume::kNDOFGeom; ip++) { // we need only free parameters - if (!vol->isFreeDOF(ip)) + if (!vol->isFreeDOF(ip)) { continue; + } double* dXYZ = &deriv[ip * 3]; // tracking XYZ derivatives over this parameter // residual is defined as diagonalized track_estimate - measured Y,Z in tracking frame // where the track is evaluated at measured X! @@ -407,9 +418,10 @@ bool AlignmentTrack::calcResidDerivGlo(AlignmentPoint* pnt) // if needed, expand derivatives buffer checkExpandDerGloBuffer(mNGloPar + det->getNCalibDOFsFree()); for (int idf = 0; idf < ndof; idf++) { - if (!det->isFreeDOF(idf)) + if (!det->isFreeDOF(idf)) { continue; - sens->dPosTraDParCalib(pnt, deriv, idf, 0); + } + sens->dPosTraDParCalib(pnt, deriv, idf, nullptr); pnt->diagonalizeResiduals((deriv[AlignmentPoint::kX] * slpY - deriv[AlignmentPoint::kY]), (deriv[AlignmentPoint::kX] * slpZ - deriv[AlignmentPoint::kZ]), mDResDGloA[0][mNGloPar], mDResDGloA[1][mNGloPar]); @@ -438,8 +450,9 @@ bool AlignmentTrack::calcResiduals(const double* extendedParams) // // If extendedParams are not provided, use internal extendedParams array // - if (!extendedParams) + if (!extendedParams) { extendedParams = mLocParA; + } int np = getNPoints(); mChi2 = 0; mNDF = 0; @@ -481,8 +494,9 @@ bool AlignmentTrack::calcResiduals(const double* extendedParams, bool invert, in // trackParam_t probe; setParams(probe, getX(), getAlpha(), extendedParams, true); - if (invert) + if (invert) { probe.invert(); + } int pinc; if (pTo > pFrom) { // fit in points decreasing order: cosmics upper leg pTo++; @@ -494,8 +508,9 @@ bool AlignmentTrack::calcResiduals(const double* extendedParams, bool invert, in // for (int ip = pFrom; ip != pTo; ip += pinc) { // points are ordered against track direction AlignmentPoint* pnt = getPoint(ip); - if (!propagateParamToPoint(probe, pnt)) + if (!propagateParamToPoint(probe, pnt)) { return false; + } // // store the current track kinematics at the point BEFORE applying eventual material // corrections. This kinematics will be later varied around supplied parameters (in the calcResidDeriv) @@ -503,8 +518,9 @@ bool AlignmentTrack::calcResiduals(const double* extendedParams, bool invert, in // // account for materials // if (pnt->ContainsMaterial()) { // apply material corrections - if (!applyMatCorr(probe, extendedParams, pnt)) + if (!applyMatCorr(probe, extendedParams, pnt)) { return false; + } // } pnt->setTrParamWSA(probe.getParams()); // @@ -520,8 +536,9 @@ bool AlignmentTrack::calcResiduals(const double* extendedParams, bool invert, in int nCorrPar = pnt->getNMatPar(); const double* corrDiag = &mLocParA[pnt->getMaxLocVarID() - nCorrPar]; // corrections in diagonalized frame float* corCov = pnt->getMatCorrCov(); // correction diagonalized covariance - for (int i = 0; i < nCorrPar; i++) + for (int i = 0; i < nCorrPar; i++) { mChi2 += corrDiag[i] * corrDiag[i] / corCov[i]; + } } } return true; @@ -647,8 +664,9 @@ bool AlignmentTrack::applyMatCorr(trackParam_t& trPar, const double* corrPar, co } // to this we should add expected parameters modification due to the deterministic eloss float* detELoss = pnt->getMatCorrExp(); - for (int i = kNKinParBON; i--;) + for (int i = kNKinParBON; i--;) { corr[i] += detELoss[i]; + } //corr[kParQ2Pt] += detELoss[kParQ2Pt]; // printf("apply corr UD %+.3e %+.3e %+.3e %+.3e %+.3e\n",corr[0],corr[1],corr[2],corr[3],corr[4]); // printf(" corr D %+.3e %+.3e %+.3e %+.3e\n",corrDiag[0],corrDiag[1],corrDiag[2],corrDiag[3]); @@ -670,8 +688,9 @@ bool AlignmentTrack::applyMatCorr(trackParam_t& trPar, const double* corr) #if DEBUG > 3 LOG(error) << "Snp is too large: " << snp; printf("DeltaPar: "); - for (int i = 0; i < kNKinParBON; i++) + for (int i = 0; i < kNKinParBON; i++) { printf("%+.3e ", corr[i]); + } printf("\n"); trPar.print(); #endif @@ -698,8 +717,9 @@ bool AlignmentTrack::applyMatCorr(trackParam_t* trSet, int ntr, const double* co pnt->unDiagMatCorr(corrDiagP, corr); } float* detELoss = pnt->getMatCorrExp(); - for (int i = kNKinParBON; i--;) + for (int i = kNKinParBON; i--;) { corr[i] += detELoss[i]; + } // if (!pnt->getELossVaried()) corr[kParQ2Pt] = pnt->getMatCorrExp()[kParQ2Pt]; // fixed eloss expected effect // printf("apply corr UD %+.3e %+.3e %+.3e %+.3e\n",corr[0],corr[1],corr[2],corr[3]); // printf(" corr D %+.3e %+.3e %+.3e %+.3e\n",corrDiagP[0],corrDiagP[1],corrDiagP[2],corrDiagP[3]); @@ -725,11 +745,13 @@ double AlignmentTrack::richardsonExtrap(double* val, int ord) // d, d/2 ... d/2^ord. // The array val is overwritten // - if (ord == 1) + if (ord == 1) { return (4. * val[1] - val[0]) * (1. / 3); + } do { - for (int i = 0; i < ord; i++) + for (int i = 0; i < ord; i++) { val[i] = (4. * val[i + 1] - val[i]) * (1. / 3); + } } while (--ord); return val[0]; } @@ -742,13 +764,15 @@ double AlignmentTrack::richardsonExtrap(const double* val, int ord) // d, d/2 ... d/2^ord. // The array val is not overwritten // - if (ord == 1) + if (ord == 1) { return (4. * val[1] - val[0]) * (1. / 3); + } double* buff = new double[ord + 1]; memcpy(buff, val, (ord + 1) * sizeof(double)); do { - for (int i = 0; i < ord; i++) + for (int i = 0; i < ord; i++) { buff[i] = (4. * buff[i + 1] - buff[i]) * (1. / 3); + } } while (--ord); return buff[0]; } @@ -796,8 +820,9 @@ void AlignmentTrack::Print(Option_t* opt) const // if (par) { printf("Ref.track corr: "); - for (int i = 0; i < mNLocExtPar; i++) + for (int i = 0; i < mNLocExtPar; i++) { printf("%+.3e ", mLocParA[i]); + } printf("\n"); } // @@ -822,22 +847,25 @@ void AlignmentTrack::Print(Option_t* opt) const int nCorrPar = pnt->getNMatPar(); const double* corrDiag = &mLocParA[pnt->getMaxLocVarID() - nCorrPar]; printf(" Corr.Diag: "); - for (int i = 0; i < nCorrPar; i++) + for (int i = 0; i < nCorrPar; i++) { printf("%+.3e ", corrDiag[i]); + } printf("\n"); printf(" Corr.Pull: "); float* corCov = pnt->getMatCorrCov(); // correction covariance //float *corExp = pnt->getMatCorrExp(); // correction expectation - for (int i = 0; i < nCorrPar; i++) + for (int i = 0; i < nCorrPar; i++) { printf("%+.3e ", (corrDiag[i] /* - corExp[i]*/) / Sqrt(corCov[i])); + } printf("\n"); if (paru) { // print also mat.corrections in track frame double corr[5] = {0}; pnt->unDiagMatCorr(corrDiag, corr); // if (!pnt->getELossVaried()) corr[kParQ2Pt] = pnt->getMatCorrExp()[kParQ2Pt]; // fixed eloss expected effect printf(" Corr.Track: "); - for (int i = 0; i < kNKinParBON; i++) + for (int i = 0; i < kNKinParBON; i++) { printf("%+.3e ", corr[i]); + } printf("\n"); } } @@ -852,8 +880,9 @@ void AlignmentTrack::dumpCoordinates() const printf("gpx/D:gpy/D:gpz/D:gtxb/D:gtyb/D:gtzb/D:gtxa/D:gtya/D:gtza/D:alp/D:px/D:py/D:pz/D:tyb/D:tzb/D:tya/D:tza/D:ey/D:ez/D\n"); for (int ip = 0; ip < getNPoints(); ip++) { AlignmentPoint* pnt = getPoint(ip); - if (!pnt->containsMeasurement()) + if (!pnt->containsMeasurement()) { continue; + } pnt->dumpCoordinates(); } } @@ -897,14 +926,16 @@ bool AlignmentTrack::iniFit() // // propagate to reference point, which is the inner point of lower leg const AlignmentPoint* refP = getPoint(getInnerPointID()); - if (!propagateToPoint(trcU, refP, MaxDefStep, MaxDefSnp, DefMatCorrType)) + if (!propagateToPoint(trcU, refP, MaxDefStep, MaxDefSnp, DefMatCorrType)) { return false; + } // mChi2CosmUp = mChi2 - mChi2CosmDn; // printf("Upper leg: %d %d\n",getInnerPointID()+1,getNPoints()-1); trcU.print(); // - if (!combineTracks(trc, trcU)) + if (!combineTracks(trc, trcU)) { return false; + } //printf("Combined\n"); trc.print(); } copyFrom(&trc); @@ -965,15 +996,18 @@ bool AlignmentTrack::combineTracks(trackParam_t& trcL, const trackParam_t& trcU) TVectorD vlUp = matK * vUmnvL; // K*(vl - vu) for (int i = mtSize; i--;) { trcL.updateParam(vlUp[i], i); // updated param: vL' = vL + K(vU-vL) - for (int j = i + 1; j--;) - trcL.updateCov(-matKdotCL(i, j), i, j); // updated covariance: Cl' = Cl - K*Cl + for (int j = i + 1; j--;) { + trcL.updateCov(-matKdotCL(i, j), i, j); + } // updated covariance: Cl' = Cl - K*Cl } // // update chi2 double chi2 = 0; - for (int i = mtSize; i--;) - for (int j = mtSize; j--;) + for (int i = mtSize; i--;) { + for (int j = mtSize; j--;) { chi2 += matCLplCU(i, j) * vUmnvL[i] * vUmnvL[j]; + } + } mChi2 += chi2; // // printf("Combined: Chi2Tot:%.2f ChiUp:%.2f ChiDn:%.2f ChiCmb:%.2f\n",mChi2,mChi2CosmUp,mChi2CosmDn, chi2); @@ -1049,8 +1083,9 @@ bool AlignmentTrack::fitLeg(trackParam_t& trc, int pFrom, int pTo, bool& inv) return false; } if (pnt->containsMeasurement()) { - if (pnt->getNeedUpdateFromTrack()) + if (pnt->getNeedUpdateFromTrack()) { pnt->updatePointByTrackInfo(&trc); + } const double* yz = pnt->getYZTracking(); const double* errYZ = pnt->getYZErrTracking(); double chi = trc.getPredictedChi2(yz, errYZ); @@ -1101,12 +1136,14 @@ bool AlignmentTrack::residKalman() // int pID = 0, nPnt = getNPoints(); ; - AlignmentPoint* pnt = 0; + AlignmentPoint* pnt = nullptr; // get 1st measured point - while (pID < nPnt && !(pnt = getPoint(pID))->containsMeasurement()) + while (pID < nPnt && !(pnt = getPoint(pID))->containsMeasurement()) { pID++; - if (!pnt) + } + if (!pnt) { return false; + } double phi = trc.getPhi(), alp = pnt->getAlphaSens(); bringTo02Pi(phi); bringTo02Pi(alp); @@ -1149,8 +1186,9 @@ bool AlignmentTrack::residKalman() if (!propagateToPoint(trc, pnt, MaxDefStep, MaxDefSnp, DefMatCorrType)) { return false; } - if (!pnt->containsMeasurement()) + if (!pnt->containsMeasurement()) { continue; + } const double* yz = pnt->getYZTracking(); const double* errYZ = pnt->getYZErrTracking(); // store track position/errors before update in the point WorkSpace-A @@ -1190,8 +1228,9 @@ bool AlignmentTrack::residKalman() if (!propagateToPoint(trc, pnt, MaxDefStep, MaxDefSnp, DefMatCorrType)) { return false; } - if (!pnt->containsMeasurement()) + if (!pnt->containsMeasurement()) { continue; + } const double* yz = pnt->getYZTracking(); const double* errYZ = pnt->getYZErrTracking(); // store track position/errors before update in the point WorkSpace-B @@ -1218,8 +1257,9 @@ bool AlignmentTrack::residKalman() // now compute smoothed prediction and residual for (int ip = 0; ip < nPnt; ip++) { pnt = getPoint(ip); - if (!pnt->containsMeasurement()) + if (!pnt->containsMeasurement()) { continue; + } double* wsA = (double*)pnt->getTrParamWSA(); // inward measurement double* wsB = (double*)pnt->getTrParamWSB(); // outward measurement double &yA = wsA[0], &zA = wsA[1], &sgAYY = wsA[2], &sgAYZ = wsA[3], &sgAZZ = wsA[4]; @@ -1227,10 +1267,11 @@ bool AlignmentTrack::residKalman() // compute weighted average double sgYY = sgAYY + sgBYY, sgYZ = sgAYZ + sgBYZ, sgZZ = sgAZZ + sgBZZ; double detI = sgYY * sgZZ - sgYZ * sgYZ; - if (TMath::Abs(detI) < constants::math::Almost0) + if (TMath::Abs(detI) < constants::math::Almost0) { return false; - else + } else { detI = 1. / detI; + } double tmp = sgYY; sgYY = sgZZ * detI; sgZZ = tmp * detI; @@ -1260,8 +1301,9 @@ bool AlignmentTrack::processMaterials() // collision track of cosmic lower leg: move along track direction from last (middle for cosmic lower leg) // point (inner) to 1st one (outer) - if (mNeedInv[0]) - trc.invert(); // track needs to be inverted ? (should be for upper leg) + if (mNeedInv[0]) { + trc.invert(); + } // track needs to be inverted ? (should be for upper leg) if (!processMaterials(trc, getInnerPointID(), 0)) { #if DEBUG > 3 LOG(error) << "Failed to process materials for leg along the track"; @@ -1271,8 +1313,9 @@ bool AlignmentTrack::processMaterials() if (isCosmic()) { // cosmic upper leg: move againg the track direction from middle point (inner) to last one (outer) trc = *this; - if (mNeedInv[1]) - trc.invert(); // track needs to be inverted ? + if (mNeedInv[1]) { + trc.invert(); + } // track needs to be inverted ? if (!processMaterials(trc, getInnerPointID() + 1, getNPoints() - 1)) { #if DEBUG > 3 LOG(error) << "Failed to process materials for leg against the track"; @@ -1360,10 +1403,12 @@ bool AlignmentTrack::processMaterials(trackParam_t& trc, int pFrom, int pTo) double* par0 = (double*)tr0.getParams(); const covMat_t& cov1 = trc.getCov(); double* par1 = (double*)trc.getParams(); - for (int l = 15; l--;) + for (int l = 15; l--;) { dcov[l] = cov1[l] - cov0[l]; - for (int l = kNKinParBON; l--;) - dpar[l] = par1[l] - par0[l]; // eloss affects all parameters! + } + for (int l = kNKinParBON; l--;) { + dpar[l] = par1[l] - par0[l]; + } // eloss affects all parameters! pnt->setMatCorrExp(dpar); //dpar[kParQ2Pt] = par1[kParQ2Pt] - par0[kParQ2Pt]; // only e-loss expectation is non-0 // @@ -1373,9 +1418,11 @@ bool AlignmentTrack::processMaterials(trackParam_t& trc, int pFrom, int pTo) bool eLossFree = pnt->getELossVaried(); int nParFree = eLossFree ? kNKinParBON : kNKinParBOFF; TMatrixDSym matCov(nParFree); - for (int i = nParFree; i--;) - for (int j = i + 1; j--;) + for (int i = nParFree; i--;) { + for (int j = i + 1; j--;) { matCov(i, j) = matCov(j, i) = dcov[j + ((i * (i + 1)) >> 1)]; + } + } // TMatrixDSymEigen matDiag(matCov); // find eigenvectors const TMatrixD& matEVec = matDiag.GetEigenVectors(); @@ -1388,8 +1435,9 @@ bool AlignmentTrack::processMaterials(trackParam_t& trc, int pFrom, int pTo) } pnt->setMatCovDiagonalizationMatrix(matEVec); // store diagonalization matrix pnt->setMatCovDiag(matDiag.GetEigenValues()); // store E.Values: diagonalized cov.matrix - if (!eLossFree) + if (!eLossFree) { pnt->setMatCovDiagElem(kParQ2Pt, dcov[14]); + } // pnt->setX2X0(matTL.getX2X0()); pnt->setXTimesRho(matTL.getXRho()); @@ -1430,8 +1478,9 @@ void AlignmentTrack::sortPoints() if (isCosmic()) { for (int ip = np; ip--;) { AlignmentPoint* pnt = getPoint(ip); - if (pnt->isInvDir()) - continue; // this is a point of upper leg + if (pnt->isInvDir()) { + continue; + } // this is a point of upper leg mInnerPointID = ip; break; } diff --git a/Detectors/Align/src/Controller.cxx b/Detectors/Align/src/Controller.cxx index 12e2e54a2c0e8..1dda9848c9911 100644 --- a/Detectors/Align/src/Controller.cxx +++ b/Detectors/Align/src/Controller.cxx @@ -48,7 +48,7 @@ #include #include #include -#include +#include #include #include "DetectorsCommonDataFormats/NameConf.h" #include "DataFormatsParameters/GRPObject.h" @@ -79,7 +79,7 @@ const Char_t* Controller::sHStatName[Controller::kNHVars] = { //________________________________________________________________ Controller::Controller(const char* configMacro, int refRun) - : mNDet(0), mNDOFs(0), mRunNumber(-1), mFieldOn(false), mTracksType(Coll), mAlgTrack(0), mVtxSens(0), mConstraints(), + : mNDet(0), mNDOFs(0), mRunNumber(-1), mFieldOn(false), mTracksType(Coll), mAlgTrack(nullptr), mVtxSens(nullptr), mConstraints(), // fSelEventSpecii(AliRecoParam::kCosmic | AliRecoParam::kLowMult | AliRecoParam::kHighMult | AliRecoParam::kDefault), FIXME(milettri): needs AliRecoParam mSelEventSpecii(0), // FIXME(milettri): needs AliRecoParam mCosmicSelStrict(false), @@ -92,24 +92,24 @@ Controller::Controller(const char* configMacro, int refRun) mMaxChi2forVC(10) // , - mGloParVal(0), - mGloParErr(0), - mGloParLab(0), - mOrderedLbl(0), - mLbl2ID(0), - mRefPoint(0), - mESDTree(0), + mGloParVal(nullptr), + mGloParErr(nullptr), + mGloParLab(nullptr), + mOrderedLbl(nullptr), + mLbl2ID(nullptr), + mRefPoint(nullptr), + mESDTree(nullptr), // fESDEvent(0), FIXME(milettri): needs AliESDEvent // fVertex(0), FIXME(milettri): needs AliESDVertex mControlFrac(1.0), mMPOutType(kMille | kMPRec | kContR), - mMille(0), - mMPRecord(0), - mCResid(0), - mMPRecTree(0), - mResidTree(0), - mMPRecFile(0), - mResidFile(0), + mMille(nullptr), + mMPRecord(nullptr), + mCResid(nullptr), + mMPRecTree(nullptr), + mResidTree(nullptr), + mMPRecFile(nullptr), + mResidFile(nullptr), mMilleDBuffer(), mMilleIBuffer(), mMPDatFileName("mpData"), @@ -126,8 +126,8 @@ Controller::Controller(const char* configMacro, int refRun) mOutCDBResponsible("") // , - mDOFStat(0), - mHistoStat(0) + mDOFStat(nullptr), + mHistoStat(nullptr) // , mConfMacroName(configMacro), @@ -139,7 +139,7 @@ Controller::Controller(const char* configMacro, int refRun) { // def c-tor for (int i = kNDetectors; i--;) { - mDetectors[i] = 0; + mDetectors[i] = nullptr; mDetPos[i] = -1; } setPtMinColl(); @@ -155,9 +155,10 @@ Controller::Controller(const char* configMacro, int refRun) setMinPointsColl(); setMinPointsCosm(); // - for (int i = kNCosmLegs; i--;) + for (int i = kNCosmLegs; i--;) { // fESDTrack[i] = 0; FIXME(milettri): needs AliESDtrack - memset(mStat, 0, kNStatCl * kMaxStat * sizeof(float)); + } + memset(mStat, 0, kNStatCl * kMaxStat * sizeof(float)); setMaxDCAforVC(); setMaxChi2forVC(); // SetOutCDBRunRange(); FIXME(milettri): needs OCDB @@ -167,10 +168,12 @@ Controller::Controller(const char* configMacro, int refRun) // run config macro if provided if (!mConfMacroName.IsNull()) { gROOT->ProcessLine(Form(".x %s+g((Controller*)%p)", mConfMacroName.Data(), this)); - if (!getInitDOFsDone()) + if (!getInitDOFsDone()) { initDOFs(); - if (!getNDOFs()) + } + if (!getNDOFs()) { LOG(FATAL) << "No DOFs found, initialization with " << mConfMacroName.Data() << " failed"; + } } } @@ -178,19 +181,23 @@ Controller::Controller(const char* configMacro, int refRun) Controller::~Controller() { // d-tor - if (mMPRecFile) + if (mMPRecFile) { closeMPRecOutput(); - if (mMille) + } + if (mMille) { closeMilleOutput(); - if (mResidFile) + } + if (mResidFile) { closeResidOutput(); + } // delete mAlgTrack; delete[] mGloParVal; delete[] mGloParErr; delete[] mGloParLab; - for (int i = 0; i < mNDet; i++) + for (int i = 0; i < mNDet; i++) { delete mDetectors[i]; + } delete mVtxSens; delete mRefPoint; delete mDOFStat; @@ -203,8 +210,9 @@ void Controller::initDetectors() { // init all detectors geometry // - if (getInitGeomDone()) + if (getInitGeomDone()) { return; + } // // @@ -220,16 +228,19 @@ void Controller::initDetectors() mVtxSens->prepareMatrixL2GIdeal(); dofCnt += mVtxSens->getNDOFs(); // - for (int i = 0; i < mNDet; i++) + for (int i = 0; i < mNDet; i++) { dofCnt += mDetectors[i]->initGeom(); - if (!dofCnt) + } + if (!dofCnt) { LOG(FATAL) << "No DOFs found"; + } // // for (int idt = 0; idt < kNDetectors; idt++) { AlignableDetector* det = getDetectorByDetID(idt); - if (!det || det->isDisabled()) + if (!det || det->isDisabled()) { continue; + } det->cacheReferenceOCDB(); } // @@ -270,14 +281,17 @@ void Controller::initDOFs() for (int i = 0; i < mNDet; i++) { AlignableDetector* det = getDetector(i); det->initDOFs(); - if (det->isDisabled()) + if (det->isDisabled()) { continue; + } nact++; ndfAct += det->getNDOFs(); } - for (int i = 0; i < NTrackTypes; i++) - if (nact < mMinDetAcc[i]) + for (int i = 0; i < NTrackTypes; i++) { + if (nact < mMinDetAcc[i]) { LOG(FATAL) << nact << " detectors are active, while " << mMinDetAcc[i] << " in track are asked"; + } + } // LOG(INFO) << mNDOFs << " global parameters " << mNDet << " detectors, " << ndfAct << " in " << nact << " active detectors"; // @@ -293,27 +307,31 @@ void Controller::assignDOFs() // to be called (of initDOFs should be called) // int ndfOld = -1; - if (mNDOFs > 0) + if (mNDOFs > 0) { ndfOld = mNDOFs; + } mNDOFs = 0; // mVtxSens->assignDOFs(mNDOFs, mGloParVal, mGloParErr, mGloParLab); // for (int idt = 0; idt < kNDetectors; idt++) { AlignableDetector* det = getDetectorByDetID(idt); - if (!det) + if (!det) { continue; + } //if (det->isDisabled()) continue; mNDOFs += det->assignDOFs(); } LOG(INFO) << "Assigned parameters/labels arrays for " << mNDOFs << " DOFs"; - if (ndfOld > -1 && ndfOld != mNDOFs) + if (ndfOld > -1 && ndfOld != mNDOFs) { LOG(ERROR) << "Recalculated NDOFs=" << mNDOFs << " not equal to saved NDOFs=" << ndfOld; + } // // build Lbl <-> parID table Sort(mNDOFs, mGloParLab, mLbl2ID, false); // sort in increasing order - for (int i = mNDOFs; i--;) + for (int i = mNDOFs; i--;) { mOrderedLbl[i] = mGloParLab[mLbl2ID[i]]; + } // } @@ -323,14 +341,16 @@ void Controller::addDetector(uint32_t id, AlignableDetector* det) LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; // add detector participating in the alignment, optionally constructed externally // - if (!mRefOCDBLoaded) + if (!mRefOCDBLoaded) { // LoadRefOCDB(); FIXME(milettri): needs OCDB - // - if (id >= kNDetectors) - LOG(FATAL) << "Detector typeID " << id << " exceeds allowed range " << 0 << ":" << (kNDetectors - 1); + } + if (id >= kNDetectors) { + LOG(FATAL) << "Detector typeID " << id << " exceeds allowed range " << 0 << ":" << (kNDetectors - 1); + } // - if (mDetPos[id] != -1) + if (mDetPos[id] != -1) { LOG(FATAL) << "Detector " << id << " was already added"; + } if (!det) { switch (id) { // case kITS: @@ -354,8 +374,9 @@ void Controller::addDetector(uint32_t id, AlignableDetector* det) mDetectors[mNDet] = det; mDetPos[id] = mNDet; det->setAlgSteer(this); - for (int i = 0; i < NTrackTypes; i++) + for (int i = 0; i < NTrackTypes; i++) { setObligatoryDetector(id, i, det->isObligatory(i)); + } mNDet++; // } @@ -383,11 +404,13 @@ bool Controller::checkDetectorPoints(const int* npsel) const int ndOK = 0; for (int idt = 0; idt < kNDetectors; idt++) { AlignableDetector* det = getDetectorByDetID(idt); - if (!det || det->isDisabled(mTracksType)) + if (!det || det->isDisabled(mTracksType)) { continue; + } if (npsel[idt] < det->getNPointsSel(mTracksType)) { - if (det->isObligatory(mTracksType)) + if (det->isObligatory(mTracksType)) { return false; + } continue; } ndOK++; @@ -402,25 +425,25 @@ bool Controller::checkDetectorPoints(const int* npsel) const // // decide if the track should be processed // AlignableDetector* det = 0; // uint32_t detAcc = 0; -// if (mFieldOn && esdTr->Pt() < mPtMin[mTracksType]) -// return 0; -// if (Abs(esdTr->Eta()) > mEtaMax[mTracksType]) -// return 0; +// if (mFieldOn && esdTr->Pt() < mPtMin[mTracksType]){ +// return 0;} +// if (Abs(esdTr->Eta()) > mEtaMax[mTracksType]){ +// return 0;} // // // for (int idet = 0; idet < kNDetectors; idet++) { -// if (!(det = getDetectorByDetID(idet)) || det->isDisabled(mTracksType)) -// continue; +// if (!(det = getDetectorByDetID(idet)) || det->isDisabled(mTracksType)){ +// continue;} // if (!det->AcceptTrack(esdTr, mTracksType)) { -// if (strict && det->isObligatory(mTracksType)) -// return 0; +// if (strict && det->isObligatory(mTracksType)){ +// return 0;} // else // continue; // } // // // detAcc |= 0x1 << idet; // } -// if (numberOfBitsSet(detAcc) < mMinDetAcc[mTracksType]) -// return 0; +// if (numberOfBitsSet(detAcc) < mMinDetAcc[mTracksType]){ +// return 0;} // return detAcc; // // //} @@ -433,16 +456,16 @@ bool Controller::checkDetectorPoints(const int* npsel) const // uint32_t detAcc = 0, detAccLeg; // for (int i = kNCosmLegs; i--;) { // detAccLeg = AcceptTrack(esdPairCosm[i], mCosmicSelStrict); // missing obligatory detectors in one leg might be allowed -// if (!detAccLeg) -// return 0; +// if (!detAccLeg){ +// return 0;} // detAcc |= detAccLeg; // } -// if (mCosmicSelStrict) -// return detAcc; +// if (mCosmicSelStrict){ +// return detAcc;} // // // // for non-stric selection check convolution of detector presence -// if (!checkDetectorPattern(detAcc)) -// return 0; +// if (!checkDetectorPattern(detAcc)){ +// return 0;} // return detAcc; // // //} @@ -477,8 +500,8 @@ bool Controller::checkDetectorPoints(const int* npsel) const // // // SetESDEvent(esdEv); // // -// if (esdEv->getRunNumber() != getRunNumber()) -// SetRunNumber(esdEv->getRunNumber()); +// if (esdEv->getRunNumber() != getRunNumber()){ +// SetRunNumber(esdEv->getRunNumber());} // // // if (!(esdEv->GetEventSpecie() & fSelEventSpecii)) { //#if DEBUG > 2 @@ -497,8 +520,8 @@ bool Controller::checkDetectorPoints(const int* npsel) const //#endif // // // setFieldOn(Abs(esdEv->GetMagneticField()) > kAlmost0Field); -// if (!isCosmic() && !CheckSetVertex(esdEv->GetPrimaryVertexTracks())) -// return false; +// if (!isCosmic() && !CheckSetVertex(esdEv->GetPrimaryVertexTracks())){ +// return false;} // fillStatHisto(kEvVtx); // // // int ntr = 0, accTr = 0; @@ -509,8 +532,8 @@ bool Controller::checkDetectorPoints(const int* npsel) const // for (int itr = 0; itr < ntr; itr++) { // accTr += ProcessTrack(esdEv->GetCosmicTrack(itr)); // } -// if (accTr) -// mStat[kAccStat][kEventCosm]++; +// if (accTr){ +// mStat[kAccStat][kEventCosm]++;} // } else { // mStat[kInpStat][kEventColl]++; // ntr = esdEv->GetNumberOfTracks(); @@ -529,8 +552,8 @@ bool Controller::checkDetectorPoints(const int* npsel) const // } // */ // } -// if (accTr) -// mStat[kAccStat][kEventColl]++; +// if (accTr){ +// mStat[kAccStat][kEventColl]++;} // } // // // fillStatHisto(kTrackAcc, accTr); @@ -553,15 +576,15 @@ bool Controller::checkDetectorPoints(const int* npsel) const // // // int nPnt = 0; // const AliESDfriendTrack* trF = esdTr->GetFriendTrack(); -// if (!trF) -// return false; +// if (!trF){ +// return false;} // const AliTrackPointArray* trPoints = trF->GetTrackPointArray(); -// if (!trPoints || (nPnt = trPoints->GetNPoints()) < 1) -// return false; +// if (!trPoints || (nPnt = trPoints->GetNPoints()) < 1){ +// return false;} // // // uint32_t detAcc = AcceptTrack(esdTr); -// if (!detAcc) -// return false; +// if (!detAcc){ +// return false;} // // // resetDetectors(); // mAlgTrack->Clear(); @@ -569,28 +592,28 @@ bool Controller::checkDetectorPoints(const int* npsel) const // // process the track points for each detector, // AlignableDetector* det = 0; // for (int idet = 0; idet < kNDetectors; idet++) { -// if (!(detAcc & (0x1 << idet))) -// continue; +// if (!(detAcc & (0x1 << idet))){ +// continue;} // det = getDetectorByDetID(idet); // if (det->ProcessPoints(esdTr, mAlgTrack) < det->getNPointsSel(kColl)) { // detAcc &= ~(0x1 << idet); // did not survive, suppress detector in the track -// if (det->isObligatory(kColl)) -// return false; +// if (det->isObligatory(kColl)){ +// return false;} // } -// if (numberOfBitsSet(detAcc) < mMinDetAcc[kColl]) -// return false; // abandon track +// if (numberOfBitsSet(detAcc) < mMinDetAcc[kColl]){ +// return false;} // abandon track // } // // -// if (mAlgTrack->getNPoints() < getMinPoints()) -// return false; +// if (mAlgTrack->getNPoints() < getMinPoints()){ +// return false;} // // fill needed points (tracking frame) in the mAlgTrack // mRefPoint->setContainsMeasurement(false); // mRefPoint->setContainsMaterial(false); // mAlgTrack->addPoint(mRefPoint); // reference point which the track will refer to // // // mAlgTrack->copyFrom(esdTr); -// if (!getFieldOn()) -// mAlgTrack->imposePtBOff(mDefPtBOff[utils::kColl]); +// if (!getFieldOn()){ +// mAlgTrack->imposePtBOff(mDefPtBOff[utils::kColl]);} // mAlgTrack->setFieldON(getFieldOn()); // mAlgTrack->sortPoints(); // // @@ -612,24 +635,24 @@ bool Controller::checkDetectorPoints(const int* npsel) const // fillStatHisto(kTrackFitInpVC); // // // fillStatHisto(kTrackFitInp); -// if (!mAlgTrack->iniFit()) -// return false; +// if (!mAlgTrack->iniFit()){ +// return false;} // fillStatHisto(kTrackProcMatInp); -// if (!mAlgTrack->processMaterials()) -// return false; +// if (!mAlgTrack->processMaterials()){ +// return false;} // mAlgTrack->defineDOFs(); // // // fillStatHisto(kTrackResDerInp); -// if (!mAlgTrack->calcResidDeriv()) -// return false; +// if (!mAlgTrack->calcResidDeriv()){ +// return false;} // // -// if (!storeProcessedTrack(mMPOutType & ~kContR)) -// return false; // store derivatives for MP +// if (!storeProcessedTrack(mMPOutType & ~kContR)){ +// return false;} // store derivatives for MP // // // if (getProduceControlRes() && // need control residuals, ignore selection fraction if this is the // (mMPOutType == kContR || gRandom->Rndm() < mControlFrac)) { // output requested -// if (!testLocalSolution() || !storeProcessedTrack(kContR)) -// return false; +// if (!testLocalSolution() || !storeProcessedTrack(kContR)){ +// return false;} // } // // // fillStatHisto(kTrackStore); @@ -680,18 +703,18 @@ bool Controller::checkDetectorPoints(const int* npsel) const // const AliESDtrack* esdTr = // fESDEvent->GetTrack(leg == kCosmLow ? cosmTr->GetESDLowerTrackIndex() : cosmTr->GetESDUpperTrackIndex()); // const AliESDfriendTrack* trF = esdTr->GetFriendTrack(); -// if (!trF) -// return false; +// if (!trF){ +// return false;} // const AliTrackPointArray* trPoints = trF->GetTrackPointArray(); -// if (!trPoints || (nPnt += trPoints->GetNPoints()) < 1) -// return false; +// if (!trPoints || (nPnt += trPoints->GetNPoints()) < 1){ +// return false;} // // // fESDTrack[leg] = esdTr; // } // // // uint32_t detAcc = AcceptTrackCosmic(fESDTrack); -// if (!detAcc) -// return false; +// if (!detAcc){ +// return false;} // // // resetDetectors(); // mAlgTrack->Clear(); @@ -707,8 +730,8 @@ bool Controller::checkDetectorPoints(const int* npsel) const // int npsel[kNDetectors] = {0}; // for (int nPleg = 0, leg = kNCosmLegs; leg--;) { // for (int idet = 0; idet < kNDetectors; idet++) { -// if (!(detAcc & (0x1 << idet))) -// continue; +// if (!(detAcc & (0x1 << idet))){ +// continue;} // det = getDetectorByDetID(idet); // // // // upper leg points marked as the track going in inverse direction @@ -719,16 +742,16 @@ bool Controller::checkDetectorPoints(const int* npsel) const // npsel[idet] += np; // nPleg += np; // } -// if (nPleg < getMinPoints()) -// return false; +// if (nPleg < getMinPoints()){ +// return false;} // } // // last check on legs-combined patter -// if (!checkDetectorPoints(npsel)) -// return false; +// if (!checkDetectorPoints(npsel)){ +// return false;} // // // mAlgTrack->copyFrom(cosmTr); -// if (!getFieldOn()) -// mAlgTrack->imposePtBOff(mDefPtBOff[utils::Cosm]); +// if (!getFieldOn()){ +// mAlgTrack->imposePtBOff(mDefPtBOff[utils::Cosm]);} // mAlgTrack->setFieldON(getFieldOn()); // mAlgTrack->sortPoints(); // // @@ -745,25 +768,25 @@ bool Controller::checkDetectorPoints(const int* npsel) const // mRefPoint->setAlphaSens(sector2Alpha(mAlgTrack->getPoint(pntMeas)->getAliceSector())); // // // fillStatHisto(kTrackFitInp); -// if (!mAlgTrack->iniFit()) -// return false; +// if (!mAlgTrack->iniFit()){ +// return false;} // // // fillStatHisto(kTrackProcMatInp); -// if (!mAlgTrack->processMaterials()) -// return false; +// if (!mAlgTrack->processMaterials()){ +// return false;} // mAlgTrack->defineDOFs(); // // // fillStatHisto(kTrackResDerInp); -// if (!mAlgTrack->calcResidDeriv()) -// return false; +// if (!mAlgTrack->calcResidDeriv()){ +// return false;} // // -// if (!storeProcessedTrack(mMPOutType & ~kContR)) -// return false; // store derivatives for MP +// if (!storeProcessedTrack(mMPOutType & ~kContR)){ +// return false;} // store derivatives for MP // // // if (getProduceControlRes() && // need control residuals, ignore selection fraction if this is the // (mMPOutType == kContR || gRandom->Rndm() < mControlFrac)) { // output requested -// if (!testLocalSolution() || !storeProcessedTrack(kContR)) -// return false; +// if (!testLocalSolution() || !storeProcessedTrack(kContR)){ +// return false;} // } // // // fillStatHisto(kTrackStore); @@ -776,12 +799,15 @@ bool Controller::storeProcessedTrack(int what) { // write alignment track bool res = true; - if ((what & kMille)) + if ((what & kMille)) { res &= fillMilleData(); - if ((what & kMPRec)) + } + if ((what & kMPRec)) { res &= fillMPRecData(); - if ((what & kContR)) + } + if ((what & kContR)) { res &= fillControlData(); + } // return res; } @@ -793,8 +819,9 @@ bool Controller::fillMilleData() if (!mMille) { TString mo = Form("%s%s", mMPDatFileName.Data(), sMPDataExt); mMille = new Mille(mo.Data(), mMilleOutBin); - if (!mMille) + if (!mMille) { LOG(FATAL) << "Failed to create output file " << mo.Data(); + } } // if (!mAlgTrack->getDerivDone()) { @@ -804,8 +831,8 @@ bool Controller::fillMilleData() int np(mAlgTrack->getNPoints()), nDGloTot(0); // total number global derivatives stored int nParETP(mAlgTrack->getNLocExtPar()); // numnber of local parameters for reference track param int nVarLoc(mAlgTrack->getNLocPar()); // number of local degrees of freedom in the track - float *buffDL(0), *buffDG(0); // faster acces arrays - int* buffI(0); + float *buffDL(nullptr), *buffDG(nullptr); // faster acces arrays + int* buffI(nullptr); // const int* gloParID(mAlgTrack->getGloParID()); // IDs of global DOFs this track depends on for (int ip = 0; ip < np; ip++) { @@ -813,14 +840,17 @@ bool Controller::fillMilleData() if (pnt->containsMeasurement()) { int gloOffs = pnt->getDGloOffs(); // 1st entry of global derivatives for this point int nDGlo = pnt->getNGloDOFs(); // number of global derivatives (number of DOFs it depends on) - if (!pnt->isStatOK()) + if (!pnt->isStatOK()) { pnt->incrementStat(); + } // check buffer sizes { - if (mMilleDBuffer.GetSize() < nVarLoc + nDGlo) + if (mMilleDBuffer.GetSize() < nVarLoc + nDGlo) { mMilleDBuffer.Set(100 + nVarLoc + nDGlo); - if (mMilleIBuffer.GetSize() < nDGlo) + } + if (mMilleIBuffer.GetSize() < nDGlo) { mMilleIBuffer.Set(100 + nDGlo); + } buffDL = mMilleDBuffer.GetArray(); // faster acces buffDG = buffDL + nVarLoc; // faster acces buffI = mMilleIBuffer.GetArray(); // faster acces @@ -831,13 +861,15 @@ bool Controller::fillMilleData() memset(buffDL, 0, nVarLoc * sizeof(float)); const double* deriv = mAlgTrack->getDResDLoc(idim, ip); // array of Dresidual/Dparams_loc // derivatives over reference track parameters - for (int j = 0; j < nParETP; j++) + for (int j = 0; j < nParETP; j++) { buffDL[j] = (isZeroAbs(deriv[j])) ? 0 : deriv[j]; + } // // point may depend on material variables within these limits int lp0 = pnt->getMinLocVarID(), lp1 = pnt->getMaxLocVarID(); - for (int j = lp0; j < lp1; j++) + for (int j = lp0; j < lp1; j++) { buffDL[j] = (isZeroAbs(deriv[j])) ? 0 : deriv[j]; + } // // derivatives over global params: this array can be 0-suppressed, no need to reset int nGlo(0); @@ -888,17 +920,17 @@ bool Controller::fillMPRecData() LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs AliESDEvent // // store MP2 in MPRecord format - // if (!mMPRecord) - // initMPRecOutput(); + // if (!mMPRecord){ + // initMPRecOutput();} // // // mMPRecord->Clear(); - // if (!mMPRecord->fillTrack(mAlgTrack, mGloParLab)) - // return false; + // if (!mMPRecord->fillTrack(mAlgTrack, mGloParLab)){ + // return false;} // mMPRecord->SetRun(mRunNumber); // mMPRecord->setTimeStamp(fESDEvent->GetTimeStamp()); // uint32_t tID = 0xffff & uint(fESDTrack[0]->GetID()); - // if (isCosmic()) - // tID |= (0xffff & uint(fESDTrack[1]->GetID())) << 16; + // if (isCosmic()){ + // tID |= (0xffff & uint(fESDTrack[1]->GetID())) << 16;} // mMPRecord->setTrackID(tID); // mMPRecTree->Fill(); return true; @@ -910,23 +942,23 @@ bool Controller::fillControlData() LOG(FATAL) << __PRETTY_FUNCTION__ << " is disabled"; //FIXME(milettri): needs AliESDEvent // // store control residuals - // if (!mCResid) - // initResidOutput(); + // if (!mCResid){ + // initResidOutput();} // // // int nps, np = mAlgTrack->getNPoints(); // nps = (!mRefPoint->containsMeasurement()) ? np - 1 : np; // ref point is dummy? - // if (nps < 0) - // return true; + // if (nps < 0){ + // return true;} // // // mCResid->Clear(); - // if (!mCResid->fillTrack(mAlgTrack, mDoKalmanResid)) - // return false; + // if (!mCResid->fillTrack(mAlgTrack, mDoKalmanResid)){ + // return false;} // mCResid->setRun(mRunNumber); // mCResid->setTimeStamp(fESDEvent->GetTimeStamp()); // mCResid->setBz(fESDEvent->GetMagneticField()); // uint32_t tID = 0xffff & uint(fESDTrack[0]->GetID()); - // if (isCosmic()) - // tID |= (0xffff & uint(fESDTrack[1]->GetID())) << 16; + // if (isCosmic()){ + // tID |= (0xffff & uint(fESDTrack[1]->GetID())) << 16;} // mCResid->setTrackID(tID); // // // mResidTree->Fill(); @@ -938,8 +970,9 @@ bool Controller::fillControlData() //_________________________________________________________ void Controller::setRunNumber(int run) { - if (run == mRunNumber) - return; // nothing to do + if (run == mRunNumber) { + return; + } // nothing to do // acknowledgeNewRun(run); } @@ -955,13 +988,13 @@ void Controller::acknowledgeNewRun(int run) //FIXME(milettri): needs AliESDEvent // // load needed info for new run - // if (run == mRunNumber) - // return; // nothing to do + // if (run == mRunNumber){ + // return;} // nothing to do // if (run > 0) { // mStat[kAccStat][kRun]++; // } - // if (mRunNumber > 0) - // fillStatHisto(kRunDone); + // if (mRunNumber > 0){ + // fillStatHisto(kRunDone);} // mRunNumber = run; // LOG(INFO) << "Processing new run " << mRunNumber; // // @@ -980,8 +1013,8 @@ void Controller::acknowledgeNewRun(int run) // // // for (int idet = 0; idet < mNDet; idet++) { // AlignableDetector* det = getDetector(idet); - // if (!det->isDisabled()) - // det->acknowledgeNewRun(run); + // if (!det->isDisabled()){ + // det->acknowledgeNewRun(run);} // } // // // // bring to virgin state @@ -1007,14 +1040,14 @@ void Controller::acknowledgeNewRun(int run) // if (!mRecoOCDBConf.IsNull() && !gSystem->AccessPathName(mRecoOCDBConf.Data(), kFileExists)) { // LOG(INFO) << "Executing reco-time OCDB setup macro " << mRecoOCDBConf.Data(); // gROOT->ProcessLine(Form(".x %s(%d)", mRecoOCDBConf.Data(), mRunNumber)); -// if (AliCDBManager::Instance()->IsDefaultStorageSet()) -// return true; +// if (AliCDBManager::Instance()->IsDefaultStorageSet()){ +// return true;} // LOG(FATAL) << "macro " << mRecoOCDBConf.Data() << " failed to configure reco-time OCDB"; // } else // LOG(WARNING) << "No reco-time OCDB config macro" << mRecoOCDBConf.Data() << " is found, will use ESD:UserInfo"; // // -// if (!mESDTree) -// LOG(FATAL) << "Cannot preload Reco-Time OCDB since the ESD tree is not set"; +// if (!mESDTree){ +// LOG(FATAL) << "Cannot preload Reco-Time OCDB since the ESD tree is not set";} // const TTree* tr = mESDTree; // go the the real ESD tree // while (tr->GetTree() && tr->GetTree() != tr) // tr = tr->GetTree(); @@ -1035,10 +1068,12 @@ void Controller::acknowledgeNewRun(int run) AlignableDetector* Controller::getDetectorByVolID(int vid) const { // get detector by sensor volid - for (int i = mNDet; i--;) - if (mDetectors[i]->sensorOfDetector(vid)) + for (int i = mNDet; i--;) { + if (mDetectors[i]->sensorOfDetector(vid)) { return mDetectors[i]; - return 0; + } + } + return nullptr; } //____________________________________________ @@ -1048,16 +1083,19 @@ void Controller::Print(const Option_t* opt) const TString opts = opt; opts.ToLower(); printf("%5d DOFs in %d detectors", mNDOFs, mNDet); - if (!mConfMacroName.IsNull()) + if (!mConfMacroName.IsNull()) { printf("(config: %s)", mConfMacroName.Data()); + } printf("\n"); - if (getMPAlignDone()) + if (getMPAlignDone()) { printf("ALIGNMENT FROM MILLEPEDE SOLUTION IS APPLIED\n"); + } // for (int idt = 0; idt < kNDetectors; idt++) { AlignableDetector* det = getDetectorByDetID(idt); - if (!det) + if (!det) { continue; + } det->Print(opt); } if (!opts.IsNull()) { @@ -1089,8 +1127,9 @@ void Controller::Print(const Option_t* opt) const printf("Cosmic tracks: Min pT: %5.2f |etaMax|: %5.2f\n", mPtMin[Cosm], mEtaMax[Cosm]); // printf("%-40s:\t%s", "Config. for reference OCDB", mRefOCDBConf.Data()); - if (mRefRunNumber >= 0) + if (mRefRunNumber >= 0) { printf("(%d)", mRefRunNumber); + } printf("\n"); printf("%-40s:\t%s\n", "Config. for reco-time OCDB", mRecoOCDBConf.Data()); // @@ -1105,14 +1144,17 @@ void Controller::Print(const Option_t* opt) const printf("%-40s:\t%s\n", "Filename for control residuals:", mResidFileName.Data()); printf("%-40s:\t%.3f\n", "Fraction of control tracks", mControlFrac); printf("MPData output :\t"); - if (getProduceMPData()) + if (getProduceMPData()) { printf("%s%s ", mMPDatFileName.Data(), sMPDataExt); - if (getProduceMPRecord()) + } + if (getProduceMPRecord()) { printf("%s%s ", mMPDatFileName.Data(), ".root"); + } printf("\n"); // - if (opts.Contains("stat")) + if (opts.Contains("stat")) { printStatistics(); + } } //________________________________________________________ @@ -1121,13 +1163,15 @@ void Controller::printStatistics() const // print processing stat printf("\nProcessing Statistics\n"); printf("Type: "); - for (int i = 0; i < kMaxStat; i++) + for (int i = 0; i < kMaxStat; i++) { printf("%s ", sStatName[i]); + } printf("\n"); for (int icl = 0; icl < kNStatCl; icl++) { printf("%s ", sStatClName[icl]); - for (int i = 0; i < kMaxStat; i++) + for (int i = 0; i < kMaxStat; i++) { printf(Form("%%%dd ", (int)strlen(sStatName[i])), (int)mStat[icl][i]); + } printf("\n"); } } @@ -1151,8 +1195,8 @@ bool Controller::testLocalSolution() // // test track local solution // TVectorD rhs; // AliSymMatrix* mat = BuildMatrix(rhs); - // if (!mat) - // return false; + // if (!mat){ + // return false;} // // mat->Print("long data"); // // rhs.Print(); // TVectorD vsl(rhs); @@ -1254,13 +1298,15 @@ bool Controller::testLocalSolution() void Controller::initMPRecOutput() { // prepare MP record output - if (!mMPRecord) + if (!mMPRecord) { mMPRecord = new Millepede2Record(); + } // TString mo = Form("%s%s", mMPDatFileName.Data(), ".root"); mMPRecFile = TFile::Open(mo.Data(), "recreate"); - if (!mMPRecFile) + if (!mMPRecFile) { LOG(FATAL) << "Failed to create output file " << mo.Data(); + } // mMPRecTree = new TTree("mpTree", "MPrecord Tree"); mMPRecTree->Branch("mprec", "Millepede2Record", &mMPRecord); @@ -1271,12 +1317,14 @@ void Controller::initMPRecOutput() void Controller::initResidOutput() { // prepare residual output - if (!mCResid) + if (!mCResid) { mCResid = new ResidualsController(); + } // mResidFile = TFile::Open(mResidFileName.Data(), "recreate"); - if (!mResidFile) + if (!mResidFile) { LOG(FATAL) << "Failed to create output file " << mResidFileName.Data(); + } // mResidTree = new TTree("res", "Control Residuals"); mResidTree->Branch("t", "ResidualsController", &mCResid); @@ -1287,46 +1335,49 @@ void Controller::initResidOutput() void Controller::closeMPRecOutput() { // close output - if (!mMPRecFile) + if (!mMPRecFile) { return; + } LOG(INFO) << "Closing " << mMPRecFile->GetName(); mMPRecFile->cd(); mMPRecTree->Write(); delete mMPRecTree; - mMPRecTree = 0; + mMPRecTree = nullptr; mMPRecFile->Close(); delete mMPRecFile; - mMPRecFile = 0; + mMPRecFile = nullptr; delete mMPRecord; - mMPRecord = 0; + mMPRecord = nullptr; } //____________________________________________ void Controller::closeResidOutput() { // close output - if (!mResidFile) + if (!mResidFile) { return; + } LOG(INFO) << "Closing " << mResidFile->GetName(); mResidFile->cd(); mResidTree->Write(); delete mResidTree; - mResidTree = 0; + mResidTree = nullptr; mResidFile->Close(); delete mResidFile; - mResidFile = 0; + mResidFile = nullptr; delete mCResid; - mCResid = 0; + mCResid = nullptr; } //____________________________________________ void Controller::closeMilleOutput() { // close output - if (mMille) + if (mMille) { LOG(INFO) << "Closing " << mMPDatFileName.Data() << sMPDataExt; + } delete mMille; - mMille = 0; + mMille = nullptr; } //____________________________________________ @@ -1335,13 +1386,15 @@ void Controller::setMPDatFileName(const char* name) // set output file name mMPDatFileName = name; // strip root or mille extensions, they will be added automatically later - if (mMPDatFileName.EndsWith(sMPDataExt)) + if (mMPDatFileName.EndsWith(sMPDataExt)) { mMPDatFileName.Remove(mMPDatFileName.Length() - strlen(sMPDataExt)); - else if (mMPDatFileName.EndsWith(".root")) + } else if (mMPDatFileName.EndsWith(".root")) { mMPDatFileName.Remove(mMPDatFileName.Length() - strlen(".root")); + } // - if (mMPDatFileName.IsNull()) + if (mMPDatFileName.IsNull()) { mMPDatFileName = "mpData"; + } // } @@ -1350,8 +1403,9 @@ void Controller::setMPParFileName(const char* name) { // set MP params output file name mMPParFileName = name; - if (mMPParFileName.IsNull()) + if (mMPParFileName.IsNull()) { mMPParFileName = "mpParams.txt"; + } // } @@ -1360,8 +1414,9 @@ void Controller::setMPConFileName(const char* name) { // set MP constraints output file name mMPConFileName = name; - if (mMPConFileName.IsNull()) + if (mMPConFileName.IsNull()) { mMPConFileName = "mpConstraints.txt"; + } // } @@ -1370,8 +1425,9 @@ void Controller::setMPSteerFileName(const char* name) { // set MP constraints output file name mMPSteerFileName = name; - if (mMPSteerFileName.IsNull()) + if (mMPSteerFileName.IsNull()) { mMPSteerFileName = "mpConstraints.txt"; + } // } @@ -1380,8 +1436,9 @@ void Controller::setResidFileName(const char* name) { // set output file name mResidFileName = name; - if (mResidFileName.IsNull()) + if (mResidFileName.IsNull()) { mResidFileName = "mpControlRes.root"; + } // } @@ -1390,8 +1447,9 @@ void Controller::setOutCDBPath(const char* name) { // set output storage name mOutCDBPath = name; - if (mOutCDBPath.IsNull()) + if (mOutCDBPath.IsNull()) { mOutCDBPath = "local://outOCDB"; + } // } @@ -1403,12 +1461,14 @@ void Controller::setObligatoryDetector(int detID, int trtype, bool v) if (!det) { LOG(ERROR) << "Detector " << detID << " is not defined"; } - if (v) + if (v) { mObligatoryDetPattern[trtype] |= 0x1 << detID; - else + } else { mObligatoryDetPattern[trtype] &= ~(0x1 << detID); - if (det->isObligatory(trtype) != v) + } + if (det->isObligatory(trtype) != v) { det->setObligatory(trtype, v); + } // } @@ -1420,29 +1480,29 @@ bool Controller::addVertexConstraint() // // if vertex is set and if particle is primary, add vertex as a meared point // // // const AliESDtrack* esdTr = fESDTrack[0]; - // if (!fVertex || !esdTr) - // return false; + // if (!fVertex || !esdTr){ + // return false;} // // - // if (esdTr->GetNcls(0) < mMinITSClforVC) - // return false; // not enough ITS clusters - // if (!AlignableDetectorITS::CheckHitPattern(esdTr, mITSPattforVC)) - // return false; + // if (esdTr->GetNcls(0) < mMinITSClforVC){ + // return false;} // not enough ITS clusters + // if (!AlignableDetectorITS::CheckHitPattern(esdTr, mITSPattforVC)){ + // return false;} // // // AliExternalTrackParam trc = *esdTr; // double dz[2], dzCov[3]; - // if (!trc.PropagateToDCA(fVertex, AliTrackerBase::GetBz(), 2 * mMaxDCAforVC[0], dz, dzCov)) - // return false; + // if (!trc.PropagateToDCA(fVertex, AliTrackerBase::GetBz(), 2 * mMaxDCAforVC[0], dz, dzCov)){ + // return false;} // // // // check if primary candidate - // if (Abs(dz[0]) > mMaxDCAforVC[0] || Abs(dz[1]) > mMaxDCAforVC[1]) - // return false; + // if (Abs(dz[0]) > mMaxDCAforVC[0] || Abs(dz[1]) > mMaxDCAforVC[1]){ + // return false;} // double covar[6]; // fVertex->GetCovMatrix(covar); // double p[2] = {trc.GetParameter()[0] - dz[0], trc.GetParameter()[1] - dz[1]}; // double c[3] = {0.5 * (covar[0] + covar[2]), 0., covar[5]}; // double chi2 = trc.GetPredictedChi2(p, c); - // if (chi2 > mMaxChi2forVC) - // return false; + // if (chi2 > mMaxChi2forVC){ + // return false;} // // // // assing measured vertex rotated to VtxSens frame as reference point // double xyz[3], xyzT[3]; @@ -1472,8 +1532,8 @@ bool Controller::addVertexConstraint() // // // AlignableDetector* det; // for (int idet = 0; idet < kNDetectors; idet++) { -// if (!(det = getDetectorByDetID(idet)) || det->isDisabled()) -// continue; +// if (!(det = getDetectorByDetID(idet)) || det->isDisabled()){ +// continue;} // det->writeCalibrationResults(); // } // // @@ -1503,8 +1563,8 @@ bool Controller::addVertexConstraint() // // // if (!mRefOCDBConf.IsNull() && !gSystem->AccessPathName(mRefOCDBConf.Data(), kFileExists)) { // LOG(INFO) << "Executing reference OCDB setup macro %s", mRefOCDBConf.Data()); -// if (mRefRunNumber > 0) -// gROOT->ProcessLine(Form(".x %s(%d)", mRefOCDBConf.Data(), mRefRunNumber)); +// if (mRefRunNumber > 0){ +// gROOT->ProcessLine(Form(".x %s(%d)", mRefOCDBConf.Data(), mRefRunNumber));} // else // gROOT->ProcessLine(Form(".x %s", mRefOCDBConf.Data())); // } else { @@ -1518,8 +1578,8 @@ bool Controller::addVertexConstraint() // AliGeomManager::Destroy(); // } // AliGeomManager::LoadGeometry("geometry.root"); -// if (!AliGeomManager::GetGeometry()) -// LOG(FATAL) << "Failed to load geometry, cannot run"); +// if (!AliGeomManager::GetGeometry()){ +// LOG(FATAL) << "Failed to load geometry, cannot run");} // // // TString detList = ""; // for (int i = 0; i < kNDetectors; i++) { @@ -1539,10 +1599,11 @@ AlignableDetector* Controller::getDetOfDOFID(int id) const // return detector owning DOF with this ID for (int i = mNDet; i--;) { AlignableDetector* det = getDetector(i); - if (det->ownsDOFID(id)) + if (det->ownsDOFID(id)) { return det; + } } - return 0; + return nullptr; } //________________________________________________________ @@ -1551,30 +1612,36 @@ AlignableVolume* Controller::getVolOfDOFID(int id) const // return volume owning DOF with this ID for (int i = mNDet; i--;) { AlignableDetector* det = getDetector(i); - if (det->ownsDOFID(id)) + if (det->ownsDOFID(id)) { return det->getVolOfDOFID(id); + } } - if (mVtxSens && mVtxSens->ownsDOFID(id)) + if (mVtxSens && mVtxSens->ownsDOFID(id)) { return mVtxSens; - return 0; + } + return nullptr; } //________________________________________________________ void Controller::terminate(bool doStat) { // finalize processing - if (mRunNumber > 0) + if (mRunNumber > 0) { fillStatHisto(kRunDone); + } if (doStat) { - if (mDOFStat) + if (mDOFStat) { delete mDOFStat; + } mDOFStat = new DOFStatistics(mNDOFs); } - if (mVtxSens) + if (mVtxSens) { mVtxSens->fillDOFStat(mDOFStat); + } // - for (int i = mNDet; i--;) + for (int i = mNDet; i--;) { getDetector(i)->terminate(); + } closeMPRecOutput(); closeMilleOutput(); closeResidOutput(); @@ -1587,16 +1654,18 @@ Char_t* Controller::getDOFLabelTxt(int idf) const { // get DOF full label AlignableVolume* vol = getVolOfDOFID(idf); - if (vol) + if (vol) { return Form("%d_%s_%s", getGloParLab(idf), vol->getSymName(), vol->getDOFName(idf - vol->getFirstParGloID())); + } // // this might be detector-specific calibration dof AlignableDetector* det = getDetOfDOFID(idf); - if (det) + if (det) { return Form("%d_%s_%s", getGloParLab(idf), det->GetName(), det->getCalibDOFName(idf - det->getFirstParGloID())); - return 0; + } + return nullptr; } //********************* interaction with PEDE ********************** @@ -1651,13 +1720,15 @@ void Controller::genPedeSteerFile(const Option_t* opt) const // fprintf(strFl, "\n\n\n%s%-20s %s %s\n\n\n", cmt[kOff], "CFiles", cmt[kOnOn], "put below *.mille files list"); // - if (mVtxSens) + if (mVtxSens) { mVtxSens->writePedeInfo(parFl, opt); + } // for (int idt = 0; idt < kNDetectors; idt++) { AlignableDetector* det = getDetectorByDetID(idt); - if (!det || det->isDisabled()) + if (!det || det->isDisabled()) { continue; + } det->writePedeInfo(parFl, opt); // } @@ -1682,8 +1753,9 @@ bool Controller::readParameters(const char* parfile, bool useErrors) return false; } memset(mGloParVal, 0, mNDOFs * sizeof(float)); - if (useErrors) + if (useErrors) { memset(mGloParErr, 0, mNDOFs * sizeof(float)); + } int cnt = 0; TString fline; fline.ReadLine(inpf); @@ -1699,24 +1771,27 @@ bool Controller::readParameters(const char* parfile, bool useErrors) while (fline.ReadLine(inpf)) { cnt++; fline = fline.Strip(TString::kBoth, ' '); - if (fline.BeginsWith("!") || fline.BeginsWith("*")) - continue; // ignore comment + if (fline.BeginsWith("!") || fline.BeginsWith("*")) { + continue; + } // ignore comment int nr = sscanf(fline.Data(), "%d%lf%lf%lf", &lab, &v0, &v1, &v2); if (nr < 3) { LOG(ERROR) << "Expected to read at least 3 numbers, got " << nr << ", this is NOT milleped output"; LOG(ERROR) << "line (" << cnt << ") was:\n " << fline.Data(); return false; } - if (nr == 3) + if (nr == 3) { asg0++; + } int parID = label2ParID(lab); if (parID < 0 || parID >= mNDOFs) { LOG(ERROR) << "Invalid label " << lab << " at line " << cnt << " -> ParID=" << parID; return false; } mGloParVal[parID] = -v0; - if (useErrors) + if (useErrors) { mGloParErr[parID] = v1; + } asg++; // }; @@ -1777,18 +1852,21 @@ void Controller::mPRec2Mille(TTree* mprTree, const char* millefile, bool bindata br->SetAddress(&rec); int nent = mprTree->GetEntries(); TString mlname = millefile; - if (mlname.IsNull()) + if (mlname.IsNull()) { mlname = "mpRec2mpData"; - if (!mlname.EndsWith(sMPDataExt)) + } + if (!mlname.EndsWith(sMPDataExt)) { mlname += sMPDataExt; + } Mille* mille = new Mille(mlname, bindata); TArrayF buffDLoc; for (int i = 0; i < nent; i++) { br->GetEntry(i); int nr = rec->getNResid(); // number of residual records int nloc = rec->getNVarLoc(); - if (buffDLoc.GetSize() < nloc) + if (buffDLoc.GetSize() < nloc) { buffDLoc.Set(nloc + 100); + } float* buffLocV = buffDLoc.GetArray(); const float* recDGlo = rec->getArrGlo(); const float* recDLoc = rec->getArrLoc(); @@ -1800,8 +1878,9 @@ void Controller::mPRec2Mille(TTree* mprTree, const char* millefile, bool bindata int ndglo = rec->getNDGlo(ir); int ndloc = rec->getNDLoc(ir); // fill 0-suppressed array from MPRecord to non-0-suppressed array of Mille - for (int l = ndloc; l--;) + for (int l = ndloc; l--;) { buffLocV[recLabLoc[l]] = recDLoc[l]; + } // mille->mille(nloc, buffLocV, ndglo, recDGlo, recLabGlo, rec->getResid(ir), rec->getResErr(ir)); // @@ -1813,15 +1892,16 @@ void Controller::mPRec2Mille(TTree* mprTree, const char* millefile, bool bindata mille->end(); } delete mille; - br->SetAddress(0); + br->SetAddress(nullptr); delete rec; } //____________________________________________________________ void Controller::fillStatHisto(int type, float w) { - if (!mHistoStat) + if (!mHistoStat) { createStatHisto(); + } mHistoStat->Fill((isCosmic() ? kNHVars : 0) + type, w); } @@ -1829,7 +1909,7 @@ void Controller::fillStatHisto(int type, float w) void Controller::createStatHisto() { mHistoStat = new TH1F("stat", "stat", 2 * kNHVars, -0.5, 2 * kNHVars - 0.5); - mHistoStat->SetDirectory(0); + mHistoStat->SetDirectory(nullptr); TAxis* xax = mHistoStat->GetXaxis(); for (int j = 0; j < 2; j++) { for (int i = 0; i < kNHVars; i++) { @@ -1842,8 +1922,9 @@ void Controller::createStatHisto() void Controller::printLabels() const { // print global IDs and Labels - for (int i = 0; i < mNDOFs; i++) + for (int i = 0; i < mNDOFs; i++) { printf("%5d %s\n", i, getDOFLabelTxt(i)); + } } //____________________________________________________________ @@ -1851,8 +1932,9 @@ int Controller::label2ParID(int lab) const { // convert Mille label to ParID (slow) int ind = findKeyIndex(lab, mOrderedLbl, mNDOFs); - if (ind < 0) + if (ind < 0) { return -1; + } return mLbl2ID[ind]; } @@ -1862,8 +1944,9 @@ void Controller::addAutoConstraints() // add default constraints on children cumulative corrections within the volumes for (int idet = 0; idet < mNDet; idet++) { AlignableDetector* det = getDetector(idet); - if (det->isDisabled()) + if (det->isDisabled()) { continue; + } det->addAutoConstraints(); } LOG(INFO) << "Added " << getNConstraints() << " automatic constraints"; @@ -1876,8 +1959,9 @@ void Controller::writePedeConstraints() const FILE* conFl = fopen(mMPConFileName.Data(), "w+"); // int nconstr = getNConstraints(); - for (int icon = 0; icon < nconstr; icon++) + for (int icon = 0; icon < nconstr; icon++) { getConstraint(icon)->writeChildrenConstraints(conFl); + } // fclose(conFl); } @@ -1896,8 +1980,9 @@ void Controller::fixLowStatFromDOFStat(int thresh) return; } for (int parID = 0; parID < mNDOFs; parID++) { - if (mDOFStat->getStat(parID) >= thresh) + if (mDOFStat->getStat(parID) >= thresh) { continue; + } mGloParErr[parID] = -999.; } // @@ -1909,29 +1994,33 @@ void Controller::loadStat(const char* flname) // load statistics histos from external file produced by alignment task TFile* fl = TFile::Open(flname); // - TObject *hdfO = 0, *hstO = 0; + TObject *hdfO = nullptr, *hstO = nullptr; TList* lst = (TList*)fl->Get("clist"); if (lst) { hdfO = lst->FindObject("DOFstat"); - if (hdfO) + if (hdfO) { lst->Remove(hdfO); + } hstO = lst->FindObject("stat"); - if (hstO) + if (hstO) { lst->Remove(hstO); + } delete lst; } else { hdfO = fl->Get("DOFstat"); hstO = fl->Get("stat"); } - TH1F* hst = 0; - if (hstO && (hst = dynamic_cast(hstO))) - hst->SetDirectory(0); - else + TH1F* hst = nullptr; + if (hstO && (hst = dynamic_cast(hstO))) { + hst->SetDirectory(nullptr); + } else { LOG(WARNING) << "did not find stat histo"; + } // - DOFStatistics* dofSt = 0; - if (!hdfO || !(dofSt = dynamic_cast(hdfO))) + DOFStatistics* dofSt = nullptr; + if (!hdfO || !(dofSt = dynamic_cast(hdfO))) { LOG(WARNING) << "did not find DOFstat object"; + } // setHistoStat(hst); setDOFStat(dofSt); @@ -1945,16 +2034,18 @@ void Controller::checkSol(TTree* mpRecTree, bool store, bool verbose, bool loc, const char* outName) { // do fast check of pede solution with MPRecord tree - ResidualsControllerFast* rLG = store ? new ResidualsControllerFast() : 0; - ResidualsControllerFast* rL = store && loc ? new ResidualsControllerFast() : 0; - TTree *trLG = 0, *trL = 0; - TFile* outFile = 0; + ResidualsControllerFast* rLG = store ? new ResidualsControllerFast() : nullptr; + ResidualsControllerFast* rL = store && loc ? new ResidualsControllerFast() : nullptr; + TTree *trLG = nullptr, *trL = nullptr; + TFile* outFile = nullptr; if (store) { TString outNS = outName; - if (outNS.IsNull()) + if (outNS.IsNull()) { outNS = "resFast"; - if (!outNS.EndsWith(".root")) + } + if (!outNS.EndsWith(".root")) { outNS += ".root"; + } outFile = TFile::Open(outNS.Data(), "recreate"); trLG = new TTree("resFLG", "Fast residuals with LG correction"); trLG->Branch("rLG", "ResidualsControllerFast", &rLG); @@ -1972,10 +2063,12 @@ void Controller::checkSol(TTree* mpRecTree, bool store, mpRecTree->GetEntry(irec); checkSol(rec, rLG, rL, verbose, loc); // store even in case of failure, to have the trees aligned with controlRes - if (trLG) + if (trLG) { trLG->Fill(); - if (trL) + } + if (trL) { trL->Fill(); + } } // // save @@ -2004,8 +2097,8 @@ bool Controller::checkSol(Millepede2Record* rec, // // If loc==true, also produces residuals for current geometry, // // neglecting global corrections // // - // if (rL) - // loc = true; // if local sol. tree asked, always evaluate it + // if (rL){ + // loc = true;} // if local sol. tree asked, always evaluate it // // // int nres = rec->getNResid(); // // @@ -2020,8 +2113,8 @@ bool Controller::checkSol(Millepede2Record* rec, // int nMatCorr = 0; // for (int irs = 0; irs < nres; irs++) { // if (rec->getNDGlo(irs) > 0) { - // if (irs == nres - 1 || rec->getNDGlo(irs + 1) == 0) - // LOG(FATAL) << ("Real coordinate measurements must come in pairs"); + // if (irs == nres - 1 || rec->getNDGlo(irs + 1) == 0){ + // LOG(FATAL) << ("Real coordinate measurements must come in pairs");} // nPoints++; // irs++; // skip 2nd // continue; @@ -2034,8 +2127,8 @@ bool Controller::checkSol(Millepede2Record* rec, // } // } // // - // if (nMatCorr % 4) - // LOG(WARNING) << "Error? NMatCorr=" << nMatCorr << " is not multiple of 4"; + // if (nMatCorr % 4){ + // LOG(WARNING) << "Error? NMatCorr=" << nMatCorr << " is not multiple of 4";} // // // if (rLG) { // rLG->Clear(); @@ -2053,8 +2146,8 @@ bool Controller::checkSol(Millepede2Record* rec, // AliSymMatrix* matpG = new AliSymMatrix(nvloc); // TVectorD *vecp = 0, *vecpG = new TVectorD(nvloc); // // - // if (loc) - // vecp = new TVectorD(nvloc); + // if (loc){ + // vecp = new TVectorD(nvloc);} // // // float chi2Ini = 0, chi2L = 0, chi2LG = 0; // // @@ -2071,15 +2164,15 @@ bool Controller::checkSol(Millepede2Record* rec, // for (int ig = 0; ig < ndglo; ig++) { // int lbI = recLabGlo[ig]; // int idP = label2ParID(lbI); - // if (idP < 0) - // LOG(FATAL) << "Did not find parameted for label " << lbI; + // if (idP < 0){ + // LOG(FATAL) << "Did not find parameted for label " << lbI;} // double parVal = getGloParVal()[idP]; // // resid[irs] -= parVal*recDGlo[ig]; // resid[irs] += parVal * recDGlo[ig]; // if (!ig) { // AlignableVolume* vol = getVolOfDOFID(idP); - // if (vol) - // volID[irs] = vol->getVolID(); + // if (vol){ + // volID[irs] = vol->getVolID();} // else // volID[irs] = -2; // calibration DOF !!! TODO // } @@ -2094,8 +2187,8 @@ bool Controller::checkSol(Millepede2Record* rec, // for (int il = 0; il < ndloc; il++) { // int lbLI = recLabLoc[il]; // id of local variable // (*vecpG)[lbLI] -= recDLoc[il] * resid[irs] * sg2inv; - // if (loc) - // (*vecp)[lbLI] -= recDLoc[il] * resOr * sg2inv; + // if (loc){ + // (*vecp)[lbLI] -= recDLoc[il] * resOr * sg2inv;} // for (int jl = il + 1; jl--;) { // int lbLJ = recLabLoc[jl]; // id of local variable // (*matpG)(lbLI, lbLJ) += recDLoc[il] * recDLoc[jl] * sg2inv; @@ -2109,10 +2202,10 @@ bool Controller::checkSol(Millepede2Record* rec, // // // } // // - // if (rL) - // rL->setChi2Ini(chi2Ini); - // if (rLG) - // rLG->setChi2Ini(chi2Ini); + // if (rL){ + // rL->setChi2Ini(chi2Ini);} + // if (rLG){ + // rLG->setChi2Ini(chi2Ini);} // // // TVectorD vecSol(nvloc); // TVectorD vecSolG(nvloc); @@ -2133,10 +2226,10 @@ bool Controller::checkSol(Millepede2Record* rec, // if (!matpG) { // failed // delete[] resid; // delete[] volID; - // if (rLG) - // rLG->Clear(); - // if (rL) - // rL->Clear(); + // if (rLG){ + // rLG->Clear();} + // if (rL){ + // rL->Clear();} // return false; // } // // check @@ -2148,8 +2241,8 @@ bool Controller::checkSol(Millepede2Record* rec, // if (verbose) { // printf(loc ? "Sol L/LG:\n" : "Sol LG:\n"); // int nExtP = (nvloc % 4) ? 5 : 4; - // for (int i = 0; i < nExtP; i++) - // loc ? printf("%+.3e/%+.3e ", vecSol[i], vecSolG[i]) : printf("%+.3e ", vecSolG[i]); + // for (int i = 0; i < nExtP; i++){ + // loc ? printf("%+.3e/%+.3e ", vecSol[i], vecSolG[i]) : printf("%+.3e ", vecSolG[i]);} // printf("\n"); // bool nln = true; // int cntL = 0; @@ -2161,14 +2254,14 @@ bool Controller::checkSol(Millepede2Record* rec, // nln = false; // } // } - // if (!nln) - // printf("\n"); - // if (loc) + // if (!nln){ + // printf("\n");} + // if (loc){ // printf("%3s (%9s) %6s | [ %7s:%7s ] [ %7s:%7s ]\n", "Pnt", "Label", - // "Sigma", "resid", "pull/L ", "resid", "pull/LG"); - // else + // "Sigma", "resid", "pull/L ", "resid", "pull/LG");} + // else{ // printf("%3s (%9s) %6s | [ %7s:%7s ]\n", "Pnt", "Label", - // "Sigma", "resid", "pull/LG"); + // "Sigma", "resid", "pull/LG");} // } // int idMeas = -1, pntID = -1, matID = -1; // for (int irs = 0; irs < nres; irs++) { @@ -2192,37 +2285,37 @@ bool Controller::checkSol(Millepede2Record* rec, // // // if (ndglo || resOr != 0) { // real measurement // idMeas++; - // if (idMeas > 1) - // idMeas = 0; - // if (idMeas == 0) - // pntID++; // measurements come in pairs + // if (idMeas > 1){ + // idMeas = 0;} + // if (idMeas == 0){ + // pntID++;} // measurements come in pairs // int lbl = rec->getVolID(irs); // lbl = ndglo ? recLabGlo[0] : 0; // TMP, until VolID is filled // RS!!!! // if (rLG) { // rLG->setResSigMeas(pntID, idMeas, resLG, sg); - // if (idMeas == 0) - // rLG->setLabel(pntID, lbl, volID[irs]); + // if (idMeas == 0){ + // rLG->setLabel(pntID, lbl, volID[irs]);} // } // if (rL) { // rL->setResSigMeas(pntID, idMeas, resL, sg); - // if (idMeas == 0) - // rL->setLabel(pntID, lbl, volID[irs]); + // if (idMeas == 0){ + // rL->setLabel(pntID, lbl, volID[irs]);} // } // } else { // matID++; // mat.correcitons come in 4-plets, but we fill each separately // // - // if (rLG) - // rLG->setMatCorr(matID, resLG, sg); - // if (rL) - // rL->setMatCorr(matID, resL, sg); + // if (rLG){ + // rLG->setMatCorr(matID, resLG, sg);} + // if (rL){ + // rL->setMatCorr(matID, resL, sg);} // } // // // if (verbose) { // int lbl = rec->getVolID(irs); // lbl = ndglo ? recLabGlo[0] : (resOr == 0 ? -1 : 0); // TMP, until VolID is filled // RS!!!! - // if (loc) + // if (loc){ // printf("%3d (%9d) %6.4f | [%+.2e:%+7.2f] [%+.2e:%+7.2f]\n", - // irs, lbl, sg, resL, resL / sg, resLG, resLG / sg); + // irs, lbl, sg, resL, resL / sg, resLG, resLG / sg);} // else // printf("%3d (%9d) %6.4f | [%+.2e:%+7.2f]\n", // irs, lbl, sg, resLG, resLG / sg); @@ -2233,24 +2326,24 @@ bool Controller::checkSol(Millepede2Record* rec, // recLabLoc += ndloc; // recDLoc += ndloc; // } - // if (rL) - // rL->setChi2(chi2L); - // if (rLG) - // rLG->setChi2(chi2LG); + // if (rL){ + // rL->setChi2(chi2L);} + // if (rLG){ + // rLG->setChi2(chi2LG);} // // // if (verbose) { // printf("Chi: G = %e | LG = %e", chi2Ini, chi2LG); - // if (loc) - // printf(" | L = %e", chi2L); + // if (loc){ + // printf(" | L = %e", chi2L);} // printf("\n"); // } // // store track corrections // int nTrCor = nvloc - matID - 1; // for (int i = 0; i < nTrCor; i++) { - // if (rLG) - // rLG->getTrCor()[i] = vecSolG[i]; - // if (rL) - // rL->getTrCor()[i] = vecSol[i]; + // if (rLG){ + // rLG->getTrCor()[i] = vecSolG[i];} + // if (rL){ + // rL->getTrCor()[i] = vecSol[i];} // } // // // delete[] resid; @@ -2265,8 +2358,9 @@ void Controller::applyAlignmentFromMPSol() LOG(INFO) << "Applying alignment from Millepede solution"; for (int idt = 0; idt < kNDetectors; idt++) { AlignableDetector* det = getDetectorByDetID(idt); - if (!det || det->isDisabled()) + if (!det || det->isDisabled()) { continue; + } det->applyAlignmentFromMPSol(); } setMPAlignDone(); diff --git a/Detectors/Align/src/GeometricalConstraint.cxx b/Detectors/Align/src/GeometricalConstraint.cxx index 9aa5891a5391f..ff776a9263c84 100644 --- a/Detectors/Align/src/GeometricalConstraint.cxx +++ b/Detectors/Align/src/GeometricalConstraint.cxx @@ -19,7 +19,7 @@ #include "Framework/Logger.h" #include #include -#include +#include ClassImp(o2::align::GeometricalConstraint); @@ -33,11 +33,12 @@ namespace align //___________________________________________________________________ GeometricalConstraint::GeometricalConstraint(const char* name, const char* title) - : TNamed(name, title), mConstraint(0), mParent(0), mChildren(2) + : TNamed(name, title), mConstraint(0), mParent(nullptr), mChildren(2) { // def. c-tor - for (int i = kNDOFGeom; i--;) + for (int i = kNDOFGeom; i--;) { mSigma[i] = 0; + } } //___________________________________________________________________ @@ -53,10 +54,11 @@ void GeometricalConstraint::setParent(const AlignableVolume* par) mParent = par; TString nm = GetName(); if (nm.IsNull()) { - if (par) + if (par) { SetNameTitle(par->getSymName(), "Automatic"); - else + } else { SetNameTitle("GLOBAL", "Automatic"); + } } } @@ -85,10 +87,12 @@ void GeometricalConstraint::writeChildrenConstraints(FILE* conOut) const // in case of parent assigned use its matrix, // otherwise Alice global frame is assumed to be the parent -> Unit matrix if (mParent && doJac) { - if (mParent->isFrameTRA()) - mParent->getMatrixT2G(mPar); // tracking to global - else - mPar = mParent->getMatrixL2GIdeal(); // local to global + if (mParent->isFrameTRA()) { + mParent->getMatrixT2G(mPar); + } // tracking to global + else { + mPar = mParent->getMatrixL2GIdeal(); + } // local to global mPar = mPar.Inverse(); } // @@ -99,25 +103,29 @@ void GeometricalConstraint::writeChildrenConstraints(FILE* conOut) const // if (doJac) { // calculate jacobian TGeoHMatrix matRel; - if (child->isFrameTRA()) - child->getMatrixT2G(matRel); // tracking to global - else - matRel = child->getMatrixL2GIdeal(); // local to global + if (child->isFrameTRA()) { + child->getMatrixT2G(matRel); + } // tracking to global + else { + matRel = child->getMatrixL2GIdeal(); + } // local to global matRel.MultiplyLeft(&mPar); constrCoefGeom(matRel, jac); // for (int ics = 0; ics < kNDOFGeom; ics++) { // DOF of parent to be constrained for (int ip = 0; ip < kNDOFGeom; ip++) { // count contributing DOFs float jv = jac[ics * kNDOFGeom + ip]; - if (!isZeroAbs(jv) && child->isFreeDOF(ip) && child->getParErr(ip) >= 0) + if (!isZeroAbs(jv) && child->isFreeDOF(ip) && child->getParErr(ip) >= 0) { nContCh[ip]++; + } } } } else { // simple constraint on the sum of requested DOF // for (int ip = 0; ip < kNDOFGeom; ip++) { - if (child->isFreeDOF(ip) && child->getParErr(ip) >= 0) + if (child->isFreeDOF(ip) && child->getParErr(ip) >= 0) { nContCh[ip]++; + } jac[ip * kNDOFGeom + ip] = 1.; } } @@ -125,8 +133,9 @@ void GeometricalConstraint::writeChildrenConstraints(FILE* conOut) const } // for (int ics = 0; ics < kNDOFGeom; ics++) { - if (!isDOFConstrained(ics)) + if (!isDOFConstrained(ics)) { continue; + } int cmtStatus = nContCh[ics] > 0 ? kOff : kOn; // do we comment this constraint? // if (cmtStatus) { @@ -142,21 +151,24 @@ void GeometricalConstraint::writeChildrenConstraints(FILE* conOut) const for (int ich = 0; ich < nch; ich++) { // contribution from this children DOFs to constraint AlignableVolume* child = getChild(ich); jac = cstrArr + kNDOFGeom * kNDOFGeom * ich; - if (cmtStatus) - fprintf(conOut, "%s", comment[cmtStatus]); // comment out contribution + if (cmtStatus) { + fprintf(conOut, "%s", comment[cmtStatus]); + } // comment out contribution // first write real constraints for (int ip = 0; ip < kNDOFGeom; ip++) { float jv = jac[ics * kNDOFGeom + ip]; - if (child->isFreeDOF(ip) && !isZeroAbs(jv) && child->getParErr(ip) >= 0) + if (child->isFreeDOF(ip) && !isZeroAbs(jv) && child->getParErr(ip) >= 0) { fprintf(conOut, "%9d %+.3e\t", child->getParLab(ip), jv); + } } // loop over DOF's of children contributing to this constraint // now, after comment, write disabled constraints fprintf(conOut, "%s ", comment[kOn]); if (doJac) { for (int ip = 0; ip < kNDOFGeom; ip++) { float jv = jac[ics * kNDOFGeom + ip]; - if (child->isFreeDOF(ip) && !isZeroAbs(jv) && child->getParErr(ip) >= 0) + if (child->isFreeDOF(ip) && !isZeroAbs(jv) && child->getParErr(ip) >= 0) { continue; + } fprintf(conOut, "%9d %+.3e\t", child->getParLab(ip), jv); } // loop over DOF's of children contributing to this constraint } @@ -172,8 +184,9 @@ void GeometricalConstraint::checkConstraint() const { // check how the constraints are satysfied int nch = getNChildren(); - if (!nch) + if (!nch) { return; + } // bool doJac = !getNoJacobian(); // do we need jacobian evaluation? float* cstrArr = new float[nch * kNDOFGeom * kNDOFGeom]; @@ -185,10 +198,12 @@ void GeometricalConstraint::checkConstraint() const // in case of parent assigned use its matrix, // otherwise Alice global frame is assumed to be the parent -> Unit matrix if (mParent && doJac) { - if (mParent->isFrameTRA()) - mParent->getMatrixT2G(mPar); // tracking to global - else - mPar = mParent->getMatrixL2GIdeal(); // local to global + if (mParent->isFrameTRA()) { + mParent->getMatrixT2G(mPar); + } // tracking to global + else { + mPar = mParent->getMatrixL2GIdeal(); + } // local to global mPar = mPar.Inverse(); } // @@ -198,25 +213,30 @@ void GeometricalConstraint::checkConstraint() const // printf("\n\n ----- Constraints Validation for %s %s ------\n", GetName(), GetTitle()); printf(" chld| "); - for (int jp = 0; jp < kNDOFGeom; jp++) + for (int jp = 0; jp < kNDOFGeom; jp++) { printf(" %3s:%3s An/Ex |", getDOFName(jp), isDOFConstrained(jp) ? "ON " : "OFF"); + } printf(" | "); - for (int jp = 0; jp < kNDOFGeom; jp++) + for (int jp = 0; jp < kNDOFGeom; jp++) { printf(" D%3s ", getDOFName(jp)); + } printf(" ! %s\n", GetName()); for (int ich = 0; ich < nch; ich++) { AlignableVolume* child = getChild(ich); double parsC[kNDOFGeom] = {0}, parsPAn[kNDOFGeom] = {0}, parsPEx[kNDOFGeom] = {0}; - for (int jc = kNDOFGeom; jc--;) - parsC[jc] = child->getParVal(jc); // child params in child frame + for (int jc = kNDOFGeom; jc--;) { + parsC[jc] = child->getParVal(jc); + } // child params in child frame printf("#%3d | ", ich); // if (doJac) { TGeoHMatrix matRel; - if (child->isFrameTRA()) - child->getMatrixT2G(matRel); // tracking to global - else - matRel = child->getMatrixL2GIdeal(); // local to global + if (child->isFrameTRA()) { + child->getMatrixT2G(matRel); + } // tracking to global + else { + matRel = child->getMatrixL2GIdeal(); + } // local to global // matRel.MultiplyLeft(&mPar); constrCoefGeom(matRel, jac); // Jacobian for analytical constraint used by MillePeded @@ -244,8 +264,9 @@ void GeometricalConstraint::checkConstraint() const // // analytically calculated child params in parent frame for (int jp = 0; jp < kNDOFGeom; jp++) { - for (int jc = 0; jc < kNDOFGeom; jc++) + for (int jc = 0; jc < kNDOFGeom; jc++) { parsPAn[jp] += jac[jp * kNDOFGeom + jc] * parsC[jc]; + } parsTotAn[jp] += parsPAn[jp]; // analyticaly calculated total modification parsTotEx[jp] += parsPEx[jp]; // explicitly calculated total modification // @@ -260,41 +281,48 @@ void GeometricalConstraint::checkConstraint() const if (acc) { printf(" %+.3e ", parsC[jc]); parsTotAn[jc] += parsC[jc]; - } else - printf(" /* %+.3e */ ", parsC[jc]); // just for info, not in the constraint + } else { + printf(" /* %+.3e */ ", parsC[jc]); + } // just for info, not in the constraint } } printf(" | "); - for (int jc = 0; jc < kNDOFGeom; jc++) - printf("%+.1e ", parsC[jc]); // child proper corrections + for (int jc = 0; jc < kNDOFGeom; jc++) { + printf("%+.1e ", parsC[jc]); + } // child proper corrections printf(" ! %s\n", child->getSymName()); } // printf(" Tot | "); for (int jp = 0; jp < kNDOFGeom; jp++) { - if (doJac) + if (doJac) { printf("%+.1e/%+.1e ", parsTotAn[jp], parsTotEx[jp]); - else { - if (isDOFConstrained(jp)) + } else { + if (isDOFConstrained(jp)) { printf(" %+.3e ", parsTotAn[jp]); - else + } else { printf(" /* %+.3e */ ", parsTotAn[jp]); + } } } printf(" | "); - if (mParent) - for (int jp = 0; jp < kNDOFGeom; jp++) - printf("%+.1e ", mParent->getParVal(jp)); // parent proper corrections - else + if (mParent) { + for (int jp = 0; jp < kNDOFGeom; jp++) { + printf("%+.1e ", mParent->getParVal(jp)); + } + } // parent proper corrections + else { printf(" no parent -> %s ", doJac ? "Global" : "Simple"); + } printf(" ! <----- %s\n", GetName()); // printf(" Sig | "); for (int jp = 0; jp < kNDOFGeom; jp++) { - if (isDOFConstrained(jp)) + if (isDOFConstrained(jp)) { printf(" %+.3e ", mSigma[jp]); - else + } else { printf(" /* %+.3e */ ", mSigma[jp]); + } } printf(" ! <----- \n"); @@ -378,12 +406,15 @@ void GeometricalConstraint::Print(const Option_t*) const { // print info printf("Constraint on "); - for (int i = 0; i < kNDOFGeom; i++) - if (isDOFConstrained(i)) + for (int i = 0; i < kNDOFGeom; i++) { + if (isDOFConstrained(i)) { printf("%3s (Sig:%+e) ", getDOFName(i), getSigma(i)); + } + } printf(" | %s %s\n", GetName(), GetTitle()); - if (getNoJacobian()) + if (getNoJacobian()) { printf("!!! This is explicit constraint on sum of DOFs (no Jacobian)!!!\n"); + } for (int i = 0; i < getNChildren(); i++) { const AlignableVolume* child = getChild(i); printf("%3d %s\n", i, child->GetName()); diff --git a/Detectors/Align/src/Mille.cxx b/Detectors/Align/src/Mille.cxx index b34d9b48590ef..c507bbd27a722 100644 --- a/Detectors/Align/src/Mille.cxx +++ b/Detectors/Align/src/Mille.cxx @@ -77,12 +77,15 @@ void Mille::mille(int NLC, const float* derLc, int NGL, const float* derGl, const int* label, float rMeas, float sigma) { - if (sigma <= 0.) + if (sigma <= 0.) { return; - if (myBufferPos == -1) - this->newSet(); // start, e.g. new track - if (!this->checkBufferSize(NLC, NGL)) + } + if (myBufferPos == -1) { + this->newSet(); + } // start, e.g. new track + if (!this->checkBufferSize(NLC, NGL)) { return; + } // first store measurement ++myBufferPos; @@ -129,17 +132,20 @@ void Mille::mille(int NLC, const float* derLc, */ void Mille::special(int nSpecial, const float* floatings, const int* integers) { - if (nSpecial == 0) + if (nSpecial == 0) { return; - if (myBufferPos == -1) - this->newSet(); // start, e.g. new track + } + if (myBufferPos == -1) { + this->newSet(); + } // start, e.g. new track if (myHasSpecial) { std::cerr << "Mille::special: Special values already stored for this record." << std::endl; return; } - if (!this->checkBufferSize(nSpecial, 0)) + if (!this->checkBufferSize(nSpecial, 0)) { return; + } myHasSpecial = true; // after newSet() (Note: MILLSP sets to buffer position...) // myBufferFloat[.] | myBufferInt[.] diff --git a/Detectors/Align/src/Millepede2Record.cxx b/Detectors/Align/src/Millepede2Record.cxx index eba710ccdd66e..bd7686779f3ae 100644 --- a/Detectors/Align/src/Millepede2Record.cxx +++ b/Detectors/Align/src/Millepede2Record.cxx @@ -18,7 +18,7 @@ #include "Align/AlignmentTrack.h" #include "Framework/Logger.h" #include -#include +#include using namespace TMath; using namespace o2::align::utils; @@ -30,7 +30,7 @@ namespace align //_________________________________________________________ Millepede2Record::Millepede2Record() - : mTrackID(0), mTimeStamp(0), mNResid(0), mNVarLoc(0), mNVarGlo(0), mNDLocTot(0), mNDGloTot(0), mNMeas(0), mChi2Ini(0), mQ2Pt(0), mTgl(0), mNDLoc(0), mNDGlo(0), mVolID(0), mResid(0), mResErr(0), mIDLoc(0), mIDGlo(0), mDLoc(0), mDGlo(0) + : mTrackID(0), mTimeStamp(0), mNResid(0), mNVarLoc(0), mNVarGlo(0), mNDLocTot(0), mNDGloTot(0), mNMeas(0), mChi2Ini(0), mQ2Pt(0), mTgl(0), mNDLoc(nullptr), mNDGlo(nullptr), mVolID(nullptr), mResid(nullptr), mResErr(nullptr), mIDLoc(nullptr), mIDGlo(nullptr), mDLoc(nullptr), mDGlo(nullptr) // , mNResidBook(0), @@ -59,8 +59,9 @@ Millepede2Record::~Millepede2Record() void Millepede2Record::dummyRecord(float res, float err, float dGlo, int labGlo) { // create dummy residuals record - if (!mNDGlo) + if (!mNDGlo) { resize(1, 1, 1); + } mChi2Ini = 0; mNMeas = 1; mNResid = 1; @@ -129,8 +130,9 @@ bool Millepede2Record::fillTrack(const AlignmentTrack* trc, const int* id2Lab) if (pnt->containsMeasurement()) { int gloOffs = pnt->getDGloOffs(); // 1st entry of global derivatives for this point int nDGlo = pnt->getNGloDOFs(); // number of global derivatives (number of DOFs it depends on) - if (!pnt->isStatOK()) + if (!pnt->isStatOK()) { pnt->incrementStat(); + } // for (int idim = 0; idim < 2; idim++) { // 2 dimensional orthogonal measurement mNDGlo[mNResid] = 0; @@ -144,8 +146,9 @@ bool Millepede2Record::fillTrack(const AlignmentTrack* trc, const int* id2Lab) const double* deriv = trc->getDResDLoc(idim, ip); // array of Dresidual/Dparams_loc int nnon0 = 0; for (int j = 0; j < nParETP; j++) { // derivatives over reference track parameters - if (isZeroAbs(deriv[j])) + if (isZeroAbs(deriv[j])) { continue; + } nnon0++; mDLoc[mNDLocTot] = deriv[j]; // store non-0 derivative mIDLoc[mNDLocTot] = j; // and variable id @@ -154,8 +157,9 @@ bool Millepede2Record::fillTrack(const AlignmentTrack* trc, const int* id2Lab) int lp0 = pnt->getMinLocVarID(); // point may depend on material variables starting from this one int lp1 = pnt->getMaxLocVarID(); // and up to this one (exclusive) for (int j = lp0; j < lp1; j++) { // derivatives over material variables - if (isZeroAbs(deriv[j])) + if (isZeroAbs(deriv[j])) { continue; + } nnon0++; mDLoc[mNDLocTot] = deriv[j]; // store non-0 derivative mIDLoc[mNDLocTot] = j; // and variable id @@ -169,8 +173,9 @@ bool Millepede2Record::fillTrack(const AlignmentTrack* trc, const int* id2Lab) deriv = trc->getDResDGlo(idim, gloOffs); const int* gloIDP = gloParID + gloOffs; for (int j = 0; j < nDGlo; j++) { - if (isZeroAbs(deriv[j])) + if (isZeroAbs(deriv[j])) { continue; + } nnon0++; mDGlo[mNDGloTot] = deriv[j]; // value of derivative mIDGlo[mNDGloTot] = id2Lab ? id2Lab[gloIDP[j]] : gloIDP[j] + 1; // global DOF ID @@ -290,11 +295,13 @@ void Millepede2Record::Print(const Option_t*) const if (((id + 1) % kNColLoc) == 0) { printf("\n"); eolOK = true; - } else + } else { eolOK = false; + } } - if (!eolOK) + if (!eolOK) { printf("\n"); + } curLoc += ndloc; // // diff --git a/Detectors/Align/src/ResidualsController.cxx b/Detectors/Align/src/ResidualsController.cxx index c7bf07fac7704..0b9a7df18ab95 100644 --- a/Detectors/Align/src/ResidualsController.cxx +++ b/Detectors/Align/src/ResidualsController.cxx @@ -20,7 +20,7 @@ #include "Framework/Logger.h" #include #include -#include +#include using namespace TMath; @@ -33,7 +33,7 @@ namespace align //____________________________________ ResidualsController::ResidualsController() - : mRun(0), mBz(0), mTimeStamp(0), mTrackID(0), mNPoints(0), mNBook(0), mChi2(0), mChi2Ini(0), mChi2K(0), mQ2Pt(0), mX(0), mY(0), mZ(0), mSnp(0), mTgl(0), mAlpha(0), mDY(0), mDZ(0), mDYK(0), mDZK(0), mSigY2(0), mSigYZ(0), mSigZ2(0), mSigY2K(0), mSigYZK(0), mSigZ2K(0), mVolID(0), mLabel(0) + : mRun(0), mBz(0), mTimeStamp(0), mTrackID(0), mNPoints(0), mNBook(0), mChi2(0), mChi2Ini(0), mChi2K(0), mQ2Pt(0), mX(nullptr), mY(nullptr), mZ(nullptr), mSnp(nullptr), mTgl(nullptr), mAlpha(nullptr), mDY(nullptr), mDZ(nullptr), mDYK(nullptr), mDZK(nullptr), mSigY2(nullptr), mSigYZ(nullptr), mSigZ2(nullptr), mSigY2K(nullptr), mSigYZK(nullptr), mSigZ2K(nullptr), mVolID(nullptr), mLabel(nullptr) { // def c-tor } @@ -152,22 +152,25 @@ void ResidualsController::Print(const Option_t* opt) const opts.ToLower(); bool lab = opts.Contains("l"); printf("%5sTr.", isCosmic() ? "Cosm." : "Coll."); - if (isCosmic()) + if (isCosmic()) { printf("%2d/%2d ", mTrackID >> 16, mTrackID & 0xffff); - else + } else { printf("%5d ", mTrackID); + } printf("Run:%6d Bz:%+4.1f Np: %3d q/Pt:%+.4f | Chi2: Ini: %6.1f LinSol:%6.1f Kalm:%6.1f |Vtx:%3s| TStamp:%d\n", mRun, mBz, mNPoints, mQ2Pt, mChi2Ini, mChi2, mChi2K, hasVertex() ? "ON" : "OFF", mTimeStamp); if (opts.Contains("r")) { bool ers = opts.Contains("e"); printf("%5s %7s %s %7s %7s %7s %5s %5s %9s %9s", " VID ", " Label ", " Alp ", " X ", " Y ", " Z ", " Snp ", " Tgl ", " DY ", " DZ "); - if (ers) - printf(" %8s %8s %8s", " pSgYY ", " pSgYZ ", " pSgZZ "); // cluster errors + if (ers) { + printf(" %8s %8s %8s", " pSgYY ", " pSgYZ ", " pSgZZ "); + } // cluster errors if (getKalmanDone()) { printf(" %9s %9s", " DYK ", " DZK "); - if (ers) - printf(" %8s %8s %8s", " tSgYY ", " tSgYZ ", " tSgZZ "); // track errors + if (ers) { + printf(" %8s %8s %8s", " tSgYY ", " tSgYZ ", " tSgZZ "); + } // track errors } printf("\n"); for (int i = 0; i < mNPoints; i++) { @@ -179,12 +182,14 @@ void ResidualsController::Print(const Option_t* opt) const } printf("%5d %7d %+5.2f %+7.2f %+7.2f %+7.2f %+5.2f %+5.2f %+9.2e %+9.2e", mVolID[i], mLabel[i], mAlpha[i], x, y, z, mSnp[i], mTgl[i], mDY[i], mDZ[i]); - if (ers) + if (ers) { printf(" %.2e %+.1e %.2e", mSigY2[i], mSigYZ[i], mSigZ2[i]); + } if (getKalmanDone()) { printf(" %+9.2e %+9.2e", mDYK[i], mDZK[i]); - if (ers) + if (ers) { printf(" %.2e %+.1e %.2e", mSigY2K[i], mSigYZK[i], mSigZ2K[i]); + } } printf("\n"); } @@ -199,10 +204,12 @@ bool ResidualsController::fillTrack(AlignmentTrack* trc, bool doKalman) if (trc->getInnerPoint()->containsMeasurement()) { setHasVertex(); nps = np; - } else - nps = np - 1; // ref point is dummy? - if (nps < 0) + } else { + nps = np - 1; + } // ref point is dummy? + if (nps < 0) { return true; + } setCosmic(trc->isCosmic()); // setNPoints(nps); @@ -213,10 +220,12 @@ bool ResidualsController::fillTrack(AlignmentTrack* trc, bool doKalman) for (int i = 0; i < np; i++) { AlignmentPoint* pnt = trc->getPoint(i); int inv = pnt->isInvDir() ? -1 : 1; // Flag invertion for cosmic upper leg - if (!pnt->containsMeasurement()) + if (!pnt->containsMeasurement()) { continue; - if (!pnt->isStatOK()) + } + if (!pnt->isStatOK()) { pnt->incrementStat(); + } mVolID[nfill] = pnt->getVolID(); mLabel[nfill] = pnt->getSensor()->getInternalID(); mAlpha[nfill] = pnt->getAlphaSens(); @@ -244,8 +253,9 @@ bool ResidualsController::fillTrack(AlignmentTrack* trc, bool doKalman) if (doKalman && trc->residKalman()) { for (int i = 0; i < np; i++) { AlignmentPoint* pnt = trc->getPoint(i); - if (!pnt->containsMeasurement()) + if (!pnt->containsMeasurement()) { continue; + } if (mVolID[nfilk] != int(pnt->getVolID())) { LOG(FATAL) << "Mismatch in Kalman filling for point " << i << ": filled VID:" << mVolID[nfilk] << ", point VID:" << pnt->getVolID(); } diff --git a/Detectors/Align/src/ResidualsControllerFast.cxx b/Detectors/Align/src/ResidualsControllerFast.cxx index bc13d9e8bca34..3207e4b1d7cdf 100644 --- a/Detectors/Align/src/ResidualsControllerFast.cxx +++ b/Detectors/Align/src/ResidualsControllerFast.cxx @@ -20,7 +20,7 @@ #include "Framework/Logger.h" #include #include -#include +#include using namespace TMath; @@ -33,11 +33,12 @@ namespace align //____________________________________ ResidualsControllerFast::ResidualsControllerFast() - : mNPoints(0), mNMatSol(0), mNBook(0), mChi2(0), mChi2Ini(0), mD0(0), mD1(0), mSig0(0), mSig1(0), mVolID(0), mLabel(0), mSolMat(0), mMatErr(0) + : mNPoints(0), mNMatSol(0), mNBook(0), mChi2(0), mChi2Ini(0), mD0(nullptr), mD1(nullptr), mSig0(nullptr), mSig1(nullptr), mVolID(nullptr), mLabel(nullptr), mSolMat(nullptr), mMatErr(nullptr) { // def c-tor - for (int i = 5; i--;) + for (int i = 0; i < 5; ++i) { mTrCorr[i] = 0; + } } //________________________________________________ @@ -116,8 +117,9 @@ void ResidualsControllerFast::Print(const Option_t* /*opt*/) const } // printf("CorrETP: "); - for (int i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) { printf("%+.3f ", mTrCorr[i]); + } printf("\n"); printf("MatCorr (corr/sig:pull)\n"); int nmp = mNMatSol / 4; From 26ccdf55ad1e152b2fdc093d62e1b06578e0053d Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 21 Apr 2021 18:07:58 +0200 Subject: [PATCH 220/770] Move globaltracking::RecoContainer into a separate data formats library --- DataFormats/Detectors/CMakeLists.txt | 1 + .../Detectors/GlobalTracking/CMakeLists.txt | 22 +++++++++++++++++++ .../RecoContainer.h | 0 .../GlobalTracking/src/RecoContainer.cxx | 4 +--- DataFormats/Reconstruction/CMakeLists.txt | 6 ++--- Detectors/GlobalTracking/CMakeLists.txt | 4 ++-- Detectors/GlobalTracking/src/MatchCosmics.cxx | 2 +- .../src/CosmicsMatchingSpec.cxx | 2 +- .../src/PrimaryVertexingSpec.cxx | 3 +-- .../src/SecondaryVertexingSpec.cxx | 2 +- .../src/VertexTrackMatcherSpec.cxx | 2 +- .../include/DetectorsVertexing/SVertexer.h | 2 +- .../DetectorsVertexing/VertexTrackMatcher.h | 2 +- 13 files changed, 36 insertions(+), 16 deletions(-) create mode 100644 DataFormats/Detectors/GlobalTracking/CMakeLists.txt rename {Detectors/GlobalTracking/include/GlobalTracking => DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking}/RecoContainer.h (100%) rename {Detectors => DataFormats/Detectors}/GlobalTracking/src/RecoContainer.cxx (99%) diff --git a/DataFormats/Detectors/CMakeLists.txt b/DataFormats/Detectors/CMakeLists.txt index 37f11d409722f..fe92c670431d4 100644 --- a/DataFormats/Detectors/CMakeLists.txt +++ b/DataFormats/Detectors/CMakeLists.txt @@ -23,6 +23,7 @@ add_subdirectory(TRD) add_subdirectory(PHOS) add_subdirectory(CPV) add_subdirectory(CTP) +add_subdirectory(GlobalTracking) if(ENABLE_UPGRADES) add_subdirectory(Upgrades) else() diff --git a/DataFormats/Detectors/GlobalTracking/CMakeLists.txt b/DataFormats/Detectors/GlobalTracking/CMakeLists.txt new file mode 100644 index 0000000000000..eb98c4e67fc9a --- /dev/null +++ b/DataFormats/Detectors/GlobalTracking/CMakeLists.txt @@ -0,0 +1,22 @@ +# Copyright CERN and copyright holders of ALICE O2. This software is distributed +# under the terms of the GNU General Public License v3 (GPL Version 3), copied +# verbatim in the file "COPYING". +# +# See http://alice-o2.web.cern.ch/license for full licensing information. +# +# In applying this license CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization or +# submit itself to any jurisdiction. + +o2_add_library( + DataFormatsGlobalTracking + SOURCES src/RecoContainer.cxx + PUBLIC_LINK_LIBRARIES + O2::Framework + O2::DataFormatsTPC + O2::DataFormatsITSMFT + O2::DataFormatsITS + O2::DataFormatsFT0 + O2::DataFormatsTOF + O2::DataFormatsFT0 + O2::ReconstructionDataFormats) diff --git a/Detectors/GlobalTracking/include/GlobalTracking/RecoContainer.h b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h similarity index 100% rename from Detectors/GlobalTracking/include/GlobalTracking/RecoContainer.h rename to DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h diff --git a/Detectors/GlobalTracking/src/RecoContainer.cxx b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx similarity index 99% rename from Detectors/GlobalTracking/src/RecoContainer.cxx rename to DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx index e72c97ee2c4e5..6af87511199eb 100644 --- a/Detectors/GlobalTracking/src/RecoContainer.cxx +++ b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx @@ -15,7 +15,7 @@ #include #include #include "DetectorsCommonDataFormats/DetID.h" -#include "GlobalTracking/RecoContainer.h" +#include "DataFormatsGlobalTracking/RecoContainer.h" #include "DataFormatsITSMFT/CompCluster.h" #include "DataFormatsITS/TrackITS.h" #include "DataFormatsTPC/TrackTPC.h" @@ -25,8 +25,6 @@ #include "ReconstructionDataFormats/TrackTPCITS.h" #include "ReconstructionDataFormats/TrackTPCTOF.h" #include "ReconstructionDataFormats/MatchInfoTOF.h" -// RSTODO to remove once the framework will start propagating the header.firstTForbit -#include "DetectorsRaw/HBFUtils.h" using namespace o2::globaltracking; using namespace o2::framework; diff --git a/DataFormats/Reconstruction/CMakeLists.txt b/DataFormats/Reconstruction/CMakeLists.txt index 48bd2ad80a846..eb680835a89bc 100644 --- a/DataFormats/Reconstruction/CMakeLists.txt +++ b/DataFormats/Reconstruction/CMakeLists.txt @@ -26,7 +26,7 @@ o2_add_library(ReconstructionDataFormats src/VtxTrackIndex.cxx src/VtxTrackRef.cxx src/TrackTPCTOF.cxx - src/TrackCosmics.cxx + src/TrackCosmics.cxx PUBLIC_LINK_LIBRARIES O2::GPUCommon O2::FrameworkLogger O2::DetectorsCommonDataFormats @@ -50,8 +50,8 @@ o2_target_root_dictionary( include/ReconstructionDataFormats/VtxTrackIndex.h include/ReconstructionDataFormats/VtxTrackRef.h include/ReconstructionDataFormats/TrackTPCTOF.h - include/ReconstructionDataFormats/TrackCosmics.h - ) + include/ReconstructionDataFormats/TrackCosmics.h + ) o2_add_test(Vertex SOURCES test/testVertex.cxx diff --git a/Detectors/GlobalTracking/CMakeLists.txt b/Detectors/GlobalTracking/CMakeLists.txt index d468f5dbd2257..aa05339f9a2a4 100644 --- a/Detectors/GlobalTracking/CMakeLists.txt +++ b/Detectors/GlobalTracking/CMakeLists.txt @@ -14,7 +14,6 @@ o2_add_library( src/MatchTPCITSParams.cxx src/MatchCosmics.cxx src/MatchCosmicsParams.cxx - src/RecoContainer.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DataFormatsTPC @@ -31,7 +30,8 @@ o2_add_library( O2::TOFBase O2::TOFCalibration O2::SimConfig - O2::DataFormatsFT0) + O2::DataFormatsFT0 + O2::DataFormatsGlobalTracking) o2_target_root_dictionary( GlobalTracking diff --git a/Detectors/GlobalTracking/src/MatchCosmics.cxx b/Detectors/GlobalTracking/src/MatchCosmics.cxx index 6f85b29239b0e..c981d738a4283 100644 --- a/Detectors/GlobalTracking/src/MatchCosmics.cxx +++ b/Detectors/GlobalTracking/src/MatchCosmics.cxx @@ -9,7 +9,7 @@ // or submit itself to any jurisdiction. #include "GlobalTracking/MatchCosmics.h" -#include "GlobalTracking/RecoContainer.h" +#include "DataFormatsGlobalTracking/RecoContainer.h" #include "GPUO2InterfaceRefit.h" #include "ReconstructionDataFormats/GlobalTrackAccessor.h" #include "DataFormatsITSMFT/CompCluster.h" diff --git a/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx index a89edf07377c7..16fc61fde220b 100644 --- a/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx @@ -41,7 +41,7 @@ #include "CommonDataFormat/InteractionRecord.h" #include "ITSBase/GeometryTGeo.h" #include "ITSMFTBase/DPLAlpideParam.h" -#include "GlobalTracking/RecoContainer.h" +#include "DataFormatsGlobalTracking/RecoContainer.h" #include "Framework/Task.h" using namespace o2::framework; diff --git a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx index 9d7dc5a4f6571..0eb2ecc520e4b 100644 --- a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx @@ -11,8 +11,7 @@ /// @file PrimaryVertexingSpec.cxx #include -#include "GlobalTracking/RecoContainer.h" - +#include "DataFormatsGlobalTracking/RecoContainer.h" #include "ReconstructionDataFormats/TrackTPCITS.h" #include "ReconstructionDataFormats/GlobalTrackID.h" #include "DetectorsBase/Propagator.h" diff --git a/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexingSpec.cxx index 8530e2a9cbfed..f2607fedc0433 100644 --- a/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexingSpec.cxx @@ -11,7 +11,7 @@ /// @file SecondaryVertexingSpec.cxx #include -#include "GlobalTracking/RecoContainer.h" +#include "DataFormatsGlobalTracking/RecoContainer.h" #include "ReconstructionDataFormats/TrackTPCITS.h" #include "DataFormatsTPC/TrackTPC.h" #include "DataFormatsITS/TrackITS.h" diff --git a/Detectors/GlobalTrackingWorkflow/src/VertexTrackMatcherSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/VertexTrackMatcherSpec.cxx index c4cc85af832be..9ae478814ce9f 100644 --- a/Detectors/GlobalTrackingWorkflow/src/VertexTrackMatcherSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/VertexTrackMatcherSpec.cxx @@ -16,7 +16,7 @@ #include "DataFormatsParameters/GRPObject.h" #include "ITSMFTBase/DPLAlpideParam.h" #include "DetectorsCommonDataFormats/NameConf.h" -#include "GlobalTracking/RecoContainer.h" +#include "DataFormatsGlobalTracking/RecoContainer.h" using namespace o2::framework; using DetID = o2::detectors::DetID; diff --git a/Detectors/Vertexing/include/DetectorsVertexing/SVertexer.h b/Detectors/Vertexing/include/DetectorsVertexing/SVertexer.h index b0c52f3a5bf8f..22f196e9a1b8d 100644 --- a/Detectors/Vertexing/include/DetectorsVertexing/SVertexer.h +++ b/Detectors/Vertexing/include/DetectorsVertexing/SVertexer.h @@ -15,7 +15,7 @@ #define O2_S_VERTEXER_H #include "gsl/span" -#include "GlobalTracking/RecoContainer.h" +#include "DataFormatsGlobalTracking/RecoContainer.h" #include "ReconstructionDataFormats/PrimaryVertex.h" #include "ReconstructionDataFormats/V0.h" #include "ReconstructionDataFormats/Cascade.h" diff --git a/Detectors/Vertexing/include/DetectorsVertexing/VertexTrackMatcher.h b/Detectors/Vertexing/include/DetectorsVertexing/VertexTrackMatcher.h index 47dfe90a74ede..df6534b59e483 100644 --- a/Detectors/Vertexing/include/DetectorsVertexing/VertexTrackMatcher.h +++ b/Detectors/Vertexing/include/DetectorsVertexing/VertexTrackMatcher.h @@ -23,7 +23,7 @@ #include "CommonDataFormat/InteractionRecord.h" #include "DetectorsVertexing/PVertexerParams.h" #include "MathUtils/Primitive2D.h" -#include "GlobalTracking/RecoContainer.h" +#include "DataFormatsGlobalTracking/RecoContainer.h" namespace o2 { From 456066fb269ec0db8e9a60e6c98e126fe6936b12 Mon Sep 17 00:00:00 2001 From: Barthelemy Date: Thu, 15 Apr 2021 11:18:17 +0200 Subject: [PATCH 221/770] [QC-369] Remove deprecated method to retrieve data from CCDB --- CCDB/include/CCDB/CcdbApi.h | 29 ---- CCDB/src/CcdbApi.cxx | 190 --------------------------- CCDB/test/testCcdbApi.cxx | 16 +-- Detectors/PHOS/calib/src/CalibDB.cxx | 4 +- 4 files changed, 10 insertions(+), 229 deletions(-) diff --git a/CCDB/include/CCDB/CcdbApi.h b/CCDB/include/CCDB/CcdbApi.h index 8762174394128..0a406bb5134e6 100644 --- a/CCDB/include/CCDB/CcdbApi.h +++ b/CCDB/include/CCDB/CcdbApi.h @@ -130,35 +130,6 @@ class CcdbApi //: public DatabaseInterface storeAsTFile(rootobj, path, metadata, startValidityTimestamp, endValidityTimestamp); } - /** - * Retrieve object at the given path for the given timestamp. - * - * @param path The path where the object is to be found. - * @param metadata Key-values representing the metadata to filter out objects. - * @param timestamp Timestamp of the object to retrieve. If omitted, current timestamp is used. - * @return the object, or nullptr if none were found. - * @deprecated in favour of retrieveFromTFileAny - */ - TObject* retrieve(std::string const& path, std::map const& metadata, - long timestamp = -1) const; - - /** - * Retrieve object at the given path for the given timestamp. - * - * @param path The path where the object is to be found. - * @param metadata Key-values representing the metadata to filter out objects. - * @param timestamp Timestamp of the object to retrieve. If omitted, current timestamp is used. - * @param headers Map to be populated with the headers we received, if it is not null. - * @param optional etag from previous call - * @param optional createdNotAfter upper time limit for the object creation timestamp (TimeMachine mode) - * @param optional createdNotBefore lower time limit for the object creation timestamp (TimeMachine mode) - * @return the object, or nullptr if none were found. - * @deprecated in favour of retrieveFromTFileAny as it is not limited to TObjects. - */ - TObject* retrieveFromTFile(std::string const& path, std::map const& metadata, - long timestamp = -1, std::map* headers = nullptr, std::string const& etag = "", - const std::string& createdNotAfter = "", const std::string& createdNotBefore = "") const; - /** * Retrieve object at the given path for the given timestamp. * diff --git a/CCDB/src/CcdbApi.cxx b/CCDB/src/CcdbApi.cxx index ffe8f4d9bdeec..b5a61bb45afed 100644 --- a/CCDB/src/CcdbApi.cxx +++ b/CCDB/src/CcdbApi.cxx @@ -17,17 +17,13 @@ #include "CCDB/CCDBQuery.h" #include "CommonUtils/StringUtils.h" #include "CommonUtils/MemFileHelper.h" -#include #include -#include #include #include #include #include #include #include -#include -#include #include #include #include @@ -307,90 +303,6 @@ static size_t WriteToFileCallback(void* ptr, size_t size, size_t nmemb, FILE* st return written; } -TObject* CcdbApi::retrieve(std::string const& path, std::map const& metadata, - long timestamp) const -{ - // Note : based on https://curl.haxx.se/libcurl/c/getinmemory.html - // Thus it does not comply to our coding guidelines as it is a copy paste. - - // Prepare CURL - CURL* curl_handle; - CURLcode res; - struct MemoryStruct chunk { - (char*)malloc(1) /*memory*/, 0 /*size*/ - }; - TObject* result = nullptr; - - /* init the curl session */ - curl_handle = curl_easy_init(); - - string fullUrl = getFullUrlForRetrieval(curl_handle, path, metadata, timestamp); - - /* specify URL to get */ - curl_easy_setopt(curl_handle, CURLOPT_URL, fullUrl.c_str()); - - /* send all data to this function */ - curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); - - /* we pass our 'chunk' struct to the callback function */ - curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void*)&chunk); - - /* some servers don't like requests that are made without a user-agent - field, so we provide one */ - curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0"); - - /* if redirected , we tell libcurl to follow redirection */ - curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1L); - - /* get it! */ - res = curl_easy_perform(curl_handle); - - /* check for errors */ - if (res != CURLE_OK) { - fprintf(stderr, "curl_easy_perform() failed: %s\n", - curl_easy_strerror(res)); - } else { - /* - * Now, our chunk.memory points to a memory block that is chunk.size - * bytes big and contains the remote file. - */ - - // printf("%lu bytes retrieved\n", (long) chunk.size); - - long response_code; - res = curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &response_code); - if ((res == CURLE_OK) && (response_code != 404)) { - std::lock_guard guard(gIOMutex); - TMessage mess(kMESS_OBJECT); - mess.SetBuffer(chunk.memory, chunk.size, kFALSE); - mess.SetReadMode(); - mess.Reset(); - result = (TObject*)(mess.ReadObjectAny(mess.GetClass())); - if (result == nullptr) { - cerr << "couldn't retrieve the object " << path << endl; - } - } else { - cerr << "invalid URL : " << fullUrl << endl; - } - - // Print data - // cout << "size : " << chunk.size << endl; - // cout << "data : " << endl; - // char* mem = (char*)chunk.memory; - // for (int i = 0 ; i < chunk.size/4 ; i++) { - // cout << mem; - // mem += 4; - // } - } - - /* cleanup curl stuff */ - curl_easy_cleanup(curl_handle); - - free(chunk.memory); - - return result; -} - std::string CcdbApi::generateFileName(const std::string& inp) { // generate file name for the CCDB object (for now augment the input string by the timestamp) @@ -416,108 +328,6 @@ size_t header_map_callback(char* buffer, size_t size, size_t nitems, void* userd } } // namespace -TObject* CcdbApi::retrieveFromTFile(std::string const& path, std::map const& metadata, - long timestamp, std::map* headers, std::string const& etag, - const std::string& createdNotAfter, const std::string& createdNotBefore) const -{ - // Note : based on https://curl.haxx.se/libcurl/c/getinmemory.html - // Thus it does not comply to our coding guidelines as it is a copy paste. - - // std::map headers2; - - // Prepare CURL - CURL* curl_handle; - CURLcode res; - struct MemoryStruct chunk { - (char*)malloc(1) /*memory*/, 0 /*size*/ - }; - - /* init the curl session */ - curl_handle = curl_easy_init(); - - string fullUrl = getFullUrlForRetrieval(curl_handle, path, metadata, timestamp); - - /* specify URL to get */ - curl_easy_setopt(curl_handle, CURLOPT_URL, fullUrl.c_str()); - - /* send all data to this function */ - curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); - - /* we pass our 'chunk' struct to the callback function */ - curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void*)&chunk); - - /* some servers don't like requests that are made without a user-agent - field, so we provide one */ - curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0"); - - /* if redirected , we tell libcurl to follow redirection */ - curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1L); - - struct curl_slist* list = nullptr; - if (!etag.empty()) { - list = curl_slist_append(list, ("If-None-Match: " + etag).c_str()); - } - - if (!createdNotAfter.empty()) { - list = curl_slist_append(list, ("If-Not-After: " + createdNotAfter).c_str()); - } - - if (!createdNotBefore.empty()) { - list = curl_slist_append(list, ("If-Not-Before: " + createdNotBefore).c_str()); - } - - // setup curl for headers handling - if (headers != nullptr) { - list = curl_slist_append(list, ("If-None-Match: " + to_string(timestamp)).c_str()); - curl_easy_setopt(curl_handle, CURLOPT_HEADERFUNCTION, header_map_callback<>); - curl_easy_setopt(curl_handle, CURLOPT_HEADERDATA, headers); - } - - if (list) { - curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, list); - } - - /* get it! */ - res = curl_easy_perform(curl_handle); - std::string errStr; - TObject* result = nullptr; - if (res == CURLE_OK) { - long response_code; - res = curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &response_code); - if ((res == CURLE_OK) && (response_code != 404)) { - Int_t previousErrorLevel = gErrorIgnoreLevel; - gErrorIgnoreLevel = kFatal; - std::lock_guard guard(gIOMutex); - TMemFile memFile("name", chunk.memory, chunk.size, "READ"); - gErrorIgnoreLevel = previousErrorLevel; - if (!memFile.IsZombie()) { - result = (TObject*)extractFromTFile(memFile, TClass::GetClass("TObject")); - if (result == nullptr) { - errStr = o2::utils::concat_string("Couldn't retrieve the object ", path); - LOG(ERROR) << errStr; - } - memFile.Close(); - } else { - LOG(DEBUG) << "Object " << path << " is stored in a TMemFile"; - } - } else { - errStr = o2::utils::concat_string("Invalid URL : ", fullUrl); - LOG(ERROR) << errStr; - } - } else { - errStr = o2::utils::concat_string("curl_easy_perform() failed: ", curl_easy_strerror(res)); - fprintf(stderr, "%s", errStr.c_str()); - } - - if (!errStr.empty() && headers) { - (*headers)["Error"] = errStr; - } - - curl_easy_cleanup(curl_handle); - free(chunk.memory); - return result; -} - void CcdbApi::retrieveBlob(std::string const& path, std::string const& targetdir, std::map const& metadata, long timestamp) const { diff --git a/CCDB/test/testCcdbApi.cxx b/CCDB/test/testCcdbApi.cxx index 40b51774c9f49..da4c3cc62f635 100644 --- a/CCDB/test/testCcdbApi.cxx +++ b/CCDB/test/testCcdbApi.cxx @@ -264,7 +264,7 @@ BOOST_AUTO_TEST_CASE(retrieveTMemFile_test, *utf::precondition(if_reachable())) { test_fixture f; - TObject* obj = f.api.retrieveFromTFile(basePath + "th1", f.metadata); + TObject* obj = f.api.retrieveFromTFileAny(basePath + "th1", f.metadata); BOOST_CHECK_NE(obj, nullptr); BOOST_CHECK_EQUAL(obj->ClassName(), "TH1F"); auto h1 = dynamic_cast(obj); @@ -272,7 +272,7 @@ BOOST_AUTO_TEST_CASE(retrieveTMemFile_test, *utf::precondition(if_reachable())) BOOST_CHECK_EQUAL(obj->GetName(), "th1name"); delete obj; - obj = f.api.retrieveFromTFile(basePath + "graph", f.metadata); + obj = f.api.retrieveFromTFileAny(basePath + "graph", f.metadata); BOOST_CHECK_NE(obj, nullptr); BOOST_CHECK_EQUAL(obj->ClassName(), "TGraph"); auto graph = dynamic_cast(obj); @@ -285,7 +285,7 @@ BOOST_AUTO_TEST_CASE(retrieveTMemFile_test, *utf::precondition(if_reachable())) delete graph; std::map headers; - obj = f.api.retrieveFromTFile(basePath + "tree", f.metadata, -1, &headers); + obj = f.api.retrieveFromTFileAny(basePath + "tree", f.metadata, -1, &headers); BOOST_CHECK_NE(obj, nullptr); BOOST_CHECK_EQUAL(obj->ClassName(), "TTree"); auto tree = dynamic_cast(obj); @@ -297,7 +297,7 @@ BOOST_AUTO_TEST_CASE(retrieveTMemFile_test, *utf::precondition(if_reachable())) BOOST_CHECK_EQUAL(headers["Hello"], "World"); // wrong url - obj = f.api.retrieveFromTFile("Wrong/wrong", f.metadata); + obj = f.api.retrieveFromTFileAny("Wrong/wrong", f.metadata); BOOST_CHECK_EQUAL(obj, nullptr); } @@ -307,10 +307,10 @@ BOOST_AUTO_TEST_CASE(truncate_test, *utf::precondition(if_reachable())) TH1F h("object1", "object1", 100, 0, 99); f.api.storeAsTFile(&h, basePath + "Detector", f.metadata); // test with explicit dates - auto h1 = f.api.retrieveFromTFile(basePath + "Detector", f.metadata); + auto h1 = f.api.retrieveFromTFileAny(basePath + "Detector", f.metadata); BOOST_CHECK(h1 != nullptr); f.api.truncate(basePath + "Detector"); - h1 = f.api.retrieveFromTFile(basePath + "Detector", f.metadata); + h1 = f.api.retrieveFromTFileAny(basePath + "Detector", f.metadata); BOOST_CHECK(h1 == nullptr); } @@ -322,10 +322,10 @@ BOOST_AUTO_TEST_CASE(delete_test, *utf::precondition(if_reachable())) long from = o2::ccdb::getCurrentTimestamp(); long to = o2::ccdb::getFutureTimestamp(60 * 60 * 24 * 365 * 10); f.api.storeAsTFile(&h1, basePath + "Detector", f.metadata, from, to); // test with explicit dates - auto h2 = f.api.retrieveFromTFile(basePath + "Detector", f.metadata); + auto h2 = f.api.retrieveFromTFileAny(basePath + "Detector", f.metadata); BOOST_CHECK(h2 != nullptr); f.api.deleteObject(basePath + "Detector"); - h2 = f.api.retrieveFromTFile(basePath + "Detector", f.metadata); + h2 = f.api.retrieveFromTFileAny(basePath + "Detector", f.metadata); BOOST_CHECK(h2 == nullptr); } diff --git a/Detectors/PHOS/calib/src/CalibDB.cxx b/Detectors/PHOS/calib/src/CalibDB.cxx index 08aa853a24997..a6a349f0b859a 100644 --- a/Detectors/PHOS/calib/src/CalibDB.cxx +++ b/Detectors/PHOS/calib/src/CalibDB.cxx @@ -37,7 +37,7 @@ BadChannelMap* CalibDB::readBadChannelMap(ULong_t timestamp, const std::map("BadChannelMap/PHS", metadata, timestamp); if (!result) { throw ObjectNotFoundException(mCCDBServer, "BadChannelMap/PHS", metadata, timestamp); } @@ -62,7 +62,7 @@ CalibParams* CalibDB::readCalibParams(ULong_t timestamp, const std::map("CalibParams/PHS", metadata, timestamp); if (!result) { throw ObjectNotFoundException(mCCDBServer, "CalibParams/PHS", metadata, timestamp); } From 15284b622d839e8c64191d6884a7826100752b63 Mon Sep 17 00:00:00 2001 From: Ole Schmidt Date: Thu, 22 Apr 2021 07:46:14 +0200 Subject: [PATCH 222/770] Static conversion trklt to spacepoint added --- GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx | 32 +++++++++++++++++++ GPU/GPUTracking/TRDTracking/GPUTRDTracker.h | 1 + 2 files changed, 33 insertions(+) diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx index b414e9ba04b8a..fcac1fa73cd7c 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx @@ -564,6 +564,38 @@ GPUd() void GPUTRDTracker_t::DoTrackingThread(int iTrk, int thread mTracks[iTrk] = trkCopy; // copy back the resulting track } +template +GPUd() bool GPUTRDTracker_t::ConvertTrkltToSpacePoint(const GPUTRDGeometry& geo, GPUTRDTrackletWord& trklt, GPUTRDSpacePointInternal& sp) +{ + // converts a single GPUTRDTrackletWord into GPUTRDSpacePointInternal + // returns true if successfull + int det = trklt.GetDetector(); + if (!geo.ChamberInGeometry(det)) { + return false; + } + auto* matrix = geo.GetClusterMatrix(det); + if (!matrix) { + return false; + } + const GPUTRDpadPlane* pp = geo.GetPadPlane(det); + int trkltZbin = trklt.GetZbin(); + My_Float xTrkltDet[3] = {0.f}; // trklt position in chamber coordinates + My_Float xTrkltSec[3] = {0.f}; // trklt position in sector coordinates + xTrkltDet[0] = geo.AnodePos() - 0.1f; // mRadialOffset = -0.1f is fix + xTrkltDet[1] = trklt.GetY(); + xTrkltDet[2] = pp->GetRowPos(trkltZbin) - pp->GetRowSize(trkltZbin) / 2.f - pp->GetRowPos(pp->GetNrows() / 2); + matrix->LocalToMaster(xTrkltDet, xTrkltSec); + sp.mR = xTrkltSec[0]; + sp.mX[0] = xTrkltSec[1]; + sp.mX[1] = xTrkltSec[2]; + sp.mDy = trklt.GetdY(); + + int modId = geo.GetSector(det) * GPUTRDGeometry::kNstack + geo.GetStack(det); // global TRD stack number + unsigned short volId = geo.GetGeomManagerVolUID(det, modId); + sp.mVolumeId = volId; + return true; +} + template GPUd() bool GPUTRDTracker_t::CalculateSpacePoints(int iCollision) { diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h index da91005d9370d..fd9b5609f875f 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h @@ -120,6 +120,7 @@ class GPUTRDTracker_t : public GPUProcessor GPUd() int GetCollisionID(float trkTime) const; GPUd() void DoTrackingThread(int iTrk, int threadId = 0); + static GPUd() bool ConvertTrkltToSpacePoint(const GPUTRDGeometry& geo, GPUTRDTrackletWord& trklt, GPUTRDSpacePointInternal& sp); GPUd() bool CalculateSpacePoints(int iCollision = 0); GPUd() bool FollowProlongation(PROP* prop, TRDTRK* t, int threadId, int collisionId); GPUd() int FillImpactAngleHistograms(PROP* prop, TRDTRK* t); From 3c34b4e80f28cfc356109008f270a2ab7d09b4b4 Mon Sep 17 00:00:00 2001 From: Piotr Konopka Date: Thu, 22 Apr 2021 09:40:29 +0200 Subject: [PATCH 223/770] DPL: Limit DataOrigin to 4 characters (not 16) when dumping (#5968) DataOrigin can take max. 4 characters. If it uses all 4, it misses a string termination character, thus the dump contains e.g. this: ``` "name": "MERGER-MultiNodeLocal1l-0", "inputs": [ { "binding": "timer-publish", "origin": "MRGR\u00012541_221\n\u001F, "description": "timer-MultiNodeL", "subspec": 65536, "lifetime": 4 }, { ``` ...which prevents it from being correctly read, as the origin becomes larger than 4. --- Framework/Core/src/WorkflowSerializationHelpers.cxx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Framework/Core/src/WorkflowSerializationHelpers.cxx b/Framework/Core/src/WorkflowSerializationHelpers.cxx index 7be2ac75ddddd..4abe6e3ff6dd4 100644 --- a/Framework/Core/src/WorkflowSerializationHelpers.cxx +++ b/Framework/Core/src/WorkflowSerializationHelpers.cxx @@ -500,13 +500,13 @@ struct WorkflowImporter : public rapidjson::BaseReaderHandler, } else if (in(State::IN_INPUT_BINDING)) { binding = s; } else if (in(State::IN_INPUT_ORIGIN)) { - origin.runtimeInit(s.c_str(), std::min(s.size(), 16UL)); + origin.runtimeInit(s.c_str(), std::min(s.size(), 4UL)); } else if (in(State::IN_INPUT_DESCRIPTION)) { description.runtimeInit(s.c_str(), std::min(s.size(), 16UL)); } else if (in(State::IN_OUTPUT_BINDING)) { binding = s; } else if (in(State::IN_OUTPUT_ORIGIN)) { - origin.runtimeInit(s.c_str(), std::min(s.size(), 16UL)); + origin.runtimeInit(s.c_str(), std::min(s.size(), 4UL)); } else if (in(State::IN_OUTPUT_DESCRIPTION)) { description.runtimeInit(s.c_str(), std::min(s.size(), 16UL)); } else if (in(State::IN_OPTION_NAME)) { @@ -695,7 +695,7 @@ void WorkflowSerializationHelpers::dump(std::ostream& out, auto origin = DataSpecUtils::getOptionalOrigin(input); if (origin.has_value()) { w.Key("origin"); - w.String(origin->str, strnlen(origin->str, 16)); + w.String(origin->str, strnlen(origin->str, 4)); } auto description = DataSpecUtils::getOptionalDescription(input); if (description.has_value()) { From 868826b5475e1bbe957e565f3a7aa7bc77019a22 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 21 Apr 2021 22:30:30 +0200 Subject: [PATCH 224/770] GPU: Never try to create O2 output in the GPU standalone benchmark if the input is Run2 data --- GPU/GPUTracking/Benchmark/standalone.cxx | 1 + 1 file changed, 1 insertion(+) diff --git a/GPU/GPUTracking/Benchmark/standalone.cxx b/GPU/GPUTracking/Benchmark/standalone.cxx index 164a7fceb2094..72930c9806de7 100644 --- a/GPU/GPUTracking/Benchmark/standalone.cxx +++ b/GPU/GPUTracking/Benchmark/standalone.cxx @@ -179,6 +179,7 @@ int ReadConfiguration(int argc, char** argv) #ifndef GPUCA_TPC_GEOMETRY_O2 configStandalone.rec.mergerReadFromTrackerDirectly = 0; configStandalone.proc.ompKernels = false; + configStandalone.proc.createO2Output = 0; if (configStandalone.rundEdx == -1) { configStandalone.rundEdx = 0; } From 2a1ca3ea0cf058f81ec362c5177989580aa13f7a Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 21 Apr 2021 22:30:55 +0200 Subject: [PATCH 225/770] GPU: Bugfix: ClusterXYZ pointers were not propagated to ioPtrs --- GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx b/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx index f403c4a01beca..09fd9e81b4c26 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx @@ -313,6 +313,7 @@ int GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput) mIOPtrs.mergedTracks = Merger.OutputTracks(); mIOPtrs.nMergedTracks = Merger.NOutputTracks(); mIOPtrs.mergedTrackHits = Merger.Clusters(); + mIOPtrs.mergedTrackHitsXYZ = Merger.ClustersXYZ(); mIOPtrs.nMergedTrackHits = Merger.NOutputTrackClusters(); mIOPtrs.mergedTrackHitAttachment = Merger.ClusterAttachment(); mIOPtrs.mergedTrackHitStates = Merger.ClusterStateExt(); @@ -326,6 +327,7 @@ int GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput) processorsShadow()->ioPtrs.mergedTracks = MergerShadow.OutputTracks(); processorsShadow()->ioPtrs.nMergedTracks = Merger.NOutputTracks(); processorsShadow()->ioPtrs.mergedTrackHits = MergerShadow.Clusters(); + processorsShadow()->ioPtrs.mergedTrackHitsXYZ = MergerShadow.ClustersXYZ(); processorsShadow()->ioPtrs.nMergedTrackHits = Merger.NOutputTrackClusters(); processorsShadow()->ioPtrs.mergedTrackHitAttachment = MergerShadow.ClusterAttachment(); processorsShadow()->ioPtrs.mergedTrackHitStates = MergerShadow.ClusterStateExt(); From 41523a3c1c5e750629edc48065971a0cce637f23 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 21 Apr 2021 22:39:23 +0200 Subject: [PATCH 226/770] GPU: Bugfix: Automatically disable certain GPU merger optimizations which will not work if not running full merger on GPU --- GPU/GPUTracking/Base/GPUReconstruction.cxx | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index b8a63dfde0d01..9344a25837d1f 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -275,6 +275,12 @@ int GPUReconstruction::InitPhaseBeforeDevice() if (mProcessingSettings.debugLevel || !mProcessingSettings.fullMergerOnGPU) { mProcessingSettings.delayedOutput = false; } + if (!mProcessingSettings.fullMergerOnGPU && GetRecoStepsGPU() & RecoStep::TPCMerging) { + param().rec.loopInterpolationInExtraPass = 0; + if (param().rec.retryRefit == 1) { + param().rec.retryRefit = 2; + } + } UpdateSettings(); GPUCA_GPUReconstructionUpdateDefailts(); From 07eedb07df8554d82620de5669a076fe2fd58dc8 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 21 Apr 2021 22:55:35 +0200 Subject: [PATCH 227/770] GPU TRD: Add missing function in interface for AliExternalTrackParam --- GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h | 1 + 1 file changed, 1 insertion(+) diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h index e5a234d6b6eca..96f90315944a1 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h @@ -81,6 +81,7 @@ class trackInterface : public AliExternalTrackParam const My_Float* getPar() const { return GetParameter(); } const My_Float* getCov() const { return GetCovariance(); } float getTime() const { return -1.f; } + GPUd() void resetCovariance(float s) { ResetCovariance(10.); } bool CheckNumericalQuality() const { return true; } // parameter manipulation From e9f52d2bda3a44452e7c633973828980b59c494c Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 21 Apr 2021 22:55:56 +0200 Subject: [PATCH 228/770] GPU: Fixes for AliRoot compilation and for OpenCL compilation using Ninja --- GPU/GPUTracking/Base/opencl/CMakeLists.txt | 2 +- GPU/GPUTracking/Base/opencl2/CMakeLists.txt | 6 +++--- GPU/GPUTracking/CMakeLists.txt | 2 +- .../Global/GPUChainTrackingDebugAndProfiling.cxx | 2 ++ 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/GPU/GPUTracking/Base/opencl/CMakeLists.txt b/GPU/GPUTracking/Base/opencl/CMakeLists.txt index 48409be64d5f6..43d25d7f2d6ed 100644 --- a/GPU/GPUTracking/Base/opencl/CMakeLists.txt +++ b/GPU/GPUTracking/Base/opencl/CMakeLists.txt @@ -68,7 +68,7 @@ add_custom_command( # cmake-format: off add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/GPUReconstructionOCLCode.S - COMMAND cat ${GPUDIR}/utils/include.S | sed "s/FILENAMEMOD/_makefile_opencl_program_Base_opencl_common_GPUReconstructionOCL_cl/g" | sed "s/FILENAMENORMAL/GPUReconstructionOCL1Code.bin/g" > ${CMAKE_CURRENT_BINARY_DIR}/GPUReconstructionOCLCode.S + COMMAND cat ${GPUDIR}/utils/include.S | sed "s/FILENAMEMOD/_makefile_opencl_program_Base_opencl_common_GPUReconstructionOCL_cl/g" | sed "s,FILENAMENORMAL,${CMAKE_CURRENT_BINARY_DIR}/GPUReconstructionOCL1Code.bin,g" > ${CMAKE_CURRENT_BINARY_DIR}/GPUReconstructionOCLCode.S MAIN_DEPENDENCY ${GPUDIR}/utils/include.S ) # cmake-format: on diff --git a/GPU/GPUTracking/Base/opencl2/CMakeLists.txt b/GPU/GPUTracking/Base/opencl2/CMakeLists.txt index fa8eeaffcb7d6..812a9c180714a 100644 --- a/GPU/GPUTracking/Base/opencl2/CMakeLists.txt +++ b/GPU/GPUTracking/Base/opencl2/CMakeLists.txt @@ -60,7 +60,7 @@ if(OPENCL2_ENABLED_AMD) # BUILD OpenCL2 binaries for AMD target # cmake-format: off add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/GPUReconstructionOCLCode.amd.S - COMMAND cat ${GPUDIR}/utils/include.S | sed "s/FILENAMEMOD/_makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_amd/g" | sed "s/FILENAMENORMAL/GPUReconstructionOCL2Code.amd/g" > ${CMAKE_CURRENT_BINARY_DIR}/GPUReconstructionOCLCode.amd.S + COMMAND cat ${GPUDIR}/utils/include.S | sed "s/FILENAMEMOD/_makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_amd/g" | sed "s,FILENAMENORMAL,${CMAKE_CURRENT_BINARY_DIR}/GPUReconstructionOCL2Code.amd,g" > ${CMAKE_CURRENT_BINARY_DIR}/GPUReconstructionOCLCode.amd.S MAIN_DEPENDENCY ${GPUDIR}/utils/include.S ) # cmake-format: on @@ -101,7 +101,7 @@ if(OPENCL2_ENABLED_SPIRV) # BUILD OpenCL2 intermediate code for SPIR-V target # cmake-format: off add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/GPUReconstructionOCLCode.spirv.S - COMMAND cat ${GPUDIR}/utils/include.S | sed "s/FILENAMEMOD/_makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_spirv/g" | sed "s/FILENAMENORMAL/GPUReconstructionOCL2Code.spirv/g" > ${CMAKE_CURRENT_BINARY_DIR}/GPUReconstructionOCLCode.spirv.S + COMMAND cat ${GPUDIR}/utils/include.S | sed "s/FILENAMEMOD/_makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_spirv/g" | sed "s,FILENAMENORMAL,${CMAKE_CURRENT_BINARY_DIR}/GPUReconstructionOCL2Code.spirv,g" > ${CMAKE_CURRENT_BINARY_DIR}/GPUReconstructionOCLCode.spirv.S MAIN_DEPENDENCY ${GPUDIR}/utils/include.S ) # cmake-format: on @@ -133,7 +133,7 @@ if(OPENCL2_ENABLED) # BUILD OpenCL2 source code for runtime compilation target # cmake-format: off add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/GPUReconstructionOCLCode.src.S - COMMAND cat ${GPUDIR}/utils/include.S | sed "s/FILENAMEMOD/_makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_src/g" | sed "s/FILENAMENORMAL/GPUReconstructionOCL2Code.src/g" > ${CMAKE_CURRENT_BINARY_DIR}/GPUReconstructionOCLCode.src.S + COMMAND cat ${GPUDIR}/utils/include.S | sed "s/FILENAMEMOD/_makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_src/g" | sed "s,FILENAMENORMAL,${CMAKE_CURRENT_BINARY_DIR}/GPUReconstructionOCL2Code.src,g" > ${CMAKE_CURRENT_BINARY_DIR}/GPUReconstructionOCLCode.src.S MAIN_DEPENDENCY ${GPUDIR}/utils/include.S ) # cmake-format: on diff --git a/GPU/GPUTracking/CMakeLists.txt b/GPU/GPUTracking/CMakeLists.txt index 2d50bac291cb1..9365c316cf91b 100644 --- a/GPU/GPUTracking/CMakeLists.txt +++ b/GPU/GPUTracking/CMakeLists.txt @@ -327,7 +327,7 @@ endif() # Main CMake part for AliRoot if(ALIGPU_BUILD_TYPE STREQUAL "ALIROOT") set(HDRS_CINT_ALIROOT ${HDRS_CINT_ALIROOT} - Base/GPUO2DataTypes.h) + DataTypes/GPUO2DataTypes.h) add_definitions(-DGPUCA_ALIROOT_LIB) include_directories(display qa) include_directories(SYSTEM ${ROOT_INCLUDE_DIR}) diff --git a/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx b/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx index b13b11111aa00..e92b4d3bf4a52 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx @@ -155,9 +155,11 @@ void GPUChainTracking::PrintMemoryStatistics() addToMap("TPC O2 ClusRefs", usageMap, processors()->tpcMerger.NOutputClusRefsTPCO2(), processors()->tpcMerger.NOutputClusRefsTPCO2()); } +#ifdef GPUCA_TPC_GEOMETRY_O2 addToMap("TPC ComprCache HitsAttached", usageMap, processors()->tpcCompressor.mOutput->nAttachedClusters, processors()->tpcCompressor.mMaxTrackClusters); addToMap("TPC ComprCache HitsUnattached", usageMap, processors()->tpcCompressor.mOutput->nUnattachedClusters, processors()->tpcCompressor.mMaxClustersInCache); addToMap("TPC ComprCache Tracks", usageMap, processors()->tpcCompressor.mOutput->nTracks, processors()->tpcCompressor.mMaxTracks); +#endif for (auto& elem : usageMap) { printf("Mem Usage %-30s : %'14lu / %'14lu (%3.0f%% / %3.0f%% / count %3u / max %'14lu)\n", elem.first.c_str(), elem.second.nSum, elem.second.nBoundSum, 100. * elem.second.nSum / std::max(1lu, elem.second.nBoundSum), 100. * elem.second.maxUse, elem.second.count, elem.second.nMax); From aa2dfacd89ef7d905cf119e5e3aaf585456942b5 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 22 Apr 2021 18:54:51 +0200 Subject: [PATCH 229/770] TPC Workflow: Bugfix: Can create shared cluster map also if clusters are provided as input --- Detectors/TPC/workflow/src/RecoWorkflow.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Detectors/TPC/workflow/src/RecoWorkflow.cxx b/Detectors/TPC/workflow/src/RecoWorkflow.cxx index 2759dc91243d9..db891ba44a15d 100644 --- a/Detectors/TPC/workflow/src/RecoWorkflow.cxx +++ b/Detectors/TPC/workflow/src/RecoWorkflow.cxx @@ -432,7 +432,7 @@ framework::WorkflowSpec getWorkflow(CompletionPolicyData* policyData, std::vecto cfg.outputCompClustersFlat = runClusterEncoder; cfg.outputCAClusters = isEnabled(OutputType::Clusters) && (caClusterer || decompressTPC); cfg.outputQA = isEnabled(OutputType::QA); - cfg.outputSharedClusterMap = isEnabled(OutputType::Clusters) && isEnabled(OutputType::Tracks) && !isEnabled(OutputType::NoSharedClusterMap); + cfg.outputSharedClusterMap = (isEnabled(OutputType::Clusters) || inputType == InputType::Clusters) && isEnabled(OutputType::Tracks) && !isEnabled(OutputType::NoSharedClusterMap); cfg.processMC = propagateMC; cfg.sendClustersPerSector = isEnabled(OutputType::SendClustersPerSector); cfg.askDISTSTF = askDISTSTF; From 59042e0b19c4c252f177a28ae2fe299ab7b95b24 Mon Sep 17 00:00:00 2001 From: afurs Date: Wed, 21 Apr 2021 22:01:09 +0200 Subject: [PATCH 230/770] FIT: std::cout changed to LOG(INFO) --- .../Detectors/FIT/FDD/src/RawEventData.cxx | 122 +++++++++--------- .../Detectors/FIT/FT0/src/RawEventData.cxx | 86 ++++++------ .../Detectors/FIT/FV0/src/RawEventData.cxx | 58 ++++----- .../FIT/raw/include/FITRaw/DataBlockBase.h | 28 ++-- 4 files changed, 145 insertions(+), 149 deletions(-) diff --git a/DataFormats/Detectors/FIT/FDD/src/RawEventData.cxx b/DataFormats/Detectors/FIT/FDD/src/RawEventData.cxx index 68cfc0b235cff..c57025e64ee12 100644 --- a/DataFormats/Detectors/FIT/FDD/src/RawEventData.cxx +++ b/DataFormats/Detectors/FIT/FDD/src/RawEventData.cxx @@ -16,81 +16,81 @@ using namespace o2::fdd; void EventHeader::print() const { - std::cout << std::hex; - std::cout << "################EventHeader###############" << std::endl; - std::cout << "startDescriptor: " << startDescriptor << std::endl; - std::cout << "nGBTWords: " << nGBTWords << std::endl; - std::cout << "BC: " << bc << std::endl; - std::cout << "Orbit: " << orbit << std::endl; - std::cout << "##########################################" << std::endl; - std::cout << std::dec; + LOG(INFO) << std::hex; + LOG(INFO) << "################EventHeader###############"; + LOG(INFO) << "startDescriptor: " << startDescriptor; + LOG(INFO) << "nGBTWords: " << nGBTWords; + LOG(INFO) << "BC: " << bc; + LOG(INFO) << "Orbit: " << orbit; + LOG(INFO) << "##########################################"; + LOG(INFO) << std::dec; } void EventData::print() const { - std::cout << std::hex; - std::cout << "###############EventData(PM)##############" << std::endl; - std::cout << "------------Channel " << channelID << "------------" << std::endl; - std::cout << "Charge: " << charge << std::endl; - std::cout << "Time: " << time << std::endl; - std::cout << "numberADC: " << numberADC << std::endl; - std::cout << "isDoubleEvent: " << isDoubleEvent << std::endl; - std::cout << "is1TimeLostEvent: " << is1TimeLostEvent << std::endl; - std::cout << "is2TimeLostEvent: " << is2TimeLostEvent << std::endl; - std::cout << "isADCinGate : " << isADCinGate << std::endl; - std::cout << "isTimeInfoLate: " << isTimeInfoLate << std::endl; - std::cout << "isAmpHigh: " << isAmpHigh << std::endl; - std::cout << "isEventInTVDC: " << isEventInTVDC << std::endl; - std::cout << "isTimeInfoLost: " << isTimeInfoLost << std::endl; - std::cout << "channelID: " << channelID << std::endl; - std::cout << "##########################################" << std::endl; - std::cout << std::dec; + LOG(INFO) << std::hex; + LOG(INFO) << "###############EventData(PM)##############"; + LOG(INFO) << "------------Channel " << channelID << "------------"; + LOG(INFO) << "Charge: " << charge; + LOG(INFO) << "Time: " << time; + LOG(INFO) << "numberADC: " << numberADC; + LOG(INFO) << "isDoubleEvent: " << isDoubleEvent; + LOG(INFO) << "is1TimeLostEvent: " << is1TimeLostEvent; + LOG(INFO) << "is2TimeLostEvent: " << is2TimeLostEvent; + LOG(INFO) << "isADCinGate : " << isADCinGate; + LOG(INFO) << "isTimeInfoLate: " << isTimeInfoLate; + LOG(INFO) << "isAmpHigh: " << isAmpHigh; + LOG(INFO) << "isEventInTVDC: " << isEventInTVDC; + LOG(INFO) << "isTimeInfoLost: " << isTimeInfoLost; + LOG(INFO) << "channelID: " << channelID; + LOG(INFO) << "##########################################"; + LOG(INFO) << std::dec; } void TCMdata::print() const { - std::cout << std::hex; - std::cout << "################TCMdata###################" << std::endl; - std::cout << "orC: " << orC << std::endl; - std::cout << "orA: " << orA << std::endl; - std::cout << "sCen: " << sCen << std::endl; - std::cout << "cen: " << cen << std::endl; - std::cout << "vertex: " << vertex << std::endl; - std::cout << "nChanA: " << nChanA << std::endl; - std::cout << "nChanC: " << nChanC << std::endl; - std::cout << "amplA: " << amplA << std::endl; - std::cout << "amplC: " << amplC << std::endl; - std::cout << "timeA: " << timeA << std::endl; - std::cout << "timeC: " << timeC << std::endl; - std::cout << "##########################################" << std::endl; - std::cout << std::dec; + LOG(INFO) << std::hex; + LOG(INFO) << "################TCMdata###################"; + LOG(INFO) << "orC: " << orC; + LOG(INFO) << "orA: " << orA; + LOG(INFO) << "sCen: " << sCen; + LOG(INFO) << "cen: " << cen; + LOG(INFO) << "vertex: " << vertex; + LOG(INFO) << "nChanA: " << nChanA; + LOG(INFO) << "nChanC: " << nChanC; + LOG(INFO) << "amplA: " << amplA; + LOG(INFO) << "amplC: " << amplC; + LOG(INFO) << "timeA: " << timeA; + LOG(INFO) << "timeC: " << timeC; + LOG(INFO) << "##########################################"; + LOG(INFO) << std::dec; } void RawEventData::print() const { - std::cout << "==================Raw event data==================" << std::endl; - std::cout << "##################Header##################" << std::endl; - std::cout << "startDescriptor: " << mEventHeader.startDescriptor << std::endl; - std::cout << "Nchannels: " << mEventHeader.nGBTWords * 2 << std::endl; - std::cout << "BC: " << mEventHeader.bc << std::endl; - std::cout << "Orbit: " << mEventHeader.orbit << std::endl; - std::cout << "##########################################" << std::endl; - std::cout << "###################DATA###################" << std::endl; + LOG(INFO) << "==================Raw event data=================="; + LOG(INFO) << "##################Header##################"; + LOG(INFO) << "startDescriptor: " << mEventHeader.startDescriptor; + LOG(INFO) << "Nchannels: " << mEventHeader.nGBTWords * 2; + LOG(INFO) << "BC: " << mEventHeader.bc; + LOG(INFO) << "Orbit: " << mEventHeader.orbit; + LOG(INFO) << "##########################################"; + LOG(INFO) << "###################DATA###################"; for (int iCh = 0; iCh < mEventHeader.nGBTWords * 2; iCh++) { - std::cout << "------------Channel " << mEventData[iCh].channelID << "------------" << std::endl; - std::cout << "Charge: " << mEventData[iCh].charge << std::endl; - std::cout << "Time: " << mEventData[iCh].time << std::endl; - std::cout << "1TimeLostEvent: " << mEventData[iCh].is1TimeLostEvent << std::endl; - std::cout << "2TimeLostEvent: " << mEventData[iCh].is2TimeLostEvent << std::endl; - std::cout << "ADCinGate: " << mEventData[iCh].isADCinGate << std::endl; - std::cout << "AmpHigh: " << mEventData[iCh].isAmpHigh << std::endl; - std::cout << "DoubleEvent: " << mEventData[iCh].isDoubleEvent << std::endl; - std::cout << "EventInTVDC: " << mEventData[iCh].isEventInTVDC << std::endl; - std::cout << "TimeInfoLate: " << mEventData[iCh].isTimeInfoLate << std::endl; - std::cout << "TimeInfoLost: " << mEventData[iCh].isTimeInfoLost << std::endl; - std::cout << "numberADC: " << mEventData[iCh].numberADC << std::endl; + LOG(INFO) << "------------Channel " << mEventData[iCh].channelID << "------------"; + LOG(INFO) << "Charge: " << mEventData[iCh].charge; + LOG(INFO) << "Time: " << mEventData[iCh].time; + LOG(INFO) << "1TimeLostEvent: " << mEventData[iCh].is1TimeLostEvent; + LOG(INFO) << "2TimeLostEvent: " << mEventData[iCh].is2TimeLostEvent; + LOG(INFO) << "ADCinGate: " << mEventData[iCh].isADCinGate; + LOG(INFO) << "AmpHigh: " << mEventData[iCh].isAmpHigh; + LOG(INFO) << "DoubleEvent: " << mEventData[iCh].isDoubleEvent; + LOG(INFO) << "EventInTVDC: " << mEventData[iCh].isEventInTVDC; + LOG(INFO) << "TimeInfoLate: " << mEventData[iCh].isTimeInfoLate; + LOG(INFO) << "TimeInfoLost: " << mEventData[iCh].isTimeInfoLost; + LOG(INFO) << "numberADC: " << mEventData[iCh].numberADC; } - std::cout << "##########################################" << std::endl; + LOG(INFO) << "##########################################"; } void RawEventData::printHexEventHeader() const diff --git a/DataFormats/Detectors/FIT/FT0/src/RawEventData.cxx b/DataFormats/Detectors/FIT/FT0/src/RawEventData.cxx index 716594c64ce6e..dd31632a6b838 100644 --- a/DataFormats/Detectors/FIT/FT0/src/RawEventData.cxx +++ b/DataFormats/Detectors/FIT/FT0/src/RawEventData.cxx @@ -17,59 +17,59 @@ using namespace o2::ft0; void EventHeader::print() const { - std::cout << std::hex; - std::cout << "################EventHeader###############" << std::endl; - std::cout << "startDescriptor: " << startDescriptor << std::endl; - std::cout << "nGBTWords: " << nGBTWords << std::endl; - std::cout << "BC: " << bc << std::endl; - std::cout << "Orbit: " << orbit << std::endl; - std::cout << "##########################################" << std::endl; - std::cout << std::dec; + LOG(INFO) << std::hex; + LOG(INFO) << "################EventHeader###############"; + LOG(INFO) << "startDescriptor: " << startDescriptor; + LOG(INFO) << "nGBTWords: " << nGBTWords; + LOG(INFO) << "BC: " << bc; + LOG(INFO) << "Orbit: " << orbit; + LOG(INFO) << "##########################################"; + LOG(INFO) << std::dec; } void EventData::print() const { - std::cout << std::hex; - std::cout << "###############EventData(PM)##############" << std::endl; - std::cout << "------------Channel " << channelID << "------------" << std::endl; - std::cout << "Charge: " << charge << std::endl; - std::cout << "Time: " << time << std::endl; - std::cout << "numberADC: " << numberADC << std::endl; - std::cout << "isDoubleEvent: " << isDoubleEvent << std::endl; - std::cout << "isTimeInfoNOTvalid: " << isTimeInfoNOTvalid << std::endl; - std::cout << "isCFDinADCgate: " << isCFDinADCgate << std::endl; - std::cout << "isTimeInfoLate: " << isTimeInfoLate << std::endl; - std::cout << "isAmpHigh: " << isAmpHigh << std::endl; - std::cout << "isEventInTVDC: " << isEventInTVDC << std::endl; - std::cout << "isTimeInfoLost: " << isTimeInfoLost << std::endl; - std::cout << "##########################################" << std::endl; - std::cout << std::dec; + LOG(INFO) << std::hex; + LOG(INFO) << "###############EventData(PM)##############"; + LOG(INFO) << "------------Channel " << channelID << "------------"; + LOG(INFO) << "Charge: " << charge; + LOG(INFO) << "Time: " << time; + LOG(INFO) << "numberADC: " << numberADC; + LOG(INFO) << "isDoubleEvent: " << isDoubleEvent; + LOG(INFO) << "isTimeInfoNOTvalid: " << isTimeInfoNOTvalid; + LOG(INFO) << "isCFDinADCgate: " << isCFDinADCgate; + LOG(INFO) << "isTimeInfoLate: " << isTimeInfoLate; + LOG(INFO) << "isAmpHigh: " << isAmpHigh; + LOG(INFO) << "isEventInTVDC: " << isEventInTVDC; + LOG(INFO) << "isTimeInfoLost: " << isTimeInfoLost; + LOG(INFO) << "##########################################"; + LOG(INFO) << std::dec; } void TCMdata::print() const { - std::cout << std::hex; - std::cout << "################TCMdata###################" << std::endl; - std::cout << "orC: " << orC << std::endl; - std::cout << "orA: " << orA << std::endl; - std::cout << "sCen: " << sCen << std::endl; - std::cout << "cen: " << cen << std::endl; - std::cout << "vertex: " << vertex << std::endl; - std::cout << "nChanA: " << nChanA << std::endl; - std::cout << "nChanC: " << nChanC << std::endl; - std::cout << "amplA: " << amplA << std::endl; - std::cout << "amplC: " << amplC << std::endl; - std::cout << "timeA: " << timeA << std::endl; - std::cout << "timeC: " << timeC << std::endl; - std::cout << "##########################################" << std::endl; - std::cout << std::dec; + LOG(INFO) << std::hex; + LOG(INFO) << "################TCMdata###################"; + LOG(INFO) << "orC: " << orC; + LOG(INFO) << "orA: " << orA; + LOG(INFO) << "sCen: " << sCen; + LOG(INFO) << "cen: " << cen; + LOG(INFO) << "vertex: " << vertex; + LOG(INFO) << "nChanA: " << nChanA; + LOG(INFO) << "nChanC: " << nChanC; + LOG(INFO) << "amplA: " << amplA; + LOG(INFO) << "amplC: " << amplC; + LOG(INFO) << "timeA: " << timeA; + LOG(INFO) << "timeC: " << timeC; + LOG(INFO) << "##########################################"; + LOG(INFO) << std::dec; } void TCMdataExtended::print() const { - std::cout << std::hex; - std::cout << "############TCMdataExtended###############" << std::endl; - std::cout << "triggerWord: " << triggerWord << std::endl; - std::cout << "##########################################" << std::endl; - std::cout << std::dec; + LOG(INFO) << std::hex; + LOG(INFO) << "############TCMdataExtended###############"; + LOG(INFO) << "triggerWord: " << triggerWord; + LOG(INFO) << "##########################################"; + LOG(INFO) << std::dec; } diff --git a/DataFormats/Detectors/FIT/FV0/src/RawEventData.cxx b/DataFormats/Detectors/FIT/FV0/src/RawEventData.cxx index d558e0b5a96cd..76ee001088fef 100644 --- a/DataFormats/Detectors/FIT/FV0/src/RawEventData.cxx +++ b/DataFormats/Detectors/FIT/FV0/src/RawEventData.cxx @@ -18,41 +18,41 @@ ClassImp(RawEventData); void EventHeader::print() const { - std::cout << std::hex; - std::cout << "################EventHeader###############" << std::endl; - std::cout << "startDescriptor: " << startDescriptor << std::endl; - std::cout << "nGBTWords: " << nGBTWords << std::endl; - std::cout << "BC: " << bc << std::endl; - std::cout << "Orbit: " << orbit << std::endl; - std::cout << "##########################################" << std::endl; - std::cout << std::dec; + LOG(INFO) << std::hex; + LOG(INFO) << "################EventHeader###############"; + LOG(INFO) << "startDescriptor: " << startDescriptor; + LOG(INFO) << "nGBTWords: " << nGBTWords; + LOG(INFO) << "BC: " << bc; + LOG(INFO) << "Orbit: " << orbit; + LOG(INFO) << "##########################################"; + LOG(INFO) << std::dec; } void RawEventData::print() const { - std::cout << "==================Raw event data==================" << std::endl; - std::cout << "##################Header##################" << std::endl; - std::cout << "startDescriptor: " << mEventHeader.startDescriptor << std::endl; - std::cout << "Nchannels: " << mEventHeader.nGBTWords * 2 << std::endl; - std::cout << "BC: " << mEventHeader.bc << std::endl; - std::cout << "Orbit: " << mEventHeader.orbit << std::endl; - std::cout << "##########################################" << std::endl; - std::cout << "###################DATA###################" << std::endl; + LOG(INFO) << "==================Raw event data=================="; + LOG(INFO) << "##################Header##################"; + LOG(INFO) << "startDescriptor: " << mEventHeader.startDescriptor; + LOG(INFO) << "Nchannels: " << mEventHeader.nGBTWords * 2; + LOG(INFO) << "BC: " << mEventHeader.bc; + LOG(INFO) << "Orbit: " << mEventHeader.orbit; + LOG(INFO) << "##########################################"; + LOG(INFO) << "###################DATA###################"; for (int iCh = 0; iCh < mEventHeader.nGBTWords * 2; iCh++) { - std::cout << "------------Channel " << mEventData[iCh].channelID << "------------" << std::endl; - std::cout << "Charge: " << mEventData[iCh].charge << std::endl; - std::cout << "Time: " << mEventData[iCh].time << std::endl; - std::cout << "1TimeLostEvent: " << mEventData[iCh].is1TimeLostEvent << std::endl; - std::cout << "2TimeLostEvent: " << mEventData[iCh].is2TimeLostEvent << std::endl; - std::cout << "ADCinGate: " << mEventData[iCh].isADCinGate << std::endl; - std::cout << "AmpHigh: " << mEventData[iCh].isAmpHigh << std::endl; - std::cout << "DoubleEvent: " << mEventData[iCh].isDoubleEvent << std::endl; - std::cout << "EventInTVDC: " << mEventData[iCh].isEventInTVDC << std::endl; - std::cout << "TimeInfoLate: " << mEventData[iCh].isTimeInfoLate << std::endl; - std::cout << "TimeInfoLost: " << mEventData[iCh].isTimeInfoLost << std::endl; - std::cout << "numberADC: " << mEventData[iCh].numberADC << std::endl; + LOG(INFO) << "------------Channel " << mEventData[iCh].channelID << "------------"; + LOG(INFO) << "Charge: " << mEventData[iCh].charge; + LOG(INFO) << "Time: " << mEventData[iCh].time; + LOG(INFO) << "1TimeLostEvent: " << mEventData[iCh].is1TimeLostEvent; + LOG(INFO) << "2TimeLostEvent: " << mEventData[iCh].is2TimeLostEvent; + LOG(INFO) << "ADCinGate: " << mEventData[iCh].isADCinGate; + LOG(INFO) << "AmpHigh: " << mEventData[iCh].isAmpHigh; + LOG(INFO) << "DoubleEvent: " << mEventData[iCh].isDoubleEvent; + LOG(INFO) << "EventInTVDC: " << mEventData[iCh].isEventInTVDC; + LOG(INFO) << "TimeInfoLate: " << mEventData[iCh].isTimeInfoLate; + LOG(INFO) << "TimeInfoLost: " << mEventData[iCh].isTimeInfoLost; + LOG(INFO) << "numberADC: " << mEventData[iCh].numberADC; } - std::cout << "##########################################" << std::endl; + LOG(INFO) << "##########################################"; } void RawEventData::printHexEventHeader() const diff --git a/Detectors/FIT/raw/include/FITRaw/DataBlockBase.h b/Detectors/FIT/raw/include/FITRaw/DataBlockBase.h index 9753bc60c5aef..8c3d8089f189d 100644 --- a/Detectors/FIT/raw/include/FITRaw/DataBlockBase.h +++ b/Detectors/FIT/raw/include/FITRaw/DataBlockBase.h @@ -322,32 +322,28 @@ struct DataBlockWrapper { //Printing LookupTables static void printLUT() { - cout << endl - << "-------------------------------------------" << endl; - std::cout << "kNELEMENTS|kNSTEPS|kISPARTED" << std::endl; + LOG(INFO) << "-------------------------------------------"; + LOG(INFO) << "kNELEMENTS|kNSTEPS|kISPARTED"; for (int i = 0; i < MaxNwords + 1; i++) { - std::cout << std::endl - << std::get(sReadingLookupTable[i]) << "|" + LOG(INFO) << std::get(sReadingLookupTable[i]) << "|" << std::get(sReadingLookupTable[i]) << "|" - << std::get(sReadingLookupTable[i]) << endl; + << std::get(sReadingLookupTable[i]); } - cout << endl - << "-------------------------------------------" << endl; - std::cout << "kELEMENTINDEX|kWORDINDEX|kNBYTES|kSRCBYTEPOS|kDESTBYTEPOS" << std::endl; + LOG(INFO) << "-------------------------------------------"; + LOG(INFO) << "kELEMENTINDEX|kWORDINDEX|kNBYTES|kSRCBYTEPOS|kDESTBYTEPOS"; for (int i = 0; i < getNsteps(); i++) { - cout << endl - << std::get(sByteLookupTable[i]) << "|" - << std::get(sByteLookupTable[i]) << "|" - << std::get(sByteLookupTable[i]) << "|" - << std::get(sByteLookupTable[i]) << "|" - << std::get(sByteLookupTable[i]) << endl; + LOG(INFO) << std::get(sByteLookupTable[i]) << "|" + << std::get(sByteLookupTable[i]) << "|" + << std::get(sByteLookupTable[i]) << "|" + << std::get(sByteLookupTable[i]) << "|" + << std::get(sByteLookupTable[i]); } } void print() const { assert(mNelements <= T::MaxNelements); for (int i = 0; i < mNelements; i++) { - std::cout << "\nPrinting element number: " << i << std::endl; + LOG(INFO) << "Printing element number: " << i; mData[i].print(); } } From b64c6f733b3062be6fa5f1e067517a7bc5a58f60 Mon Sep 17 00:00:00 2001 From: afurs Date: Wed, 21 Apr 2021 22:03:38 +0200 Subject: [PATCH 231/770] FT0: filenaming fixed in digit2raw --- Detectors/FIT/FT0/reconstruction/src/test-raw2digit.cxx | 2 +- Detectors/FIT/FT0/simulation/src/Digits2Raw.cxx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Detectors/FIT/FT0/reconstruction/src/test-raw2digit.cxx b/Detectors/FIT/FT0/reconstruction/src/test-raw2digit.cxx index cb963083f3dce..143b1033526c0 100644 --- a/Detectors/FIT/FT0/reconstruction/src/test-raw2digit.cxx +++ b/Detectors/FIT/FT0/reconstruction/src/test-raw2digit.cxx @@ -83,7 +83,7 @@ int main() std::cout << "\nTOTAL EVENTS: " << vecTotalEvents.size() << std::endl; std::cout << "Simulation completed!" << std::endl; - gSystem->Exec("$O2_ROOT/bin/o2-ft0-digi2raw --configKeyValues \"HBFUtils.nHBFPerTF=128;HBFUtils.orbitFirst=0\""); + gSystem->Exec("$O2_ROOT/bin/o2-ft0-digi2raw --file-per-link --configKeyValues \"HBFUtils.nHBFPerTF=128;HBFUtils.orbitFirst=0\""); gSystem->Exec("$O2_ROOT/bin/o2-raw-file-reader-workflow -b --input-conf FT0raw.cfg --configKeyValues \"HBFUtils.nHBFPerTF=128;HBFUtils.orbitFirst=0\"|$O2_ROOT/bin/o2-ft0-flp-dpl-workflow -b"); TFile flIn2("o2_ft0digits.root"); std::unique_ptr treeInput2((TTree*)flIn2.Get("o2sim")); diff --git a/Detectors/FIT/FT0/simulation/src/Digits2Raw.cxx b/Detectors/FIT/FT0/simulation/src/Digits2Raw.cxx index 4ba9fc9bee700..3ea2f9ea8c1f9 100644 --- a/Detectors/FIT/FT0/simulation/src/Digits2Raw.cxx +++ b/Detectors/FIT/FT0/simulation/src/Digits2Raw.cxx @@ -119,7 +119,7 @@ void Digits2Raw::readDigits(const std::string& outDir, const std::string& fileDi LOG(INFO) << " registered links " << mLinkID << " endpoint " << mEndPointID; } //TCM - std::string outFileLink = mOutputPerLink ? o2::utils::concat_string(outDir, "ft0_link", std::to_string(NPMs), ".raw") : o2::utils::concat_string(outDir, "ft0.raw"); + std::string outFileLink = mOutputPerLink ? o2::utils::concat_string(outDir, "ft0_link", std::to_string(NPMs - 1), ".raw") : o2::utils::concat_string(outDir, "ft0.raw"); mWriter.registerLink(mLinkTCM + 8, mCruID, mLinkTCM, 0, outFileLink); LOG(INFO) << " registered link TCM " << mLinkTCM; From c2af20f2a69d55d9551460908861887593af48e3 Mon Sep 17 00:00:00 2001 From: afurs Date: Wed, 21 Apr 2021 22:05:34 +0200 Subject: [PATCH 232/770] FT0: isTCM method added to LUT --- .../FIT/FT0/include/DataFormatsFT0/LookUpTable.h | 4 ++++ .../FIT/FT0/raw/include/FT0Raw/RawReaderFT0Base.h | 13 +++---------- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/DataFormats/Detectors/FIT/FT0/include/DataFormatsFT0/LookUpTable.h b/DataFormats/Detectors/FIT/FT0/include/DataFormatsFT0/LookUpTable.h index ce8cadb2d1f17..5d5b62cad5d25 100644 --- a/DataFormats/Detectors/FIT/FT0/include/DataFormatsFT0/LookUpTable.h +++ b/DataFormats/Detectors/FIT/FT0/include/DataFormatsFT0/LookUpTable.h @@ -228,6 +228,10 @@ class LookUpTable std::cout << "lut_data.size " << lut_data.size() << std::endl; return o2::ft0::LookUpTable{lut_data}; } + bool isTCM(int link, int ep) + { + return getChannel(link, 1, ep) == TCM_channel; + } private: std::vector mTopoVector; diff --git a/Detectors/FIT/FT0/raw/include/FT0Raw/RawReaderFT0Base.h b/Detectors/FIT/FT0/raw/include/FT0Raw/RawReaderFT0Base.h index 8cc8110b8452f..a5bb8c78cddd4 100644 --- a/Detectors/FIT/FT0/raw/include/FT0Raw/RawReaderFT0Base.h +++ b/Detectors/FIT/FT0/raw/include/FT0Raw/RawReaderFT0Base.h @@ -50,20 +50,13 @@ class RawReaderFT0Base : public RawReaderBase payload, int ep) { - int linkTCM = 11; - if (0 <= linkID && linkID != linkTCM) { - //PM data proccessing - RawReaderBaseType::template processBinaryData(payload, linkID, ep); - } else if (linkID == linkTCM && ep == 0) { + if (o2::ft0::SingleLUT::Instance().isTCM(linkID, ep)) { //TCM data proccessing RawReaderBaseType::template processBinaryData(payload, linkID, ep); } else { - //put here code in case of bad rdh.linkID value - LOG(INFO) << "WARNING! WRONG LINK ID! " << linkID; - return; + //PM data proccessing + RawReaderBaseType::template processBinaryData(payload, linkID, ep); } - - // } }; //Normal TCM mode From dbf945929bcd45e3fc8f87506376067d933128c0 Mon Sep 17 00:00:00 2001 From: jmyrcha Date: Thu, 22 Apr 2021 22:36:48 +0200 Subject: [PATCH 233/770] Json reader (#5971) * adding JSON reader * adding JSON reader * adding JSON reader - fix build/O2/fullCI complaints Co-authored-by: Julian Myrcha --- EventVisualisation/Base/CMakeLists.txt | 1 + .../EventVisualisationBase/DataInterpreter.h | 2 +- .../EventVisualisationBase/DataReader.h | 9 +- .../EventVisualisationBase/DataSource.h | 3 +- .../DataSourceOffline.h | 2 +- .../VisualisationConstants.h | 10 +- EventVisualisation/Base/src/DataReader.cxx | 37 ++++ .../Base/src/DataSourceOffline.cxx | 11 +- .../DataConverter/CMakeLists.txt | 1 + .../ConversionConstants.h | 9 + .../VisualisationCluster.h | 4 + .../VisualisationEvent.h | 71 ++++++- .../VisualisationTrack.h | 52 +++-- .../src/VisualisationCluster.cxx | 26 +++ .../DataConverter/src/VisualisationEvent.cxx | 121 ++++++++++-- .../DataConverter/src/VisualisationTrack.cxx | 101 ++++++---- EventVisualisation/Detectors/CMakeLists.txt | 7 +- .../DataInterpreterITS.h | 2 +- .../DataInterpreterTPC.h | 2 +- .../DataInterpreterVSD.h | 2 +- .../DataReaderITS.h | 4 +- .../DataReaderJSON.h | 43 ++++ .../DataReaderTPC.h | 2 +- .../DataReaderVSD.h | 2 +- .../Detectors/src/DataInterpreterITS.cxx | 39 ++-- .../Detectors/src/DataInterpreterTPC.cxx | 38 ++-- .../Detectors/src/DataInterpreterVSD.cxx | 21 +- .../Detectors/src/DataReaderJSON.cxx | 47 +++++ .../Detectors/src/DataReaderTPC.cxx | 2 +- .../Detectors/src/DataReaderVSD.cxx | 4 +- EventVisualisation/View/CMakeLists.txt | 21 +- .../EventVisualisationView/EventManager.h | 3 +- .../EventVisualisationView/Initializer.h | 9 +- .../include/EventVisualisationView/Options.h | 66 +++++++ EventVisualisation/View/src/EventManager.cxx | 21 +- EventVisualisation/View/src/Initializer.cxx | 27 ++- EventVisualisation/View/src/Options.cxx | 186 ++++++++++++++++++ EventVisualisation/View/src/main.cxx | 59 +----- 38 files changed, 840 insertions(+), 227 deletions(-) create mode 100644 EventVisualisation/Base/src/DataReader.cxx create mode 100644 EventVisualisation/Detectors/include/EventVisualisationDetectors/DataReaderJSON.h create mode 100644 EventVisualisation/Detectors/src/DataReaderJSON.cxx create mode 100644 EventVisualisation/View/include/EventVisualisationView/Options.h create mode 100644 EventVisualisation/View/src/Options.cxx diff --git a/EventVisualisation/Base/CMakeLists.txt b/EventVisualisation/Base/CMakeLists.txt index 229aa5adf6c98..56ef37116afc7 100644 --- a/EventVisualisation/Base/CMakeLists.txt +++ b/EventVisualisation/Base/CMakeLists.txt @@ -11,6 +11,7 @@ o2_add_library(EventVisualisationBase SOURCES src/ConfigurationManager.cxx src/DataInterpreter.cxx + src/DataReader.cxx src/DataSourceOffline.cxx src/GeometryManager.cxx PUBLIC_LINK_LIBRARIES ROOT::Eve diff --git a/EventVisualisation/Base/include/EventVisualisationBase/DataInterpreter.h b/EventVisualisation/Base/include/EventVisualisationBase/DataInterpreter.h index 3568492c0fd98..9f5c288d8625d 100644 --- a/EventVisualisation/Base/include/EventVisualisationBase/DataInterpreter.h +++ b/EventVisualisation/Base/include/EventVisualisationBase/DataInterpreter.h @@ -54,7 +54,7 @@ class DataInterpreter } // Should return visualisation objects for required data type - virtual std::unique_ptr interpretDataForType(TObject* data, EVisualisationDataType type) = 0; + virtual VisualisationEvent interpretDataForType(TObject* data, EVisualisationDataType type) = 0; static DataInterpreter* getInstance(EVisualisationGroup type) { return instance[type]; } //static void setInstance(DataInterpreter* instance, EVisualisationGroup type) { DataInterpreter::instance[type] = instance; } diff --git a/EventVisualisation/Base/include/EventVisualisationBase/DataReader.h b/EventVisualisation/Base/include/EventVisualisationBase/DataReader.h index 27b95bc51e1f6..5663009fad5bf 100644 --- a/EventVisualisation/Base/include/EventVisualisationBase/DataReader.h +++ b/EventVisualisation/Base/include/EventVisualisationBase/DataReader.h @@ -15,6 +15,9 @@ #ifndef ALICE_O2_EVENTVISUALISATION_BASE_DATAREADER_H #define ALICE_O2_EVENTVISUALISATION_BASE_DATAREADER_H +#include "EventVisualisationDataConverter/VisualisationEvent.h" +#include "EventVisualisationBase/DataInterpreter.h" + class TObject; namespace o2 @@ -24,11 +27,15 @@ namespace event_visualisation class DataReader { + DataInterpreter* mInterpreter; + virtual TObject* getEventData(int /*no*/) { return nullptr; }; + public: + DataReader(DataInterpreter* interpreter); virtual int GetEventCount() const = 0; virtual ~DataReader() = default; virtual void open() = 0; - virtual TObject* getEventData(int no) = 0; + virtual VisualisationEvent getEvent(int no, EVisualisationDataType dataType); }; } // namespace event_visualisation diff --git a/EventVisualisation/Base/include/EventVisualisationBase/DataSource.h b/EventVisualisation/Base/include/EventVisualisationBase/DataSource.h index ba0be3f206b52..ff2752ba0cd45 100644 --- a/EventVisualisation/Base/include/EventVisualisationBase/DataSource.h +++ b/EventVisualisation/Base/include/EventVisualisationBase/DataSource.h @@ -17,6 +17,7 @@ #define ALICE_O2_EVENTVISUALISATION_BASE_DATASOURCE_H #include +#include class TObject; @@ -28,7 +29,7 @@ namespace event_visualisation class DataSource { public: - virtual TObject* getEventData(int /*no*/, EVisualisationGroup /*purpose*/) { return nullptr; }; + virtual VisualisationEvent getEventData(int /*no*/, EVisualisationGroup /*purpose*/, EVisualisationDataType dataType) = 0; virtual int GetEventCount() { return 0; }; DataSource() = default; diff --git a/EventVisualisation/Base/include/EventVisualisationBase/DataSourceOffline.h b/EventVisualisation/Base/include/EventVisualisationBase/DataSourceOffline.h index eb36151b51e20..8bfae88a10c00 100644 --- a/EventVisualisation/Base/include/EventVisualisationBase/DataSourceOffline.h +++ b/EventVisualisation/Base/include/EventVisualisationBase/DataSourceOffline.h @@ -47,7 +47,7 @@ class DataSourceOffline : public DataSource instance[purpose] = reader; } - TObject* getEventData(int no, EVisualisationGroup purpose) override; + VisualisationEvent getEventData(int no, EVisualisationGroup purpose, EVisualisationDataType dataType) override; }; } // namespace event_visualisation diff --git a/EventVisualisation/Base/include/EventVisualisationBase/VisualisationConstants.h b/EventVisualisation/Base/include/EventVisualisationBase/VisualisationConstants.h index 1bb9ef1ca8f5d..0f7db6e1a7ad0 100644 --- a/EventVisualisation/Base/include/EventVisualisationBase/VisualisationConstants.h +++ b/EventVisualisation/Base/include/EventVisualisationBase/VisualisationConstants.h @@ -40,6 +40,7 @@ enum EVisualisationGroup { TRD, RND, VSD, + JSON, NvisualisationGroups }; @@ -58,7 +59,8 @@ const std::string gVisualisationGroupName[NvisualisationGroups] = { "TPC", "TRD", "RND", - "VSD"}; + "VSD", + "JSON"}; const bool R2Visualisation[NvisualisationGroups] = { true, //"ACO", @@ -75,7 +77,8 @@ const bool R2Visualisation[NvisualisationGroups] = { true, //"TPC", true, //"TRD", true, //"RND", - true //"VSD" + true, //"VSD" + true //"JSON" }; const bool R3Visualisation[NvisualisationGroups] = { @@ -93,7 +96,8 @@ const bool R3Visualisation[NvisualisationGroups] = { true, //"TPC", false, //"TRD", false, //"RND", - false //"VSD" + false, //"VSD" + true //"JSON" }; enum EVisualisationDataType { diff --git a/EventVisualisation/Base/src/DataReader.cxx b/EventVisualisation/Base/src/DataReader.cxx new file mode 100644 index 0000000000000..e31acab615abb --- /dev/null +++ b/EventVisualisation/Base/src/DataReader.cxx @@ -0,0 +1,37 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// +/// \file DataInterpreter.cxx +/// \author julian.myrcha@cern.ch + +#include "EventVisualisationBase/DataReader.h" +#include "FairLogger.h" + +using namespace std; + +namespace o2 +{ +namespace event_visualisation +{ + +DataReader::DataReader(DataInterpreter* interpreter) : mInterpreter(interpreter) +{ +} + +VisualisationEvent DataReader::getEvent(int no, EVisualisationDataType dataType) +{ + TObject* data = this->getEventData(no); + VisualisationEvent event = mInterpreter->interpretDataForType(data, dataType); + return event; +} + +} // namespace event_visualisation +} // namespace o2 diff --git a/EventVisualisation/Base/src/DataSourceOffline.cxx b/EventVisualisation/Base/src/DataSourceOffline.cxx index 9f5021c9d6759..bf770331ba8eb 100644 --- a/EventVisualisation/Base/src/DataSourceOffline.cxx +++ b/EventVisualisation/Base/src/DataSourceOffline.cxx @@ -35,12 +35,17 @@ namespace event_visualisation DataReader* DataSourceOffline::instance[EVisualisationGroup::NvisualisationGroups]; -TObject* DataSourceOffline::getEventData(int no, EVisualisationGroup purpose) +VisualisationEvent DataSourceOffline::getEventData(int no, EVisualisationGroup purpose, EVisualisationDataType dataType) { if (instance[purpose] == nullptr) { - return nullptr; + return VisualisationEvent({.eventNumber = -1, + .runNumber = -1, + .energy = -1, + .multiplicity = -1, + .collidingSystem = "", + .timeStamp = 0}); } - return instance[purpose]->getEventData(no); + return instance[purpose]->getEvent(no, dataType); } int DataSourceOffline::GetEventCount() diff --git a/EventVisualisation/DataConverter/CMakeLists.txt b/EventVisualisation/DataConverter/CMakeLists.txt index 7d8139ecca9f7..e9a6dfff0bd6c 100644 --- a/EventVisualisation/DataConverter/CMakeLists.txt +++ b/EventVisualisation/DataConverter/CMakeLists.txt @@ -12,5 +12,6 @@ o2_add_library(EventVisualisationDataConverter SOURCES src/VisualisationEvent.cxx src/VisualisationTrack.cxx src/VisualisationCluster.cxx + PUBLIC_LINK_LIBRARIES RapidJSON::RapidJSON ) diff --git a/EventVisualisation/DataConverter/include/EventVisualisationDataConverter/ConversionConstants.h b/EventVisualisation/DataConverter/include/EventVisualisationDataConverter/ConversionConstants.h index 2d69cbee1f2bb..2f06e21dd418f 100644 --- a/EventVisualisation/DataConverter/include/EventVisualisationDataConverter/ConversionConstants.h +++ b/EventVisualisation/DataConverter/include/EventVisualisationDataConverter/ConversionConstants.h @@ -19,6 +19,15 @@ #include +/// +/// Which visualisation import method was used to obtain track +/// +enum ETrackSource { + CosmicSource, + TPCSource, + ITSSource +}; + enum ETrackType { Standard, diff --git a/EventVisualisation/DataConverter/include/EventVisualisationDataConverter/VisualisationCluster.h b/EventVisualisation/DataConverter/include/EventVisualisationDataConverter/VisualisationCluster.h index 81e36d813ea92..662501fbf30f3 100644 --- a/EventVisualisation/DataConverter/include/EventVisualisationDataConverter/VisualisationCluster.h +++ b/EventVisualisation/DataConverter/include/EventVisualisationDataConverter/VisualisationCluster.h @@ -17,6 +17,7 @@ #define ALICE_O2_DATACONVERTER_VISUALISATIONCLUSTER_H #include "EventVisualisationDataConverter/VisualisationTrack.h" +#include "rapidjson/document.h" #include #include @@ -35,6 +36,9 @@ namespace event_visualisation class VisualisationCluster { public: + VisualisationCluster(rapidjson::Value& tree); + rapidjson::Value jsonTree(rapidjson::Document::AllocatorType& allocator); + // Default constructor VisualisationCluster(double XYZ[]); diff --git a/EventVisualisation/DataConverter/include/EventVisualisationDataConverter/VisualisationEvent.h b/EventVisualisation/DataConverter/include/EventVisualisationDataConverter/VisualisationEvent.h index 21ea814c6c723..e1ad4cc2e2182 100644 --- a/EventVisualisation/DataConverter/include/EventVisualisationDataConverter/VisualisationEvent.h +++ b/EventVisualisation/DataConverter/include/EventVisualisationDataConverter/VisualisationEvent.h @@ -19,7 +19,7 @@ #include "EventVisualisationDataConverter/VisualisationTrack.h" #include "EventVisualisationDataConverter/VisualisationCluster.h" -#include +#include #include namespace o2 @@ -37,27 +37,80 @@ namespace event_visualisation class VisualisationEvent { public: + std::string toJson(); + void fromJson(std::string json); + bool fromFile(std::string fileName); + VisualisationEvent() = default; + VisualisationEvent(std::string fileName); + void toFile(std::string fileName); + static std::string fileNameIndexed(const std::string fileName, const int index); + + //VisualisationEvent() {} + + /// constructor parametrisation (Value Object) for VisualisationEvent class + /// + /// Simplifies passing parameters to constructor of VisualisationEvent + /// by providing their names + struct VisualisationEventVO { + int eventNumber; + int runNumber; + double energy; + int multiplicity; + std::string collidingSystem; + time_t timeStamp; + }; // Default constructor - VisualisationEvent(int eventNumber, int runNumber, double energy, int multiplicity, std::string collidingSystem, time_t timeStamp); + VisualisationEvent(const VisualisationEventVO vo); // Adds visualisation track inside visualisation event - void addTrack(const VisualisationTrack& track) { mTracks.push_back(track); } + //void addTrack(const VisualisationTrack& track) + //{ mTracks.push_back(track); } + + VisualisationTrack* addTrack(VisualisationTrack::VisualisationTrackVO vo) + { + mTracks.emplace_back(vo); + return &mTracks.back(); + } + void remove_last_track() { mTracks.pop_back(); } // used to remove track assigned optimistically // Adds visualisation cluser inside visualisation event - void addCluster(const VisualisationCluster& cluster) { mClusters.push_back(cluster); } + //void addCluster(const VisualisationCluster& cluster) + //{ mClusters.push_back(cluster); } + VisualisationCluster& addCluster(double XYZ[]) + { + mClusters.emplace_back(XYZ); + return mClusters.back(); + } // Multiplicity getter - int GetMultiplicity() const { return mMultiplicity; } + int GetMultiplicity() const + { + return mMultiplicity; + } // Returns track with index i - const VisualisationTrack& getTrack(int i) const { return mTracks[i]; }; + const VisualisationTrack& getTrack(int i) const + { + return mTracks[i]; + }; + // Returns number of tracks - size_t getTrackCount() const { return mTracks.size(); } + size_t getTrackCount() const + { + return mTracks.size(); + } // Returns cluster with index i - const VisualisationCluster& getCluster(int i) const { return mClusters[i]; }; + const VisualisationCluster& getCluster(int i) const + { + return mClusters[i]; + }; + // Returns number of clusters - size_t getClusterCount() const { return mClusters.size(); } + size_t getClusterCount() const + { + return mClusters.size(); + } private: int mEventNumber; /// event number in file diff --git a/EventVisualisation/DataConverter/include/EventVisualisationDataConverter/VisualisationTrack.h b/EventVisualisation/DataConverter/include/EventVisualisationDataConverter/VisualisationTrack.h index 82747545510ff..93c31f4866ebe 100644 --- a/EventVisualisation/DataConverter/include/EventVisualisationDataConverter/VisualisationTrack.h +++ b/EventVisualisation/DataConverter/include/EventVisualisationDataConverter/VisualisationTrack.h @@ -18,6 +18,7 @@ #define ALICE_O2_EVENTVISUALISATION_BASE_VISUALISATIONTRACK_H #include "ConversionConstants.h" +#include "rapidjson/document.h" #include #include @@ -41,23 +42,34 @@ class VisualisationTrack public: // Default constructor VisualisationTrack(); - + // create track from their JSON representation + VisualisationTrack(rapidjson::Value& tree); + // create JSON representation of the track + rapidjson::Value jsonTree(rapidjson::Document::AllocatorType& allocator); + + /// constructor parametrisation (Value Object) for VisualisationTrack class + /// + /// Simplifies passing parameters to constructor of VisualisationTrack + /// by providing their names + struct VisualisationTrackVO { + int charge; + double energy; + int ID; + int PID; + double mass; + double signedPT; + double startXYZ[3]; + double endXYZ[3]; + double pxpypz[3]; + int parentID; + double phi; + double theta; + double helixCurvature; + int type; + ETrackSource source; + }; // Constructor with properties initialisation - VisualisationTrack( - int charge, - double energy, - int ID, - int PID, - double mass, - double signedPT, - double startXYZ[], - double endXYZ[], - double pxpypz[], - int parentID, - double phi, - double theta, - double helixCurvature, - int type); + VisualisationTrack(const VisualisationTrackVO vo); // Add child particle (coming from decay of this particle) void addChild(int childID); @@ -67,6 +79,7 @@ class VisualisationTrack void addPolyPoint(double xyz[3]); // Track type setter (standard track, V0, kink, cascade) void setTrackType(ETrackType type); + std::string getTrackType() { return this->mType; } // Vertex getter double* getVertex() { return mStartCoordinates; } @@ -84,11 +97,11 @@ class VisualisationTrack private: // Set coordinates of the beginning of the track - void addStartCoordinates(double xyz[3]); + void addStartCoordinates(const double xyz[3]); // Set coordinates of the end of the track - void addEndCoordinates(double xyz[3]); + void addEndCoordinates(const double xyz[3]); /// Set momentum vector - void addMomentum(double pxpypz[3]); + void addMomentum(const double pxpypz[3]); int mID; /// Unique identifier of the track std::string mType; /// Type (standard, V0 mother, daughter etc.) @@ -106,6 +119,7 @@ class VisualisationTrack double mPhi; /// An angle from X-axis to the radius vector pointing to the particle std::vector mChildrenIDs; /// Uniqe IDs of children particles + ETrackSource mSource; /// data source of the track (debug) /// Polylines -- array of points along the trajectory of the track std::vector mPolyX; diff --git a/EventVisualisation/DataConverter/src/VisualisationCluster.cxx b/EventVisualisation/DataConverter/src/VisualisationCluster.cxx index 0b287a14a2573..32836c001d824 100644 --- a/EventVisualisation/DataConverter/src/VisualisationCluster.cxx +++ b/EventVisualisation/DataConverter/src/VisualisationCluster.cxx @@ -35,5 +35,31 @@ void VisualisationCluster::setCoordinates(double xyz[3]) } } +VisualisationCluster::VisualisationCluster(rapidjson::Value& tree) +{ + rapidjson::Value& jsonX = tree["X"]; + rapidjson::Value& jsonY = tree["Y"]; + rapidjson::Value& jsonZ = tree["Z"]; + + this->mCoordinates[0] = jsonX.GetDouble(); + this->mCoordinates[1] = jsonY.GetDouble(); + this->mCoordinates[2] = jsonZ.GetDouble(); +} + +rapidjson::Value VisualisationCluster::jsonTree(rapidjson::MemoryPoolAllocator<>& allocator) +{ + rapidjson::Value tree(rapidjson::kObjectType); + rapidjson::Value jsonX(rapidjson::kNumberType); + rapidjson::Value jsonY(rapidjson::kNumberType); + rapidjson::Value jsonZ(rapidjson::kNumberType); + jsonX.SetDouble(mCoordinates[0]); + jsonY.SetDouble(mCoordinates[1]); + jsonZ.SetDouble(mCoordinates[2]); + tree.AddMember("X", jsonX, allocator); + tree.AddMember("Y", jsonY, allocator); + tree.AddMember("Z", jsonZ, allocator); + return tree; +} + } // namespace event_visualisation } // namespace o2 diff --git a/EventVisualisation/DataConverter/src/VisualisationEvent.cxx b/EventVisualisation/DataConverter/src/VisualisationEvent.cxx index d68ec8c8fadef..e998887eaec4f 100644 --- a/EventVisualisation/DataConverter/src/VisualisationEvent.cxx +++ b/EventVisualisation/DataConverter/src/VisualisationEvent.cxx @@ -15,8 +15,18 @@ /// #include "EventVisualisationDataConverter/VisualisationEvent.h" +#include "rapidjson/document.h" +#include "rapidjson/writer.h" +#include "rapidjson/stringbuffer.h" + +#include +#include +#include +#include +#include using namespace std; +using namespace rapidjson; namespace o2 { @@ -24,18 +34,107 @@ namespace event_visualisation { /// Ctor -- set the minimalistic event up -VisualisationEvent::VisualisationEvent(int eventNumber, - int runNumber, - double energy, - int multiplicity, - string collidingSystem, - time_t timeStamp) : mEventNumber(eventNumber), - mRunNumber(runNumber), - mEnergy(energy), - mMultiplicity(multiplicity), - mCollidingSystem(collidingSystem), - mTimeStamp(timeStamp) +VisualisationEvent::VisualisationEvent(VisualisationEventVO vo) +{ + this->mEventNumber = vo.eventNumber; + this->mRunNumber = vo.runNumber; + this->mEnergy = vo.energy; + this->mMultiplicity = vo.multiplicity; + this->mCollidingSystem = vo.collidingSystem; + this->mTimeStamp = vo.timeStamp; +} + +std::string VisualisationEvent::toJson() +{ + Document tree(kObjectType); + Document::AllocatorType& allocator = tree.GetAllocator(); + + // Tracks + rapidjson::Value trackCount(rapidjson::kNumberType); + trackCount.SetInt(this->getTrackCount()); + tree.AddMember("trackCount", trackCount, allocator); + Value jsonTracks(kArrayType); + for (size_t i = 0; i < this->getTrackCount(); i++) { + jsonTracks.PushBack(this->mTracks[i].jsonTree(allocator), allocator); + } + tree.AddMember("mTracks", jsonTracks, allocator); + + // Clusters + rapidjson::Value clusterCount(rapidjson::kNumberType); + clusterCount.SetInt(this->getClusterCount()); + tree.AddMember("clusterCount", clusterCount, allocator); + Value jsonClusters(kArrayType); + for (size_t i = 0; i < this->getClusterCount(); i++) { + jsonClusters.PushBack(this->mClusters[i].jsonTree(allocator), allocator); + } + tree.AddMember("mClusters", jsonClusters, allocator); + + // stringify + StringBuffer buffer; + Writer writer(buffer); + tree.Accept(writer); + return buffer.GetString(); +} + +VisualisationEvent::VisualisationEvent(std::string fileName) +{ + this->fromFile(fileName); +} + +void VisualisationEvent::fromJson(std::string json) { + mTracks.clear(); + mClusters.clear(); + + rapidjson::Document tree; + tree.Parse(json.c_str()); + + rapidjson::Value& trackCount = tree["trackCount"]; + this->mTracks.reserve(trackCount.GetInt()); + rapidjson::Value& jsonTracks = tree["mTracks"]; + for (auto& v : jsonTracks.GetArray()) { + mTracks.emplace_back(v); + } + + rapidjson::Value& clusterCount = tree["clusterCount"]; + this->mClusters.reserve(clusterCount.GetInt()); + rapidjson::Value& jsonClusters = tree["mClusters"]; + for (auto& v : jsonClusters.GetArray()) { + mClusters.emplace_back(v); + } +} + +void VisualisationEvent::toFile(std::string fileName) +{ + std::string json = toJson(); + std::ofstream out(fileName); + out << json; + out.close(); +} + +std::string VisualisationEvent::fileNameIndexed(const std::string fileName, const int index) +{ + std::stringstream buffer; + buffer << fileName << std::setfill('0') << std::setw(3) << index << ".json"; + return buffer.str(); +} + +bool VisualisationEvent::fromFile(std::string fileName) +{ + if (FILE* file = fopen(fileName.c_str(), "r")) { + fclose(file); // file exists + } else { + return false; + } + std::ifstream inFile; + inFile.open(fileName); + + std::stringstream strStream; + strStream << inFile.rdbuf(); //read the file + inFile.close(); + std::string str = strStream.str(); //str holds the content of the file + fromJson(str); + return true; } } // namespace event_visualisation diff --git a/EventVisualisation/DataConverter/src/VisualisationTrack.cxx b/EventVisualisation/DataConverter/src/VisualisationTrack.cxx index 8a64472ed8ef0..c64becbbf375c 100644 --- a/EventVisualisation/DataConverter/src/VisualisationTrack.cxx +++ b/EventVisualisation/DataConverter/src/VisualisationTrack.cxx @@ -15,7 +15,6 @@ /// #include "EventVisualisationDataConverter/VisualisationTrack.h" -#include using namespace std; @@ -26,36 +25,23 @@ namespace event_visualisation VisualisationTrack::VisualisationTrack() = default; -VisualisationTrack::VisualisationTrack( - int charge, - double energy, - int ID, - int PID, - double mass, - double signedPT, - double startXYZ[], - double endXYZ[], - double pxpypz[], - int parentID, - double phi, - double theta, - double helixCurvature, - int type) - : mCharge(charge), - mEnergy(energy), - mParentID(parentID), - mPID(PID), - mSignedPT(signedPT), - mMass(mass), - mHelixCurvature(helixCurvature), - mTheta(theta), - mPhi(phi) +VisualisationTrack::VisualisationTrack(const VisualisationTrackVO vo) { - addMomentum(pxpypz); - addStartCoordinates(startXYZ); - addEndCoordinates(endXYZ); - mID = ID; - mType = gTrackTypes[type]; + this->mCharge = vo.charge; + this->mEnergy = vo.energy; + this->mParentID = vo.parentID; + this->mPID = vo.PID; + this->mSignedPT = vo.signedPT; + this->mMass = vo.mass; + this->mHelixCurvature = vo.helixCurvature; + this->mTheta = vo.theta; + this->mPhi = vo.phi; + this->addMomentum(vo.pxpypz); + this->addStartCoordinates(vo.startXYZ); + this->addEndCoordinates(vo.endXYZ); + this->mID = vo.ID; + this->mType = gTrackTypes[vo.type]; + this->mSource = vo.source; } void VisualisationTrack::addChild(int childID) @@ -63,21 +49,21 @@ void VisualisationTrack::addChild(int childID) mChildrenIDs.push_back(childID); } -void VisualisationTrack::addMomentum(double pxpypz[3]) +void VisualisationTrack::addMomentum(const double pxpypz[3]) { for (int i = 0; i < 3; i++) { mMomentum[i] = pxpypz[i]; } } -void VisualisationTrack::addStartCoordinates(double xyz[3]) +void VisualisationTrack::addStartCoordinates(const double xyz[3]) { for (int i = 0; i < 3; i++) { mStartCoordinates[i] = xyz[i]; } } -void VisualisationTrack::addEndCoordinates(double xyz[3]) +void VisualisationTrack::addEndCoordinates(const double xyz[3]) { for (int i = 0; i < 3; i++) { mEndCoordinates[i] = xyz[i]; @@ -103,5 +89,54 @@ void VisualisationTrack::setTrackType(ETrackType type) mType = gTrackTypes[type]; } +VisualisationTrack::VisualisationTrack(rapidjson::Value& tree) +{ + rapidjson::Value& jsonPolyX = tree["mPolyX"]; + rapidjson::Value& jsonPolyY = tree["mPolyY"]; + rapidjson::Value& jsonPolyZ = tree["mPolyZ"]; + rapidjson::Value& count = tree["count"]; + rapidjson::Value& source = tree["source"]; + + this->mSource = (ETrackSource)source.GetInt(); + mPolyX.reserve(count.GetInt()); + mPolyY.reserve(count.GetInt()); + mPolyZ.reserve(count.GetInt()); + for (auto& v : jsonPolyX.GetArray()) { + mPolyX.push_back(v.GetDouble()); + } + for (auto& v : jsonPolyY.GetArray()) { + mPolyY.push_back(v.GetDouble()); + } + for (auto& v : jsonPolyZ.GetArray()) { + mPolyZ.push_back(v.GetDouble()); + } +} + +rapidjson::Value VisualisationTrack::jsonTree(rapidjson::Document::AllocatorType& allocator) +{ + rapidjson::Value tree(rapidjson::kObjectType); + rapidjson::Value count(rapidjson::kNumberType); + rapidjson::Value source(rapidjson::kNumberType); + rapidjson::Value jsonPolyX(rapidjson::kArrayType); + rapidjson::Value jsonPolyY(rapidjson::kArrayType); + rapidjson::Value jsonPolyZ(rapidjson::kArrayType); + + count.SetInt(this->getPointCount()); + tree.AddMember("count", count, allocator); + source.SetInt(this->mSource); + tree.AddMember("source", source, allocator); + + for (size_t i = 0; i < this->getPointCount(); i++) { + jsonPolyX.PushBack((float)mPolyX[i], allocator); + jsonPolyY.PushBack((float)mPolyY[i], allocator); + jsonPolyZ.PushBack((float)mPolyZ[i], allocator); + } + tree.AddMember("mPolyX", jsonPolyX, allocator); + tree.AddMember("mPolyY", jsonPolyY, allocator); + tree.AddMember("mPolyZ", jsonPolyZ, allocator); + + return tree; +} + } // namespace event_visualisation } // namespace o2 diff --git a/EventVisualisation/Detectors/CMakeLists.txt b/EventVisualisation/Detectors/CMakeLists.txt index 5390b15ed4cfd..bfbcc2786ebf9 100644 --- a/EventVisualisation/Detectors/CMakeLists.txt +++ b/EventVisualisation/Detectors/CMakeLists.txt @@ -10,11 +10,12 @@ o2_add_library(EventVisualisationDetectors SOURCES - src/DataInterpreterTPC.cxx - src/DataReaderTPC.cxx src/DataInterpreterITS.cxx - src/DataReaderITS.cxx + src/DataInterpreterTPC.cxx src/DataInterpreterVSD.cxx + src/DataReaderITS.cxx + src/DataReaderJSON.cxx + src/DataReaderTPC.cxx src/DataReaderVSD.cxx PUBLIC_LINK_LIBRARIES O2::EventVisualisationBase diff --git a/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataInterpreterITS.h b/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataInterpreterITS.h index 20755fd52a93e..e814ebc1f01ba 100644 --- a/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataInterpreterITS.h +++ b/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataInterpreterITS.h @@ -38,7 +38,7 @@ class DataInterpreterITS final : public DataInterpreter ~DataInterpreterITS() final = default; // Returns a visualisation Event for this data type - std::unique_ptr interpretDataForType(TObject* data, EVisualisationDataType type) final; + VisualisationEvent interpretDataForType(TObject* data, EVisualisationDataType type) final; }; } // namespace event_visualisation diff --git a/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataInterpreterTPC.h b/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataInterpreterTPC.h index c0572e468c861..872aba9b95cf5 100644 --- a/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataInterpreterTPC.h +++ b/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataInterpreterTPC.h @@ -39,7 +39,7 @@ class DataInterpreterTPC final : public DataInterpreter ~DataInterpreterTPC() final; // Returns a visualisation Event for this data type - std::unique_ptr interpretDataForType(TObject* data, EVisualisationDataType type) final; + VisualisationEvent interpretDataForType(TObject* data, EVisualisationDataType type) final; }; } // namespace event_visualisation diff --git a/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataInterpreterVSD.h b/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataInterpreterVSD.h index 6f7a18614a5c5..38dbe8c9d74f2 100644 --- a/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataInterpreterVSD.h +++ b/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataInterpreterVSD.h @@ -58,7 +58,7 @@ class DataInterpreterVSD final : public DataInterpreter ~DataInterpreterVSD() final; // Returns a visualisation Event for this data type - std::unique_ptr interpretDataForType(TObject* data, EVisualisationDataType type) final; + VisualisationEvent interpretDataForType(TObject* data, EVisualisationDataType type) final; }; } // namespace event_visualisation diff --git a/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataReaderITS.h b/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataReaderITS.h index a66d37a190784..58dddc67cb216 100644 --- a/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataReaderITS.h +++ b/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataReaderITS.h @@ -31,8 +31,8 @@ class DataReaderITS : public DataReader TFile* mTracFile; public: - DataReaderITS() = default; - ; + DataReaderITS(DataInterpreter* interpreter) : DataReader(interpreter) {} + void open() override; int GetEventCount() const override { return mMaxEv; } diff --git a/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataReaderJSON.h b/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataReaderJSON.h new file mode 100644 index 0000000000000..b88a1a7414bf7 --- /dev/null +++ b/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataReaderJSON.h @@ -0,0 +1,43 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file DataReaderITS.h +/// \brief JSON specific reading from file(s) +/// \author julian.myrcha@cern.ch + +#ifndef O2EVE_EVENTVISUALISATION_DETECTORS_DATAREADERJSON_H +#define O2EVE_EVENTVISUALISATION_DETECTORS_DATAREADERJSON_H + +#include +#include "EventVisualisationBase/DataReader.h" + +namespace o2 +{ +namespace event_visualisation +{ + +class DataReaderJSON : public DataReader +{ + private: + Int_t mMaxEv; + std::string mFileName; + + public: + DataReaderJSON(DataInterpreter* interpreter) : DataReader(interpreter) {} + + void open() override; + int GetEventCount() const override { return mMaxEv; } + VisualisationEvent getEvent(int no, EVisualisationDataType dataType) override; +}; + +} // namespace event_visualisation +} // namespace o2 + +#endif //O2EVE_DATAREADERJSON_H diff --git a/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataReaderTPC.h b/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataReaderTPC.h index 9de5cb109e9a8..7b7428e9b81b3 100644 --- a/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataReaderTPC.h +++ b/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataReaderTPC.h @@ -31,7 +31,7 @@ class DataReaderTPC : public DataReader TFile* mTracFile; public: - DataReaderTPC(); + DataReaderTPC(DataInterpreter* interpreter); void open() override; Int_t GetEventCount() const override { return mMaxEv; }; TObject* getEventData(int no) override; diff --git a/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataReaderVSD.h b/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataReaderVSD.h index fce3c4d26e8bf..f0ea6e567db73 100644 --- a/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataReaderVSD.h +++ b/EventVisualisation/Detectors/include/EventVisualisationDetectors/DataReaderVSD.h @@ -38,7 +38,7 @@ class DataReaderVSD : public DataReader public: //Int_t GetEventCount() override { return mEvDirKeys->GetEntriesFast(); }; int GetEventCount() const override { return mEvDirKeys.size(); }; - DataReaderVSD(); + DataReaderVSD(DataInterpreter* interpreter); ~DataReaderVSD() override; void open() override; TObject* getEventData(int no) override; diff --git a/EventVisualisation/Detectors/src/DataInterpreterITS.cxx b/EventVisualisation/Detectors/src/DataInterpreterITS.cxx index 10a77310610f6..81f902a4e7a00 100644 --- a/EventVisualisation/Detectors/src/DataInterpreterITS.cxx +++ b/EventVisualisation/Detectors/src/DataInterpreterITS.cxx @@ -35,8 +35,6 @@ #include #endif -using namespace std; - namespace o2 { namespace event_visualisation @@ -50,12 +48,17 @@ DataInterpreterITS::DataInterpreterITS() gman->fillMatrixCache(o2::math_utils::bit2Mask(o2::math_utils::TransformType::T2GRot)); } -std::unique_ptr DataInterpreterITS::interpretDataForType(TObject* data, EVisualisationDataType type) +VisualisationEvent DataInterpreterITS::interpretDataForType(TObject* data, EVisualisationDataType type) { TList* list = (TList*)data; Int_t event = ((TVector2*)list->At(2))->X(); - auto ret_event = std::make_unique(0, 0, 0, 0, "", 0); + VisualisationEvent ret_event({.eventNumber = 0, + .runNumber = 0, + .energy = 0, + .multiplicity = 0, + .collidingSystem = "", + .timeStamp = 0}); if (type == Clusters) { its::GeometryTGeo* gman = its::GeometryTGeo::Instance(); @@ -82,9 +85,7 @@ std::unique_ptr DataInterpreterITS::interpretDataForType(TOb for (const auto& c : mClusters) { const auto& gloC = c.getXYZGloRot(*gman); double xyz[3] = {gloC.X(), gloC.Y(), gloC.Z()}; - VisualisationCluster cluster(xyz); - - ret_event->addCluster(cluster); + ret_event.addCluster(xyz); } } else if (type == ESD) { TFile* trackFile = (TFile*)list->At(0); @@ -137,16 +138,26 @@ std::unique_ptr DataInterpreterITS::interpretDataForType(TOb auto start = eve_track->GetLineStart(); auto end = eve_track->GetLineEnd(); - double track_start[3] = {start.fX, start.fY, start.fZ}; - double track_end[3] = {end.fX, end.fY, end.fZ}; - double track_p[3] = {p[0], p[1], p[2]}; - - VisualisationTrack track(rec.getSign(), 0.0, 0, 0, 0.0, 0.0, track_start, track_end, track_p, 0, 0.0, 0.0, 0.0, 0); + VisualisationTrack* track = ret_event.addTrack({.charge = rec.getSign(), + .energy = 0.0, + .ID = 0, + .PID = 0, + .mass = 0.0, + .signedPT = 0.0, + .startXYZ = {start.fX, start.fY, start.fZ}, + .endXYZ = {end.fX, end.fY, end.fZ}, + .pxpypz = {p[0], p[1], p[2]}, + .parentID = 0, + .phi = 0.0, + .theta = 0.0, + .helixCurvature = 0.0, + .type = 0, + .source = ITSSource}); for (Int_t i = 0; i < eve_track->GetN(); ++i) { Float_t x, y, z; eve_track->GetPoint(i, x, y, z); - track.addPolyPoint(x, y, z); + track->addPolyPoint(x, y, z); } delete eve_track; @@ -158,8 +169,6 @@ std::unique_ptr DataInterpreterITS::interpretDataForType(TOb // const auto& gloC = c.getXYZGloRot(*gman); // tpoints->SetNextPoint(gloC.X(), gloC.Y(), gloC.Z()); // } - - ret_event->addTrack(track); } delete trackList; } diff --git a/EventVisualisation/Detectors/src/DataInterpreterTPC.cxx b/EventVisualisation/Detectors/src/DataInterpreterTPC.cxx index 9e78c98c2e40b..3a62365f6bed3 100644 --- a/EventVisualisation/Detectors/src/DataInterpreterTPC.cxx +++ b/EventVisualisation/Detectors/src/DataInterpreterTPC.cxx @@ -34,8 +34,6 @@ #include #include -using namespace std; - namespace o2 { namespace event_visualisation @@ -43,12 +41,17 @@ namespace event_visualisation DataInterpreterTPC::~DataInterpreterTPC() = default; -std::unique_ptr DataInterpreterTPC::interpretDataForType(TObject* data, EVisualisationDataType type) +VisualisationEvent DataInterpreterTPC::interpretDataForType(TObject* data, EVisualisationDataType type) { TList* list = (TList*)data; // Int_t event = ((TVector2*)list->At(2))->X(); - auto ret_event = std::make_unique(0, 0, 0, 0, "", 0); + VisualisationEvent ret_event({.eventNumber = 0, + .runNumber = 0, + .energy = 0, + .multiplicity = 0, + .collidingSystem = "", + .timeStamp = 0}); if (type == Clusters) { TFile* clustFile = (TFile*)list->At(1); @@ -76,8 +79,7 @@ std::unique_ptr DataInterpreterTPC::interpretDataForType(TOb const auto globalXYZ = mapper.LocalToGlobal(localXYZ, sector); double xyz[3] = {globalXYZ.X(), globalXYZ.Y(), globalXYZ.Z()}; - VisualisationCluster cluster(xyz); - ret_event->addCluster(cluster); + ret_event.addCluster(xyz); } } } else if (type == ESD) { @@ -112,20 +114,28 @@ std::unique_ptr DataInterpreterTPC::interpretDataForType(TOb auto start = eve_track->GetLineStart(); auto end = eve_track->GetLineEnd(); - double track_start[3] = {start.fX, start.fY, start.fZ}; - double track_end[3] = {end.fX, end.fY, end.fZ}; - double track_p[3] = {p[0], p[1], p[2]}; - - VisualisationTrack track(rec.getSign(), 0.0, 0, 0, 0.0, 0.0, track_start, track_end, track_p, 0, 0.0, 0.0, 0.0, 0); + VisualisationTrack* track = ret_event.addTrack({.charge = rec.getSign(), + .energy = 0.0, + .ID = 0, + .PID = 0, + .mass = 0.0, + .signedPT = 0.0, + .startXYZ = {start.fX, start.fY, start.fZ}, + .endXYZ = {end.fX, end.fY, end.fZ}, + .pxpypz = {p[0], p[1], p[2]}, + .parentID = 0, + .phi = 0.0, + .theta = 0.0, + .helixCurvature = 0.0, + .type = 0, + .source = TPCSource}); for (Int_t i = 0; i < eve_track->GetN(); ++i) { Float_t x, y, z; eve_track->GetPoint(i, x, y, z); - track.addPolyPoint(x, y, z); + track->addPolyPoint(x, y, z); } delete eve_track; - - ret_event->addTrack(track); } delete trackList; } diff --git a/EventVisualisation/Detectors/src/DataInterpreterVSD.cxx b/EventVisualisation/Detectors/src/DataInterpreterVSD.cxx index be63509e60f94..eb1c73e420de7 100644 --- a/EventVisualisation/Detectors/src/DataInterpreterVSD.cxx +++ b/EventVisualisation/Detectors/src/DataInterpreterVSD.cxx @@ -25,8 +25,6 @@ #include #include -using namespace std; - namespace o2 { namespace event_visualisation @@ -41,7 +39,7 @@ DataInterpreterVSD::~DataInterpreterVSD() } } -std::unique_ptr DataInterpreterVSD::interpretDataForType(TObject* data, EVisualisationDataType type) +VisualisationEvent DataInterpreterVSD::interpretDataForType(TObject* data, EVisualisationDataType type) { if (mVSD == nullptr) { mVSD = new TEveVSD; @@ -54,16 +52,17 @@ std::unique_ptr DataInterpreterVSD::interpretDataForType(TOb this->AttachEvent(); - auto ret_event = std::make_unique(0, 0, 0, 0, "", 0); - // Load event data into visualization structures. + VisualisationEvent ret_event({.eventNumber = 0, + .runNumber = 0, + .energy = 0, + .multiplicity = 0, + .collidingSystem = "", + .timeStamp = 0}); - // this->LoadClusters(this->fITSClusters, "ITS", 0); - // this->LoadClusters(this->fTPCClusters, "TPC", 1); - // this->LoadClusters(this->fTRDClusters, "TRD", 2); - // this->LoadClusters(this->fTOFClusters, "TOF", 3); + // Load event data into visualization structures. if (type == ESD) { - LoadEsdTracks(*ret_event); + LoadEsdTracks(ret_event); } return ret_event; @@ -156,4 +155,4 @@ void DataInterpreterVSD::LoadEsdTracks(VisualisationEvent& /*event*/) } } // namespace event_visualisation -} // namespace o2 \ No newline at end of file +} // namespace o2 diff --git a/EventVisualisation/Detectors/src/DataReaderJSON.cxx b/EventVisualisation/Detectors/src/DataReaderJSON.cxx new file mode 100644 index 0000000000000..9ebed704511ff --- /dev/null +++ b/EventVisualisation/Detectors/src/DataReaderJSON.cxx @@ -0,0 +1,47 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// +/// \file DataReaderJSON.cxx +/// \brief JSON specific reading from file(s) +/// \author julian.myrcha@cern.ch + +#include "EventVisualisationDetectors/DataReaderJSON.h" + +#include + +namespace o2 +{ +namespace event_visualisation +{ + +void DataReaderJSON::open() +{ + this->mFileName = "/home/jmy/CERN/event"; + this->mMaxEv = 0; + while (true) { + FILE* file = fopen(VisualisationEvent::fileNameIndexed(this->mFileName, this->mMaxEv).c_str(), "r"); + if (file == nullptr) { + break; + } + fclose(file); + this->mMaxEv++; + } +} + +VisualisationEvent DataReaderJSON::getEvent(int no, EVisualisationDataType /*dataType*/) +{ + VisualisationEvent vEvent; + vEvent.fromFile(VisualisationEvent::fileNameIndexed(this->mFileName, no)); + return vEvent; +} + +} // namespace event_visualisation +} // namespace o2 diff --git a/EventVisualisation/Detectors/src/DataReaderTPC.cxx b/EventVisualisation/Detectors/src/DataReaderTPC.cxx index 2dea82284bd4f..44db115aeb5a5 100644 --- a/EventVisualisation/Detectors/src/DataReaderTPC.cxx +++ b/EventVisualisation/Detectors/src/DataReaderTPC.cxx @@ -25,7 +25,7 @@ namespace o2 namespace event_visualisation { -DataReaderTPC::DataReaderTPC() = default; +DataReaderTPC::DataReaderTPC(DataInterpreter* interpreter) : DataReader(interpreter) {} void DataReaderTPC::open() { diff --git a/EventVisualisation/Detectors/src/DataReaderVSD.cxx b/EventVisualisation/Detectors/src/DataReaderVSD.cxx index 77b902caa1591..cd5238c01bbeb 100644 --- a/EventVisualisation/Detectors/src/DataReaderVSD.cxx +++ b/EventVisualisation/Detectors/src/DataReaderVSD.cxx @@ -27,8 +27,8 @@ namespace o2 namespace event_visualisation { -DataReaderVSD::DataReaderVSD() - : DataReader(), +DataReaderVSD::DataReaderVSD(DataInterpreter* interpreter) + : DataReader(interpreter), mFile(nullptr), mMaxEv(-1), mCurEv(-1) diff --git a/EventVisualisation/View/CMakeLists.txt b/EventVisualisation/View/CMakeLists.txt index 97069d9d14b8d..5943acabbc4c7 100644 --- a/EventVisualisation/View/CMakeLists.txt +++ b/EventVisualisation/View/CMakeLists.txt @@ -12,17 +12,22 @@ o2_add_library(EventVisualisationView SOURCES src/MultiView.cxx src/Initializer.cxx src/EventManager.cxx + src/Options.cxx src/EventManagerFrame.cxx PUBLIC_LINK_LIBRARIES O2::EventVisualisationBase - O2::EventVisualisationDetectors) + O2::EventVisualisationDetectors + RapidJSON::RapidJSON) o2_target_root_dictionary(EventVisualisationView - HEADERS include/EventVisualisationView/MultiView.h - include/EventVisualisationView/Initializer.h - include/EventVisualisationView/EventManagerFrame.h - LINKDEF src/EventVisualisationViewLinkDef.h) + HEADERS include/EventVisualisationView/MultiView.h + include/EventVisualisationView/Initializer.h + include/EventVisualisationView/Options.h + include/EventVisualisationView/EventManagerFrame.h + LINKDEF src/EventVisualisationViewLinkDef.h) o2_add_executable(eve - SOURCES src/main.cxx - PUBLIC_LINK_LIBRARIES O2::EventVisualisationView - ) + SOURCES src/main.cxx + PUBLIC_LINK_LIBRARIES O2::EventVisualisationView + ) + + diff --git a/EventVisualisation/View/include/EventVisualisationView/EventManager.h b/EventVisualisation/View/include/EventVisualisationView/EventManager.h index b76b8d178e260..ed4fcfae0a9a3 100644 --- a/EventVisualisation/View/include/EventVisualisationView/EventManager.h +++ b/EventVisualisation/View/include/EventVisualisationView/EventManager.h @@ -81,13 +81,12 @@ class EventManager final : public TEveEventManager, public TQObject void RemoveNewEventCommand(const TString& cmd) override; void ClearNewEventCommands() override; - void registerDetector(DataReader* reader, DataInterpreter* interpreter, EVisualisationGroup type); + void registerDetector(DataReader* reader, EVisualisationGroup type); void DropEvent(); private: static EventManager* instance; o2::ccdb::CcdbApi ccdbApi; - DataInterpreter* dataInterpreters[EVisualisationGroup::NvisualisationGroups]; DataReader* dataReaders[EVisualisationGroup::NvisualisationGroups]; TEveElementList* dataTypeLists[EVisualisationDataType::NdataTypes]; EDataSource mCurrentDataSourceType = EDataSource::SourceOffline; diff --git a/EventVisualisation/View/include/EventVisualisationView/Initializer.h b/EventVisualisation/View/include/EventVisualisationView/Initializer.h index d97633645ffe3..dfd2d92a28e8f 100644 --- a/EventVisualisation/View/include/EventVisualisationView/Initializer.h +++ b/EventVisualisation/View/include/EventVisualisationView/Initializer.h @@ -23,13 +23,6 @@ namespace o2 namespace event_visualisation { -struct Options { - bool randomTracks; // -r - bool vsd; // -v - bool itc; // -i - std::string fileName; // -f 'data.root' -}; - /// This class initializes a core of the visualisation system. /// /// Initializer should be created only once when starting @@ -41,7 +34,7 @@ class Initializer { public: /// Default constructor - static void setup(const Options options, const EventManager::EDataSource defaultDataSource = EventManager::SourceOffline); // default data source will be moved to a config file + static void setup(const EventManager::EDataSource defaultDataSource = EventManager::SourceOffline); // default data source will be moved to a config file private: /// Loads geometry for all detectors static void setupGeometry(); diff --git a/EventVisualisation/View/include/EventVisualisationView/Options.h b/EventVisualisation/View/include/EventVisualisationView/Options.h new file mode 100644 index 0000000000000..663fd0f71d531 --- /dev/null +++ b/EventVisualisation/View/include/EventVisualisationView/Options.h @@ -0,0 +1,66 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// +/// \file Options.cxx +/// \author Julian Myrcha + +#ifndef ALICE_O2_EVENTVISUALISATION_VIEW_OPTIONS_H +#define ALICE_O2_EVENTVISUALISATION_VIEW_OPTIONS_H + +#include + +namespace o2 +{ +namespace event_visualisation +{ + +class Options +{ + private: + // stored options + bool mIts; // -i + bool mJSON; // -j + bool mRandomTracks; // -r + bool mTpc; // -t + bool mVsd; // -v + std::string mFileName; // -f 'data.root' + std::string mDataFolder; // -d './' + + // helper methods + static Options instance; + bool saveToJSON(std::string filename); // stores options to current folder + bool readFromJSON(std::string filename); // read options from option file + Options() + { + mFileName = "data.root"; + mDataFolder = "./"; + } + + public: + static Options* Instance() { return &instance; } + std::string printOptions(); + std::string usage(); + bool processCommandLine(int argc, char* argv[]); + + // get access methods + bool its() { return this->mIts; } + bool json() { return this->mJSON; } + std::string dataFolder() { return this->mDataFolder; } + std::string fileName() { return this->mFileName; } + bool randomTracks() { return this->mRandomTracks; } + bool vsd() { return this->mVsd; } + bool tpc() { return this->mTpc; } +}; + +} // namespace event_visualisation +} // namespace o2 + +#endif //ALICE_O2_EVENTVISUALISATION_VIEW_OPTIONS_H diff --git a/EventVisualisation/View/src/EventManager.cxx b/EventVisualisation/View/src/EventManager.cxx index 15fcdd8cd8b41..3fed36fdf37de 100644 --- a/EventVisualisation/View/src/EventManager.cxx +++ b/EventVisualisation/View/src/EventManager.cxx @@ -52,9 +52,6 @@ EventManager& EventManager::getInstance() EventManager::EventManager() : TEveEventManager("Event", "") { LOG(INFO) << "Initializing TEveManager"; - for (unsigned int i = 0; i < elemof(dataInterpreters); i++) { - dataInterpreters[i] = nullptr; - } for (unsigned int i = 0; i < elemof(dataReaders); i++) { dataReaders[i] = nullptr; } @@ -71,7 +68,7 @@ void EventManager::Open() case SourceOffline: { DataSourceOffline* source = new DataSourceOffline(); for (int i = 0; i < EVisualisationGroup::NvisualisationGroups; i++) { - if (dataInterpreters[i] != nullptr) { + if (dataReaders[i] != nullptr) { dataReaders[i]->open(); source->registerReader(dataReaders[i], static_cast(i)); } @@ -98,12 +95,13 @@ void EventManager::GotoEvent(Int_t no) } for (int i = 0; i < EVisualisationGroup::NvisualisationGroups; ++i) { - for (int dataType = 0; dataType < EVisualisationDataType::NdataTypes; ++dataType) { - DataInterpreter* interpreter = dataInterpreters[i]; - if (interpreter) { - TObject* data = getDataSource()->getEventData(no, (EVisualisationGroup)i); - std::unique_ptr event = interpreter->interpretDataForType(data, (EVisualisationDataType)dataType); - displayVisualisationEvent(*event, gVisualisationGroupName[i]); + DataReader* reader = dataReaders[i]; + if (reader) { + for (int dataType = 0; dataType < EVisualisationDataType::NdataTypes; ++dataType) { + //TObject* data = getDataSource()->getEventData(no, (EVisualisationGroup)i); + //std::unique_ptr event = interpreter->interpretDataForType(data, (EVisualisationDataType)dataType); + VisualisationEvent event = getDataSource()->getEventData(no, (EVisualisationGroup)i, (EVisualisationDataType)dataType); + displayVisualisationEvent(event, gVisualisationGroupName[i]); } } } @@ -206,10 +204,9 @@ void EventManager::displayVisualisationEvent(VisualisationEvent& event, const st } } -void EventManager::registerDetector(DataReader* reader, DataInterpreter* interpreter, EVisualisationGroup type) +void EventManager::registerDetector(DataReader* reader, EVisualisationGroup type) { dataReaders[type] = reader; - dataInterpreters[type] = interpreter; } } // namespace event_visualisation diff --git a/EventVisualisation/View/src/Initializer.cxx b/EventVisualisation/View/src/Initializer.cxx index 5df21b9f0fc15..7ba0ec3a24801 100644 --- a/EventVisualisation/View/src/Initializer.cxx +++ b/EventVisualisation/View/src/Initializer.cxx @@ -23,11 +23,16 @@ #include "EventVisualisationView/MultiView.h" #include "EventVisualisationBase/VisualisationConstants.h" #include "EventVisualisationBase/DataSourceOffline.h" -#include "EventVisualisationDetectors/DataReaderTPC.h" -#include "EventVisualisationDetectors/DataInterpreterTPC.h" -#include "EventVisualisationDetectors/DataReaderITS.h" -#include "EventVisualisationDetectors/DataInterpreterITS.h" #include "EventVisualisationView/EventManagerFrame.h" +#include "EventVisualisationView/Options.h" + +#include "EventVisualisationDetectors/DataInterpreterITS.h" +#include "EventVisualisationDetectors/DataReaderITS.h" +#include "EventVisualisationDetectors/DataInterpreterTPC.h" +#include "EventVisualisationDetectors/DataReaderTPC.h" + +#include "EventVisualisationDetectors/DataReaderJSON.h" + #include "FairLogger.h" #include @@ -37,7 +42,6 @@ #include #include #include -#include using namespace std; namespace o2 @@ -45,7 +49,7 @@ namespace o2 namespace event_visualisation { -void Initializer::setup(const Options options, EventManager::EDataSource defaultDataSource) +void Initializer::setup(EventManager::EDataSource defaultDataSource) { TEnv settings; ConfigurationManager::getInstance().getConfig(settings); @@ -58,8 +62,15 @@ void Initializer::setup(const Options options, EventManager::EDataSource default eventManager.setDataSourceType(defaultDataSource); eventManager.setCdbPath(ocdbStorage); - eventManager.registerDetector(new DataReaderTPC(), new DataInterpreterTPC(), EVisualisationGroup::TPC); - eventManager.registerDetector(new DataReaderITS(), new DataInterpreterITS(), EVisualisationGroup::ITS); + if (Options::Instance()->tpc()) { + eventManager.registerDetector(new DataReaderTPC(new DataInterpreterTPC()), EVisualisationGroup::TPC); + } + if (Options::Instance()->its()) { + eventManager.registerDetector(new DataReaderITS(new DataInterpreterITS()), EVisualisationGroup::ITS); + } + if (Options::Instance()->json()) { + eventManager.registerDetector(new DataReaderJSON(nullptr), EVisualisationGroup::JSON); + } eventManager.setDataSourceType(EventManager::EDataSource::SourceOffline); eventManager.Open(); diff --git a/EventVisualisation/View/src/Options.cxx b/EventVisualisation/View/src/Options.cxx new file mode 100644 index 0000000000000..1b6172d978f2f --- /dev/null +++ b/EventVisualisation/View/src/Options.cxx @@ -0,0 +1,186 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// +/// \file Options.cxx +/// \author Julian Myrcha + +#include "EventVisualisationView/Options.h" +#include "rapidjson/document.h" +#include "rapidjson/stringbuffer.h" +#include "rapidjson/prettywriter.h" +#include "FairLogger.h" +#include +#include +#include +#include + +namespace o2 +{ +namespace event_visualisation +{ + +Options Options::instance; + +std::string Options::printOptions() +{ + static const char* str[2] = {"false", "true"}; + std::stringstream ss; + ss << "fileName : " << this->fileName() << std::endl; + ss << "randomTracks: " << str[this->randomTracks()] << std::endl; + ss << "itc : " << str[this->its()] << std::endl; + ss << "json : " << str[this->json()] << std::endl; + ss << "vsd : " << str[this->vsd()] << std::endl; + ss << "tpc : " << str[this->tpc()] << std::endl; + return ss.str(); +} + +std::string Options::usage() +{ + std::stringstream ss; + ss << "usage:" << std::endl; + ss << "\t" + << "o2eve " << std::endl; + ss << "\t\t" + << "where are any from the following:" << std::endl; + ss << "\t\t" + << "-h this help message" << std::endl; + ss << "\t\t" + << "-d name name of the data folder" << std::endl; + ss << "\t\t" + << "-f name name of the data file" << std::endl; + ss << "\t\t" + << "-i use itc reading from files as a source" << std::endl; + ss << "\t\t" + << "-j use json files as a source" << std::endl; + ss << "\t\t" + << "-o name name of the options file" << std::endl; + ss << "\t\t" + << "-r use random tracks" << std::endl; + ss << "\t\t" + << "-s save options to o2eve.json in current folder" << std::endl; + ss << "\t\t" + << "-t use tpc reading from files as a source" << std::endl; + ss << "\t\t" + << "-v use vsd files as a source" << std::endl; + ss << "\tdefault values are always taken from o2eve.json in current folder if present" << std::endl; + return ss.str(); +} + +bool Options::processCommandLine(int argc, char* argv[]) +{ + int opt; + bool save = false; + std::string optionsFileName = "o2eve.json"; // name with options to use + + // put ':' in the starting of the + // string so that program can + //distinguish between '?' and ':' + while ((opt = getopt(argc, argv, ":d:f:hijo:rsvt")) != -1) { + switch (opt) { + case 'f': + this->mFileName = optarg; + break; + case 'i': + this->mIts = true; + break; + case 'h': + std::cout << usage() << std::endl; + return false; + case 'j': + this->mJSON = true; + break; + case 'o': + optionsFileName = optarg; + break; + case 'r': + this->mRandomTracks = true; + break; + case 's': + save = true; + break; + case 't': + this->mTpc = true; + break; + case 'v': + this->mVsd = true; + break; + case ':': + LOG(ERROR) << "option needs a value: " << char(optopt); + LOG(INFO) << usage(); + return false; + case '?': + LOG(ERROR) << "unknown option: " << char(optopt); + LOG(INFO) << usage(); + return false; + } + } + + // optind is for the extra arguments + // which are not parsed + for (; optind < argc; optind++) { + LOG(ERROR) << "extra arguments: " << argv[optind]; + LOG(INFO) << usage(); + return false; + } + + if (save) { + this->saveToJSON("o2eve.json"); + return false; + } + + return true; +} + +bool Options::saveToJSON(std::string filename) +{ + rapidjson::Value dataFolder; + rapidjson::Value fileName; + rapidjson::Value its(rapidjson::kNumberType); + rapidjson::Value json(rapidjson::kNumberType); + rapidjson::Value randomTracks(rapidjson::kNumberType); + rapidjson::Value tpc(rapidjson::kNumberType); + rapidjson::Value vsd(rapidjson::kNumberType); + + dataFolder.SetString(rapidjson::StringRef(this->dataFolder().c_str())); + fileName.SetString(rapidjson::StringRef(this->fileName().c_str())); + its.SetBool(this->its()); + json.SetBool(this->json()); + randomTracks.SetBool(this->randomTracks()); + tpc.SetBool(this->tpc()); + vsd.SetBool(this->vsd()); + + rapidjson::Document tree(rapidjson::kObjectType); + rapidjson::Document::AllocatorType& allocator = tree.GetAllocator(); + tree.AddMember("dataFolder", dataFolder, allocator); + tree.AddMember("fileName", fileName, allocator); + tree.AddMember("its", its, allocator); + tree.AddMember("json", json, allocator); + tree.AddMember("randomTracks", randomTracks, allocator); + tree.AddMember("tpc", tpc, allocator); + tree.AddMember("vsd", vsd, allocator); + + rapidjson::StringBuffer buffer; + rapidjson::PrettyWriter writer(buffer); + tree.Accept(writer); + + std::ofstream out(filename); + out << buffer.GetString(); + out.close(); + return true; +} + +bool Options::readFromJSON(std::string /*filename*/) +{ + return false; +} + +} // namespace event_visualisation +} // namespace o2 diff --git a/EventVisualisation/View/src/main.cxx b/EventVisualisation/View/src/main.cxx index f9d2c57aaf7d0..d28f3089af12c 100644 --- a/EventVisualisation/View/src/main.cxx +++ b/EventVisualisation/View/src/main.cxx @@ -16,7 +16,9 @@ #include "EventVisualisationView/Initializer.h" #include "EventVisualisationBase/ConfigurationManager.h" + #include "EventVisualisationBase/DataInterpreter.h" +#include "EventVisualisationView/Options.h" #include "FairLogger.h" @@ -25,67 +27,16 @@ #include #include -#include #include using namespace std; using namespace o2::event_visualisation; -std::string printOptions(Options* o) -{ - std::string res; - res.append(std::string("randomTracks: ") + (o->randomTracks ? "true" : "false") + "\n"); - res.append(std::string("vds : ") + (o->vsd ? "true" : "false") + "\n"); - res.append(std::string("itc : ") + (o->itc ? "true" : "false") + "\n"); - return res; -} - -Options* processCommandLine(int argc, char* argv[]) -{ - static Options options; - int opt; - - // put ':' in the starting of the - // string so that program can - //distinguish between '?' and ':' - while ((opt = getopt(argc, argv, ":if:rv")) != -1) { - switch (opt) { - case 'r': - options.randomTracks = true; - break; - case 'i': - options.itc = true; - break; - case 'v': - options.vsd = true; - break; - case 'f': - options.fileName = optarg; - break; - case ':': - printf("option needs a value\n"); - return nullptr; - case '?': - printf("unknown option: %c\n", optopt); - return nullptr; - } - } - - // optind is for the extra arguments - // which are not parsed - for (; optind < argc; optind++) { - printf("extra arguments: %s\n", argv[optind]); - return nullptr; - } - - return &options; -} - int main(int argc, char** argv) { LOG(INFO) << "Welcome in O2 event visualisation tool"; - Options* options = processCommandLine(argc, argv); - if (options == nullptr) { + + if (!Options::Instance()->processCommandLine(argc, argv)) { exit(-1); } @@ -113,7 +64,7 @@ int main(int argc, char** argv) } // Initialize o2 Event Visualisation - Initializer::setup(*options); + Initializer::setup(); // Start the application app->Run(kTRUE); From 83bc982594983a70749780e4ff0e4ec5f9bdb71d Mon Sep 17 00:00:00 2001 From: Ole Schmidt Date: Thu, 22 Apr 2021 09:07:17 +0200 Subject: [PATCH 234/770] Make radial offset static class member --- GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx | 10 +++++----- GPU/GPUTracking/TRDTracking/GPUTRDTracker.h | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx index fcac1fa73cd7c..e6e55326b5190 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx @@ -105,7 +105,7 @@ void* GPUTRDTracker_t::SetPointersTracks(void* base) } template -GPUTRDTracker_t::GPUTRDTracker_t() : mR(nullptr), mIsInitialized(false), mTrkltTransfNeeded(true), mProcessPerTimeFrame(false), mDoImpactAngleHistograms(false), mNAngleHistogramBins(25), mAngleHistogramRange(50), mMemoryPermanent(-1), mMemoryTracklets(-1), mMemoryTracks(-1), mNMaxCollisions(1), mNMaxTracks(0), mNMaxSpacePoints(0), mTracks(nullptr), mNCandidates(1), mNCollisions(1), mNTracks(0), mNEvents(0), mTriggerRecordIndices(nullptr), mTriggerRecordTimes(nullptr), mTracklets(nullptr), mTrackletIndices(nullptr), mMaxThreads(100), mNTracklets(0), mTrackletIndexArray(nullptr), mHypothesis(nullptr), mCandidates(nullptr), mSpacePoints(nullptr), mAngleDiffSums(nullptr), mAngleDiffCounters(nullptr), mTrackletLabels(nullptr), mGeo(nullptr), mRPhiA2(0), mRPhiB(0), mRPhiC2(0), mDyA2(0), mDyB(0), mDyC2(0), mAngleToDyA(0), mAngleToDyB(0), mAngleToDyC(0), mDebugOutput(false), mTimeWindow(.1f), mRadialOffset(-0.1), mMaxEta(0.84f), mExtraRoadY(2.f), mRoadZ(18.f), mZCorrCoefNRC(1.4f), mMCEvent(nullptr), mDebug(new GPUTRDTrackerDebug()) +GPUTRDTracker_t::GPUTRDTracker_t() : mR(nullptr), mIsInitialized(false), mTrkltTransfNeeded(true), mProcessPerTimeFrame(false), mDoImpactAngleHistograms(false), mNAngleHistogramBins(25), mAngleHistogramRange(50), mMemoryPermanent(-1), mMemoryTracklets(-1), mMemoryTracks(-1), mNMaxCollisions(1), mNMaxTracks(0), mNMaxSpacePoints(0), mTracks(nullptr), mNCandidates(1), mNCollisions(1), mNTracks(0), mNEvents(0), mTriggerRecordIndices(nullptr), mTriggerRecordTimes(nullptr), mTracklets(nullptr), mTrackletIndices(nullptr), mMaxThreads(100), mNTracklets(0), mTrackletIndexArray(nullptr), mHypothesis(nullptr), mCandidates(nullptr), mSpacePoints(nullptr), mAngleDiffSums(nullptr), mAngleDiffCounters(nullptr), mTrackletLabels(nullptr), mGeo(nullptr), mRPhiA2(0), mRPhiB(0), mRPhiC2(0), mDyA2(0), mDyB(0), mDyC2(0), mAngleToDyA(0), mAngleToDyB(0), mAngleToDyC(0), mDebugOutput(false), mTimeWindow(.1f), mMaxEta(0.84f), mExtraRoadY(2.f), mRoadZ(18.f), mZCorrCoefNRC(1.4f), mMCEvent(nullptr), mDebug(new GPUTRDTrackerDebug()) { //-------------------------------------------------------------------- // Default constructor @@ -579,9 +579,9 @@ GPUd() bool GPUTRDTracker_t::ConvertTrkltToSpacePoint(const GPUTRD } const GPUTRDpadPlane* pp = geo.GetPadPlane(det); int trkltZbin = trklt.GetZbin(); - My_Float xTrkltDet[3] = {0.f}; // trklt position in chamber coordinates - My_Float xTrkltSec[3] = {0.f}; // trklt position in sector coordinates - xTrkltDet[0] = geo.AnodePos() - 0.1f; // mRadialOffset = -0.1f is fix + My_Float xTrkltDet[3] = {0.f}; // trklt position in chamber coordinates + My_Float xTrkltSec[3] = {0.f}; // trklt position in sector coordinates + xTrkltDet[0] = geo.AnodePos() - sRadialOffset; xTrkltDet[1] = trklt.GetY(); xTrkltDet[2] = pp->GetRowPos(trkltZbin) - pp->GetRowSize(trkltZbin) / 2.f - pp->GetRowPos(pp->GetNrows() / 2); matrix->LocalToMaster(xTrkltDet, xTrkltSec); @@ -633,7 +633,7 @@ GPUd() bool GPUTRDTracker_t::CalculateSpacePoints(int iCollision) int trkltZbin = mTracklets[trkltIdxGlb].GetZbin(); My_Float xTrkltDet[3] = {0.f}; // trklt position in chamber coordinates My_Float xTrkltSec[3] = {0.f}; // trklt position in sector coordinates - xTrkltDet[0] = mGeo->AnodePos() + mRadialOffset; + xTrkltDet[0] = mGeo->AnodePos() + sRadialOffset; xTrkltDet[1] = mTracklets[trkltIdxGlb].GetY(); xTrkltDet[2] = pp->GetRowPos(trkltZbin) - pp->GetRowSize(trkltZbin) / 2.f - pp->GetRowPos(pp->GetNrows() / 2); //GPUInfo("Space point local %i: x=%f, y=%f, z=%f", trkltIdxGlb, xTrkltDet[0], xTrkltDet[1], xTrkltDet[2]); diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h index fd9b5609f875f..1c022d735c51c 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h @@ -223,7 +223,7 @@ class GPUTRDTracker_t : public GPUProcessor /// ---- end error parametrization ---- bool mDebugOutput; // store debug output float mTimeWindow; // max. deviation of the ITS-TPC track time w.r.t. TRD trigger record time stamp (in us, default is 100 ns) - float mRadialOffset; // due to mis-calibration of t0 + static CONSTEXPR float sRadialOffset GPUCA_CPP11_INIT(= -0.1f); // due to (possible) mis-calibration of t0 -> will become obsolete when tracklet conversion is done outside of the tracker float mMaxEta; // TPC tracks with higher eta are ignored float mExtraRoadY; // addition to search road in r-phi to account for not exact radial match of tracklets and tracks in first iteration float mRoadZ; // in z, a constant search road is used From 482a0e7c44e611d6ac4cd63f294faf567cbadb34 Mon Sep 17 00:00:00 2001 From: Laurent Aphecetche Date: Fri, 23 Apr 2021 08:35:39 +0200 Subject: [PATCH 235/770] [CMake] Fix CMP0115 warnings with CMake 3.20 (#5992) > cmake --help-policy CMP0115 CMP0115 ------- Source file extensions must be explicit. In CMake 3.19 and below, if a source file could not be found by the name specified, it would append a list of known extensions to the name to see if the file with the extension could be found. For example, this would allow the user to run: add_executable(exe main) and put ``main.c`` in the executable without specifying the extension. Starting in CMake 3.20, CMake prefers all source files to have their extensions explicitly listed: add_executable(exe main.c) The ``OLD`` behavior for this policy is to implicitly append known extensions to source files if they can't be found. The ``NEW`` behavior of this policy is to not append known extensions and require them to be explicit. This policy was introduced in CMake version 3.20. CMake version 3.20.1 warns when the policy is not set and uses ``OLD`` behavior. Use the ``cmake_policy()`` command to set it to ``OLD`` or ``NEW`` explicitly. .. note:: The ``OLD`` behavior of a policy is ``deprecated by definition`` and may be removed in a future version of CMake. --- Analysis/Tasks/PWGLF/CMakeLists.txt | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Analysis/Tasks/PWGLF/CMakeLists.txt b/Analysis/Tasks/PWGLF/CMakeLists.txt index 1bc5edc4eea39..3103556034c03 100644 --- a/Analysis/Tasks/PWGLF/CMakeLists.txt +++ b/Analysis/Tasks/PWGLF/CMakeLists.txt @@ -59,32 +59,32 @@ o2_add_dpl_workflow(nuclei-spectra COMPONENT_NAME Analysis) o2_add_dpl_workflow(lambdakzerobuilder - SOURCES lambdakzerobuilder + SOURCES lambdakzerobuilder.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore O2::DetectorsVertexing COMPONENT_NAME Analysis) o2_add_dpl_workflow(lambdakzeroanalysis - SOURCES lambdakzeroanalysis + SOURCES lambdakzeroanalysis.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore O2::DetectorsVertexing COMPONENT_NAME Analysis) o2_add_dpl_workflow(lambdakzerofinder - SOURCES lambdakzerofinder + SOURCES lambdakzerofinder.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore O2::DetectorsVertexing COMPONENT_NAME Analysis) o2_add_dpl_workflow(cascadebuilder - SOURCES cascadebuilder + SOURCES cascadebuilder.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore O2::DetectorsVertexing COMPONENT_NAME Analysis) o2_add_dpl_workflow(cascadeanalysis - SOURCES cascadeanalysis + SOURCES cascadeanalysis.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore O2::DetectorsVertexing COMPONENT_NAME Analysis) o2_add_dpl_workflow(cascadefinder - SOURCES cascadefinder + SOURCES cascadefinder.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore O2::DetectorsVertexing COMPONENT_NAME Analysis) From 0b46699ac460408ec8b31d8909dd4887d63f393c Mon Sep 17 00:00:00 2001 From: Matteo Concas Date: Fri, 23 Apr 2021 11:25:18 +0200 Subject: [PATCH 236/770] Revert "Use functor to check if we trick Clang13" * Revert "Use functor to check if we trick Clang13" This reverts commit 3a3a4c4e4526a7b31b891fade442fecb17764622. * Revert "GPU: test compatibility of SMatrixGPU OpenCL2.0" This reverts commit 3a9df5e621e5e0874dc22bd24d11cac0c80cb64b. * Include SMatrixGPU in OpenCL compilation --- Common/MathUtils/include/MathUtils/Cartesian.h | 2 +- Common/MathUtils/include/MathUtils/SMatrixGPU.h | 15 +++++---------- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/Common/MathUtils/include/MathUtils/Cartesian.h b/Common/MathUtils/include/MathUtils/Cartesian.h index 6b71b126a2190..ef51fa4a9203b 100644 --- a/Common/MathUtils/include/MathUtils/Cartesian.h +++ b/Common/MathUtils/include/MathUtils/Cartesian.h @@ -33,8 +33,8 @@ #include "GPUCommonMath.h" #include "CartesianGPU.h" #include "SMatrixGPU.h" -#endif +#endif #include "GPUROOTCartesianFwd.h" #include "GPUROOTSMatrixFwd.h" diff --git a/Common/MathUtils/include/MathUtils/SMatrixGPU.h b/Common/MathUtils/include/MathUtils/SMatrixGPU.h index 703dee12fc579..bbadb828b6804 100644 --- a/Common/MathUtils/include/MathUtils/SMatrixGPU.h +++ b/Common/MathUtils/include/MathUtils/SMatrixGPU.h @@ -259,14 +259,6 @@ struct meta_matrix_dot<0> { namespace row_offsets_utils { -template -struct proxy_offset { - static constexpr int off0(int i) { return i == 0 ? 0 : off0(i - 1) + i; } - static constexpr int off2(int i, int j) { return j < i ? off0(i) + j : off0(j) + i; } - static constexpr int off1(int i) { return off2(i / D, i % D); } - int operator()(int i) const { return off1(i); } -}; - template struct indices { }; @@ -361,10 +353,13 @@ class MatRepSymGPU kSize = D * (D + 1) / 2 // rows*columns }; + static constexpr int off0(int i) { return i == 0 ? 0 : off0(i - 1) + i; } + static constexpr int off2(int i, int j) { return j < i ? off0(i) + j : off0(j) + i; } + static constexpr int off1(int i) { return off2(i / D, i % D); } + static GPUdi() int off(int i) { - row_offsets_utils::proxy_offset proxy; - static constexpr auto v = row_offsets_utils::make(proxy); + static constexpr auto v = row_offsets_utils::make(off1); return v[i]; } From 4af1ce2a8be01608c869719515a8806c7f23b3bf Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 23 Apr 2021 12:00:19 +0200 Subject: [PATCH 237/770] Porting reconstruction code --- .../ZDC/include/DataFormatsZDC/RecEvent.h | 35 +- .../ZDC/base/include/ZDCBase/Constants.h | 18 + Detectors/ZDC/reconstruction/CMakeLists.txt | 4 + .../include/ZDCReconstruction/DigiReco.h | 63 +++ .../include/ZDCReconstruction/RecoParamZDC.h | 50 ++ .../ZDCReconstruction/ZDCIntegrationParam.h | 42 ++ .../include/ZDCReconstruction/ZDCTDCParam.h | 40 ++ Detectors/ZDC/reconstruction/src/DigiReco.cxx | 429 ++++++++++++++++++ .../ZDC/reconstruction/src/RecoParamZDC.cxx | 24 + .../src/ZDCIntegrationParam.cxx | 49 ++ .../ZDC/reconstruction/src/ZDCTDCParam.cxx | 47 ++ 11 files changed, 790 insertions(+), 11 deletions(-) create mode 100644 Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h create mode 100644 Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h create mode 100644 Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCIntegrationParam.h create mode 100644 Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h create mode 100644 Detectors/ZDC/reconstruction/src/DigiReco.cxx create mode 100644 Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx create mode 100644 Detectors/ZDC/reconstruction/src/ZDCIntegrationParam.cxx create mode 100644 Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h index 1b70cb64e731b..a9350727c74d0 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h @@ -27,18 +27,31 @@ namespace zdc { struct RecEvent { - using TDCChannel = std::array; - + //using TDCChannel = std::array; + //using TDCAmplitude = std::array; + //using TDCChannel = std::vector; + //using TDCAmplitude = std::vector; o2::InteractionRecord ir; - uint32_t flags; /// reconstruction flags - std::array energyZEM; /// signal in the electromagnetic ZDCs - std::array energyZNA; /// reco E in 5 ZNA sectors + sum - std::array energyZNC; /// reco E in 5 ZNC sectors + sum - std::array energyZPA; /// reco E in 5 ZPA sectors + sum - std::array energyZPC; /// reco E in 5 ZPC sectors + sum - math_utils::Point2D centroidZNA; /// centroid coordinates for ZNA - math_utils::Point2D centroidZNC; /// centroid coordinates for ZNC - std::array tdcChannels; /// At most MaxTDCValues Values in ns per TDC channel + uint32_t flags; /// reconstruction flags +// std::array energyZEM; /// signal in the electromagnetic ZDCs +// std::array energyZNA; /// reco E in 5 ZNA sectors + sum +// std::array energyZNC; /// reco E in 5 ZNC sectors + sum +// std::array energyZPA; /// reco E in 5 ZPA sectors + sum +// std::array energyZPC; /// reco E in 5 ZPC sectors + sum + float energyZEM[NChannelsZEM]; /// signal in the electromagnetic ZDCs + float energyZNA[NChannelsZN]; /// reco E in 5 ZNA sectors + sum + float energyZNC[NChannelsZN]; /// reco E in 5 ZNC sectors + sum + float energyZPA[NChannelsZP]; /// reco E in 5 ZPA sectors + sum + float energyZPC[NChannelsZP]; /// reco E in 5 ZPC sectors + sum + math_utils::Point2D centroidZNA; /// centroid coordinates for ZNA + math_utils::Point2D centroidZNC; /// centroid coordinates for ZNC + //std::array tdcChannels; /// At most MaxTDCValues Values in ns per TDC channel + //std::array tdcAmplitudes; /// At most MaxTDCValues Values in ns per TDC channel + int16_t tdcChannels[NTDCChannels][MaxTDCValues]; /// TdcChannels + float tdcAmplitudes[NTDCChannels][MaxTDCValues]; /// TdcAmplitudes + std::array pattern; /// Pattern of TDC + Short_t fired[NTDCChannels][NTimeBinsPerBC] = {0}; /// Position at which the trigger algorithm is fired + float inter[NTDCChannels][NTimeBinsPerBC * TSN] = {0}; /// Interpolated samples void print() const; diff --git a/Detectors/ZDC/base/include/ZDCBase/Constants.h b/Detectors/ZDC/base/include/ZDCBase/Constants.h index c834344b2d071..b773bfda76383 100644 --- a/Detectors/ZDC/base/include/ZDCBase/Constants.h +++ b/Detectors/ZDC/base/include/ZDCBase/Constants.h @@ -63,6 +63,11 @@ constexpr int ADCMin = -2048, ADCMax = 2047, ADCRange = 4096; // 12 bit ADC constexpr int MaxTDCValues = 5; // max number of TDC values to store in reconstructed event constexpr int NTDCChannels = 10; // max number of TDC values to store in reconstructed event +// Parameters of interpolating function +constexpr int TSL = 6; // number of zeros on the right (and on the left) of central peak +constexpr int TSN = 200; // Number of interpolated points between each pair = TSN-1 +constexpr int TSNS = 96; // Number of interpolated points per ns +constexpr int NTS = 2 * TSL * TSN + 1; //Tapered sinc function array size enum TDCChannelID { TDCZNAC, TDCZNAS, @@ -155,6 +160,19 @@ constexpr std::string_view ChannelNames[] = { "ZPC4", "ZPCS"}; +const int TDCSignal[NTDCChannels] = { + IdZNAC, // TDCZNAC + IdZNASum, // TDCZNAS + IdZPAC, // TDCZPAC + IdZPASum, // TDCZPAS + IdZEM1, // TDCZEM1 + IdZEM2, // TDCZEM2 + IdZNCC, // TDCZNCC + IdZNCSum, // TDCZNCS + IdZPCC, // TDCZPCC + IdZPCSum // TDCZPCS +}; + // paths to CCDB objects // TODO: eventually these paths should be retrieved from NameConfigurator class // TODO: we would better use "constexpr string_view" here, but it makes sense only if diff --git a/Detectors/ZDC/reconstruction/CMakeLists.txt b/Detectors/ZDC/reconstruction/CMakeLists.txt index cf9a288d2bc57..cde859dd602ce 100644 --- a/Detectors/ZDC/reconstruction/CMakeLists.txt +++ b/Detectors/ZDC/reconstruction/CMakeLists.txt @@ -11,8 +11,12 @@ o2_add_library(ZDCReconstruction SOURCES src/CTFCoder.cxx src/CTFHelper.cxx + src/DigiReco.cxx + src/RecoParamZDC.cxx + src/ZDCTDCParam.cxx PUBLIC_LINK_LIBRARIES O2::ZDCBase O2::DataFormatsZDC + O2::ZDCSimulation O2::DetectorsRaw AliceO2::InfoLogger O2::rANS diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h new file mode 100644 index 0000000000000..14c342387a8f2 --- /dev/null +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h @@ -0,0 +1,63 @@ +#include +#include +#include +#include "ZDCBase/Constants.h" +#include "ZDCSimulation/ZDCSimParam.h" +#include "ZDCReconstruction/RecoParamZDC.h" +#include "ZDCReconstruction/ZDCTDCParam.h" +#include "ZDCReconstruction/ZDCIntegrationParam.h" +#include "ZDCBase/ModuleConfig.h" +#include "DataFormatsZDC/BCData.h" +#include "DataFormatsZDC/ChannelData.h" +#include "DataFormatsZDC/OrbitData.h" +#include "DataFormatsZDC/RecEvent.h" + +#ifndef ALICEO2_ZDC_DIGI_RECO_H +#define ALICEO2_ZDC_DIGI_RECO_H +namespace o2 +{ +namespace zdc +{ +class DigiReco +{ + public: + DigiReco() = default; + void init(); + int process(const std::vector *orbitdata, const std::vector *bcdata, std::vector *chdata); + int write(); + void setVerbosity(int v) + { + mVerbosity = v; + } + int getVerbosity() const { return mVerbosity; } + + void setModuleConfig(const ModuleConfig* moduleConfig) { mModuleConfig = moduleConfig; }; + const ModuleConfig* getModuleConfig() { return mModuleConfig; }; + void setTDCParam(const ZDCTDCParam* param) { mTDCParam = param; }; + const ZDCTDCParam* getTDCParam() { return mTDCParam; }; + void setIntegrationParam(const ZDCIntegrationParam* param) { mIntParam = param; }; + const ZDCIntegrationParam* getIntegrationParam() { return mIntParam; }; + const ModuleConfig* mModuleConfig = nullptr; /// Trigger/readout configuration object + + private: + int reconstruct(int seq_beg, int seq_end); + bool mIsContinuous = true; /// continuous (self-triggered) or externally-triggered readout + int mNBCAHead = 0; /// when storing triggered BC, store also mNBCAHead BCs + const ZDCTDCParam* mTDCParam = nullptr; /// TDC calibration object + const ZDCIntegrationParam* mIntParam = nullptr; /// Configuration of integration + bool mVerbosity; + Double_t mTS[NTS]; /// Tapered sinc function + TFile* mDbg = nullptr; /// Debug output + TTree* mTDbg = nullptr; /// Debug tree + const std::vector *mOrbitData; /// Reconstructed data + const std::vector *mBCData; /// BC info + const std::vector *mChData; /// Payload + std::vector mReco; /// Reconstructed data + std::map mOrbit; /// Information about orbit + static constexpr int mNSB = TSN * NTimeBinsPerBC; /// Total number of interpolated points per bunch crossing + RecEvent mRec; /// Debug reconstruction event + int mNBC = 0; +}; +} // namespace zdc +} // namespace o2 +#endif diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h new file mode 100644 index 0000000000000..1bb44d1de0371 --- /dev/null +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h @@ -0,0 +1,50 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_ZDC_RECOPARAMZDC_H_ +#define O2_ZDC_RECOPARAMZDC_H_ + +#include +#include "CommonUtils/ConfigurableParam.h" +#include "CommonUtils/ConfigurableParamHelper.h" +#include "ZDCBase/Constants.h" + +/// \file RecoParamZDC.h +/// \brief ZDC reconstruction parameters +/// \author P. Cortese + +namespace o2 +{ +namespace zdc +{ +// parameters of ZDC reconstruction + +struct RecoParamZDC : public o2::conf::ConfigurableParamHelper { + Int_t tsh[NTDCChannels] = {4, 4, 4, 4, 4, 4, 4, 4, 4, 4}; // Trigger shift + Int_t tth[NTDCChannels] = {8, 8, 8, 8, 8, 8, 8, 8, 8, 8}; // Trigger threshold + Int_t tmod[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of TDC channel in raw data + Int_t tch[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of TDC channel in raw data + Int_t amod[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of ADC channel in raw data + Int_t ach[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of ADC channel in raw data + float tdc_shift[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Correction of TDC position (0-25 ns, units of ~10 ps) + float tdc_search[NTDCChannels] = {250, 250, 250, 250, 250, 250, 250, 250, 250, 250}; // Search zone for a TDC signal ideally 2.5 ns (units of ~10 ps) + Int_t beg_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Start integration - signal + Int_t end_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // End integration - signal + Int_t beg_ped_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Start integration - pedestal + Int_t end_ped_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // End integration - pedestal + std::array bitset = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Set bits in coincidence + public: + void setBit(uint32_t ibit, bool val = true); + O2ParamDef(RecoParamZDC, "RecoParamZDC"); +}; +} // namespace zdc +} // namespace o2 + +#endif diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCIntegrationParam.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCIntegrationParam.h new file mode 100644 index 0000000000000..5e62533d37a63 --- /dev/null +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCIntegrationParam.h @@ -0,0 +1,42 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_ZDC_INTEGRATIONPARAM_H_ +#define O2_ZDC_INTEGRATIONPARAM_H_ + +#include "ZDCBase/Constants.h" +#include +#include + +/// \file ZDCIntegrationParam.h +/// \brief Parameters to configure integration +/// \author P. Cortese + +namespace o2 +{ +namespace zdc +{ +// parameters of ZDC reconstruction + +struct ZDCIntegrationParam { + public: + Int_t beg_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Start integration - signal + Int_t end_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // End integration - signal + Int_t beg_ped_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Start integration - pedestal + Int_t end_ped_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // End integration - pedestal + void setIntegration(uint32_t ich, int beg, int end, int beg_ped, int end_ped); + void print(); + + ClassDefNV(ZDCIntegrationParam, 1); +}; +} // namespace zdc +} // namespace o2 + +#endif diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h new file mode 100644 index 0000000000000..312c949e252e9 --- /dev/null +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h @@ -0,0 +1,40 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_ZDC_TDCPARAM_H_ +#define O2_ZDC_TDCPARAM_H_ + +#include "ZDCBase/Constants.h" +#include +#include + +/// \file ZDCTDCParam.h +/// \brief Parameters to correct TDCs +/// \author P. Cortese + +namespace o2 +{ +namespace zdc +{ +// parameters of ZDC reconstruction + +struct ZDCTDCParam { + float tdc_shift[NTDCChannels] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Correction of TDC position (ns) + public: + void setShift(uint32_t ich, float val); + float getShift(uint32_t ich) const; + void print(); + + ClassDefNV(ZDCTDCParam, 1); +}; +} // namespace zdc +} // namespace o2 + +#endif diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx new file mode 100644 index 0000000000000..2ae7bfb4a4ff5 --- /dev/null +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -0,0 +1,429 @@ +#include +#include "FairLogger.h" +#include "ZDCReconstruction/DigiReco.h" +namespace o2 +{ +namespace zdc +{ + +void DigiReco::init(){ + // Load configuration parameters + auto& sopt = ZDCSimParam::Instance(); + mIsContinuous = sopt.continuous; + mNBCAHead = mIsContinuous ? sopt.nBCAheadCont : sopt.nBCAheadTrig; + + if (!mModuleConfig) { + LOG(FATAL) << "Missing ModuleConfig configuration object"; + return; + } + + // Prepare tapered sinc function + // tsc/TSN =3.75 (~ 4) and TSL*TSN*sqrt(2)/tsc >> 1 (n. of sigma) + const Double_t tsc = 750; + Int_t n = TSL * TSN; + for (Int_t tsi = 0; tsi <= n; tsi++) { + Double_t arg1 = TMath::Pi() * Double_t(tsi) / Double_t(TSN); + Double_t fs = 1; + if (arg1 != 0) + fs = TMath::Sin(arg1) / arg1; + Double_t arg2 = Double_t(tsi) / tsc; + Double_t fg = TMath::Exp(-arg2 * arg2); + mTS[n + tsi] = fs * fg; + mTS[n - tsi] = mTS[n + tsi]; // Function is even + } + + // Open debug file + mDbg = new TFile("ZDCReco.root", "recreate"); + mTDbg = new TTree("zdcr", "ZDCReco"); + mTDbg->Branch("zdcr", "RecEvent", &mRec); + // Update reconstruction parameters + //auto& ropt=RecoParamZDC::Instance(); + o2::zdc::RecoParamZDC& ropt = const_cast(RecoParamZDC::Instance()); + + // Fill maps + for (Int_t itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { + // If the reconstruction parameters were not manually set + if (ropt.tmod[itdc] < 0 || ropt.tch[itdc] < 0) { + Int_t isig = TDCSignal[itdc]; + for (Int_t im = 0; im < NModules; im++) { + for (UInt_t ic = 0; ic < NChPerModule; ic++) { + if (mModuleConfig->modules[im].channelID[ic] == isig && mModuleConfig->modules[im].readChannel[ic]) { + //ropt.updateFromString(TString::Format("RecoParamZDC.tmod[%d]=%d;",itdc,im)); + //ropt.updateFromString(TString::Format("RecoParamZDC.tch[%d]=%d;",itdc,ic)); + ropt.tmod[itdc] = im; + ropt.tch[itdc] = ic; + goto next_itdc; + } + } + } + } + next_itdc:; + LOG(INFO) << "TDC " << itdc << "(" << ChannelNames[TDCSignal[itdc]] << ")" << " mod " << ropt.tmod[itdc] << " ch " << ropt.tch[itdc]; + } + + // Fill maps channel maps for integration + for (Int_t ich = 0; ich < NChannels; ich++) { + // If the reconstruction parameters were not manually set + if (ropt.amod[ich] < 0 || ropt.ach[ich] < 0) { + for (Int_t im = 0; im < NModules; im++) { + for (UInt_t ic = 0; ic < NChPerModule; ic++) { + if (mModuleConfig->modules[im].channelID[ic] == ich && mModuleConfig->modules[im].readChannel[ic]) { + ropt.amod[ich] = im; + ropt.ach[ich] = ic; + goto next_ich; + } + } + } + } + next_ich:; + LOG(INFO) << "ADC " << ich << "(" << ChannelNames[ich] << ") mod " << ropt.amod[ich] << " ch " << ropt.ach[ich]; + } + + // Integration ranges + for (Int_t ich = 0; ich < NChannels; ich++) { + // If the reconstruction parameters were not manually set + if (ropt.beg_int[ich] < 0 || ropt.end_int[ich] < 0) { + if (!mIntParam) { + LOG(ERROR) << "Integration for signal " << ich << " missing configuration object and no manual override"; + } else { + ropt.beg_int[ich] = mIntParam->beg_int[ich]; + ropt.end_int[ich] = mIntParam->end_int[ich]; + } + } + if (ropt.beg_ped_int[ich] < 0 || ropt.end_ped_int[ich] < 0) { + if (!mIntParam) { + LOG(ERROR) << "Integration for pedestal " << ich << " missing configuration object and no manual override"; + } else { + ropt.beg_ped_int[ich] = mIntParam->beg_ped_int[ich]; + ropt.end_ped_int[ich] = mIntParam->end_ped_int[ich]; + } + } + LOG(INFO) << ChannelNames[ich] << " integration: signal=[" << ropt.beg_int[ich] << "-" << ropt.end_int[ich] << "] pedestal=[" << ropt.beg_ped_int[ich] << "-" << ropt.end_ped_int[ich] <<"]"; + } +} + +int DigiReco::process(const std::vector *orbitdata, const std::vector *bcdata, std::vector *chdata){ + // We assume that vectors contain data from a full time frame + mOrbitData=orbitdata; + mBCData=bcdata; + mChData=chdata; + + const std::vector &OrbitData=*orbitdata; + const std::vector &BCData=*bcdata; + const std::vector &ChData=*chdata; + + // Initialization of lookup structure for pedestals + mOrbit.clear(); + int norb=OrbitData.size(); + for(Int_t iorb=0; iorb1){ + // Detected a gap + reconstruct(seq_beg, seq_end); + seq_beg=ibc; + seq_end=ibc; + }else if(ibc==(mNBC-1)){ + // Last bunch + seq_end=ibc; + reconstruct(seq_beg, seq_end); + seq_beg=mNBC; + seq_end=mNBC; + }else{ + // Look for another bunch + seq_end=ibc; + } + } + +/* + +std::map::iterator it; + + mymap['a']=50; + mymap['b']=100; + mymap['c']=150; + mymap['d']=200; + + it = mymap.find('b'); + if (it != mymap.end()) + mymap.erase (it); + */ + return 0; +} + +int DigiReco::reconstruct(int seq_beg, int seq_end){ + // Process consecutive BCs + if (seq_beg == seq_end) { + LOG(INFO) << "Lonely bunch " << mReco[seq_beg].ir.orbit << "." << mReco[seq_beg].ir.bc; + return 0; + } + LOG(INFO) << "Processing " << mReco[seq_beg].ir.orbit << "." << mReco[seq_beg].ir.bc << " - " << mReco[seq_end].ir.orbit << "." << mReco[seq_end].ir.bc; + auto& ropt = ZDCRecoParam::Instance(); + /* + // Apply differential discrimination with triple condition + for (Int_t itdc = 0; itdc < NTDCChannels; itdc++) { + Int_t im = ropt.tmod[itdc]; + Int_t ic = ropt.tch[itdc]; + // Check if the TDC channel is connected + if (im >= 0 && ic >= 0) { + // Check if channel has valid data for consecutive bunches in current bunch range + // N.B. there are events recorded from ibeg-iend but we are not sure if it is the + // case for every TDC channel + int istart = -1, istop = -1; + // Loop allows for gaps in the data sequence for each TDC channel + for (int ibun = ibeg; ibun <= iend; ibun++) { + auto& ch = mData[ibun].data[im][ic]; + if (ch.f.fixed_0 == Id_w0 && ch.f.fixed_1 == Id_w1 && ch.f.fixed_2 == Id_w2) { + if (istart < 0) { + istart = ibun; + } + istop = ibun; + } else { + // A gap is detected gap + if (istart >= 0 && (istop - istart) > 0) { + // Need data for at least two consecutive bunch crossings + processTrigger(itdc, istart, istop); + } + istart = -1; + istop = -1; + } + } + // Check if there are consecutive bunch crossings at the end of group + if (istart >= 0 && (istop - istart) > 0) { + processTrigger(itdc, istart, istop); + } + } + } + // Reconstruct integrated charges and fill output tree + // TODO: compare average pedestal with estimation from current event + // TODO: failover in case of discrepancy + for (Int_t ibun = ibeg; ibun <= iend; ibun++) { + mRec = mReco[ibun]; + for (Int_t itdc = 0; itdc < NTDCChannels; itdc++) { + printf("%d %u.%u %d ", ibun, mReco[ibun].ir.orbit, mReco[ibun].ir.bc, itdc); + for (Int_t isam = 0; isam < NTimeBinsPerBC; isam++) { + printf("%d", mRec.fired[itdc][isam]); + } + printf("\n"); + for (Int_t i = 0; i < MaxTDCValues; i++) { + mRec.TdcChannels[itdc][i] = kMinShort; + mRec.TdcAmplitudes[itdc][i] = -999; + } + Int_t i = 0; + mRec.pattern[itdc] = 0; + for (int16_t val : mReco[ibun].tdcChannels[itdc]) { + LOG(INFO) << "TdcChannels[" << itdc << "][" << i << "]=" << val; + mRec.TdcChannels[itdc][i] = val; + // There is a TDC value in the search zone around main-main position + if (std::abs(mRec.TdcChannels[itdc][i]) < ropt.tdc_search[itdc]) { + mRec.pattern[itdc] = 1; + } + i++; + } + i = 0; + for (float val : mReco[ibun].tdcAmplitudes[itdc]) { + //mRec.tdcAmplitudes[itdc].push_back(val); + //LOG(INFO) << itdc << " valt=" << val; + LOG(INFO) << "TdcAmplitudes[" << itdc << "][" << i << "]=" << val; + mRec.TdcAmplitudes[itdc][i] = val; + i++; + } + } + printf("%d PATTERN: ", ibun); + for (Int_t itdc = 0; itdc < NTDCChannels; itdc++) { + printf("%d", mRec.pattern[itdc]); + } + printf("\n"); + + // Check if coincidence of common PM and sum of towers is satisfied + bool fired[NChannels] = {0}; + // Side A + if ((mRec.pattern[TDCZNAC] || ropt.bitset[TDCZNAC]) && (mRec.pattern[TDCZNAS] || ropt.bitset[TDCZNAS])) { + for (Int_t ich = IdZNAC; ich <= IdZNASum; ich++) { + fired[ich] = true; + } + } + if ((mRec.pattern[TDCZPAC] || ropt.bitset[TDCZPAC]) && (mRec.pattern[TDCZPAS] || ropt.bitset[TDCZPAS])) { + for (Int_t ich = IdZPAC; ich <= IdZPASum; ich++) { + fired[ich] = true; + } + } + // ZEM1 and ZEM2 are not in coincidence + fired[IdZEM1] = mRec.pattern[TDCZEM1]; + fired[IdZEM2] = mRec.pattern[TDCZEM2]; + // Side C + if ((mRec.pattern[TDCZNCC] || ropt.bitset[TDCZNCC]) && (mRec.pattern[TDCZNCS] || ropt.bitset[TDCZNCS])) { + for (Int_t ich = IdZNCC; ich <= IdZNCSum; ich++) { + fired[ich] = true; + } + } + if ((mRec.pattern[TDCZPCC] || ropt.bitset[TDCZPCC]) && (mRec.pattern[TDCZPCS] || ropt.bitset[TDCZPCS])) { + for (Int_t ich = IdZPCC; ich <= IdZPCSum; ich++) { + fired[ich] = true; + } + } + + // Access samples from raw data + for (Int_t i = 0; i < NChannelsZEM; i++) { + mRec.energyZEM[i] = -999; + } + for (Int_t i = 0; i < NChannelsZN; i++) { + mRec.energyZNA[i] = -999; + } + for (Int_t i = 0; i < NChannelsZN; i++) { + mRec.energyZNC[i] = -999; + } + for (Int_t i = 0; i < NChannelsZP; i++) { + mRec.energyZPA[i] = -999; + } + for (Int_t i = 0; i < NChannelsZP; i++) { + mRec.energyZPC[i] = -999; + } + auto& data = mData[ibun]; + printf("%d FIRED: ", ibun); + for (Int_t ich = 0; ich < NChannels; ich++) { + printf("%d", fired[ich]); + } + printf("\n"); + for (Int_t ich = 0; ich < NChannels; ich++) { + // Check if the corresponding TDC is fired + if (fired[ich]) { + // Check if channels are present in payload + Int_t im = ropt.amod[ich]; + Int_t ic = ropt.ach[ich]; + // Check if the ADC channel is connected + if (im >= 0 && ic >= 0) { + // Check if the ADC has payload + auto& ch = data.data[im][ic]; + if (ch.f.fixed_0 == Id_w0 && ch.f.fixed_1 == Id_w1 && ch.f.fixed_2 == Id_w2) { + float sum = 0; + for (Int_t is = ropt.beg_int[ich]; is <= ropt.end_int[ich]; is++) { + // TODO: fallback if offset is missing + // TODO: fallback if channel has pile-up + sum += (mOffset[im][ic] - float(data.s[im][ic][is])); + } + printf("CH %d %s: %f\n", ich, ChannelNames[ich].data(), sum); + if (ich == IdZNAC) { + mRec.energyZNA[0] = sum; + } + if (ich == IdZNA1) { + mRec.energyZNA[1] = sum; + } + if (ich == IdZNA2) { + mRec.energyZNA[2] = sum; + } + if (ich == IdZNA3) { + mRec.energyZNA[3] = sum; + } + if (ich == IdZNA4) { + mRec.energyZNA[4] = sum; + } + if (ich == IdZNASum) { + mRec.energyZNA[5] = sum; + } + if (ich == IdZPAC) { + mRec.energyZPA[0] = sum; + } + if (ich == IdZPA1) { + mRec.energyZPA[1] = sum; + } + if (ich == IdZPA2) { + mRec.energyZPA[2] = sum; + } + if (ich == IdZPA3) { + mRec.energyZPA[3] = sum; + } + if (ich == IdZPA4) { + mRec.energyZPA[4] = sum; + } + if (ich == IdZPASum) { + mRec.energyZPA[5] = sum; + } + if (ich == IdZEM1) { + mRec.energyZEM[0] = sum; + } + if (ich == IdZEM2) { + mRec.energyZEM[1] = sum; + } + if (ich == IdZNCC) { + mRec.energyZNC[0] = sum; + } + if (ich == IdZNC1) { + mRec.energyZNC[1] = sum; + } + if (ich == IdZNC2) { + mRec.energyZNC[2] = sum; + } + if (ich == IdZNC3) { + mRec.energyZNC[3] = sum; + } + if (ich == IdZNC4) { + mRec.energyZNC[4] = sum; + } + if (ich == IdZNCSum) { + mRec.energyZNC[5] = sum; + } + if (ich == IdZPCC) { + mRec.energyZPC[0] = sum; + } + if (ich == IdZPC1) { + mRec.energyZPC[1] = sum; + } + if (ich == IdZPC2) { + mRec.energyZPC[2] = sum; + } + if (ich == IdZPC3) { + mRec.energyZPC[3] = sum; + } + if (ich == IdZPC4) { + mRec.energyZPC[4] = sum; + } + if (ich == IdZPCSum) { + mRec.energyZPC[5] = sum; + } + } + } + } + } + // TODO: energy calibration + mTDbg->Fill(); + } + */ +} + +} // namespace zdc +} // namespace o2 diff --git a/Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx b/Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx new file mode 100644 index 0000000000000..9c1c61ee98163 --- /dev/null +++ b/Detectors/ZDC/reconstruction/src/RecoParamZDC.cxx @@ -0,0 +1,24 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "FairLogger.h" +#include "ZDCReconstruction/RecoParamZDC.h" + +using namespace o2::zdc; + +O2ParamImpl(RecoParamZDC); + +void RecoParamZDC::setBit(uint32_t ibit, bool val){ + if(ibit>=0 && ibit= 0 && ich < NChannels) { + if (beg < 0 || beg >= NTimeBinsPerBC) { + LOG(FATAL) << "Integration start = " << beg << " for signal " << ich << " (" << ChannelNames[ich] << ") not in allowed range [0-" << NTimeBinsPerBC - 1; + return; + } + if (end < 0 || end >= NTimeBinsPerBC) { + LOG(FATAL) << "Integration end = " << end << " for signal " << ich << " (" << ChannelNames[ich] << ") not in allowed range [0-" << NTimeBinsPerBC - 1; + return; + } + if (beg_ped < 0 || beg_ped >= NTimeBinsPerBC) { + LOG(FATAL) << "Pedestal integration start = " << beg_ped << " for signal " << ich << " (" << ChannelNames[ich] << ") not in allowed range [0-" << NTimeBinsPerBC - 1; + return; + } + if (beg < 0 || beg >= NTimeBinsPerBC) { + LOG(FATAL) << "Pedestal integration end = " << end_ped << " for signal " << ich << " (" << ChannelNames[ich] << ") not in allowed range [0-" << NTimeBinsPerBC - 1; + return; + } + beg_int[ich] = beg; + end_int[ich] = end; + beg_ped_int[ich] = beg_ped; + end_ped_int[ich] = end_ped; + } else { + LOG(FATAL) << __func__ << " channel " << ich << " not in allowed range"; + } +} + +void ZDCIntegrationParam::print() +{ + for (Int_t ich = 0; ich < NChannels; ich++) { + LOG(INFO) << ChannelNames[ich] << " integration: signal=[" << beg_int[ich] << "-" << end_int[ich] << "] pedestal=[" << beg_ped_int[ich] << "-" << end_ped_int[ich] <<"]"; + } +} diff --git a/Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx b/Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx new file mode 100644 index 0000000000000..7cbccde9863fa --- /dev/null +++ b/Detectors/ZDC/reconstruction/src/ZDCTDCParam.cxx @@ -0,0 +1,47 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "FairLogger.h" +#include "ZDCReconstruction/ZDCTDCParam.h" + +using namespace o2::zdc; + +void ZDCTDCParam::setShift(uint32_t ich, float val) +{ + if (ich >= 0 && ich < NTDCChannels) { + tdc_shift[ich] = val; + } else { + LOG(FATAL) << __func__ << " channel " << ich << " not in allowed range"; + } +} + +void ZDCTDCParam::print() +{ + LOG(INFO) << "TDCZNAC shift " << tdc_shift[TDCZNAC] << " ns"; + LOG(INFO) << "TDCZNAS shift " << tdc_shift[TDCZNAS] << " ns"; + LOG(INFO) << "TDCZPAC shift " << tdc_shift[TDCZPAC] << " ns"; + LOG(INFO) << "TDCZPAS shift " << tdc_shift[TDCZPAS] << " ns"; + LOG(INFO) << "TDCZEM1 shift " << tdc_shift[TDCZEM1] << " ns"; + LOG(INFO) << "TDCZEM2 shift " << tdc_shift[TDCZEM2] << " ns"; + LOG(INFO) << "TDCZNCC shift " << tdc_shift[TDCZNCC] << " ns"; + LOG(INFO) << "TDCZNCS shift " << tdc_shift[TDCZNCS] << " ns"; + LOG(INFO) << "TDCZPCC shift " << tdc_shift[TDCZPCC] << " ns"; + LOG(INFO) << "TDCZPCS shift " << tdc_shift[TDCZPCS] << " ns"; +} + +float ZDCTDCParam::getShift(uint32_t ich) const +{ + if (ich >= 0 && ich < NTDCChannels) { + return tdc_shift[ich]; + } else { + LOG(FATAL) << __func__ << " channel " << ich << " not in allowed range"; + return 0; + } +} From ac174d3ab79dea76091e6e2fc5be65a9d3738e5e Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 23 Apr 2021 16:16:04 +0200 Subject: [PATCH 238/770] Fix copy and paste error --- Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx index 4ef0b738ba2aa..1f124e2245918 100644 --- a/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx @@ -55,7 +55,7 @@ void customize(std::vector& policies) { // the TPC sector completion policy checks when the set of TPC/CLUSTERNATIVE data is complete // in addition we require to have input from all other routes - policies.push_back(o2::tpc::TPCSectorCompletionPolicy("itstpc-track-matcher", + policies.push_back(o2::tpc::TPCSectorCompletionPolicy("cosmics-matcher", o2::tpc::TPCSectorCompletionPolicy::Config::RequireAll, InputSpec{"cluster", o2::framework::ConcreteDataTypeMatcher{"TPC", "CLUSTERNATIVE"}})()); } From 7e1052e73014d5db19259bc13f91c363ee6bce61 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 22 Apr 2021 20:54:26 +0200 Subject: [PATCH 239/770] TPC Workflow: Move ClusterReader into a separate unit, such that it can be used by other workflows --- .../src/MatchTPCITSWorkflow.cxx | 17 +---- .../src/cosmics-match-workflow.cxx | 17 +---- .../tofworkflow/src/tof-matcher-tpc.cxx | 17 +---- .../TPCInterpolationSpec.h | 2 +- .../src/TPCInterpolationSpec.cxx | 2 +- .../src/TrackInterpolationWorkflow.cxx | 18 +---- Detectors/TPC/workflow/CMakeLists.txt | 1 + .../include/TPCWorkflow/ClusterReaderSpec.h | 26 +++++++ .../TPC/workflow/src/ClusterReaderSpec.cxx | 70 +++++++++++++++++++ .../TPC/workflow/src/FileReaderWorkflow.cxx | 35 +--------- Detectors/TPC/workflow/src/RecoWorkflow.cxx | 14 +--- 11 files changed, 112 insertions(+), 107 deletions(-) create mode 100644 Detectors/TPC/workflow/include/TPCWorkflow/ClusterReaderSpec.h create mode 100644 Detectors/TPC/workflow/src/ClusterReaderSpec.cxx diff --git a/Detectors/GlobalTrackingWorkflow/src/MatchTPCITSWorkflow.cxx b/Detectors/GlobalTrackingWorkflow/src/MatchTPCITSWorkflow.cxx index 10c9dcecb1f34..c183943946da1 100644 --- a/Detectors/GlobalTrackingWorkflow/src/MatchTPCITSWorkflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/MatchTPCITSWorkflow.cxx @@ -13,7 +13,7 @@ #include "ITSMFTWorkflow/ClusterReaderSpec.h" #include "ITSWorkflow/TrackReaderSpec.h" #include "TPCWorkflow/TrackReaderSpec.h" -#include "TPCWorkflow/PublisherSpec.h" +#include "TPCWorkflow/ClusterReaderSpec.h" #include "TPCWorkflow/ClusterSharingMapSpec.h" #include "FT0Workflow/RecPointReaderSpec.h" #include "GlobalTrackingWorkflow/TPCITSMatchingSpec.h" @@ -32,24 +32,11 @@ framework::WorkflowSpec getMatchTPCITSWorkflow(bool useFT0, bool useMC, bool dis { framework::WorkflowSpec specs; - std::vector tpcClusSectors = o2::RangeTokenizer::tokenize("0-35"); - std::vector tpcClusLanes = tpcClusSectors; - if (!disableRootInp) { specs.emplace_back(o2::its::getITSTrackReaderSpec(useMC)); specs.emplace_back(o2::itsmft::getITSClusterReaderSpec(useMC, true)); specs.emplace_back(o2::tpc::getTPCTrackReaderSpec(useMC)); - specs.emplace_back(o2::tpc::getPublisherSpec(o2::tpc::PublisherConf{ - "tpc-native-cluster-reader", - "tpc-native-clusters.root", - "tpcrec", - {"clusterbranch", "TPCClusterNative", "Branch with TPC native clusters"}, - {"clustermcbranch", "TPCClusterNativeMCTruth", "MC label branch"}, - OutputSpec{"TPC", "CLUSTERNATIVE"}, - OutputSpec{"TPC", "CLNATIVEMCLBL"}, - tpcClusSectors, - tpcClusLanes}, - useMC)); + specs.emplace_back(o2::tpc::getClusterReaderSpec(useMC)); specs.emplace_back(o2::tpc::getClusterSharingMapSpec()); if (useFT0) { diff --git a/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx index 1f124e2245918..74c09a7440c2c 100644 --- a/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx @@ -14,7 +14,7 @@ #include "ITSWorkflow/TrackReaderSpec.h" #include "ITSMFTWorkflow/ClusterReaderSpec.h" #include "TPCWorkflow/TrackReaderSpec.h" -#include "TPCWorkflow/PublisherSpec.h" +#include "TPCWorkflow/ClusterReaderSpec.h" #include "TPCWorkflow/ClusterSharingMapSpec.h" #include "TOFWorkflowUtils/ClusterReaderSpec.h" #include "TOFWorkflow/TOFMatchedReaderSpec.h" @@ -78,9 +78,6 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) auto disableRootInp = configcontext.options().get("disable-root-input"); auto disableRootOut = configcontext.options().get("disable-root-output"); - std::vector tpcClusSectors = o2::RangeTokenizer::tokenize("0-35"); - std::vector tpcClusLanes = tpcClusSectors; - GID::mask_t src = alowedSources & GID::getSourcesMask(configcontext.options().get("track-sources")); if (!disableRootInp) { @@ -111,17 +108,7 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) specs.emplace_back(o2::itsmft::getITSClusterReaderSpec(false, true)); // mc not neaded } if (GID::includesDet(DetID::TPC, src)) { - specs.emplace_back(o2::tpc::getPublisherSpec(o2::tpc::PublisherConf{ - "tpc-native-cluster-reader", - "tpc-native-clusters.root", - "tpcrec", - {"clusterbranch", "TPCClusterNative", "Branch with TPC native clusters"}, - {"clustermcbranch", "TPCClusterNativeMCTruth", "MC label branch"}, - OutputSpec{"TPC", "CLUSTERNATIVE"}, - OutputSpec{"TPC", "CLNATIVEMCLBL"}, - tpcClusSectors, - tpcClusLanes}, - false)); + specs.emplace_back(o2::tpc::getClusterReaderSpec(false)); specs.emplace_back(o2::tpc::getClusterSharingMapSpec()); } } diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-tpc.cxx b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-tpc.cxx index 68f22d7f74b8d..d209fb38de2f3 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-tpc.cxx +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-tpc.cxx @@ -25,7 +25,7 @@ #include "CommonUtils/ConfigurableParam.h" #include "DetectorsCommonDataFormats/NameConf.h" #include "TPCWorkflow/TrackReaderSpec.h" -#include "TPCWorkflow/PublisherSpec.h" +#include "TPCWorkflow/ClusterReaderSpec.h" #include "TPCWorkflow/ClusterSharingMapSpec.h" #include "DetectorsRaw/HBFUtilsInitializer.h" @@ -121,9 +121,6 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) // writecalib = false; // LOG(INFO) << "TOF CalibInfo disabled (forced)"; - std::vector tpcClusSectors = o2::RangeTokenizer::tokenize("0-35"); - std::vector tpcClusLanes = tpcClusSectors; - if (!disableRootInput) { // input data loaded from root files LOG(INFO) << "Insert TOF Cluster Reader"; specs.emplace_back(o2::tof::getClusterReaderSpec(useMC)); @@ -133,17 +130,7 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) if (doTPCRefit) { LOG(INFO) << "Insert TPC Cluster Reader"; - specs.emplace_back(o2::tpc::getPublisherSpec(o2::tpc::PublisherConf{ - "tpc-native-cluster-reader", - "tpc-native-clusters.root", - "tpcrec", - {"clusterbranch", "TPCClusterNative", "Branch with TPC native clusters"}, - {"clustermcbranch", "TPCClusterNativeMCTruth", "MC label branch"}, - OutputSpec{"TPC", "CLUSTERNATIVE"}, - OutputSpec{"TPC", "CLNATIVEMCLBL"}, - tpcClusSectors, - tpcClusLanes}, - false)); + specs.emplace_back(o2::tpc::getClusterReaderSpec(false)); specs.emplace_back(o2::tpc::getClusterSharingMapSpec()); } diff --git a/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/include/TPCInterpolationWorkflow/TPCInterpolationSpec.h b/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/include/TPCInterpolationWorkflow/TPCInterpolationSpec.h index 08cae7bfb464c..0e1a812e0aa29 100644 --- a/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/include/TPCInterpolationWorkflow/TPCInterpolationSpec.h +++ b/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/include/TPCInterpolationWorkflow/TPCInterpolationSpec.h @@ -41,7 +41,7 @@ class TPCInterpolationDPL : public Task }; /// create a processor spec -framework::DataProcessorSpec getTPCInterpolationSpec(bool useMC, const std::vector& tpcClusLanes); +framework::DataProcessorSpec getTPCInterpolationSpec(bool useMC); } // namespace tpc } // namespace o2 diff --git a/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TPCInterpolationSpec.cxx b/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TPCInterpolationSpec.cxx index dddd04f23781b..2b08d7dd064f0 100644 --- a/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TPCInterpolationSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TPCInterpolationSpec.cxx @@ -79,7 +79,7 @@ void TPCInterpolationDPL::endOfStream(EndOfStreamContext& ec) mTimer.CpuTime(), mTimer.RealTime(), mTimer.Counter() - 1); } -DataProcessorSpec getTPCInterpolationSpec(bool useMC, const std::vector& tpcClusLanes) +DataProcessorSpec getTPCInterpolationSpec(bool useMC) { std::vector inputs; std::vector outputs; diff --git a/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TrackInterpolationWorkflow.cxx b/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TrackInterpolationWorkflow.cxx index 3e5e23b50861a..51f35793df446 100644 --- a/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TrackInterpolationWorkflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TrackInterpolationWorkflow.cxx @@ -14,7 +14,7 @@ #include "ITSWorkflow/TrackReaderSpec.h" #include "TPCWorkflow/TrackReaderSpec.h" -#include "TPCWorkflow/PublisherSpec.h" +#include "TPCWorkflow/ClusterReaderSpec.h" #include "GlobalTrackingWorkflow/TrackTPCITSReaderSpec.h" #include "TOFWorkflowUtils/ClusterReaderSpec.h" #include "TOFWorkflow/TOFMatchedReaderSpec.h" @@ -32,28 +32,16 @@ framework::WorkflowSpec getTPCInterpolationWorkflow(bool disableRootInp, bool di { framework::WorkflowSpec specs; bool useMC = false; - std::vector tpcClusSectors = o2::RangeTokenizer::tokenize("0-35"); - std::vector tpcClusLanes = tpcClusSectors; if (!disableRootInp) { specs.emplace_back(o2::its::getITSTrackReaderSpec(useMC)); specs.emplace_back(o2::tpc::getTPCTrackReaderSpec(useMC)); - specs.emplace_back(o2::tpc::getPublisherSpec(o2::tpc::PublisherConf{ - "tpc-native-cluster-reader", - "tpc-native-clusters.root", - "tpcrec", - {"clusterbranch", "TPCClusterNative", "Branch with TPC native clusters"}, - {"clustermcbranch", "TPCClusterNativeMCTruth", "MC label branch"}, - OutputSpec{"TPC", "CLUSTERNATIVE"}, - OutputSpec{"TPC", "CLNATIVEMCLBL"}, - tpcClusSectors, - tpcClusLanes}, - useMC)); + specs.emplace_back(o2::tpc::getClusterReaderSpec(useMC)); specs.emplace_back(o2::globaltracking::getTrackTPCITSReaderSpec(useMC)); specs.emplace_back(o2::tof::getClusterReaderSpec(useMC)); specs.emplace_back(o2::tof::getTOFMatchedReaderSpec(useMC)); } - specs.emplace_back(o2::tpc::getTPCInterpolationSpec(useMC, tpcClusLanes)); + specs.emplace_back(o2::tpc::getTPCInterpolationSpec(useMC)); if (!disableRootOut) { specs.emplace_back(o2::tpc::getTPCResidualWriterSpec(useMC)); diff --git a/Detectors/TPC/workflow/CMakeLists.txt b/Detectors/TPC/workflow/CMakeLists.txt index 6a9f2beef7ae1..4fdf431c3a2e3 100644 --- a/Detectors/TPC/workflow/CMakeLists.txt +++ b/Detectors/TPC/workflow/CMakeLists.txt @@ -12,6 +12,7 @@ # FIXME: do we really need a library here ? Is the exe not enough ? o2_add_library(TPCWorkflow SOURCES src/RecoWorkflow.cxx + src/ClusterReaderSpec.cxx src/PublisherSpec.cxx src/ClustererSpec.cxx src/ClusterDecoderRawSpec.cxx diff --git a/Detectors/TPC/workflow/include/TPCWorkflow/ClusterReaderSpec.h b/Detectors/TPC/workflow/include/TPCWorkflow/ClusterReaderSpec.h new file mode 100644 index 0000000000000..1a24c0748763f --- /dev/null +++ b/Detectors/TPC/workflow/include/TPCWorkflow/ClusterReaderSpec.h @@ -0,0 +1,26 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_TPC_CLUSTERREADERSPEC_H +#define O2_TPC_CLUSTERREADERSPEC_H +/// @file ClusterReaderSpec.h +/// @author David Rohr + +#include "Framework/WorkflowSpec.h" +#include + +namespace o2 +{ +namespace tpc +{ +framework::DataProcessorSpec getClusterReaderSpec(bool useMC, const std::vector* tpcSectors = nullptr, const std::vector* laneConfiguration = nullptr); +} // end namespace tpc +} // end namespace o2 +#endif // O2_TPC_CLUSTERREADERSPEC_H diff --git a/Detectors/TPC/workflow/src/ClusterReaderSpec.cxx b/Detectors/TPC/workflow/src/ClusterReaderSpec.cxx new file mode 100644 index 0000000000000..23a3b9d4353c4 --- /dev/null +++ b/Detectors/TPC/workflow/src/ClusterReaderSpec.cxx @@ -0,0 +1,70 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file ClusterReaderSpec1.cxx +/// @author David Rohr + +#include "Framework/WorkflowSpec.h" +#include "DPLUtils/RootTreeReader.h" +#include "TPCWorkflow/PublisherSpec.h" +#include "SimulationDataFormat/IOMCTruthContainerView.h" +#include "SimulationDataFormat/ConstMCTruthContainer.h" +#include "SimulationDataFormat/MCCompLabel.h" +#include "TPCBase/Sector.h" + +using namespace o2::framework; + +namespace o2 +{ +namespace tpc +{ + +framework::DataProcessorSpec getClusterReaderSpec(bool useMC, const std::vector* tpcSectors, const std::vector* laneConfiguration) +{ + static RootTreeReader::SpecialPublishHook hook{[](std::string_view name, ProcessingContext& context, o2::framework::Output const& output, char* data) -> bool { + if (TString(name.data()).Contains("TPCDigitMCTruth") || TString(name.data()).Contains("TPCClusterHwMCTruth") || TString(name.data()).Contains("TPCClusterNativeMCTruth")) { + auto storedlabels = reinterpret_cast(data); + o2::dataformats::ConstMCTruthContainer flatlabels; + storedlabels->copyandflatten(flatlabels); + //LOG(INFO) << "PUBLISHING CONST LABELS " << flatlabels.getNElements(); + context.outputs().snapshot(output, flatlabels); + return true; + } + return false; + }}; + + std::vector defaultSectors; + std::vector defaultLaneConfig; + if (tpcSectors == nullptr) { + defaultSectors.resize(Sector::MAXSECTOR); + std::iota(defaultSectors.begin(), defaultSectors.end(), 0); + tpcSectors = &defaultSectors; + } + if (laneConfiguration == nullptr) { + defaultLaneConfig = *tpcSectors; + laneConfiguration = &defaultLaneConfig; + } + + return std::move(o2::tpc::getPublisherSpec(PublisherConf{ + "tpc-native-cluster-reader", + "tpc-native-clusters.root", + "tpcrec", + {"clusterbranch", "TPCClusterNative", "Branch with TPC native clusters"}, + {"clustermcbranch", "TPCClusterNativeMCTruth", "MC label branch"}, + OutputSpec{"TPC", "CLUSTERNATIVE"}, + OutputSpec{"TPC", "CLNATIVEMCLBL"}, + *tpcSectors, + *laneConfiguration, + &hook}, + useMC)); +} + +} // end namespace tpc +} // end namespace o2 diff --git a/Detectors/TPC/workflow/src/FileReaderWorkflow.cxx b/Detectors/TPC/workflow/src/FileReaderWorkflow.cxx index 07825ecf06e6a..fc860708eeb65 100644 --- a/Detectors/TPC/workflow/src/FileReaderWorkflow.cxx +++ b/Detectors/TPC/workflow/src/FileReaderWorkflow.cxx @@ -10,7 +10,7 @@ /// @file FileReaderWorkflow.cxx -#include "TPCWorkflow/PublisherSpec.h" +#include "TPCWorkflow/ClusterReaderSpec.h" #include "TPCWorkflow/TrackReaderSpec.h" #include "Algorithm/RangeTokenizer.h" @@ -65,38 +65,7 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) }; if (isEnabled(Input::Clusters)) { - - // We provide a special publishing method for labels which have been stored in a split format and need - // to be transformed into a contiguous shareable container before publishing. For other branches/types this returns - // false and the generic RootTreeWriter publishing proceeds - static RootTreeReader::SpecialPublishHook hook{[](std::string_view name, ProcessingContext& context, o2::framework::Output const& output, char* data) -> bool { - if (TString(name.data()).Contains("TPCDigitMCTruth") || TString(name.data()).Contains("TPCClusterHwMCTruth") || TString(name.data()).Contains("TPCClusterNativeMCTruth")) { - auto storedlabels = reinterpret_cast(data); - o2::dataformats::ConstMCTruthContainer flatlabels; - storedlabels->copyandflatten(flatlabels); - LOG(INFO) << "PUBLISHING CONST LABELS " << flatlabels.getNElements(); - context.outputs().snapshot(output, flatlabels); - return true; - } - return false; - }}; - - std::vector tpcSectors(36); - std::iota(tpcSectors.begin(), tpcSectors.end(), 0); - std::vector laneConfiguration = tpcSectors; - - specs.emplace_back(o2::tpc::getPublisherSpec(o2::tpc::PublisherConf{ - "tpc-native-cluster-reader", - "tpc-native-clusters.root", - "tpcrec", - {"clusterbranch", "TPCClusterNative", "Branch with TPC native clusters"}, - {"clustermcbranch", "TPCClusterNativeMCTruth", "MC label branch"}, - OutputSpec{"TPC", "CLUSTERNATIVE"}, - OutputSpec{"TPC", "CLNATIVEMCLBL"}, - tpcSectors, - laneConfiguration, - &hook}, - doMC)); + specs.emplace_back(o2::tpc::getClusterReaderSpec(doMC)); } if (isEnabled(Input::Tracks)) { diff --git a/Detectors/TPC/workflow/src/RecoWorkflow.cxx b/Detectors/TPC/workflow/src/RecoWorkflow.cxx index db891ba44a15d..2dfda3f38ae2f 100644 --- a/Detectors/TPC/workflow/src/RecoWorkflow.cxx +++ b/Detectors/TPC/workflow/src/RecoWorkflow.cxx @@ -37,6 +37,7 @@ #include "SimulationDataFormat/MCCompLabel.h" #include "DataFormatsTPC/Helpers.h" #include "DataFormatsTPC/ZeroSuppression.h" +#include "TPCWorkflow/ClusterReaderSpec.h" #include #include @@ -191,18 +192,7 @@ framework::WorkflowSpec getWorkflow(CompletionPolicyData* policyData, std::vecto &hook}, propagateMC)); } else if (inputType == InputType::Clusters) { - specs.emplace_back(o2::tpc::getPublisherSpec(PublisherConf{ - "tpc-native-cluster-reader", - "tpc-native-clusters.root", - "tpcrec", - {"clusterbranch", "TPCClusterNative", "Branch with TPC native clusters"}, - {"clustermcbranch", "TPCClusterNativeMCTruth", "MC label branch"}, - OutputSpec{"TPC", "CLUSTERNATIVE"}, - OutputSpec{"TPC", "CLNATIVEMCLBL"}, - tpcSectors, - laneConfiguration, - &hook}, - propagateMC)); + specs.emplace_back(o2::tpc::getClusterReaderSpec(propagateMC, &tpcSectors, &laneConfiguration)); } else if (inputType == InputType::CompClusters) { // TODO: need to check if we want to store the MC labels alongside with compressed clusters // for the moment reading of labels is disabled (last parameter is false) From d344c2dddb50dfd5cd71651d70fe1c308c92fe8e Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 22 Apr 2021 20:54:33 +0200 Subject: [PATCH 240/770] Add Helper library to automatically add input specs for reading clusters / tracks from ROOT files --- .../GlobalTrackingWorkflow/CMakeLists.txt | 1 + .../helpers/CMakeLists.txt | 22 ++++++ .../InputHelper.h | 38 ++++++++++ .../helpers/src/InputHelper.cxx | 71 +++++++++++++++++++ 4 files changed, 132 insertions(+) create mode 100644 Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt create mode 100644 Detectors/GlobalTrackingWorkflow/helpers/include/GlobalTrackingWorkflowHelpers/InputHelper.h create mode 100644 Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx diff --git a/Detectors/GlobalTrackingWorkflow/CMakeLists.txt b/Detectors/GlobalTrackingWorkflow/CMakeLists.txt index fee5c7e889e14..80cbf3394e7ef 100644 --- a/Detectors/GlobalTrackingWorkflow/CMakeLists.txt +++ b/Detectors/GlobalTrackingWorkflow/CMakeLists.txt @@ -67,3 +67,4 @@ o2_add_executable(vertexing-workflow add_subdirectory(tofworkflow) add_subdirectory(tpcinterpolationworkflow) +add_subdirectory(helpers) diff --git a/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt b/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt new file mode 100644 index 0000000000000..eaea625bf063d --- /dev/null +++ b/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt @@ -0,0 +1,22 @@ +# Copyright CERN and copyright holders of ALICE O2. This software is distributed +# under the terms of the GNU General Public License v3 (GPL Version 3), copied +# verbatim in the file "COPYING". +# +# See http://alice-o2.web.cern.ch/license for full licensing information. +# +# In applying this license CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization or +# submit itself to any jurisdiction. + +o2_add_library(GlobalTrackingWorkflowHelpers + SOURCES src/InputHelper.cxx + PUBLIC_LINK_LIBRARIES O2::ReconstructionDataFormats + PRIVATE_LINK_LIBRARIES O2::GlobalTracking # We link all the workflow libs etc as PRIVATE, such that we do not expose tons of headers automatically + O2::GlobalTrackingWorkflow + O2::ITSWorkflow + O2::ITSMFTWorkflow + O2::TPCWorkflow + O2::TOFWorkflow + O2::FT0Workflow + O2::ITSMFTWorkflow + O2::SimulationDataFormat) diff --git a/Detectors/GlobalTrackingWorkflow/helpers/include/GlobalTrackingWorkflowHelpers/InputHelper.h b/Detectors/GlobalTrackingWorkflow/helpers/include/GlobalTrackingWorkflowHelpers/InputHelper.h new file mode 100644 index 0000000000000..14ea58ed91811 --- /dev/null +++ b/Detectors/GlobalTrackingWorkflow/helpers/include/GlobalTrackingWorkflowHelpers/InputHelper.h @@ -0,0 +1,38 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_GLOBALTRACKING_INPUTHELPER_H +#define O2_GLOBALTRACKING_INPUTHELPER_H + +#include "Framework/DataProcessorSpec.h" +#include "ReconstructionDataFormats/GlobalTrackID.h" +#include "Framework/ConfigContext.h" +#include "Framework/WorkflowSpec.h" + +namespace o2 +{ +namespace globaltracking +{ + +class InputHelper +{ + public: + using GID = o2::dataformats::GlobalTrackID; + // If "--disable-mc" is passed as option, useMC is overwritten to false. + // If useMC is false, maskClustersMC and maskTracksMC are overwritten to NONE. + // The masks define what data to load in a quite generic way, masks with MC suffix are for the corresponding MC labels. + // For matched tracks, maskMatches refers only to the matching information, while the corresponding maskTracks can still be set to load also the refit matched tracks + static int addInputSpecs(const o2::framework::ConfigContext& configcontext, o2::framework::WorkflowSpec& specs, GID::mask_t maskClusters, GID::mask_t maskMatches, GID::mask_t maskTracks, bool useMC = true, GID::mask_t maskClustersMC = GID::getSourcesMask(GID::ALL), GID::mask_t maskTracksMC = GID::getSourcesMask(GID::ALL)); +}; + +} // namespace globaltracking +} // namespace o2 + +#endif diff --git a/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx b/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx new file mode 100644 index 0000000000000..cc5be51427932 --- /dev/null +++ b/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx @@ -0,0 +1,71 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file SecondaryVertexingSpec.cxx + +#include "GlobalTrackingWorkflowHelpers/InputHelper.h" +#include "Framework/ConfigParamRegistry.h" +#include "ITSMFTWorkflow/ClusterReaderSpec.h" +#include "ITSWorkflow/TrackReaderSpec.h" +#include "TPCWorkflow/TrackReaderSpec.h" +#include "TPCWorkflow/ClusterReaderSpec.h" +#include "TPCWorkflow/ClusterSharingMapSpec.h" +#include "GlobalTrackingWorkflow/TrackTPCITSReaderSpec.h" +#include "TOFWorkflowUtils/ClusterReaderSpec.h" +#include "TOFWorkflow/TOFMatchedReaderSpec.h" + +using namespace o2::framework; +using namespace o2::globaltracking; +using namespace o2::dataformats; +using GID = o2::dataformats::GlobalTrackID; + +int InputHelper::addInputSpecs(const ConfigContext& configcontext, WorkflowSpec& specs, GID::mask_t maskClusters, GID::mask_t maskMatches, GID::mask_t maskTracks, bool useMC, GID::mask_t maskClustersMC, GID::mask_t maskTracksMC) +{ + if (configcontext.options().get("disable-root-input")) { + return 0; + } + if (useMC && configcontext.options().get("disable-mc")) { + useMC = false; + } + if (!useMC) { + maskClustersMC = GID::getSourcesMask(GID::NONE); + maskTracksMC = GID::getSourcesMask(GID::NONE); + } + + if (maskTracks[GID::ITS]) { + specs.emplace_back(o2::its::getITSTrackReaderSpec(maskTracksMC[GID::ITS])); + } + if (maskClusters[GID::ITS]) { + specs.emplace_back(o2::itsmft::getITSClusterReaderSpec(maskClustersMC[GID::ITS], true)); + } + if (maskTracks[GID::TPC]) { + specs.emplace_back(o2::tpc::getTPCTrackReaderSpec(maskTracksMC[GID::TPC])); + } + if (maskClusters[GID::TPC]) { + specs.emplace_back(o2::tpc::getClusterReaderSpec(maskClustersMC[GID::TPC])); + } + if (maskTracks[GID::TPC] && maskClusters[GID::TPC]) { + specs.emplace_back(o2::tpc::getClusterSharingMapSpec()); + } + if (maskMatches[GID::ITSTPC] || maskMatches[GID::ITSTPCTOF] || maskTracks[GID::ITSTPC] || maskTracks[GID::ITSTPCTOF]) { + specs.emplace_back(o2::globaltracking::getTrackTPCITSReaderSpec(maskTracksMC[GID::ITSTPC] || maskTracksMC[GID::ITSTPCTOF])); + } + if (maskMatches[GID::ITSTPCTOF] || maskTracks[GID::ITSTPCTOF]) { + specs.emplace_back(o2::tof::getTOFMatchedReaderSpec(maskTracksMC[GID::ITSTPCTOF], false, /*maskTracks[GID::ITSTPCTOF]*/ false)); // ITSTPCTOF does not provide tracks, only matchInfo + } + if (maskClusters[GID::TOF]) { + specs.emplace_back(o2::tof::getClusterReaderSpec(maskClustersMC[GID::TOF])); + } + if (maskMatches[GID::TPCTOF]) { + specs.emplace_back(o2::tof::getTOFMatchedReaderSpec(maskTracksMC[GID::TPCTOF], true, maskTracks[GID::TPCTOF])); + } + + return 0; +} From 0bfe88e30d80b70d887a8da13de2bdfc8d47cc21 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 22 Apr 2021 20:35:21 +0200 Subject: [PATCH 241/770] Global Tracking Workflow: Move all reader specs to readers library, to reduce the dependency chain of its users, and avoid cyclic dependencies --- Detectors/AOD/src/AODProducerWorkflow.cxx | 4 ++-- .../GlobalTrackingWorkflow/CMakeLists.txt | 10 ++++------ .../helpers/CMakeLists.txt | 1 - .../helpers/src/InputHelper.cxx | 4 ++-- .../readers/CMakeLists.txt | 18 ++++++++++++++++++ .../PrimaryVertexReaderSpec.h | 0 .../SecondaryVertexReaderSpec.h | 0 .../TrackCosmicsReaderSpec.h | 0 .../TrackTPCITSReaderSpec.h | 0 .../src/PrimaryVertexReaderSpec.cxx | 2 +- .../src/SecondaryVertexReaderSpec.cxx | 2 +- .../src/TrackCosmicsReaderSpec.cxx | 2 +- .../src/TrackTPCITSReaderSpec.cxx | 2 +- .../src/cosmics-match-workflow.cxx | 2 +- .../src/primary-vertex-reader-workflow.cxx | 2 +- .../src/primary-vertexing-workflow.cxx | 2 +- .../src/secondary-vertex-reader-workflow.cxx | 2 +- .../src/secondary-vertexing-workflow.cxx | 4 ++-- .../tofworkflow/CMakeLists.txt | 4 ++-- .../tofworkflow/src/tof-calibinfo-reader.cxx | 2 +- .../tofworkflow/src/tof-matcher-global.cxx | 2 +- .../tofworkflow/src/tof-reco-workflow.cxx | 2 +- .../src/TrackInterpolationWorkflow.cxx | 2 +- Detectors/TRD/workflow/CMakeLists.txt | 2 +- .../TRD/workflow/src/TRDTrackingWorkflow.cxx | 2 +- 25 files changed, 44 insertions(+), 29 deletions(-) create mode 100644 Detectors/GlobalTrackingWorkflow/readers/CMakeLists.txt rename Detectors/GlobalTrackingWorkflow/{include/GlobalTrackingWorkflow => readers/include/GlobalTrackingWorkflowReaders}/PrimaryVertexReaderSpec.h (100%) rename Detectors/GlobalTrackingWorkflow/{include/GlobalTrackingWorkflow => readers/include/GlobalTrackingWorkflowReaders}/SecondaryVertexReaderSpec.h (100%) rename Detectors/GlobalTrackingWorkflow/{include/GlobalTrackingWorkflow => readers/include/GlobalTrackingWorkflowReaders}/TrackCosmicsReaderSpec.h (100%) rename Detectors/GlobalTrackingWorkflow/{include/GlobalTrackingWorkflow => readers/include/GlobalTrackingWorkflowReaders}/TrackTPCITSReaderSpec.h (100%) rename Detectors/GlobalTrackingWorkflow/{ => readers}/src/PrimaryVertexReaderSpec.cxx (98%) rename Detectors/GlobalTrackingWorkflow/{ => readers}/src/SecondaryVertexReaderSpec.cxx (98%) rename Detectors/GlobalTrackingWorkflow/{ => readers}/src/TrackCosmicsReaderSpec.cxx (97%) rename Detectors/GlobalTrackingWorkflow/{ => readers}/src/TrackTPCITSReaderSpec.cxx (97%) diff --git a/Detectors/AOD/src/AODProducerWorkflow.cxx b/Detectors/AOD/src/AODProducerWorkflow.cxx index 1ec498956fc93..b8bc74dd001a3 100644 --- a/Detectors/AOD/src/AODProducerWorkflow.cxx +++ b/Detectors/AOD/src/AODProducerWorkflow.cxx @@ -19,9 +19,9 @@ #include "GlobalTracking/MatchTPCITSParams.h" #include "GlobalTrackingWorkflow/MatchTPCITSWorkflow.h" #include "GlobalTrackingWorkflow/PrimaryVertexingSpec.h" -#include "GlobalTrackingWorkflow/PrimaryVertexReaderSpec.h" +#include "GlobalTrackingWorkflowReaders/PrimaryVertexReaderSpec.h" #include "GlobalTrackingWorkflow/TPCITSMatchingSpec.h" -#include "GlobalTrackingWorkflow/TrackTPCITSReaderSpec.h" +#include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" #include "GlobalTrackingWorkflow/TrackWriterTPCITSSpec.h" #include "ITSMFTWorkflow/ClusterReaderSpec.h" #include "ITSWorkflow/TrackReaderSpec.h" diff --git a/Detectors/GlobalTrackingWorkflow/CMakeLists.txt b/Detectors/GlobalTrackingWorkflow/CMakeLists.txt index 80cbf3394e7ef..78668d43b4f1b 100644 --- a/Detectors/GlobalTrackingWorkflow/CMakeLists.txt +++ b/Detectors/GlobalTrackingWorkflow/CMakeLists.txt @@ -14,22 +14,19 @@ o2_add_library(GlobalTrackingWorkflow SOURCES src/TrackWriterTPCITSSpec.cxx src/TPCITSMatchingSpec.cxx src/MatchTPCITSWorkflow.cxx - src/TrackTPCITSReaderSpec.cxx src/PrimaryVertexingSpec.cxx src/PrimaryVertexWriterSpec.cxx - src/PrimaryVertexReaderSpec.cxx src/VertexTrackMatcherSpec.cxx src/SecondaryVertexingSpec.cxx src/SecondaryVertexWriterSpec.cxx - src/SecondaryVertexReaderSpec.cxx src/CosmicsMatchingSpec.cxx - src/TrackCosmicsWriterSpec.cxx - src/TrackCosmicsReaderSpec.cxx + src/TrackCosmicsWriterSpec.cxx PUBLIC_LINK_LIBRARIES O2::GlobalTracking + O2::GlobalTrackingWorkflowReaders O2::ITStracking O2::ITSWorkflow O2::TPCWorkflow - O2::FT0Workflow + O2::FT0Workflow O2::ITSMFTWorkflow O2::SimulationDataFormat O2::DetectorsVertexing) @@ -68,3 +65,4 @@ o2_add_executable(vertexing-workflow add_subdirectory(tofworkflow) add_subdirectory(tpcinterpolationworkflow) add_subdirectory(helpers) +add_subdirectory(readers) diff --git a/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt b/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt index eaea625bf063d..7fe9b6e2fb605 100644 --- a/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt +++ b/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt @@ -12,7 +12,6 @@ o2_add_library(GlobalTrackingWorkflowHelpers SOURCES src/InputHelper.cxx PUBLIC_LINK_LIBRARIES O2::ReconstructionDataFormats PRIVATE_LINK_LIBRARIES O2::GlobalTracking # We link all the workflow libs etc as PRIVATE, such that we do not expose tons of headers automatically - O2::GlobalTrackingWorkflow O2::ITSWorkflow O2::ITSMFTWorkflow O2::TPCWorkflow diff --git a/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx b/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx index cc5be51427932..e787f61630858 100644 --- a/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx +++ b/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file SecondaryVertexingSpec.cxx +/// @file InputHelper.cxx #include "GlobalTrackingWorkflowHelpers/InputHelper.h" #include "Framework/ConfigParamRegistry.h" @@ -17,7 +17,7 @@ #include "TPCWorkflow/TrackReaderSpec.h" #include "TPCWorkflow/ClusterReaderSpec.h" #include "TPCWorkflow/ClusterSharingMapSpec.h" -#include "GlobalTrackingWorkflow/TrackTPCITSReaderSpec.h" +#include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" #include "TOFWorkflowUtils/ClusterReaderSpec.h" #include "TOFWorkflow/TOFMatchedReaderSpec.h" diff --git a/Detectors/GlobalTrackingWorkflow/readers/CMakeLists.txt b/Detectors/GlobalTrackingWorkflow/readers/CMakeLists.txt new file mode 100644 index 0000000000000..29383d39cc5f1 --- /dev/null +++ b/Detectors/GlobalTrackingWorkflow/readers/CMakeLists.txt @@ -0,0 +1,18 @@ +# Copyright CERN and copyright holders of ALICE O2. This software is distributed +# under the terms of the GNU General Public License v3 (GPL Version 3), copied +# verbatim in the file "COPYING". +# +# See http://alice-o2.web.cern.ch/license for full licensing information. +# +# In applying this license CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization or +# submit itself to any jurisdiction. + +o2_add_library(GlobalTrackingWorkflowReaders + SOURCES src/TrackCosmicsReaderSpec.cxx + src/SecondaryVertexReaderSpec.cxx + src/PrimaryVertexReaderSpec.cxx + src/TrackTPCITSReaderSpec.cxx + PUBLIC_LINK_LIBRARIES O2::ReconstructionDataFormats + O2::GlobalTracking + O2::SimulationDataFormat) diff --git a/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/PrimaryVertexReaderSpec.h b/Detectors/GlobalTrackingWorkflow/readers/include/GlobalTrackingWorkflowReaders/PrimaryVertexReaderSpec.h similarity index 100% rename from Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/PrimaryVertexReaderSpec.h rename to Detectors/GlobalTrackingWorkflow/readers/include/GlobalTrackingWorkflowReaders/PrimaryVertexReaderSpec.h diff --git a/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/SecondaryVertexReaderSpec.h b/Detectors/GlobalTrackingWorkflow/readers/include/GlobalTrackingWorkflowReaders/SecondaryVertexReaderSpec.h similarity index 100% rename from Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/SecondaryVertexReaderSpec.h rename to Detectors/GlobalTrackingWorkflow/readers/include/GlobalTrackingWorkflowReaders/SecondaryVertexReaderSpec.h diff --git a/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/TrackCosmicsReaderSpec.h b/Detectors/GlobalTrackingWorkflow/readers/include/GlobalTrackingWorkflowReaders/TrackCosmicsReaderSpec.h similarity index 100% rename from Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/TrackCosmicsReaderSpec.h rename to Detectors/GlobalTrackingWorkflow/readers/include/GlobalTrackingWorkflowReaders/TrackCosmicsReaderSpec.h diff --git a/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/TrackTPCITSReaderSpec.h b/Detectors/GlobalTrackingWorkflow/readers/include/GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h similarity index 100% rename from Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/TrackTPCITSReaderSpec.h rename to Detectors/GlobalTrackingWorkflow/readers/include/GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h diff --git a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexReaderSpec.cxx b/Detectors/GlobalTrackingWorkflow/readers/src/PrimaryVertexReaderSpec.cxx similarity index 98% rename from Detectors/GlobalTrackingWorkflow/src/PrimaryVertexReaderSpec.cxx rename to Detectors/GlobalTrackingWorkflow/readers/src/PrimaryVertexReaderSpec.cxx index fbe0b6290f479..3e3ffe37c5358 100644 --- a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexReaderSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/readers/src/PrimaryVertexReaderSpec.cxx @@ -15,7 +15,7 @@ #include "Framework/ControlService.h" #include "Framework/ConfigParamRegistry.h" #include "Framework/Logger.h" -#include "GlobalTrackingWorkflow/PrimaryVertexReaderSpec.h" +#include "GlobalTrackingWorkflowReaders/PrimaryVertexReaderSpec.h" #include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; diff --git a/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexReaderSpec.cxx b/Detectors/GlobalTrackingWorkflow/readers/src/SecondaryVertexReaderSpec.cxx similarity index 98% rename from Detectors/GlobalTrackingWorkflow/src/SecondaryVertexReaderSpec.cxx rename to Detectors/GlobalTrackingWorkflow/readers/src/SecondaryVertexReaderSpec.cxx index 7618e6c56c66f..f6c945348b09d 100644 --- a/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexReaderSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/readers/src/SecondaryVertexReaderSpec.cxx @@ -15,7 +15,7 @@ #include "Framework/ControlService.h" #include "Framework/ConfigParamRegistry.h" #include "Framework/Logger.h" -#include "GlobalTrackingWorkflow/SecondaryVertexReaderSpec.h" +#include "GlobalTrackingWorkflowReaders/SecondaryVertexReaderSpec.h" #include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; diff --git a/Detectors/GlobalTrackingWorkflow/src/TrackCosmicsReaderSpec.cxx b/Detectors/GlobalTrackingWorkflow/readers/src/TrackCosmicsReaderSpec.cxx similarity index 97% rename from Detectors/GlobalTrackingWorkflow/src/TrackCosmicsReaderSpec.cxx rename to Detectors/GlobalTrackingWorkflow/readers/src/TrackCosmicsReaderSpec.cxx index ba181c59a1052..279a111e8923d 100644 --- a/Detectors/GlobalTrackingWorkflow/src/TrackCosmicsReaderSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/readers/src/TrackCosmicsReaderSpec.cxx @@ -14,7 +14,7 @@ #include "Framework/ConfigParamRegistry.h" #include "Framework/ControlService.h" -#include "GlobalTrackingWorkflow/TrackCosmicsReaderSpec.h" +#include "GlobalTrackingWorkflowReaders/TrackCosmicsReaderSpec.h" #include "DataFormatsParameters/GRPObject.h" #include "Framework/SerializationMethods.h" #include "DetectorsCommonDataFormats/NameConf.h" diff --git a/Detectors/GlobalTrackingWorkflow/src/TrackTPCITSReaderSpec.cxx b/Detectors/GlobalTrackingWorkflow/readers/src/TrackTPCITSReaderSpec.cxx similarity index 97% rename from Detectors/GlobalTrackingWorkflow/src/TrackTPCITSReaderSpec.cxx rename to Detectors/GlobalTrackingWorkflow/readers/src/TrackTPCITSReaderSpec.cxx index 340244fd0e3b9..4eccbab9ba0d7 100644 --- a/Detectors/GlobalTrackingWorkflow/src/TrackTPCITSReaderSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/readers/src/TrackTPCITSReaderSpec.cxx @@ -14,7 +14,7 @@ #include "Framework/ConfigParamRegistry.h" #include "Framework/ControlService.h" -#include "GlobalTrackingWorkflow/TrackTPCITSReaderSpec.h" +#include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" #include "DataFormatsParameters/GRPObject.h" #include "Framework/SerializationMethods.h" #include "DetectorsCommonDataFormats/NameConf.h" diff --git a/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx index 74c09a7440c2c..9829d6b347769 100644 --- a/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx @@ -21,7 +21,7 @@ #include "TOFWorkflowUtils/ClusterReaderSpec.h" #include "ReconstructionDataFormats/GlobalTrackID.h" #include "DetectorsCommonDataFormats/DetID.h" -#include "GlobalTrackingWorkflow/TrackTPCITSReaderSpec.h" +#include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" #include "GlobalTrackingWorkflow/CosmicsMatchingSpec.h" #include "GlobalTrackingWorkflow/TrackCosmicsWriterSpec.h" #include "Algorithm/RangeTokenizer.h" diff --git a/Detectors/GlobalTrackingWorkflow/src/primary-vertex-reader-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/primary-vertex-reader-workflow.cxx index 1342cdb22a4b0..2011865bed311 100644 --- a/Detectors/GlobalTrackingWorkflow/src/primary-vertex-reader-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/primary-vertex-reader-workflow.cxx @@ -11,7 +11,7 @@ #include "CommonUtils/ConfigurableParam.h" #include "Framework/CompletionPolicy.h" #include "Framework/ConfigParamSpec.h" -#include "GlobalTrackingWorkflow/PrimaryVertexReaderSpec.h" +#include "GlobalTrackingWorkflowReaders/PrimaryVertexReaderSpec.h" using namespace o2::framework; diff --git a/Detectors/GlobalTrackingWorkflow/src/primary-vertexing-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/primary-vertexing-workflow.cxx index bd5818228bf89..8123aa72c6730 100644 --- a/Detectors/GlobalTrackingWorkflow/src/primary-vertexing-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/primary-vertexing-workflow.cxx @@ -10,7 +10,7 @@ #include "GlobalTrackingWorkflow/PrimaryVertexingSpec.h" #include "GlobalTrackingWorkflow/PrimaryVertexWriterSpec.h" -#include "GlobalTrackingWorkflow/TrackTPCITSReaderSpec.h" +#include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" #include "GlobalTrackingWorkflow/VertexTrackMatcherSpec.h" #include "ITSWorkflow/TrackReaderSpec.h" #include "TPCWorkflow/TrackReaderSpec.h" diff --git a/Detectors/GlobalTrackingWorkflow/src/secondary-vertex-reader-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/secondary-vertex-reader-workflow.cxx index 433d095889277..440e431414417 100644 --- a/Detectors/GlobalTrackingWorkflow/src/secondary-vertex-reader-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/secondary-vertex-reader-workflow.cxx @@ -11,7 +11,7 @@ #include "CommonUtils/ConfigurableParam.h" #include "Framework/CompletionPolicy.h" #include "Framework/ConfigParamSpec.h" -#include "GlobalTrackingWorkflow/SecondaryVertexReaderSpec.h" +#include "GlobalTrackingWorkflowReaders/SecondaryVertexReaderSpec.h" using namespace o2::framework; diff --git a/Detectors/GlobalTrackingWorkflow/src/secondary-vertexing-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/secondary-vertexing-workflow.cxx index f068109e489f8..1b0607894aef3 100644 --- a/Detectors/GlobalTrackingWorkflow/src/secondary-vertexing-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/secondary-vertexing-workflow.cxx @@ -10,8 +10,8 @@ #include "GlobalTrackingWorkflow/SecondaryVertexingSpec.h" #include "GlobalTrackingWorkflow/SecondaryVertexWriterSpec.h" -#include "GlobalTrackingWorkflow/TrackTPCITSReaderSpec.h" -#include "GlobalTrackingWorkflow/PrimaryVertexReaderSpec.h" +#include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" +#include "GlobalTrackingWorkflowReaders/PrimaryVertexReaderSpec.h" #include "ITSWorkflow/TrackReaderSpec.h" #include "TPCWorkflow/TrackReaderSpec.h" #include "TOFWorkflow/TOFMatchedReaderSpec.h" diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/CMakeLists.txt b/Detectors/GlobalTrackingWorkflow/tofworkflow/CMakeLists.txt index 22e5e927b488d..411cbd935bd6a 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/CMakeLists.txt +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/CMakeLists.txt @@ -15,8 +15,8 @@ o2_add_library(TOFWorkflow src/TOFCalibWriterSpec.cxx src/TOFMatchedReaderSpec.cxx src/CalibInfoReaderSpec.cxx - PUBLIC_LINK_LIBRARIES O2::Framework O2::TOFBase O2::DataFormatsTOF O2::TOFReconstruction - O2::GlobalTracking O2::GlobalTrackingWorkflow O2::TOFWorkflowUtils + PUBLIC_LINK_LIBRARIES O2::Framework O2::TOFBase O2::DataFormatsTOF O2::TOFReconstruction + O2::GlobalTracking O2::GlobalTrackingWorkflowReaders O2::TOFWorkflowUtils O2::TOFCalibration O2::DataFormatsFT0 O2::FT0Reconstruction O2::FT0Workflow O2::TPCWorkflow) diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-calibinfo-reader.cxx b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-calibinfo-reader.cxx index 1ef91b1047e27..f66630a798d55 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-calibinfo-reader.cxx +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-calibinfo-reader.cxx @@ -14,7 +14,7 @@ /// @brief Basic DPL workflow for TOF reconstruction starting from digits #include "DetectorsBase/Propagator.h" -#include "GlobalTrackingWorkflow/TrackTPCITSReaderSpec.h" +#include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" #include "TOFWorkflow/CalibInfoReaderSpec.h" #include "Framework/WorkflowSpec.h" #include "Framework/ConfigParamSpec.h" diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-global.cxx b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-global.cxx index 8db17a14a17c4..447e43b66ef38 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-global.cxx +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-global.cxx @@ -14,7 +14,7 @@ /// @brief Basic DPL workflow for TOF reconstruction starting from digits #include "DetectorsBase/Propagator.h" -#include "GlobalTrackingWorkflow/TrackTPCITSReaderSpec.h" +#include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" #include "TOFWorkflowUtils/ClusterReaderSpec.h" #include "TOFWorkflow/TOFMatchedWriterSpec.h" #include "TOFWorkflow/TOFCalibWriterSpec.h" diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-reco-workflow.cxx b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-reco-workflow.cxx index 5b07c20c2db69..ee523d55f5c34 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-reco-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-reco-workflow.cxx @@ -14,7 +14,7 @@ /// @brief Basic DPL workflow for TOF reconstruction starting from digits #include "DetectorsBase/Propagator.h" -#include "GlobalTrackingWorkflow/TrackTPCITSReaderSpec.h" +#include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" #include "TOFWorkflowUtils/DigitReaderSpec.h" #include "TOFWorkflowUtils/TOFDigitWriterSpec.h" #include "TOFWorkflowUtils/ClusterReaderSpec.h" diff --git a/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TrackInterpolationWorkflow.cxx b/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TrackInterpolationWorkflow.cxx index 51f35793df446..985b30532ef34 100644 --- a/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TrackInterpolationWorkflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TrackInterpolationWorkflow.cxx @@ -15,7 +15,7 @@ #include "ITSWorkflow/TrackReaderSpec.h" #include "TPCWorkflow/TrackReaderSpec.h" #include "TPCWorkflow/ClusterReaderSpec.h" -#include "GlobalTrackingWorkflow/TrackTPCITSReaderSpec.h" +#include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" #include "TOFWorkflowUtils/ClusterReaderSpec.h" #include "TOFWorkflow/TOFMatchedReaderSpec.h" #include "Algorithm/RangeTokenizer.h" diff --git a/Detectors/TRD/workflow/CMakeLists.txt b/Detectors/TRD/workflow/CMakeLists.txt index 402102d857b2e..c5e2e2047006b 100644 --- a/Detectors/TRD/workflow/CMakeLists.txt +++ b/Detectors/TRD/workflow/CMakeLists.txt @@ -26,7 +26,7 @@ o2_add_library(TRDWorkflow src/TRDTrackingWorkflow.cxx src/EntropyDecoderSpec.cxx src/EntropyEncoderSpec.cxx - PUBLIC_LINK_LIBRARIES O2::Framework O2::DPLUtils O2::Steer O2::Algorithm O2::DataFormatsTRD O2::TRDSimulation O2::TRDReconstruction O2::DetectorsBase O2::SimulationDataFormat O2::TRDBase O2::TRDCalibration O2::GPUTracking O2::GlobalTrackingWorkflow) + PUBLIC_LINK_LIBRARIES O2::Framework O2::DPLUtils O2::Steer O2::Algorithm O2::DataFormatsTRD O2::TRDSimulation O2::TRDReconstruction O2::DetectorsBase O2::SimulationDataFormat O2::TRDBase O2::TRDCalibration O2::GPUTracking O2::GlobalTrackingWorkflowReaders) #o2_target_root_dictionary(TRDWorkflow # HEADERS include/TRDWorkflow/TRDTrapSimulatorSpec.h) diff --git a/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx b/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx index 281c4f9d20a9e..aa9852843eb7d 100644 --- a/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx +++ b/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx @@ -13,7 +13,7 @@ #include #include "Framework/WorkflowSpec.h" -#include "GlobalTrackingWorkflow/TrackTPCITSReaderSpec.h" +#include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" #include "TRDWorkflow/TRDTrackletReaderSpec.h" #include "TRDWorkflow/TRDGlobalTrackingSpec.h" #include "TRDWorkflow/TRDTrackWriterSpec.h" From 82cb9677f7a5d72c33e48f258097ac0e65b28cda Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 22 Apr 2021 20:46:18 +0200 Subject: [PATCH 242/770] Add Generic global track and cluster reader as example for InputHelper --- .../helpers/CMakeLists.txt | 7 +++ .../helpers/src/GlobalTrackClusterReader.cxx | 43 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 Detectors/GlobalTrackingWorkflow/helpers/src/GlobalTrackClusterReader.cxx diff --git a/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt b/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt index 7fe9b6e2fb605..b94b5fe6b37e6 100644 --- a/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt +++ b/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt @@ -11,6 +11,7 @@ o2_add_library(GlobalTrackingWorkflowHelpers SOURCES src/InputHelper.cxx PUBLIC_LINK_LIBRARIES O2::ReconstructionDataFormats + O2::Framework PRIVATE_LINK_LIBRARIES O2::GlobalTracking # We link all the workflow libs etc as PRIVATE, such that we do not expose tons of headers automatically O2::ITSWorkflow O2::ITSMFTWorkflow @@ -19,3 +20,9 @@ o2_add_library(GlobalTrackingWorkflowHelpers O2::FT0Workflow O2::ITSMFTWorkflow O2::SimulationDataFormat) + +o2_add_executable(track-cluster-reader + COMPONENT_NAME global + TARGETVARNAME targetName + SOURCES src/GlobalTrackClusterReader.cxx + PUBLIC_LINK_LIBRARIES O2::GlobalTrackingWorkflowHelpers) diff --git a/Detectors/GlobalTrackingWorkflow/helpers/src/GlobalTrackClusterReader.cxx b/Detectors/GlobalTrackingWorkflow/helpers/src/GlobalTrackClusterReader.cxx new file mode 100644 index 0000000000000..642bdfc081290 --- /dev/null +++ b/Detectors/GlobalTrackingWorkflow/helpers/src/GlobalTrackClusterReader.cxx @@ -0,0 +1,43 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "Framework/ConfigParamSpec.h" +#include "GlobalTrackingWorkflowHelpers/InputHelper.h" +#include "ReconstructionDataFormats/GlobalTrackID.h" + +using namespace o2::framework; +using namespace o2::globaltracking; +using namespace o2::dataformats; + +void customize(std::vector& workflowOptions) +{ + std::vector options{ + {"disable-mc", o2::framework::VariantType::Bool, false, {"disable visualization of MC data"}}, + {"track-types", VariantType::String, std::string{GlobalTrackID::ALL}, {"comma-separated list of track sources to read"}}, + {"cluster-types", VariantType::String, std::string{GlobalTrackID::ALL}, {"comma-separated list of cluster sources to read"}}, + {"disable-root-input", o2::framework::VariantType::Bool, false, {"disable reading root files, essentially making this workflow void, but needed for compatibility"}}, + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings ..."}}}; + + std::swap(workflowOptions, options); +} + +#include "Framework/runDataProcessing.h" + +WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) +{ + WorkflowSpec specs; + + bool useMC = !cfgc.options().get("disable-mc"); + GlobalTrackID::mask_t srcTrk = GlobalTrackID::getSourcesMask(cfgc.options().get("track-types")); + GlobalTrackID::mask_t srcCl = GlobalTrackID::getSourcesMask(cfgc.options().get("cluster-types")); + InputHelper::addInputSpecs(cfgc, specs, srcCl, srcTrk, srcTrk, useMC); + + return std::move(specs); +} From a5de4ca7a3b43479c158b0e55e3aad5c8ed7abb2 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 22 Apr 2021 21:41:11 +0200 Subject: [PATCH 243/770] TPC Workflow: add --disable-root-input option --- .../include/TPCWorkflow/RecoWorkflow.h | 1 + Detectors/TPC/workflow/src/RecoWorkflow.cxx | 106 +++++++++--------- .../TPC/workflow/src/tpc-reco-workflow.cxx | 2 + 3 files changed, 57 insertions(+), 52 deletions(-) diff --git a/Detectors/TPC/workflow/include/TPCWorkflow/RecoWorkflow.h b/Detectors/TPC/workflow/include/TPCWorkflow/RecoWorkflow.h index 5f2ef01fdb2ca..653b3e526c1df 100644 --- a/Detectors/TPC/workflow/include/TPCWorkflow/RecoWorkflow.h +++ b/Detectors/TPC/workflow/include/TPCWorkflow/RecoWorkflow.h @@ -74,6 +74,7 @@ framework::WorkflowSpec getWorkflow(CompletionPolicyData* policyData, bool propagateMC = true, unsigned nLanes = 1, // std::string const& cfgInput = "digitizer", // std::string const& cfgOutput = "tracks", // + bool disableRootInput = false, // int caClusterer = 0, // int zsOnTheFly = 0, int zs10bit = 0, diff --git a/Detectors/TPC/workflow/src/RecoWorkflow.cxx b/Detectors/TPC/workflow/src/RecoWorkflow.cxx index 2dfda3f38ae2f..804b5cc1fb6e8 100644 --- a/Detectors/TPC/workflow/src/RecoWorkflow.cxx +++ b/Detectors/TPC/workflow/src/RecoWorkflow.cxx @@ -88,7 +88,7 @@ const std::unordered_map OutputMap{ {"no-shared-cluster-map", OutputType::NoSharedClusterMap}}; framework::WorkflowSpec getWorkflow(CompletionPolicyData* policyData, std::vector const& tpcSectors, unsigned long tpcSectorMask, std::vector const& laneConfiguration, - bool propagateMC, unsigned nLanes, std::string const& cfgInput, std::string const& cfgOutput, + bool propagateMC, unsigned nLanes, std::string const& cfgInput, std::string const& cfgOutput, bool disableRootInput, int caClusterer, int zsOnTheFly, int zs10bit, float zsThreshold, bool askDISTSTF) { InputType inputType; @@ -159,57 +159,59 @@ framework::WorkflowSpec getWorkflow(CompletionPolicyData* policyData, std::vecto return false; }}; - // The OutputSpec of the PublisherSpec is configured depending on the input - // type. Note that the configuration of the dispatch trigger in the main file - // needs to be done in accordance. This means, if a new input option is added - // also the dispatch trigger needs to be updated. - if (inputType == InputType::Digits) { - using Type = std::vector; - - specs.emplace_back(o2::tpc::getPublisherSpec(PublisherConf{ - "tpc-digit-reader", - "tpcdigits.root", - "o2sim", - {"digitbranch", "TPCDigit", "Digit branch"}, - {"mcbranch", "TPCDigitMCTruth", "MC label branch"}, - OutputSpec{"TPC", "DIGITS"}, - OutputSpec{"TPC", "DIGITSMCTR"}, - tpcSectors, - laneConfiguration, - &hook}, - propagateMC)); - } else if (inputType == InputType::ClustersHardware) { - specs.emplace_back(o2::tpc::getPublisherSpec(PublisherConf{ - "tpc-clusterhardware-reader", - "tpc-clusterhardware.root", - "tpcclustershardware", - {"databranch", "TPCClusterHw", "Branch with TPC ClustersHardware"}, - {"mcbranch", "TPCClusterHwMCTruth", "MC label branch"}, - OutputSpec{"TPC", "CLUSTERHW"}, - OutputSpec{"TPC", "CLUSTERHWMCLBL"}, - tpcSectors, - laneConfiguration, - &hook}, - propagateMC)); - } else if (inputType == InputType::Clusters) { - specs.emplace_back(o2::tpc::getClusterReaderSpec(propagateMC, &tpcSectors, &laneConfiguration)); - } else if (inputType == InputType::CompClusters) { - // TODO: need to check if we want to store the MC labels alongside with compressed clusters - // for the moment reading of labels is disabled (last parameter is false) - // TODO: make a different publisher spec for only one output spec, for now using the - // PublisherSpec with only sector 0, '_0' is thus appended to the branch name - specs.emplace_back(o2::tpc::getPublisherSpec(PublisherConf{ - "tpc-compressed-cluster-reader", - "tpc-compclusters.root", - "tpcrec", - {"clusterbranch", "TPCCompClusters", "Branch with TPC compressed clusters"}, - {"", "", ""}, // No MC labels - OutputSpec{"TPC", "COMPCLUSTERS"}, - OutputSpec{"", ""}, // No MC labels - std::vector(1, 0), - std::vector(1, 0), - &hook}, - false)); + if (!disableRootInput) { + // The OutputSpec of the PublisherSpec is configured depending on the input + // type. Note that the configuration of the dispatch trigger in the main file + // needs to be done in accordance. This means, if a new input option is added + // also the dispatch trigger needs to be updated. + if (inputType == InputType::Digits) { + using Type = std::vector; + + specs.emplace_back(o2::tpc::getPublisherSpec(PublisherConf{ + "tpc-digit-reader", + "tpcdigits.root", + "o2sim", + {"digitbranch", "TPCDigit", "Digit branch"}, + {"mcbranch", "TPCDigitMCTruth", "MC label branch"}, + OutputSpec{"TPC", "DIGITS"}, + OutputSpec{"TPC", "DIGITSMCTR"}, + tpcSectors, + laneConfiguration, + &hook}, + propagateMC)); + } else if (inputType == InputType::ClustersHardware) { + specs.emplace_back(o2::tpc::getPublisherSpec(PublisherConf{ + "tpc-clusterhardware-reader", + "tpc-clusterhardware.root", + "tpcclustershardware", + {"databranch", "TPCClusterHw", "Branch with TPC ClustersHardware"}, + {"mcbranch", "TPCClusterHwMCTruth", "MC label branch"}, + OutputSpec{"TPC", "CLUSTERHW"}, + OutputSpec{"TPC", "CLUSTERHWMCLBL"}, + tpcSectors, + laneConfiguration, + &hook}, + propagateMC)); + } else if (inputType == InputType::Clusters) { + specs.emplace_back(o2::tpc::getClusterReaderSpec(propagateMC, &tpcSectors, &laneConfiguration)); + } else if (inputType == InputType::CompClusters) { + // TODO: need to check if we want to store the MC labels alongside with compressed clusters + // for the moment reading of labels is disabled (last parameter is false) + // TODO: make a different publisher spec for only one output spec, for now using the + // PublisherSpec with only sector 0, '_0' is thus appended to the branch name + specs.emplace_back(o2::tpc::getPublisherSpec(PublisherConf{ + "tpc-compressed-cluster-reader", + "tpc-compclusters.root", + "tpcrec", + {"clusterbranch", "TPCCompClusters", "Branch with TPC compressed clusters"}, + {"", "", ""}, // No MC labels + OutputSpec{"TPC", "COMPCLUSTERS"}, + OutputSpec{"", ""}, // No MC labels + std::vector(1, 0), + std::vector(1, 0), + &hook}, + false)); + } } // output matrix diff --git a/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx b/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx index 38e0fece3b9ff..432639f2cd7af 100644 --- a/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx +++ b/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx @@ -49,6 +49,7 @@ void customize(std::vector& workflowOptions) std::vector options{ {"input-type", VariantType::String, "digits", {"digitizer, digits, zsraw, clustershw, clustersnative, compressed-clusters, compressed-clusters-ctf"}}, {"output-type", VariantType::String, "tracks", {"digits, zsraw, clustershw, clustersnative, tracks, compressed-clusters, encoded-clusters, disable-writer, send-clusters-per-sector, qa, no-shared-cluster-map"}}, + {"disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input reader"}}, {"no-ca-clusterer", VariantType::Bool, false, {"Use HardwareClusterer instead of clusterer of GPUCATracking"}}, {"disable-mc", VariantType::Bool, false, {"disable sending of MC information"}}, {"tpc-sectors", VariantType::String, "0-35", {"TPC sector range, e.g. 5-7,8,9"}}, @@ -157,6 +158,7 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) nLanes, // inputType, // cfgc.options().get("output-type"), // + cfgc.options().get("disable-root-input"), // !cfgc.options().get("no-ca-clusterer"), // !cfgc.options().get("no-tpc-zs-on-the-fly"), // cfgc.options().get("zs-10bit"), // From d2c7b5ed16a01a77d11fb592b7bf16d1e8cb77fa Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 23 Apr 2021 09:03:40 +0200 Subject: [PATCH 244/770] TPC Workflow: by Ruben - fix copy and paste error --- Detectors/TPC/workflow/src/tpc-reco-workflow.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx b/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx index 432639f2cd7af..d460ccece3665 100644 --- a/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx +++ b/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx @@ -166,8 +166,8 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) !cfgc.options().get("ignore-dist-stf") // ); - // write the configuration used for the digitizer workflow - o2::conf::ConfigurableParam::writeINI("o2tpcrecoflow_configuration.ini"); + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(cfgc, wf); return std::move(wf); } From 4a67dc0933a1c5affdede7334aa68139fe27e227 Mon Sep 17 00:00:00 2001 From: pillot Date: Fri, 23 Apr 2021 19:40:40 +0200 Subject: [PATCH 245/770] [MCH] (Legacy) Clustering: move *all* pixels to be kept at the beginning (#5991) --- .../MCHClustering/ClusterFinderOriginal.h | 1 - .../Clustering/src/ClusterFinderOriginal.cxx | 20 +++---------------- 2 files changed, 3 insertions(+), 18 deletions(-) diff --git a/Detectors/MUON/MCH/Clustering/include/MCHClustering/ClusterFinderOriginal.h b/Detectors/MUON/MCH/Clustering/include/MCHClustering/ClusterFinderOriginal.h index be7a99c5bd69d..23bc881c8d753 100644 --- a/Detectors/MUON/MCH/Clustering/include/MCHClustering/ClusterFinderOriginal.h +++ b/Detectors/MUON/MCH/Clustering/include/MCHClustering/ClusterFinderOriginal.h @@ -91,7 +91,6 @@ class ClusterFinderOriginal double mlem(const std::vector& coef, const std::vector& prob, int nIter); void findCOG(const TH2D& histMLEM, double xy[2]) const; void refinePixelArray(const double xyCOG[2], size_t nPixMax, double& xMin, double& xMax, double& yMin, double& yMax); - void shiftPixelsToKeep(double charge); void cleanPixelArray(double threshold, std::vector& prob); int fit(const std::vector*>& clustersOfPixels, const double fitRange[2][2], double fitParam[SNFitParamMax + 1]); diff --git a/Detectors/MUON/MCH/Clustering/src/ClusterFinderOriginal.cxx b/Detectors/MUON/MCH/Clustering/src/ClusterFinderOriginal.cxx index 0c5cf9d1f5432..97d9ef12077c7 100644 --- a/Detectors/MUON/MCH/Clustering/src/ClusterFinderOriginal.cxx +++ b/Detectors/MUON/MCH/Clustering/src/ClusterFinderOriginal.cxx @@ -1125,12 +1125,11 @@ void ClusterFinderOriginal::refinePixelArray(const double xyCOG[2], size_t nPixM yMin = std::numeric_limits::max(); yMax = -std::numeric_limits::max(); - // sort pixels according to the charge and move all pixels that must be kept at the begining - shiftPixelsToKeep(10000.); + // sort pixels according to the charge and move all pixels that must be kept at the beginning std::stable_sort(mPixels.begin(), mPixels.end(), [](const PadOriginal& pixel1, const PadOriginal& pixel2) { - return pixel1.charge() > pixel2.charge(); + return (pixel1.status() == PadOriginal::kMustKeep && pixel2.status() != PadOriginal::kMustKeep) || + (pixel1.status() == pixel2.status() && pixel1.charge() > pixel2.charge()); }); - shiftPixelsToKeep(-10000.); double pixMinCharge = TMath::Min(0.01 * mPixels.front().charge(), 100. * SLowestPixelCharge); // define the half-size and shift of the new pixels depending on the direction of splitting @@ -1218,19 +1217,6 @@ void ClusterFinderOriginal::refinePixelArray(const double xyCOG[2], size_t nPixM } } -//_________________________________________________________________________________________________ -void ClusterFinderOriginal::shiftPixelsToKeep(double charge) -{ - /// add the given charge to the pixels tagged as kMustKeep - /// (just a trick to put them in front when sorting pixels by charge) - - for (auto& pixel : mPixels) { - if (pixel.status() == PadOriginal::kMustKeep) { - pixel.setCharge(pixel.charge() + charge); - } - } -} - //_________________________________________________________________________________________________ void ClusterFinderOriginal::cleanPixelArray(double threshold, std::vector& prob) { From e5fffbeb2e796747dd9b2dac245c5e23a314c440 Mon Sep 17 00:00:00 2001 From: shahoian Date: Fri, 23 Apr 2021 22:14:53 +0200 Subject: [PATCH 246/770] fix in GlobalTrackID::getSourcesNames format --- DataFormats/Reconstruction/src/GlobalTrackID.cxx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/DataFormats/Reconstruction/src/GlobalTrackID.cxx b/DataFormats/Reconstruction/src/GlobalTrackID.cxx index 44fb86e07d5bf..dd6f0f5c3eb9e 100644 --- a/DataFormats/Reconstruction/src/GlobalTrackID.cxx +++ b/DataFormats/Reconstruction/src/GlobalTrackID.cxx @@ -113,5 +113,6 @@ std::string GlobalTrackID::getSourcesNames(GlobalTrackID::mask_t srcm) s += getSourceName(i); } } + s += ']'; return std::move(s); -} \ No newline at end of file +} From 880a986fa009fd25e506c187bb05b9cba499a5b8 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Sat, 24 Apr 2021 07:25:35 +0200 Subject: [PATCH 247/770] DPL: fix in booking metrics (#5989) --- .../include/Framework/DeviceMetricsInfo.h | 14 ++- Framework/Core/src/DeviceMetricsHelper.cxx | 98 ++++++++++++------- .../Core/src/ResourcesMonitoringHelper.cxx | 38 ++++--- Framework/Core/src/runDataProcessing.cxx | 4 +- .../Core/test/test_DeviceMetricsInfo.cxx | 33 +++++-- .../GUISupport/src/FrameworkGUIDebugger.cxx | 10 +- 6 files changed, 121 insertions(+), 76 deletions(-) diff --git a/Framework/Core/include/Framework/DeviceMetricsInfo.h b/Framework/Core/include/Framework/DeviceMetricsInfo.h index e37415b711b32..afe4cd4b9857b 100644 --- a/Framework/Core/include/Framework/DeviceMetricsInfo.h +++ b/Framework/Core/include/Framework/DeviceMetricsInfo.h @@ -44,15 +44,18 @@ struct StringMetric { char data[MAX_SIZE]; }; -// Also for the keys it does not make much sense to keep more than 247 chars. +// Also for the keys it does not make much sense to keep more than 255 chars. // They should be nevertheless 0 terminated. -struct MetricLabelIndex { - static constexpr size_t MAX_METRIC_LABEL_SIZE = 256 - sizeof(size_t) - sizeof(unsigned char); // Maximum size for a metric name. - size_t index; +struct MetricLabel { + static constexpr size_t MAX_METRIC_LABEL_SIZE = 256 - sizeof(unsigned char); // Maximum size for a metric name. unsigned char size = 0; char label[MAX_METRIC_LABEL_SIZE]; }; +struct MetricLabelIndex { + size_t index; +}; + /// Temporary struct to hold a metric after it has been parsed. struct ParsedMetricMatch { char const* beginKey; @@ -80,7 +83,8 @@ struct DeviceMetricsInfo { std::vector min; std::vector minDomain; std::vector maxDomain; - std::vector metricLabelsIdx; + std::vector metricLabels; + std::vector metricLabelsAlphabeticallySortedIdx; std::vector metrics; std::vector changed; }; diff --git a/Framework/Core/src/DeviceMetricsHelper.cxx b/Framework/Core/src/DeviceMetricsHelper.cxx index ff1316c26a0a0..852c405a5bca4 100644 --- a/Framework/Core/src/DeviceMetricsHelper.cxx +++ b/Framework/Core/src/DeviceMetricsHelper.cxx @@ -110,35 +110,59 @@ bool DeviceMetricsHelper::parseMetric(std::string_view const s, ParsedMetricMatc return true; } -size_t DeviceMetricsHelper::bookMetricInfo(DeviceMetricsInfo& metrics, char const* name) +size_t DeviceMetricsHelper::bookMetricInfo(DeviceMetricsInfo& info, char const* name) { + // Add the index by name in the correct position + // this will require moving the tail of the index, + // but inserting should happen only once for each metric, + // so who cares. + // Add the the actual Metric info to the store + MetricLabel metricLabel; + strncpy(metricLabel.label, name, MetricLabel::MAX_METRIC_LABEL_SIZE - 1); + metricLabel.label[MetricLabel::MAX_METRIC_LABEL_SIZE - 1] = '\0'; + metricLabel.size = strlen(metricLabel.label); + + // Find the insertion point for the sorted index + auto cmpFn = [namePtr = metricLabel.label, + &labels = info.metricLabels, + nameSize = metricLabel.size](MetricLabelIndex const& a, MetricLabelIndex const& b) + -> bool { + return strncmp(labels[a.index].label, namePtr, nameSize) < 0; + }; + + auto mi = std::lower_bound(info.metricLabelsAlphabeticallySortedIdx.begin(), + info.metricLabelsAlphabeticallySortedIdx.end(), + MetricLabelIndex{}, + cmpFn); + + // If it was already there, return the old index. + if (mi != info.metricLabelsAlphabeticallySortedIdx.end() && (strncmp(info.metricLabels[mi->index].label, metricLabel.label, std::min((size_t)metricLabel.size, (size_t)MetricLabel::MAX_METRIC_LABEL_SIZE - 1)) == 0)) { + return mi->index; + } + // Add the the actual Metric info to the store - auto metricIndex = metrics.metrics.size(); - metrics.metrics.push_back(MetricInfo{}); + auto metricIndex = info.metrics.size(); + + // Insert the sorted location where it belongs to. + MetricLabelIndex metricLabelIdx{metricIndex}; + info.metricLabelsAlphabeticallySortedIdx.insert(mi, metricLabelIdx); + info.metrics.push_back(MetricInfo{}); + // Create a new metric - auto& metricInfo = metrics.metrics.back(); + auto& metricInfo = info.metrics.back(); metricInfo.pos = 0; metricInfo.filledMetrics = 0; // Add the timestamp buffer for it - metrics.timestamps.emplace_back(std::array{}); - metrics.max.push_back(std::numeric_limits::lowest()); - metrics.min.push_back(std::numeric_limits::max()); - metrics.maxDomain.push_back(std::numeric_limits::lowest()); - metrics.minDomain.push_back(std::numeric_limits::max()); - metrics.changed.push_back(true); + info.timestamps.emplace_back(std::array{}); + info.max.push_back(std::numeric_limits::lowest()); + info.min.push_back(std::numeric_limits::max()); + info.maxDomain.push_back(std::numeric_limits::lowest()); + info.minDomain.push_back(std::numeric_limits::max()); + info.changed.push_back(true); + + info.metricLabels.push_back(metricLabel); - // Add the index by name in the correct position - // this will require moving the tail of the index, - // but inserting should happen only once for each metric, - // so who cares. - // Add the the actual Metric info to the store - MetricLabelIndex metricLabelIdx; - strncpy(metricLabelIdx.label, name, MetricLabelIndex::MAX_METRIC_LABEL_SIZE - 1); - metricLabelIdx.label[MetricLabelIndex::MAX_METRIC_LABEL_SIZE - 1] = '\0'; - metricLabelIdx.index = metricIndex; - metricLabelIdx.size = strlen(metricLabelIdx.label); - metrics.metricLabelsIdx.push_back(metricLabelIdx); return metricIndex; } @@ -167,17 +191,19 @@ bool DeviceMetricsHelper::processMetric(ParsedMetricMatch& match, // Find the metric based on the label. Create it if not found. auto cmpFn = [namePtr = match.beginKey, + &labels = info.metricLabels, nameSize = match.endKey - match.beginKey](MetricLabelIndex const& a, MetricLabelIndex const& b) -> bool { - return strncmp(a.label, namePtr, nameSize) < 0; + return strncmp(labels[a.index].label, namePtr, nameSize) < 0; }; - auto mi = std::lower_bound(info.metricLabelsIdx.begin(), - info.metricLabelsIdx.end(), + auto mi = std::lower_bound(info.metricLabelsAlphabeticallySortedIdx.begin(), + info.metricLabelsAlphabeticallySortedIdx.end(), MetricLabelIndex{}, cmpFn); // We could not find the metric, lets insert a new one. - if (mi == info.metricLabelsIdx.end() || (strncmp(mi->label, match.beginKey, std::min(match.endKey - match.beginKey, (long)MetricLabelIndex::MAX_METRIC_LABEL_SIZE - 1)) != 0)) { + auto matchSize = match.endKey - match.beginKey; + if (mi == info.metricLabelsAlphabeticallySortedIdx.end() || (strncmp(info.metricLabels[mi->index].label, match.beginKey, std::min(matchSize, (long)MetricLabel::MAX_METRIC_LABEL_SIZE - 1)) != 0)) { // Create a new metric MetricInfo metricInfo; metricInfo.pos = 0; @@ -217,19 +243,21 @@ bool DeviceMetricsHelper::processMetric(ParsedMetricMatch& match, // this will require moving the tail of the index, // but inserting should happen only once for each metric, // so who cares. + MetricLabel metricLabel; + auto lastChar = std::min(match.endKey - match.beginKey, (ptrdiff_t)MetricLabel::MAX_METRIC_LABEL_SIZE - 1); + memcpy(metricLabel.label, match.beginKey, lastChar); + metricLabel.label[lastChar] = '\0'; + metricLabel.size = lastChar; MetricLabelIndex metricLabelIdx; - auto lastChar = std::min(match.endKey - match.beginKey, (ptrdiff_t)MetricLabelIndex::MAX_METRIC_LABEL_SIZE - 1); - memcpy(metricLabelIdx.label, match.beginKey, lastChar); - metricLabelIdx.label[lastChar] = '\0'; - metricLabelIdx.size = lastChar; metricLabelIdx.index = info.metrics.size(); - info.metricLabelsIdx.insert(mi, metricLabelIdx); + info.metricLabels.push_back(metricLabel); + info.metricLabelsAlphabeticallySortedIdx.insert(mi, metricLabelIdx); // Add the the actual Metric info to the store metricIndex = info.metrics.size(); assert(metricInfo.storeIdx != -1); - assert(metricLabelIdx.label[0] != '\0'); + assert(metricLabel.label[0] != '\0'); if (newMetricsCallback != nullptr) { - newMetricsCallback(metricLabelIdx.label, metricInfo, match.intValue, metricIndex); + newMetricsCallback(metricLabel.label, metricInfo, match.intValue, metricIndex); } info.metrics.push_back(metricInfo); } else { @@ -297,12 +325,12 @@ bool DeviceMetricsHelper::processMetric(ParsedMetricMatch& match, size_t DeviceMetricsHelper::metricIdxByName(const std::string& name, const DeviceMetricsInfo& info) { size_t i = 0; - while (i < info.metricLabelsIdx.size()) { - auto& metricName = info.metricLabelsIdx[i]; + while (i < info.metricLabels.size()) { + auto& metricName = info.metricLabels[i]; // We check the size first and then the last character because that's // likely to be different for multi-index metrics if (metricName.size == name.size() && metricName.label[metricName.size - 1] == name[metricName.size - 1] && memcmp(metricName.label, name.c_str(), metricName.size) == 0) { - return metricName.index; + return i; } ++i; } diff --git a/Framework/Core/src/ResourcesMonitoringHelper.cxx b/Framework/Core/src/ResourcesMonitoringHelper.cxx index 0b6ed333052af..3a0d33a1d21a4 100644 --- a/Framework/Core/src/ResourcesMonitoringHelper.cxx +++ b/Framework/Core/src/ResourcesMonitoringHelper.cxx @@ -68,10 +68,11 @@ bool ResourcesMonitoringHelper::dumpMetricsToJSON(const std::vector c // Calculate the unique set of metrics, as available in the metrics service static std::unordered_set allMetricsNames; for (const auto& metricsInfo : metricsInfos) { - for (const auto& labelsPairs : metricsInfo.metricLabelsIdx) { + for (const auto& labelsPairs : metricsInfo.metricLabels) { allMetricsNames.insert(std::string(labelsPairs.label)); } } - for (const auto& labelsPairs : driverInfo.metrics.metricLabelsIdx) { + for (const auto& labelsPairs : driverInfo.metrics.metricLabels) { allMetricsNames.insert(std::string(labelsPairs.label)); } std::vector result(allMetricsNames.begin(), allMetricsNames.end()); diff --git a/Framework/Core/test/test_DeviceMetricsInfo.cxx b/Framework/Core/test/test_DeviceMetricsInfo.cxx index 332c4e67c33b8..032a6ce7ead8d 100644 --- a/Framework/Core/test/test_DeviceMetricsInfo.cxx +++ b/Framework/Core/test/test_DeviceMetricsInfo.cxx @@ -39,9 +39,10 @@ BOOST_AUTO_TEST_CASE(TestDeviceMetricsInfo) // Add the first metric to the store result = DeviceMetricsHelper::processMetric(match, info); BOOST_CHECK_EQUAL(result, true); - BOOST_CHECK_EQUAL(info.metricLabelsIdx.size(), 1); - BOOST_CHECK(strncmp(info.metricLabelsIdx[0].label, "bkey", 4) == 0); - BOOST_CHECK_EQUAL(info.metricLabelsIdx[0].index, 0); + BOOST_CHECK_EQUAL(info.metricLabelsAlphabeticallySortedIdx.size(), 1); + BOOST_CHECK_EQUAL(info.metricLabels.size(), 1); + BOOST_CHECK(strncmp(info.metricLabels[0].label, "bkey", 4) == 0); + BOOST_CHECK_EQUAL(info.metricLabelsAlphabeticallySortedIdx[0].index, 0); BOOST_CHECK_EQUAL(info.intMetrics.size(), 1); BOOST_CHECK_EQUAL(info.floatMetrics.size(), 0); BOOST_CHECK_EQUAL(info.timestamps.size(), 1); @@ -61,7 +62,7 @@ BOOST_AUTO_TEST_CASE(TestDeviceMetricsInfo) BOOST_CHECK_EQUAL(match.intValue, 13); result = DeviceMetricsHelper::processMetric(match, info); BOOST_CHECK_EQUAL(result, true); - BOOST_CHECK_EQUAL(info.metricLabelsIdx.size(), 1); + BOOST_CHECK_EQUAL(info.metricLabels.size(), 1); BOOST_CHECK_EQUAL(info.intMetrics.size(), 1); BOOST_CHECK_EQUAL(info.intMetrics[0][0], 12); BOOST_CHECK_EQUAL(info.intMetrics[0][1], 13); @@ -74,7 +75,7 @@ BOOST_AUTO_TEST_CASE(TestDeviceMetricsInfo) BOOST_CHECK_EQUAL(result, true); result = DeviceMetricsHelper::processMetric(match, info); BOOST_CHECK_EQUAL(result, true); - BOOST_CHECK_EQUAL(info.metricLabelsIdx.size(), 2); + BOOST_CHECK_EQUAL(info.metricLabels.size(), 2); BOOST_CHECK_EQUAL(info.intMetrics.size(), 2); BOOST_CHECK_EQUAL(info.intMetrics[0][0], 12); BOOST_CHECK_EQUAL(info.intMetrics[0][1], 13); @@ -91,7 +92,7 @@ BOOST_AUTO_TEST_CASE(TestDeviceMetricsInfo) BOOST_CHECK_EQUAL(result, true); result = DeviceMetricsHelper::processMetric(match, info); BOOST_CHECK_EQUAL(result, true); - BOOST_CHECK_EQUAL(info.metricLabelsIdx.size(), 3); + BOOST_CHECK_EQUAL(info.metricLabels.size(), 3); BOOST_CHECK_EQUAL(info.intMetrics.size(), 2); BOOST_CHECK_EQUAL(info.floatMetrics.size(), 1); BOOST_CHECK_EQUAL(info.metrics.size(), 3); @@ -107,7 +108,7 @@ BOOST_AUTO_TEST_CASE(TestDeviceMetricsInfo) BOOST_CHECK_EQUAL(result, true); result = DeviceMetricsHelper::processMetric(match, info); BOOST_CHECK_EQUAL(result, true); - BOOST_CHECK_EQUAL(info.metricLabelsIdx.size(), 3); + BOOST_CHECK_EQUAL(info.metricLabels.size(), 3); BOOST_CHECK_EQUAL(info.intMetrics.size(), 2); BOOST_CHECK_EQUAL(info.floatMetrics.size(), 1); BOOST_CHECK_EQUAL(info.metrics.size(), 3); @@ -129,7 +130,8 @@ BOOST_AUTO_TEST_CASE(TestDeviceMetricsInfo) BOOST_CHECK_EQUAL(result, true); result = DeviceMetricsHelper::processMetric(match, info); BOOST_CHECK_EQUAL(result, true); - BOOST_CHECK_EQUAL(info.metricLabelsIdx.size(), 4); + BOOST_CHECK_EQUAL(info.metricLabels.size(), 4); + BOOST_CHECK_EQUAL(info.metricLabelsAlphabeticallySortedIdx.size(), 4); BOOST_CHECK_EQUAL(info.metrics.size(), 4); BOOST_CHECK_EQUAL(info.stringMetrics.size(), 1); BOOST_CHECK_EQUAL(info.metrics[3].type, MetricType::String); @@ -143,7 +145,8 @@ BOOST_AUTO_TEST_CASE(TestDeviceMetricsInfo) BOOST_CHECK_EQUAL(result, true); result = DeviceMetricsHelper::processMetric(match, info); BOOST_CHECK_EQUAL(result, true); - BOOST_CHECK_EQUAL(info.metricLabelsIdx.size(), 5); + BOOST_CHECK_EQUAL(info.metricLabels.size(), 5); + BOOST_CHECK_EQUAL(info.metricLabelsAlphabeticallySortedIdx.size(), 5); BOOST_CHECK_EQUAL(info.metrics.size(), 5); BOOST_CHECK_EQUAL(info.stringMetrics.size(), 2); BOOST_CHECK_EQUAL(info.metrics[4].type, MetricType::String); @@ -207,3 +210,15 @@ BOOST_AUTO_TEST_CASE(TestDeviceMetricsInfo2) BOOST_CHECK_EQUAL(info.uint64Metrics[0][1], 1025); BOOST_CHECK_EQUAL(info.uint64Metrics[0][2], 2); } + +BOOST_AUTO_TEST_CASE(TestHelpers) +{ + using namespace o2::framework; + DeviceMetricsInfo info; + auto metric1 = DeviceMetricsHelper::bookMetricInfo(info, "bkey"); + auto metric2 = DeviceMetricsHelper::bookMetricInfo(info, "bkey"); + auto metric3 = DeviceMetricsHelper::bookMetricInfo(info, "akey"); + BOOST_CHECK_EQUAL(metric1, 0); + BOOST_CHECK_EQUAL(metric2, 0); + BOOST_CHECK_EQUAL(metric3, 1); +} diff --git a/Framework/GUISupport/src/FrameworkGUIDebugger.cxx b/Framework/GUISupport/src/FrameworkGUIDebugger.cxx index 0dbcf3e5ef991..2fbd286107dff 100644 --- a/Framework/GUISupport/src/FrameworkGUIDebugger.cxx +++ b/Framework/GUISupport/src/FrameworkGUIDebugger.cxx @@ -197,7 +197,7 @@ void displayDeviceMetrics(const char* label, std::string const& selectedMetricNa for (int mi = 0; mi < metricsInfos.size(); ++mi) { auto vi = DeviceMetricsHelper::metricIdxByName(selectedMetricName, metricsInfos[mi]); - if (vi == metricsInfos[mi].metricLabelsIdx.size()) { + if (vi == metricsInfos[mi].metricLabels.size()) { continue; } auto& metric = metricsInfos[mi].metrics[vi]; @@ -239,7 +239,7 @@ void displayDeviceMetrics(const char* label, std::string const& selectedMetricNa } if (true) { auto vi = DeviceMetricsHelper::metricIdxByName(selectedMetricName, driverMetric); - if (vi < driverMetric.metricLabelsIdx.size()) { + if (vi < driverMetric.metricLabels.size()) { auto& metric = driverMetric.metrics[vi]; deviceNames.push_back("driver"); metricType = metric.type; @@ -411,7 +411,7 @@ void historyBar(gui::WorkspaceGUIState& globalGUIState, size_t i = DeviceMetricsHelper::metricIdxByName(currentMetricName, metricsInfo); // We did not find any plot, skipping this. - if (i == metricsInfo.metricLabelsIdx.size()) { + if (i == metricsInfo.metricLabels.size()) { ImGui::NextColumn(); return; } @@ -491,7 +491,7 @@ std::vector calculateTableIndex(gui::WorkspaceGUIState& globalGUISta size_t idx = DeviceMetricsHelper::metricIdxByName(currentMetricName, metricsInfo); // We did not find any plot, skipping this. - if (idx == metricsInfo.metricLabelsIdx.size()) { + if (idx == metricsInfo.metricLabels.size()) { columns.push_back({MetricType::Int, -1}); continue; } @@ -556,7 +556,7 @@ void displayDeviceHistograms(gui::WorkspaceGUIState& state, currentMetricName = driverInfo.availableMetrics[state.selectedMetric]; for (auto& metricInfo : metricsInfos) { size_t mi = DeviceMetricsHelper::metricIdxByName(currentMetricName, metricInfo); - if (mi == metricInfo.metricLabelsIdx.size()) { + if (mi == metricInfo.metricLabels.size()) { continue; } auto& metric = metricInfo.metrics[mi]; From 2a7783a8369033ad1659af85bf36160aedfbc9ce Mon Sep 17 00:00:00 2001 From: Dmitri Peresunko Date: Tue, 20 Apr 2021 23:37:20 +0300 Subject: [PATCH 248/770] Cell bits reordered; Geometry fixed; LG/HG ratio fixes --- .../PHOS/include/DataFormatsPHOS/Cell.h | 28 ++++----- DataFormats/Detectors/PHOS/src/Cell.cxx | 60 +++++++++---------- DataFormats/Detectors/PHOS/test/testCell.cxx | 16 ++--- Detectors/PHOS/base/README.md | 5 +- .../PHOS/base/include/PHOSBase/Geometry.h | 2 + Detectors/PHOS/base/src/Geometry.cxx | 18 +++--- Detectors/PHOS/base/src/Mapping.cxx | 26 ++++---- .../include/PHOSReconstruction/Clusterer.h | 9 ++- .../PHOS/reconstruction/src/AltroDecoder.cxx | 1 + .../PHOS/reconstruction/src/Clusterer.cxx | 4 +- .../include/PHOSSimulation/GeometryParams.h | 2 +- Detectors/PHOS/simulation/src/Detector.cxx | 40 +++++-------- Detectors/PHOS/simulation/src/Digitizer.cxx | 10 +++- .../PHOS/simulation/src/GeometryParams.cxx | 4 +- Detectors/PHOS/simulation/src/RawWriter.cxx | 14 +++-- .../workflow/src/RawToCellConverterSpec.cxx | 6 +- 16 files changed, 127 insertions(+), 118 deletions(-) diff --git a/DataFormats/Detectors/PHOS/include/DataFormatsPHOS/Cell.h b/DataFormats/Detectors/PHOS/include/DataFormatsPHOS/Cell.h index 809296a48eace..3d853882501e6 100644 --- a/DataFormats/Detectors/PHOS/include/DataFormatsPHOS/Cell.h +++ b/DataFormats/Detectors/PHOS/include/DataFormatsPHOS/Cell.h @@ -16,20 +16,19 @@ // Structure: // Bits 39: Cell type: 0=Low Gain, 1=High Gain -// Bits 24-38: Energy (input/output in GeV/c^2, resolution 1 ADC count) -// Bits 14-23: Time (ns) -// Bits 0-13: Address: absID or TRU address +// Bits 27-38: 12 bit, Amplitude (HG, resolution 0.25 ADC count, LG resolution 1 ADC count, dynamic range 4096) +// Bits 14-26: 13 bit, Time (ns) +// Bits 0-13: 14 bit, Address: absID or TRU address namespace o2 { namespace phos { -constexpr int kOffset = 1792; // offset due to missing half of module 1: 56*32 -constexpr int kNmaxCell = 14337; //56*64*4 + 1 - kOffset -constexpr float kEnergyConv = 0.005; //Energy digitization step -constexpr float kTimeAccuracy = 0.3e-9; //Time digitization step -constexpr float kTime0 = 150.e-9; //-Minimal time to be digitized +constexpr int kOffset = 1792; // offset due to missing half of module 1: 56*32 +constexpr int kNmaxCell = 14337; //56*64*4 + 1 - kOffset +constexpr float kTimeAccuracy = 0.25e-9; //Time digitization step +constexpr float kTime0 = -500.e-9; //Minimal time to be digitized with 13 bits -500,1548 ns enum ChannelType_t { HIGH_GAIN, ///< High gain channel @@ -48,12 +47,13 @@ class Cell void setAbsId(short absId); short getAbsId() const; - void setTRUId(short truId); + //return pure TRUid (absId with subtracted readout channels offset) short getTRUId() const; void setTime(float time); float getTime() const; + //make sure that type of Cell (HG/LG) set before filling energy: scale will be different! void setEnergy(float energy); float getEnergy() const; @@ -77,18 +77,18 @@ class Cell uint16_t getPackedID() const { return getLong() & 0x3fff; } void setPackedID(uint16_t v) { mBits = (getLong() & 0xffffffc000) + (v & 0x3fff); } - uint16_t getPackedTime() const { return (getLong() >> 14) & 0x3ff; } - void setPackedTime(uint16_t v) { mBits = (getLong() & 0xffff003fff) + (uint64_t(v & 0x3ff) << 14); } + uint16_t getPackedTime() const { return (getLong() >> 14) & 0x1fff; } + void setPackedTime(uint16_t v) { mBits = (getLong() & 0xfff8003fff) + (uint64_t(v & 0x1fff) << 14); } - uint16_t getPackedEnergy() const { return (getLong() >> 24) & 0x7fff; } - void setPackedEnergy(uint16_t v) { mBits = (getLong() & 0x8000ffffff) + (uint64_t(v & 0x7fff) << 24); } + uint16_t getPackedEnergy() const { return (getLong() >> 27) & 0xfff; } + void setPackedEnergy(uint16_t v) { mBits = (getLong() & 0x8007ffffff) + (uint64_t(v & 0xfff) << 27); } uint8_t getPackedCellStatus() const { return mBits[39]; } void setPackedCellStatus(uint8_t v) { mBits[39] = v ? true : false; } void setPacked(uint16_t id, uint16_t t, uint16_t en, uint16_t status) { - mBits = uint64_t(id & 0x3fff) + (uint64_t(t & 0x3ff) << 14) + (uint64_t(en & 0x7fff) << 24) + (uint64_t(status & 0x1) << 39); + mBits = uint64_t(id & 0x3fff) + (uint64_t(t & 0x1fff) << 14) + (uint64_t(en & 0xfff) << 27) + (uint64_t(status & 0x1) << 39); } private: diff --git a/DataFormats/Detectors/PHOS/src/Cell.cxx b/DataFormats/Detectors/PHOS/src/Cell.cxx index 320c76d9656f1..08fa8c5c3f137 100644 --- a/DataFormats/Detectors/PHOS/src/Cell.cxx +++ b/DataFormats/Detectors/PHOS/src/Cell.cxx @@ -22,20 +22,16 @@ using namespace o2::phos; Cell::Cell(short absId, float energy, float time, ChannelType_t ctype) { - if (ctype == ChannelType_t::TRU2x2 || ctype == ChannelType_t::TRU4x4) { - setTRUId(absId); - } else { - setAbsId(absId); - } + setAbsId(absId); setTime(time); - setEnergy(energy); setType(ctype); + setEnergy(energy); } void Cell::setAbsId(short absId) { //14 bits available - if (absId > kNmaxCell || absId < kOffset) { + if (absId < kOffset) { absId = kNmaxCell; } ULong_t t = (ULong_t)(absId - kOffset); @@ -43,16 +39,6 @@ void Cell::setAbsId(short absId) ULong_t b = getLong() & 0xffffffc000; // 1111 1111 1111 1111 1111 1111 1100 0000 0000 0000 mBits = b + t; } -void Cell::setTRUId(short absId) -{ - //14 bits available - absId += kNmaxCell - kOffset + 1; - ULong_t t = (ULong_t)absId; - - ULong_t b = getLong() & 0xffffffc000; // 1111 1111 1111 1111 1111 1111 1100 0000 0000 0000 - mBits = b + t; -} - short Cell::getAbsId() const { ULong_t t = getLong() & 0x3fff; //14 bits @@ -80,9 +66,9 @@ void Cell::setTime(float time) //10 bits available for time ULong_t t = 0; //Convert time to long - t = ULong_t((time + kTime0) / kTimeAccuracy); - if (t > 0x3ff) { - t = 0x3ff; + t = ULong_t((time - kTime0) / kTimeAccuracy); + if (t > 0x1fff) { + t = 0x1fff; } else { if (t < 0) { t = 0; @@ -90,37 +76,45 @@ void Cell::setTime(float time) } t <<= 14; - ULong_t b = getLong() & 0xffff003fff; // 1111 1111 1111 1111 0000 0000 0011 1111 1111 1111 + ULong_t b = getLong() & 0xfff8003fff; // 1111 1111 1111 1000 0000 0000 0011 1111 1111 1111 mBits = b + t; } - float Cell::getTime() const { ULong_t t = getLong(); t >>= 14; - t &= 0x3ff; + t &= 0x1fff; //Convert back long to float - return float(t * kTimeAccuracy) - kTime0; + return float(t * kTimeAccuracy) + kTime0; } -void Cell::setEnergy(float energy) +void Cell::setEnergy(float amp) { - //15 bits - ULong_t a = static_cast(energy / kEnergyConv); - a = a & 0x7FFF; //15 bits + //12 bits + ULong_t a; + if (getType() == HIGH_GAIN) { + a = static_cast(amp * 4); + } else { + a = static_cast(amp); + } + a = a & 0xfff; //12 bits - a <<= 24; - ULong_t b = getLong() & 0x8000ffffff; // 1000 0000 0000 0000 1111 1111 1111 1111 1111 1111 + a <<= 27; + ULong_t b = getLong() & 0x8007ffffff; // 1000 0000 0000 0111 1111 1111 1111 1111 1111 1111 mBits = b + a; } float Cell::getEnergy() const { ULong_t a = getLong(); - a >>= 24; - a &= 0x7FFF; - return float(a * kEnergyConv); + a >>= 27; + a &= 0xfff; + if (getType() == HIGH_GAIN) { + return float(0.25 * a); + } else { + return float(a); + } } void Cell::setType(ChannelType_t ctype) diff --git a/DataFormats/Detectors/PHOS/test/testCell.cxx b/DataFormats/Detectors/PHOS/test/testCell.cxx index c2ea2b085f2d4..a9b8850610fa5 100644 --- a/DataFormats/Detectors/PHOS/test/testCell.cxx +++ b/DataFormats/Detectors/PHOS/test/testCell.cxx @@ -34,16 +34,16 @@ BOOST_AUTO_TEST_CASE(Cell_test) BOOST_CHECK_EQUAL(c.getAbsId(), j); BOOST_CHECK_EQUAL(c.getTRUId(), 0); BOOST_CHECK_SMALL(c.getTime() - float(0.), kTimeAccuracy); - BOOST_CHECK_SMALL(c.getEnergy() - 0, kEnergyConv); + BOOST_CHECK_SMALL(c.getEnergy() - 0, float(0.1)); BOOST_CHECK_EQUAL(c.getLowGain(), true); BOOST_CHECK_EQUAL(c.getTRU(), false); } for (short j = 0; j < 3136; j++) { //TRU - c.setTRUId(j); + c.setAbsId(14337 + 1 + j); BOOST_CHECK_EQUAL(c.getAbsId(), 0); BOOST_CHECK_EQUAL(c.getTRUId(), j); BOOST_CHECK_SMALL(c.getTime() - float(0.), kTimeAccuracy); - BOOST_CHECK_SMALL(c.getEnergy() - float(0), kEnergyConv); + BOOST_CHECK_SMALL(c.getEnergy() - float(0), float(0.1)); BOOST_CHECK_EQUAL(c.getTRU(), true); } @@ -54,18 +54,18 @@ BOOST_AUTO_TEST_CASE(Cell_test) c.setTime(t); BOOST_CHECK_EQUAL(c.getAbsId(), 1793); BOOST_CHECK_SMALL(c.getTime() - t, kTimeAccuracy); - BOOST_CHECK_SMALL(c.getEnergy() - float(0), kEnergyConv); + BOOST_CHECK_SMALL(c.getEnergy() - float(0), float(0.1)); BOOST_CHECK_EQUAL(c.getLowGain(), true); } c.setTime(0); - std::vector energies = {0.010, 0.025, 1, 2, 5, 10, 20, 40, 60, 100, 150}; + std::vector energies = {2., 5., 10., 50., 100., 200., 500., 900., 1200., 1600., 2000.}; for (float e : energies) { c.setEnergy(e); BOOST_CHECK_EQUAL(c.getAbsId(), 1793); BOOST_CHECK_SMALL(c.getTime() - float(0.), kTimeAccuracy); - BOOST_CHECK_SMALL(e - c.getEnergy(), kEnergyConv); // Require 5 MeV resolution + BOOST_CHECK_SMALL(e - c.getEnergy(), float(0.1)); BOOST_CHECK_EQUAL(c.getLowGain(), true); } @@ -74,7 +74,7 @@ BOOST_AUTO_TEST_CASE(Cell_test) c.setLowGain(); BOOST_CHECK_EQUAL(c.getAbsId(), 1793); BOOST_CHECK_SMALL(c.getTime() - float(0.), kTimeAccuracy); - BOOST_CHECK_SMALL(c.getEnergy() - float(0), kEnergyConv); + BOOST_CHECK_SMALL(c.getEnergy() - float(0), float(0.1)); BOOST_CHECK_EQUAL(c.getLowGain(), true); BOOST_CHECK_EQUAL(c.getHighGain(), false); BOOST_CHECK_EQUAL(c.getTRU(), false); @@ -82,7 +82,7 @@ BOOST_AUTO_TEST_CASE(Cell_test) c.setHighGain(); BOOST_CHECK_EQUAL(c.getAbsId(), 1793); BOOST_CHECK_SMALL(c.getTime() - float(0.), kTimeAccuracy); - BOOST_CHECK_SMALL(c.getEnergy() - float(0), kEnergyConv); + BOOST_CHECK_SMALL(c.getEnergy() - float(0), float(0.1)); BOOST_CHECK_EQUAL(c.getLowGain(), false); BOOST_CHECK_EQUAL(c.getHighGain(), true); BOOST_CHECK_EQUAL(c.getTRU(), false); diff --git a/Detectors/PHOS/base/README.md b/Detectors/PHOS/base/README.md index 57abc096aaf21..c7d4d441c34f7 100644 --- a/Detectors/PHOS/base/README.md +++ b/Detectors/PHOS/base/README.md @@ -6,11 +6,12 @@ Module numbering: start from module 0 (non-existing), 1 (half-module), 2 (bottom),... 4(highest) -All channels have unique absId: start from 1 till 4*64*56. Numbering in each module starts at bottom left and first go in z direction: +All channels have unique absId: start from 1 till 4x64x56 (no absId in non-existing module). Numbering in each module starts at bottom left and first go in z direction: +``` 56 112 3584 ... ... ... 1 57 ...3529 - +``` One can use also relative numbering relid[3]: (module number[0...3], iphi[1...64], iz[1...56]) diff --git a/Detectors/PHOS/base/include/PHOSBase/Geometry.h b/Detectors/PHOS/base/include/PHOSBase/Geometry.h index 2d5b810df73b5..62f598e523060 100644 --- a/Detectors/PHOS/base/include/PHOSBase/Geometry.h +++ b/Detectors/PHOS/base/include/PHOSBase/Geometry.h @@ -126,6 +126,8 @@ class Geometry const std::string& GetName() const { return mGeoName; } + const TGeoHMatrix* getAlignmentMatrix(int mod) const { return &(mPHOS[mod]); } + private: static Geometry* sGeom; // Pointer to the unique instance of the singleton std::array mPHOS; //Rotation/shift matrices diff --git a/Detectors/PHOS/base/src/Geometry.cxx b/Detectors/PHOS/base/src/Geometry.cxx index 2be47cb493d66..c818c327a740e 100644 --- a/Detectors/PHOS/base/src/Geometry.cxx +++ b/Detectors/PHOS/base/src/Geometry.cxx @@ -59,7 +59,7 @@ short Geometry::relToAbsId(char moduleNumber, int strip, int cell) short row = nStrpZ - (strip - 1) % nStrpZ; short col = (int)std::ceil((float)strip / (nStrpZ)) - 1; - return moduleNumber * nCrystalsInModule + row * 2 + (col * nCellsXInStrip + (cell - 1) / 2) * nZ - + return (moduleNumber - 1) * nCrystalsInModule + row * 2 + (col * nCellsXInStrip + (cell - 1) / 2) * nZ - (cell & 1 ? 1 : 0); } @@ -74,7 +74,7 @@ bool Geometry::absToRelNumbering(short absId, char* relid) short phosmodulenumber = (absId - 1) / (nZ * nPhi); - relid[0] = phosmodulenumber; + relid[0] = phosmodulenumber + 1; absId -= phosmodulenumber * nPhi * nZ; relid[1] = 1 + (absId - 1) / nZ; relid[2] = absId - (relid[1] - 1) * nZ; @@ -98,7 +98,7 @@ short Geometry::truRelToAbsNumbering(const char* relId) } bool Geometry::truRelId2RelId(const char* truRelId, char* relId) { - relId[0] = (truRelId[0] + 2) / 4; + relId[0] = 1 + (truRelId[0] + 2) / 4; relId[1] = ((truRelId[0] + 2) % 4) * 16 + truRelId[1] * 2 + 1; relId[2] = truRelId[2] * 2 + 1; return true; @@ -108,7 +108,7 @@ short Geometry::relPosToTruId(char mod, float x, float z, short& ddl) //tranform local cluster coordinates to truId const float cellStep = 2.25; char relid[3] = {mod, static_cast(ceil(x / cellStep + 32.5)), static_cast(ceil(z / cellStep + 28.5))}; - ddl = mod / 4 + relid[1] / 16 - 2; + ddl = (mod - 1) * 4 + relid[1] / 16 - 2; char truid[3] = {static_cast(ddl), static_cast((relid[1] % 16) / 2), static_cast(relid[2] / 2)}; return truRelToAbsNumbering(truid); } @@ -118,7 +118,7 @@ char Geometry::absIdToModule(short absId) const short nZ = 56; const short nPhi = 64; - return (absId - 1) / (nZ * nPhi); + return 1 + (absId - 1) / (nZ * nPhi); } int Geometry::areNeighbours(short absId1, short absId2) @@ -177,9 +177,9 @@ bool Geometry::relToAbsNumbering(const char* relId, short& absId) const short nPhi = 64; // nStripZ * nCellsZInStrip absId = - relId[0] * nPhi * nZ + // the offset of PHOS modules - (relId[1] - 1) * nZ + // the offset along phi - relId[2]; // the offset along z + (relId[0] - 1) * nPhi * nZ + // the offset of PHOS modules + (relId[1] - 1) * nZ + // the offset along phi + relId[2]; // the offset along z return true; } @@ -197,7 +197,7 @@ void Geometry::local2Global(char module, float x, float z, TVector3& globaPos) c { // constexpr float shiftY=-10.76; Run2 constexpr float shiftY = -1.26; //Depth-optimized - Double_t posL[3] = {x, shiftY, -z}; + Double_t posL[3] = {x, z, shiftY}; Double_t posG[3]; mPHOS[module].LocalToMaster(posL, posG); globaPos.SetXYZ(posG[0], posG[1], posG[2]); diff --git a/Detectors/PHOS/base/src/Mapping.cxx b/Detectors/PHOS/base/src/Mapping.cxx index 45f1832616112..e4d31b8d1ec61 100644 --- a/Detectors/PHOS/base/src/Mapping.cxx +++ b/Detectors/PHOS/base/src/Mapping.cxx @@ -48,7 +48,7 @@ Mapping::ErrorStatus Mapping::hwToAbsId(short ddl, short hwAddr, short& absId, C absId = mAbsId[ddl][hwAddr]; caloFlag = mCaloFlag[ddl][hwAddr]; - if (absId > NCHANNELS) { + if (absId > NCHANNELS || absId <= 1792) { absId = 0; return kWrongHWAddress; } @@ -58,16 +58,24 @@ Mapping::ErrorStatus Mapping::hwToAbsId(short ddl, short hwAddr, short& absId, C Mapping::ErrorStatus Mapping::absIdTohw(short absId, short caloFlag, short& ddl, short& hwAddr) { - if (absId < 0 || absId > NCHANNELS) { - ddl = 0; - hwAddr = 0; - return kWrongAbsId; - } if (caloFlag < 0 || caloFlag > 2) { ddl = 0; hwAddr = 0; return kWrongCaloFlag; } + if (caloFlag < 2) { + if (absId <= 1792 || absId > NCHANNELS) { + ddl = 0; + hwAddr = 0; + return kWrongAbsId; + } + } else { + if (absId < 0 || absId > NTRUReadoutChannels) { + ddl = 0; + hwAddr = 0; + return kWrongAbsId; + } + } if (!mInitialized) { LOG(ERROR) << "Mapping not initialized"; @@ -83,8 +91,6 @@ Mapping::ErrorStatus Mapping::setMapping() { //Read mapping from data files a-la Run2 - o2::phos::Geometry* geom = o2::phos::Geometry::GetInstance(); - std::string p; if (mPath.empty()) { //use default path p = gSystem->Getenv("O2_ROOT"); @@ -158,8 +164,8 @@ Mapping::ErrorStatus Mapping::setMapping() short absId; if (caloFlag < 2) { //readout channels - char relid[3] = {static_cast(m), static_cast(row + 1), static_cast(col + 1)}; - geom->relToAbsNumbering(relid, absId); + char relid[3] = {static_cast(m + 1), static_cast(row + 1), static_cast(col + 1)}; + Geometry::relToAbsNumbering(relid, absId); } else { //TRU channels if (isTRUReadoutchannel(hwAddress)) { if (hwAddress < 2048) { //branch 28<=z<56 diff --git a/Detectors/PHOS/reconstruction/include/PHOSReconstruction/Clusterer.h b/Detectors/PHOS/reconstruction/include/PHOSReconstruction/Clusterer.h index 6b16274cb98b7..86514aec3ae2f 100644 --- a/Detectors/PHOS/reconstruction/include/PHOSReconstruction/Clusterer.h +++ b/Detectors/PHOS/reconstruction/include/PHOSReconstruction/Clusterer.h @@ -60,7 +60,14 @@ class Clusterer void convertCellsToDigits(gsl::span cells, int firstCellInEvent, int lastCellInEvent); //Calibrate energy - inline float calibrate(float amp, short absId) { return amp * mCalibParams->getGain(absId); } + inline float calibrate(float amp, short absId, bool isHighGain) + { + if (isHighGain) { + return amp * mCalibParams->getGain(absId); + } else { + return amp * mCalibParams->getGain(absId) * mCalibParams->getHGLGRatio(absId); + } + } //Calibrate time inline float calibrateT(float time, short absId, bool isHighGain) { diff --git a/Detectors/PHOS/reconstruction/src/AltroDecoder.cxx b/Detectors/PHOS/reconstruction/src/AltroDecoder.cxx index c3bb280da368b..cfe9e3a325dea 100644 --- a/Detectors/PHOS/reconstruction/src/AltroDecoder.cxx +++ b/Detectors/PHOS/reconstruction/src/AltroDecoder.cxx @@ -86,6 +86,7 @@ void AltroDecoder::readChannels() continue; } std::vector bunchwords; + bunchwords.reserve(3 * numberofwords); for (int iword = 0; iword < numberofwords; iword++) { currentword = buffer[currentpos++]; if ((currentword >> 30) != 0) { diff --git a/Detectors/PHOS/reconstruction/src/Clusterer.cxx b/Detectors/PHOS/reconstruction/src/Clusterer.cxx index 861467e374bf5..8b820a76e1fb8 100644 --- a/Detectors/PHOS/reconstruction/src/Clusterer.cxx +++ b/Detectors/PHOS/reconstruction/src/Clusterer.cxx @@ -219,7 +219,7 @@ void Clusterer::makeClusters(gsl::span digits) if (digitSeed.isTRU()) { continue; } - float digitSeedEnergy = calibrate(digitSeed.getAmplitude(), digitSeed.getAbsId()); + float digitSeedEnergy = calibrate(digitSeed.getAmplitude(), digitSeed.getAbsId(), digitSeed.isHighGain()); if (isBadChannel(digitSeed.getAbsId())) { digitSeedEnergy = 0.; } @@ -255,7 +255,7 @@ void Clusterer::makeClusters(gsl::span digits) if (digitN->isTRU()) { continue; } - float digitNEnergy = calibrate(digitN->getAmplitude(), digitN->getAbsId()); + float digitNEnergy = calibrate(digitN->getAmplitude(), digitN->getAbsId(), digitN->isHighGain()); if (isBadChannel(digitN->getAbsId())) { //remove digit digitNEnergy = 0.; } diff --git a/Detectors/PHOS/simulation/include/PHOSSimulation/GeometryParams.h b/Detectors/PHOS/simulation/include/PHOSSimulation/GeometryParams.h index b4f95f91ac1ed..a0d82f1fb5136 100644 --- a/Detectors/PHOS/simulation/include/PHOSSimulation/GeometryParams.h +++ b/Detectors/PHOS/simulation/include/PHOSSimulation/GeometryParams.h @@ -143,7 +143,7 @@ class GeometryParams final : public TNamed // General PHOS modules parameters int mNModules; ///< Number of PHOS modules float mAngle; ///< Position angles between modules - float mPHOSAngle[4]; ///< Position angles of modules + float mPHOSAngle[5]; ///< Position angles of modules float mPHOSParams[4]; ///< Half-sizes of PHOS trapecoid float mPHOSATBParams[4]; ///< Half-sizes of (air-filled) inner part of PHOS air tight box float mCrystalShift; ///< Distance from crystal center to front surface diff --git a/Detectors/PHOS/simulation/src/Detector.cxx b/Detectors/PHOS/simulation/src/Detector.cxx index 10a5286539228..7f0d7679b1a3f 100644 --- a/Detectors/PHOS/simulation/src/Detector.cxx +++ b/Detectors/PHOS/simulation/src/Detector.cxx @@ -175,8 +175,7 @@ Bool_t Detector::ProcessHits(FairVolume* v) fMC->CurrentVolOffID(3, strip); // 3: number of geom levels between PXTL and strip: get strip number in PHOS module Int_t cell; fMC->CurrentVolOffID(2, cell); // 2: number of geom levels between PXTL and cell: get sell in strip number. - Int_t detID = Geometry::relToAbsId(moduleNumber - 1, strip, cell); - + Int_t detID = Geometry::relToAbsId(moduleNumber, strip, cell); if (superParent == mCurentSuperParent && detID == mCurrentCellID && mCurrentHit) { // continue with current hit mCurrentHit->addEnergyLoss(lostenergy); @@ -234,6 +233,7 @@ void Detector::ConstructGeometry() LOG(DEBUG) << "Creating PHOS geometry\n"; phos::GeometryParams* geom = phos::GeometryParams::GetInstance("Run2"); + Geometry::GetInstance("Run2"); if (!geom) { LOG(ERROR) << "ConstructGeometry: PHOS Geometry class has not been set up.\n"; @@ -261,6 +261,7 @@ void Detector::ConstructGeometry() // Depending on configuration we should prepare containers for normal PHOS module "PHOS" // and half-module "PHOH" // This is still air tight box around PHOS + fMC->Gsvolu("PHOS", "TRD1", getMediumID(ID_FE), geom->getPHOSParams(), 4); if (mCreateHalfMod) { fMC->Gsvolu("PHOH", "TRD1", getMediumID(ID_FE), geom->getPHOSParams(), 4); @@ -275,21 +276,20 @@ void Detector::ConstructGeometry() Int_t idrotm[5]; Int_t iXYZ, iAngle; char im[5]; - for (Int_t iModule = 0; iModule < 5; iModule++) { - if (!mActiveModule[iModule + 1]) { + for (Int_t iModule = 1; iModule < 5; iModule++) { + if (!mActiveModule[iModule]) { continue; } Float_t angle[3][2] = {0}; geom->getModuleAngle(iModule, angle); Matrix(idrotm[iModule], angle[0][0], angle[0][1], angle[1][0], angle[1][1], angle[2][0], angle[2][1]); - Float_t pos[3] = {0}; geom->getModuleCenter(iModule, pos); - if (iModule == 0) { // special 1/2 module - fMC->Gspos("PHOH", iModule + 1, "barrel", pos[0], pos[1] + 30., pos[2], idrotm[iModule], "ONLY"); + if (iModule == 1) { // special 1/2 module + fMC->Gspos("PHOH", iModule, "barrel", pos[0], pos[1] + 30., pos[2], idrotm[iModule], "ONLY"); } else { - fMC->Gspos("PHOS", iModule + 1, "barrel", pos[0], pos[1] + 30., pos[2], idrotm[iModule], "ONLY"); + fMC->Gspos("PHOS", iModule, "barrel", pos[0], pos[1] + 30., pos[2], idrotm[iModule], "ONLY"); } } @@ -799,9 +799,9 @@ void Detector::ConstructEMCGeometry() fMC->Gspos("PEMH", 1, "PATH", 0., 0., z, 0, "ONLY"); } - fMC->Gspos("PATB", 1, "PHOS", 0., 0., 0, 0, "ONLY"); + fMC->Gspos("PATB", 1, "PHOS", 0., 0., 0., 0, "ONLY"); if (mCreateHalfMod) { // half of PHOS module - fMC->Gspos("PATH", 1, "PHOH", 0., 0., 0, 0, "ONLY"); + fMC->Gspos("PATH", 1, "PHOH", 0., 0., 0., 0, "ONLY"); } } @@ -823,7 +823,7 @@ void Detector::ConstructSupportGeometry() fMC->Gsvolu("PRRD", "BOX ", getMediumID(ID_AIR), par, 3); y0 = -(geom->getRailsDistanceFromIP() - geom->getRailRoadSize(1) / 2.0); - fMC->Gspos("PRRD", 1, "barrel", 0.0, y0 + 30., 0.0, 0, "ONLY"); + fMC->Gspos("PRRD", 1, "barrel", 0.0, y0 + 30. - 6.15, 0.0, 0, "ONLY"); // --- Dummy box containing one rail @@ -926,7 +926,7 @@ void Detector::defineSensitiveVolumes() //----------------------------------------- void Detector::addAlignableVolumes() const { - // + // Create entries for alignable volumes associating the symbolic volume // name with the corresponding volume path. @@ -938,15 +938,16 @@ void Detector::addAlignableVolumes() const o2::detectors::DetID::ID idPHOS = o2::detectors::DetID::PHS; TString physModulePath = "/cave_1/barrel_1/PHOS_"; + TString physModulePath2 = "/cave_1/barrel_1/PHOH_"; TString symbModuleName = "PHOS/Module"; for (Int_t iModule = 1; iModule <= geom->getNModules(); iModule++) { - if (!mActiveModule[iModule - 1]) { + if (!mActiveModule[iModule]) { continue; } - TString volPath(physModulePath); + TString volPath(iModule == 1 ? physModulePath2 : physModulePath); volPath += iModule; TString symName(symbModuleName); @@ -961,7 +962,6 @@ void Detector::addAlignableVolumes() const LOG(DEBUG) << "symName=" << symName << "\n"; LOG(DEBUG) << "--------------------------------------------" << "\n"; - LOG(DEBUG) << "Check for alignable entry: " << symName; if (!gGeoManager->SetAlignableEntry(symName.Data(), volPath.Data(), modUID)) { @@ -972,16 +972,8 @@ void Detector::addAlignableVolumes() const // Create the Tracking to Local transformation matrix for PHOS modules TGeoPNEntry* alignableEntry = gGeoManager->GetAlignableEntryByUID(modUID); LOG(DEBUG) << "Got TGeoPNEntry " << alignableEntry; - if (alignableEntry) { - Float_t angle = geom->getPHOSAngle(iModule); - TGeoHMatrix* globMatrix = alignableEntry->GetGlobalOrig(); - - TGeoHMatrix* matTtoL = new TGeoHMatrix; - matTtoL->RotateZ(270. + angle); - const TGeoHMatrix& globmatrixi = globMatrix->Inverse(); - matTtoL->MultiplyLeft(&globmatrixi); - alignableEntry->SetMatrix(matTtoL); + alignableEntry->SetMatrix(Geometry::GetInstance()->getAlignmentMatrix(iModule)); } } } diff --git a/Detectors/PHOS/simulation/src/Digitizer.cxx b/Detectors/PHOS/simulation/src/Digitizer.cxx index feaa3db3e49c3..22655e7c94e2e 100644 --- a/Detectors/PHOS/simulation/src/Digitizer.cxx +++ b/Detectors/PHOS/simulation/src/Digitizer.cxx @@ -94,21 +94,25 @@ void Digitizer::processHits(const std::vector* hits, const std::vector 0) { //update energy and time - mArrayD[i].addEnergyTime(energy, time); - //if overflow occured? if (mArrayD[i].isHighGain()) { + mArrayD[i].addEnergyTime(energy, time); + //if overflow occured? if (mArrayD[i].getAmplitude() > o2::phos::PHOSSimParams::Instance().mMCOverflow) { //10bit ADC float hglgratio = mCalibParams->getHGLGRatio(absId); mArrayD[i].setAmplitude(mArrayD[i].getAmplitude() / hglgratio); mArrayD[i].setHighGain(false); } + } else { //digit already in LG + float hglgratio = mCalibParams->getHGLGRatio(absId); + energy /= hglgratio; + mArrayD[i].addEnergyTime(energy, time); } } else { mArrayD[i].setHighGain(energy < o2::phos::PHOSSimParams::Instance().mMCOverflow); //10bit ADC diff --git a/Detectors/PHOS/simulation/src/GeometryParams.cxx b/Detectors/PHOS/simulation/src/GeometryParams.cxx index bedee16625c91..44677161dbef5 100644 --- a/Detectors/PHOS/simulation/src/GeometryParams.cxx +++ b/Detectors/PHOS/simulation/src/GeometryParams.cxx @@ -379,11 +379,11 @@ GeometryParams::GeometryParams(const std::string_view name) mAngle = 20; for (Int_t i = 1; i <= mNModules; i++) { Float_t angle = mAngle * (i - 2); - mPHOSAngle[i - 1] = angle; + mPHOSAngle[i] = angle; } Float_t r = mIPtoOuterCoverDistance + mPHOSParams[3]; - for (Int_t iModule = 0; iModule < mNModules; iModule++) { + for (Int_t iModule = 1; iModule <= mNModules; iModule++) { mModuleCenter[iModule][0] = r * TMath::Sin(mPHOSAngle[iModule] / kRADDEG); mModuleCenter[iModule][1] = -r * TMath::Cos(mPHOSAngle[iModule] / kRADDEG); mModuleCenter[iModule][2] = 0.; diff --git a/Detectors/PHOS/simulation/src/RawWriter.cxx b/Detectors/PHOS/simulation/src/RawWriter.cxx index 1dadda93942bd..e2caca5344f22 100644 --- a/Detectors/PHOS/simulation/src/RawWriter.cxx +++ b/Detectors/PHOS/simulation/src/RawWriter.cxx @@ -109,7 +109,7 @@ bool RawWriter::processTrigger(const gsl::span digitsbranch, co short ddl, hwAddr; //get ddl and High Gain hw addresses if (mMapping->absIdTohw(absId, Mapping::kTRU, ddl, hwAddr) != o2::phos::Mapping::kOK) { - LOG(ERROR) << "Wrong truId" << absId; + LOG(ERROR) << "Wrong truId=" << absId; } //Collect possible several digits (signal+pileup) into one map record auto celldata = mTRUdata[ddl].mChannels.find(absId); @@ -150,9 +150,9 @@ bool RawWriter::processTrigger(const gsl::span digitsbranch, co short trmask[2 * Mapping::NTRUBranchReadoutChannels] = {0}; //Time bin in which trigger was fired. for (auto ch = mTRUdata[ddl].mChannels.cbegin(); ch != mTRUdata[ddl].mChannels.cend(); ch++) { short truId = ch->first; - short hwAddr, iddl; //High gain always filled + short hwAddr, iddl; if ((mMapping->absIdTohw(truId, Mapping::kTRU, iddl, hwAddr) != o2::phos::Mapping::kOK) || iddl != ddl) { - LOG(ERROR) << "Wrong truId" << truId << "iDDL=" << iddl << "!=" << ddl; + LOG(ERROR) << "Wrong truId=" << truId << ", iDDL=" << iddl << "!=" << ddl; } rawbunchesTRU.clear(); createTRUBunches(truId, ch->second, rawbunchesTRU); @@ -184,7 +184,6 @@ bool RawWriter::processTrigger(const gsl::span digitsbranch, co } } if (mTRUdata[ddl].mChannels.size()) { // if there are TRU digits, fill trigger flags - short chan = 0; std::vector a; for (short chan = 0; chan < Mapping::NTRUBranchReadoutChannels; chan++) { if (trmask[chan] > 0) { @@ -362,13 +361,16 @@ void RawWriter::createRawBunches(short absId, const std::vectorgetHGLGRatio(absId); for (auto dig : channelDigits) { //Convert energy and time to ADC counts and time ticks - float ampADC = dig->getAmplitude(); // Digits amplitude already in ADC channels - if (ampADC > o2::phos::PHOSSimParams::Instance().mMCOverflow) { //High Gain in saturation, fill also Low Gain + float ampADC = dig->getAmplitude(); // Digits amplitude already in ADC channels + if (!dig->isHighGain() || ampADC > o2::phos::PHOSSimParams::Instance().mMCOverflow) { //High Gain in saturation, fill also Low Gain isLGFilled = true; } float timeTicks = dig->getTime(); //time in ns timeTicks /= o2::phos::PHOSSimParams::Instance().mTimeTick; //time in PHOS ticks //Add to current sample contribution from digit + if (!dig->isHighGain()) { + ampADC *= hglgratio; + } fillGamma2(ampADC, timeTicks, samples); } diff --git a/Detectors/PHOS/workflow/src/RawToCellConverterSpec.cxx b/Detectors/PHOS/workflow/src/RawToCellConverterSpec.cxx index 5b5d908897dfe..e62447048268d 100644 --- a/Detectors/PHOS/workflow/src/RawToCellConverterSpec.cxx +++ b/Detectors/PHOS/workflow/src/RawToCellConverterSpec.cxx @@ -285,7 +285,7 @@ void RawToCellConverterSpec::run(framework::ProcessingContext& ctx) auto currentTRUFlags = found3->second; bool is4x4Trigger = (*currentTRUFlags)[Mapping::NTRUReadoutChannels]; for (Cell c : *currentTRUContainer) { - if ((*currentTRUFlags)[c.getAbsId()]) { //there is corresponding flag + if ((*currentTRUFlags)[c.getTRUId()]) { //there is corresponding flag if (is4x4Trigger) { c.setType(ChannelType_t::TRU4x4); } else { @@ -326,7 +326,7 @@ void RawToCellConverterSpec::readTRUDigit(const std::vector& bunchlist, s timeBin++; } } - currentTRUContainer->emplace_back(absId, smax, tmax * 1.e-9, TRU2x2); //add TRU cells + currentTRUContainer->emplace_back(absId + 14337 + 1, smax, tmax * 1.e-9, TRU2x2); //add TRU cells } void RawToCellConverterSpec::readTRUFlags(short hwAddress, const std::vector& bunchlist, std::shared_ptr>& currentTRUFlags) { @@ -344,7 +344,7 @@ void RawToCellConverterSpec::readTRUFlags(short hwAddress, const std::vector& signal = b.getADC(); // Loop over all the time steps in the signal - for (std::vector::const_reverse_iterator it = signal.rbegin(); it != signal.rend(); ++it, ++timeBin) { + for (std::vector::const_reverse_iterator it = signal.rbegin(); it != signal.rend(); it++, timeBin++) { // If bit 112 is 1, we are considering 4x4 algorithm if (hwAddress == Mapping::TRUFinalProductionChannel) { From 4e3aafd3e955f7df880be91b9862220cd878b832 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 21 Apr 2021 17:43:18 +0200 Subject: [PATCH 249/770] GPU: Add DPL executable to run GPU Standalone display --- GPU/CMakeLists.txt | 10 ++++ GPU/Workflow/CMakeLists.txt | 15 ++++++ GPU/Workflow/O2GPUDPLDisplay.cxx | 90 ++++++++++++++++++++++++++++++++ GPU/Workflow/O2GPUDPLDisplay.h | 37 +++++++++++++ 4 files changed, 152 insertions(+) create mode 100644 GPU/Workflow/CMakeLists.txt create mode 100644 GPU/Workflow/O2GPUDPLDisplay.cxx create mode 100644 GPU/Workflow/O2GPUDPLDisplay.h diff --git a/GPU/CMakeLists.txt b/GPU/CMakeLists.txt index 03b9b7d00427f..26caeb87a745e 100644 --- a/GPU/CMakeLists.txt +++ b/GPU/CMakeLists.txt @@ -21,3 +21,13 @@ add_subdirectory(Common) add_subdirectory(Utils) add_subdirectory(TPCFastTransformation) add_subdirectory(GPUTracking) + +if(ALIGPU_BUILD_TYPE STREQUAL "O2" + AND OPENGL_FOUND + AND GLFW_FOUND + AND TARGET AliceO2::DebugGUI + AND OPENGL_GLU_FOUND + AND NOT CMAKE_SYSTEM_NAME STREQUAL "Darwin" +) + add_subdirectory(Workflow) +endif() diff --git a/GPU/Workflow/CMakeLists.txt b/GPU/Workflow/CMakeLists.txt new file mode 100644 index 0000000000000..8ba083b985b64 --- /dev/null +++ b/GPU/Workflow/CMakeLists.txt @@ -0,0 +1,15 @@ +# Copyright CERN and copyright holders of ALICE O2. This software is distributed +# under the terms of the GNU General Public License v3 (GPL Version 3), copied +# verbatim in the file "COPYING". +# +# See http://alice-o2.web.cern.ch/license for full licensing information. +# +# In applying this license CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization or +# submit itself to any jurisdiction. + +o2_add_executable(display + COMPONENT_NAME gpu + TARGETVARNAME targetName + SOURCES O2GPUDPLDisplay.cxx + PUBLIC_LINK_LIBRARIES O2::GPUO2Interface O2::DataFormatsGlobalTracking) diff --git a/GPU/Workflow/O2GPUDPLDisplay.cxx b/GPU/Workflow/O2GPUDPLDisplay.cxx new file mode 100644 index 0000000000000..de1c51964ad49 --- /dev/null +++ b/GPU/Workflow/O2GPUDPLDisplay.cxx @@ -0,0 +1,90 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "O2GPUDPLDisplay.h" +#include "Framework/ConfigParamSpec.h" +#include "DataFormatsParameters/GRPObject.h" +#include "DataFormatsGlobalTracking/RecoContainer.h" +#include "DetectorsCommonDataFormats/NameConf.h" +#include "DetectorsBase/GeometryManager.h" +#include "DetectorsBase/Propagator.h" +#include "GPUO2InterfaceDisplay.h" +#include "GPUO2InterfaceConfiguration.h" + +using namespace o2::framework; +using namespace o2::dataformats; +using namespace o2::gpu; + +static std::unique_ptr display; +std::unique_ptr config; + +void customize(std::vector& workflowOptions) +{ + std::vector options{ + {"enable-mc", o2::framework::VariantType::Bool, false, {"enable visualization of MC data"}}, + {"display-clusters", VariantType::String, "TPC", {"comma-separated list of clusters to display"}}, + {"display-tracks", VariantType::String, "TPC", {"comma-separated list of tracks to display"}}, + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings ..."}}}; + + std::swap(workflowOptions, options); +} + +// ------------------------------------------------------------------ + +#include "Framework/runDataProcessing.h" + +static o2::globaltracking::DataRequest dataRequest; + +void O2GPUDPLDisplaySpec::init(InitContext& ic) +{ + const auto grp = o2::parameters::GRPObject::loadFrom(o2::base::NameConf::getGRPFileName()); + o2::base::GeometryManager::loadGeometry(); + o2::base::Propagator::initFieldFromGRP(o2::base::NameConf::getGRPFileName()); + config.reset(new GPUO2InterfaceConfiguration); + config->configGRP.solenoidBz = 5.00668f * grp->getL3Current() / 30000.; + config->configGRP.continuousMaxTimeBin = grp->isDetContinuousReadOut(o2::detectors::DetID::TPC) ? -1 : 0; // Number of timebins in timeframe if continuous, 0 otherwise + config->ReadConfigurableParam(); + display.reset(new GPUO2InterfaceDisplay(config.get())); +} + +void O2GPUDPLDisplaySpec::run(ProcessingContext& pc) +{ + o2::globaltracking::RecoContainer recoData; + recoData.collectData(pc, dataRequest); + static bool first = false; + if (first == false) { + display->startDisplay(); + } + display->show(); +} + +void O2GPUDPLDisplaySpec::endOfStream(EndOfStreamContext& ec) +{ + display->endDisplay(); +} + +WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) +{ + WorkflowSpec specs; + + bool useMC = cfgc.options().get("enable-mc"); + GlobalTrackID::mask_t srcTrk = GlobalTrackID::getSourcesMask(cfgc.options().get("display-tracks")); + GlobalTrackID::mask_t srcCl = GlobalTrackID::getSourcesMask(cfgc.options().get("display-clusters")); + dataRequest.requestTracks(srcTrk, useMC); + dataRequest.requestClusters(srcCl, useMC); + + specs.emplace_back(DataProcessorSpec{ + "o2-gpu-display", + dataRequest.inputs, + {}, + AlgorithmSpec{adaptFromTask(useMC, srcTrk, srcCl)}}); + + return std::move(specs); +} diff --git a/GPU/Workflow/O2GPUDPLDisplay.h b/GPU/Workflow/O2GPUDPLDisplay.h new file mode 100644 index 0000000000000..cab295c39c55e --- /dev/null +++ b/GPU/Workflow/O2GPUDPLDisplay.h @@ -0,0 +1,37 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_GPU_DPL_DISPLAY_H +#define O2_GPU_DPL_DISPLAY_H + +#include "Framework/DataProcessorSpec.h" +#include "ReconstructionDataFormats/GlobalTrackID.h" +#include "Framework/Task.h" + +namespace o2::gpu +{ +class O2GPUDPLDisplaySpec : public o2::framework::Task +{ + public: + O2GPUDPLDisplaySpec(bool useMC, o2::dataformats::GlobalTrackID::mask_t trkMask, o2::dataformats::GlobalTrackID::mask_t clMask) : mUseMC(useMC), mTrkMask(trkMask), mClMask(clMask) {} + ~O2GPUDPLDisplaySpec() override = default; + void init(o2::framework::InitContext& ic) final; + void run(o2::framework::ProcessingContext& pc) final; + void endOfStream(o2::framework::EndOfStreamContext& ec) final; + + private: + bool mUseMC = false; + o2::dataformats::GlobalTrackID::mask_t mTrkMask; + o2::dataformats::GlobalTrackID::mask_t mClMask; +}; + +} // namespace o2::gpu + +#endif From 457b9561a23315f24023490d8ce21df577264704 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 21 Apr 2021 19:49:44 +0200 Subject: [PATCH 250/770] GPU: Add interface class to use GPU standalone display externally --- GPU/GPUTracking/Interface/CMakeLists.txt | 9 +++ .../Interface/GPUO2InterfaceDisplay.cxx | 56 +++++++++++++++++++ .../Interface/GPUO2InterfaceDisplay.h | 54 ++++++++++++++++++ 3 files changed, 119 insertions(+) create mode 100644 GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx create mode 100644 GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.h diff --git a/GPU/GPUTracking/Interface/CMakeLists.txt b/GPU/GPUTracking/Interface/CMakeLists.txt index 262fbff53d595..5f05c8195cc5c 100644 --- a/GPU/GPUTracking/Interface/CMakeLists.txt +++ b/GPU/GPUTracking/Interface/CMakeLists.txt @@ -12,6 +12,15 @@ set(MODULE GPUO2Interface) set(SRCS GPUO2Interface.cxx GPUO2InterfaceRefit.cxx GPUO2InterfaceQA.cxx GPUO2InterfaceConfiguration.cxx) +if(OPENGL_FOUND + AND GLFW_FOUND + AND TARGET AliceO2::DebugGUI + AND OPENGL_GLU_FOUND + AND NOT CMAKE_SYSTEM_NAME STREQUAL "Darwin" +) + set(SRCS ${SRCS} GPUO2InterfaceDisplay.cxx) +endif() + string(REPLACE ".cxx" ".h" HDRS_TMP "${SRCS}") set(HDRS ${HDRS_TMP}) diff --git a/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx new file mode 100644 index 0000000000000..a395fcdb5a8b9 --- /dev/null +++ b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx @@ -0,0 +1,56 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file GPUO2InterfaceDisplay.cxx +/// \author David Rohr + +#include "GPUParam.h" +#include "GPUDisplay.h" +#include "GPUO2InterfaceConfiguration.h" +#include "GPUO2InterfaceDisplay.h" +#include "GPUDisplayBackend.h" +#include "GPUDisplayBackendGlfw.h" + +using namespace o2::gpu; +using namespace o2::tpc; + +GPUO2InterfaceDisplay::GPUO2InterfaceDisplay(const GPUO2InterfaceConfiguration* config) +{ + mBackend.reset(new GPUDisplayBackendGlfw); + //config.configProcessing.eventDisplay = processAttributes->displayBackend.get(); + mParam.reset(new GPUParam); + mParam->SetDefaults(&config->configGRP, &config->configReconstruction, &config->configProcessing, nullptr); + + //mDisplay.reset(new GPUDisplay(nullptr, &config->configDisplay, mParam.get())); + mDisplay.reset(new GPUDisplay(mBackend.get(), nullptr, nullptr)); +} + +GPUO2InterfaceDisplay::~GPUO2InterfaceDisplay() = default; + +int GPUO2InterfaceDisplay::startDisplay() +{ + return mDisplay->StartDisplay(); +} + +int GPUO2InterfaceDisplay::show() +{ + mDisplay->ShowNextEvent(); + do { + usleep(10000); + } while (mBackend->mDisplayControl == 0); + mDisplay->WaitForNextEvent(); + return 0; +} + +int GPUO2InterfaceDisplay::endDisplay() +{ + mBackend->DisplayExit(); + return 0; +} diff --git a/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.h b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.h new file mode 100644 index 0000000000000..2af8f5773e704 --- /dev/null +++ b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.h @@ -0,0 +1,54 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file GPUO2InterfaceDisplay.h +/// \author David Rohr + +#ifndef GPUO2INTERFACEDisplay_H +#define GPUO2INTERFACEDisplay_H + +// Some defines denoting that we are compiling for O2 +#ifndef HAVE_O2HEADERS +#define HAVE_O2HEADERS +#endif +#ifndef GPUCA_TPC_GEOMETRY_O2 +#define GPUCA_TPC_GEOMETRY_O2 +#endif +#ifndef GPUCA_O2_INTERFACE +#define GPUCA_O2_INTERFACE +#endif + +#include +#include + +namespace o2::gpu +{ +class GPUDisplay; +class GPUParam; +class GPUO2InterfaceConfiguration; +class GPUDisplayBackend; +class GPUO2InterfaceDisplay +{ + public: + GPUO2InterfaceDisplay(const GPUO2InterfaceConfiguration* config = nullptr); + ~GPUO2InterfaceDisplay(); + + int startDisplay(); + int show(); + int endDisplay(); + + private: + std::unique_ptr mDisplay; + std::unique_ptr mParam; + std::unique_ptr mBackend; +}; +} // namespace o2::gpu + +#endif From ebcab7769ae79f0d8d906ec5d2a7949562ca08ef Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 21 Apr 2021 19:50:35 +0200 Subject: [PATCH 251/770] GPU: Fix and simplify access to ioptrs in GPU standalone display --- GPU/GPUTracking/display/GPUDisplay.cxx | 48 ++++++++++++++------------ GPU/GPUTracking/display/GPUDisplay.h | 2 +- 2 files changed, 26 insertions(+), 24 deletions(-) diff --git a/GPU/GPUTracking/display/GPUDisplay.cxx b/GPU/GPUTracking/display/GPUDisplay.cxx index cb77852970039..0c519656fbc63 100644 --- a/GPU/GPUTracking/display/GPUDisplay.cxx +++ b/GPU/GPUTracking/display/GPUDisplay.cxx @@ -74,7 +74,7 @@ using namespace GPUCA_NAMESPACE::gpu; #define SEPERATE_GLOBAL_TRACKS_LIMIT (mSeparateGlobalTracks ? tGLOBALTRACK : TRACK_TYPE_ID_LIMIT) -#define GET_CID(slice, i) (tracker.Param().par.earlyTpcTransform ? tracker.ClusterData()[i].id : (tracker.GetConstantMem()->ioPtrs.clustersNative->clusterOffset[slice][0] + i)) +#define GET_CID(slice, i) (tracker.Param().par.earlyTpcTransform ? tracker.ClusterData()[i].id : (mIOPtrs.clustersNative->clusterOffset[slice][0] + i)) static const GPUSettingsDisplay& GPUDisplay_GetConfig(GPUChainTracking* chain) { @@ -95,7 +95,6 @@ GPUDisplay::GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQ const GPUParam& GPUDisplay::param() { return mChain->GetParam(); } const GPUTPCTracker& GPUDisplay::sliceTracker(int iSlice) { return mChain->GetTPCSliceTrackers()[iSlice]; } const GPUTRDTrackerGPU& GPUDisplay::trdTracker() { return *mChain->GetTRDTracker(); } -const GPUTrackingInOutPointers GPUDisplay::ioptrs() { return mChain->mIOPtrs; } inline void GPUDisplay::drawVertices(const vboList& v, const GLenum t) { @@ -713,7 +712,7 @@ GPUDisplay::vboList GPUDisplay::DrawClusters(const GPUTPCTracker& tracker, int s bool draw = mGlobalPos[cid].w == select; if (mMarkAdjacentClusters) { - const int attach = tracker.GetConstantMem()->ioPtrs.mergedTrackHitAttachment[cid]; + const int attach = mIOPtrs->mergedTrackHitAttachment[cid]; if (attach) { if (mMarkAdjacentClusters >= 32) { if (mQA && mQA->clusterRemovable(attach, mMarkAdjacentClusters == 33)) { @@ -728,7 +727,7 @@ GPUDisplay::vboList GPUDisplay::DrawClusters(const GPUTPCTracker& tracker, int s } else if ((mMarkAdjacentClusters & 16) && (attach & gputpcgmmergertypes::attachHighIncl)) { draw = select == tMARKED; } else if (mMarkAdjacentClusters & 8) { - if (fabsf(tracker.GetConstantMem()->ioPtrs.mergedTracks[attach & gputpcgmmergertypes::attachTrackMask].GetParam().GetQPt()) > 20.f) { + if (fabsf(mIOPtrs.mergedTracks[attach & gputpcgmmergertypes::attachTrackMask].GetParam().GetQPt()) > 20.f) { draw = select == tMARKED; } } @@ -738,7 +737,7 @@ GPUDisplay::vboList GPUDisplay::DrawClusters(const GPUTPCTracker& tracker, int s if (tracker.Param().par.earlyTpcTransform) { flags = tracker.ClusterData()[cidInSlice].flags; } else { - flags = tracker.GetConstantMem()->ioPtrs.clustersNative->clustersLinear[cid].getFlags(); + flags = mIOPtrs->clustersNative->clustersLinear[cid].getFlags(); } const bool match = flags & mMarkClusters; draw = (select == tMARKED) ? (match) : (draw && !match); @@ -883,7 +882,7 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s break; } i = trackList[0][ii]; - track = &mMerger.GetConstantMem()->ioPtrs.mergedTracks[i]; + track = &mIOPtrs->mergedTracks[i]; size_t startCountInner = mVertexBuffer[iSlice].size(); bool drawing = false; @@ -911,10 +910,10 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s } } for (unsigned int k = 0; k < track->NClusters(); k++) { - if (mHideRejectedClusters && (mMerger.GetConstantMem()->ioPtrs.mergedTrackHits[track->FirstClusterRef() + k].state & GPUTPCGMMergedTrackHit::flagReject)) { + if (mHideRejectedClusters && (mIOPtrs->mergedTrackHits[track->FirstClusterRef() + k].state & GPUTPCGMMergedTrackHit::flagReject)) { continue; } - int cid = mMerger.GetConstantMem()->ioPtrs.mergedTrackHits[track->FirstClusterRef() + k].num; + int cid = mIOPtrs->mergedTrackHits[track->FirstClusterRef() + k].num; int w = mGlobalPos[cid].w; if (drawing) { drawPointLinestrip(iSlice, cid, tFINALTRACK, SEPERATE_GLOBAL_TRACKS_LIMIT); @@ -932,7 +931,7 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s drawPointLinestrip(iSlice, cid, tFINALTRACK, SEPERATE_GLOBAL_TRACKS_LIMIT); } if (!drawing && lastCluster != -1) { - drawPointLinestrip(iSlice, mMerger.GetConstantMem()->ioPtrs.mergedTrackHits[track->FirstClusterRef() + lastCluster].num, 7, SEPERATE_GLOBAL_TRACKS_LIMIT); + drawPointLinestrip(iSlice, mIOPtrs->mergedTrackHits[track->FirstClusterRef() + lastCluster].num, 7, SEPERATE_GLOBAL_TRACKS_LIMIT); } drawing = true; } @@ -971,14 +970,14 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s x = cl.x; ZOffset = track->GetParam().GetTZOffset(); } else { - auto cl = mMerger.GetConstantMem()->ioPtrs.mergedTrackHits[track->FirstClusterRef() + lastCluster]; - const auto& cln = mMerger.GetConstantMem()->ioPtrs.clustersNative->clustersLinear[cl.num]; + auto cl = mIOPtrs->mergedTrackHits[track->FirstClusterRef() + lastCluster]; + const auto& cln = mIOPtrs->clustersNative->clustersLinear[cl.num]; float y, z; GPUTPCConvertImpl::convert(*mMerger.GetConstantMem(), cl.slice, cl.row, cln.getPad(), cln.getTime(), x, y, z); ZOffset = mMerger.GetConstantMem()->calibObjects.fastTransform->convTimeToZinTimeFrame(slice, track->GetParam().GetTZOffset(), mMerger.Param().par.continuousMaxTimeBin); } } else { - const GPUTPCMCInfo& mc = ioptrs().mcInfosTPC[i]; + const GPUTPCMCInfo& mc = mIOPtrs->mcInfosTPC[i]; if (mc.charge == 0.f) { break; } @@ -1195,6 +1194,9 @@ GPUDisplay::vboList GPUDisplay::DrawGridTRD(int sector) int GPUDisplay::DrawGLScene(bool mixAnimation, float mAnimateTime) { + if (mIOPtrs == nullptr && mChain) { + mIOPtrs = &mChain->mIOPtrs; + } try { if (DrawGLScene_internal(mixAnimation, mAnimateTime)) { return (1); @@ -1236,10 +1238,10 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) mGlobalPosTRD = mGlobalPosPtrTRD.get(); mGlobalPosTRD2 = mGlobalPosPtrTRD2.get(); } - if ((size_t)mMerger.GetConstantMem()->ioPtrs.nMergedTracks > mTRDTrackIds.size()) { - mTRDTrackIds.resize(mMerger.GetConstantMem()->ioPtrs.nMergedTracks); + if ((size_t)mIOPtrs->nMergedTracks > mTRDTrackIds.size()) { + mTRDTrackIds.resize(mIOPtrs->nMergedTracks); } - for (unsigned int i = 0; i < mMerger.GetConstantMem()->ioPtrs.nMergedTracks; i++) { + for (unsigned int i = 0; i < mIOPtrs->nMergedTracks; i++) { mTRDTrackIds[i] = -1; } for (int i = 0; i < trdTracker().NTracks(); i++) { @@ -1264,8 +1266,8 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) cid = cl.id; row = cl.row; } else { - cid = ioptrs().clustersNative->clusterOffset[iSlice][0] + i; - while (row < GPUCA_ROW_COUNT && ioptrs().clustersNative->clusterOffset[iSlice][row + 1] <= (unsigned int)cid) { + cid = mIOPtrs->clustersNative->clusterOffset[iSlice][0] + i; + while (row < GPUCA_ROW_COUNT && mIOPtrs->clustersNative->clusterOffset[iSlice][row + 1] <= (unsigned int)cid) { row++; } } @@ -1280,7 +1282,7 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) mChain->GetParam().Slice2Global(iSlice, (mConfig.clustersOnNominalRow ? mMerger.Param().tpcGeometry.Row2X(row) : cl.x) + mXadd, cl.y, cl.z, &ptr->x, &ptr->y, &ptr->z); } else { float x, y, z; - const auto& cln = ioptrs().clustersNative->clusters[iSlice][0][i]; + const auto& cln = mIOPtrs->clustersNative->clusters[iSlice][0][i]; GPUTPCConvertImpl::convert(*mMerger.GetConstantMem(), iSlice, row, cln.getPad(), cln.getTime(), x, y, z); mChain->GetParam().Slice2Global(iSlice, x + mXadd, y, z, &ptr->x, &ptr->y, &ptr->z); } @@ -1714,15 +1716,15 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) } } GPUCA_OPENMP(for) - for (unsigned int i = 0; i < mMerger.GetConstantMem()->ioPtrs.nMergedTracks; i++) { - const GPUTPCGMMergedTrack* track = &mMerger.GetConstantMem()->ioPtrs.mergedTracks[i]; + for (unsigned int i = 0; i < mIOPtrs->nMergedTracks; i++) { + const GPUTPCGMMergedTrack* track = &mIOPtrs->mergedTracks[i]; if (track->NClusters() == 0) { continue; } if (mHideRejectedTracks && !track->OK()) { continue; } - int slice = mMerger.GetConstantMem()->ioPtrs.mergedTrackHits[track->FirstClusterRef() + track->NClusters() - 1].slice; + int slice = mIOPtrs->mergedTrackHits[track->FirstClusterRef() + track->NClusters() - 1].slice; unsigned int col = 0; if (mNCollissions > 1) { int label = mQA ? mQA->GetMCTrackLabel(i) : -1; @@ -1733,8 +1735,8 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) mThreadTracks[numThread][col][slice][0].emplace_back(i); } GPUCA_OPENMP(for) - for (unsigned int i = 0; i < ioptrs().nMCInfosTPC; i++) { - const GPUTPCMCInfo& mc = ioptrs().mcInfosTPC[i]; + for (unsigned int i = 0; i < mIOPtrs->nMCInfosTPC; i++) { + const GPUTPCMCInfo& mc = mIOPtrs->mcInfosTPC[i]; if (mc.charge == 0.f) { continue; } diff --git a/GPU/GPUTracking/display/GPUDisplay.h b/GPU/GPUTracking/display/GPUDisplay.h index 099f17633bb0f..78d6d77a01a48 100644 --- a/GPU/GPUTracking/display/GPUDisplay.h +++ b/GPU/GPUTracking/display/GPUDisplay.h @@ -194,7 +194,7 @@ class GPUDisplay const GPUParam& param(); const GPUTPCTracker& sliceTracker(int iSlice); const GPUTRDTrackerGPU& trdTracker(); - const GPUTrackingInOutPointers ioptrs(); + const GPUTrackingInOutPointers* mIOPtrs = nullptr; void drawVertices(const vboList& v, const GLenum t); void insertVertexList(std::pair*, vecpod*>& vBuf, size_t first, size_t last); void insertVertexList(int iSlice, size_t first, size_t last); From 93291677b037b1f5530d228af11cb3c360fb5723 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 21 Apr 2021 20:01:17 +0200 Subject: [PATCH 252/770] GPU: Simplify usage of GPUParam in GPU standalone display --- GPU/GPUTracking/display/GPUDisplay.cxx | 54 +++++++++++++------------- GPU/GPUTracking/display/GPUDisplay.h | 5 ++- 2 files changed, 30 insertions(+), 29 deletions(-) diff --git a/GPU/GPUTracking/display/GPUDisplay.cxx b/GPU/GPUTracking/display/GPUDisplay.cxx index 0c519656fbc63..7480041394a0f 100644 --- a/GPU/GPUTracking/display/GPUDisplay.cxx +++ b/GPU/GPUTracking/display/GPUDisplay.cxx @@ -74,7 +74,7 @@ using namespace GPUCA_NAMESPACE::gpu; #define SEPERATE_GLOBAL_TRACKS_LIMIT (mSeparateGlobalTracks ? tGLOBALTRACK : TRACK_TYPE_ID_LIMIT) -#define GET_CID(slice, i) (tracker.Param().par.earlyTpcTransform ? tracker.ClusterData()[i].id : (mIOPtrs.clustersNative->clusterOffset[slice][0] + i)) +#define GET_CID(slice, i) (mParam->par.earlyTpcTransform ? tracker.ClusterData()[i].id : (mIOPtrs->clustersNative->clusterOffset[slice][0] + i)) static const GPUSettingsDisplay& GPUDisplay_GetConfig(GPUChainTracking* chain) { @@ -86,13 +86,13 @@ static const GPUSettingsDisplay& GPUDisplay_GetConfig(GPUChainTracking* chain) } } -GPUDisplay::GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa) : mBackend(backend), mChain(chain), mConfig(GPUDisplay_GetConfig(chain)), mQA(qa), mMerger(chain->GetTPCMerger()) +GPUDisplay::GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa, const GPUParam* param) : mBackend(backend), mChain(chain), mConfig(GPUDisplay_GetConfig(chain)), mQA(qa), mMerger(chain->GetTPCMerger()) { backend->mDisplay = this; mOpenGLCore = GPUCA_DISPLAY_OPENGL_CORE_FLAGS; + mParam = param ? param : &mChain->GetParam(); } -const GPUParam& GPUDisplay::param() { return mChain->GetParam(); } const GPUTPCTracker& GPUDisplay::sliceTracker(int iSlice) { return mChain->GetTPCSliceTrackers()[iSlice]; } const GPUTRDTrackerGPU& GPUDisplay::trdTracker() { return *mChain->GetTRDTracker(); } @@ -727,14 +727,14 @@ GPUDisplay::vboList GPUDisplay::DrawClusters(const GPUTPCTracker& tracker, int s } else if ((mMarkAdjacentClusters & 16) && (attach & gputpcgmmergertypes::attachHighIncl)) { draw = select == tMARKED; } else if (mMarkAdjacentClusters & 8) { - if (fabsf(mIOPtrs.mergedTracks[attach & gputpcgmmergertypes::attachTrackMask].GetParam().GetQPt()) > 20.f) { + if (fabsf(mIOPtrs->mergedTracks[attach & gputpcgmmergertypes::attachTrackMask].GetParam().GetQPt()) > 20.f) { draw = select == tMARKED; } } } } else if (mMarkClusters) { short flags; - if (tracker.Param().par.earlyTpcTransform) { + if (mParam->par.earlyTpcTransform) { flags = tracker.ClusterData()[cidInSlice].flags; } else { flags = mIOPtrs->clustersNative->clustersLinear[cid].getFlags(); @@ -962,10 +962,10 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s float ZOffset = 0; float x = 0; int slice = iSlice; - float alpha = param().Alpha(slice); + float alpha = mParam->Alpha(slice); if (iMC == 0) { trkParam.Set(track->GetParam()); - if (mMerger.Param().par.earlyTpcTransform) { + if (mParam->par.earlyTpcTransform) { auto cl = mMerger.ClustersXYZ()[track->FirstClusterRef() + lastCluster]; // Todo: Remove direct usage of merger x = cl.x; ZOffset = track->GetParam().GetTZOffset(); @@ -974,7 +974,7 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s const auto& cln = mIOPtrs->clustersNative->clustersLinear[cl.num]; float y, z; GPUTPCConvertImpl::convert(*mMerger.GetConstantMem(), cl.slice, cl.row, cln.getPad(), cln.getTime(), x, y, z); - ZOffset = mMerger.GetConstantMem()->calibObjects.fastTransform->convTimeToZinTimeFrame(slice, track->GetParam().GetTZOffset(), mMerger.Param().par.continuousMaxTimeBin); + ZOffset = mMerger.GetConstantMem()->calibObjects.fastTransform->convTimeToZinTimeFrame(slice, track->GetParam().GetTZOffset(), mParam->par.continuousMaxTimeBin); } } else { const GPUTPCMCInfo& mc = mIOPtrs->mcInfosTPC[i]; @@ -1016,7 +1016,7 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s if (fabsf(trkParam.SinPhi()) > 1) { break; } - alpha = param().Alpha(slice); + alpha = mParam->Alpha(slice); vecpod& useBuffer = iMC && inFlyDirection == 0 ? buffer : mVertexBuffer[iSlice]; int nPoints = 0; @@ -1038,7 +1038,7 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s } x = trkParam.X() + 1.f; if (!mPropagateLoopers) { - float diff = fabsf(alpha - param().Alpha(slice)) / (2. * CAMath::Pi()); + float diff = fabsf(alpha - mParam->Alpha(slice)) / (2. * CAMath::Pi()); diff -= floor(diff); if (diff > 0.25 && diff < 0.75) { break; @@ -1088,8 +1088,8 @@ GPUDisplay::vboList GPUDisplay::DrawGrid(const GPUTPCTracker& tracker) float x = row.X() + mXadd; float y = row.Grid().YMin() + (float)j / row.Grid().StepYInv(); float zz1, zz2, yy1, yy2, xx1, xx2; - tracker.Param().Slice2Global(tracker.ISlice(), x, y, z1, &xx1, &yy1, &zz1); - tracker.Param().Slice2Global(tracker.ISlice(), x, y, z2, &xx2, &yy2, &zz2); + mParam->Slice2Global(tracker.ISlice(), x, y, z1, &xx1, &yy1, &zz1); + mParam->Slice2Global(tracker.ISlice(), x, y, z2, &xx2, &yy2, &zz2); if (iSlice < 18) { zz1 += mZadd; zz2 += mZadd; @@ -1106,8 +1106,8 @@ GPUDisplay::vboList GPUDisplay::DrawGrid(const GPUTPCTracker& tracker) float x = row.X() + mXadd; float z = row.Grid().ZMin() + (float)j / row.Grid().StepZInv(); float zz1, zz2, yy1, yy2, xx1, xx2; - tracker.Param().Slice2Global(tracker.ISlice(), x, y1, z, &xx1, &yy1, &zz1); - tracker.Param().Slice2Global(tracker.ISlice(), x, y2, z, &xx2, &yy2, &zz2); + mParam->Slice2Global(tracker.ISlice(), x, y1, z, &xx1, &yy1, &zz1); + mParam->Slice2Global(tracker.ISlice(), x, y2, z, &xx2, &yy2, &zz2); if (iSlice < 18) { zz1 += mZadd; zz2 += mZadd; @@ -1258,11 +1258,11 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) continue; } int row = 0; - unsigned int nCls = mMerger.Param().par.earlyTpcTransform ? ioptrs().nClusterData[iSlice] : ioptrs().clustersNative->nClustersSector[iSlice]; + unsigned int nCls = mParam->par.earlyTpcTransform ? mIOPtrs->nClusterData[iSlice] : mIOPtrs->clustersNative->nClustersSector[iSlice]; for (unsigned int i = 0; i < nCls; i++) { int cid; - if (mMerger.Param().par.earlyTpcTransform) { - const auto& cl = ioptrs().clusterData[iSlice][i]; + if (mParam->par.earlyTpcTransform) { + const auto& cl = mIOPtrs->clusterData[iSlice][i]; cid = cl.id; row = cl.row; } else { @@ -1277,14 +1277,14 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) break; } float4* ptr = &mGlobalPos[cid]; - if (mMerger.Param().par.earlyTpcTransform) { - const auto& cl = ioptrs().clusterData[iSlice][i]; - mChain->GetParam().Slice2Global(iSlice, (mConfig.clustersOnNominalRow ? mMerger.Param().tpcGeometry.Row2X(row) : cl.x) + mXadd, cl.y, cl.z, &ptr->x, &ptr->y, &ptr->z); + if (mParam->par.earlyTpcTransform) { + const auto& cl = mIOPtrs->clusterData[iSlice][i]; + mParam->Slice2Global(iSlice, (mConfig.clustersOnNominalRow ? mParam->tpcGeometry.Row2X(row) : cl.x) + mXadd, cl.y, cl.z, &ptr->x, &ptr->y, &ptr->z); } else { float x, y, z; const auto& cln = mIOPtrs->clustersNative->clusters[iSlice][0][i]; GPUTPCConvertImpl::convert(*mMerger.GetConstantMem(), iSlice, row, cln.getPad(), cln.getTime(), x, y, z); - mChain->GetParam().Slice2Global(iSlice, x + mXadd, y, z, &ptr->x, &ptr->y, &ptr->z); + mParam->Slice2Global(iSlice, x + mXadd, y, z, &ptr->x, &ptr->y, &ptr->z); } if (fabsf(ptr->z) > mMaxClusterZ) { @@ -1313,7 +1313,7 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) const auto& sp = trdTracker().SpacePoints()[i]; int iSec = mChain->GetTRDGeometry()->GetSector(trdTracker().Tracklets()[i].GetDetector()); float4* ptr = &mGlobalPosTRD[i]; - mChain->GetParam().Slice2Global(iSec, sp.mR + mXadd, sp.mX[0], sp.mX[1], &ptr->x, &ptr->y, &ptr->z); + mParam->Slice2Global(iSec, sp.mR + mXadd, sp.mX[0], sp.mX[1], &ptr->x, &ptr->y, &ptr->z); ptr->x /= GL_SCALE_FACTOR; ptr->y /= GL_SCALE_FACTOR; ptr->z /= GL_SCALE_FACTOR; @@ -1322,7 +1322,7 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) } ptr->w = tTRDCLUSTER; ptr = &mGlobalPosTRD2[i]; - mChain->GetParam().Slice2Global(iSec, sp.mR + mXadd + 4.5f, sp.mX[0] + 1.5f * sp.mDy, sp.mX[1], &ptr->x, &ptr->y, &ptr->z); + mParam->Slice2Global(iSec, sp.mR + mXadd + 4.5f, sp.mX[0] + 1.5f * sp.mDy, sp.mX[1], &ptr->x, &ptr->y, &ptr->z); ptr->x /= GL_SCALE_FACTOR; ptr->y /= GL_SCALE_FACTOR; ptr->z /= GL_SCALE_FACTOR; @@ -1473,7 +1473,7 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) nextViewMatrix = nextViewMatrix * HMM_Translate({-vals[0], -vals[1], -vals[2]}); } } else if (mResetScene) { - nextViewMatrix = nextViewMatrix * HMM_Translate({0, 0, param().par.ContinuousTracking ? (-mMaxClusterZ / GL_SCALE_FACTOR - 8) : -8}); + nextViewMatrix = nextViewMatrix * HMM_Translate({0, 0, mParam->par.ContinuousTracking ? (-mMaxClusterZ / GL_SCALE_FACTOR - 8) : -8}); mViewMatrix = MY_HMM_IDENTITY; mModelMatrix = MY_HMM_IDENTITY; @@ -1681,8 +1681,8 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) GPUTPCGMPropagator prop; prop.SetMaxSinPhi(.999); prop.SetMaterialTPC(); - prop.SetPolynomialField(&mMerger.Param().polynomialField); - prop.SetToyMCEventsFlag(mMerger.Param().par.ToyMCEventsFlag); + prop.SetPolynomialField(&mParam->polynomialField); + prop.SetToyMCEventsFlag(mParam->par.ToyMCEventsFlag); GPUCA_OPENMP(barrier) GPUCA_OPENMP(for) @@ -1862,7 +1862,7 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) } { - const float zFar = ((param().par.ContinuousTracking ? (mMaxClusterZ / GL_SCALE_FACTOR) : 8.f) + 50.f) * 2.f; + const float zFar = ((mParam->par.ContinuousTracking ? (mMaxClusterZ / GL_SCALE_FACTOR) : 8.f) + 50.f) * 2.f; const hmm_mat4 proj = HMM_Perspective(mFOV, (GLfloat)mScreenwidth / (GLfloat)mScreenheight, 0.1f, zFar); nextViewMatrix = nextViewMatrix * mModelMatrix; #ifndef GPUCA_DISPLAY_OPENGL_CORE diff --git a/GPU/GPUTracking/display/GPUDisplay.h b/GPU/GPUTracking/display/GPUDisplay.h index 78d6d77a01a48..32b160648e28f 100644 --- a/GPU/GPUTracking/display/GPUDisplay.h +++ b/GPU/GPUTracking/display/GPUDisplay.h @@ -53,7 +53,7 @@ namespace gpu class GPUDisplay { public: - GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa) {} + GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa, const GPUParam* param = nullptr) {} ~GPUDisplay() = default; GPUDisplay(const GPUDisplay&) = delete; @@ -94,7 +94,7 @@ struct GPUParam; class GPUDisplay { public: - GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa); + GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa, const GPUParam* param = nullptr); ~GPUDisplay() = default; GPUDisplay(const GPUDisplay&) = delete; @@ -261,6 +261,7 @@ class GPUDisplay GPUDisplayBackend* mBackend; GPUChainTracking* mChain; + const GPUParam* mParam; const GPUSettingsDisplay& mConfig; GPUSettingsDisplayLight mCfg; GPUQA* mQA; From b6fcc5dde2b7da669dbc500c7a003dc041252701 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 21 Apr 2021 19:50:17 +0200 Subject: [PATCH 253/770] GPU: Make GPU standalone display work without access to GPU tracking chain --- GPU/GPUTracking/display/GPUDisplay.cxx | 139 ++++++++++++++----------- GPU/GPUTracking/display/GPUDisplay.h | 4 +- 2 files changed, 82 insertions(+), 61 deletions(-) diff --git a/GPU/GPUTracking/display/GPUDisplay.cxx b/GPU/GPUTracking/display/GPUDisplay.cxx index 7480041394a0f..7d99163761f74 100644 --- a/GPU/GPUTracking/display/GPUDisplay.cxx +++ b/GPU/GPUTracking/display/GPUDisplay.cxx @@ -74,12 +74,12 @@ using namespace GPUCA_NAMESPACE::gpu; #define SEPERATE_GLOBAL_TRACKS_LIMIT (mSeparateGlobalTracks ? tGLOBALTRACK : TRACK_TYPE_ID_LIMIT) -#define GET_CID(slice, i) (mParam->par.earlyTpcTransform ? tracker.ClusterData()[i].id : (mIOPtrs->clustersNative->clusterOffset[slice][0] + i)) +#define GET_CID(slice, i) (mParam->par.earlyTpcTransform ? mIOPtrs->clusterData[slice][i].id : (mIOPtrs->clustersNative->clusterOffset[slice][0] + i)) static const GPUSettingsDisplay& GPUDisplay_GetConfig(GPUChainTracking* chain) { static GPUSettingsDisplay defaultConfig; - if (chain->mConfigDisplay) { + if (chain && chain->mConfigDisplay) { return *chain->mConfigDisplay; } else { return defaultConfig; @@ -95,6 +95,18 @@ GPUDisplay::GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQ const GPUTPCTracker& GPUDisplay::sliceTracker(int iSlice) { return mChain->GetTPCSliceTrackers()[iSlice]; } const GPUTRDTrackerGPU& GPUDisplay::trdTracker() { return *mChain->GetTRDTracker(); } +inline int GPUDisplay::getNumThreads() +{ + if (mChain) { + return mChain->GetProcessingSettings().ompThreads; + } else { +#ifdef WITH_OPENMP + return omp_get_max_threads(); +#else + return 1; +#endif + } +} inline void GPUDisplay::drawVertices(const vboList& v, const GLenum t) { @@ -641,8 +653,8 @@ int GPUDisplay::InitGL_internal() setDepthBuffer(); setQuality(); ReSizeGLScene(GPUDisplayBackend::INIT_WIDTH, GPUDisplayBackend::INIT_HEIGHT, true); - mThreadBuffers.resize(mChain->GetProcessingSettings().ompThreads); - mThreadTracks.resize(mChain->GetProcessingSettings().ompThreads); + mThreadBuffers.resize(getNumThreads()); + mThreadTracks.resize(getNumThreads()); CHKERR(mVertexShader = glCreateShader(GL_VERTEX_SHADER)); CHKERR(glShaderSource(mVertexShader, 1, &GPUDisplayShaders::vertexShader, nullptr)); CHKERR(glCompileShader(mVertexShader)); @@ -683,8 +695,8 @@ GPUDisplay::vboList GPUDisplay::DrawSpacePointsTRD(int iSlice, int select, int i size_t startCountInner = mVertexBuffer[iSlice].size(); if (iCol == 0) { - for (int i = 0; i < trdTracker().NTracklets(); i++) { - int iSec = mChain->GetTRDGeometry()->GetSector(trdTracker().Tracklets()[i].GetDetector()); + for (unsigned int i = 0; i < mIOPtrs->nTRDTracklets; i++) { + int iSec = mChain->GetTRDGeometry()->GetSector(mIOPtrs->trdTracklets[i].GetDetector()); bool draw = iSlice == iSec && mGlobalPosTRD[i].w == select; if (draw) { mVertexBuffer[iSlice].emplace_back(mGlobalPosTRD[i].x, mGlobalPosTRD[i].y, mProjectXY ? 0 : mGlobalPosTRD[i].z); @@ -697,13 +709,12 @@ GPUDisplay::vboList GPUDisplay::DrawSpacePointsTRD(int iSlice, int select, int i return (vboList(startCount, mVertexBufferStart[iSlice].size() - startCount, iSlice)); } -GPUDisplay::vboList GPUDisplay::DrawClusters(const GPUTPCTracker& tracker, int select, int iCol) +GPUDisplay::vboList GPUDisplay::DrawClusters(int iSlice, int select, int iCol) { - int iSlice = tracker.ISlice(); size_t startCount = mVertexBufferStart[iSlice].size(); size_t startCountInner = mVertexBuffer[iSlice].size(); const int firstCluster = (mNCollissions > 1 && iCol > 0) ? mCollisionClusters[iCol - 1][iSlice] : 0; - const int lastCluster = (mNCollissions > 1 && iCol + 1 < mNCollissions) ? mCollisionClusters[iCol][iSlice] : tracker.Data().NumberOfHits(); + const int lastCluster = (mNCollissions > 1 && iCol + 1 < mNCollissions) ? mCollisionClusters[iCol][iSlice] : (mParam->par.earlyTpcTransform ? mIOPtrs->nClusterData[iSlice] : mIOPtrs->clustersNative->nClustersSector[iSlice]); for (int cidInSlice = firstCluster; cidInSlice < lastCluster; cidInSlice++) { const int cid = GET_CID(iSlice, cidInSlice); if (mHideUnmatchedClusters && mQA && mQA->SuppressHit(cid)) { @@ -735,7 +746,7 @@ GPUDisplay::vboList GPUDisplay::DrawClusters(const GPUTPCTracker& tracker, int s } else if (mMarkClusters) { short flags; if (mParam->par.earlyTpcTransform) { - flags = tracker.ClusterData()[cidInSlice].flags; + flags = mIOPtrs->clusterData[iSlice][cidInSlice].flags; } else { flags = mIOPtrs->clustersNative->clustersLinear[cid].getFlags(); } @@ -887,7 +898,7 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s size_t startCountInner = mVertexBuffer[iSlice].size(); bool drawing = false; - if (mTrackFilter) { + if (mTrackFilter && mChain) { if (mTrackFilter == 2 && (!trdTracker().PreCheckTrackTRDCandidate(*track) || !trdTracker().CheckTrackTRDCandidate((GPUTRDTrackGPU)*track))) { break; } @@ -897,7 +908,7 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s } if (mTRDTrackIds[i] != -1) { - auto& trk = trdTracker().Tracks()[mTRDTrackIds[i]]; + auto& trk = mIOPtrs->trdTracks[mTRDTrackIds[i]]; for (int k = 5; k >= 0; k--) { int cid = trk.GetTrackletIndex(k); if (cid < 0) { @@ -941,6 +952,10 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s break; } + if (!mChain) { + continue; + } + for (int iMC = 0; iMC < 2; iMC++) { if (iMC) { if (ii >= trackList[1].size()) { @@ -966,7 +981,7 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s if (iMC == 0) { trkParam.Set(track->GetParam()); if (mParam->par.earlyTpcTransform) { - auto cl = mMerger.ClustersXYZ()[track->FirstClusterRef() + lastCluster]; // Todo: Remove direct usage of merger + auto cl = mIOPtrs->mergedTrackHitsXYZ[track->FirstClusterRef() + lastCluster]; // Todo: Remove direct usage of merger x = cl.x; ZOffset = track->GetParam().GetTZOffset(); } else { @@ -1220,9 +1235,13 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) if (!mixAnimation && (mUpdateDLList || mResetScene)) { showTimer = true; mTimerDraw.ResetStart(); - mCurrentClusters = 0; - for (int iSlice = 0; iSlice < NSLICES; iSlice++) { - mCurrentClusters += sliceTracker(iSlice).NHitsTotal(); + if (mIOPtrs->clustersNative) { + mCurrentClusters = mIOPtrs->clustersNative->nClustersTotal; + } else { + mCurrentClusters = 0; + for (int iSlice = 0; iSlice < NSLICES; iSlice++) { + mCurrentClusters += mIOPtrs->nClusterData[iSlice]; + } } if (mNMaxClusters < mCurrentClusters) { mNMaxClusters = mCurrentClusters; @@ -1230,7 +1249,7 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) mGlobalPos = mGlobalPosPtr.get(); } - mCurrentSpacePointsTRD = trdTracker().NTracklets(); + mCurrentSpacePointsTRD = mIOPtrs->nTRDTracklets; if (mCurrentSpacePointsTRD > mNMaxSpacePointsTRD) { mNMaxSpacePointsTRD = mCurrentSpacePointsTRD; mGlobalPosPtrTRD.reset(new float4[mNMaxSpacePointsTRD]); @@ -1244,15 +1263,15 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) for (unsigned int i = 0; i < mIOPtrs->nMergedTracks; i++) { mTRDTrackIds[i] = -1; } - for (int i = 0; i < trdTracker().NTracks(); i++) { - if (trdTracker().Tracks()[i].GetNtracklets()) { - mTRDTrackIds[trdTracker().Tracks()[i].GetTPCtrackId()] = i; + for (unsigned int i = 0; i < mIOPtrs->nTRDTracks; i++) { + if (mIOPtrs->trdTracks[i].GetNtracklets()) { + mTRDTrackIds[mIOPtrs->trdTracks[i].GetTPCtrackId()] = i; } } mMaxClusterZ = 0; bool error = false; - GPUCA_OPENMP(parallel for num_threads(mChain->GetProcessingSettings().ompThreads) reduction(max : mMaxClusterZ)) + GPUCA_OPENMP(parallel for num_threads(getNumThreads()) reduction(max : mMaxClusterZ)) for (int iSlice = 0; iSlice < NSLICES; iSlice++) { if (error) { continue; @@ -1308,10 +1327,10 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) return (1); } - GPUCA_OPENMP(parallel for num_threads(mChain->GetProcessingSettings().ompThreads) reduction(max : mMaxClusterZ)) + GPUCA_OPENMP(parallel for num_threads(getNumThreads()) reduction(max : mMaxClusterZ)) for (int i = 0; i < mCurrentSpacePointsTRD; i++) { const auto& sp = trdTracker().SpacePoints()[i]; - int iSec = mChain->GetTRDGeometry()->GetSector(trdTracker().Tracklets()[i].GetDetector()); + int iSec = mChain->GetTRDGeometry()->GetSector(mIOPtrs->trdTracklets[i].GetDetector()); float4* ptr = &mGlobalPosTRD[i]; mParam->Slice2Global(iSec, sp.mR + mXadd, sp.mX[0], sp.mX[1], &ptr->x, &ptr->y, &ptr->z); ptr->x /= GL_SCALE_FACTOR; @@ -1663,7 +1682,7 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) mGlDLFinal[iSlice].resize(mNCollissions); } } - GPUCA_OPENMP(parallel num_threads(mChain->GetProcessingSettings().ompThreads)) + GPUCA_OPENMP(parallel num_threads(getNumThreads())) { #ifdef WITH_OPENMP int numThread = omp_get_thread_num(); @@ -1671,42 +1690,38 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) #else int numThread = 0, numThreads = 1; #endif - GPUCA_OPENMP(for) - for (int iSlice = 0; iSlice < NSLICES; iSlice++) { - GPUTPCTracker& tracker = (GPUTPCTracker&)sliceTracker(iSlice); - tracker.SetPointersDataLinks(tracker.LinkTmpMemory()); - mGlDLLines[iSlice][tINITLINK] = DrawLinks(tracker, tINITLINK, true); - tracker.SetPointersDataLinks(mChain->rec()->Res(tracker.MemoryResLinks()).Ptr()); - } - GPUTPCGMPropagator prop; - prop.SetMaxSinPhi(.999); - prop.SetMaterialTPC(); - prop.SetPolynomialField(&mParam->polynomialField); - prop.SetToyMCEventsFlag(mParam->par.ToyMCEventsFlag); - - GPUCA_OPENMP(barrier) - GPUCA_OPENMP(for) - for (int iSlice = 0; iSlice < NSLICES; iSlice++) { - const GPUTPCTracker& tracker = sliceTracker(iSlice); - - mGlDLLines[iSlice][tLINK] = DrawLinks(tracker, tLINK); - mGlDLLines[iSlice][tSEED] = DrawSeeds(tracker); - mGlDLLines[iSlice][tTRACKLET] = DrawTracklets(tracker); - mGlDLLines[iSlice][tSLICETRACK] = DrawTracks(tracker, 0); - mGlDLGrid[iSlice] = DrawGrid(tracker); - if (iSlice < NSLICES / 2) { - mGlDLGridTRD[iSlice] = DrawGridTRD(iSlice); + if (mChain) { + GPUCA_OPENMP(for) + for (int iSlice = 0; iSlice < NSLICES; iSlice++) { + GPUTPCTracker& tracker = (GPUTPCTracker&)sliceTracker(iSlice); + tracker.SetPointersDataLinks(tracker.LinkTmpMemory()); + mGlDLLines[iSlice][tINITLINK] = DrawLinks(tracker, tINITLINK, true); + tracker.SetPointersDataLinks(mChain->rec()->Res(tracker.MemoryResLinks()).Ptr()); + } + GPUCA_OPENMP(barrier) + + GPUCA_OPENMP(for) + for (int iSlice = 0; iSlice < NSLICES; iSlice++) { + const GPUTPCTracker& tracker = sliceTracker(iSlice); + + mGlDLLines[iSlice][tLINK] = DrawLinks(tracker, tLINK); + mGlDLLines[iSlice][tSEED] = DrawSeeds(tracker); + mGlDLLines[iSlice][tTRACKLET] = DrawTracklets(tracker); + mGlDLLines[iSlice][tSLICETRACK] = DrawTracks(tracker, 0); + mGlDLGrid[iSlice] = DrawGrid(tracker); + if (iSlice < NSLICES / 2) { + mGlDLGridTRD[iSlice] = DrawGridTRD(iSlice); + } } - } + GPUCA_OPENMP(barrier) - GPUCA_OPENMP(barrier) - GPUCA_OPENMP(for) - for (int iSlice = 0; iSlice < NSLICES; iSlice++) { - const GPUTPCTracker& tracker = sliceTracker(iSlice); - mGlDLLines[iSlice][tGLOBALTRACK] = DrawTracks(tracker, 1); + GPUCA_OPENMP(for) + for (int iSlice = 0; iSlice < NSLICES; iSlice++) { + const GPUTPCTracker& tracker = sliceTracker(iSlice); + mGlDLLines[iSlice][tGLOBALTRACK] = DrawTracks(tracker, 1); + } + GPUCA_OPENMP(barrier) } - - GPUCA_OPENMP(barrier) mThreadTracks[numThread].resize(mNCollissions); for (int i = 0; i < mNCollissions; i++) { for (int j = 0; j < NSLICES; j++) { @@ -1761,6 +1776,13 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) mThreadTracks[numThread][col][slice][1].emplace_back(i); } GPUCA_OPENMP(barrier) + + GPUTPCGMPropagator prop; + prop.SetMaxSinPhi(.999); + prop.SetMaterialTPC(); + prop.SetPolynomialField(&mParam->polynomialField); + prop.SetToyMCEventsFlag(mParam->par.ToyMCEventsFlag); + GPUCA_OPENMP(for) for (int iSlice = 0; iSlice < NSLICES; iSlice++) { for (int iCol = 0; iCol < mNCollissions; iCol++) { @@ -1783,10 +1805,9 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) GPUCA_OPENMP(barrier) GPUCA_OPENMP(for) for (int iSlice = 0; iSlice < NSLICES; iSlice++) { - const GPUTPCTracker& tracker = sliceTracker(iSlice); for (int i = 0; i < N_POINTS_TYPE_TPC; i++) { for (int iCol = 0; iCol < mNCollissions; iCol++) { - mGlDLPoints[iSlice][i][iCol] = DrawClusters(tracker, i, iCol); + mGlDLPoints[iSlice][i][iCol] = DrawClusters(iSlice, i, iCol); } } } diff --git a/GPU/GPUTracking/display/GPUDisplay.h b/GPU/GPUTracking/display/GPUDisplay.h index 32b160648e28f..4c5ce83bf9e33 100644 --- a/GPU/GPUTracking/display/GPUDisplay.h +++ b/GPU/GPUTracking/display/GPUDisplay.h @@ -191,7 +191,7 @@ class GPUDisplay int DrawGLScene_internal(bool mixAnimation, float mAnimateTime); int InitGL_internal(); - const GPUParam& param(); + int getNumThreads(); const GPUTPCTracker& sliceTracker(int iSlice); const GPUTRDTrackerGPU& trdTracker(); const GPUTrackingInOutPointers* mIOPtrs = nullptr; @@ -238,7 +238,7 @@ class GPUDisplay void UpdateOffscreenBuffers(bool clean = false); void updateConfig(); void drawPointLinestrip(int iSlice, int cid, int id, int id_limit = TRACK_TYPE_ID_LIMIT); - vboList DrawClusters(const GPUTPCTracker& tracker, int select, int iCol); + vboList DrawClusters(int iSlice, int select, int iCol); vboList DrawSpacePointsTRD(int iSlice, int select, int iCol); vboList DrawSpacePointsTRD(const GPUTPCTracker& tracker, int select, int iCol); vboList DrawLinks(const GPUTPCTracker& tracker, int id, bool dodown = false); From cfdfad0b97973e4abd5c87ef7e526f7e0a33e748 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 22 Apr 2021 00:05:30 +0200 Subject: [PATCH 254/770] GPU Display: Pass in calib objects structure instead of fetching them from tracking chain --- GPU/GPUTracking/Global/GPUChain.h | 1 + .../Interface/GPUO2InterfaceDisplay.cxx | 8 ++++---- .../Interface/GPUO2InterfaceDisplay.h | 1 + GPU/GPUTracking/display/GPUDisplay.cxx | 15 +++++++++------ GPU/GPUTracking/display/GPUDisplay.h | 6 ++++-- GPU/Workflow/CMakeLists.txt | 6 +++++- GPU/Workflow/O2GPUDPLDisplay.cxx | 18 ++++++++++++++++++ 7 files changed, 42 insertions(+), 13 deletions(-) diff --git a/GPU/GPUTracking/Global/GPUChain.h b/GPU/GPUTracking/Global/GPUChain.h index 7965bf283677c..06855bd92e6b9 100644 --- a/GPU/GPUTracking/Global/GPUChain.h +++ b/GPU/GPUTracking/Global/GPUChain.h @@ -59,6 +59,7 @@ class GPUChain const GPUSettingsGRP& GetGRPSettings() const { return mRec->mGRPSettings; } const GPUSettingsDeviceBackend& GetDeviceBackendSettings() const { return mRec->mDeviceBackendSettings; } const GPUSettingsProcessing& GetProcessingSettings() const { return mRec->mProcessingSettings; } + const GPUCalibObjectsConst& calib() const { return processors()->calibObjects; } GPUReconstruction* rec() { return mRec; } const GPUReconstruction* rec() const { return mRec; } diff --git a/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx index a395fcdb5a8b9..d34f3e141c4a7 100644 --- a/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx +++ b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx @@ -23,13 +23,13 @@ using namespace o2::tpc; GPUO2InterfaceDisplay::GPUO2InterfaceDisplay(const GPUO2InterfaceConfiguration* config) { + mConfig.reset(new GPUO2InterfaceConfiguration(*config)); mBackend.reset(new GPUDisplayBackendGlfw); - //config.configProcessing.eventDisplay = processAttributes->displayBackend.get(); + mConfig->configProcessing.eventDisplay = mBackend.get(); mParam.reset(new GPUParam); mParam->SetDefaults(&config->configGRP, &config->configReconstruction, &config->configProcessing, nullptr); - - //mDisplay.reset(new GPUDisplay(nullptr, &config->configDisplay, mParam.get())); - mDisplay.reset(new GPUDisplay(mBackend.get(), nullptr, nullptr)); + mParam->par.earlyTpcTransform = 0; + mDisplay.reset(new GPUDisplay(mBackend.get(), nullptr, nullptr, mParam.get(), (const GPUCalibObjectsConst*)&mConfig->configCalib)); } GPUO2InterfaceDisplay::~GPUO2InterfaceDisplay() = default; diff --git a/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.h b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.h index 2af8f5773e704..a6b13de818d32 100644 --- a/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.h +++ b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.h @@ -48,6 +48,7 @@ class GPUO2InterfaceDisplay std::unique_ptr mDisplay; std::unique_ptr mParam; std::unique_ptr mBackend; + std::unique_ptr mConfig; }; } // namespace o2::gpu diff --git a/GPU/GPUTracking/display/GPUDisplay.cxx b/GPU/GPUTracking/display/GPUDisplay.cxx index 7d99163761f74..afb77c98063fd 100644 --- a/GPU/GPUTracking/display/GPUDisplay.cxx +++ b/GPU/GPUTracking/display/GPUDisplay.cxx @@ -86,13 +86,15 @@ static const GPUSettingsDisplay& GPUDisplay_GetConfig(GPUChainTracking* chain) } } -GPUDisplay::GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa, const GPUParam* param) : mBackend(backend), mChain(chain), mConfig(GPUDisplay_GetConfig(chain)), mQA(qa), mMerger(chain->GetTPCMerger()) +GPUDisplay::GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa, const GPUParam* param, const GPUCalibObjectsConst* calib) : mBackend(backend), mChain(chain), mConfig(GPUDisplay_GetConfig(chain)), mQA(qa), mMerger(chain->GetTPCMerger()) { backend->mDisplay = this; mOpenGLCore = GPUCA_DISPLAY_OPENGL_CORE_FLAGS; mParam = param ? param : &mChain->GetParam(); + mCalib = calib; } +inline const GPUTRDGeometry& GPUDisplay::trdGeometry() { return *(GPUTRDGeometry*)mCalib->trdGeometry; } const GPUTPCTracker& GPUDisplay::sliceTracker(int iSlice) { return mChain->GetTPCSliceTrackers()[iSlice]; } const GPUTRDTrackerGPU& GPUDisplay::trdTracker() { return *mChain->GetTRDTracker(); } inline int GPUDisplay::getNumThreads() @@ -696,7 +698,7 @@ GPUDisplay::vboList GPUDisplay::DrawSpacePointsTRD(int iSlice, int select, int i if (iCol == 0) { for (unsigned int i = 0; i < mIOPtrs->nTRDTracklets; i++) { - int iSec = mChain->GetTRDGeometry()->GetSector(mIOPtrs->trdTracklets[i].GetDetector()); + int iSec = trdGeometry().GetSector(mIOPtrs->trdTracklets[i].GetDetector()); bool draw = iSlice == iSec && mGlobalPosTRD[i].w == select; if (draw) { mVertexBuffer[iSlice].emplace_back(mGlobalPosTRD[i].x, mGlobalPosTRD[i].y, mProjectXY ? 0 : mGlobalPosTRD[i].z); @@ -989,7 +991,7 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s const auto& cln = mIOPtrs->clustersNative->clustersLinear[cl.num]; float y, z; GPUTPCConvertImpl::convert(*mMerger.GetConstantMem(), cl.slice, cl.row, cln.getPad(), cln.getTime(), x, y, z); - ZOffset = mMerger.GetConstantMem()->calibObjects.fastTransform->convTimeToZinTimeFrame(slice, track->GetParam().GetTZOffset(), mParam->par.continuousMaxTimeBin); + ZOffset = mCalib->fastTransform->convTimeToZinTimeFrame(slice, track->GetParam().GetTZOffset(), mParam->par.continuousMaxTimeBin); } } else { const GPUTPCMCInfo& mc = mIOPtrs->mcInfosTPC[i]; @@ -1144,7 +1146,7 @@ GPUDisplay::vboList GPUDisplay::DrawGridTRD(int sector) size_t startCount = mVertexBufferStart[sector].size(); size_t startCountInner = mVertexBuffer[sector].size(); #ifdef HAVE_O2HEADERS - auto* geo = mChain->GetTRDGeometry(); + auto* geo = &trdGeometry(); if (geo) { int trdsector = NSLICES / 2 - 1 - sector; float alpha = geo->GetAlpha() / 2.f + geo->GetAlpha() * trdsector; @@ -1209,8 +1211,9 @@ GPUDisplay::vboList GPUDisplay::DrawGridTRD(int sector) int GPUDisplay::DrawGLScene(bool mixAnimation, float mAnimateTime) { - if (mIOPtrs == nullptr && mChain) { + if (mChain) { mIOPtrs = &mChain->mIOPtrs; + mCalib = &mChain->calib(); } try { if (DrawGLScene_internal(mixAnimation, mAnimateTime)) { @@ -1330,7 +1333,7 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) GPUCA_OPENMP(parallel for num_threads(getNumThreads()) reduction(max : mMaxClusterZ)) for (int i = 0; i < mCurrentSpacePointsTRD; i++) { const auto& sp = trdTracker().SpacePoints()[i]; - int iSec = mChain->GetTRDGeometry()->GetSector(mIOPtrs->trdTracklets[i].GetDetector()); + int iSec = trdGeometry().GetSector(mIOPtrs->trdTracklets[i].GetDetector()); float4* ptr = &mGlobalPosTRD[i]; mParam->Slice2Global(iSec, sp.mR + mXadd, sp.mX[0], sp.mX[1], &ptr->x, &ptr->y, &ptr->z); ptr->x /= GL_SCALE_FACTOR; diff --git a/GPU/GPUTracking/display/GPUDisplay.h b/GPU/GPUTracking/display/GPUDisplay.h index 4c5ce83bf9e33..6150316f3681e 100644 --- a/GPU/GPUTracking/display/GPUDisplay.h +++ b/GPU/GPUTracking/display/GPUDisplay.h @@ -53,7 +53,7 @@ namespace gpu class GPUDisplay { public: - GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa, const GPUParam* param = nullptr) {} + GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa, const GPUParam* param = nullptr, const GPUCalibObjectsConst* calib = nullptr) {} ~GPUDisplay() = default; GPUDisplay(const GPUDisplay&) = delete; @@ -94,7 +94,7 @@ struct GPUParam; class GPUDisplay { public: - GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa, const GPUParam* param = nullptr); + GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa, const GPUParam* param = nullptr, const GPUCalibObjectsConst* calib = nullptr); ~GPUDisplay() = default; GPUDisplay(const GPUDisplay&) = delete; @@ -194,6 +194,7 @@ class GPUDisplay int getNumThreads(); const GPUTPCTracker& sliceTracker(int iSlice); const GPUTRDTrackerGPU& trdTracker(); + const GPUTRDGeometry& trdGeometry(); const GPUTrackingInOutPointers* mIOPtrs = nullptr; void drawVertices(const vboList& v, const GLenum t); void insertVertexList(std::pair*, vecpod*>& vBuf, size_t first, size_t last); @@ -262,6 +263,7 @@ class GPUDisplay GPUDisplayBackend* mBackend; GPUChainTracking* mChain; const GPUParam* mParam; + const GPUCalibObjectsConst* mCalib; const GPUSettingsDisplay& mConfig; GPUSettingsDisplayLight mCfg; GPUQA* mQA; diff --git a/GPU/Workflow/CMakeLists.txt b/GPU/Workflow/CMakeLists.txt index 8ba083b985b64..b52f17c366580 100644 --- a/GPU/Workflow/CMakeLists.txt +++ b/GPU/Workflow/CMakeLists.txt @@ -12,4 +12,8 @@ o2_add_executable(display COMPONENT_NAME gpu TARGETVARNAME targetName SOURCES O2GPUDPLDisplay.cxx - PUBLIC_LINK_LIBRARIES O2::GPUO2Interface O2::DataFormatsGlobalTracking) + PUBLIC_LINK_LIBRARIES O2::GPUO2Interface + O2::DataFormatsGlobalTracking + O2::TPCFastTransformation + O2::TRDBase + O2::TPCReconstruction) diff --git a/GPU/Workflow/O2GPUDPLDisplay.cxx b/GPU/Workflow/O2GPUDPLDisplay.cxx index de1c51964ad49..58b9e0fd62d4d 100644 --- a/GPU/Workflow/O2GPUDPLDisplay.cxx +++ b/GPU/Workflow/O2GPUDPLDisplay.cxx @@ -14,16 +14,24 @@ #include "DataFormatsGlobalTracking/RecoContainer.h" #include "DetectorsCommonDataFormats/NameConf.h" #include "DetectorsBase/GeometryManager.h" +#include "TRDBase/GeometryFlat.h" +#include "TRDBase/Geometry.h" #include "DetectorsBase/Propagator.h" #include "GPUO2InterfaceDisplay.h" #include "GPUO2InterfaceConfiguration.h" +#include "TPCFastTransform.h" +#include "TPCReconstruction/TPCFastTransformHelperO2.h" using namespace o2::framework; using namespace o2::dataformats; using namespace o2::gpu; +using namespace o2::tpc; +using namespace o2::trd; static std::unique_ptr display; std::unique_ptr config; +std::unique_ptr fastTransform; +std::unique_ptr trdGeo; void customize(std::vector& workflowOptions) { @@ -51,6 +59,16 @@ void O2GPUDPLDisplaySpec::init(InitContext& ic) config->configGRP.solenoidBz = 5.00668f * grp->getL3Current() / 30000.; config->configGRP.continuousMaxTimeBin = grp->isDetContinuousReadOut(o2::detectors::DetID::TPC) ? -1 : 0; // Number of timebins in timeframe if continuous, 0 otherwise config->ReadConfigurableParam(); + + fastTransform = std::move(TPCFastTransformHelperO2::instance()->create(0)); + config->configCalib.fastTransform = fastTransform.get(); + + auto gm = o2::trd::Geometry::instance(); + gm->createPadPlaneArray(); + gm->createClusterMatrixArray(); + trdGeo.reset(new o2::trd::GeometryFlat(*gm)); + config->configCalib.trdGeometry = trdGeo.get(); + display.reset(new GPUO2InterfaceDisplay(config.get())); } From f9846b0d132cdc7dbd6f2db757c222943b99e36f Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 22 Apr 2021 00:09:09 +0200 Subject: [PATCH 255/770] GPU Display: Get rid of reference to GPUTPCMerger class --- GPU/GPUTracking/TPCConvert/GPUTPCConvertImpl.h | 8 ++++++++ GPU/GPUTracking/display/GPUDisplay.cxx | 6 +++--- GPU/GPUTracking/display/GPUDisplay.h | 1 - 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/GPU/GPUTracking/TPCConvert/GPUTPCConvertImpl.h b/GPU/GPUTracking/TPCConvert/GPUTPCConvertImpl.h index 3bd58e336ca50..9768466da4c8d 100644 --- a/GPU/GPUTracking/TPCConvert/GPUTPCConvertImpl.h +++ b/GPU/GPUTracking/TPCConvert/GPUTPCConvertImpl.h @@ -34,6 +34,14 @@ class GPUTPCConvertImpl cm.calibObjects.fastTransform->Transform(slice, row, pad, time, x, y, z); } } + GPUd() static void convert(const TPCFastTransform& GPUrestrict() transform, const GPUParam& GPUrestrict() param, int slice, int row, float pad, float time, float& GPUrestrict() x, float& GPUrestrict() y, float& GPUrestrict() z) + { + if (param.par.ContinuousTracking) { + transform.TransformInTimeFrame(slice, row, pad, time, x, y, z, param.par.continuousMaxTimeBin); + } else { + transform.Transform(slice, row, pad, time, x, y, z); + } + } }; } // namespace gpu diff --git a/GPU/GPUTracking/display/GPUDisplay.cxx b/GPU/GPUTracking/display/GPUDisplay.cxx index afb77c98063fd..9cd7dcf048318 100644 --- a/GPU/GPUTracking/display/GPUDisplay.cxx +++ b/GPU/GPUTracking/display/GPUDisplay.cxx @@ -86,7 +86,7 @@ static const GPUSettingsDisplay& GPUDisplay_GetConfig(GPUChainTracking* chain) } } -GPUDisplay::GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa, const GPUParam* param, const GPUCalibObjectsConst* calib) : mBackend(backend), mChain(chain), mConfig(GPUDisplay_GetConfig(chain)), mQA(qa), mMerger(chain->GetTPCMerger()) +GPUDisplay::GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa, const GPUParam* param, const GPUCalibObjectsConst* calib) : mBackend(backend), mChain(chain), mConfig(GPUDisplay_GetConfig(chain)), mQA(qa) { backend->mDisplay = this; mOpenGLCore = GPUCA_DISPLAY_OPENGL_CORE_FLAGS; @@ -990,7 +990,7 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s auto cl = mIOPtrs->mergedTrackHits[track->FirstClusterRef() + lastCluster]; const auto& cln = mIOPtrs->clustersNative->clustersLinear[cl.num]; float y, z; - GPUTPCConvertImpl::convert(*mMerger.GetConstantMem(), cl.slice, cl.row, cln.getPad(), cln.getTime(), x, y, z); + GPUTPCConvertImpl::convert(*mCalib->fastTransform, *mParam, cl.slice, cl.row, cln.getPad(), cln.getTime(), x, y, z); ZOffset = mCalib->fastTransform->convTimeToZinTimeFrame(slice, track->GetParam().GetTZOffset(), mParam->par.continuousMaxTimeBin); } } else { @@ -1305,7 +1305,7 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) } else { float x, y, z; const auto& cln = mIOPtrs->clustersNative->clusters[iSlice][0][i]; - GPUTPCConvertImpl::convert(*mMerger.GetConstantMem(), iSlice, row, cln.getPad(), cln.getTime(), x, y, z); + GPUTPCConvertImpl::convert(*mCalib->fastTransform, *mParam, iSlice, row, cln.getPad(), cln.getTime(), x, y, z); mParam->Slice2Global(iSlice, x + mXadd, y, z, &ptr->x, &ptr->y, &ptr->z); } diff --git a/GPU/GPUTracking/display/GPUDisplay.h b/GPU/GPUTracking/display/GPUDisplay.h index 6150316f3681e..5eecea9f3843e 100644 --- a/GPU/GPUTracking/display/GPUDisplay.h +++ b/GPU/GPUTracking/display/GPUDisplay.h @@ -267,7 +267,6 @@ class GPUDisplay const GPUSettingsDisplay& mConfig; GPUSettingsDisplayLight mCfg; GPUQA* mQA; - const GPUTPCGMMerger& mMerger; qSem mSemLockDisplay; GLfb mMixBuffer; From 773d306318ccbaf792f650ced2acbd7ef7dceb80 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 22 Apr 2021 11:08:51 +0200 Subject: [PATCH 256/770] GPU Display: Show blank display if no data is present --- GPU/GPUTracking/display/GPUDisplay.cxx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/GPU/GPUTracking/display/GPUDisplay.cxx b/GPU/GPUTracking/display/GPUDisplay.cxx index 9cd7dcf048318..3b119baed4578 100644 --- a/GPU/GPUTracking/display/GPUDisplay.cxx +++ b/GPU/GPUTracking/display/GPUDisplay.cxx @@ -1234,8 +1234,12 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) mSemLockDisplay.Lock(); } + if (!mIOPtrs) { + mNCollissions = 0; + } + // Extract global cluster information - if (!mixAnimation && (mUpdateDLList || mResetScene)) { + if (!mixAnimation && (mUpdateDLList || mResetScene) && mIOPtrs) { showTimer = true; mTimerDraw.ResetStart(); if (mIOPtrs->clustersNative) { @@ -1663,7 +1667,7 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) CHKERR(glLineWidth(mCfg.lineWidth * (mDrawQualityDownsampleFSAA > 1 ? mDrawQualityDownsampleFSAA : 1))); // Prepare Event - if (!mGlDLrecent) { + if (!mGlDLrecent && mIOPtrs) { for (int i = 0; i < NSLICES; i++) { mVertexBuffer[i].clear(); mVertexBufferStart[i].clear(); From 2343142aad47dc18f9c7f0e5be65c06dc5772d50 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 22 Apr 2021 11:51:48 +0200 Subject: [PATCH 257/770] GPU DPL Display: Propagate TPC clusters from workflow as external input to GPU Display --- GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx | 11 ++++++++--- GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.h | 7 ++++--- GPU/GPUTracking/display/GPUDisplay.cxx | 6 +++++- GPU/GPUTracking/display/GPUDisplay.h | 4 ++-- GPU/Workflow/O2GPUDPLDisplay.cxx | 10 ++++++++-- 5 files changed, 27 insertions(+), 11 deletions(-) diff --git a/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx index d34f3e141c4a7..5d33c86b15ab5 100644 --- a/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx +++ b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx @@ -36,12 +36,17 @@ GPUO2InterfaceDisplay::~GPUO2InterfaceDisplay() = default; int GPUO2InterfaceDisplay::startDisplay() { - return mDisplay->StartDisplay(); + int retVal = mDisplay->StartDisplay(); + if (retVal) { + return retVal; + } + mDisplay->WaitForNextEvent(); + return 0; } -int GPUO2InterfaceDisplay::show() +int GPUO2InterfaceDisplay::show(const GPUTrackingInOutPointers* ptrs) { - mDisplay->ShowNextEvent(); + mDisplay->ShowNextEvent(ptrs); do { usleep(10000); } while (mBackend->mDisplayControl == 0); diff --git a/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.h b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.h index a6b13de818d32..850b307989bbc 100644 --- a/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.h +++ b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.h @@ -31,8 +31,9 @@ namespace o2::gpu { class GPUDisplay; -class GPUParam; -class GPUO2InterfaceConfiguration; +struct GPUParam; +struct GPUTrackingInOutPointers; +struct GPUO2InterfaceConfiguration; class GPUDisplayBackend; class GPUO2InterfaceDisplay { @@ -41,7 +42,7 @@ class GPUO2InterfaceDisplay ~GPUO2InterfaceDisplay(); int startDisplay(); - int show(); + int show(const GPUTrackingInOutPointers* ptrs); int endDisplay(); private: diff --git a/GPU/GPUTracking/display/GPUDisplay.cxx b/GPU/GPUTracking/display/GPUDisplay.cxx index 3b119baed4578..5d38c1ef5ee97 100644 --- a/GPU/GPUTracking/display/GPUDisplay.cxx +++ b/GPU/GPUTracking/display/GPUDisplay.cxx @@ -2290,8 +2290,12 @@ void GPUDisplay::showInfo(const char* info) #endif } -void GPUDisplay::ShowNextEvent() +void GPUDisplay::ShowNextEvent(const GPUTrackingInOutPointers* ptrs) { + if (ptrs) { + mIOPtrs = ptrs; + mNCollissions = 1; + } mSemLockDisplay.Unlock(); mBackend->mNeedUpdate = 1; mUpdateDLList = true; diff --git a/GPU/GPUTracking/display/GPUDisplay.h b/GPU/GPUTracking/display/GPUDisplay.h index 5eecea9f3843e..f5ef966fad82c 100644 --- a/GPU/GPUTracking/display/GPUDisplay.h +++ b/GPU/GPUTracking/display/GPUDisplay.h @@ -58,7 +58,7 @@ class GPUDisplay GPUDisplay(const GPUDisplay&) = delete; int StartDisplay() { return 1; } - void ShowNextEvent() {} + void ShowNextEvent(const GPUTrackingInOutPointers* ptrs = nullptr) {} void WaitForNextEvent() {} void SetCollisionFirstCluster(unsigned int collision, int slice, int cluster) {} @@ -99,7 +99,7 @@ class GPUDisplay GPUDisplay(const GPUDisplay&) = delete; int StartDisplay(); - void ShowNextEvent(); + void ShowNextEvent(const GPUTrackingInOutPointers* ptrs = nullptr); void WaitForNextEvent(); void SetCollisionFirstCluster(unsigned int collision, int slice, int cluster); diff --git a/GPU/Workflow/O2GPUDPLDisplay.cxx b/GPU/Workflow/O2GPUDPLDisplay.cxx index 58b9e0fd62d4d..1d35206f9043e 100644 --- a/GPU/Workflow/O2GPUDPLDisplay.cxx +++ b/GPU/Workflow/O2GPUDPLDisplay.cxx @@ -78,9 +78,15 @@ void O2GPUDPLDisplaySpec::run(ProcessingContext& pc) recoData.collectData(pc, dataRequest); static bool first = false; if (first == false) { - display->startDisplay(); + if (display->startDisplay()) { + throw std::runtime_error("Error starting event display"); + } } - display->show(); + GPUTrackingInOutPointers ptrs; + recoData.addTPCClusters(pc, false); + recoData.addTPCTracks(pc, mUseMC); + ptrs.clustersNative = &recoData.inputsTPCclusters->clusterIndex; + display->show(&ptrs); } void O2GPUDPLDisplaySpec::endOfStream(EndOfStreamContext& ec) From 9697d54ef1d87178c0fa3b3c23e88562cfe4b505 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 22 Apr 2021 12:28:44 +0200 Subject: [PATCH 258/770] GPU Display: Add option to receive configuration from extern --- GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx | 2 +- GPU/GPUTracking/display/GPUDisplay.cxx | 2 +- GPU/GPUTracking/display/GPUDisplay.h | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx index 5d33c86b15ab5..6a2c989d99263 100644 --- a/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx +++ b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx @@ -29,7 +29,7 @@ GPUO2InterfaceDisplay::GPUO2InterfaceDisplay(const GPUO2InterfaceConfiguration* mParam.reset(new GPUParam); mParam->SetDefaults(&config->configGRP, &config->configReconstruction, &config->configProcessing, nullptr); mParam->par.earlyTpcTransform = 0; - mDisplay.reset(new GPUDisplay(mBackend.get(), nullptr, nullptr, mParam.get(), (const GPUCalibObjectsConst*)&mConfig->configCalib)); + mDisplay.reset(new GPUDisplay(mBackend.get(), nullptr, nullptr, mParam.get(), (const GPUCalibObjectsConst*)&mConfig->configCalib, &mConfig->configDisplay)); } GPUO2InterfaceDisplay::~GPUO2InterfaceDisplay() = default; diff --git a/GPU/GPUTracking/display/GPUDisplay.cxx b/GPU/GPUTracking/display/GPUDisplay.cxx index 5d38c1ef5ee97..44d3e9cae00c6 100644 --- a/GPU/GPUTracking/display/GPUDisplay.cxx +++ b/GPU/GPUTracking/display/GPUDisplay.cxx @@ -86,7 +86,7 @@ static const GPUSettingsDisplay& GPUDisplay_GetConfig(GPUChainTracking* chain) } } -GPUDisplay::GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa, const GPUParam* param, const GPUCalibObjectsConst* calib) : mBackend(backend), mChain(chain), mConfig(GPUDisplay_GetConfig(chain)), mQA(qa) +GPUDisplay::GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa, const GPUParam* param, const GPUCalibObjectsConst* calib, const GPUSettingsDisplay* config) : mBackend(backend), mChain(chain), mConfig(config ? *config : GPUDisplay_GetConfig(chain)), mQA(qa) { backend->mDisplay = this; mOpenGLCore = GPUCA_DISPLAY_OPENGL_CORE_FLAGS; diff --git a/GPU/GPUTracking/display/GPUDisplay.h b/GPU/GPUTracking/display/GPUDisplay.h index f5ef966fad82c..3eca765091284 100644 --- a/GPU/GPUTracking/display/GPUDisplay.h +++ b/GPU/GPUTracking/display/GPUDisplay.h @@ -53,7 +53,7 @@ namespace gpu class GPUDisplay { public: - GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa, const GPUParam* param = nullptr, const GPUCalibObjectsConst* calib = nullptr) {} + GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa, const GPUParam* param = nullptr, const GPUCalibObjectsConst* calib = nullptr, const GPUSettingsDisplay* config = nullptr) {} ~GPUDisplay() = default; GPUDisplay(const GPUDisplay&) = delete; @@ -94,7 +94,7 @@ struct GPUParam; class GPUDisplay { public: - GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa, const GPUParam* param = nullptr, const GPUCalibObjectsConst* calib = nullptr); + GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa, const GPUParam* param = nullptr, const GPUCalibObjectsConst* calib = nullptr, const GPUSettingsDisplay* config = nullptr); ~GPUDisplay() = default; GPUDisplay(const GPUDisplay&) = delete; From bbc1e3d2d1b9ebc50713c8f0aca72730ab9630c6 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 22 Apr 2021 12:53:29 +0200 Subject: [PATCH 259/770] GPU Display: Automatically disable unsupported option combinations that would lead to crashes --- GPU/GPUTracking/display/GPUDisplay.cxx | 18 +++++++++++++++++- GPU/GPUTracking/display/GPUDisplay.h | 1 + 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/GPU/GPUTracking/display/GPUDisplay.cxx b/GPU/GPUTracking/display/GPUDisplay.cxx index 44d3e9cae00c6..36ccd308d47dd 100644 --- a/GPU/GPUTracking/display/GPUDisplay.cxx +++ b/GPU/GPUTracking/display/GPUDisplay.cxx @@ -110,6 +110,19 @@ inline int GPUDisplay::getNumThreads() } } +void GPUDisplay::disableUnsupportedOptions() +{ + if (!mIOPtrs->mergedTrackHitAttachment) { + mMarkAdjacentClusters = 0; + } + if (!mQA) { + mMarkFakeClusters = 0; + } + if (!mChain) { + mCfg.excludeClusters = mCfg.drawInitLinks = mCfg.drawLinks = mCfg.drawSeeds = mCfg.drawTracklets = mCfg.drawTracks = mCfg.drawGlobalTracks = 0; + } +} + inline void GPUDisplay::drawVertices(const vboList& v, const GLenum t) { auto first = std::get<0>(v); @@ -755,7 +768,7 @@ GPUDisplay::vboList GPUDisplay::DrawClusters(int iSlice, int select, int iCol) const bool match = flags & mMarkClusters; draw = (select == tMARKED) ? (match) : (draw && !match); } else if (mMarkFakeClusters) { - const bool fake = (mQA && mQA->HitAttachStatus(cid)); + const bool fake = (mQA->HitAttachStatus(cid)); draw = (select == tMARKED) ? (fake) : (draw && !fake); } if (draw) { @@ -1237,6 +1250,9 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) if (!mIOPtrs) { mNCollissions = 0; } + if (!mixAnimation && (mUpdateDLList || mResetScene || !mGlDLrecent) && mIOPtrs) { + disableUnsupportedOptions(); + } // Extract global cluster information if (!mixAnimation && (mUpdateDLList || mResetScene) && mIOPtrs) { diff --git a/GPU/GPUTracking/display/GPUDisplay.h b/GPU/GPUTracking/display/GPUDisplay.h index 3eca765091284..00b072783a2ab 100644 --- a/GPU/GPUTracking/display/GPUDisplay.h +++ b/GPU/GPUTracking/display/GPUDisplay.h @@ -192,6 +192,7 @@ class GPUDisplay int DrawGLScene_internal(bool mixAnimation, float mAnimateTime); int InitGL_internal(); int getNumThreads(); + void disableUnsupportedOptions(); const GPUTPCTracker& sliceTracker(int iSlice); const GPUTRDTrackerGPU& trdTracker(); const GPUTRDGeometry& trdGeometry(); From 944639baa3ed136791680ed9d22ccd1bb36c7518 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 22 Apr 2021 13:57:01 +0200 Subject: [PATCH 260/770] GPU: Move track param converter functions into a header --- GPU/GPUTracking/CMakeLists.txt | 1 + GPU/GPUTracking/Refit/GPUTrackParamConvert.h | 51 ++++++++++++++++++++ GPU/GPUTracking/Refit/GPUTrackingRefit.cxx | 42 +++++----------- 3 files changed, 64 insertions(+), 30 deletions(-) create mode 100644 GPU/GPUTracking/Refit/GPUTrackParamConvert.h diff --git a/GPU/GPUTracking/CMakeLists.txt b/GPU/GPUTracking/CMakeLists.txt index 9365c316cf91b..7a92d31311bcf 100644 --- a/GPU/GPUTracking/CMakeLists.txt +++ b/GPU/GPUTracking/CMakeLists.txt @@ -139,6 +139,7 @@ set(HDRS_INSTALL qconfigoptions.h qa/GPUQAHelper.h DataCompression/GPUTPCClusterRejection.h + Refit/GPUTrackParamConvert.h Definitions/GPUDef.h Definitions/GPUDefConstantsAndSettings.h Definitions/GPUDefGPUParameters.h diff --git a/GPU/GPUTracking/Refit/GPUTrackParamConvert.h b/GPU/GPUTracking/Refit/GPUTrackParamConvert.h new file mode 100644 index 0000000000000..c52c11f42524a --- /dev/null +++ b/GPU/GPUTracking/Refit/GPUTrackParamConvert.h @@ -0,0 +1,51 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file GPUTrackParamConvert.h +/// \author David Rohr + +#ifndef O2_GPU_TRACKPARAMCONVERT_H +#define O2_GPU_TRACKPARAMCONVERT_H + +#include "GPUO2DataTypes.h" +#include "GPUTPCGMTrackParam.h" +#include "GPUTPCGMMergedTrack.h" +#include "GPUTPCGMPropagator.h" +#include "ReconstructionDataFormats/Track.h" +#include "DetectorsBase/Propagator.h" +#include "DataFormatsTPC/TrackTPC.h" + +namespace o2::gpu +{ + +GPUdi() static void convertTrackParam(GPUTPCGMTrackParam& trk, const o2::track::TrackParCov& trkX) +{ + for (int i = 0; i < 5; i++) { + trk.Par()[i] = trkX.getParams()[i]; + } + for (int i = 0; i < 15; i++) { + trk.Cov()[i] = trkX.getCov()[i]; + } + trk.X() = trkX.getX(); +} +GPUdi() static void convertTrackParam(o2::track::TrackParCov& trk, const GPUTPCGMTrackParam& trkX) +{ + for (int i = 0; i < 5; i++) { + trk.setParam(trkX.GetPar()[i], i); + } + for (int i = 0; i < 15; i++) { + trk.setCov(trkX.GetCov()[i], i); + } + trk.setX(trkX.GetX()); +} + +} // namespace o2::gpu + +#endif diff --git a/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx b/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx index 023694186c481..b1f05f8bcb54c 100644 --- a/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx +++ b/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx @@ -26,6 +26,7 @@ #include "GPUParam.inc" #include "GPUCommonArray.h" #include "GPUParam.h" +#include "GPUTrackParamConvert.h" using namespace GPUCA_NAMESPACE::gpu; using namespace o2::track; @@ -98,26 +99,7 @@ GPUd() void GPUTrackingRefit::convertTrack(T& trk, const S& trkX, U& prop, float { trk = trkX; } -GPUd() static void convertTrackParam(GPUTPCGMTrackParam& trk, const TrackParCov& trkX) -{ - for (int i = 0; i < 5; i++) { - trk.Par()[i] = trkX.getParams()[i]; - } - for (int i = 0; i < 15; i++) { - trk.Cov()[i] = trkX.getCov()[i]; - } - trk.X() = trkX.getX(); -} -GPUd() static void convertTrackParam(TrackParCov& trk, const GPUTPCGMTrackParam& trkX) -{ - for (int i = 0; i < 5; i++) { - trk.setParam(trkX.GetPar()[i], i); - } - for (int i = 0; i < 15; i++) { - trk.setCov(trkX.GetCov()[i], i); - } - trk.setX(trkX.GetX()); -} + // Generic template <> GPUd() void GPUTrackingRefit::convertTrack(GPUTPCGMTrackParam& trk, const TrackParCov& trkX, GPUTPCGMPropagator& prop, float* chi2) @@ -233,7 +215,7 @@ GPUd() int GPUTrackingRefit::RefitTrack(T& trkX, bool outward, bool resetCov) convertTrack(trk, trkX, prop, &TrackParCovChi2); int begin = 0, count; float tOffset; - if constexpr (std::is_same::value) { + if constexpr (std::is_same_v) { count = trkX.NClusters(); if (trkX.Looper()) { int leg = mPtrackHits[trkX.FirstClusterRef() + trkX.NClusters() - 1].leg; @@ -245,10 +227,10 @@ GPUd() int GPUTrackingRefit::RefitTrack(T& trkX, bool outward, bool resetCov) } } tOffset = trkX.GetParam().GetTZOffset(); - } else if constexpr (std::is_same::value) { + } else if constexpr (std::is_same_v) { count = trkX.getNClusters(); tOffset = trkX.getTime0(); - } else if constexpr (std::is_same::value) { + } else if constexpr (std::is_same_v) { count = trkX.clusRef.getEntries(); tOffset = trkX.time0; } else { @@ -267,7 +249,7 @@ GPUd() int GPUTrackingRefit::RefitTrack(T& trkX, bool outward, bool resetCov) while (true) { if (!cl) { CADEBUG(ii = i); - if constexpr (std::is_same::value) { + if constexpr (std::is_same_v) { const auto& hit = mPtrackHits[trkX.FirstClusterRef() + i]; cl = &mPclusterNative->clustersLinear[hit.num]; if (hit.state & (GPUTPCGMMergedTrackHit::flagReject | GPUTPCGMMergedTrackHit::flagNotFit)) { @@ -281,10 +263,10 @@ GPUd() int GPUTrackingRefit::RefitTrack(T& trkX, bool outward, bool resetCov) row = hit.row; sector = hit.slice; nextState = mPclusterState[hit.num]; - } else if constexpr (std::is_same::value) { + } else if constexpr (std::is_same_v) { cl = &trkX.getCluster(mPtrackHitReferences, i, *mPclusterNative, sector, row); nextState = mPclusterState[cl - mPclusterNative->clustersLinear]; - } else if constexpr (std::is_same::value) { + } else if constexpr (std::is_same_v) { cl = &TrackTPC::getCluster(mPtrackHitReferences, i, *mPclusterNative, sector, row, trkX.clusRef); nextState = mPclusterState[cl - mPclusterNative->clustersLinear]; } else { @@ -332,7 +314,7 @@ GPUd() int GPUTrackingRefit::RefitTrack(T& trkX, bool outward, bool resetCov) CADEBUG(printf("\tMerged Hit Row %3d: Cluster Alpha %8.3f %3d, X %8.3f - Y %8.3f, Z %8.3f\n", row, mPparam->Alpha(sector), (int)sector, x, y, z)); } - if constexpr (std::is_same::value) { + if constexpr (std::is_same_v) { if (prop.PropagateToXAlpha(x, mPparam->Alpha(currentSector), !outward)) { IgnoreErrors(trk.GetSinPhi()); return -2; @@ -346,7 +328,7 @@ GPUd() int GPUTrackingRefit::RefitTrack(T& trkX, bool outward, bool resetCov) return -3; } CADEBUG(printf("\t%21sFit Alpha %8.3f , X %8.3f - Y %8.3f, Z %8.3f - QPt %7.2f (%7.2f), SP %5.2f (%5.2f), DzDs %5.2f %16s --- Cov sY %8.3f sZ %8.3f sSP %8.3f sPt %8.3f - YPt %8.3f\n", "", prop.GetAlpha(), x, trk.Par()[0], trk.Par()[1], trk.Par()[4], prop.GetQPt0(), trk.Par()[2], prop.GetSinPhi0(), trk.Par()[3], "", sqrtf(trk.Cov()[0]), sqrtf(trk.Cov()[2]), sqrtf(trk.Cov()[5]), sqrtf(trk.Cov()[14]), trk.Cov()[10])); - } else if constexpr (std::is_same::value) { + } else if constexpr (std::is_same_v) { if (!trk.rotate(mPparam->Alpha(currentSector))) { IgnoreErrors(trk.getSnp()); return -1; @@ -376,12 +358,12 @@ GPUd() int GPUTrackingRefit::RefitTrack(T& trkX, bool outward, bool resetCov) resetCov = false; nFitted++; } - if constexpr (std::is_same::value) { + if constexpr (std::is_same_v) { float alpha = prop.GetAlpha(); trk.MoveToReference(prop, *mPparam, alpha); trk.NormalizeAlpha(alpha); prop.SetAlpha(alpha); - } else if constexpr (std::is_same::value) { + } else if constexpr (std::is_same_v) { static constexpr float kDeg2Rad = M_PI / 180.f; static constexpr float kSectAngle = 2 * M_PI / 18.f; if (mPparam->rec.TrackReferenceX <= 500) { From 9ef7bc2b63df2b2d2d68a2821898ec8f63270201 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 22 Apr 2021 14:21:18 +0200 Subject: [PATCH 261/770] GPU: ioPtrs should hold only pointers to const arrays --- GPU/GPUTracking/DataTypes/GPUDataTypes.h | 10 +++++----- .../Interface/GPUO2InterfaceConfiguration.h | 12 ++++++------ 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/GPU/GPUTracking/DataTypes/GPUDataTypes.h b/GPU/GPUTracking/DataTypes/GPUDataTypes.h index 48e32b259eea1..e45bb777362c9 100644 --- a/GPU/GPUTracking/DataTypes/GPUDataTypes.h +++ b/GPU/GPUTracking/DataTypes/GPUDataTypes.h @@ -235,13 +235,13 @@ struct GPUTrackingInOutPointers { const GPUTPCGMMergedTrackHit* mergedTrackHits = nullptr; const GPUTPCGMMergedTrackHitXYZ* mergedTrackHitsXYZ = nullptr; unsigned int nMergedTrackHits = 0; - unsigned int* mergedTrackHitAttachment = nullptr; - unsigned char* mergedTrackHitStates = nullptr; - o2::tpc::TrackTPC* outputTracksTPCO2 = nullptr; + const unsigned int* mergedTrackHitAttachment = nullptr; + const unsigned char* mergedTrackHitStates = nullptr; + const o2::tpc::TrackTPC* outputTracksTPCO2 = nullptr; unsigned int nOutputTracksTPCO2 = 0; - unsigned int* outputClusRefsTPCO2 = nullptr; + const unsigned int* outputClusRefsTPCO2 = nullptr; unsigned int nOutputClusRefsTPCO2 = 0; - o2::MCCompLabel* outputTracksTPCO2MC = nullptr; + const o2::MCCompLabel* outputTracksTPCO2MC = nullptr; const o2::tpc::CompressedClustersFlat* tpcCompressedClusters = nullptr; const GPUTRDTrackletWord* trdTracklets = nullptr; unsigned int nTRDTracklets = 0; diff --git a/GPU/GPUTracking/Interface/GPUO2InterfaceConfiguration.h b/GPU/GPUTracking/Interface/GPUO2InterfaceConfiguration.h index b55624663dd6f..8e43d8809f3c5 100644 --- a/GPU/GPUTracking/Interface/GPUO2InterfaceConfiguration.h +++ b/GPU/GPUTracking/Interface/GPUO2InterfaceConfiguration.h @@ -115,13 +115,13 @@ struct GPUO2InterfaceIOPtrs { // Input / Output for Merged TPC tracks, two ptrs, for the tracks themselves, and for the MC labels. #ifdef MS_GSL_V3 - gsl::span outputTracks = {nullptr, (gsl::span::size_type)0}; - gsl::span outputClusRefs = {nullptr, (gsl::span::size_type)0}; - gsl::span outputTracksMCTruth = {nullptr, (gsl::span::size_type)0}; + gsl::span outputTracks = {nullptr, (gsl::span::size_type)0}; + gsl::span outputClusRefs = {nullptr, (gsl::span::size_type)0}; + gsl::span outputTracksMCTruth = {nullptr, (gsl::span::size_type)0}; #else - gsl::span outputTracks = {nullptr, (gsl::span::index_type)0}; - gsl::span outputClusRefs = {nullptr, (gsl::span::index_type)0}; - gsl::span outputTracksMCTruth = {nullptr, (gsl::span::index_type)0}; + gsl::span outputTracks = {nullptr, (gsl::span::index_type)0}; + gsl::span outputClusRefs = {nullptr, (gsl::span::index_type)0}; + gsl::span outputTracksMCTruth = {nullptr, (gsl::span::index_type)0}; #endif // Output for entropy-reduced clusters of TPC compression const o2::tpc::CompressedClustersFlat* compressedClusters = nullptr; From 9a787bd43f737f5536a31dca00da9410726b7581 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 22 Apr 2021 13:59:14 +0200 Subject: [PATCH 262/770] GPU Display: Can optionally show TPC tracks from O2 format instead of GPU format --- GPU/GPUTracking/Definitions/GPUSettingsList.h | 1 + .../Interface/GPUO2InterfaceDisplay.cxx | 1 + GPU/GPUTracking/display/GPUDisplay.cxx | 144 +++++++++++++----- GPU/GPUTracking/display/GPUDisplay.h | 1 + GPU/Workflow/O2GPUDPLDisplay.cxx | 12 ++ 5 files changed, 119 insertions(+), 40 deletions(-) diff --git a/GPU/GPUTracking/Definitions/GPUSettingsList.h b/GPU/GPUTracking/Definitions/GPUSettingsList.h index c5edb7241e120..6bd651578dbae 100644 --- a/GPU/GPUTracking/Definitions/GPUSettingsList.h +++ b/GPU/GPUTracking/Definitions/GPUSettingsList.h @@ -154,6 +154,7 @@ EndConfig() BeginSubConfig(GPUSettingsDisplay, GL, configStandalone, "GL", 'g', "OpenGL display settings") AddOption(clustersOnly, bool, false, "", 0, "Visualize clusters only") AddOption(clustersOnNominalRow, bool, false, "", 0, "Show clusters at nominal x of pad row for early-transformed data") +AddOption(showTPCTracksFromO2Format, bool, false, "", 0, "Use TPC tracks in O2 output format instead of GPU format") AddHelp("help", 'h') EndConfig() diff --git a/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx index 6a2c989d99263..2799b4183b42e 100644 --- a/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx +++ b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx @@ -26,6 +26,7 @@ GPUO2InterfaceDisplay::GPUO2InterfaceDisplay(const GPUO2InterfaceConfiguration* mConfig.reset(new GPUO2InterfaceConfiguration(*config)); mBackend.reset(new GPUDisplayBackendGlfw); mConfig->configProcessing.eventDisplay = mBackend.get(); + mConfig->configDisplay.showTPCTracksFromO2Format = true; mParam.reset(new GPUParam); mParam->SetDefaults(&config->configGRP, &config->configReconstruction, &config->configProcessing, nullptr); mParam->par.earlyTpcTransform = 0; diff --git a/GPU/GPUTracking/display/GPUDisplay.cxx b/GPU/GPUTracking/display/GPUDisplay.cxx index 36ccd308d47dd..97168a89377c0 100644 --- a/GPU/GPUTracking/display/GPUDisplay.cxx +++ b/GPU/GPUTracking/display/GPUDisplay.cxx @@ -23,6 +23,7 @@ #include #include #include +#include #ifndef _WIN32 #include "bitmapfile.h" @@ -45,11 +46,16 @@ #include "GPUTPCClusterData.h" #include "GPUTRDTrackletWord.h" #include "GPUTRDGeometry.h" +#include "GPUTrackParamConvert.h" #include "GPUO2DataTypes.h" #include "GPUParam.inc" #include "GPUTPCConvertImpl.h" #include "utils/qconfig.h" +#ifdef HAVE_O2HEADERS +#include "DataFormatsTPC/TrackTPC.h" +#endif + #include "GPUDisplayShaders.h" constexpr hmm_mat4 MY_HMM_IDENTITY = {{{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}}; @@ -121,6 +127,9 @@ void GPUDisplay::disableUnsupportedOptions() if (!mChain) { mCfg.excludeClusters = mCfg.drawInitLinks = mCfg.drawLinks = mCfg.drawSeeds = mCfg.drawTracklets = mCfg.drawTracks = mCfg.drawGlobalTracks = 0; } + if (mConfig.showTPCTracksFromO2Format && mParam->par.earlyTpcTransform) { + throw std::runtime_error("Cannot run GPU display with early Transform when input is O2 tracks"); + } } inline void GPUDisplay::drawVertices(const vboList& v, const GLenum t) @@ -891,6 +900,7 @@ GPUDisplay::vboList GPUDisplay::DrawTracks(const GPUTPCTracker& tracker, int glo return (vboList(startCount, mVertexBufferStart[iSlice].size() - startCount, iSlice)); } +template void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, std::array, 2>& trackList, threadVertexBuffer& threadBuffer) { auto& vBuf = threadBuffer.vBuf; @@ -901,24 +911,33 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s } for (unsigned int ii = 0; ii < nTracks; ii++) { int i = 0; - const GPUTPCGMMergedTrack* track = nullptr; + const T* track = nullptr; int lastCluster = -1; while (true) { if (ii >= trackList[0].size()) { break; } i = trackList[0][ii]; - track = &mIOPtrs->mergedTracks[i]; + int nClusters; + if constexpr (std::is_same_v) { + track = &mIOPtrs->mergedTracks[i]; + nClusters = track->NClusters(); + } else { + track = &mIOPtrs->outputTracksTPCO2[i]; + nClusters = track->getNClusters(); + } size_t startCountInner = mVertexBuffer[iSlice].size(); bool drawing = false; - if (mTrackFilter && mChain) { - if (mTrackFilter == 2 && (!trdTracker().PreCheckTrackTRDCandidate(*track) || !trdTracker().CheckTrackTRDCandidate((GPUTRDTrackGPU)*track))) { - break; - } - if (mTrackFilter == 1 && mTRDTrackIds[i] == -1) { - break; + if constexpr (std::is_same_v) { + if (mTrackFilter && mChain) { + if (mTrackFilter == 2 && (!trdTracker().PreCheckTrackTRDCandidate(*track) || !trdTracker().CheckTrackTRDCandidate((GPUTRDTrackGPU)*track))) { + break; + } + if (mTrackFilter == 1 && mTRDTrackIds[i] == -1) { + break; + } } } @@ -935,11 +954,18 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s mGlobalPosTRD[cid].w = tTRDATTACHED; } } - for (unsigned int k = 0; k < track->NClusters(); k++) { - if (mHideRejectedClusters && (mIOPtrs->mergedTrackHits[track->FirstClusterRef() + k].state & GPUTPCGMMergedTrackHit::flagReject)) { - continue; + for (unsigned int k = 0; k < nClusters; k++) { + if constexpr (std::is_same_v) { + if (mHideRejectedClusters && (mIOPtrs->mergedTrackHits[track->FirstClusterRef() + k].state & GPUTPCGMMergedTrackHit::flagReject)) { + continue; + } + } + int cid; + if constexpr (std::is_same_v) { + cid = mIOPtrs->mergedTrackHits[track->FirstClusterRef() + k].num; + } else { + cid = &track->getCluster(mIOPtrs->outputClusRefsTPCO2, k, *mIOPtrs->clustersNative) - mIOPtrs->clustersNative->clustersLinear; } - int cid = mIOPtrs->mergedTrackHits[track->FirstClusterRef() + k].num; int w = mGlobalPos[cid].w; if (drawing) { drawPointLinestrip(iSlice, cid, tFINALTRACK, SEPERATE_GLOBAL_TRACKS_LIMIT); @@ -957,7 +983,12 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s drawPointLinestrip(iSlice, cid, tFINALTRACK, SEPERATE_GLOBAL_TRACKS_LIMIT); } if (!drawing && lastCluster != -1) { - drawPointLinestrip(iSlice, mIOPtrs->mergedTrackHits[track->FirstClusterRef() + lastCluster].num, 7, SEPERATE_GLOBAL_TRACKS_LIMIT); + if constexpr (std::is_same_v) { + cid = mIOPtrs->mergedTrackHits[track->FirstClusterRef() + lastCluster].num; + } else { + cid = &track->getCluster(mIOPtrs->outputClusRefsTPCO2, lastCluster, *mIOPtrs->clustersNative) - mIOPtrs->clustersNative->clustersLinear; + } + drawPointLinestrip(iSlice, cid, 7, SEPERATE_GLOBAL_TRACKS_LIMIT); } drawing = true; } @@ -994,17 +1025,32 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s int slice = iSlice; float alpha = mParam->Alpha(slice); if (iMC == 0) { - trkParam.Set(track->GetParam()); + if constexpr (std::is_same_v) { + trkParam.Set(track->GetParam()); + } else { + GPUTPCGMTrackParam t; + convertTrackParam(t, *track); + trkParam.Set(t); + } + if (mParam->par.earlyTpcTransform) { - auto cl = mIOPtrs->mergedTrackHitsXYZ[track->FirstClusterRef() + lastCluster]; // Todo: Remove direct usage of merger - x = cl.x; - ZOffset = track->GetParam().GetTZOffset(); + if constexpr (std::is_same_v) { + x = mIOPtrs->mergedTrackHitsXYZ[track->FirstClusterRef() + lastCluster].x; + ZOffset = track->GetParam().GetTZOffset(); + } } else { - auto cl = mIOPtrs->mergedTrackHits[track->FirstClusterRef() + lastCluster]; - const auto& cln = mIOPtrs->clustersNative->clustersLinear[cl.num]; float y, z; - GPUTPCConvertImpl::convert(*mCalib->fastTransform, *mParam, cl.slice, cl.row, cln.getPad(), cln.getTime(), x, y, z); - ZOffset = mCalib->fastTransform->convTimeToZinTimeFrame(slice, track->GetParam().GetTZOffset(), mParam->par.continuousMaxTimeBin); + if constexpr (std::is_same_v) { + auto cl = mIOPtrs->mergedTrackHits[track->FirstClusterRef() + lastCluster]; + const auto& cln = mIOPtrs->clustersNative->clustersLinear[cl.num]; + GPUTPCConvertImpl::convert(*mCalib->fastTransform, *mParam, cl.slice, cl.row, cln.getPad(), cln.getTime(), x, y, z); + ZOffset = mCalib->fastTransform->convTimeToZinTimeFrame(slice, track->GetParam().GetTZOffset(), mParam->par.continuousMaxTimeBin); + } else { + uint8_t sector, row; + auto cln = track->getCluster(mIOPtrs->outputClusRefsTPCO2, lastCluster, *mIOPtrs->clustersNative, sector, row); + GPUTPCConvertImpl::convert(*mCalib->fastTransform, *mParam, sector, row, cln.getPad(), cln.getTime(), x, y, z); + ZOffset = mCalib->fastTransform->convTimeToZinTimeFrame(slice, track->getTime0(), mParam->par.continuousMaxTimeBin); + } } } else { const GPUTPCMCInfo& mc = mIOPtrs->mcInfosTPC[i]; @@ -1280,10 +1326,11 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) mGlobalPosTRD = mGlobalPosPtrTRD.get(); mGlobalPosTRD2 = mGlobalPosPtrTRD2.get(); } - if ((size_t)mIOPtrs->nMergedTracks > mTRDTrackIds.size()) { - mTRDTrackIds.resize(mIOPtrs->nMergedTracks); + unsigned int nTpcMergedTracks = mConfig.showTPCTracksFromO2Format ? mIOPtrs->nOutputTracksTPCO2 : mIOPtrs->nMergedTracks; + if ((size_t)nTpcMergedTracks > mTRDTrackIds.size()) { + mTRDTrackIds.resize(nTpcMergedTracks); } - for (unsigned int i = 0; i < mIOPtrs->nMergedTracks; i++) { + for (unsigned int i = 0; i < nTpcMergedTracks; i++) { mTRDTrackIds[i] = -1; } for (unsigned int i = 0; i < mIOPtrs->nTRDTracks; i++) { @@ -1753,24 +1800,34 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) } } } - GPUCA_OPENMP(for) - for (unsigned int i = 0; i < mIOPtrs->nMergedTracks; i++) { - const GPUTPCGMMergedTrack* track = &mIOPtrs->mergedTracks[i]; - if (track->NClusters() == 0) { - continue; - } - if (mHideRejectedTracks && !track->OK()) { - continue; - } - int slice = mIOPtrs->mergedTrackHits[track->FirstClusterRef() + track->NClusters() - 1].slice; + if (mConfig.showTPCTracksFromO2Format) { unsigned int col = 0; - if (mNCollissions > 1) { - int label = mQA ? mQA->GetMCTrackLabel(i) : -1; - while (col < mCollisionClusters.size() && mCollisionClusters[col][NSLICES] < label) { - col++; + GPUCA_OPENMP(for) + for (unsigned int i = 0; i < mIOPtrs->nOutputTracksTPCO2; i++) { + uint8_t sector, row; + mIOPtrs->outputTracksTPCO2[i].getCluster(mIOPtrs->outputClusRefsTPCO2, 0, *mIOPtrs->clustersNative, sector, row); + mThreadTracks[numThread][col][sector][0].emplace_back(i); + } + } else { + GPUCA_OPENMP(for) + for (unsigned int i = 0; i < mIOPtrs->nMergedTracks; i++) { + const GPUTPCGMMergedTrack* track = &mIOPtrs->mergedTracks[i]; + if (track->NClusters() == 0) { + continue; + } + if (mHideRejectedTracks && !track->OK()) { + continue; } + int slice = mIOPtrs->mergedTrackHits[track->FirstClusterRef() + track->NClusters() - 1].slice; + unsigned int col = 0; + if (mNCollissions > 1) { + int label = mQA ? mQA->GetMCTrackLabel(i) : -1; + while (col < mCollisionClusters.size() && mCollisionClusters[col][NSLICES] < label) { + col++; + } + } + mThreadTracks[numThread][col][slice][0].emplace_back(i); } - mThreadTracks[numThread][col][slice][0].emplace_back(i); } GPUCA_OPENMP(for) for (unsigned int i = 0; i < mIOPtrs->nMCInfosTPC; i++) { @@ -1811,7 +1868,14 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) for (int iCol = 0; iCol < mNCollissions; iCol++) { mThreadBuffers[numThread].clear(); for (int iSet = 0; iSet < numThreads; iSet++) { - DrawFinal(iSlice, iCol, &prop, mThreadTracks[iSet][iCol][iSlice], mThreadBuffers[numThread]); +#ifdef HAVE_O2HEADERS + if (mConfig.showTPCTracksFromO2Format) { + DrawFinal(iSlice, iCol, &prop, mThreadTracks[iSet][iCol][iSlice], mThreadBuffers[numThread]); + } else +#endif + { + DrawFinal(iSlice, iCol, &prop, mThreadTracks[iSet][iCol][iSlice], mThreadBuffers[numThread]); + } } vboList* list = &mGlDLFinal[iSlice][iCol][0]; for (int i = 0; i < N_FINAL_TYPE; i++) { diff --git a/GPU/GPUTracking/display/GPUDisplay.h b/GPU/GPUTracking/display/GPUDisplay.h index 00b072783a2ab..ef9f6f1333e70 100644 --- a/GPU/GPUTracking/display/GPUDisplay.h +++ b/GPU/GPUTracking/display/GPUDisplay.h @@ -247,6 +247,7 @@ class GPUDisplay vboList DrawSeeds(const GPUTPCTracker& tracker); vboList DrawTracklets(const GPUTPCTracker& tracker); vboList DrawTracks(const GPUTPCTracker& tracker, int global); + template void DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, std::array, 2>& trackList, threadVertexBuffer& threadBuffer); vboList DrawGrid(const GPUTPCTracker& tracker); vboList DrawGridTRD(int sector); diff --git a/GPU/Workflow/O2GPUDPLDisplay.cxx b/GPU/Workflow/O2GPUDPLDisplay.cxx index 1d35206f9043e..fb0c72d73e83d 100644 --- a/GPU/Workflow/O2GPUDPLDisplay.cxx +++ b/GPU/Workflow/O2GPUDPLDisplay.cxx @@ -82,10 +82,22 @@ void O2GPUDPLDisplaySpec::run(ProcessingContext& pc) throw std::runtime_error("Error starting event display"); } } + GPUTrackingInOutPointers ptrs; recoData.addTPCClusters(pc, false); recoData.addTPCTracks(pc, mUseMC); ptrs.clustersNative = &recoData.inputsTPCclusters->clusterIndex; + const auto& tpcTracks = recoData.getTPCTracks(); + const auto& tpcClusRefs = recoData.getTPCTracksClusterRefs(); + ptrs.outputTracksTPCO2 = tpcTracks.data(); + ptrs.nOutputTracksTPCO2 = tpcTracks.size(); + ptrs.outputClusRefsTPCO2 = tpcClusRefs.data(); + ptrs.nOutputClusRefsTPCO2 = tpcClusRefs.size(); + if (mUseMC) { + const auto& tpcTracksMC = recoData.getTPCTracksMCLabels(); + ptrs.outputTracksTPCO2MC = tpcTracksMC.data(); + } + display->show(&ptrs); } From 6d1a05c53bcc9c313b605034bee34d1572269089 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 22 Apr 2021 14:38:54 +0200 Subject: [PATCH 263/770] GPU Display: If the first event was empty, we set the initial camera z position for the first non-empty event --- GPU/GPUTracking/display/GPUDisplay.cxx | 3 +++ GPU/GPUTracking/display/GPUDisplay.h | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/GPU/GPUTracking/display/GPUDisplay.cxx b/GPU/GPUTracking/display/GPUDisplay.cxx index 97168a89377c0..6b864c38f3f5d 100644 --- a/GPU/GPUTracking/display/GPUDisplay.cxx +++ b/GPU/GPUTracking/display/GPUDisplay.cxx @@ -2376,6 +2376,9 @@ void GPUDisplay::ShowNextEvent(const GPUTrackingInOutPointers* ptrs) mIOPtrs = ptrs; mNCollissions = 1; } + if (mMaxClusterZ <= 0) { + mResetScene = true; + } mSemLockDisplay.Unlock(); mBackend->mNeedUpdate = 1; mUpdateDLList = true; diff --git a/GPU/GPUTracking/display/GPUDisplay.h b/GPU/GPUTracking/display/GPUDisplay.h index ef9f6f1333e70..f3bb68d6c450c 100644 --- a/GPU/GPUTracking/display/GPUDisplay.h +++ b/GPU/GPUTracking/display/GPUDisplay.h @@ -302,7 +302,7 @@ class GPUDisplay float mFOV = 45.f; float mAngleRollOrigin = -1e9; - float mMaxClusterZ = 0; + float mMaxClusterZ = -1; int screenshot_scale = 1; From 851cb73374f4d42e94dfeb01ee60ef82542a57f4 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 22 Apr 2021 22:45:36 +0200 Subject: [PATCH 264/770] GPU DPL Display: Add option to read inputs from ROOT files using InputHelper class --- GPU/Workflow/CMakeLists.txt | 3 ++- GPU/Workflow/O2GPUDPLDisplay.cxx | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/GPU/Workflow/CMakeLists.txt b/GPU/Workflow/CMakeLists.txt index b52f17c366580..0698fe3c3970a 100644 --- a/GPU/Workflow/CMakeLists.txt +++ b/GPU/Workflow/CMakeLists.txt @@ -16,4 +16,5 @@ o2_add_executable(display O2::DataFormatsGlobalTracking O2::TPCFastTransformation O2::TRDBase - O2::TPCReconstruction) + O2::TPCReconstruction + O2::GlobalTrackingWorkflowHelpers) diff --git a/GPU/Workflow/O2GPUDPLDisplay.cxx b/GPU/Workflow/O2GPUDPLDisplay.cxx index fb0c72d73e83d..ebd313cf609fa 100644 --- a/GPU/Workflow/O2GPUDPLDisplay.cxx +++ b/GPU/Workflow/O2GPUDPLDisplay.cxx @@ -21,6 +21,7 @@ #include "GPUO2InterfaceConfiguration.h" #include "TPCFastTransform.h" #include "TPCReconstruction/TPCFastTransformHelperO2.h" +#include "GlobalTrackingWorkflowHelpers/InputHelper.h" using namespace o2::framework; using namespace o2::dataformats; @@ -39,6 +40,8 @@ void customize(std::vector& workflowOptions) {"enable-mc", o2::framework::VariantType::Bool, false, {"enable visualization of MC data"}}, {"display-clusters", VariantType::String, "TPC", {"comma-separated list of clusters to display"}}, {"display-tracks", VariantType::String, "TPC", {"comma-separated list of tracks to display"}}, + {"read-from-files", o2::framework::VariantType::Bool, false, {"comma-separated list of tracks to display"}}, + {"disable-root-input", o2::framework::VariantType::Bool, false, {"Disable root input overriding read-from-files"}}, {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings ..."}}}; std::swap(workflowOptions, options); @@ -116,6 +119,10 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) dataRequest.requestTracks(srcTrk, useMC); dataRequest.requestClusters(srcCl, useMC); + if (cfgc.options().get("read-from-files")) { + InputHelper::addInputSpecs(cfgc, specs, srcCl, srcTrk, srcTrk, useMC); + } + specs.emplace_back(DataProcessorSpec{ "o2-gpu-display", dataRequest.inputs, From 1de3ed294712a7b94657ae4e04e364e42b890f6e Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 22 Apr 2021 20:01:25 +0200 Subject: [PATCH 265/770] GPU DPL Display: Avoid using global variables through shared ptr and move files to proper folders --- GPU/GPUTracking/Interface/GPUO2InterfaceQA.h | 4 +- GPU/Workflow/CMakeLists.txt | 3 +- .../GPUWorkflow}/O2GPUDPLDisplay.h | 22 +++++++- GPU/Workflow/{ => src}/O2GPUDPLDisplay.cxx | 51 ++++++++----------- 4 files changed, 46 insertions(+), 34 deletions(-) rename GPU/Workflow/{ => include/GPUWorkflow}/O2GPUDPLDisplay.h (62%) rename GPU/Workflow/{ => src}/O2GPUDPLDisplay.cxx (76%) diff --git a/GPU/GPUTracking/Interface/GPUO2InterfaceQA.h b/GPU/GPUTracking/Interface/GPUO2InterfaceQA.h index d328cd1401a84..365e91d70877e 100644 --- a/GPU/GPUTracking/Interface/GPUO2InterfaceQA.h +++ b/GPU/GPUTracking/Interface/GPUO2InterfaceQA.h @@ -46,8 +46,8 @@ struct ClusterNativeAccess; namespace o2::gpu { class GPUQA; -class GPUParam; -class GPUO2InterfaceConfiguration; +struct GPUParam; +struct GPUO2InterfaceConfiguration; class GPUO2InterfaceQA { public: diff --git a/GPU/Workflow/CMakeLists.txt b/GPU/Workflow/CMakeLists.txt index 0698fe3c3970a..9e76b078642cf 100644 --- a/GPU/Workflow/CMakeLists.txt +++ b/GPU/Workflow/CMakeLists.txt @@ -11,10 +11,11 @@ o2_add_executable(display COMPONENT_NAME gpu TARGETVARNAME targetName - SOURCES O2GPUDPLDisplay.cxx + SOURCES src/O2GPUDPLDisplay.cxx PUBLIC_LINK_LIBRARIES O2::GPUO2Interface O2::DataFormatsGlobalTracking O2::TPCFastTransformation O2::TRDBase O2::TPCReconstruction O2::GlobalTrackingWorkflowHelpers) +target_include_directories(${targetName} PUBLIC "include") diff --git a/GPU/Workflow/O2GPUDPLDisplay.h b/GPU/Workflow/include/GPUWorkflow/O2GPUDPLDisplay.h similarity index 62% rename from GPU/Workflow/O2GPUDPLDisplay.h rename to GPU/Workflow/include/GPUWorkflow/O2GPUDPLDisplay.h index cab295c39c55e..2211dedb65793 100644 --- a/GPU/Workflow/O2GPUDPLDisplay.h +++ b/GPU/Workflow/include/GPUWorkflow/O2GPUDPLDisplay.h @@ -11,16 +11,29 @@ #ifndef O2_GPU_DPL_DISPLAY_H #define O2_GPU_DPL_DISPLAY_H -#include "Framework/DataProcessorSpec.h" #include "ReconstructionDataFormats/GlobalTrackID.h" #include "Framework/Task.h" +#include + +namespace o2::trd +{ +class GeometryFlat; +} +namespace o2::globaltracking +{ +struct DataRequest; +} namespace o2::gpu { +class GPUO2InterfaceDisplay; +struct GPUO2InterfaceConfiguration; +class TPCFastTransform; + class O2GPUDPLDisplaySpec : public o2::framework::Task { public: - O2GPUDPLDisplaySpec(bool useMC, o2::dataformats::GlobalTrackID::mask_t trkMask, o2::dataformats::GlobalTrackID::mask_t clMask) : mUseMC(useMC), mTrkMask(trkMask), mClMask(clMask) {} + O2GPUDPLDisplaySpec(bool useMC, o2::dataformats::GlobalTrackID::mask_t trkMask, o2::dataformats::GlobalTrackID::mask_t clMask, std::shared_ptr dataRequest) : mUseMC(useMC), mTrkMask(trkMask), mClMask(clMask), mDataRequest(dataRequest) {} ~O2GPUDPLDisplaySpec() override = default; void init(o2::framework::InitContext& ic) final; void run(o2::framework::ProcessingContext& pc) final; @@ -30,6 +43,11 @@ class O2GPUDPLDisplaySpec : public o2::framework::Task bool mUseMC = false; o2::dataformats::GlobalTrackID::mask_t mTrkMask; o2::dataformats::GlobalTrackID::mask_t mClMask; + std::unique_ptr mDisplay; + std::unique_ptr mConfig; + std::unique_ptr mFastTransform; + std::unique_ptr mTrdGeo; + std::shared_ptr mDataRequest; }; } // namespace o2::gpu diff --git a/GPU/Workflow/O2GPUDPLDisplay.cxx b/GPU/Workflow/src/O2GPUDPLDisplay.cxx similarity index 76% rename from GPU/Workflow/O2GPUDPLDisplay.cxx rename to GPU/Workflow/src/O2GPUDPLDisplay.cxx index ebd313cf609fa..b6e12b97fa847 100644 --- a/GPU/Workflow/O2GPUDPLDisplay.cxx +++ b/GPU/Workflow/src/O2GPUDPLDisplay.cxx @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#include "O2GPUDPLDisplay.h" +#include "GPUWorkflow/O2GPUDPLDisplay.h" #include "Framework/ConfigParamSpec.h" #include "DataFormatsParameters/GRPObject.h" #include "DataFormatsGlobalTracking/RecoContainer.h" @@ -25,15 +25,11 @@ using namespace o2::framework; using namespace o2::dataformats; +using namespace o2::globaltracking; using namespace o2::gpu; using namespace o2::tpc; using namespace o2::trd; -static std::unique_ptr display; -std::unique_ptr config; -std::unique_ptr fastTransform; -std::unique_ptr trdGeo; - void customize(std::vector& workflowOptions) { std::vector options{ @@ -47,45 +43,41 @@ void customize(std::vector& workflowOptions) std::swap(workflowOptions, options); } -// ------------------------------------------------------------------ - #include "Framework/runDataProcessing.h" -static o2::globaltracking::DataRequest dataRequest; - void O2GPUDPLDisplaySpec::init(InitContext& ic) { const auto grp = o2::parameters::GRPObject::loadFrom(o2::base::NameConf::getGRPFileName()); o2::base::GeometryManager::loadGeometry(); o2::base::Propagator::initFieldFromGRP(o2::base::NameConf::getGRPFileName()); - config.reset(new GPUO2InterfaceConfiguration); - config->configGRP.solenoidBz = 5.00668f * grp->getL3Current() / 30000.; - config->configGRP.continuousMaxTimeBin = grp->isDetContinuousReadOut(o2::detectors::DetID::TPC) ? -1 : 0; // Number of timebins in timeframe if continuous, 0 otherwise - config->ReadConfigurableParam(); + mConfig.reset(new GPUO2InterfaceConfiguration); + mConfig->configGRP.solenoidBz = 5.00668f * grp->getL3Current() / 30000.; + mConfig->configGRP.continuousMaxTimeBin = grp->isDetContinuousReadOut(o2::detectors::DetID::TPC) ? -1 : 0; // Number of timebins in timeframe if continuous, 0 otherwise + mConfig->ReadConfigurableParam(); - fastTransform = std::move(TPCFastTransformHelperO2::instance()->create(0)); - config->configCalib.fastTransform = fastTransform.get(); + mFastTransform = std::move(TPCFastTransformHelperO2::instance()->create(0)); + mConfig->configCalib.fastTransform = mFastTransform.get(); auto gm = o2::trd::Geometry::instance(); gm->createPadPlaneArray(); gm->createClusterMatrixArray(); - trdGeo.reset(new o2::trd::GeometryFlat(*gm)); - config->configCalib.trdGeometry = trdGeo.get(); + mTrdGeo.reset(new o2::trd::GeometryFlat(*gm)); + mConfig->configCalib.trdGeometry = mTrdGeo.get(); - display.reset(new GPUO2InterfaceDisplay(config.get())); + mDisplay.reset(new GPUO2InterfaceDisplay(mConfig.get())); } void O2GPUDPLDisplaySpec::run(ProcessingContext& pc) { o2::globaltracking::RecoContainer recoData; - recoData.collectData(pc, dataRequest); + recoData.collectData(pc, *mDataRequest); static bool first = false; if (first == false) { - if (display->startDisplay()) { + if (mDisplay->startDisplay()) { throw std::runtime_error("Error starting event display"); } } - + GPUTrackingInOutPointers ptrs; recoData.addTPCClusters(pc, false); recoData.addTPCTracks(pc, mUseMC); @@ -100,13 +92,13 @@ void O2GPUDPLDisplaySpec::run(ProcessingContext& pc) const auto& tpcTracksMC = recoData.getTPCTracksMCLabels(); ptrs.outputTracksTPCO2MC = tpcTracksMC.data(); } - - display->show(&ptrs); + + mDisplay->show(&ptrs); } void O2GPUDPLDisplaySpec::endOfStream(EndOfStreamContext& ec) { - display->endDisplay(); + mDisplay->endDisplay(); } WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) @@ -116,8 +108,9 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) bool useMC = cfgc.options().get("enable-mc"); GlobalTrackID::mask_t srcTrk = GlobalTrackID::getSourcesMask(cfgc.options().get("display-tracks")); GlobalTrackID::mask_t srcCl = GlobalTrackID::getSourcesMask(cfgc.options().get("display-clusters")); - dataRequest.requestTracks(srcTrk, useMC); - dataRequest.requestClusters(srcCl, useMC); + std::shared_ptr dataRequest = std::make_shared(); + dataRequest->requestTracks(srcTrk, useMC); + dataRequest->requestClusters(srcCl, useMC); if (cfgc.options().get("read-from-files")) { InputHelper::addInputSpecs(cfgc, specs, srcCl, srcTrk, srcTrk, useMC); @@ -125,9 +118,9 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) specs.emplace_back(DataProcessorSpec{ "o2-gpu-display", - dataRequest.inputs, + dataRequest->inputs, {}, - AlgorithmSpec{adaptFromTask(useMC, srcTrk, srcCl)}}); + AlgorithmSpec{adaptFromTask(useMC, srcTrk, srcCl, dataRequest)}}); return std::move(specs); } From 8376dcc2ea54682dfd96a1bb5515845eafe439ed Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 23 Apr 2021 20:58:53 +0200 Subject: [PATCH 266/770] GPU: Remove unneeded forward declarations for dummy classes and replace by void* --- GPU/GPUTracking/display/GPUDisplay.h | 12 ++---------- GPU/GPUTracking/qa/GPUQA.h | 4 +--- 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/GPU/GPUTracking/display/GPUDisplay.h b/GPU/GPUTracking/display/GPUDisplay.h index f3bb68d6c450c..d0d68a4ed0673 100644 --- a/GPU/GPUTracking/display/GPUDisplay.h +++ b/GPU/GPUTracking/display/GPUDisplay.h @@ -35,15 +35,6 @@ #include "GPUSettings.h" #include "GPUDisplayBackend.h" -namespace GPUCA_NAMESPACE -{ -namespace gpu -{ -class GPUChainTracking; -class GPUQA; -} // namespace gpu -} // namespace GPUCA_NAMESPACE - #ifndef GPUCA_BUILD_EVENT_DISPLAY namespace GPUCA_NAMESPACE @@ -53,7 +44,7 @@ namespace gpu class GPUDisplay { public: - GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQA* qa, const GPUParam* param = nullptr, const GPUCalibObjectsConst* calib = nullptr, const GPUSettingsDisplay* config = nullptr) {} + GPUDisplay(void* backend, void* chain, void* qa, const void* param = nullptr, const void* calib = nullptr, const void* config = nullptr) {} ~GPUDisplay() = default; GPUDisplay(const GPUDisplay&) = delete; @@ -90,6 +81,7 @@ namespace gpu { class GPUTPCTracker; struct GPUParam; +class GPUQA; class GPUDisplay { diff --git a/GPU/GPUTracking/qa/GPUQA.h b/GPU/GPUTracking/qa/GPUQA.h index faeb7a47614c3..b06b18061309f 100644 --- a/GPU/GPUTracking/qa/GPUQA.h +++ b/GPU/GPUTracking/qa/GPUQA.h @@ -35,12 +35,10 @@ namespace GPUCA_NAMESPACE { namespace gpu { -class GPUChainTracking; - class GPUQA { public: - GPUQA(GPUChainTracking* chain) {} + GPUQA(void* chain) {} ~GPUQA() = default; int InitQA(int tasks = 0) { return 1; } From 9e73fd88c39287be9d32e566bbdd774813603eb7 Mon Sep 17 00:00:00 2001 From: dsekihat Date: Sun, 25 Apr 2021 17:00:11 +0900 Subject: [PATCH 267/770] Analysis/Task/PWGDQ: add a sample task for V0 selection (#5988) * Analysis/Task/PWGDQ: add a sample task for V0 selection * replace stdio.h with cstdio * remove unnecessary include * remove unnecessary include2 * add braces for if * fix for clang-format --- Analysis/Tasks/PWGDQ/CMakeLists.txt | 5 + Analysis/Tasks/PWGDQ/v0selector.cxx | 231 ++++++++++++++++++++++++++++ 2 files changed, 236 insertions(+) create mode 100644 Analysis/Tasks/PWGDQ/v0selector.cxx diff --git a/Analysis/Tasks/PWGDQ/CMakeLists.txt b/Analysis/Tasks/PWGDQ/CMakeLists.txt index 60a347e6048cc..47e6e090cbbf1 100644 --- a/Analysis/Tasks/PWGDQ/CMakeLists.txt +++ b/Analysis/Tasks/PWGDQ/CMakeLists.txt @@ -37,3 +37,8 @@ o2_add_dpl_workflow(table-maker-muon-pp SOURCES tableMakerMuon_pp.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::AnalysisDataModel O2::DetectorsBase O2::AnalysisCore O2::PWGDQCore COMPONENT_NAME Analysis) + +o2_add_dpl_workflow(v0-selector + SOURCES v0selector.cxx + PUBLIC_LINK_LIBRARIES O2::Framework O2::AnalysisDataModel O2::DetectorsBase O2::AnalysisCore O2::PWGDQCore O2::DetectorsVertexing + COMPONENT_NAME Analysis) diff --git a/Analysis/Tasks/PWGDQ/v0selector.cxx b/Analysis/Tasks/PWGDQ/v0selector.cxx new file mode 100644 index 0000000000000..663e14234e748 --- /dev/null +++ b/Analysis/Tasks/PWGDQ/v0selector.cxx @@ -0,0 +1,231 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. +// +// Example analysis task to select clean V0 sample +// ======================== +// +// This code loops over a V0Data table and produces some +// standard analysis output. It requires either +// the lambdakzerofinder or the lambdakzeroproducer tasks +// to have been executed in the workflow (before). +// +// Comments, questions, complaints, suggestions? +// Please write to: +// daiki.sekihata@cern.ch +// +#include "Framework/runDataProcessing.h" +#include "Framework/AnalysisTask.h" +#include "Framework/AnalysisDataModel.h" +#include "Framework/ASoAHelpers.h" +#include "ReconstructionDataFormats/Track.h" +#include "AnalysisCore/trackUtilities.h" +#include "AnalysisDataModel/StrangenessTables.h" +#include "AnalysisCore/TrackSelection.h" +#include "AnalysisDataModel/TrackSelectionTables.h" +#include "AnalysisDataModel/EventSelection.h" +#include "AnalysisDataModel/Centrality.h" + +#include +#include +#include "Framework/ASoAHelpers.h" +#include "AnalysisDataModel/PID/PIDResponse.h" + +using namespace o2; +using namespace o2::framework; +using namespace o2::framework::expressions; +using std::array; + +//using FullTracksExt = soa::Join; +using FullTracksExt = soa::Join; + +struct v0selector { + + void init(o2::framework::InitContext&) + { + } + + //Basic checks + HistogramRegistry registry{ + "registry", + { + {"hMassGamma", "hMassGamma", {HistType::kTH1F, {{100, 0.0f, 0.1f}}}}, + {"hMassK0S", "hMassK0S", {HistType::kTH1F, {{100, 0.45, 0.55}}}}, + {"hMassLambda", "hMasLambda", {HistType::kTH1F, {{100, 1.05, 1.15f}}}}, + {"hMassAntiLambda", "hAntiMasLambda", {HistType::kTH1F, {{100, 1.05, 1.15f}}}}, + + {"hMassGamma_AP", "hMassGamma_AP", {HistType::kTH1F, {{100, 0.0f, 0.1f}}}}, + {"hMassK0S_AP", "hMassK0S_AP", {HistType::kTH1F, {{100, 0.45, 0.55}}}}, + {"hMassLambda_AP", "hMasLambda_AP", {HistType::kTH1F, {{100, 1.05, 1.15}}}}, + {"hMassAntiLambda_AP", "hAntiMasLambda_AP", {HistType::kTH1F, {{100, 1.05, 1.15}}}}, + + {"h2MassGammaR", "h2MassGammaR", {HistType::kTH2F, {{1000, 0.0, 100}, {100, 0.0f, 0.1f}}}}, + + {"hV0Pt", "pT", {HistType::kTH1F, {{100, 0.0f, 10}}}}, + {"hV0EtaPhi", "#eta vs. #varphi", {HistType::kTH2F, {{126, -6.3, 6.3}, {20, -1.0f, 1.0f}}}}, + + {"hV0Radius", "hV0Radius", {HistType::kTH1F, {{1000, 0.0f, 100.0f}}}}, + {"hV0CosPA", "hV0CosPA", {HistType::kTH1F, {{1000, 0.95f, 1.0f}}}}, + {"hDCAPosToPV", "hDCAPosToPV", {HistType::kTH1F, {{1000, 0.0f, 10.0f}}}}, + {"hDCANegToPV", "hDCANegToPV", {HistType::kTH1F, {{1000, 0.0f, 10.0f}}}}, + {"hDCAV0Dau", "hDCAV0Dau", {HistType::kTH1F, {{1000, 0.0f, 10.0f}}}}, + {"hV0APplot", "hV0APplot", {HistType::kTH2F, {{200, -1.0f, +1.0f}, {300, 0.0f, 0.3f}}}}, + {"hV0APplot_Gamma", "hV0APplot Gamma", {HistType::kTH2F, {{200, -1.0f, +1.0f}, {300, 0.0f, 0.3f}}}}, + + {"h2TPCdEdx_Pin_Pos", "TPC dEdx vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {200, 0.0, 200.}}}}, + {"h2TPCdEdx_Pin_Neg", "TPC dEdx vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {200, 0.0, 200.}}}}, + {"h2TPCdEdx_Pin_El_plus", "TPC dEdx vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {200, 0.0, 200.}}}}, + {"h2TPCdEdx_Pin_El_minus", "TPC dEdx vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {200, 0.0, 200.}}}}, + {"h2TPCdEdx_Pin_Pi_plus", "TPC dEdx vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {200, 0.0, 200.}}}}, + {"h2TPCdEdx_Pin_Pi_minus", "TPC dEdx vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {200, 0.0, 200.}}}}, + {"h2TPCdEdx_Pin_Ka_plus", "TPC dEdx vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {200, 0.0, 200.}}}}, + {"h2TPCdEdx_Pin_Ka_minus", "TPC dEdx vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {200, 0.0, 200.}}}}, + {"h2TPCdEdx_Pin_Pr_plus", "TPC dEdx vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {200, 0.0, 200.}}}}, + {"h2TPCdEdx_Pin_Pr_minus", "TPC dEdx vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {200, 0.0, 200.}}}}, + + {"h2TOFbeta_Pin_Pos", "TOF #beta vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {120, 0.0, 1.2}}}}, + {"h2TOFbeta_Pin_Neg", "TOF #beta vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {120, 0.0, 1.2}}}}, + {"h2TOFbeta_Pin_El_plus", "TPC dEdx vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {120, 0.0, 1.2}}}}, + {"h2TOFbeta_Pin_El_minus", "TPC dEdx vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {120, 0.0, 1.2}}}}, + {"h2TOFbeta_Pin_Pi_plus", "TPC dEdx vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {120, 0.0, 1.2}}}}, + {"h2TOFbeta_Pin_Pi_minus", "TPC dEdx vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {120, 0.0, 1.2}}}}, + {"h2TOFbeta_Pin_Ka_plus", "TPC dEdx vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {120, 0.0, 1.2}}}}, + {"h2TOFbeta_Pin_Ka_minus", "TPC dEdx vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {120, 0.0, 1.2}}}}, + {"h2TOFbeta_Pin_Pr_plus", "TPC dEdx vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {120, 0.0, 1.2}}}}, + {"h2TOFbeta_Pin_Pr_minus", "TPC dEdx vs. p_{in}", {HistType::kTH2F, {{1000, 0.0, 10}, {120, 0.0, 1.2}}}}, + + {"h2MggPt", "M_{#gamma#gamma} vs. p_{T}", {HistType::kTH2F, {{400, 0.0, 0.8}, {100, 0.0, 10.}}}}, + }, + }; + + void process(soa::Join::iterator const& collision, aod::V0Datas const& fullV0s, FullTracksExt const& tracks) + { + + //if (!collision.alias()[kINT7]) { + // return; + //} + //if (!collision.sel7()) { + // return; + //} + + for (auto& v0 : fullV0s) { + if (v0.negTrack_as().tpcChi2NCl() > 4.0 || v0.posTrack_as().tpcChi2NCl() > 4.0) { + continue; + } + if (v0.negTrack_as().tpcNClsCrossedRows() < 70 || v0.posTrack_as().tpcNClsCrossedRows() < 70) { + continue; + } + if (!(v0.negTrack_as().trackType() & o2::aod::track::TPCrefit) || !(v0.posTrack_as().trackType() & o2::aod::track::TPCrefit)) { + continue; + } + + registry.fill(HIST("hV0Pt"), v0.pt()); + registry.fill(HIST("hV0EtaPhi"), v0.phi(), v0.eta()); + + registry.fill(HIST("hV0Radius"), v0.v0radius()); + registry.fill(HIST("hV0CosPA"), v0.v0cosPA(collision.posX(), collision.posY(), collision.posZ())); + registry.fill(HIST("hDCAPosToPV"), v0.dcapostopv()); + registry.fill(HIST("hDCANegToPV"), v0.dcanegtopv()); + registry.fill(HIST("hDCAV0Dau"), v0.dcaV0daughters()); + registry.fill(HIST("hV0APplot"), v0.alpha(), v0.qtarm()); + + registry.fill(HIST("hMassK0S"), v0.mK0Short()); + registry.fill(HIST("hMassLambda"), v0.mLambda()); + registry.fill(HIST("hMassAntiLambda"), v0.mAntiLambda()); + + registry.fill(HIST("h2TPCdEdx_Pin_Neg"), v0.negTrack_as().tpcInnerParam(), v0.negTrack_as().tpcSignal()); + registry.fill(HIST("h2TPCdEdx_Pin_Pos"), v0.posTrack_as().tpcInnerParam(), v0.posTrack_as().tpcSignal()); + + registry.fill(HIST("h2TOFbeta_Pin_Neg"), v0.negTrack_as().tpcInnerParam(), v0.negTrack_as().beta()); + registry.fill(HIST("h2TOFbeta_Pin_Pos"), v0.posTrack_as().tpcInnerParam(), v0.posTrack_as().beta()); + + if ((70.0 < v0.negTrack_as().tpcSignal() && v0.negTrack_as().tpcSignal() < 90) && (70.0 < v0.posTrack_as().tpcSignal() && v0.posTrack_as().tpcSignal() < 90)) { + registry.fill(HIST("hMassGamma"), v0.mGamma()); + registry.fill(HIST("hV0APplot_Gamma"), v0.alpha(), v0.qtarm()); + registry.fill(HIST("h2MassGammaR"), v0.v0radius(), v0.mGamma()); + } + + if (TMath::Abs(v0.alpha()) < 0.4 && v0.qtarm() < 0.03 && v0.mGamma() < 0.01) { //photon conversion + registry.fill(HIST("hMassGamma_AP"), v0.mGamma()); + registry.fill(HIST("h2TPCdEdx_Pin_El_minus"), v0.negTrack_as().tpcInnerParam(), v0.negTrack_as().tpcSignal()); + registry.fill(HIST("h2TPCdEdx_Pin_El_plus"), v0.posTrack_as().tpcInnerParam(), v0.posTrack_as().tpcSignal()); + registry.fill(HIST("h2TOFbeta_Pin_El_minus"), v0.negTrack_as().tpcInnerParam(), v0.negTrack_as().beta()); + registry.fill(HIST("h2TOFbeta_Pin_El_plus"), v0.posTrack_as().tpcInnerParam(), v0.posTrack_as().beta()); + + } else if (TMath::Abs(v0.alpha()) < 0.7 && (0.11 < v0.qtarm() && v0.qtarm() < 0.22) && (0.49 < v0.mK0Short() && v0.mK0Short() < 0.51)) { //K0S-> pi pi + registry.fill(HIST("hMassK0S_AP"), v0.mK0Short()); + registry.fill(HIST("h2TPCdEdx_Pin_Pi_minus"), v0.negTrack_as().tpcInnerParam(), v0.negTrack_as().tpcSignal()); + registry.fill(HIST("h2TPCdEdx_Pin_Pi_plus"), v0.posTrack_as().tpcInnerParam(), v0.posTrack_as().tpcSignal()); + registry.fill(HIST("h2TOFbeta_Pin_Pi_minus"), v0.negTrack_as().tpcInnerParam(), v0.negTrack_as().beta()); + registry.fill(HIST("h2TOFbeta_Pin_Pi_plus"), v0.posTrack_as().tpcInnerParam(), v0.posTrack_as().beta()); + + } else if ((+0.45 < v0.alpha() && v0.alpha() < +0.7) && (0.03 < v0.qtarm() && v0.qtarm() < 0.11) && (1.112 < v0.mLambda() && v0.mLambda() < 1.120)) { //L->p + pi- + registry.fill(HIST("hMassLambda_AP"), v0.mLambda()); + registry.fill(HIST("h2TPCdEdx_Pin_Pi_minus"), v0.negTrack_as().tpcInnerParam(), v0.negTrack_as().tpcSignal()); + registry.fill(HIST("h2TPCdEdx_Pin_Pr_plus"), v0.posTrack_as().tpcInnerParam(), v0.posTrack_as().tpcSignal()); + registry.fill(HIST("h2TOFbeta_Pin_Pi_minus"), v0.negTrack_as().tpcInnerParam(), v0.negTrack_as().beta()); + registry.fill(HIST("h2TOFbeta_Pin_Pr_plus"), v0.posTrack_as().tpcInnerParam(), v0.posTrack_as().beta()); + + } else if ((-0.7 < v0.alpha() && v0.alpha() < -0.45) && (0.03 < v0.qtarm() && v0.qtarm() < 0.11) && (1.112 < v0.mAntiLambda() && v0.mAntiLambda() < 1.120)) { //Lbar -> pbar + pi+ + registry.fill(HIST("hMassAntiLambda_AP"), v0.mAntiLambda()); + registry.fill(HIST("h2TPCdEdx_Pin_Pr_minus"), v0.negTrack_as().tpcInnerParam(), v0.negTrack_as().tpcSignal()); + registry.fill(HIST("h2TPCdEdx_Pin_Pi_plus"), v0.posTrack_as().tpcInnerParam(), v0.posTrack_as().tpcSignal()); + registry.fill(HIST("h2TOFbeta_Pin_Pr_minus"), v0.negTrack_as().tpcInnerParam(), v0.negTrack_as().beta()); + registry.fill(HIST("h2TOFbeta_Pin_Pi_plus"), v0.posTrack_as().tpcInnerParam(), v0.posTrack_as().beta()); + } + } + + //loop for pi0/eta->gamma gamma + for (auto& [t1, t2] : combinations(fullV0s, fullV0s)) { + + if (t1.negTrack_as().tpcSignal() < 70.0 || 90.0 < t1.negTrack_as().tpcSignal()) { + continue; + } + if (t1.posTrack_as().tpcSignal() < 70.0 || 90.0 < t1.posTrack_as().tpcSignal()) { + continue; + } + if (t2.negTrack_as().tpcSignal() < 70.0 || 90.0 < t2.negTrack_as().tpcSignal()) { + continue; + } + if (t2.posTrack_as().tpcSignal() < 70.0 || 90.0 < t2.posTrack_as().tpcSignal()) { + continue; + } + if (t1.negTrack_as().tpcChi2NCl() > 4.0 || t1.posTrack_as().tpcChi2NCl() > 4.0) { + continue; + } + if (t2.negTrack_as().tpcChi2NCl() > 4.0 || t2.posTrack_as().tpcChi2NCl() > 4.0) { + continue; + } + + //if(TMath::Abs(t1.alpha()) > 0.35 || TMath::Abs(t2.alpha()) > 0.35) continue; + if (t1.qtarm() > 0.03 || t2.qtarm() > 0.03) { + continue; + } + if (t1.mGamma() > 0.01 || t2.mGamma() > 0.01) { + continue; + } + if (t1.v0radius() > 50 || t2.v0radius() > 50) { + continue; + } + + //ROOT::Math::PtEtaPhiMVector v1(t1.pt(), t1.eta(), t1.phi(), t1.mGamma()); + //ROOT::Math::PtEtaPhiMVector v2(t2.pt(), t2.eta(), t2.phi(), t2.mGamma()); + ROOT::Math::PtEtaPhiMVector v1(t1.pt(), t1.eta(), t1.phi(), 0.0); + ROOT::Math::PtEtaPhiMVector v2(t2.pt(), t2.eta(), t2.phi(), 0.0); + ROOT::Math::PtEtaPhiMVector v12 = v1 + v2; + registry.fill(HIST("h2MggPt"), v12.M(), v12.Pt()); + } + } +}; + +WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) +{ + return WorkflowSpec{ + adaptAnalysisTask(cfgc)}; +} From 3bc19f84f1cbc856d14e46a204a771ea4311a219 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B2=20Jacazio?= Date: Sun, 25 Apr 2021 10:01:13 +0200 Subject: [PATCH 268/770] PID: extend QA, add parametrizations for the TOF (#5987) - Add TOF calibration for ALICE3 - Add handler for Alice 3 param - Update RICH QA task - Add HMPID QA task - Add task for FAST PID response - Add beta in TOF QA task - Remove fast and qa tasks - Extend TOF task with Fast PID and more QA - Add fast TPC response - Add fast implementation in PID response of TPC and TOF - Update TOF task for QA - Update TPC param handler - Add number of photons detected to the HMPID table - Delegating track selection in QA to dedicated task - Add ALICE3 track extension task - Add ALICE3 task for multiplicity - Add separate task for the TOF beta - Update RICH table to build indices, use indeces in RICH QA task Update PID param. handlers - Writing TOF reso parameters and saving them to the CCDB - Add ALICE3 PID TOF response PID tasks: - Add QA tasks to split task - Add expected resolution and for the event time resolution plot to the QA of ALICE3 TOF PID - Add cut on minimum TOF multiplicity for QA --- Analysis/ALICE3/CMakeLists.txt | 15 + Analysis/ALICE3/include/ALICE3Analysis/RICH.h | 29 +- Analysis/ALICE3/src/alice3-pidTOF.cxx | 284 ++++++++++++++++++ .../ALICE3/src/alice3-qa-multiplicity.cxx | 53 ++++ Analysis/ALICE3/src/alice3-trackextension.cxx | 43 +++ Analysis/ALICE3/src/alice3-trackselection.cxx | 40 ++- Analysis/ALICE3/src/pidRICHqa.cxx | 114 ++++--- Analysis/DataModel/CMakeLists.txt | 6 + .../AnalysisDataModel/PID/BetheBloch.h | 12 + .../AnalysisDataModel/PID/DetectorResponse.h | 3 +- .../include/AnalysisDataModel/PID/PIDTOF.h | 4 +- .../include/AnalysisDataModel/PID/ParamBase.h | 59 +++- .../include/AnalysisDataModel/PID/TOFReso.h | 21 +- .../AnalysisDataModel/PID/TOFResoALICE3.h | 85 ++++++ .../include/AnalysisDataModel/PID/TPCReso.h | 12 + .../DataModel/src/AnalysisDataModelLinkDef.h | 1 + Analysis/DataModel/src/ParamBase.cxx | 40 ++- Analysis/DataModel/src/handleParamTOFReso.cxx | 58 ++-- .../src/handleParamTOFResoALICE3.cxx | 131 ++++++++ .../src/handleParamTPCBetheBloch.cxx | 57 ++-- Analysis/Tasks/PID/CMakeLists.txt | 16 + Analysis/Tasks/PID/pidTOF.cxx | 21 +- Analysis/Tasks/PID/pidTOF_tiny.cxx | 2 +- Analysis/Tasks/PID/pidTPC.cxx | 2 +- Analysis/Tasks/PID/pidTPC_tiny.cxx | 2 +- Analysis/Tasks/PID/qaHMPID.cxx | 99 ++++++ .../Tasks/PID/{pidTOFqa.cxx => qaTOFMC.cxx} | 2 +- .../include/Framework/AnalysisDataModel.h | 2 + 28 files changed, 1082 insertions(+), 131 deletions(-) create mode 100644 Analysis/ALICE3/src/alice3-pidTOF.cxx create mode 100644 Analysis/ALICE3/src/alice3-qa-multiplicity.cxx create mode 100644 Analysis/ALICE3/src/alice3-trackextension.cxx create mode 100644 Analysis/DataModel/include/AnalysisDataModel/PID/TOFResoALICE3.h create mode 100644 Analysis/DataModel/src/handleParamTOFResoALICE3.cxx create mode 100644 Analysis/Tasks/PID/qaHMPID.cxx rename Analysis/Tasks/PID/{pidTOFqa.cxx => qaTOFMC.cxx} (99%) diff --git a/Analysis/ALICE3/CMakeLists.txt b/Analysis/ALICE3/CMakeLists.txt index 6d6864b9adb56..f7f83e20ea85e 100644 --- a/Analysis/ALICE3/CMakeLists.txt +++ b/Analysis/ALICE3/CMakeLists.txt @@ -15,7 +15,22 @@ o2_add_dpl_workflow(alice3-trackselection PUBLIC_LINK_LIBRARIES O2::Framework O2::AnalysisDataModel O2::AnalysisCore COMPONENT_NAME Analysis) +o2_add_dpl_workflow(alice3-trackextension + SOURCES src/alice3-trackextension.cxx + PUBLIC_LINK_LIBRARIES O2::Framework O2::AnalysisDataModel O2::AnalysisCore + COMPONENT_NAME Analysis) + +o2_add_dpl_workflow(alice3-qa-multiplicity + SOURCES src/alice3-qa-multiplicity.cxx + PUBLIC_LINK_LIBRARIES O2::Framework O2::AnalysisDataModel O2::AnalysisCore + COMPONENT_NAME Analysis) + o2_add_dpl_workflow(alice3-pid-rich-qa SOURCES src/pidRICHqa.cxx PUBLIC_LINK_LIBRARIES O2::AnalysisDataModel O2::AnalysisCore O2::ALICE3Analysis COMPONENT_NAME Analysis) + +o2_add_dpl_workflow(alice3-pid-tof + SOURCES src/alice3-pidTOF.cxx + PUBLIC_LINK_LIBRARIES O2::AnalysisDataModel O2::AnalysisCore O2::ALICE3Analysis + COMPONENT_NAME Analysis) diff --git a/Analysis/ALICE3/include/ALICE3Analysis/RICH.h b/Analysis/ALICE3/include/ALICE3Analysis/RICH.h index edb789790c8ac..ce2b08296b145 100644 --- a/Analysis/ALICE3/include/ALICE3Analysis/RICH.h +++ b/Analysis/ALICE3/include/ALICE3Analysis/RICH.h @@ -25,22 +25,23 @@ namespace o2::aod { namespace alice3rich { -DECLARE_SOA_INDEX_COLUMN(Track, track); -DECLARE_SOA_COLUMN(RICHSignal, richSignal, float); -DECLARE_SOA_COLUMN(RICHSignalError, richSignalError, float); -DECLARE_SOA_COLUMN(RICHDeltaEl, richDeltaEl, float); -DECLARE_SOA_COLUMN(RICHDeltaMu, richDeltaMu, float); -DECLARE_SOA_COLUMN(RICHDeltaPi, richDeltaPi, float); -DECLARE_SOA_COLUMN(RICHDeltaKa, richDeltaKa, float); -DECLARE_SOA_COLUMN(RICHDeltaPr, richDeltaPr, float); -DECLARE_SOA_COLUMN(RICHNsigmaEl, richNsigmaEl, float); -DECLARE_SOA_COLUMN(RICHNsigmaMu, richNsigmaMu, float); -DECLARE_SOA_COLUMN(RICHNsigmaPi, richNsigmaPi, float); -DECLARE_SOA_COLUMN(RICHNsigmaKa, richNsigmaKa, float); -DECLARE_SOA_COLUMN(RICHNsigmaPr, richNsigmaPr, float); +DECLARE_SOA_INDEX_COLUMN(Track, track); //! +DECLARE_SOA_COLUMN(RICHSignal, richSignal, float); //! +DECLARE_SOA_COLUMN(RICHSignalError, richSignalError, float); //! +DECLARE_SOA_COLUMN(RICHDeltaEl, richDeltaEl, float); //! +DECLARE_SOA_COLUMN(RICHDeltaMu, richDeltaMu, float); //! +DECLARE_SOA_COLUMN(RICHDeltaPi, richDeltaPi, float); //! +DECLARE_SOA_COLUMN(RICHDeltaKa, richDeltaKa, float); //! +DECLARE_SOA_COLUMN(RICHDeltaPr, richDeltaPr, float); //! +DECLARE_SOA_COLUMN(RICHNsigmaEl, richNsigmaEl, float); //! +DECLARE_SOA_COLUMN(RICHNsigmaMu, richNsigmaMu, float); //! +DECLARE_SOA_COLUMN(RICHNsigmaPi, richNsigmaPi, float); //! +DECLARE_SOA_COLUMN(RICHNsigmaKa, richNsigmaKa, float); //! +DECLARE_SOA_COLUMN(RICHNsigmaPr, richNsigmaPr, float); //! } // namespace alice3rich -DECLARE_SOA_TABLE(RICHs, "AOD", "RICH", +DECLARE_SOA_TABLE(RICHs, "AOD", "RICH", //! + o2::soa::Index<>, alice3rich::TrackId, alice3rich::RICHSignal, alice3rich::RICHSignalError, diff --git a/Analysis/ALICE3/src/alice3-pidTOF.cxx b/Analysis/ALICE3/src/alice3-pidTOF.cxx new file mode 100644 index 0000000000000..d6feee11dd170 --- /dev/null +++ b/Analysis/ALICE3/src/alice3-pidTOF.cxx @@ -0,0 +1,284 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +// O2 includes +#include "Framework/AnalysisTask.h" +#include "Framework/HistogramRegistry.h" +#include "ReconstructionDataFormats/Track.h" +#include +#include "AnalysisDataModel/PID/PIDResponse.h" +#include "AnalysisDataModel/PID/PIDTOF.h" +#include "AnalysisDataModel/PID/TOFResoALICE3.h" +#include "AnalysisDataModel/TrackSelectionTables.h" + +using namespace o2; +using namespace o2::framework; +using namespace o2::pid; +using namespace o2::framework::expressions; +using namespace o2::track; + +void customize(std::vector& workflowOptions) +{ + std::vector options{{"add-qa", VariantType::Int, 0, {"Produce TOF PID QA histograms"}}}; + std::swap(workflowOptions, options); +} + +#include "Framework/runDataProcessing.h" + +struct ALICE3pidTOFTask { + using Trks = soa::Join; + using Coll = aod::Collisions; + // Tables to produce + Produces tablePIDEl; + Produces tablePIDMu; + Produces tablePIDPi; + Produces tablePIDKa; + Produces tablePIDPr; + Produces tablePIDDe; + Produces tablePIDTr; + Produces tablePIDHe; + Produces tablePIDAl; + Parameters resoParameters{1}; + Service ccdb; + Configurable paramfile{"param-file", "", "Path to the parametrization object, if emtpy the parametrization is not taken from file"}; + Configurable sigmaname{"param-sigma", "TOFResoALICE3", "Name of the parametrization for the expected sigma, used in both file and CCDB mode"}; + Configurable url{"ccdb-url", "http://ccdb-test.cern.ch:8080", "url of the ccdb repository"}; + Configurable timestamp{"ccdb-timestamp", -1, "timestamp of the object"}; + + void init(o2::framework::InitContext&) + { + ccdb->setURL(url.value); + ccdb->setTimestamp(timestamp.value); + ccdb->setCaching(true); + ccdb->setLocalObjectValidityChecking(); + // Not later than now objects + ccdb->setCreatedNotAfter(std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count()); + // + const std::vector p = {24.5}; + resoParameters.SetParameters(p); + const std::string fname = paramfile.value; + if (!fname.empty()) { // Loading the parametrization from file + LOG(INFO) << "Loading parametrization from file" << fname << ", using param: " << sigmaname; + resoParameters.LoadParamFromFile(fname.data(), sigmaname.value.data()); + } else { // Loading it from CCDB + const std::string path = "Analysis/ALICE3/PID/TOF/Parameters"; + resoParameters.SetParameters(ccdb->getForTimeStamp(path + "/" + sigmaname.value, timestamp.value)); + } + } + + template + float sigma(Trks::iterator track) + { + return o2::pid::tof::TOFResoALICE3ParamTrack(track.collision(), track, resoParameters); + } + template + float nsigma(Trks::iterator track) + { + // return (track.tofSignal() - tof::ExpTimes::GetExpectedSignal(track.collision(), track)) / sigma(track); + return (track.tofSignal() - track.collision().collisionTime() * 1000.f - tof::ExpTimes::GetExpectedSignal(track.collision(), track)) / sigma(track); + } + void process(Coll const& collisions, Trks const& tracks) + { + tablePIDEl.reserve(tracks.size()); + tablePIDMu.reserve(tracks.size()); + tablePIDPi.reserve(tracks.size()); + tablePIDKa.reserve(tracks.size()); + tablePIDPr.reserve(tracks.size()); + tablePIDDe.reserve(tracks.size()); + tablePIDTr.reserve(tracks.size()); + tablePIDHe.reserve(tracks.size()); + tablePIDAl.reserve(tracks.size()); + for (auto const& trk : tracks) { + tablePIDEl(sigma(trk), nsigma(trk)); + tablePIDMu(sigma(trk), nsigma(trk)); + tablePIDPi(sigma(trk), nsigma(trk)); + tablePIDKa(sigma(trk), nsigma(trk)); + tablePIDPr(sigma(trk), nsigma(trk)); + tablePIDDe(sigma(trk), nsigma(trk)); + tablePIDTr(sigma(trk), nsigma(trk)); + tablePIDHe(sigma(trk), nsigma(trk)); + tablePIDAl(sigma(trk), nsigma(trk)); + } + } +}; + +struct ALICE3pidTOFTaskQA { + + static constexpr int Np = 9; + static constexpr const char* pT[Np] = {"e", "#mu", "#pi", "K", "p", "d", "t", "^{3}He", "#alpha"}; + static constexpr std::string_view hexpected[Np] = {"expected/El", "expected/Mu", "expected/Pi", + "expected/Ka", "expected/Pr", "expected/De", + "expected/Tr", "expected/He", "expected/Al"}; + static constexpr std::string_view hexpected_diff[Np] = {"expected_diff/El", "expected_diff/Mu", "expected_diff/Pi", + "expected_diff/Ka", "expected_diff/Pr", "expected_diff/De", + "expected_diff/Tr", "expected_diff/He", "expected_diff/Al"}; + static constexpr std::string_view hexpsigma[Np] = {"expsigma/El", "expsigma/Mu", "expsigma/Pi", + "expsigma/Ka", "expsigma/Pr", "expsigma/De", + "expsigma/Tr", "expsigma/He", "expsigma/Al"}; + static constexpr std::string_view hnsigma[Np] = {"nsigma/El", "nsigma/Mu", "nsigma/Pi", + "nsigma/Ka", "nsigma/Pr", "nsigma/De", + "nsigma/Tr", "nsigma/He", "nsigma/Al"}; + HistogramRegistry histos{"Histos", {}, OutputObjHandlingPolicy::QAObject}; + + Configurable logAxis{"logAxis", 1, "Flag to use a log momentum axis"}; + Configurable nBinsP{"nBinsP", 400, "Number of bins for the momentum"}; + Configurable MinP{"MinP", 0.1f, "Minimum momentum in range"}; + Configurable MaxP{"MaxP", 5.f, "Maximum momentum in range"}; + Configurable nBinsDelta{"nBinsDelta", 200, "Number of bins for the Delta"}; + Configurable MinDelta{"MinDelta", -1000.f, "Minimum Delta in range"}; + Configurable MaxDelta{"MaxDelta", 1000.f, "Maximum Delta in range"}; + Configurable nBinsExpSigma{"nBinsExpSigma", 200, "Number of bins for the ExpSigma"}; + Configurable MinExpSigma{"MinExpSigma", 0.f, "Minimum ExpSigma in range"}; + Configurable MaxExpSigma{"MaxExpSigma", 200.f, "Maximum ExpSigma in range"}; + Configurable nBinsNSigma{"nBinsNSigma", 200, "Number of bins for the NSigma"}; + Configurable MinNSigma{"MinNSigma", -10.f, "Minimum NSigma in range"}; + Configurable MaxNSigma{"MaxNSigma", 10.f, "Maximum NSigma in range"}; + Configurable MinMult{"MinMult", 1, "Minimum track multiplicity with TOF"}; + + template + void makelogaxis(T h) + { + if (logAxis == 0) { + return; + } + const int nbins = h->GetNbinsX(); + double binp[nbins + 1]; + double max = h->GetXaxis()->GetBinUpEdge(nbins); + double min = h->GetXaxis()->GetBinLowEdge(1); + if (min <= 0) { + min = 0.00001; + } + double lmin = TMath::Log10(min); + double ldelta = (TMath::Log10(max) - lmin) / ((double)nbins); + for (int i = 0; i < nbins; i++) { + binp[i] = TMath::Exp(TMath::Log(10) * (lmin + i * ldelta)); + } + binp[nbins] = max + 1; + h->GetXaxis()->Set(nbins, binp); + } + + template + void addParticleHistos() + { + // Exp signal + histos.add(hexpected[i].data(), Form(";#it{p} (GeV/#it{c});t_{exp}(%s)", pT[i]), HistType::kTH2F, {{nBinsP, MinP, MaxP}, {1000, 0, 2e6}}); + makelogaxis(histos.get(HIST(hexpected[i]))); + + // T-Texp + histos.add(hexpected_diff[i].data(), Form(";#it{p} (GeV/#it{c});(t-t_{evt}-t_{exp}(%s))", pT[i]), HistType::kTH2F, {{nBinsP, MinP, MaxP}, {nBinsDelta, MinDelta, MaxDelta}}); + makelogaxis(histos.get(HIST(hexpected_diff[i]))); + + // Exp Sigma + histos.add(hexpsigma[i].data(), Form(";#it{p} (GeV/#it{c});Exp_{#sigma}^{TOF}(%s)", pT[i]), HistType::kTH2F, {{nBinsP, MinP, MaxP}, {nBinsExpSigma, MinExpSigma, MaxExpSigma}}); + makelogaxis(histos.get(HIST(hexpsigma[i]))); + + // NSigma + histos.add(hnsigma[i].data(), Form(";#it{p} (GeV/#it{c});N_{#sigma}^{TOF}(%s)", pT[i]), HistType::kTH2F, {{nBinsP, MinP, MaxP}, {nBinsNSigma, MinNSigma, MaxNSigma}}); + makelogaxis(histos.get(HIST(hnsigma[i]))); + } + + void init(o2::framework::InitContext&) + { + // Event properties + histos.add("event/vertexz", ";Vtx_{z} (cm);Entries", HistType::kTH1F, {{100, -20, 20}}); + histos.add("event/tofmultiplicity", ";TOF multiplicity;Events", HistType::kTH1F, {{100, 0, 100}}); + histos.add("event/colltime", ";Collision time (ps);Entries", HistType::kTH1F, {{100, -2000, 2000}}); + histos.add("event/colltimereso", ";TOF multiplicity;Collision time resolution (ps);Entries", HistType::kTH2F, {{100, 0, 100}, {100, 0, 2000}}); + histos.add("event/tofsignal", ";#it{p} (GeV/#it{c});TOF Signal", HistType::kTH2F, {{nBinsP, MinP, MaxP}, {10000, 0, 2e6}}); + makelogaxis(histos.get(HIST("event/tofsignal"))); + histos.add("event/eta", ";#it{#eta};Entries", HistType::kTH1F, {{100, -2, 2}}); + histos.add("event/length", ";Track length (cm);Entries", HistType::kTH1F, {{100, 0, 500}}); + histos.add("event/pt", ";#it{p}_{T} (GeV/#it{c});Entries", HistType::kTH1F, {{nBinsP, MinP, MaxP}}); + histos.add("event/p", ";#it{p} (GeV/#it{c});Entries", HistType::kTH1F, {{nBinsP, MinP, MaxP}}); + histos.add("event/ptreso", ";#it{p} (GeV/#it{c});Entries", HistType::kTH2F, {{nBinsP, MinP, MaxP}, {100, 0, 0.1}}); + + addParticleHistos<0>(); + addParticleHistos<1>(); + addParticleHistos<2>(); + addParticleHistos<3>(); + addParticleHistos<4>(); + addParticleHistos<5>(); + addParticleHistos<6>(); + addParticleHistos<7>(); + addParticleHistos<8>(); + } + + template + void fillParticleHistos(const T& t, const float& tof, const float& exp_diff, const float& expsigma, const float& nsigma) + { + histos.fill(HIST(hexpected[i]), t.p(), tof - exp_diff); + histos.fill(HIST(hexpected_diff[i]), t.p(), exp_diff); + histos.fill(HIST(hexpsigma[i]), t.p(), expsigma); + histos.fill(HIST(hnsigma[i]), t.p(), nsigma); + } + + void process(aod::Collision const& collision, + soa::Join const& tracks) + { + // Computing Multiplicity first + int mult = 0; + for (auto t : tracks) { + // + if (t.tofSignal() < 0) { // Skipping tracks without TOF + continue; + } + mult++; + } + if (mult < MinMult) { // Cutting on low multiplicity events + return; + } + const float collisionTime_ps = collision.collisionTime() * 1000.f; + histos.fill(HIST("event/vertexz"), collision.posZ()); + histos.fill(HIST("event/colltime"), collisionTime_ps); + histos.fill(HIST("event/tofmultiplicity"), mult); + histos.fill(HIST("event/colltimereso"), mult, collision.collisionTimeRes() * 1000.f); + for (auto t : tracks) { + // + if (t.tofSignal() < 0) { // Skipping tracks without TOF + continue; + } + if (!t.isGlobalTrack()) { + continue; + } + + const float tof = t.tofSignal() - collisionTime_ps; + + // + histos.fill(HIST("event/tofsignal"), t.p(), t.tofSignal()); + histos.fill(HIST("event/eta"), t.eta()); + histos.fill(HIST("event/length"), t.length()); + histos.fill(HIST("event/pt"), t.pt()); + histos.fill(HIST("event/ptreso"), t.p(), t.sigma1Pt() * t.pt() * t.pt()); + // + fillParticleHistos<0>(t, tof, t.tofExpSignalDiffEl(), t.tofExpSigmaEl(), t.tofNSigmaEl()); + fillParticleHistos<1>(t, tof, t.tofExpSignalDiffMu(), t.tofExpSigmaMu(), t.tofNSigmaMu()); + fillParticleHistos<2>(t, tof, t.tofExpSignalDiffPi(), t.tofExpSigmaPi(), t.tofNSigmaPi()); + fillParticleHistos<3>(t, tof, t.tofExpSignalDiffKa(), t.tofExpSigmaKa(), t.tofNSigmaKa()); + fillParticleHistos<4>(t, tof, t.tofExpSignalDiffPr(), t.tofExpSigmaPr(), t.tofNSigmaPr()); + fillParticleHistos<5>(t, tof, t.tofExpSignalDiffDe(), t.tofExpSigmaDe(), t.tofNSigmaDe()); + fillParticleHistos<6>(t, tof, t.tofExpSignalDiffTr(), t.tofExpSigmaTr(), t.tofNSigmaTr()); + fillParticleHistos<7>(t, tof, t.tofExpSignalDiffHe(), t.tofExpSigmaHe(), t.tofNSigmaHe()); + fillParticleHistos<8>(t, tof, t.tofExpSignalDiffAl(), t.tofExpSigmaAl(), t.tofNSigmaAl()); + } + } +}; + +WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) +{ + auto workflow = WorkflowSpec{adaptAnalysisTask(cfgc, TaskName{"alice3-pidTOF-task"})}; + if (cfgc.options().get("add-qa")) { + workflow.push_back(adaptAnalysisTask(cfgc, TaskName{"alice3-pidTOFQA-task"})); + } + return workflow; +} diff --git a/Analysis/ALICE3/src/alice3-qa-multiplicity.cxx b/Analysis/ALICE3/src/alice3-qa-multiplicity.cxx new file mode 100644 index 0000000000000..8ccda89c5b4b6 --- /dev/null +++ b/Analysis/ALICE3/src/alice3-qa-multiplicity.cxx @@ -0,0 +1,53 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. +/// \author Nicolo' Jacazio , CERN + +// O2 includes +#include "Framework/AnalysisTask.h" +#include "Framework/runDataProcessing.h" + +using namespace o2; +using namespace o2::framework; +using namespace o2::framework::expressions; + +struct ALICE3MultTask { + HistogramRegistry histos{"Histos", {}, OutputObjHandlingPolicy::QAObject}; + + Configurable MinEta{"MinEta", -0.8f, "Minimum eta in range"}; + Configurable MaxEta{"MaxEta", 0.8f, "Maximum eta in range"}; + Configurable MaxMult{"MaxMult", 1000.f, "Maximum multiplicity in range"}; + + void init(InitContext&) + { + histos.add("multiplicity/numberOfTracks", ";Reconstructed tracks", kTH1D, {{(int)MaxMult, 0, MaxMult}}); + } + + void process(const o2::aod::Collision& collision, const o2::aod::Tracks& tracks) + { + if (collision.numContrib() < 2) { + return; + } + + int nTracks = 0; + for (const auto& track : tracks) { + if (track.eta() < MinEta || track.eta() > MaxEta) { + continue; + } + nTracks++; + } + + histos.fill(HIST("multiplicity/numberOfTracks"), nTracks); + } +}; + +WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) +{ + return WorkflowSpec{adaptAnalysisTask(cfgc)}; +} diff --git a/Analysis/ALICE3/src/alice3-trackextension.cxx b/Analysis/ALICE3/src/alice3-trackextension.cxx new file mode 100644 index 0000000000000..624061378ea4e --- /dev/null +++ b/Analysis/ALICE3/src/alice3-trackextension.cxx @@ -0,0 +1,43 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +// +// Task performing basic track selection for the ALICE3. +// + +#include "Framework/AnalysisDataModel.h" +#include "Framework/AnalysisTask.h" +#include "Framework/runDataProcessing.h" +#include "AnalysisDataModel/TrackSelectionTables.h" +#include "AnalysisCore/trackUtilities.h" + +using namespace o2; +using namespace o2::framework; +using namespace o2::framework::expressions; + +struct TrackExtensionTask { + Configurable magField{"magField", 5.f, "Magnetic field for the propagation to the primary vertex in kG"}; + Produces extendedTrackQuantities; + + void process(aod::Collision const& collision, aod::FullTracks const& tracks) + { + std::array dca{1e10f, 1e10f}; + for (auto& track : tracks) { + auto trackPar = getTrackPar(track); + trackPar.propagateParamToDCA({collision.posX(), collision.posY(), collision.posZ()}, magField, &dca); + extendedTrackQuantities(dca[0], dca[1]); + } + } +}; + +WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) +{ + return WorkflowSpec{adaptAnalysisTask(cfgc)}; +} diff --git a/Analysis/ALICE3/src/alice3-trackselection.cxx b/Analysis/ALICE3/src/alice3-trackselection.cxx index ce9d17b17b617..c16bc4d82d42b 100644 --- a/Analysis/ALICE3/src/alice3-trackselection.cxx +++ b/Analysis/ALICE3/src/alice3-trackselection.cxx @@ -13,7 +13,6 @@ /// \brief Track selection for the ALICE3 studies /// -#include "Framework/AnalysisDataModel.h" #include "Framework/AnalysisTask.h" #include "Framework/runDataProcessing.h" #include "AnalysisCore/TrackSelection.h" @@ -29,18 +28,49 @@ using namespace o2::framework::expressions; * Produce track filter table. */ //**************************************************************************************** -struct TrackSelectionTask { +struct Alice3TrackSelectionTask { Produces filterTable; + HistogramRegistry histos{"Histos", {}, OutputObjHandlingPolicy::QAObject}; + + Configurable MaxDCAxy{"MaxDCAxy", 0.1f, "Maximum DCAxy"}; + Configurable MinEta{"MinEta", -0.8f, "Minimum eta in range"}; + Configurable MaxEta{"MaxEta", 0.8f, "Maximum eta in range"}; void init(InitContext&) { + histos.add("selection", "Selection process;Check;Entries", HistType::kTH1F, {{10, -0.5, 9.5}}); + histos.get(HIST("selection"))->GetXaxis()->SetBinLabel(1, "Tracks read"); + histos.get(HIST("selection"))->GetXaxis()->SetBinLabel(2, "DCAxy"); + histos.get(HIST("selection"))->GetXaxis()->SetBinLabel(3, "Eta"); + histos.add("dcaXY/selected", "Selected;DCA_{xy} (cm);Entries", HistType::kTH1F, {{100, -5, 5}}); + histos.add("dcaXY/nonselected", "Not selected;DCA_{xy} (cm);Entries", HistType::kTH1F, {{100, -5, 5}}); + histos.add("eta/selected", "Selected;#eta;Entries", HistType::kTH1F, {{100, -2, 2}}); + histos.add("eta/nonselected", "Not selected;#eta;Entries", HistType::kTH1F, {{100, -2, 2}}); } void process(soa::Join const& tracks) { + filterTable.reserve(tracks.size()); for (auto& track : tracks) { - filterTable(kTRUE, - kTRUE); + histos.fill(HIST("selection"), 0); + histos.fill(HIST("dcaXY/nonselected"), track.dcaXY()); + histos.fill(HIST("eta/nonselected"), track.eta()); + + uint8_t sel = true; + if (abs(track.dcaXY()) > MaxDCAxy) { + histos.fill(HIST("selection"), 1); + sel = false; + } + if (track.eta() < MinEta || track.eta() > MaxEta) { + histos.fill(HIST("selection"), 2); + sel = false; + } + if (sel) { + histos.fill(HIST("dcaXY/selected"), track.dcaXY()); + histos.fill(HIST("eta/selected"), track.eta()); + } + + filterTable(sel, sel); } } }; @@ -52,6 +82,6 @@ struct TrackSelectionTask { //**************************************************************************************** WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { - WorkflowSpec workflow{adaptAnalysisTask(cfgc, TaskName{"track-selection"})}; + WorkflowSpec workflow{adaptAnalysisTask(cfgc)}; return workflow; } diff --git a/Analysis/ALICE3/src/pidRICHqa.cxx b/Analysis/ALICE3/src/pidRICHqa.cxx index 04775ca732dba..ae9c143bb1382 100644 --- a/Analysis/ALICE3/src/pidRICHqa.cxx +++ b/Analysis/ALICE3/src/pidRICHqa.cxx @@ -22,26 +22,51 @@ using namespace o2; using namespace o2::framework; using namespace o2::framework::expressions; +namespace o2::aod +{ + +namespace indices +{ +DECLARE_SOA_INDEX_COLUMN(Track, track); +DECLARE_SOA_INDEX_COLUMN(RICH, rich); +} // namespace indices + +DECLARE_SOA_INDEX_TABLE_USER(RICHTracksIndex, Tracks, "RICHTRK", indices::TrackId, indices::RICHId); +} // namespace o2::aod + +struct RICHindexbuilder { + Builds ind; + void init(o2::framework::InitContext&) + { + } +}; + struct pidRICHQAMC { - HistogramRegistry histos{"Histos", {}, OutputObjHandlingPolicy::AnalysisObject}; + HistogramRegistry histos{"Histos", {}, OutputObjHandlingPolicy::QAObject}; Configurable pdgCode{"pdgCode", 0, "pdg code of the particles to accept"}; Configurable useOnlyPhysicsPrimary{"useOnlyPhysicsPrimary", 1, "Whether to use only physical primary particles."}; Configurable minLength{"minLength", 0, "Minimum length of accepted tracks (cm)"}; Configurable maxLength{"maxLength", 1000, "Maximum length of accepted tracks (cm)"}; - Configurable nBinsP{"nBinsP", 100, "Number of momentum bins"}; + Configurable minEta{"minEta", -1.4, "Minimum eta of accepted tracks"}; + Configurable maxEta{"maxEta", 1.4, "Maximum eta of accepted tracks"}; + Configurable nBinsP{"nBinsP", 500, "Number of momentum bins"}; Configurable minP{"minP", 0.01, "Minimum momentum plotted (GeV/c)"}; Configurable maxP{"maxP", 100, "Maximum momentum plotted (GeV/c)"}; Configurable nBinsNsigma{"nBinsNsigma", 600, "Number of Nsigma bins"}; - Configurable minNsigma{"minNsigma", -10.f, "Minimum Nsigma plotted"}; - Configurable maxNsigma{"maxNsigma", 10.f, "Maximum Nsigma plotted"}; + Configurable minNsigma{"minNsigma", -100.f, "Minimum Nsigma plotted"}; + Configurable maxNsigma{"maxNsigma", 100.f, "Maximum Nsigma plotted"}; Configurable nBinsDelta{"nBinsDelta", 100, "Number of delta bins"}; Configurable minDelta{"minDelta", -1.f, "Minimum delta plotted (rad)"}; Configurable maxDelta{"maxDelta", 1.f, "Maximum delta plotted (rad)"}; + Configurable logAxis{"logAxis", 1, "Flag to use a log momentum axis"}; template void makelogaxis(T h) { + if (logAxis == 0) { + return; + } const int nbins = h->GetNbinsX(); double binp[nbins + 1]; double max = h->GetXaxis()->GetBinUpEdge(nbins); @@ -60,26 +85,29 @@ struct pidRICHQAMC { void init(o2::framework::InitContext&) { - AxisSpec momAxis{nBinsP.value, minP.value, maxP.value}; - AxisSpec nsigmaAxis{nBinsNsigma.value, minNsigma.value, maxNsigma.value}; - AxisSpec deltaAxis{nBinsDelta.value, minDelta.value, maxDelta.value}; + AxisSpec momAxis{nBinsP, minP, maxP}; + AxisSpec nsigmaAxis{nBinsNsigma, minNsigma, maxNsigma}; + AxisSpec deltaAxis{nBinsDelta, minDelta, maxDelta}; + histos.add("event/vertexz", ";Vtx_{z} (cm);Entries", kTH1F, {{100, -20, 20}}); histos.add("p/Unselected", "Unselected;#it{p} (GeV/#it{c})", kTH1F, {momAxis}); histos.add("p/Prim", "Primaries;#it{p} (GeV/#it{c})", kTH1F, {momAxis}); histos.add("p/Sec", "Secondaries;#it{p} (GeV/#it{c})", kTH1F, {momAxis}); histos.add("pt/Unselected", "Unselected;#it{p} (GeV/#it{c})", kTH1F, {momAxis}); - histos.add("qa/signal", ";#theta (rad)", kTH1F, {{100, 0, 1}}); - histos.add("qa/signalerror", ";#theta (rad)", kTH1F, {{100, 0, 1}}); + histos.add("qa/signal", ";Cherenkov angle (rad)", kTH1F, {{100, 0, 1}}); + histos.add("qa/signalerror", ";Cherenkov angle (rad)", kTH1F, {{100, 0, 1}}); + histos.add("qa/signalvsP", ";#it{p} (GeV/#it{c});Cherenkov angle (rad)", kTH2F, {momAxis, {1000, 0, 0.3}}); histos.add("qa/deltaEl", ";#it{p} (GeV/#it{c});#Delta(e) (rad)", kTH2F, {momAxis, deltaAxis}); histos.add("qa/deltaMu", ";#it{p} (GeV/#it{c});#Delta(#mu) (rad)", kTH2F, {momAxis, deltaAxis}); histos.add("qa/deltaPi", ";#it{p} (GeV/#it{c});#Delta(#pi) (rad)", kTH2F, {momAxis, deltaAxis}); histos.add("qa/deltaKa", ";#it{p} (GeV/#it{c});#Delta(K) (rad)", kTH2F, {momAxis, deltaAxis}); histos.add("qa/deltaPr", ";#it{p} (GeV/#it{c});#Delta(p) (rad)", kTH2F, {momAxis, deltaAxis}); - histos.add("qa/nsigmaEl", ";#it{p} (GeV/#it{c});n#sigma(e)", kTH2F, {momAxis, nsigmaAxis}); - histos.add("qa/nsigmaMu", ";#it{p} (GeV/#it{c});n#sigma(#mu)", kTH2F, {momAxis, nsigmaAxis}); - histos.add("qa/nsigmaPi", ";#it{p} (GeV/#it{c});n#sigma(#pi)", kTH2F, {momAxis, nsigmaAxis}); - histos.add("qa/nsigmaKa", ";#it{p} (GeV/#it{c});n#sigma(K)", kTH2F, {momAxis, nsigmaAxis}); - histos.add("qa/nsigmaPr", ";#it{p} (GeV/#it{c});n#sigma(p)", kTH2F, {momAxis, nsigmaAxis}); + histos.add("qa/nsigmaEl", ";#it{p} (GeV/#it{c});N_{#sigma}^{RICH}(e)", kTH2F, {momAxis, nsigmaAxis}); + histos.add("qa/nsigmaMu", ";#it{p} (GeV/#it{c});N_{#sigma}^{RICH}(#mu)", kTH2F, {momAxis, nsigmaAxis}); + histos.add("qa/nsigmaPi", ";#it{p} (GeV/#it{c});N_{#sigma}^{RICH}(#pi)", kTH2F, {momAxis, nsigmaAxis}); + histos.add("qa/nsigmaKa", ";#it{p} (GeV/#it{c});N_{#sigma}^{RICH}(K)", kTH2F, {momAxis, nsigmaAxis}); + histos.add("qa/nsigmaPr", ";#it{p} (GeV/#it{c});N_{#sigma}^{RICH}(p)", kTH2F, {momAxis, nsigmaAxis}); + makelogaxis(histos.get(HIST("qa/signalvsP"))); makelogaxis(histos.get(HIST("qa/deltaEl"))); makelogaxis(histos.get(HIST("qa/deltaMu"))); makelogaxis(histos.get(HIST("qa/deltaPi"))); @@ -92,50 +120,58 @@ struct pidRICHQAMC { makelogaxis(histos.get(HIST("qa/nsigmaPr"))); } - void process(const aod::Tracks& tracks, - const aod::TracksExtra& tracksExtra, + using Trks = soa::Join; + void process(const Trks& tracks, const aod::McTrackLabels& labels, - const aod::RICHs& tracks_rich, - const aod::McParticles& mcParticles) + const aod::RICHs&, + const aod::McParticles& mcParticles, + const aod::Collisions& colls) { - for (const auto& t : tracks_rich) { - const auto track = t.track(); - const auto trackExtra = tracksExtra.iteratorAt(track.globalIndex()); - if (trackExtra.length() < minLength.value) { + for (const auto& col : colls) { + histos.fill(HIST("event/vertexz"), col.posZ()); + } + for (const auto& track : tracks) { + if (!track.has_rich()) { + continue; + } + if (track.length() < minLength) { + continue; + } + if (track.length() > maxLength) { continue; } - if (trackExtra.length() > maxLength.value) { + if (track.eta() > maxEta || track.eta() < minEta) { continue; } const auto mcParticle = labels.iteratorAt(track.globalIndex()).mcParticle(); - if (pdgCode.value != 0 && abs(mcParticle.pdgCode()) != pdgCode.value) { + if (pdgCode != 0 && abs(mcParticle.pdgCode()) != pdgCode) { continue; } - if (useOnlyPhysicsPrimary.value == 1 && !MC::isPhysicalPrimary(mcParticles, mcParticle)) { // Selecting primaries + if (useOnlyPhysicsPrimary == 1 && !MC::isPhysicalPrimary(mcParticles, mcParticle)) { // Selecting primaries histos.fill(HIST("p/Sec"), track.p()); continue; } histos.fill(HIST("p/Prim"), track.p()); histos.fill(HIST("p/Unselected"), track.p()); histos.fill(HIST("pt/Unselected"), track.pt()); - histos.fill(HIST("qa/signal"), t.richSignal()); - histos.fill(HIST("qa/signalerror"), t.richSignalError()); - histos.fill(HIST("qa/deltaEl"), track.p(), t.richDeltaEl()); - histos.fill(HIST("qa/deltaMu"), track.p(), t.richDeltaMu()); - histos.fill(HIST("qa/deltaPi"), track.p(), t.richDeltaPi()); - histos.fill(HIST("qa/deltaKa"), track.p(), t.richDeltaKa()); - histos.fill(HIST("qa/deltaPr"), track.p(), t.richDeltaPr()); - histos.fill(HIST("qa/nsigmaEl"), track.p(), t.richNsigmaEl()); - histos.fill(HIST("qa/nsigmaMu"), track.p(), t.richNsigmaMu()); - histos.fill(HIST("qa/nsigmaPi"), track.p(), t.richNsigmaPi()); - histos.fill(HIST("qa/nsigmaKa"), track.p(), t.richNsigmaKa()); - histos.fill(HIST("qa/nsigmaPr"), track.p(), t.richNsigmaPr()); + histos.fill(HIST("qa/signal"), track.rich().richSignal()); + histos.fill(HIST("qa/signalerror"), track.rich().richSignalError()); + histos.fill(HIST("qa/signalvsP"), track.p(), track.rich().richSignal()); + histos.fill(HIST("qa/deltaEl"), track.p(), track.rich().richDeltaEl()); + histos.fill(HIST("qa/deltaMu"), track.p(), track.rich().richDeltaMu()); + histos.fill(HIST("qa/deltaPi"), track.p(), track.rich().richDeltaPi()); + histos.fill(HIST("qa/deltaKa"), track.p(), track.rich().richDeltaKa()); + histos.fill(HIST("qa/deltaPr"), track.p(), track.rich().richDeltaPr()); + histos.fill(HIST("qa/nsigmaEl"), track.p(), track.rich().richNsigmaEl()); + histos.fill(HIST("qa/nsigmaMu"), track.p(), track.rich().richNsigmaMu()); + histos.fill(HIST("qa/nsigmaPi"), track.p(), track.rich().richNsigmaPi()); + histos.fill(HIST("qa/nsigmaKa"), track.p(), track.rich().richNsigmaKa()); + histos.fill(HIST("qa/nsigmaPr"), track.p(), track.rich().richNsigmaPr()); } } }; WorkflowSpec defineDataProcessing(ConfigContext const& cfg) { - WorkflowSpec workflow{adaptAnalysisTask(cfg, "pidRICH-qa")}; - return workflow; + return WorkflowSpec{adaptAnalysisTask(cfg), adaptAnalysisTask(cfg, TaskName{"pidRICH-qa"})}; } diff --git a/Analysis/DataModel/CMakeLists.txt b/Analysis/DataModel/CMakeLists.txt index 9f77bbb2aa502..7a50640d969d7 100644 --- a/Analysis/DataModel/CMakeLists.txt +++ b/Analysis/DataModel/CMakeLists.txt @@ -20,6 +20,7 @@ o2_target_root_dictionary(AnalysisDataModel include/AnalysisDataModel/PID/DetectorResponse.h include/AnalysisDataModel/PID/PIDTOF.h include/AnalysisDataModel/PID/TOFReso.h + include/AnalysisDataModel/PID/TOFResoALICE3.h include/AnalysisDataModel/PID/PIDTPC.h include/AnalysisDataModel/PID/BetheBloch.h include/AnalysisDataModel/PID/TPCReso.h @@ -40,3 +41,8 @@ o2_add_executable(pidparam-tof-reso SOURCES src/handleParamTOFReso.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::AnalysisDataModel ) + +o2_add_executable(pidparam-tof-reso-alice3 + SOURCES src/handleParamTOFResoALICE3.cxx + PUBLIC_LINK_LIBRARIES O2::Framework O2::AnalysisDataModel + ) diff --git a/Analysis/DataModel/include/AnalysisDataModel/PID/BetheBloch.h b/Analysis/DataModel/include/AnalysisDataModel/PID/BetheBloch.h index 37affbc22e91f..889929080201c 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/PID/BetheBloch.h +++ b/Analysis/DataModel/include/AnalysisDataModel/PID/BetheBloch.h @@ -20,6 +20,7 @@ #include "TPCSimulation/Detector.h" #include "AnalysisDataModel/PID/ParamBase.h" +#include "ReconstructionDataFormats/PID.h" namespace o2::pid::tpc { @@ -36,6 +37,17 @@ class BetheBloch : public Parametrization ClassDef(BetheBloch, 1); }; +float BetheBlochParam(const float& momentum, const float& mass, const float& charge, const Parameters& parameters) +{ + return parameters[5] * o2::tpc::Detector::BetheBlochAleph(momentum / mass, parameters[0], parameters[1], parameters[2], parameters[3], parameters[4]) * pow(charge, parameters[6]); +} + +template +float BetheBlochParamTrack(const T& track, const Parameters& parameters) +{ + return BetheBlochParam(track.tpcInnerParam(), o2::track::pid_constants::sMasses[id], (float)o2::track::pid_constants::sCharges[id], parameters); +} + } // namespace o2::pid::tpc #endif diff --git a/Analysis/DataModel/include/AnalysisDataModel/PID/DetectorResponse.h b/Analysis/DataModel/include/AnalysisDataModel/PID/DetectorResponse.h index 8e4bd405cd164..bf4fd80b3bb49 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/PID/DetectorResponse.h +++ b/Analysis/DataModel/include/AnalysisDataModel/PID/DetectorResponse.h @@ -69,7 +69,7 @@ class DetectorResponse /// Getter for the value of the parametrization /// \param ptype parametrization type /// \param x array with parameters - virtual pidvar_t operator()(const Param_t ptype, const pidvar_t* x) const { return mParam[ptype]->operator()(x); } + pidvar_t operator()(const Param_t ptype, const pidvar_t* x) const { return mParam[ptype]->operator()(x); } private: /// Parametrizations for the expected signal and sigma @@ -86,7 +86,6 @@ inline void DetectorResponse::LoadParamFromFile(const TString fname, const TStri f.GetObject(pname, mParam[ptype]); f.Close(); mParam[ptype]->Print(); - mParam[ptype]->PrintParametrization(); } inline void DetectorResponse::SetParameters(const DetectorResponse::Param_t ptype, std::vector p) diff --git a/Analysis/DataModel/include/AnalysisDataModel/PID/PIDTOF.h b/Analysis/DataModel/include/AnalysisDataModel/PID/PIDTOF.h index 5b1d43848c9d3..32211e03acbca 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/PID/PIDTOF.h +++ b/Analysis/DataModel/include/AnalysisDataModel/PID/PIDTOF.h @@ -107,7 +107,7 @@ class ExpTimes static float ComputeExpectedTime(const float& tofExpMom, const float& length, const float& massZ); /// Gets the expected signal of the track of interest under the PID assumption - float GetExpectedSignal(const Coll& col, const Trck& trk) const { return ComputeExpectedTime(trk.tofExpMom() / kCSPEED, trk.length(), o2::track::PID::getMass2Z(id)); } + static float GetExpectedSignal(const Coll& col, const Trck& trk) { return ComputeExpectedTime(trk.tofExpMom() / kCSPEED, trk.length(), o2::track::PID::getMass2Z(id)); } /// Gets the expected resolution of the measurement float GetExpectedSigma(const DetectorResponse& response, const Coll& col, const Trck& trk) const; @@ -131,7 +131,7 @@ float ExpTimes::GetExpectedSigma(const DetectorResponse& respons if (trk.tofSignal() <= 0) { return -999.f; } - const float x[4] = {trk.p(), trk.tofSignal(), col.collisionTimeRes() * 1000.f, o2::track::PID::getMass2Z(id)}; + const float x[7] = {trk.p(), trk.tofSignal(), col.collisionTimeRes() * 1000.f, o2::track::PID::getMass2Z(id), trk.length(), trk.sigma1Pt(), trk.pt()}; return response(response.kSigma, x); // return response(response.kSigma, const Coll& col, const Trck& trk, id); } diff --git a/Analysis/DataModel/include/AnalysisDataModel/PID/ParamBase.h b/Analysis/DataModel/include/AnalysisDataModel/PID/ParamBase.h index 9681800e7dc39..fbcefac1157ff 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/PID/ParamBase.h +++ b/Analysis/DataModel/include/AnalysisDataModel/PID/ParamBase.h @@ -28,19 +28,23 @@ namespace o2::pid using pidvar_t = float; /// \brief Class to handle the parameters of a given detector response -class Parameters : public TObject +class Parameters : public TNamed { public: /// Default constructor Parameters() = default; /// Parametric constructor - /// \param npar Number of parameters in the container - Parameters(unsigned int npar) : mPar(std::vector(npar)){}; + /// \param size Number of parameters in the container + Parameters(unsigned int size) : mPar(std::vector(size)){}; + + /// Parametric constructor + /// \param size Number of parameters in the container + Parameters(const TString name, unsigned int size) : TNamed(name, name), mPar(std::vector(size)){}; /// Parametric constructor /// \param params Parameters to initialize the container - Parameters(const std::vector params) : mPar{} { SetParameters(params); }; + Parameters(const TString name, const std::vector params) : TNamed(name, name), mPar{} { SetParameters(params); }; /// Default destructor ~Parameters() override = default; @@ -54,12 +58,25 @@ class Parameters : public TObject /// \param param array with parameters void SetParameters(const pidvar_t* params) { std::copy(params, params + mPar.size(), mPar.begin()); } - /// Setter for the parameter, using an array - /// \param params array with parameters + /// Setter for the parameter, using a vector + /// \param params vector with parameters void SetParameters(const std::vector params); + /// Setter for the parameter, using a parameter object + /// \param params parameter object with parameters + void SetParameters(const Parameters params) { SetParameters(params.mPar); }; + + /// Setter for the parameter, using a parameter pointer + /// \param params pointer to parameter object with parameters + void SetParameters(const Parameters* params) { SetParameters(params->mPar); }; + /// Printer of the parameter values - void PrintParameters() const; + virtual void Print(Option_t* option = "") const override; + + /// Loader from file + /// \param FileName name of the input file + /// \param ParamName name of the input object + void LoadParamFromFile(const TString FileName, const TString ParamName); /// Getter for the parameters /// \return returns an array of parameters @@ -72,7 +89,7 @@ class Parameters : public TObject /// Getter of the parameter at position i /// \param i index of the parameter to get /// \return returns the parameter value at position i - pidvar_t operator[](unsigned int i) const { return mPar[i]; } + pidvar_t operator[](const unsigned int i) const { return mPar[i]; } private: /// Vector of the parameter @@ -91,12 +108,12 @@ class Parametrization : public TNamed /// Parametric constructor /// \param name Name (and title) of the parametrization /// \param size Number of parameters of the parametrization - Parametrization(TString name, unsigned int size) : TNamed(name, name), mParameters{size} {}; + Parametrization(TString name, unsigned int size) : TNamed(name, name), mParameters(name + "Parameters", size){}; /// Parametric constructor /// \param name Name (and title) of the parametrization /// \param params Parameters of the parametrization - Parametrization(TString name, const std::vector params) : TNamed(name, name), mParameters{params} {}; + Parametrization(TString name, const std::vector params) : TNamed(name, name), mParameters{name + "Parameters", params} {}; /// Default destructor ~Parametrization() override = default; @@ -105,21 +122,33 @@ class Parametrization : public TNamed /// \param x array of variables to use in order to compute the return value virtual pidvar_t operator()(const pidvar_t* x) const; - /// Printer for parameters - void PrintParametrization() const; + /// Printer for the parametrization + virtual void Print(Option_t* option = "") const override; + + /// Loader from file + /// \param FileName name of the input file + /// \param ParamName name of the input object + void LoadParamFromFile(const TString FileName, const TString ParamName); /// Setter for the parameter at position iparam /// \param iparam index in the array of the parameters /// \param value value of the parameter at position iparam void SetParameter(const unsigned int iparam, const pidvar_t value) { mParameters.SetParameter(iparam, value); } - /// Setter for the parameter, using an array - /// \param params array with parameters - void SetParameters(const std::vector params) { mParameters.SetParameters(params); } + /// Setter for the parameter, using a vector, a parameter object or a pointer to a parameter object + /// \param params vector, parameter object, pointer to parameter object with parameters + template + void SetParameters(const T params) + { + mParameters.SetParameters(params); + } /// Getter for the parameters Parameters GetParameters() const { return mParameters; } + /// Getter for the parameters + void GetParameters(Parameters*& parameters) { parameters = &mParameters; } + protected: /// Parameters of the parametrization Parameters mParameters; diff --git a/Analysis/DataModel/include/AnalysisDataModel/PID/TOFReso.h b/Analysis/DataModel/include/AnalysisDataModel/PID/TOFReso.h index 45cdb6cd7b657..cef242d63b183 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/PID/TOFReso.h +++ b/Analysis/DataModel/include/AnalysisDataModel/PID/TOFReso.h @@ -18,10 +18,9 @@ #ifndef O2_ANALYSIS_PID_TOFRESO_H_ #define O2_ANALYSIS_PID_TOFRESO_H_ -// Root includes -#include "TMath.h" // O2 includes #include "AnalysisDataModel/PID/ParamBase.h" +#include "ReconstructionDataFormats/PID.h" namespace o2::pid::tof { @@ -42,11 +41,27 @@ class TOFReso : public Parametrization const float mass = x[3]; const float dpp = mParameters[0] + mParameters[1] * mom + mParameters[2] * mass / mom; // mean relative pt resolution; const float sigma = dpp * time / (1. + mom * mom / (mass * mass)); - return TMath::Sqrt(sigma * sigma + mParameters[3] * mParameters[3] / mom / mom + mParameters[4] * mParameters[4] + evtimereso * evtimereso); + return sqrt(sigma * sigma + mParameters[3] * mParameters[3] / mom / mom + mParameters[4] * mParameters[4] + evtimereso * evtimereso); } ClassDef(TOFReso, 1); }; +float TOFResoParam(const float& momentum, const float& time, const float& evtimereso, const float& mass, const Parameters& parameters) +{ + if (momentum <= 0) { + return -999; + } + const float dpp = parameters[0] + parameters[1] * momentum + parameters[2] * mass / momentum; // mean relative pt resolution; + const float sigma = dpp * time / (1. + momentum * momentum / (mass * mass)); + return sqrt(sigma * sigma + parameters[3] * parameters[3] / momentum / momentum + parameters[4] * parameters[4] + evtimereso * evtimereso); +} + +template +float TOFResoParamTrack(const C& collision, const T& track, const Parameters& parameters) +{ + return TOFResoParam(track.p(), track.tofSignal(), collision.collisionTimeRes() * 1000.f, o2::track::pid_constants::sMasses[id], parameters); +} + } // namespace o2::pid::tof #endif diff --git a/Analysis/DataModel/include/AnalysisDataModel/PID/TOFResoALICE3.h b/Analysis/DataModel/include/AnalysisDataModel/PID/TOFResoALICE3.h new file mode 100644 index 0000000000000..c5727eb891e24 --- /dev/null +++ b/Analysis/DataModel/include/AnalysisDataModel/PID/TOFResoALICE3.h @@ -0,0 +1,85 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// +/// \file TOFResoALICE3.h +/// \author Nicolo' Jacazio +/// \since 11/03/2021 +/// \brief Implementation for the TOF PID response of the expected times resolution +/// + +#ifndef O2_ANALYSIS_PID_TOFRESOALICE3_H_ +#define O2_ANALYSIS_PID_TOFRESOALICE3_H_ + +// O2 includes +#include "AnalysisDataModel/PID/ParamBase.h" +#include "ReconstructionDataFormats/PID.h" + +namespace o2::pid::tof +{ + +class TOFResoALICE3 : public Parametrization +{ + public: + TOFResoALICE3() : Parametrization("TOFResoALICE3", 1){}; + ~TOFResoALICE3() override = default; + float operator()(const float* x) const override + { + const float p = abs(x[0]); + if (p <= 0) { + return -999; + } + + /** get info **/ + const float time = x[1]; + const float evtimereso = x[2]; + const float mass = x[3]; + const float L = x[4]; + const float p2 = p * p; + // const float ep = x[5] * x[6]; + const float ep = x[5] * p2; + const float Lc = L / 0.0299792458f; + // const float Lc = L / 29.9792458f; + + const float mass2 = mass * mass; + const float etexp = Lc * mass2 / p2 / sqrt(mass2 + p2) * ep; + return sqrt(etexp * etexp + mParameters[0] * mParameters[0] + evtimereso * evtimereso); + } + ClassDef(TOFResoALICE3, 1); +}; + +float TOFResoALICE3Param(const float& momentum, const float& momentumError, const float& evtimereso, const float& length, const float& mass, const Parameters& parameters) +{ + if (momentum <= 0) { + return -999; + } + + const float p2 = momentum * momentum; + const float Lc = length / 0.0299792458f; + const float mass2 = mass * mass; + const float ep = momentumError * momentum; + // const float ep = momentumError * p2; + const float etexp = Lc * mass2 / p2 / sqrt(mass2 + p2) * ep; + return sqrt(etexp * etexp + parameters[0] * parameters[0] + evtimereso * evtimereso); +} + +template +float TOFResoALICE3ParamTrack(const C& collision, const T& track, const Parameters& parameters) +{ + const float BETA = tan(0.25f * static_cast(M_PI) - 0.5f * atan(track.tgl())); + const float sigmaP = sqrt(pow(track.pt(), 2) * pow(track.sigma1Pt(), 2) + (BETA * BETA - 1.f) / (BETA * (BETA * BETA + 1.f)) * (track.tgl() / sqrt(track.tgl() * track.tgl() + 1.f) - 1.f) * pow(track.sigmaTgl(), 2)); + // const float sigmaP = std::sqrt( track.getSigma1Pt2() ) * track.pt(); + return TOFResoALICE3Param(track.p(), sigmaP, collision.collisionTimeRes() * 1000.f, track.length(), o2::track::pid_constants::sMasses[id], parameters); + // return TOFResoALICE3Param(track.p(), track.sigma1Pt(), collision.collisionTimeRes() * 1000.f, track.length(), o2::track::pid_constants::sMasses[id], parameters); +} + +} // namespace o2::pid::tof + +#endif diff --git a/Analysis/DataModel/include/AnalysisDataModel/PID/TPCReso.h b/Analysis/DataModel/include/AnalysisDataModel/PID/TPCReso.h index 8f6d2171ee277..09fb7525ffbf4 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/PID/TPCReso.h +++ b/Analysis/DataModel/include/AnalysisDataModel/PID/TPCReso.h @@ -19,6 +19,7 @@ #define O2_ANALYSIS_PID_TPCRESO_H_ #include "AnalysisDataModel/PID/ParamBase.h" +#include "ReconstructionDataFormats/PID.h" namespace o2::pid::tpc { @@ -36,6 +37,17 @@ class TPCReso : public Parametrization ClassDef(TPCReso, 1); }; +float TPCResoParam(const float& signal, const float& npoints, const Parameters& parameters) +{ + return signal * parameters[0] * (npoints > 0 ? sqrt(1. + parameters[1] / npoints) : 1.f); +} + +template +float TPCResoParamTrack(const T& track, const Parameters& parameters) +{ + return TPCResoParam(track.tpcSignal(), (float)track.tpcNClsFound(), parameters); +} + } // namespace o2::pid::tpc #endif diff --git a/Analysis/DataModel/src/AnalysisDataModelLinkDef.h b/Analysis/DataModel/src/AnalysisDataModelLinkDef.h index 5db890293367e..f92bacdbb0538 100644 --- a/Analysis/DataModel/src/AnalysisDataModelLinkDef.h +++ b/Analysis/DataModel/src/AnalysisDataModelLinkDef.h @@ -16,6 +16,7 @@ #pragma link C++ class o2::pid::Parametrization + ; #pragma link C++ class o2::pid::tof::TOFReso + ; +#pragma link C++ class o2::pid::tof::TOFResoALICE3 + ; #pragma link C++ class o2::pid::tpc::BetheBloch + ; #pragma link C++ class o2::pid::tpc::TPCReso + ; diff --git a/Analysis/DataModel/src/ParamBase.cxx b/Analysis/DataModel/src/ParamBase.cxx index 865f566c905e4..b17e83f1e0f45 100644 --- a/Analysis/DataModel/src/ParamBase.cxx +++ b/Analysis/DataModel/src/ParamBase.cxx @@ -18,6 +18,7 @@ #include "AnalysisDataModel/PID/ParamBase.h" #include "Framework/Logger.h" +#include "TFile.h" namespace o2::pid { @@ -25,28 +26,57 @@ namespace o2::pid void Parameters::SetParameters(const std::vector params) { if (mPar.size() != params.size()) { - LOG(fatal) << "Updating parametrization size!"; + LOG(fatal) << "Updating parametrization size! Trying to fit a parametrization of size " << params.size() << " into one of size " << mPar.size(); } mPar.assign(params.begin(), params.end()); } -void Parameters::PrintParameters() const +void Parameters::Print(Option_t* options) const { + LOG(info) << "Parameters '" << fName << "'"; for (unsigned int i = 0; i < size(); i++) { LOG(info) << "Parameter " << i << "/" << size() - 1 << " is " << mPar[i]; } }; +void Parameters::LoadParamFromFile(const TString FileName, const TString ParamName) +{ + TFile f(FileName, "READ"); + if (!f.Get(ParamName)) { + LOG(fatal) << "Did not find parameters " << ParamName << " in file " << FileName; + } + LOG(info) << "Loading parameters " << ParamName << " from TFile " << FileName; + Parameters* p; + f.GetObject(ParamName, p); + f.Close(); + SetParameters(p); + Print(); +} + pidvar_t Parametrization::operator()(const pidvar_t* x) const { LOG(fatal) << "Parametrization " << fName << " is not implemented!"; return -999.999f; } -void Parametrization::PrintParametrization() const +void Parametrization::Print(Option_t* options) const { - LOG(info) << "Parametrization " << fName; - mParameters.PrintParameters(); + LOG(info) << "Parametrization '" << fName << "'"; + mParameters.Print(options); }; +void Parametrization::LoadParamFromFile(const TString FileName, const TString ParamName) +{ + TFile f(FileName, "READ"); + if (!f.Get(ParamName)) { + LOG(fatal) << "Did not find parameters " << ParamName << " in file " << FileName; + } + LOG(info) << "Loading parameters " << ParamName << " from TFile " << FileName; + Parametrization* p; + f.GetObject(ParamName, p); + f.Close(); + SetParameters(p->mParameters); + Print(); +} + } // namespace o2::pid \ No newline at end of file diff --git a/Analysis/DataModel/src/handleParamTOFReso.cxx b/Analysis/DataModel/src/handleParamTOFReso.cxx index 75441a1ec662a..91e7aa4f892b4 100644 --- a/Analysis/DataModel/src/handleParamTOFReso.cxx +++ b/Analysis/DataModel/src/handleParamTOFReso.cxx @@ -9,7 +9,7 @@ // or submit itself to any jurisdiction. /// -/// \file handleParamTOFBetheBloch.cxx +/// \file handleParamTOFReso.cxx /// \author Nicolo' Jacazio /// \since 2020-06-22 /// \brief A simple tool to produce Bethe Bloch parametrization objects for the TOF PID Response @@ -28,10 +28,13 @@ bool initOptionsAndParse(bpo::options_description& options, int argc, char* argv { options.add_options()( "url,u", bpo::value()->default_value("http://ccdb-test.cern.ch:8080"), "URL of the CCDB database")( + "ccdb-path,c", bpo::value()->default_value("Analysis/PID/TOF"), "CCDB path for storage/retrieval")( "start,s", bpo::value()->default_value(0), "Start timestamp of object validity")( "stop,S", bpo::value()->default_value(4108971600000), "Stop timestamp of object validity")( - "delete_previous,d", bpo::value()->default_value(0), "Flag to delete previous versions of converter objects in the CCDB before uploading the new one so as to avoid proliferation on CCDB")( - "file,f", bpo::value()->default_value(""), "Option to save parametrization to file instead of uploading to ccdb")( + "delete-previous,delete_previous,d", bpo::value()->default_value(0), "Flag to delete previous versions of converter objects in the CCDB before uploading the new one so as to avoid proliferation on CCDB")( + "save-to-file,file,f,o", bpo::value()->default_value(""), "Option to save parametrization to file instead of uploading to ccdb")( + "read-from-file,i", bpo::value()->default_value(""), "Option to get parametrization from a file")( + "reso-name,n", bpo::value()->default_value("TOFReso"), "Name of the parametrization object")( "mode,m", bpo::value()->default_value(1), "Working mode: 0 push 1 pull and test")( "p0", bpo::value()->default_value(0.008f), "Parameter 0 of the TOF resolution")( "p1", bpo::value()->default_value(0.008f), "Parameter 1 of the TOF resolution")( @@ -68,7 +71,7 @@ int main(int argc, char* argv[]) } const unsigned int mode = vm["mode"].as(); - const std::string path = "Analysis/PID/TOF"; + const std::string path = vm["ccdb-path"].as(); std::map metadata; std::map* headers; o2::ccdb::CcdbApi api; @@ -78,21 +81,31 @@ int main(int argc, char* argv[]) LOG(WARNING) << "CCDB host " << url << " is not reacheable, cannot go forward"; return 1; } + TOFReso* reso = nullptr; + const std::string reso_name = vm["reso-name"].as(); if (mode == 0) { // Push mode - LOG(INFO) << "Handling TOF resolution parametrization in create mode"; - const std::vector resoparams = {vm["p0"].as(), vm["p1"].as(), vm["p2"].as(), vm["p3"].as(), vm["p4"].as()}; - TOFReso reso; - reso.SetParameters(resoparams); - reso.PrintParametrization(); - const float x[4] = {1, 1, 1, 1}; // mom, time, ev. reso, mass - LOG(INFO) << "TOF expected resolution at p=" << x[0] << " GeV/c " - << " and mass " << x[3] << ":" << reso(x); - - const std::string fname = vm["file"].as(); + LOG(INFO) << "Handling TOF parametrization in create mode"; + const std::string input_file_name = vm["read-from-file"].as(); + if (!input_file_name.empty()) { + TFile f(input_file_name.data(), "READ"); + if (!f.IsOpen()) { + LOG(WARNING) << "Input file " << input_file_name << " is not reacheable, cannot get param from file"; + } + f.GetObject(reso_name.c_str(), reso); + f.Close(); + } + if (!reso) { + reso = new TOFReso(); + const std::vector resoparams = {vm["p0"].as(), vm["p1"].as(), vm["p2"].as(), vm["p3"].as(), vm["p4"].as()}; + reso->SetParameters(resoparams); + } + reso->Print(); + const std::string fname = vm["save-to-file"].as(); if (!fname.empty()) { // Saving it to file LOG(INFO) << "Saving parametrization to file " << fname; TFile f(fname.data(), "RECREATE"); - reso.Write(); + reso->Write(); + reso->GetParameters().Write(); f.ls(); f.Close(); } else { // Saving it to CCDB @@ -101,16 +114,19 @@ int main(int argc, char* argv[]) long start = vm["start"].as(); long stop = vm["stop"].as(); - if (vm["delete_previous"].as()) { + if (vm["delete-previous"].as()) { api.truncate(path); } - api.storeAsTFileAny(&reso, path + "/TOFReso", metadata, start, stop); + api.storeAsTFileAny(reso, path + "/" + reso_name, metadata, start, stop); + o2::pid::Parameters* params; + reso->GetParameters(params); + api.storeAsTFileAny(params, path + "/Parameters/" + reso_name, metadata, start, stop); } } else { // Pull and test mode - LOG(INFO) << "Handling TOF resolution parametrization in test mode"; - const float x[4] = {1, 1, 1, 1}; // mom, time, ev. reso, mass - TOFReso* reso = api.retrieveFromTFileAny(path + "/TOFReso", metadata, -1, headers); - reso->PrintParametrization(); + LOG(INFO) << "Handling TOF parametrization in test mode"; + const float x[7] = {1, 1, 1, 1, 1, 1, 1}; // mom, time, ev. reso, mass, length, sigma1pt, pt + reso = api.retrieveFromTFileAny(path + "/" + reso_name, metadata, -1, headers); + reso->Print(); LOG(INFO) << "TOF expected resolution at p=" << x[0] << " GeV/c " << " and mass " << x[3] << ":" << reso->operator()(x); } diff --git a/Analysis/DataModel/src/handleParamTOFResoALICE3.cxx b/Analysis/DataModel/src/handleParamTOFResoALICE3.cxx new file mode 100644 index 0000000000000..dbf5054de8935 --- /dev/null +++ b/Analysis/DataModel/src/handleParamTOFResoALICE3.cxx @@ -0,0 +1,131 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// +/// \file handleParamTOFResoALICE3.cxx +/// \author Nicolo' Jacazio +/// \since 2020-06-22 +/// \brief A simple tool to produce Bethe Bloch parametrization objects for the TOF PID Response +/// + +#include "CCDB/CcdbApi.h" +#include +#include +#include "TFile.h" +#include "AnalysisDataModel/PID/TOFResoALICE3.h" + +using namespace o2::pid::tof; +namespace bpo = boost::program_options; + +bool initOptionsAndParse(bpo::options_description& options, int argc, char* argv[], bpo::variables_map& vm) +{ + options.add_options()( + "url,u", bpo::value()->default_value("http://ccdb-test.cern.ch:8080"), "URL of the CCDB database")( + "ccdb-path,c", bpo::value()->default_value("Analysis/ALICE3/PID/TOF"), "CCDB path for storage/retrieval")( + "start,s", bpo::value()->default_value(0), "Start timestamp of object validity")( + "stop,S", bpo::value()->default_value(4108971600000), "Stop timestamp of object validity")( + "delete-previous,delete_previous,d", bpo::value()->default_value(0), "Flag to delete previous versions of converter objects in the CCDB before uploading the new one so as to avoid proliferation on CCDB")( + "save-to-file,file,f,o", bpo::value()->default_value(""), "Option to save parametrization to file instead of uploading to ccdb")( + "read-from-file,i", bpo::value()->default_value(""), "Option to get parametrization from a file")( + "reso-name,n", bpo::value()->default_value("TOFResoALICE3"), "Name of the parametrization object")( + "mode,m", bpo::value()->default_value(1), "Working mode: 0 push 1 pull and test")( + "p0", bpo::value()->default_value(20.0f), "Parameter 0 of the TOF resolution: average TOF resolution")( + "verbose,v", bpo::value()->default_value(0), "Verbose level 0, 1")( + "help,h", "Produce help message."); + try { + bpo::store(parse_command_line(argc, argv, options), vm); + + // help + if (vm.count("help")) { + LOG(INFO) << options; + return false; + } + + bpo::notify(vm); + } catch (const bpo::error& e) { + LOG(ERROR) << e.what() << "\n"; + LOG(ERROR) << "Error parsing command line arguments; Available options:"; + LOG(ERROR) << options; + return false; + } + return true; +} + +int main(int argc, char* argv[]) +{ + bpo::options_description options("Allowed options"); + bpo::variables_map vm; + if (!initOptionsAndParse(options, argc, argv, vm)) { + return 1; + } + + const unsigned int mode = vm["mode"].as(); + const std::string path = vm["ccdb-path"].as(); + std::map metadata; + std::map* headers; + o2::ccdb::CcdbApi api; + const std::string url = vm["url"].as(); + api.init(url); + if (!api.isHostReachable()) { + LOG(WARNING) << "CCDB host " << url << " is not reacheable, cannot go forward"; + return 1; + } + TOFResoALICE3* reso = nullptr; + const std::string reso_name = vm["reso-name"].as(); + if (mode == 0) { // Push mode + LOG(INFO) << "Handling TOF parametrization in create mode"; + const std::string input_file_name = vm["read-from-file"].as(); + if (!input_file_name.empty()) { + TFile f(input_file_name.data(), "READ"); + if (!f.IsOpen()) { + LOG(WARNING) << "Input file " << input_file_name << " is not reacheable, cannot get param from file"; + } + f.GetObject(reso_name.c_str(), reso); + f.Close(); + } + if (!reso) { + reso = new TOFResoALICE3(); + const std::vector resoparams = {vm["p0"].as()}; + reso->SetParameters(resoparams); + } + reso->Print(); + const std::string fname = vm["save-to-file"].as(); + if (!fname.empty()) { // Saving it to file + LOG(INFO) << "Saving parametrization to file " << fname; + TFile f(fname.data(), "RECREATE"); + reso->Write(); + reso->GetParameters().Write(); + f.ls(); + f.Close(); + } else { // Saving it to CCDB + LOG(INFO) << "Saving parametrization to CCDB " << path; + + long start = vm["start"].as(); + long stop = vm["stop"].as(); + + if (vm["delete-previous"].as()) { + api.truncate(path); + } + api.storeAsTFileAny(reso, path + "/" + reso_name, metadata, start, stop); + o2::pid::Parameters* params; + reso->GetParameters(params); + api.storeAsTFileAny(params, path + "/Parameters/" + reso_name, metadata, start, stop); + } + } else { // Pull and test mode + LOG(INFO) << "Handling TOF parametrization in test mode"; + const float x[7] = {1, 1, 1, 1, 1, 1, 1}; // mom, time, ev. reso, mass, length, sigma1pt, pt + reso = api.retrieveFromTFileAny(path + "/" + reso_name, metadata, -1, headers); + reso->Print(); + LOG(INFO) << "TOF expected resolution at p=" << x[0] << " GeV/c " + << " and mass " << x[3] << ":" << reso->operator()(x); + } + + return 0; +} diff --git a/Analysis/DataModel/src/handleParamTPCBetheBloch.cxx b/Analysis/DataModel/src/handleParamTPCBetheBloch.cxx index cd3d7b33496ba..f0bddf71eb675 100644 --- a/Analysis/DataModel/src/handleParamTPCBetheBloch.cxx +++ b/Analysis/DataModel/src/handleParamTPCBetheBloch.cxx @@ -29,12 +29,22 @@ bool initOptionsAndParse(bpo::options_description& options, int argc, char* argv { options.add_options()( "url,u", bpo::value()->default_value("http://ccdb-test.cern.ch:8080"), "URL of the CCDB database")( + "ccdb-path,c", bpo::value()->default_value("Analysis/PID/TPC"), "CCDB path for storage/retrieval")( "start,s", bpo::value()->default_value(0), "Start timestamp of object validity")( "stop,S", bpo::value()->default_value(4108971600000), "Stop timestamp of object validity")( - "delete-previous,d", bpo::value()->default_value(0), "Flag to delete previous versions of converter objects in the CCDB before uploading the new one so as to avoid proliferation on CCDB")( - "save-to-file,f", bpo::value()->default_value(""), "Option to save parametrization to file instead of uploading to ccdb")( - "read-from-file", bpo::value()->default_value(""), "Option to get parametrization from a file")( - "mode,m", bpo::value()->default_value(0), "Working mode: 0 push 1 pull and test")( + "delete-previous,delete_previous,d", bpo::value()->default_value(0), "Flag to delete previous versions of converter objects in the CCDB before uploading the new one so as to avoid proliferation on CCDB")( + "save-to-file,file,f,o", bpo::value()->default_value(""), "Option to save parametrization to file instead of uploading to ccdb")( + "read-from-file,i", bpo::value()->default_value(""), "Option to get parametrization from a file")( + "exp-name,n", bpo::value()->default_value("BetheBloch"), "Name of the parametrization object")( + "reso-name,n", bpo::value()->default_value("TPCReso"), "Name of the parametrization object")( + "mode,m", bpo::value()->default_value(1), "Working mode: 0 push 1 pull and test")( + "p0", bpo::value()->default_value(0.0320981), "Parameter 0 of the TPC expected value")( + "p1", bpo::value()->default_value(19.9768), "Parameter 1 of the TPC expected value")( + "p2", bpo::value()->default_value(2.52666e-16), "Parameter 2 of the TPC expected value")( + "p3", bpo::value()->default_value(2.72123), "Parameter 3 of the TPC expected value")( + "p4", bpo::value()->default_value(6.08092), "Parameter 4 of the TPC expected value")( + "p5", bpo::value()->default_value(50.f), "Parameter 5 of the TPC expected value")( + "p6", bpo::value()->default_value(2.3), "Parameter 6 of the TPC expected value")( "verbose,v", bpo::value()->default_value(0), "Verbose level 0, 1")( "help,h", "Produce help message."); try { @@ -65,7 +75,7 @@ int main(int argc, char* argv[]) } const unsigned int mode = vm["mode"].as(); - const std::string path = "Analysis/PID/TPC"; + const std::string path = vm["ccdb-path"].as(); std::map metadata; std::map* headers; o2::ccdb::CcdbApi api; @@ -75,23 +85,25 @@ int main(int argc, char* argv[]) LOG(WARNING) << "CCDB host " << url << " is not reacheable, cannot go forward"; return 1; } + BetheBloch* bb = nullptr; + TPCReso* reso = nullptr; + const std::string exp_name = vm["exp-name"].as(); + const std::string reso_name = vm["reso-name"].as(); if (mode == 0) { // Push mode - BetheBloch* bb = nullptr; - TPCReso* reso = nullptr; + LOG(INFO) << "Handling TPC parametrization in create mode"; const std::string input_file_name = vm["read-from-file"].as(); - if (!input_file_name.empty()) { TFile f(input_file_name.data(), "READ"); if (!f.IsOpen()) { LOG(WARNING) << "Input file " << input_file_name << " is not reacheable, cannot get param from file"; } - f.GetObject("BetheBloch", bb); - f.GetObject("TPCReso", reso); + f.GetObject(exp_name.c_str(), bb); + f.GetObject(reso_name.c_str(), reso); f.Close(); } if (!bb) { bb = new BetheBloch(); - const std::vector bbparams = {0.0320981, 19.9768, 2.52666e-16, 2.72123, 6.08092, 50.f, 2.3}; + const std::vector bbparams = {vm["p0"].as(), vm["p1"].as(), vm["p2"].as(), vm["p3"].as(), vm["p4"].as(), vm["p5"].as(), vm["p6"].as()}; bb->SetParameters(bbparams); } if (!reso) { @@ -99,14 +111,19 @@ int main(int argc, char* argv[]) const std::vector resoparams = {0.07, 0.0}; reso->SetParameters(resoparams); } + bb->Print(); const std::string fname = vm["save-to-file"].as(); if (!fname.empty()) { // Saving it to file + LOG(INFO) << "Saving parametrization to file " << fname; TFile f(fname.data(), "RECREATE"); bb->Write(); + bb->GetParameters().Write(); reso->Write(); + reso->GetParameters().Write(); f.ls(); f.Close(); } else { // Saving it to CCDB + LOG(INFO) << "Saving parametrization to CCDB " << path; long start = vm["start"].as(); long stop = vm["stop"].as(); @@ -114,16 +131,22 @@ int main(int argc, char* argv[]) if (vm["delete-previous"].as()) { api.truncate(path); } - api.storeAsTFileAny(bb, path + "/BetheBloch", metadata, start, stop); - api.storeAsTFileAny(reso, path + "/TPCReso", metadata, start, stop); + api.storeAsTFileAny(bb, path + "/" + exp_name, metadata, start, stop); + o2::pid::Parameters* params; + bb->GetParameters(params); + api.storeAsTFileAny(params, path + "/Parameters/" + exp_name, metadata, start, stop); + api.storeAsTFileAny(reso, path + "/" + reso_name, metadata, start, stop); + reso->GetParameters(params); + api.storeAsTFileAny(params, path + "/Parameters/" + reso_name, metadata, start, stop); } } else { // Pull and test mode + LOG(INFO) << "Handling TPC parametrization in test mode"; const float x[2] = {1, 1}; - BetheBloch* bb = api.retrieveFromTFileAny(path + "/BetheBloch", metadata, -1, headers); - bb->PrintParametrization(); + BetheBloch* bb = api.retrieveFromTFileAny(path + "/" + exp_name, metadata, -1, headers); + bb->Print(); LOG(INFO) << "BetheBloch " << bb->operator()(x); - TPCReso* reso = api.retrieveFromTFileAny(path + "/TPCReso", metadata, -1, headers); - reso->PrintParametrization(); + TPCReso* reso = api.retrieveFromTFileAny(path + "/" + reso_name, metadata, -1, headers); + reso->Print(); LOG(INFO) << "TPCReso " << reso->operator()(x); } diff --git a/Analysis/Tasks/PID/CMakeLists.txt b/Analysis/Tasks/PID/CMakeLists.txt index 86725c40682d9..ebe0493dde5f9 100644 --- a/Analysis/Tasks/PID/CMakeLists.txt +++ b/Analysis/Tasks/PID/CMakeLists.txt @@ -8,6 +8,8 @@ # granted to it by virtue of its status as an Intergovernmental Organization or # submit itself to any jurisdiction. +# TOF + o2_add_dpl_workflow(pid-tof SOURCES pidTOF.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore @@ -18,11 +20,18 @@ o2_add_dpl_workflow(pid-tof-beta PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore COMPONENT_NAME Analysis) +o2_add_dpl_workflow(pid-tof-qa-mc + SOURCES qaTOFMC.cxx + PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore + COMPONENT_NAME Analysis) + o2_add_dpl_workflow(pid-tof-tiny SOURCES pidTOF_tiny.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore COMPONENT_NAME Analysis) +# TPC + o2_add_dpl_workflow(pid-tpc SOURCES pidTPC.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore @@ -32,3 +41,10 @@ o2_add_dpl_workflow(pid-tpc-tiny SOURCES pidTPC_tiny.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore COMPONENT_NAME Analysis) + +# HMPID + +o2_add_dpl_workflow(pid-hmpid-qa + SOURCES qaHMPID.cxx + PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore + COMPONENT_NAME Analysis) diff --git a/Analysis/Tasks/PID/pidTOF.cxx b/Analysis/Tasks/PID/pidTOF.cxx index 2246921408457..d6b77ba8e89b8 100644 --- a/Analysis/Tasks/PID/pidTOF.cxx +++ b/Analysis/Tasks/PID/pidTOF.cxx @@ -141,13 +141,23 @@ struct pidTOFTaskQA { "nsigma/Tr", "nsigma/He", "nsigma/Al"}; HistogramRegistry histos{"Histos", {}, OutputObjHandlingPolicy::QAObject}; + Configurable logAxis{"logAxis", 1, "Flag to use a log momentum axis"}; Configurable nBinsP{"nBinsP", 400, "Number of bins for the momentum"}; - Configurable MinP{"MinP", 0.1, "Minimum momentum in range"}; - Configurable MaxP{"MaxP", 5, "Maximum momentum in range"}; + Configurable MinP{"MinP", 0.1f, "Minimum momentum in range"}; + Configurable MaxP{"MaxP", 5.f, "Maximum momentum in range"}; + Configurable nBinsDelta{"nBinsDelta", 200, "Number of bins for the Delta"}; + Configurable MinDelta{"MinDelta", -1000.f, "Minimum Delta in range"}; + Configurable MaxDelta{"MaxDelta", 1000.f, "Maximum Delta in range"}; + Configurable nBinsNSigma{"nBinsNSigma", 200, "Number of bins for the NSigma"}; + Configurable MinNSigma{"MinNSigma", -10.f, "Minimum NSigma in range"}; + Configurable MaxNSigma{"MaxNSigma", 10.f, "Maximum NSigma in range"}; template void makelogaxis(T h) { + if (logAxis == 0) { + return; + } const int nbins = h->GetNbinsX(); double binp[nbins + 1]; double max = h->GetXaxis()->GetBinUpEdge(nbins); @@ -172,11 +182,11 @@ struct pidTOFTaskQA { makelogaxis(histos.get(HIST(hexpected[i]))); // T-Texp - histos.add(hexpected_diff[i].data(), Form(";#it{p} (GeV/#it{c});(t-t_{evt}-t_{exp}(%s))", pT[i]), HistType::kTH2F, {{nBinsP, MinP, MaxP}, {100, -1000, 1000}}); + histos.add(hexpected_diff[i].data(), Form(";#it{p} (GeV/#it{c});(t-t_{evt}-t_{exp}(%s))", pT[i]), HistType::kTH2F, {{nBinsP, MinP, MaxP}, {nBinsDelta, MinDelta, MaxDelta}}); makelogaxis(histos.get(HIST(hexpected_diff[i]))); // NSigma - histos.add(hnsigma[i].data(), Form(";#it{p} (GeV/#it{c});N_{#sigma}^{TOF}(%s)", pT[i]), HistType::kTH2F, {{nBinsP, MinP, MaxP}, {200, -10, 10}}); + histos.add(hnsigma[i].data(), Form(";#it{p} (GeV/#it{c});N_{#sigma}^{TOF}(%s)", pT[i]), HistType::kTH2F, {{nBinsP, MinP, MaxP}, {nBinsNSigma, MinNSigma, MaxNSigma}}); makelogaxis(histos.get(HIST(hnsigma[i]))); } @@ -227,6 +237,9 @@ struct pidTOFTaskQA { if (t.tofSignal() < 0) { // Skipping tracks without TOF continue; } + if (!t.isGlobalTrack()) { + continue; + } const float tof = t.tofSignal() - collisionTime_ps; diff --git a/Analysis/Tasks/PID/pidTOF_tiny.cxx b/Analysis/Tasks/PID/pidTOF_tiny.cxx index c7759445f609e..3d946bb3d38bb 100644 --- a/Analysis/Tasks/PID/pidTOF_tiny.cxx +++ b/Analysis/Tasks/PID/pidTOF_tiny.cxx @@ -39,7 +39,7 @@ void customize(std::vector& workflowOptions) #include "Framework/runDataProcessing.h" struct pidTOFTaskTiny { - using Trks = soa::Join; + using Trks = soa::Join; using Coll = aod::Collisions; // Tables to produce Produces tablePIDEl; diff --git a/Analysis/Tasks/PID/pidTPC.cxx b/Analysis/Tasks/PID/pidTPC.cxx index cb4bcc57bb113..9c1c53a0e2eac 100644 --- a/Analysis/Tasks/PID/pidTPC.cxx +++ b/Analysis/Tasks/PID/pidTPC.cxx @@ -91,7 +91,7 @@ struct pidTPCTaskSplit { } template - using ResponseImplementation = tpc::ELoss; + using ResponseImplementation = o2::pid::tpc::ELoss; void process(Coll const& collisions, Trks const& tracks) { constexpr auto responseEl = ResponseImplementation(); diff --git a/Analysis/Tasks/PID/pidTPC_tiny.cxx b/Analysis/Tasks/PID/pidTPC_tiny.cxx index 0d918702774d2..14e25070d28e7 100644 --- a/Analysis/Tasks/PID/pidTPC_tiny.cxx +++ b/Analysis/Tasks/PID/pidTPC_tiny.cxx @@ -91,7 +91,7 @@ struct pidTPCTaskTiny { } template - using ResponseImplementation = tpc::ELoss; + using ResponseImplementation = o2::pid::tpc::ELoss; void process(Coll const& collisions, Trks const& tracks) { constexpr auto responseEl = ResponseImplementation(); diff --git a/Analysis/Tasks/PID/qaHMPID.cxx b/Analysis/Tasks/PID/qaHMPID.cxx new file mode 100644 index 0000000000000..554da99a27884 --- /dev/null +++ b/Analysis/Tasks/PID/qaHMPID.cxx @@ -0,0 +1,99 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +// O2 includes +#include "ReconstructionDataFormats/Track.h" +#include "Framework/runDataProcessing.h" +#include "Framework/AnalysisTask.h" +#include "Framework/AnalysisDataModel.h" +#include "Framework/ASoAHelpers.h" +#include "AnalysisDataModel/TrackSelectionTables.h" +#include "AnalysisCore/MC.h" +#include "AnalysisDataModel/TrackSelectionTables.h" +#include "AnalysisDataModel/TrackSelectionTables.h" + +using namespace o2; +using namespace o2::framework; +using namespace o2::framework::expressions; + +struct pidHMPIDQA { + HistogramRegistry histos{"Histos", {}, OutputObjHandlingPolicy::QAObject}; + Configurable nBinsP{"nBinsP", 500, "Number of momentum bins"}; + Configurable minP{"minP", 0.01, "Minimum momentum plotted (GeV/c)"}; + Configurable maxP{"maxP", 10, "Maximum momentum plotted (GeV/c)"}; + Configurable maxDCA{"maxDCA", 3, "Maximum DCA xy use for the plot (cm)"}; + + template + void makelogaxis(T h) + { + // return; + const int nbins = h->GetNbinsX(); + double binp[nbins + 1]; + double max = h->GetXaxis()->GetBinUpEdge(nbins); + double min = h->GetXaxis()->GetBinLowEdge(1); + if (min <= 0) { + min = 0.00001; + } + double lmin = TMath::Log10(min); + double ldelta = (TMath::Log10(max) - lmin) / ((double)nbins); + for (int i = 0; i < nbins; i++) { + binp[i] = TMath::Exp(TMath::Log(10) * (lmin + i * ldelta)); + } + binp[nbins] = max + 1; + h->GetXaxis()->Set(nbins, binp); + } + + void init(o2::framework::InitContext&) + { + AxisSpec momAxis{nBinsP, minP, maxP}; + histos.add("qa/signalvsP", ";#it{p} (GeV/#it{c});Cherenkov angle (rad)", kTH2F, {momAxis, {1000, 0, 1}}); + histos.add("distance/selected", ";HMPID distance", kTH1F, {{100, 0, 20}}); + histos.add("distance/nonselected", ";HMPID distance", kTH1F, {{100, 0, 20}}); + histos.add("qmip/selected", ";HMPID mip charge (ADC)", kTH1F, {{100, 0, 4000}}); + histos.add("qmip/nonselected", ";HMPID mip charge (ADC)", kTH1F, {{100, 0, 4000}}); + histos.add("nphotons/selected", ";HMPID number of detected photons", kTH1F, {{100, 0, 1000}}); + histos.add("nphotons/nonselected", ";HMPID number of detected photons", kTH1F, {{100, 0, 1000}}); + } + + using TrackCandidates = soa::Join; + void process(const TrackCandidates& tracks, + const aod::HMPIDs& hmpids, + const aod::Collisions& colls) + { + for (const auto& t : hmpids) { + + if (t.track_as().isGlobalTrack() != (uint8_t) true) { + continue; + } + if (abs(t.track_as().dcaXY()) > maxDCA) { + continue; + } + histos.fill(HIST("distance/nonselected"), t.hmpidDistance()); + histos.fill(HIST("qmip/nonselected"), t.hmpidQMip()); + histos.fill(HIST("nphotons/nonselected"), t.hmpidNPhotons()); + if (t.hmpidDistance() > 5.f) { + continue; + } + if (t.hmpidQMip() < 120.f) { + continue; + } + histos.fill(HIST("distance/selected"), t.hmpidDistance()); + histos.fill(HIST("qmip/selected"), t.hmpidQMip()); + histos.fill(HIST("nphotons/selected"), t.hmpidNPhotons()); + histos.fill(HIST("qa/signalvsP"), t.track_as().p(), t.hmpidSignal()); + } + } +}; + +WorkflowSpec defineDataProcessing(ConfigContext const& cfg) +{ + WorkflowSpec workflow{adaptAnalysisTask(cfg, TaskName{"pidHMPID-qa"})}; + return workflow; +} diff --git a/Analysis/Tasks/PID/pidTOFqa.cxx b/Analysis/Tasks/PID/qaTOFMC.cxx similarity index 99% rename from Analysis/Tasks/PID/pidTOFqa.cxx rename to Analysis/Tasks/PID/qaTOFMC.cxx index b0335451b47c9..eb3caad2fe49b 100644 --- a/Analysis/Tasks/PID/pidTOFqa.cxx +++ b/Analysis/Tasks/PID/qaTOFMC.cxx @@ -102,7 +102,7 @@ struct pidTOFTaskQA { void init(o2::framework::InitContext&) { - histos.add("event/T0", ";Tracks with TOF;T0 (ps);Counts", HistType::kTH2F, {{1000, 0, 100}, {1000, -600, 600}}); + histos.add("event/T0", ";Tracks with TOF;T0 (ps);Counts", HistType::kTH2F, {{1000, 0, 1000}, {1000, -1000, 1000}}); histos.add(hnsigma[pid_type].data(), Form(";#it{p}_{T} (GeV/#it{c});N_{#sigma}^{TOF}(%s)", pT[pid_type]), HistType::kTH2F, {{nBinsP, MinP, MaxP}, {2000, -30, 30}}); makelogaxis(histos.get(HIST(hnsigma[pid_type]))); histos.add(hnsigmaprm[pid_type].data(), Form("Primary;#it{p}_{T} (GeV/#it{c});N_{#sigma}^{TOF}(%s)", pT[pid_type]), HistType::kTH2F, {{nBinsP, MinP, MaxP}, {2000, -30, 30}}); diff --git a/Framework/Core/include/Framework/AnalysisDataModel.h b/Framework/Core/include/Framework/AnalysisDataModel.h index 42997095efe56..b48ac2f60ae8e 100644 --- a/Framework/Core/include/Framework/AnalysisDataModel.h +++ b/Framework/Core/include/Framework/AnalysisDataModel.h @@ -486,6 +486,7 @@ namespace hmpid DECLARE_SOA_INDEX_COLUMN(Track, track); //! DECLARE_SOA_COLUMN(HMPIDSignal, hmpidSignal, float); //! DECLARE_SOA_COLUMN(HMPIDDistance, hmpidDistance, float); //! +DECLARE_SOA_COLUMN(HMPIDNPhotons, hmpidNPhotons, short); //! DECLARE_SOA_COLUMN(HMPIDQMip, hmpidQMip, short); //! } // namespace hmpid @@ -494,6 +495,7 @@ DECLARE_SOA_TABLE(HMPIDs, "AOD", "HMPID", //! hmpid::TrackId, hmpid::HMPIDSignal, hmpid::HMPIDDistance, + hmpid::HMPIDNPhotons, hmpid::HMPIDQMip); using HMPID = HMPIDs::iterator; From e9ab6a6ef547dd941a44276802048a76d783f0dc Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 23 Apr 2021 19:09:01 +0200 Subject: [PATCH 269/770] GPU Workflow: Move TPC CA Tracker Spec into GPU workflow --- Detectors/TPC/workflow/CMakeLists.txt | 6 ++--- Detectors/TPC/workflow/src/RecoWorkflow.cxx | 6 ++--- GPU/Workflow/CMakeLists.txt | 10 +++++++- .../include/GPUWorkflow/GPUWorkflowSpec.h | 20 +++++++++------- .../Workflow/src/GPUWorkflowSpec.cxx | 23 ++++++++----------- 5 files changed, 35 insertions(+), 30 deletions(-) rename Detectors/TPC/workflow/include/TPCWorkflow/CATrackerSpec.h => GPU/Workflow/include/GPUWorkflow/GPUWorkflowSpec.h (81%) rename Detectors/TPC/workflow/src/CATrackerSpec.cxx => GPU/Workflow/src/GPUWorkflowSpec.cxx (98%) diff --git a/Detectors/TPC/workflow/CMakeLists.txt b/Detectors/TPC/workflow/CMakeLists.txt index 4fdf431c3a2e3..6307211f40e37 100644 --- a/Detectors/TPC/workflow/CMakeLists.txt +++ b/Detectors/TPC/workflow/CMakeLists.txt @@ -8,15 +8,12 @@ # granted to it by virtue of its status as an Intergovernmental Organization or # submit itself to any jurisdiction. - -# FIXME: do we really need a library here ? Is the exe not enough ? o2_add_library(TPCWorkflow SOURCES src/RecoWorkflow.cxx src/ClusterReaderSpec.cxx src/PublisherSpec.cxx src/ClustererSpec.cxx src/ClusterDecoderRawSpec.cxx - src/CATrackerSpec.cxx src/EntropyEncoderSpec.cxx src/EntropyDecoderSpec.cxx src/TrackReaderSpec.cxx @@ -33,7 +30,8 @@ o2_add_library(TPCWorkflow PUBLIC_LINK_LIBRARIES O2::Framework O2::DataFormatsTPC O2::DPLUtils O2::TPCReconstruction O2::TPCCalibration O2::TPCSimulation - O2::TPCQC O2::DetectorsCalibration) + O2::TPCQC O2::DetectorsCalibration + O2::GPUWorkflow) o2_add_executable(chunkeddigit-merger diff --git a/Detectors/TPC/workflow/src/RecoWorkflow.cxx b/Detectors/TPC/workflow/src/RecoWorkflow.cxx index 804b5cc1fb6e8..9a6cb1b879303 100644 --- a/Detectors/TPC/workflow/src/RecoWorkflow.cxx +++ b/Detectors/TPC/workflow/src/RecoWorkflow.cxx @@ -21,7 +21,7 @@ #include "TPCWorkflow/PublisherSpec.h" #include "TPCWorkflow/ClustererSpec.h" #include "TPCWorkflow/ClusterDecoderRawSpec.h" -#include "TPCWorkflow/CATrackerSpec.h" +#include "GPUWorkflow/GPUWorkflowSpec.h" #include "TPCWorkflow/EntropyEncoderSpec.h" #include "TPCWorkflow/ZSSpec.h" #include "Algorithm/RangeTokenizer.h" @@ -413,7 +413,7 @@ framework::WorkflowSpec getWorkflow(CompletionPolicyData* policyData, std::vecto // // selected by output type 'tracks' if (runTracker) { - ca::Config cfg; + o2::gpu::GPUWorkflow::Config cfg; cfg.decompressTPC = decompressTPC; cfg.decompressTPCFromROOT = decompressTPC && inputType == InputType::CompClusters; cfg.caClusterer = caClusterer; @@ -428,7 +428,7 @@ framework::WorkflowSpec getWorkflow(CompletionPolicyData* policyData, std::vecto cfg.processMC = propagateMC; cfg.sendClustersPerSector = isEnabled(OutputType::SendClustersPerSector); cfg.askDISTSTF = askDISTSTF; - specs.emplace_back(o2::tpc::getCATrackerSpec(policyData, cfg, tpcSectors, tpcSectorMask)); + specs.emplace_back(o2::gpu::getGPURecoWorkflowSpec(policyData, cfg, tpcSectors, tpcSectorMask)); } ////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/GPU/Workflow/CMakeLists.txt b/GPU/Workflow/CMakeLists.txt index 9e76b078642cf..3ffda134d2092 100644 --- a/GPU/Workflow/CMakeLists.txt +++ b/GPU/Workflow/CMakeLists.txt @@ -7,7 +7,15 @@ # In applying this license CERN does not waive the privileges and immunities # granted to it by virtue of its status as an Intergovernmental Organization or # submit itself to any jurisdiction. - + +o2_add_library(GPUWorkflow + SOURCES src/GPUWorkflowSpec.cxx + TARGETVARNAME targetName + PUBLIC_LINK_LIBRARIES O2::Framework O2::DataFormatsTPC + O2::DPLUtils O2::TPCReconstruction + O2::TPCCalibration O2::TPCSimulation + O2::TPCQC O2::DetectorsCalibration) + o2_add_executable(display COMPONENT_NAME gpu TARGETVARNAME targetName diff --git a/Detectors/TPC/workflow/include/TPCWorkflow/CATrackerSpec.h b/GPU/Workflow/include/GPUWorkflow/GPUWorkflowSpec.h similarity index 81% rename from Detectors/TPC/workflow/include/TPCWorkflow/CATrackerSpec.h rename to GPU/Workflow/include/GPUWorkflow/GPUWorkflowSpec.h index cfea1793149b5..4c8e22555de12 100644 --- a/Detectors/TPC/workflow/include/TPCWorkflow/CATrackerSpec.h +++ b/GPU/Workflow/include/GPUWorkflow/GPUWorkflowSpec.h @@ -8,13 +8,15 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file CATrackerSpec.h +/// @file GPURecoWorkflowSpec.h /// @author Matthias Richter /// @since 2018-04-18 /// @brief Processor spec for running TPC CA tracking +#ifndef O2_GPU_WORKFLOW_SPEC_H +#define O2_GPU_WORKFLOW_SPEC_H + #include "Framework/DataProcessorSpec.h" -#include "RecoWorkflow.h" #include // std::forward namespace o2 @@ -24,10 +26,9 @@ namespace framework struct CompletionPolicy; } -namespace tpc +namespace gpu { - -namespace ca +namespace GPUWorkflow { struct Config { bool decompressTPC = false; @@ -45,7 +46,8 @@ struct Config { bool sendClustersPerSector = false; bool askDISTSTF = true; }; -} // namespace ca +using CompletionPolicyData = std::vector; +} // namespace GPUWorkflow /// create a processor spec for the CATracker /// The CA tracker is actually much more than the tracker it has evolved to a @@ -63,8 +65,10 @@ struct Config { /// /// @param specconfig configuration options for the processor spec /// @param tpcsectors list of sector numbers -framework::DataProcessorSpec getCATrackerSpec(o2::tpc::reco_workflow::CompletionPolicyData* policyData, ca::Config const& specconfig, std::vector const& tpcsectors, unsigned long tpcSectorMask); +framework::DataProcessorSpec getGPURecoWorkflowSpec(GPUWorkflow::CompletionPolicyData* policyData, GPUWorkflow::Config const& specconfig, std::vector const& tpcsectors, unsigned long tpcSectorMask); o2::framework::CompletionPolicy getCATrackerCompletionPolicy(); -} // end namespace tpc +} // end namespace gpu } // end namespace o2 + +#endif // O2_GPU_WORKFLOW_SPEC_H diff --git a/Detectors/TPC/workflow/src/CATrackerSpec.cxx b/GPU/Workflow/src/GPUWorkflowSpec.cxx similarity index 98% rename from Detectors/TPC/workflow/src/CATrackerSpec.cxx rename to GPU/Workflow/src/GPUWorkflowSpec.cxx index 08fe4e96e1f80..e6b0c0d2648e9 100644 --- a/Detectors/TPC/workflow/src/CATrackerSpec.cxx +++ b/GPU/Workflow/src/GPUWorkflowSpec.cxx @@ -8,12 +8,12 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// @file CATrackerSpec.cxx +/// @file GPUWorkflowSpec.cxx /// @author Matthias Richter /// @since 2018-04-18 /// @brief Processor spec for running TPC CA tracking -#include "TPCWorkflow/CATrackerSpec.h" +#include "GPUWorkflow/GPUWorkflowSpec.h" #include "Headers/DataHeader.h" #include "Framework/WorkflowSpec.h" // o2::framework::mergeInputs #include "Framework/DataRefUtils.h" @@ -79,14 +79,11 @@ using namespace o2::header; using namespace o2::gpu; using namespace o2::base; using namespace o2::dataformats; -using namespace o2::tpc::reco_workflow; +using namespace o2::tpc; -namespace o2 +namespace o2::gpu { -namespace tpc -{ - -DataProcessorSpec getCATrackerSpec(CompletionPolicyData* policyData, ca::Config const& specconfig, std::vector const& tpcsectors, unsigned long tpcSectorMask) +DataProcessorSpec getGPURecoWorkflowSpec(GPUWorkflow::CompletionPolicyData* policyData, GPUWorkflow::Config const& specconfig, std::vector const& tpcsectors, unsigned long tpcSectorMask) { if (specconfig.outputCAClusters && !specconfig.caClusterer && !specconfig.decompressTPC) { throw std::runtime_error("inconsistent configuration: cluster output is only possible if CA clusterer is activated"); @@ -157,7 +154,7 @@ DataProcessorSpec getCATrackerSpec(CompletionPolicyData* policyData, ca::Config } if (config.configGRP.continuousMaxTimeBin == -1) { - config.configGRP.continuousMaxTimeBin = (o2::raw::HBFUtils::Instance().getNOrbitsPerTF() * o2::constants::lhc::LHCMaxBunches + 2 * constants::LHCBCPERTIMEBIN - 2) / constants::LHCBCPERTIMEBIN; + config.configGRP.continuousMaxTimeBin = (o2::raw::HBFUtils::Instance().getNOrbitsPerTF() * o2::constants::lhc::LHCMaxBunches + 2 * o2::tpc::constants::LHCBCPERTIMEBIN - 2) / o2::tpc::constants::LHCBCPERTIMEBIN; } if (config.configProcessing.deviceNum == -2) { int myId = ic.services().get().inputTimesliceId; @@ -657,7 +654,7 @@ DataProcessorSpec getCATrackerSpec(CompletionPolicyData* policyData, ca::Config char* buffer = pc.outputs().make({gDataOriginTPC, "CLUSTERNATIVE", subspec, Lifetime::Timeframe, {clusterOutputSectorHeader}}, accessIndex.nClustersSector[i] * sizeof(*accessIndex.clustersLinear) + sizeof(ClusterCountIndex)).data(); ClusterCountIndex* outIndex = reinterpret_cast(buffer); memset(outIndex, 0, sizeof(*outIndex)); - for (int j = 0; j < constants::MAXGLOBALPADROW; j++) { + for (int j = 0; j < o2::tpc::constants::MAXGLOBALPADROW; j++) { outIndex->nClusters[i][j] = accessIndex.nClusters[i][j]; } memcpy(buffer + sizeof(*outIndex), accessIndex.clusters[i][0], accessIndex.nClustersSector[i] * sizeof(*accessIndex.clustersLinear)); @@ -709,7 +706,7 @@ DataProcessorSpec getCATrackerSpec(CompletionPolicyData* policyData, ca::Config auto createInputSpecs = [&tpcsectors, &specconfig, policyData]() { Inputs inputs; if (specconfig.decompressTPC) { - inputs.emplace_back(InputSpec{"input", ConcreteDataTypeMatcher{gDataOriginTPC, specconfig.decompressTPCFromROOT ? header::DataDescription("COMPCLUSTERS") : header::DataDescription("COMPCLUSTERSFLAT")}, Lifetime::Timeframe}); + inputs.emplace_back(InputSpec{"input", ConcreteDataTypeMatcher{gDataOriginTPC, specconfig.decompressTPCFromROOT ? o2::header::DataDescription("COMPCLUSTERS") : o2::header::DataDescription("COMPCLUSTERSFLAT")}, Lifetime::Timeframe}); } else if (specconfig.caClusterer) { // We accept digits and MC labels also if we run on ZS Raw data, since they are needed for MC label propagation if ((!specconfig.zsOnTheFly || specconfig.processMC) && !specconfig.zsDecoder) { @@ -799,6 +796,4 @@ DataProcessorSpec getCATrackerSpec(CompletionPolicyData* policyData, ca::Config {createOutputSpecs()}, AlgorithmSpec(initFunction)}; } - -} // namespace tpc -} // namespace o2 +} // namespace o2::gpu From 274cfcab0838ca49abd03d5d38ece297e7578baf Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 23 Apr 2021 00:19:26 +0200 Subject: [PATCH 270/770] GPU Workflow: Rename the tpc-tracker process into gpu-reconstruction --- Detectors/TPC/workflow/README.md | 2 +- Detectors/TPC/workflow/src/tpc-reco-workflow.cxx | 2 +- GPU/Workflow/src/GPUWorkflowSpec.cxx | 2 +- prodtests/full-system-test/dpl-workflow.sh | 2 +- prodtests/full_system_test.sh | 4 ++-- prodtests/full_system_test_pipeline.sh | 4 ++-- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Detectors/TPC/workflow/README.md b/Detectors/TPC/workflow/README.md index c72edb70e72e0..81ef1dfcbee42 100644 --- a/Detectors/TPC/workflow/README.md +++ b/Detectors/TPC/workflow/README.md @@ -18,7 +18,7 @@ The workflow consists of the following DPL processors: * `tpc-digit-reader` -> using tool [o2::framework::RootTreeReader](../../../Framework/Utils/include/Utils/RootTreeReader.h) * `tpc-clusterer` -> interfaces [o2::tpc::HwClusterer](../reconstruction/include/TPCReconstruction/HwClusterer.h) * `tpc-cluster-decoder` -> interfaces [o2::tpc::HardwareClusterDecoder](../reconstruction/include/TPCReconstruction/HardwareClusterDecoder.h) -* `tpc-tracker` -> interfaces [o2::tpc::GPUCATracking](../reconstruction/include/TPCReconstruction/GPUCATracking.h) +* `gpu-reconstruction` -> interfaces [o2::tpc::GPUCATracking](../reconstruction/include/TPCReconstruction/GPUCATracking.h) * `tpc-track-writer` -> implements simple writing to ROOT file Depending on the input and output types the default workflow is extended by the following readers and writers: diff --git a/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx b/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx index d460ccece3665..0c15bed320217 100644 --- a/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx +++ b/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx @@ -94,7 +94,7 @@ void customize(std::vector& policies) policies.push_back(CompletionPolicyHelpers::defineByName("tpc-cluster-decoder.*", CompletionPolicy::CompletionOp::Consume)); policies.push_back(CompletionPolicyHelpers::defineByName("tpc-clusterer.*", CompletionPolicy::CompletionOp::Consume)); // the custom completion policy for the tracker - policies.push_back(o2::tpc::TPCSectorCompletionPolicy("tpc-tracker.*", o2::tpc::TPCSectorCompletionPolicy::Config::RequireAll, &gPolicyData, &gTpcSectorMask)()); + policies.push_back(o2::tpc::TPCSectorCompletionPolicy("gpu-reconstruction.*", o2::tpc::TPCSectorCompletionPolicy::Config::RequireAll, &gPolicyData, &gTpcSectorMask)()); } #include "Framework/runDataProcessing.h" // the main driver diff --git a/GPU/Workflow/src/GPUWorkflowSpec.cxx b/GPU/Workflow/src/GPUWorkflowSpec.cxx index e6b0c0d2648e9..23ffba9117a4d 100644 --- a/GPU/Workflow/src/GPUWorkflowSpec.cxx +++ b/GPU/Workflow/src/GPUWorkflowSpec.cxx @@ -791,7 +791,7 @@ DataProcessorSpec getGPURecoWorkflowSpec(GPUWorkflow::CompletionPolicyData* poli return std::move(outputSpecs); }; - return DataProcessorSpec{"tpc-tracker", // process id + return DataProcessorSpec{"gpu-reconstruction", // process id {createInputSpecs()}, {createOutputSpecs()}, AlgorithmSpec(initFunction)}; diff --git a/prodtests/full-system-test/dpl-workflow.sh b/prodtests/full-system-test/dpl-workflow.sh index dad6677db1280..0203003fe4907 100755 --- a/prodtests/full-system-test/dpl-workflow.sh +++ b/prodtests/full-system-test/dpl-workflow.sh @@ -108,7 +108,7 @@ fi # Common workflows WORKFLOW+="o2-its-reco-workflow $ARGS_ALL --trackerCA $DISABLE_MC --clusters-from-upstream --disable-root-output $ITS_CONFIG --configKeyValues \"HBFUtils.nHBFPerTF=${NHBPERTF};$ITS_CONFIG_KEY\" | " -WORKFLOW+="o2-tpc-reco-workflow ${ARGS_ALL/--severity $SEVERITY/--severity $SEVERITY_TPC} --input-type=$TPC_INPUT $DISABLE_MC --output-type $TPC_OUTPUT --pipeline tpc-tracker:$NGPUS,tpc-entropy-encoder:$N_TPCENT $TPC_CONFIG --configKeyValues \"HBFUtils.nHBFPerTF=$NHBPERTF;GPU_global.deviceType=$GPUTYPE;GPU_proc.debugLevel=0;$TPC_CONFIG_KEY;$TPC_EXTRA_CONFIG\" | " +WORKFLOW+="o2-tpc-reco-workflow ${ARGS_ALL/--severity $SEVERITY/--severity $SEVERITY_TPC} --input-type=$TPC_INPUT $DISABLE_MC --output-type $TPC_OUTPUT --pipeline gpu-reconstruction:$NGPUS,tpc-entropy-encoder:$N_TPCENT $TPC_CONFIG --configKeyValues \"HBFUtils.nHBFPerTF=$NHBPERTF;GPU_global.deviceType=$GPUTYPE;GPU_proc.debugLevel=0;$TPC_CONFIG_KEY;$TPC_EXTRA_CONFIG\" | " WORKFLOW+="o2-tpcits-match-workflow $ARGS_ALL --disable-root-input --disable-root-output $DISABLE_MC --pipeline itstpc-track-matcher:$N_TPCITS --configKeyValues \"HBFUtils.nHBFPerTF=${NHBPERTF};\" | " WORKFLOW+="o2-ft0-reco-workflow $ARGS_ALL --disable-root-input --disable-root-output $DISABLE_MC --configKeyValues \"HBFUtils.nHBFPerTF=${NHBPERTF};\" | " WORKFLOW+="o2-tof-reco-workflow $ARGS_ALL --configKeyValues \"HBFUtils.nHBFPerTF=$NHBPERTF\" --input-type $TOF_INPUT --output-type $TOF_OUTPUT --disable-root-input --disable-root-output $DISABLE_MC | " diff --git a/prodtests/full_system_test.sh b/prodtests/full_system_test.sh index 78c410e9dd33d..bf4092403c76e 100755 --- a/prodtests/full_system_test.sh +++ b/prodtests/full_system_test.sh @@ -168,7 +168,7 @@ for STAGE in $STAGES; do echo "walltime_${STAGE},${TAG} value=${walltime}" >> ${METRICFILE} # GPU reconstruction (also in CPU version) processing time - gpurecotime=`grep "tpc-tracker" reco_NOGPU.log | grep -e "Total Wall Time:" | awk '//{printf "%f", $6/1000000}'` + gpurecotime=`grep "gpu-reconstruction" reco_NOGPU.log | grep -e "Total Wall Time:" | awk '//{printf "%f", $6/1000000}'` echo "gpurecotime_${STAGE},${TAG} value=${gpurecotime}" >> ${METRICFILE} # memory @@ -178,7 +178,7 @@ for STAGE in $STAGES; do echo "avgmem_${STAGE},${TAG} value=${avgmem}" >> ${METRICFILE} # some physics quantities - tpctracks=`grep "tpc-tracker" ${logfile} | grep -e "found.*track" | awk '//{print $4}'` + tpctracks=`grep "gpu-reconstruction" ${logfile} | grep -e "found.*track" | awk '//{print $4}'` echo "tpctracks_${STAGE},${TAG} value=${tpctracks}" >> ${METRICFILE} tpcclusters=`grep -e "Event has.*TPC Clusters" ${logfile} | awk '//{print $5}'` echo "tpcclusters_${STAGE},${TAG} value=${tpcclusters}" >> ${METRICFILE} diff --git a/prodtests/full_system_test_pipeline.sh b/prodtests/full_system_test_pipeline.sh index 7c597769dfb5e..235a590953d8e 100755 --- a/prodtests/full_system_test_pipeline.sh +++ b/prodtests/full_system_test_pipeline.sh @@ -88,7 +88,7 @@ for STAGE in $STAGES; do echo "walltime_${STAGE},${TAG} value=${walltime}" >> ${METRICFILE} # GPU reconstruction (also in CPU version) processing time - gpurecotime=`grep "tpc-tracker" reco_NOGPU.log | grep -e "Total Wall Time:" | awk '//{printf "%f", $6/1000000}'` + gpurecotime=`grep "gpu-reconstruction" reco_NOGPU.log | grep -e "Total Wall Time:" | awk '//{printf "%f", $6/1000000}'` echo "gpurecotime_${STAGE},${TAG} value=${gpurecotime}" >> ${METRICFILE} # memory @@ -98,7 +98,7 @@ for STAGE in $STAGES; do echo "avgmem_${STAGE},${TAG} value=${avgmem}" >> ${METRICFILE} # some physics quantities - tpctracks=`grep "tpc-tracker" ${logfile} | grep -e "found.*track" | awk '//{print $4}'` + tpctracks=`grep "gpu-reconstruction" ${logfile} | grep -e "found.*track" | awk '//{print $4}'` echo "tpctracks_${STAGE},${TAG} value=${tpctracks}" >> ${METRICFILE} tpcclusters=`grep -e "Event has.*TPC Clusters" ${logfile} | awk '//{print $5}'` echo "tpcclusters_${STAGE},${TAG} value=${tpcclusters}" >> ${METRICFILE} From 11b250bfa532e347b2e90ba709f92fcb5fe16b54 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 23 Apr 2021 16:18:10 +0200 Subject: [PATCH 271/770] GPU Workflow: Add a 'standalone' GPU workflow, currenly basically identical to the processing part of the tpc-reco-workflow, to be extended... --- .../src/cosmics-match-workflow.cxx | 2 +- .../src/tpcits-match-workflow.cxx | 2 +- .../src/tpc-interpolation-workflow.cxx | 2 +- Detectors/TPC/workflow/CMakeLists.txt | 1 - Detectors/TPC/workflow/src/RecoWorkflow.cxx | 4 +- .../src/TPCSectorCompletionPolicy.cxx | 25 --- .../TPC/workflow/src/TrackReaderWorkflow.cxx | 1 - .../TPC/workflow/src/tpc-reco-workflow.cxx | 4 +- GPU/Workflow/CMakeLists.txt | 7 + .../include/GPUWorkflow/GPUWorkflowSpec.h | 9 +- .../GPUWorkflow}/TPCSectorCompletionPolicy.h | 10 +- GPU/Workflow/src/GPUWorkflowSpec.cxx | 4 +- GPU/Workflow/src/gpu-reco-workflow.cxx | 146 ++++++++++++++++++ 13 files changed, 172 insertions(+), 45 deletions(-) delete mode 100644 Detectors/TPC/workflow/src/TPCSectorCompletionPolicy.cxx rename {Detectors/TPC/workflow/include/TPCWorkflow => GPU/Workflow/include/GPUWorkflow}/TPCSectorCompletionPolicy.h (96%) create mode 100644 GPU/Workflow/src/gpu-reco-workflow.cxx diff --git a/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx index 9829d6b347769..47a4c6a17d50f 100644 --- a/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx @@ -10,7 +10,7 @@ #include "CommonUtils/ConfigurableParam.h" #include "Framework/CompletionPolicy.h" -#include "TPCWorkflow/TPCSectorCompletionPolicy.h" +#include "GPUWorkflow/TPCSectorCompletionPolicy.h" #include "ITSWorkflow/TrackReaderSpec.h" #include "ITSMFTWorkflow/ClusterReaderSpec.h" #include "TPCWorkflow/TrackReaderSpec.h" diff --git a/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx index e4c5a5571415a..9cecf4aa08e22 100644 --- a/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx @@ -11,7 +11,7 @@ #include "GlobalTrackingWorkflow/MatchTPCITSWorkflow.h" #include "CommonUtils/ConfigurableParam.h" #include "Framework/CompletionPolicy.h" -#include "TPCWorkflow/TPCSectorCompletionPolicy.h" +#include "GPUWorkflow/TPCSectorCompletionPolicy.h" #include "DetectorsRaw/HBFUtilsInitializer.h" using namespace o2::framework; diff --git a/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/tpc-interpolation-workflow.cxx b/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/tpc-interpolation-workflow.cxx index 1cbbbbc62aaca..b49410add2878 100644 --- a/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/tpc-interpolation-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/tpc-interpolation-workflow.cxx @@ -11,7 +11,7 @@ #include "TPCInterpolationWorkflow/TrackInterpolationWorkflow.h" #include "CommonUtils/ConfigurableParam.h" #include "Framework/CompletionPolicy.h" -#include "TPCWorkflow/TPCSectorCompletionPolicy.h" +#include "GPUWorkflow/TPCSectorCompletionPolicy.h" #include "DetectorsRaw/HBFUtilsInitializer.h" using namespace o2::framework; diff --git a/Detectors/TPC/workflow/CMakeLists.txt b/Detectors/TPC/workflow/CMakeLists.txt index 6307211f40e37..b741b0fc3fd67 100644 --- a/Detectors/TPC/workflow/CMakeLists.txt +++ b/Detectors/TPC/workflow/CMakeLists.txt @@ -19,7 +19,6 @@ o2_add_library(TPCWorkflow src/TrackReaderSpec.cxx src/RawToDigitsSpec.cxx src/LinkZSToDigitsSpec.cxx - src/TPCSectorCompletionPolicy.cxx src/ZSSpec.cxx src/CalibProcessingHelper.cxx src/ClusterSharingMapSpec.cxx diff --git a/Detectors/TPC/workflow/src/RecoWorkflow.cxx b/Detectors/TPC/workflow/src/RecoWorkflow.cxx index 9a6cb1b879303..355ebb9407b60 100644 --- a/Detectors/TPC/workflow/src/RecoWorkflow.cxx +++ b/Detectors/TPC/workflow/src/RecoWorkflow.cxx @@ -413,7 +413,7 @@ framework::WorkflowSpec getWorkflow(CompletionPolicyData* policyData, std::vecto // // selected by output type 'tracks' if (runTracker) { - o2::gpu::GPUWorkflow::Config cfg; + o2::gpu::gpuworkflow::Config cfg; cfg.decompressTPC = decompressTPC; cfg.decompressTPCFromROOT = decompressTPC && inputType == InputType::CompClusters; cfg.caClusterer = caClusterer; @@ -428,7 +428,7 @@ framework::WorkflowSpec getWorkflow(CompletionPolicyData* policyData, std::vecto cfg.processMC = propagateMC; cfg.sendClustersPerSector = isEnabled(OutputType::SendClustersPerSector); cfg.askDISTSTF = askDISTSTF; - specs.emplace_back(o2::gpu::getGPURecoWorkflowSpec(policyData, cfg, tpcSectors, tpcSectorMask)); + specs.emplace_back(o2::gpu::getGPURecoWorkflowSpec(policyData, cfg, tpcSectors, tpcSectorMask, "tpc-tracker")); } ////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Detectors/TPC/workflow/src/TPCSectorCompletionPolicy.cxx b/Detectors/TPC/workflow/src/TPCSectorCompletionPolicy.cxx deleted file mode 100644 index 6d5b07a4e5e53..0000000000000 --- a/Detectors/TPC/workflow/src/TPCSectorCompletionPolicy.cxx +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// @file TPCSectorCompletionPolicy.cxx -/// @author Matthias Richter -/// @since 2020-05-20 -/// @brief DPL completion policy helper for TPC scetor data - -#include "TPCWorkflow/TPCSectorCompletionPolicy.h" -#include "Framework/CompletionPolicy.h" - -namespace o2 -{ -namespace tpc -{ - -} // namespace tpc -} // namespace o2 diff --git a/Detectors/TPC/workflow/src/TrackReaderWorkflow.cxx b/Detectors/TPC/workflow/src/TrackReaderWorkflow.cxx index 97fc95a4dbda1..d24c8343091ca 100644 --- a/Detectors/TPC/workflow/src/TrackReaderWorkflow.cxx +++ b/Detectors/TPC/workflow/src/TrackReaderWorkflow.cxx @@ -18,7 +18,6 @@ #include "Framework/PartRef.h" #include "Framework/ConcreteDataMatcher.h" #include "TPCWorkflow/RecoWorkflow.h" -#include "TPCWorkflow/TPCSectorCompletionPolicy.h" #include "DataFormatsTPC/TPCSectorHeader.h" #include "Algorithm/RangeTokenizer.h" #include "CommonUtils/ConfigurableParam.h" diff --git a/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx b/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx index 0c15bed320217..0eb1958db691d 100644 --- a/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx +++ b/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx @@ -21,7 +21,7 @@ #include "Framework/PartRef.h" #include "Framework/ConcreteDataMatcher.h" #include "TPCWorkflow/RecoWorkflow.h" -#include "TPCWorkflow/TPCSectorCompletionPolicy.h" +#include "GPUWorkflow/TPCSectorCompletionPolicy.h" #include "DataFormatsTPC/TPCSectorHeader.h" #include "Algorithm/RangeTokenizer.h" #include "CommonUtils/ConfigurableParam.h" @@ -94,7 +94,7 @@ void customize(std::vector& policies) policies.push_back(CompletionPolicyHelpers::defineByName("tpc-cluster-decoder.*", CompletionPolicy::CompletionOp::Consume)); policies.push_back(CompletionPolicyHelpers::defineByName("tpc-clusterer.*", CompletionPolicy::CompletionOp::Consume)); // the custom completion policy for the tracker - policies.push_back(o2::tpc::TPCSectorCompletionPolicy("gpu-reconstruction.*", o2::tpc::TPCSectorCompletionPolicy::Config::RequireAll, &gPolicyData, &gTpcSectorMask)()); + policies.push_back(o2::tpc::TPCSectorCompletionPolicy("tpc-tracker.*", o2::tpc::TPCSectorCompletionPolicy::Config::RequireAll, &gPolicyData, &gTpcSectorMask)()); } #include "Framework/runDataProcessing.h" // the main driver diff --git a/GPU/Workflow/CMakeLists.txt b/GPU/Workflow/CMakeLists.txt index 3ffda134d2092..6e0a11fa1cac8 100644 --- a/GPU/Workflow/CMakeLists.txt +++ b/GPU/Workflow/CMakeLists.txt @@ -27,3 +27,10 @@ o2_add_executable(display O2::TPCReconstruction O2::GlobalTrackingWorkflowHelpers) target_include_directories(${targetName} PUBLIC "include") + +o2_add_executable(reco-workflow + COMPONENT_NAME gpu + TARGETVARNAME targetName + SOURCES src/gpu-reco-workflow.cxx + PUBLIC_LINK_LIBRARIES O2::GPUWorkflow + O2::GlobalTrackingWorkflowHelpers) diff --git a/GPU/Workflow/include/GPUWorkflow/GPUWorkflowSpec.h b/GPU/Workflow/include/GPUWorkflow/GPUWorkflowSpec.h index 4c8e22555de12..0a021f13c6114 100644 --- a/GPU/Workflow/include/GPUWorkflow/GPUWorkflowSpec.h +++ b/GPU/Workflow/include/GPUWorkflow/GPUWorkflowSpec.h @@ -17,7 +17,8 @@ #define O2_GPU_WORKFLOW_SPEC_H #include "Framework/DataProcessorSpec.h" -#include // std::forward +#include +#include namespace o2 { @@ -28,7 +29,7 @@ struct CompletionPolicy; namespace gpu { -namespace GPUWorkflow +namespace gpuworkflow { struct Config { bool decompressTPC = false; @@ -47,7 +48,7 @@ struct Config { bool askDISTSTF = true; }; using CompletionPolicyData = std::vector; -} // namespace GPUWorkflow +} // namespace gpuworkflow /// create a processor spec for the CATracker /// The CA tracker is actually much more than the tracker it has evolved to a @@ -65,7 +66,7 @@ using CompletionPolicyData = std::vector; /// /// @param specconfig configuration options for the processor spec /// @param tpcsectors list of sector numbers -framework::DataProcessorSpec getGPURecoWorkflowSpec(GPUWorkflow::CompletionPolicyData* policyData, GPUWorkflow::Config const& specconfig, std::vector const& tpcsectors, unsigned long tpcSectorMask); +framework::DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* policyData, gpuworkflow::Config const& specconfig, std::vector const& tpcsectors, unsigned long tpcSectorMask, std::string processorName); o2::framework::CompletionPolicy getCATrackerCompletionPolicy(); } // end namespace gpu diff --git a/Detectors/TPC/workflow/include/TPCWorkflow/TPCSectorCompletionPolicy.h b/GPU/Workflow/include/GPUWorkflow/TPCSectorCompletionPolicy.h similarity index 96% rename from Detectors/TPC/workflow/include/TPCWorkflow/TPCSectorCompletionPolicy.h rename to GPU/Workflow/include/GPUWorkflow/TPCSectorCompletionPolicy.h index cf0275c2c13b7..773b30293afef 100644 --- a/Detectors/TPC/workflow/include/TPCWorkflow/TPCSectorCompletionPolicy.h +++ b/GPU/Workflow/include/GPUWorkflow/TPCSectorCompletionPolicy.h @@ -199,17 +199,17 @@ class TPCSectorCompletionPolicy void init(Arg&& arg, Args&&... args) { using Type = std::decay_t; - if constexpr (std::is_same::value) { + if constexpr (std::is_same_v) { mInputMatchers.emplace_back(std::move(arg)); - } else if constexpr (std::is_same::value) { + } else if constexpr (std::is_same_v) { switch (arg) { case Config::RequireAll: mRequireAll = true; break; } - } else if constexpr (std::is_same*>::value) { + } else if constexpr (std::is_same_v*>) { mExternalInputMatchers = arg; - } else if constexpr (std::is_same::value) { + } else if constexpr (std::is_same_v || std::is_same_v) { mTpcSectorMask = arg; } else { static_assert(framework::always_static_assert_v); @@ -225,7 +225,7 @@ class TPCSectorCompletionPolicy // - They are controlled externally and the external entity can modify them, e.g. after parsing command line arguments. // - They are all matched independently, it is not sufficient that one of them is present for all sectors const std::vector* mExternalInputMatchers = nullptr; - unsigned long* mTpcSectorMask = nullptr; + const unsigned long* mTpcSectorMask = nullptr; bool mRequireAll = false; }; } // namespace tpc diff --git a/GPU/Workflow/src/GPUWorkflowSpec.cxx b/GPU/Workflow/src/GPUWorkflowSpec.cxx index 23ffba9117a4d..a0b3b7b895263 100644 --- a/GPU/Workflow/src/GPUWorkflowSpec.cxx +++ b/GPU/Workflow/src/GPUWorkflowSpec.cxx @@ -83,7 +83,7 @@ using namespace o2::tpc; namespace o2::gpu { -DataProcessorSpec getGPURecoWorkflowSpec(GPUWorkflow::CompletionPolicyData* policyData, GPUWorkflow::Config const& specconfig, std::vector const& tpcsectors, unsigned long tpcSectorMask) +DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* policyData, gpuworkflow::Config const& specconfig, std::vector const& tpcsectors, unsigned long tpcSectorMask, std::string processorName) { if (specconfig.outputCAClusters && !specconfig.caClusterer && !specconfig.decompressTPC) { throw std::runtime_error("inconsistent configuration: cluster output is only possible if CA clusterer is activated"); @@ -791,7 +791,7 @@ DataProcessorSpec getGPURecoWorkflowSpec(GPUWorkflow::CompletionPolicyData* poli return std::move(outputSpecs); }; - return DataProcessorSpec{"gpu-reconstruction", // process id + return DataProcessorSpec{processorName, // process id {createInputSpecs()}, {createOutputSpecs()}, AlgorithmSpec(initFunction)}; diff --git a/GPU/Workflow/src/gpu-reco-workflow.cxx b/GPU/Workflow/src/gpu-reco-workflow.cxx new file mode 100644 index 0000000000000..b07c287b24ae0 --- /dev/null +++ b/GPU/Workflow/src/gpu-reco-workflow.cxx @@ -0,0 +1,146 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file gpu-reco-workflow.cxx +/// @author David Rohr + +#include "Framework/WorkflowSpec.h" +#include "Framework/ConfigParamSpec.h" +#include "Framework/CompletionPolicyHelpers.h" +#include "Framework/DispatchPolicy.h" +#include "Framework/ConcreteDataMatcher.h" +#include "GPUWorkflow/TPCSectorCompletionPolicy.h" +#include "GPUWorkflow/GPUWorkflowSpec.h" +#include "CommonUtils/ConfigurableParam.h" +#include "DetectorsRaw/HBFUtilsInitializer.h" +#include "TPCBase/Sector.h" +#include "Algorithm/RangeTokenizer.h" +#include "GlobalTrackingWorkflowHelpers/InputHelper.h" +#include "ReconstructionDataFormats/GlobalTrackID.h" + +#include + +using namespace o2::framework; +using namespace o2::dataformats; +using CompletionPolicyData = std::vector; +CompletionPolicyData gPolicyData; +static constexpr unsigned long gTpcSectorMask = 0xFFFFFFFFF; + +void customize(std::vector& workflowOptions) +{ + + std::vector options{ + {"input-type", VariantType::String, "digits", {"digitizer, digits, zsraw, zsonthefly, clustersnative, compressed-clusters-root, compressed-clusters-ctf"}}, + {"output-type", VariantType::String, "tracks", {"clustersnative, tracks, compressed-clusters, qa, no-shared-cluster-map"}}, + {"disable-root-input", VariantType::Bool, true, {"disable root-files input reader"}}, + {"disable-mc", VariantType::Bool, false, {"disable sending of MC information"}}, + {"ignore-dist-stf", VariantType::Bool, false, {"do not subscribe to FLP/DISTSUBTIMEFRAME/0 message (no lost TF recovery)"}}, + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings (e.g.: 'TPCHwClusterer.peakChargeThreshold=4;...')"}}, + {"configFile", VariantType::String, "", {"configuration file for configurable parameters"}}}; + + o2::raw::HBFUtilsInitializer::addConfigOption(options); + + std::swap(workflowOptions, options); +} + +// customize dispatch policy, dispatch immediately what is ready +void customize(std::vector& policies) +{ + using DispatchOp = DispatchPolicy::DispatchOp; + policies.push_back({"prompt-for-gpu-reco", [](auto const& spec) { return true; }, DispatchOp::WhenReady}); +} + +void customize(std::vector& policies) +{ + policies.push_back(o2::tpc::TPCSectorCompletionPolicy("gpu-reconstruction.*", o2::tpc::TPCSectorCompletionPolicy::Config::RequireAll, &gPolicyData, &gTpcSectorMask)()); +} + +#include "Framework/runDataProcessing.h" // the main driver + +using namespace o2::framework; + +enum struct ioType { Digits, + Clusters, + ZSRaw, + ZSRawOTF, + CompClustROOT, + CompClustCTF, + Tracks, + QA, + NoSharedMap }; + +static const std::unordered_map InputMap{ + {"digits", ioType::Digits}, + {"clusters", ioType::Clusters}, + {"zsraw", ioType::ZSRaw}, + {"zsonthefly", ioType::ZSRawOTF}, + {"compressed-clusters-root", ioType::CompClustROOT}, + {"compressed-clusters-ctf", ioType::CompClustCTF}}; + +static const std::unordered_map OutputMap{ + {"clusters", ioType::Clusters}, + {"tracks", ioType::Tracks}, + {"compressed-clusters", ioType::CompClustCTF}, + {"qa", ioType::QA}, + {"no-shared-cluster-map", ioType::NoSharedMap}}; + +WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) +{ + WorkflowSpec specs; + std::vector tpcSectors(o2::tpc::Sector::MAXSECTOR); + std::iota(tpcSectors.begin(), tpcSectors.end(), 0); + + auto inputType = cfgc.options().get("input-type"); + bool doMC = !cfgc.options().get("disable-mc"); + + o2::conf::ConfigurableParam::updateFromFile(cfgc.options().get("configFile")); + o2::conf::ConfigurableParam::updateFromString(cfgc.options().get("configKeyValues")); + o2::conf::ConfigurableParam::writeINI("o2gpurecoworkflow_configuration.ini"); + + std::vector outputTypes, inputTypes; + try { + outputTypes = o2::RangeTokenizer::tokenize(cfgc.options().get("output-type"), [](std::string const& token) { return OutputMap.at(token); }); + inputTypes = o2::RangeTokenizer::tokenize(cfgc.options().get("input-type"), [](std::string const& token) { return InputMap.at(token); }); + } catch (std::out_of_range&) { + throw std::invalid_argument("invalid input / output type"); + } + + auto isEnabled = [](auto& list, ioType type) { + return std::find(list.begin(), list.end(), type) != list.end(); + }; + + o2::gpu::gpuworkflow::Config cfg; + cfg.decompressTPC = isEnabled(inputTypes, ioType::CompClustCTF); + cfg.decompressTPCFromROOT = isEnabled(inputTypes, ioType::CompClustROOT); + cfg.zsDecoder = isEnabled(inputTypes, ioType::ZSRaw); + cfg.zsOnTheFly = isEnabled(inputTypes, ioType::ZSRawOTF); + cfg.caClusterer = cfg.zsDecoder || cfg.zsOnTheFly || isEnabled(inputTypes, ioType::Digits); + cfg.outputTracks = isEnabled(outputTypes, ioType::Tracks); + cfg.outputCompClusters = isEnabled(outputTypes, ioType::CompClustROOT); + cfg.outputCompClustersFlat = isEnabled(outputTypes, ioType::CompClustCTF); + cfg.outputCAClusters = isEnabled(outputTypes, ioType::Clusters); + cfg.outputQA = isEnabled(outputTypes, ioType::QA); + cfg.outputSharedClusterMap = (cfg.outputCAClusters || cfg.caClusterer || isEnabled(inputTypes, ioType::Clusters)) && cfg.outputTracks && !isEnabled(outputTypes, ioType::NoSharedMap); + cfg.processMC = doMC; + cfg.sendClustersPerSector = false; + cfg.askDISTSTF = !cfgc.options().get("ignore-dist-stf"); + specs.emplace_back(o2::gpu::getGPURecoWorkflowSpec(&gPolicyData, cfg, tpcSectors, gTpcSectorMask, "gpu-reconstruction")); + + if (!cfgc.options().get("ignore-dist-stf")) { + GlobalTrackID::mask_t srcTrk = GlobalTrackID::getSourcesMask("none"); + GlobalTrackID::mask_t srcCl = GlobalTrackID::getSourcesMask("TPC"); + o2::globaltracking::InputHelper::addInputSpecs(cfgc, specs, srcCl, srcTrk, srcTrk, doMC); + } + + // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit + o2::raw::HBFUtilsInitializer hbfIni(cfgc, specs); + + return std::move(specs); +} From d0aad1b6888f522050c4ca8c4ad0a1893a5b4149 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 23 Apr 2021 17:01:24 +0200 Subject: [PATCH 272/770] TPC Workflow: DisableWriter option should also disable the raw writer output --- Detectors/TPC/workflow/src/RecoWorkflow.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Detectors/TPC/workflow/src/RecoWorkflow.cxx b/Detectors/TPC/workflow/src/RecoWorkflow.cxx index 355ebb9407b60..f17434e10fdd5 100644 --- a/Detectors/TPC/workflow/src/RecoWorkflow.cxx +++ b/Detectors/TPC/workflow/src/RecoWorkflow.cxx @@ -230,7 +230,7 @@ framework::WorkflowSpec getWorkflow(CompletionPolicyData* policyData, std::vecto runHWDecoder &= runClusterer || inputType == InputType::ClustersHardware; runTracker &= caClusterer || runHWDecoder || inputType == InputType::Clusters || decompressTPC; - bool outRaw = inputType == InputType::Digits && isEnabled(OutputType::ZSRaw); + bool outRaw = inputType == InputType::Digits && isEnabled(OutputType::ZSRaw) && !isEnabled(OutputType::DisableWriter); //bool runZSDecode = inputType == InputType::ZSRaw; bool zsToDigit = inputType == InputType::ZSRaw && isEnabled(OutputType::Digits); From e6ce57be9f857fdd434be496d34d5565da271d51 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 23 Apr 2021 18:48:29 +0200 Subject: [PATCH 273/770] TPC Workflow: Add an input type compressed-clusters-flat, such that the workflow acts only as entropy encoder --- .../TPC/workflow/include/TPCWorkflow/RecoWorkflow.h | 1 + Detectors/TPC/workflow/src/RecoWorkflow.cxx | 9 +++++---- GPU/Workflow/src/gpu-reco-workflow.cxx | 4 ++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/Detectors/TPC/workflow/include/TPCWorkflow/RecoWorkflow.h b/Detectors/TPC/workflow/include/TPCWorkflow/RecoWorkflow.h index 653b3e526c1df..081ca5a4c666c 100644 --- a/Detectors/TPC/workflow/include/TPCWorkflow/RecoWorkflow.h +++ b/Detectors/TPC/workflow/include/TPCWorkflow/RecoWorkflow.h @@ -39,6 +39,7 @@ enum struct InputType { Digitizer, // directly read digits from channel { Clusters, // read native clusters from file CompClusters, // read compressed cluster container CompClustersCTF, // compressed clusters from CTF, as flat format + CompClustersFlat, // compressed clusters in flat format, used as input for the entropy encoder EncodedClusters, // read encoded clusters ZSRaw, }; diff --git a/Detectors/TPC/workflow/src/RecoWorkflow.cxx b/Detectors/TPC/workflow/src/RecoWorkflow.cxx index f17434e10fdd5..1f82caeef446f 100644 --- a/Detectors/TPC/workflow/src/RecoWorkflow.cxx +++ b/Detectors/TPC/workflow/src/RecoWorkflow.cxx @@ -72,7 +72,8 @@ const std::unordered_map InputMap{ {"clusters", InputType::Clusters}, {"zsraw", InputType::ZSRaw}, {"compressed-clusters", InputType::CompClusters}, - {"compressed-clusters-ctf", InputType::CompClustersCTF}}; + {"compressed-clusters-ctf", InputType::CompClustersCTF}, + {"compressed-clusters-flat", InputType::CompClustersFlat}}; const std::unordered_map OutputMap{ {"digits", OutputType::Digits}, @@ -114,7 +115,7 @@ framework::WorkflowSpec getWorkflow(CompletionPolicyData* policyData, std::vecto zsOnTheFly = false; propagateMC = false; } - if (inputType == InputType::ZSRaw) { + if (inputType == InputType::ZSRaw || inputType == InputType::CompClustersFlat) { caClusterer = true; zsOnTheFly = false; propagateMC = false; @@ -219,7 +220,7 @@ framework::WorkflowSpec getWorkflow(CompletionPolicyData* policyData, std::vecto // ClusterDecoderRawSpec bool produceCompClusters = isEnabled(OutputType::CompClusters); bool produceTracks = isEnabled(OutputType::Tracks); - bool runTracker = produceTracks || produceCompClusters || (isEnabled(OutputType::Clusters) && caClusterer); + bool runTracker = (produceTracks || produceCompClusters || (isEnabled(OutputType::Clusters) && caClusterer)) && inputType != InputType::CompClustersFlat; bool runHWDecoder = !caClusterer && (runTracker || isEnabled(OutputType::Clusters)); bool runClusterer = !caClusterer && (runHWDecoder || isEnabled(OutputType::ClustersHardware)); bool zsDecoder = inputType == InputType::ZSRaw; @@ -437,7 +438,7 @@ framework::WorkflowSpec getWorkflow(CompletionPolicyData* policyData, std::vecto // // selected by output type 'encoded-clusters' if (runClusterEncoder) { - specs.emplace_back(o2::tpc::getEntropyEncoderSpec(!runTracker)); + specs.emplace_back(o2::tpc::getEntropyEncoderSpec(!runTracker && inputType != InputType::CompClustersFlat)); } ////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/GPU/Workflow/src/gpu-reco-workflow.cxx b/GPU/Workflow/src/gpu-reco-workflow.cxx index b07c287b24ae0..c667536e7dac8 100644 --- a/GPU/Workflow/src/gpu-reco-workflow.cxx +++ b/GPU/Workflow/src/gpu-reco-workflow.cxx @@ -38,7 +38,7 @@ void customize(std::vector& workflowOptions) std::vector options{ {"input-type", VariantType::String, "digits", {"digitizer, digits, zsraw, zsonthefly, clustersnative, compressed-clusters-root, compressed-clusters-ctf"}}, - {"output-type", VariantType::String, "tracks", {"clustersnative, tracks, compressed-clusters, qa, no-shared-cluster-map"}}, + {"output-type", VariantType::String, "tracks", {"clustersnative, tracks, compressed-clusters-ctf, qa, no-shared-cluster-map"}}, {"disable-root-input", VariantType::Bool, true, {"disable root-files input reader"}}, {"disable-mc", VariantType::Bool, false, {"disable sending of MC information"}}, {"ignore-dist-stf", VariantType::Bool, false, {"do not subscribe to FLP/DISTSUBTIMEFRAME/0 message (no lost TF recovery)"}}, @@ -87,7 +87,7 @@ static const std::unordered_map InputMap{ static const std::unordered_map OutputMap{ {"clusters", ioType::Clusters}, {"tracks", ioType::Tracks}, - {"compressed-clusters", ioType::CompClustCTF}, + {"compressed-clusters-ctf", ioType::CompClustCTF}, {"qa", ioType::QA}, {"no-shared-cluster-map", ioType::NoSharedMap}}; From 280e71241f3b9e8d7bf645f2568d95b7541bc710 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 23 Apr 2021 21:38:05 +0200 Subject: [PATCH 274/770] Full system test: Use the GPU workflow instead of the TPC workflow for GPU processing --- prodtests/full-system-test/dpl-workflow.sh | 27 +++++++++++----------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/prodtests/full-system-test/dpl-workflow.sh b/prodtests/full-system-test/dpl-workflow.sh index 0203003fe4907..2ac78edf5a3a7 100755 --- a/prodtests/full-system-test/dpl-workflow.sh +++ b/prodtests/full-system-test/dpl-workflow.sh @@ -24,24 +24,24 @@ fi CTF_DETECTORS=ITS,MFT,TPC,TOF,FT0,MID,EMC,PHS,CPV,ZDC,FDD CTF_DIR= CTF_DICT_DIR= -TPC_INPUT=zsraw -TPC_OUTPUT=tracks,clusters,disable-writer -TPC_CONFIG= -TPC_CONFIG_KEY= +GPU_INPUT=zsraw +GPU_OUTPUT=tracks,clusters +GPU_CONFIG= +GPU_CONFIG_KEY= TOF_INPUT=raw TOF_OUTPUT=clusters,matching-info ITS_CONFIG= ITS_CONFIG_KEY= if [ $SYNCMODE == 1 ]; then ITS_CONFIG_KEY+="fastMultConfig.cutMultClusLow=30;fastMultConfig.cutMultClusHigh=2000;fastMultConfig.cutMultVtxHigh=500;" - TPC_CONFIG_KEY+="GPU_global.synchronousProcessing=1;GPU_proc.clearO2OutputFromGPU=1;" + GPU_CONFIG_KEY+="GPU_global.synchronousProcessing=1;GPU_proc.clearO2OutputFromGPU=1;" fi if [ $CTFINPUT == 1 ]; then ITS_CONFIG+=" --tracking-mode async" else ITS_CONFIG+=" --entropy-encoding" TOF_OUTPUT+=",ctf" - TPC_OUTPUT+=",encoded-clusters" + GPU_OUTPUT+=",compressed-clusters-ctf" fi if [ $GPUTYPE == "HIP" ]; then @@ -50,22 +50,22 @@ if [ $GPUTYPE == "HIP" ]; then else export TIMESLICEOFFSET=$NGPUS fi - TPC_CONFIG_KEY+="GPU_proc.deviceNum=0;GPU_global.mutexMemReg=true;" - TPC_CONFIG+=" --environment \"ROCR_VISIBLE_DEVICES={timeslice${TIMESLICEOFFSET}}\"" + GPU_CONFIG_KEY+="GPU_proc.deviceNum=0;GPU_global.mutexMemReg=true;" + GPU_CONFIG+=" --environment \"ROCR_VISIBLE_DEVICES={timeslice${TIMESLICEOFFSET}}\"" export HSA_NO_SCRATCH_RECLAIM=1 #export HSA_TOOLS_LIB=/opt/rocm/lib/librocm-debug-agent.so.2 else - TPC_CONFIG_KEY+="GPU_proc.deviceNum=-2;" + GPU_CONFIG_KEY+="GPU_proc.deviceNum=-2;" fi if [ $GPUTYPE != "CPU" ]; then - TPC_CONFIG_KEY+="GPU_proc.forceMemoryPoolSize=$GPUMEMSIZE;" + GPU_CONFIG_KEY+="GPU_proc.forceMemoryPoolSize=$GPUMEMSIZE;" if [ $HOSTMEMSIZE == "0" ]; then HOSTMEMSIZE=$(( 1 << 30 )) fi fi if [ $HOSTMEMSIZE != "0" ]; then - TPC_CONFIG_KEY+="GPU_proc.forceHostMemoryPoolSize=$HOSTMEMSIZE;" + GPU_CONFIG_KEY+="GPU_proc.forceHostMemoryPoolSize=$HOSTMEMSIZE;" fi if [ $EPNPIPELINES != 0 ]; then @@ -84,7 +84,7 @@ fi # Input workflow if [ $CTFINPUT == 1 ]; then - TPC_INPUT=compressed-clusters-ctf + GPU_INPUT=compressed-clusters-ctf TOF_INPUT=digits CTFName=`ls -t o2_ctf_*.root | head -n1` CTF_DICT= @@ -108,7 +108,7 @@ fi # Common workflows WORKFLOW+="o2-its-reco-workflow $ARGS_ALL --trackerCA $DISABLE_MC --clusters-from-upstream --disable-root-output $ITS_CONFIG --configKeyValues \"HBFUtils.nHBFPerTF=${NHBPERTF};$ITS_CONFIG_KEY\" | " -WORKFLOW+="o2-tpc-reco-workflow ${ARGS_ALL/--severity $SEVERITY/--severity $SEVERITY_TPC} --input-type=$TPC_INPUT $DISABLE_MC --output-type $TPC_OUTPUT --pipeline gpu-reconstruction:$NGPUS,tpc-entropy-encoder:$N_TPCENT $TPC_CONFIG --configKeyValues \"HBFUtils.nHBFPerTF=$NHBPERTF;GPU_global.deviceType=$GPUTYPE;GPU_proc.debugLevel=0;$TPC_CONFIG_KEY;$TPC_EXTRA_CONFIG\" | " +WORKFLOW+="o2-gpu-reco-workflow ${ARGS_ALL/--severity $SEVERITY/--severity $SEVERITY_TPC} --input-type=$GPU_INPUT $DISABLE_MC --output-type $GPU_OUTPUT --pipeline gpu-reconstruction:$NGPUS $GPU_CONFIG --configKeyValues \"HBFUtils.nHBFPerTF=$NHBPERTF;GPU_global.deviceType=$GPUTYPE;GPU_proc.debugLevel=0;$GPU_CONFIG_KEY;$GPU_EXTRA_CONFIG\" | " WORKFLOW+="o2-tpcits-match-workflow $ARGS_ALL --disable-root-input --disable-root-output $DISABLE_MC --pipeline itstpc-track-matcher:$N_TPCITS --configKeyValues \"HBFUtils.nHBFPerTF=${NHBPERTF};\" | " WORKFLOW+="o2-ft0-reco-workflow $ARGS_ALL --disable-root-input --disable-root-output $DISABLE_MC --configKeyValues \"HBFUtils.nHBFPerTF=${NHBPERTF};\" | " WORKFLOW+="o2-tof-reco-workflow $ARGS_ALL --configKeyValues \"HBFUtils.nHBFPerTF=$NHBPERTF\" --input-type $TOF_INPUT --output-type $TOF_OUTPUT --disable-root-input --disable-root-output $DISABLE_MC | " @@ -139,6 +139,7 @@ if [ $CTFINPUT == 0 ]; then WORKFLOW+="o2-emcal-entropy-encoder-workflow $ARGS_ALL | " WORKFLOW+="o2-zdc-entropy-encoder-workflow $ARGS_ALL | " WORKFLOW+="o2-fdd-entropy-encoder-workflow $ARGS_ALL | " + WORKFLOW+="o2-tpc-reco-workflow --input-type compressed-clusters-flat --output-type encoded-clusters,disable-writer --pipeline tpc-entropy-encoder:$N_TPCENT $ARGS_ALL | " WORKFLOW+="o2-tpc-scdcalib-interpolation-workflow $ARGS_ALL --disable-root-output --disable-root-input | " From 85f21d7b71169fb64784483b549118b6245ddc31 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sat, 24 Apr 2021 21:50:50 +0200 Subject: [PATCH 275/770] GPU Workflow: The workflow should be compiled on Mac, only the gpu display shouldn't --- GPU/CMakeLists.txt | 11 +--------- GPU/Workflow/CMakeLists.txt | 43 ++++++++++++++++++++++--------------- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/GPU/CMakeLists.txt b/GPU/CMakeLists.txt index 26caeb87a745e..f36f5a379ab2f 100644 --- a/GPU/CMakeLists.txt +++ b/GPU/CMakeLists.txt @@ -21,13 +21,4 @@ add_subdirectory(Common) add_subdirectory(Utils) add_subdirectory(TPCFastTransformation) add_subdirectory(GPUTracking) - -if(ALIGPU_BUILD_TYPE STREQUAL "O2" - AND OPENGL_FOUND - AND GLFW_FOUND - AND TARGET AliceO2::DebugGUI - AND OPENGL_GLU_FOUND - AND NOT CMAKE_SYSTEM_NAME STREQUAL "Darwin" -) - add_subdirectory(Workflow) -endif() +add_subdirectory(Workflow) diff --git a/GPU/Workflow/CMakeLists.txt b/GPU/Workflow/CMakeLists.txt index 6e0a11fa1cac8..756eef86f26cb 100644 --- a/GPU/Workflow/CMakeLists.txt +++ b/GPU/Workflow/CMakeLists.txt @@ -16,21 +16,30 @@ o2_add_library(GPUWorkflow O2::TPCCalibration O2::TPCSimulation O2::TPCQC O2::DetectorsCalibration) -o2_add_executable(display - COMPONENT_NAME gpu - TARGETVARNAME targetName - SOURCES src/O2GPUDPLDisplay.cxx - PUBLIC_LINK_LIBRARIES O2::GPUO2Interface - O2::DataFormatsGlobalTracking - O2::TPCFastTransformation - O2::TRDBase - O2::TPCReconstruction - O2::GlobalTrackingWorkflowHelpers) -target_include_directories(${targetName} PUBLIC "include") - o2_add_executable(reco-workflow - COMPONENT_NAME gpu - TARGETVARNAME targetName - SOURCES src/gpu-reco-workflow.cxx - PUBLIC_LINK_LIBRARIES O2::GPUWorkflow - O2::GlobalTrackingWorkflowHelpers) + COMPONENT_NAME gpu + TARGETVARNAME targetName + SOURCES src/gpu-reco-workflow.cxx + PUBLIC_LINK_LIBRARIES O2::GPUWorkflow + O2::GlobalTrackingWorkflowHelpers) + + +if(ALIGPU_BUILD_TYPE STREQUAL "O2" + AND OPENGL_FOUND + AND GLFW_FOUND + AND TARGET AliceO2::DebugGUI + AND OPENGL_GLU_FOUND + AND NOT CMAKE_SYSTEM_NAME STREQUAL "Darwin" +) + o2_add_executable(display + COMPONENT_NAME gpu + TARGETVARNAME targetName + SOURCES src/O2GPUDPLDisplay.cxx + PUBLIC_LINK_LIBRARIES O2::GPUO2Interface + O2::DataFormatsGlobalTracking + O2::TPCFastTransformation + O2::TRDBase + O2::TPCReconstruction + O2::GlobalTrackingWorkflowHelpers) + target_include_directories(${targetName} PUBLIC "include") +endif() From 0a7ab57ef47f1ba2df52290ad459a44d11c05b41 Mon Sep 17 00:00:00 2001 From: Nazar Burmasov Date: Fri, 23 Apr 2021 17:52:51 +0200 Subject: [PATCH 276/770] Add MC collision labels to AOD --- Detectors/AOD/src/AODProducerWorkflowSpec.cxx | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/Detectors/AOD/src/AODProducerWorkflowSpec.cxx b/Detectors/AOD/src/AODProducerWorkflowSpec.cxx index 602fbf289e5e1..e9b54cd6b2971 100644 --- a/Detectors/AOD/src/AODProducerWorkflowSpec.cxx +++ b/Detectors/AOD/src/AODProducerWorkflowSpec.cxx @@ -14,7 +14,7 @@ #include "DataFormatsFT0/RecPoints.h" #include "DataFormatsITS/TrackITS.h" #include "DataFormatsTPC/TrackTPC.h" -#include +#include "CCDB/BasicCCDBManager.h" #include "CommonDataFormat/InteractionRecord.h" #include "Framework/AnalysisDataModel.h" #include "Framework/ConfigParamRegistry.h" @@ -29,6 +29,7 @@ #include "SimulationDataFormat/DigitizationContext.h" #include "SimulationDataFormat/MCTrack.h" #include "SimulationDataFormat/MCTruthContainer.h" +#include "SimulationDataFormat/MCEventLabel.h" #include "TMath.h" #include "MathUtils/Utils.h" #include @@ -414,6 +415,7 @@ void AODProducerWorkflowDPL::run(ProcessingContext& pc) auto primVer2TRefs = pc.inputs().get>("primVer2TRefs"); auto primVerGIs = pc.inputs().get>("primVerGIs"); auto primVertices = pc.inputs().get>("primVertices"); + auto primVerLabels = pc.inputs().get>("primVerLabels"); auto tracksITS = pc.inputs().get>("trackITS"); auto tracksITSTPC = pc.inputs().get>("tracksITSTPC"); auto tracksTPC = pc.inputs().get>("trackTPC"); @@ -426,6 +428,7 @@ void AODProducerWorkflowDPL::run(ProcessingContext& pc) TableBuilder bcBuilderS; TableBuilder collisionsBuilderS; + TableBuilder mcColLabelsBuilderS; TableBuilder ft0BuilderS; TableBuilder mcCollisionsBuilderS; TableBuilder tracksBuilderS; @@ -440,6 +443,7 @@ void AODProducerWorkflowDPL::run(ProcessingContext& pc) auto& bcBuilder = mIgnoreWriter == 0 ? pc.outputs().make(Output{"AOD", "BC"}) : bcBuilderS; auto& collisionsBuilder = mIgnoreWriter == 0 ? pc.outputs().make(Output{"AOD", "COLLISION"}) : collisionsBuilderS; + auto& mcColLabelsBuilder = mIgnoreWriter == 0 ? pc.outputs().make(Output{"AOD", "MCCOLLISLABEL"}) : mcColLabelsBuilderS; auto& ft0Builder = mIgnoreWriter == 0 ? pc.outputs().make(Output{"AOD", "FT0"}) : ft0BuilderS; auto& mcCollisionsBuilder = mIgnoreWriter == 0 ? pc.outputs().make(Output{"AOD", "MCCOLLISION"}) : mcCollisionsBuilderS; auto& tracksBuilder = mIgnoreWriter == 0 ? pc.outputs().make(Output{"AOD", "TRACK"}) : tracksBuilderS; @@ -454,6 +458,7 @@ void AODProducerWorkflowDPL::run(ProcessingContext& pc) auto bcCursor = bcBuilder.cursor(); auto collisionsCursor = collisionsBuilder.cursor(); + auto mcColLabelsCursor = mcColLabelsBuilder.cursor(); auto ft0Cursor = ft0Builder.cursor(); auto mcCollisionsCursor = mcCollisionsBuilder.cursor(); auto tracksCursor = tracksBuilder.cursor(); @@ -670,6 +675,19 @@ void AODProducerWorkflowDPL::run(ProcessingContext& pc) std::vector vCollRefsTPC(tracksTPC.size(), -1); std::vector vCollRefsTPCITS(tracksITSTPC.size(), -1); + // filling MC collision labels + for (auto& label : primVerLabels) { + int32_t mcCollisionID = label.getEventID(); + uint16_t mcMask = 0; // todo: set mask using normalized weights? + mcColLabelsCursor(0, mcCollisionID, mcMask); + } + + if (mIgnoreWriter) { + std::shared_ptr tableMCColLabels = mcColLabelsBuilder.finalize(); + std::string tableName("O2mccollisionlabel"); + writeTableToFile(outfile, tableMCColLabels, tableName, tfNumber); + } + // filling collisions table int collisionID = 0; for (auto& vertex : primVertices) { @@ -897,6 +915,7 @@ DataProcessorSpec getAODProducerWorkflowSpec(int mIgnoreWriter) inputs.emplace_back("primVer2TRefs", "GLO", "PVTX_TRMTCREFS", 0, Lifetime::Timeframe); inputs.emplace_back("primVerGIs", "GLO", "PVTX_TRMTC", 0, Lifetime::Timeframe); inputs.emplace_back("primVertices", "GLO", "PVTX", 0, Lifetime::Timeframe); + inputs.emplace_back("primVerLabels", "GLO", "PVTX_MCTR", 0, Lifetime::Timeframe); inputs.emplace_back("trackITS", "ITS", "TRACKS", 0, Lifetime::Timeframe); inputs.emplace_back("tracksITSTPC", "GLO", "TPCITS", 0, Lifetime::Timeframe); inputs.emplace_back("trackTPC", "TPC", "TRACKS", 0, Lifetime::Timeframe); @@ -908,6 +927,7 @@ DataProcessorSpec getAODProducerWorkflowSpec(int mIgnoreWriter) outputs.emplace_back(OutputLabel{"O2collision"}, "AOD", "COLLISION", 0, Lifetime::Timeframe); outputs.emplace_back(OutputLabel{"O2ft0"}, "AOD", "FT0", 0, Lifetime::Timeframe); outputs.emplace_back(OutputLabel{"O2mccollision"}, "AOD", "MCCOLLISION", 0, Lifetime::Timeframe); + outputs.emplace_back(OutputLabel{"O2mccollisionlabel"}, "AOD", "MCCOLLISLABEL", 0, Lifetime::Timeframe); outputs.emplace_back(OutputLabel{"O2track"}, "AOD", "TRACK", 0, Lifetime::Timeframe); outputs.emplace_back(OutputLabel{"O2trackcov"}, "AOD", "TRACKCOV", 0, Lifetime::Timeframe); outputs.emplace_back(OutputLabel{"O2trackextra"}, "AOD", "TRACKEXTRA", 0, Lifetime::Timeframe); From acfe1dff5c44a2d6f67632c62f2895ec8d2bee20 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sun, 25 Apr 2021 11:26:02 +0200 Subject: [PATCH 277/770] GPU Clusterizer: Remove redundant defines --- GPU/GPUTracking/TPCClusterFinder/GPUTPCCFCheckPadBaseline.cxx | 2 +- GPU/GPUTracking/TPCClusterFinder/TPCPadGainCalib.cxx | 2 +- GPU/GPUTracking/TPCClusterFinder/TPCPadGainCalib.h | 4 ++-- GPU/GPUTracking/TPCClusterFinder/clusterFinderDefs.h | 4 +--- 4 files changed, 5 insertions(+), 7 deletions(-) diff --git a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFCheckPadBaseline.cxx b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFCheckPadBaseline.cxx index cc6cac6faed7e..0b5fec5a27905 100644 --- a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFCheckPadBaseline.cxx +++ b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFCheckPadBaseline.cxx @@ -134,7 +134,7 @@ GPUd() ChargePos GPUTPCCFCheckPadBaseline::padToChargePos(int& pad, const GPUTPC const GPUTPCGeometry& geo = clusterer.Param().tpcGeometry; int padOffset = 0; - for (Row r = 0; r < TPC_NUM_OF_ROWS; r++) { + for (Row r = 0; r < GPUCA_ROW_COUNT; r++) { int npads = geo.NPads(r); int padInRow = pad - padOffset; if (0 <= padInRow && padInRow < CAMath::nextMultipleOf(npads)) { diff --git a/GPU/GPUTracking/TPCClusterFinder/TPCPadGainCalib.cxx b/GPU/GPUTracking/TPCClusterFinder/TPCPadGainCalib.cxx index a2cad4760ada0..62ca2964a172e 100644 --- a/GPU/GPUTracking/TPCClusterFinder/TPCPadGainCalib.cxx +++ b/GPU/GPUTracking/TPCClusterFinder/TPCPadGainCalib.cxx @@ -23,7 +23,7 @@ TPCPadGainCalib::TPCPadGainCalib() { GPUTPCGeometry geo{}; int offset = 0; - for (int r = 0; r < TPC_NUM_OF_ROWS; r++) { + for (int r = 0; r < GPUCA_ROW_COUNT; r++) { mPadOffsetPerRow[r] = offset; offset += geo.NPads(r); } diff --git a/GPU/GPUTracking/TPCClusterFinder/TPCPadGainCalib.h b/GPU/GPUTracking/TPCClusterFinder/TPCPadGainCalib.h index d1ad18cd6d863..8a35348e4ea03 100644 --- a/GPU/GPUTracking/TPCClusterFinder/TPCPadGainCalib.h +++ b/GPU/GPUTracking/TPCClusterFinder/TPCPadGainCalib.h @@ -123,8 +123,8 @@ struct TPCPadGainCalib { } }; - unsigned short mPadOffsetPerRow[TPC_NUM_OF_ROWS]; - SectorPadGainCorrection mGainCorrection[TPC_SECTORS]; + unsigned short mPadOffsetPerRow[GPUCA_ROW_COUNT]; + SectorPadGainCorrection mGainCorrection[GPUCA_NSLICES]; }; } // namespace GPUCA_NAMESPACE::gpu diff --git a/GPU/GPUTracking/TPCClusterFinder/clusterFinderDefs.h b/GPU/GPUTracking/TPCClusterFinder/clusterFinderDefs.h index c4df31b9d7f86..6b8c4db8b74df 100644 --- a/GPU/GPUTracking/TPCClusterFinder/clusterFinderDefs.h +++ b/GPU/GPUTracking/TPCClusterFinder/clusterFinderDefs.h @@ -43,11 +43,9 @@ using ulong = unsigned long; #define PADDING_TIME 4 #define TPC_PADS_PER_ROW 144 -#define TPC_SECTORS 36 #define TPC_ROWS_PER_CRU 18 -#define TPC_NUM_OF_ROWS 152 #define TPC_PADS_PER_ROW_PADDED (TPC_PADS_PER_ROW + PADDING_PAD) -#define TPC_NUM_OF_PADS (TPC_NUM_OF_ROWS * TPC_PADS_PER_ROW_PADDED + PADDING_PAD) +#define TPC_NUM_OF_PADS (GPUCA_ROW_COUNT * TPC_PADS_PER_ROW_PADDED + PADDING_PAD) #define TPC_PADS_IN_SECTOR 14560 #define TPC_MAX_FRAGMENT_LEN 4000 #define TPC_MAX_FRAGMENT_LEN_PADDED (TPC_MAX_FRAGMENT_LEN + 2 * PADDING_TIME) From a63e96f84351ae334a3aeaee54f9fee89896f33c Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sun, 25 Apr 2021 11:35:34 +0200 Subject: [PATCH 278/770] GPU: Move TPC Pad gain calib map to DataTypes folder --- .../TPC/reconstruction/test/testGPUCATracking.cxx | 3 ++- GPU/GPUTracking/CMakeLists.txt | 4 ++-- .../TPCPadGainCalib.cxx | 0 .../{TPCClusterFinder => DataTypes}/TPCPadGainCalib.h | 0 .../clusterFinderDefs.h | 0 GPU/GPUTracking/Interface/GPUO2Interface.cxx | 11 +++++++++++ GPU/GPUTracking/Interface/GPUO2Interface.h | 5 +++++ GPU/Workflow/src/GPUWorkflowSpec.cxx | 5 +++-- 8 files changed, 23 insertions(+), 5 deletions(-) rename GPU/GPUTracking/{TPCClusterFinder => DataTypes}/TPCPadGainCalib.cxx (100%) rename GPU/GPUTracking/{TPCClusterFinder => DataTypes}/TPCPadGainCalib.h (100%) rename GPU/GPUTracking/{TPCClusterFinder => Definitions}/clusterFinderDefs.h (100%) diff --git a/Detectors/TPC/reconstruction/test/testGPUCATracking.cxx b/Detectors/TPC/reconstruction/test/testGPUCATracking.cxx index e4e7732e5eb54..8786d55b7a352 100644 --- a/Detectors/TPC/reconstruction/test/testGPUCATracking.cxx +++ b/Detectors/TPC/reconstruction/test/testGPUCATracking.cxx @@ -26,6 +26,7 @@ #include "TPCFastTransform.h" #include "TPCdEdxCalibrationSplines.h" +#include "GPUO2Interface.h" #include "GPUO2InterfaceConfiguration.h" #include "TPCPadGainCalib.h" @@ -77,7 +78,7 @@ BOOST_AUTO_TEST_CASE(CATracking_test1) config.configCalib.fastTransform = fastTransform.get(); std::unique_ptr dEdxSplines(new TPCdEdxCalibrationSplines); config.configCalib.dEdxSplines = dEdxSplines.get(); - std::unique_ptr gainCalib(new TPCPadGainCalib{}); + std::unique_ptr gainCalib = GPUO2Interface::getPadGainCalibDefault(); config.configCalib.tpcPadGain = gainCalib.get(); tracker.initialize(config); diff --git a/GPU/GPUTracking/CMakeLists.txt b/GPU/GPUTracking/CMakeLists.txt index 7a92d31311bcf..b6f98ea2dbc45 100644 --- a/GPU/GPUTracking/CMakeLists.txt +++ b/GPU/GPUTracking/CMakeLists.txt @@ -188,7 +188,7 @@ if(ALIGPU_BUILD_TYPE STREQUAL "O2" OR CONFIG_O2_EXTENSIONS) TPCClusterFinder/GPUTPCCFMCLabelFlattener.cxx TPCClusterFinder/GPUTPCCFDecodeZS.cxx TPCClusterFinder/GPUTPCCFGather.cxx - TPCClusterFinder/TPCPadGainCalib.cxx + DataTypes/TPCPadGainCalib.cxx Refit/GPUTrackingRefit.cxx Refit/GPUTrackingRefitKernel.cxx Merger/GPUTPCGMO2Output.cxx) @@ -203,7 +203,7 @@ if(ALIGPU_BUILD_TYPE STREQUAL "O2" OR CONFIG_O2_EXTENSIONS) TPCClusterFinder/CfFragment.h TPCClusterFinder/CfUtils.h TPCClusterFinder/ChargePos.h - TPCClusterFinder/clusterFinderDefs.h + Definitions/clusterFinderDefs.h TPCClusterFinder/GPUTPCClusterFinderKernels.h TPCClusterFinder/PackedCharge.h TPCClusterFinder/GPUTPCCFChainContext.h) diff --git a/GPU/GPUTracking/TPCClusterFinder/TPCPadGainCalib.cxx b/GPU/GPUTracking/DataTypes/TPCPadGainCalib.cxx similarity index 100% rename from GPU/GPUTracking/TPCClusterFinder/TPCPadGainCalib.cxx rename to GPU/GPUTracking/DataTypes/TPCPadGainCalib.cxx diff --git a/GPU/GPUTracking/TPCClusterFinder/TPCPadGainCalib.h b/GPU/GPUTracking/DataTypes/TPCPadGainCalib.h similarity index 100% rename from GPU/GPUTracking/TPCClusterFinder/TPCPadGainCalib.h rename to GPU/GPUTracking/DataTypes/TPCPadGainCalib.h diff --git a/GPU/GPUTracking/TPCClusterFinder/clusterFinderDefs.h b/GPU/GPUTracking/Definitions/clusterFinderDefs.h similarity index 100% rename from GPU/GPUTracking/TPCClusterFinder/clusterFinderDefs.h rename to GPU/GPUTracking/Definitions/clusterFinderDefs.h diff --git a/GPU/GPUTracking/Interface/GPUO2Interface.cxx b/GPU/GPUTracking/Interface/GPUO2Interface.cxx index 5a16963a05300..9dc8046392789 100644 --- a/GPU/GPUTracking/Interface/GPUO2Interface.cxx +++ b/GPU/GPUTracking/Interface/GPUO2Interface.cxx @@ -20,6 +20,7 @@ #include "GPUParam.inc" #include "GPUQA.h" #include "GPUOutputControl.h" +#include "TPCPadGainCalib.h" #include #include @@ -160,3 +161,13 @@ int GPUO2Interface::unregisterMemoryForGPU(const void* ptr) { return mRec->unregisterMemoryForGPU(ptr); } + +std::unique_ptr GPUO2Interface::getPadGainCalibDefault() +{ + return std::make_unique(); +} + +std::unique_ptr GPUO2Interface::getPadGainCalib(const o2::tpc::CalDet& in) +{ + return std::make_unique(in); +} diff --git a/GPU/GPUTracking/Interface/GPUO2Interface.h b/GPU/GPUTracking/Interface/GPUO2Interface.h index 757c4ed5aa0f7..e9a17351d16fa 100644 --- a/GPU/GPUTracking/Interface/GPUO2Interface.h +++ b/GPU/GPUTracking/Interface/GPUO2Interface.h @@ -33,6 +33,8 @@ namespace o2::tpc { struct ClusterNativeAccess; struct ClusterNative; +template +class CalDet; } // namespace o2::tpc namespace o2::gpu @@ -58,6 +60,9 @@ class GPUO2Interface bool GetParamContinuous() { return (mContinuous); } void GetClusterErrors2(int row, float z, float sinPhi, float DzDs, short clusterState, float& ErrY2, float& ErrZ2) const; + static std::unique_ptr getPadGainCalibDefault(); + static std::unique_ptr getPadGainCalib(const o2::tpc::CalDet& in); + int registerMemoryForGPU(const void* ptr, size_t size); int unregisterMemoryForGPU(const void* ptr); diff --git a/GPU/Workflow/src/GPUWorkflowSpec.cxx b/GPU/Workflow/src/GPUWorkflowSpec.cxx index a0b3b7b895263..42bfb3e5fa59c 100644 --- a/GPU/Workflow/src/GPUWorkflowSpec.cxx +++ b/GPU/Workflow/src/GPUWorkflowSpec.cxx @@ -45,6 +45,7 @@ #include "TPCBase/RDHUtils.h" #include "GPUO2InterfaceConfiguration.h" #include "GPUO2InterfaceQA.h" +#include "GPUO2Interface.h" #include "TPCPadGainCalib.h" #include "GPUDisplayBackend.h" #ifdef GPUCA_BUILD_EVENT_DISPLAY @@ -245,12 +246,12 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli if (boost::filesystem::exists(confParam.gainCalibFile)) { LOG(INFO) << "Loading tpc gain correction from file " << confParam.gainCalibFile; const auto* gainMap = o2::tpc::utils::readCalPads(confParam.gainCalibFile, "GainMap")[0]; - processAttributes->tpcPadGainCalib.reset(new TPCPadGainCalib{*gainMap}); + processAttributes->tpcPadGainCalib = GPUO2Interface::getPadGainCalib(*gainMap); } else { if (not confParam.gainCalibFile.empty()) { LOG(WARN) << "Couldn't find tpc gain correction file " << confParam.gainCalibFile << ". Not applying any gain correction."; } - processAttributes->tpcPadGainCalib.reset(new TPCPadGainCalib{}); + processAttributes->tpcPadGainCalib = GPUO2Interface::getPadGainCalibDefault(); } config.configCalib.tpcPadGain = processAttributes->tpcPadGainCalib.get(); From 1c33984ce61680a0cf0f76f41812d905df5cdc96 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sun, 25 Apr 2021 11:52:07 +0200 Subject: [PATCH 279/770] GPU: Refit Interface should not expose private headers of GPUTracking library --- .../Interface/GPUO2InterfaceRefit.cxx | 21 ++++++---- .../Interface/GPUO2InterfaceRefit.h | 38 +++++++++++++++---- 2 files changed, 44 insertions(+), 15 deletions(-) diff --git a/GPU/GPUTracking/Interface/GPUO2InterfaceRefit.cxx b/GPU/GPUTracking/Interface/GPUO2InterfaceRefit.cxx index 38f0cd9c18f0d..4c5a525219b4f 100644 --- a/GPU/GPUTracking/Interface/GPUO2InterfaceRefit.cxx +++ b/GPU/GPUTracking/Interface/GPUO2InterfaceRefit.cxx @@ -16,6 +16,7 @@ #include "DataFormatsTPC/TrackTPC.h" #include "GPUParam.h" #include "GPUTPCGMMergedTrackHit.h" +#include "GPUTrackingRefit.h" using namespace o2::gpu; using namespace o2::tpc; @@ -37,7 +38,7 @@ void GPUO2InterfaceRefit::fillSharedClustersMap(const ClusterNativeAccess* cl, c } } -GPUO2InterfaceRefit::GPUO2InterfaceRefit(const ClusterNativeAccess* cl, const TPCFastTransform* trans, float bz, const TPCClRefElem* trackRef, const unsigned char* sharedmap, const std::vector* trks, o2::base::Propagator* p) : mRefit(), mParam(new GPUParam) +GPUO2InterfaceRefit::GPUO2InterfaceRefit(const ClusterNativeAccess* cl, const TPCFastTransform* trans, float bz, const TPCClRefElem* trackRef, const unsigned char* sharedmap, const std::vector* trks, o2::base::Propagator* p) : mParam(new GPUParam) { if (sharedmap == nullptr && trks == nullptr) { throw std::runtime_error("Must provide either shared cluster map or vector of tpc tracks to build the map"); @@ -48,15 +49,21 @@ GPUO2InterfaceRefit::GPUO2InterfaceRefit(const ClusterNativeAccess* cl, const TP fillSharedClustersMap(cl, *trks, trackRef, mSharedMap.data()); } + mRefit = std::make_unique(); mParam->SetDefaults(bz); - mRefit.SetGPUParam(mParam.get()); - mRefit.SetClusterStateArray(sharedmap); - mRefit.SetPropagator(p); - mRefit.SetClusterNative(cl); - mRefit.SetTrackHitReferences(trackRef); - mRefit.SetFastTransform(trans); + mRefit->SetGPUParam(mParam.get()); + mRefit->SetClusterStateArray(sharedmap); + mRefit->SetPropagator(p); + mRefit->SetClusterNative(cl); + mRefit->SetTrackHitReferences(trackRef); + mRefit->SetFastTransform(trans); } +int GPUO2InterfaceRefit::RefitTrackAsGPU(o2::tpc::TrackTPC& trk, bool outward, bool resetCov) { return mRefit->RefitTrackAsGPU(trk, outward, resetCov); } +int GPUO2InterfaceRefit::RefitTrackAsTrackParCov(o2::tpc::TrackTPC& trk, bool outward, bool resetCov) { return mRefit->RefitTrackAsTrackParCov(trk, outward, resetCov); } +int GPUO2InterfaceRefit::RefitTrackAsGPU(o2::track::TrackParCov& trk, const o2::tpc::TrackTPCClusRef& clusRef, float time0, float* chi2, bool outward, bool resetCov) { return mRefit->RefitTrackAsGPU(trk, clusRef, time0, chi2, outward, resetCov); } +int GPUO2InterfaceRefit::RefitTrackAsTrackParCov(o2::track::TrackParCov& trk, const o2::tpc::TrackTPCClusRef& clusRef, float time0, float* chi2, bool outward, bool resetCov) { return mRefit->RefitTrackAsTrackParCov(trk, clusRef, time0, chi2, outward, resetCov); } +void GPUO2InterfaceRefit::setIgnoreErrorsAtTrackEnds(bool v) { mRefit->mIgnoreErrorsOnTrackEnds = v; } void GPUO2InterfaceRefit::setGPUTrackFitInProjections(bool v) { mParam->rec.fitInProjections = v; } void GPUO2InterfaceRefit::setTrackReferenceX(float v) { mParam->rec.TrackReferenceX = v; } diff --git a/GPU/GPUTracking/Interface/GPUO2InterfaceRefit.h b/GPU/GPUTracking/Interface/GPUO2InterfaceRefit.h index be15f79c2befb..6d620f47464e5 100644 --- a/GPU/GPUTracking/Interface/GPUO2InterfaceRefit.h +++ b/GPU/GPUTracking/Interface/GPUO2InterfaceRefit.h @@ -25,19 +25,41 @@ #define GPUCA_O2_INTERFACE #endif -#include "GPUTrackingRefit.h" #include #include #include +namespace o2::base +{ +template +class PropagatorImpl; +using Propagator = PropagatorImpl; +} // namespace o2::base +namespace o2::dataformats +{ +template +class RangeReference; +} namespace o2::tpc { using TPCClRefElem = uint32_t; -} +using TrackTPCClusRef = o2::dataformats::RangeReference; +class TrackTPC; +struct ClusterNativeAccess; +} // namespace o2::tpc +namespace o2::track +{ +template +class TrackParametrizationWithError; +using TrackParCovF = TrackParametrizationWithError; +using TrackParCov = TrackParCovF; +} // namespace o2::track namespace o2::gpu { class GPUParam; +class GPUTrackingRefit; +class TPCFastTransform; class GPUO2InterfaceRefit { public: @@ -49,18 +71,18 @@ class GPUO2InterfaceRefit GPUO2InterfaceRefit(const o2::tpc::ClusterNativeAccess* cl, const TPCFastTransform* trans, float bz, const o2::tpc::TPCClRefElem* trackRef, const unsigned char* sharedmap = nullptr, const std::vector* trks = nullptr, o2::base::Propagator* p = nullptr); ~GPUO2InterfaceRefit(); - int RefitTrackAsGPU(o2::tpc::TrackTPC& trk, bool outward = false, bool resetCov = false) { return mRefit.RefitTrackAsGPU(trk, outward, resetCov); } - int RefitTrackAsTrackParCov(o2::tpc::TrackTPC& trk, bool outward = false, bool resetCov = false) { return mRefit.RefitTrackAsTrackParCov(trk, outward, resetCov); } - int RefitTrackAsGPU(o2::track::TrackParCov& trk, const o2::tpc::TrackTPCClusRef& clusRef, float time0, float* chi2 = nullptr, bool outward = false, bool resetCov = false) { return mRefit.RefitTrackAsGPU(trk, clusRef, time0, chi2, outward, resetCov); } - int RefitTrackAsTrackParCov(o2::track::TrackParCov& trk, const o2::tpc::TrackTPCClusRef& clusRef, float time0, float* chi2 = nullptr, bool outward = false, bool resetCov = false) { return mRefit.RefitTrackAsTrackParCov(trk, clusRef, time0, chi2, outward, resetCov); } + int RefitTrackAsGPU(o2::tpc::TrackTPC& trk, bool outward = false, bool resetCov = false); + int RefitTrackAsTrackParCov(o2::tpc::TrackTPC& trk, bool outward = false, bool resetCov = false); + int RefitTrackAsGPU(o2::track::TrackParCov& trk, const o2::tpc::TrackTPCClusRef& clusRef, float time0, float* chi2 = nullptr, bool outward = false, bool resetCov = false); + int RefitTrackAsTrackParCov(o2::track::TrackParCov& trk, const o2::tpc::TrackTPCClusRef& clusRef, float time0, float* chi2 = nullptr, bool outward = false, bool resetCov = false); void setGPUTrackFitInProjections(bool v = true); void setTrackReferenceX(float v); - void setIgnoreErrorsAtTrackEnds(bool v) { mRefit.mIgnoreErrorsOnTrackEnds = v; } + void setIgnoreErrorsAtTrackEnds(bool v); static void fillSharedClustersMap(const o2::tpc::ClusterNativeAccess* cl, const gsl::span trks, const o2::tpc::TPCClRefElem* trackRef, unsigned char* shmap); private: - GPUTrackingRefit mRefit; + std::unique_ptr mRefit; std::unique_ptr mParam; std::vector mSharedMap; }; From e1a28fc44dfb1f7f2bb8840a6ccd9b60bd3182b1 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sun, 25 Apr 2021 12:14:39 +0200 Subject: [PATCH 280/770] GPU Interface: GPU Interface exposes getter for default calib splines, so you can create them without linking to full GPUTracking --- Detectors/TPC/reconstruction/test/testGPUCATracking.cxx | 2 +- GPU/GPUTracking/Interface/GPUO2Interface.cxx | 6 ++++++ GPU/GPUTracking/Interface/GPUO2Interface.h | 1 + 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Detectors/TPC/reconstruction/test/testGPUCATracking.cxx b/Detectors/TPC/reconstruction/test/testGPUCATracking.cxx index 8786d55b7a352..177d0b3ee1be0 100644 --- a/Detectors/TPC/reconstruction/test/testGPUCATracking.cxx +++ b/Detectors/TPC/reconstruction/test/testGPUCATracking.cxx @@ -76,7 +76,7 @@ BOOST_AUTO_TEST_CASE(CATracking_test1) std::unique_ptr fastTransform(TPCFastTransformHelperO2::instance()->create(0)); config.configCalib.fastTransform = fastTransform.get(); - std::unique_ptr dEdxSplines(new TPCdEdxCalibrationSplines); + std::unique_ptr dEdxSplines = GPUO2Interface::getdEdxCalibrationSplinesDefault(); config.configCalib.dEdxSplines = dEdxSplines.get(); std::unique_ptr gainCalib = GPUO2Interface::getPadGainCalibDefault(); config.configCalib.tpcPadGain = gainCalib.get(); diff --git a/GPU/GPUTracking/Interface/GPUO2Interface.cxx b/GPU/GPUTracking/Interface/GPUO2Interface.cxx index 9dc8046392789..78717ca32fc5a 100644 --- a/GPU/GPUTracking/Interface/GPUO2Interface.cxx +++ b/GPU/GPUTracking/Interface/GPUO2Interface.cxx @@ -21,6 +21,7 @@ #include "GPUQA.h" #include "GPUOutputControl.h" #include "TPCPadGainCalib.h" +#include "TPCdEdxCalibrationSplines.h" #include #include @@ -171,3 +172,8 @@ std::unique_ptr GPUO2Interface::getPadGainCalib(const o2::tpc:: { return std::make_unique(in); } + +std::unique_ptr GPUO2Interface::getdEdxCalibrationSplinesDefault() +{ + return std::make_unique(); +} diff --git a/GPU/GPUTracking/Interface/GPUO2Interface.h b/GPU/GPUTracking/Interface/GPUO2Interface.h index e9a17351d16fa..85765c2cac354 100644 --- a/GPU/GPUTracking/Interface/GPUO2Interface.h +++ b/GPU/GPUTracking/Interface/GPUO2Interface.h @@ -62,6 +62,7 @@ class GPUO2Interface static std::unique_ptr getPadGainCalibDefault(); static std::unique_ptr getPadGainCalib(const o2::tpc::CalDet& in); + static std::unique_ptr getdEdxCalibrationSplinesDefault(); int registerMemoryForGPU(const void* ptr, size_t size); int unregisterMemoryForGPU(const void* ptr); From 2ffc764f8ac6e1286aad5bd43fe4dfb5a98221ef Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sun, 25 Apr 2021 11:22:53 +0200 Subject: [PATCH 281/770] TPC: Reduce library dependency --- Detectors/GlobalTracking/CMakeLists.txt | 3 ++- Detectors/GlobalTracking/src/MatchTPCITS.cxx | 1 - Detectors/TPC/reconstruction/CMakeLists.txt | 2 +- Detectors/TPC/workflow/CMakeLists.txt | 4 +++- GPU/Workflow/CMakeLists.txt | 3 ++- 5 files changed, 8 insertions(+), 5 deletions(-) diff --git a/Detectors/GlobalTracking/CMakeLists.txt b/Detectors/GlobalTracking/CMakeLists.txt index aa05339f9a2a4..df01cf3f02f11 100644 --- a/Detectors/GlobalTracking/CMakeLists.txt +++ b/Detectors/GlobalTracking/CMakeLists.txt @@ -31,7 +31,8 @@ o2_add_library( O2::TOFCalibration O2::SimConfig O2::DataFormatsFT0 - O2::DataFormatsGlobalTracking) + O2::DataFormatsGlobalTracking + O2::ITStracking) o2_target_root_dictionary( GlobalTracking diff --git a/Detectors/GlobalTracking/src/MatchTPCITS.cxx b/Detectors/GlobalTracking/src/MatchTPCITS.cxx index 23f6236e1d824..6cbbb7aa633b7 100644 --- a/Detectors/GlobalTracking/src/MatchTPCITS.cxx +++ b/Detectors/GlobalTracking/src/MatchTPCITS.cxx @@ -42,7 +42,6 @@ #include "GlobalTracking/MatchTPCITS.h" #include "GPUO2Interface.h" // Needed for propper settings in GPUParam.h -#include "GPUParam.inc" // Consider more universal access using namespace o2::globaltracking; diff --git a/Detectors/TPC/reconstruction/CMakeLists.txt b/Detectors/TPC/reconstruction/CMakeLists.txt index 84d1304afc1cb..5c6d79aae44a2 100644 --- a/Detectors/TPC/reconstruction/CMakeLists.txt +++ b/Detectors/TPC/reconstruction/CMakeLists.txt @@ -32,7 +32,7 @@ o2_add_library(TPCReconstruction O2::SimulationDataFormat O2::TPCBase O2::GPUO2Interface - O2::GPUTracking + O2::TPCFastTransformation O2::DetectorsRaw) o2_target_root_dictionary( diff --git a/Detectors/TPC/workflow/CMakeLists.txt b/Detectors/TPC/workflow/CMakeLists.txt index b741b0fc3fd67..2d22b18cd1f59 100644 --- a/Detectors/TPC/workflow/CMakeLists.txt +++ b/Detectors/TPC/workflow/CMakeLists.txt @@ -30,7 +30,9 @@ o2_add_library(TPCWorkflow O2::DPLUtils O2::TPCReconstruction O2::TPCCalibration O2::TPCSimulation O2::TPCQC O2::DetectorsCalibration - O2::GPUWorkflow) + O2::GPUWorkflow + PRIVATE_LINK_LIBRARIES O2::GPUTracking # For the Zero Suppression includes + ) o2_add_executable(chunkeddigit-merger diff --git a/GPU/Workflow/CMakeLists.txt b/GPU/Workflow/CMakeLists.txt index 756eef86f26cb..4ba0580d59f1d 100644 --- a/GPU/Workflow/CMakeLists.txt +++ b/GPU/Workflow/CMakeLists.txt @@ -14,7 +14,8 @@ o2_add_library(GPUWorkflow PUBLIC_LINK_LIBRARIES O2::Framework O2::DataFormatsTPC O2::DPLUtils O2::TPCReconstruction O2::TPCCalibration O2::TPCSimulation - O2::TPCQC O2::DetectorsCalibration) + O2::TPCQC O2::DetectorsCalibration + PRIVATE_LINK_LIBRARIES O2::GPUTracking) o2_add_executable(reco-workflow COMPONENT_NAME gpu From d23359b4b7a0c84eae567d42617a692e7e2c21a9 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sun, 25 Apr 2021 09:00:53 +0200 Subject: [PATCH 282/770] GPU Display: Fix compiler warning --- GPU/GPUTracking/display/GPUDisplay.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/GPUTracking/display/GPUDisplay.cxx b/GPU/GPUTracking/display/GPUDisplay.cxx index 6b864c38f3f5d..efce7e90c08dd 100644 --- a/GPU/GPUTracking/display/GPUDisplay.cxx +++ b/GPU/GPUTracking/display/GPUDisplay.cxx @@ -954,7 +954,7 @@ void GPUDisplay::DrawFinal(int iSlice, int /*iCol*/, GPUTPCGMPropagator* prop, s mGlobalPosTRD[cid].w = tTRDATTACHED; } } - for (unsigned int k = 0; k < nClusters; k++) { + for (int k = 0; k < nClusters; k++) { if constexpr (std::is_same_v) { if (mHideRejectedClusters && (mIOPtrs->mergedTrackHits[track->FirstClusterRef() + k].state & GPUTPCGMMergedTrackHit::flagReject)) { continue; From 8b35b6f078ebe741ca8473e94780da2dbdd13dea Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sun, 25 Apr 2021 09:07:57 +0200 Subject: [PATCH 283/770] GPU Workflow: Only build when building AliGPU for O2 --- GPU/CMakeLists.txt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/GPU/CMakeLists.txt b/GPU/CMakeLists.txt index f36f5a379ab2f..2c96e07096167 100644 --- a/GPU/CMakeLists.txt +++ b/GPU/CMakeLists.txt @@ -21,4 +21,6 @@ add_subdirectory(Common) add_subdirectory(Utils) add_subdirectory(TPCFastTransformation) add_subdirectory(GPUTracking) -add_subdirectory(Workflow) +if(ALIGPU_BUILD_TYPE STREQUAL "O2") + add_subdirectory(Workflow) +endif() From 0a531e49756e553cd935fa7eaa1a3984698786e7 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sun, 25 Apr 2021 09:08:28 +0200 Subject: [PATCH 284/770] Fix CUDA version check, apparently the CMake way has changed meanwhile --- dependencies/FindO2GPU.cmake | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/dependencies/FindO2GPU.cmake b/dependencies/FindO2GPU.cmake index f3008f604b072..e878dd019ebf2 100644 --- a/dependencies/FindO2GPU.cmake +++ b/dependencies/FindO2GPU.cmake @@ -27,7 +27,6 @@ string(TOUPPER "${ENABLE_HIP}" ENABLE_HIP) # Detect and enable CUDA if(ENABLE_CUDA) - set(CUDA_MINIMUM_VERSION "11.3") set(CMAKE_CUDA_STANDARD 17) set(CMAKE_CUDA_STANDARD_REQUIRED TRUE) include(CheckLanguage) @@ -50,6 +49,9 @@ if(ENABLE_CUDA) if(THRUST_INCLUDE_DIR STREQUAL "THRUST_INCLUDE_DIR-NOTFOUND") message(FATAL_ERROR "CUDA found but thrust not available") endif() + if (NOT CMAKE_CUDA_COMPILER_VERSION VERSION_GREATER_EQUAL "11.3") + message(FATAL_ERROR "CUDA Version too old: ${CMAKE_CUDA_COMPILER_VERSION}, 11.3 required") + endif() # Forward CXX flags to CUDA C++ Host compiler (for warnings, gdb, etc.) STRING(REGEX REPLACE "\-std=[^ ]*" "" CMAKE_CXX_FLAGS_NOSTD ${CMAKE_CXX_FLAGS}) # Need to strip c++17 imposed by alidist defaults From 9e0cdf0599ea5c9fc53ca6a123f1076c96634274 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sun, 25 Apr 2021 08:53:31 +0200 Subject: [PATCH 285/770] GPU: Add OpenCL support for fp16 / pointers to non-standard types in kernel arguments --- .../Base/opencl-common/GPUReconstructionOCL.cl | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/GPU/GPUTracking/Base/opencl-common/GPUReconstructionOCL.cl b/GPU/GPUTracking/Base/opencl-common/GPUReconstructionOCL.cl index 1b3203032ec36..c222162c44ef4 100644 --- a/GPU/GPUTracking/Base/opencl-common/GPUReconstructionOCL.cl +++ b/GPU/GPUTracking/Base/opencl-common/GPUReconstructionOCL.cl @@ -19,10 +19,12 @@ #ifdef GPUCA_OPENCLCPP_NO_CONSTANT_MEMORY #define GPUCA_NO_CONSTANT_MEMORY #endif - #pragma OPENCL EXTENSION cl_khr_fp64 : enable + #pragma OPENCL EXTENSION cl_khr_fp64 : enable // Allow double precision variables + #pragma OPENCL EXTENSION cl_khr_fp16 : enable // Allow half precision #ifdef __clang__ - #pragma OPENCL EXTENSION cl_clang_storage_class_specifiers : enable - #pragma OPENCL EXTENSION __cl_clang_function_pointers : enable + #pragma OPENCL EXTENSION cl_clang_storage_class_specifiers : enable // + #pragma OPENCL EXTENSION __cl_clang_function_pointers : enable // Allow function pointers + #pragma OPENCL EXTENSION __cl_clang_allow_unsafe_kernel_parameters : enable // Allow pointers to non-standard types as kernel arguments #define global __global #define local __local #define constant __constant From bc99bc41cd3bb6ace6db5f5bd00e5dd18fab395c Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sun, 25 Apr 2021 08:53:44 +0200 Subject: [PATCH 286/770] TRD: AliRoot TRD geometry functions are non-const, and cannot work with a const geometry --- GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx index e6e55326b5190..61352f69013c6 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx @@ -564,6 +564,7 @@ GPUd() void GPUTRDTracker_t::DoTrackingThread(int iTrk, int thread mTracks[iTrk] = trkCopy; // copy back the resulting track } +#ifndef GPUCA_ALIROOT_LIB // AliRoot TRD geometry functions are non-const, and cannot work with a const geometry template GPUd() bool GPUTRDTracker_t::ConvertTrkltToSpacePoint(const GPUTRDGeometry& geo, GPUTRDTrackletWord& trklt, GPUTRDSpacePointInternal& sp) { @@ -595,6 +596,7 @@ GPUd() bool GPUTRDTracker_t::ConvertTrkltToSpacePoint(const GPUTRD sp.mVolumeId = volId; return true; } +#endif template GPUd() bool GPUTRDTracker_t::CalculateSpacePoints(int iCollision) From ea1a9a0dc2c7ce3bc4d59ad14c6ab830fedd0695 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sun, 25 Apr 2021 08:54:49 +0200 Subject: [PATCH 287/770] GPU: Update OpenCL test script --- GPU/GPUTracking/Standalone/tools/.gitignore | 1 + GPU/GPUTracking/Standalone/tools/testCL.sh | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/GPU/GPUTracking/Standalone/tools/.gitignore b/GPU/GPUTracking/Standalone/tools/.gitignore index 313c07d6e8ca4..6ddce7f156a23 100644 --- a/GPU/GPUTracking/Standalone/tools/.gitignore +++ b/GPU/GPUTracking/Standalone/tools/.gitignore @@ -2,3 +2,4 @@ *.bc *.cl *.spv +*.spirv diff --git a/GPU/GPUTracking/Standalone/tools/testCL.sh b/GPU/GPUTracking/Standalone/tools/testCL.sh index 3a53b724d1089..4f9ad94d4844e 100755 --- a/GPU/GPUTracking/Standalone/tools/testCL.sh +++ b/GPU/GPUTracking/Standalone/tools/testCL.sh @@ -6,8 +6,8 @@ LLVM_SPIRV=llvm-spirv #COMPILER=/usr/lib/llvm/roc-2.1.0/bin/clang++ #COMPILER=/usr/lib/llvm/9/bin/clang++ -#COMPILER=/home/qon/clang-build/install/bin/clang++ -#LLVM_SPIRV=/home/qon/clang-build/SPIRV-LLVM-Translator/build/tools/llvm-spirv/llvm-spirv +#COMPILER=/home/qon/alice/llvm-project/build/bin/clang++ +#LLVM_SPIRV=/home/qon/alice/llvm-project/build/bin/llvm-spirv INCLUDES="-I../. -I../DataTypes -I../Definitions -I../Base -I../SliceTracker -I../Common -I../Merger -I../Refit -I../TRDTracking -I../ITS -I../dEdx -I../TPCConvert -I../TPCFastTransformation -I../DataCompression -I../TPCClusterFinder -I../Global -I ../GPUUtils \ -I$HOME/alice/O2/DataFormats/Detectors/TPC/include -I$HOME/alice/O2/Detectors/Base/include -I$HOME/alice/O2/Detectors/Base/src -I$HOME/alice/O2/Common/MathUtils/include -I$HOME/alice/O2/DataFormats/Headers/include \ From 69bbd60e2be54d7479967b49d9bdfb731234f761 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Fri, 9 Apr 2021 16:12:08 +0200 Subject: [PATCH 288/770] DPL: make sure the WSDriverClient flushes only on main thread This will avoid thread safety issues within libuv. Notice this will most likely kill any rate limiting as currently implemented as I will need a protection against event loop being waken up by metrics rather than sigusr1. --- Framework/Core/src/WSDriverClient.cxx | 29 +++++++++++++++++---------- Framework/Core/src/WSDriverClient.h | 5 +++++ 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/Framework/Core/src/WSDriverClient.cxx b/Framework/Core/src/WSDriverClient.cxx index 20c54b5b8d89e..b9df0c92c5d52 100644 --- a/Framework/Core/src/WSDriverClient.cxx +++ b/Framework/Core/src/WSDriverClient.cxx @@ -95,6 +95,13 @@ WSDriverClient::WSDriverClient(ServiceRegistry& registry, DeviceState& state, ch // On successful connection we can then start to send commands to the driver. // We keep a backlog to make sure we do not lose messages. connectToDriver(this, state.loop, ip, port); + this->mAwakeMainThread = (uv_async_t*)malloc(sizeof(uv_async_t)); + uv_async_init(state.loop, this->mAwakeMainThread, nullptr); +} + +WSDriverClient::~WSDriverClient() +{ + free(this->mAwakeMainThread); } void sendMessageToDriver(std::unique_ptr& client, char const* message, size_t s) @@ -119,20 +126,20 @@ void WSDriverClient::observe(const char*, std::function) void WSDriverClient::tell(const char* msg, size_t s, bool flush) { - static bool printed1 = false; - static bool printed2 = false; - if (mConnected && mClient->isHandshaken() && flush) { - flushPending(); - std::lock_guard lock(mClientMutex); - std::vector outputs; - encode_websocket_frames(outputs, msg, s, WebSocketOpCode::Binary, 0); - mClient->write(outputs); - } else { - std::lock_guard lock(mClientMutex); - encode_websocket_frames(mBacklog, msg, s, WebSocketOpCode::Binary, 0); + // Tell will always accumulate and we signal the main thread we + // have metrics to push + std::lock_guard lock(mClientMutex); + encode_websocket_frames(mBacklog, msg, s, WebSocketOpCode::Binary, 0); + if (flush) { + this->awake(); } } +void WSDriverClient::awake() +{ + uv_async_send(mAwakeMainThread); +} + void WSDriverClient::flushPending() { std::lock_guard lock(mClientMutex); diff --git a/Framework/Core/src/WSDriverClient.h b/Framework/Core/src/WSDriverClient.h index b4314584168ab..c70ca0af9468b 100644 --- a/Framework/Core/src/WSDriverClient.h +++ b/Framework/Core/src/WSDriverClient.h @@ -20,6 +20,7 @@ #include typedef struct uv_connect_s uv_connect_t; +typedef struct uv_async_s uv_async_t; namespace o2::framework { @@ -36,6 +37,7 @@ class WSDriverClient : public DriverClient { public: WSDriverClient(ServiceRegistry& registry, DeviceState& state, char const* ip, unsigned short port); + ~WSDriverClient(); void tell(const char* msg, size_t s, bool flush = true) final; void observe(const char* command, std::function) final; void flushPending() final; @@ -47,11 +49,14 @@ class WSDriverClient : public DriverClient std::mutex& mutex() { return mClientMutex; } private: + /// Use this to awake the main thread. + void awake(); // Whether or not we managed to connect. std::atomic mConnected = false; std::mutex mClientMutex; DeviceSpec const& mSpec; std::vector mBacklog; + uv_async_t* mAwakeMainThread = nullptr; uv_connect_t* mConnection = nullptr; std::unique_ptr mClient; }; From 17beb364de6ba507b940f86d6d75a26c9b2c2230 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Mon, 12 Apr 2021 20:12:57 +0200 Subject: [PATCH 289/770] DPL: keep track of what triggered processing --- .../Core/include/Framework/DeviceState.h | 18 +++++ Framework/Core/src/DPLWebSocket.cxx | 65 ++++++++++++------ Framework/Core/src/DPLWebSocket.h | 9 ++- Framework/Core/src/DataProcessingDevice.cxx | 67 ++++++++++++++++--- Framework/Core/src/DeviceSpecHelpers.cxx | 12 +++- Framework/Core/src/DriverClientContext.h | 28 ++++++++ Framework/Core/src/WSDriverClient.cxx | 34 ++++++++-- 7 files changed, 189 insertions(+), 44 deletions(-) create mode 100644 Framework/Core/src/DriverClientContext.h diff --git a/Framework/Core/include/Framework/DeviceState.h b/Framework/Core/include/Framework/DeviceState.h index a3bfac05b7239..56f4d0228ccf8 100644 --- a/Framework/Core/include/Framework/DeviceState.h +++ b/Framework/Core/include/Framework/DeviceState.h @@ -37,6 +37,23 @@ enum struct StreamingState { /// Running state information of a given device struct DeviceState { + /// Motivation for the loop being triggered. + enum LoopReason : int { + NO_REASON = 0, // No tracked reason to wake up + METRICS_MUST_FLUSH = 1, // Metrics available to flush + SIGNAL_ARRIVED = 2, // Signal has arrived + DATA_SOCKET_POLLED = 4, // Data has arrived + DATA_INCOMING = 8, // Data was read + DATA_OUTGOING = 16, // Data was written + WS_COMMUNICATION = 32, // Communication over WS + TIMER_EXPIRED = 64, // Timer expired + WS_CONNECTED = 128, // Connection to driver established + WS_CLOSING = 256, // Events related to WS shutting down + WS_READING = 512, // Events related to WS shutting down + WS_WRITING = 1024, // Events related to WS shutting down + ASYNC_NOTIFICATION = 2048 + }; + std::vector inputChannelInfos; StreamingState streaming = StreamingState::Streaming; bool quitRequested = false; @@ -50,6 +67,7 @@ struct DeviceState { std::vector activeOutputPollers; /// The list of active signal handlers std::vector activeSignals; + int loopReason = 0; }; } // namespace o2::framework diff --git a/Framework/Core/src/DPLWebSocket.cxx b/Framework/Core/src/DPLWebSocket.cxx index 90ea6280a49da..3fe1092e343f0 100644 --- a/Framework/Core/src/DPLWebSocket.cxx +++ b/Framework/Core/src/DPLWebSocket.cxx @@ -13,6 +13,7 @@ #include "Framework/DeviceSpec.h" #include "Framework/DeviceController.h" #include "DriverServerContext.h" +#include "DriverClientContext.h" #include "HTTPParser.h" #include #include @@ -241,8 +242,9 @@ void close_client_websocket(uv_handle_t* stream) void websocket_client_callback(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) { - WSDPLClient* client = (WSDPLClient*)stream->data; - assert(client); + DriverClientContext* context = (DriverClientContext*)stream->data; + context->state->loopReason |= DeviceState::WS_COMMUNICATION; + assert(context->client); if (nread == 0) { return; } @@ -262,7 +264,7 @@ void websocket_client_callback(uv_stream_t* stream, ssize_t nread, const uv_buf_ } try { LOG(debug) << "Data received from server"; - parse_http_request(buf->base, nread, client); + parse_http_request(buf->base, nread, context->client); } catch (RuntimeErrorRef& ref) { auto& err = o2::framework::error_from_ref(ref); LOG(ERROR) << "Error while parsing request: " << err.what; @@ -270,14 +272,15 @@ void websocket_client_callback(uv_stream_t* stream, ssize_t nread, const uv_buf_ } // FIXME: mNonce should be random -WSDPLClient::WSDPLClient(uv_stream_t* s, DeviceSpec const& spec, std::function handshake, std::unique_ptr handler) +WSDPLClient::WSDPLClient(uv_stream_t* s, std::unique_ptr context, std::function handshake, std::unique_ptr handler) : mStream{s}, mNonce{"dGhlIHNhbXBsZSBub25jZQ=="}, - mSpec{spec}, + mContext{std::move(context)}, mHandshake{handshake}, mHandler{std::move(handler)} { - s->data = this; + mContext->client = this; + s->data = mContext.get(); uv_read_start((uv_stream_t*)s, (uv_alloc_cb)my_alloc_cb, websocket_client_callback); } @@ -285,8 +288,8 @@ void WSDPLClient::sendHandshake() { std::vector> headers = { {{"x-dpl-pid"}, std::to_string(getpid())}, - {{"x-dpl-id"}, mSpec.id}, - {{"x-dpl-name"}, mSpec.name}}; + {{"x-dpl-id"}, mContext->spec.id}, + {{"x-dpl-name"}, mContext->spec.name}}; std::string handShakeString = encode_websocket_handshake_request("/", "dpl", 13, mNonce.c_str(), headers); this->write(handShakeString.c_str(), handShakeString.size()); } @@ -341,33 +344,47 @@ void WSDPLClient::endHeaders() mHandshake(); } +struct WriteRequestContext { + uv_buf_t buf; + DeviceState* state; +}; + +struct BulkWriteRequestContext { + std::vector buffers; + DeviceState* state; +}; + void ws_client_write_callback(uv_write_t* h, int status) { + WriteRequestContext* context = (WriteRequestContext*)h->data; if (status) { LOG(ERROR) << "uv_write error: " << uv_err_name(status); free(h); return; } - if (h->data) { - free(h->data); + context->state->loopReason |= DeviceState::WS_COMMUNICATION; + if (context->buf.base) { + free(context->buf.base); } + delete context; free(h); } void ws_client_bulk_write_callback(uv_write_t* h, int status) { - if (status) { + BulkWriteRequestContext* context = (BulkWriteRequestContext*)h->data; + context->state->loopReason |= DeviceState::WS_COMMUNICATION; + if (status < 0) { LOG(ERROR) << "uv_write error: " << uv_err_name(status); free(h); return; } - std::vector* buffers = (std::vector*)h->data; - if (buffers) { - for (auto& b : *buffers) { + if (context->buffers.size()) { + for (auto& b : context->buffers) { free(b.base); } } - delete buffers; + delete context; free(h); } @@ -380,10 +397,12 @@ void WSDPLClient::body(char* data, size_t s) /// Helper to return an error void WSDPLClient::write(char const* message, size_t s) { - uv_buf_t bfr = uv_buf_init(strdup(message), s); + WriteRequestContext* context = new WriteRequestContext; + context->buf = uv_buf_init(strdup(message), s); + context->state = mContext->state; uv_write_t* write_req = (uv_write_t*)malloc(sizeof(uv_write_t)); - write_req->data = bfr.base; - uv_write(write_req, (uv_stream_t*)mStream, &bfr, 1, ws_client_write_callback); + write_req->data = context; + uv_write(write_req, (uv_stream_t*)mStream, &context->buf, 1, ws_client_write_callback); } void WSDPLClient::write(std::vector& outputs) @@ -392,10 +411,12 @@ void WSDPLClient::write(std::vector& outputs) return; } uv_write_t* write_req = (uv_write_t*)malloc(sizeof(uv_write_t)); - std::vector* buffers = new std::vector; - buffers->swap(outputs); - write_req->data = buffers; - uv_write(write_req, (uv_stream_t*)mStream, &buffers->at(0), buffers->size(), ws_client_bulk_write_callback); + BulkWriteRequestContext* context = new BulkWriteRequestContext; + context->buffers.swap(outputs); + context->state = mContext->state; + write_req->data = context; + uv_write(write_req, (uv_stream_t*)mStream, &context->buffers.at(0), + context->buffers.size(), ws_client_bulk_write_callback); } } // namespace o2::framework diff --git a/Framework/Core/src/DPLWebSocket.h b/Framework/Core/src/DPLWebSocket.h index 66e4cd4f1a91d..da08b01e7efa2 100644 --- a/Framework/Core/src/DPLWebSocket.h +++ b/Framework/Core/src/DPLWebSocket.h @@ -25,6 +25,7 @@ namespace o2::framework struct DeviceSpec; struct DriverServerContext; +struct DriverClientContext; struct WSError { int code; @@ -66,7 +67,11 @@ struct WSDPLClient : public HTTPParser { /// to the driver. /// @a spec the DeviceSpec associated with this client /// @a handshake a callback to invoke whenever we have a successful handshake - WSDPLClient(uv_stream_t* stream, DeviceSpec const& spec, std::function handshake, std::unique_ptr handler); + WSDPLClient(uv_stream_t* stream, + std::unique_ptr context, + std::function handshake, + std::unique_ptr handler); + void replyVersion(std::string_view const& s) override; void replyCode(std::string_view const& s) override; void header(std::string_view const& k, std::string_view const& v) override; @@ -85,9 +90,9 @@ struct WSDPLClient : public HTTPParser { bool isHandshaken() { return mHandshaken; } std::string mNonce; - DeviceSpec const& mSpec; std::atomic mHandshaken = false; std::function mHandshake; + std::unique_ptr mContext; std::unique_ptr mHandler; uv_stream_t* mStream = nullptr; std::map mHeaders; diff --git a/Framework/Core/src/DataProcessingDevice.cxx b/Framework/Core/src/DataProcessingDevice.cxx index ce9d582194d70..08c74657157df 100644 --- a/Framework/Core/src/DataProcessingDevice.cxx +++ b/Framework/Core/src/DataProcessingDevice.cxx @@ -73,9 +73,11 @@ struct ServiceKindExtractor { /// We schedule a timer to reduce CPU usage. /// Watching stdin for commands probably a better approach. -void idle_timer(uv_timer_t* handle) +void on_idle_timer(uv_timer_t* handle) { ZoneScopedN("Idle timer"); + DeviceState* state = (DeviceState*)handle->data; + state->loopReason |= DeviceState::TIMER_EXPIRED; } DataProcessingDevice::DataProcessingDevice(RunningWorkflowInfo const& runningWorkflow, RunningDeviceRef ref, ServiceRegistry& registry, DeviceState& state) @@ -140,23 +142,27 @@ void run_completion(uv_work_t* handle, int status) // Context for polling struct PollerContext { - char const* name; - uv_loop_t* loop; - DataProcessingDevice* device; + char const* name = nullptr; + uv_loop_t* loop = nullptr; + DataProcessingDevice* device = nullptr; + DeviceState* state = nullptr; int fd; }; void on_socket_polled(uv_poll_t* poller, int status, int events) { PollerContext* context = (PollerContext*)poller->data; + context->state->loopReason |= DeviceState::DATA_SOCKET_POLLED; switch (events) { case UV_READABLE: { ZoneScopedN("socket readable event"); LOG(debug) << "socket polled UV_READABLE: " << context->name; + context->state->loopReason |= DeviceState::DATA_INCOMING; } break; case UV_WRITABLE: { ZoneScopedN("socket writeable"); LOG(debug) << "socket polled UV_WRITEABLE"; + context->state->loopReason |= DeviceState::DATA_OUTGOING; } break; case UV_DISCONNECT: { ZoneScopedN("socket disconnect"); @@ -170,6 +176,12 @@ void on_socket_polled(uv_poll_t* poller, int status, int events) // We do nothing, all the logic for now stays in DataProcessingDevice::doRun() } +void on_communication_requested(uv_async_t* s) +{ + DeviceState* state = (DeviceState*)s->data; + state->loopReason |= DeviceState::METRICS_MUST_FLUSH; +} + /// This takes care of initialising the device from its specification. In /// particular it needs to: /// @@ -264,7 +276,8 @@ void DataProcessingDevice::Init() } uv_async_t* wakeHandle = (uv_async_t*)malloc(sizeof(uv_async_t)); assert(mState.loop); - int res = uv_async_init(mState.loop, wakeHandle, nullptr); + int res = uv_async_init(mState.loop, wakeHandle, on_communication_requested); + wakeHandle->data = &mState; if (res < 0) { LOG(ERROR) << "Unable to initialise subscription"; } @@ -283,6 +296,8 @@ void on_signal_callback(uv_signal_t* handle, int signum) { ZoneScopedN("Signal callaback"); LOG(debug) << "Signal " << signum << " received."; + DeviceState* state = (DeviceState*)handle->data; + state->loopReason |= DeviceState::SIGNAL_ARRIVED; } void DataProcessingDevice::InitTask() @@ -305,12 +320,8 @@ void DataProcessingDevice::InitTask() // is no data pending to be processed. uv_signal_t* sigusr1Handle = (uv_signal_t*)malloc(sizeof(uv_signal_t)); uv_signal_init(mState.loop, sigusr1Handle); + sigusr1Handle->data = &mState; uv_signal_start(sigusr1Handle, on_signal_callback, SIGUSR1); - // Handle SIGWINCH by simply forcing the event loop to continue. - // This will hopefully hide it from FairMQ on linux. - uv_signal_t* sigwinchHandle = (uv_signal_t*)malloc(sizeof(uv_signal_t)); - uv_signal_init(mState.loop, sigwinchHandle); - uv_signal_start(sigwinchHandle, on_signal_callback, SIGWINCH); // We add a timer only in case a channel poller is not there. if ((mStatefulProcess != nullptr) || (mStatelessProcess != nullptr)) { @@ -340,6 +351,7 @@ void DataProcessingDevice::InitTask() pCtx->name = strdup(x.first.c_str()); pCtx->loop = mState.loop; pCtx->device = this; + pCtx->state = &mState; pCtx->fd = zmq_fd; poller->data = pCtx; uv_poll_init(mState.loop, poller, zmq_fd); @@ -372,6 +384,7 @@ void DataProcessingDevice::InitTask() pCtx->name = strdup(x.first.c_str()); pCtx->loop = mState.loop; pCtx->device = this; + pCtx->state = &mState; pCtx->fd = zmq_fd; poller->data = pCtx; uv_poll_init(mState.loop, poller, zmq_fd); @@ -385,7 +398,8 @@ void DataProcessingDevice::InitTask() // A two second timer to stop internal devices which do not want to uv_timer_t* timer = (uv_timer_t*)malloc(sizeof(uv_timer_t)); uv_timer_init(mState.loop, timer); - uv_timer_start(timer, idle_timer, 2000, 2000); + timer->data = &mState; + uv_timer_start(timer, on_idle_timer, 2000, 2000); mState.activeTimers.push_back(timer); } @@ -453,6 +467,37 @@ bool DataProcessingDevice::ConditionalRun() shouldNotWait = true; } uv_run(mState.loop, shouldNotWait ? UV_RUN_NOWAIT : UV_RUN_ONCE); + if (mDataProcessorContexes.at(0).state->loopReason & DeviceState::METRICS_MUST_FLUSH) { + LOG(debug) << "New metric to be sent"; + } + if (mDataProcessorContexes.at(0).state->loopReason & DeviceState::SIGNAL_ARRIVED) { + LOG(debug) << "Signal arrived"; + } + if (mDataProcessorContexes.at(0).state->loopReason & DeviceState::DATA_SOCKET_POLLED) { + LOG(debug) << "Socket polled"; + } + if (mDataProcessorContexes.at(0).state->loopReason & DeviceState::DATA_INCOMING) { + LOG(debug) << "Data read"; + } + if (mDataProcessorContexes.at(0).state->loopReason & DeviceState::DATA_OUTGOING) { + LOG(debug) << "Data written"; + } + if (mDataProcessorContexes.at(0).state->loopReason & DeviceState::WS_COMMUNICATION) { + LOG(debug) << "Communication with WS"; + } + if (mDataProcessorContexes.at(0).state->loopReason & DeviceState::TIMER_EXPIRED) { + LOG(debug) << "Timer expired"; + } + if (mDataProcessorContexes.at(0).state->loopReason & DeviceState::WS_CONNECTED) { + LOG(debug) << "WS Connected"; + } + if (shouldNotWait) { + LOG(debug) << "Should not wait"; + } + if ((mDataProcessorContexes.at(0).state->loopReason == DeviceState::NO_REASON) && (shouldNotWait == false)) { + LOG(debug) << "Unknown reason to trigger the loop"; + } + mDataProcessorContexes.at(0).state->loopReason = DeviceState::NO_REASON; // A new state was requested, we exit. if (NewStatePending()) { diff --git a/Framework/Core/src/DeviceSpecHelpers.cxx b/Framework/Core/src/DeviceSpecHelpers.cxx index ac76eddbc91fd..314007373fcfc 100644 --- a/Framework/Core/src/DeviceSpecHelpers.cxx +++ b/Framework/Core/src/DeviceSpecHelpers.cxx @@ -51,14 +51,20 @@ namespace o2::framework namespace detail { -void timer_callback(uv_timer_t*) +void timer_callback(uv_timer_t* handle) { // We simply wake up the event loop. Nothing to be done here. + DeviceState* state = (DeviceState*)handle->data; + state->loopReason |= DeviceState::TIMER_EXPIRED; + state->loopReason |= DeviceState::DATA_INCOMING; } -void signal_callback(uv_signal_t*, int) +void signal_callback(uv_signal_t* handle, int) { // We simply wake up the event loop. Nothing to be done here. + DeviceState* state = (DeviceState*)handle->data; + state->loopReason |= DeviceState::SIGNAL_ARRIVED; + state->loopReason |= DeviceState::DATA_INCOMING; } } // namespace detail @@ -77,6 +83,7 @@ struct ExpirationHandlerHelpers { // timeslot creation and record expiration still happens // in a synchronous way. uv_timer_t* timer = (uv_timer_t*)(malloc(sizeof(uv_timer_t))); + timer->data = &state; uv_timer_init(state.loop, timer); uv_timer_start(timer, detail::timer_callback, period / 1000, period / 1000); state.activeTimers.push_back(timer); @@ -99,6 +106,7 @@ struct ExpirationHandlerHelpers { // in a synchronous way. uv_signal_t* sh = (uv_signal_t*)(malloc(sizeof(uv_signal_t))); uv_signal_init(state.loop, sh); + sh->data = &state; uv_signal_start(sh, detail::signal_callback, SIGUSR1); state.activeSignals.push_back(sh); diff --git a/Framework/Core/src/DriverClientContext.h b/Framework/Core/src/DriverClientContext.h new file mode 100644 index 0000000000000..251c1a067eb60 --- /dev/null +++ b/Framework/Core/src/DriverClientContext.h @@ -0,0 +1,28 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. +/// Helper struct which holds all the lists the Driver needs to know about. +#ifndef O2_FRAMEWORK_DRIVERCLIENTCONTEXT_H_ +#define O2_FRAMEWORK_DRIVERCLIENTCONTEXT_H_ + +namespace o2::framework +{ +struct DeviceSpec; +struct DeviceState; +struct WSDPLClient; + +/// Context for the client callbacks +struct DriverClientContext { + DeviceSpec const& spec; + DeviceState* state = nullptr; + WSDPLClient* client = nullptr; +}; +} // namespace o2::framework + +#endif // O2_FRAMEWORK_DRIVERCLIENTCONTEXT_H_ diff --git a/Framework/Core/src/WSDriverClient.cxx b/Framework/Core/src/WSDriverClient.cxx index b9df0c92c5d52..a4dc60fdb3623 100644 --- a/Framework/Core/src/WSDriverClient.cxx +++ b/Framework/Core/src/WSDriverClient.cxx @@ -9,9 +9,11 @@ // or submit itself to any jurisdiction. #include "WSDriverClient.h" #include "Framework/DeviceState.h" +#include "Framework/DeviceSpec.h" #include "Framework/Logger.h" #include "Framework/ServiceRegistry.h" #include "Framework/DeviceSpec.h" +#include "DriverClientContext.h" #include "DPLWebSocket.h" #include @@ -58,29 +60,40 @@ struct ClientWebSocketHandler : public WebSocketHandler { WSDriverClient& mClient; }; +struct ConnectionContext { + WSDriverClient* client; + DeviceState* state; +}; + void on_connect(uv_connect_t* connection, int status) { if (status < 0) { LOG(ERROR) << "Unable to connect to driver."; return; } - WSDriverClient* client = (WSDriverClient*)connection->data; + ConnectionContext* context = (ConnectionContext*)connection->data; + WSDriverClient* client = context->client; + context->state->loopReason |= DeviceState::WS_CONNECTED; auto onHandshake = [client]() { client->flushPending(); }; std::lock_guard lock(client->mutex()); auto handler = std::make_unique(*client); - client->setDPLClient(std::make_unique(connection->handle, client->spec(), onHandshake, std::move(handler))); + auto clientContext = std::make_unique(DriverClientContext{client->spec(), context->state}); + client->setDPLClient(std::make_unique(connection->handle, std::move(clientContext), onHandshake, std::move(handler))); client->sendHandshake(); } /// Helper to connect to a -void connectToDriver(WSDriverClient* driver, uv_loop_t* loop, char const* address, short port) +void connectToDriver(WSDriverClient* driver, DeviceState* state, char const* address, short port) { uv_tcp_t* socket = (uv_tcp_t*)malloc(sizeof(uv_tcp_t)); - uv_tcp_init(loop, socket); + uv_tcp_init(state->loop, socket); uv_connect_t* connection = (uv_connect_t*)malloc(sizeof(uv_connect_t)); - connection->data = driver; + ConnectionContext* context = new ConnectionContext; + context->client = driver; + context->state = state; + connection->data = context; struct sockaddr_in dest; uv_ip4_addr(strdup(address), port, &dest); @@ -88,15 +101,22 @@ void connectToDriver(WSDriverClient* driver, uv_loop_t* loop, char const* addres uv_tcp_connect(connection, socket, (const struct sockaddr*)&dest, on_connect); } +void on_awake_main_thread(uv_async_t* handle) +{ + DeviceState* state = (DeviceState*)handle->data; + state->loopReason |= DeviceState::ASYNC_NOTIFICATION; +} + WSDriverClient::WSDriverClient(ServiceRegistry& registry, DeviceState& state, char const* ip, unsigned short port) : mSpec{registry.get()} { // Must connect the device to the server and send a websocket request. // On successful connection we can then start to send commands to the driver. // We keep a backlog to make sure we do not lose messages. - connectToDriver(this, state.loop, ip, port); + connectToDriver(this, &state, ip, port); this->mAwakeMainThread = (uv_async_t*)malloc(sizeof(uv_async_t)); - uv_async_init(state.loop, this->mAwakeMainThread, nullptr); + this->mAwakeMainThread->data = &state; + uv_async_init(state.loop, this->mAwakeMainThread, on_awake_main_thread); } WSDriverClient::~WSDriverClient() From ebf908482499a4ac6c917e9969f76c7a609d7f31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B2=20Jacazio?= Date: Tue, 27 Apr 2021 08:03:40 +0200 Subject: [PATCH 290/770] Remove virtual before override (#6005) --- Analysis/DataModel/include/AnalysisDataModel/PID/ParamBase.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Analysis/DataModel/include/AnalysisDataModel/PID/ParamBase.h b/Analysis/DataModel/include/AnalysisDataModel/PID/ParamBase.h index fbcefac1157ff..bc9f33bc4aee0 100644 --- a/Analysis/DataModel/include/AnalysisDataModel/PID/ParamBase.h +++ b/Analysis/DataModel/include/AnalysisDataModel/PID/ParamBase.h @@ -71,7 +71,7 @@ class Parameters : public TNamed void SetParameters(const Parameters* params) { SetParameters(params->mPar); }; /// Printer of the parameter values - virtual void Print(Option_t* option = "") const override; + void Print(Option_t* option = "") const override; /// Loader from file /// \param FileName name of the input file @@ -123,7 +123,7 @@ class Parametrization : public TNamed virtual pidvar_t operator()(const pidvar_t* x) const; /// Printer for the parametrization - virtual void Print(Option_t* option = "") const override; + void Print(Option_t* option = "") const override; /// Loader from file /// \param FileName name of the input file From f4538e1b05780600b72178b5b49adca0eb6c2d54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B2=20Jacazio?= Date: Tue, 27 Apr 2021 08:04:43 +0200 Subject: [PATCH 291/770] PID: autoenabling the tables needed for analysis (#6007) --- Analysis/Tasks/PID/pidTOF.cxx | 54 +++++++++++++++++++++--------- Analysis/Tasks/PID/pidTOF_tiny.cxx | 52 ++++++++++++++++++++-------- Analysis/Tasks/PID/pidTPC.cxx | 54 +++++++++++++++++++++--------- Analysis/Tasks/PID/pidTPC_tiny.cxx | 54 +++++++++++++++++++++--------- 4 files changed, 155 insertions(+), 59 deletions(-) diff --git a/Analysis/Tasks/PID/pidTOF.cxx b/Analysis/Tasks/PID/pidTOF.cxx index d6b77ba8e89b8..5727eefcfcaf7 100644 --- a/Analysis/Tasks/PID/pidTOF.cxx +++ b/Analysis/Tasks/PID/pidTOF.cxx @@ -9,7 +9,7 @@ // or submit itself to any jurisdiction. /// -/// \file pidTOF_split.cxx +/// \file pidTOF.cxx /// \author Nicolo' Jacazio /// \brief Task to produce PID tables for TOF split for each particle. /// Only the tables for the mass hypotheses requested are filled, the others are sent empty. @@ -18,6 +18,7 @@ // O2 includes #include "Framework/AnalysisTask.h" #include "Framework/HistogramRegistry.h" +#include "Framework/RunningWorkflowInfo.h" #include "ReconstructionDataFormats/Track.h" #include #include "AnalysisDataModel/PID/PIDResponse.h" @@ -38,7 +39,7 @@ void customize(std::vector& workflowOptions) #include "Framework/runDataProcessing.h" -struct pidTOFTaskSplit { +struct tofPid { using Trks = soa::Join; using Coll = aod::Collisions; // Tables to produce @@ -59,18 +60,41 @@ struct pidTOFTaskSplit { Configurable url{"ccdb-url", "http://ccdb-test.cern.ch:8080", "url of the ccdb repository"}; Configurable timestamp{"ccdb-timestamp", -1, "timestamp of the object"}; // Configuration flags to include and exclude particle hypotheses - Configurable pidEl{"pid-el", 0, {"Produce PID information for the Electron mass hypothesis"}}; - Configurable pidMu{"pid-mu", 0, {"Produce PID information for the Muon mass hypothesis"}}; - Configurable pidPi{"pid-pi", 0, {"Produce PID information for the Pion mass hypothesis"}}; - Configurable pidKa{"pid-ka", 0, {"Produce PID information for the Kaon mass hypothesis"}}; - Configurable pidPr{"pid-pr", 0, {"Produce PID information for the Proton mass hypothesis"}}; - Configurable pidDe{"pid-de", 0, {"Produce PID information for the Deuterons mass hypothesis"}}; - Configurable pidTr{"pid-tr", 0, {"Produce PID information for the Triton mass hypothesis"}}; - Configurable pidHe{"pid-he", 0, {"Produce PID information for the Helium3 mass hypothesis"}}; - Configurable pidAl{"pid-al", 0, {"Produce PID information for the Alpha mass hypothesis"}}; + Configurable pidEl{"pid-el", -1, {"Produce PID information for the Electron mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidMu{"pid-mu", -1, {"Produce PID information for the Muon mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidPi{"pid-pi", -1, {"Produce PID information for the Pion mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidKa{"pid-ka", -1, {"Produce PID information for the Kaon mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidPr{"pid-pr", -1, {"Produce PID information for the Proton mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidDe{"pid-de", -1, {"Produce PID information for the Deuterons mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidTr{"pid-tr", -1, {"Produce PID information for the Triton mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidHe{"pid-he", -1, {"Produce PID information for the Helium3 mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidAl{"pid-al", -1, {"Produce PID information for the Alpha mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; - void init(o2::framework::InitContext&) + void init(o2::framework::InitContext& initContext) { + // Checking the tables are requested in the workflow and enabling them + auto& workflows = initContext.services().get(); + for (DeviceSpec device : workflows.devices) { + for (auto input : device.inputs) { + auto enableFlag = [&input](const std::string particle, Configurable& flag) { + if (input.matcher.binding == "pidRespTOF" + particle) { + if (flag < 0) { + flag.value = 1; + } + } + }; + enableFlag("El", pidEl); + enableFlag("Mu", pidMu); + enableFlag("Pi", pidPi); + enableFlag("Ka", pidKa); + enableFlag("Pr", pidPr); + enableFlag("De", pidDe); + enableFlag("Tr", pidTr); + enableFlag("He", pidHe); + enableFlag("Al", pidAl); + } + } + // Getting the parametrization parameters ccdb->setURL(url.value); ccdb->setTimestamp(timestamp.value); ccdb->setCaching(true); @@ -126,7 +150,7 @@ struct pidTOFTaskSplit { } }; -struct pidTOFTaskQA { +struct tofPidQa { static constexpr int Np = 9; static constexpr const char* pT[Np] = {"e", "#mu", "#pi", "K", "p", "d", "t", "^{3}He", "#alpha"}; @@ -265,9 +289,9 @@ struct pidTOFTaskQA { WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { - auto workflow = WorkflowSpec{adaptAnalysisTask(cfgc, TaskName{"pidTOF-split-task"})}; + auto workflow = WorkflowSpec{adaptAnalysisTask(cfgc)}; if (cfgc.options().get("add-qa")) { - workflow.push_back(adaptAnalysisTask(cfgc, TaskName{"pidTOFQA-task"})); + workflow.push_back(adaptAnalysisTask(cfgc)); } return workflow; } diff --git a/Analysis/Tasks/PID/pidTOF_tiny.cxx b/Analysis/Tasks/PID/pidTOF_tiny.cxx index 3d946bb3d38bb..b25a67375de2a 100644 --- a/Analysis/Tasks/PID/pidTOF_tiny.cxx +++ b/Analysis/Tasks/PID/pidTOF_tiny.cxx @@ -18,6 +18,7 @@ // O2 includes #include "Framework/AnalysisTask.h" #include "Framework/HistogramRegistry.h" +#include "Framework/RunningWorkflowInfo.h" #include "ReconstructionDataFormats/Track.h" #include #include "AnalysisDataModel/PID/PIDResponse.h" @@ -38,7 +39,7 @@ void customize(std::vector& workflowOptions) #include "Framework/runDataProcessing.h" -struct pidTOFTaskTiny { +struct tofPidTiny { using Trks = soa::Join; using Coll = aod::Collisions; // Tables to produce @@ -59,18 +60,41 @@ struct pidTOFTaskTiny { Configurable url{"ccdb-url", "http://ccdb-test.cern.ch:8080", "url of the ccdb repository"}; Configurable timestamp{"ccdb-timestamp", -1, "timestamp of the object"}; // Configuration flags to include and exclude particle hypotheses - Configurable pidEl{"pid-el", 0, {"Produce PID information for the Electron mass hypothesis"}}; - Configurable pidMu{"pid-mu", 0, {"Produce PID information for the Muon mass hypothesis"}}; - Configurable pidPi{"pid-pi", 0, {"Produce PID information for the Pion mass hypothesis"}}; - Configurable pidKa{"pid-ka", 0, {"Produce PID information for the Kaon mass hypothesis"}}; - Configurable pidPr{"pid-pr", 0, {"Produce PID information for the Proton mass hypothesis"}}; - Configurable pidDe{"pid-de", 0, {"Produce PID information for the Deuterons mass hypothesis"}}; - Configurable pidTr{"pid-tr", 0, {"Produce PID information for the Triton mass hypothesis"}}; - Configurable pidHe{"pid-he", 0, {"Produce PID information for the Helium3 mass hypothesis"}}; - Configurable pidAl{"pid-al", 0, {"Produce PID information for the Alpha mass hypothesis"}}; + Configurable pidEl{"pid-el", -1, {"Produce PID information for the Electron mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidMu{"pid-mu", -1, {"Produce PID information for the Muon mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidPi{"pid-pi", -1, {"Produce PID information for the Pion mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidKa{"pid-ka", -1, {"Produce PID information for the Kaon mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidPr{"pid-pr", -1, {"Produce PID information for the Proton mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidDe{"pid-de", -1, {"Produce PID information for the Deuterons mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidTr{"pid-tr", -1, {"Produce PID information for the Triton mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidHe{"pid-he", -1, {"Produce PID information for the Helium3 mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidAl{"pid-al", -1, {"Produce PID information for the Alpha mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; - void init(o2::framework::InitContext&) + void init(o2::framework::InitContext& initContext) { + // Checking the tables are requested in the workflow and enabling them + auto& workflows = initContext.services().get(); + for (DeviceSpec device : workflows.devices) { + for (auto input : device.inputs) { + auto enableFlag = [&input](const std::string particle, Configurable& flag) { + if (input.matcher.binding == "pidRespTOFT" + particle) { + if (flag < 0) { + flag.value = 1; + } + } + }; + enableFlag("El", pidEl); + enableFlag("Mu", pidMu); + enableFlag("Pi", pidPi); + enableFlag("Ka", pidKa); + enableFlag("Pr", pidPr); + enableFlag("De", pidDe); + enableFlag("Tr", pidTr); + enableFlag("He", pidHe); + enableFlag("Al", pidAl); + } + } + // Getting the parametrization parameters ccdb->setURL(url.value); ccdb->setTimestamp(timestamp.value); ccdb->setCaching(true); @@ -134,7 +158,7 @@ struct pidTOFTaskTiny { } }; -struct pidTOFTaskQA { +struct tofPidTinyQa { static constexpr int Np = 9; static constexpr const char* pT[Np] = {"e", "#mu", "#pi", "K", "p", "d", "t", "^{3}He", "#alpha"}; @@ -263,9 +287,9 @@ struct pidTOFTaskQA { WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { - auto workflow = WorkflowSpec{adaptAnalysisTask(cfgc, TaskName{"pidTOF-tiny-task"})}; + auto workflow = WorkflowSpec{adaptAnalysisTask(cfgc)}; if (cfgc.options().get("add-qa")) { - workflow.push_back(adaptAnalysisTask(cfgc, TaskName{"pidTOFQA-task"})); + workflow.push_back(adaptAnalysisTask(cfgc)); } return workflow; } \ No newline at end of file diff --git a/Analysis/Tasks/PID/pidTPC.cxx b/Analysis/Tasks/PID/pidTPC.cxx index 9c1c53a0e2eac..4486a3508cb38 100644 --- a/Analysis/Tasks/PID/pidTPC.cxx +++ b/Analysis/Tasks/PID/pidTPC.cxx @@ -9,7 +9,7 @@ // or submit itself to any jurisdiction. /// -/// \file pidTPC_split.cxx +/// \file pidTPC.cxx /// \author Nicolo' Jacazio /// \brief Task to produce PID tables for TPC split for each particle. /// Only the tables for the mass hypotheses requested are filled, the others are sent empty. @@ -18,6 +18,7 @@ // O2 includes #include "Framework/AnalysisTask.h" #include "Framework/HistogramRegistry.h" +#include "Framework/RunningWorkflowInfo.h" #include "ReconstructionDataFormats/Track.h" #include #include "AnalysisDataModel/PID/PIDResponse.h" @@ -38,7 +39,7 @@ void customize(std::vector& workflowOptions) #include "Framework/runDataProcessing.h" -struct pidTPCTaskSplit { +struct tpcPid { using Trks = soa::Join; using Coll = aod::Collisions; // Tables to produce @@ -60,18 +61,41 @@ struct pidTPCTaskSplit { Configurable url{"ccdb-url", "http://ccdb-test.cern.ch:8080", "url of the ccdb repository"}; Configurable timestamp{"ccdb-timestamp", -1, "timestamp of the object"}; // Configuration flags to include and exclude particle hypotheses - Configurable pidEl{"pid-el", 0, {"Produce PID information for the Electron mass hypothesis"}}; - Configurable pidMu{"pid-mu", 0, {"Produce PID information for the Muon mass hypothesis"}}; - Configurable pidPi{"pid-pi", 0, {"Produce PID information for the Pion mass hypothesis"}}; - Configurable pidKa{"pid-ka", 0, {"Produce PID information for the Kaon mass hypothesis"}}; - Configurable pidPr{"pid-pr", 0, {"Produce PID information for the Proton mass hypothesis"}}; - Configurable pidDe{"pid-de", 0, {"Produce PID information for the Deuterons mass hypothesis"}}; - Configurable pidTr{"pid-tr", 0, {"Produce PID information for the Triton mass hypothesis"}}; - Configurable pidHe{"pid-he", 0, {"Produce PID information for the Helium3 mass hypothesis"}}; - Configurable pidAl{"pid-al", 0, {"Produce PID information for the Alpha mass hypothesis"}}; + Configurable pidEl{"pid-el", -1, {"Produce PID information for the Electron mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidMu{"pid-mu", -1, {"Produce PID information for the Muon mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidPi{"pid-pi", -1, {"Produce PID information for the Pion mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidKa{"pid-ka", -1, {"Produce PID information for the Kaon mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidPr{"pid-pr", -1, {"Produce PID information for the Proton mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidDe{"pid-de", -1, {"Produce PID information for the Deuterons mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidTr{"pid-tr", -1, {"Produce PID information for the Triton mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidHe{"pid-he", -1, {"Produce PID information for the Helium3 mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidAl{"pid-al", -1, {"Produce PID information for the Alpha mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; - void init(o2::framework::InitContext&) + void init(o2::framework::InitContext& initContext) { + // Checking the tables are requested in the workflow and enabling them + auto& workflows = initContext.services().get(); + for (DeviceSpec device : workflows.devices) { + for (auto input : device.inputs) { + auto enableFlag = [&input](const std::string particle, Configurable& flag) { + if (input.matcher.binding == "pidRespTPC" + particle) { + if (flag < 0) { + flag.value = 1; + } + } + }; + enableFlag("El", pidEl); + enableFlag("Mu", pidMu); + enableFlag("Pi", pidPi); + enableFlag("Ka", pidKa); + enableFlag("Pr", pidPr); + enableFlag("De", pidDe); + enableFlag("Tr", pidTr); + enableFlag("He", pidHe); + enableFlag("Al", pidAl); + } + } + // Getting the parametrization parameters ccdb->setURL(url.value); ccdb->setTimestamp(timestamp.value); ccdb->setCaching(true); @@ -127,7 +151,7 @@ struct pidTPCTaskSplit { } }; -struct pidTPCTaskQA { +struct tpcPidQa { static constexpr int Np = 9; static constexpr const char* pT[Np] = {"e", "#mu", "#pi", "K", "p", "d", "t", "^{3}He", "#alpha"}; static constexpr std::string_view hexpected[Np] = {"expected/El", "expected/Mu", "expected/Pi", @@ -234,9 +258,9 @@ struct pidTPCTaskQA { WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { - auto workflow = WorkflowSpec{adaptAnalysisTask(cfgc, TaskName{"pidTPC-split-task"})}; + auto workflow = WorkflowSpec{adaptAnalysisTask(cfgc)}; if (cfgc.options().get("add-qa")) { - workflow.push_back(adaptAnalysisTask(cfgc, TaskName{"pidTOFQA-task"})); + workflow.push_back(adaptAnalysisTask(cfgc)); } return workflow; } diff --git a/Analysis/Tasks/PID/pidTPC_tiny.cxx b/Analysis/Tasks/PID/pidTPC_tiny.cxx index 14e25070d28e7..4eee848c81f25 100644 --- a/Analysis/Tasks/PID/pidTPC_tiny.cxx +++ b/Analysis/Tasks/PID/pidTPC_tiny.cxx @@ -9,7 +9,7 @@ // or submit itself to any jurisdiction. /// -/// \file pidTPC_split.cxx +/// \file pidTPC_tiny.cxx /// \author Nicolo' Jacazio /// \brief Task to produce PID tables for TPC split for each particle with only the Nsigma information. /// Only the tables for the mass hypotheses requested are filled, the others are sent empty. @@ -18,6 +18,7 @@ // O2 includes #include "Framework/AnalysisTask.h" #include "Framework/HistogramRegistry.h" +#include "Framework/RunningWorkflowInfo.h" #include "ReconstructionDataFormats/Track.h" #include #include "AnalysisDataModel/PID/PIDResponse.h" @@ -38,7 +39,7 @@ void customize(std::vector& workflowOptions) #include "Framework/runDataProcessing.h" -struct pidTPCTaskTiny { +struct tpcPidTiny { using Trks = soa::Join; using Coll = aod::Collisions; // Tables to produce @@ -60,18 +61,41 @@ struct pidTPCTaskTiny { Configurable url{"ccdb-url", "http://ccdb-test.cern.ch:8080", "url of the ccdb repository"}; Configurable timestamp{"ccdb-timestamp", -1, "timestamp of the object"}; // Configuration flags to include and exclude particle hypotheses - Configurable pidEl{"pid-el", 0, {"Produce PID information for the Electron mass hypothesis"}}; - Configurable pidMu{"pid-mu", 0, {"Produce PID information for the Muon mass hypothesis"}}; - Configurable pidPi{"pid-pi", 0, {"Produce PID information for the Pion mass hypothesis"}}; - Configurable pidKa{"pid-ka", 0, {"Produce PID information for the Kaon mass hypothesis"}}; - Configurable pidPr{"pid-pr", 0, {"Produce PID information for the Proton mass hypothesis"}}; - Configurable pidDe{"pid-de", 0, {"Produce PID information for the Deuterons mass hypothesis"}}; - Configurable pidTr{"pid-tr", 0, {"Produce PID information for the Triton mass hypothesis"}}; - Configurable pidHe{"pid-he", 0, {"Produce PID information for the Helium3 mass hypothesis"}}; - Configurable pidAl{"pid-al", 0, {"Produce PID information for the Alpha mass hypothesis"}}; + Configurable pidEl{"pid-el", -1, {"Produce PID information for the Electron mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidMu{"pid-mu", -1, {"Produce PID information for the Muon mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidPi{"pid-pi", -1, {"Produce PID information for the Pion mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidKa{"pid-ka", -1, {"Produce PID information for the Kaon mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidPr{"pid-pr", -1, {"Produce PID information for the Proton mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidDe{"pid-de", -1, {"Produce PID information for the Deuterons mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidTr{"pid-tr", -1, {"Produce PID information for the Triton mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidHe{"pid-he", -1, {"Produce PID information for the Helium3 mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; + Configurable pidAl{"pid-al", -1, {"Produce PID information for the Alpha mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; - void init(o2::framework::InitContext&) + void init(o2::framework::InitContext& initContext) { + // Checking the tables are requested in the workflow and enabling them + auto& workflows = initContext.services().get(); + for (DeviceSpec device : workflows.devices) { + for (auto input : device.inputs) { + auto enableFlag = [&input](const std::string particle, Configurable& flag) { + if (input.matcher.binding == "pidRespTPCT" + particle) { + if (flag < 0) { + flag.value = 1; + } + } + }; + enableFlag("El", pidEl); + enableFlag("Mu", pidMu); + enableFlag("Pi", pidPi); + enableFlag("Ka", pidKa); + enableFlag("Pr", pidPr); + enableFlag("De", pidDe); + enableFlag("Tr", pidTr); + enableFlag("He", pidHe); + enableFlag("Al", pidAl); + } + } + // Getting the parametrization parameters ccdb->setURL(url.value); ccdb->setTimestamp(timestamp.value); ccdb->setCaching(true); @@ -135,7 +159,7 @@ struct pidTPCTaskTiny { } }; -struct pidTPCTaskQA { +struct tpcPidTinyQa { static constexpr int Np = 9; static constexpr const char* pT[Np] = {"e", "#mu", "#pi", "K", "p", "d", "t", "^{3}He", "#alpha"}; static constexpr std::string_view hexpected[Np] = {"expected/El", "expected/Mu", "expected/Pi", @@ -240,9 +264,9 @@ struct pidTPCTaskQA { WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { - auto workflow = WorkflowSpec{adaptAnalysisTask(cfgc, TaskName{"pidTPC-tiny-task"})}; + auto workflow = WorkflowSpec{adaptAnalysisTask(cfgc)}; if (cfgc.options().get("add-qa")) { - workflow.push_back(adaptAnalysisTask(cfgc, TaskName{"pidTOFQA-task"})); + workflow.push_back(adaptAnalysisTask(cfgc)); } return workflow; } From f35fa364a1e24ad0721bf80991beef916a5456a2 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 26 Apr 2021 14:15:07 +0200 Subject: [PATCH 292/770] TPC Reconstruction: Get rid of obsolete GPUCATracking wrapper class --- Detectors/TPC/reconstruction/CMakeLists.txt | 4 +- .../include/TPCReconstruction/GPUCATracking.h | 76 --------- .../TPCTrackingDigitsPreCheck.h | 53 +++++++ .../TPC/reconstruction/src/GPUCATracking.cxx | 149 ------------------ .../src/TPCReconstructionLinkDef.h | 1 - .../src/TPCTrackingDigitsPreCheck.cxx | 97 ++++++++++++ .../reconstruction/test/testGPUCATracking.cxx | 13 +- Detectors/TPC/workflow/src/ZSSpec.cxx | 1 - GPU/Workflow/src/GPUWorkflowSpec.cxx | 36 ++++- macro/runTPCRefit.C | 3 + 10 files changed, 189 insertions(+), 244 deletions(-) delete mode 100644 Detectors/TPC/reconstruction/include/TPCReconstruction/GPUCATracking.h create mode 100644 Detectors/TPC/reconstruction/include/TPCReconstruction/TPCTrackingDigitsPreCheck.h delete mode 100644 Detectors/TPC/reconstruction/src/GPUCATracking.cxx create mode 100644 Detectors/TPC/reconstruction/src/TPCTrackingDigitsPreCheck.cxx diff --git a/Detectors/TPC/reconstruction/CMakeLists.txt b/Detectors/TPC/reconstruction/CMakeLists.txt index 5c6d79aae44a2..15ef66461a963 100644 --- a/Detectors/TPC/reconstruction/CMakeLists.txt +++ b/Detectors/TPC/reconstruction/CMakeLists.txt @@ -22,7 +22,7 @@ o2_add_library(TPCReconstruction src/RawReaderCRU.cxx src/RawReaderEventSync.cxx src/SyncPatternMonitor.cxx - src/GPUCATracking.cxx + src/TPCTrackingDigitsPreCheck.cxx src/HardwareClusterDecoder.cxx src/DigitalCurrentClusterIntegrator.cxx src/TPCFastTransformHelperO2.cxx @@ -51,7 +51,7 @@ o2_target_root_dictionary( include/TPCReconstruction/RawReaderCRU.h include/TPCReconstruction/RawReaderEventSync.h include/TPCReconstruction/SyncPatternMonitor.h - include/TPCReconstruction/GPUCATracking.h + include/TPCReconstruction/TPCTrackingDigitsPreCheck.h include/TPCReconstruction/HardwareClusterDecoder.h include/TPCReconstruction/DigitalCurrentClusterIntegrator.h include/TPCReconstruction/TPCFastTransformHelperO2.h diff --git a/Detectors/TPC/reconstruction/include/TPCReconstruction/GPUCATracking.h b/Detectors/TPC/reconstruction/include/TPCReconstruction/GPUCATracking.h deleted file mode 100644 index 6f4b89cf9f603..0000000000000 --- a/Detectors/TPC/reconstruction/include/TPCReconstruction/GPUCATracking.h +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// \file GPUCATracking.h -/// \brief Wrapper class for TPC CA Tracker algorithm -/// \author David Rohr -#ifndef ALICEO2_TPC_TPCCATRACKING_H_ -#define ALICEO2_TPC_TPCCATRACKING_H_ -#include -#include -#include "DataFormatsTPC/ClusterNative.h" -#include "DataFormatsTPC/TrackTPC.h" - -namespace o2 -{ -namespace gpu -{ -struct GPUO2InterfaceConfiguration; -struct GPUO2InterfaceIOPtrs; -struct GPUInterfaceOutputs; -class GPUO2Interface; -} // namespace gpu -} // namespace o2 - -namespace o2 -{ -class MCCompLabel; -namespace dataformats -{ -template -class MCTruthContainer; -} -} // namespace o2 - -namespace o2 -{ -namespace tpc -{ - -class GPUCATracking -{ - public: - GPUCATracking(); - ~GPUCATracking(); - GPUCATracking(const GPUCATracking&) = delete; // Disable copy - GPUCATracking& operator=(const GPUCATracking&) = delete; // Disable assignment - - int initialize(const o2::gpu::GPUO2InterfaceConfiguration& config); - void deinitialize(); - - //Input: cluster structure, possibly including MC labels, pointers to std::vectors for tracks and track MC labels. outputTracksMCTruth may be nullptr to indicate missing cluster MC labels. Otherwise, cluster MC labels are assumed to be present. - int runTracking(o2::gpu::GPUO2InterfaceIOPtrs* data, o2::gpu::GPUInterfaceOutputs* outputs = nullptr); - - void GetClusterErrors2(int row, float z, float sinPhi, float DzDs, short clusterState, float& ErrY2, float& ErrZ2) const; - - int registerMemoryForGPU(const void* ptr, size_t size); - int unregisterMemoryForGPU(const void* ptr); - - private: - std::unique_ptr mTrackingCAO2Interface; //Pointer to Interface class in HLT O2 CA Tracking library. - //The tracking code itself is not included in the O2 package, but contained in the CA library. - //The GPUCATracking class interfaces this library via this pointer to GPUO2Interface class. - - static constexpr float sTrackMCMaxFake = 0.1; -}; - -} // namespace tpc -} // namespace o2 -#endif diff --git a/Detectors/TPC/reconstruction/include/TPCReconstruction/TPCTrackingDigitsPreCheck.h b/Detectors/TPC/reconstruction/include/TPCReconstruction/TPCTrackingDigitsPreCheck.h new file mode 100644 index 0000000000000..ffe78b8ea2c7b --- /dev/null +++ b/Detectors/TPC/reconstruction/include/TPCReconstruction/TPCTrackingDigitsPreCheck.h @@ -0,0 +1,53 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file TPCTrackingDigitsPreCheck.h +/// \brief Wrapper class for TPC CA Tracker algorithm +/// \author David Rohr + +#ifndef ALICEO2_TPC_TRACKING_DIGITSPRECHECK_H +#define ALICEO2_TPC_TRACKING_DIGITSPRECHECK_H + +#include +namespace o2 +{ +namespace gpu +{ +struct GPUO2InterfaceIOPtrs; +struct GPUTrackingInOutPointers; +struct GPUO2InterfaceConfiguration; +} // namespace gpu +} // namespace o2 + +namespace o2 +{ +namespace tpc +{ + +class TPCTrackingDigitsPreCheck +{ + struct precheckModifiedDataInternal; // This struct might hold some internal data which the modified members of the data argument might point to + + public: + class precheckModifiedData + { + std::unique_ptr data; + + public: + precheckModifiedData(); + precheckModifiedData(std::unique_ptr&& v); + ~precheckModifiedData(); + }; + static precheckModifiedData runPrecheck(o2::gpu::GPUO2InterfaceIOPtrs* data, o2::gpu::GPUTrackingInOutPointers* ptrs, o2::gpu::GPUO2InterfaceConfiguration* config); +}; + +} // namespace tpc +} // namespace o2 +#endif // ALICEO2_TPC_TRACKING_DIGITSPRECHECK_H diff --git a/Detectors/TPC/reconstruction/src/GPUCATracking.cxx b/Detectors/TPC/reconstruction/src/GPUCATracking.cxx deleted file mode 100644 index 19557590e57f1..0000000000000 --- a/Detectors/TPC/reconstruction/src/GPUCATracking.cxx +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// \file GPUCATracking.cxx -/// \author David Rohr - -#include "TPCReconstruction/GPUCATracking.h" - -#include "SimulationDataFormat/MCCompLabel.h" -#include "SimulationDataFormat/ConstMCTruthContainer.h" -#include "DataFormatsTPC/Digit.h" - -#include "GPUO2Interface.h" -#include "GPUO2InterfaceConfiguration.h" -#include "TPCBase/Sector.h" - -#include -#include -#ifdef WITH_OPENMP -#include -#endif - -using namespace o2::gpu; -using namespace o2::tpc; -using namespace o2; -using namespace o2::dataformats; - -GPUCATracking::GPUCATracking() = default; -GPUCATracking::~GPUCATracking() { deinitialize(); } - -int GPUCATracking::initialize(const GPUO2InterfaceConfiguration& config) -{ - mTrackingCAO2Interface.reset(new GPUO2Interface); - int retVal = mTrackingCAO2Interface->Initialize(config); - if (retVal) { - mTrackingCAO2Interface.reset(); - } - return (retVal); -} - -void GPUCATracking::deinitialize() -{ - mTrackingCAO2Interface.reset(); -} - -int GPUCATracking::runTracking(GPUO2InterfaceIOPtrs* data, GPUInterfaceOutputs* outputs) -{ - if ((int)(data->tpcZS != nullptr) + (int)(data->o2Digits != nullptr && (data->tpcZS == nullptr || data->o2DigitsMC == nullptr)) + (int)(data->clusters != nullptr) + (int)(data->compressedClusters != nullptr) != 1) { - throw std::runtime_error("Invalid input for gpu tracking"); - } - - std::vector gpuDigits[Sector::MAXSECTOR]; - o2::dataformats::MCTruthContainer gpuDigitsMC[Sector::MAXSECTOR]; - ClusterNativeAccess::ConstMCLabelContainerViewWithBuffer gpuDigitsMCConst[Sector::MAXSECTOR]; - - GPUTrackingInOutDigits gpuDigitsMap; - GPUTPCDigitsMCInput gpuDigitsMapMC; - GPUTrackingInOutPointers ptrs; - - ptrs.settingsTF = data->settingsTF; - ptrs.tpcCompressedClusters = data->compressedClusters; - ptrs.tpcZS = data->tpcZS; - if (data->o2Digits) { - const float zsThreshold = mTrackingCAO2Interface->getConfig().configReconstruction.tpcZSthreshold; - const int maxContTimeBin = mTrackingCAO2Interface->getConfig().configGRP.continuousMaxTimeBin; - for (int i = 0; i < Sector::MAXSECTOR; i++) { - const auto& d = (*data->o2Digits)[i]; - if (zsThreshold > 0 && data->tpcZS == nullptr) { - gpuDigits[i].reserve(d.size()); - } - for (int j = 0; j < d.size(); j++) { - if (maxContTimeBin && d[j].getTimeStamp() >= maxContTimeBin) { - throw std::runtime_error("Digit time bin exceeds time frame length"); - } - if (zsThreshold > 0 && data->tpcZS == nullptr) { - if (d[j].getChargeFloat() >= zsThreshold) { - if (data->o2DigitsMC) { - for (const auto& element : (*data->o2DigitsMC)[i]->getLabels(j)) { - gpuDigitsMC[i].addElement(gpuDigits[i].size(), element); - } - } - gpuDigits[i].emplace_back(d[j]); - } - } - } - if (zsThreshold > 0 && data->tpcZS == nullptr) { - gpuDigitsMap.tpcDigits[i] = gpuDigits[i].data(); - gpuDigitsMap.nTPCDigits[i] = gpuDigits[i].size(); - if (data->o2DigitsMC) { - gpuDigitsMC[i].flatten_to(gpuDigitsMCConst[i].first); - gpuDigitsMCConst[i].second = gpuDigitsMCConst[i].first; - gpuDigitsMapMC.v[i] = &gpuDigitsMCConst[i].second; - } - } else { - gpuDigitsMap.tpcDigits[i] = (*(data->o2Digits))[i].data(); - gpuDigitsMap.nTPCDigits[i] = (*(data->o2Digits))[i].size(); - if (data->o2DigitsMC) { - gpuDigitsMapMC.v[i] = (*data->o2DigitsMC)[i]; - } - } - } - if (data->o2DigitsMC) { - gpuDigitsMap.tpcDigitsMC = &gpuDigitsMapMC; - } - ptrs.tpcPackedDigits = &gpuDigitsMap; - } - ptrs.clustersNative = data->clusters; - int retVal = mTrackingCAO2Interface->RunTracking(&ptrs, outputs); - if (data->o2Digits || data->tpcZS || data->compressedClusters) { - data->clusters = ptrs.clustersNative; - } - data->compressedClusters = ptrs.tpcCompressedClusters; - data->outputTracks = {ptrs.outputTracksTPCO2, ptrs.nOutputTracksTPCO2}; - data->outputClusRefs = {ptrs.outputClusRefsTPCO2, ptrs.nOutputClusRefsTPCO2}; - data->outputTracksMCTruth = {ptrs.outputTracksTPCO2MC, ptrs.outputTracksTPCO2MC ? ptrs.nOutputTracksTPCO2 : 0}; - - if (retVal || mTrackingCAO2Interface->getConfig().configInterface.dumpEvents >= 2) { - return retVal; - } - - mTrackingCAO2Interface->Clear(false); - - return (retVal); -} - -void GPUCATracking::GetClusterErrors2(int row, float z, float sinPhi, float DzDs, short clusterState, float& ErrY2, float& ErrZ2) const -{ - if (mTrackingCAO2Interface == nullptr) { - return; - } - mTrackingCAO2Interface->GetClusterErrors2(row, z, sinPhi, DzDs, clusterState, ErrY2, ErrZ2); -} - -int GPUCATracking::registerMemoryForGPU(const void* ptr, size_t size) -{ - return mTrackingCAO2Interface->registerMemoryForGPU(ptr, size); -} - -int GPUCATracking::unregisterMemoryForGPU(const void* ptr) -{ - return mTrackingCAO2Interface->unregisterMemoryForGPU(ptr); -} diff --git a/Detectors/TPC/reconstruction/src/TPCReconstructionLinkDef.h b/Detectors/TPC/reconstruction/src/TPCReconstructionLinkDef.h index 4417ee16e038f..03a3545bcf76b 100644 --- a/Detectors/TPC/reconstruction/src/TPCReconstructionLinkDef.h +++ b/Detectors/TPC/reconstruction/src/TPCReconstructionLinkDef.h @@ -25,7 +25,6 @@ #pragma link C++ class o2::tpc::rawreader::RawReaderCRUManager + ; #pragma link C++ class o2::tpc::RawReaderEventSync + ; #pragma link C++ class o2::tpc::SyncPatternMonitor + ; -#pragma link C++ class o2::tpc::GPUCATracking + ; #pragma link C++ class o2::tpc::HardwareClusterDecoder + ; #pragma link C++ class o2::tpc::KrBoxClusterFinder + ; #pragma link C++ class o2::tpc::KrCluster + ; diff --git a/Detectors/TPC/reconstruction/src/TPCTrackingDigitsPreCheck.cxx b/Detectors/TPC/reconstruction/src/TPCTrackingDigitsPreCheck.cxx new file mode 100644 index 0000000000000..d675ab9e43b05 --- /dev/null +++ b/Detectors/TPC/reconstruction/src/TPCTrackingDigitsPreCheck.cxx @@ -0,0 +1,97 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file TPCTrackingDigitsPreCheck.cxx +/// \author David Rohr + +#include "TPCReconstruction/TPCTrackingDigitsPreCheck.h" + +#include "SimulationDataFormat/MCCompLabel.h" +#include "SimulationDataFormat/ConstMCTruthContainer.h" +#include "DataFormatsTPC/Digit.h" +#include "DataFormatsTPC/ClusterNative.h" + +#include "GPUO2Interface.h" +#include "GPUO2InterfaceConfiguration.h" +#include "TPCBase/Sector.h" + +#include +#include +#ifdef WITH_OPENMP +#include +#endif + +using namespace o2::gpu; +using namespace o2::tpc; +using namespace o2; +using namespace o2::dataformats; + +TPCTrackingDigitsPreCheck::precheckModifiedData::precheckModifiedData() = default; +TPCTrackingDigitsPreCheck::precheckModifiedData::~precheckModifiedData() = default; +TPCTrackingDigitsPreCheck::precheckModifiedData::precheckModifiedData(std::unique_ptr&& v) : data(std::move(v)) {} + +struct TPCTrackingDigitsPreCheck::precheckModifiedDataInternal { + std::vector gpuDigits[Sector::MAXSECTOR]; + o2::dataformats::MCTruthContainer gpuDigitsMC[Sector::MAXSECTOR]; + ClusterNativeAccess::ConstMCLabelContainerViewWithBuffer gpuDigitsMCConst[Sector::MAXSECTOR]; + GPUTrackingInOutDigits gpuDigitsMap; + GPUTPCDigitsMCInput gpuDigitsMapMC; +}; + +TPCTrackingDigitsPreCheck::precheckModifiedData TPCTrackingDigitsPreCheck::runPrecheck(o2::gpu::GPUO2InterfaceIOPtrs* data, o2::gpu::GPUTrackingInOutPointers* ptrs, o2::gpu::GPUO2InterfaceConfiguration* config) +{ + if (data->o2Digits) { + std::unique_ptr retVal = std::make_unique(); + const float zsThreshold = config->configReconstruction.tpcZSthreshold; + const int maxContTimeBin = config->configGRP.continuousMaxTimeBin; + for (int i = 0; i < Sector::MAXSECTOR; i++) { + const auto& d = (*data->o2Digits)[i]; + if (zsThreshold > 0 && data->tpcZS == nullptr) { + retVal->gpuDigits[i].reserve(d.size()); + } + for (int j = 0; j < d.size(); j++) { + if (maxContTimeBin && d[j].getTimeStamp() >= maxContTimeBin) { + throw std::runtime_error("Digit time bin exceeds time frame length"); + } + if (zsThreshold > 0 && data->tpcZS == nullptr) { + if (d[j].getChargeFloat() >= zsThreshold) { + if (data->o2DigitsMC) { + for (const auto& element : (*data->o2DigitsMC)[i]->getLabels(j)) { + retVal->gpuDigitsMC[i].addElement(retVal->gpuDigits[i].size(), element); + } + } + retVal->gpuDigits[i].emplace_back(d[j]); + } + } + } + if (zsThreshold > 0 && data->tpcZS == nullptr) { + retVal->gpuDigitsMap.tpcDigits[i] = retVal->gpuDigits[i].data(); + retVal->gpuDigitsMap.nTPCDigits[i] = retVal->gpuDigits[i].size(); + if (data->o2DigitsMC) { + retVal->gpuDigitsMC[i].flatten_to(retVal->gpuDigitsMCConst[i].first); + retVal->gpuDigitsMCConst[i].second = retVal->gpuDigitsMCConst[i].first; + retVal->gpuDigitsMapMC.v[i] = &retVal->gpuDigitsMCConst[i].second; + } + } else { + retVal->gpuDigitsMap.tpcDigits[i] = (*(data->o2Digits))[i].data(); + retVal->gpuDigitsMap.nTPCDigits[i] = (*(data->o2Digits))[i].size(); + if (data->o2DigitsMC) { + retVal->gpuDigitsMapMC.v[i] = (*data->o2DigitsMC)[i]; + } + } + } + if (data->o2DigitsMC) { + retVal->gpuDigitsMap.tpcDigitsMC = &retVal->gpuDigitsMapMC; + } + ptrs->tpcPackedDigits = &retVal->gpuDigitsMap; + return precheckModifiedData(std::move(retVal)); + } + return precheckModifiedData(); +} diff --git a/Detectors/TPC/reconstruction/test/testGPUCATracking.cxx b/Detectors/TPC/reconstruction/test/testGPUCATracking.cxx index 177d0b3ee1be0..9ee3502f50a29 100644 --- a/Detectors/TPC/reconstruction/test/testGPUCATracking.cxx +++ b/Detectors/TPC/reconstruction/test/testGPUCATracking.cxx @@ -21,7 +21,6 @@ #include "DataFormatsTPC/TrackTPC.h" #include "DataFormatsTPC/ClusterNative.h" #include "DataFormatsTPC/ClusterNativeHelper.h" -#include "TPCReconstruction/GPUCATracking.h" #include "TPCReconstruction/TPCFastTransformHelperO2.h" #include "TPCFastTransform.h" @@ -46,7 +45,7 @@ namespace tpc /// @brief Test 1 basic class IO tests BOOST_AUTO_TEST_CASE(CATracking_test1) { - GPUCATracking tracker; + GPUO2Interface tracker; float solenoidBz = -5.00668; //B-field float refX = 1000.; //transport tracks to this x after tracking, >500 for disabling @@ -81,7 +80,7 @@ BOOST_AUTO_TEST_CASE(CATracking_test1) std::unique_ptr gainCalib = GPUO2Interface::getPadGainCalibDefault(); config.configCalib.tpcPadGain = gainCalib.get(); - tracker.initialize(config); + tracker.Initialize(config); std::vector cont(constants::MAXGLOBALPADROW); for (int i = 0; i < constants::MAXGLOBALPADROW; i++) { @@ -98,12 +97,12 @@ BOOST_AUTO_TEST_CASE(CATracking_test1) std::unique_ptr clusterBuffer; std::unique_ptr clusters = ClusterNativeHelper::createClusterNativeIndex(clusterBuffer, cont, nullptr, nullptr); - GPUO2InterfaceIOPtrs ptrs; - ptrs.clusters = clusters.get(); + GPUTrackingInOutPointers ptrs; + ptrs.clustersNative = clusters.get(); - int retVal = tracker.runTracking(&ptrs); + int retVal = tracker.RunTracking(&ptrs); BOOST_CHECK_EQUAL(retVal, 0); - BOOST_CHECK_EQUAL((int)ptrs.outputTracks.size(), 1); + BOOST_CHECK_EQUAL((int)ptrs.nMergedTracks, 1); } } // namespace tpc } // namespace o2 diff --git a/Detectors/TPC/workflow/src/ZSSpec.cxx b/Detectors/TPC/workflow/src/ZSSpec.cxx index 91d260e892a24..ae568ec3df735 100644 --- a/Detectors/TPC/workflow/src/ZSSpec.cxx +++ b/Detectors/TPC/workflow/src/ZSSpec.cxx @@ -19,7 +19,6 @@ #include "DataFormatsTPC/TPCSectorHeader.h" #include "DataFormatsTPC/ZeroSuppression.h" #include "DataFormatsTPC/Helpers.h" -#include "TPCReconstruction/GPUCATracking.h" #include "DataFormatsTPC/Digit.h" #include "GPUDataTypes.h" #include "GPUHostDataTypes.h" diff --git a/GPU/Workflow/src/GPUWorkflowSpec.cxx b/GPU/Workflow/src/GPUWorkflowSpec.cxx index 42bfb3e5fa59c..48caaa599bc62 100644 --- a/GPU/Workflow/src/GPUWorkflowSpec.cxx +++ b/GPU/Workflow/src/GPUWorkflowSpec.cxx @@ -31,7 +31,7 @@ #include "DataFormatsTPC/Helpers.h" #include "DataFormatsTPC/ZeroSuppression.h" #include "DataFormatsTPC/WorkflowHelper.h" -#include "TPCReconstruction/GPUCATracking.h" +#include "TPCReconstruction/TPCTrackingDigitsPreCheck.h" #include "TPCReconstruction/TPCFastTransformHelperO2.h" #include "DataFormatsTPC/Digit.h" #include "TPCFastTransform.h" @@ -97,7 +97,7 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli using ClusterGroupParser = o2::algorithm::ForwardParser; struct ProcessAttributes { std::unique_ptr parser; - std::unique_ptr tracker; + std::unique_ptr tracker; std::unique_ptr displayBackend; std::unique_ptr fastTransform; std::unique_ptr dEdxSplines; @@ -125,7 +125,7 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli auto& parser = processAttributes->parser; auto& tracker = processAttributes->tracker; parser = std::make_unique(); - tracker = std::make_unique(); + tracker = std::make_unique(); // Create configuration object and fill settings const auto grp = o2::parameters::GRPObject::loadFrom(o2::base::NameConf::getGRPFileName()); @@ -184,7 +184,7 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli config.configReconstruction.NWaysOuter = true; config.configInterface.outputToExternalBuffers = true; - // Configure the "GPU workflow" i.e. which steps we run on the GPU (or CPU) with this instance of GPUCATracking + // Configure the "GPU workflow" i.e. which steps we run on the GPU (or CPU) config.configWorkflow.steps.set(GPUDataTypes::RecoStep::TPCConversion, GPUDataTypes::RecoStep::TPCSliceTracking, GPUDataTypes::RecoStep::TPCMerging, @@ -229,7 +229,7 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli config.configCalib.fastTransform = processAttributes->fastTransform.get(); } if (config.configCalib.fastTransform == nullptr) { - throw std::invalid_argument("GPUCATracking: initialization of the TPC transformation failed"); + throw std::invalid_argument("GPU workflow: initialization of the TPC transformation failed"); } if (confParam.matLUTFile.size()) { @@ -265,8 +265,8 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli config.trdGeometry = gf.get();*/ // Configuration is prepared, initialize the tracker. - if (tracker->initialize(config) != 0) { - throw std::invalid_argument("GPUCATracking initialization failed"); + if (tracker->Initialize(config) != 0) { + throw std::invalid_argument("GPU Reconstruction initialization failed"); } if (specconfig.outputQA) { processAttributes->qa = std::make_unique(processAttributes->config.get()); @@ -610,7 +610,27 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli } } - int retVal = tracker->runTracking(&ptrs, &outputRegions); + if ((int)(ptrs.tpcZS != nullptr) + (int)(ptrs.o2Digits != nullptr && (ptrs.tpcZS == nullptr || ptrs.o2DigitsMC == nullptr)) + (int)(ptrs.clusters != nullptr) + (int)(ptrs.compressedClusters != nullptr) != 1) { + throw std::runtime_error("Invalid input for gpu tracking"); + } + + GPUTrackingInOutPointers ptrs2; + ptrs2.settingsTF = ptrs.settingsTF; + ptrs2.tpcCompressedClusters = ptrs.compressedClusters; + ptrs2.tpcZS = ptrs.tpcZS; + ptrs2.clustersNative = ptrs.clusters; + const auto& holdData = TPCTrackingDigitsPreCheck::runPrecheck(&ptrs, &ptrs2, processAttributes->config.get()); + int retVal = tracker->RunTracking(&ptrs2, &outputRegions); + if (ptrs.o2Digits || ptrs.tpcZS || ptrs.compressedClusters) { + ptrs.clusters = ptrs2.clustersNative; + } + ptrs.compressedClusters = ptrs2.tpcCompressedClusters; + ptrs.outputTracks = {ptrs2.outputTracksTPCO2, ptrs2.nOutputTracksTPCO2}; + ptrs.outputClusRefs = {ptrs2.outputClusRefsTPCO2, ptrs2.nOutputClusRefsTPCO2}; + ptrs.outputTracksMCTruth = {ptrs2.outputTracksTPCO2MC, ptrs2.outputTracksTPCO2MC ? ptrs2.nOutputTracksTPCO2 : 0}; + + tracker->Clear(false); + if (processAttributes->suppressOutput) { return; } diff --git a/macro/runTPCRefit.C b/macro/runTPCRefit.C index b5fa14db04087..5f65b74618113 100644 --- a/macro/runTPCRefit.C +++ b/macro/runTPCRefit.C @@ -40,6 +40,9 @@ using namespace o2::base; using namespace o2::track; using namespace std; +// This is actually defined in the TPC DataFormats, but for whatever reason ROOT Cling doesn't pick it up from there. +using TPCClRefElem = uint32_t; + int runTPCRefit(TString trackFile = "tpctracks.root", TString clusterFile = "tpc-native-clusters.root") { GeometryManager::loadGeometry(); From b0ff591d0b0666d774608fa03342a48ad4c8483c Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 26 Apr 2021 19:54:58 +0200 Subject: [PATCH 293/770] GPU Interface: Get rid of obsolete GPUO2InterfaceIOPtrs class --- .../TPCTrackingDigitsPreCheck.h | 3 +- .../src/TPCTrackingDigitsPreCheck.cxx | 54 +++++++------ GPU/GPUTracking/DataTypes/GPUDataTypes.h | 2 +- .../Interface/GPUO2InterfaceConfiguration.h | 32 -------- GPU/Workflow/src/GPUWorkflowSpec.cxx | 76 ++++++++++--------- 5 files changed, 68 insertions(+), 99 deletions(-) diff --git a/Detectors/TPC/reconstruction/include/TPCReconstruction/TPCTrackingDigitsPreCheck.h b/Detectors/TPC/reconstruction/include/TPCReconstruction/TPCTrackingDigitsPreCheck.h index ffe78b8ea2c7b..8420790c8c48c 100644 --- a/Detectors/TPC/reconstruction/include/TPCReconstruction/TPCTrackingDigitsPreCheck.h +++ b/Detectors/TPC/reconstruction/include/TPCReconstruction/TPCTrackingDigitsPreCheck.h @@ -20,7 +20,6 @@ namespace o2 { namespace gpu { -struct GPUO2InterfaceIOPtrs; struct GPUTrackingInOutPointers; struct GPUO2InterfaceConfiguration; } // namespace gpu @@ -45,7 +44,7 @@ class TPCTrackingDigitsPreCheck precheckModifiedData(std::unique_ptr&& v); ~precheckModifiedData(); }; - static precheckModifiedData runPrecheck(o2::gpu::GPUO2InterfaceIOPtrs* data, o2::gpu::GPUTrackingInOutPointers* ptrs, o2::gpu::GPUO2InterfaceConfiguration* config); + static precheckModifiedData runPrecheck(o2::gpu::GPUTrackingInOutPointers* ptrs, o2::gpu::GPUO2InterfaceConfiguration* config); }; } // namespace tpc diff --git a/Detectors/TPC/reconstruction/src/TPCTrackingDigitsPreCheck.cxx b/Detectors/TPC/reconstruction/src/TPCTrackingDigitsPreCheck.cxx index d675ab9e43b05..ece4cfe08d1a2 100644 --- a/Detectors/TPC/reconstruction/src/TPCTrackingDigitsPreCheck.cxx +++ b/Detectors/TPC/reconstruction/src/TPCTrackingDigitsPreCheck.cxx @@ -41,56 +41,54 @@ struct TPCTrackingDigitsPreCheck::precheckModifiedDataInternal { std::vector gpuDigits[Sector::MAXSECTOR]; o2::dataformats::MCTruthContainer gpuDigitsMC[Sector::MAXSECTOR]; ClusterNativeAccess::ConstMCLabelContainerViewWithBuffer gpuDigitsMCConst[Sector::MAXSECTOR]; - GPUTrackingInOutDigits gpuDigitsMap; - GPUTPCDigitsMCInput gpuDigitsMapMC; + GPUTrackingInOutDigits tpcDigitsMap; + GPUTPCDigitsMCInput tpcDigitsMapMC; }; -TPCTrackingDigitsPreCheck::precheckModifiedData TPCTrackingDigitsPreCheck::runPrecheck(o2::gpu::GPUO2InterfaceIOPtrs* data, o2::gpu::GPUTrackingInOutPointers* ptrs, o2::gpu::GPUO2InterfaceConfiguration* config) +TPCTrackingDigitsPreCheck::precheckModifiedData TPCTrackingDigitsPreCheck::runPrecheck(o2::gpu::GPUTrackingInOutPointers* ptrs, o2::gpu::GPUO2InterfaceConfiguration* config) { - if (data->o2Digits) { + if (ptrs->tpcPackedDigits) { std::unique_ptr retVal = std::make_unique(); + retVal->tpcDigitsMap = *ptrs->tpcPackedDigits; const float zsThreshold = config->configReconstruction.tpcZSthreshold; const int maxContTimeBin = config->configGRP.continuousMaxTimeBin; + bool updateDigits = zsThreshold > 0 && ptrs->tpcZS == nullptr; + const auto& d = ptrs->tpcPackedDigits; for (int i = 0; i < Sector::MAXSECTOR; i++) { - const auto& d = (*data->o2Digits)[i]; - if (zsThreshold > 0 && data->tpcZS == nullptr) { - retVal->gpuDigits[i].reserve(d.size()); + if (updateDigits) { + retVal->gpuDigits[i].reserve(d->nTPCDigits[i]); } - for (int j = 0; j < d.size(); j++) { - if (maxContTimeBin && d[j].getTimeStamp() >= maxContTimeBin) { + for (int j = 0; j < d->nTPCDigits[i]; j++) { + if (maxContTimeBin && d->tpcDigits[i][j].getTimeStamp() >= maxContTimeBin) { throw std::runtime_error("Digit time bin exceeds time frame length"); } - if (zsThreshold > 0 && data->tpcZS == nullptr) { - if (d[j].getChargeFloat() >= zsThreshold) { - if (data->o2DigitsMC) { - for (const auto& element : (*data->o2DigitsMC)[i]->getLabels(j)) { + if (updateDigits) { + if (d->tpcDigits[i][j].getChargeFloat() >= zsThreshold) { + if (d->tpcDigitsMC) { + for (const auto& element : d->tpcDigitsMC->v[i]->getLabels(j)) { retVal->gpuDigitsMC[i].addElement(retVal->gpuDigits[i].size(), element); } } - retVal->gpuDigits[i].emplace_back(d[j]); + retVal->gpuDigits[i].emplace_back(d->tpcDigits[i][j]); } } } - if (zsThreshold > 0 && data->tpcZS == nullptr) { - retVal->gpuDigitsMap.tpcDigits[i] = retVal->gpuDigits[i].data(); - retVal->gpuDigitsMap.nTPCDigits[i] = retVal->gpuDigits[i].size(); - if (data->o2DigitsMC) { + if (updateDigits) { + retVal->tpcDigitsMap.tpcDigits[i] = retVal->gpuDigits[i].data(); + retVal->tpcDigitsMap.nTPCDigits[i] = retVal->gpuDigits[i].size(); + if (ptrs->tpcPackedDigits->tpcDigitsMC) { retVal->gpuDigitsMC[i].flatten_to(retVal->gpuDigitsMCConst[i].first); retVal->gpuDigitsMCConst[i].second = retVal->gpuDigitsMCConst[i].first; - retVal->gpuDigitsMapMC.v[i] = &retVal->gpuDigitsMCConst[i].second; - } - } else { - retVal->gpuDigitsMap.tpcDigits[i] = (*(data->o2Digits))[i].data(); - retVal->gpuDigitsMap.nTPCDigits[i] = (*(data->o2Digits))[i].size(); - if (data->o2DigitsMC) { - retVal->gpuDigitsMapMC.v[i] = (*data->o2DigitsMC)[i]; + retVal->tpcDigitsMapMC.v[i] = &retVal->gpuDigitsMCConst[i].second; } } } - if (data->o2DigitsMC) { - retVal->gpuDigitsMap.tpcDigitsMC = &retVal->gpuDigitsMapMC; + if (updateDigits) { + if (ptrs->tpcPackedDigits->tpcDigitsMC) { + retVal->tpcDigitsMap.tpcDigitsMC = &retVal->tpcDigitsMapMC; + } + ptrs->tpcPackedDigits = &retVal->tpcDigitsMap; } - ptrs->tpcPackedDigits = &retVal->gpuDigitsMap; return precheckModifiedData(std::move(retVal)); } return precheckModifiedData(); diff --git a/GPU/GPUTracking/DataTypes/GPUDataTypes.h b/GPU/GPUTracking/DataTypes/GPUDataTypes.h index e45bb777362c9..cd0b38095dcee 100644 --- a/GPU/GPUTracking/DataTypes/GPUDataTypes.h +++ b/GPU/GPUTracking/DataTypes/GPUDataTypes.h @@ -207,7 +207,7 @@ struct GPUTrackingInOutDigits { static constexpr unsigned int NSLICES = GPUDataTypes::NSLICES; const o2::tpc::Digit* tpcDigits[NSLICES] = {nullptr}; size_t nTPCDigits[NSLICES] = {0}; - GPUTPCDigitsMCInput* tpcDigitsMC = nullptr; + const GPUTPCDigitsMCInput* tpcDigitsMC = nullptr; }; struct GPUTrackingInOutPointers { diff --git a/GPU/GPUTracking/Interface/GPUO2InterfaceConfiguration.h b/GPU/GPUTracking/Interface/GPUO2InterfaceConfiguration.h index 8e43d8809f3c5..d83040c1a9c83 100644 --- a/GPU/GPUTracking/Interface/GPUO2InterfaceConfiguration.h +++ b/GPU/GPUTracking/Interface/GPUO2InterfaceConfiguration.h @@ -97,38 +97,6 @@ struct GPUO2InterfaceConfiguration { GPUSettingsO2 ReadConfigurableParam_internal(); }; -// Structure with pointers to actual data for input and output -// Which ptr is used for input and which for output is defined in GPUO2InterfaceConfiguration::configWorkflow -// Inputs and outputs are mutually exclusive. -// Inputs which are nullptr are considered empty, and will not throw an error. -// Outputs, which point to std::[container] / MCTruthContainer, will be filled and no output -// is written if the ptr is a nullptr. -// Outputs, which point to other structures are set by GPUCATracking to the location of the output. The previous -// value of the pointer is overridden. GPUCATracking will try to place the output in the "void* outputBuffer" -// location if it is not a nullptr. -struct GPUO2InterfaceIOPtrs { - // Input: TPC clusters in cluster native format, or digits, or list of ZS pages - const as it can only be input - const o2::tpc::ClusterNativeAccess* clusters = nullptr; - const std::array, o2::tpc::constants::MAXSECTOR>* o2Digits = nullptr; - const std::array*, o2::tpc::constants::MAXSECTOR>* o2DigitsMC = nullptr; - const o2::gpu::GPUTrackingInOutZS* tpcZS = nullptr; - - // Input / Output for Merged TPC tracks, two ptrs, for the tracks themselves, and for the MC labels. -#ifdef MS_GSL_V3 - gsl::span outputTracks = {nullptr, (gsl::span::size_type)0}; - gsl::span outputClusRefs = {nullptr, (gsl::span::size_type)0}; - gsl::span outputTracksMCTruth = {nullptr, (gsl::span::size_type)0}; -#else - gsl::span outputTracks = {nullptr, (gsl::span::index_type)0}; - gsl::span outputClusRefs = {nullptr, (gsl::span::index_type)0}; - gsl::span outputTracksMCTruth = {nullptr, (gsl::span::index_type)0}; -#endif - // Output for entropy-reduced clusters of TPC compression - const o2::tpc::CompressedClustersFlat* compressedClusters = nullptr; - - // Ptr to parameters for current TF - const GPUSettingsTF* settingsTF = nullptr; -}; } // namespace gpu } // namespace o2 diff --git a/GPU/Workflow/src/GPUWorkflowSpec.cxx b/GPU/Workflow/src/GPUWorkflowSpec.cxx index 48caaa599bc62..35daabda0a143 100644 --- a/GPU/Workflow/src/GPUWorkflowSpec.cxx +++ b/GPU/Workflow/src/GPUWorkflowSpec.cxx @@ -478,35 +478,47 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli } } - ClusterNativeHelper::ConstMCLabelContainerViewWithBuffer clustersMCBuffer; - GPUO2InterfaceIOPtrs ptrs; - void* ptrEp[NSectors * NEndpoints] = {}; - const auto& inputsClustersDigits = getWorkflowTPCInput(pc, verbosity, getWorkflowTPCInput_mc, getWorkflowTPCInput_clusters, processAttributes->tpcSectorMask, getWorkflowTPCInput_digits); + GPUTrackingInOutPointers ptrs; + + void* ptrEp[NSectors * NEndpoints] = {}; + bool doInputDigits = false, doInputDigitsMC = false; if (specconfig.decompressTPC) { - ptrs.compressedClusters = pCompClustersFlat; + ptrs.tpcCompressedClusters = pCompClustersFlat; } else if (specconfig.zsOnTheFly) { const unsigned long long int* buffer = reinterpret_cast(&inputZS[0]); o2::gpu::GPUReconstructionConvert::RunZSEncoderCreateMeta(buffer, tpcZSonTheFlySizes.data(), *&ptrEp, &tpcZS); ptrs.tpcZS = &tpcZS; - if (specconfig.processMC) { - ptrs.o2Digits = &inputsClustersDigits->inputDigits; - ptrs.o2DigitsMC = &inputsClustersDigits->inputDigitsMCPtrs; - } + doInputDigits = doInputDigitsMC = specconfig.processMC; } else if (specconfig.zsDecoder) { ptrs.tpcZS = &tpcZS; if (specconfig.processMC) { throw std::runtime_error("Cannot process MC information, none available"); } } else if (specconfig.caClusterer) { - ptrs.o2Digits = &inputsClustersDigits->inputDigits; - if (specconfig.processMC) { - ptrs.o2DigitsMC = &inputsClustersDigits->inputDigitsMCPtrs; - } + doInputDigits = true; + doInputDigitsMC = specconfig.processMC; } else { - ptrs.clusters = &inputsClustersDigits->clusterIndex; + ptrs.clustersNative = &inputsClustersDigits->clusterIndex; } + + GPUTrackingInOutDigits tpcDigitsMap; + GPUTPCDigitsMCInput tpcDigitsMapMC; + if (doInputDigits) { + ptrs.tpcPackedDigits = &tpcDigitsMap; + if (doInputDigitsMC) { + tpcDigitsMap.tpcDigitsMC = &tpcDigitsMapMC; + } + for (unsigned int i = 0; i < NSectors; i++) { + tpcDigitsMap.tpcDigits[i] = inputsClustersDigits->inputDigits[i].data(); + tpcDigitsMap.nTPCDigits[i] = inputsClustersDigits->inputDigits[i].size(); + if (doInputDigitsMC) { + tpcDigitsMapMC.v[i] = inputsClustersDigits->inputDigitsMCPtrs[i]; + } + } + } + // a byte size resizable vector object, the DataAllocator returns reference to internal object // initialize optional pointer to the vector object TPCSectorHeader clusterOutputSectorHeader{0}; @@ -586,6 +598,7 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli setOutputAllocator("TRACKS", specconfig.outputTracks, outputRegions.tpcTracksO2, std::make_tuple(gDataOriginTPC, (DataDescription) "TRACKS", 0)); setOutputAllocator("CLUSREFS", specconfig.outputTracks, outputRegions.tpcTracksO2ClusRefs, std::make_tuple(gDataOriginTPC, (DataDescription) "CLUSREFS", 0)); setOutputAllocator("TRACKSMCLBL", specconfig.outputTracks && specconfig.processMC, outputRegions.tpcTracksO2Labels, std::make_tuple(gDataOriginTPC, (DataDescription) "TRACKSMCLBL", 0)); + ClusterNativeHelper::ConstMCLabelContainerViewWithBuffer clustersMCBuffer; if (specconfig.processMC && specconfig.caClusterer) { outputRegions.clusterLabels.allocator = [&clustersMCBuffer](size_t size) -> void* { return &clustersMCBuffer; }; } @@ -610,24 +623,15 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli } } - if ((int)(ptrs.tpcZS != nullptr) + (int)(ptrs.o2Digits != nullptr && (ptrs.tpcZS == nullptr || ptrs.o2DigitsMC == nullptr)) + (int)(ptrs.clusters != nullptr) + (int)(ptrs.compressedClusters != nullptr) != 1) { + if ((int)(ptrs.tpcZS != nullptr) + (int)(ptrs.tpcPackedDigits != nullptr && (ptrs.tpcZS == nullptr || ptrs.tpcPackedDigits->tpcDigitsMC == nullptr)) + (int)(ptrs.clustersNative != nullptr) + (int)(ptrs.tpcCompressedClusters != nullptr) != 1) { throw std::runtime_error("Invalid input for gpu tracking"); } - GPUTrackingInOutPointers ptrs2; - ptrs2.settingsTF = ptrs.settingsTF; - ptrs2.tpcCompressedClusters = ptrs.compressedClusters; - ptrs2.tpcZS = ptrs.tpcZS; - ptrs2.clustersNative = ptrs.clusters; - const auto& holdData = TPCTrackingDigitsPreCheck::runPrecheck(&ptrs, &ptrs2, processAttributes->config.get()); - int retVal = tracker->RunTracking(&ptrs2, &outputRegions); - if (ptrs.o2Digits || ptrs.tpcZS || ptrs.compressedClusters) { - ptrs.clusters = ptrs2.clustersNative; - } - ptrs.compressedClusters = ptrs2.tpcCompressedClusters; - ptrs.outputTracks = {ptrs2.outputTracksTPCO2, ptrs2.nOutputTracksTPCO2}; - ptrs.outputClusRefs = {ptrs2.outputClusRefsTPCO2, ptrs2.nOutputClusRefsTPCO2}; - ptrs.outputTracksMCTruth = {ptrs2.outputTracksTPCO2MC, ptrs2.outputTracksTPCO2MC ? ptrs2.nOutputTracksTPCO2 : 0}; + const auto& holdData = TPCTrackingDigitsPreCheck::runPrecheck(&ptrs, processAttributes->config.get()); + int retVal = tracker->RunTracking(&ptrs, &outputRegions); + gsl::span spanOutputTracks = {ptrs.outputTracksTPCO2, ptrs.nOutputTracksTPCO2}; + gsl::span spanOutputClusRefs = {ptrs.outputClusRefsTPCO2, ptrs.nOutputClusRefsTPCO2}; + gsl::span spanOutputTracksMCTruth = {ptrs.outputTracksTPCO2MC, ptrs.outputTracksTPCO2MC ? ptrs.nOutputTracksTPCO2 : 0}; tracker->Clear(false); @@ -649,23 +653,23 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli } } } - downSizeBufferToSpan(outputRegions.tpcTracksO2, ptrs.outputTracks); - downSizeBufferToSpan(outputRegions.tpcTracksO2ClusRefs, ptrs.outputClusRefs); - downSizeBufferToSpan(outputRegions.tpcTracksO2Labels, ptrs.outputTracksMCTruth); + downSizeBufferToSpan(outputRegions.tpcTracksO2, spanOutputTracks); + downSizeBufferToSpan(outputRegions.tpcTracksO2ClusRefs, spanOutputClusRefs); + downSizeBufferToSpan(outputRegions.tpcTracksO2Labels, spanOutputTracksMCTruth); - LOG(INFO) << "found " << ptrs.outputTracks.size() << " track(s)"; + LOG(INFO) << "found " << spanOutputTracks.size() << " track(s)"; if (specconfig.outputCompClusters) { - CompressedClustersROOT compressedClusters = *ptrs.compressedClusters; + CompressedClustersROOT compressedClusters = *ptrs.tpcCompressedClusters; pc.outputs().snapshot(Output{gDataOriginTPC, "COMPCLUSTERS", 0}, ROOTSerialized(compressedClusters)); } if (processAttributes->clusterOutputIds.size() > 0) { - if ((void*)ptrs.clusters->clustersLinear != (void*)(outputBuffers[outputRegions.getIndex(outputRegions.clustersNative)].second + sizeof(ClusterCountIndex))) { + if ((void*)ptrs.clustersNative->clustersLinear != (void*)(outputBuffers[outputRegions.getIndex(outputRegions.clustersNative)].second + sizeof(ClusterCountIndex))) { throw std::runtime_error("cluster native output ptrs out of sync"); // sanity check } - ClusterNativeAccess const& accessIndex = *ptrs.clusters; + ClusterNativeAccess const& accessIndex = *ptrs.clustersNative; if (specconfig.sendClustersPerSector) { // Clusters are shipped by sector, we are copying into per-sector buffers (anyway only for ROOT output) for (int i = 0; i < NSectors; i++) { From 71468510948aa3466a18024a085d62d77a67d7d6 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 26 Apr 2021 20:12:14 +0200 Subject: [PATCH 294/770] TPC Workflow: Remove obsolete command line options --- .../TPC/workflow/include/TPCWorkflow/RecoWorkflow.h | 2 -- Detectors/TPC/workflow/include/TPCWorkflow/ZSSpec.h | 2 +- Detectors/TPC/workflow/src/RecoWorkflow.cxx | 4 ++-- Detectors/TPC/workflow/src/ZSSpec.cxx | 11 +++++------ Detectors/TPC/workflow/src/tpc-reco-workflow.cxx | 4 ---- GPU/GPUTracking/Definitions/GPUSettingsList.h | 2 +- 6 files changed, 9 insertions(+), 16 deletions(-) diff --git a/Detectors/TPC/workflow/include/TPCWorkflow/RecoWorkflow.h b/Detectors/TPC/workflow/include/TPCWorkflow/RecoWorkflow.h index 081ca5a4c666c..7136299d7ed0c 100644 --- a/Detectors/TPC/workflow/include/TPCWorkflow/RecoWorkflow.h +++ b/Detectors/TPC/workflow/include/TPCWorkflow/RecoWorkflow.h @@ -78,8 +78,6 @@ framework::WorkflowSpec getWorkflow(CompletionPolicyData* policyData, bool disableRootInput = false, // int caClusterer = 0, // int zsOnTheFly = 0, - int zs10bit = 0, - float zsThreshold = 2.0f, bool askDISTSTF = true); } // end namespace reco_workflow diff --git a/Detectors/TPC/workflow/include/TPCWorkflow/ZSSpec.h b/Detectors/TPC/workflow/include/TPCWorkflow/ZSSpec.h index 6e9d05fe15dbc..7b9eed75a658f 100644 --- a/Detectors/TPC/workflow/include/TPCWorkflow/ZSSpec.h +++ b/Detectors/TPC/workflow/include/TPCWorkflow/ZSSpec.h @@ -16,7 +16,7 @@ namespace tpc { /// create a processor spec -framework::DataProcessorSpec getZSEncoderSpec(std::vector const& tpcSectors, bool zs12bit, float threshold, bool outRaw, unsigned long tpcSectorMask); +framework::DataProcessorSpec getZSEncoderSpec(std::vector const& tpcSectors, bool outRaw, unsigned long tpcSectorMask); framework::DataProcessorSpec getZStoDigitsSpec(std::vector const& tpcSectors); diff --git a/Detectors/TPC/workflow/src/RecoWorkflow.cxx b/Detectors/TPC/workflow/src/RecoWorkflow.cxx index 1f82caeef446f..1a798c6f0760d 100644 --- a/Detectors/TPC/workflow/src/RecoWorkflow.cxx +++ b/Detectors/TPC/workflow/src/RecoWorkflow.cxx @@ -90,7 +90,7 @@ const std::unordered_map OutputMap{ framework::WorkflowSpec getWorkflow(CompletionPolicyData* policyData, std::vector const& tpcSectors, unsigned long tpcSectorMask, std::vector const& laneConfiguration, bool propagateMC, unsigned nLanes, std::string const& cfgInput, std::string const& cfgOutput, bool disableRootInput, - int caClusterer, int zsOnTheFly, int zs10bit, float zsThreshold, bool askDISTSTF) + int caClusterer, int zsOnTheFly, bool askDISTSTF) { InputType inputType; try { @@ -401,7 +401,7 @@ framework::WorkflowSpec getWorkflow(CompletionPolicyData* policyData, std::vecto } if (zsOnTheFly) { - specs.emplace_back(o2::tpc::getZSEncoderSpec(tpcSectors, zs10bit, zsThreshold, outRaw, tpcSectorMask)); + specs.emplace_back(o2::tpc::getZSEncoderSpec(tpcSectors, outRaw, tpcSectorMask)); } if (zsToDigit) { diff --git a/Detectors/TPC/workflow/src/ZSSpec.cxx b/Detectors/TPC/workflow/src/ZSSpec.cxx index ae568ec3df735..14afe6e458732 100644 --- a/Detectors/TPC/workflow/src/ZSSpec.cxx +++ b/Detectors/TPC/workflow/src/ZSSpec.cxx @@ -55,7 +55,7 @@ namespace o2 namespace tpc { -DataProcessorSpec getZSEncoderSpec(std::vector const& tpcSectors, bool zs10bit, float threshold = 2.f, bool outRaw = false, unsigned long tpcSectorMask = 0xFFFFFFFFF) +DataProcessorSpec getZSEncoderSpec(std::vector const& tpcSectors, bool outRaw = false, unsigned long tpcSectorMask = 0xFFFFFFFFF) { std::string processorName = "tpc-zsEncoder"; constexpr static size_t NSectors = o2::tpc::Sector::MAXSECTOR; @@ -71,7 +71,7 @@ DataProcessorSpec getZSEncoderSpec(std::vector const& tpcSectors, bool zs10 bool finished = false; }; - auto initFunction = [tpcSectors, zs10bit, threshold, outRaw, tpcSectorMask](InitContext& ic) { + auto initFunction = [tpcSectors, outRaw, tpcSectorMask](InitContext& ic) { auto processAttributes = std::make_shared(); auto& zsoutput = processAttributes->zsoutput; processAttributes->tpcSectors = tpcSectors; @@ -79,7 +79,7 @@ DataProcessorSpec getZSEncoderSpec(std::vector const& tpcSectors, bool zs10 auto& sizes = processAttributes->sizes; auto& verbosity = processAttributes->verbosity; - auto processingFct = [processAttributes, zs10bit, threshold, outRaw, tpcSectorMask]( + auto processingFct = [processAttributes, outRaw, tpcSectorMask]( ProcessingContext& pc) { if (processAttributes->finished) { return; @@ -100,9 +100,8 @@ DataProcessorSpec getZSEncoderSpec(std::vector const& tpcSectors, bool zs10 const auto& inputs = getWorkflowTPCInput(pc, 0, false, false, tpcSectorMask, true); sizes.resize(NSectors * NEndpoints); - bool zs12bit = !zs10bit; o2::InteractionRecord ir = o2::raw::HBFUtils::Instance().getFirstIR(); - o2::gpu::GPUReconstructionConvert::RunZSEncoder(inputs->inputDigits, &zsoutput, sizes.data(), nullptr, &ir, _GPUParam, zs12bit, verify, threshold); + o2::gpu::GPUReconstructionConvert::RunZSEncoder(inputs->inputDigits, &zsoutput, sizes.data(), nullptr, &ir, _GPUParam, true, verify, config.configReconstruction.tpcZSthreshold); ZeroSuppressedContainer8kb* page = reinterpret_cast(zsoutput.get()); unsigned int offset = 0; for (unsigned int i = 0; i < NSectors; i++) { @@ -153,7 +152,7 @@ DataProcessorSpec getZSEncoderSpec(std::vector const& tpcSectors, bool zs10 if (useGrouping != LinksGrouping::Link) { writer.useCaching(); } - o2::gpu::GPUReconstructionConvert::RunZSEncoder(inputDigits, nullptr, nullptr, &writer, &ir, _GPUParam, zs12bit, false, threshold); + o2::gpu::GPUReconstructionConvert::RunZSEncoder(inputDigits, nullptr, nullptr, &writer, &ir, _GPUParam, true, false, config.configReconstruction.tpcZSthreshold); writer.writeConfFile("TPC", "RAWDATA", fmt::format("{}tpcraw.cfg", outDir)); } zsoutput.reset(nullptr); diff --git a/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx b/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx index 0eb1958db691d..e1c404e999b83 100644 --- a/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx +++ b/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx @@ -56,8 +56,6 @@ void customize(std::vector& workflowOptions) {"tpc-lanes", VariantType::Int, 1, {"number of parallel lanes up to the tracker"}}, {"dispatching-mode", VariantType::String, "prompt", {"determines when to dispatch: prompt, complete"}}, {"no-tpc-zs-on-the-fly", VariantType::Bool, false, {"Do not use TPC zero suppression on the fly"}}, - {"zs-threshold", VariantType::Float, 2.0f, {"zero suppression threshold"}}, - {"zs-10bit", VariantType::Bool, false, {"use 10 bit ADCs for TPC zero suppression, default = 12 bit ADC"}}, {"ignore-dist-stf", VariantType::Bool, false, {"do not subscribe to FLP/DISTSUBTIMEFRAME/0 message (no lost TF recovery)"}}, {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings (e.g.: 'TPCHwClusterer.peakChargeThreshold=4;...')"}}, {"configFile", VariantType::String, "", {"configuration file for configurable parameters"}}}; @@ -161,8 +159,6 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) cfgc.options().get("disable-root-input"), // !cfgc.options().get("no-ca-clusterer"), // !cfgc.options().get("no-tpc-zs-on-the-fly"), // - cfgc.options().get("zs-10bit"), // - cfgc.options().get("zs-threshold"), // !cfgc.options().get("ignore-dist-stf") // ); diff --git a/GPU/GPUTracking/Definitions/GPUSettingsList.h b/GPU/GPUTracking/Definitions/GPUSettingsList.h index 6bd651578dbae..1d49e4b602177 100644 --- a/GPU/GPUTracking/Definitions/GPUSettingsList.h +++ b/GPU/GPUTracking/Definitions/GPUSettingsList.h @@ -317,7 +317,7 @@ AddSubConfig(GPUSettingsDisplay, GL) AddSubConfig(GPUSettingsDisplayLight, GLlight) AddSubConfig(GPUSettingsEG, EG) EndConfig() -#endif +#endif // BeginConfig //Settings for the O2 workfllow #if !defined(QCONFIG_PARSER_CXX) && (defined(GPUCA_O2_LIB) || defined(GPUCA_O2_INTERFACE)) From 0cbdea8425758992d57784ebdb62673001e922b1 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Mon, 26 Apr 2021 10:38:32 +0200 Subject: [PATCH 295/770] DPL Analysis: add table name to spawner errors --- Framework/Core/include/Framework/TableBuilder.h | 15 ++++++++++----- Framework/Core/src/AODReaderHelpers.cxx | 2 +- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/Framework/Core/include/Framework/TableBuilder.h b/Framework/Core/include/Framework/TableBuilder.h index d7f2fde76cdcc..31757b1ada93b 100644 --- a/Framework/Core/include/Framework/TableBuilder.h +++ b/Framework/Core/include/Framework/TableBuilder.h @@ -770,7 +770,7 @@ auto makeEmptyTable() /// Expression-based column generator to materialize columns template -auto spawner(framework::pack columns, arrow::Table* atable) +auto spawner(framework::pack columns, arrow::Table* atable, const char* name) { static auto new_schema = o2::soa::createSchemaFromColumns(columns); static auto projectors = framework::expressions::createProjectors(columns, atable->schema()); @@ -788,15 +788,20 @@ auto spawner(framework::pack columns, arrow::Table* atable) while (true) { auto s = reader.ReadNext(&batch); if (!s.ok()) { - throw runtime_error_f("Cannot read batches from table: %s", s.ToString().c_str()); + throw runtime_error_f("Cannot read batches from table %s: %s", name, s.ToString().c_str()); } if (batch == nullptr) { break; } - s = projectors->Evaluate(*batch, arrow::default_memory_pool(), &v); - if (!s.ok()) { - throw runtime_error_f("Cannot apply projector: %s", s.ToString().c_str()); + try { + s = projectors->Evaluate(*batch, arrow::default_memory_pool(), &v); + if (!s.ok()) { + throw runtime_error_f("Cannot apply projector to table %s: %s", name, s.ToString().c_str()); + } + } catch (std::exception& e) { + throw runtime_error_f("Cannot apply projector to table %s: exception caught: %s", name, e.what()); } + for (auto i = 0u; i < sizeof...(C); ++i) { chunks[i].emplace_back(v.at(i)); } diff --git a/Framework/Core/src/AODReaderHelpers.cxx b/Framework/Core/src/AODReaderHelpers.cxx index 70727052e247e..744ba3c29bb69 100644 --- a/Framework/Core/src/AODReaderHelpers.cxx +++ b/Framework/Core/src/AODReaderHelpers.cxx @@ -167,7 +167,7 @@ AlgorithmSpec AODReaderHelpers::aodSpawnerCallback(std::vector reques using metadata_t = decltype(metadata); using expressions = typename metadata_t::expression_pack_t; auto original_table = pc.inputs().get(input.binding)->asArrowTable(); - return o2::framework::spawner(expressions{}, original_table.get()); + return o2::framework::spawner(expressions{}, original_table.get(), input.binding.c_str()); }; if (description == header::DataDescription{"TRACK"}) { From 5ef0632c0becbdee39b218e859aae0f88148972d Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Mon, 26 Apr 2021 11:32:02 +0200 Subject: [PATCH 296/770] fixup! DPL Analysis: add table name to spawner errors --- Framework/Core/include/Framework/AnalysisHelpers.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Framework/Core/include/Framework/AnalysisHelpers.h b/Framework/Core/include/Framework/AnalysisHelpers.h index 801cb1a1d3bd0..d8e628a0070f1 100644 --- a/Framework/Core/include/Framework/AnalysisHelpers.h +++ b/Framework/Core/include/Framework/AnalysisHelpers.h @@ -577,7 +577,7 @@ auto Extend(T const& table) { static_assert((soa::is_type_spawnable_v && ...), "You can only extend a table with expression columns"); using output_t = Join>; - return output_t{{o2::framework::spawner(framework::pack{}, table.asArrowTable().get()), table.asArrowTable()}, 0}; + return output_t{{o2::framework::spawner(framework::pack{}, table.asArrowTable().get(), "dynamic extension"), table.asArrowTable()}, 0}; } /// Template function to attach dynamic columns on-the-fly (e.g. inside From 28642b51ccec2f7a1732297de9f649fe316d3bfa Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Mon, 26 Apr 2021 14:13:37 +0200 Subject: [PATCH 297/770] fixup! fixup! DPL Analysis: add table name to spawner errors --- Framework/Core/src/AnalysisManagers.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Framework/Core/src/AnalysisManagers.h b/Framework/Core/src/AnalysisManagers.h index f069a9591b4d6..bc940b87ee1be 100644 --- a/Framework/Core/src/AnalysisManagers.h +++ b/Framework/Core/src/AnalysisManagers.h @@ -241,7 +241,7 @@ struct OutputManager> { original_table = makeEmptyTable(); } - what.extension = std::make_shared::extension_t>(o2::framework::spawner(what.pack(), original_table.get())); + what.extension = std::make_shared::extension_t>(o2::framework::spawner(what.pack(), original_table.get(), aod::MetadataTrait::extension_t>::metadata::tableLabel())); what.table = std::make_shared(soa::ArrowHelpers::joinTables({what.extension->asArrowTable(), original_table})); return true; } From 65d6e70f7c89ed17f1605a54118d20f10fdfd3a8 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 27 Apr 2021 13:49:31 +0200 Subject: [PATCH 298/770] GPU Workflow: Read nOrbitsPerTF from GRP instead of HBFUtils --- GPU/GPUTracking/DataTypes/GPUSettings.h | 2 ++ GPU/Workflow/src/GPUWorkflowSpec.cxx | 17 ++++++++++------- prodtests/full-system-test/dpl-workflow.sh | 12 ++++++------ 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/GPU/GPUTracking/DataTypes/GPUSettings.h b/GPU/GPUTracking/DataTypes/GPUSettings.h index 1ae6efe991678..8f7ea8d8dcfff 100644 --- a/GPU/GPUTracking/DataTypes/GPUSettings.h +++ b/GPU/GPUTracking/DataTypes/GPUSettings.h @@ -68,6 +68,8 @@ struct GPUSettingsTF { int runStartOrbit = 0; int hasSimStartOrbit = 0; int simStartOrbit = 0; + int hasNHBFPerTF = 0; + int nHBFPerTF = 0; }; // Settings defining the setup of the GPUReconstruction processing (basically selecting the device / class instance) diff --git a/GPU/Workflow/src/GPUWorkflowSpec.cxx b/GPU/Workflow/src/GPUWorkflowSpec.cxx index 35daabda0a143..be305de7c6f28 100644 --- a/GPU/Workflow/src/GPUWorkflowSpec.cxx +++ b/GPU/Workflow/src/GPUWorkflowSpec.cxx @@ -41,7 +41,6 @@ #include "DetectorsBase/Propagator.h" #include "DetectorsBase/GeometryManager.h" #include "DetectorsCommonDataFormats/NameConf.h" -#include "DetectorsRaw/HBFUtils.h" #include "TPCBase/RDHUtils.h" #include "GPUO2InterfaceConfiguration.h" #include "GPUO2InterfaceQA.h" @@ -108,6 +107,7 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli std::vector clusterOutputIds; unsigned long outputBufferSize = 0; unsigned long tpcSectorMask = 0; + unsigned int nHBFPerTF; int verbosity = 0; bool readyToQuit = false; bool allocateOutputOnTheFly = false; @@ -131,13 +131,14 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli const auto grp = o2::parameters::GRPObject::loadFrom(o2::base::NameConf::getGRPFileName()); o2::base::GeometryManager::loadGeometry(); o2::base::Propagator::initFieldFromGRP(o2::base::NameConf::getGRPFileName()); - if (grp) { - config.configGRP.solenoidBz = 5.00668f * grp->getL3Current() / 30000.; - config.configGRP.continuousMaxTimeBin = grp->isDetContinuousReadOut(o2::detectors::DetID::TPC) ? -1 : 0; // Number of timebins in timeframe if continuous, 0 otherwise - LOG(INFO) << "Initializing run paramerers from GRP bz=" << config.configGRP.solenoidBz << " cont=" << grp->isDetContinuousReadOut(o2::detectors::DetID::TPC); - } else { + if (!grp) { throw std::runtime_error("Failed to initialize run parameters from GRP"); } + config.configGRP.solenoidBz = 5.00668f * grp->getL3Current() / 30000.; + config.configGRP.continuousMaxTimeBin = grp->isDetContinuousReadOut(o2::detectors::DetID::TPC) ? -1 : 0; // Number of timebins in timeframe if continuous, 0 otherwise + processAttributes->nHBFPerTF = grp->getNHBFPerTF(); + LOG(INFO) << "Initializing run paramerers from GRP bz=" << config.configGRP.solenoidBz << " cont=" << grp->isDetContinuousReadOut(o2::detectors::DetID::TPC); + confParam = config.ReadConfigurableParam(); processAttributes->allocateOutputOnTheFly = confParam.allocateOutputOnTheFly; processAttributes->outputBufferSize = confParam.outputBufferSize; @@ -155,7 +156,7 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli } if (config.configGRP.continuousMaxTimeBin == -1) { - config.configGRP.continuousMaxTimeBin = (o2::raw::HBFUtils::Instance().getNOrbitsPerTF() * o2::constants::lhc::LHCMaxBunches + 2 * o2::tpc::constants::LHCBCPERTIMEBIN - 2) / o2::tpc::constants::LHCBCPERTIMEBIN; + config.configGRP.continuousMaxTimeBin = (processAttributes->nHBFPerTF * o2::constants::lhc::LHCMaxBunches + 2 * o2::tpc::constants::LHCBCPERTIMEBIN - 2) / o2::tpc::constants::LHCBCPERTIMEBIN; } if (config.configProcessing.deviceNum == -2) { int myId = ic.services().get().inputTimesliceId; @@ -606,6 +607,8 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli const auto* dh = o2::header::get(pc.inputs().getByPos(0).header); tfSettings.tfStartOrbit = dh->firstTForbit; tfSettings.hasTfStartOrbit = 1; + tfSettings.nHBFPerTF = processAttributes->nHBFPerTF; + tfSettings.hasNHBFPerTF = 1; ptrs.settingsTF = &tfSettings; if (processAttributes->tpcSectorMask != 0xFFFFFFFFF) { diff --git a/prodtests/full-system-test/dpl-workflow.sh b/prodtests/full-system-test/dpl-workflow.sh index 2ac78edf5a3a7..1dd9c945b14ab 100755 --- a/prodtests/full-system-test/dpl-workflow.sh +++ b/prodtests/full-system-test/dpl-workflow.sh @@ -107,17 +107,17 @@ if [ $CTFINPUT == 0 ]; then fi # Common workflows -WORKFLOW+="o2-its-reco-workflow $ARGS_ALL --trackerCA $DISABLE_MC --clusters-from-upstream --disable-root-output $ITS_CONFIG --configKeyValues \"HBFUtils.nHBFPerTF=${NHBPERTF};$ITS_CONFIG_KEY\" | " -WORKFLOW+="o2-gpu-reco-workflow ${ARGS_ALL/--severity $SEVERITY/--severity $SEVERITY_TPC} --input-type=$GPU_INPUT $DISABLE_MC --output-type $GPU_OUTPUT --pipeline gpu-reconstruction:$NGPUS $GPU_CONFIG --configKeyValues \"HBFUtils.nHBFPerTF=$NHBPERTF;GPU_global.deviceType=$GPUTYPE;GPU_proc.debugLevel=0;$GPU_CONFIG_KEY;$GPU_EXTRA_CONFIG\" | " -WORKFLOW+="o2-tpcits-match-workflow $ARGS_ALL --disable-root-input --disable-root-output $DISABLE_MC --pipeline itstpc-track-matcher:$N_TPCITS --configKeyValues \"HBFUtils.nHBFPerTF=${NHBPERTF};\" | " -WORKFLOW+="o2-ft0-reco-workflow $ARGS_ALL --disable-root-input --disable-root-output $DISABLE_MC --configKeyValues \"HBFUtils.nHBFPerTF=${NHBPERTF};\" | " +WORKFLOW+="o2-its-reco-workflow $ARGS_ALL --trackerCA $DISABLE_MC --clusters-from-upstream --disable-root-output $ITS_CONFIG --configKeyValues \"$ITS_CONFIG_KEY\" | " +WORKFLOW+="o2-gpu-reco-workflow ${ARGS_ALL/--severity $SEVERITY/--severity $SEVERITY_TPC} --input-type=$GPU_INPUT $DISABLE_MC --output-type $GPU_OUTPUT --pipeline gpu-reconstruction:$NGPUS $GPU_CONFIG --configKeyValues \"GPU_global.deviceType=$GPUTYPE;GPU_proc.debugLevel=0;$GPU_CONFIG_KEY;$GPU_EXTRA_CONFIG\" | " +WORKFLOW+="o2-tpcits-match-workflow $ARGS_ALL --disable-root-input --disable-root-output $DISABLE_MC --pipeline itstpc-track-matcher:$N_TPCITS | " +WORKFLOW+="o2-ft0-reco-workflow $ARGS_ALL --disable-root-input --disable-root-output $DISABLE_MC | " WORKFLOW+="o2-tof-reco-workflow $ARGS_ALL --configKeyValues \"HBFUtils.nHBFPerTF=$NHBPERTF\" --input-type $TOF_INPUT --output-type $TOF_OUTPUT --disable-root-input --disable-root-output $DISABLE_MC | " # Workflows disabled in sync mode if [ $SYNCMODE == 0 ]; then - WORKFLOW+="o2-tof-matcher-tpc $ARGS_ALL --configKeyValues \"HBFUtils.nHBFPerTF=$NHBPERTF\" --disable-root-input --disable-root-output $DISABLE_MC | " + WORKFLOW+="o2-tof-matcher-tpc $ARGS_ALL --disable-root-input --disable-root-output $DISABLE_MC | " WORKFLOW+="o2-mid-reco-workflow $ARGS_ALL --disable-root-output $DISABLE_MC | " - WORKFLOW+="o2-mft-reco-workflow $ARGS_ALL --clusters-from-upstream $DISABLE_MC --disable-root-output --configKeyValues \"HBFUtils.nHBFPerTF=${NHBPERTF};\" | " + WORKFLOW+="o2-mft-reco-workflow $ARGS_ALL --clusters-from-upstream $DISABLE_MC --disable-root-output | " WORKFLOW+="o2-primary-vertexing-workflow $ARGS_ALL $DISABLE_MC --disable-root-input --disable-root-output --validate-with-ft0 | " WORKFLOW+="o2-secondary-vertexing-workflow $ARGS_ALL --disable-root-input --disable-root-output | " WORKFLOW+="o2-fdd-reco-workflow $ARGS_ALL --disable-root-input --disable-root-output | " From 852ff1e42f9bbce71c9fe4a29b54cd01f14dbbd0 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 27 Apr 2021 13:55:09 +0200 Subject: [PATCH 299/770] Full system test: Fail if simulation environment missing --- prodtests/full_system_test.sh | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/prodtests/full_system_test.sh b/prodtests/full_system_test.sh index bf4092403c76e..2900bdd2ced4f 100755 --- a/prodtests/full_system_test.sh +++ b/prodtests/full_system_test.sh @@ -12,6 +12,11 @@ # # authors: D. Rohr / S. Wenzel +if [ "0$O2_ROOT" == "0" ] || [ "0$AEGIS_ROOT" == "0" ]; then + echo Missing O2sim environment + exit 1 +fi + # include jobutils, which notably brings # --> the taskwrapper as a simple control and monitoring tool # (look inside the jobutils.sh file for documentation) From 549b955e66080c92199b67e14822e1051f8d1fd2 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 28 Apr 2021 09:10:38 +0200 Subject: [PATCH 300/770] Revert "GPU: Workaround for random crashes on AMD GPUs" This reverts commit 37d55dedb6fa6b940299c8a49c6e1c442b58f06b. --- GPU/GPUTracking/Global/GPUChainTrackingSliceTracker.cxx | 3 --- 1 file changed, 3 deletions(-) diff --git a/GPU/GPUTracking/Global/GPUChainTrackingSliceTracker.cxx b/GPU/GPUTracking/Global/GPUChainTrackingSliceTracker.cxx index 460c56e5242b7..2984ec6812e87 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingSliceTracker.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingSliceTracker.cxx @@ -147,9 +147,6 @@ int GPUChainTracking::RunTPCTrackingSlices_internal() bool error = false; GPUCA_OPENMP(parallel for if(!doGPU && GetProcessingSettings().ompKernels != 1) num_threads(mRec->SetAndGetNestedLoopOmpFactor(!doGPU, NSLICES))) for (unsigned int iSlice = 0; iSlice < NSLICES; iSlice++) { - if (mRec->GetDeviceType() == GPUReconstruction::DeviceType::HIP) { - SynchronizeGPU(); // BUG: Workaround for probable bug in AMD runtime, crashes randomly if not synchronized here - } GPUTPCTracker& trk = processors()->tpcTrackers[iSlice]; GPUTPCTracker& trkShadow = doGPU ? processorsShadow()->tpcTrackers[iSlice] : trk; int useStream = (iSlice % mRec->NStreams()); From 80c2f06980b2fae9f92ab588474a2f72f162adb9 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 28 Apr 2021 09:11:54 +0200 Subject: [PATCH 301/770] GPU: hip compiler must not create binaries, will lead to linking problem, if hip-clang was compiled with lower CXXABI than the GCC we are using --- GPU/GPUTracking/Base/hip/CMakeLists.txt | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/GPU/GPUTracking/Base/hip/CMakeLists.txt b/GPU/GPUTracking/Base/hip/CMakeLists.txt index 775b58d6d9198..a2e98e7952d78 100644 --- a/GPU/GPUTracking/Base/hip/CMakeLists.txt +++ b/GPU/GPUTracking/Base/hip/CMakeLists.txt @@ -40,11 +40,11 @@ if(ALIGPU_BUILD_TYPE STREQUAL "O2") install(FILES ${HDRS} DESTINATION include/GPU) - o2_add_test(GPUsortHIP NAME test_GPUsortHIP - SOURCES test/testGPUsortHIP.hip.cxx - PUBLIC_LINK_LIBRARIES O2::GPUCommon hip::host hip::device hip::hipcub roc::rocthrust - COMPONENT_NAME GPU - LABELS gpu) +# o2_add_test(GPUsortHIP NAME test_GPUsortHIP +# SOURCES test/testGPUsortHIP.hip.cxx +# PUBLIC_LINK_LIBRARIES O2::GPUCommon hip::host hip::device hip::hipcub roc::rocthrust +# COMPONENT_NAME GPU +# LABELS gpu) endif() if(ALIGPU_BUILD_TYPE STREQUAL "ALIROOT") From 2c1130789eb3e57420ee6f73be90efbef5c3ad72 Mon Sep 17 00:00:00 2001 From: Ole Schmidt Date: Fri, 16 Apr 2021 22:02:16 +0200 Subject: [PATCH 302/770] TRD tracking based on TPC-only tracks implemented - created track interface for TrackParCov - references to ITS and TPC track seeds are added as GlobalTrackID - TRD tracking can be configured via CLI to use ITS-TPC tracks, TPC-only tracks or both as input - ITS-TPC track time uncertainty accounted for by increasing sigZ2 - TRD matches are written into separate files to allow for running two separate workflows --- Detectors/TRD/workflow/CMakeLists.txt | 2 +- .../TRDWorkflow/TRDGlobalTrackingSpec.h | 5 +- .../include/TRDWorkflow/TRDTrackWriterSpec.h | 7 +- .../include/TRDWorkflow/TRDTrackingWorkflow.h | 3 +- .../workflow/src/TRDGlobalTrackingSpec.cxx | 117 ++++++++++++++---- .../TRD/workflow/src/TRDTrackWriterSpec.cxx | 42 ++++++- .../TRD/workflow/src/TRDTrackingWorkflow.cxx | 22 +++- .../workflow/src/trd-tracking-workflow.cxx | 6 +- GPU/GPUTracking/DataTypes/GPUTRDDef.h | 7 +- GPU/GPUTracking/GPUTrackingLinkDef_O2.h | 6 +- .../TRDTracking/GPUTRDInterfaces.h | 113 ++++++++++++----- GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx | 64 ++++++---- GPU/GPUTracking/TRDTracking/GPUTRDTrack.h | 19 +++ GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx | 81 +++++++----- GPU/GPUTracking/TRDTracking/GPUTRDTracker.h | 5 +- 15 files changed, 369 insertions(+), 130 deletions(-) diff --git a/Detectors/TRD/workflow/CMakeLists.txt b/Detectors/TRD/workflow/CMakeLists.txt index c5e2e2047006b..59e86a5a3754d 100644 --- a/Detectors/TRD/workflow/CMakeLists.txt +++ b/Detectors/TRD/workflow/CMakeLists.txt @@ -26,7 +26,7 @@ o2_add_library(TRDWorkflow src/TRDTrackingWorkflow.cxx src/EntropyDecoderSpec.cxx src/EntropyEncoderSpec.cxx - PUBLIC_LINK_LIBRARIES O2::Framework O2::DPLUtils O2::Steer O2::Algorithm O2::DataFormatsTRD O2::TRDSimulation O2::TRDReconstruction O2::DetectorsBase O2::SimulationDataFormat O2::TRDBase O2::TRDCalibration O2::GPUTracking O2::GlobalTrackingWorkflowReaders) + PUBLIC_LINK_LIBRARIES O2::Framework O2::DPLUtils O2::Steer O2::Algorithm O2::DataFormatsTRD O2::TRDSimulation O2::TRDReconstruction O2::DetectorsBase O2::SimulationDataFormat O2::TRDBase O2::TRDCalibration O2::GPUTracking O2::GlobalTrackingWorkflowReaders O2::ReconstructionDataFormats O2::TPCWorkflow) #o2_target_root_dictionary(TRDWorkflow # HEADERS include/TRDWorkflow/TRDTrapSimulatorSpec.h) diff --git a/Detectors/TRD/workflow/include/TRDWorkflow/TRDGlobalTrackingSpec.h b/Detectors/TRD/workflow/include/TRDWorkflow/TRDGlobalTrackingSpec.h index ec7bb972b8bec..29fdc6ad76821 100644 --- a/Detectors/TRD/workflow/include/TRDWorkflow/TRDGlobalTrackingSpec.h +++ b/Detectors/TRD/workflow/include/TRDWorkflow/TRDGlobalTrackingSpec.h @@ -32,6 +32,7 @@ class TRDGlobalTracking : public o2::framework::Task TRDGlobalTracking(bool useMC, bool useTrkltTransf) : mUseMC(useMC), mUseTrackletTransform(useTrkltTransf) {} ~TRDGlobalTracking() override = default; void init(o2::framework::InitContext& ic) final; + void updateTimeDependentParams(); void run(o2::framework::ProcessingContext& pc) final; void endOfStream(o2::framework::EndOfStreamContext& ec) final; @@ -42,12 +43,14 @@ class TRDGlobalTracking : public o2::framework::Task std::unique_ptr mFlatGeo{nullptr}; ///< flat TRD geometry bool mUseMC{false}; ///< MC flag bool mUseTrackletTransform{false}; ///< if true, output from TrackletTransformer is used instead of uncalibrated Tracklet64 directly + float mTPCTBinMUS{.2f}; ///< width of a TPC time bin in us + float mTPCVdrift{2.58f}; ///< TPC drift velocity (for shifting TPC tracks along Z) CalibVDrift mCalibVDrift{}; ///< steers the vDrift calibration TStopwatch mTimer; }; /// create a processor spec -framework::DataProcessorSpec getTRDGlobalTrackingSpec(bool useMC, bool useTrkltTransf); +framework::DataProcessorSpec getTRDGlobalTrackingSpec(bool useMC, bool useTrkltTransf, o2::dataformats::GlobalTrackID::mask_t src); } // namespace trd } // namespace o2 diff --git a/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackWriterSpec.h b/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackWriterSpec.h index 4bacd79c5a014..540590a51a9e2 100644 --- a/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackWriterSpec.h +++ b/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackWriterSpec.h @@ -20,8 +20,11 @@ namespace o2 namespace trd { -/// create a processor spec -framework::DataProcessorSpec getTRDTrackWriterSpec(bool useMC); +/// writer for matches to ITS-TPC tracks +framework::DataProcessorSpec getTRDGlobalTrackWriterSpec(bool useMC); + +/// writer for matches with TPC-only tracks +framework::DataProcessorSpec getTRDTPCTrackWriterSpec(bool useMC); } // namespace trd } // namespace o2 diff --git a/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackingWorkflow.h b/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackingWorkflow.h index 3a363d1990b03..3856a7370220c 100644 --- a/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackingWorkflow.h +++ b/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackingWorkflow.h @@ -14,13 +14,14 @@ /// @file TRDTrackingWorkflow.h #include "Framework/WorkflowSpec.h" +#include "ReconstructionDataFormats/GlobalTrackID.h" namespace o2 { namespace trd { -framework::WorkflowSpec getTRDTrackingWorkflow(bool disableRootInp, bool disableRootOut, bool useTrackletTransformer); +framework::WorkflowSpec getTRDTrackingWorkflow(bool disableRootInp, bool disableRootOut, bool useTrackletTransformer, o2::dataformats::GlobalTrackID::mask_t srcTRD); } // namespace trd } // namespace o2 diff --git a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx index c7a3596fcece8..47dc853717cbc 100644 --- a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx @@ -23,6 +23,9 @@ #include "DataFormatsTRD/CalibratedTracklet.h" #include "DataFormatsTRD/TriggerRecord.h" #include "DataFormatsTRD/Constants.h" +#include "TPCBase/ParameterElectronics.h" +#include "TPCBase/ParameterGas.h" +#include "DataFormatsGlobalTracking/RecoContainer.h" // GPU header #include "GPUReconstruction.h" @@ -38,11 +41,15 @@ using namespace o2::framework; using namespace o2::gpu; +using GTrackID = o2::dataformats::GlobalTrackID; + namespace o2 { namespace trd { +o2::globaltracking::DataRequest dataRequestTRD; + void TRDGlobalTracking::init(InitContext& ic) { @@ -83,17 +90,33 @@ void TRDGlobalTracking::init(InitContext& ic) mTimer.Reset(); } +void TRDGlobalTracking::updateTimeDependentParams() +{ + // strictly speaking, one should do this only in case of the CCDB objects update + // TODO: add CCDB interface + auto& elParam = o2::tpc::ParameterElectronics::Instance(); + auto& gasParam = o2::tpc::ParameterGas::Instance(); + mTPCTBinMUS = elParam.ZbinWidth; + mTPCVdrift = gasParam.DriftV; + mTracker->SetTPCVdrift(mTPCVdrift); +} + void TRDGlobalTracking::run(ProcessingContext& pc) { mTimer.Start(false); - const auto tracksITSTPC = pc.inputs().get>("tpcitstrack"); + o2::globaltracking::RecoContainer inputTracks; + inputTracks.collectData(pc, dataRequestTRD); + const auto tracksITSTPC = inputTracks.getTPCITSTracks(); + const auto tracksTPC = inputTracks.getTPCTracks(); const auto trackletsTRD = pc.inputs().get>("trdtracklets"); const auto triggerRecords = pc.inputs().get>("trdtriggerrec"); - int nTracks = tracksITSTPC.size(); + int nTracksITSTPC = tracksITSTPC.size(); + int nTracksTPC = tracksTPC.size(); int nCollisions = triggerRecords.size(); int nTracklets = trackletsTRD.size(); LOGF(INFO, "There are %i tracklets in total from %i trigger records", nTracklets, nCollisions); + LOGF(INFO, "As input seeds are available: %i ITS-TPC matched tracks and %i TPC tracks", nTracksITSTPC, nTracksTPC); const gsl::span* cTrkltsPtr = nullptr; using cTrkltType = std::decay_t>(""))>; @@ -106,7 +129,7 @@ void TRDGlobalTracking::run(ProcessingContext& pc) nTrackletsCal = cTrkltsPtr->size(); LOGF(INFO, "Got %i calibrated tracklets as input", nTrackletsCal); if (nTracklets != nTrackletsCal) { - LOGF(ERROR, "Number of calibrated tracklets (%i) differs from the number of uncalibrated tracklets (%i)", nTrackletsCal, nTracklets); + LOGF(FATAL, "Number of calibrated tracklets (%i) differs from the number of uncalibrated tracklets (%i)", nTrackletsCal, nTracklets); } } @@ -128,36 +151,52 @@ void TRDGlobalTracking::run(ProcessingContext& pc) } mTracker->Reset(); + updateTimeDependentParams(); - mChainTracking->mIOPtrs.nMergedTracks = nTracks; + // the number of tracks loaded into the TRD tracker depends on the defined input sources + // TPC-only tracks which are already matched to the ITS will not be loaded as seeds for the tracking + // => the maximum number of seeds it the number of TPC-only tracks. If only ITS-TPC matches are considered than that + // of course defines the number of input tracks + mChainTracking->mIOPtrs.nMergedTracks = (nTracksTPC == 0) ? nTracksITSTPC : nTracksTPC; mChainTracking->mIOPtrs.nTRDTracklets = nTracklets; mChainTracking->AllocateIOMemory(); mRec->PrepareEvent(); mRec->SetupGPUProcessor(mTracker, true); LOG(DEBUG) << "Start loading input into TRD tracker"; - // load everything into the tracker - int nTracksLoaded = 0; - for (int iTrk = 0; iTrk < nTracks; ++iTrk) { - const auto& match = tracksITSTPC[iTrk]; - const auto& trk = match.getParamOut(); - GPUTRDTrack trkLoad; - trkLoad.setX(trk.getX()); - trkLoad.setAlpha(trk.getAlpha()); - for (int i = 0; i < 5; ++i) { - trkLoad.setParam(trk.getParam(i), i); + + int nTracksLoadedITSTPC = 0; + int nTracksLoadedTPC = 0; + std::vector loadedTPCtracks; + + // load ITS-TPC matched tracks + for (const auto& match : tracksITSTPC) { + GPUTRDTrack trkLoad(match, mTPCVdrift); + if (mTracker->LoadTrack(trkLoad)) { + continue; } - for (int i = 0; i < 15; ++i) { - trkLoad.setCov(trk.getCov()[i], i); + loadedTPCtracks.push_back(match.getRefTPC()); + ++nTracksLoadedITSTPC; + LOGF(DEBUG, "Loaded ITS-TPC track %i with time %f", nTracksLoadedITSTPC, trkLoad.getTime()); + } + + // load TPC-only tracks + for (int iTrk = 0; iTrk < tracksTPC.size(); ++iTrk) { + if (std::find(loadedTPCtracks.begin(), loadedTPCtracks.end(), iTrk) != loadedTPCtracks.end()) { + // this TPC tracks has already been matched to ITS and the ITS-TPC track has already been loaded in the tracker + continue; } - trkLoad.setTime(match.getTimeMUS().getTimeStamp()); + const auto& trkTpc = tracksTPC[iTrk]; + GPUTRDTrack trkLoad(trkTpc, mTPCTBinMUS, mTPCVdrift, iTrk); if (mTracker->LoadTrack(trkLoad)) { continue; } - ++nTracksLoaded; - LOGF(DEBUG, "Loaded track %i with time %f", nTracksLoaded, trkLoad.getTime()); + ++nTracksLoadedTPC; + LOGF(DEBUG, "Loaded TPC track %i with time %f", nTracksLoadedTPC, trkLoad.getTime()); } + LOGF(INFO, "%i tracks are loaded into the TRD tracker. Out of those %i ITS-TPC tracks and %i TPC tracks", nTracksLoadedITSTPC + nTracksLoadedTPC, nTracksLoadedITSTPC, nTracksLoadedTPC); + // load the TRD tracklets for (int iTrklt = 0; iTrklt < nTracklets; ++iTrklt) { auto trklt = trackletsTRD[iTrklt]; GPUTRDTrackletWord trkltLoad(trklt.getTrackletWord()); @@ -169,6 +208,7 @@ void TRDGlobalTracking::run(ProcessingContext& pc) mTracker->SetInternalSpacePoint(iTrklt, cTrklt.getX(), cTrklt.getY(), cTrklt.getZ(), cTrklt.getDy()); } } + mTracker->SetTriggerRecordTimes(&(trdTriggerTimes[0])); mTracker->SetTriggerRecordIndices(&(trdTriggerIndices[0])); mTracker->SetNCollisions(nCollisions); @@ -177,15 +217,28 @@ void TRDGlobalTracking::run(ProcessingContext& pc) mTracker->DoTracking(mChainTracking); //mTracker->DumpTracks(); - std::vector tracksOut(mTracker->NTracks()); - std::copy(mTracker->Tracks(), mTracker->Tracks() + mTracker->NTracks(), tracksOut.begin()); + std::vector tracksOutITSTPC(nTracksLoadedITSTPC); + std::vector tracksOutTPC(nTracksLoadedTPC); + if (mTracker->NTracks() != nTracksLoadedITSTPC + nTracksLoadedTPC) { + LOGF(FATAL, "Got %i matched tracks in total whereas %i ITS-TPC + %i TPC = %i tracks were loaded as input", mTracker->NTracks(), nTracksLoadedITSTPC, nTracksLoadedTPC, nTracksLoadedITSTPC + nTracksLoadedTPC); + } + + // copy ITS-TPC matched tracks first + std::copy(mTracker->Tracks(), mTracker->Tracks() + nTracksLoadedITSTPC, tracksOutITSTPC.begin()); + // and now the remaining TPC-only matches + std::copy(mTracker->Tracks() + nTracksLoadedITSTPC, mTracker->Tracks() + mTracker->NTracks(), tracksOutTPC.begin()); // Temporary until it is transferred to its own DPL device for calibrations mCalibVDrift.setAngleDiffSums(mTracker->AngleDiffSums()); mCalibVDrift.setAngleDiffCounters(mTracker->AngleDiffCounters()); mCalibVDrift.process(); - pc.outputs().snapshot(Output{o2::header::gDataOriginTRD, "MATCHTRD", 0, Lifetime::Timeframe}, tracksOut); + if (inputTracks.isTrackSourceLoaded(GTrackID::Source::ITSTPC)) { + pc.outputs().snapshot(Output{o2::header::gDataOriginTRD, "MATCHTRD_GLO", 0, Lifetime::Timeframe}, tracksOutITSTPC); + } + if (inputTracks.isTrackSourceLoaded(GTrackID::Source::TPC)) { + pc.outputs().snapshot(Output{o2::header::gDataOriginTRD, "MATCHTRD_TPC", 0, Lifetime::Timeframe}, tracksOutTPC); + } mTimer.Stop(); } @@ -196,11 +249,13 @@ void TRDGlobalTracking::endOfStream(EndOfStreamContext& ec) mTimer.CpuTime(), mTimer.RealTime(), mTimer.Counter() - 1); } -DataProcessorSpec getTRDGlobalTrackingSpec(bool useMC, bool useTrkltTransf) +DataProcessorSpec getTRDGlobalTrackingSpec(bool useMC, bool useTrkltTransf, GTrackID::mask_t src) { - std::vector inputs; std::vector outputs; - inputs.emplace_back("tpcitstrack", "GLO", "TPCITS", 0, Lifetime::Timeframe); + + dataRequestTRD.requestTracks(src, false); + auto& inputs = dataRequestTRD.inputs; + if (useTrkltTransf) { inputs.emplace_back("trdctracklets", o2::header::gDataOriginTRD, "CTRACKLETS", 0, Lifetime::Timeframe); } @@ -211,10 +266,18 @@ DataProcessorSpec getTRDGlobalTrackingSpec(bool useMC, bool useTrkltTransf) LOG(FATAL) << "MC usage must be disabled for this workflow, since it is not yet implemented"; } - outputs.emplace_back(o2::header::gDataOriginTRD, "MATCHTRD", 0, Lifetime::Timeframe); + if (GTrackID::includesSource(GTrackID::Source::ITSTPC, src)) { + outputs.emplace_back(o2::header::gDataOriginTRD, "MATCHTRD_GLO", 0, Lifetime::Timeframe); + } + if (GTrackID::includesSource(GTrackID::Source::TPC, src)) { + outputs.emplace_back(o2::header::gDataOriginTRD, "MATCHTRD_TPC", 0, Lifetime::Timeframe); + } + + std::string processorName = o2::utils::concat_string("trd-globaltracking", GTrackID::getSourcesNames(src)); + std::replace(processorName.begin(), processorName.end(), ',', '_'); return DataProcessorSpec{ - "trd-globaltracking", + processorName, inputs, outputs, AlgorithmSpec{adaptFromTask(useMC, useTrkltTransf)}, diff --git a/Detectors/TRD/workflow/src/TRDTrackWriterSpec.cxx b/Detectors/TRD/workflow/src/TRDTrackWriterSpec.cxx index f42af52207f57..c8dfc3c39b133 100644 --- a/Detectors/TRD/workflow/src/TRDTrackWriterSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDTrackWriterSpec.cxx @@ -16,10 +16,13 @@ #include "GPUTRDTrack.h" #include "DPLUtils/MakeRootTreeWriterSpec.h" +#include "TRDWorkflow/TRDTrackWriterSpec.h" using namespace o2::framework; using namespace o2::gpu; +using GTrackID = o2::dataformats::GlobalTrackID; + namespace o2 { namespace trd @@ -27,7 +30,38 @@ namespace trd template using BranchDefinition = MakeRootTreeWriterSpec::BranchDefinition; -DataProcessorSpec getTRDTrackWriterSpec(bool useMC) +DataProcessorSpec getTRDGlobalTrackWriterSpec(bool useMC) +{ + // TODO: not clear if the writer is supposed to write MC labels at some point + // this is just a dummy definition for the template branch definition below + // define the correct type and the input specs + using LabelsType = std::vector; + // force, this will disable the branch for now, can be adjusted in the future + useMC = false; + + // A spectator to store the size of the data array for the logger below + auto tracksSize = std::make_shared(); + auto tracksLogger = [tracksSize](std::vector const& tracks) { + *tracksSize = tracks.size(); + }; + + return MakeRootTreeWriterSpec("trd-track-writer-tpcits", + "trdmatches_itstpc.root", + "tracksTRD", + BranchDefinition>{InputSpec{"tracks", o2::header::gDataOriginTRD, "MATCHTRD_GLO", 0}, + "tracks", + "tracks-branch-name", + 1, + tracksLogger}, + // NOTE: this branch template is to show how the conditional MC labels can + // be defined, the '0' disables the branch for the moment + BranchDefinition{InputSpec{"matchtpclabels", "GLO", "SOME_LABELS", 0}, + "labels", + (useMC ? 1 : 0), // one branch if mc labels enabled + "labels-branch-name"})(); +} + +DataProcessorSpec getTRDTPCTrackWriterSpec(bool useMC) { // TODO: not clear if the writer is supposed to write MC labels at some point // this is just a dummy definition for the template branch definition below @@ -42,10 +76,10 @@ DataProcessorSpec getTRDTrackWriterSpec(bool useMC) *tracksSize = tracks.size(); }; - return MakeRootTreeWriterSpec("trd-track-writer", - "trdtracks.root", + return MakeRootTreeWriterSpec("trd-track-writer-tpc", + "trdmatches_tpc.root", "tracksTRD", - BranchDefinition>{InputSpec{"tracks", o2::header::gDataOriginTRD, "MATCHTRD", 0}, + BranchDefinition>{InputSpec{"tracks", o2::header::gDataOriginTRD, "MATCHTRD_TPC", 0}, "tracks", "tracks-branch-name", 1, diff --git a/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx b/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx index aa9852843eb7d..a1767814f55d9 100644 --- a/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx +++ b/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx @@ -14,28 +14,42 @@ #include "Framework/WorkflowSpec.h" #include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" +#include "TPCWorkflow/TrackReaderSpec.h" #include "TRDWorkflow/TRDTrackletReaderSpec.h" #include "TRDWorkflow/TRDGlobalTrackingSpec.h" #include "TRDWorkflow/TRDTrackWriterSpec.h" +#include "TRDWorkflow/TRDTrackingWorkflow.h" + +using GTrackID = o2::dataformats::GlobalTrackID; namespace o2 { namespace trd { -framework::WorkflowSpec getTRDTrackingWorkflow(bool disableRootInp, bool disableRootOut, bool useTrkltTransf) +framework::WorkflowSpec getTRDTrackingWorkflow(bool disableRootInp, bool disableRootOut, bool useTrkltTransf, GTrackID::mask_t srcTRD) { framework::WorkflowSpec specs; bool useMC = false; if (!disableRootInp) { - specs.emplace_back(o2::globaltracking::getTrackTPCITSReaderSpec(useMC)); + if (GTrackID::includesSource(GTrackID::Source::ITSTPC, srcTRD)) { + specs.emplace_back(o2::globaltracking::getTrackTPCITSReaderSpec(useMC)); + } + if (GTrackID::includesSource(GTrackID::Source::TPC, srcTRD)) { + specs.emplace_back(o2::tpc::getTPCTrackReaderSpec(useMC)); + } specs.emplace_back(o2::trd::getTRDTrackletReaderSpec(useMC, useTrkltTransf)); } - specs.emplace_back(o2::trd::getTRDGlobalTrackingSpec(useMC, useTrkltTransf)); + specs.emplace_back(o2::trd::getTRDGlobalTrackingSpec(useMC, useTrkltTransf, srcTRD)); if (!disableRootOut) { - specs.emplace_back(o2::trd::getTRDTrackWriterSpec(useMC)); + if (GTrackID::includesSource(GTrackID::Source::ITSTPC, srcTRD)) { + specs.emplace_back(o2::trd::getTRDGlobalTrackWriterSpec(useMC)); + } + if (GTrackID::includesSource(GTrackID::Source::TPC, srcTRD)) { + specs.emplace_back(o2::trd::getTRDTPCTrackWriterSpec(useMC)); + } } return specs; } diff --git a/Detectors/TRD/workflow/src/trd-tracking-workflow.cxx b/Detectors/TRD/workflow/src/trd-tracking-workflow.cxx index 49782fdba0a1f..2f0f4cba5897d 100644 --- a/Detectors/TRD/workflow/src/trd-tracking-workflow.cxx +++ b/Detectors/TRD/workflow/src/trd-tracking-workflow.cxx @@ -12,6 +12,7 @@ #include "CommonUtils/ConfigurableParam.h" #include "Framework/CompletionPolicy.h" #include "DetectorsRaw/HBFUtilsInitializer.h" +#include "ReconstructionDataFormats/GlobalTrackID.h" using namespace o2::framework; @@ -26,6 +27,7 @@ void customize(std::vector& workflowOptions) {"use-tracklet-transformer", VariantType::Bool, false, {"Use calibrated tracklets instead raw Tracklet64"}}, {"disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}, {"disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}, + {"tracking-sources", VariantType::String, std::string{o2::dataformats::GlobalTrackID::ALL}, {"comma-separated list of sources to use for tracking"}}, {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}}; o2::raw::HBFUtilsInitializer::addConfigOption(options); @@ -39,6 +41,7 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { + o2::dataformats::GlobalTrackID::mask_t allowedSources = o2::dataformats::GlobalTrackID::getSourcesMask("ITS-TPC,TPC"); // Update the (declared) parameters if changed from the command line o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); // write the configuration used for the workflow @@ -46,8 +49,9 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) auto disableRootInp = configcontext.options().get("disable-root-input"); auto disableRootOut = configcontext.options().get("disable-root-output"); auto useTrackletTransformer = configcontext.options().get("use-tracklet-transformer"); + o2::dataformats::GlobalTrackID::mask_t srcTRD = allowedSources & o2::dataformats::GlobalTrackID::getSourcesMask(configcontext.options().get("tracking-sources")); - auto wf = o2::trd::getTRDTrackingWorkflow(disableRootInp, disableRootOut, useTrackletTransformer); + auto wf = o2::trd::getTRDTrackingWorkflow(disableRootInp, disableRootOut, useTrackletTransformer, srcTRD); // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit o2::raw::HBFUtilsInitializer hbfIni(configcontext, wf); diff --git a/GPU/GPUTracking/DataTypes/GPUTRDDef.h b/GPU/GPUTracking/DataTypes/GPUTRDDef.h index d4dc655dfe0c5..d264abac08d12 100644 --- a/GPU/GPUTracking/DataTypes/GPUTRDDef.h +++ b/GPU/GPUTracking/DataTypes/GPUTRDDef.h @@ -28,9 +28,10 @@ class AliTrackerBase; #else namespace o2 { -namespace dataformats +namespace track { -class TrackTPCITS; +template +class TrackParametrizationWithError; } // namespace dataformats namespace base { @@ -56,7 +57,7 @@ typedef AliExternalTrackParam TRDBaseTrack; class GPUTPCGMTrackParam; typedef GPUTPCGMTrackParam TRDBaseTrackGPU; #elif defined(TRD_TRACK_TYPE_O2) -typedef o2::dataformats::TrackTPCITS TRDBaseTrack; +typedef o2::track::TrackParametrizationWithError TRDBaseTrack; class GPUTPCGMTrackParam; typedef GPUTPCGMTrackParam TRDBaseTrackGPU; #endif diff --git a/GPU/GPUTracking/GPUTrackingLinkDef_O2.h b/GPU/GPUTracking/GPUTrackingLinkDef_O2.h index 528d4a285fbc4..ef4f034e022f0 100644 --- a/GPU/GPUTracking/GPUTrackingLinkDef_O2.h +++ b/GPU/GPUTracking/GPUTrackingLinkDef_O2.h @@ -18,9 +18,9 @@ #pragma link off all functions; #pragma link C++ class o2::gpu::TPCdEdxCalibrationSplines + ; -#pragma link C++ class o2::gpu::trackInterface < o2::dataformats::TrackTPCITS> + ; -#pragma link C++ class o2::gpu::GPUTRDTrack_t < o2::gpu::trackInterface < o2::dataformats::TrackTPCITS>> + ; -#pragma link C++ class std::vector < o2::gpu::GPUTRDTrack_t < o2::gpu::trackInterface < o2::dataformats::TrackTPCITS>>> + ; +#pragma link C++ class o2::gpu::trackInterface < o2::track::TrackParCov> + ; +#pragma link C++ class o2::gpu::GPUTRDTrack_t < o2::gpu::trackInterface < o2::track::TrackParCov>> + ; +#pragma link C++ class std::vector < o2::gpu::GPUTRDTrack_t < o2::gpu::trackInterface < o2::track::TrackParCov>>> + ; #pragma link C++ class o2::gpu::GPUConfigurableParamGPUSettingsO2 + ; #pragma link C++ class o2::gpu::GPUConfigurableParamGPUSettingsRec + ; #pragma link C++ class o2::gpu::GPUConfigurableParamGPUSettingsProcessing + ; diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h index 96f90315944a1..aa6bb594084f7 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h @@ -80,8 +80,13 @@ class trackInterface : public AliExternalTrackParam const My_Float* getPar() const { return GetParameter(); } const My_Float* getCov() const { return GetCovariance(); } + void resetCovariance(float s) { ResetCovariance(10.); } float getTime() const { return -1.f; } - GPUd() void resetCovariance(float s) { ResetCovariance(10.); } + float getTimeMax() const { return 0.f; } + float getTimeMin() const { return 0.f; } + short getSide() const { return 0; } + void setZShift(float) {} + float getZShift() const { return 0.f; } bool CheckNumericalQuality() const { return true; } // parameter manipulation @@ -130,8 +135,12 @@ class propagatorInterface : public AliTrackerBase #if (defined(GPUCA_O2_LIB) || defined(GPUCA_O2_INTERFACE)) && !defined(GPUCA_GPUCODE) // Interface for O2, build only with O2 +#include "ReconstructionDataFormats/Track.h" #include "ReconstructionDataFormats/TrackTPCITS.h" +#include "DataFormatsTPC/TrackTPC.h" +#include "ReconstructionDataFormats/GlobalTrackID.h" #include "DetectorsBase/Propagator.h" +#include namespace GPUCA_NAMESPACE { @@ -140,35 +149,36 @@ namespace gpu { template <> -class trackInterface : public o2::dataformats::TrackTPCITS +class trackInterface : public o2::track::TrackParCov { public: - trackInterface() = default; - trackInterface(const trackInterface& param) = default; - trackInterface(const o2::dataformats::TrackTPCITS& param) = delete; - trackInterface(const GPUTPCGMMergedTrack& trk) + trackInterface() = default; + trackInterface(const o2::track::TrackParCov& param) = delete; + trackInterface(const o2::dataformats::TrackTPCITS& trkItsTpc, float vDrift) : o2::track::TrackParCov(trkItsTpc.getParamOut()) { - setX(trk.OuterParam().X); - setAlpha(trk.OuterParam().alpha); - for (int i = 0; i < 5; i++) { - setParam(trk.OuterParam().P[i], i); - } - for (int i = 0; i < 15; i++) { - setCov(trk.OuterParam().C[i], i); - } + mTime = trkItsTpc.getTimeMUS().getTimeStamp(); + mTimeAddMax = trkItsTpc.getTimeMUS().getTimeStampError(); + mTimeSubMax = trkItsTpc.getTimeMUS().getTimeStampError(); + mRefITS = trkItsTpc.getRefITS(); + mRefTPC = trkItsTpc.getRefTPC(); + updateCov(std::pow(trkItsTpc.getTimeMUS().getTimeStampError() * vDrift, 2), o2::track::CovLabels::kSigZ2); // account for time uncertainty by increasing sigmaZ2 } - trackInterface(const GPUTPCGMTrackParam::GPUTPCOuterParam& param) + trackInterface(const o2::tpc::TrackTPC& trkTpc, float tbWidth, float vDrift, unsigned int iTrk) : o2::track::TrackParCov(trkTpc.getParamOut()) { - setX(param.X); - setAlpha(param.alpha); - for (int i = 0; i < 5; i++) { - setParam(param.P[i], i); - } - for (int i = 0; i < 15; i++) { - setCov(param.C[i], i); + mRefTPC = {iTrk, o2::dataformats::GlobalTrackID::TPC}; + mTime = trkTpc.getTime0() * tbWidth; + mTimeAddMax = trkTpc.getDeltaTFwd() * tbWidth; + mTimeSubMax = trkTpc.getDeltaTBwd() * tbWidth; + if (trkTpc.hasASideClustersOnly()) { + mSide = -1; + } else if (trkTpc.hasCSideClustersOnly()) { + mSide = 1; + } else { + // CE-crossing tracks are not shifted along z, but the time uncertainty is taken into account by increasing sigmaZ2 + float timeWindow = (mTimeAddMax + mTimeSubMax) * .5f; + updateCov(std::pow(timeWindow * vDrift, 2), o2::track::CovLabels::kSigZ2); } - }; - + } void set(float x, float alpha, const float param[5], const float cov[15]) { setX(x); @@ -180,17 +190,30 @@ class trackInterface : public o2::dataformats::Tra setCov(cov[i], i); } } + trackInterface(const GPUTPCGMMergedTrack& trk) { set(trk.OuterParam().X, trk.OuterParam().alpha, trk.OuterParam().P, trk.OuterParam().C); } + trackInterface(const GPUTPCGMTrackParam::GPUTPCOuterParam& param) { set(param.X, param.alpha, param.P, param.C); } const float* getPar() const { return getParams(); } float getTime() const { return mTime; } void setTime(float t) { mTime = t; } + float getTimeMax() const { return mTime + mTimeAddMax; } + float getTimeMin() const { return mTime - mTimeSubMax; } + short getSide() const { return mSide; } + float getZShift() const { return mZShift; } + void setZShift(float z) { mZShift = z; } bool CheckNumericalQuality() const { return true; } - typedef o2::dataformats::TrackTPCITS baseClass; + typedef o2::track::TrackParCov baseClass; private: - float mTime; + o2::dataformats::GlobalTrackID mRefTPC; // reference on TPC track entry in its original container + o2::dataformats::GlobalTrackID mRefITS; // reference on ITS track entry in its original container + float mTime{-1.f}; // time estimate for this track in us + float mTimeAddMax{0.f}; // max. time that can be added to this track in us + float mTimeSubMax{0.f}; // max. time that can be subtracted to this track in us + short mSide{0}; // -1 : A-side, +1 : C-side (relevant only for TPC-only tracks) + float mZShift{0.f}; // calculated new for each TRD trigger candidate for this track }; template <> @@ -204,7 +227,7 @@ class propagatorInterface bool propagateToX(float x, float maxSnp, float maxStep) { return mProp->PropagateToXBxByBz(*mParam, x, maxSnp, maxStep); } int getPropagatedYZ(float x, float& projY, float& projZ) { return static_cast(mParam->getYZAt(x, mProp->getNominalBz(), projY, projZ)); } - void setTrack(trackInterface* trk) { mParam = trk; } + void setTrack(trackInterface* trk) { mParam = trk; } void setFitInProjections(bool flag) {} float getAlpha() { return (mParam) ? mParam->getAlpha() : 99999.f; } @@ -230,7 +253,7 @@ class propagatorInterface } bool rotate(float alpha) { return (mParam) ? mParam->rotate(alpha) : false; } - trackInterface* mParam{nullptr}; + trackInterface* mParam{nullptr}; o2::base::Propagator* mProp{o2::base::Propagator::Instance()}; }; @@ -242,6 +265,9 @@ class propagatorInterface #include "GPUTPCGMPropagator.h" #include "GPUParam.h" #include "GPUDef.h" +#ifdef GPUCA_O2_LIB +#include "DataFormatsTPC/TrackTPC.h" +#endif namespace GPUCA_NAMESPACE { @@ -283,6 +309,32 @@ class trackInterface : public GPUTPCGMTrackParam } }; #endif +#if defined(GPUCA_O2_LIB) && !defined(GPUCA_GPUCODE) + trackInterface(const o2::dataformats::TrackTPCITS& param, float) : GPUTPCGMTrackParam(), mAlpha(param.getParamOut().getAlpha()) + { + SetX(param.getParamOut().getX()); + SetPar(0, param.getParamOut().getY()); + SetPar(1, param.getParamOut().getZ()); + SetPar(2, param.getParamOut().getSnp()); + SetPar(3, param.getParamOut().getTgl()); + SetPar(4, param.getParamOut().getQ2Pt()); + for (int i = 0; i < 15; i++) { + SetCov(i, param.getParamOut().getCov()[i]); + } + } + trackInterface(const o2::tpc::TrackTPC& param, float, float, unsigned int) : GPUTPCGMTrackParam(), mAlpha(param.getParamOut().getAlpha()) + { + SetX(param.getParamOut().getX()); + SetPar(0, param.getParamOut().getY()); + SetPar(1, param.getParamOut().getZ()); + SetPar(2, param.getParamOut().getSnp()); + SetPar(3, param.getParamOut().getTgl()); + SetPar(4, param.getParamOut().getQ2Pt()); + for (int i = 0; i < 15; i++) { + SetCov(i, param.getParamOut().getCov()[i]); + } + } +#endif GPUd() float getX() const { @@ -302,6 +354,11 @@ class trackInterface : public GPUTPCGMTrackParam GPUd() const float* getPar() const { return GetPar(); } GPUd() const float* getCov() const { return GetCov(); } GPUd() float getTime() const { return -1.f; } + GPUd() float getTimeMax() const { return 0.f; } + GPUd() float getTimeMin() const { return 0.f; } + GPUd() short getSide() const { return 0; } + GPUd() void setZShift(float) {} + GPUd() float getZShift() const { return 0.f; } GPUd() void resetCovariance(float s) { ResetCovariance(); } GPUd() void setAlpha(float alpha) { mAlpha = alpha; } GPUd() void set(float x, float alpha, const float param[5], const float cov[15]) diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx index df0201333d450..203a8834afb15 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx @@ -16,15 +16,27 @@ using namespace GPUCA_NAMESPACE::gpu; -#ifdef GPUCA_ALIROOT_LIB -#include "AliHLTExternalTrackParam.h" - template -GPUd() GPUTRDTrack_t::GPUTRDTrack_t(const AliHLTExternalTrackParam& t) : T(t), mChi2(0.f), mMass(0.f), mLabel(-1), mTPCTrackId(0), mNTracklets(0), mNMissingConsecLayers(0), mLabelOffline(-1), mIsStopped(false) +GPUd() GPUTRDTrack_t::GPUTRDTrack_t() { //------------------------------------------------------------------ - // copy constructor from AliHLTExternalTrackParam struct + // default constructor //------------------------------------------------------------------ + Initialize(); +} + +template +GPUd() void GPUTRDTrack_t::Initialize() +{ + // set all members to their default values (needed since in-class initialization not possible with AliRoot) + mChi2 = 0.f; + mMass = 0.f; + mLabel = -1; + mTPCTrackId = 0; + mNTracklets = 0; + mNMissingConsecLayers = 0; + mLabelOffline = -1; + mIsStopped = false; for (int i = 0; i < kNLayers; ++i) { mAttachedTracklets[i] = -1; mIsFindable[i] = 0; @@ -33,22 +45,30 @@ GPUd() GPUTRDTrack_t::GPUTRDTrack_t(const AliHLTExternalTrackParam& t) : T(t) mNTrackletsOffline[j] = 0; } } + +#ifdef GPUCA_ALIROOT_LIB +#include "AliHLTExternalTrackParam.h" +template +GPUd() GPUTRDTrack_t::GPUTRDTrack_t(const AliHLTExternalTrackParam& t) : T(t) +{ + Initialize(); +} #endif +#if defined(GPUCA_O2_LIB) && !defined(GPUCA_GPUCODE) +#include "ReconstructionDataFormats/TrackTPCITS.h" +#include "DataFormatsTPC/TrackTPC.h" template -GPUd() GPUTRDTrack_t::GPUTRDTrack_t() : mChi2(0.f), mMass(0.f), mLabel(-1), mTPCTrackId(0), mNTracklets(0), mNMissingConsecLayers(0), mLabelOffline(-1), mIsStopped(false) +GPUd() GPUTRDTrack_t::GPUTRDTrack_t(const o2::dataformats::TrackTPCITS& t, float vDrift) : T(t, vDrift) { - //------------------------------------------------------------------ - // default constructor - //------------------------------------------------------------------ - for (int i = 0; i < kNLayers; ++i) { - mAttachedTracklets[i] = -1; - mIsFindable[i] = 0; - } - for (int j = 0; j < 4; ++j) { - mNTrackletsOffline[j] = 0; - } + Initialize(); +} +template +GPUd() GPUTRDTrack_t::GPUTRDTrack_t(const o2::tpc::TrackTPC& t, float tbWidth, float vDrift, unsigned int iTrk) : T(t, tbWidth, vDrift, iTrk) +{ + Initialize(); } +#endif template GPUd() GPUTRDTrack_t::GPUTRDTrack_t(const GPUTRDTrack_t& t) @@ -67,18 +87,12 @@ GPUd() GPUTRDTrack_t::GPUTRDTrack_t(const GPUTRDTrack_t& t) } template -GPUd() GPUTRDTrack_t::GPUTRDTrack_t(const T& t) : T(t), mChi2(0.f), mMass(0.f), mLabel(-1), mTPCTrackId(0), mNTracklets(0), mNMissingConsecLayers(0), mLabelOffline(-1), mIsStopped(false) +GPUd() GPUTRDTrack_t::GPUTRDTrack_t(const T& t) : T(t) { //------------------------------------------------------------------ // copy constructor from anything //------------------------------------------------------------------ - for (int i = 0; i < kNLayers; ++i) { - mAttachedTracklets[i] = -1; - mIsFindable[i] = 0; - } - for (int j = 0; j < 4; ++j) { - mNTrackletsOffline[j] = 0; - } + Initialize(); } template @@ -213,7 +227,7 @@ namespace gpu template class GPUTRDTrack_t>; #endif #ifdef GPUCA_O2_LIB // Instantiate O2 track version -template class GPUTRDTrack_t>; +template class GPUTRDTrack_t>; #endif #endif template class GPUTRDTrack_t>; // Always instatiate GM track version diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTrack.h b/GPU/GPUTracking/TRDTracking/GPUTRDTrack.h index 515927fac8452..a526b1d770eea 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTrack.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTrack.h @@ -20,6 +20,18 @@ struct GPUTRDTrackDataRecord; class AliHLTExternalTrackParam; +namespace o2 +{ +namespace tpc +{ +class TrackTPC; +} +namespace dataformats +{ +class TrackTPCITS; +} +} // namespace o2 + //_____________________________________________________________________________ #if (defined(__CINT__) || defined(__ROOTCINT__)) && !defined(__CLING__) namespace GPUCA_NAMESPACE @@ -48,6 +60,10 @@ class GPUTRDTrack_t : public T GPUTRDTrack_t(const typename T::baseClass& t) = delete; GPUd() GPUTRDTrack_t(const GPUTRDTrack_t& t); GPUd() GPUTRDTrack_t(const AliHLTExternalTrackParam& t); +#ifndef GPUCA_GPUCODE + GPUd() GPUTRDTrack_t(const o2::dataformats::TrackTPCITS& t, float vDrift); + GPUd() GPUTRDTrack_t(const o2::tpc::TrackTPC& t, float tbWidth, float vDrift, unsigned int iTrk); +#endif GPUd() GPUTRDTrack_t(const T& t); GPUd() GPUTRDTrack_t& operator=(const GPUTRDTrack_t& t); @@ -99,6 +115,9 @@ class GPUTRDTrack_t : public T int mAttachedTracklets[kNLayers]; // IDs for attached tracklets sorted by layer bool mIsFindable[kNLayers]; // number of layers where tracklet should exist bool mIsStopped; // track ends in TRD + + private: + GPUd() void Initialize(); }; } // namespace gpu } // namespace GPUCA_NAMESPACE diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx index 61352f69013c6..4180eb8dee8e0 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx @@ -105,7 +105,7 @@ void* GPUTRDTracker_t::SetPointersTracks(void* base) } template -GPUTRDTracker_t::GPUTRDTracker_t() : mR(nullptr), mIsInitialized(false), mTrkltTransfNeeded(true), mProcessPerTimeFrame(false), mDoImpactAngleHistograms(false), mNAngleHistogramBins(25), mAngleHistogramRange(50), mMemoryPermanent(-1), mMemoryTracklets(-1), mMemoryTracks(-1), mNMaxCollisions(1), mNMaxTracks(0), mNMaxSpacePoints(0), mTracks(nullptr), mNCandidates(1), mNCollisions(1), mNTracks(0), mNEvents(0), mTriggerRecordIndices(nullptr), mTriggerRecordTimes(nullptr), mTracklets(nullptr), mTrackletIndices(nullptr), mMaxThreads(100), mNTracklets(0), mTrackletIndexArray(nullptr), mHypothesis(nullptr), mCandidates(nullptr), mSpacePoints(nullptr), mAngleDiffSums(nullptr), mAngleDiffCounters(nullptr), mTrackletLabels(nullptr), mGeo(nullptr), mRPhiA2(0), mRPhiB(0), mRPhiC2(0), mDyA2(0), mDyB(0), mDyC2(0), mAngleToDyA(0), mAngleToDyB(0), mAngleToDyC(0), mDebugOutput(false), mTimeWindow(.1f), mMaxEta(0.84f), mExtraRoadY(2.f), mRoadZ(18.f), mZCorrCoefNRC(1.4f), mMCEvent(nullptr), mDebug(new GPUTRDTrackerDebug()) +GPUTRDTracker_t::GPUTRDTracker_t() : mR(nullptr), mIsInitialized(false), mTrkltTransfNeeded(true), mProcessPerTimeFrame(false), mDoImpactAngleHistograms(false), mNAngleHistogramBins(25), mAngleHistogramRange(50), mMemoryPermanent(-1), mMemoryTracklets(-1), mMemoryTracks(-1), mNMaxCollisions(1), mNMaxTracks(0), mNMaxSpacePoints(0), mTracks(nullptr), mNCandidates(1), mNCollisions(1), mNTracks(0), mNEvents(0), mTriggerRecordIndices(nullptr), mTriggerRecordTimes(nullptr), mTracklets(nullptr), mTrackletIndices(nullptr), mMaxThreads(100), mNTracklets(0), mTrackletIndexArray(nullptr), mHypothesis(nullptr), mCandidates(nullptr), mSpacePoints(nullptr), mAngleDiffSums(nullptr), mAngleDiffCounters(nullptr), mTrackletLabels(nullptr), mGeo(nullptr), mRPhiA2(0), mRPhiB(0), mRPhiC2(0), mDyA2(0), mDyB(0), mDyC2(0), mAngleToDyA(0), mAngleToDyB(0), mAngleToDyC(0), mDebugOutput(false), mMaxEta(0.84f), mExtraRoadY(2.f), mRoadZ(18.f), mZCorrCoefNRC(1.4f), mTPCVdrift(2.58f), mMCEvent(nullptr), mDebug(new GPUTRDTrackerDebug()) { //-------------------------------------------------------------------- // Default constructor @@ -526,17 +526,26 @@ GPUd() void GPUTRDTracker_t::DumpTracks() } template -GPUd() int GPUTRDTracker_t::GetCollisionID(float trkTime) const +GPUd() int GPUTRDTracker_t::GetCollisionIDs(TRDTRK& trk, int* collisionIds) const { + //-------------------------------------------------------------------- + // Check which TRD trigger times possibly match given input track. + // If ITS-TPC matches or CE-crossing TPC tracks the time is precisely + // known and max 1 trigger time can be assigned. + // For TPC-only tracks the collision IDs are stored in collisionIds array + // and the number of valid entries in the array is returned + //-------------------------------------------------------------------- + int nColls = 0; for (int iColl = 0; iColl < mNCollisions; ++iColl) { - if (CAMath::Abs(trkTime - mTriggerRecordTimes[iColl]) < mTimeWindow) { - if (ENABLE_INFO) { - GPUInfo("TRD info found from interaction %i at %f for track with time %f", iColl, mTriggerRecordTimes[iColl], trkTime); + if (mTriggerRecordTimes[iColl] > trk.getTimeMin() && mTriggerRecordTimes[iColl] < trk.getTimeMax()) { + if (nColls == 20) { + GPUError("Found too many collision candidates for track with tMin(%f) and tMax(%f)", trk.getTimeMin(), trk.getTimeMax()); + return nColls; } - return iColl; + collisionIds[nColls++] = iColl; } } - return -1; + return nColls; } template @@ -545,23 +554,31 @@ GPUd() void GPUTRDTracker_t::DoTrackingThread(int iTrk, int thread //-------------------------------------------------------------------- // perform the tracking for one track (must be threadsafe) //-------------------------------------------------------------------- - int collisionId = 0; + int collisionIds[20] = {0}; // due to the dead time there will never exist more possible TRD triggers for a single track + int nCollisionIds = 1; // initialize with 1 for AliRoot compatibility if (mProcessPerTimeFrame) { - collisionId = GetCollisionID(mTracks[iTrk].getTime()); - if (collisionId < 0) { + nCollisionIds = GetCollisionIDs(mTracks[iTrk], collisionIds); + if (nCollisionIds == 0) { if (ENABLE_INFO) { - GPUInfo("Did not find TRD data for track with t=%f", mTracks[iTrk].getTime()); + GPUInfo("Did not find TRD data for track with t=%f. tMin(%f), tMax(%f)", mTracks[iTrk].getTime(), mTracks[iTrk].getTimeMin(), mTracks[iTrk].getTimeMax()); } // no TRD data available for the bunch crossing this track originates from return; } } PROP prop(&Param().polynomialField); - auto trkCopy = mTracks[iTrk]; - prop.setTrack(&trkCopy); - prop.setFitInProjections(true); - FollowProlongation(&prop, &trkCopy, threadId, collisionId); - mTracks[iTrk] = trkCopy; // copy back the resulting track + mTracks[iTrk].SetChi2(Param().rec.trdPenaltyChi2); + auto trkStart = mTracks[iTrk]; + for (int iColl = 0; iColl < nCollisionIds; ++iColl) { + // do track following for each collision candidate and keep best track + auto trkCopy = trkStart; + prop.setTrack(&trkCopy); + prop.setFitInProjections(true); + FollowProlongation(&prop, &trkCopy, threadId, collisionIds[iColl]); + if (trkCopy.GetReducedChi2() < mTracks[iTrk].GetReducedChi2()) { + mTracks[iTrk] = trkCopy; // copy back the resulting track + } + } } #ifndef GPUCA_ALIROOT_LIB // AliRoot TRD geometry functions are non-const, and cannot work with a const geometry @@ -787,6 +804,7 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK int iTrack = t->GetTPCtrackId(); t->SetChi2(0.f); const GPUTRDpadPlane* pad = nullptr; + t->setZShift((t->getTime() - mTriggerRecordTimes[collisionId]) * mTPCVdrift * t->getSide()); #ifdef ENABLE_GPUTRDDEBUG TRDTRK trackNoUp(*t); @@ -881,9 +899,9 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK // roadZ = 7.f * CAMath::Sqrt(trkWork->getSigmaZ2() + 9.f * 9.f / 12.f); // take longest pad length roadZ = mRoadZ; // simply twice the longest pad length -> efficiency 99.996% // - if (CAMath::Abs(trkWork->getZ()) - roadZ >= zMaxTRD) { + if (CAMath::Abs(trkWork->getZ() + trkWork->getZShift()) - roadZ >= zMaxTRD) { if (ENABLE_INFO) { - GPUInfo("FollowProlongation: Track out of TRD acceptance with z=%f in layer %i (eta=%f)", trkWork->getZ(), iLayer, trkWork->getEta()); + GPUInfo("FollowProlongation: Track out of TRD acceptance with z=%f in layer %i (eta=%f)", trkWork->getZ() + trkWork->getZShift(), iLayer, trkWork->getEta()); } continue; } @@ -923,7 +941,7 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK // first propagate track to x of tracklet for (int trkltIdx = glbTrkltIdxOffset + mTrackletIndexArray[trkltIdxOffset + currDet]; trkltIdx < glbTrkltIdxOffset + mTrackletIndexArray[trkltIdxOffset + currDet + 1]; ++trkltIdx) { int trkltIdxGlb = mTrackletIndices[trkltIdx]; - if (CAMath::Abs(trkWork->getY() - mSpacePoints[trkltIdxGlb].mX[0]) > roadY || CAMath::Abs(trkWork->getZ() - mSpacePoints[trkltIdxGlb].mX[1]) > roadZ) { + if (CAMath::Abs(trkWork->getY() - mSpacePoints[trkltIdxGlb].mX[0]) > roadY || CAMath::Abs(trkWork->getZ() + trkWork->getZShift() - mSpacePoints[trkltIdxGlb].mX[1]) > roadZ) { // skip tracklets which are too far away // although the radii of space points and tracks may differ by ~ few mm the roads are large enough to allow no efficiency loss by this cut continue; @@ -934,11 +952,12 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK float tiltCorr = tilt * (mSpacePoints[trkltIdxGlb].mX[1] - projZ); float lPad = pad->GetRowSize(mTracklets[trkltIdxGlb].GetZbin()); if (!((CAMath::Abs(mSpacePoints[trkltIdxGlb].mX[1] - projZ) < lPad) && (trkWork->getSigmaZ2() < (lPad * lPad / 12.f)))) { - tiltCorr = 0.f; + tiltCorr = 0.f; // will be zero also for TPC tracks which are shifted in z } // correction for mean z position of tracklet (is not the center of the pad if track eta != 0) float zPosCorr = mSpacePoints[trkltIdxGlb].mX[1] + mZCorrCoefNRC * trkWork->getTgl(); float yPosCorr = mSpacePoints[trkltIdxGlb].mX[0] - tiltCorr; + zPosCorr -= trkWork->getZShift(); // shift tracklet instead of track in order to avoid having to do a re-fit for each collision float deltaY = yPosCorr - projY; float deltaZ = zPosCorr - projZ; My_Float trkltPosTmpYZ[2] = {yPosCorr, zPosCorr}; @@ -948,6 +967,7 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK RecalcTrkltCov(tilt, trkWork->getSnp(), pad->GetRowSize(mTracklets[trkltIdxGlb].GetZbin()), trkltCovTmp); float chi2 = prop->getPredictedChi2(trkltPosTmpYZ, trkltCovTmp); // GPUInfo("layer %i: chi2 = %f", iLayer, chi2); + // TODO cut on angular pull should be made stricter when proper v-drift calibration for the TRD tracklets is implemented if (chi2 < Param().rec.trdMaxChi2 && CAMath::Abs(GetAngularPull(mSpacePoints[trkltIdxGlb].mDy, trkWork->getSnp())) < 4) { Hypothesis hypo(trkWork->GetNlayers(), iCandidate, trkltIdxGlb, trkWork->GetChi2() + chi2); InsertHypothesis(hypo, nCurrHypothesis, hypothesisIdxOffset); @@ -1062,6 +1082,7 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK pad = mGeo->GetPadPlane(mTracklets[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].GetDetector()); float tiltCorrUp = tilt * (mSpacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].mX[1] - trkWork->getZ()); float zPosCorrUp = mSpacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].mX[1] + mZCorrCoefNRC * trkWork->getTgl(); + zPosCorrUp -= trkWork->getZShift(); float padLength = pad->GetRowSize(mTracklets[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].GetZbin()); if (!((trkWork->getSigmaZ2() < (padLength * padLength / 12.f)) && (CAMath::Abs(mSpacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].mX[1] - trkWork->getZ()) < padLength))) { tiltCorrUp = 0.f; @@ -1383,6 +1404,8 @@ GPUd() void GPUTRDTracker_t::FindChambersInRoad(const TRDTRK* t, c int nDets = 0; + float zTrk = t->getZ() + t->getZShift(); + if (currStack > -1) { // chamber unambiguous currDet = mGeo->GetDetector(iLayer, currStack, currSec); @@ -1390,16 +1413,16 @@ GPUd() void GPUTRDTracker_t::FindChambersInRoad(const TRDTRK* t, c const GPUTRDpadPlane* pp = mGeo->GetPadPlane(iLayer, currStack); int lastPadRow = mGeo->GetRowMax(iLayer, currStack, 0); float zCenter = pp->GetRowPos(lastPadRow / 2); - if ((t->getZ() + roadZ) > pp->GetRow0() || (t->getZ() - roadZ) < pp->GetRowEnd()) { - int addStack = t->getZ() > zCenter ? currStack - 1 : currStack + 1; + if ((zTrk + roadZ) > pp->GetRow0() || (zTrk - roadZ) < pp->GetRowEnd()) { + int addStack = zTrk > zCenter ? currStack - 1 : currStack + 1; if (addStack < kNStacks && addStack > -1) { det[nDets++] = mGeo->GetDetector(iLayer, addStack, currSec); } } } else { - if (CAMath::Abs(t->getZ()) > zMax) { + if (CAMath::Abs(zTrk) > zMax) { // shift track in z so it is in the TRD acceptance - if (t->getZ() > 0) { + if (zTrk > 0) { currDet = mGeo->GetDetector(iLayer, 0, currSec); } else { currDet = mGeo->GetDetector(iLayer, kNStacks - 1, currSec); @@ -1409,11 +1432,11 @@ GPUd() void GPUTRDTracker_t::FindChambersInRoad(const TRDTRK* t, c } else { // track in between two stacks, add both surrounding chambers // gap between two stacks is 4 cm wide - currDet = GetDetectorNumber(t->getZ() + 4.0f, alpha, iLayer); + currDet = GetDetectorNumber(zTrk + 4.0f, alpha, iLayer); if (currDet != -1) { det[nDets++] = currDet; } - currDet = GetDetectorNumber(t->getZ() - 4.0f, alpha, iLayer); + currDet = GetDetectorNumber(zTrk - 4.0f, alpha, iLayer); if (currDet != -1) { det[nDets++] = currDet; } @@ -1449,7 +1472,9 @@ GPUd() bool GPUTRDTracker_t::IsGeoFindable(const TRDTRK* t, const // and not too close to the boundaries //-------------------------------------------------------------------- - int det = GetDetectorNumber(t->getZ(), alpha, layer); + float zTrk = t->getZ() + t->getZShift(); + + int det = GetDetectorNumber(zTrk, alpha, layer); // reject tracks between stacks if (det < 0) { @@ -1474,7 +1499,7 @@ GPUd() bool GPUTRDTracker_t::IsGeoFindable(const TRDTRK* t, const return false; } // reject tracks closer than epsZ cm to stack boundary - if (!((t->getZ() > zMin + epsZ) && (t->getZ() < zMax - epsZ))) { + if (!((zTrk > zMin + epsZ) && (zTrk < zMax - epsZ))) { return false; } diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h index 1c022d735c51c..332b5ceb42b86 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h @@ -118,7 +118,7 @@ class GPUTRDTracker_t : public GPUProcessor GPUd() bool CheckTrackTRDCandidate(const TRDTRK& trk) const; GPUd() int LoadTrack(const TRDTRK& trk, const int label = -1, const int* nTrkltsOffline = nullptr, const int labelOffline = -1, int tpcTrackId = -1, bool checkTrack = true); - GPUd() int GetCollisionID(float trkTime) const; + GPUd() int GetCollisionIDs(TRDTRK& trk, int* collisionIds) const; GPUd() void DoTrackingThread(int iTrk, int threadId = 0); static GPUd() bool ConvertTrkltToSpacePoint(const GPUTRDGeometry& geo, GPUTRDTrackletWord& trklt, GPUTRDSpacePointInternal& sp); GPUd() bool CalculateSpacePoints(int iCollision = 0); @@ -156,6 +156,7 @@ class GPUTRDTracker_t : public GPUProcessor GPUd() void SetMaxEta(float maxEta) { mMaxEta = maxEta; } GPUd() void SetExtraRoadY(float extraRoadY) { mExtraRoadY = extraRoadY; } GPUd() void SetRoadZ(float roadZ) { mRoadZ = roadZ; } + GPUd() void SetTPCVdrift(float vDrift) { mTPCVdrift = vDrift; } GPUd() AliMCEvent* GetMCEvent() const { return mMCEvent; } GPUd() bool GetIsDebugOutputOn() const { return mDebugOutput; } @@ -222,12 +223,12 @@ class GPUTRDTracker_t : public GPUProcessor float mAngleToDyC; // parameterization for conversion track angle -> tracklet deflection /// ---- end error parametrization ---- bool mDebugOutput; // store debug output - float mTimeWindow; // max. deviation of the ITS-TPC track time w.r.t. TRD trigger record time stamp (in us, default is 100 ns) static CONSTEXPR float sRadialOffset GPUCA_CPP11_INIT(= -0.1f); // due to (possible) mis-calibration of t0 -> will become obsolete when tracklet conversion is done outside of the tracker float mMaxEta; // TPC tracks with higher eta are ignored float mExtraRoadY; // addition to search road in r-phi to account for not exact radial match of tracklets and tracks in first iteration float mRoadZ; // in z, a constant search road is used float mZCorrCoefNRC; // tracklet z-position depends linearly on track dip angle + float mTPCVdrift; // TPC drift velocity used for shifting TPC tracks along Z AliMCEvent* mMCEvent; //! externaly supplied optional MC event GPUTRDTrackerDebug* mDebug; // debug output }; From 2b1e8cc9f954a058612e58b54fea5cb1201e7964 Mon Sep 17 00:00:00 2001 From: Ole Schmidt Date: Tue, 27 Apr 2021 21:00:22 +0200 Subject: [PATCH 303/770] Add dummy TRD base class. Probably to be reverted After ROOT bump to 6.22 or newer. Not clear why, but this is a workaround for an issue with the ROOT interpreter which is not seen anymore in ROOT 6.22. More details in PR 5969 --- GPU/GPUTracking/CMakeLists.txt | 5 ++- GPU/GPUTracking/DataTypes/GPUTRDDef.h | 9 ++--- GPU/GPUTracking/GPUTrackingLinkDef_O2.h | 7 ++-- .../TRDTracking/GPUTRDInterfaces.h | 21 +++++----- .../TRDTracking/GPUTRDO2BaseTrack.h | 38 +++++++++++++++++++ GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx | 2 +- 6 files changed, 61 insertions(+), 21 deletions(-) create mode 100644 GPU/GPUTracking/TRDTracking/GPUTRDO2BaseTrack.h diff --git a/GPU/GPUTracking/CMakeLists.txt b/GPU/GPUTracking/CMakeLists.txt index b6f98ea2dbc45..bdfd79d8e21d8 100644 --- a/GPU/GPUTracking/CMakeLists.txt +++ b/GPU/GPUTracking/CMakeLists.txt @@ -153,7 +153,7 @@ set(HDRS_INSTALL if(ALIGPU_BUILD_TYPE STREQUAL "O2") set(SRCS ${SRCS} Interface/GPUO2InterfaceConfigurableParam.cxx) set(HDRS_CINT_O2 ${HDRS_CINT_O2} DataTypes/TPCdEdxCalibrationSplines.h Interface/GPUO2InterfaceConfigurableParam.h) - set(HDRS_CINT_O2_ADDITIONAL DataTypes/GPUSettings.h Definitions/GPUSettingsList.h DataTypes/GPUDataTypes.h TRDTracking/GPUTRDTrack.h) # Manual dependencies for ROOT dictionary generation + set(HDRS_CINT_O2_ADDITIONAL DataTypes/GPUSettings.h Definitions/GPUSettingsList.h DataTypes/GPUDataTypes.h TRDTracking/GPUTRDTrack.h TRDTracking/GPUTRDO2BaseTrack.h) # Manual dependencies for ROOT dictionary generation endif() # Sources for O2 and for Standalone if requested in config file @@ -206,7 +206,8 @@ if(ALIGPU_BUILD_TYPE STREQUAL "O2" OR CONFIG_O2_EXTENSIONS) Definitions/clusterFinderDefs.h TPCClusterFinder/GPUTPCClusterFinderKernels.h TPCClusterFinder/PackedCharge.h - TPCClusterFinder/GPUTPCCFChainContext.h) + TPCClusterFinder/GPUTPCCFChainContext.h + TRDTracking/GPUTRDO2BaseTrack.h) endif() # Sources only for AliRoot diff --git a/GPU/GPUTracking/DataTypes/GPUTRDDef.h b/GPU/GPUTracking/DataTypes/GPUTRDDef.h index d264abac08d12..2d2c294353e94 100644 --- a/GPU/GPUTracking/DataTypes/GPUTRDDef.h +++ b/GPU/GPUTracking/DataTypes/GPUTRDDef.h @@ -28,11 +28,10 @@ class AliTrackerBase; #else namespace o2 { -namespace track +namespace gpu { -template -class TrackParametrizationWithError; -} // namespace dataformats +class GPUTRDO2BaseTrack; +} // namespace gpu namespace base { template @@ -57,7 +56,7 @@ typedef AliExternalTrackParam TRDBaseTrack; class GPUTPCGMTrackParam; typedef GPUTPCGMTrackParam TRDBaseTrackGPU; #elif defined(TRD_TRACK_TYPE_O2) -typedef o2::track::TrackParametrizationWithError TRDBaseTrack; +typedef o2::gpu::GPUTRDO2BaseTrack TRDBaseTrack; class GPUTPCGMTrackParam; typedef GPUTPCGMTrackParam TRDBaseTrackGPU; #endif diff --git a/GPU/GPUTracking/GPUTrackingLinkDef_O2.h b/GPU/GPUTracking/GPUTrackingLinkDef_O2.h index ef4f034e022f0..fea264b7a8e78 100644 --- a/GPU/GPUTracking/GPUTrackingLinkDef_O2.h +++ b/GPU/GPUTracking/GPUTrackingLinkDef_O2.h @@ -18,9 +18,10 @@ #pragma link off all functions; #pragma link C++ class o2::gpu::TPCdEdxCalibrationSplines + ; -#pragma link C++ class o2::gpu::trackInterface < o2::track::TrackParCov> + ; -#pragma link C++ class o2::gpu::GPUTRDTrack_t < o2::gpu::trackInterface < o2::track::TrackParCov>> + ; -#pragma link C++ class std::vector < o2::gpu::GPUTRDTrack_t < o2::gpu::trackInterface < o2::track::TrackParCov>>> + ; +#pragma link C++ class o2::gpu::GPUTRDO2BaseTrack + ; +#pragma link C++ class o2::gpu::trackInterface < o2::gpu::GPUTRDO2BaseTrack> + ; +#pragma link C++ class o2::gpu::GPUTRDTrack_t < o2::gpu::trackInterface < o2::gpu::GPUTRDO2BaseTrack>> + ; +#pragma link C++ class std::vector < o2::gpu::GPUTRDTrack_t < o2::gpu::trackInterface < o2::gpu::GPUTRDO2BaseTrack>>> + ; #pragma link C++ class o2::gpu::GPUConfigurableParamGPUSettingsO2 + ; #pragma link C++ class o2::gpu::GPUConfigurableParamGPUSettingsRec + ; #pragma link C++ class o2::gpu::GPUConfigurableParamGPUSettingsProcessing + ; diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h index aa6bb594084f7..379c5221cb25d 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h @@ -140,6 +140,7 @@ class propagatorInterface : public AliTrackerBase #include "DataFormatsTPC/TrackTPC.h" #include "ReconstructionDataFormats/GlobalTrackID.h" #include "DetectorsBase/Propagator.h" +#include "GPUTRDO2BaseTrack.h" #include namespace GPUCA_NAMESPACE @@ -149,12 +150,12 @@ namespace gpu { template <> -class trackInterface : public o2::track::TrackParCov +class trackInterface : public GPUTRDO2BaseTrack { public: - trackInterface() = default; - trackInterface(const o2::track::TrackParCov& param) = delete; - trackInterface(const o2::dataformats::TrackTPCITS& trkItsTpc, float vDrift) : o2::track::TrackParCov(trkItsTpc.getParamOut()) + trackInterface() = default; + trackInterface(const GPUTRDO2BaseTrack& param) = delete; + trackInterface(const o2::dataformats::TrackTPCITS& trkItsTpc, float vDrift) : GPUTRDO2BaseTrack(trkItsTpc.getParamOut()) { mTime = trkItsTpc.getTimeMUS().getTimeStamp(); mTimeAddMax = trkItsTpc.getTimeMUS().getTimeStampError(); @@ -163,7 +164,7 @@ class trackInterface : public o2::track::TrackParCov mRefTPC = trkItsTpc.getRefTPC(); updateCov(std::pow(trkItsTpc.getTimeMUS().getTimeStampError() * vDrift, 2), o2::track::CovLabels::kSigZ2); // account for time uncertainty by increasing sigmaZ2 } - trackInterface(const o2::tpc::TrackTPC& trkTpc, float tbWidth, float vDrift, unsigned int iTrk) : o2::track::TrackParCov(trkTpc.getParamOut()) + trackInterface(const o2::tpc::TrackTPC& trkTpc, float tbWidth, float vDrift, unsigned int iTrk) : GPUTRDO2BaseTrack(trkTpc.getParamOut()) { mRefTPC = {iTrk, o2::dataformats::GlobalTrackID::TPC}; mTime = trkTpc.getTime0() * tbWidth; @@ -190,8 +191,8 @@ class trackInterface : public o2::track::TrackParCov setCov(cov[i], i); } } - trackInterface(const GPUTPCGMMergedTrack& trk) { set(trk.OuterParam().X, trk.OuterParam().alpha, trk.OuterParam().P, trk.OuterParam().C); } - trackInterface(const GPUTPCGMTrackParam::GPUTPCOuterParam& param) { set(param.X, param.alpha, param.P, param.C); } + trackInterface(const GPUTPCGMMergedTrack& trk) { set(trk.OuterParam().X, trk.OuterParam().alpha, trk.OuterParam().P, trk.OuterParam().C); } + trackInterface(const GPUTPCGMTrackParam::GPUTPCOuterParam& param) { set(param.X, param.alpha, param.P, param.C); } const float* getPar() const { return getParams(); } float getTime() const { return mTime; } @@ -204,7 +205,7 @@ class trackInterface : public o2::track::TrackParCov bool CheckNumericalQuality() const { return true; } - typedef o2::track::TrackParCov baseClass; + typedef GPUTRDO2BaseTrack baseClass; private: o2::dataformats::GlobalTrackID mRefTPC; // reference on TPC track entry in its original container @@ -227,7 +228,7 @@ class propagatorInterface bool propagateToX(float x, float maxSnp, float maxStep) { return mProp->PropagateToXBxByBz(*mParam, x, maxSnp, maxStep); } int getPropagatedYZ(float x, float& projY, float& projZ) { return static_cast(mParam->getYZAt(x, mProp->getNominalBz(), projY, projZ)); } - void setTrack(trackInterface* trk) { mParam = trk; } + void setTrack(trackInterface* trk) { mParam = trk; } void setFitInProjections(bool flag) {} float getAlpha() { return (mParam) ? mParam->getAlpha() : 99999.f; } @@ -253,7 +254,7 @@ class propagatorInterface } bool rotate(float alpha) { return (mParam) ? mParam->rotate(alpha) : false; } - trackInterface* mParam{nullptr}; + trackInterface* mParam{nullptr}; o2::base::Propagator* mProp{o2::base::Propagator::Instance()}; }; diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDO2BaseTrack.h b/GPU/GPUTracking/TRDTracking/GPUTRDO2BaseTrack.h new file mode 100644 index 0000000000000..4f9e13d454cde --- /dev/null +++ b/GPU/GPUTracking/TRDTracking/GPUTRDO2BaseTrack.h @@ -0,0 +1,38 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file GPUTRDO2BaseTrack.h +/// \author Ole Schmidt + +#ifndef GPUTRDO2BASETRACK_H +#define GPUTRDO2BASETRACK_H + +#include "ReconstructionDataFormats/Track.h" + +namespace GPUCA_NAMESPACE +{ +namespace gpu +{ + +class GPUTRDO2BaseTrack : public o2::track::TrackParCov +{ + public: + GPUTRDO2BaseTrack() = default; + GPUTRDO2BaseTrack(const o2::track::TrackParCov& t) : o2::track::TrackParCov(t) {} + + private: + // dummy class to avoid problems, see https://github.com/AliceO2Group/AliceO2/pull/5969#issuecomment-827475822 + ClassDefNV(GPUTRDO2BaseTrack, 1); +}; + +} // namespace gpu +} // namespace GPUCA_NAMESPACE + +#endif diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx index 203a8834afb15..a298ee201ff63 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx @@ -227,7 +227,7 @@ namespace gpu template class GPUTRDTrack_t>; #endif #ifdef GPUCA_O2_LIB // Instantiate O2 track version -template class GPUTRDTrack_t>; +template class GPUTRDTrack_t>; #endif #endif template class GPUTRDTrack_t>; // Always instatiate GM track version From b0b5fc054ad2715b7db5bc4c9647f124e3abac66 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Wed, 28 Apr 2021 13:36:55 +0200 Subject: [PATCH 304/770] DPL: fix for XCode 12.5 --- Framework/Core/test/test_SimpleRDataFrameProcessing.cxx | 2 -- 1 file changed, 2 deletions(-) diff --git a/Framework/Core/test/test_SimpleRDataFrameProcessing.cxx b/Framework/Core/test/test_SimpleRDataFrameProcessing.cxx index 6af1a87b4d114..508a002e23d40 100644 --- a/Framework/Core/test/test_SimpleRDataFrameProcessing.cxx +++ b/Framework/Core/test/test_SimpleRDataFrameProcessing.cxx @@ -25,8 +25,6 @@ using namespace o2::framework; using DataHeader = o2::header::DataHeader; -template class std::shared_ptr; - /// Example of how to use ROOT::RDataFrame using DPL. WorkflowSpec defineDataProcessing(ConfigContext const&) { From 8fd850e9b23c1badf1d194e01935c5d5927cb044 Mon Sep 17 00:00:00 2001 From: Bogdan Vulpescu Date: Thu, 22 Apr 2021 09:09:11 +0200 Subject: [PATCH 305/770] MFT: introduce a cluster reader; remove some temporary fixes --- Detectors/ITSMFT/MFT/tracking/src/IOUtils.cxx | 15 +++---- Detectors/ITSMFT/MFT/workflow/CMakeLists.txt | 5 +++ .../src/mft-cluster-reader-workflow.cxx | 43 +++++++++++++++++++ 3 files changed, 53 insertions(+), 10 deletions(-) create mode 100644 Detectors/ITSMFT/MFT/workflow/src/mft-cluster-reader-workflow.cxx diff --git a/Detectors/ITSMFT/MFT/tracking/src/IOUtils.cxx b/Detectors/ITSMFT/MFT/tracking/src/IOUtils.cxx index 577db2c8bdc84..e0cec66c14008 100644 --- a/Detectors/ITSMFT/MFT/tracking/src/IOUtils.cxx +++ b/Detectors/ITSMFT/MFT/tracking/src/IOUtils.cxx @@ -34,8 +34,7 @@ namespace o2 namespace mft { -int ioutils::loadROFrameData(const o2::itsmft::ROFRecord& rof, ROframe& event, gsl::span clusters, gsl::span::iterator& pattIt, const itsmft::TopologyDictionary& dict, - const dataformats::MCTruthContainer* mcLabels, const o2::mft::Tracker* tracker) +int ioutils::loadROFrameData(const o2::itsmft::ROFRecord& rof, ROframe& event, gsl::span clusters, gsl::span::iterator& pattIt, const itsmft::TopologyDictionary& dict, const dataformats::MCTruthContainer* mcLabels, const o2::mft::Tracker* tracker) { event.clear(); GeometryTGeo* geom = GeometryTGeo::Instance(); @@ -44,16 +43,14 @@ int ioutils::loadROFrameData(const o2::itsmft::ROFRecord& rof, ROframe& event, g auto first = rof.getFirstEntry(); auto clusters_in_frame = rof.getROFData(clusters); for (auto& c : clusters_in_frame) { - int layer = geom->getLayer(c.getSensorID()); + auto sensorID = c.getSensorID(); + int layer = geom->getLayer(sensorID); auto pattID = c.getPatternID(); o2::math_utils::Point3D locXYZ; float sigmaX2 = ioutils::DefClusError2Row, sigmaY2 = ioutils::DefClusError2Col; //Dummy COG errors (about half pixel size) if (pattID != itsmft::CompCluster::InvalidPatternID) { - //sigmaX2 = dict.getErr2X(pattID); // ALPIDE local X coordinate => MFT global X coordinate (ALPIDE rows) - //sigmaY2 = dict.getErr2Z(pattID); // ALPIDE local Z coordinate => MFT global Y coordinate (ALPIDE columns) - // temporary, until ITS bug fix - sigmaX2 = dict.getErrX(pattID) * dict.getErrX(pattID); - sigmaY2 = dict.getErrZ(pattID) * dict.getErrZ(pattID); + sigmaX2 = dict.getErr2X(pattID); // ALPIDE local X coordinate => MFT global X coordinate (ALPIDE rows) + sigmaY2 = dict.getErr2Z(pattID); // ALPIDE local Z coordinate => MFT global Y coordinate (ALPIDE columns) if (!dict.isGroup(pattID)) { locXYZ = dict.getClusterCoordinates(c); } else { @@ -64,7 +61,6 @@ int ioutils::loadROFrameData(const o2::itsmft::ROFRecord& rof, ROframe& event, g o2::itsmft::ClusterPattern patt(pattIt); locXYZ = dict.getClusterCoordinates(c, patt); } - auto sensorID = c.getSensorID(); // Transformation to the local --> global auto gloXYZ = geom->getMatrixL2G(sensorID) * locXYZ; @@ -75,7 +71,6 @@ int ioutils::loadROFrameData(const o2::itsmft::ROFRecord& rof, ROframe& event, g int rBinIndex = tracker->getRBinIndex(rCoord); int phiBinIndex = tracker->getPhiBinIndex(phiCoord); int binIndex = tracker->getBinIndex(rBinIndex, phiBinIndex); - // TODO: Check consistency of sigmaX2 and sigmaY2 event.addClusterToLayer(layer, gloXYZ.x(), gloXYZ.y(), gloXYZ.z(), phiCoord, rCoord, event.getClustersInLayer(layer).size(), binIndex, sigmaX2, sigmaY2, sensorID); if (mcLabels) { event.addClusterLabelToLayer(layer, *(mcLabels->getLabels(first + clusterId).begin())); diff --git a/Detectors/ITSMFT/MFT/workflow/CMakeLists.txt b/Detectors/ITSMFT/MFT/workflow/CMakeLists.txt index 45862540adc24..e1d3e71d87f61 100644 --- a/Detectors/ITSMFT/MFT/workflow/CMakeLists.txt +++ b/Detectors/ITSMFT/MFT/workflow/CMakeLists.txt @@ -28,3 +28,8 @@ o2_add_executable(reco-workflow SOURCES src/mft-reco-workflow.cxx COMPONENT_NAME mft PUBLIC_LINK_LIBRARIES O2::MFTWorkflow) + +o2_add_executable(cluster-reader-workflow + SOURCES src/mft-cluster-reader-workflow.cxx + COMPONENT_NAME mft + PUBLIC_LINK_LIBRARIES O2::MFTWorkflow) diff --git a/Detectors/ITSMFT/MFT/workflow/src/mft-cluster-reader-workflow.cxx b/Detectors/ITSMFT/MFT/workflow/src/mft-cluster-reader-workflow.cxx new file mode 100644 index 0000000000000..5b038f196608e --- /dev/null +++ b/Detectors/ITSMFT/MFT/workflow/src/mft-cluster-reader-workflow.cxx @@ -0,0 +1,43 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "Framework/ConfigParamSpec.h" + +using namespace o2::framework; + +void customize(std::vector& workflowOptions) +{ + workflowOptions.push_back( + ConfigParamSpec{ + "with-mc", + o2::framework::VariantType::Bool, + false, + {"propagate MC labels"}}); + workflowOptions.push_back( + ConfigParamSpec{ + "without-patterns", + o2::framework::VariantType::Bool, + false, + {"do not propagate pixel patterns"}}); +} + +#include "Framework/runDataProcessing.h" +#include "ITSMFTWorkflow/ClusterReaderSpec.h" + +WorkflowSpec defineDataProcessing(ConfigContext const& cc) +{ + WorkflowSpec specs; + auto withMC = cc.options().get("with-mc"); + auto withPatterns = !cc.options().get("without-patterns"); + + specs.emplace_back(o2::itsmft::getMFTClusterReaderSpec(withMC, withPatterns)); + + return specs; +} From c19f80f9d917ec8e04dec981001b8149afc2186d Mon Sep 17 00:00:00 2001 From: Jorge Lopez Date: Thu, 29 Apr 2021 11:40:25 -0400 Subject: [PATCH 306/770] TRD: Move Digit class to DataFormatsTRD (#6014) * Move Digit to DataFormats * Use correct header in macro * TRD: back compatibility for QC --- DataFormats/Detectors/TRD/CMakeLists.txt | 11 +++ .../TRD/include/DataFormatsTRD/Digit.h | 97 +++++++++++++++++++ .../include/DataFormatsTRD/HelperMethods.h | 74 ++++++++++++++ .../Detectors/TRD/src/DataFormatsTRDLinkDef.h | 2 + .../Detectors/TRD}/src/Digit.cxx | 2 +- .../Detectors/TRD}/test/testDigit.cxx | 2 +- Detectors/TRD/base/CMakeLists.txt | 10 +- Detectors/TRD/base/include/TRDBase/Digit.h | 87 +---------------- Detectors/TRD/base/src/FeeParam.cxx | 33 ++----- Detectors/TRD/base/src/TRDBaseLinkDef.h | 2 - Detectors/TRD/macros/CheckDigits.C | 2 +- .../include/TRDReconstruction/CTFHelper.h | 2 +- .../include/TRDSimulation/Digitizer.h | 2 +- .../include/TRDSimulation/Trap2CRU.h | 2 +- .../include/TRDSimulation/TrapSimulator.h | 3 +- .../TRD/simulation/src/TrapSimulator.cxx | 2 +- .../TRDWorkflow/TRDTrackletWriterSpec.h | 2 +- .../TRD/workflow/src/TRDDigitReaderSpec.cxx | 2 +- .../TRD/workflow/src/TRDDigitWriterSpec.cxx | 2 +- .../TRD/workflow/src/TRDDigitizerSpec.cxx | 2 +- .../workflow/src/TRDTrackletWriterSpec.cxx | 2 +- .../TRD/workflow/src/TRDTrapSimulatorSpec.cxx | 2 +- 22 files changed, 210 insertions(+), 135 deletions(-) create mode 100644 DataFormats/Detectors/TRD/include/DataFormatsTRD/Digit.h create mode 100644 DataFormats/Detectors/TRD/include/DataFormatsTRD/HelperMethods.h rename {Detectors/TRD/base => DataFormats/Detectors/TRD}/src/Digit.cxx (98%) rename {Detectors/TRD/base => DataFormats/Detectors/TRD}/test/testDigit.cxx (99%) diff --git a/DataFormats/Detectors/TRD/CMakeLists.txt b/DataFormats/Detectors/TRD/CMakeLists.txt index 29695d0843c2b..e239f3c4e4946 100644 --- a/DataFormats/Detectors/TRD/CMakeLists.txt +++ b/DataFormats/Detectors/TRD/CMakeLists.txt @@ -14,6 +14,7 @@ o2_add_library(DataFormatsTRD src/Tracklet64.cxx src/RawData.cxx src/CTF.cxx + src/Digit.cxx PUBLIC_LINK_LIBRARIES O2::CommonDataFormat O2::SimulationDataFormat) o2_target_root_dictionary(DataFormatsTRD @@ -23,6 +24,16 @@ o2_target_root_dictionary(DataFormatsTRD include/DataFormatsTRD/RawData.h include/DataFormatsTRD/Constants.h include/DataFormatsTRD/CalibratedTracklet.h + include/DataFormatsTRD/HelperMethods.h include/DataFormatsTRD/Hit.h + include/DataFormatsTRD/Digit.h include/DataFormatsTRD/CTF.h include/DataFormatsTRD/SignalArray.h) + +o2_add_test(Digit + COMPONENT_NAME trd + PUBLIC_LINK_LIBRARIES O2::DataFormatsTRD + SOURCES test/testDigit.cxx + ENVIRONMENT O2_ROOT=${CMAKE_BINARY_DIR}/stage + LABELS trd +) \ No newline at end of file diff --git a/DataFormats/Detectors/TRD/include/DataFormatsTRD/Digit.h b/DataFormats/Detectors/TRD/include/DataFormatsTRD/Digit.h new file mode 100644 index 0000000000000..3c80817f59fb6 --- /dev/null +++ b/DataFormats/Detectors/TRD/include/DataFormatsTRD/Digit.h @@ -0,0 +1,97 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef ALICEO2_TRD_DIGIT_H_ +#define ALICEO2_TRD_DIGIT_H_ + +#include +#include +#include +#include +#include +#include "Rtypes.h" // for ClassDef + +#include "DataFormatsTRD/HelperMethods.h" +#include "DataFormatsTRD/Constants.h" +#include + +namespace o2 +{ +namespace trd +{ + +using ADC_t = std::uint16_t; +using ArrayADC = std::array; + +// Digit class for TRD +// Notes: +// Shared pads: +// the lower mcm and rob is chosen for a given shared pad. +// this negates the need for need alternate indexing strategies. +// if you are trying to go from mcm/rob/adc to pad/row and back to mcm/rob/adc , +// you may not end up in the same place, you need to remember to manually check for shared pads. + +class Digit +{ + public: + Digit() = default; + ~Digit() = default; + Digit(const int det, const int row, const int pad, const ArrayADC adc); + Digit(const int det, const int row, const int pad); // add adc data in a seperate step + Digit(const int det, const int rob, const int mcm, const int channel, const ArrayADC adc); + Digit(const int det, const int rob, const int mcm, const int channel); // add adc data in a seperate step + + // Copy + Digit(const Digit&) = default; + // Assignment + Digit& operator=(const Digit&) = default; + // Modifiers + void setROB(int rob) { mROB = rob; } + void setROB(int row, int pad) { mROB = HelperMethods::getROBfromPad(row, pad); } + void setMCM(int mcm) { mMCM = mcm; } + void setMCM(int row, int pad) { mMCM = HelperMethods::getMCMfromPad(row, pad); } + void setChannel(int channel) { mChannel = channel; } + void setDetector(int det) { mDetector = det; } + void setADC(ArrayADC const& adc) { mADC = adc; } + void setADC(const gsl::span& adc) { std::copy(adc.begin(), adc.end(), mADC.begin()); } + // Get methods + int getDetector() const { return mDetector; } + int getHCId() const { return mDetector * 2 + (mROB % 2); } + int getRow() const { return HelperMethods::getPadRowFromMCM(mROB, mMCM); } + int getPad() const { return HelperMethods::getPadColFromADC(mROB, mMCM, mChannel); } + int getROB() const { return mROB; } + int getMCM() const { return mMCM; } + int getChannel() const { return mChannel; } + bool isSharedDigit() const; + + ArrayADC const& getADC() const { return mADC; } + ADC_t getADCsum() const { return std::accumulate(mADC.begin(), mADC.end(), (ADC_t)0); } + + bool operator==(const Digit& o) const + { + return mDetector == o.mDetector && mROB == o.mROB && mMCM == o.mMCM && mChannel == o.mChannel && mADC == o.mADC; + } + + private: + std::uint16_t mDetector{0}; // detector, the chamber [0-539] + std::uint8_t mROB{0}; // read out board within chamber [0-7] [0-5] depending on C0 or C1 + std::uint8_t mMCM{0}; // MCM chip this digit is attached [0-15] + std::uint8_t mChannel{0}; // channel of this chip the digit is attached to, see TDP chapter ?? TODO fill in later the figure number of ROB to MCM mapping picture + + ArrayADC mADC{}; // ADC vector (30 time-bins) + ClassDefNV(Digit, 3); +}; + +std::ostream& operator<<(std::ostream& stream, const Digit& d); + +} // namespace trd +} // namespace o2 + +#endif diff --git a/DataFormats/Detectors/TRD/include/DataFormatsTRD/HelperMethods.h b/DataFormats/Detectors/TRD/include/DataFormatsTRD/HelperMethods.h new file mode 100644 index 0000000000000..259286d59a29d --- /dev/null +++ b/DataFormats/Detectors/TRD/include/DataFormatsTRD/HelperMethods.h @@ -0,0 +1,74 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef ALICEO2_TRD_HELPERMETHODS_HH +#define ALICEO2_TRD_HELPERMETHODS_HH + +#include "DataFormatsTRD/Constants.h" + +namespace o2 +{ +namespace trd +{ + +struct HelperMethods { + static int getROBfromPad(int irow, int icol) + { + return (irow / constants::NMCMROBINROW) * 2 + getColSide(icol); + } + + static int getMCMfromPad(int irow, int icol) + { + if (irow < 0 || icol < 0 || irow > constants::NROWC1 || icol > constants::NCOLUMN) { + return -1; + } + return (icol % (constants::NCOLUMN / 2)) / constants::NCOLMCM + constants::NMCMROBINCOL * (irow % constants::NMCMROBINROW); + } + + static int getColSide(int icol) + { + if (icol < 0 || icol >= constants::NCOLUMN) { + return -1; + } + + return icol / (constants::NCOLUMN / 2); + } + + static int getPadRowFromMCM(int irob, int imcm) + { + return constants::NMCMROBINROW * (irob / 2) + imcm / constants::NMCMROBINCOL; + } + + static int getPadColFromADC(int irob, int imcm, int iadc) + { + if (iadc < 0 || iadc > constants::NADCMCM) { + return -100; + } + int mcmcol = imcm % constants::NMCMROBINCOL + getROBSide(irob) * constants::NMCMROBINCOL; // MCM column number on ROC [0..7] + int padcol = mcmcol * constants::NCOLMCM + constants::NCOLMCM + 1 - iadc; + if (padcol < 0 || padcol >= constants::NCOLUMN) { + return -1; // this is commented because of reason above OK + } + return padcol; + } + + static int getROBSide(int irob) + { + if (irob < 0 || irob >= constants::NROBC1) { + return -1; + } + return irob % 2; + } +}; + +} // namespace trd +} // namespace o2 + +#endif diff --git a/DataFormats/Detectors/TRD/src/DataFormatsTRDLinkDef.h b/DataFormats/Detectors/TRD/src/DataFormatsTRDLinkDef.h index 169552d887c90..2a56e00fda4c3 100644 --- a/DataFormats/Detectors/TRD/src/DataFormatsTRDLinkDef.h +++ b/DataFormats/Detectors/TRD/src/DataFormatsTRDLinkDef.h @@ -23,11 +23,13 @@ #pragma link C++ class o2::trd::Tracklet64 + ; #pragma link C++ class o2::trd::CalibratedTracklet + ; #pragma link C++ class o2::trd::Hit + ; +#pragma link C++ class o2::trd::Digit + ; #pragma link C++ class std::vector < o2::trd::Tracklet64> + ; #pragma link C++ class std::vector < o2::trd::CalibratedTracklet> + ; #pragma link C++ class std::vector < o2::trd::TriggerRecord > +; #pragma link C++ class std::vector < o2::trd::LinkRecord > +; #pragma link C++ class std::vector < o2::trd::Hit > +; +#pragma link C++ class std::vector < o2::trd::Digit> + ; #pragma link C++ struct o2::trd::CTFHeader + ; #pragma link C++ struct o2::trd::CTF + ; diff --git a/Detectors/TRD/base/src/Digit.cxx b/DataFormats/Detectors/TRD/src/Digit.cxx similarity index 98% rename from Detectors/TRD/base/src/Digit.cxx rename to DataFormats/Detectors/TRD/src/Digit.cxx index 91822cc4dd74b..d1585204f19b1 100644 --- a/Detectors/TRD/base/src/Digit.cxx +++ b/DataFormats/Detectors/TRD/src/Digit.cxx @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#include "TRDBase/Digit.h" +#include "DataFormatsTRD/Digit.h" #include namespace o2::trd diff --git a/Detectors/TRD/base/test/testDigit.cxx b/DataFormats/Detectors/TRD/test/testDigit.cxx similarity index 99% rename from Detectors/TRD/base/test/testDigit.cxx rename to DataFormats/Detectors/TRD/test/testDigit.cxx index 7fb088a1b43ac..e54a796251737 100644 --- a/Detectors/TRD/base/test/testDigit.cxx +++ b/DataFormats/Detectors/TRD/test/testDigit.cxx @@ -19,7 +19,7 @@ #include #include -#include "TRDBase/Digit.h" +#include "DataFormatsTRD/Digit.h" #include "DataFormatsTRD/Constants.h" namespace o2 diff --git a/Detectors/TRD/base/CMakeLists.txt b/Detectors/TRD/base/CMakeLists.txt index 7477a4f52f4a4..82fc328cf7214 100644 --- a/Detectors/TRD/base/CMakeLists.txt +++ b/Detectors/TRD/base/CMakeLists.txt @@ -13,7 +13,6 @@ o2_add_library(TRDBase src/Geometry.cxx src/GeometryFlat.cxx src/CommonParam.cxx - src/Digit.cxx src/DiffAndTimeStructEstimator.cxx src/SimParam.cxx src/PadResponse.cxx @@ -47,7 +46,6 @@ o2_target_root_dictionary(TRDBase include/TRDBase/GeometryFlat.h include/TRDBase/SimParam.h include/TRDBase/CommonParam.h - include/TRDBase/Digit.h include/TRDBase/PadResponse.h include/TRDBase/MCLabel.h include/TRDBase/CalDet.h @@ -64,6 +62,7 @@ o2_target_root_dictionary(TRDBase include/TRDBase/Calibrations.h include/TRDBase/ChamberNoise.h include/TRDBase/CalOnlineGainTables.h + include/TRDBase/Digit.h include/TRDBase/Tracklet.h include/TRDBase/TrackletTransformer.h) @@ -88,10 +87,3 @@ o2_add_test(RawData ENVIRONMENT O2_ROOT=${CMAKE_BINARY_DIR}/stage LABELS trd ) -o2_add_test(Digit - COMPONENT_NAME trd - PUBLIC_LINK_LIBRARIES O2::TRDBase O2::DataFormatsTRD - SOURCES test/testDigit.cxx - ENVIRONMENT O2_ROOT=${CMAKE_BINARY_DIR}/stage - LABELS trd - ) diff --git a/Detectors/TRD/base/include/TRDBase/Digit.h b/Detectors/TRD/base/include/TRDBase/Digit.h index 1d51d6bc9d690..c9cf990c22adb 100644 --- a/Detectors/TRD/base/include/TRDBase/Digit.h +++ b/Detectors/TRD/base/include/TRDBase/Digit.h @@ -8,90 +8,9 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef ALICEO2_TRD_DIGIT_H_ -#define ALICEO2_TRD_DIGIT_H_ +#ifndef ALICEO2_TRD_DIGIT_BACKCOMPAT_H_ +#define ALICEO2_TRD_DIGIT_BACKCOMPAT_H_ -#include -#include -#include -#include -#include -#include "Rtypes.h" // for ClassDef - -#include "TRDBase/FeeParam.h" -#include "DataFormatsTRD/Constants.h" -#include - -namespace o2 -{ -namespace trd -{ - -using ADC_t = std::uint16_t; -using ArrayADC = std::array; - -// Digit class for TRD -// Notes: -// Shared pads: -// the lower mcm and rob is chosen for a given shared pad. -// this negates the need for need alternate indexing strategies. -// if you are trying to go from mcm/rob/adc to pad/row and back to mcm/rob/adc , -// you may not end up in the same place, you need to remember to manually check for shared pads. - -class Digit -{ - public: - Digit() = default; - ~Digit() = default; - Digit(const int det, const int row, const int pad, const ArrayADC adc); - Digit(const int det, const int row, const int pad); // add adc data in a seperate step - Digit(const int det, const int rob, const int mcm, const int channel, const ArrayADC adc); - Digit(const int det, const int rob, const int mcm, const int channel); // add adc data in a seperate step - - // Copy - Digit(const Digit&) = default; - // Assignment - Digit& operator=(const Digit&) = default; - // Modifiers - void setROB(int rob) { mROB = rob; } - void setROB(int row, int pad) { mROB = FeeParam::getROBfromPad(row, pad); } - void setMCM(int mcm) { mMCM = mcm; } - void setMCM(int row, int pad) { mMCM = FeeParam::getMCMfromPad(row, pad); } - void setChannel(int channel) { mChannel = channel; } - void setDetector(int det) { mDetector = det; } - void setADC(ArrayADC const& adc) { mADC = adc; } - void setADC(const gsl::span& adc) { std::copy(adc.begin(), adc.end(), mADC.begin()); } - // Get methods - int getDetector() const { return mDetector; } - int getHCId() const { return mDetector * 2 + (mROB % 2); } - int getRow() const { return FeeParam::getPadRowFromMCM(mROB, mMCM); } - int getPad() const { return FeeParam::getPadColFromADC(mROB, mMCM, mChannel); } - int getROB() const { return mROB; } - int getMCM() const { return mMCM; } - int getChannel() const { return mChannel; } - bool isSharedDigit() const; - - ArrayADC const& getADC() const { return mADC; } - ADC_t getADCsum() const { return std::accumulate(mADC.begin(), mADC.end(), (ADC_t)0); } - - bool operator==(const Digit& o) const - { - return mDetector == o.mDetector && mROB == o.mROB && mMCM == o.mMCM && mChannel == o.mChannel && mADC == o.mADC; - } - - private: - std::uint16_t mDetector{0}; // detector, the chamber [0-539] - std::uint8_t mROB{0}; // read out board within chamber [0-7] [0-5] depending on C0 or C1 - std::uint8_t mMCM{0}; // MCM chip this digit is attached [0-15] - std::uint8_t mChannel{0}; // channel of this chip the digit is attached to, see TDP chapter ?? TODO fill in later the figure number of ROB to MCM mapping picture - - ArrayADC mADC{}; // ADC vector (30 time-bins) - ClassDefNV(Digit, 3); -}; - -std::ostream& operator<<(std::ostream& stream, const Digit& d); - -} // namespace trd -} // namespace o2 +#include "DataFormatsTRD/Digit.h" #endif diff --git a/Detectors/TRD/base/src/FeeParam.cxx b/Detectors/TRD/base/src/FeeParam.cxx index 9369ee8931168..104e93acbda15 100644 --- a/Detectors/TRD/base/src/FeeParam.cxx +++ b/Detectors/TRD/base/src/FeeParam.cxx @@ -35,6 +35,7 @@ #include #include +#include "DataFormatsTRD/HelperMethods.h" #include "DetectorsBase/GeometryManager.h" #include "TRDBase/Geometry.h" #include "TRDBase/PadPlane.h" @@ -99,7 +100,7 @@ int FeeParam::getPadRowFromMCM(int irob, int imcm) // Return on which pad row this mcm sits // - return NMCMROBINROW * (irob / 2) + imcm / NMCMROBINCOL; + return HelperMethods::getPadRowFromMCM(irob, imcm); } //_____________________________________________________________________________ @@ -118,15 +119,7 @@ int FeeParam::getPadColFromADC(int irob, int imcm, int iadc) // http://wiki.kip.uni-heidelberg.de/ti/TRD/index.php/Image:ROB_MCM_numbering.pdf // - if (iadc < 0 || iadc > NADCMCM) { - return -100; - } - int mcmcol = imcm % NMCMROBINCOL + getROBSide(irob) * NMCMROBINCOL; // MCM column number on ROC [0..7] - int padcol = mcmcol * NCOLMCM + NCOLMCM + 1 - iadc; - if (padcol < 0 || padcol >= NCOLUMN) { - return -1; // this is commented because of reason above OK - } - return padcol; + return HelperMethods::getPadColFromADC(irob, imcm, iadc); } //_____________________________________________________________________________ @@ -155,10 +148,7 @@ int FeeParam::getMCMfromPad(int irow, int icol) // Return -1 for error. // - if (irow < 0 || icol < 0 || irow > NROWC1 || icol > NCOLUMN) { - return -1; - } - return (icol % (NCOLUMN / 2)) / NCOLMCM + NMCMROBINCOL * (irow % NMCMROBINROW); + return HelperMethods::getMCMfromPad(irow, icol); } //_____________________________________________________________________________ @@ -198,7 +188,7 @@ int FeeParam::getROBfromPad(int irow, int icol) // // Return on which rob this pad is // - return (irow / NMCMROBINROW) * 2 + getColSide(icol); + return HelperMethods::getROBfromPad(irow, icol); } //_____________________________________________________________________________ @@ -221,12 +211,7 @@ int FeeParam::getROBSide(int irob) // // Return on which side this rob sits (A side = 0, B side = 1) // - - if (irob < 0 || irob >= NROBC1) { - return -1; - } - - return irob % 2; + return HelperMethods::getROBSide(irob); } //_____________________________________________________________________________ @@ -236,11 +221,7 @@ int FeeParam::getColSide(int icol) // Return on which side this column sits (A side = 0, B side = 1) // - if (icol < 0 || icol >= NCOLUMN) { - return -1; - } - - return icol / (NCOLUMN / 2); + return HelperMethods::getColSide(icol); } unsigned int FeeParam::aliToExtAli(int rob, int aliid) diff --git a/Detectors/TRD/base/src/TRDBaseLinkDef.h b/Detectors/TRD/base/src/TRDBaseLinkDef.h index 956287595f00e..ba7c9fc9093a7 100644 --- a/Detectors/TRD/base/src/TRDBaseLinkDef.h +++ b/Detectors/TRD/base/src/TRDBaseLinkDef.h @@ -18,8 +18,6 @@ #pragma link C++ class o2::trd::Geometry + ; #pragma link C++ class o2::trd::GeometryBase + ; #pragma link C++ class o2::trd::CommonParam + ; -#pragma link C++ class o2::trd::Digit + ; -#pragma link C++ class std::vector < o2::trd::Digit > +; #pragma link C++ class o2::trd::SimParam + ; #pragma link C++ class o2::trd::FeeParam + ; #pragma link C++ class o2::trd::CalDet + ; diff --git a/Detectors/TRD/macros/CheckDigits.C b/Detectors/TRD/macros/CheckDigits.C index 95a5bc9aaf4bb..49fa6d3d07466 100644 --- a/Detectors/TRD/macros/CheckDigits.C +++ b/Detectors/TRD/macros/CheckDigits.C @@ -21,9 +21,9 @@ #include #include "FairLogger.h" -#include "TRDBase/Digit.h" #include "TRDBase/SimParam.h" #include "TRDBase/CommonParam.h" +#include "DataFormatsTRD/Digit.h" #include "DataFormatsTRD/Constants.h" #endif diff --git a/Detectors/TRD/reconstruction/include/TRDReconstruction/CTFHelper.h b/Detectors/TRD/reconstruction/include/TRDReconstruction/CTFHelper.h index e106e9b3a0044..2d2f67cecf78c 100644 --- a/Detectors/TRD/reconstruction/include/TRDReconstruction/CTFHelper.h +++ b/Detectors/TRD/reconstruction/include/TRDReconstruction/CTFHelper.h @@ -18,7 +18,7 @@ #include "DataFormatsTRD/CTF.h" #include "DataFormatsTRD/TriggerRecord.h" #include "DataFormatsTRD/Tracklet64.h" -#include "TRDBase/Digit.h" // TODO Consider moving to DataFormats +#include "DataFormatsTRD/Digit.h" #include #include diff --git a/Detectors/TRD/simulation/include/TRDSimulation/Digitizer.h b/Detectors/TRD/simulation/include/TRDSimulation/Digitizer.h index 598740c1d2657..0864dbd97c998 100644 --- a/Detectors/TRD/simulation/include/TRDSimulation/Digitizer.h +++ b/Detectors/TRD/simulation/include/TRDSimulation/Digitizer.h @@ -14,12 +14,12 @@ #include "TRDSimulation/Detector.h" #include "TRDBase/Calibrations.h" -#include "TRDBase/Digit.h" #include "TRDBase/MCLabel.h" #include "TRDBase/CommonParam.h" #include "TRDBase/DiffAndTimeStructEstimator.h" #include "TRDSimulation/PileupTool.h" +#include "DataFormatsTRD/Digit.h" #include "DataFormatsTRD/SignalArray.h" #include "DataFormatsTRD/Constants.h" diff --git a/Detectors/TRD/simulation/include/TRDSimulation/Trap2CRU.h b/Detectors/TRD/simulation/include/TRDSimulation/Trap2CRU.h index 3ae35af655143..96024327e2ede 100644 --- a/Detectors/TRD/simulation/include/TRDSimulation/Trap2CRU.h +++ b/Detectors/TRD/simulation/include/TRDSimulation/Trap2CRU.h @@ -23,7 +23,7 @@ #include "DataFormatsTRD/LinkRecord.h" #include "DataFormatsTRD/RawData.h" #include "DataFormatsTRD/Tracklet64.h" -#include "TRDBase/Digit.h" +#include "DataFormatsTRD/Digit.h" //#include "DetectorsRaw/HBFUtils.h" #include "DetectorsRaw/RawFileWriter.h" diff --git a/Detectors/TRD/simulation/include/TRDSimulation/TrapSimulator.h b/Detectors/TRD/simulation/include/TRDSimulation/TrapSimulator.h index 50f113270e620..4a2bed412e266 100644 --- a/Detectors/TRD/simulation/include/TRDSimulation/TrapSimulator.h +++ b/Detectors/TRD/simulation/include/TRDSimulation/TrapSimulator.h @@ -24,9 +24,10 @@ #include #include "TRDBase/FeeParam.h" -#include "TRDBase/Digit.h" #include "TRDSimulation/Digitizer.h" #include "TRDSimulation/TrapConfig.h" + +#include "DataFormatsTRD/Digit.h" #include "DataFormatsTRD/Tracklet64.h" #include "DataFormatsTRD/RawData.h" #include "DataFormatsTRD/Constants.h" diff --git a/Detectors/TRD/simulation/src/TrapSimulator.cxx b/Detectors/TRD/simulation/src/TrapSimulator.cxx index cf1f2ae5b5ec2..c7c2cddb9669f 100644 --- a/Detectors/TRD/simulation/src/TrapSimulator.cxx +++ b/Detectors/TRD/simulation/src/TrapSimulator.cxx @@ -28,7 +28,7 @@ #include "fairlogger/Logger.h" //to pull in the digitzer incomnig data. -#include "TRDBase/Digit.h" +#include "DataFormatsTRD/Digit.h" #include "TRDSimulation/Digitizer.h" #include #include diff --git a/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackletWriterSpec.h b/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackletWriterSpec.h index 292f0a5c38a85..6039ade93a13d 100644 --- a/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackletWriterSpec.h +++ b/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackletWriterSpec.h @@ -11,7 +11,7 @@ #ifndef O2_TRDTRAPSIMULATORTRACKLETWRITER_H #define O2_TRDTRAPSIMULATORTRACKLETWRITER_H -#include "TRDBase/Digit.h" +#include "DataFormatsTRD/Digit.h" #include #include "TRDBase/MCLabel.h" #include "TRDBase/Tracklet.h" diff --git a/Detectors/TRD/workflow/src/TRDDigitReaderSpec.cxx b/Detectors/TRD/workflow/src/TRDDigitReaderSpec.cxx index 1fc93483de10e..e9711a140ef0a 100644 --- a/Detectors/TRD/workflow/src/TRDDigitReaderSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDDigitReaderSpec.cxx @@ -28,7 +28,7 @@ #include #include "Framework/Task.h" #include "DataFormatsParameters/GRPObject.h" -#include "TRDBase/Digit.h" // for the Digit type +#include "DataFormatsTRD/Digit.h" // for the Digit type #include "TRDSimulation/TrapSimulator.h" #include "TRDSimulation/Digitizer.h" #include "TRDSimulation/Detector.h" // for the Hit type diff --git a/Detectors/TRD/workflow/src/TRDDigitWriterSpec.cxx b/Detectors/TRD/workflow/src/TRDDigitWriterSpec.cxx index e0b607dc502d6..647da43894553 100644 --- a/Detectors/TRD/workflow/src/TRDDigitWriterSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDDigitWriterSpec.cxx @@ -14,7 +14,7 @@ #include "Framework/DataProcessorSpec.h" #include "DPLUtils/MakeRootTreeWriterSpec.h" #include "Framework/InputSpec.h" -#include "TRDBase/Digit.h" +#include "DataFormatsTRD/Digit.h" #include "DataFormatsTRD/TriggerRecord.h" #include #include diff --git a/Detectors/TRD/workflow/src/TRDDigitizerSpec.cxx b/Detectors/TRD/workflow/src/TRDDigitizerSpec.cxx index c21dbfef1ce87..e33dc4708f4e8 100644 --- a/Detectors/TRD/workflow/src/TRDDigitizerSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDDigitizerSpec.cxx @@ -26,7 +26,7 @@ #include "DataFormatsTRD/TriggerRecord.h" #include "DataFormatsTRD/Constants.h" #include "DataFormatsTRD/Hit.h" -#include "TRDBase/Digit.h" // for the Digit type +#include "DataFormatsTRD/Digit.h" // for the Digit type #include "TRDBase/Calibrations.h" #include "TRDSimulation/Digitizer.h" #include "TRDSimulation/Detector.h" // for the Hit type diff --git a/Detectors/TRD/workflow/src/TRDTrackletWriterSpec.cxx b/Detectors/TRD/workflow/src/TRDTrackletWriterSpec.cxx index e95fd7369ef36..887715886df93 100644 --- a/Detectors/TRD/workflow/src/TRDTrackletWriterSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDTrackletWriterSpec.cxx @@ -15,7 +15,7 @@ #include "DPLUtils/MakeRootTreeWriterSpec.h" #include "Framework/InputSpec.h" #include "TRDWorkflow/TRDTrackletWriterSpec.h" -#include "TRDBase/Digit.h" +#include "DataFormatsTRD/Digit.h" #include #include "TRDBase/MCLabel.h" #include "DataFormatsTRD/TriggerRecord.h" diff --git a/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx b/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx index 8e9ae3d3b37c4..66f791f2e48d7 100644 --- a/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDTrapSimulatorSpec.cxx @@ -27,9 +27,9 @@ #include "fairlogger/Logger.h" #include "CCDB/BasicCCDBManager.h" -#include "TRDBase/Digit.h" #include "TRDBase/Calibrations.h" #include "TRDSimulation/TRDSimParams.h" +#include "DataFormatsTRD/Digit.h" #include "DataFormatsTRD/TriggerRecord.h" using namespace o2::framework; From 3162c20b22f262ac114533987301b5b231515794 Mon Sep 17 00:00:00 2001 From: Kavaldrin <37471854+Kavaldrin@users.noreply.github.com> Date: Thu, 29 Apr 2021 17:41:59 +0200 Subject: [PATCH 307/770] [FIT] calibration workflow refactoring (#5985) * FIT calibration refactoring pt1 * FIT calibration refactoring pt2 * FIT calibration refactoring pt3 * FIT calibration refactoring pt4 * FIT calibration workflow - bugfix --- Detectors/FIT/FT0/calibration/CMakeLists.txt | 25 ++- .../FT0Calibration/FT0CalibrationInfoObject.h | 2 +- ...ct.h => FT0ChannelTimeCalibrationObject.h} | 26 +-- ...er.h => FT0ChannelTimeTimeSlotContainer.h} | 29 ++- .../FT0DummyCalibrationObject.h | 66 +++++++ .../macros/makeDummyFT0CalibObjectInCCDB.C | 27 +-- .../calibration/src/FT0CalibrationLinkDef.h | 10 +- .../calibration/src/FT0CalibrationObject.cxx | 34 ---- .../src/FT0ChannelDataTimeSlotContainer.cxx | 88 --------- .../src/FT0ChannelTimeCalibrationObject.cxx | 25 +++ .../src/FT0ChannelTimeTimeSlotContainer.cxx | 84 +++++++++ .../testWorkflow/FT0Calibration-Workflow.cxx | 27 +++ ...w.cxx => FT0CalibrationDummy-Workflow.cxx} | 38 ++-- .../FT0ChannelTimeCalibration-Workflow.cxx | 26 +++ .../FT0ChannelTimeCalibrationSpec.h | 45 +++++ .../testWorkflow/FT0TFProcessor-Workflow.cxx | 1 - .../FIT/common/calibration/CMakeLists.txt | 6 +- Detectors/FIT/common/calibration/README.md | 36 ++++ .../FITCalibrationAlgorithmGetter.h | 28 --- .../FITCalibration/FITCalibrationApi.h | 170 ++++++++++++++++++ .../FITCalibration/FITCalibrationDevice.h | 60 +++---- .../FITCalibrationObjectProducer.h | 63 +++++++ .../include/FITCalibration/FITCalibrator.h | 103 +++++------ .../src/FITCalibrationAlgorithmGetter.cxx | 26 --- .../calibration/src/FITCalibrationLinkDef.h | 2 +- 25 files changed, 684 insertions(+), 363 deletions(-) rename Detectors/FIT/FT0/calibration/include/FT0Calibration/{FT0CalibrationObject.h => FT0ChannelTimeCalibrationObject.h} (50%) rename Detectors/FIT/FT0/calibration/include/FT0Calibration/{FT0ChannelDataTimeSlotContainer.h => FT0ChannelTimeTimeSlotContainer.h} (61%) create mode 100644 Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0DummyCalibrationObject.h delete mode 100644 Detectors/FIT/FT0/calibration/src/FT0CalibrationObject.cxx delete mode 100644 Detectors/FIT/FT0/calibration/src/FT0ChannelDataTimeSlotContainer.cxx create mode 100644 Detectors/FIT/FT0/calibration/src/FT0ChannelTimeCalibrationObject.cxx create mode 100644 Detectors/FIT/FT0/calibration/src/FT0ChannelTimeTimeSlotContainer.cxx create mode 100644 Detectors/FIT/FT0/calibration/testWorkflow/FT0Calibration-Workflow.cxx rename Detectors/FIT/FT0/calibration/testWorkflow/{FT0ChannelCalibration-Workflow.cxx => FT0CalibrationDummy-Workflow.cxx} (51%) create mode 100644 Detectors/FIT/FT0/calibration/testWorkflow/FT0ChannelTimeCalibration-Workflow.cxx create mode 100644 Detectors/FIT/FT0/calibration/testWorkflow/FT0ChannelTimeCalibrationSpec.h create mode 100644 Detectors/FIT/common/calibration/README.md delete mode 100644 Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrationAlgorithmGetter.h create mode 100644 Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrationApi.h create mode 100644 Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrationObjectProducer.h delete mode 100644 Detectors/FIT/common/calibration/src/FITCalibrationAlgorithmGetter.cxx diff --git a/Detectors/FIT/FT0/calibration/CMakeLists.txt b/Detectors/FIT/FT0/calibration/CMakeLists.txt index e6bf04c898214..0f7926ddd7168 100644 --- a/Detectors/FIT/FT0/calibration/CMakeLists.txt +++ b/Detectors/FIT/FT0/calibration/CMakeLists.txt @@ -10,8 +10,8 @@ o2_add_library(FT0Calibration SOURCES - src/FT0ChannelDataTimeSlotContainer.cxx - src/FT0CalibrationObject.cxx + src/FT0ChannelTimeTimeSlotContainer.cxx + src/FT0ChannelTimeCalibrationObject.cxx PUBLIC_LINK_LIBRARIES O2::DataFormatsFT0 O2::CCDB @@ -24,14 +24,15 @@ o2_add_library(FT0Calibration o2_target_root_dictionary(FT0Calibration HEADERS include/FT0Calibration/FT0CalibrationInfoObject.h - include/FT0Calibration/FT0CalibrationObject.h - include/FT0Calibration/FT0ChannelDataTimeSlotContainer.h + include/FT0Calibration/FT0ChannelTimeCalibrationObject.h + include/FT0Calibration/FT0ChannelTimeTimeSlotContainer.h + include/FT0Calibration/FT0DummyCalibrationObject.h ) o2_add_executable(ft0-channel-offset-calibration COMPONENT_NAME calibration - SOURCES testWorkflow/FT0ChannelCalibration-Workflow.cxx + SOURCES testWorkflow/FT0ChannelTimeCalibration-Workflow.cxx PUBLIC_LINK_LIBRARIES O2::DataFormatsFT0 O2::FITCalibration ) @@ -41,4 +42,18 @@ o2_add_executable(ft0-tf-processor SOURCES testWorkflow/FT0TFProcessor-Workflow.cxx PUBLIC_LINK_LIBRARIES O2::DataFormatsFT0 O2::FITCalibration + ) + +o2_add_executable(ft0-calibration + COMPONENT_NAME calibration + SOURCES testWorkflow/FT0Calibration-Workflow.cxx + PUBLIC_LINK_LIBRARIES + O2::DataFormatsFT0 O2::FITCalibration + ) + +o2_add_executable(ft0-dummy-example + COMPONENT_NAME calibration + SOURCES testWorkflow/FT0CalibrationDummy-Workflow.cxx + PUBLIC_LINK_LIBRARIES + O2::DataFormatsFT0 O2::FITCalibration ) \ No newline at end of file diff --git a/Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0CalibrationInfoObject.h b/Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0CalibrationInfoObject.h index 6498f1d4b137e..abf5c27eba613 100644 --- a/Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0CalibrationInfoObject.h +++ b/Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0CalibrationInfoObject.h @@ -18,7 +18,7 @@ namespace o2::ft0 class FT0CalibrationInfoObject { public: - FT0CalibrationInfoObject(uint8_t channel, uint16_t time) : mChannelIndex(channel), mTime(time){}; + FT0CalibrationInfoObject(uint8_t channel, int16_t time) : mChannelIndex(channel), mTime(time){}; FT0CalibrationInfoObject() = default; ~FT0CalibrationInfoObject() = default; diff --git a/Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0CalibrationObject.h b/Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0ChannelTimeCalibrationObject.h similarity index 50% rename from Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0CalibrationObject.h rename to Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0ChannelTimeCalibrationObject.h index 83e1bb1093cc0..dcb628c4d368e 100644 --- a/Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0CalibrationObject.h +++ b/Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0ChannelTimeCalibrationObject.h @@ -8,39 +8,31 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef O2_FT0CALIBRATIONOBJECT_H -#define O2_FT0CALIBRATIONOBJECT_H +#ifndef O2_FT0CHANNELTIMECALIBRATIONOBJECT_H +#define O2_FT0CHANNELTIMECALIBRATIONOBJECT_H #include #include "Rtypes.h" #include "DataFormatsFT0/RawEventData.h" -#include "CommonUtils/MemFileHelper.h" -#include "TGraph.h" namespace o2::ft0 { -struct FT0CalibrationObject { +struct FT0ChannelTimeCalibrationObject { - std::array mChannelOffsets{}; + std::array mTimeOffsets{}; - ClassDefNV(FT0CalibrationObject, 1); + ClassDefNV(FT0ChannelTimeCalibrationObject, 1); }; -class FT0ChannelDataTimeSlotContainer; +class FT0ChannelTimeTimeSlotContainer; -class FT0CalibrationObjectAlgorithm +class FT0TimeChannelOffsetCalibrationObjectAlgorithm { public: - static void calibrate(FT0CalibrationObject& calibrationObject, const FT0ChannelDataTimeSlotContainer& container); -}; - -class FT0CalibrationObjectConverter -{ - public: - static std::unique_ptr toTGraph(const FT0CalibrationObject& object); + [[nodiscard]] static FT0ChannelTimeCalibrationObject generateCalibrationObject(const FT0ChannelTimeTimeSlotContainer& container); }; } // namespace o2::ft0 -#endif //O2_FT0CALIBRATIONOBJECT_H +#endif //O2_FT0CHANNELTIMECALIBRATIONOBJECT_H diff --git a/Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0ChannelDataTimeSlotContainer.h b/Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0ChannelTimeTimeSlotContainer.h similarity index 61% rename from Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0ChannelDataTimeSlotContainer.h rename to Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0ChannelTimeTimeSlotContainer.h index 58c9d35f1d4cd..6b57cc8ca4742 100644 --- a/Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0ChannelDataTimeSlotContainer.h +++ b/Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0ChannelTimeTimeSlotContainer.h @@ -8,57 +8,48 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef O2_FT0CHANNELDATATIMESLOTCONTAINER_H -#define O2_FT0CHANNELDATATIMESLOTCONTAINER_H +#ifndef O2_FT0CHANNELTIMETIMESLOTCONTAINER_H +#define O2_FT0CHANNELTIMETIMESLOTCONTAINER_H #include #include #include -#include "TH1F.h" -#include "TGraph.h" -#include #include "FT0Calibration/FT0CalibrationInfoObject.h" -#include "FT0Calibration/FT0CalibrationObject.h" +#include "FT0Calibration/FT0ChannelTimeCalibrationObject.h" #include "DataFormatsFT0/RawEventData.h" #include "Rtypes.h" -#include "TH2D.h" #include namespace o2::ft0 { -class FT0ChannelDataTimeSlotContainer final +class FT0ChannelTimeTimeSlotContainer final { //ranges to be discussed static constexpr int HISTOGRAM_RANGE = 200; static constexpr unsigned int NUMBER_OF_HISTOGRAM_BINS = 2 * HISTOGRAM_RANGE; - static constexpr bool TEST_MODE = true; - static constexpr unsigned int TIMER_FOR_TEST_MODE = 3; - using BoostHistogramType = boost::histogram::histogram, + using BoostHistogramType = boost::histogram::histogram, boost::histogram::axis::integer<>>, boost::histogram::unlimited_storage>>; public: - explicit FT0ChannelDataTimeSlotContainer(const FT0CalibrationObject& calibrationObject, std::size_t minEntries); + explicit FT0ChannelTimeTimeSlotContainer(std::size_t minEntries); [[nodiscard]] bool hasEnoughEntries() const; void fill(const gsl::span& data); - [[nodiscard]] int16_t getAverageTimeForChannel(std::size_t channelID) const; - void merge(FT0ChannelDataTimeSlotContainer* prev); + [[nodiscard]] int16_t getMeanGaussianFitValue(std::size_t channelID) const; + void merge(FT0ChannelTimeTimeSlotContainer* prev); void print() const; private: - const FT0CalibrationObject& mCalibrationObject; - std::chrono::time_point mCreationTimestamp; std::size_t mMinEntries; - std::array mEntriesPerChannel{}; BoostHistogramType mHistogram; - ClassDefNV(FT0ChannelDataTimeSlotContainer, 1); + ClassDefNV(FT0ChannelTimeTimeSlotContainer, 1); }; } // namespace o2::ft0 -#endif //O2_FT0CHANNELDATATIMESLOTCONTAINER_H +#endif //O2_FT0CHANNELTIMETIMESLOTCONTAINER_H diff --git a/Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0DummyCalibrationObject.h b/Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0DummyCalibrationObject.h new file mode 100644 index 0000000000000..f6d68ebe31cc0 --- /dev/null +++ b/Detectors/FIT/FT0/calibration/include/FT0Calibration/FT0DummyCalibrationObject.h @@ -0,0 +1,66 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +//Dummy calibration object to present usage of FIT calibration module +//Should be deleted if no more needed as an example + +#ifndef O2_FT0DUMMYCALIBRATIONOBJECT_H +#define O2_FT0DUMMYCALIBRATIONOBJECT_H + +#include +#include "Rtypes.h" +#include "DataFormatsFT0/RawEventData.h" + +namespace o2::ft0 +{ + +struct FT0DummyCalibrationObjectTime { + + std::array mStorage{}; + ClassDefNV(FT0DummyCalibrationObjectTime, 1); +}; + +struct FT0DummyCalibrationObjectCharge { + std::array mStorage{}; + ClassDefNV(FT0DummyCalibrationObjectCharge, 1); +}; + +struct FT0DummyNeededCalibrationObject { + std::array mStorage{}; + ClassDefNV(FT0DummyNeededCalibrationObject, 1); +}; + +//lets assume this object contains other calibration objects +struct FT0DummyCalibrationObject { + + FT0DummyCalibrationObjectTime mTimeCalibrationObject; + FT0DummyCalibrationObjectCharge mChargeCalibrationObject; + + ClassDefNV(FT0DummyCalibrationObject, 1); +}; + +//lets use existing container (which can be also modified if needed) +class FT0ChannelTimeTimeSlotContainer; + +class FT0DummyCalibrationObjectAlgorithm +{ + public: + [[nodiscard]] static FT0DummyCalibrationObject generateCalibrationObject(const FT0ChannelTimeTimeSlotContainer& container, const FT0DummyNeededCalibrationObject& additionalObjectNeededForCalibration) + { + //(add here your printing stuff for debug) + //do nothing + (void)additionalObjectNeededForCalibration; + return {}; + } +}; + +} // namespace o2::ft0 + +#endif //O2_FT0DUMMYCALIBRATIONOBJECT_H diff --git a/Detectors/FIT/FT0/calibration/macros/makeDummyFT0CalibObjectInCCDB.C b/Detectors/FIT/FT0/calibration/macros/makeDummyFT0CalibObjectInCCDB.C index 3eafa862c9bf7..3ac857bf33448 100644 --- a/Detectors/FIT/FT0/calibration/macros/makeDummyFT0CalibObjectInCCDB.C +++ b/Detectors/FIT/FT0/calibration/macros/makeDummyFT0CalibObjectInCCDB.C @@ -12,33 +12,16 @@ #include "TFile.h" #include "CCDB/CcdbApi.h" #include -#include "FT0Calibration/FT0CalibrationObject.h" +#include "FT0Calibration/FT0DummyCalibrationObject.h" int makeDummyFT0CalibObjectInCCDB(const std::string url = "http://localhost:8080") { - const char* OBJECT_PATH = "FT0/Calibration/CalibrationObject"; - o2::ccdb::CcdbApi api; - api.init(url); // or http://localhost:8080 for a local installation + api.init(url); std::map md; + o2::ft0::FT0DummyNeededCalibrationObject obj; + api.storeAsTFileAny(&obj, "FT0/Calibration/DummyNeeded", md, 0); - o2::ft0::FT0CalibrationObject calibObject; - api.storeAsTFileAny(&calibObject, OBJECT_PATH, md, 0); - - const auto testCalibObject = api.retrieveFromTFileAny(OBJECT_PATH, md, 0); - if (testCalibObject) { - for (unsigned int i = 0; i < 208; ++i) { - if (calibObject.mChannelOffsets[i] != testCalibObject->mChannelOffsets[i]) { - std::cout << "=====FAILURE=====" << std::endl; - std::cout << "Saved and retrieved objects are different!\n"; - return 1; - } - } - std::cout << "=====SUCCESS=====" << std::endl; - return 0; - } - - std::cout << "=====FAILURE=====" << std::endl; - return 1; + return 0; } diff --git a/Detectors/FIT/FT0/calibration/src/FT0CalibrationLinkDef.h b/Detectors/FIT/FT0/calibration/src/FT0CalibrationLinkDef.h index 864fd3253229f..b65cc0e690b88 100644 --- a/Detectors/FIT/FT0/calibration/src/FT0CalibrationLinkDef.h +++ b/Detectors/FIT/FT0/calibration/src/FT0CalibrationLinkDef.h @@ -15,7 +15,13 @@ #pragma link off all functions; #pragma link C++ class o2::ft0::FT0CalibrationInfoObject + ; -#pragma link C++ class o2::ft0::FT0CalibrationObject + ; -#pragma link C++ class o2::ft0::FT0ChannelDataTimeSlotContainer + ; +#pragma link C++ class o2::ft0::FT0ChannelTimeCalibrationObject + ; +#pragma link C++ class o2::ft0::FT0ChannelTimeTimeSlotContainer + ; + +//delete lines below +#pragma link C++ class o2::ft0::FT0DummyCalibrationObject + ; +#pragma link C++ class o2::ft0::FT0DummyCalibrationObjectTime + ; +#pragma link C++ class o2::ft0::FT0DummyCalibrationObjectCharge + ; +#pragma link C++ class o2::ft0::FT0DummyNeededCalibrationObject + ; #endif \ No newline at end of file diff --git a/Detectors/FIT/FT0/calibration/src/FT0CalibrationObject.cxx b/Detectors/FIT/FT0/calibration/src/FT0CalibrationObject.cxx deleted file mode 100644 index 8a7fe6b0add9f..0000000000000 --- a/Detectors/FIT/FT0/calibration/src/FT0CalibrationObject.cxx +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -#include "FT0Calibration/FT0CalibrationObject.h" -#include "FT0Calibration/FT0ChannelDataTimeSlotContainer.h" - -using namespace o2::ft0; - -void FT0CalibrationObjectAlgorithm::calibrate(FT0CalibrationObject& calibrationObject, - const FT0ChannelDataTimeSlotContainer& container) -{ - for (unsigned int iCh = 0; iCh < o2::ft0::Nchannels_FT0; ++iCh) { - int16_t dOffset = container.getAverageTimeForChannel(iCh); - calibrationObject.mChannelOffsets[iCh] -= dOffset; - } -} -std::unique_ptr FT0CalibrationObjectConverter::toTGraph(const FT0CalibrationObject& object) -{ - auto graph = std::make_unique(o2::ft0::Nchannels_FT0); - uint8_t channelID = 0; - - for (const auto& channelOffset : object.mChannelOffsets) { - graph->SetPoint(channelID, channelID, channelOffset); - ++channelID; - } - return graph; -} diff --git a/Detectors/FIT/FT0/calibration/src/FT0ChannelDataTimeSlotContainer.cxx b/Detectors/FIT/FT0/calibration/src/FT0ChannelDataTimeSlotContainer.cxx deleted file mode 100644 index 93b9ad2f8ce14..0000000000000 --- a/Detectors/FIT/FT0/calibration/src/FT0ChannelDataTimeSlotContainer.cxx +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -#include "FT0Calibration/FT0ChannelDataTimeSlotContainer.h" -#include -#include - -using namespace o2::ft0; - -FT0ChannelDataTimeSlotContainer::FT0ChannelDataTimeSlotContainer(const FT0CalibrationObject& calibObject, - std::size_t minEntries) - : mCalibrationObject(calibObject), mMinEntries(minEntries), mCreationTimestamp(std::chrono::system_clock::now()) -{ - - mHistogram = boost::histogram::make_histogram(boost::histogram::axis::regular<>(NUMBER_OF_HISTOGRAM_BINS, -HISTOGRAM_RANGE, HISTOGRAM_RANGE, "channel_times"), - boost::histogram::axis::integer<>(0, o2::ft0::Nchannels_FT0, "channel_ID")); -} - -bool FT0ChannelDataTimeSlotContainer::hasEnoughEntries() const -{ - - if constexpr (!TEST_MODE) { - //we have test data only for 8 channels - - auto min_elem = std::min_element(mEntriesPerChannel.begin(), mEntriesPerChannel.end()); - if (*min_elem > mMinEntries) { - return true; - } - return false; - } else { - return std::chrono::duration_cast(std::chrono::system_clock::now() - mCreationTimestamp).count() > TIMER_FOR_TEST_MODE; - } -} -void FT0ChannelDataTimeSlotContainer::fill(const gsl::span& data) -{ - - for (auto& entry : data) { - - const auto chID = entry.getChannelIndex(); - const auto chTime = entry.getTime(); - - //i dont really know when should it be marked as invalid - if (o2::ft0::ChannelData::DUMMY_CHANNEL_ID != chID && o2::ft0::ChannelData::DUMMY_CFD_TIME != chTime) { - mHistogram(chTime + mCalibrationObject.mChannelOffsets[chID], chID); - ++mEntriesPerChannel[chID]; - } else { - LOG(FATAL) << "Invalid channel data"; - } - } -} - -void FT0ChannelDataTimeSlotContainer::merge(FT0ChannelDataTimeSlotContainer* prev) -{ - - mHistogram += prev->mHistogram; - for (unsigned int iCh = 0; iCh < o2::ft0::Nchannels_FT0; ++iCh) { - mEntriesPerChannel[iCh] += prev->mEntriesPerChannel[iCh]; - } - - //will be deleted, when test data will be complete (all channels) - mCreationTimestamp = prev->mCreationTimestamp; -} - -int16_t FT0ChannelDataTimeSlotContainer::getAverageTimeForChannel(std::size_t channelID) const -{ - - if (0 == mEntriesPerChannel[channelID]) { - return 0; - } - - double avg = 0.; - for (int iBin = 0; iBin < NUMBER_OF_HISTOGRAM_BINS; ++iBin) { - const auto& v = mHistogram.at(iBin, channelID); - avg += v * (iBin - HISTOGRAM_RANGE); - } - return avg / mEntriesPerChannel[channelID]; -} -void FT0ChannelDataTimeSlotContainer::print() const -{ - //QC will do visualisation, no need to print -} diff --git a/Detectors/FIT/FT0/calibration/src/FT0ChannelTimeCalibrationObject.cxx b/Detectors/FIT/FT0/calibration/src/FT0ChannelTimeCalibrationObject.cxx new file mode 100644 index 0000000000000..49c3d49906942 --- /dev/null +++ b/Detectors/FIT/FT0/calibration/src/FT0ChannelTimeCalibrationObject.cxx @@ -0,0 +1,25 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "FT0Calibration/FT0ChannelTimeCalibrationObject.h" +#include "FT0Calibration/FT0ChannelTimeTimeSlotContainer.h" + +using namespace o2::ft0; + +FT0ChannelTimeCalibrationObject FT0TimeChannelOffsetCalibrationObjectAlgorithm::generateCalibrationObject(const FT0ChannelTimeTimeSlotContainer& container) +{ + FT0ChannelTimeCalibrationObject calibrationObject; + + for (unsigned int iCh = 0; iCh < o2::ft0::Nchannels_FT0; ++iCh) { + calibrationObject.mTimeOffsets[iCh] = container.getMeanGaussianFitValue(iCh); + } + + return calibrationObject; +} diff --git a/Detectors/FIT/FT0/calibration/src/FT0ChannelTimeTimeSlotContainer.cxx b/Detectors/FIT/FT0/calibration/src/FT0ChannelTimeTimeSlotContainer.cxx new file mode 100644 index 0000000000000..b895e890f99d5 --- /dev/null +++ b/Detectors/FIT/FT0/calibration/src/FT0ChannelTimeTimeSlotContainer.cxx @@ -0,0 +1,84 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "FT0Calibration/FT0ChannelTimeTimeSlotContainer.h" +#include +#include +#include "MathUtils/fit.h" + +using namespace o2::ft0; + +FT0ChannelTimeTimeSlotContainer::FT0ChannelTimeTimeSlotContainer(std::size_t minEntries) + : mMinEntries(minEntries) +{ + + mHistogram = boost::histogram::make_histogram(boost::histogram::axis::integer<>(-HISTOGRAM_RANGE, HISTOGRAM_RANGE, "channel_times"), + boost::histogram::axis::integer<>(0, o2::ft0::Nchannels_FT0, "channel_ID")); +} + +bool FT0ChannelTimeTimeSlotContainer::hasEnoughEntries() const +{ + return *std::min_element(mEntriesPerChannel.begin(), mEntriesPerChannel.end()) > mMinEntries; +} +void FT0ChannelTimeTimeSlotContainer::fill(const gsl::span& data) +{ + + for (auto& entry : data) { + + const auto chID = entry.getChannelIndex(); + const auto chTime = entry.getTime(); + + //i dont really know when should it be marked as invalid + if (o2::ft0::ChannelData::DUMMY_CHANNEL_ID != chID && o2::ft0::ChannelData::DUMMY_CFD_TIME != chTime) { + mHistogram(chTime, chID); + ++mEntriesPerChannel[chID]; + } else { + LOG(FATAL) << "Invalid channel data"; + } + } +} + +void FT0ChannelTimeTimeSlotContainer::merge(FT0ChannelTimeTimeSlotContainer* prev) +{ + + mHistogram += prev->mHistogram; + for (unsigned int iCh = 0; iCh < o2::ft0::Nchannels_FT0; ++iCh) { + mEntriesPerChannel[iCh] += prev->mEntriesPerChannel[iCh]; + } +} + +int16_t FT0ChannelTimeTimeSlotContainer::getMeanGaussianFitValue(std::size_t channelID) const +{ + + static constexpr size_t MEAN_VALUE_INDEX_IN_OUTPUT_VECTOR = 1; + + if (0 == mEntriesPerChannel[channelID]) { + return 0; + } + + std::vector channelHistogramData(NUMBER_OF_HISTOGRAM_BINS); + std::vector outputGaussianFitValues; + for (int iBin = 0; iBin < NUMBER_OF_HISTOGRAM_BINS; ++iBin) { + channelHistogramData[iBin] = mHistogram.at(iBin, channelID); + } + + double returnCode = math_utils::fitGaus(NUMBER_OF_HISTOGRAM_BINS, channelHistogramData.data(), + -HISTOGRAM_RANGE, HISTOGRAM_RANGE, outputGaussianFitValues); + if (returnCode < 0) { + LOG(ERROR) << "Gaussian fit error!"; + return 0; + } + + return static_cast(std::round(outputGaussianFitValues[MEAN_VALUE_INDEX_IN_OUTPUT_VECTOR])); +} +void FT0ChannelTimeTimeSlotContainer::print() const +{ + //QC will do that part +} diff --git a/Detectors/FIT/FT0/calibration/testWorkflow/FT0Calibration-Workflow.cxx b/Detectors/FIT/FT0/calibration/testWorkflow/FT0Calibration-Workflow.cxx new file mode 100644 index 0000000000000..390b62f6af31e --- /dev/null +++ b/Detectors/FIT/FT0/calibration/testWorkflow/FT0Calibration-Workflow.cxx @@ -0,0 +1,27 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "FT0ChannelTimeCalibrationSpec.h" + +void customize(std::vector& workflowOptions) +{ + //probably some option will be added +} + +#include "Framework/runDataProcessing.h" + +using namespace o2::framework; +WorkflowSpec defineDataProcessing(ConfigContext const& config) +{ + WorkflowSpec workflow; + workflow.emplace_back(o2::ft0::getFT0ChannelTimeCalibrationSpec()); + //add calib spec here... + return workflow; +} \ No newline at end of file diff --git a/Detectors/FIT/FT0/calibration/testWorkflow/FT0ChannelCalibration-Workflow.cxx b/Detectors/FIT/FT0/calibration/testWorkflow/FT0CalibrationDummy-Workflow.cxx similarity index 51% rename from Detectors/FIT/FT0/calibration/testWorkflow/FT0ChannelCalibration-Workflow.cxx rename to Detectors/FIT/FT0/calibration/testWorkflow/FT0CalibrationDummy-Workflow.cxx index 5cff5bb7564a1..b5a974a8509cc 100644 --- a/Detectors/FIT/FT0/calibration/testWorkflow/FT0ChannelCalibration-Workflow.cxx +++ b/Detectors/FIT/FT0/calibration/testWorkflow/FT0CalibrationDummy-Workflow.cxx @@ -8,12 +8,13 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#include "FT0Calibration/FT0CalibrationInfoObject.h" -#include "FITCalibration/FITCalibrationDevice.h" -#include "FT0Calibration/FT0ChannelDataTimeSlotContainer.h" -#include "FT0Calibration/FT0CalibrationObject.h" +//Dummy, delete this file if example not needed anymore -using namespace o2::fit; +#include "Framework/DataProcessorSpec.h" +#include "FITCalibration/FITCalibrationDevice.h" +#include "FT0Calibration/FT0CalibrationInfoObject.h" +#include "FT0Calibration/FT0ChannelTimeTimeSlotContainer.h" +#include "FT0Calibration/FT0DummyCalibrationObject.h" void customize(std::vector& workflowOptions) { @@ -25,28 +26,27 @@ void customize(std::vector& workflowOptions) using namespace o2::framework; WorkflowSpec defineDataProcessing(ConfigContext const& config) { + WorkflowSpec workflow; using CalibrationDeviceType = o2::fit::FITCalibrationDevice; + o2::ft0::FT0ChannelTimeTimeSlotContainer, o2::ft0::FT0DummyCalibrationObject>; - std::vector outputs; - outputs.emplace_back(ConcreteDataTypeMatcher{o2::calibration::Utils::gDataOriginCLB, o2::calibration::Utils::gDataDescriptionCLBPayload}); - outputs.emplace_back(ConcreteDataTypeMatcher{o2::calibration::Utils::gDataOriginCLB, o2::calibration::Utils::gDataDescriptionCLBInfo}); + std::vector outputs; + outputs.emplace_back(o2::framework::ConcreteDataTypeMatcher{o2::calibration::Utils::gDataOriginCLB, o2::calibration::Utils::gDataDescriptionCLBPayload}); + outputs.emplace_back(o2::framework::ConcreteDataTypeMatcher{o2::calibration::Utils::gDataOriginCLB, o2::calibration::Utils::gDataDescriptionCLBInfo}); - constexpr const char* inputDataLabel = "calib"; - constexpr const char* calibrationObjectPath = "FT0/Calibration/CalibrationObject"; + constexpr const char* DEFAULT_INPUT_LABEL = "calib"; - std::vector inputs; - inputs.emplace_back(inputDataLabel, "FT0", "CALIB_INFO"); + std::vector inputs; + inputs.emplace_back(DEFAULT_INPUT_LABEL, "FT0", "CALIB_INFO"); - DataProcessorSpec dataProcessorSpec{ - "calib-ft0channel-calibration", + o2::framework::DataProcessorSpec dataProcessorSpec{ + "calib-ft0-channel-time", inputs, outputs, - AlgorithmSpec{adaptFromTask(inputDataLabel, calibrationObjectPath)}, - Options{}}; + o2::framework::AlgorithmSpec{o2::framework::adaptFromTask(DEFAULT_INPUT_LABEL)}, + o2::framework::Options{}}; - WorkflowSpec workflow; workflow.emplace_back(dataProcessorSpec); return workflow; -} +} \ No newline at end of file diff --git a/Detectors/FIT/FT0/calibration/testWorkflow/FT0ChannelTimeCalibration-Workflow.cxx b/Detectors/FIT/FT0/calibration/testWorkflow/FT0ChannelTimeCalibration-Workflow.cxx new file mode 100644 index 0000000000000..53cbd2f6f129c --- /dev/null +++ b/Detectors/FIT/FT0/calibration/testWorkflow/FT0ChannelTimeCalibration-Workflow.cxx @@ -0,0 +1,26 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "FT0ChannelTimeCalibrationSpec.h" + +void customize(std::vector& workflowOptions) +{ + //probably some option will be added +} + +#include "Framework/runDataProcessing.h" + +using namespace o2::framework; +WorkflowSpec defineDataProcessing(ConfigContext const& config) +{ + WorkflowSpec workflow; + workflow.emplace_back(o2::ft0::getFT0ChannelTimeCalibrationSpec()); + return workflow; +} diff --git a/Detectors/FIT/FT0/calibration/testWorkflow/FT0ChannelTimeCalibrationSpec.h b/Detectors/FIT/FT0/calibration/testWorkflow/FT0ChannelTimeCalibrationSpec.h new file mode 100644 index 0000000000000..a1e1e35d57c7e --- /dev/null +++ b/Detectors/FIT/FT0/calibration/testWorkflow/FT0ChannelTimeCalibrationSpec.h @@ -0,0 +1,45 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_FT0CHANNELTIMECALIBRATIONSPEC_H +#define O2_FT0CHANNELTIMECALIBRATIONSPEC_H + +#include "Framework/DataProcessorSpec.h" +#include "FITCalibration/FITCalibrationDevice.h" +#include "FT0Calibration/FT0CalibrationInfoObject.h" +#include "FT0Calibration/FT0ChannelTimeCalibrationObject.h" +#include "FT0Calibration/FT0ChannelTimeTimeSlotContainer.h" + +namespace o2::ft0 +{ +o2::framework::DataProcessorSpec getFT0ChannelTimeCalibrationSpec() +{ + using CalibrationDeviceType = o2::fit::FITCalibrationDevice; + + std::vector outputs; + outputs.emplace_back(o2::framework::ConcreteDataTypeMatcher{o2::calibration::Utils::gDataOriginCLB, o2::calibration::Utils::gDataDescriptionCLBPayload}); + outputs.emplace_back(o2::framework::ConcreteDataTypeMatcher{o2::calibration::Utils::gDataOriginCLB, o2::calibration::Utils::gDataDescriptionCLBInfo}); + + constexpr const char* DEFAULT_INPUT_LABEL = "calib"; + + std::vector inputs; + inputs.emplace_back(DEFAULT_INPUT_LABEL, "FT0", "CALIB_INFO"); + + return o2::framework::DataProcessorSpec{ + "calib-ft0-channel-time", + inputs, + outputs, + o2::framework::AlgorithmSpec{o2::framework::adaptFromTask(DEFAULT_INPUT_LABEL)}, + o2::framework::Options{}}; +} +} // namespace o2::ft0 + +#endif //O2_FT0CHANNELTIMECALIBRATIONSPEC_H diff --git a/Detectors/FIT/FT0/calibration/testWorkflow/FT0TFProcessor-Workflow.cxx b/Detectors/FIT/FT0/calibration/testWorkflow/FT0TFProcessor-Workflow.cxx index ce3f98df23306..c4cd0c41f5201 100644 --- a/Detectors/FIT/FT0/calibration/testWorkflow/FT0TFProcessor-Workflow.cxx +++ b/Detectors/FIT/FT0/calibration/testWorkflow/FT0TFProcessor-Workflow.cxx @@ -11,7 +11,6 @@ #include #include "Framework/DeviceSpec.h" #include "Framework/WorkflowSpec.h" -#include "Framework/CompletionPolicyHelpers.h" #include "Framework/Task.h" #include "DataFormatsFT0/ChannelData.h" #include "DataFormatsFT0/Digit.h" diff --git a/Detectors/FIT/common/calibration/CMakeLists.txt b/Detectors/FIT/common/calibration/CMakeLists.txt index 2d01227f0f874..c9f049475bea5 100644 --- a/Detectors/FIT/common/calibration/CMakeLists.txt +++ b/Detectors/FIT/common/calibration/CMakeLists.txt @@ -9,8 +9,7 @@ # submit itself to any jurisdiction. o2_add_library(FITCalibration - SOURCES - src/FITCalibrationAlgorithmGetter.cxx + PUBLIC_LINK_LIBRARIES O2::FT0Calibration O2::Framework @@ -25,6 +24,7 @@ o2_target_root_dictionary(FITCalibration HEADERS include/FITCalibration/FITCalibrator.h include/FITCalibration/FITCalibrationDevice.h - include/FITCalibration/FITCalibrationAlgorithmGetter.h + include/FITCalibration/FITCalibrationObjectProducer.h + include/FITCalibration/FITCalibrationApi.h ) diff --git a/Detectors/FIT/common/calibration/README.md b/Detectors/FIT/common/calibration/README.md new file mode 100644 index 0000000000000..653ff2497bbdd --- /dev/null +++ b/Detectors/FIT/common/calibration/README.md @@ -0,0 +1,36 @@ +## FIT Calibration workflow + +###Overview +The module was implemented in a generic way. Adding new calibration object should be easy and intuitive. Calibration device uses https://github.com/AliceO2Group/AliceO2/tree/dev/Detectors/Calibration for TimeFrame management (see link above for more detailed information). + +###How to use TimeSlotCalibration? +####It is required to define classes listed below to be able to use prepared TimeSlotCalibration module. +- TimeSlot Container class (for current state of the code, example - `FT0ChannelTimeTimeSlotContainer`). Container is responsible for data storage (CFDTime, Charge, etc.) and providing data for calibration object generation +- Calibration Info Object class (for current state of the code, example - `FT0CalibrationInfoObject`). This class is responsible for providing input data which will be saved in TimeSlot Container instance. (so we can assume it's simplified channel data type, with extracted data that will be required for calibration process) +- Calibration Object class (for current state of the code, example - `FT0ChannelTimeCalibrationObject`, `FT0DummyCalibrationObject`) - representing correction values + +To conclude, data stored in calibration info object is required to fill TimeSlot container with data and that data stored in the container is needed to generate calibration object. + +###Implementation details +FITCalibration module is based on templates, so it can be used for FT0, FDD and FV0 calibration workflows. One has to define definition of the classes described above and also provide formula for calibration object generation. + +###How to add new code, new calibration object? +- Define your calibration object class (can be combined more than one into one class) +- Define your timeslot container class (can be used for many calibration objects) +- Define algorithm / function for calibration object generation. Add template specialization with your classes in `FITCalibrationObjectProducer` `generateCalibrationObject` method +- Add template specialization for calibration object in `FitCalibrationApi`, define ccdb calib object path and also recipe how to store them in CCDB +- Create separated workflow or add your `DataProcessorSpec` to main calibration workflow + +For example check `FT0CalibrationDummy-Workflow` which uses combined calibration object. It is also uses mechanism to retrieve (from CCDB) another calibration object needed for calibration. Before running this workflow it is required to run `makeDummyFt0CalibObjectInCCDB` macro to generate dummy object in the local CCDB instance. + +###How to run these workflows? +- Dummy: +`root -l ~/alice/O2/Detectors/FIT/FT0/calibration/macros/makeDummyFT0CalibObjectInCCDB.C+` + `o2-ft0-digits-reader-workflow | o2-calibration-ft0-tf-processor | o2-calibration-ft0-dummy-example | o2-calibration-ccdb-populator-workflow --ccdb-path=http://localhost:8080 -b` +- Channel Time calibration: +`o2-ft0-digits-reader-workflow | o2-calibration-ft0-tf-processor | o2-calibration-ft0-channel-offset-calibration | o2-calibration-ccdb-populator-workflow --ccdb-path=http://localhost:8080 -` + +- General calibration workflow (for now, the same as Channel Time calibration) +`o2-ft0-digits-reader-workflow | o2-calibration-ft0-tf-processor | o2-calibration-ft0-calibration | o2-calibration-ccdb-populator-workflow --ccdb-path=http://localhost:8080 -b` + +You have to specify path to digits file in `o2-ft0-digits-reader-workflow`. If you don't need to store generated calib object you can delete last workflow part (`o2-calibration-ccdb-populator-workflow --ccdb-path=http://localhost:8080 -b`) \ No newline at end of file diff --git a/Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrationAlgorithmGetter.h b/Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrationAlgorithmGetter.h deleted file mode 100644 index ca3498d756c35..0000000000000 --- a/Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrationAlgorithmGetter.h +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -#ifndef O2_FITCALIBRATIONALGORITHMGETTER_H -#define O2_FITCALIBRATIONALGORITHMGETTER_H - -#include "FT0Calibration/FT0CalibrationObject.h" -#include "FT0Calibration/FT0ChannelDataTimeSlotContainer.h" - -namespace o2::fit -{ -class FITCalibrationAlgorithmGetter -{ - public: - template - static void doCalibrationAndUpdateCalibrationObject(CalibrationObjectType& calibrationObject, const TimeSlotContainerType& container); -}; - -} // namespace o2::fit - -#endif //O2_FITCALIBRATIONALGORITHMGETTER_H diff --git a/Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrationApi.h b/Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrationApi.h new file mode 100644 index 0000000000000..add5fc0cb2e9a --- /dev/null +++ b/Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrationApi.h @@ -0,0 +1,170 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_FITCALIBRATIONAPI_H +#define O2_FITCALIBRATIONAPI_H + +#include "FT0Calibration/FT0ChannelTimeCalibrationObject.h" +#include "CommonUtils/MemFileHelper.h" +#include "CCDB/CCDBTimeStampUtils.h" +#include "FT0Calibration/FT0DummyCalibrationObject.h" //delete this when example not needed anymore +#include "CCDB/CcdbObjectInfo.h" +#include + +namespace o2::fit +{ +class FITCalibrationApi +{ + private: + static constexpr const char* DEFAULT_CCDB_URL = "http://localhost:8080"; + using CalibObjWithInfoType = std::pair>>; + inline static unsigned long mProcessingTimestamp = 0; + + public: + FITCalibrationApi() = delete; + FITCalibrationApi(const FITCalibrationApi&) = delete; + FITCalibrationApi(FITCalibrationApi&&) = delete; + + static void init(); + static void setProcessingTimestamp(unsigned long tf) { mProcessingTimestamp = tf; } + [[nodiscard]] static unsigned long getProcessingTimestamp() { return mProcessingTimestamp; } + + template + [[nodiscard]] static const char* getObjectPath(); + + template + [[nodiscard]] static const CalibrationObjectType& getMostRecentCalibrationObject(); + + template + [[nodiscard]] static const CalibrationObjectType& getCalibrationObjectForGivenTimestamp(long timestamp); + + template + [[nodiscard]] static std::vector prepareCalibrationObjectToSend(const CalibrationObjectType& calibrationObject); + + private: + template + static void handleInvalidCalibrationObjectType(); + + template + [[nodiscard]] static CalibObjWithInfoType doSerializationAndPrepareObjectInfo(const CalibrationObjectType& calibrationObject); +}; + +void FITCalibrationApi::init() +{ + //caching in basicCCDBManager enabled by default + o2::ccdb::BasicCCDBManager::instance().setURL(DEFAULT_CCDB_URL); +} + +template +void FITCalibrationApi::handleInvalidCalibrationObjectType() +{ + static_assert(sizeof(CalibrationObjectType) == 0, "[FITCalibrationApi] Cannot find specialization provided Calibration Object Type"); +} + +template +FITCalibrationApi::CalibObjWithInfoType FITCalibrationApi::doSerializationAndPrepareObjectInfo(const CalibrationObjectType& calibrationObject) +{ + static std::map metaData; + static std::string dummyStringVariableThatWillBeChangedAnyway; + + CalibObjWithInfoType result; + result.first = o2::ccdb::CcdbObjectInfo(FITCalibrationApi::getObjectPath(), dummyStringVariableThatWillBeChangedAnyway, dummyStringVariableThatWillBeChangedAnyway, metaData, o2::ccdb::getCurrentTimestamp(), -1); + result.second = o2::ccdb::CcdbApi::createObjectImage(&calibrationObject, &result.first); + + return result; +} + +template +const CalibrationObjectType& FITCalibrationApi::getCalibrationObjectForGivenTimestamp(long timestamp) +{ + + o2::ccdb::BasicCCDBManager::instance().setTimestamp(timestamp); + auto calibObjectPtr = o2::ccdb::BasicCCDBManager::instance().get(getObjectPath()); + if (nullptr == calibObjectPtr) { + throw std::runtime_error("Cannot read requested calibration object"); + } + return *calibObjectPtr; +} + +template +const CalibrationObjectType& FITCalibrationApi::getMostRecentCalibrationObject() +{ + return getCalibrationObjectForGivenTimestamp(o2::ccdb::getCurrentTimestamp()); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +template +std::vector FITCalibrationApi::prepareCalibrationObjectToSend(const CalibrationObjectType& calibrationObject) +{ + handleInvalidCalibrationObjectType(); + return {}; +} + +template +const char* FITCalibrationApi::getObjectPath() +{ + handleInvalidCalibrationObjectType(); + return {}; +} + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +template <> +const char* FITCalibrationApi::getObjectPath() +{ + return "FT0/Calibration/ChannelTimeOffset"; +} + +template <> +std::vector FITCalibrationApi::prepareCalibrationObjectToSend(const o2::ft0::FT0ChannelTimeCalibrationObject& calibrationObject) +{ + std::vector result; + result.emplace_back(doSerializationAndPrepareObjectInfo(calibrationObject)); + return result; +} + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// DUMMY STUFF DELETE IT WHEN EXAMPLE NOT NEEDED ANYMORE +template <> +const char* FITCalibrationApi::getObjectPath() +{ + return "FT0/Calibration/DummyTime"; +} + +template <> +const char* FITCalibrationApi::getObjectPath() +{ + return "FT0/Calibration/DummyCharge"; +} + +template <> +const char* FITCalibrationApi::getObjectPath() +{ + return "FT0/Calibration/DummyNeeded"; +} + +template <> +std::vector FITCalibrationApi::prepareCalibrationObjectToSend(const o2::ft0::FT0DummyCalibrationObject& calibrationObject) +{ + std::vector result; + result.emplace_back(doSerializationAndPrepareObjectInfo(calibrationObject.mChargeCalibrationObject)); + result.emplace_back(doSerializationAndPrepareObjectInfo(calibrationObject.mTimeCalibrationObject)); + return result; +} + +// END OF DUMMY STUFF DELETE IT WHEN EXAMPLE NOT NEEDED ANYMORE + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +} // namespace o2::fit + +#endif //O2_FITCALIBRATIONAPI_H diff --git a/Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrationDevice.h b/Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrationDevice.h index 4719e2f862e8f..3f677901b5d1f 100644 --- a/Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrationDevice.h +++ b/Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrationDevice.h @@ -21,15 +21,22 @@ namespace o2::fit { -template +#define FIT_CALIBRATION_DEVICE_TEMPLATES \ + template + +#define FIT_CALIBRATION_DEVICE_TYPE \ + FITCalibrationDevice + +FIT_CALIBRATION_DEVICE_TEMPLATES class FITCalibrationDevice : public o2::framework::Task { + static constexpr const char* DEFAULT_INPUT_DATA_LABEL = "calib"; using CalibratorType = FITCalibrator; public: - explicit FITCalibrationDevice(std::string inputDataLabel, std::string calibrationObjectPath) - : mInputDataLabel(std::move(inputDataLabel)), mCalibrationObjectPath(std::move(calibrationObjectPath)) {} + explicit FITCalibrationDevice(std::string inputDataLabel = DEFAULT_INPUT_DATA_LABEL) + : mInputDataLabel(std::move(inputDataLabel)) {} void init(o2::framework::InitContext& context) final; void run(o2::framework::ProcessingContext& context) final; @@ -40,25 +47,15 @@ class FITCalibrationDevice : public o2::framework::Task void _sendCalibrationObjectIfSlotFinalized(o2::framework::DataAllocator& outputs); private: - std::string mInputDataLabel; - std::string mCalibrationObjectPath; + const std::string mInputDataLabel; std::unique_ptr mCalibrator; }; -#define FIT_CALIBRATION_DEVICE_TEMPLATES \ - template - -#define FIT_CALIBRATION_DEVICE_TYPE \ - FITCalibrationDevice - FIT_CALIBRATION_DEVICE_TEMPLATES void FIT_CALIBRATION_DEVICE_TYPE::init(o2::framework::InitContext& context) { - mCalibrator = std::make_unique(mCalibrationObjectPath); - - //local db instance for testing - //caching is enabled by default - o2::ccdb::BasicCCDBManager::instance().setURL("http://localhost:8080"); + mCalibrator = std::make_unique(); + FITCalibrationApi::init(); } FIT_CALIBRATION_DEVICE_TEMPLATES @@ -68,8 +65,8 @@ void FIT_CALIBRATION_DEVICE_TYPE::run(o2::framework::ProcessingContext& context) auto TFCounter = o2::header::get(context.inputs().get(mInputDataLabel).header)->startTime; auto data = context.inputs().get>(mInputDataLabel); - //for testing purposes - mCalibrator->setCalibrationObject(o2::ccdb::BasicCCDBManager::instance().get(mCalibrationObjectPath)); + //something like that probably in the future + // FITCalibrationApi::setProcessingTimestamp( getTimestampForTF(TFCounter)) ); mCalibrator->process(TFCounter, data); _sendCalibrationObjectIfSlotFinalized(context.outputs()); @@ -78,9 +75,10 @@ void FIT_CALIBRATION_DEVICE_TYPE::run(o2::framework::ProcessingContext& context) FIT_CALIBRATION_DEVICE_TEMPLATES void FIT_CALIBRATION_DEVICE_TYPE::endOfStream(o2::framework::EndOfStreamContext& context) { - //should be finalized even if not enough data? - mCalibrator->finalizeOldestSlot(); - _sendOutputs(context.outputs()); + //nope, we have to check if we can finalize slot anyway - scenario with one batch + static constexpr uint64_t INFINITE_TF = 0xffffffffffffffff; + mCalibrator->checkSlotsToFinalize(INFINITE_TF); + _sendCalibrationObjectIfSlotFinalized(context.outputs()); } FIT_CALIBRATION_DEVICE_TEMPLATES @@ -96,21 +94,15 @@ void FIT_CALIBRATION_DEVICE_TYPE::_sendOutputs(o2::framework::DataAllocator& out { using clbUtils = o2::calibration::Utils; + const auto& objectsToSend = mCalibrator->getStoredCalibrationObjects(); - const auto& payloadVec = mCalibrator->getCalibrationObjectVector(); - auto& infoVec = mCalibrator->getCalibrationInfoVector(); - assert(payloadVec.size() == infoVec.size()); - - for (uint32_t i = 0; i < payloadVec.size(); ++i) { - auto& w = infoVec[i]; - auto image = o2::ccdb::CcdbApi::createObjectImage(&payloadVec[i], &w); - outputs.snapshot(o2::framework::Output{clbUtils::gDataOriginCLB, clbUtils::gDataDescriptionCLBPayload, i}, *image); - outputs.snapshot(o2::framework::Output{clbUtils::gDataOriginCLB, clbUtils::gDataDescriptionCLBInfo, i}, w); - } - - if (!payloadVec.empty()) { - mCalibrator->initOutput(); + uint32_t iSendChannel = 0; + for (const auto& [ccdbInfo, calibObject] : objectsToSend) { + outputs.snapshot(o2::framework::Output{clbUtils::gDataOriginCLB, clbUtils::gDataDescriptionCLBPayload, iSendChannel}, *calibObject); + outputs.snapshot(o2::framework::Output{clbUtils::gDataOriginCLB, clbUtils::gDataDescriptionCLBInfo, iSendChannel}, ccdbInfo); + ++iSendChannel; } + mCalibrator->initOutput(); } #undef FIT_CALIBRATION_DEVICE_TEMPLATES diff --git a/Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrationObjectProducer.h b/Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrationObjectProducer.h new file mode 100644 index 0000000000000..e7df95407d025 --- /dev/null +++ b/Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrationObjectProducer.h @@ -0,0 +1,63 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_FITCALIBRATIONOBJECTPRODUCER_H +#define O2_FITCALIBRATIONOBJECTPRODUCER_H + +#include "FITCalibration/FITCalibrationApi.h" +#include "FT0Calibration/FT0ChannelTimeCalibrationObject.h" +#include "FT0Calibration/FT0ChannelTimeTimeSlotContainer.h" +#include "FITCalibration/FITCalibrationObjectProducer.h" +#include "FT0Calibration/FT0DummyCalibrationObject.h" // delete this + +namespace o2::fit +{ +class FITCalibrationObjectProducer +{ + public: + template + static CalibrationObjectType generateCalibrationObject(const TimeSlotContainerType& container); +}; + +template +CalibrationObjectType FITCalibrationObjectProducer::generateCalibrationObject(const TimeSlotContainerType& container) +{ + static_assert(sizeof(CalibrationObjectType) == 0, "[FITCalibrationObjectProducer] Cannot find specialization provided Calibration Object Type"); + return {}; +} + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +template <> +o2::ft0::FT0ChannelTimeCalibrationObject FITCalibrationObjectProducer::generateCalibrationObject(const o2::ft0::FT0ChannelTimeTimeSlotContainer& container) +{ + return o2::ft0::FT0TimeChannelOffsetCalibrationObjectAlgorithm::generateCalibrationObject(container); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// DUMMY STUFF DELETE IT WHEN EXAMPLE NOT NEEDED ANYMORE + +template <> +o2::ft0::FT0DummyCalibrationObject FITCalibrationObjectProducer::generateCalibrationObject(const o2::ft0::FT0ChannelTimeTimeSlotContainer& container) +{ + //We need additional object here for calibration + const auto& neededObjectForCalibration = FITCalibrationApi::getMostRecentCalibrationObject(); + // const auto& neededObjectForCalibration = FITCalibrationApi::getCalibrationObjectForGivenTimestamp(FITCalibrationApi::getProcessingTimestamp()); + return o2::ft0::FT0DummyCalibrationObjectAlgorithm::generateCalibrationObject(container, neededObjectForCalibration); +} + +// END OF DUMMY STUFF DELETE IT WHEN EXAMPLE NOT NEEDED ANYMORE + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +} // namespace o2::fit + +#endif //O2_FITCALIBRATIONOBJECTPRODUCER_H diff --git a/Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrator.h b/Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrator.h index 5002d5661fa33..ebf8dacf58b5d 100644 --- a/Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrator.h +++ b/Detectors/FIT/common/calibration/include/FITCalibration/FITCalibrator.h @@ -16,21 +16,33 @@ #include "DetectorsCalibration/Utils.h" #include "CommonUtils/MemFileHelper.h" #include "Rtypes.h" -#include "FITCalibration/FITCalibrationAlgorithmGetter.h" +#include "FITCalibration/FITCalibrationObjectProducer.h" +#include "FITCalibration/FITCalibrationApi.h" namespace o2::fit { -template +#define FIT_CALIBRATOR_TEMPLATES \ + template + +#define FIT_CALIBRATOR_TYPE \ + FITCalibrator + +FIT_CALIBRATOR_TEMPLATES class FITCalibrator final : public o2::calibration::TimeSlotCalibration { + //probably will be set via run parameter static constexpr unsigned int DEFAULT_MIN_ENTRIES = 10000; + + //temp param for testing + static constexpr bool DEFAULT_TEST_MODE = true; + using TFType = uint64_t; using Slot = o2::calibration::TimeSlot; public: - explicit FITCalibrator(const std::string& calibrationObjectPath, unsigned int minimumEntries = DEFAULT_MIN_ENTRIES); + explicit FITCalibrator(unsigned int minimumEntries = DEFAULT_MIN_ENTRIES, bool testMode = DEFAULT_TEST_MODE); ~FITCalibrator() final = default; @@ -38,103 +50,68 @@ class FITCalibrator final : public o2::calibration::TimeSlotCalibration& getCalibrationObjectVector() const { return mCalibrationObjectVector; } - [[nodiscard]] const std::vector& getCalibrationInfoVector() const { return mInfoVector; } - [[nodiscard]] std::vector& getCalibrationInfoVector() { return mInfoVector; } - - //for testing purposes - void setCalibrationObject(CalibrationObjectType* calibObj); + [[nodiscard]] bool isCalibrationObjectReadyToSend() const { return !mStoredCalibrationObjects.empty(); } + [[nodiscard]] const std::vector>>>& getStoredCalibrationObjects() const { return mStoredCalibrationObjects; } private: - void _storeCurrentCalibrationObject(const CalibrationObjectType& calibrationObject); - void _doCalibrationAndUpdatedCalibrationObject(const TimeSlotStorageType& container, CalibrationObjectType& calibrationObject); + [[nodiscard]] bool _isTestModeEnabled() const { return mTestMode; } private: - std::vector mInfoVector; - std::vector mCalibrationObjectVector; - const std::string& mCalibrationObjectPath; + std::vector>>> mStoredCalibrationObjects{}; const unsigned int mMinEntries; - - //for testing purposes - CalibrationObjectType* mCurrentCalibObject; + const bool mTestMode; }; -#define FIT_CALIBRATOR_TEMPLATES \ - template - -#define FIT_CALIBRATOR_TYPE \ - FITCalibrator - FIT_CALIBRATOR_TEMPLATES -FIT_CALIBRATOR_TYPE::FITCalibrator(const std::string& calibrationObjectPath, const unsigned int minimumEntries) - : mCalibrationObjectPath(calibrationObjectPath), mMinEntries(minimumEntries) +FIT_CALIBRATOR_TYPE::FITCalibrator(unsigned int minimumEntries, bool testMode) + : mMinEntries(minimumEntries), mTestMode(testMode) { } FIT_CALIBRATOR_TEMPLATES bool FIT_CALIBRATOR_TYPE::hasEnoughData(const Slot& slot) const { + if (_isTestModeEnabled()) { + static unsigned int testCounter = 0; + ++testCounter; + if (!(testCounter % 1000)) { + return true; + } + } + return slot.getContainer()->hasEnoughEntries(); } FIT_CALIBRATOR_TEMPLATES void FIT_CALIBRATOR_TYPE::initOutput() { - mInfoVector.clear(); - mCalibrationObjectVector.clear(); + mStoredCalibrationObjects.clear(); } FIT_CALIBRATOR_TEMPLATES void FIT_CALIBRATOR_TYPE::finalizeSlot(Slot& slot) { - + static std::map md; const auto& container = slot.getContainer(); - _doCalibrationAndUpdatedCalibrationObject(*container, *mCurrentCalibObject); - _storeCurrentCalibrationObject(*mCurrentCalibObject); + + auto calibrationObject = FITCalibrationObjectProducer::generateCalibrationObject(*container); + auto preparedCalibObjects = FITCalibrationApi::prepareCalibrationObjectToSend(calibrationObject); + + mStoredCalibrationObjects.insert(mStoredCalibrationObjects.end(), + std::make_move_iterator(preparedCalibObjects.begin()), + std::make_move_iterator(preparedCalibObjects.end())); } FIT_CALIBRATOR_TEMPLATES typename FIT_CALIBRATOR_TYPE::Slot& FIT_CALIBRATOR_TYPE::emplaceNewSlot( bool front, TFType tstart, TFType tend) { - auto& cont = o2::calibration::TimeSlotCalibration::getSlots(); auto& slot = front ? cont.emplace_front(tstart, tend) : cont.emplace_back(tstart, tend); - slot.setContainer(std::make_unique(*mCurrentCalibObject, mMinEntries)); + slot.setContainer(std::make_unique(mMinEntries)); return slot; } -FIT_CALIBRATOR_TEMPLATES -void FIT_CALIBRATOR_TYPE::setCalibrationObject(CalibrationObjectType* calibObj) -{ - - if (!calibObj) { - throw std::runtime_error("Provided invalid calib object!"); - } - mCurrentCalibObject = calibObj; -} - -FIT_CALIBRATOR_TEMPLATES -void FIT_CALIBRATOR_TYPE::_storeCurrentCalibrationObject(const CalibrationObjectType& calibrationObject) -{ - - static std::map md; - - auto clName = o2::utils::MemFileHelper::getClassName(calibrationObject); - auto flName = o2::ccdb::CcdbApi::generateFileName(clName); - // end of validity = -1 means currentTimestamp + 1 year - mInfoVector.emplace_back(mCalibrationObjectPath, clName, flName, md, ccdb::getCurrentTimestamp(), -1); - mCalibrationObjectVector.emplace_back(calibrationObject); -} - -FIT_CALIBRATOR_TEMPLATES -void FIT_CALIBRATOR_TYPE::_doCalibrationAndUpdatedCalibrationObject(const TimeSlotStorageType& container, CalibrationObjectType& calibrationObject) -{ - FITCalibrationAlgorithmGetter::doCalibrationAndUpdateCalibrationObject(calibrationObject, container); -} - #undef FIT_CALIBRATOR_TEMPLATES #undef FIT_CALIBRATOR_TYPE diff --git a/Detectors/FIT/common/calibration/src/FITCalibrationAlgorithmGetter.cxx b/Detectors/FIT/common/calibration/src/FITCalibrationAlgorithmGetter.cxx deleted file mode 100644 index 47f3cf606983e..0000000000000 --- a/Detectors/FIT/common/calibration/src/FITCalibrationAlgorithmGetter.cxx +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -#include "FITCalibration/FITCalibrationAlgorithmGetter.h" -#include "FairLogger.h" - -using namespace o2::fit; - -template -void FITCalibrationAlgorithmGetter::doCalibrationAndUpdateCalibrationObject(CalibrationObjectType& calibrationObject, const TimeSlotContainerType& container) -{ - LOG(WARN) << "Unable to find proper calibration algorithm, object will not be modified!\n"; -} - -template <> -void FITCalibrationAlgorithmGetter::doCalibrationAndUpdateCalibrationObject(o2::ft0::FT0CalibrationObject& calibrationObject, const o2::ft0::FT0ChannelDataTimeSlotContainer& container) -{ - o2::ft0::FT0CalibrationObjectAlgorithm::calibrate(calibrationObject, container); -} diff --git a/Detectors/FIT/common/calibration/src/FITCalibrationLinkDef.h b/Detectors/FIT/common/calibration/src/FITCalibrationLinkDef.h index 6d428558168a3..025a0bcc48345 100644 --- a/Detectors/FIT/common/calibration/src/FITCalibrationLinkDef.h +++ b/Detectors/FIT/common/calibration/src/FITCalibrationLinkDef.h @@ -14,6 +14,6 @@ #pragma link off all classes; #pragma link off all functions; -#pragma link C++ class o2::calibration::TimeSlotCalibration < o2::ft0::FT0CalibrationInfoObject, o2::ft0::FT0ChannelDataTimeSlotContainer> + ; +#pragma link C++ class o2::calibration::TimeSlotCalibration < o2::ft0::FT0CalibrationInfoObject, o2::ft0::FT0ChannelTimeTimeSlotContainer> + ; #endif \ No newline at end of file From c7286ac5cce46043aa17d78092e756ab47f3c6d2 Mon Sep 17 00:00:00 2001 From: Jorge Lopez Date: Tue, 27 Apr 2021 16:07:56 +0200 Subject: [PATCH 308/770] TRD: Fix FeeParam variable initialization --- Detectors/TRD/base/src/FeeParam.cxx | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/Detectors/TRD/base/src/FeeParam.cxx b/Detectors/TRD/base/src/FeeParam.cxx index 104e93acbda15..18fbe20795341 100644 --- a/Detectors/TRD/base/src/FeeParam.cxx +++ b/Detectors/TRD/base/src/FeeParam.cxx @@ -79,14 +79,11 @@ FeeParam::FeeParam() // Default constructor // - // These variables are used internally in the class to elliminate divisions. - // putting them at the top was messy. - int j = 0; - std::for_each(mInvX.begin(), mInvX.end(), [&](float& x) { x = 1. / mX[j]; }); - j = 0; - std::for_each(mInvWidthPad.begin(), mInvWidthPad.end(), [&](float& x) { x = 1. / mWidthPad[j]; }); - j = 0; - std::for_each(mTiltingAngleTan.begin(), mTiltingAngleTan.end(), [&](float& x) { x = std::tan(mTiltingAngle[j] * M_PI / 180.0); }); + for (int j = 0; j < constants::NLAYER; ++j) { + mInvX[j] = 1. / mX[j]; + mInvWidthPad[j] = 1. / mWidthPad[j]; + mTiltingAngleTan[j] = std::tan(mTiltingAngle[j] * M_PI / 180.0); + } fillPad2MCMLookUpTable(); } From 7a6920c611c8f3e39f4cffa37f0cdc2cc494b6d4 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Thu, 29 Apr 2021 19:31:46 +0200 Subject: [PATCH 309/770] DPL: remove debug template instanciation They do not work with XCode 12.5 --- Framework/Core/src/ArrowDebugHelpers.h | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/Framework/Core/src/ArrowDebugHelpers.h b/Framework/Core/src/ArrowDebugHelpers.h index e7800e949a6da..076bcf7d9118e 100644 --- a/Framework/Core/src/ArrowDebugHelpers.h +++ b/Framework/Core/src/ArrowDebugHelpers.h @@ -10,16 +10,4 @@ #ifndef O2_FRAMEWORK_ARROWDEBUGHELPERS_H_ #define O2_FRAMEWORK_ARROWDEBUGHELPERS_H_ -// Explicit template declarations to help LLDB debug arrow related parts. - -#ifndef NDEBUG -template class std::shared_ptr; -template class std::shared_ptr; -template class std::shared_ptr; -template class std::shared_ptr; -template class std::shared_ptr; -template class std::vector>; -template class std::vector>; -#endif - #endif // O2_FRAMEWORK_ARROWDEBUGHELPERS_H_ From 4c3c3d8f0f52a1d75fa9a1332f19b72c0b8f27b9 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 29 Apr 2021 23:05:01 +0200 Subject: [PATCH 310/770] HMPID: Fix several memory errors in the raw writer --- .../simulation/include/HMPIDSimulation/HmpidCoder2.h | 7 ++++--- Detectors/HMPID/simulation/src/HmpidCoder2.cxx | 11 ++++++----- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/Detectors/HMPID/simulation/include/HMPIDSimulation/HmpidCoder2.h b/Detectors/HMPID/simulation/include/HMPIDSimulation/HmpidCoder2.h index ed17afff72365..c334281329ad1 100644 --- a/Detectors/HMPID/simulation/include/HMPIDSimulation/HmpidCoder2.h +++ b/Detectors/HMPID/simulation/include/HMPIDSimulation/HmpidCoder2.h @@ -24,6 +24,7 @@ #include #include #include +#include #include "Headers/RAWDataHeader.h" #include "CommonDataFormat/InteractionRecord.h" @@ -71,11 +72,11 @@ class HmpidCoder2 uint32_t* mPadMap; int mEventSizePerEquipment[Geo::MAXEQUIPMENTS]; int mEventPadsPerEquipment[Geo::MAXEQUIPMENTS]; - int mPailoadBufferDimPerEquipment; + int mPayloadBufferDimPerEquipment; long mPadsCoded; bool mSkipEmptyEvents; - std::unique_ptr mUPayloadBufferPtr; - std::unique_ptr mUPadMap; + std::unique_ptr mUPayloadBufferPtr; + std::unique_ptr mUPadMap; LinkSubSpec_t mTheRFWLinks[Geo::MAXEQUIPMENTS]; diff --git a/Detectors/HMPID/simulation/src/HmpidCoder2.cxx b/Detectors/HMPID/simulation/src/HmpidCoder2.cxx index ff8e88504eadb..ec2d1835e270b 100644 --- a/Detectors/HMPID/simulation/src/HmpidCoder2.cxx +++ b/Detectors/HMPID/simulation/src/HmpidCoder2.cxx @@ -40,11 +40,12 @@ HmpidCoder2::HmpidCoder2(int numOfEquipments) mNumberOfEquipments = numOfEquipments; mVerbose = 0; mSkipEmptyEvents = true; - mPailoadBufferDimPerEquipment = ((Geo::N_SEGMENTS * (Geo::N_COLXSEGMENT * (Geo::N_DILOGICS * (Geo::N_CHANNELS + 1) + 1) + 1)) + 10); - auto UPayloadBufferPtr = std::make_unique(sizeof(uint32_t) * mNumberOfEquipments * mPailoadBufferDimPerEquipment); - auto UPadMap = std::make_unique(sizeof(uint32_t) * Geo::N_HMPIDTOTALPADS); - mPayloadBufferPtr = UPayloadBufferPtr.get(); - mPadMap = UPadMap.get(); + mPayloadBufferDimPerEquipment = ((Geo::N_SEGMENTS * (Geo::N_COLXSEGMENT * (Geo::N_DILOGICS * (Geo::N_CHANNELS + 1) + 1) + 1)) + 10); + mUPayloadBufferPtr = std::make_unique(mNumberOfEquipments * mPayloadBufferDimPerEquipment); + mUPadMap = std::make_unique(Geo::N_HMPIDTOTALPADS); + mPayloadBufferPtr = mUPayloadBufferPtr.get(); + mPadMap = mUPadMap.get(); + std::memset(mPadMap, 0, sizeof(uint32_t) * Geo::N_HMPIDTOTALPADS); // Zero the map for the first event mBusyTime = 20000; // 1 milli sec mHmpidErrorFlag = 0; mHmpidFrwVersion = 9; From 3a92e96d12e92de69b6e67b8b45b9e4205d5fe74 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Fri, 30 Apr 2021 09:25:28 +0200 Subject: [PATCH 311/770] Update ArrowSupport.cxx (#6024) --- Framework/Core/src/ArrowSupport.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Framework/Core/src/ArrowSupport.cxx b/Framework/Core/src/ArrowSupport.cxx index c68ddb93c5bcf..7d5a94e845897 100644 --- a/Framework/Core/src/ArrowSupport.cxx +++ b/Framework/Core/src/ArrowSupport.cxx @@ -140,7 +140,7 @@ o2::framework::ServiceSpec ArrowSupport::arrowBackendSpec() static auto totalBytesDestroyedMetric = DeviceMetricsHelper::createNumericMetric(driverMetrics, "total-arrow-bytes-destroyed"); static auto totalMessagesCreatedMetric = DeviceMetricsHelper::createNumericMetric(driverMetrics, "total-arrow-messages-created"); static auto totalMessagesDestroyedMetric = DeviceMetricsHelper::createNumericMetric(driverMetrics, "total-arrow-messages-destroyed"); - static auto totalBytesDeltaMetric = DeviceMetricsHelper::createNumericMetric(driverMetrics, "arrow-bytes-delta"); + static auto totalBytesDeltaMetric = DeviceMetricsHelper::createNumericMetric(driverMetrics, "arrow-bytes-delta"); static auto totalSignalsMetric = DeviceMetricsHelper::createNumericMetric(driverMetrics, "aod-reader-signals"); static auto skippedSignalsMetric = DeviceMetricsHelper::createNumericMetric(driverMetrics, "aod-skipped-signals"); static auto remainingBytes = DeviceMetricsHelper::createNumericMetric(driverMetrics, "aod-remaining-bytes"); From 5637ff1c2094520fffce9b0f661431a48e9ecd48 Mon Sep 17 00:00:00 2001 From: Christoph Mayer Date: Mon, 26 Apr 2021 17:09:04 +0200 Subject: [PATCH 312/770] FV0: simulate CFD threshold and dead-time --- .../include/FV0Simulation/Digitizer.h | 19 ++-- .../include/FV0Simulation/FV0DigParam.h | 9 +- .../FIT/FV0/simulation/src/Digitizer.cxx | 97 +++++++++++-------- 3 files changed, 71 insertions(+), 54 deletions(-) diff --git a/Detectors/FIT/FV0/simulation/include/FV0Simulation/Digitizer.h b/Detectors/FIT/FV0/simulation/include/FV0Simulation/Digitizer.h index 0eba60c97bab3..be9c5ce6fceea 100644 --- a/Detectors/FIT/FV0/simulation/include/FV0Simulation/Digitizer.h +++ b/Detectors/FIT/FV0/simulation/include/FV0Simulation/Digitizer.h @@ -35,7 +35,7 @@ class Digitizer public: Digitizer() - : mTimeStamp(0), mIntRecord(), mEventId(-1), mSrcId(-1), mMCLabels(), mCache(), mPmtChargeVsTime(), mNBins(), mNTimeBinsPerBC(), mPmtResponseGlobal(), mPmtResponseTemp() + : mTimeStamp(0), mIntRecord(), mEventId(-1), mSrcId(-1), mMCLabels(), mCache(), mPmtChargeVsTime(), mNBins(), mNTimeBinsPerBC(), mPmtResponseGlobal(), mPmtResponseTemp(), mLastBCCache(), mCfdStartIndex() { } @@ -76,7 +76,7 @@ class Digitizer void clear() { for (auto& channel : mPmtChargeVsTime) { - std::fill(channel.begin(), channel.end(), 0.); + std::fill(std::begin(channel), std::end(channel), 0.); } labels.clear(); } @@ -94,10 +94,10 @@ class Digitizer void createPulse(float mipFraction, int parID, const double hitTime, std::array const& cachedIR, int nCachedIR, const int detID); - long mTimeStamp; // TF (run) timestamp + long mTimeStamp; // TF (run) timestamp InteractionTimeRecord mIntRecord; // Interaction record (orbit, bc) -> InteractionTimeRecord - Int_t mEventId; // ID of the current event - Int_t mSrcId; // signal, background or QED + Int_t mEventId; // ID of the current event + Int_t mSrcId; // signal, background or QED std::deque mMCLabels; std::deque mCache; @@ -113,17 +113,20 @@ class Digitizer std::array, Constants::nFv0Channels> mPmtChargeVsTime; // Charge time series aka analogue signal pulse from PM UInt_t mNBins; // UInt_t mNTimeBinsPerBC; - Float_t mBinSize; // Time width of the pulse bin - HPTDC resolution + Float_t mBinSize; // Time width of the pulse bin - HPTDC resolution /// vectors to store the PMT signal from cosmic muons std::vector mPmtResponseGlobal; std::vector mPmtResponseTemp; + /// for CFD + BCCache mLastBCCache; // buffer for the last BC + std::array mCfdStartIndex; // start indices for the CFD detector + /// Internal helper methods related to conversion of energy-deposition into el. signal Int_t SimulateLightYield(Int_t pmt, Int_t nPhot) const; - Float_t SimulateTimeCfd(const ChannelBCDataF& pulse) const; + Float_t SimulateTimeCfd(int& startIndex, const ChannelBCDataF& pulseLast, const ChannelBCDataF& pulse) const; Float_t IntegrateCharge(const ChannelBCDataF& pulse) const; - // Float_t SimulateTimeCfd(Int_t channel, Int_t iCache) const; /// Functions related to splitting ring-5 cell signal to two readout channels static float getDistFromCellCenter(UInt_t cellId, double hitx, double hity); diff --git a/Detectors/FIT/FV0/simulation/include/FV0Simulation/FV0DigParam.h b/Detectors/FIT/FV0/simulation/include/FV0Simulation/FV0DigParam.h index 96d9055b60d3b..6f6f047e23e61 100644 --- a/Detectors/FIT/FV0/simulation/include/FV0Simulation/FV0DigParam.h +++ b/Detectors/FIT/FV0/simulation/include/FV0Simulation/FV0DigParam.h @@ -36,16 +36,17 @@ struct FV0DigParam : public o2::conf::ConfigurableParamHelper { float timeShiftCfd = 5.3; // TODO: adjust after FV0 with FEE measurements are done float singleMipThreshold = 3.0; // in [MeV] of deposited energy float singleHitTimeThreshold = 120.0; // in [ns] to skip very slow particles - float waveformNbins = 10000; // number of bins for the analog pulse waveform - float waveformBinWidth = 0.01302; // number of bins for the analog - float avgCfdTimeForMip = 8.63; // in ns to shift the CFD time to zero TODO do ring wise + UInt_t waveformNbins = 10000; // number of bins for the analog pulse waveform + float waveformBinWidth = 0.01302; // bin width [ns] for analog pulse waveform + float avgCfdTimeForMip = 8.63; // in ns to shift the CFD time to zero TODO do ring wise int chargeIntBinMin = (avgCfdTimeForMip - 6.0) / waveformBinWidth; //Charge integration offset (cfd mean time - 6 ns) int chargeIntBinMax = (avgCfdTimeForMip + 14.0) / waveformBinWidth; //Charge integration offset (cfd mean time + 14 ns) bool isIntegrateFull = false; // Full charge integration widow in 25 ns float cfdCheckWindow = 2.5; // time window for the cfd in ns to trigger the charge integration int avgNumberPhElectronPerMip = 201; // avg number of photo-electrons per MIP float globalTimeOfFlight = 315.0 / o2::constants::physics::LightSpeedCm2NS; //TODO check the correct value for distance of FV0 to IP - + float mCFDdeadTime = 15.6; // ns + float mCFD_trsh = 3.; // [mV] ///Parameters for trigger simulation int adcChargeHighMultTh = 3.0 * 498; //threshold value of ADC charge for high multiplicity trigger diff --git a/Detectors/FIT/FV0/simulation/src/Digitizer.cxx b/Detectors/FIT/FV0/simulation/src/Digitizer.cxx index aa3559e461ad3..c4c9acaa7426c 100644 --- a/Detectors/FIT/FV0/simulation/src/Digitizer.cxx +++ b/Detectors/FIT/FV0/simulation/src/Digitizer.cxx @@ -28,6 +28,8 @@ void Digitizer::clear() for (auto& analogSignal : mPmtChargeVsTime) { std::fill_n(std::begin(analogSignal), analogSignal.size(), 0); } + mLastBCCache.clear(); + mCfdStartIndex.fill(0); } //_______________________________________________________________________ @@ -37,10 +39,11 @@ void Digitizer::init() mNBins = FV0DigParam::Instance().waveformNbins; //Will be computed using detector set-up from CDB mBinSize = FV0DigParam::Instance().waveformBinWidth; //Will be set-up from CDB - mNTimeBinsPerBC = int(o2::constants::lhc::LHCBunchSpacingNS / mBinSize); + mNTimeBinsPerBC = std::lround(o2::constants::lhc::LHCBunchSpacingNS / mBinSize); // 1920 bins/BC for (Int_t detID = 0; detID < Constants::nFv0Channels; detID++) { mPmtChargeVsTime[detID].resize(mNBins); + mLastBCCache.mPmtChargeVsTime[detID].resize(mNBins); } // set up PMT response function [avg] @@ -52,14 +55,17 @@ void Digitizer::init() FV0DigParam::Instance().shapeN); // PMT response per hit [Global] - float x = mBinSize / 2.0; /// Calculate at BinCenter + double x = mBinSize / 2.0; /// Calculate at BinCenter mPmtResponseGlobal.resize(mNBins); - for (Int_t j = 0; j < mPmtResponseGlobal.size(); ++j) { - mPmtResponseGlobal[j] = signalShapeFn.Eval(x); + for (auto& y : mPmtResponseGlobal) { + y = signalShapeFn.Eval(x); //LOG(INFO)< finished"; } @@ -76,7 +82,7 @@ void Digitizer::process(const std::vector& hits, std::iota(std::begin(hitIdx), std::end(hitIdx), 0); std::sort(std::begin(hitIdx), std::end(hitIdx), [&hits](int a, int b) { return hits[a].GetTrackID() < hits[b].GetTrackID(); }); - Int_t parentIdPrev = -10; + // use ordered hits for (auto ids : hitIdx) { const auto& hit = hits[ids]; @@ -109,14 +115,14 @@ void Digitizer::process(const std::vector& hits, } Double_t const nPhotons = hitEdep * DP::N_PHOTONS_PER_MEV; float const nPhE = SimulateLightYield(detId, nPhotons); - float mipFraction = float(nPhE / FV0DigParam::Instance().avgNumberPhElectronPerMip); + float const mipFraction = float(nPhE / FV0DigParam::Instance().avgNumberPhElectronPerMip); Float_t timeHit = hitTime; timeHit += mIntRecord.getTimeNS(); - o2::InteractionTimeRecord irHit(timeHit); + o2::InteractionTimeRecord const irHit(timeHit); std::array cachedIR; int nCachedIR = 0; for (int i = BCCacheMin; i < BCCacheMax + 1; i++) { - double tNS = timeHit + o2::constants::lhc::LHCBunchSpacingNS * i; + double const tNS = timeHit + o2::constants::lhc::LHCBunchSpacingNS * i; cachedIR[nCachedIR].setFromNS(tNS); if (tNS < 0 && cachedIR[nCachedIR] > irHit) { continue; // don't go to negative BC/orbit (it will wrap) @@ -133,10 +139,8 @@ void Digitizer::createPulse(float mipFraction, int parID, const double hitTime, std::array const& cachedIR, int nCachedIR, const int detId) { - bool added[nCachedIR]; - for (int ir = 0; ir < nCachedIR; ir++) { - added[ir] = false; - } + std::array added; + added.fill(false); for (int ir = 0; ir < NBC2Cache; ir++) { auto bcCache = getBCCache(cachedIR[ir]); @@ -146,7 +150,7 @@ void Digitizer::createPulse(float mipFraction, int parID, const double hitTime, } ///Time of flight subtracted from Hit time //TODO have different TOF according to thr ring number - Int_t NBinShift = std::lround((hitTime - FV0DigParam::Instance().globalTimeOfFlight) / FV0DigParam::Instance().waveformBinWidth); + Int_t const NBinShift = std::lround((hitTime - FV0DigParam::Instance().globalTimeOfFlight) / FV0DigParam::Instance().waveformBinWidth); if (NBinShift >= 0 && NBinShift < FV0DigParam::Instance().waveformNbins) { mPmtResponseTemp.resize(FV0DigParam::Instance().waveformNbins, 0.); @@ -180,12 +184,8 @@ void Digitizer::flush(std::vector& digitsBC, std::vector& digitsTrig, o2::dataformats::MCTruthContainer& labels) { - int nCached = mCache.size(); - if (nCached < 1) { - return; - } - for (auto bc : mCache) { - if (mIntRecord.differenceInBC(bc) > NBC2Cache) { // Build events those are separated by NBC2Cache BCs from current BC + for (auto const& bc : mCache) { + if (mIntRecord.differenceInBC(bc) > NBC2Cache) { // Build events that are separated by NBC2Cache BCs from current BC storeBC(bc, digitsBC, digitsCh, digitsTrig, labels); mCache.pop_front(); } else { @@ -201,29 +201,31 @@ void Digitizer::storeBC(const BCCache& bc, o2::dataformats::MCTruthContainer& labels) { - int first = digitsCh.size(); + size_t const first = digitsCh.size(); size_t nStored = 0; - double totalCharge = 0; double totalChargeAllRing = 0; double nSignalInner = 0; double nSignalOuter = 0; + if (mLastBCCache.differenceInBC(bc) != 1) { // if the last buffered BC is not the one before the current BC + mLastBCCache.clear(); // clear the bufffer (mPmtChargeVsTime set to 0s) + mCfdStartIndex.fill(0); // reset all start indices to 0, i.e., to the beginning of the BC + } + for (int iPmt = 0; iPmt < Constants::nFv0Channels; iPmt++) { - double cfdWithOffset = SimulateTimeCfd(bc.mPmtChargeVsTime[iPmt]); + // run the CFD: this updates the start index for the next BC in case the CFD dead time ends in the next BC + double cfdWithOffset = SimulateTimeCfd(mCfdStartIndex[iPmt], mLastBCCache.mPmtChargeVsTime[iPmt], bc.mPmtChargeVsTime[iPmt]); double cfdZero = cfdWithOffset - FV0DigParam::Instance().avgCfdTimeForMip; if (cfdZero < -FV0DigParam::Instance().cfdCheckWindow || cfdZero > FV0DigParam::Instance().cfdCheckWindow) { continue; } - float charge = IntegrateCharge(bc.mPmtChargeVsTime[iPmt]); - totalCharge += charge; - totalChargeAllRing += charge; + float totalCharge = IntegrateCharge(bc.mPmtChargeVsTime[iPmt]); + totalChargeAllRing += totalCharge; totalCharge *= DP::INV_CHARGE_PER_ADC; cfdZero *= DP::INV_TIME_PER_TDCCHANNEL; - digitsCh.emplace_back(iPmt, static_cast(std::round(cfdZero)), - static_cast(std::round(totalCharge))); - totalCharge = 0; + digitsCh.emplace_back(iPmt, std::lround(cfdZero), std::lround(totalCharge)); ++nStored; //---trigger--- if (iPmt < 25) { @@ -232,6 +234,8 @@ void Digitizer::storeBC(const BCCache& bc, nSignalOuter++; } } + // save BC information for the CFD detector + mLastBCCache = bc; if (nStored < 1) { return; } @@ -249,8 +253,8 @@ void Digitizer::storeBC(const BCCache& bc, triggers.setTriggers(isMinBias, isMinBiasInner, isMinBiasOuter, isHighMult, isDummy, nStored, totalChargeAllRing); digitsBC.emplace_back(first, nStored, bc, triggers); digitsTrig.emplace_back(bc, isMinBias, isMinBiasInner, isMinBiasOuter, isHighMult, isDummy); - int nBC = digitsBC.size(); - for (const auto& lbl : bc.labels) { + size_t const nBC = digitsBC.size(); + for (auto const& lbl : bc.labels) { labels.addElement(nBC, lbl); } } @@ -274,8 +278,8 @@ Int_t Digitizer::SimulateLightYield(Int_t pmt, Int_t nPhot) const //--------------------------------------------------------------------------- Float_t Digitizer::IntegrateCharge(const ChannelBCDataF& pulse) const { - int chargeIntMin = FV0DigParam::Instance().isIntegrateFull ? 0 : FV0DigParam::Instance().chargeIntBinMin; - int chargeIntMax = FV0DigParam::Instance().isIntegrateFull ? mNTimeBinsPerBC : FV0DigParam::Instance().chargeIntBinMax; + int const chargeIntMin = FV0DigParam::Instance().isIntegrateFull ? 0 : FV0DigParam::Instance().chargeIntBinMin; + int const chargeIntMax = FV0DigParam::Instance().isIntegrateFull ? mNTimeBinsPerBC : FV0DigParam::Instance().chargeIntBinMax; Float_t totalCharge = 0.0f; for (int iTimeBin = chargeIntMin; iTimeBin < chargeIntMax; iTimeBin++) { @@ -286,23 +290,32 @@ Float_t Digitizer::IntegrateCharge(const ChannelBCDataF& pulse) const return totalCharge; } //--------------------------------------------------------------------------- -Float_t Digitizer::SimulateTimeCfd(/*Int_t channel, */ const ChannelBCDataF& pulse) const +Float_t Digitizer::SimulateTimeCfd(int& startIndex, const ChannelBCDataF& pulseLast, const ChannelBCDataF& pulse) const { Float_t timeCfd = -1024.0f; - //auto& bc= mCache[iCache]; - if (pulse.empty()) { + startIndex = 0; return timeCfd; } + Float_t const cfdThrInCoulomb = FV0DigParam::Instance().mCFD_trsh * 1e-3 / 50 * mBinSize * 1e-9; // convert mV into Coulomb assuming 50 Ohm + Int_t const binShift = TMath::Nint(FV0DigParam::Instance().timeShiftCfd / mBinSize); - Float_t sigPrev = -pulse[0]; //[0]; - for (Int_t iTimeBin = 1; iTimeBin < mNTimeBinsPerBC; ++iTimeBin) { - Float_t const sigCurrent = (iTimeBin >= binShift ? 5.0f * pulse[iTimeBin - binShift] - pulse[iTimeBin] : -pulse[iTimeBin]); - if (sigPrev < 0.0f && sigCurrent >= 0.0f) { - timeCfd = Float_t(iTimeBin) * mBinSize; - break; + Float_t sigPrev = 5 * pulseLast[mNTimeBinsPerBC - binShift - 1] - pulseLast[mNTimeBinsPerBC - 1]; // CFD output from the last bin of the last BC + for (Int_t iTimeBin = 0; iTimeBin < mNTimeBinsPerBC; ++iTimeBin) { + Float_t const sigCurrent = 5.0f * (iTimeBin >= binShift ? pulse[iTimeBin - binShift] : pulseLast[mNTimeBinsPerBC - binShift + iTimeBin]) - pulse[iTimeBin]; + if (iTimeBin >= startIndex && std::abs(pulse[iTimeBin]) > cfdThrInCoulomb) { // enable + if (sigPrev < 0.0f && sigCurrent >= 0.0f) { // test for zero-crossing + timeCfd = Float_t(iTimeBin) * mBinSize; + startIndex = iTimeBin + std::lround(FV0DigParam::Instance().mCFDdeadTime / mBinSize); // update startIndex (CFD dead time) + if (startIndex < mNTimeBinsPerBC) { + startIndex = 0; // dead-time ends in same BC: no impact on the following BC + } else { + startIndex -= mNTimeBinsPerBC; + } + break; // only detects the 1st zero-crossing in the BC + } } sigPrev = sigCurrent; } @@ -326,7 +339,7 @@ float Digitizer::getDistFromCellCenter(UInt_t cellId, double hitx, double hity) float Digitizer::getSignalFraction(float distanceFromXc, bool isFirstChannel) { - float fraction = sigmoidPmtRing5(distanceFromXc); + float const fraction = sigmoidPmtRing5(distanceFromXc); if (distanceFromXc > 0) { return isFirstChannel ? fraction : (1. - fraction); } else { From 4ac1d3acdf4836c56065fea69fcb0f6d0c94481f Mon Sep 17 00:00:00 2001 From: Christoph Mayer Date: Mon, 26 Apr 2021 17:27:28 +0200 Subject: [PATCH 313/770] FV0: clang-format (using O2 clang) --- .../include/FV0Simulation/FV0DigParam.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Detectors/FIT/FV0/simulation/include/FV0Simulation/FV0DigParam.h b/Detectors/FIT/FV0/simulation/include/FV0Simulation/FV0DigParam.h index 6f6f047e23e61..4059c4d579d09 100644 --- a/Detectors/FIT/FV0/simulation/include/FV0Simulation/FV0DigParam.h +++ b/Detectors/FIT/FV0/simulation/include/FV0Simulation/FV0DigParam.h @@ -33,20 +33,20 @@ struct FV0DigParam : public o2::conf::ConfigurableParamHelper { float shapeN = 2.36408e+00; // Crystal ball N parameter float shapeSigma = 3.55445; // Crystal ball sigma parameter //float timeShiftCfd = 3.3; // From the cosmic measurements of FV0 [keep it for reference] - float timeShiftCfd = 5.3; // TODO: adjust after FV0 with FEE measurements are done - float singleMipThreshold = 3.0; // in [MeV] of deposited energy - float singleHitTimeThreshold = 120.0; // in [ns] to skip very slow particles - UInt_t waveformNbins = 10000; // number of bins for the analog pulse waveform - float waveformBinWidth = 0.01302; // bin width [ns] for analog pulse waveform - float avgCfdTimeForMip = 8.63; // in ns to shift the CFD time to zero TODO do ring wise + float timeShiftCfd = 5.3; // TODO: adjust after FV0 with FEE measurements are done + float singleMipThreshold = 3.0; // in [MeV] of deposited energy + float singleHitTimeThreshold = 120.0; // in [ns] to skip very slow particles + UInt_t waveformNbins = 10000; // number of bins for the analog pulse waveform + float waveformBinWidth = 0.01302; // bin width [ns] for analog pulse waveform + float avgCfdTimeForMip = 8.63; // in ns to shift the CFD time to zero TODO do ring wise int chargeIntBinMin = (avgCfdTimeForMip - 6.0) / waveformBinWidth; //Charge integration offset (cfd mean time - 6 ns) int chargeIntBinMax = (avgCfdTimeForMip + 14.0) / waveformBinWidth; //Charge integration offset (cfd mean time + 14 ns) bool isIntegrateFull = false; // Full charge integration widow in 25 ns float cfdCheckWindow = 2.5; // time window for the cfd in ns to trigger the charge integration int avgNumberPhElectronPerMip = 201; // avg number of photo-electrons per MIP float globalTimeOfFlight = 315.0 / o2::constants::physics::LightSpeedCm2NS; //TODO check the correct value for distance of FV0 to IP - float mCFDdeadTime = 15.6; // ns - float mCFD_trsh = 3.; // [mV] + float mCFDdeadTime = 15.6; // ns + float mCFD_trsh = 3.; // [mV] ///Parameters for trigger simulation int adcChargeHighMultTh = 3.0 * 498; //threshold value of ADC charge for high multiplicity trigger From 0aead5a77e634e7c29d3c493d0dc7baeed0a5124 Mon Sep 17 00:00:00 2001 From: Christoph Mayer Date: Tue, 27 Apr 2021 11:12:38 +0200 Subject: [PATCH 314/770] FV0: fix MC label index bug (mslupeck) --- Detectors/FIT/FV0/simulation/src/Digitizer.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Detectors/FIT/FV0/simulation/src/Digitizer.cxx b/Detectors/FIT/FV0/simulation/src/Digitizer.cxx index c4c9acaa7426c..1655038587319 100644 --- a/Detectors/FIT/FV0/simulation/src/Digitizer.cxx +++ b/Detectors/FIT/FV0/simulation/src/Digitizer.cxx @@ -201,7 +201,8 @@ void Digitizer::storeBC(const BCCache& bc, o2::dataformats::MCTruthContainer& labels) { - size_t const first = digitsCh.size(); + size_t const nBC = digitsBC.size(); // save before digitsBC is being modified + size_t const first = digitsCh.size(); // save before digitsCh is being modified size_t nStored = 0; double totalChargeAllRing = 0; double nSignalInner = 0; @@ -253,7 +254,6 @@ void Digitizer::storeBC(const BCCache& bc, triggers.setTriggers(isMinBias, isMinBiasInner, isMinBiasOuter, isHighMult, isDummy, nStored, totalChargeAllRing); digitsBC.emplace_back(first, nStored, bc, triggers); digitsTrig.emplace_back(bc, isMinBias, isMinBiasInner, isMinBiasOuter, isHighMult, isDummy); - size_t const nBC = digitsBC.size(); for (auto const& lbl : bc.labels) { labels.addElement(nBC, lbl); } From eeef72abd22e5a237042adf69697af9afb3daa99 Mon Sep 17 00:00:00 2001 From: Christoph Mayer Date: Thu, 29 Apr 2021 17:33:49 +0200 Subject: [PATCH 315/770] FV0: avoid calculations for FV0DigiParam default values --- .../FIT/FV0/base/include/FV0Base/Geometry.h | 4 ++-- .../include/FV0Simulation/FV0DigParam.h | 22 +++++++++---------- .../FIT/FV0/simulation/src/Digitizer.cxx | 14 +++++++----- 3 files changed, 21 insertions(+), 19 deletions(-) diff --git a/Detectors/FIT/FV0/base/include/FV0Base/Geometry.h b/Detectors/FIT/FV0/base/include/FV0Base/Geometry.h index c659c0c47c621..c0cb9403ad874 100644 --- a/Detectors/FIT/FV0/base/include/FV0Base/Geometry.h +++ b/Detectors/FIT/FV0/base/include/FV0Base/Geometry.h @@ -138,8 +138,8 @@ class Geometry static constexpr float sDzHalvesSeparation = 0; ///< z-position of the right detector part relative to the left part /// Cell and scintillator constants - static constexpr int sNumberOfCellSectors = 4; ///< Number of cell sectors for one half of the detector - static constexpr int sNumberOfCellRings = 5; ///< Number of cell rings + static constexpr int sNumberOfCellSectors = 4; ///< Number of cell sectors for one half of the detector + static constexpr int sNumberOfCellRings = 5; ///< Number of cell rings static constexpr int sNumberOfCells = sNumberOfCellRings * sNumberOfCellSectors * 2; ///< Number of cells static constexpr int sNumberOfReadoutChannels = sNumberOfCells + sNumberOfCellSectors * 2; ///< Number of ch (2 ch per cell in r5) diff --git a/Detectors/FIT/FV0/simulation/include/FV0Simulation/FV0DigParam.h b/Detectors/FIT/FV0/simulation/include/FV0Simulation/FV0DigParam.h index 4059c4d579d09..c0c90c0b784b4 100644 --- a/Detectors/FIT/FV0/simulation/include/FV0Simulation/FV0DigParam.h +++ b/Detectors/FIT/FV0/simulation/include/FV0Simulation/FV0DigParam.h @@ -21,17 +21,17 @@ namespace fv0 { // parameters of FV0 digitization / transport simulation struct FV0DigParam : public o2::conf::ConfigurableParamHelper { - float intrinsicTimeRes = 0.91; // time resolution + // NOTUSED float intrinsicTimeRes = 0.91; // time resolution float photoCathodeEfficiency = 0.23; // quantum efficiency = nOfPhotoE_emitted_by_photocathode / nIncidentPhotons float lightYield = 0.01; // light collection efficiency to be tuned using collision data [1%] - float pmtGain = 5e4; // value for PMT R5924-70 at default FV0 gain - float pmtTransitTime = 9.5; // PMT response time (corresponds to 1.9 ns rise time) - float pmtTransparency = 0.25; // Transparency of the first dynode of the PMT - float shapeConst = 1.18059e-14; // Crystal ball const parameter - float shapeMean = 9.5; // Crystal ball mean parameter - float shapeAlpha = -6.56586e-01; // Crystal ball alpha parameter - float shapeN = 2.36408e+00; // Crystal ball N parameter - float shapeSigma = 3.55445; // Crystal ball sigma parameter + // NOTUSED float pmtGain = 5e4; // value for PMT R5924-70 at default FV0 gain + // NOTUSED float pmtTransitTime = 9.5; // PMT response time (corresponds to 1.9 ns rise time) + // NOTUSED float pmtTransparency = 0.25; // Transparency of the first dynode of the PMT + float shapeConst = 1.18059e-14; // Crystal ball const parameter + float shapeMean = 9.5; // Crystal ball mean parameter + float shapeAlpha = -6.56586e-01; // Crystal ball alpha parameter + float shapeN = 2.36408e+00; // Crystal ball N parameter + float shapeSigma = 3.55445; // Crystal ball sigma parameter //float timeShiftCfd = 3.3; // From the cosmic measurements of FV0 [keep it for reference] float timeShiftCfd = 5.3; // TODO: adjust after FV0 with FEE measurements are done float singleMipThreshold = 3.0; // in [MeV] of deposited energy @@ -39,8 +39,6 @@ struct FV0DigParam : public o2::conf::ConfigurableParamHelper { UInt_t waveformNbins = 10000; // number of bins for the analog pulse waveform float waveformBinWidth = 0.01302; // bin width [ns] for analog pulse waveform float avgCfdTimeForMip = 8.63; // in ns to shift the CFD time to zero TODO do ring wise - int chargeIntBinMin = (avgCfdTimeForMip - 6.0) / waveformBinWidth; //Charge integration offset (cfd mean time - 6 ns) - int chargeIntBinMax = (avgCfdTimeForMip + 14.0) / waveformBinWidth; //Charge integration offset (cfd mean time + 14 ns) bool isIntegrateFull = false; // Full charge integration widow in 25 ns float cfdCheckWindow = 2.5; // time window for the cfd in ns to trigger the charge integration int avgNumberPhElectronPerMip = 201; // avg number of photo-electrons per MIP @@ -48,7 +46,7 @@ struct FV0DigParam : public o2::conf::ConfigurableParamHelper { float mCFDdeadTime = 15.6; // ns float mCFD_trsh = 3.; // [mV] ///Parameters for trigger simulation - int adcChargeHighMultTh = 3.0 * 498; //threshold value of ADC charge for high multiplicity trigger + int adcChargeHighMultTh = 3 * 498; //threshold value of ADC charge for high multiplicity trigger O2ParamDef(FV0DigParam, "FV0DigParam"); }; diff --git a/Detectors/FIT/FV0/simulation/src/Digitizer.cxx b/Detectors/FIT/FV0/simulation/src/Digitizer.cxx index 1655038587319..cbe4a47fe4b3a 100644 --- a/Detectors/FIT/FV0/simulation/src/Digitizer.cxx +++ b/Detectors/FIT/FV0/simulation/src/Digitizer.cxx @@ -278,14 +278,15 @@ Int_t Digitizer::SimulateLightYield(Int_t pmt, Int_t nPhot) const //--------------------------------------------------------------------------- Float_t Digitizer::IntegrateCharge(const ChannelBCDataF& pulse) const { - int const chargeIntMin = FV0DigParam::Instance().isIntegrateFull ? 0 : FV0DigParam::Instance().chargeIntBinMin; - int const chargeIntMax = FV0DigParam::Instance().isIntegrateFull ? mNTimeBinsPerBC : FV0DigParam::Instance().chargeIntBinMax; + int const chargeIntMin = FV0DigParam::Instance().isIntegrateFull ? 0 : (FV0DigParam::Instance().avgCfdTimeForMip - 6.0) / mBinSize; //Charge integration offset (cfd mean time - 6 ns) + int const chargeIntMax = FV0DigParam::Instance().isIntegrateFull ? mNTimeBinsPerBC : (FV0DigParam::Instance().avgCfdTimeForMip + 14.0) / mBinSize; //Charge integration offset (cfd mean time + 14 ns) + if (chargeIntMin < 0 || chargeIntMin > mNTimeBinsPerBC || chargeIntMax > mNTimeBinsPerBC) { + LOG(FATAL) << "invalid indicess: chargeInMin=" << chargeIntMin << " chargeIntMax=" << chargeIntMax; + } Float_t totalCharge = 0.0f; for (int iTimeBin = chargeIntMin; iTimeBin < chargeIntMax; iTimeBin++) { - Float_t const timeBinCharge = pulse[iTimeBin]; - //LOG(INFO)< mNTimeBinsPerBC) { + LOG(FATAL) << "CFD dead-time was set to > 25 ns"; + } break; // only detects the 1st zero-crossing in the BC } } From 25c7713d4d433cae934526a90af750312dd2362d Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 28 Apr 2021 22:54:13 +0200 Subject: [PATCH 316/770] GPU DPL Display: add missing header --- GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx | 1 + 1 file changed, 1 insertion(+) diff --git a/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx index 2799b4183b42e..91c4faeec8812 100644 --- a/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx +++ b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx @@ -17,6 +17,7 @@ #include "GPUO2InterfaceDisplay.h" #include "GPUDisplayBackend.h" #include "GPUDisplayBackendGlfw.h" +#include using namespace o2::gpu; using namespace o2::tpc; From 70ecec615595fde0e134595389b4bcea48e62787 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 28 Apr 2021 19:38:24 +0200 Subject: [PATCH 317/770] GPU: Add GPUCommonTypeTraits.h header to provide some simple type traits functionality on GPU --- GPU/Common/CMakeLists.txt | 1 + GPU/Common/GPUCommonArray.h | 4 +-- GPU/Common/GPUCommonTypeTraits.h | 46 ++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 GPU/Common/GPUCommonTypeTraits.h diff --git a/GPU/Common/CMakeLists.txt b/GPU/Common/CMakeLists.txt index 497b90fe12361..0c56ec4221d53 100644 --- a/GPU/Common/CMakeLists.txt +++ b/GPU/Common/CMakeLists.txt @@ -19,6 +19,7 @@ set(HDRS_INSTALL GPUCommonMath.h GPUCommonRtypes.h GPUCommonArray.h + GPUCommonTypeTraits.h GPUCommonTransform3D.h GPUROOTSMatrixFwd.h GPUROOTCartesianFwd.h) diff --git a/GPU/Common/GPUCommonArray.h b/GPU/Common/GPUCommonArray.h index c93e1be99510b..6a1b5222800f3 100644 --- a/GPU/Common/GPUCommonArray.h +++ b/GPU/Common/GPUCommonArray.h @@ -11,8 +11,8 @@ /// \file GPUCommonArray.h /// \author David Rohr -#ifndef GPUCOMMONFAIRARRAY_H -#define GPUCOMMONFAIRARRAY_H +#ifndef GPUCOMMONARRAY_H +#define GPUCOMMONARRAY_H #ifndef GPUCA_GPUCODE_DEVICE #include diff --git a/GPU/Common/GPUCommonTypeTraits.h b/GPU/Common/GPUCommonTypeTraits.h new file mode 100644 index 0000000000000..2c34e9e2d8e95 --- /dev/null +++ b/GPU/Common/GPUCommonTypeTraits.h @@ -0,0 +1,46 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file GPUCommonTypeTraits.h +/// \author David Rohr + +#ifndef GPUCOMMONTYPETRAITS_H +#define GPUCOMMONTYPETRAITS_H + +#if !defined(GPUCA_GPUCODE_DEVICE) || defined(__CUDACC__) || defined(__HIPCC__) +#include +#elif !defined(__OPENCL__) || defined(__OPENCLCPP__) +// We just reimplement some type traits in std for the GPU +namespace std +{ +template +struct conditional { + typedef T type; +}; +template +struct conditional { + typedef F type; +}; +template +using contitional_t = typename conditional::type; +template +struct is_same { + static constexpr bool value = false; +}; +template +struct is_same { + static constexpr bool value = true; +}; +template +static constexpr bool is_same_v = is_same::value; +} // namespace std +#endif + +#endif From 171223037bfe8f55dbbaa38dadf80729e7b98c09 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 28 Apr 2021 23:44:06 +0200 Subject: [PATCH 318/770] GPU: Add std::bitset reimplementation to GPUCommon --- GPU/Utils/CMakeLists.txt | 4 +- GPU/Utils/GPUCommonBitSet.h | 108 ++++++++++++++++++++++++++++++++++++ GPU/Utils/GPUUtilsLinkDef.h | 32 +++++++++++ 3 files changed, 143 insertions(+), 1 deletion(-) create mode 100644 GPU/Utils/GPUCommonBitSet.h diff --git a/GPU/Utils/CMakeLists.txt b/GPU/Utils/CMakeLists.txt index 7420801222ff3..a5aacd93b801f 100644 --- a/GPU/Utils/CMakeLists.txt +++ b/GPU/Utils/CMakeLists.txt @@ -10,7 +10,9 @@ set(MODULE GPUUtils) -set(HDRS_CINT FlatObject.h) +set(HDRS_CINT FlatObject.h + GPUCommonBitSet.h +) set(HDRS_INSTALL ) diff --git a/GPU/Utils/GPUCommonBitSet.h b/GPU/Utils/GPUCommonBitSet.h new file mode 100644 index 0000000000000..44369e0c78372 --- /dev/null +++ b/GPU/Utils/GPUCommonBitSet.h @@ -0,0 +1,108 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file GPUCommonBitSet.h +/// \author David Rohr + +#ifndef GPUCOMMONBITSET_H +#define GPUCOMMONBITSET_H + +// Limited reimplementation of std::bitset for the GPU. +// Fixed to 32 bits for now. +// In contrast to the GPUCommonArray, we cannot just use std::bitset on the host. +// The layout may be implementation defined, so it is not guarantueed that we +// get correct data after copying it into a gpustd::bitset on the GPU. + +#include "GPUCommonDef.h" +#include "GPUCommonRtypes.h" +#ifndef GPUCA_GPUCODE_DEVICE +#include +#endif + +namespace o2::gpu::gpustd +{ +template +class bitset +{ + static_assert(N <= 32, "> 32 bits not supported"); + + public: + GPUdDefault() constexpr bitset() = default; + GPUdDefault() constexpr bitset(const bitset&) = default; + GPUd() constexpr bitset(unsigned int vv) : v(vv){}; + static constexpr unsigned int full_set = ((1ul << N) - 1ul); + + GPUd() constexpr bool all() const { return (v & full_set) == full_set; } + GPUd() constexpr bool any() const { return v & full_set; } + GPUd() constexpr bool none() const { return !any(); } + + GPUd() constexpr void set() { v = full_set; } + GPUd() constexpr void set(unsigned int i) { v |= (1u << i) & full_set; } + GPUd() constexpr void reset() { v = 0; } + GPUd() constexpr void reset(unsigned int i) { v &= ~(1u << i); } + GPUd() constexpr void flip() { v = (~v) & full_set; } + + GPUdDefault() constexpr bitset& operator=(const bitset&) = default; + GPUd() constexpr bitset operator|(const bitset b) const { return v | b.v; } + GPUd() constexpr bitset& operator|=(const bitset b) + { + v |= b.v; + return *this; + } + GPUd() constexpr bitset operator&(const bitset b) const { return v & b.v; } + GPUd() constexpr bitset& operator&=(const bitset b) + { + v &= b.v; + return *this; + } + GPUd() constexpr bitset operator^(const bitset b) const { return v ^ b.v; } + GPUd() constexpr bitset& operator^=(const bitset b) + { + v ^= b.v; + return *this; + } + GPUd() constexpr bitset operator~() const { return (~v) & full_set; } + GPUd() constexpr bool operator==(const bitset b) { return v == b.v; } + GPUd() constexpr bool operator!=(const bitset b) { return v != b.v; } + + GPUd() constexpr bool operator[](unsigned int i) const { return (v >> i) & 1u; } + + GPUd() constexpr unsigned int to_ulong() const { return v; } +#ifndef GPUCA_GPUCODE_DEVICE + std::string to_string() const; +#endif + + private: + unsigned int v = 0; + + ClassDefNV(bitset, 1); +}; + +#ifndef GPUCA_GPUCODE_DEVICE +template +inline std::string bitset::to_string() const +{ + std::string retVal; + for (unsigned int i = 0; i < N; i++) { + retVal += std::to_string((int)((*this)[i])); + } + return retVal; +} +template +std::basic_ostream& operator<<(std::basic_ostream& os, const bitset& x) +{ + os << x.to_string(); + return os; +} + +#endif +} // namespace o2::gpu::gpustd + +#endif diff --git a/GPU/Utils/GPUUtilsLinkDef.h b/GPU/Utils/GPUUtilsLinkDef.h index b348375c78dd3..15a011907df05 100644 --- a/GPU/Utils/GPUUtilsLinkDef.h +++ b/GPU/Utils/GPUUtilsLinkDef.h @@ -18,5 +18,37 @@ #pragma link off all functions; #pragma link C++ class o2::gpu::FlatObject + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 1> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 2> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 3> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 4> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 5> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 6> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 7> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 8> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 9> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 10> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 11> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 12> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 13> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 14> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 15> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 16> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 17> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 18> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 19> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 20> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 21> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 22> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 23> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 24> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 25> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 26> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 27> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 28> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 29> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 30> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 31> + ; +#pragma link C++ class o2::gpu::gpustd::bitset < 32> + ; #endif From 896ed5c78141f094085845cb2ab5ec8f1cbf26d1 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 28 Apr 2021 18:42:44 +0200 Subject: [PATCH 319/770] GPU: Adapt DetID and GlobalTrackID for GPU usage --- DataFormats/Detectors/Common/CMakeLists.txt | 1 + .../DetectorsCommonDataFormats/DetID.h | 91 +++++++++++------- DataFormats/Detectors/Common/src/DetID.cxx | 1 - .../include/DataFormatsParameters/GRPObject.h | 2 +- DataFormats/Reconstruction/CMakeLists.txt | 1 + .../ReconstructionDataFormats/GlobalTrackID.h | 93 +++++++++++++++---- .../Reconstruction/src/GlobalTrackID.cxx | 37 +------- .../include/CommonDataFormat/AbstractRef.h | 49 +++++----- 8 files changed, 160 insertions(+), 115 deletions(-) diff --git a/DataFormats/Detectors/Common/CMakeLists.txt b/DataFormats/Detectors/Common/CMakeLists.txt index f4a7b7d029a0a..cb2f164048fd3 100644 --- a/DataFormats/Detectors/Common/CMakeLists.txt +++ b/DataFormats/Detectors/Common/CMakeLists.txt @@ -17,6 +17,7 @@ o2_add_library(DetectorsCommonDataFormats ROOT::Core ROOT::Geom O2::GPUCommon + O2::GPUUtils O2::MathUtils O2::FrameworkLogger O2::Headers diff --git a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h index 277f9b6e10c63..41a1bf265371f 100644 --- a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h +++ b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h @@ -27,7 +27,11 @@ #ifndef O2_BASE_DETID_ #define O2_BASE_DETID_ -#include +#include "GPUCommonRtypes.h" +#include "GPUCommonBitSet.h" +#include "MathUtils/Utils.h" +#ifndef GPUCA_GPUCODE_DEVICE +#include "Headers/DataHeader.h" #include #include #include @@ -35,11 +39,13 @@ #include #include #include -#include "MathUtils/Utils.h" -#include "Headers/DataHeader.h" +#endif namespace o2 { +namespace header +{ +} namespace detectors { @@ -50,7 +56,7 @@ class DetID { public: /// Detector identifiers: continuous, starting from 0 - typedef std::int32_t ID; + typedef int ID; static constexpr ID ITS = 0; static constexpr ID TPC = 1; @@ -80,35 +86,43 @@ class DetID static constexpr ID First = ITS; static constexpr int nDetectors = Last + 1; ///< number of defined detectors + typedef o2::gpu::gpustd::bitset<32> mask_t; +#ifndef GPUCA_GPUCODE_DEVICE static constexpr std::string_view NONE{"none"}; ///< keywork for no-detector static constexpr std::string_view ALL{"all"}; ///< keywork for all detectors +#endif // GPUCA_GPUCODE_DEVICE - typedef std::bitset<32> mask_t; - - DetID(ID id) : mID(id) {} + GPUdi() DetID(ID id) : mID(id) + { + } DetID(const char* name); - DetID(const DetID& src) = default; - DetID& operator=(const DetID& src) = default; + GPUdDefault() DetID(const DetID& src) = default; + GPUdDefault() DetID& operator=(const DetID& src) = default; + // we need default c-tor only for root persistency, code must use c-tor with argument + DetID() : mID(First) {} /// get derector id - ID getID() const { return mID; } + GPUdi() ID getID() const { return mID; } /// get detector mask - mask_t getMask() const { return getMask(mID); } - /// get detector mask - o2h::DataOrigin getDataOrigin() const { return getDataOrigin(mID); } + GPUdi() mask_t getMask() const { return getMask(mID); } +#ifndef GPUCA_GPUCODE_DEVICE + /// get detector origin + GPUdi() o2h::DataOrigin getDataOrigin() const { return getDataOrigin(mID); } /// get detector name const char* getName() const { return getName(mID); } +#endif // GPUCA_GPUCODE_DEVICE /// conversion operator to int - operator int() const { return static_cast(mID); } + GPUdi() operator int() const { return static_cast(mID); } // ---------------- general static methods ----------------- /// get number of defined detectors - static constexpr int getNDetectors() { return nDetectors; } + GPUdi() static constexpr int getNDetectors() { return nDetectors; } + // detector ID to mask conversion + GPUd() static constexpr mask_t getMask(ID id); +#ifndef GPUCA_GPUCODE_DEVICE /// names of defined detectors static constexpr const char* getName(ID id) { return sDetNames[id]; } - // detector ID to mask conversion - static constexpr mask_t getMask(ID id) { return sMasks[id]; } // detector ID to DataOrigin conversions static constexpr o2h::DataOrigin getDataOrigin(ID id) { return sOrigins[id]; } @@ -116,41 +130,30 @@ class DetID static mask_t getMask(const std::string_view detList); static std::string getNames(mask_t mask, char delimiter = ','); - - // we need default c-tor only for root persistency, code must use c-tor with argument - DetID() : mID(First) {} +#endif // GPUCA_GPUCODE_DEVICE private: // are 2 strings equal ? (trick from Giulio) - inline static constexpr bool sameStr(char const* x, char const* y) + GPUdi() static constexpr bool sameStr(char const* x, char const* y) { return !*x && !*y ? true : /* default */ (*x == *y && sameStr(x + 1, y + 1)); } + ID mID = First; ///< detector ID + +#ifndef GPUCA_GPUCODE_DEVICE inline static constexpr int nameToID(char const* name, int id) { return id > Last ? id : sameStr(name, sDetNames[id]) ? id : nameToID(name, id + 1); } - ID mID = First; ///< detector ID - + // detector names, will be defined in DataSources static constexpr const char* sDetNames[nDetectors + 1] = ///< defined detector names #ifdef ENABLE_UPGRADES {"ITS", "TPC", "TRD", "TOF", "PHS", "CPV", "EMC", "HMP", "MFT", "MCH", "MID", "ZDC", "FT0", "FV0", "FDD", "ACO", "CTP", "IT3", "TRK", "FT3", nullptr}; #else {"ITS", "TPC", "TRD", "TOF", "PHS", "CPV", "EMC", "HMP", "MFT", "MCH", "MID", "ZDC", "FT0", "FV0", "FDD", "ACO", "CTP", nullptr}; #endif - // detector names, will be defined in DataSources - static constexpr std::array sMasks = ///< detectot masks - {math_utils::bit2Mask(ITS), math_utils::bit2Mask(TPC), math_utils::bit2Mask(TRD), math_utils::bit2Mask(TOF), math_utils::bit2Mask(PHS), - math_utils::bit2Mask(CPV), math_utils::bit2Mask(EMC), math_utils::bit2Mask(HMP), math_utils::bit2Mask(MFT), math_utils::bit2Mask(MCH), - math_utils::bit2Mask(MID), math_utils::bit2Mask(ZDC), math_utils::bit2Mask(FT0), math_utils::bit2Mask(FV0), math_utils::bit2Mask(FDD), - math_utils::bit2Mask(ACO) -#ifdef ENABLE_UPGRADES - , - math_utils::bit2Mask(IT3), math_utils::bit2Mask(TRK), math_utils::bit2Mask(FT3) -#endif - }; static constexpr std::array sOrigins = ///< detector data origins @@ -163,9 +166,27 @@ class DetID o2h::gDataOriginIT3, o2h::gDataOriginTRK, o2h::gDataOriginFT3 #endif }; +#endif // GPUCA_GPUCODE_DEVICE + + ClassDefNV(DetID, 3); +}; - ClassDefNV(DetID, 2); +namespace detid_internal +{ +// static constexpr array class members not possible on the GPU, thus we use this trick. +GPUconstexpr() DetID::mask_t sMasks[DetID::nDetectors] = ///< detectot masks + {math_utils::bit2Mask(DetID::ITS), math_utils::bit2Mask(DetID::TPC), math_utils::bit2Mask(DetID::TRD), math_utils::bit2Mask(DetID::TOF), math_utils::bit2Mask(DetID::PHS), + math_utils::bit2Mask(DetID::CPV), math_utils::bit2Mask(DetID::EMC), math_utils::bit2Mask(DetID::HMP), math_utils::bit2Mask(DetID::MFT), math_utils::bit2Mask(DetID::MCH), + math_utils::bit2Mask(DetID::MID), math_utils::bit2Mask(DetID::ZDC), math_utils::bit2Mask(DetID::FT0), math_utils::bit2Mask(DetID::FV0), math_utils::bit2Mask(DetID::FDD), + math_utils::bit2Mask(DetID::ACO) +#ifdef ENABLE_UPGRADES + , + math_utils::bit2Mask(DetID::IT3), math_utils::bit2Mask(DetID::TRK), math_utils::bit2Mask(DetID::FT3) +#endif }; +} // namespace detid_internal + +GPUdi() constexpr DetID::mask_t DetID::getMask(ID id) { return detid_internal::sMasks[id]; } } // namespace detectors } // namespace o2 diff --git a/DataFormats/Detectors/Common/src/DetID.cxx b/DataFormats/Detectors/Common/src/DetID.cxx index a9834373c619f..bd442509c5902 100644 --- a/DataFormats/Detectors/Common/src/DetID.cxx +++ b/DataFormats/Detectors/Common/src/DetID.cxx @@ -22,7 +22,6 @@ using namespace o2::detectors; ClassImp(o2::detectors::DetID); constexpr const char* DetID::sDetNames[DetID::nDetectors + 1]; -constexpr std::array DetID::sMasks; // redundant declarations constexpr DetID::ID DetID::ITS, DetID::TPC, DetID::TRD, DetID::TOF, DetID::PHS, DetID::CPV, DetID::EMC, diff --git a/DataFormats/Parameters/include/DataFormatsParameters/GRPObject.h b/DataFormats/Parameters/include/DataFormatsParameters/GRPObject.h index a8e7e2142590b..d0ec0ac9e7651 100644 --- a/DataFormats/Parameters/include/DataFormatsParameters/GRPObject.h +++ b/DataFormats/Parameters/include/DataFormatsParameters/GRPObject.h @@ -164,7 +164,7 @@ class GRPObject std::string mDataPeriod = ""; ///< name of the period std::string mLHCState = ""; ///< machine state - ClassDefNV(GRPObject, 4); + ClassDefNV(GRPObject, 5); }; //______________________________________________ diff --git a/DataFormats/Reconstruction/CMakeLists.txt b/DataFormats/Reconstruction/CMakeLists.txt index eb680835a89bc..be3d16c7bd867 100644 --- a/DataFormats/Reconstruction/CMakeLists.txt +++ b/DataFormats/Reconstruction/CMakeLists.txt @@ -28,6 +28,7 @@ o2_add_library(ReconstructionDataFormats src/TrackTPCTOF.cxx src/TrackCosmics.cxx PUBLIC_LINK_LIBRARIES O2::GPUCommon + O2::GPUUtils O2::FrameworkLogger O2::DetectorsCommonDataFormats O2::CommonDataFormat) diff --git a/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h b/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h index ded237f7fc231..4cbaedd6eaac6 100644 --- a/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h +++ b/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h @@ -15,13 +15,16 @@ #ifndef O2_GLOBAL_TRACK_ID #define O2_GLOBAL_TRACK_ID +#include "GPUCommonBitSet.h" #include "CommonDataFormat/AbstractRef.h" #include "DetectorsCommonDataFormats/DetID.h" +#ifndef GPUCA_GPUCODE #include #include #include #include #include +#endif // GPUCA_GPUCODE_DEVICE namespace o2 { @@ -61,46 +64,97 @@ class GlobalTrackID : public AbstractRef<25, 5, 2> }; using AbstractRef<25, 5, 2>::AbstractRef; + typedef o2::gpu::gpustd::bitset mask_t; - static const std::array SourceDetectorsMasks; // RS cannot be made constexpr since operator| is not constexpr +#ifndef GPUCA_GPUCODE static constexpr std::string_view NONE{"none"}; ///< keywork for no sources static constexpr std::string_view ALL{"all"}; ///< keywork for all sources - typedef std::bitset mask_t; - - static constexpr std::array sMasks = ///< detectot masks - {math_utils::bit2Mask(ITS), math_utils::bit2Mask(TPC), math_utils::bit2Mask(TRD), math_utils::bit2Mask(TOF), math_utils::bit2Mask(PHS), - math_utils::bit2Mask(CPV), math_utils::bit2Mask(EMC), math_utils::bit2Mask(HMP), math_utils::bit2Mask(MFT), math_utils::bit2Mask(MCH), - math_utils::bit2Mask(MID), math_utils::bit2Mask(ZDC), math_utils::bit2Mask(FT0), math_utils::bit2Mask(FV0), math_utils::bit2Mask(FDD), - math_utils::bit2Mask(ITSTPC), math_utils::bit2Mask(TPCTOF), math_utils::bit2Mask(TPCTRD), math_utils::bit2Mask(ITSTPCTRD), - math_utils::bit2Mask(ITSTPCTOF), math_utils::bit2Mask(TPCTRDTOF), math_utils::bit2Mask(ITSTPCTRDTOF)}; +#endif // methods for detector level manipulations - static const auto getSourceDetectorsMask(int i) { return SourceDetectorsMasks[i]; } - static bool includesDet(DetID id, GlobalTrackID::mask_t srcm); - auto getSourceDetectorsMask() const { return getSourceDetectorsMask(getSource()); } - bool includesDet(DetID id) const { return (getSourceDetectorsMask() & DetID::getMask(id)).any(); } + GPUd() static constexpr DetID::mask_t getSourceDetectorsMask(int i); + GPUd() static bool includesDet(DetID id, GlobalTrackID::mask_t srcm); + GPUdi() auto getSourceDetectorsMask() const { return getSourceDetectorsMask(getSource()); } + GPUdi() bool includesDet(DetID id) const { return (getSourceDetectorsMask() & DetID::getMask(id)).any(); } // methods for source level manipulations +#ifndef GPUCA_GPUCODE static auto getSourceName(int s) { return DetID::getNames(getSourceDetectorsMask(s), '-'); } - constexpr mask_t getSourceMask(int s) const { return sMasks[s]; } - mask_t getSourceMask() const { return getSourceMask(getSource()); } - auto getSourceName() const { return getSourceName(getSource()); } static mask_t getSourcesMask(const std::string_view srcList); - static bool includesSource(int s, mask_t srcm) { return srcm[s]; } static std::string getSourcesNames(mask_t srcm); - operator int() const { return int(getIndex()); } + auto getSourceName() const { return getSourceName(getSource()); } +#endif // GPUCA_GPUCODE + GPUd() static constexpr mask_t getSourceMask(int s); + GPUdi() mask_t getSourceMask() const { return getSourceMask(getSource()); } + GPUdi() static bool includesSource(int s, mask_t srcm) { return srcm[s]; } + GPUdi() operator int() const { return int(getIndex()); } +#ifndef GPUCA_GPUCODE std::string asString() const; void print() const; +#endif // GPUCA_GPUCODE - ClassDefNV(GlobalTrackID, 2); + ClassDefNV(GlobalTrackID, 3); }; +#ifndef GPUCA_GPUCODE std::ostream& operator<<(std::ostream& os, const o2::dataformats::GlobalTrackID& v); +#endif // GPUCA_GPUCODE + +namespace globaltrackid_internal +{ +// static constexpr array class members not possible on the GPU, thus we use this trick. +using DetID = o2::detectors::DetID; +GPUconstexpr() DetID::mask_t SourceDetectorsMasks[GlobalTrackID::NSources] = { + DetID::getMask(DetID::ITS), + DetID::getMask(DetID::TPC), + DetID::getMask(DetID::TRD), + DetID::getMask(DetID::TOF), + DetID::getMask(DetID::PHS), + DetID::getMask(DetID::CPV), + DetID::getMask(DetID::EMC), + DetID::getMask(DetID::HMP), + DetID::getMask(DetID::MFT), + DetID::getMask(DetID::MCH), + DetID::getMask(DetID::MID), + DetID::getMask(DetID::ZDC), + DetID::getMask(DetID::FT0), + DetID::getMask(DetID::FV0), + DetID::getMask(DetID::FDD), + // + DetID::getMask(DetID::ITS) | DetID::getMask(DetID::TPC), + DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TOF), + DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TRD), + DetID::getMask(DetID::ITS) | DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TRD), + DetID::getMask(DetID::ITS) | DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TOF), + DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TRD) | DetID::getMask(DetID::TOF), + DetID::getMask(DetID::ITS) | DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TRD) | DetID::getMask(DetID::TOF)}; + +GPUconstexpr() GlobalTrackID::mask_t sMasks[GlobalTrackID::NSources] = ///< detectot masks + {math_utils::bit2Mask(GlobalTrackID::ITS), math_utils::bit2Mask(GlobalTrackID::TPC), math_utils::bit2Mask(GlobalTrackID::TRD), math_utils::bit2Mask(GlobalTrackID::TOF), math_utils::bit2Mask(GlobalTrackID::PHS), + math_utils::bit2Mask(GlobalTrackID::CPV), math_utils::bit2Mask(GlobalTrackID::EMC), math_utils::bit2Mask(GlobalTrackID::HMP), math_utils::bit2Mask(GlobalTrackID::MFT), math_utils::bit2Mask(GlobalTrackID::MCH), + math_utils::bit2Mask(GlobalTrackID::MID), math_utils::bit2Mask(GlobalTrackID::ZDC), math_utils::bit2Mask(GlobalTrackID::FT0), math_utils::bit2Mask(GlobalTrackID::FV0), math_utils::bit2Mask(GlobalTrackID::FDD), + math_utils::bit2Mask(GlobalTrackID::ITSTPC), math_utils::bit2Mask(GlobalTrackID::TPCTOF), math_utils::bit2Mask(GlobalTrackID::TPCTRD), math_utils::bit2Mask(GlobalTrackID::ITSTPCTRD), + math_utils::bit2Mask(GlobalTrackID::ITSTPCTOF), math_utils::bit2Mask(GlobalTrackID::TPCTRDTOF), math_utils::bit2Mask(GlobalTrackID::ITSTPCTRDTOF)}; +} // namespace globaltrackid_internal + +GPUdi() constexpr GlobalTrackID::DetID::mask_t GlobalTrackID::getSourceDetectorsMask(int i) { return globaltrackid_internal::SourceDetectorsMasks[i]; } +GPUdi() constexpr GlobalTrackID::mask_t GlobalTrackID::getSourceMask(int s) { return globaltrackid_internal::sMasks[s]; } + +GPUdi() bool GlobalTrackID::includesDet(DetID id, GlobalTrackID::mask_t srcm) +{ + for (int i = 0; i < NSources; i++) { + if (includesSource(i, srcm) && getSourceDetectorsMask(i) == id.getMask()) { + return true; + } + } + return false; +} } // namespace dataformats } // namespace o2 +#ifndef GPUCA_GPUCODE namespace std { // defining std::hash for GlobalTrackIndex to be used with std containers @@ -113,5 +167,6 @@ struct hash { } }; } // namespace std +#endif // GPUCA_GPUCODE #endif diff --git a/DataFormats/Reconstruction/src/GlobalTrackID.cxx b/DataFormats/Reconstruction/src/GlobalTrackID.cxx index dd6f0f5c3eb9e..d8dad6551fe23 100644 --- a/DataFormats/Reconstruction/src/GlobalTrackID.cxx +++ b/DataFormats/Reconstruction/src/GlobalTrackID.cxx @@ -21,31 +21,6 @@ using namespace o2::dataformats; using DetID = o2::detectors::DetID; -const std::array GlobalTrackID::SourceDetectorsMasks = { - DetID::getMask(DetID::ITS), - DetID::getMask(DetID::TPC), - DetID::getMask(DetID::TRD), - DetID::getMask(DetID::TOF), - DetID::getMask(DetID::PHS), - DetID::getMask(DetID::CPV), - DetID::getMask(DetID::EMC), - DetID::getMask(DetID::HMP), - DetID::getMask(DetID::MFT), - DetID::getMask(DetID::MCH), - DetID::getMask(DetID::MID), - DetID::getMask(DetID::ZDC), - DetID::getMask(DetID::FT0), - DetID::getMask(DetID::FV0), - DetID::getMask(DetID::FDD), - // - DetID::getMask(DetID::ITS) | DetID::getMask(DetID::TPC), - DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TOF), - DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TRD), - DetID::getMask(DetID::ITS) | DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TRD), - DetID::getMask(DetID::ITS) | DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TOF), - DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TRD) | DetID::getMask(DetID::TOF), - DetID::getMask(DetID::ITS) | DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TRD) | DetID::getMask(DetID::TOF)}; - std::string GlobalTrackID::asString() const { std::bitset bits{getFlags()}; @@ -60,7 +35,7 @@ GlobalTrackID::mask_t GlobalTrackID::getSourcesMask(const std::string_view srcLi return mask; } if (ss.find(ALL) != std::string::npos) { - mask.set(); + mask = (0x1u << NSources) - 1; return mask; } std::replace(ss.begin(), ss.end(), ' ', ','); @@ -80,16 +55,6 @@ GlobalTrackID::mask_t GlobalTrackID::getSourcesMask(const std::string_view srcLi return mask; } -bool GlobalTrackID::includesDet(DetID id, GlobalTrackID::mask_t srcm) -{ - for (int i = 0; i < NSources; i++) { - if (includesSource(i, srcm) && getSourceDetectorsMask(i) == id.getMask()) { - return true; - } - } - return false; -} - std::ostream& o2::dataformats::operator<<(std::ostream& os, const o2::dataformats::GlobalTrackID& v) { // stream itself diff --git a/DataFormats/common/include/CommonDataFormat/AbstractRef.h b/DataFormats/common/include/CommonDataFormat/AbstractRef.h index edefd742d9da1..982675f31a6fb 100644 --- a/DataFormats/common/include/CommonDataFormat/AbstractRef.h +++ b/DataFormats/common/include/CommonDataFormat/AbstractRef.h @@ -15,7 +15,9 @@ #ifndef ALICEO2_ABSTRACT_REF_H #define ALICEO2_ABSTRACT_REF_H -#include +#include "GPUCommonDef.h" +#include "GPUCommonRtypes.h" +#include "GPUCommonTypeTraits.h" namespace o2 { @@ -28,6 +30,7 @@ class AbstractRef template static constexpr auto MVAR() { + static_assert(NBIT <= 64, "> 64 bits not supported"); typename std::conditional<(NBIT > 32), uint64_t, typename std::conditional<(NBIT > 16), uint32_t, typename std::conditional<(NBIT > 8), uint16_t, uint8_t>::type>::type>::type tp = 0; return tp; } @@ -46,35 +49,35 @@ class AbstractRef static constexpr int NBitsSource() { return NBSrc; } static constexpr int NBitsFlags() { return NBFlg; } - AbstractRef() = default; + GPUdDefault() AbstractRef() = default; - AbstractRef(Idx_t idx, Src_t src) { set(idx, src); } + GPUdi() AbstractRef(Idx_t idx, Src_t src) { set(idx, src); } - AbstractRef(const AbstractRef& src) = default; + GPUdDefault() AbstractRef(const AbstractRef& src) = default; // - Idx_t getIndex() const { return static_cast(mRef & IdxMask); } - void setIndex(Idx_t idx) { mRef = (mRef & (BaseMask & ~IdxMask)) | (IdxMask & idx); } + GPUdi() Idx_t getIndex() const { return static_cast(mRef & IdxMask); } + GPUdi() void setIndex(Idx_t idx) { mRef = (mRef & (BaseMask & ~IdxMask)) | (IdxMask & idx); } // - Src_t getSource() const { return static_cast((mRef >> NBIdx) & SrcMask); } - void setSource(Src_t src) { mRef = (mRef & (BaseMask & ~(SrcMask << NBIdx))) | ((SrcMask & src) << NBIdx); } + GPUdi() Src_t getSource() const { return static_cast((mRef >> NBIdx) & SrcMask); } + GPUdi() void setSource(Src_t src) { mRef = (mRef & (BaseMask & ~(SrcMask << NBIdx))) | ((SrcMask & src) << NBIdx); } // - Flg_t getFlags() const { return static_cast((mRef >> (NBIdx + NBSrc)) & FlgMask); } - void setFlags(Flg_t f) { mRef = (mRef & (BaseMask & ~(FlgMask << (NBIdx + NBSrc)))) | ((FlgMask & f) << NBIdx); } - bool testBit(int i) const { return (mRef >> (NBIdx + NBSrc)) & ((0x1U << i) & FlgMask); } - void setBit(int i) { mRef = (mRef & (BaseMask & ~(0x1U << (i + NBIdx + NBSrc)))) | (((0x1U << i) & FlgMask) << (NBIdx + NBSrc)); } - void resetBit(int i) { mRef = (mRef & (BaseMask & ~(0x1U << (i + NBIdx + NBSrc)))); } - void set(Idx_t idx, Src_t src) { mRef = (mRef & (FlgMask << (NBIdx + NBSrc))) | ((SrcMask & Src_t(src)) << NBIdx) | (IdxMask & Idx_t(idx)); } - - Base_t getRaw() const { return mRef; } - void setRaw(Base_t v) { mRef = v; } - Base_t getRawWOFlags() const { return mRef & (IdxMask | (SrcMask << NBIdx)); } - bool isIndexSet() const { return getIndex() != IdxMask; } - bool isSourceSet() const { return getSource() != SrcMask; } - - bool operator==(const AbstractRef& o) const { return getRawWOFlags() == o.getRawWOFlags(); } - bool operator!=(const AbstractRef& o) const { return !operator==(o); } + GPUdi() Flg_t getFlags() const { return static_cast((mRef >> (NBIdx + NBSrc)) & FlgMask); } + GPUdi() void setFlags(Flg_t f) { mRef = (mRef & (BaseMask & ~(FlgMask << (NBIdx + NBSrc)))) | ((FlgMask & f) << NBIdx); } + GPUdi() bool testBit(int i) const { return (mRef >> (NBIdx + NBSrc)) & ((0x1U << i) & FlgMask); } + GPUdi() void setBit(int i) { mRef = (mRef & (BaseMask & ~(0x1U << (i + NBIdx + NBSrc)))) | (((0x1U << i) & FlgMask) << (NBIdx + NBSrc)); } + GPUdi() void resetBit(int i) { mRef = (mRef & (BaseMask & ~(0x1U << (i + NBIdx + NBSrc)))); } + GPUdi() void set(Idx_t idx, Src_t src) { mRef = (mRef & ((Base_t)FlgMask << (NBIdx + NBSrc))) | ((SrcMask & Src_t(src)) << NBIdx) | (IdxMask & Idx_t(idx)); } + + GPUdi() Base_t getRaw() const { return mRef; } + GPUdi() void setRaw(Base_t v) { mRef = v; } + GPUdi() Base_t getRawWOFlags() const { return mRef & (IdxMask | (SrcMask << NBIdx)); } + GPUdi() bool isIndexSet() const { return getIndex() != IdxMask; } + GPUdi() bool isSourceSet() const { return getSource() != SrcMask; } + + GPUdi() bool operator==(const AbstractRef& o) const { return getRawWOFlags() == o.getRawWOFlags(); } + GPUdi() bool operator!=(const AbstractRef& o) const { return !operator==(o); } protected: Base_t mRef = IdxMask | (SrcMask << NBIdx); // packed reference, dummy by default From 542cdfa3baef34b49ee30e9de8a98155820fac79 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 29 Apr 2021 00:36:00 +0200 Subject: [PATCH 320/770] Bugfix: Add missing detectors (CTP), mask array and ID enum were out of sync --- .../Detectors/Common/include/DetectorsCommonDataFormats/DetID.h | 2 +- DataFormats/Detectors/Common/src/DetID.cxx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h index 41a1bf265371f..65b444e0a16a0 100644 --- a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h +++ b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h @@ -178,7 +178,7 @@ GPUconstexpr() DetID::mask_t sMasks[DetID::nDetectors] = ///< detectot masks {math_utils::bit2Mask(DetID::ITS), math_utils::bit2Mask(DetID::TPC), math_utils::bit2Mask(DetID::TRD), math_utils::bit2Mask(DetID::TOF), math_utils::bit2Mask(DetID::PHS), math_utils::bit2Mask(DetID::CPV), math_utils::bit2Mask(DetID::EMC), math_utils::bit2Mask(DetID::HMP), math_utils::bit2Mask(DetID::MFT), math_utils::bit2Mask(DetID::MCH), math_utils::bit2Mask(DetID::MID), math_utils::bit2Mask(DetID::ZDC), math_utils::bit2Mask(DetID::FT0), math_utils::bit2Mask(DetID::FV0), math_utils::bit2Mask(DetID::FDD), - math_utils::bit2Mask(DetID::ACO) + math_utils::bit2Mask(DetID::ACO), math_utils::bit2Mask(DetID::CTP) #ifdef ENABLE_UPGRADES , math_utils::bit2Mask(DetID::IT3), math_utils::bit2Mask(DetID::TRK), math_utils::bit2Mask(DetID::FT3) diff --git a/DataFormats/Detectors/Common/src/DetID.cxx b/DataFormats/Detectors/Common/src/DetID.cxx index bd442509c5902..1ef87c7bb8b5d 100644 --- a/DataFormats/Detectors/Common/src/DetID.cxx +++ b/DataFormats/Detectors/Common/src/DetID.cxx @@ -25,7 +25,7 @@ constexpr const char* DetID::sDetNames[DetID::nDetectors + 1]; // redundant declarations constexpr DetID::ID DetID::ITS, DetID::TPC, DetID::TRD, DetID::TOF, DetID::PHS, DetID::CPV, DetID::EMC, - DetID::HMP, DetID::MFT, DetID::MCH, DetID::MID, DetID::ZDC, DetID::FT0, DetID::FV0, DetID::FDD, DetID::ACO, DetID::First, DetID::Last; + DetID::HMP, DetID::MFT, DetID::MCH, DetID::MID, DetID::ZDC, DetID::FT0, DetID::FV0, DetID::FDD, DetID::ACO, DetID::CTP, DetID::First, DetID::Last; #ifdef ENABLE_UPGRADES constexpr DetID::ID DetID::IT3; From 0d8585d3a0bb2529f050b6be5d427df192d4d5de Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 29 Apr 2021 00:36:42 +0200 Subject: [PATCH 321/770] GPU: Workaround for OpenCL bug: not picking the right constructor --- .../DetectorsCommonDataFormats/DetID.h | 12 ++--- .../ReconstructionDataFormats/GlobalTrackID.h | 54 +++++++++---------- 2 files changed, 33 insertions(+), 33 deletions(-) diff --git a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h index 65b444e0a16a0..366832d77e390 100644 --- a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h +++ b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h @@ -175,13 +175,13 @@ namespace detid_internal { // static constexpr array class members not possible on the GPU, thus we use this trick. GPUconstexpr() DetID::mask_t sMasks[DetID::nDetectors] = ///< detectot masks - {math_utils::bit2Mask(DetID::ITS), math_utils::bit2Mask(DetID::TPC), math_utils::bit2Mask(DetID::TRD), math_utils::bit2Mask(DetID::TOF), math_utils::bit2Mask(DetID::PHS), - math_utils::bit2Mask(DetID::CPV), math_utils::bit2Mask(DetID::EMC), math_utils::bit2Mask(DetID::HMP), math_utils::bit2Mask(DetID::MFT), math_utils::bit2Mask(DetID::MCH), - math_utils::bit2Mask(DetID::MID), math_utils::bit2Mask(DetID::ZDC), math_utils::bit2Mask(DetID::FT0), math_utils::bit2Mask(DetID::FV0), math_utils::bit2Mask(DetID::FDD), - math_utils::bit2Mask(DetID::ACO), math_utils::bit2Mask(DetID::CTP) + {DetID::mask_t(math_utils::bit2Mask(DetID::ITS)), DetID::mask_t(math_utils::bit2Mask(DetID::TPC)), DetID::mask_t(math_utils::bit2Mask(DetID::TRD)), DetID::mask_t(math_utils::bit2Mask(DetID::TOF)), DetID::mask_t(math_utils::bit2Mask(DetID::PHS)), + DetID::mask_t(math_utils::bit2Mask(DetID::CPV)), DetID::mask_t(math_utils::bit2Mask(DetID::EMC)), DetID::mask_t(math_utils::bit2Mask(DetID::HMP)), DetID::mask_t(math_utils::bit2Mask(DetID::MFT)), DetID::mask_t(math_utils::bit2Mask(DetID::MCH)), + DetID::mask_t(math_utils::bit2Mask(DetID::MID)), DetID::mask_t(math_utils::bit2Mask(DetID::ZDC)), DetID::mask_t(math_utils::bit2Mask(DetID::FT0)), DetID::mask_t(math_utils::bit2Mask(DetID::FV0)), DetID::mask_t(math_utils::bit2Mask(DetID::FDD)), + DetID::mask_t(math_utils::bit2Mask(DetID::ACO)), DetID::mask_t(math_utils::bit2Mask(DetID::CTP)) #ifdef ENABLE_UPGRADES - , - math_utils::bit2Mask(DetID::IT3), math_utils::bit2Mask(DetID::TRK), math_utils::bit2Mask(DetID::FT3) + , + DetID::mask_t(math_utils::bit2Mask(DetID::IT3)), DetID::mask_t(math_utils::bit2Mask(DetID::TRK)), DetID::mask_t(math_utils::bit2Mask(DetID::FT3)) #endif }; } // namespace detid_internal diff --git a/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h b/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h index 4cbaedd6eaac6..774fa0ef7b16e 100644 --- a/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h +++ b/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h @@ -106,36 +106,36 @@ namespace globaltrackid_internal // static constexpr array class members not possible on the GPU, thus we use this trick. using DetID = o2::detectors::DetID; GPUconstexpr() DetID::mask_t SourceDetectorsMasks[GlobalTrackID::NSources] = { - DetID::getMask(DetID::ITS), - DetID::getMask(DetID::TPC), - DetID::getMask(DetID::TRD), - DetID::getMask(DetID::TOF), - DetID::getMask(DetID::PHS), - DetID::getMask(DetID::CPV), - DetID::getMask(DetID::EMC), - DetID::getMask(DetID::HMP), - DetID::getMask(DetID::MFT), - DetID::getMask(DetID::MCH), - DetID::getMask(DetID::MID), - DetID::getMask(DetID::ZDC), - DetID::getMask(DetID::FT0), - DetID::getMask(DetID::FV0), - DetID::getMask(DetID::FDD), + DetID::mask_t(DetID::getMask(DetID::ITS)), + DetID::mask_t(DetID::getMask(DetID::TPC)), + DetID::mask_t(DetID::getMask(DetID::TRD)), + DetID::mask_t(DetID::getMask(DetID::TOF)), + DetID::mask_t(DetID::getMask(DetID::PHS)), + DetID::mask_t(DetID::getMask(DetID::CPV)), + DetID::mask_t(DetID::getMask(DetID::EMC)), + DetID::mask_t(DetID::getMask(DetID::HMP)), + DetID::mask_t(DetID::getMask(DetID::MFT)), + DetID::mask_t(DetID::getMask(DetID::MCH)), + DetID::mask_t(DetID::getMask(DetID::MID)), + DetID::mask_t(DetID::getMask(DetID::ZDC)), + DetID::mask_t(DetID::getMask(DetID::FT0)), + DetID::mask_t(DetID::getMask(DetID::FV0)), + DetID::mask_t(DetID::getMask(DetID::FDD)), // - DetID::getMask(DetID::ITS) | DetID::getMask(DetID::TPC), - DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TOF), - DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TRD), - DetID::getMask(DetID::ITS) | DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TRD), - DetID::getMask(DetID::ITS) | DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TOF), - DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TRD) | DetID::getMask(DetID::TOF), - DetID::getMask(DetID::ITS) | DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TRD) | DetID::getMask(DetID::TOF)}; + DetID::mask_t(DetID::getMask(DetID::ITS) | DetID::getMask(DetID::TPC)), + DetID::mask_t(DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TOF)), + DetID::mask_t(DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TRD)), + DetID::mask_t(DetID::getMask(DetID::ITS) | DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TRD)), + DetID::mask_t(DetID::getMask(DetID::ITS) | DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TOF)), + DetID::mask_t(DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TRD) | DetID::getMask(DetID::TOF)), + DetID::mask_t(DetID::getMask(DetID::ITS) | DetID::getMask(DetID::TPC) | DetID::getMask(DetID::TRD) | DetID::getMask(DetID::TOF))}; GPUconstexpr() GlobalTrackID::mask_t sMasks[GlobalTrackID::NSources] = ///< detectot masks - {math_utils::bit2Mask(GlobalTrackID::ITS), math_utils::bit2Mask(GlobalTrackID::TPC), math_utils::bit2Mask(GlobalTrackID::TRD), math_utils::bit2Mask(GlobalTrackID::TOF), math_utils::bit2Mask(GlobalTrackID::PHS), - math_utils::bit2Mask(GlobalTrackID::CPV), math_utils::bit2Mask(GlobalTrackID::EMC), math_utils::bit2Mask(GlobalTrackID::HMP), math_utils::bit2Mask(GlobalTrackID::MFT), math_utils::bit2Mask(GlobalTrackID::MCH), - math_utils::bit2Mask(GlobalTrackID::MID), math_utils::bit2Mask(GlobalTrackID::ZDC), math_utils::bit2Mask(GlobalTrackID::FT0), math_utils::bit2Mask(GlobalTrackID::FV0), math_utils::bit2Mask(GlobalTrackID::FDD), - math_utils::bit2Mask(GlobalTrackID::ITSTPC), math_utils::bit2Mask(GlobalTrackID::TPCTOF), math_utils::bit2Mask(GlobalTrackID::TPCTRD), math_utils::bit2Mask(GlobalTrackID::ITSTPCTRD), - math_utils::bit2Mask(GlobalTrackID::ITSTPCTOF), math_utils::bit2Mask(GlobalTrackID::TPCTRDTOF), math_utils::bit2Mask(GlobalTrackID::ITSTPCTRDTOF)}; + {GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::ITS)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::TPC)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::TRD)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::TOF)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::PHS)), + GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::CPV)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::EMC)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::HMP)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::MFT)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::MCH)), + GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::MID)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::ZDC)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::FT0)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::FV0)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::FDD)), + GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::ITSTPC)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::TPCTOF)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::TPCTRD)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::ITSTPCTRD)), + GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::ITSTPCTOF)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::TPCTRDTOF)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::ITSTPCTRDTOF))}; } // namespace globaltrackid_internal GPUdi() constexpr GlobalTrackID::DetID::mask_t GlobalTrackID::getSourceDetectorsMask(int i) { return globaltrackid_internal::SourceDetectorsMasks[i]; } From d1718d2751ba04cc76a824a53194389f5d66c984 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 29 Apr 2021 00:46:31 +0200 Subject: [PATCH 322/770] GPU: Workaround for OpenCL bug, cannot read from __constant constexpr variables using constexpr function --- .../Common/include/DetectorsCommonDataFormats/DetID.h | 2 +- .../include/ReconstructionDataFormats/GlobalTrackID.h | 4 ++-- GPU/Utils/GPUCommonBitSet.h | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h index 366832d77e390..dd27fdfc27196 100644 --- a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h +++ b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h @@ -186,7 +186,7 @@ GPUconstexpr() DetID::mask_t sMasks[DetID::nDetectors] = ///< detectot masks }; } // namespace detid_internal -GPUdi() constexpr DetID::mask_t DetID::getMask(ID id) { return detid_internal::sMasks[id]; } +GPUdi() constexpr DetID::mask_t DetID::getMask(ID id) { return detid_internal::sMasks[id].v; } } // namespace detectors } // namespace o2 diff --git a/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h b/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h index 774fa0ef7b16e..b40165535213a 100644 --- a/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h +++ b/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h @@ -138,8 +138,8 @@ GPUconstexpr() GlobalTrackID::mask_t sMasks[GlobalTrackID::NSources] = ///< dete GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::ITSTPCTOF)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::TPCTRDTOF)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::ITSTPCTRDTOF))}; } // namespace globaltrackid_internal -GPUdi() constexpr GlobalTrackID::DetID::mask_t GlobalTrackID::getSourceDetectorsMask(int i) { return globaltrackid_internal::SourceDetectorsMasks[i]; } -GPUdi() constexpr GlobalTrackID::mask_t GlobalTrackID::getSourceMask(int s) { return globaltrackid_internal::sMasks[s]; } +GPUdi() constexpr GlobalTrackID::DetID::mask_t GlobalTrackID::getSourceDetectorsMask(int i) { return globaltrackid_internal::SourceDetectorsMasks[i].v; } +GPUdi() constexpr GlobalTrackID::mask_t GlobalTrackID::getSourceMask(int s) { return globaltrackid_internal::sMasks[s].v; } GPUdi() bool GlobalTrackID::includesDet(DetID id, GlobalTrackID::mask_t srcm) { diff --git a/GPU/Utils/GPUCommonBitSet.h b/GPU/Utils/GPUCommonBitSet.h index 44369e0c78372..999ccfe88b079 100644 --- a/GPU/Utils/GPUCommonBitSet.h +++ b/GPU/Utils/GPUCommonBitSet.h @@ -79,7 +79,7 @@ class bitset std::string to_string() const; #endif - private: + //private: // Workaround for OpenCL unsigned int v = 0; ClassDefNV(bitset, 1); From 14c1e6376beda7ef779ceb22e54594f2823f8f79 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 29 Apr 2021 10:59:30 +0200 Subject: [PATCH 323/770] Use bitset<32> in GlobalTrackID to avoid schema evolution issues with future changes. --- .../Common/include/DetectorsCommonDataFormats/DetID.h | 1 + .../include/ReconstructionDataFormats/GlobalTrackID.h | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h index dd27fdfc27196..63deb8e334a58 100644 --- a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h +++ b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h @@ -87,6 +87,7 @@ class DetID static constexpr int nDetectors = Last + 1; ///< number of defined detectors typedef o2::gpu::gpustd::bitset<32> mask_t; + static_assert(nDetectors <= 32, "bitset<32> insufficient"); #ifndef GPUCA_GPUCODE_DEVICE static constexpr std::string_view NONE{"none"}; ///< keywork for no-detector diff --git a/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h b/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h index b40165535213a..efe7477c9a491 100644 --- a/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h +++ b/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h @@ -64,7 +64,8 @@ class GlobalTrackID : public AbstractRef<25, 5, 2> }; using AbstractRef<25, 5, 2>::AbstractRef; - typedef o2::gpu::gpustd::bitset mask_t; + static_assert(NSources <= 32, "bitset<32> insufficient"); + typedef o2::gpu::gpustd::bitset<32> mask_t; #ifndef GPUCA_GPUCODE static constexpr std::string_view NONE{"none"}; ///< keywork for no sources From ba12d4d292b0e95899566b05c9fe3dca9edf214d Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 29 Apr 2021 20:04:12 +0200 Subject: [PATCH 324/770] Full System Test: StfBuilder uses a dummy SHM segment, since it uses the unmanaged region exclusively anyway --- prodtests/full-system-test/datadistribution.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/prodtests/full-system-test/datadistribution.sh b/prodtests/full-system-test/datadistribution.sh index 241f5f3b5eb86..52ef255acbb6a 100755 --- a/prodtests/full-system-test/datadistribution.sh +++ b/prodtests/full-system-test/datadistribution.sh @@ -15,7 +15,7 @@ export DATADIST_FILE_READ_COUNT=$NTIMEFRAMES export TF_DIR=./raw/timeframe export TFRATE=$(awk "BEGIN {printf \"%.6f\",1/$TFDELAY}") -ARGS_ALL="--session default --severity $SEVERITY --shm-segment-size $SHMSIZE --no-cleanup" +ARGS_ALL="--session default --severity $SEVERITY --shm-segment-id 2 --shm-segment-size 1000000 --no-cleanup" StfBuilder --id stfb --transport shmem \ --dpl-channel-name dpl-chan --channel-config "name=dpl-chan,type=push,method=bind,address=ipc://@$INRAWCHANNAME,transport=shmem,rateLogging=1" \ From ff46fbd7d02c01b4be1c331cd0f6cfa9b76d6036 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 29 Apr 2021 20:04:42 +0200 Subject: [PATCH 325/770] Full System Test: Pass the numactl command via the child-driver option --- prodtests/full-system-test/dpl-workflow.sh | 3 +++ prodtests/full-system-test/start_tmux.sh | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/prodtests/full-system-test/dpl-workflow.sh b/prodtests/full-system-test/dpl-workflow.sh index 1dd9c945b14ab..2e02592e3f053 100755 --- a/prodtests/full-system-test/dpl-workflow.sh +++ b/prodtests/full-system-test/dpl-workflow.sh @@ -19,6 +19,9 @@ fi if [ $NORATELOG == 1 ]; then ARGS_ALL+=" --fairmq-rate-logging 0" fi +if [ $NUMAGPUIDS != 0 ]; then + ARGS_ALL+=" --child-driver 'numactl --membind $NUMAID --cpunodebind $NUMAID'" +fi # Set some individual workflow arguments depending on configuration CTF_DETECTORS=ITS,MFT,TPC,TOF,FT0,MID,EMC,PHS,CPV,ZDC,FDD diff --git a/prodtests/full-system-test/start_tmux.sh b/prodtests/full-system-test/start_tmux.sh index 3ca8c55419775..7a12a09c9f867 100755 --- a/prodtests/full-system-test/start_tmux.sh +++ b/prodtests/full-system-test/start_tmux.sh @@ -36,7 +36,7 @@ fi rm -f /dev/shm/*fmq* tmux \ - new-session "NUMAID=0 numactl --membind 0 --cpunodebind 0 $MYDIR/dpl-workflow.sh; echo END; sleep 1000" \; \ - split-window "sleep 30; NUMAID=1 numactl --membind 1 --cpunodebind 1 $MYDIR/dpl-workflow.sh; echo END; sleep 1000" \; \ + new-session "NUMAID=0 $MYDIR/dpl-workflow.sh; echo END; sleep 1000" \; \ + split-window "sleep 30; NUMAID=1 $MYDIR/dpl-workflow.sh; echo END; sleep 1000" \; \ split-window "sleep 60; SEVERITY=debug numactl --interleave=all $MYDIR/$CMD; echo END; sleep 1000" \; \ select-layout even-vertical From 177677e5a980e44ec31fc4fa889495a4407be479 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 30 Apr 2021 11:25:11 +0200 Subject: [PATCH 326/770] First reconstruction on digits --- .../ZDC/include/DataFormatsZDC/RecEvent.h | 4 +- .../ZDC/base/include/ZDCBase/Constants.h | 10 + .../include/ZDCReconstruction/DigiReco.h | 16 +- Detectors/ZDC/reconstruction/src/DigiReco.cxx | 778 ++++++++++++++---- 4 files changed, 633 insertions(+), 175 deletions(-) diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h index a9350727c74d0..6e13d1489a15c 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h @@ -49,9 +49,11 @@ struct RecEvent { //std::array tdcAmplitudes; /// At most MaxTDCValues Values in ns per TDC channel int16_t tdcChannels[NTDCChannels][MaxTDCValues]; /// TdcChannels float tdcAmplitudes[NTDCChannels][MaxTDCValues]; /// TdcAmplitudes + int ntdc[NTDCChannels]={0}; std::array pattern; /// Pattern of TDC - Short_t fired[NTDCChannels][NTimeBinsPerBC] = {0}; /// Position at which the trigger algorithm is fired + uint16_t fired[NTDCChannels] = {0}; /// Position at which the trigger algorithm is fired float inter[NTDCChannels][NTimeBinsPerBC * TSN] = {0}; /// Interpolated samples + uint32_t ref[NChannels]={O2_ZDC_REF_INIT}; /// Cache of references void print() const; diff --git a/Detectors/ZDC/base/include/ZDCBase/Constants.h b/Detectors/ZDC/base/include/ZDCBase/Constants.h index b773bfda76383..583542fdf4b30 100644 --- a/Detectors/ZDC/base/include/ZDCBase/Constants.h +++ b/Detectors/ZDC/base/include/ZDCBase/Constants.h @@ -51,6 +51,11 @@ constexpr float ChannelTimeBinNS = 2.; //< bin length in NS constexpr float SampleLenghtNS = NTimeBinsPerBC * ChannelTimeBinNS; constexpr int NChannels = 2 * (NChannelsZN + NChannelsZP) + NChannelsZEM; +#define O2_ZDC_REF_INIT_VAL 0xffffffff +#define O2_ZDC_REF_INIT_ZEM O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL +#define O2_ZDC_REF_INIT_ZDC O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL +#define O2_ZDC_REF_INIT O2_ZDC_REF_INIT_ZDC, O2_ZDC_REF_INIT_ZDC, O2_ZDC_REF_INIT_ZEM, O2_ZDC_REF_INIT_ZDC, O2_ZDC_REF_INIT_ZDC + constexpr uint8_t ALICETriggerMask = 0x1; constexpr int NModules = 8; @@ -173,6 +178,11 @@ const int TDCSignal[NTDCChannels] = { IdZPCSum // TDCZPCS }; +constexpr int DbgZero = 0; +constexpr int DbgMinimal = 1; +constexpr int DbgMedium = 2; +constexpr int DbgFull = 3; + // paths to CCDB objects // TODO: eventually these paths should be retrieved from NameConfigurator class // TODO: we would better use "constexpr string_view" here, but it makes sense only if diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h index 14c342387a8f2..7ebdf7357a0ab 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h @@ -22,8 +22,12 @@ class DigiReco { public: DigiReco() = default; + ~DigiReco() { + mTDbg->Write(); + mDbg->Close(); + } void init(); - int process(const std::vector *orbitdata, const std::vector *bcdata, std::vector *chdata); + int process(const std::vector *orbitdata, const std::vector *bcdata, const std::vector *chdata); int write(); void setVerbosity(int v) { @@ -40,12 +44,16 @@ class DigiReco const ModuleConfig* mModuleConfig = nullptr; /// Trigger/readout configuration object private: - int reconstruct(int seq_beg, int seq_end); + int reconstruct(int seq_beg, int seq_end); /// Main method for data reconstruction + void processTrigger(int itdc, int ibeg, int iend); /// Replay of trigger algorithm on acquired data + void interpolate(int itdc, int ibeg, int iend); /// Interpolation of samples to evaluate signal amplitude and arrival time + void assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float amp); // Set reconstructed TDC values bool mIsContinuous = true; /// continuous (self-triggered) or externally-triggered readout int mNBCAHead = 0; /// when storing triggered BC, store also mNBCAHead BCs const ZDCTDCParam* mTDCParam = nullptr; /// TDC calibration object + uint32_t mTDCMask[NTDCChannels]={0}; /// Identify TDC channels in trigger mask const ZDCIntegrationParam* mIntParam = nullptr; /// Configuration of integration - bool mVerbosity; + bool mVerbosity=DbgFull; Double_t mTS[NTS]; /// Tapered sinc function TFile* mDbg = nullptr; /// Debug output TTree* mTDbg = nullptr; /// Debug tree @@ -57,6 +65,8 @@ class DigiReco static constexpr int mNSB = TSN * NTimeBinsPerBC; /// Total number of interpolated points per bunch crossing RecEvent mRec; /// Debug reconstruction event int mNBC = 0; + int16_t tdc_shift[NTDCChannels] = {0}; /// TDC correction (units of 1/96 ns) + constexpr static uint16_t mMask[NTimeBinsPerBC]={0x0001,0x002,0x004,0x008, 0x0010,0x0020,0x0040,0x0080, 0x0100,0x0200,0x0400,0x0800}; }; } // namespace zdc } // namespace o2 diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index 2ae7bfb4a4ff5..f8a420dc441f5 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -1,6 +1,8 @@ #include #include "FairLogger.h" #include "ZDCReconstruction/DigiReco.h" +#include "ZDCReconstruction/RecoParamZDC.h" + namespace o2 { namespace zdc @@ -52,6 +54,8 @@ void DigiReco::init(){ //ropt.updateFromString(TString::Format("RecoParamZDC.tch[%d]=%d;",itdc,ic)); ropt.tmod[itdc] = im; ropt.tch[itdc] = ic; + // Fill mask to identify TDC channels + mTDCMask[itdc]=(0x1<<(4*im+ic)); goto next_itdc; } } @@ -61,6 +65,34 @@ void DigiReco::init(){ LOG(INFO) << "TDC " << itdc << "(" << ChannelNames[TDCSignal[itdc]] << ")" << " mod " << ropt.tmod[itdc] << " ch " << ropt.tch[itdc]; } + // TDC calibration + for (Int_t itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { + float fval = ropt.tdc_shift[itdc]; + // If the reconstruction parameters were not manually set + if (fval < 0) { + // Check if calibration object is present + if (!mTDCParam) { + LOG(FATAL) << "TDC " << itdc << " missing configuration object and no manual override"; + } else { + fval = mTDCParam->getShift(itdc) * 96.; + } + } + auto val = std::nearbyint(fval); + if (val < kMinShort) { + LOG(FATAL) << "Shift for TDC " << itdc << " " << val << " is out of range"; + } + if (val > kMaxShort) { + LOG(FATAL) << "Shift for TDC " << itdc << " " << val << " is out of range"; + } + tdc_shift[itdc] = val; + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " shift= " << tdc_shift[itdc] << " i.s. = " << val / 96. << " ns"; + } + // TDC search zone + // TODO: override with configuration object + for (Int_t itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << ropt.tdc_search[itdc] << " i.s. = " << ropt.tdc_search[itdc] / 96. << " ns"; + } + // Fill maps channel maps for integration for (Int_t ich = 0; ich < NChannels; ich++) { // If the reconstruction parameters were not manually set @@ -102,7 +134,7 @@ void DigiReco::init(){ } } -int DigiReco::process(const std::vector *orbitdata, const std::vector *bcdata, std::vector *chdata){ +int DigiReco::process(const std::vector *orbitdata, const std::vector *bcdata, const std::vector *chdata){ // We assume that vectors contain data from a full time frame mOrbitData=orbitdata; mBCData=bcdata; @@ -117,14 +149,25 @@ int DigiReco::process(const std::vector *orbitdata, const st int norb=OrbitData.size(); for(Int_t iorb=0; iorb=DbgFull){ + LOG(INFO) << "OrbitData[" << OrbitData[iorb].ir.orbit << "] = " << iorb; + } } mNBC=BCData.size(); mReco.clear(); mReco.reserve(mNBC); // Initialization of reco structure for(Int_t ibc=0; ibcIdDummy && chd.id ::iterator it; return 0; } -int DigiReco::reconstruct(int seq_beg, int seq_end){ +int DigiReco::reconstruct(int ibeg, int iend){ // Process consecutive BCs - if (seq_beg == seq_end) { - LOG(INFO) << "Lonely bunch " << mReco[seq_beg].ir.orbit << "." << mReco[seq_beg].ir.bc; + if (ibeg == iend) { + LOG(INFO) << "Lonely bunch " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc; return 0; } - LOG(INFO) << "Processing " << mReco[seq_beg].ir.orbit << "." << mReco[seq_beg].ir.bc << " - " << mReco[seq_end].ir.orbit << "." << mReco[seq_end].ir.bc; - auto& ropt = ZDCRecoParam::Instance(); - /* + LOG(INFO) << __func__ << "(" << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; + // Get references to arrays + const std::vector &OrbitData=*mOrbitData; + const std::vector &BCData=*mBCData; + const std::vector &ChData=*mChData; + + // Get reconstruction parameters + auto& ropt = RecoParamZDC::Instance(); + +// int chEnt = bcd.ref.getFirstEntry(); +// for (int ic = 0; ic < bcd.ref.getEntries(); ic++) { +// const auto& chd = zdcChData[chEnt++]; +// chd.print(); +// UShort_t bc=bcd.ir.bc; +// UInt_t orbit=bcd.ir.orbit; +// for(Int_t is=0; isGetN(); +// gr[chd.id]->SetPoint(ip,3564.*orbit+bc+is/12.,myval); +// } +// } + // Apply differential discrimination with triple condition for (Int_t itdc = 0; itdc < NTDCChannels; itdc++) { - Int_t im = ropt.tmod[itdc]; - Int_t ic = ropt.tch[itdc]; - // Check if the TDC channel is connected - if (im >= 0 && ic >= 0) { - // Check if channel has valid data for consecutive bunches in current bunch range - // N.B. there are events recorded from ibeg-iend but we are not sure if it is the - // case for every TDC channel - int istart = -1, istop = -1; - // Loop allows for gaps in the data sequence for each TDC channel - for (int ibun = ibeg; ibun <= iend; ibun++) { - auto& ch = mData[ibun].data[im][ic]; - if (ch.f.fixed_0 == Id_w0 && ch.f.fixed_1 == Id_w1 && ch.f.fixed_2 == Id_w2) { - if (istart < 0) { - istart = ibun; - } - istop = ibun; - } else { - // A gap is detected gap - if (istart >= 0 && (istop - istart) > 0) { - // Need data for at least two consecutive bunch crossings - processTrigger(itdc, istart, istop); - } - istart = -1; - istop = -1; + // Check if channel has valid data for consecutive bunches in current bunch range + // N.B. there are events recorded from ibeg-iend but we are not sure if it is the + // case for every TDC channel + int istart = -1, istop = -1; + // Loop allows for gaps in the data sequence for each TDC channel + for (int ibun = ibeg; ibun <= iend; ibun++) { + if (BCData[ibun].channels&mTDCMask[itdc]) { // TDC channel has data for this event + if (istart < 0) { + istart = ibun; } + istop = ibun; + } else { // No data from channel + // A gap is detected + if (istart >= 0 && (istop - istart) > 0) { + // Need data for at least two consecutive bunch crossings + processTrigger(itdc, istart, istop); + } + istart = -1; + istop = -1; } - // Check if there are consecutive bunch crossings at the end of group - if (istart >= 0 && (istop - istart) > 0) { - processTrigger(itdc, istart, istop); - } + } + // Check if there are consecutive bunch crossings at the end of group + if (istart >= 0 && (istop - istart) > 0) { + processTrigger(itdc, istart, istop); } } + + // Loop on bunches after trigger evaluation // Reconstruct integrated charges and fill output tree // TODO: compare average pedestal with estimation from current event // TODO: failover in case of discrepancy for (Int_t ibun = ibeg; ibun <= iend; ibun++) { - mRec = mReco[ibun]; - for (Int_t itdc = 0; itdc < NTDCChannels; itdc++) { - printf("%d %u.%u %d ", ibun, mReco[ibun].ir.orbit, mReco[ibun].ir.bc, itdc); - for (Int_t isam = 0; isam < NTimeBinsPerBC; isam++) { - printf("%d", mRec.fired[itdc][isam]); + // Look for offset + float pbun[NChannels]; + auto orbit=BCData[ibun].ir.orbit; + std::map::iterator it = mOrbit.find(orbit); + if (it != mOrbit.end()){ + // Subtract pedestal + auto &orbitdata=OrbitData[it->second]; + for(int ich=0; ich::infinity(); } - Int_t i = 0; - mRec.pattern[itdc] = 0; - for (int16_t val : mReco[ibun].tdcChannels[itdc]) { - LOG(INFO) << "TdcChannels[" << itdc << "][" << i << "]=" << val; - mRec.TdcChannels[itdc][i] = val; - // There is a TDC value in the search zone around main-main position - if (std::abs(mRec.TdcChannels[itdc][i]) < ropt.tdc_search[itdc]) { - mRec.pattern[itdc] = 1; - } - i++; + } + // Debug dump of pedestal + if(mVerbosity>=DbgFull){ + for(int ich=0; ich= 0 && ic >= 0) { - // Check if the ADC has payload - auto& ch = data.data[im][ic]; - if (ch.f.fixed_0 == Id_w0 && ch.f.fixed_1 == Id_w1 && ch.f.fixed_2 == Id_w2) { - float sum = 0; - for (Int_t is = ropt.beg_int[ich]; is <= ropt.end_int[ich]; is++) { - // TODO: fallback if offset is missing - // TODO: fallback if channel has pile-up - sum += (mOffset[im][ic] - float(data.s[im][ic][is])); - } - printf("CH %d %s: %f\n", ich, ChannelNames[ich].data(), sum); - if (ich == IdZNAC) { - mRec.energyZNA[0] = sum; - } - if (ich == IdZNA1) { - mRec.energyZNA[1] = sum; - } - if (ich == IdZNA2) { - mRec.energyZNA[2] = sum; - } - if (ich == IdZNA3) { - mRec.energyZNA[3] = sum; - } - if (ich == IdZNA4) { - mRec.energyZNA[4] = sum; - } - if (ich == IdZNASum) { - mRec.energyZNA[5] = sum; - } - if (ich == IdZPAC) { - mRec.energyZPA[0] = sum; - } - if (ich == IdZPA1) { - mRec.energyZPA[1] = sum; - } - if (ich == IdZPA2) { - mRec.energyZPA[2] = sum; - } - if (ich == IdZPA3) { - mRec.energyZPA[3] = sum; - } - if (ich == IdZPA4) { - mRec.energyZPA[4] = sum; - } - if (ich == IdZPASum) { - mRec.energyZPA[5] = sum; - } - if (ich == IdZEM1) { - mRec.energyZEM[0] = sum; - } - if (ich == IdZEM2) { - mRec.energyZEM[1] = sum; - } - if (ich == IdZNCC) { - mRec.energyZNC[0] = sum; - } - if (ich == IdZNC1) { - mRec.energyZNC[1] = sum; - } - if (ich == IdZNC2) { - mRec.energyZNC[2] = sum; - } - if (ich == IdZNC3) { - mRec.energyZNC[3] = sum; - } - if (ich == IdZNC4) { - mRec.energyZNC[4] = sum; - } - if (ich == IdZNCSum) { - mRec.energyZNC[5] = sum; - } - if (ich == IdZPCC) { - mRec.energyZPC[0] = sum; - } - if (ich == IdZPC1) { - mRec.energyZPC[1] = sum; - } - if (ich == IdZPC2) { - mRec.energyZPC[2] = sum; - } - if (ich == IdZPC3) { - mRec.energyZPC[3] = sum; - } - if (ich == IdZPC4) { - mRec.energyZPC[4] = sum; - } - if (ich == IdZPCSum) { - mRec.energyZPC[5] = sum; - } + // Check if channel data are present in payload + auto ref = mReco[ibun].ref[ich]; + if(ref < O2_ZDC_REF_INIT_VAL){ + float sum = 0; + for (Int_t is = ropt.beg_int[ich]; is <= ropt.end_int[ich]; is++) { + // TODO: fallback if offset is missing + // TODO: fallback if channel has pile-up + // TODO: manage signal positioned across boundary + sum += (pbun[ich] - float(ChData[ref].data[is])); + } + printf("CH %d %s: %f\n", ich, ChannelNames[ich].data(), sum); + if (ich == IdZNAC) { + rec.energyZNA[0] = sum; + } + if (ich == IdZNA1) { + rec.energyZNA[1] = sum; + } + if (ich == IdZNA2) { + rec.energyZNA[2] = sum; + } + if (ich == IdZNA3) { + rec.energyZNA[3] = sum; + } + if (ich == IdZNA4) { + rec.energyZNA[4] = sum; + } + if (ich == IdZNASum) { + rec.energyZNA[5] = sum; + } + if (ich == IdZPAC) { + rec.energyZPA[0] = sum; + } + if (ich == IdZPA1) { + rec.energyZPA[1] = sum; + } + if (ich == IdZPA2) { + rec.energyZPA[2] = sum; + } + if (ich == IdZPA3) { + rec.energyZPA[3] = sum; + } + if (ich == IdZPA4) { + rec.energyZPA[4] = sum; + } + if (ich == IdZPASum) { + rec.energyZPA[5] = sum; + } + if (ich == IdZEM1) { + rec.energyZEM[0] = sum; + } + if (ich == IdZEM2) { + rec.energyZEM[1] = sum; + } + if (ich == IdZNCC) { + rec.energyZNC[0] = sum; + } + if (ich == IdZNC1) { + rec.energyZNC[1] = sum; + } + if (ich == IdZNC2) { + rec.energyZNC[2] = sum; + } + if (ich == IdZNC3) { + rec.energyZNC[3] = sum; + } + if (ich == IdZNC4) { + rec.energyZNC[4] = sum; + } + if (ich == IdZNCSum) { + rec.energyZNC[5] = sum; + } + if (ich == IdZPCC) { + rec.energyZPC[0] = sum; + } + if (ich == IdZPC1) { + rec.energyZPC[1] = sum; + } + if (ich == IdZPC2) { + rec.energyZPC[2] = sum; + } + if (ich == IdZPC3) { + rec.energyZPC[3] = sum; + } + if (ich == IdZPC4) { + rec.energyZPC[4] = sum; + } + if (ich == IdZPCSum) { + rec.energyZPC[5] = sum; } } } } // TODO: energy calibration + mRec=rec; mTDbg->Fill(); + } // Loop on bunches +} + +void DigiReco::processTrigger(int itdc, int ibeg, int iend) +{ + LOG(INFO) << __func__ << "(itdc=" << itdc << "[" << ChannelNames[TDCSignal[itdc]] << "] ," << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; + + const std::vector &OrbitData=*mOrbitData; + const std::vector &BCData=*mBCData; + const std::vector &ChData=*mChData; + + // Get reconstruction parameters + auto& ropt = RecoParamZDC::Instance(); + +// int chEnt = bcd.ref.getFirstEntry(); +// for (int ic = 0; ic < bcd.ref.getEntries(); ic++) { +// const auto& chd = zdcChData[chEnt++]; +// chd.print(); +// UShort_t bc=bcd.ir.bc; +// UInt_t orbit=bcd.ir.orbit; +// for(Int_t is=0; isGetN(); +// gr[chd.id]->SetPoint(ip,3564.*orbit+bc+is/12.,myval); +// } +// } + + Int_t nbun = iend - ibeg + 1; + Int_t maxs2 = NTimeBinsPerBC * nbun - 1; + Int_t shift = ropt.tsh[itdc]; + Int_t thr = ropt.tth[itdc]; + + Int_t is1 = 0, is2 = 1; + Int_t isfired[3] = {0}; + Int_t it1=0,it2=0,ib1=-1,ib2=-1; + for (;;) { + // Shift data + for (Int_t i = 1; i < 3; i++) { + isfired[i] = isfired[i - 1]; + } + // Bunches and samples that are used in the difference + Int_t b1 = ibeg + is1 / NTimeBinsPerBC; + Int_t b2 = ibeg + is2 / NTimeBinsPerBC; + Int_t s1 = is1 % NTimeBinsPerBC; + Int_t s2 = is2 % NTimeBinsPerBC; + auto ref_m = mReco[b1].ref[TDCSignal[itdc]]; + auto ref_s = mReco[b2].ref[TDCSignal[itdc]]; + // Check data consistency before computing difference + if(ref_m == O2_ZDC_REF_INIT_VAL || ref_s == O2_ZDC_REF_INIT_VAL){ + LOG(FATAL) << "Missing information for bunch crossing"; + return; + } + // TODO: More checks that bunch crossings are indeed consecutive + int diff = ChData[ref_m].data[s1] - ChData[ref_s].data[s2]; + // Triple trigger condition + if (diff > thr) { + isfired[0] = 1; + if (isfired[1] == 1 && isfired[2] == 1) { + // Fired bit is assigned to the second sample, i.e. to the one that can identify the + // signal peak position + mReco[b2].fired[itdc]|=mMask[s2]; + //LOG(INFO) << itdc << " Fired @ " << mReco[b2].ir.orbit << "." << mReco[b2].ir.bc << " " << b2 - ibeg << "." << s2 << "=" << NTimeBinsPerBC * (b2 - ibeg) + s2; + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " Fired @ " << mReco[b2].ir.orbit << "." << mReco[b2].ir.bc << ".s" << s2; + } + } + if (is2 >= shift) { + is1++; + } + if (is2 < maxs2) { + is2++; + } + if (is1 == maxs2) { + break; + } + } + interpolate(itdc, ibeg, iend); +} + +void DigiReco::interpolate(int itdc, int ibeg, int iend) +{ + LOG(INFO) << __func__ << "(itdc=" << itdc << "[" << ChannelNames[TDCSignal[itdc]] << "] ," << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; + // TODO: get data from preceding time frame + constexpr int MaxTimeBin = NTimeBinsPerBC - 1; //< number of samples per BC + constexpr int tsnh = TSN / 2; // Half number of points in interpolation + constexpr int nsbun = TSN * NTimeBinsPerBC; // Total number of interpolated points per bunch crossing + Int_t nbun = iend - ibeg + 1; // Number of adjacent bunches + Int_t nsam = nbun * NTimeBinsPerBC; // Number of acquired samples + Int_t ntot = nsam * TSN; // Total number of points in the interpolated arrays + Int_t nint = (nbun * NTimeBinsPerBC - 1) * TSN; // Total points in the interpolation region (-1) + constexpr int nsp = 5; // Number of points to be searched + + const std::vector &OrbitData=*mOrbitData; + const std::vector &BCData=*mBCData; + const std::vector &ChData=*mChData; + + // At this level there should be no need to check if the TDC channel is connected + // since a fatal should have been raised already + for(int ibun=ibeg; ibun<=iend; ibun++){ + auto ref = mReco[ibun].ref[TDCSignal[itdc]]; + if(ref == O2_ZDC_REF_INIT_VAL){ + LOG(FATAL) << "Missing information for bunch crossing"; + } + } + + // Get reconstruction parameters + auto& ropt = RecoParamZDC::Instance(); + + Int_t imod = ropt.tmod[itdc]; // Module corresponding to TDC channel + Int_t ich = ropt.tch[itdc]; // Hardware channel corresponding to TDC channel + + auto ref_beg = mReco[ibeg].ref[TDCSignal[itdc]]; + auto ref_end = mReco[iend].ref[TDCSignal[itdc]]; + + Double_t first_sample = ChData[ref_beg].data[0]; + Double_t last_sample = ChData[ref_end].data[NTimeBinsPerBC - 1]; + + // Constant extrapolation at the beginning and at the end of the array + // Assign value of first sample + for (Int_t i = 0; i < tsnh; i++) { + mReco[ibeg].inter[itdc][i] = first_sample; + } + // Assign value of last sample + for (Int_t i = ntot - tsnh; i < ntot; i++) { + Int_t isam = i % nsbun; + mReco[iend].inter[itdc][isam] = last_sample; + } + // Interpolation between acquired points (n.b. loop from 0 to nint) + for (Int_t i = 0; i < nint; i++) { + // Identification of the point to be assigned (need to add tsnh to identify the point) + Int_t ibun = ibeg + (i + tsnh) / nsbun; + Int_t isam = (i + tsnh) % nsbun; + Int_t im = i % TSN; + if (im == 0) { + // This is an acquired point + Int_t ip = (i / TSN) % NTimeBinsPerBC; + Int_t ib = ibeg + (i / TSN) / NTimeBinsPerBC; + if (ib != ibun) { + LOG(FATAL) << "ib=" << ib << " ibun=" << ibun; + return; + } + mReco[ibun].inter[itdc][isam] = ChData[mReco[ibun].ref[TDCSignal[itdc]]].data[ip]; + } else { + // Do the actual interpolation + Double_t y = 0; + Int_t ip = i / TSN; + Double_t sum = 0; + for (Int_t is = TSN - im, ii = ip - TSL + 1; is < NTS; is += TSN, ii++) { + // Default is first point in the array + Double_t yy = first_sample; + if (ii > 0) { + if (ii < nsam) { + Int_t ip = ii % NTimeBinsPerBC; + Int_t ib = ibeg + ii / NTimeBinsPerBC; + yy = ChData[mReco[ib].ref[TDCSignal[itdc]]].data[ip]; + } else { + // Last acquired point + yy = last_sample; + } + } + sum += mTS[is]; + y += yy * mTS[is]; + } + y = y / sum; + mReco[ibun].inter[itdc][isam] = y; + } + } + // Looking for a local maximum in a searching zone + float amp = std::numeric_limits::infinity(); // Amplitude to be stored + Int_t isam_amp = 0; // Sample at maximum amplitude (relative to beginning of group) + Int_t ip_old = -1, ip_cur = -1, ib_cur = -1; // Current and old points + bool is_searchable = false; // Flag for point in the search zone for maximum amplitude + bool was_searchable = false; // Flag for point in the search zone for maximum amplitude + Int_t ib[nsp] = {-1, -1, -1, -1, -1}; + Int_t ip[nsp] = {-1, -1, -1, -1, -1}; + // N.B. Points at the extremes are constant therefore no local maximum + // can occur in these two regions + for (Int_t i = 0; i < nint; i++) { + Int_t isam = i + tsnh; + // Check if trigger is fired for this point + // For the moment we don't take into account possible extensions of the search zone + // ip_cur can span several bunches and is used just to identify transitions + ip_cur = isam / TSN; + // Speed up computation + if (ip_cur != ip_old) { + ip_old = ip_cur; + for (Int_t j = 0; j < 5; j++) { + ib[j] = -1; + ip[j] = -1; + } + // There are three possible triple conditions that involve current point (middle is current point) + ip[2] = ip_cur % NTimeBinsPerBC; + ib[2] = ibeg + ip_cur / NTimeBinsPerBC; + ib_cur = ib[2]; + if (ip[2] > 0) { + ip[1] = ip[2] - 1; + ib[1] = ib[2]; + } else if (ip[2] == 0) { + if (ib[2] > ibeg) { + ib[1] = ib[2] - 1; + ip[1] = MaxTimeBin; + } + } + if (ip[1] > 0) { + ip[0] = ip[1] - 1; + ib[0] = ib[1]; + } else if (ip[1] == 0) { + if (ib[1] > ibeg) { + ib[0] = ib[1] - 1; + ip[0] = MaxTimeBin; + } + } + if (ip[2] < MaxTimeBin) { + ip[3] = ip[2] + 1; + ib[3] = ib[2]; + } else if (ip[2] == MaxTimeBin) { + if (ib[2] < iend) { + ib[3] = ib[2] + 1; + ip[3] = 0; + } + } + if (ip[3] < MaxTimeBin) { + ip[4] = ip[3] + 1; + ib[4] = ib[3]; + } else if (ip[3] == MaxTimeBin) { + if (ib[3] < iend) { + ib[4] = ib[3] + 1; + ip[4] = 0; + } + } + // meet the threshold condition + was_searchable = is_searchable; + // Search conditions with list of allowed patterns + // No need to double check ib[?] and ip[?] because either we assign both or none + uint16_t triggered=0x0000; + for (Int_t j = 0; j < 5; j++) { + if (ib[j] >= 0 && (mReco[ib[j]].fired[itdc]&mMask[ip[j]]) > 0) { + triggered |= (0x1<reject) + is_searchable = 0; + if(triggered!=0){ + for(Int_t j=0; j<14; j++){ + if(triggered==accept[j]){ + is_searchable = 1; + break; + } + } + } + } + // We do not restrict search zone around expected main-main collision + // because we would like to be able to identify pile-up from collisions + // with satellites (buggy) + + // If we exit from searching zone + if (was_searchable && !is_searchable) { + if (amp <= ADCMax) { + // Store identified peak + Int_t ibun = ibeg + isam_amp / nsbun; + Int_t tdc = isam_amp % nsbun; + // Look for offset + auto orbit=BCData[ibun].ir.orbit; + std::map::iterator it = mOrbit.find(orbit); + if (it != mOrbit.end()){ + // Subtract pedestal + auto &orbitdata=OrbitData[it->second]; + amp = orbitdata.asFloat(ich) - amp; + }else{ + LOG(ERROR) << "Missing pedestal"; + amp = std::numeric_limits::infinity(); + } + assignTDC(ibun, ibeg, iend, itdc, tdc, amp); + } + amp = std::numeric_limits::infinity(); + isam_amp = 0; + was_searchable = 0; + } + if (is_searchable) { + Int_t mysam = isam % nsbun; + if (mReco[ib_cur].inter[itdc][mysam] < amp) { + amp = mReco[ib_cur].inter[itdc][mysam]; + isam_amp = isam; + } + } + } + // Trigger flag still present at the of the scan + if (is_searchable) { + // Add last identified peak + if (amp <= ADCMax) { + // Store identified peak + Int_t ibun = ibeg + isam_amp / nsbun; + Int_t tdc = isam_amp % nsbun; + // Look for offset + auto orbit=BCData[ibun].ir.orbit; + std::map::iterator it = mOrbit.find(orbit); + if (it != mOrbit.end()){ + // Subtract pedestal + auto &orbitdata=OrbitData[it->second]; + amp = orbitdata.asFloat(ich) - amp; + }else{ + LOG(ERROR) << "Missing pedestal"; + amp = std::numeric_limits::infinity(); + } + assignTDC(ibun, ibeg, iend, itdc, tdc, amp); + } + } +} + +void DigiReco::assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float amp) +{ + constexpr int nsbun = TSN * NTimeBinsPerBC; // Total number of interpolated points per bunch crossing + constexpr int tdc_max = nsbun / 2; + constexpr int tdc_min = -tdc_max; + + // Apply tdc shift correction + Int_t tdc_cor = tdc - tdc_shift[itdc]; + // Correct bunch assignment + if (tdc_cor < tdc_min && ibun >= ibeg) { + // Assign to preceding bunch + ibun = ibun - 1; + tdc_cor = tdc_cor + nsbun; + } else if (tdc_cor >= tdc_max && ibun < iend) { + // Assign to following bunch + ibun = ibun + 1; + tdc_cor = tdc_cor - nsbun; + } + if (tdc_cor < kMinShort) { + LOG(ERROR) << "TDC " << itdc << " " << tdc_cor << " is out of range"; + tdc_cor = kMinShort; + } + if (tdc_cor > kMaxShort) { + LOG(ERROR) << "TDC " << itdc << " " << tdc_cor << " is out of range"; + tdc_cor = kMaxShort; + } + // Assign to correct bunch + int &ihit=mReco[ibun].ntdc[itdc]; + if(ihit Date: Thu, 29 Apr 2021 17:16:27 +0200 Subject: [PATCH 327/770] rename getDictionaryFileName to getAlpideClusterDictionaryFileName --- .../DetectorsCommonDataFormats/NameConf.h | 2 +- DataFormats/Detectors/Common/src/NameConf.cxx | 2 +- .../src/CosmicsMatchingSpec.cxx | 2 +- .../src/TPCITSMatchingSpec.cxx | 2 +- .../ITSMFT/ITS/macros/EVE/DisplayEventsComp.C | 2 +- .../ITSMFT/ITS/macros/test/CheckClusters.C | 2 +- Detectors/ITSMFT/ITS/macros/test/CheckLUtime.C | 2 +- .../ITS/macros/test/CreateDictionaries.C | 18 +++++++++--------- .../ITSMFT/ITS/macros/test/DisplayTrack.C | 2 +- .../macros/test/dictionary_integrity_test.C | 2 +- .../ITSMFT/ITS/workflow/src/ClustererSpec.cxx | 2 +- .../ITS/workflow/src/CookedTrackerSpec.cxx | 2 +- .../ITSMFT/ITS/workflow/src/TrackerSpec.cxx | 2 +- .../ITSMFT/MFT/macros/test/CheckTopologies.C | 18 +++++++++--------- .../ITSMFT/MFT/workflow/src/ClustererSpec.cxx | 2 +- .../ITSMFT/MFT/workflow/src/TrackerSpec.cxx | 2 +- .../common/workflow/src/STFDecoderSpec.cxx | 4 ++-- macro/compareTopologyDistributions.C | 2 +- macro/run_clus_itsSA.C | 2 +- macro/run_primary_vertexer_ITS.C | 2 +- macro/run_trac_ca_its.C | 2 +- macro/run_trac_its.C | 2 +- 22 files changed, 39 insertions(+), 39 deletions(-) diff --git a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h index 66cf2ddd4e6af..968ca70b54656 100644 --- a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h +++ b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h @@ -80,7 +80,7 @@ class NameConf static std::string getGeomFileName(const std::string_view prefix = ""); // Filename to for decoding dictionaries - static std::string getDictionaryFileName(DId det, const std::string_view prefix = "", const std::string_view ext = ""); + static std::string getAlpideClusterDictionaryFileName(DId det, const std::string_view prefix = "", const std::string_view ext = ""); // Filename to store material LUT file static std::string getMatLUTFileName(const std::string_view prefix = ""); diff --git a/DataFormats/Detectors/Common/src/NameConf.cxx b/DataFormats/Detectors/Common/src/NameConf.cxx index 78c6af08ced06..44038743b1f6c 100644 --- a/DataFormats/Detectors/Common/src/NameConf.cxx +++ b/DataFormats/Detectors/Common/src/NameConf.cxx @@ -62,7 +62,7 @@ std::string NameConf::getCutProcFileName(std::string_view prefix) } // Filename to store ITSMFT dictionary -std::string NameConf::getDictionaryFileName(DId det, const std::string_view prefix, const std::string_view ext) +std::string NameConf::getAlpideClusterDictionaryFileName(DId det, const std::string_view prefix, const std::string_view ext) { // check if the prefix is an existing path if (pathIsDirectory(prefix)) { diff --git a/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx index 16fc61fde220b..992c1526f17ef 100644 --- a/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx @@ -87,7 +87,7 @@ void CosmicsMatchingSpec::init(InitContext& ic) } // std::string dictPath = ic.options().get("its-dictionary-path"); - std::string dictFile = o2::base::NameConf::getDictionaryFileName(DetID::ITS, dictPath, ".bin"); + std::string dictFile = o2::base::NameConf::getAlpideClusterDictionaryFileName(DetID::ITS, dictPath, ".bin"); auto itsDict = std::make_unique(); if (o2::base::NameConf::pathExists(dictFile)) { itsDict->readBinaryFile(dictFile); diff --git a/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx index 0129e0c2ac9fb..010b914b37d52 100644 --- a/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx @@ -93,7 +93,7 @@ void TPCITSMatchingDPL::init(InitContext& ic) mMatching.setVDriftCalib(mCalibMode); // std::string dictPath = ic.options().get("its-dictionary-path"); - std::string dictFile = o2::base::NameConf::getDictionaryFileName(o2::detectors::DetID::ITS, dictPath, ".bin"); + std::string dictFile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::ITS, dictPath, ".bin"); if (o2::base::NameConf::pathExists(dictFile)) { mITSDict.readBinaryFile(dictFile); LOG(INFO) << "Matching is running with a provided ITS dictionary: " << dictFile; diff --git a/Detectors/ITSMFT/ITS/macros/EVE/DisplayEventsComp.C b/Detectors/ITSMFT/ITS/macros/EVE/DisplayEventsComp.C index 91aec1299b87c..175e5e016a82b 100644 --- a/Detectors/ITSMFT/ITS/macros/EVE/DisplayEventsComp.C +++ b/Detectors/ITSMFT/ITS/macros/EVE/DisplayEventsComp.C @@ -430,7 +430,7 @@ void init(int entry = 0, int chip = 13, std::string tracfile = "o2trac_its.root", std::string inputGeom = "") { - dict.readBinaryFile(o2::base::NameConf::getDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin")); + dict.readBinaryFile(o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin")); TEveManager::Create(kTRUE, "V"); TEveBrowser* browser = gEve->GetBrowser(); diff --git a/Detectors/ITSMFT/ITS/macros/test/CheckClusters.C b/Detectors/ITSMFT/ITS/macros/test/CheckClusters.C index d48808d06bc10..0de7a42637778 100644 --- a/Detectors/ITSMFT/ITS/macros/test/CheckClusters.C +++ b/Detectors/ITSMFT/ITS/macros/test/CheckClusters.C @@ -70,7 +70,7 @@ void CheckClusters(std::string clusfile = "o2clus_its.root", std::string hitfile pattBranch->SetAddress(&patternsPtr); } if (dictfile.empty()) { - dictfile = o2::base::NameConf::getDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin"); + dictfile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin"); } o2::itsmft::TopologyDictionary dict; std::ifstream file(dictfile.c_str()); diff --git a/Detectors/ITSMFT/ITS/macros/test/CheckLUtime.C b/Detectors/ITSMFT/ITS/macros/test/CheckLUtime.C index 7c4096d7286c6..f76dfaeaf2358 100644 --- a/Detectors/ITSMFT/ITS/macros/test/CheckLUtime.C +++ b/Detectors/ITSMFT/ITS/macros/test/CheckLUtime.C @@ -37,7 +37,7 @@ void CheckLUtime(std::string clusfile = "o2clus_its.root", std::string dictfile sw.Start(); if (dictfile.empty()) { - dictfile = o2::base::NameConf::getDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin"); + dictfile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin"); } std::ifstream file(dictfile.c_str()); if (file.good()) { diff --git a/Detectors/ITSMFT/ITS/macros/test/CreateDictionaries.C b/Detectors/ITSMFT/ITS/macros/test/CreateDictionaries.C index 175dda2f52f48..0ed7ae34b946a 100644 --- a/Detectors/ITSMFT/ITS/macros/test/CreateDictionaries.C +++ b/Detectors/ITSMFT/ITS/macros/test/CreateDictionaries.C @@ -259,9 +259,9 @@ void CreateDictionaries(bool saveDeltas = false, completeDictionary.setThreshold(0.0001); completeDictionary.groupRareTopologies(); - completeDictionary.printDictionaryBinary(o2::base::NameConf::getDictionaryFileName(dID, "", ".bin")); - completeDictionary.printDictionary(o2::base::NameConf::getDictionaryFileName(dID, "", ".txt")); - completeDictionary.saveDictionaryRoot(o2::base::NameConf::getDictionaryFileName(dID, "", ".root")); + completeDictionary.printDictionaryBinary(o2::base::NameConf::getAlpideClusterDictionaryFileName(dID, "", ".bin")); + completeDictionary.printDictionary(o2::base::NameConf::getAlpideClusterDictionaryFileName(dID, "", ".txt")); + completeDictionary.saveDictionaryRoot(o2::base::NameConf::getAlpideClusterDictionaryFileName(dID, "", ".root")); TFile histogramOutput("histograms.root", "recreate"); TCanvas* cComplete = new TCanvas("cComplete", "Distribution of all the topologies"); @@ -282,14 +282,14 @@ void CreateDictionaries(bool saveDeltas = false, if (clusLabArr) { noiseDictionary.setThreshold(0.0001); noiseDictionary.groupRareTopologies(); - noiseDictionary.printDictionaryBinary(o2::base::NameConf::getDictionaryFileName(dID, "noise", ".bin")); - noiseDictionary.printDictionary(o2::base::NameConf::getDictionaryFileName(dID, "noise", ".txt")); - noiseDictionary.saveDictionaryRoot(o2::base::NameConf::getDictionaryFileName(dID, "noise", ".root")); + noiseDictionary.printDictionaryBinary(o2::base::NameConf::getAlpideClusterDictionaryFileName(dID, "noise", ".bin")); + noiseDictionary.printDictionary(o2::base::NameConf::getAlpideClusterDictionaryFileName(dID, "noise", ".txt")); + noiseDictionary.saveDictionaryRoot(o2::base::NameConf::getAlpideClusterDictionaryFileName(dID, "noise", ".root")); signalDictionary.setThreshold(0.0001); signalDictionary.groupRareTopologies(); - signalDictionary.printDictionaryBinary(o2::base::NameConf::getDictionaryFileName(dID, "signal", ".bin")); - signalDictionary.printDictionary(o2::base::NameConf::getDictionaryFileName(dID, "signal", ".txt")); - signalDictionary.saveDictionaryRoot(o2::base::NameConf::getDictionaryFileName(dID, "signal", ".root")); + signalDictionary.printDictionaryBinary(o2::base::NameConf::getAlpideClusterDictionaryFileName(dID, "signal", ".bin")); + signalDictionary.printDictionary(o2::base::NameConf::getAlpideClusterDictionaryFileName(dID, "signal", ".txt")); + signalDictionary.saveDictionaryRoot(o2::base::NameConf::getAlpideClusterDictionaryFileName(dID, "signal", ".root")); cNoise = new TCanvas("cNoise", "Distribution of noise topologies"); cNoise->cd(); cNoise->SetLogy(); diff --git a/Detectors/ITSMFT/ITS/macros/test/DisplayTrack.C b/Detectors/ITSMFT/ITS/macros/test/DisplayTrack.C index e4d47cd3666f9..156eab7e735b3 100644 --- a/Detectors/ITSMFT/ITS/macros/test/DisplayTrack.C +++ b/Detectors/ITSMFT/ITS/macros/test/DisplayTrack.C @@ -130,7 +130,7 @@ void DisplayTrack(Int_t event = 0, Int_t track = 0, std::string tracfile = "o2tr std::vector* clusArr = nullptr; tree->SetBranchAddress("ITSClusterComp", &clusArr); if (dictfile.empty()) { - dictfile = o2::base::NameConf::getDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin"); + dictfile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin"); } o2::itsmft::TopologyDictionary dict; std::ifstream file(dictfile.c_str()); diff --git a/Detectors/ITSMFT/ITS/macros/test/dictionary_integrity_test.C b/Detectors/ITSMFT/ITS/macros/test/dictionary_integrity_test.C index c78e9cdd8b99d..b47994711a414 100644 --- a/Detectors/ITSMFT/ITS/macros/test/dictionary_integrity_test.C +++ b/Detectors/ITSMFT/ITS/macros/test/dictionary_integrity_test.C @@ -20,7 +20,7 @@ void dictionary_integrity_test(std::string dictfile = "", std::string output_nam TopologyDictionary dict; if (dictfile.empty()) { - dictfile = o2::base::NameConf::getDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin"); + dictfile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin"); } dict.readBinaryFile(dictfile); LookUp finder(dictfile); diff --git a/Detectors/ITSMFT/ITS/workflow/src/ClustererSpec.cxx b/Detectors/ITSMFT/ITS/workflow/src/ClustererSpec.cxx index 094b60ec5370d..ec6ebeb5ad1e0 100644 --- a/Detectors/ITSMFT/ITS/workflow/src/ClustererSpec.cxx +++ b/Detectors/ITSMFT/ITS/workflow/src/ClustererSpec.cxx @@ -63,7 +63,7 @@ void ClustererDPL::init(InitContext& ic) mClusterer->setMaxRowColDiffToMask(clParams.maxRowColDiffToMask); std::string dictPath = ic.options().get("its-dictionary-path"); - std::string dictFile = o2::base::NameConf::getDictionaryFileName(o2::detectors::DetID::ITS, dictPath, ".bin"); + std::string dictFile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::ITS, dictPath, ".bin"); if (o2::base::NameConf::pathExists(dictFile)) { mClusterer->loadDictionary(dictFile); LOG(INFO) << "ITSClusterer running with a provided dictionary: " << dictFile; diff --git a/Detectors/ITSMFT/ITS/workflow/src/CookedTrackerSpec.cxx b/Detectors/ITSMFT/ITS/workflow/src/CookedTrackerSpec.cxx index 1103157c3adbf..63efd2a45ace5 100644 --- a/Detectors/ITSMFT/ITS/workflow/src/CookedTrackerSpec.cxx +++ b/Detectors/ITSMFT/ITS/workflow/src/CookedTrackerSpec.cxx @@ -78,7 +78,7 @@ void CookedTrackerDPL::init(InitContext& ic) } std::string dictPath = ic.options().get("its-dictionary-path"); - std::string dictFile = o2::base::NameConf::getDictionaryFileName(o2::detectors::DetID::ITS, dictPath, ".bin"); + std::string dictFile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::ITS, dictPath, ".bin"); if (o2::base::NameConf::pathExists(dictFile)) { mDict.readBinaryFile(dictFile); LOG(INFO) << "Tracker running with a provided dictionary: " << dictFile; diff --git a/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx b/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx index 7e05671323620..a07d12bb13904 100644 --- a/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx +++ b/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx @@ -135,7 +135,7 @@ void TrackerDPL::init(InitContext& ic) } std::string dictPath = ic.options().get("its-dictionary-path"); - std::string dictFile = o2::base::NameConf::getDictionaryFileName(o2::detectors::DetID::ITS, dictPath, ".bin"); + std::string dictFile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::ITS, dictPath, ".bin"); if (o2::base::NameConf::pathExists(dictFile)) { mDict.readBinaryFile(dictFile); LOG(INFO) << "Tracker running with a provided dictionary: " << dictFile; diff --git a/Detectors/ITSMFT/MFT/macros/test/CheckTopologies.C b/Detectors/ITSMFT/MFT/macros/test/CheckTopologies.C index 5b67403432d68..d1e3ff5e38496 100644 --- a/Detectors/ITSMFT/MFT/macros/test/CheckTopologies.C +++ b/Detectors/ITSMFT/MFT/macros/test/CheckTopologies.C @@ -245,9 +245,9 @@ void CheckTopologies(std::string clusfile = "mftclusters.root", completeDictionary.setThreshold(0.0001); completeDictionary.groupRareTopologies(); - completeDictionary.printDictionaryBinary(o2::base::NameConf::getDictionaryFileName(dID, "", ".bin")); - completeDictionary.printDictionary(o2::base::NameConf::getDictionaryFileName(dID, "", ".txt")); - completeDictionary.saveDictionaryRoot(o2::base::NameConf::getDictionaryFileName(dID, "", ".root")); + completeDictionary.printDictionaryBinary(o2::base::NameConf::getAlpideClusterDictionaryFileName(dID, "", ".bin")); + completeDictionary.printDictionary(o2::base::NameConf::getAlpideClusterDictionaryFileName(dID, "", ".txt")); + completeDictionary.saveDictionaryRoot(o2::base::NameConf::getAlpideClusterDictionaryFileName(dID, "", ".root")); TFile histogramOutput("histograms.root", "recreate"); TCanvas* cComplete = new TCanvas("cComplete", "Distribution of all the topologies"); @@ -268,14 +268,14 @@ void CheckTopologies(std::string clusfile = "mftclusters.root", if (clusLabArr) { noiseDictionary.setThreshold(0.0001); noiseDictionary.groupRareTopologies(); - noiseDictionary.printDictionaryBinary(o2::base::NameConf::getDictionaryFileName(dID, "noise", ".bin")); - noiseDictionary.printDictionary(o2::base::NameConf::getDictionaryFileName(dID, "noise", ".txt")); - noiseDictionary.saveDictionaryRoot(o2::base::NameConf::getDictionaryFileName(dID, "noise", ".root")); + noiseDictionary.printDictionaryBinary(o2::base::NameConf::getAlpideClusterDictionaryFileName(dID, "noise", ".bin")); + noiseDictionary.printDictionary(o2::base::NameConf::getAlpideClusterDictionaryFileName(dID, "noise", ".txt")); + noiseDictionary.saveDictionaryRoot(o2::base::NameConf::getAlpideClusterDictionaryFileName(dID, "noise", ".root")); signalDictionary.setThreshold(0.0001); signalDictionary.groupRareTopologies(); - signalDictionary.printDictionaryBinary(o2::base::NameConf::getDictionaryFileName(dID, "signal", ".bin")); - signalDictionary.printDictionary(o2::base::NameConf::getDictionaryFileName(dID, "signal", ".txt")); - signalDictionary.saveDictionaryRoot(o2::base::NameConf::getDictionaryFileName(dID, "signal", ".root")); + signalDictionary.printDictionaryBinary(o2::base::NameConf::getAlpideClusterDictionaryFileName(dID, "signal", ".bin")); + signalDictionary.printDictionary(o2::base::NameConf::getAlpideClusterDictionaryFileName(dID, "signal", ".txt")); + signalDictionary.saveDictionaryRoot(o2::base::NameConf::getAlpideClusterDictionaryFileName(dID, "signal", ".root")); cNoise = new TCanvas("cNoise", "Distribution of noise topologies"); cNoise->cd(); cNoise->SetLogy(); diff --git a/Detectors/ITSMFT/MFT/workflow/src/ClustererSpec.cxx b/Detectors/ITSMFT/MFT/workflow/src/ClustererSpec.cxx index 388f18514b414..6d28683b6a1af 100644 --- a/Detectors/ITSMFT/MFT/workflow/src/ClustererSpec.cxx +++ b/Detectors/ITSMFT/MFT/workflow/src/ClustererSpec.cxx @@ -69,7 +69,7 @@ void ClustererDPL::init(InitContext& ic) mClusterer->setMaxRowColDiffToMask(clParams.maxRowColDiffToMask); std::string dictPath = ic.options().get("mft-dictionary-path"); - std::string dictFile = o2::base::NameConf::getDictionaryFileName(o2::detectors::DetID::MFT, dictPath, ".bin"); + std::string dictFile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::MFT, dictPath, ".bin"); if (o2::base::NameConf::pathExists(dictFile)) { mClusterer->loadDictionary(dictFile); LOG(INFO) << "MFTClusterer running with a provided dictionary: " << dictFile; diff --git a/Detectors/ITSMFT/MFT/workflow/src/TrackerSpec.cxx b/Detectors/ITSMFT/MFT/workflow/src/TrackerSpec.cxx index 250d47171ed8e..2c5ce1dca0386 100644 --- a/Detectors/ITSMFT/MFT/workflow/src/TrackerSpec.cxx +++ b/Detectors/ITSMFT/MFT/workflow/src/TrackerSpec.cxx @@ -71,7 +71,7 @@ void TrackerDPL::init(InitContext& ic) } std::string dictPath = ic.options().get("mft-dictionary-path"); - std::string dictFile = o2::base::NameConf::getDictionaryFileName(o2::detectors::DetID::MFT, dictPath, ".bin"); + std::string dictFile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::MFT, dictPath, ".bin"); if (o2::base::NameConf::pathExists(dictFile)) { mDict.readBinaryFile(dictFile); LOG(INFO) << "Tracker running with a provided dictionary: " << dictFile; diff --git a/Detectors/ITSMFT/common/workflow/src/STFDecoderSpec.cxx b/Detectors/ITSMFT/common/workflow/src/STFDecoderSpec.cxx index bf2cdb9a6ce99..e56c5edb7d230 100644 --- a/Detectors/ITSMFT/common/workflow/src/STFDecoderSpec.cxx +++ b/Detectors/ITSMFT/common/workflow/src/STFDecoderSpec.cxx @@ -61,7 +61,7 @@ void STFDecoder::init(InitContext& ic) mDecoder->setFormat(ic.options().get("old-format") ? GBTLink::OldFormat : GBTLink::NewFormat); mDecoder->setVerbosity(ic.options().get("decoder-verbosity")); mDecoder->setFillCalibData(mDoCalibData); - std::string noiseFile = o2::base::NameConf::getDictionaryFileName(detID, mNoiseName, ".root"); + std::string noiseFile = o2::base::NameConf::getAlpideClusterDictionaryFileName(detID, mNoiseName, ".root"); if (o2::base::NameConf::pathExists(noiseFile)) { TFile* f = TFile::Open(noiseFile.data(), "old"); auto pnoise = (NoiseMap*)f->Get("Noise"); @@ -89,7 +89,7 @@ void STFDecoder::init(InitContext& ic) mClusterer->setMaxBCSeparationToMask(nbc); mClusterer->setMaxRowColDiffToMask(clParams.maxRowColDiffToMask); - std::string dictFile = o2::base::NameConf::getDictionaryFileName(detID, mDictName, ".bin"); + std::string dictFile = o2::base::NameConf::getAlpideClusterDictionaryFileName(detID, mDictName, ".bin"); if (o2::base::NameConf::pathExists(dictFile)) { mClusterer->loadDictionary(dictFile); LOG(INFO) << mSelfName << " clusterer running with a provided dictionary: " << dictFile; diff --git a/macro/compareTopologyDistributions.C b/macro/compareTopologyDistributions.C index 1224eb8a5e120..d05c3b46796c9 100644 --- a/macro/compareTopologyDistributions.C +++ b/macro/compareTopologyDistributions.C @@ -24,7 +24,7 @@ void compareTopologyDistributions( string output_file_name = "comparison.root") { if (dictionary_file_name.empty()) { - dictionary_file_name = o2::base::NameConf::getDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin"); + dictionary_file_name = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin"); } o2::itsmft::TopologyDictionary dict; dict.readBinaryFile(dictionary_file_name.c_str()); diff --git a/macro/run_clus_itsSA.C b/macro/run_clus_itsSA.C index b0e080bd30edb..7a4391275b0e6 100644 --- a/macro/run_clus_itsSA.C +++ b/macro/run_clus_itsSA.C @@ -42,7 +42,7 @@ void run_clus_itsSA(std::string inputfile = "rawits.bin", // input file name clus->setMaxROframe(2 << 21); // about 3 cluster files per a raw data chunk if (dictionaryfile.empty()) { - dictionaryfile = o2::base::NameConf::getDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin"); + dictionaryfile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin"); } std::ifstream file(dictionaryfile.c_str()); if (file.good()) { diff --git a/macro/run_primary_vertexer_ITS.C b/macro/run_primary_vertexer_ITS.C index fc0599a84ae91..b9729119664b8 100644 --- a/macro/run_primary_vertexer_ITS.C +++ b/macro/run_primary_vertexer_ITS.C @@ -124,7 +124,7 @@ int run_primary_vertexer_ITS(const GPUDataTypes::DeviceType dtype = GPUDataTypes o2::itsmft::TopologyDictionary dict; if (dictfile.empty()) { - dictfile = o2::base::NameConf::getDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin"); + dictfile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin"); } std::ifstream file(dictfile.c_str()); if (file.good()) { diff --git a/macro/run_trac_ca_its.C b/macro/run_trac_ca_its.C index 5595362209949..acd13ec29992a 100644 --- a/macro/run_trac_ca_its.C +++ b/macro/run_trac_ca_its.C @@ -164,7 +164,7 @@ void run_trac_ca_its(bool cosmics = false, o2::itsmft::TopologyDictionary dict; if (dictfile.empty()) { - dictfile = o2::base::NameConf::getDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin"); + dictfile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin"); } std::ifstream file(dictfile.c_str()); if (file.good()) { diff --git a/macro/run_trac_its.C b/macro/run_trac_its.C index 252db1a899072..1cc19aa0873d3 100644 --- a/macro/run_trac_its.C +++ b/macro/run_trac_its.C @@ -123,7 +123,7 @@ void run_trac_its(std::string path = "./", std::string outputfile = "o2trac_its. o2::itsmft::TopologyDictionary dict; if (dictfile.empty()) { - dictfile = o2::base::NameConf::getDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin"); + dictfile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::ITS, "", ".bin"); } std::ifstream file(dictfile.c_str()); if (file.good()) { From 5868b9c1bd5fc4667cbd3540c686410577109856 Mon Sep 17 00:00:00 2001 From: shahoian Date: Thu, 29 Apr 2021 19:47:51 +0200 Subject: [PATCH 328/770] Promote StringUtils to static class, alias path methods to boost::filesystem Also collect in StringUtils some common methods like tokenize(string) etc. --- CCDB/src/CcdbApi.cxx | 4 +- Common/Utils/CMakeLists.txt | 3 +- .../Utils/include/CommonUtils/MemFileHelper.h | 2 +- .../Utils/include/CommonUtils/StringUtils.h | 146 +++++++++--------- Common/Utils/src/CommonUtilsLinkDef.h | 1 + Common/Utils/src/ConfigurableParam.cxx | 66 ++------ Common/Utils/src/StringUtils.cxx | 64 ++++++++ .../EncodedBlocks.h | 12 +- .../DetectorsCommonDataFormats/NameConf.h | 26 +--- DataFormats/Detectors/Common/src/NameConf.cxx | 58 +++---- .../Reconstruction/src/PrimaryVertex.cxx | 8 +- .../Base/include/DetectorsBase/CTFCoderBase.h | 2 +- Detectors/CPV/simulation/src/RawCreator.cxx | 2 +- Detectors/CPV/workflow/src/ReaderSpec.cxx | 4 +- Detectors/CTF/workflow/src/CTFReaderSpec.cxx | 6 +- Detectors/CTF/workflow/src/CTFWriterSpec.cxx | 16 +- Detectors/EMCAL/simulation/src/RawCreator.cxx | 2 +- .../EMCAL/workflow/src/PublisherSpec.cxx | 4 +- .../FIT/FDD/simulation/src/digit2raw.cxx | 4 +- .../FIT/FDD/workflow/src/DigitReaderSpec.cxx | 4 +- .../FDD/workflow/src/RecPointReaderSpec.cxx | 4 +- .../FIT/FT0/simulation/src/Digits2Raw.cxx | 4 +- Detectors/FIT/FT0/simulation/src/digi2raw.cxx | 2 +- .../FIT/FT0/workflow/src/DigitReaderSpec.cxx | 4 +- .../FT0/workflow/src/RecPointReaderSpec.cxx | 4 +- .../FIT/FV0/simulation/src/digit2raw.cxx | 4 +- .../FIT/FV0/workflow/src/DigitReaderSpec.cxx | 4 +- .../readers/src/PrimaryVertexReaderSpec.cxx | 4 +- .../readers/src/SecondaryVertexReaderSpec.cxx | 4 +- .../readers/src/TrackCosmicsReaderSpec.cxx | 4 +- .../readers/src/TrackTPCITSReaderSpec.cxx | 4 +- .../src/CosmicsMatchingSpec.cxx | 4 +- .../src/PrimaryVertexingSpec.cxx | 2 +- .../src/SecondaryVertexingSpec.cxx | 2 +- .../src/TPCITSMatchingSpec.cxx | 4 +- .../tofworkflow/src/CalibInfoReaderSpec.cxx | 2 +- .../tofworkflow/src/RecoWorkflowSpec.cxx | 2 +- .../src/RecoWorkflowWithTPCSpec.cxx | 2 +- .../tofworkflow/src/TOFMatchedReaderSpec.cxx | 6 +- .../HMPID/workflow/src/DigitsToRawSpec.cxx | 4 +- .../ITSMFT/ITS/simulation/src/digi2raw.cxx | 20 +-- .../ITSMFT/ITS/workflow/src/ClustererSpec.cxx | 2 +- .../ITS/workflow/src/CookedTrackerSpec.cxx | 4 +- .../ITS/workflow/src/TrackReaderSpec.cxx | 4 +- .../ITSMFT/ITS/workflow/src/TrackerSpec.cxx | 6 +- .../ITS/workflow/src/VertexReaderSpec.cxx | 4 +- .../ITSMFT/MFT/simulation/src/digi2raw.cxx | 18 +-- .../MFT/workflow/src/ClusterReaderSpec.cxx | 4 +- .../ITSMFT/MFT/workflow/src/ClustererSpec.cxx | 2 +- .../ITSMFT/MFT/workflow/src/TrackerSpec.cxx | 4 +- .../reconstruction/src/RawPixelDecoder.cxx | 2 +- .../common/workflow/src/ClusterReaderSpec.cxx | 4 +- .../common/workflow/src/DigitReaderSpec.cxx | 4 +- .../common/workflow/src/STFDecoderSpec.cxx | 6 +- .../MUON/MID/Workflow/src/DigitReaderSpec.cxx | 4 +- .../MUON/MID/Workflow/src/RawWriterSpec.cxx | 4 +- Detectors/PHOS/simulation/src/RawCreator.cxx | 2 +- Detectors/PHOS/workflow/src/ReaderSpec.cxx | 8 +- Detectors/Raw/src/HBFUtilsInitializer.cxx | 2 +- Detectors/Raw/src/RawFileWriter.cxx | 6 +- Detectors/Raw/src/rawfileSplit.cxx | 20 +-- Detectors/Raw/test/testRawReaderWriter.cxx | 2 +- Detectors/TOF/reconstruction/src/Encoder.cxx | 8 +- Detectors/TOF/simulation/src/digi2raw.cxx | 8 +- .../TOF/workflow/src/ClusterReaderSpec.cxx | 4 +- .../TOF/workflow/src/DigitReaderSpec.cxx | 4 +- .../TOF/workflow/src/TOFRawWriterSpec.cxx | 2 +- Detectors/TPC/workflow/src/PublisherSpec.cxx | 4 +- .../TPC/workflow/src/TrackReaderSpec.cxx | 4 +- Detectors/TRD/simulation/src/Trap2CRU.cxx | 10 +- Detectors/TRD/simulation/src/trap2raw.cxx | 2 +- .../workflow/src/TRDGlobalTrackingSpec.cxx | 2 +- .../workflow/src/TRDTrackletReaderSpec.cxx | 8 +- Detectors/ZDC/simulation/src/Digits2Raw.cxx | 2 +- Detectors/ZDC/simulation/src/digi2raw.cxx | 2 +- .../ZDC/workflow/src/DigitReaderSpec.cxx | 4 +- 76 files changed, 345 insertions(+), 355 deletions(-) create mode 100644 Common/Utils/src/StringUtils.cxx diff --git a/CCDB/src/CcdbApi.cxx b/CCDB/src/CcdbApi.cxx index b5a61bb45afed..a6108e3f43fe0 100644 --- a/CCDB/src/CcdbApi.cxx +++ b/CCDB/src/CcdbApi.cxx @@ -429,7 +429,7 @@ void* CcdbApi::extractFromTFile(TFile& file, TClass const* cl) // it could be that object was stored with previous convention // where the classname was taken as key std::string objectName(cl->GetName()); - utils::trim(objectName); + o2::utils::Str::trim(objectName); object = file.GetObjectChecked(objectName.c_str(), cl); LOG(WARN) << "Did not find object under expected name " << CCDBOBJECT_ENTRY; if (!object) { @@ -518,7 +518,7 @@ void* CcdbApi::interpretAsTMemFileAndExtract(char* contentptr, size_t contentsiz auto tcl = tinfo2TClass(tinfo); result = extractFromTFile(memFile, tcl); if (!result) { - LOG(ERROR) << o2::utils::concat_string("Couldn't retrieve object corresponding to ", tcl->GetName(), " from TFile"); + LOG(ERROR) << o2::utils::Str::concat_string("Couldn't retrieve object corresponding to ", tcl->GetName(), " from TFile"); } memFile.Close(); } diff --git a/Common/Utils/CMakeLists.txt b/Common/Utils/CMakeLists.txt index 9f21534c7a367..60905d045f34c 100644 --- a/Common/Utils/CMakeLists.txt +++ b/Common/Utils/CMakeLists.txt @@ -12,9 +12,10 @@ o2_add_library(CommonUtils SOURCES src/TreeStream.cxx src/TreeStreamRedirector.cxx src/RootChain.cxx src/CompStream.cxx src/ShmManager.cxx src/ValueMonitor.cxx + src/StringUtils.cxx src/ConfigurableParamHelper.cxx src/ConfigurableParam.cxx src/RootSerializableKeyValueStore.cxx src/KeyValParam.cxx - PUBLIC_LINK_LIBRARIES ROOT::Hist ROOT::Tree Boost::iostreams O2::CommonDataFormat O2::Headers + PUBLIC_LINK_LIBRARIES ROOT::Hist ROOT::Tree Boost::iostreams Boost::filesystem O2::CommonDataFormat O2::Headers FairLogger::FairLogger) o2_target_root_dictionary(CommonUtils diff --git a/Common/Utils/include/CommonUtils/MemFileHelper.h b/Common/Utils/include/CommonUtils/MemFileHelper.h index 87fa2ba896e81..60afd2cd5107a 100644 --- a/Common/Utils/include/CommonUtils/MemFileHelper.h +++ b/Common/Utils/include/CommonUtils/MemFileHelper.h @@ -78,7 +78,7 @@ struct MemFileHelper { LOG(ERROR) << "Could not retrieve ROOT dictionary for type " << tinfo.name(); } else { clname = tcl->GetName(); - utils::trim(clname); + o2::utils::Str::trim(clname); } return clname; } diff --git a/Common/Utils/include/CommonUtils/StringUtils.h b/Common/Utils/include/CommonUtils/StringUtils.h index 2b73082d13b3f..328eef522bcd0 100644 --- a/Common/Utils/include/CommonUtils/StringUtils.h +++ b/Common/Utils/include/CommonUtils/StringUtils.h @@ -17,116 +17,110 @@ #define ALICEO2_STRINGUTILS_H #include -#include -#include +#include #include +#include namespace o2 { namespace utils { -// Code for trimming coming from https://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring +struct Str { -/** + // Code for trimming coming from https://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring + + /** * Trim from start (in place) * @param s */ -static inline void ltrim(std::string& s) -{ - s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { - return !std::isspace(ch); - })); -} + static inline void ltrim(std::string& s) + { + s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { return !std::isspace(ch); })); + } -/** Trim from end (in place) + /** Trim from end (in place) * * @param s */ -static inline void rtrim(std::string& s) -{ - s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { - return !std::isspace(ch); - }).base(), - s.end()); -} + static inline void rtrim(std::string& s) + { + s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return !std::isspace(ch); }).base(), s.end()); + } -/** + /** * Trim from both ends (in place) * @param s */ -static inline void trim(std::string& s) -{ - ltrim(s); - rtrim(s); -} + static inline void trim(std::string& s) + { + ltrim(s); + rtrim(s); + } -/** + /** * Trim from start (copying) * @param s * @return */ -static inline std::string ltrim_copy(std::string s) -{ - ltrim(s); - return s; -} + static inline std::string ltrim_copy(const std::string& s) + { + std::string ss = s; + ltrim(ss); + return ss; + } -/** + /** * Trim from end (copying) * @param s * @return */ -static inline std::string rtrim_copy(std::string s) -{ - rtrim(s); - return s; -} + static inline std::string rtrim_copy(const std::string& s) + { + std::string ss = s; + rtrim(ss); + return ss; + } -// concatenate arbitrary number of strings -template -std::string concat_string(Ts const&... ts) -{ - std::stringstream s; - (s << ... << ts); - return s.str(); -} + /** + * Trim from both sides (copying) + * @param s + * @return + */ + static inline std::string trim_copy(const std::string& s) + { + std::string ss = s; + rtrim(ss); + ltrim(ss); + return ss; + } -// Check if the path exists -static inline bool pathExists(const std::string_view p) -{ - struct stat buffer; - return (stat(p.data(), &buffer) == 0); -} + // return vector of tokens from the string with provided delimiter. If requested, trim the spaces from tokens + static std::vector tokenize(const std::string& src, char delim, bool trimToken = true); -// Check if the path is a directory -static inline bool pathIsDirectory(const std::string_view p) -{ - struct stat buffer; - return (stat(p.data(), &buffer) == 0) && S_ISDIR(buffer.st_mode); -} + // concatenate arbitrary number of strings + template + static std::string concat_string(Ts const&... ts) + { + std::stringstream s; + (s << ... << ts); + return s.str(); + } -static inline std::string getFullPath(const std::string_view p) -{ - std::unique_ptr real_path(realpath(p.data(), nullptr)); - return std::string(real_path.get()); -} + // Check if the path exists + static bool pathExists(const std::string_view p); -static inline std::string rectifyDirectory(const std::string& _dir) -{ - std::string dir = _dir; - if (dir.empty() || dir == "none") { - dir = ""; - } else { - dir = getFullPath(dir); - if (!pathIsDirectory(dir)) { - throw std::runtime_error(fmt::format("{:s} is not an accessible directory", dir)); - } else { - dir += '/'; - } - } - return dir; -} + // Check if the path is a directory + static bool pathIsDirectory(const std::string_view p); + + // create full path + static std::string getFullPath(const std::string_view p); + + // rectify directory, applying convention "none"=="" + static std::string rectifyDirectory(const std::string& _dir); + + ClassDefNV(Str, 1); +}; } // namespace utils } // namespace o2 diff --git a/Common/Utils/src/CommonUtilsLinkDef.h b/Common/Utils/src/CommonUtilsLinkDef.h index db1c758ad2549..108512e47ac86 100644 --- a/Common/Utils/src/CommonUtilsLinkDef.h +++ b/Common/Utils/src/CommonUtilsLinkDef.h @@ -20,6 +20,7 @@ #pragma link C++ class o2::utils::RngHelper; #pragma link C++ class o2::utils::MemFileHelper + ; #pragma link C++ class o2::utils::RootSerializableKeyValueStore::SerializedInfo + ; +#pragma link C++ class o2::utils::Str + ; #pragma link C++ class pair < string, o2::utils::RootSerializableKeyValueStore::SerializedInfo> + ; #pragma link C++ class map < string, o2::utils::RootSerializableKeyValueStore::SerializedInfo> + ; #pragma link C++ class o2::utils::RootSerializableKeyValueStore + ; diff --git a/Common/Utils/src/ConfigurableParam.cxx b/Common/Utils/src/ConfigurableParam.cxx index 17a85800447a0..c5db3730b6a4f 100644 --- a/Common/Utils/src/ConfigurableParam.cxx +++ b/Common/Utils/src/ConfigurableParam.cxx @@ -60,44 +60,6 @@ std::ostream& operator<<(std::ostream& out, ConfigurableParam const& param) return out; } -// ------------------------------------------------------------------ - -// Remove leading whitespace -std::string ltrimSpace(std::string src) -{ - return src.erase(0, src.find_first_not_of(' ')); -} - -// Remove trailing whitespace -std::string rtrimSpace(std::string src) -{ - return src.erase(src.find_last_not_of(' ') + 1); -} - -// Remove leading/trailing whitespace -std::string trimSpace(std::string const& src) -{ - return ltrimSpace(rtrimSpace(src)); -} - -// Split a given string on a delim character, return vector of tokens -// If trim is true, then also remove leading/trailing whitespace of each token. -std::vector splitString(const std::string& src, char delim, bool trim = false) -{ - std::stringstream ss(src); - std::string token; - std::vector tokens; - - while (std::getline(ss, token, delim)) { - token = (trim ? trimSpace(token) : token); - if (!token.empty()) { - tokens.push_back(std::move(token)); - } - } - - return tokens; -} - // Does the given key exist in the boost property tree? bool keyInTree(boost::property_tree::ptree* pt, const std::string& key) { @@ -207,7 +169,7 @@ int EnumLegalValues::getIntValue(const std::string& value) const void ConfigurableParam::writeINI(std::string const& filename, std::string const& keyOnly) { - auto outfilename = o2::utils::concat_string(sOutputDir, filename); + auto outfilename = o2::utils::Str::concat_string(sOutputDir, filename); initPropertyTree(); // update the boost tree before writing if (!keyOnly.empty()) { // write ini for selected key only try { @@ -226,7 +188,7 @@ void ConfigurableParam::writeINI(std::string const& filename, std::string const& boost::property_tree::ptree ConfigurableParam::readConfigFile(std::string const& filepath) { - auto inpfilename = o2::utils::concat_string(sInputDir, filepath); + auto inpfilename = o2::utils::Str::concat_string(sInputDir, filepath); if (!boost::filesystem::exists(inpfilename)) { LOG(FATAL) << inpfilename << " : config file does not exist!"; } @@ -280,7 +242,7 @@ boost::property_tree::ptree ConfigurableParam::readJSON(std::string const& filep void ConfigurableParam::writeJSON(std::string const& filename, std::string const& keyOnly) { initPropertyTree(); // update the boost tree before writing - auto outfilename = o2::utils::concat_string(sOutputDir, filename); + auto outfilename = o2::utils::Str::concat_string(sOutputDir, filename); if (!keyOnly.empty()) { // write ini for selected key only try { boost::property_tree::ptree kTree; @@ -424,7 +386,7 @@ void ConfigurableParam::updateFromFile(std::string const& configFile, std::strin initialize(); } - auto cfgfile = trimSpace(configFile); + auto cfgfile = o2::utils::Str::trim_copy(configFile); if (cfgfile.length() == 0) { return; @@ -433,7 +395,7 @@ void ConfigurableParam::updateFromFile(std::string const& configFile, std::strin boost::property_tree::ptree pt = readConfigFile(cfgfile); std::vector> keyValPairs; - auto request = splitString(paramsList, ',', true); + auto request = o2::utils::Str::tokenize(paramsList, ',', true); std::unordered_map requestMap; for (const auto& par : request) { if (!par.empty()) { @@ -456,7 +418,7 @@ void ConfigurableParam::updateFromFile(std::string const& configFile, std::strin auto value = subKey.second.get_value(); std::string key = mainKey + "." + name; if (!unchangedOnly || getProvenance(key) == kCODE) { - std::pair pair = std::make_pair(key, trimSpace(value)); + std::pair pair = std::make_pair(key, o2::utils::Str::trim_copy(value)); keyValPairs.push_back(pair); } } @@ -490,7 +452,7 @@ void ConfigurableParam::updateFromString(std::string const& configString) initialize(); } - auto cfgStr = trimSpace(configString); + auto cfgStr = o2::utils::Str::trim_copy(configString); if (cfgStr.length() == 0) { return; } @@ -501,13 +463,13 @@ void ConfigurableParam::updateFromString(std::string const& configString) std::vector> pairs; for (auto& token : tokens) { - auto keyval = splitString(token, '='); + auto keyval = o2::utils::Str::tokenize(token, '='); if (keyval.size() != 2) { LOG(FATAL) << "Illegal command-line key/value string: " << token; continue; } - std::pair pair = std::make_pair(keyval[0], trimSpace(keyval[1])); + std::pair pair = std::make_pair(keyval[0], o2::utils::Str::trim_copy(keyval[1])); pairs.push_back(pair); } @@ -534,7 +496,7 @@ void ConfigurableParam::updateFromString(std::string const& configString) // ---- end of helper functions -------------------- // Command-line string is a ;-separated list of key=value params - auto params = splitString(configString, ';', true); + auto params = o2::utils::Str::tokenize(configString, ';', true); // Now split each key=value string into its std::pair parts auto keyValues = toKeyValPairs(params); @@ -543,10 +505,10 @@ void ConfigurableParam::updateFromString(std::string const& configString) const auto& kv = o2::conf::KeyValParam::Instance(); if (getProvenance("keyval.input_dir") != kCODE) { - sInputDir = o2::utils::concat_string(o2::utils::rectifyDirectory(kv.input_dir)); + sInputDir = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(kv.input_dir)); } if (getProvenance("keyval.output_dir") != kCODE) { - sOutputDir = o2::utils::concat_string(o2::utils::rectifyDirectory(kv.output_dir)); + sOutputDir = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(kv.output_dir)); } } @@ -567,7 +529,7 @@ void ConfigurableParam::setValues(std::vector +//#include +#include + +using namespace o2::utils; + +std::vector Str::tokenize(const std::string& src, char delim, bool trimToken) +{ + std::stringstream ss(src); + std::string token; + std::vector tokens; + + while (std::getline(ss, token, delim)) { + if (trimToken) { + trim(token); + } + if (!token.empty()) { + tokens.push_back(std::move(token)); + } + } + return tokens; +} + +bool Str::pathExists(const std::string_view p) +{ + return boost::filesystem::exists(std::string{p}); +} + +bool Str::pathIsDirectory(const std::string_view p) +{ + return boost::filesystem::is_directory(std::string{p}); +} + +std::string Str::getFullPath(const std::string_view p) +{ + return boost::filesystem::canonical(std::string{p}).generic_string(); +} + +std::string Str::rectifyDirectory(const std::string& _dir) +{ + std::string dir = _dir; + if (dir.empty() || dir == "none") { + dir = ""; + } else { + dir = getFullPath(dir); + if (!pathIsDirectory(dir)) { + throw std::runtime_error(fmt::format("{:s} is not an accessible directory", dir)); + } else { + dir += '/'; + } + } + return dir; +} diff --git a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/EncodedBlocks.h b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/EncodedBlocks.h index 149a3a009a25a..cde986ae286b6 100644 --- a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/EncodedBlocks.h +++ b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/EncodedBlocks.h @@ -460,9 +460,9 @@ class EncodedBlocks template void EncodedBlocks::readFromTree(TTree& tree, const std::string& name, int ev) { - readTreeBranch(tree, o2::utils::concat_string(name, "_wrapper."), *this, ev); + readTreeBranch(tree, o2::utils::Str::concat_string(name, "_wrapper."), *this, ev); for (int i = 0; i < N; i++) { - readTreeBranch(tree, o2::utils::concat_string(name, "_block.", std::to_string(i), "."), mBlocks[i]); + readTreeBranch(tree, o2::utils::Str::concat_string(name, "_block.", std::to_string(i), "."), mBlocks[i]); } } @@ -473,11 +473,11 @@ template void EncodedBlocks::readFromTree(VD& vec, TTree& tree, const std::string& name, int ev) { auto tmp = create(vec); - readTreeBranch(tree, o2::utils::concat_string(name, "_wrapper."), *tmp, ev); + readTreeBranch(tree, o2::utils::Str::concat_string(name, "_wrapper."), *tmp, ev); tmp = tmp->expand(vec, tmp->estimateSizeFromMetadata()); for (int i = 0; i < N; i++) { Block bl; - readTreeBranch(tree, o2::utils::concat_string(name, "_block.", std::to_string(i), "."), bl); + readTreeBranch(tree, o2::utils::Str::concat_string(name, "_block.", std::to_string(i), "."), bl); tmp->mBlocks[i].store(bl.getNDict(), bl.getNData(), bl.getNLiterals(), bl.getDict(), bl.getData(), bl.getLiterals()); } } @@ -487,10 +487,10 @@ void EncodedBlocks::readFromTree(VD& vec, TTree& tree, const std::strin template void EncodedBlocks::appendToTree(TTree& tree, const std::string& name) const { - fillTreeBranch(tree, o2::utils::concat_string(name, "_wrapper."), const_cast(*this), WrappersCompressionLevel, WrappersSplitLevel); + fillTreeBranch(tree, o2::utils::Str::concat_string(name, "_wrapper."), const_cast(*this), WrappersCompressionLevel, WrappersSplitLevel); for (int i = 0; i < N; i++) { int compression = mMetadata[i].opt == Metadata::OptStore::ROOTCompression ? 1 : 0; - fillTreeBranch(tree, o2::utils::concat_string(name, "_block.", std::to_string(i), "."), const_cast&>(mBlocks[i]), compression); + fillTreeBranch(tree, o2::utils::Str::concat_string(name, "_block.", std::to_string(i), "."), const_cast&>(mBlocks[i]), compression); } tree.SetEntries(tree.GetEntries() + 1); } diff --git a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h index 968ca70b54656..10cef797c86e7 100644 --- a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h +++ b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h @@ -13,6 +13,7 @@ #include "DetectorsCommonDataFormats/DetID.h" #include "CommonUtils/StringUtils.h" +#include "CommonUtils/ConfigurableParamHelper.h" #include /// \file NameConf.h @@ -28,52 +29,41 @@ class NameConf using DId = o2::detectors::DetID; public: - // Check if the path exists - static bool pathExists(const std::string_view p); - - // Check if the path is a directory - static bool pathIsDirectory(const std::string_view p); - - // Expand to full path - static std::string getFullPath(const std::string_view p); - - // Rectify directory allowing empty one and adding '/' if it is not empty - static std::string rectifyDirectory(const std::string& _dir); // The Hits file name are generated by hardcoded schema, only prefix is mutable to allow the embedding static std::string getHitsFileName(o2::detectors::DetID d, const std::string_view prefix = STANDARDSIMPREFIX) { - return o2::utils::concat_string(prefix, "_", HITS_STRING, d.getName(), ".root"); + return o2::utils::Str::concat_string(prefix, "_", HITS_STRING, d.getName(), ".root"); } // The Digits file name are generated by hardcoded schema, only prefix is mutable to allow the embedding static std::string getDigitsFileName(o2::detectors::DetID d, const std::string_view prefix = STANDARDSIMPREFIX) { - return o2::utils::concat_string(prefix, "_", DIGITS_STRING, d.getName(), ".root"); + return o2::utils::Str::concat_string(prefix, "_", DIGITS_STRING, d.getName(), ".root"); } // Filename to store general run parameters (GRP) static std::string getGRPFileName(const std::string_view prefix = STANDARDSIMPREFIX) { - return o2::utils::concat_string(prefix, "_", GRP_STRING, ".root"); + return o2::utils::Str::concat_string(prefix, "_", GRP_STRING, ".root"); } // Filename to store kinematics + TrackRefs static std::string getMCKinematicsFileName(const std::string_view prefix = STANDARDSIMPREFIX) { - return o2::utils::concat_string(prefix, "_", KINE_STRING, ".root"); + return o2::utils::Str::concat_string(prefix, "_", KINE_STRING, ".root"); } // Filename to store kinematics + TrackRefs static std::string getMCHeadersFileName(const std::string_view prefix = STANDARDSIMPREFIX) { - return o2::utils::concat_string(prefix, "_", MCHEADER_STRING, ".root"); + return o2::utils::Str::concat_string(prefix, "_", MCHEADER_STRING, ".root"); } // Filename to store final MC configuration file static std::string getMCConfigFileName(const std::string_view prefix = STANDARDSIMPREFIX) { - return o2::utils::concat_string(prefix, "_", CONFIG_STRING, ".ini"); + return o2::utils::Str::concat_string(prefix, "_", CONFIG_STRING, ".ini"); } // Filename to store geometry file @@ -121,7 +111,7 @@ class NameConf static constexpr std::string_view CUT_FILE_STRING = "proc-cut"; static constexpr std::string_view CONFIG_STRING = "configuration"; - static constexpr std::string_view DICTFILENAME = "dictionary"; + static constexpr std::string_view ALPIDECLUSDICTFILENAME = "dictionary"; static constexpr std::string_view MATBUDLUT = "matbud"; }; diff --git a/DataFormats/Detectors/Common/src/NameConf.cxx b/DataFormats/Detectors/Common/src/NameConf.cxx index 44038743b1f6c..3802bc4a91e82 100644 --- a/DataFormats/Detectors/Common/src/NameConf.cxx +++ b/DataFormats/Detectors/Common/src/NameConf.cxx @@ -15,82 +15,60 @@ using namespace o2::base; using DId = o2::detectors::DetID; -// Check if the path exists -bool NameConf::pathExists(const std::string_view p) -{ - return o2::utils::pathExists(p); -} - -// Check if the path is a directory -bool NameConf::pathIsDirectory(const std::string_view p) -{ - return o2::utils::pathIsDirectory(p); -} - -std::string NameConf::getFullPath(const std::string_view p) -{ - return o2::utils::getFullPath(p); -} - -std::string NameConf::rectifyDirectory(const std::string& _dir) -{ - return o2::utils::rectifyDirectory(_dir); -} - // Filename to store geometry file std::string NameConf::getGeomFileName(const std::string_view prefix) { // check if the prefix is an existing path - if (pathIsDirectory(prefix)) { - return o2::utils::concat_string(prefix, "/", STANDARDSIMPREFIX, "_", GEOM_FILE_STRING, ".root"); - } else if (pathExists(prefix)) { + if (o2::utils::Str::pathIsDirectory(prefix)) { + return o2::utils::Str::concat_string(prefix, "/", STANDARDSIMPREFIX, "_", GEOM_FILE_STRING, ".root"); + } else if (o2::utils::Str::pathExists(prefix)) { return std::string(prefix); // it is a full file } - return o2::utils::concat_string(prefix.empty() ? STANDARDSIMPREFIX : prefix, "_", GEOM_FILE_STRING, ".root"); + return o2::utils::Str::concat_string(prefix.empty() ? STANDARDSIMPREFIX : prefix, "_", GEOM_FILE_STRING, ".root"); } // Filename to store simulation cuts/process summary std::string NameConf::getCutProcFileName(std::string_view prefix) { // check if the prefix is an existing path - if (pathIsDirectory(prefix)) { - return o2::utils::concat_string(prefix, "/", STANDARDSIMPREFIX, "_", CUT_FILE_STRING, ".dat"); - } else if (pathExists(prefix)) { + if (o2::utils::Str::pathIsDirectory(prefix)) { + return o2::utils::Str::concat_string(prefix, "/", STANDARDSIMPREFIX, "_", CUT_FILE_STRING, ".dat"); + } else if (o2::utils::Str::pathExists(prefix)) { return std::string(prefix); // it is a full file } - return o2::utils::concat_string(prefix.empty() ? STANDARDSIMPREFIX : prefix, "_", CUT_FILE_STRING, ".dat"); + return o2::utils::Str::concat_string(prefix.empty() ? STANDARDSIMPREFIX : prefix, "_", CUT_FILE_STRING, ".dat"); } // Filename to store ITSMFT dictionary std::string NameConf::getAlpideClusterDictionaryFileName(DId det, const std::string_view prefix, const std::string_view ext) { // check if the prefix is an existing path - if (pathIsDirectory(prefix)) { - return o2::utils::concat_string(prefix, "/", det.getName(), DICTFILENAME, ext); - } else if (pathExists(prefix)) { + if (o2::utils::Str::pathIsDirectory(prefix)) { + return o2::utils::Str::concat_string(prefix, "/", det.getName(), ALPIDECLUSDICTFILENAME, ext); + } else if (o2::utils::Str::pathExists(prefix)) { return std::string(prefix); // it is a full file } - return o2::utils::concat_string(prefix, det.getName(), DICTFILENAME, ext); + return o2::utils::Str::concat_string(prefix, det.getName(), ALPIDECLUSDICTFILENAME, ext); } // Filename to store material LUT file std::string NameConf::getMatLUTFileName(const std::string_view prefix) { // check if the prefix is an existing path - if (pathIsDirectory(prefix)) { - return o2::utils::concat_string(prefix, "/", MATBUDLUT, ".root"); - } else if (pathExists(prefix)) { + if (o2::utils::Str::pathIsDirectory(prefix)) { + return o2::utils::Str::concat_string(prefix, "/", MATBUDLUT, ".root"); + } else if (o2::utils::Str::pathExists(prefix)) { return std::string(prefix); // it is a full file } - return o2::utils::concat_string(prefix, MATBUDLUT, ".root"); + return o2::utils::Str::concat_string(prefix, MATBUDLUT, ".root"); } std::string NameConf::getCTFFileName(uint32_t run, uint32_t orb, uint32_t id, const std::string_view prefix) { - return o2::utils::concat_string(prefix, '_', fmt::format("run{:08d}_orbit{:010d}_tf{:010d}", run, orb, id), ".root"); + return o2::utils::Str::concat_string(prefix, '_', fmt::format("run{:08d}_orbit{:010d}_tf{:010d}", run, orb, id), ".root"); } std::string NameConf::getCTFDictFileName() { - return o2::utils::concat_string(CTFDICT, ".root"); + return o2::utils::Str::concat_string(CTFDICT, ".root"); } diff --git a/DataFormats/Reconstruction/src/PrimaryVertex.cxx b/DataFormats/Reconstruction/src/PrimaryVertex.cxx index fb4f7d3b652e5..74c376ca66b1a 100644 --- a/DataFormats/Reconstruction/src/PrimaryVertex.cxx +++ b/DataFormats/Reconstruction/src/PrimaryVertex.cxx @@ -22,11 +22,11 @@ namespace dataformats std::string PrimaryVertex::asString() const { - auto str = o2::utils::concat_string(VertexBase::asString(), - fmt::format("Chi2={:.2f} NCont={:d}: T={:.3f}+-{:.3f} IR=", mChi2, mNContributors, mTimeStamp.getTimeStamp(), mTimeStamp.getTimeStampError()), - mIRMin.asString()); + auto str = o2::utils::Str::concat_string(VertexBase::asString(), + fmt::format("Chi2={:.2f} NCont={:d}: T={:.3f}+-{:.3f} IR=", mChi2, mNContributors, mTimeStamp.getTimeStamp(), mTimeStamp.getTimeStampError()), + mIRMin.asString()); if (!hasUniqueIR()) { - str = o2::utils::concat_string(str, " : ", mIRMax.asString()); + str = o2::utils::Str::concat_string(str, " : ", mIRMax.asString()); } return str; } diff --git a/Detectors/Base/include/DetectorsBase/CTFCoderBase.h b/Detectors/Base/include/DetectorsBase/CTFCoderBase.h index 59da6d5c2187b..adf67a1c2b88d 100644 --- a/Detectors/Base/include/DetectorsBase/CTFCoderBase.h +++ b/Detectors/Base/include/DetectorsBase/CTFCoderBase.h @@ -77,7 +77,7 @@ class CTFCoderBase } protected: - std::string getPrefix() const { return o2::utils::concat_string(mDet.getName(), "_CTF: "); } + std::string getPrefix() const { return o2::utils::Str::concat_string(mDet.getName(), "_CTF: "); } std::vector> mCoders; // encoders/decoders DetID mDet; diff --git a/Detectors/CPV/simulation/src/RawCreator.cxx b/Detectors/CPV/simulation/src/RawCreator.cxx index f4cda9cdf11c1..4e5e6741c2aa5 100644 --- a/Detectors/CPV/simulation/src/RawCreator.cxx +++ b/Detectors/CPV/simulation/src/RawCreator.cxx @@ -110,7 +110,7 @@ int main(int argc, const char** argv) for (auto en : *treereader) { rawwriter.digitsToRaw(*digitbranch, *triggerbranch); } - rawwriter.getWriter().writeConfFile("CPV", "RAWDATA", o2::utils::concat_string(outputdir, "/CPVraw.cfg")); + rawwriter.getWriter().writeConfFile("CPV", "RAWDATA", o2::utils::Str::concat_string(outputdir, "/CPVraw.cfg")); o2::raw::HBFUtils::Instance().print(); diff --git a/Detectors/CPV/workflow/src/ReaderSpec.cxx b/Detectors/CPV/workflow/src/ReaderSpec.cxx index 75f81e0959da6..a61dd1a3cef81 100644 --- a/Detectors/CPV/workflow/src/ReaderSpec.cxx +++ b/Detectors/CPV/workflow/src/ReaderSpec.cxx @@ -43,8 +43,8 @@ DataProcessorSpec getDigitsReaderSpec(bool propagateMC) auto initFunction = [propagateMC](InitContext& ic) { // get the option from the init context - auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("infile")); + auto filename = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("infile")); auto treename = ic.options().get("treename"); auto nofEvents = ic.options().get("nevents"); auto publishingMode = nofEvents == -1 ? RootTreeReader::PublishingMode::Single : RootTreeReader::PublishingMode::Loop; diff --git a/Detectors/CTF/workflow/src/CTFReaderSpec.cxx b/Detectors/CTF/workflow/src/CTFReaderSpec.cxx index a615a0d077a3d..a785748ccbc75 100644 --- a/Detectors/CTF/workflow/src/CTFReaderSpec.cxx +++ b/Detectors/CTF/workflow/src/CTFReaderSpec.cxx @@ -91,7 +91,7 @@ CTFReaderSpec::CTFReaderSpec(DetID::mask_t dm, const std::string& inp) : mDets(d ///_______________________________________ void CTFReaderSpec::init(InitContext& ic) { - mCTFDir = o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")); + mCTFDir = o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")); } ///_______________________________________ @@ -103,7 +103,7 @@ void CTFReaderSpec::run(ProcessingContext& pc) auto cput = mTimer.CpuTime(); mTimer.Start(false); - std::string inputFile = o2::utils::concat_string(mCTFDir, mInput[mNextToProcess]); + std::string inputFile = o2::utils::Str::concat_string(mCTFDir, mInput[mNextToProcess]); LOG(INFO) << "Reading CTF input " << mNextToProcess << ' ' << inputFile; TFile flIn(inputFile.c_str()); @@ -124,7 +124,7 @@ void CTFReaderSpec::run(ProcessingContext& pc) auto setFirstTFOrbit = [&](const std::string& label) { auto* hd = pc.outputs().findMessageHeader({label}); if (!hd) { - throw std::runtime_error(o2::utils::concat_string("failed to find output message header for ", label)); + throw std::runtime_error(o2::utils::Str::concat_string("failed to find output message header for ", label)); } hd->firstTForbit = ctfHeader.firstTForbit; hd->tfCounter = mTFCounter; diff --git a/Detectors/CTF/workflow/src/CTFWriterSpec.cxx b/Detectors/CTF/workflow/src/CTFWriterSpec.cxx index b3b3a3cb875d2..5322b13e03389 100644 --- a/Detectors/CTF/workflow/src/CTFWriterSpec.cxx +++ b/Detectors/CTF/workflow/src/CTFWriterSpec.cxx @@ -121,7 +121,7 @@ void CTFWriterSpec::processDet(o2::framework::ProcessingContext& pc, DetID det, } auto ctfBuffer = pc.inputs().get>(det.getName()); const auto ctfImage = C::getImage(ctfBuffer.data()); - ctfImage.print(o2::utils::concat_string(det.getName(), ": ")); + ctfImage.print(o2::utils::Str::concat_string(det.getName(), ": ")); if (mWriteCTF) { ctfImage.appendToTree(*tree, det.getName()); header.detectors.set(det); @@ -159,7 +159,7 @@ void CTFWriterSpec::storeDictionary(DetID det, CTFHeader& header) auto dictBlocks = C::createDictionaryBlocks(mFreqsAccumulation[det], mFreqsMetaData[det]); auto& h = C::get(dictBlocks.data())->getHeader(); h = *reinterpret_cast::type*>(mHeaders[det].get()); - C::get(dictBlocks.data())->print(o2::utils::concat_string("Storing dictionary for ", det.getName(), ": ")); + C::get(dictBlocks.data())->print(o2::utils::Str::concat_string("Storing dictionary for ", det.getName(), ": ")); C::get(dictBlocks.data())->appendToTree(*mDictTreeOut.get(), det.getName()); // cast to EncodedBlock // mFreqsAccumulation[det].clear(); // mFreqsMetaData[det].clear(); @@ -184,7 +184,7 @@ CTFWriterSpec::CTFWriterSpec(DetID::mask_t dm, uint64_t r, bool doCTF, bool doDi if (isPresent(det)) { auto dictName = dictionaryFileName(det.getName()); if (gSystem->AccessPathName(dictName.c_str()) == 0) { - throw std::runtime_error(o2::utils::concat_string("CTF dictionary creation is requested but ", dictName, " already exists, remove it!")); + throw std::runtime_error(o2::utils::Str::concat_string("CTF dictionary creation is requested but ", dictName, " already exists, remove it!")); } if (!mDictPerDetector) { break; // no point in checking further @@ -197,8 +197,8 @@ CTFWriterSpec::CTFWriterSpec(DetID::mask_t dm, uint64_t r, bool doCTF, bool doDi void CTFWriterSpec::init(InitContext& ic) { mSaveDictAfter = ic.options().get("save-dict-after"); - mDictDir = o2::base::NameConf::rectifyDirectory(ic.options().get("ctf-dict-dir")); - mCTFDir = o2::base::NameConf::rectifyDirectory(ic.options().get("output-dir")); + mDictDir = o2::utils::Str::rectifyDirectory(ic.options().get("ctf-dict-dir")); + mCTFDir = o2::utils::Str::rectifyDirectory(ic.options().get("output-dir")); } void CTFWriterSpec::run(ProcessingContext& pc) @@ -210,7 +210,7 @@ void CTFWriterSpec::run(ProcessingContext& pc) std::unique_ptr fileOut; std::unique_ptr treeOut; if (mWriteCTF) { - fileOut.reset(TFile::Open(o2::utils::concat_string(mCTFDir, o2::base::NameConf::getCTFFileName(dh->runNumber, dh->firstTForbit, dh->tfCounter)).c_str(), "recreate")); + fileOut.reset(TFile::Open(o2::utils::Str::concat_string(mCTFDir, o2::base::NameConf::getCTFFileName(dh->runNumber, dh->firstTForbit, dh->tfCounter)).c_str(), "recreate")); treeOut = std::make_unique(std::string(o2::base::NameConf::CTFTREENAME).c_str(), "O2 CTF tree"); } @@ -284,9 +284,9 @@ std::string CTFWriterSpec::dictionaryFileName(const std::string& detName) if (detName.empty()) { throw std::runtime_error("Per-detector dictionary files are requested but detector name is not provided"); } - return o2::utils::concat_string(mDictDir, detName, '_', o2::base::NameConf::CTFDICT, ".root"); + return o2::utils::Str::concat_string(mDictDir, detName, '_', o2::base::NameConf::CTFDICT, ".root"); } else { - return o2::utils::concat_string(mDictDir, o2::base::NameConf::CTFDICT, ".root"); + return o2::utils::Str::concat_string(mDictDir, o2::base::NameConf::CTFDICT, ".root"); } } diff --git a/Detectors/EMCAL/simulation/src/RawCreator.cxx b/Detectors/EMCAL/simulation/src/RawCreator.cxx index 2b40410b559c6..8a3c3c61c8552 100644 --- a/Detectors/EMCAL/simulation/src/RawCreator.cxx +++ b/Detectors/EMCAL/simulation/src/RawCreator.cxx @@ -121,7 +121,7 @@ int main(int argc, const char** argv) for (auto en : *treereader) { rawwriter.digitsToRaw(*digitbranch, *triggerbranch); } - rawwriter.getWriter().writeConfFile("EMC", "RAWDATA", o2::utils::concat_string(outputdir, "/EMCraw.cfg")); + rawwriter.getWriter().writeConfFile("EMC", "RAWDATA", o2::utils::Str::concat_string(outputdir, "/EMCraw.cfg")); o2::raw::HBFUtils::Instance().print(); diff --git a/Detectors/EMCAL/workflow/src/PublisherSpec.cxx b/Detectors/EMCAL/workflow/src/PublisherSpec.cxx index 1281ce7a6dfb1..666261ef58641 100644 --- a/Detectors/EMCAL/workflow/src/PublisherSpec.cxx +++ b/Detectors/EMCAL/workflow/src/PublisherSpec.cxx @@ -34,8 +34,8 @@ o2::framework::DataProcessorSpec createPublisherSpec(PublisherConf const& config auto initFunction = [config, propagateMC, creator](o2::framework::InitContext& ic) { // get the option from the init context - auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("infile")); + auto filename = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("infile")); auto treename = ic.options().get("treename"); auto dtbrName = ic.options().get(config.databranch.option.c_str()); // databranch name auto trgbrName = ic.options().get(config.triggerrecordbranch.option.c_str()); // triggerbranch name diff --git a/Detectors/FIT/FDD/simulation/src/digit2raw.cxx b/Detectors/FIT/FDD/simulation/src/digit2raw.cxx index 4c97617125118..f2efffc90d507 100644 --- a/Detectors/FIT/FDD/simulation/src/digit2raw.cxx +++ b/Detectors/FIT/FDD/simulation/src/digit2raw.cxx @@ -118,8 +118,8 @@ void digi2raw(const std::string& inpName, const std::string& outDir, bool filePe } m2r.readDigits(outDirName, inpName); - wr.writeConfFile(wr.getOrigin().str, "RAWDATA", o2::utils::concat_string(outDirName, wr.getOrigin().str, "raw.cfg")); - //LOG(INFO)<("input-dir")), - ic.options().get("fdd-digits-infile")); + mInputFileName = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("fdd-digits-infile")); } void DigitReader::run(ProcessingContext& pc) diff --git a/Detectors/FIT/FDD/workflow/src/RecPointReaderSpec.cxx b/Detectors/FIT/FDD/workflow/src/RecPointReaderSpec.cxx index 6576e6d59a87c..9782bbcb2f026 100644 --- a/Detectors/FIT/FDD/workflow/src/RecPointReaderSpec.cxx +++ b/Detectors/FIT/FDD/workflow/src/RecPointReaderSpec.cxx @@ -38,8 +38,8 @@ RecPointReader::RecPointReader(bool useMC) void RecPointReader::init(InitContext& ic) { - mInputFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("fdd-recpoints-infile")); + mInputFileName = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("fdd-recpoints-infile")); connectTree(mInputFileName); } diff --git a/Detectors/FIT/FT0/simulation/src/Digits2Raw.cxx b/Detectors/FIT/FT0/simulation/src/Digits2Raw.cxx index 3ea2f9ea8c1f9..800b7a5379cdb 100644 --- a/Detectors/FIT/FT0/simulation/src/Digits2Raw.cxx +++ b/Detectors/FIT/FT0/simulation/src/Digits2Raw.cxx @@ -114,12 +114,12 @@ void Digits2Raw::readDigits(const std::string& outDir, const std::string& fileDi mEndPointID = uint32_t(1); mFeeID = uint64_t(ilink); } - std::string outFileLink = mOutputPerLink ? o2::utils::concat_string(outDir, "ft0_link", std::to_string(ilink), ".raw") : o2::utils::concat_string(outDir, "ft0.raw"); + std::string outFileLink = mOutputPerLink ? o2::utils::Str::concat_string(outDir, "ft0_link", std::to_string(ilink), ".raw") : o2::utils::Str::concat_string(outDir, "ft0.raw"); mWriter.registerLink(mFeeID, mCruID, mLinkID, mEndPointID, outFileLink); LOG(INFO) << " registered links " << mLinkID << " endpoint " << mEndPointID; } //TCM - std::string outFileLink = mOutputPerLink ? o2::utils::concat_string(outDir, "ft0_link", std::to_string(NPMs - 1), ".raw") : o2::utils::concat_string(outDir, "ft0.raw"); + std::string outFileLink = mOutputPerLink ? o2::utils::Str::concat_string(outDir, "ft0_link", std::to_string(NPMs - 1), ".raw") : o2::utils::Str::concat_string(outDir, "ft0.raw"); mWriter.registerLink(mLinkTCM + 8, mCruID, mLinkTCM, 0, outFileLink); LOG(INFO) << " registered link TCM " << mLinkTCM; diff --git a/Detectors/FIT/FT0/simulation/src/digi2raw.cxx b/Detectors/FIT/FT0/simulation/src/digi2raw.cxx index 54b6096164011..5fb01edda1814 100644 --- a/Detectors/FIT/FT0/simulation/src/digi2raw.cxx +++ b/Detectors/FIT/FT0/simulation/src/digi2raw.cxx @@ -120,7 +120,7 @@ void digi2raw(const std::string& inpName, const std::string& outDir, int verbosi } m2r.readDigits(outDirName, inpName); - wr.writeConfFile(wr.getOrigin().str, "RAWDATA", o2::utils::concat_string(outDirName, wr.getOrigin().str, "raw.cfg")); + wr.writeConfFile(wr.getOrigin().str, "RAWDATA", o2::utils::Str::concat_string(outDirName, wr.getOrigin().str, "raw.cfg")); // swTot.Stop(); swTot.Print(); diff --git a/Detectors/FIT/FT0/workflow/src/DigitReaderSpec.cxx b/Detectors/FIT/FT0/workflow/src/DigitReaderSpec.cxx index 1752e84179cdb..d504e5e6d75ed 100644 --- a/Detectors/FIT/FT0/workflow/src/DigitReaderSpec.cxx +++ b/Detectors/FIT/FT0/workflow/src/DigitReaderSpec.cxx @@ -33,8 +33,8 @@ namespace ft0 void DigitReader::init(InitContext& ic) { - auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("ft0-digit-infile")); + auto filename = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("ft0-digit-infile")); mFile = std::make_unique(filename.c_str(), "OLD"); if (!mFile->IsOpen()) { LOG(ERROR) << "Cannot open the " << filename.c_str() << " file !"; diff --git a/Detectors/FIT/FT0/workflow/src/RecPointReaderSpec.cxx b/Detectors/FIT/FT0/workflow/src/RecPointReaderSpec.cxx index be46819c1fb78..10bbf30f1cf05 100644 --- a/Detectors/FIT/FT0/workflow/src/RecPointReaderSpec.cxx +++ b/Detectors/FIT/FT0/workflow/src/RecPointReaderSpec.cxx @@ -38,8 +38,8 @@ RecPointReader::RecPointReader(bool useMC) void RecPointReader::init(InitContext& ic) { - mInputFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("ft0-recpoints-infile")); + mInputFileName = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("ft0-recpoints-infile")); connectTree(mInputFileName); } diff --git a/Detectors/FIT/FV0/simulation/src/digit2raw.cxx b/Detectors/FIT/FV0/simulation/src/digit2raw.cxx index 4d2b30ae6ca14..5693e97d7b758 100644 --- a/Detectors/FIT/FV0/simulation/src/digit2raw.cxx +++ b/Detectors/FIT/FV0/simulation/src/digit2raw.cxx @@ -118,8 +118,8 @@ void digi2raw(const std::string& inpName, const std::string& outDir, bool filePe } m2r.readDigits(outDirName, inpName); - wr.writeConfFile(wr.getOrigin().str, "RAWDATA", o2::utils::concat_string(outDirName, wr.getOrigin().str, "raw.cfg")); - //LOG(INFO)<("input-dir")), - ic.options().get("fv0-digit-infile")); + auto filename = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("fv0-digit-infile")); mFile = std::make_unique(filename.c_str(), "OLD"); if (!mFile->IsOpen()) { LOG(ERROR) << "Cannot open the " << filename.c_str() << " file !"; diff --git a/Detectors/GlobalTrackingWorkflow/readers/src/PrimaryVertexReaderSpec.cxx b/Detectors/GlobalTrackingWorkflow/readers/src/PrimaryVertexReaderSpec.cxx index 3e3ffe37c5358..86adb8194a57d 100644 --- a/Detectors/GlobalTrackingWorkflow/readers/src/PrimaryVertexReaderSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/readers/src/PrimaryVertexReaderSpec.cxx @@ -27,8 +27,8 @@ namespace vertexing void PrimaryVertexReader::init(InitContext& ic) { - mFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("primary-vertex-infile")); + mFileName = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("primary-vertex-infile")); connectTree(); } diff --git a/Detectors/GlobalTrackingWorkflow/readers/src/SecondaryVertexReaderSpec.cxx b/Detectors/GlobalTrackingWorkflow/readers/src/SecondaryVertexReaderSpec.cxx index f6c945348b09d..678a459416d21 100644 --- a/Detectors/GlobalTrackingWorkflow/readers/src/SecondaryVertexReaderSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/readers/src/SecondaryVertexReaderSpec.cxx @@ -27,8 +27,8 @@ namespace vertexing void SecondaryVertexReader::init(InitContext& ic) { - mFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("secondary-vertex-infile")); + mFileName = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("secondary-vertex-infile")); connectTree(); } diff --git a/Detectors/GlobalTrackingWorkflow/readers/src/TrackCosmicsReaderSpec.cxx b/Detectors/GlobalTrackingWorkflow/readers/src/TrackCosmicsReaderSpec.cxx index 279a111e8923d..b5ebc458861eb 100644 --- a/Detectors/GlobalTrackingWorkflow/readers/src/TrackCosmicsReaderSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/readers/src/TrackCosmicsReaderSpec.cxx @@ -28,8 +28,8 @@ namespace globaltracking { void TrackCosmicsReader::init(InitContext& ic) { - mFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("cosmics-infile")); + mFileName = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("cosmics-infile")); connectTree(mFileName); } diff --git a/Detectors/GlobalTrackingWorkflow/readers/src/TrackTPCITSReaderSpec.cxx b/Detectors/GlobalTrackingWorkflow/readers/src/TrackTPCITSReaderSpec.cxx index 4eccbab9ba0d7..1079d0481292d 100644 --- a/Detectors/GlobalTrackingWorkflow/readers/src/TrackTPCITSReaderSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/readers/src/TrackTPCITSReaderSpec.cxx @@ -28,8 +28,8 @@ namespace globaltracking { void TrackTPCITSReader::init(InitContext& ic) { - mFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("itstpc-track-infile")); + mFileName = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("itstpc-track-infile")); connectTree(mFileName); } diff --git a/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx index 992c1526f17ef..c33f2bc3a60d6 100644 --- a/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx @@ -89,7 +89,7 @@ void CosmicsMatchingSpec::init(InitContext& ic) std::string dictPath = ic.options().get("its-dictionary-path"); std::string dictFile = o2::base::NameConf::getAlpideClusterDictionaryFileName(DetID::ITS, dictPath, ".bin"); auto itsDict = std::make_unique(); - if (o2::base::NameConf::pathExists(dictFile)) { + if (o2::utils::Str::pathExists(dictFile)) { itsDict->readBinaryFile(dictFile); LOG(INFO) << "Matching is running with a provided ITS dictionary: " << dictFile; } else { @@ -101,7 +101,7 @@ void CosmicsMatchingSpec::init(InitContext& ic) // this is a hack to provide Mat.LUT from the local file, in general will be provided by the framework from CCDB std::string matLUTPath = ic.options().get("material-lut-path"); std::string matLUTFile = o2::base::NameConf::getMatLUTFileName(matLUTPath); - if (o2::base::NameConf::pathExists(matLUTFile)) { + if (o2::utils::Str::pathExists(matLUTFile)) { auto* lut = o2::base::MatLayerCylSet::loadFromFile(matLUTFile); o2::base::Propagator::Instance()->setMatLUT(lut); LOG(INFO) << "Loaded material LUT from " << matLUTFile; diff --git a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx index 0eb2ecc520e4b..0b532150d896d 100644 --- a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx @@ -52,7 +52,7 @@ void PrimaryVertexingSpec::init(InitContext& ic) // this is a hack to provide Mat.LUT from the local file, in general will be provided by the framework from CCDB std::string matLUTPath = ic.options().get("material-lut-path"); std::string matLUTFile = o2::base::NameConf::getMatLUTFileName(matLUTPath); - if (o2::base::NameConf::pathExists(matLUTFile)) { + if (o2::utils::Str::pathExists(matLUTFile)) { auto* lut = o2::base::MatLayerCylSet::loadFromFile(matLUTFile); o2::base::Propagator::Instance()->setMatLUT(lut); LOG(INFO) << "Loaded material LUT from " << matLUTFile; diff --git a/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexingSpec.cxx index f2607fedc0433..f6743143a9e6c 100644 --- a/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexingSpec.cxx @@ -50,7 +50,7 @@ void SecondaryVertexingSpec::init(InitContext& ic) // this is a hack to provide Mat.LUT from the local file, in general will be provided by the framework from CCDB std::string matLUTPath = ic.options().get("material-lut-path"); std::string matLUTFile = o2::base::NameConf::getMatLUTFileName(matLUTPath); - if (o2::base::NameConf::pathExists(matLUTFile)) { + if (o2::utils::Str::pathExists(matLUTFile)) { auto* lut = o2::base::MatLayerCylSet::loadFromFile(matLUTFile); o2::base::Propagator::Instance()->setMatLUT(lut); LOG(INFO) << "Loaded material LUT from " << matLUTFile; diff --git a/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx index 010b914b37d52..11907718e4025 100644 --- a/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx @@ -94,7 +94,7 @@ void TPCITSMatchingDPL::init(InitContext& ic) // std::string dictPath = ic.options().get("its-dictionary-path"); std::string dictFile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::ITS, dictPath, ".bin"); - if (o2::base::NameConf::pathExists(dictFile)) { + if (o2::utils::Str::pathExists(dictFile)) { mITSDict.readBinaryFile(dictFile); LOG(INFO) << "Matching is running with a provided ITS dictionary: " << dictFile; } else { @@ -104,7 +104,7 @@ void TPCITSMatchingDPL::init(InitContext& ic) // this is a hack to provide Mat.LUT from the local file, in general will be provided by the framework from CCDB std::string matLUTPath = ic.options().get("material-lut-path"); std::string matLUTFile = o2::base::NameConf::getMatLUTFileName(matLUTPath); - if (o2::base::NameConf::pathExists(matLUTFile)) { + if (o2::utils::Str::pathExists(matLUTFile)) { auto* lut = o2::base::MatLayerCylSet::loadFromFile(matLUTFile); o2::base::Propagator::Instance()->setMatLUT(lut); LOG(INFO) << "Loaded material LUT from " << matLUTFile; diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/CalibInfoReaderSpec.cxx b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/CalibInfoReaderSpec.cxx index 3423cd076b06e..5ec04e510b9a7 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/CalibInfoReaderSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/CalibInfoReaderSpec.cxx @@ -35,7 +35,7 @@ constexpr o2::header::DataDescription ddCalib{"CALIBDATA"}, ddCalib_tpc{"CALIBDA void CalibInfoReader::init(InitContext& ic) { LOG(INFO) << "Init CalibInfo reader!"; - auto fname = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), mFileName); + auto fname = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), mFileName); mFile = fopen(fname.c_str(), "r"); if (!mFile) { LOG(ERROR) << "Cannot open the " << fname << " file !"; diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/RecoWorkflowSpec.cxx b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/RecoWorkflowSpec.cxx index 1313a08c38cf2..1d2a67a3be371 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/RecoWorkflowSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/RecoWorkflowSpec.cxx @@ -59,7 +59,7 @@ class TOFDPLRecoWorkflowTask o2::base::Propagator::initFieldFromGRP("o2sim_grp.root"); std::string matLUTPath = ic.options().get("material-lut-path"); std::string matLUTFile = o2::base::NameConf::getMatLUTFileName(matLUTPath); - if (o2::base::NameConf::pathExists(matLUTFile)) { + if (o2::utils::Str::pathExists(matLUTFile)) { auto* lut = o2::base::MatLayerCylSet::loadFromFile(matLUTFile); o2::base::Propagator::Instance()->setMatLUT(lut); LOG(INFO) << "Loaded material LUT from " << matLUTFile; diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/RecoWorkflowWithTPCSpec.cxx b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/RecoWorkflowWithTPCSpec.cxx index ca42fa626516b..aa37f00d399d1 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/RecoWorkflowWithTPCSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/RecoWorkflowWithTPCSpec.cxx @@ -61,7 +61,7 @@ class TOFDPLRecoWorkflowWithTPCTask o2::base::Propagator::initFieldFromGRP("o2sim_grp.root"); std::string matLUTPath = ic.options().get("material-lut-path"); std::string matLUTFile = o2::base::NameConf::getMatLUTFileName(matLUTPath); - if (o2::base::NameConf::pathExists(matLUTFile)) { + if (o2::utils::Str::pathExists(matLUTFile)) { auto* lut = o2::base::MatLayerCylSet::loadFromFile(matLUTFile); o2::base::Propagator::Instance()->setMatLUT(lut); LOG(INFO) << "Loaded material LUT from " << matLUTFile; diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/TOFMatchedReaderSpec.cxx b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/TOFMatchedReaderSpec.cxx index 61b8b424b8eda..fef16ce7758f2 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/TOFMatchedReaderSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/TOFMatchedReaderSpec.cxx @@ -38,8 +38,8 @@ void TOFMatchedReader::init(InitContext& ic) { // get the option from the init context LOG(INFO) << "Init TOF matching info reader!"; - mInFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("tof-matched-infile")); + mInFileName = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("tof-matched-infile")); mInTreeName = ic.options().get("treename"); connectTree(mInFileName); } @@ -98,7 +98,7 @@ DataProcessorSpec getTOFMatchedReaderSpec(bool useMC, bool tpcmatch, bool readTr } return DataProcessorSpec{ - o2::utils::concat_string("TOFMatchedReader_", tpcmatch ? "tpc" : "glo"), + o2::utils::Str::concat_string("TOFMatchedReader_", tpcmatch ? "tpc" : "glo"), Inputs{}, outputs, AlgorithmSpec{adaptFromTask(useMC, tpcmatch, readTracks)}, diff --git a/Detectors/HMPID/workflow/src/DigitsToRawSpec.cxx b/Detectors/HMPID/workflow/src/DigitsToRawSpec.cxx index cd58458a6dff6..0b510217230cb 100644 --- a/Detectors/HMPID/workflow/src/DigitsToRawSpec.cxx +++ b/Detectors/HMPID/workflow/src/DigitsToRawSpec.cxx @@ -83,7 +83,7 @@ void DigitsToRawSpec::init(framework::InitContext& ic) LOG(INFO) << "created output directory " << mDirectoryName; } } - std::string fullFName = o2::utils::concat_string(mDirectoryName, "/", mBaseFileName); + std::string fullFName = o2::utils::Str::concat_string(mDirectoryName, "/", mBaseFileName); // Setup the Coder mCod = new HmpidCoder2(Geo::MAXEQUIPMENTS); @@ -100,7 +100,7 @@ void DigitsToRawSpec::init(framework::InitContext& ic) mDigTree = (TTree*)fdig->Get("o2sim"); // Ready to operate - mCod->getWriter().writeConfFile("HMP", "RAWDATA", o2::utils::concat_string(mDirectoryName, '/', "HMPraw.cfg")); + mCod->getWriter().writeConfFile("HMP", "RAWDATA", o2::utils::Str::concat_string(mDirectoryName, '/', "HMPraw.cfg")); mExTimer.start(); } diff --git a/Detectors/ITSMFT/ITS/simulation/src/digi2raw.cxx b/Detectors/ITSMFT/ITS/simulation/src/digi2raw.cxx index 9823f4e342508..a68b261fe268c 100644 --- a/Detectors/ITSMFT/ITS/simulation/src/digi2raw.cxx +++ b/Detectors/ITSMFT/ITS/simulation/src/digi2raw.cxx @@ -128,7 +128,7 @@ void digi2raw(std::string_view inpName, std::string_view outDir, std::string_vie digTree.SetBranchStatus("*MCTruth*", 0); // ignore MC info std::vector digiVec, *digiVecP = &digiVec; - std::string digBranchName = o2::utils::concat_string(MAP::getName(), "Digit"); + std::string digBranchName = o2::utils::Str::concat_string(MAP::getName(), "Digit"); if (!digTree.GetBranch(digBranchName.c_str())) { LOG(FATAL) << "Failed to find the branch " << digBranchName << " in the tree " << digTreeName; } @@ -136,7 +136,7 @@ void digi2raw(std::string_view inpName, std::string_view outDir, std::string_vie // ROF record entries in the digit tree ROFRVEC rofRecVec, *rofRecVecP = &rofRecVec; - std::string rofRecName = o2::utils::concat_string(MAP::getName(), "DigitROF"); + std::string rofRecName = o2::utils::Str::concat_string(MAP::getName(), "DigitROF"); if (!digTree.GetBranch(rofRecName.c_str())) { LOG(FATAL) << "Failed to find the branch " << rofRecName << " in the tree " << digTreeName; } @@ -148,7 +148,7 @@ void digi2raw(std::string_view inpName, std::string_view outDir, std::string_vie o2::itsmft::MC2RawEncoder m2r; m2r.setVerbosity(verbosity); m2r.setContinuousReadout(grp->isDetContinuousReadOut(MAP::getDetID())); // must be set explicitly - m2r.setDefaultSinkName(o2::utils::concat_string(MAP::getName(), ".raw")); + m2r.setDefaultSinkName(o2::utils::Str::concat_string(MAP::getName(), ".raw")); m2r.setMinMaxRUSW(ruSWMin, ruSWMax); m2r.getWriter().setSuperPageSize(superPageSizeInB); m2r.getWriter().useRDHVersion(rdhV); @@ -179,7 +179,7 @@ void digi2raw(std::string_view inpName, std::string_view outDir, std::string_vie } } // loop over multiple ROFvectors (in case of chaining) - m2r.getWriter().writeConfFile(MAP::getName(), "RAWDATA", o2::utils::concat_string(outDir, '/', MAP::getName(), "raw.cfg")); + m2r.getWriter().writeConfFile(MAP::getName(), "RAWDATA", o2::utils::Str::concat_string(outDir, '/', MAP::getName(), "raw.cfg")); m2r.finalize(); // finish TF and flush data // swTot.Stop(); @@ -275,15 +275,15 @@ void setupLinks(o2::itsmft::MC2RawEncoder& m2r, std::string_view outDir, st // register the link in the writer, if not done here, its data will be dumped to common default file if (fileFor == "all") { // single file for all links - outFileLink = o2::utils::concat_string(outDir, "/", outPrefix, ".raw"); + outFileLink = o2::utils::Str::concat_string(outDir, "/", outPrefix, ".raw"); } else if (fileFor == "layer") { - outFileLink = o2::utils::concat_string(outDir, "/", outPrefix, "_lr", std::to_string(ilr), ".raw"); + outFileLink = o2::utils::Str::concat_string(outDir, "/", outPrefix, "_lr", std::to_string(ilr), ".raw"); } else if (fileFor == "cru") { - outFileLink = o2::utils::concat_string(outDir, "/", outPrefix, "_cru", std::to_string(cruID), ".raw"); + outFileLink = o2::utils::Str::concat_string(outDir, "/", outPrefix, "_cru", std::to_string(cruID), ".raw"); } else if (fileFor == "link") { - outFileLink = o2::utils::concat_string(outDir, "/", outPrefix, "_cru", std::to_string(cruID), - "_link", std::to_string(linkID), "_ep", std::to_string(link->endPointID), - "_feeid", std::to_string(link->feeID), ".raw"); + outFileLink = o2::utils::Str::concat_string(outDir, "/", outPrefix, "_cru", std::to_string(cruID), + "_link", std::to_string(linkID), "_ep", std::to_string(link->endPointID), + "_feeid", std::to_string(link->feeID), ".raw"); } else { throw std::runtime_error("invalid option provided for file grouping"); } diff --git a/Detectors/ITSMFT/ITS/workflow/src/ClustererSpec.cxx b/Detectors/ITSMFT/ITS/workflow/src/ClustererSpec.cxx index ec6ebeb5ad1e0..306c329c68cbc 100644 --- a/Detectors/ITSMFT/ITS/workflow/src/ClustererSpec.cxx +++ b/Detectors/ITSMFT/ITS/workflow/src/ClustererSpec.cxx @@ -64,7 +64,7 @@ void ClustererDPL::init(InitContext& ic) std::string dictPath = ic.options().get("its-dictionary-path"); std::string dictFile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::ITS, dictPath, ".bin"); - if (o2::base::NameConf::pathExists(dictFile)) { + if (o2::utils::Str::pathExists(dictFile)) { mClusterer->loadDictionary(dictFile); LOG(INFO) << "ITSClusterer running with a provided dictionary: " << dictFile; } else { diff --git a/Detectors/ITSMFT/ITS/workflow/src/CookedTrackerSpec.cxx b/Detectors/ITSMFT/ITS/workflow/src/CookedTrackerSpec.cxx index 63efd2a45ace5..16c9d744bf706 100644 --- a/Detectors/ITSMFT/ITS/workflow/src/CookedTrackerSpec.cxx +++ b/Detectors/ITSMFT/ITS/workflow/src/CookedTrackerSpec.cxx @@ -74,12 +74,12 @@ void CookedTrackerDPL::init(InitContext& ic) LOG(INFO) << "ITSCookedTracker RO: continuous=" << continuous; mTracker.setContinuousMode(continuous); } else { - throw std::runtime_error(o2::utils::concat_string("Cannot retrieve GRP from the ", filename)); + throw std::runtime_error(o2::utils::Str::concat_string("Cannot retrieve GRP from the ", filename)); } std::string dictPath = ic.options().get("its-dictionary-path"); std::string dictFile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::ITS, dictPath, ".bin"); - if (o2::base::NameConf::pathExists(dictFile)) { + if (o2::utils::Str::pathExists(dictFile)) { mDict.readBinaryFile(dictFile); LOG(INFO) << "Tracker running with a provided dictionary: " << dictFile; } else { diff --git a/Detectors/ITSMFT/ITS/workflow/src/TrackReaderSpec.cxx b/Detectors/ITSMFT/ITS/workflow/src/TrackReaderSpec.cxx index f0a1bac2dd354..34190c6766768 100644 --- a/Detectors/ITSMFT/ITS/workflow/src/TrackReaderSpec.cxx +++ b/Detectors/ITSMFT/ITS/workflow/src/TrackReaderSpec.cxx @@ -32,8 +32,8 @@ TrackReader::TrackReader(bool useMC) void TrackReader::init(InitContext& ic) { - mInputFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("its-tracks-infile")); + mInputFileName = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("its-tracks-infile")); connectTree(mInputFileName); } diff --git a/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx b/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx index a07d12bb13904..b1d72528ee4a2 100644 --- a/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx +++ b/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx @@ -67,7 +67,7 @@ void TrackerDPL::init(InitContext& ic) std::string matLUTPath = ic.options().get("material-lut-path"); std::string matLUTFile = o2::base::NameConf::getMatLUTFileName(matLUTPath); - if (o2::base::NameConf::pathExists(matLUTFile)) { + if (o2::utils::Str::pathExists(matLUTFile)) { auto* lut = o2::base::MatLayerCylSet::loadFromFile(matLUTFile); o2::base::Propagator::Instance()->setMatLUT(lut); LOG(INFO) << "Loaded material LUT from " << matLUTFile; @@ -131,12 +131,12 @@ void TrackerDPL::init(InitContext& ic) double origD[3] = {0., 0., 0.}; mTracker->setBz(field->getBz(origD)); } else { - throw std::runtime_error(o2::utils::concat_string("Cannot retrieve GRP from the ", filename)); + throw std::runtime_error(o2::utils::Str::concat_string("Cannot retrieve GRP from the ", filename)); } std::string dictPath = ic.options().get("its-dictionary-path"); std::string dictFile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::ITS, dictPath, ".bin"); - if (o2::base::NameConf::pathExists(dictFile)) { + if (o2::utils::Str::pathExists(dictFile)) { mDict.readBinaryFile(dictFile); LOG(INFO) << "Tracker running with a provided dictionary: " << dictFile; } else { diff --git a/Detectors/ITSMFT/ITS/workflow/src/VertexReaderSpec.cxx b/Detectors/ITSMFT/ITS/workflow/src/VertexReaderSpec.cxx index 1b07168e67416..1f8728d4d38a1 100644 --- a/Detectors/ITSMFT/ITS/workflow/src/VertexReaderSpec.cxx +++ b/Detectors/ITSMFT/ITS/workflow/src/VertexReaderSpec.cxx @@ -28,8 +28,8 @@ namespace its void VertexReader::init(InitContext& ic) { - mFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("its-vertex-infile")); + mFileName = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("its-vertex-infile")); connectTree(mFileName); } diff --git a/Detectors/ITSMFT/MFT/simulation/src/digi2raw.cxx b/Detectors/ITSMFT/MFT/simulation/src/digi2raw.cxx index d6323e18b1198..8e2604bbd02a1 100644 --- a/Detectors/ITSMFT/MFT/simulation/src/digi2raw.cxx +++ b/Detectors/ITSMFT/MFT/simulation/src/digi2raw.cxx @@ -126,7 +126,7 @@ void digi2raw(std::string_view inpName, std::string_view outDir, std::string_vie digTree.SetBranchStatus("*MCTruth*", 0); // ignore MC info std::vector digiVec, *digiVecP = &digiVec; - std::string digBranchName = o2::utils::concat_string(MAP::getName(), "Digit"); + std::string digBranchName = o2::utils::Str::concat_string(MAP::getName(), "Digit"); if (!digTree.GetBranch(digBranchName.c_str())) { LOG(FATAL) << "Failed to find the branch " << digBranchName << " in the tree " << digTreeName; } @@ -134,7 +134,7 @@ void digi2raw(std::string_view inpName, std::string_view outDir, std::string_vie // ROF record entries in the digit tree ROFRVEC rofRecVec, *rofRecVecP = &rofRecVec; - std::string rofRecName = o2::utils::concat_string(MAP::getName(), "DigitROF"); + std::string rofRecName = o2::utils::Str::concat_string(MAP::getName(), "DigitROF"); if (!digTree.GetBranch(rofRecName.c_str())) { LOG(FATAL) << "Failed to find the branch " << rofRecName << " in the tree " << digTreeName; } @@ -146,7 +146,7 @@ void digi2raw(std::string_view inpName, std::string_view outDir, std::string_vie o2::itsmft::MC2RawEncoder m2r; m2r.setVerbosity(verbosity); m2r.setContinuousReadout(grp->isDetContinuousReadOut(MAP::getDetID())); // must be set explicitly - m2r.setDefaultSinkName(o2::utils::concat_string(MAP::getName(), ".raw")); + m2r.setDefaultSinkName(o2::utils::Str::concat_string(MAP::getName(), ".raw")); m2r.setMinMaxRUSW(ruSWMin, ruSWMax); m2r.getWriter().setSuperPageSize(superPageSizeInB); m2r.getWriter().useRDHVersion(rdhV); @@ -177,7 +177,7 @@ void digi2raw(std::string_view inpName, std::string_view outDir, std::string_vie } } // loop over multiple ROFvectors (in case of chaining) - m2r.getWriter().writeConfFile(MAP::getName(), "RAWDATA", o2::utils::concat_string(outDir, '/', MAP::getName(), "raw.cfg")); + m2r.getWriter().writeConfFile(MAP::getName(), "RAWDATA", o2::utils::Str::concat_string(outDir, '/', MAP::getName(), "raw.cfg")); m2r.finalize(); // finish TF and flush data // swTot.Stop(); @@ -257,14 +257,14 @@ void setupLinks(o2::itsmft::MC2RawEncoder& m2r, std::string_view outDir, st //LOG(INFO) << "with lanes " << bv_lanes; if (fileFor == "all") { // single file for all links - outFileLink = o2::utils::concat_string(outDir, "/", outPrefix, ".raw"); + outFileLink = o2::utils::Str::concat_string(outDir, "/", outPrefix, ".raw"); } else if (fileFor == "layer") { - outFileLink = o2::utils::concat_string(outDir, "/", outPrefix, "_lr", std::to_string(ilr), ".raw"); + outFileLink = o2::utils::Str::concat_string(outDir, "/", outPrefix, "_lr", std::to_string(ilr), ".raw"); } else if (fileFor == "cru") { - outFileLink = o2::utils::concat_string(outDir, "/", outPrefix, "_cru", std::to_string(link->cruID), ".raw"); + outFileLink = o2::utils::Str::concat_string(outDir, "/", outPrefix, "_cru", std::to_string(link->cruID), ".raw"); } else if (fileFor == "link") { - outFileLink = o2::utils::concat_string(outDir, "/", outPrefix, "_cru", std::to_string(cruID), - "_link", std::to_string(linkID), "_ep", std::to_string(link->endPointID), ".raw"); + outFileLink = o2::utils::Str::concat_string(outDir, "/", outPrefix, "_cru", std::to_string(cruID), + "_link", std::to_string(linkID), "_ep", std::to_string(link->endPointID), ".raw"); } else { throw std::runtime_error("invalid option provided for file grouping"); } diff --git a/Detectors/ITSMFT/MFT/workflow/src/ClusterReaderSpec.cxx b/Detectors/ITSMFT/MFT/workflow/src/ClusterReaderSpec.cxx index 7cce47c89e778..76ff07107d98d 100644 --- a/Detectors/ITSMFT/MFT/workflow/src/ClusterReaderSpec.cxx +++ b/Detectors/ITSMFT/MFT/workflow/src/ClusterReaderSpec.cxx @@ -34,8 +34,8 @@ namespace mft void ClusterReader::init(InitContext& ic) { - auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("mft-cluster-infile")); + auto filename = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("mft-cluster-infile")); mFile = std::make_unique(filename.c_str(), "OLD"); if (!mFile->IsOpen()) { LOG(ERROR) << "Cannot open the " << filename.c_str() << " file !"; diff --git a/Detectors/ITSMFT/MFT/workflow/src/ClustererSpec.cxx b/Detectors/ITSMFT/MFT/workflow/src/ClustererSpec.cxx index 6d28683b6a1af..818d158716970 100644 --- a/Detectors/ITSMFT/MFT/workflow/src/ClustererSpec.cxx +++ b/Detectors/ITSMFT/MFT/workflow/src/ClustererSpec.cxx @@ -70,7 +70,7 @@ void ClustererDPL::init(InitContext& ic) std::string dictPath = ic.options().get("mft-dictionary-path"); std::string dictFile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::MFT, dictPath, ".bin"); - if (o2::base::NameConf::pathExists(dictFile)) { + if (o2::utils::Str::pathExists(dictFile)) { mClusterer->loadDictionary(dictFile); LOG(INFO) << "MFTClusterer running with a provided dictionary: " << dictFile; } else { diff --git a/Detectors/ITSMFT/MFT/workflow/src/TrackerSpec.cxx b/Detectors/ITSMFT/MFT/workflow/src/TrackerSpec.cxx index 2c5ce1dca0386..571eb86a1f78a 100644 --- a/Detectors/ITSMFT/MFT/workflow/src/TrackerSpec.cxx +++ b/Detectors/ITSMFT/MFT/workflow/src/TrackerSpec.cxx @@ -67,12 +67,12 @@ void TrackerDPL::init(InitContext& ic) mTracker->initConfig(mftTrackingParam, true); mTracker->initialize(); } else { - throw std::runtime_error(o2::utils::concat_string("Cannot retrieve GRP from the ", filename)); + throw std::runtime_error(o2::utils::Str::concat_string("Cannot retrieve GRP from the ", filename)); } std::string dictPath = ic.options().get("mft-dictionary-path"); std::string dictFile = o2::base::NameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::MFT, dictPath, ".bin"); - if (o2::base::NameConf::pathExists(dictFile)) { + if (o2::utils::Str::pathExists(dictFile)) { mDict.readBinaryFile(dictFile); LOG(INFO) << "Tracker running with a provided dictionary: " << dictFile; } else { diff --git a/Detectors/ITSMFT/common/reconstruction/src/RawPixelDecoder.cxx b/Detectors/ITSMFT/common/reconstruction/src/RawPixelDecoder.cxx index ef625bdf48826..545e73c1bd4cc 100644 --- a/Detectors/ITSMFT/common/reconstruction/src/RawPixelDecoder.cxx +++ b/Detectors/ITSMFT/common/reconstruction/src/RawPixelDecoder.cxx @@ -34,7 +34,7 @@ RawPixelDecoder::RawPixelDecoder() mTimerTFStart.Stop(); mTimerDecode.Stop(); mTimerFetchData.Stop(); - mSelfName = o2::utils::concat_string(Mapping::getName(), "Decoder"); + mSelfName = o2::utils::Str::concat_string(Mapping::getName(), "Decoder"); } ///______________________________________________________________ diff --git a/Detectors/ITSMFT/common/workflow/src/ClusterReaderSpec.cxx b/Detectors/ITSMFT/common/workflow/src/ClusterReaderSpec.cxx index 77c8623a8f900..b1adc7e02f323 100644 --- a/Detectors/ITSMFT/common/workflow/src/ClusterReaderSpec.cxx +++ b/Detectors/ITSMFT/common/workflow/src/ClusterReaderSpec.cxx @@ -40,8 +40,8 @@ ClusterReader::ClusterReader(o2::detectors::DetID id, bool useMC, bool usePatter void ClusterReader::init(InitContext& ic) { - mFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get((mDetNameLC + "-cluster-infile").c_str())); + mFileName = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get((mDetNameLC + "-cluster-infile").c_str())); connectTree(mFileName); } diff --git a/Detectors/ITSMFT/common/workflow/src/DigitReaderSpec.cxx b/Detectors/ITSMFT/common/workflow/src/DigitReaderSpec.cxx index ec6ea26f258dd..56da02475c29e 100644 --- a/Detectors/ITSMFT/common/workflow/src/DigitReaderSpec.cxx +++ b/Detectors/ITSMFT/common/workflow/src/DigitReaderSpec.cxx @@ -52,8 +52,8 @@ DigitReader::DigitReader(o2::detectors::DetID id, bool useMC, bool useCalib) void DigitReader::init(InitContext& ic) { - mFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get((mDetNameLC + "-digit-infile").c_str())); + mFileName = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get((mDetNameLC + "-digit-infile").c_str())); connectTree(mFileName); } diff --git a/Detectors/ITSMFT/common/workflow/src/STFDecoderSpec.cxx b/Detectors/ITSMFT/common/workflow/src/STFDecoderSpec.cxx index e56c5edb7d230..9687edff9a857 100644 --- a/Detectors/ITSMFT/common/workflow/src/STFDecoderSpec.cxx +++ b/Detectors/ITSMFT/common/workflow/src/STFDecoderSpec.cxx @@ -43,7 +43,7 @@ template STFDecoder::STFDecoder(bool doClusters, bool doPatterns, bool doDigits, bool doCalib, std::string_view dict, std::string_view noise) : mDoClusters(doClusters), mDoPatterns(doPatterns), mDoDigits(doDigits), mDoCalibData(doCalib), mDictName(dict), mNoiseName(noise) { - mSelfName = o2::utils::concat_string(Mapping::getName(), "STFDecoder"); + mSelfName = o2::utils::Str::concat_string(Mapping::getName(), "STFDecoder"); mTimer.Stop(); mTimer.Reset(); } @@ -62,7 +62,7 @@ void STFDecoder::init(InitContext& ic) mDecoder->setVerbosity(ic.options().get("decoder-verbosity")); mDecoder->setFillCalibData(mDoCalibData); std::string noiseFile = o2::base::NameConf::getAlpideClusterDictionaryFileName(detID, mNoiseName, ".root"); - if (o2::base::NameConf::pathExists(noiseFile)) { + if (o2::utils::Str::pathExists(noiseFile)) { TFile* f = TFile::Open(noiseFile.data(), "old"); auto pnoise = (NoiseMap*)f->Get("Noise"); AlpideCoder::setNoisyPixels(pnoise); @@ -90,7 +90,7 @@ void STFDecoder::init(InitContext& ic) mClusterer->setMaxRowColDiffToMask(clParams.maxRowColDiffToMask); std::string dictFile = o2::base::NameConf::getAlpideClusterDictionaryFileName(detID, mDictName, ".bin"); - if (o2::base::NameConf::pathExists(dictFile)) { + if (o2::utils::Str::pathExists(dictFile)) { mClusterer->loadDictionary(dictFile); LOG(INFO) << mSelfName << " clusterer running with a provided dictionary: " << dictFile; } else { diff --git a/Detectors/MUON/MID/Workflow/src/DigitReaderSpec.cxx b/Detectors/MUON/MID/Workflow/src/DigitReaderSpec.cxx index 04b50383fa0e0..e33c999e472ce 100644 --- a/Detectors/MUON/MID/Workflow/src/DigitReaderSpec.cxx +++ b/Detectors/MUON/MID/Workflow/src/DigitReaderSpec.cxx @@ -47,8 +47,8 @@ class DigitsReaderDeviceDPL DigitsReaderDeviceDPL(bool useMC, const std::vector& descriptions) : mUseMC(useMC), mDescriptions(descriptions) {} void init(o2::framework::InitContext& ic) { - auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("mid-digit-infile")); + auto filename = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("mid-digit-infile")); mFile = std::make_unique(filename.c_str()); if (!mFile->IsOpen()) { LOG(ERROR) << "Cannot open the " << filename << " file !"; diff --git a/Detectors/MUON/MID/Workflow/src/RawWriterSpec.cxx b/Detectors/MUON/MID/Workflow/src/RawWriterSpec.cxx index ce4741c29b1b5..f93f65eb5379e 100644 --- a/Detectors/MUON/MID/Workflow/src/RawWriterSpec.cxx +++ b/Detectors/MUON/MID/Workflow/src/RawWriterSpec.cxx @@ -53,7 +53,7 @@ class RawWriterDeviceDPL } } - std::string fullFName = o2::utils::concat_string(dirname, "/", filename); + std::string fullFName = o2::utils::Str::concat_string(dirname, "/", filename); mEncoder.init(fullFName.c_str(), perLink); std::string inputGRP = o2::base::NameConf::getGRPFileName(); @@ -66,7 +66,7 @@ class RawWriterDeviceDPL ic.services().get().set(of::CallbackService::Id::Stop, stop); // Write basic config files to be used with raw data reader workflow - mEncoder.getWriter().writeConfFile("MID", "RAWDATA", o2::utils::concat_string(dirname, '/', "MIDraw.cfg")); + mEncoder.getWriter().writeConfFile("MID", "RAWDATA", o2::utils::Str::concat_string(dirname, '/', "MIDraw.cfg")); } void run(o2::framework::ProcessingContext& pc) diff --git a/Detectors/PHOS/simulation/src/RawCreator.cxx b/Detectors/PHOS/simulation/src/RawCreator.cxx index d9dac3da0356c..a203e3f6853fe 100644 --- a/Detectors/PHOS/simulation/src/RawCreator.cxx +++ b/Detectors/PHOS/simulation/src/RawCreator.cxx @@ -110,7 +110,7 @@ int main(int argc, const char** argv) for (auto en : *treereader) { rawwriter.digitsToRaw(*digitbranch, *triggerbranch); } - rawwriter.getWriter().writeConfFile("PHS", "RAWDATA", o2::utils::concat_string(outputdir, "/PHSraw.cfg")); + rawwriter.getWriter().writeConfFile("PHS", "RAWDATA", o2::utils::Str::concat_string(outputdir, "/PHSraw.cfg")); o2::raw::HBFUtils::Instance().print(); diff --git a/Detectors/PHOS/workflow/src/ReaderSpec.cxx b/Detectors/PHOS/workflow/src/ReaderSpec.cxx index a0afec314b5d6..b4b568ee62344 100644 --- a/Detectors/PHOS/workflow/src/ReaderSpec.cxx +++ b/Detectors/PHOS/workflow/src/ReaderSpec.cxx @@ -43,8 +43,8 @@ DataProcessorSpec getDigitsReaderSpec(bool propagateMC) auto initFunction = [propagateMC](InitContext& ic) { // get the option from the init context - auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("infile")); + auto filename = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("infile")); auto treename = ic.options().get("treename"); auto nofEvents = ic.options().get("nevents"); auto publishingMode = nofEvents == -1 ? RootTreeReader::PublishingMode::Single : RootTreeReader::PublishingMode::Loop; @@ -142,8 +142,8 @@ DataProcessorSpec getCellReaderSpec(bool propagateMC) auto initFunction = [propagateMC](InitContext& ic) { // get the option from the init context - auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("infile")); + auto filename = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("infile")); auto treename = ic.options().get("treename"); auto nofEvents = ic.options().get("nevents"); auto publishingMode = nofEvents == -1 ? RootTreeReader::PublishingMode::Single : RootTreeReader::PublishingMode::Loop; diff --git a/Detectors/Raw/src/HBFUtilsInitializer.cxx b/Detectors/Raw/src/HBFUtilsInitializer.cxx index b82be031124ae..fb939200895d7 100644 --- a/Detectors/Raw/src/HBFUtilsInitializer.cxx +++ b/Detectors/Raw/src/HBFUtilsInitializer.cxx @@ -36,7 +36,7 @@ HBFUtilsInitializer::HBFUtilsInitializer(const o2f::ConfigContext& configcontext if (!done) { bool helpasked = configcontext.helpOnCommandLine(); // if help is asked, don't take for granted that the ini file is there, don't produce an error if it is not! std::string conf = configcontext.options().isSet(HBFConfOpt) ? configcontext.options().get(HBFConfOpt) : ""; - if (!conf.empty() && conf != "none" && !(helpasked && !o2::base::NameConf::pathExists(conf))) { + if (!conf.empty() && conf != "none" && !(helpasked && !o2::utils::Str::pathExists(conf))) { o2::conf::ConfigurableParam::updateFromFile(conf, "HBFUtils", true); // update only those values which were not touched yet (provenance == kCODE) } done = true; diff --git a/Detectors/Raw/src/RawFileWriter.cxx b/Detectors/Raw/src/RawFileWriter.cxx index 5fa0bb2153f61..6a72f3d933868 100644 --- a/Detectors/Raw/src/RawFileWriter.cxx +++ b/Detectors/Raw/src/RawFileWriter.cxx @@ -234,7 +234,7 @@ void RawFileWriter::writeConfFile(std::string_view origin, std::string_view desc cfgfile << "dataOrigin = " << origin << std::endl; cfgfile << "dataDescription = " << description << std::endl; cfgfile << "readoutCard = " << (isCRUDetector() ? "CRU" : "RORC") << std::endl; - cfgfile << "filePath = " << (fullPath ? o2::base::NameConf::getFullPath(getOutputFileName(i)) : getOutputFileName(i)) << std::endl; + cfgfile << "filePath = " << (fullPath ? o2::utils::Str::getFullPath(getOutputFileName(i)) : getOutputFileName(i)) << std::endl; } cfgfile.close(); } @@ -250,7 +250,7 @@ void RawFileWriter::useCaching() if (mCacheFile) { return; // already done } - auto cachename = o2::utils::concat_string("_rawWriter_cache_", mOrigin.str, ::getpid(), ".root"); + auto cachename = o2::utils::Str::concat_string("_rawWriter_cache_", mOrigin.str, ::getpid(), ".root"); mCacheFile.reset(TFile::Open(cachename.c_str(), "recreate")); LOG(INFO) << "Switched caching ON"; } @@ -264,7 +264,7 @@ void RawFileWriter::LinkData::cacheData(const IR& ir, const gsl::span data std::lock_guard lock(writer->mCacheFileMtx); if (!cacheTree) { writer->mCacheFile->cd(); - cacheTree = std::make_unique(o2::utils::concat_string("lnk", std::to_string(subspec)).c_str(), "cache"); + cacheTree = std::make_unique(o2::utils::Str::concat_string("lnk", std::to_string(subspec)).c_str(), "cache"); cacheTree->Branch("cache", &cacheBuffer); } cacheBuffer.preformatted = preformatted; diff --git a/Detectors/Raw/src/rawfileSplit.cxx b/Detectors/Raw/src/rawfileSplit.cxx index a1cf0b2a8b091..e7020ace237f6 100644 --- a/Detectors/Raw/src/rawfileSplit.cxx +++ b/Detectors/Raw/src/rawfileSplit.cxx @@ -164,9 +164,9 @@ int main(int argc, char* argv[]) if (reinitWriter) { if (writer) { // generate config for previous chunk - writer->writeConfFile(writer->getOrigin().str, "RAWDATA", o2::utils::concat_string(outDir, '/', writer->getOrigin().str, "raw.cfg")); + writer->writeConfFile(writer->getOrigin().str, "RAWDATA", o2::utils::Str::concat_string(outDir, '/', writer->getOrigin().str, "raw.cfg")); } - outDir = o2::utils::concat_string(outDirPrefix, "_", std::to_string(chunkID)); + outDir = o2::utils::Str::concat_string(outDirPrefix, "_", std::to_string(chunkID)); if (gSystem->AccessPathName(outDir.data())) { if (gSystem->mkdir(outDir.data(), kTRUE)) { LOG(FATAL) << "could not create output directory " << outDir; @@ -182,15 +182,15 @@ int main(int argc, char* argv[]) std::string outFileName; if (fileFor == "all") { // single file for all links - outFileName = o2::utils::concat_string(outDir, "/", fileFor, ".raw"); + outFileName = o2::utils::Str::concat_string(outDir, "/", fileFor, ".raw"); } else if (fileFor == "cru") { - outFileName = o2::utils::concat_string(outDir, "/", fileFor, "_", std::to_string(RDHUtils::getCRUID(link.rdhl)), ".raw"); + outFileName = o2::utils::Str::concat_string(outDir, "/", fileFor, "_", std::to_string(RDHUtils::getCRUID(link.rdhl)), ".raw"); } else if (fileFor == "link") { - outFileName = o2::utils::concat_string(outDir, "/", fileFor, - "_", std::to_string(RDHUtils::getLinkID(link.rdhl)), - "_cru", std::to_string(RDHUtils::getCRUID(link.rdhl)), - "_ep", std::to_string(RDHUtils::getEndPointID(link.rdhl)), - "_feeid", std::to_string(RDHUtils::getFEEID(link.rdhl)), ".raw"); + outFileName = o2::utils::Str::concat_string(outDir, "/", fileFor, + "_", std::to_string(RDHUtils::getLinkID(link.rdhl)), + "_cru", std::to_string(RDHUtils::getCRUID(link.rdhl)), + "_ep", std::to_string(RDHUtils::getEndPointID(link.rdhl)), + "_feeid", std::to_string(RDHUtils::getFEEID(link.rdhl)), ".raw"); } else { throw std::runtime_error("invalid option provided for file grouping"); } @@ -205,7 +205,7 @@ int main(int argc, char* argv[]) } } if (writer) { // generate config for previous chunk - writer->writeConfFile(writer->getOrigin().str, "RAWDATA", o2::utils::concat_string(outDir, '/', writer->getOrigin().str, "raw.cfg")); + writer->writeConfFile(writer->getOrigin().str, "RAWDATA", o2::utils::Str::concat_string(outDir, '/', writer->getOrigin().str, "raw.cfg")); } writer.reset(); diff --git a/Detectors/Raw/test/testRawReaderWriter.cxx b/Detectors/Raw/test/testRawReaderWriter.cxx index 9643a5b1ac508..8f7a9790a3610 100644 --- a/Detectors/Raw/test/testRawReaderWriter.cxx +++ b/Detectors/Raw/test/testRawReaderWriter.cxx @@ -70,7 +70,7 @@ struct TestRawWriter { // simple class to create detector payload for multiple l int feeIDShift = writer.isCRUDetector() ? 8 : 9; // register links for (int icru = 0; icru < NCRU; icru++) { - std::string outFileName = o2::utils::concat_string("testdata_", writer.isCRUDetector() ? "cru" : "rorc", std::to_string(icru), ".raw"); + std::string outFileName = o2::utils::Str::concat_string("testdata_", writer.isCRUDetector() ? "cru" : "rorc", std::to_string(icru), ".raw"); for (int il = 0; il < NLinkPerCRU; il++) { auto& link = writer.registerLink((icru << feeIDShift) + il, icru, il, 0, outFileName); RDHUtils::setDetectorField(link.rdhCopy, 0xff << icru); // if needed, set extra link info, will be copied to all RDHs diff --git a/Detectors/TOF/reconstruction/src/Encoder.cxx b/Detectors/TOF/reconstruction/src/Encoder.cxx index 41f0146bc97b5..92bd34e08051b 100644 --- a/Detectors/TOF/reconstruction/src/Encoder.cxx +++ b/Detectors/TOF/reconstruction/src/Encoder.cxx @@ -76,12 +76,12 @@ bool Encoder::open(const std::string& name, const std::string& path, const std:: std::string outFileLink; if (mCrateOn[feeid]) { if (fileFor == "all") { // single file for all links - outFileLink = o2::utils::concat_string(path, "/TOF.raw"); + outFileLink = o2::utils::Str::concat_string(path, "/TOF.raw"); } else if (fileFor == "cru") { - outFileLink = o2::utils::concat_string(path, "/", "TOF_cru", std::to_string(RDHUtils::getCRUID(rdh)), ".raw"); + outFileLink = o2::utils::Str::concat_string(path, "/", "TOF_cru", std::to_string(RDHUtils::getCRUID(rdh)), ".raw"); } else if (fileFor == "link") { - outFileLink = o2::utils::concat_string(path, "/", "TOF_cru", std::to_string(RDHUtils::getCRUID(rdh)), "_link", - std::to_string(RDHUtils::getLinkID(rdh)), "_ep", std::to_string(RDHUtils::getEndPointID(rdh)), ".raw"); + outFileLink = o2::utils::Str::concat_string(path, "/", "TOF_cru", std::to_string(RDHUtils::getCRUID(rdh)), "_link", + std::to_string(RDHUtils::getLinkID(rdh)), "_ep", std::to_string(RDHUtils::getEndPointID(rdh)), ".raw"); } else { throw std::runtime_error("invalid option provided for file grouping"); } diff --git a/Detectors/TOF/simulation/src/digi2raw.cxx b/Detectors/TOF/simulation/src/digi2raw.cxx index b24611578b411..1d4843b995750 100644 --- a/Detectors/TOF/simulation/src/digi2raw.cxx +++ b/Detectors/TOF/simulation/src/digi2raw.cxx @@ -54,9 +54,9 @@ int main(int argc, char** argv) exit(2); } - auto cmd = o2::utils::concat_string("o2-tof-reco-workflow -b --output-type raw --tof-raw-outdir ", vm["output-dir"].as(), - " --tof-raw-file-for ", vm["file-for"].as(), - " --hbfutils-config ", vm["hbfutils-config"].as(), - R"( --configKeyValues ")", vm["configKeyValues"].as(), '"'); + auto cmd = o2::utils::Str::concat_string("o2-tof-reco-workflow -b --output-type raw --tof-raw-outdir ", vm["output-dir"].as(), + " --tof-raw-file-for ", vm["file-for"].as(), + " --hbfutils-config ", vm["hbfutils-config"].as(), + R"( --configKeyValues ")", vm["configKeyValues"].as(), '"'); return system(cmd.c_str()); } diff --git a/Detectors/TOF/workflow/src/ClusterReaderSpec.cxx b/Detectors/TOF/workflow/src/ClusterReaderSpec.cxx index 1a0a081c1174d..dbef0b5588f29 100644 --- a/Detectors/TOF/workflow/src/ClusterReaderSpec.cxx +++ b/Detectors/TOF/workflow/src/ClusterReaderSpec.cxx @@ -29,8 +29,8 @@ namespace tof void ClusterReader::init(InitContext& ic) { LOG(INFO) << "Init Cluster reader!"; - mFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("tof-cluster-infile")); + mFileName = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("tof-cluster-infile")); connectTree(mFileName); } diff --git a/Detectors/TOF/workflow/src/DigitReaderSpec.cxx b/Detectors/TOF/workflow/src/DigitReaderSpec.cxx index d4034aea05ba7..7748152b08c66 100644 --- a/Detectors/TOF/workflow/src/DigitReaderSpec.cxx +++ b/Detectors/TOF/workflow/src/DigitReaderSpec.cxx @@ -32,8 +32,8 @@ namespace tof void DigitReader::init(InitContext& ic) { LOG(INFO) << "Init Digit reader!"; - auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("tof-digit-infile")); + auto filename = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("tof-digit-infile")); mFile = std::make_unique(filename.c_str(), "OLD"); if (!mFile->IsOpen()) { LOG(ERROR) << "Cannot open the " << filename.c_str() << " file !"; diff --git a/Detectors/TOF/workflow/src/TOFRawWriterSpec.cxx b/Detectors/TOF/workflow/src/TOFRawWriterSpec.cxx index 832e18b4995f2..3b0cabc85a682 100644 --- a/Detectors/TOF/workflow/src/TOFRawWriterSpec.cxx +++ b/Detectors/TOF/workflow/src/TOFRawWriterSpec.cxx @@ -99,7 +99,7 @@ void RawWriter::run(ProcessingContext& pc) } // create configuration file for rawreader - encoder.getWriter().writeConfFile("TOF", "RAWDATA", o2::utils::concat_string(mOutDirName, '/', "TOFraw.cfg")); + encoder.getWriter().writeConfFile("TOF", "RAWDATA", o2::utils::Str::concat_string(mOutDirName, '/', "TOFraw.cfg")); encoder.close(); } diff --git a/Detectors/TPC/workflow/src/PublisherSpec.cxx b/Detectors/TPC/workflow/src/PublisherSpec.cxx index 203bb9facd588..619c6ad7a3d57 100644 --- a/Detectors/TPC/workflow/src/PublisherSpec.cxx +++ b/Detectors/TPC/workflow/src/PublisherSpec.cxx @@ -64,8 +64,8 @@ DataProcessorSpec createPublisherSpec(PublisherConf const& config, bool propagat auto initFunction = [config, propagateMC, creator](InitContext& ic) { // get the option from the init context - auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("infile")); + auto filename = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("infile")); auto treename = ic.options().get("treename"); auto clbrName = ic.options().get(config.databranch.option.c_str()); auto mcbrName = ic.options().get(config.mcbranch.option.c_str()); diff --git a/Detectors/TPC/workflow/src/TrackReaderSpec.cxx b/Detectors/TPC/workflow/src/TrackReaderSpec.cxx index 338b2ffa81266..dd860bd5cc6cf 100644 --- a/Detectors/TPC/workflow/src/TrackReaderSpec.cxx +++ b/Detectors/TPC/workflow/src/TrackReaderSpec.cxx @@ -30,8 +30,8 @@ TrackReader::TrackReader(bool useMC) void TrackReader::init(InitContext& ic) { - mInputFileName = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("infile")); + mInputFileName = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("infile")); connectTree(mInputFileName); } diff --git a/Detectors/TRD/simulation/src/Trap2CRU.cxx b/Detectors/TRD/simulation/src/Trap2CRU.cxx index cfcfedea3d724..e974195b3733d 100644 --- a/Detectors/TRD/simulation/src/Trap2CRU.cxx +++ b/Detectors/TRD/simulation/src/Trap2CRU.cxx @@ -175,22 +175,22 @@ void Trap2CRU::readTrapData() // filename structure of trd_cru_[CRU#]_[upper/lower].raw std::string whichrun = mUseTrackletHCHeader ? "run3" : "run2"; if (mFilePer == "all") { // single file for all links - outFileLink = o2::utils::concat_string(mOutputDir, "/", outPrefix, outSuffix); + outFileLink = o2::utils::Str::concat_string(mOutputDir, "/", outPrefix, outSuffix); } else if (mFilePer == "sm") { int sm = link / 4; std::stringstream ss; ss << std::setw(2) << std::setfill('0') << sm; std::string supermodule = ss.str(); - outFileLink = o2::utils::concat_string(mOutputDir, "/", outPrefix, "_sm_", supermodule, outSuffix); + outFileLink = o2::utils::Str::concat_string(mOutputDir, "/", outPrefix, "_sm_", supermodule, outSuffix); } else if (mFilePer == "cru") { - outFileLink = o2::utils::concat_string(mOutputDir, "/", outPrefix, "_cru_", std::to_string(mCruID), outSuffix); + outFileLink = o2::utils::Str::concat_string(mOutputDir, "/", outPrefix, "_cru_", std::to_string(mCruID), outSuffix); } else if (mFilePer == "halfcru") { - outFileLink = o2::utils::concat_string(mOutputDir, "/", outPrefix, "_cru_", std::to_string(mCruID), trdside, outSuffix); + outFileLink = o2::utils::Str::concat_string(mOutputDir, "/", outPrefix, "_cru_", std::to_string(mCruID), trdside, outSuffix); } else { throw std::runtime_error("invalid option provided for file grouping"); } - //std::string outputFilelink = o2::utils::concat_string(prefix, "trd_cru_", std::to_string(mCruID), "_", trdside, "_", whichrun, ".raw"); + //std::string outputFilelink = o2::utils::Str::concat_string(prefix, "trd_cru_", std::to_string(mCruID), "_", trdside, "_", whichrun, ".raw"); LOG(info) << "registering links"; mWriter.registerLink(mFeeID, mCruID, mLinkID, mEndPointID, outFileLink); } diff --git a/Detectors/TRD/simulation/src/trap2raw.cxx b/Detectors/TRD/simulation/src/trap2raw.cxx index cb32d62b7e9f4..e4f6e9f54747a 100644 --- a/Detectors/TRD/simulation/src/trap2raw.cxx +++ b/Detectors/TRD/simulation/src/trap2raw.cxx @@ -136,7 +136,7 @@ void trap2raw(const std::string& inpDigitsName, const std::string& inpTrackletsN } mc2raw.setTrackletHCHeader(trackletHCHeader); mc2raw.readTrapData(); - wr.writeConfFile(wr.getOrigin().str, "RAWDATA", o2::utils::concat_string(outDirName, wr.getOrigin().str, "raw.cfg")); + wr.writeConfFile(wr.getOrigin().str, "RAWDATA", o2::utils::Str::concat_string(outDirName, wr.getOrigin().str, "raw.cfg")); // swTot.Stop(); swTot.Print(); diff --git a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx index 47dc853717cbc..dcdf90b3d48d1 100644 --- a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx @@ -273,7 +273,7 @@ DataProcessorSpec getTRDGlobalTrackingSpec(bool useMC, bool useTrkltTransf, GTra outputs.emplace_back(o2::header::gDataOriginTRD, "MATCHTRD_TPC", 0, Lifetime::Timeframe); } - std::string processorName = o2::utils::concat_string("trd-globaltracking", GTrackID::getSourcesNames(src)); + std::string processorName = o2::utils::Str::concat_string("trd-globaltracking", GTrackID::getSourcesNames(src)); std::replace(processorName.begin(), processorName.end(), ',', '_'); return DataProcessorSpec{ diff --git a/Detectors/TRD/workflow/src/TRDTrackletReaderSpec.cxx b/Detectors/TRD/workflow/src/TRDTrackletReaderSpec.cxx index ab53c8ec1efa9..80186031c2fc8 100644 --- a/Detectors/TRD/workflow/src/TRDTrackletReaderSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDTrackletReaderSpec.cxx @@ -29,10 +29,10 @@ void TRDTrackletReader::init(InitContext& ic) { // get the option from the init context LOG(INFO) << "Init TRD tracklet reader!"; - mInFileNameTrklt = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("trd-tracklet-infile")); - mInTreeNameTrklt = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("treename")); + mInFileNameTrklt = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("trd-tracklet-infile")); + mInTreeNameTrklt = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("treename")); connectTree(); if (mUseTrackletTransform) { connectTreeCTracklet(); diff --git a/Detectors/ZDC/simulation/src/Digits2Raw.cxx b/Detectors/ZDC/simulation/src/Digits2Raw.cxx index 7b294dc615a92..c4e04c6568d48 100644 --- a/Detectors/ZDC/simulation/src/Digits2Raw.cxx +++ b/Detectors/ZDC/simulation/src/Digits2Raw.cxx @@ -61,7 +61,7 @@ void Digits2Raw::processDigits(const std::string& outDir, const std::string& fil mEndPointID = uint32_t(0); for (int ilink = 0; ilink < NLinks; ilink++) { mFeeID = uint64_t(ilink); - std::string outFileLink = mOutputPerLink ? o2::utils::concat_string(outd, "zdc_link", std::to_string(ilink), ".raw") : o2::utils::concat_string(outd, "zdc.raw"); + std::string outFileLink = mOutputPerLink ? o2::utils::Str::concat_string(outd, "zdc_link", std::to_string(ilink), ".raw") : o2::utils::Str::concat_string(outd, "zdc.raw"); mWriter.registerLink(mFeeID, mCruID, mLinkID, mEndPointID, outFileLink); } diff --git a/Detectors/ZDC/simulation/src/digi2raw.cxx b/Detectors/ZDC/simulation/src/digi2raw.cxx index f34efd45213fd..dbb8cf1f7dc17 100644 --- a/Detectors/ZDC/simulation/src/digi2raw.cxx +++ b/Detectors/ZDC/simulation/src/digi2raw.cxx @@ -171,7 +171,7 @@ void digi2raw(const std::string& inpName, const std::string& outDir, int verbosi d2r.emptyBunches(bp); d2r.setVerbosity(verbosity); d2r.processDigits(outDirName, inpName); - wr.writeConfFile(wr.getOrigin().str, "RAWDATA", o2::utils::concat_string(outDirName, wr.getOrigin().str, "raw.cfg")); + wr.writeConfFile(wr.getOrigin().str, "RAWDATA", o2::utils::Str::concat_string(outDirName, wr.getOrigin().str, "raw.cfg")); // swTot.Stop(); swTot.Print(); diff --git a/Detectors/ZDC/workflow/src/DigitReaderSpec.cxx b/Detectors/ZDC/workflow/src/DigitReaderSpec.cxx index 809660efb573c..276371b5b48f9 100644 --- a/Detectors/ZDC/workflow/src/DigitReaderSpec.cxx +++ b/Detectors/ZDC/workflow/src/DigitReaderSpec.cxx @@ -34,8 +34,8 @@ namespace zdc void DigitReader::init(InitContext& ic) { - auto filename = o2::utils::concat_string(o2::base::NameConf::rectifyDirectory(ic.options().get("input-dir")), - ic.options().get("zdc-digit-infile")); + auto filename = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("zdc-digit-infile")); mFile = std::make_unique(filename.c_str()); if (!mFile->IsOpen()) { LOG(ERROR) << "Cannot open the " << filename.c_str() << " file !"; From 8c618a8c3f9365558661edd05e28cfdfe0adf67a Mon Sep 17 00:00:00 2001 From: shahoian Date: Fri, 30 Apr 2021 01:42:02 +0200 Subject: [PATCH 329/770] Convert NameConf to ConfigurableParam, allow setting directories * one can pass --configKeyValues NameConf.mDirXXX for certain common files, currently defined keys are NameConf.mDirGRP, NameConf.mDirGeom, NameConf.mDirMatLUT * Adapt GRPObject::loadFrom and GeomManager::loadGeometry to use these paths * Make sure that all workflows contributing to FST and many others, which potentially may need to read these common files, are parsing and updating ConfigurableParam --- .../Utils/include/CommonUtils/StringUtils.h | 2 +- Common/Utils/src/StringUtils.cxx | 4 +- .../DetectorsCommonDataFormats/NameConf.h | 23 +++++--- .../src/DetectorsCommonDataFormatsLinkDef.h | 1 + DataFormats/Detectors/Common/src/NameConf.cxx | 59 ++++++++++--------- .../include/DataFormatsParameters/GRPObject.h | 2 +- DataFormats/Parameters/src/GRPObject.cxx | 6 +- .../simulation/src/DigitizationContext.cxx | 2 +- Detectors/AOD/src/aod-producer-workflow.cxx | 4 +- Detectors/Align/src/Controller.cxx | 4 +- .../Base/include/DetectorsBase/Propagator.h | 2 +- .../src/cpv-calib-workflow.cxx | 3 + .../CTF/workflow/src/ctf-reader-workflow.cxx | 3 + .../CTF/workflow/src/ctf-writer-workflow.cxx | 3 + .../workflow/ccdb-populator-workflow.cxx | 12 ++++ .../src/mean-vertex-calibration-workflow.cxx | 6 +- .../src/dcs-data-client-workflow.cxx | 6 ++ .../testWorkflow/src/dcs-data-workflow.cxx | 15 +++-- .../emc-channel-calib-workflow.cxx | 7 ++- .../EMCAL/workflow/src/emc-reco-workflow.cxx | 2 + .../workflow/src/digits-reader-workflow.cxx | 2 +- .../FIT/FDD/workflow/src/fdd-flp-workflow.cxx | 7 +++ .../FT0CalibrationDummy-Workflow.cxx | 15 +++-- .../workflow/src/digits-reader-workflow.cxx | 2 +- .../FIT/FT0/workflow/src/ft0-flp-workflow.cxx | 5 ++ .../workflow/src/digits-reader-workflow.cxx | 2 +- .../helpers/src/GlobalTrackClusterReader.cxx | 2 + .../src/CosmicsMatchingSpec.cxx | 4 +- .../src/PrimaryVertexingSpec.cxx | 4 +- .../src/SecondaryVertexingSpec.cxx | 2 +- .../src/TPCITSMatchingSpec.cxx | 4 +- .../tofworkflow/src/RecoWorkflowSpec.cxx | 16 +---- .../src/RecoWorkflowWithTPCSpec.cxx | 2 +- .../tofworkflow/src/tof-matcher-global.cxx | 1 + .../tofworkflow/src/tof-matcher-tpc.cxx | 2 + .../src/TPCInterpolationSpec.cxx | 2 +- .../testWorkflow/its-calib-workflow.cxx | 8 +++ .../ITS/workflow/src/CookedTrackerSpec.cxx | 2 +- .../ITSMFT/ITS/workflow/src/TrackerSpec.cxx | 2 +- .../src/its-cluster-reader-workflow.cxx | 8 +++ .../common/workflow/src/STFDecoderSpec.cxx | 2 +- .../Common/src/dcs-processor-workflow.cxx | 1 + .../src/pedestal-calib-workflow.cxx | 3 + .../src/pedestal-decoding-workflow.cxx | 4 ++ .../tracks-to-tracks-at-vertex-workflow.cxx | 15 ++++- .../Workflow/src/raw-to-digits-workflow.cxx | 5 +- .../MUON/MID/Workflow/src/reco-workflow.cxx | 6 +- .../src/phos-calib-workflow.cxx | 4 ++ Detectors/TOF/compression/CMakeLists.txt | 5 ++ .../TOF/compression/src/tof-compressor.cxx | 5 +- Detectors/TPC/qc/src/Tracking.cxx | 2 +- .../workflow/src/TRDGlobalTrackingSpec.cxx | 2 +- .../src/TRDTrackletTransformerWorkflow.cxx | 3 + .../Vertexing/src/VertexTrackMatcher.cxx | 2 +- Detectors/ZDC/raw/src/raw-parser.cxx | 9 ++- .../TRDTracking/macros/run_trd_tracker.C | 2 +- GPU/Workflow/src/GPUWorkflowSpec.cxx | 4 +- GPU/Workflow/src/O2GPUDPLDisplay.cxx | 4 +- .../src/SimpleDigitizerWorkflow.cxx | 5 +- macro/analyzeHits.C | 2 +- macro/initSimGeomAndField.C | 51 +--------------- macro/migrateSimFiles.C | 2 +- prodtests/full-system-test/dpl-workflow.sh | 4 ++ 63 files changed, 244 insertions(+), 156 deletions(-) diff --git a/Common/Utils/include/CommonUtils/StringUtils.h b/Common/Utils/include/CommonUtils/StringUtils.h index 328eef522bcd0..068c2e7e64459 100644 --- a/Common/Utils/include/CommonUtils/StringUtils.h +++ b/Common/Utils/include/CommonUtils/StringUtils.h @@ -117,7 +117,7 @@ struct Str { static std::string getFullPath(const std::string_view p); // rectify directory, applying convention "none"=="" - static std::string rectifyDirectory(const std::string& _dir); + static std::string rectifyDirectory(const std::string_view p); ClassDefNV(Str, 1); }; diff --git a/Common/Utils/src/StringUtils.cxx b/Common/Utils/src/StringUtils.cxx index 5f5dea484ecce..154b4b6c27ebd 100644 --- a/Common/Utils/src/StringUtils.cxx +++ b/Common/Utils/src/StringUtils.cxx @@ -47,9 +47,9 @@ std::string Str::getFullPath(const std::string_view p) return boost::filesystem::canonical(std::string{p}).generic_string(); } -std::string Str::rectifyDirectory(const std::string& _dir) +std::string Str::rectifyDirectory(const std::string_view p) { - std::string dir = _dir; + std::string dir(p); if (dir.empty() || dir == "none") { dir = ""; } else { diff --git a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h index 10cef797c86e7..c49679b16bd07 100644 --- a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h +++ b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h @@ -24,7 +24,7 @@ namespace base { // Class for standardization of the names for output files and trees -class NameConf +class NameConf : public o2::conf::ConfigurableParamHelper { using DId = o2::detectors::DetID; @@ -42,11 +42,8 @@ class NameConf return o2::utils::Str::concat_string(prefix, "_", DIGITS_STRING, d.getName(), ".root"); } - // Filename to store general run parameters (GRP) - static std::string getGRPFileName(const std::string_view prefix = STANDARDSIMPREFIX) - { - return o2::utils::Str::concat_string(prefix, "_", GRP_STRING, ".root"); - } + // Filename of general run parameters (GRP) + static std::string getGRPFileName(const std::string_view prefix = STANDARDSIMPREFIX); // Filename to store kinematics + TrackRefs static std::string getMCKinematicsFileName(const std::string_view prefix = STANDARDSIMPREFIX) @@ -100,6 +97,10 @@ class NameConf static std::string getCTFDictFileName(); private: + // helper method to build filenames + static std::string buildFileName(const std::string_view prefix, const std::string_view delimiter, const std::string_view defPrefix, const std::string_view defName, + const std::string_view extension, const std::string_view optDir = ""); + // unmodifiable constants used to construct filenames etc static constexpr std::string_view STANDARDSIMPREFIX = "o2sim"; static constexpr std::string_view HITS_STRING = "Hits"; // hardcoded @@ -110,9 +111,17 @@ class NameConf static constexpr std::string_view GEOM_FILE_STRING = "geometry"; static constexpr std::string_view CUT_FILE_STRING = "proc-cut"; static constexpr std::string_view CONFIG_STRING = "configuration"; - + static constexpr std::string_view ROOT_EXT_STRING = "root"; + static constexpr std::string_view DAT_EXT_STRING = "dat"; static constexpr std::string_view ALPIDECLUSDICTFILENAME = "dictionary"; static constexpr std::string_view MATBUDLUT = "matbud"; + + // these are configurable paths for some commonly used files + std::string mDirGRP = "none"; // directory for GRP file ("none" == "") + std::string mDirGeom = "none"; // directory for geometry file + std::string mDirMatLUT = "none"; // directory for material LUT + + O2ParamDef(NameConf, "NameConf"); }; } // namespace base diff --git a/DataFormats/Detectors/Common/src/DetectorsCommonDataFormatsLinkDef.h b/DataFormats/Detectors/Common/src/DetectorsCommonDataFormatsLinkDef.h index 019a2bca9499f..18c3a6133636c 100644 --- a/DataFormats/Detectors/Common/src/DetectorsCommonDataFormatsLinkDef.h +++ b/DataFormats/Detectors/Common/src/DetectorsCommonDataFormatsLinkDef.h @@ -24,6 +24,7 @@ #pragma link C++ class o2::detectors::SimTraits + ; #pragma link C++ class o2::base::NameConf + ; +#pragma link C++ class o2::conf::ConfigurableParamHelper < o2::base::NameConf> + ; #pragma link C++ class o2::ctf::CTFHeader + ; #pragma link C++ class o2::ctf::Registry + ; diff --git a/DataFormats/Detectors/Common/src/NameConf.cxx b/DataFormats/Detectors/Common/src/NameConf.cxx index 3802bc4a91e82..ebebcabee0e04 100644 --- a/DataFormats/Detectors/Common/src/NameConf.cxx +++ b/DataFormats/Detectors/Common/src/NameConf.cxx @@ -12,55 +12,58 @@ #include #include +O2ParamImpl(o2::base::NameConf); + using namespace o2::base; using DId = o2::detectors::DetID; +std::string NameConf::buildFileName(const std::string_view prefix, const std::string_view delimiter, const std::string_view defPrefix, const std::string_view defName, + const std::string_view extension, const std::string_view optDir) +{ + if (o2::utils::Str::pathIsDirectory(prefix)) { // if path is directory, just add to default name, ignoring optional directory optDir argument + return o2::utils::Str::concat_string(prefix, "/", defPrefix, delimiter, defName, extension); + } else if (!prefix.empty() && o2::utils::Str::pathExists(prefix)) { // explicit file path is provided, use it directly + return std::string(prefix); + } + auto dir = o2::utils::Str::rectifyDirectory(optDir); // directory might have been provided + // is the prefix really prefix or a file-name + if (!prefix.empty()) { + auto path = o2::utils::Str::concat_string(dir, prefix); + if (o2::utils::Str::pathExists(path)) { + return path; + } + } + return o2::utils::Str::concat_string(dir, prefix.empty() ? defPrefix : prefix, delimiter, defName, '.', extension); +} + // Filename to store geometry file std::string NameConf::getGeomFileName(const std::string_view prefix) { - // check if the prefix is an existing path - if (o2::utils::Str::pathIsDirectory(prefix)) { - return o2::utils::Str::concat_string(prefix, "/", STANDARDSIMPREFIX, "_", GEOM_FILE_STRING, ".root"); - } else if (o2::utils::Str::pathExists(prefix)) { - return std::string(prefix); // it is a full file - } - return o2::utils::Str::concat_string(prefix.empty() ? STANDARDSIMPREFIX : prefix, "_", GEOM_FILE_STRING, ".root"); + return buildFileName(prefix, "_", STANDARDSIMPREFIX, GEOM_FILE_STRING, ROOT_EXT_STRING, Instance().mDirGeom); +} + +// Filename to store general run parameters (GRP) +std::string NameConf::getGRPFileName(const std::string_view prefix) +{ + return buildFileName(prefix, "_", STANDARDSIMPREFIX, GRP_STRING, ROOT_EXT_STRING, Instance().mDirGRP); } // Filename to store simulation cuts/process summary std::string NameConf::getCutProcFileName(std::string_view prefix) { - // check if the prefix is an existing path - if (o2::utils::Str::pathIsDirectory(prefix)) { - return o2::utils::Str::concat_string(prefix, "/", STANDARDSIMPREFIX, "_", CUT_FILE_STRING, ".dat"); - } else if (o2::utils::Str::pathExists(prefix)) { - return std::string(prefix); // it is a full file - } - return o2::utils::Str::concat_string(prefix.empty() ? STANDARDSIMPREFIX : prefix, "_", CUT_FILE_STRING, ".dat"); + return buildFileName(prefix, "_", STANDARDSIMPREFIX, CUT_FILE_STRING, DAT_EXT_STRING); } // Filename to store ITSMFT dictionary std::string NameConf::getAlpideClusterDictionaryFileName(DId det, const std::string_view prefix, const std::string_view ext) { - // check if the prefix is an existing path - if (o2::utils::Str::pathIsDirectory(prefix)) { - return o2::utils::Str::concat_string(prefix, "/", det.getName(), ALPIDECLUSDICTFILENAME, ext); - } else if (o2::utils::Str::pathExists(prefix)) { - return std::string(prefix); // it is a full file - } - return o2::utils::Str::concat_string(prefix, det.getName(), ALPIDECLUSDICTFILENAME, ext); + return buildFileName(prefix, "", det.getName(), ALPIDECLUSDICTFILENAME, ext); } // Filename to store material LUT file std::string NameConf::getMatLUTFileName(const std::string_view prefix) { - // check if the prefix is an existing path - if (o2::utils::Str::pathIsDirectory(prefix)) { - return o2::utils::Str::concat_string(prefix, "/", MATBUDLUT, ".root"); - } else if (o2::utils::Str::pathExists(prefix)) { - return std::string(prefix); // it is a full file - } - return o2::utils::Str::concat_string(prefix, MATBUDLUT, ".root"); + return buildFileName(prefix, "", "", MATBUDLUT, ROOT_EXT_STRING, Instance().mDirMatLUT); } std::string NameConf::getCTFFileName(uint32_t run, uint32_t orb, uint32_t id, const std::string_view prefix) diff --git a/DataFormats/Parameters/include/DataFormatsParameters/GRPObject.h b/DataFormats/Parameters/include/DataFormatsParameters/GRPObject.h index d0ec0ac9e7651..88634152c4727 100644 --- a/DataFormats/Parameters/include/DataFormatsParameters/GRPObject.h +++ b/DataFormats/Parameters/include/DataFormatsParameters/GRPObject.h @@ -138,7 +138,7 @@ class GRPObject /// print itself void print() const; - static GRPObject* loadFrom(const std::string& grpFileName, const std::string& grpName = "GRP"); + static GRPObject* loadFrom(const std::string& grpFileName = "", const std::string& grpName = "GRP"); private: timePoint mTimeStart = 0; ///< DAQ_time_start entry from DAQ logbook diff --git a/DataFormats/Parameters/src/GRPObject.cxx b/DataFormats/Parameters/src/GRPObject.cxx index 9eb6f09629e77..8287681745342 100644 --- a/DataFormats/Parameters/src/GRPObject.cxx +++ b/DataFormats/Parameters/src/GRPObject.cxx @@ -17,6 +17,7 @@ #include "DataFormatsParameters/GRPObject.h" #include #include "CommonConstants/PhysicsConstants.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::parameters; using namespace o2::constants::physics; @@ -112,9 +113,10 @@ GRPObject::ROMode GRPObject::getDetROMode(o2::detectors::DetID id) const GRPObject* GRPObject::loadFrom(const std::string& grpFileName, const std::string& grpName) { // load object from file - TFile flGRP(grpFileName.data()); + auto fname = o2::base::NameConf::getGRPFileName(grpFileName); + TFile flGRP(fname.c_str()); if (flGRP.IsZombie()) { - LOG(ERROR) << "Failed to open " << grpFileName; + LOG(ERROR) << "Failed to open " << fname; throw std::runtime_error("Failed to open GRP file"); } auto grp = reinterpret_cast( diff --git a/DataFormats/simulation/src/DigitizationContext.cxx b/DataFormats/simulation/src/DigitizationContext.cxx index f6263a1accd26..75d49a459e58f 100644 --- a/DataFormats/simulation/src/DigitizationContext.cxx +++ b/DataFormats/simulation/src/DigitizationContext.cxx @@ -178,7 +178,7 @@ o2::parameters::GRPObject const& DigitizationContext::getGRP() const if (!mGRP) { // we take the GRP from the background file // maybe we should add a check that all GRPs are consistent .. - mGRP = o2::parameters::GRPObject::loadFrom(o2::base::NameConf::getGRPFileName(mSimPrefixes[0].data()).c_str()); + mGRP = o2::parameters::GRPObject::loadFrom(mSimPrefixes[0]); } return *mGRP; } diff --git a/Detectors/AOD/src/aod-producer-workflow.cxx b/Detectors/AOD/src/aod-producer-workflow.cxx index a569e7df6d50e..6ad5990e040ce 100644 --- a/Detectors/AOD/src/aod-producer-workflow.cxx +++ b/Detectors/AOD/src/aod-producer-workflow.cxx @@ -18,7 +18,8 @@ void customize(std::vector& workflowOptions) { // option allowing to set parameters std::vector options{ - ConfigParamSpec{"ignore-aod-writer", VariantType::Int, 0, {"Ignore DPL AOD writer and write tables directly into a file. 0 -- off, != 0 -- on"}}}; + {"ignore-aod-writer", VariantType::Int, 0, {"Ignore DPL AOD writer and write tables directly into a file. 0 -- off, != 0 -- on"}}, + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}}; std::swap(workflowOptions, options); } @@ -27,6 +28,7 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { + o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); // o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("ignore-aod-writer")); int ignoreWriter = configcontext.options().get("ignore-aod-writer"); return std::move(o2::aodproducer::getAODProducerWorkflow(ignoreWriter)); diff --git a/Detectors/Align/src/Controller.cxx b/Detectors/Align/src/Controller.cxx index 1dda9848c9911..2c0d38b1975ad 100644 --- a/Detectors/Align/src/Controller.cxx +++ b/Detectors/Align/src/Controller.cxx @@ -983,8 +983,8 @@ void Controller::acknowledgeNewRun(int run) LOG(WARNING) << __PRETTY_FUNCTION__ << " yet incomplete"; o2::base::GeometryManager::loadGeometry(); - o2::base::PropagatorImpl::initFieldFromGRP(o2::base::NameConf::getGRPFileName()); - std::unique_ptr grp{o2::parameters::GRPObject::loadFrom(o2::base::NameConf::getGRPFileName())}; + o2::base::PropagatorImpl::initFieldFromGRP(); + std::unique_ptr grp{o2::parameters::GRPObject::loadFrom()}; //FIXME(milettri): needs AliESDEvent // // load needed info for new run diff --git a/Detectors/Base/include/DetectorsBase/Propagator.h b/Detectors/Base/include/DetectorsBase/Propagator.h index 206990a9e94b0..04e110a63ef0e 100644 --- a/Detectors/Base/include/DetectorsBase/Propagator.h +++ b/Detectors/Base/include/DetectorsBase/Propagator.h @@ -134,7 +134,7 @@ class PropagatorImpl } static int initFieldFromGRP(const o2::parameters::GRPObject* grp, bool verbose = false); - static int initFieldFromGRP(const std::string grpFileName, std::string grpName = "GRP", bool verbose = false); + static int initFieldFromGRP(const std::string grpFileName = "", std::string grpName = "GRP", bool verbose = false); #endif GPUd() MatBudget getMatBudget(MatCorrType corrType, const o2::math_utils::Point3D& p0, const o2::math_utils::Point3D& p1) const; diff --git a/Detectors/CPV/calib/CPVCalibWorkflow/src/cpv-calib-workflow.cxx b/Detectors/CPV/calib/CPVCalibWorkflow/src/cpv-calib-workflow.cxx index 8abc7effd52ec..0ae61ea9e259f 100644 --- a/Detectors/CPV/calib/CPVCalibWorkflow/src/cpv-calib-workflow.cxx +++ b/Detectors/CPV/calib/CPVCalibWorkflow/src/cpv-calib-workflow.cxx @@ -12,6 +12,7 @@ #include "CPVCalibWorkflow/CPVGainCalibDevice.h" #include "CPVCalibWorkflow/CPVBadMapCalibDevice.h" #include "Framework/DataProcessorSpec.h" +#include "CommonUtils/ConfigurableParam.h" using namespace o2::framework; @@ -25,6 +26,7 @@ void customize(std::vector& workflowOptions) workflowOptions.push_back(ConfigParamSpec{"gains", o2::framework::VariantType::Bool, false, {"do gain calculation"}}); workflowOptions.push_back(ConfigParamSpec{"badmap", o2::framework::VariantType::Bool, false, {"do bad map calculation"}}); workflowOptions.push_back(ConfigParamSpec{"path", o2::framework::VariantType::String, "./", {"path to store temp files"}}); + workflowOptions.push_back(ConfigParamSpec{"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}); } // ------------------------------------------------------------------ @@ -34,6 +36,7 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { WorkflowSpec specs; + o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); auto useCCDB = configcontext.options().get("use-ccdb"); auto forceUpdate = configcontext.options().get("forceupdate"); auto doPedestals = configcontext.options().get("pedestals"); diff --git a/Detectors/CTF/workflow/src/ctf-reader-workflow.cxx b/Detectors/CTF/workflow/src/ctf-reader-workflow.cxx index b0a60fcbac9d1..cc63ae4545213 100644 --- a/Detectors/CTF/workflow/src/ctf-reader-workflow.cxx +++ b/Detectors/CTF/workflow/src/ctf-reader-workflow.cxx @@ -18,6 +18,7 @@ #include "CTFWorkflow/CTFReaderSpec.h" #include "DataFormatsParameters/GRPObject.h" #include "DetectorsCommonDataFormats/DetID.h" +#include "CommonUtils/ConfigurableParam.h" // Specific detectors specs #include "ITSMFTWorkflow/EntropyDecoderSpec.h" @@ -46,6 +47,7 @@ void customize(std::vector& workflowOptions) options.push_back(ConfigParamSpec{"onlyDet", VariantType::String, std::string{DetID::NONE}, {"comma-separated list of detectors to accept. Overrides skipDet"}}); options.push_back(ConfigParamSpec{"skipDet", VariantType::String, std::string{DetID::NONE}, {"comma-separate list of detectors to skip"}}); options.push_back(ConfigParamSpec{"ctf-input", VariantType::String, "none", {"comma-separated list CTF input files"}}); + options.push_back(ConfigParamSpec{"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}); std::swap(workflowOptions, options); } @@ -55,6 +57,7 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { + o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); DetID::mask_t dets; dets.set(); // by default read all WorkflowSpec specs; diff --git a/Detectors/CTF/workflow/src/ctf-writer-workflow.cxx b/Detectors/CTF/workflow/src/ctf-writer-workflow.cxx index 59703d645c946..06cbc0a1f7522 100644 --- a/Detectors/CTF/workflow/src/ctf-writer-workflow.cxx +++ b/Detectors/CTF/workflow/src/ctf-writer-workflow.cxx @@ -18,6 +18,7 @@ #include "CTFWorkflow/CTFWriterSpec.h" #include "DataFormatsParameters/GRPObject.h" #include "DetectorsCommonDataFormats/DetID.h" +#include "CommonUtils/ConfigurableParam.h" using namespace o2::framework; using DetID = o2::detectors::DetID; @@ -33,6 +34,7 @@ void customize(std::vector& workflowOptions) options.push_back(ConfigParamSpec{"grpfile", VariantType::String, o2::base::NameConf::getGRPFileName(), {"name of the grp file"}}); options.push_back(ConfigParamSpec{"no-grp", VariantType::Bool, false, {"do not read GRP file"}}); options.push_back(ConfigParamSpec{"output-type", VariantType::String, "ctf", {"output types: ctf (per TF) or dict (create dictionaries) or both or none"}}); + options.push_back(ConfigParamSpec{"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}); std::swap(workflowOptions, options); } @@ -42,6 +44,7 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { DetID::mask_t dets; + o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); long run = 0; bool doCTF = true, doDict = false, dictPerDet = false; if (!configcontext.helpOnCommandLine()) { diff --git a/Detectors/Calibration/workflow/ccdb-populator-workflow.cxx b/Detectors/Calibration/workflow/ccdb-populator-workflow.cxx index 6b3466895b9ca..f8c51c8ba12a6 100644 --- a/Detectors/Calibration/workflow/ccdb-populator-workflow.cxx +++ b/Detectors/Calibration/workflow/ccdb-populator-workflow.cxx @@ -10,9 +10,20 @@ #include "Framework/DataProcessorSpec.h" #include "CCDBPopulatorSpec.h" +#include "CommonUtils/ConfigurableParam.h" using namespace o2::framework; +// we need to add workflow options before including Framework/runDataProcessing +void customize(std::vector& workflowOptions) +{ + // option allowing to set parameters + std::vector options{ + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}}; + + std::swap(workflowOptions, options); +} + // we need to add workflow options before including Framework/runDataProcessing void customize(std::vector& policies) { @@ -29,6 +40,7 @@ void customize(std::vector& policies) WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { WorkflowSpec specs; + o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); specs.emplace_back(getCCDBPopulatorDeviceSpec()); return specs; } diff --git a/Detectors/Calibration/workflow/src/mean-vertex-calibration-workflow.cxx b/Detectors/Calibration/workflow/src/mean-vertex-calibration-workflow.cxx index 030a201ef954d..47b2574956471 100644 --- a/Detectors/Calibration/workflow/src/mean-vertex-calibration-workflow.cxx +++ b/Detectors/Calibration/workflow/src/mean-vertex-calibration-workflow.cxx @@ -10,14 +10,17 @@ #include "Framework/DataProcessorSpec.h" #include "DetectorsCalibrationWorkflow/MeanVertexCalibratorSpec.h" +#include "CommonUtils/ConfigurableParam.h" using namespace o2::framework; -// we need to add workflow options before including Framework/runDataProcessing // we need to add workflow options before including Framework/runDataProcessing void customize(std::vector& workflowOptions) { // option allowing to set parameters + std::vector options{ + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}}; + std::swap(workflowOptions, options); } // ------------------------------------------------------------------ @@ -27,6 +30,7 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { WorkflowSpec specs; + o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); specs.emplace_back(getMeanVertexCalibDeviceSpec()); return specs; } diff --git a/Detectors/DCS/testWorkflow/src/dcs-data-client-workflow.cxx b/Detectors/DCS/testWorkflow/src/dcs-data-client-workflow.cxx index 5f6eb0337f4b0..334e7008ddfb4 100644 --- a/Detectors/DCS/testWorkflow/src/dcs-data-client-workflow.cxx +++ b/Detectors/DCS/testWorkflow/src/dcs-data-client-workflow.cxx @@ -13,6 +13,7 @@ #include "Framework/DataProcessorSpec.h" #include "DCSConsumerSpec.h" +#include "CommonUtils/ConfigurableParam.h" using namespace o2::framework; @@ -20,6 +21,10 @@ using namespace o2::framework; void customize(std::vector& workflowOptions) { // option allowing to set parameters + std::vector options{ + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}}; + + std::swap(workflowOptions, options); } // ------------------------------------------------------------------ @@ -29,6 +34,7 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { WorkflowSpec specs; + o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); specs.emplace_back(getDCSConsumerSpec()); return specs; } diff --git a/Detectors/DCS/testWorkflow/src/dcs-data-workflow.cxx b/Detectors/DCS/testWorkflow/src/dcs-data-workflow.cxx index 739fc562f8432..66ad084ab7412 100644 --- a/Detectors/DCS/testWorkflow/src/dcs-data-workflow.cxx +++ b/Detectors/DCS/testWorkflow/src/dcs-data-workflow.cxx @@ -21,15 +21,19 @@ #include "Framework/DataProcessorSpec.h" #include "DCSDataGeneratorSpec.h" #include "DCSDataProcessorSpec.h" +#include "CommonUtils/ConfigurableParam.h" using namespace o2::framework; -// // we need to add workflow options before including Framework/runDataProcessing -// void customize(std::vector& workflowOptions) -// { -// // option allowing to set parameters -// } +// we need to add workflow options before including Framework/runDataProcessing +void customize(std::vector& workflowOptions) +{ + // option allowing to set parameters + std::vector options{ + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}}; + std::swap(workflowOptions, options); +} // ------------------------------------------------------------------ #include "Framework/runDataProcessing.h" @@ -37,6 +41,7 @@ using namespace o2::framework; WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { WorkflowSpec specs; + o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); specs.emplace_back(getDCSDataGeneratorSpec()); specs.emplace_back(getDCSDataProcessorSpec()); return specs; diff --git a/Detectors/EMCAL/calibration/testWorkflow/emc-channel-calib-workflow.cxx b/Detectors/EMCAL/calibration/testWorkflow/emc-channel-calib-workflow.cxx index 9aa92ae0ee66a..a2c84bc05e9fe 100644 --- a/Detectors/EMCAL/calibration/testWorkflow/emc-channel-calib-workflow.cxx +++ b/Detectors/EMCAL/calibration/testWorkflow/emc-channel-calib-workflow.cxx @@ -17,6 +17,7 @@ #include "Framework/WorkflowSpec.h" #include "Framework/ConfigParamSpec.h" #include "Algorithm/RangeTokenizer.h" +#include "CommonUtils/ConfigurableParam.h" #include #include @@ -26,7 +27,10 @@ // including Framework/runDataProcessing void customize(std::vector& workflowOptions) { - // we don't have any configuration options for this task + std::vector options{ + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}}; + + std::swap(workflowOptions, options); } #include "Framework/runDataProcessing.h" // the main driver @@ -34,6 +38,7 @@ void customize(std::vector& workflowOptions) o2::framework::WorkflowSpec defineDataProcessing(o2::framework::ConfigContext const& cfgc) { WorkflowSpec specs; + o2::conf::ConfigurableParam::updateFromString(cfgc.options().get("configKeyValues")); specs.emplace_back(getEMCALChannelCalibDeviceSpec()); return specs; } diff --git a/Detectors/EMCAL/workflow/src/emc-reco-workflow.cxx b/Detectors/EMCAL/workflow/src/emc-reco-workflow.cxx index f52babc6e9c7d..44fa18b4381e9 100644 --- a/Detectors/EMCAL/workflow/src/emc-reco-workflow.cxx +++ b/Detectors/EMCAL/workflow/src/emc-reco-workflow.cxx @@ -18,6 +18,7 @@ #include "EMCALWorkflow/RecoWorkflow.h" #include "Algorithm/RangeTokenizer.h" #include "DetectorsRaw/HBFUtilsInitializer.h" +#include "CommonUtils/ConfigurableParam.h" #include #include @@ -59,6 +60,7 @@ void customize(std::vector& workflowOptions) o2::framework::WorkflowSpec defineDataProcessing(o2::framework::ConfigContext const& cfgc) { //bla + o2::conf::ConfigurableParam::updateFromString(cfgc.options().get("configKeyValues")); auto wf = o2::emcal::reco_workflow::getWorkflow(not cfgc.options().get("disable-mc"), // cfgc.options().get("enable-digits-printer"), // cfgc.options().get("input-type"), // diff --git a/Detectors/FIT/FDD/workflow/src/digits-reader-workflow.cxx b/Detectors/FIT/FDD/workflow/src/digits-reader-workflow.cxx index de9c7439b9aac..2b7b3c54bfd92 100644 --- a/Detectors/FIT/FDD/workflow/src/digits-reader-workflow.cxx +++ b/Detectors/FIT/FDD/workflow/src/digits-reader-workflow.cxx @@ -38,7 +38,7 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(const ConfigContext& ctx) { WorkflowSpec specs; - + o2::conf::ConfigurableParam::updateFromString(ctx.options().get("configKeyValues")); DataProcessorSpec producer = o2::fdd::getFDDDigitReaderSpec(ctx.options().get("disable-mc")); specs.push_back(producer); return specs; diff --git a/Detectors/FIT/FDD/workflow/src/fdd-flp-workflow.cxx b/Detectors/FIT/FDD/workflow/src/fdd-flp-workflow.cxx index 02d2c45635e99..047b02b466ec6 100644 --- a/Detectors/FIT/FDD/workflow/src/fdd-flp-workflow.cxx +++ b/Detectors/FIT/FDD/workflow/src/fdd-flp-workflow.cxx @@ -39,6 +39,12 @@ void customize(std::vector& workflowOptions) o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}); + workflowOptions.push_back( + ConfigParamSpec{ + "configKeyValues", + o2::framework::VariantType::String, + "", + {"Semicolon separated key=value strings"}}); } // ------------------------------------------------------------------ @@ -48,6 +54,7 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { LOG(INFO) << "WorkflowSpec defineDataProcessing"; + o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); auto useProcessor = configcontext.options().get("use-process"); auto dumpProcessor = configcontext.options().get("dump-blocks-process"); auto dumpReader = configcontext.options().get("dump-blocks-reader"); diff --git a/Detectors/FIT/FT0/calibration/testWorkflow/FT0CalibrationDummy-Workflow.cxx b/Detectors/FIT/FT0/calibration/testWorkflow/FT0CalibrationDummy-Workflow.cxx index b5a974a8509cc..4903558eb1a5c 100644 --- a/Detectors/FIT/FT0/calibration/testWorkflow/FT0CalibrationDummy-Workflow.cxx +++ b/Detectors/FIT/FT0/calibration/testWorkflow/FT0CalibrationDummy-Workflow.cxx @@ -9,24 +9,31 @@ // or submit itself to any jurisdiction. //Dummy, delete this file if example not needed anymore - #include "Framework/DataProcessorSpec.h" #include "FITCalibration/FITCalibrationDevice.h" #include "FT0Calibration/FT0CalibrationInfoObject.h" #include "FT0Calibration/FT0ChannelTimeTimeSlotContainer.h" #include "FT0Calibration/FT0DummyCalibrationObject.h" +#include "CommonUtils/ConfigurableParam.h" + +using namespace o2::fit; +using namespace o2::framework; void customize(std::vector& workflowOptions) { - //probably some option will be added + // option allowing to set parameters + std::vector options{ + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}}; + + std::swap(workflowOptions, options); } #include "Framework/runDataProcessing.h" -using namespace o2::framework; WorkflowSpec defineDataProcessing(ConfigContext const& config) { WorkflowSpec workflow; + o2::conf::ConfigurableParam::updateFromString(config.options().get("configKeyValues")); using CalibrationDeviceType = o2::fit::FITCalibrationDevice; @@ -49,4 +56,4 @@ WorkflowSpec defineDataProcessing(ConfigContext const& config) workflow.emplace_back(dataProcessorSpec); return workflow; -} \ No newline at end of file +} diff --git a/Detectors/FIT/FT0/workflow/src/digits-reader-workflow.cxx b/Detectors/FIT/FT0/workflow/src/digits-reader-workflow.cxx index be09e4ac3a212..1c342397d1dac 100644 --- a/Detectors/FIT/FT0/workflow/src/digits-reader-workflow.cxx +++ b/Detectors/FIT/FT0/workflow/src/digits-reader-workflow.cxx @@ -41,7 +41,7 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(const ConfigContext& ctx) { WorkflowSpec specs; - + o2::conf::ConfigurableParam::updateFromString(ctx.options().get("configKeyValues")); DataProcessorSpec producer = o2::ft0::getDigitReaderSpec(ctx.options().get("disable-mc"), ctx.options().get("disable-trigger-input")); specs.push_back(producer); return specs; diff --git a/Detectors/FIT/FT0/workflow/src/ft0-flp-workflow.cxx b/Detectors/FIT/FT0/workflow/src/ft0-flp-workflow.cxx index cd846a5141dc8..0ea45643e33f8 100644 --- a/Detectors/FIT/FT0/workflow/src/ft0-flp-workflow.cxx +++ b/Detectors/FIT/FT0/workflow/src/ft0-flp-workflow.cxx @@ -46,6 +46,11 @@ void customize(std::vector& workflowOptions) o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}); + workflowOptions.push_back( + ConfigParamSpec{"configKeyValues", + o2::framework::VariantType::String, + "", + {"Semicolon separated key=value strings"}}); workflowOptions.push_back(ConfigParamSpec{"ignore-dist-stf", VariantType::Bool, false, {"do not subscribe to FLP/DISTSUBTIMEFRAME/0 message (no lost TF recovery)"}}); } diff --git a/Detectors/FIT/FV0/workflow/src/digits-reader-workflow.cxx b/Detectors/FIT/FV0/workflow/src/digits-reader-workflow.cxx index a833355c2bb9b..a933f9ceedd46 100644 --- a/Detectors/FIT/FV0/workflow/src/digits-reader-workflow.cxx +++ b/Detectors/FIT/FV0/workflow/src/digits-reader-workflow.cxx @@ -38,7 +38,7 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(const ConfigContext& ctx) { WorkflowSpec specs; - + o2::conf::ConfigurableParam::updateFromString(ctx.options().get("configKeyValues")); DataProcessorSpec producer = o2::fv0::getDigitReaderSpec(ctx.options().get("disable-mc")); specs.push_back(producer); return specs; diff --git a/Detectors/GlobalTrackingWorkflow/helpers/src/GlobalTrackClusterReader.cxx b/Detectors/GlobalTrackingWorkflow/helpers/src/GlobalTrackClusterReader.cxx index 642bdfc081290..134ca8e122c3f 100644 --- a/Detectors/GlobalTrackingWorkflow/helpers/src/GlobalTrackClusterReader.cxx +++ b/Detectors/GlobalTrackingWorkflow/helpers/src/GlobalTrackClusterReader.cxx @@ -11,6 +11,7 @@ #include "Framework/ConfigParamSpec.h" #include "GlobalTrackingWorkflowHelpers/InputHelper.h" #include "ReconstructionDataFormats/GlobalTrackID.h" +#include "CommonUtils/ConfigurableParam.h" using namespace o2::framework; using namespace o2::globaltracking; @@ -33,6 +34,7 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { WorkflowSpec specs; + o2::conf::ConfigurableParam::updateFromString(cfgc.options().get("configKeyValues")); bool useMC = !cfgc.options().get("disable-mc"); GlobalTrackID::mask_t srcTrk = GlobalTrackID::getSourcesMask(cfgc.options().get("track-types")); diff --git a/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx index c33f2bc3a60d6..41c7f94924804 100644 --- a/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx @@ -77,8 +77,8 @@ void CosmicsMatchingSpec::init(InitContext& ic) mTimer.Reset(); //-------- init geometry and field --------// o2::base::GeometryManager::loadGeometry(); - o2::base::Propagator::initFieldFromGRP(o2::base::NameConf::getGRPFileName()); - std::unique_ptr grp{o2::parameters::GRPObject::loadFrom(o2::base::NameConf::getGRPFileName())}; + o2::base::Propagator::initFieldFromGRP(); + std::unique_ptr grp{o2::parameters::GRPObject::loadFrom()}; const auto& alpParams = o2::itsmft::DPLAlpideParam::Instance(); if (!grp->isDetContinuousReadOut(DetID::ITS)) { mMatching.setITSROFrameLengthMUS(alpParams.roFrameLengthTrig / 1.e3); // ITS ROFrame duration in \mus diff --git a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx index 0b532150d896d..dc3d22360cd54 100644 --- a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx @@ -39,9 +39,9 @@ void PrimaryVertexingSpec::init(InitContext& ic) { //-------- init geometry and field --------// o2::base::GeometryManager::loadGeometry(); - o2::base::Propagator::initFieldFromGRP("o2sim_grp.root"); + o2::base::Propagator::initFieldFromGRP(); - std::unique_ptr grp{o2::parameters::GRPObject::loadFrom(o2::base::NameConf::getGRPFileName())}; + std::unique_ptr grp{o2::parameters::GRPObject::loadFrom()}; const auto& alpParams = o2::itsmft::DPLAlpideParam::Instance(); if (!grp->isDetContinuousReadOut(DetID::ITS)) { mITSROFrameLengthMUS = alpParams.roFrameLengthTrig / 1.e3; // ITS ROFrame duration in \mus diff --git a/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexingSpec.cxx index f6743143a9e6c..3509cb3eb3833 100644 --- a/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexingSpec.cxx @@ -46,7 +46,7 @@ void SecondaryVertexingSpec::init(InitContext& ic) { //-------- init geometry and field --------// o2::base::GeometryManager::loadGeometry(); - o2::base::Propagator::initFieldFromGRP("o2sim_grp.root"); + o2::base::Propagator::initFieldFromGRP(); // this is a hack to provide Mat.LUT from the local file, in general will be provided by the framework from CCDB std::string matLUTPath = ic.options().get("material-lut-path"); std::string matLUTFile = o2::base::NameConf::getMatLUTFileName(matLUTPath); diff --git a/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx index 11907718e4025..c34670705e779 100644 --- a/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx @@ -79,8 +79,8 @@ void TPCITSMatchingDPL::init(InitContext& ic) mTimer.Reset(); //-------- init geometry and field --------// o2::base::GeometryManager::loadGeometry(); - o2::base::Propagator::initFieldFromGRP(o2::base::NameConf::getGRPFileName()); - std::unique_ptr grp{o2::parameters::GRPObject::loadFrom(o2::base::NameConf::getGRPFileName())}; + o2::base::Propagator::initFieldFromGRP(); + std::unique_ptr grp{o2::parameters::GRPObject::loadFrom()}; mMatching.setITSTriggered(!grp->isDetContinuousReadOut(o2::detectors::DetID::ITS)); const auto& alpParams = o2::itsmft::DPLAlpideParam::Instance(); if (mMatching.isITSTriggered()) { diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/RecoWorkflowSpec.cxx b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/RecoWorkflowSpec.cxx index 1d2a67a3be371..2a3a7251b148f 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/RecoWorkflowSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/RecoWorkflowSpec.cxx @@ -56,7 +56,7 @@ class TOFDPLRecoWorkflowTask { // nothing special to be set up o2::base::GeometryManager::loadGeometry(); - o2::base::Propagator::initFieldFromGRP("o2sim_grp.root"); + o2::base::Propagator::initFieldFromGRP(); std::string matLUTPath = ic.options().get("material-lut-path"); std::string matLUTFile = o2::base::NameConf::getMatLUTFileName(matLUTPath); if (o2::utils::Str::pathExists(matLUTFile)) { @@ -86,20 +86,6 @@ class TOFDPLRecoWorkflowTask LOG(INFO) << "TOF Reco Workflow pulled " << recPoints.size() << " FIT RecPoints"; } - //-------- init geometry and field --------// - // std::string path = "./"; - // std::string inputGeom = "O2geometry.root"; - // std::string inputGRP = "o2sim_grp.root"; - - // o2::base::GeometryManager::loadGeometry(path); - // o2::base::Propagator::initFieldFromGRP(path + inputGRP); - - // call actual matching info routine - //#ifdef _ALLOW_DEBUG_TREES_ - // mMatcher.setDebugTreeFileName(path + mMatcher.getDebugTreeFileName()); - // mMatcher.setDebugFlag(o2::globaltracking::MatchTOF::MatchTreeAll); - //#endif - // we do a copy of the input but we are looking for a way to avoid it (current problem in conversion form unique_ptr to *) gsl::span itstpclab; diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/RecoWorkflowWithTPCSpec.cxx b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/RecoWorkflowWithTPCSpec.cxx index aa37f00d399d1..94949db47be00 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/RecoWorkflowWithTPCSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/RecoWorkflowWithTPCSpec.cxx @@ -58,7 +58,7 @@ class TOFDPLRecoWorkflowWithTPCTask { // nothing special to be set up o2::base::GeometryManager::loadGeometry(); - o2::base::Propagator::initFieldFromGRP("o2sim_grp.root"); + o2::base::Propagator::initFieldFromGRP(); std::string matLUTPath = ic.options().get("material-lut-path"); std::string matLUTFile = o2::base::NameConf::getMatLUTFileName(matLUTPath); if (o2::utils::Str::pathExists(matLUTFile)) { diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-global.cxx b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-global.cxx index 447e43b66ef38..e93bf0a7bab7e 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-global.cxx +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-global.cxx @@ -77,6 +77,7 @@ using namespace o2::framework; WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { WorkflowSpec specs; + o2::conf::ConfigurableParam::updateFromString(cfgc.options().get("configKeyValues")); // the lane configuration defines the subspecification ids to be distributed among the lanes. auto nLanes = cfgc.options().get("tof-lanes"); diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-tpc.cxx b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-tpc.cxx index d209fb38de2f3..a7256d388e2e4 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-tpc.cxx +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-tpc.cxx @@ -83,6 +83,8 @@ using namespace o2::framework; WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { WorkflowSpec specs; + o2::conf::ConfigurableParam::updateFromString(cfgc.options().get("configKeyValues")); + // the lane configuration defines the subspecification ids to be distributed among the lanes. auto nLanes = cfgc.options().get("tof-lanes"); auto outputType = cfgc.options().get("output-type"); diff --git a/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TPCInterpolationSpec.cxx b/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TPCInterpolationSpec.cxx index 2b08d7dd064f0..73d95045cd7b0 100644 --- a/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TPCInterpolationSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TPCInterpolationSpec.cxx @@ -32,7 +32,7 @@ void TPCInterpolationDPL::init(InitContext& ic) { //-------- init geometry and field --------// o2::base::GeometryManager::loadGeometry(); - o2::base::Propagator::initFieldFromGRP("o2sim_grp.root"); + o2::base::Propagator::initFieldFromGRP(); mTimer.Stop(); mTimer.Reset(); mInterpolation.init(); diff --git a/Detectors/ITSMFT/ITS/calibration/testWorkflow/its-calib-workflow.cxx b/Detectors/ITSMFT/ITS/calibration/testWorkflow/its-calib-workflow.cxx index af9ddcb72af6c..855130ca419de 100644 --- a/Detectors/ITSMFT/ITS/calibration/testWorkflow/its-calib-workflow.cxx +++ b/Detectors/ITSMFT/ITS/calibration/testWorkflow/its-calib-workflow.cxx @@ -9,6 +9,7 @@ // or submit itself to any jurisdiction. #include "Framework/ConfigParamSpec.h" +#include "CommonUtils/ConfigurableParam.h" using namespace o2::framework; @@ -22,6 +23,12 @@ void customize(std::vector& workflowOptions) VariantType::Bool, true, {"Generate noisy-pixel maps"}}); + workflowOptions.push_back( + ConfigParamSpec{ + "configKeyValues", + VariantType::String, + "", + {"Semicolon separated key=value strings"}}); } // ------------------------------------------------------------------ @@ -33,6 +40,7 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { WorkflowSpec specs; + o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); auto doNoise = configcontext.options().get("doNoise"); LOG(INFO) << "ITS calibration workflow options"; diff --git a/Detectors/ITSMFT/ITS/workflow/src/CookedTrackerSpec.cxx b/Detectors/ITSMFT/ITS/workflow/src/CookedTrackerSpec.cxx index 16c9d744bf706..71cd90d3c3f1e 100644 --- a/Detectors/ITSMFT/ITS/workflow/src/CookedTrackerSpec.cxx +++ b/Detectors/ITSMFT/ITS/workflow/src/CookedTrackerSpec.cxx @@ -55,7 +55,7 @@ void CookedTrackerDPL::init(InitContext& ic) auto nthreads = ic.options().get("nthreads"); mTracker.setNumberOfThreads(nthreads); auto filename = ic.options().get("grp-file"); - const auto grp = o2::parameters::GRPObject::loadFrom(filename.c_str()); + const auto grp = o2::parameters::GRPObject::loadFrom(filename); if (grp) { mGRP.reset(grp); o2::base::Propagator::initFieldFromGRP(grp); diff --git a/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx b/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx index b1d72528ee4a2..6adbd8853b061 100644 --- a/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx +++ b/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx @@ -54,7 +54,7 @@ void TrackerDPL::init(InitContext& ic) mTimer.Stop(); mTimer.Reset(); auto filename = ic.options().get("grp-file"); - const auto grp = parameters::GRPObject::loadFrom(filename.c_str()); + const auto grp = parameters::GRPObject::loadFrom(filename); if (grp) { mGRP.reset(grp); base::Propagator::initFieldFromGRP(grp); diff --git a/Detectors/ITSMFT/ITS/workflow/src/its-cluster-reader-workflow.cxx b/Detectors/ITSMFT/ITS/workflow/src/its-cluster-reader-workflow.cxx index 4722ef0f2cb33..3d921144a4bc2 100644 --- a/Detectors/ITSMFT/ITS/workflow/src/its-cluster-reader-workflow.cxx +++ b/Detectors/ITSMFT/ITS/workflow/src/its-cluster-reader-workflow.cxx @@ -9,6 +9,7 @@ // or submit itself to any jurisdiction. #include "Framework/ConfigParamSpec.h" +#include "CommonUtils/ConfigurableParam.h" using namespace o2::framework; @@ -26,6 +27,12 @@ void customize(std::vector& workflowOptions) o2::framework::VariantType::Bool, false, {"do not propagate pixel patterns"}}); + workflowOptions.push_back( + ConfigParamSpec{ + "configKeyValues", + VariantType::String, + "", + {"Semicolon separated key=value strings"}}); } #include "Framework/runDataProcessing.h" @@ -34,6 +41,7 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(ConfigContext const& cc) { WorkflowSpec specs; + o2::conf::ConfigurableParam::updateFromString(cc.options().get("configKeyValues")); auto withMC = cc.options().get("with-mc"); auto withPatterns = !cc.options().get("without-patterns"); diff --git a/Detectors/ITSMFT/common/workflow/src/STFDecoderSpec.cxx b/Detectors/ITSMFT/common/workflow/src/STFDecoderSpec.cxx index 9687edff9a857..3aa7b0c43098c 100644 --- a/Detectors/ITSMFT/common/workflow/src/STFDecoderSpec.cxx +++ b/Detectors/ITSMFT/common/workflow/src/STFDecoderSpec.cxx @@ -74,7 +74,7 @@ void STFDecoder::init(InitContext& ic) if (mDoClusters) { mClusterer = std::make_unique(); mClusterer->setNChips(Mapping::getNChips()); - const auto grp = o2::parameters::GRPObject::loadFrom(o2::base::NameConf::getGRPFileName()); + const auto grp = o2::parameters::GRPObject::loadFrom(); if (grp) { mClusterer->setContinuousReadOut(grp->isDetContinuousReadOut(detID)); } else { diff --git a/Detectors/MUON/Common/src/dcs-processor-workflow.cxx b/Detectors/MUON/Common/src/dcs-processor-workflow.cxx index c8e388ab1da7a..0af2b094d5aab 100644 --- a/Detectors/MUON/Common/src/dcs-processor-workflow.cxx +++ b/Detectors/MUON/Common/src/dcs-processor-workflow.cxx @@ -24,6 +24,7 @@ #include #include #include +#include "CommonUtils/ConfigurableParam.h" #if defined(MUON_SUBSYSTEM_MCH) #include "MCHConditions/DCSNamer.h" #endif diff --git a/Detectors/MUON/MCH/Calibration/src/pedestal-calib-workflow.cxx b/Detectors/MUON/MCH/Calibration/src/pedestal-calib-workflow.cxx index 0b4139799ecbb..97fd1a968e51c 100644 --- a/Detectors/MUON/MCH/Calibration/src/pedestal-calib-workflow.cxx +++ b/Detectors/MUON/MCH/Calibration/src/pedestal-calib-workflow.cxx @@ -12,6 +12,7 @@ #include "Framework/DataProcessorSpec.h" #include "Framework/ConfigParamSpec.h" #include "Framework/CompletionPolicyHelpers.h" +#include "CommonUtils/ConfigurableParam.h" using namespace o2::framework; @@ -27,6 +28,7 @@ void customize(std::vector& workflowOptions) { // option allowing to set parameters workflowOptions.push_back(ConfigParamSpec{"input-spec", VariantType::String, "digits:MCH/PDIGITS", {"selection string input specs"}}); + workflowOptions.push_back(ConfigParamSpec{"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}); } // ------------------------------------------------------------------ @@ -35,6 +37,7 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { + o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); const std::string inputSpec = configcontext.options().get("input-spec"); WorkflowSpec specs; specs.emplace_back(getMCHPedestalCalibSpec(inputSpec)); diff --git a/Detectors/MUON/MCH/Calibration/src/pedestal-decoding-workflow.cxx b/Detectors/MUON/MCH/Calibration/src/pedestal-decoding-workflow.cxx index b9b43c029141f..b76acf627dd47 100644 --- a/Detectors/MUON/MCH/Calibration/src/pedestal-decoding-workflow.cxx +++ b/Detectors/MUON/MCH/Calibration/src/pedestal-decoding-workflow.cxx @@ -48,6 +48,8 @@ #include "MCHBase/DecoderError.h" #include "MCHCalibration/PedestalDigit.h" +#include "CommonUtils/ConfigurableParam.h" + static const size_t SOLAR_ID_MAX = 100 * 8; namespace o2 @@ -374,6 +376,7 @@ void customize(std::vector& policies) void customize(std::vector& workflowOptions) { workflowOptions.push_back(ConfigParamSpec{"input-spec", VariantType::String, "TF:MCH/RAWDATA", {"selection string for the input data"}}); + workflowOptions.push_back(ConfigParamSpec{"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}); } #include "Framework/runDataProcessing.h" @@ -401,6 +404,7 @@ o2::framework::DataProcessorSpec getMCHPedestalDecodingSpec(std::string inputSpe WorkflowSpec defineDataProcessing(const ConfigContext& config) { auto inputSpec = config.options().get("input-spec"); + o2::conf::ConfigurableParam::updateFromString(config.options().get("configKeyValues")); WorkflowSpec specs; diff --git a/Detectors/MUON/MCH/Workflow/src/tracks-to-tracks-at-vertex-workflow.cxx b/Detectors/MUON/MCH/Workflow/src/tracks-to-tracks-at-vertex-workflow.cxx index 4f5d55ca857a0..58f140d1711c0 100644 --- a/Detectors/MUON/MCH/Workflow/src/tracks-to-tracks-at-vertex-workflow.cxx +++ b/Detectors/MUON/MCH/Workflow/src/tracks-to-tracks-at-vertex-workflow.cxx @@ -14,12 +14,23 @@ /// \author Philippe Pillot, Subatech #include "Framework/runDataProcessing.h" - +#include "CommonUtils/ConfigurableParam.h" #include "TrackAtVertexSpec.h" using namespace o2::framework; -WorkflowSpec defineDataProcessing(const ConfigContext&) +// we need to add workflow options before including Framework/runDataProcessing +void customize(std::vector& workflowOptions) +{ + // option allowing to set parameters + std::vector options{ + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}}; + + std::swap(workflowOptions, options); +} + +WorkflowSpec defineDataProcessing(const ConfigContext& configcontext) { + o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); return WorkflowSpec{o2::mch::getTrackAtVertexSpec()}; } diff --git a/Detectors/MUON/MID/Workflow/src/raw-to-digits-workflow.cxx b/Detectors/MUON/MID/Workflow/src/raw-to-digits-workflow.cxx index 9f42c3dc6623d..ae92840e90d44 100644 --- a/Detectors/MUON/MID/Workflow/src/raw-to-digits-workflow.cxx +++ b/Detectors/MUON/MID/Workflow/src/raw-to-digits-workflow.cxx @@ -19,6 +19,7 @@ #include "Framework/ConfigParamSpec.h" #include "MIDWorkflow/RawDecoderSpec.h" #include "MIDWorkflow/RawAggregatorSpec.h" +#include "CommonUtils/ConfigurableParam.h" using namespace o2::framework; @@ -30,7 +31,8 @@ void customize(std::vector& workflowOptions) {"feeId-config-file", VariantType::String, "", {"Filename with crate FEE ID correspondence"}}, {"crate-masks-file", VariantType::String, "", {"Filename with crate masks"}}, {"electronics-delay-file", VariantType::String, "", {"Filename with electronics delay"}}, - {"decode-only", o2::framework::VariantType::Bool, false, {"Output decoded boards instead of digits"}}}; + {"decode-only", o2::framework::VariantType::Bool, false, {"Output decoded boards instead of digits"}}, + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}}; workflowOptions.insert(workflowOptions.end(), options.begin(), options.end()); } @@ -38,6 +40,7 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { + o2::conf::ConfigurableParam::updateFromString(cfgc.options().get("configKeyValues")); auto feeIdConfigFilename = cfgc.options().get("feeId-config-file"); o2::mid::FEEIdConfig feeIdConfig; if (!feeIdConfigFilename.empty()) { diff --git a/Detectors/MUON/MID/Workflow/src/reco-workflow.cxx b/Detectors/MUON/MID/Workflow/src/reco-workflow.cxx index bf4a6167ae181..d9d4b5d8b9cfe 100644 --- a/Detectors/MUON/MID/Workflow/src/reco-workflow.cxx +++ b/Detectors/MUON/MID/Workflow/src/reco-workflow.cxx @@ -27,6 +27,7 @@ #include "MIDWorkflow/ClusterizerSpec.h" #include "MIDWorkflow/TrackerMCSpec.h" #include "MIDWorkflow/TrackerSpec.h" +#include "CommonUtils/ConfigurableParam.h" using namespace o2::framework; @@ -37,7 +38,9 @@ void customize(std::vector& workflowOptions) options{ {"disable-mc", VariantType::Bool, false, {"Do not propagate MC labels"}}, {"disable-tracking", VariantType::Bool, false, {"Only run clustering"}}, - {"disable-root-output", VariantType::Bool, false, {"Do not write output to file"}}}; + {"disable-root-output", VariantType::Bool, false, {"Do not write output to file"}}, + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}}; + workflowOptions.insert(workflowOptions.end(), options.begin(), options.end()); } @@ -48,6 +51,7 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) bool disableMC = cfgc.options().get("disable-mc"); bool disableTracking = cfgc.options().get("disable-tracking"); bool disableFile = cfgc.options().get("disable-root-output"); + o2::conf::ConfigurableParam::updateFromString(cfgc.options().get("configKeyValues")); WorkflowSpec specs; specs.emplace_back(disableMC ? o2::mid::getClusterizerSpec() : o2::mid::getClusterizerMCSpec()); diff --git a/Detectors/PHOS/calib/PHOSCalibWorkflow/src/phos-calib-workflow.cxx b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/phos-calib-workflow.cxx index b25b6254eaac4..3e5b6a847362c 100644 --- a/Detectors/PHOS/calib/PHOSCalibWorkflow/src/phos-calib-workflow.cxx +++ b/Detectors/PHOS/calib/PHOSCalibWorkflow/src/phos-calib-workflow.cxx @@ -14,6 +14,7 @@ #include "PHOSCalibWorkflow/PHOSTurnonCalibDevice.h" #include "PHOSCalibWorkflow/PHOSRunbyrunCalibDevice.h" #include "Framework/DataProcessorSpec.h" +#include "CommonUtils/ConfigurableParam.h" using namespace o2::framework; @@ -33,6 +34,8 @@ void customize(std::vector& workflowOptions) workflowOptions.push_back(ConfigParamSpec{"forceupdate", o2::framework::VariantType::Bool, false, {"update ccdb even difference to previous object large"}}); workflowOptions.push_back(ConfigParamSpec{"ccdbpath", o2::framework::VariantType::String, "http://ccdb-test.cern.ch:8080", {"CCDB address to get current objects"}}); workflowOptions.push_back(ConfigParamSpec{"digitspath", o2::framework::VariantType::String, "./CalibDigits.root", {"path and name of file to store calib. digits"}}); + + workflowOptions.push_back(ConfigParamSpec{"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}); } // ------------------------------------------------------------------ @@ -42,6 +45,7 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { WorkflowSpec specs; + o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); auto doPedestals = configcontext.options().get("pedestals"); auto doHgLgRatio = configcontext.options().get("hglgratio"); auto doTurnOn = configcontext.options().get("turnon"); diff --git a/Detectors/TOF/compression/CMakeLists.txt b/Detectors/TOF/compression/CMakeLists.txt index adef2471c81e4..58070e8bf5270 100644 --- a/Detectors/TOF/compression/CMakeLists.txt +++ b/Detectors/TOF/compression/CMakeLists.txt @@ -19,6 +19,7 @@ o2_add_executable(compressor COMPONENT_NAME tof SOURCES src/tof-compressor.cxx PUBLIC_LINK_LIBRARIES O2::TOFCompression + TARGETVARNAME tofcompressor ) o2_add_executable(compressed-inspector @@ -33,4 +34,8 @@ o2_add_executable(compressed-analysis PUBLIC_LINK_LIBRARIES O2::TOFWorkflowUtils ) +if(NOT APPLE) + set_property(TARGET ${tofcompressor} PROPERTY LINK_WHAT_YOU_USE ON) + +endif() diff --git a/Detectors/TOF/compression/src/tof-compressor.cxx b/Detectors/TOF/compression/src/tof-compressor.cxx index 8483702c5843c..058637e340485 100644 --- a/Detectors/TOF/compression/src/tof-compressor.cxx +++ b/Detectors/TOF/compression/src/tof-compressor.cxx @@ -19,6 +19,8 @@ #include "Framework/ConcreteDataMatcher.h" #include "Framework/Logger.h" #include "DetectorsRaw/RDHUtils.h" +#include "CommonUtils/ConfigurableParam.h" +#include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; @@ -35,6 +37,7 @@ void customize(std::vector& workflowOptions) workflowOptions.push_back(outputDesc); workflowOptions.push_back(rdhVersion); workflowOptions.push_back(verbose); + workflowOptions.push_back(ConfigParamSpec{"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}); } #include "Framework/runDataProcessing.h" // the main driver @@ -42,7 +45,7 @@ void customize(std::vector& workflowOptions) /// This function hooks up the the workflow specifications into the DPL driver. WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { - + o2::conf::ConfigurableParam::updateFromString(cfgc.options().get("configKeyValues")); auto config = cfgc.options().get("tof-compressor-config"); // auto outputDesc = cfgc.options().get("output-desc"); auto rdhVersion = cfgc.options().get("tof-compressor-rdh-version"); diff --git a/Detectors/TPC/qc/src/Tracking.cxx b/Detectors/TPC/qc/src/Tracking.cxx index 64c06ddff52f7..f3b07eb89cb8f 100644 --- a/Detectors/TPC/qc/src/Tracking.cxx +++ b/Detectors/TPC/qc/src/Tracking.cxx @@ -46,7 +46,7 @@ void Tracking::initialize(outputModes outputMode, bool postprocessOnly) { mOutputMode = outputMode; mQAConfig = std::make_unique(); - const auto grp = o2::parameters::GRPObject::loadFrom(o2::base::NameConf::getGRPFileName()); + const auto grp = o2::parameters::GRPObject::loadFrom(); if (grp) { mQAConfig->configGRP.solenoidBz = 5.00668f * grp->getL3Current() / 30000.; mQAConfig->configGRP.continuousMaxTimeBin = grp->isDetContinuousReadOut(o2::detectors::DetID::TPC) ? -1 : 0; diff --git a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx index dcdf90b3d48d1..a5230ccdfb288 100644 --- a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx @@ -55,7 +55,7 @@ void TRDGlobalTracking::init(InitContext& ic) //-------- init geometry and field --------// o2::base::GeometryManager::loadGeometry(); - o2::base::Propagator::initFieldFromGRP(o2::base::NameConf::getGRPFileName()); + o2::base::Propagator::initFieldFromGRP(); auto geo = Geometry::instance(); geo->createPadPlaneArray(); geo->createClusterMatrixArray(); diff --git a/Detectors/TRD/workflow/src/TRDTrackletTransformerWorkflow.cxx b/Detectors/TRD/workflow/src/TRDTrackletTransformerWorkflow.cxx index b89a94f7f5e2a..5b0b3cdde6ab1 100644 --- a/Detectors/TRD/workflow/src/TRDTrackletTransformerWorkflow.cxx +++ b/Detectors/TRD/workflow/src/TRDTrackletTransformerWorkflow.cxx @@ -23,6 +23,8 @@ void customize(std::vector& workflowOptions) "root-in", VariantType::Int, 1, {"enable (1) or disable (0) input from ROOT file"}}); workflowOptions.push_back(ConfigParamSpec{ "root-out", VariantType::Int, 1, {"enable (1) or disable (0) output to ROOT file"}}); + workflowOptions.push_back( + ConfigParamSpec{"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings"}}); } #include "Framework/runDataProcessing.h" @@ -31,6 +33,7 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { int rootIn = configcontext.options().get("root-in"); int rootOut = configcontext.options().get("root-out"); + o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); WorkflowSpec spec; diff --git a/Detectors/Vertexing/src/VertexTrackMatcher.cxx b/Detectors/Vertexing/src/VertexTrackMatcher.cxx index 26ed328be7641..bfaae5a93b967 100644 --- a/Detectors/Vertexing/src/VertexTrackMatcher.cxx +++ b/Detectors/Vertexing/src/VertexTrackMatcher.cxx @@ -42,7 +42,7 @@ void VertexTrackMatcher::updateTPCTimeDependentParams() mMaxTPCDriftTimeMUS = detParam.TPClength / gasParam.DriftV; } if (mITSROFrameLengthMUS == 0) { - std::unique_ptr grp{o2::parameters::GRPObject::loadFrom(o2::base::NameConf::getGRPFileName())}; + std::unique_ptr grp{o2::parameters::GRPObject::loadFrom()}; const auto& alpParams = o2::itsmft::DPLAlpideParam::Instance(); mITSROFrameLengthMUS = grp->isDetContinuousReadOut(o2::detectors::DetID::ITS) ? alpParams.roFrameLengthInBC * o2::constants::lhc::LHCBunchSpacingMUS : alpParams.roFrameLengthTrig * 1.e-3; } diff --git a/Detectors/ZDC/raw/src/raw-parser.cxx b/Detectors/ZDC/raw/src/raw-parser.cxx index 3af0d877544bb..05350ba749dda 100644 --- a/Detectors/ZDC/raw/src/raw-parser.cxx +++ b/Detectors/ZDC/raw/src/raw-parser.cxx @@ -20,6 +20,7 @@ #include "DataFormatsZDC/RawEventData.h" #include "ZDCSimulation/Digits2Raw.h" #include "ZDCRaw/DumpRaw.h" +#include "CommonUtils/ConfigurableParam.h" #include #include @@ -28,9 +29,14 @@ using namespace o2::framework; // we need to add workflow options before including Framework/runDataProcessing void customize(std::vector& workflowOptions) { + workflowOptions.push_back( + ConfigParamSpec{"input-spec", VariantType::String, "A:ZDC/RAWDATA", {"selection string input specs"}}); workflowOptions.push_back( ConfigParamSpec{ - "input-spec", VariantType::String, "A:ZDC/RAWDATA", {"selection string input specs"}}); + "configKeyValues", + VariantType::String, + "", + {"Semicolon separated key=value strings"}}); } #include "Framework/runDataProcessing.h" @@ -38,6 +44,7 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(ConfigContext const& config) { WorkflowSpec workflow; + o2::conf::ConfigurableParam::updateFromString(config.options().get("configKeyValues")); workflow.emplace_back(DataProcessorSpec{ "zdc-raw-parser", select(config.options().get("input-spec").c_str()), diff --git a/GPU/GPUTracking/TRDTracking/macros/run_trd_tracker.C b/GPU/GPUTracking/TRDTracking/macros/run_trd_tracker.C index 4fb531dbba1ba..c6dcf50f8eb6b 100644 --- a/GPU/GPUTracking/TRDTracking/macros/run_trd_tracker.C +++ b/GPU/GPUTracking/TRDTracking/macros/run_trd_tracker.C @@ -48,7 +48,7 @@ void run_trd_tracker(std::string path = "./", //-------- init geometry and field --------// o2::base::GeometryManager::loadGeometry(); - o2::base::Propagator::initFieldFromGRP(o2::base::NameConf::getGRPFileName()); + o2::base::Propagator::initFieldFromGRP(); auto geo = o2::trd::Geometry::instance(); geo->createPadPlaneArray(); diff --git a/GPU/Workflow/src/GPUWorkflowSpec.cxx b/GPU/Workflow/src/GPUWorkflowSpec.cxx index be305de7c6f28..6968ea170c7df 100644 --- a/GPU/Workflow/src/GPUWorkflowSpec.cxx +++ b/GPU/Workflow/src/GPUWorkflowSpec.cxx @@ -128,9 +128,9 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli tracker = std::make_unique(); // Create configuration object and fill settings - const auto grp = o2::parameters::GRPObject::loadFrom(o2::base::NameConf::getGRPFileName()); + const auto grp = o2::parameters::GRPObject::loadFrom(); o2::base::GeometryManager::loadGeometry(); - o2::base::Propagator::initFieldFromGRP(o2::base::NameConf::getGRPFileName()); + o2::base::Propagator::initFieldFromGRP(); if (!grp) { throw std::runtime_error("Failed to initialize run parameters from GRP"); } diff --git a/GPU/Workflow/src/O2GPUDPLDisplay.cxx b/GPU/Workflow/src/O2GPUDPLDisplay.cxx index b6e12b97fa847..e0135d977e5f9 100644 --- a/GPU/Workflow/src/O2GPUDPLDisplay.cxx +++ b/GPU/Workflow/src/O2GPUDPLDisplay.cxx @@ -47,9 +47,9 @@ void customize(std::vector& workflowOptions) void O2GPUDPLDisplaySpec::init(InitContext& ic) { - const auto grp = o2::parameters::GRPObject::loadFrom(o2::base::NameConf::getGRPFileName()); + const auto grp = o2::parameters::GRPObject::loadFrom(); o2::base::GeometryManager::loadGeometry(); - o2::base::Propagator::initFieldFromGRP(o2::base::NameConf::getGRPFileName()); + o2::base::Propagator::initFieldFromGRP(); mConfig.reset(new GPUO2InterfaceConfiguration); mConfig->configGRP.solenoidBz = 5.00668f * grp->getL3Current() / 30000.; mConfig->configGRP.continuousMaxTimeBin = grp->isDetContinuousReadOut(o2::detectors::DetID::TPC) ? -1 : 0; // Number of timebins in timeframe if continuous, 0 otherwise diff --git a/Steer/DigitizerWorkflow/src/SimpleDigitizerWorkflow.cxx b/Steer/DigitizerWorkflow/src/SimpleDigitizerWorkflow.cxx index ea1e554b73287..f4f1ed67a1538 100644 --- a/Steer/DigitizerWorkflow/src/SimpleDigitizerWorkflow.cxx +++ b/Steer/DigitizerWorkflow/src/SimpleDigitizerWorkflow.cxx @@ -371,16 +371,15 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) // which sim productions to overlay and digitize auto simPrefixes = splitString(configcontext.options().get("sims"), ','); - // First, read the GRP to detect which components need instantiations - auto grpfile = o2::base::NameConf::getGRPFileName(simPrefixes[0]); std::shared_ptr grp(nullptr); if (!helpasked) { - grp = readGRP(grpfile.c_str()); + grp = readGRP(simPrefixes[0]); if (!grp) { return WorkflowSpec{}; } } + auto grpfile = o2::base::NameConf::getGRPFileName(simPrefixes[0]); // update the digitization configuration with the right geometry file // we take the geometry from the first simPrefix (could actually check if they are diff --git a/macro/analyzeHits.C b/macro/analyzeHits.C index c868ffcd1033e..7983e6b1188b6 100644 --- a/macro/analyzeHits.C +++ b/macro/analyzeHits.C @@ -377,7 +377,7 @@ void analyzeHits(const char* filebase = "o2sim", const char* prefix = "") gPrefix = prefix; // READ GRP AND ITERATE OVER DETECTED PARTS - auto grp = o2::parameters::GRPObject::loadFrom(o2::base::NameConf::getGRPFileName(filebase).c_str()); + auto grp = o2::parameters::GRPObject::loadFrom(filebase); // should correspond to the same number as defined in DetID analyzeITS(getHitTree(grp, filebase, o2::detectors::DetID::ITS)); diff --git a/macro/initSimGeomAndField.C b/macro/initSimGeomAndField.C index 1e6ecf8095e4f..7fb594110e282 100644 --- a/macro/initSimGeomAndField.C +++ b/macro/initSimGeomAndField.C @@ -8,8 +8,6 @@ #include "DetectorsBase/GeometryManager.h" #endif -int initFieldFromGRP(const o2::parameters::GRPObject* grp); -int initFieldFromGRP(const std::string grpFileName = "o2sim_grp.root", std::string grpName = "GRP"); int initSimGeom(std::string geom = ""); int initSimGeomAndField(std::string geom = "", std::string grpFileName = "o2sim_grp.root", std::string grpName = "GRP") @@ -19,7 +17,7 @@ int initSimGeomAndField(std::string geom = "", std::string grpFileName = "o2sim_ if (res) { return res; } - res = initFieldFromGRP(grpFileName, grpName); + res = o2::base::Propagator::initFieldFromGRP(grpFileName, grpName); return res; } @@ -29,50 +27,3 @@ int initSimGeom(std::string geom) o2::base::GeometryManager::loadGeometry(geom); return 0; } - -//____________________________________________________________ -int initFieldFromGRP(const std::string grpFileName, std::string grpName) -{ - /// load grp and init magnetic field - std::cout << "Loading field from GRP of " << grpFileName << std::endl; - TFile flGRP(grpFileName.data()); - if (flGRP.IsZombie()) { - std::cout << "Failed to open " << grpFileName << std::endl; - return -10; - } - auto grp = - static_cast(flGRP.GetObjectChecked(grpName.data(), o2::parameters::GRPObject::Class())); - if (!grp) { - std::cout << "Did not find GRP object named " << grpName << std::endl; - return -12; - } - grp->print(); - - return initFieldFromGRP(grp); -} - -//____________________________________________________________ -int initFieldFromGRP(const o2::parameters::GRPObject* grp) -{ - /// init mag field from GRP data and attach it to TGeoGlobalMagField - - if (TGeoGlobalMagField::Instance()->IsLocked()) { - if (TGeoGlobalMagField::Instance()->GetField()->TestBit(o2::field::MagneticField::kOverrideGRP)) { - std::cout << "ExpertMode!!! GRP information will be ignored" << std::endl; - std::cout << "ExpertMode!!! Running with the externally locked B field" << std::endl; - return 0; - } else { - std::cout << "Destroying existing B field instance" << std::endl; - delete TGeoGlobalMagField::Instance(); - } - } - auto fld = o2::field::MagneticField::createFieldMap(grp->getL3Current(), grp->getDipoleCurrent(), o2::field::MagneticField::kConvLHC, grp->getFieldUniformity()); - TGeoGlobalMagField::Instance()->SetField(fld); - TGeoGlobalMagField::Instance()->Lock(); - std::cout << "Running with the B field constructed out of GRP" << std::endl; - std::cout << "Access field via TGeoGlobalMagField::Instance()->Field(xyz,bxyz) or via" << std::endl; - std::cout << "auto o2field = static_cast( TGeoGlobalMagField::Instance()->GetField() )" - << std::endl; - - return 0; -} diff --git a/macro/migrateSimFiles.C b/macro/migrateSimFiles.C index 243fc0965d88c..79015d8df9b15 100644 --- a/macro/migrateSimFiles.C +++ b/macro/migrateSimFiles.C @@ -65,7 +65,7 @@ void migrateSimFiles(const char* filebase = "o2sim") { // READ GRP AND ITERATE OVER DETECTED PARTS - auto grp = o2::parameters::GRPObject::loadFrom(o2::base::NameConf::getGRPFileName(filebase).c_str()); + auto grp = o2::parameters::GRPObject::loadFrom(filebase); if (!grp) { std::cerr << "No GRP found. Exiting\n"; } diff --git a/prodtests/full-system-test/dpl-workflow.sh b/prodtests/full-system-test/dpl-workflow.sh index 2e02592e3f053..c5e473a55ba38 100755 --- a/prodtests/full-system-test/dpl-workflow.sh +++ b/prodtests/full-system-test/dpl-workflow.sh @@ -1,5 +1,9 @@ #!/bin/bash +# In order to use o2sim_grp.root, o2sim_geometry.root or matbud.root from arbitrary directory one can provide to the workflow +# --configKeyValues "NameConf.mDirGRP=;NameConf.mDirGeom=;NameConf.mDirMatLUT=;" +# All workflows currently running in the FST parce the configKeyValues option, so the NameConf.mDirXXX keys can be added via global env.var. + MYDIR="$(dirname $(readlink -f $0))" source $MYDIR/setenv.sh From 451fb66cd634329fff26ee4e0620d6a3c422620d Mon Sep 17 00:00:00 2001 From: shahoian Date: Fri, 30 Apr 2021 09:35:35 +0200 Subject: [PATCH 330/770] Temporarily restore old method to not crash the QC --- .../Common/include/DetectorsCommonDataFormats/NameConf.h | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h index c49679b16bd07..7ff532252915f 100644 --- a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h +++ b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/NameConf.h @@ -69,6 +69,12 @@ class NameConf : public o2::conf::ConfigurableParamHelper // Filename to for decoding dictionaries static std::string getAlpideClusterDictionaryFileName(DId det, const std::string_view prefix = "", const std::string_view ext = ""); + // Temporary alias to not crash the QC: Filename to for decoding dictionaries + static std::string getDictionaryFileName(DId det, const std::string_view prefix = "", const std::string_view ext = "") + { + return getAlpideClusterDictionaryFileName(det, prefix, ext); + } + // Filename to store material LUT file static std::string getMatLUTFileName(const std::string_view prefix = ""); From 93270c76ae001abdb856724a435b7a9a2e10c110 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 29 Apr 2021 15:21:22 +0200 Subject: [PATCH 331/770] Revert "GPU: Workaround for OpenCL bug, cannot read from __constant constexpr variables using constexpr function" This reverts commit b3777a089e21c03aa85f75085fd4ee094a3055e1. --- .../Common/include/DetectorsCommonDataFormats/DetID.h | 2 +- .../include/ReconstructionDataFormats/GlobalTrackID.h | 4 ++-- GPU/Utils/GPUCommonBitSet.h | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h index 63deb8e334a58..9f107b9df55f7 100644 --- a/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h +++ b/DataFormats/Detectors/Common/include/DetectorsCommonDataFormats/DetID.h @@ -187,7 +187,7 @@ GPUconstexpr() DetID::mask_t sMasks[DetID::nDetectors] = ///< detectot masks }; } // namespace detid_internal -GPUdi() constexpr DetID::mask_t DetID::getMask(ID id) { return detid_internal::sMasks[id].v; } +GPUdi() constexpr DetID::mask_t DetID::getMask(ID id) { return detid_internal::sMasks[id]; } } // namespace detectors } // namespace o2 diff --git a/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h b/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h index efe7477c9a491..57c1c797e31d5 100644 --- a/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h +++ b/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h @@ -139,8 +139,8 @@ GPUconstexpr() GlobalTrackID::mask_t sMasks[GlobalTrackID::NSources] = ///< dete GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::ITSTPCTOF)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::TPCTRDTOF)), GlobalTrackID::mask_t(math_utils::bit2Mask(GlobalTrackID::ITSTPCTRDTOF))}; } // namespace globaltrackid_internal -GPUdi() constexpr GlobalTrackID::DetID::mask_t GlobalTrackID::getSourceDetectorsMask(int i) { return globaltrackid_internal::SourceDetectorsMasks[i].v; } -GPUdi() constexpr GlobalTrackID::mask_t GlobalTrackID::getSourceMask(int s) { return globaltrackid_internal::sMasks[s].v; } +GPUdi() constexpr GlobalTrackID::DetID::mask_t GlobalTrackID::getSourceDetectorsMask(int i) { return globaltrackid_internal::SourceDetectorsMasks[i]; } +GPUdi() constexpr GlobalTrackID::mask_t GlobalTrackID::getSourceMask(int s) { return globaltrackid_internal::sMasks[s]; } GPUdi() bool GlobalTrackID::includesDet(DetID id, GlobalTrackID::mask_t srcm) { diff --git a/GPU/Utils/GPUCommonBitSet.h b/GPU/Utils/GPUCommonBitSet.h index 999ccfe88b079..44369e0c78372 100644 --- a/GPU/Utils/GPUCommonBitSet.h +++ b/GPU/Utils/GPUCommonBitSet.h @@ -79,7 +79,7 @@ class bitset std::string to_string() const; #endif - //private: // Workaround for OpenCL + private: unsigned int v = 0; ClassDefNV(bitset, 1); From 275196a936eb8fcc3a0420555cc864855fe58bc4 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 29 Apr 2021 15:27:12 +0200 Subject: [PATCH 332/770] GPU: Better workaround for OpenCL bug report https://bugs.llvm.org/show_bug.cgi?id=50164 --- GPU/Utils/GPUCommonBitSet.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/GPU/Utils/GPUCommonBitSet.h b/GPU/Utils/GPUCommonBitSet.h index 44369e0c78372..f38b7f81f9ef6 100644 --- a/GPU/Utils/GPUCommonBitSet.h +++ b/GPU/Utils/GPUCommonBitSet.h @@ -36,6 +36,9 @@ class bitset public: GPUdDefault() constexpr bitset() = default; GPUdDefault() constexpr bitset(const bitset&) = default; +#ifdef __OPENCL__ + GPUdDefault() constexpr bitset(const __constant bitset&) = default; +#endif // __OPENCL__ GPUd() constexpr bitset(unsigned int vv) : v(vv){}; static constexpr unsigned int full_set = ((1ul << N) - 1ul); From 90106de3f91007f0cfcaa9e2c7ee27cb33a9b51f Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 28 Apr 2021 19:39:02 +0200 Subject: [PATCH 333/770] GPU: Refit with OpenCL should work now --- GPU/GPUTracking/Refit/GPUTrackingRefit.cxx | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx b/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx index b1f05f8bcb54c..cfb4daaefd3dd 100644 --- a/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx +++ b/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx @@ -27,6 +27,7 @@ #include "GPUCommonArray.h" #include "GPUParam.h" #include "GPUTrackParamConvert.h" +#include "GPUCommonTypeTraits.h" using namespace GPUCA_NAMESPACE::gpu; using namespace o2::track; @@ -207,7 +208,6 @@ GPUd() static const float* getPar(const TrackParCov& trk) { return trk.getParams template GPUd() int GPUTrackingRefit::RefitTrack(T& trkX, bool outward, bool resetCov) { -#ifndef __OPENCL__ CADEBUG(int ii; printf("\nRefitting track\n")); typename refitTrackTypes::propagator prop; S trk; @@ -381,9 +381,6 @@ GPUd() int GPUTrackingRefit::RefitTrack(T& trkX, bool outward, bool resetCov) convertTrack(trkX, trk, prop, &TrackParCovChi2); return nFitted; -#else - return 0; // TODO: Fixme, implement std::isSame for opencl -#endif } template GPUd() int GPUTrackingRefit::RefitTrack(GPUTPCGMMergedTrack& trk, bool outward, bool resetCov); From d9b1c6a89b75d0c3659dd371e3e5c32e6be35409 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 28 Apr 2021 21:24:05 +0200 Subject: [PATCH 334/770] GPU: Add more missing data types to OpenCL --- GPU/GPUTracking/Base/opencl-common/GPUReconstructionOCL.cl | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/GPU/GPUTracking/Base/opencl-common/GPUReconstructionOCL.cl b/GPU/GPUTracking/Base/opencl-common/GPUReconstructionOCL.cl index c222162c44ef4..29aff13247e25 100644 --- a/GPU/GPUTracking/Base/opencl-common/GPUReconstructionOCL.cl +++ b/GPU/GPUTracking/Base/opencl-common/GPUReconstructionOCL.cl @@ -62,6 +62,10 @@ #define uint32_t unsigned int #define uint16_t unsigned short #define uint8_t unsigned char +#define int64_t long +#define int32_t int +#define int16_t short +#define int8_t char // Disable assertions since they produce errors in GPU Code #ifdef assert From 2e7b37a9a65af0b3260e91be0ec7086f18f2a071 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 28 Apr 2021 21:24:23 +0200 Subject: [PATCH 335/770] GPU: Avoid false compiler warning --- GPU/GPUTracking/SliceTracker/GPUTPCSliceData.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/GPUTracking/SliceTracker/GPUTPCSliceData.cxx b/GPU/GPUTracking/SliceTracker/GPUTPCSliceData.cxx index 22bb02f75a61f..b06abcd555a69 100644 --- a/GPU/GPUTracking/SliceTracker/GPUTPCSliceData.cxx +++ b/GPU/GPUTracking/SliceTracker/GPUTPCSliceData.cxx @@ -310,7 +310,7 @@ GPUdii() int GPUTPCSliceData::InitFromClusterData(int nBlocks, int nThreads, int GPUbarrier(); const GPUTPCGrid& grid = row.mGrid; const int numberOfBins = grid.N(); - CONSTEXPR int maxBins = sizeof(calink) < 4 ? (1 << (sizeof(calink) * 8)) : 0x7FFFFFFF; // NOLINT: false warning + CONSTEXPR int maxBins = sizeof(calink) < 4 ? (int)(1ul << (sizeof(calink) * 8)) : 0x7FFFFFFF; // NOLINT: false warning if (sizeof(calink) < 4 && numberOfBins >= maxBins) { if (iThread == 0) { mem->errorCodes.raiseError(GPUErrors::ERROR_SLICEDATA_BIN_OVERFLOW, rowIndex, numberOfBins, maxBins); From d286c7cd06b7c8b8fd8b8238249ad9e35fcf69a6 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 28 Apr 2021 21:40:24 +0200 Subject: [PATCH 336/770] GPU TRD: Should not use std::pow to compute square --- GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h index 379c5221cb25d..72b9c3c552434 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h @@ -162,7 +162,8 @@ class trackInterface : public GPUTRDO2BaseTrack mTimeSubMax = trkItsTpc.getTimeMUS().getTimeStampError(); mRefITS = trkItsTpc.getRefITS(); mRefTPC = trkItsTpc.getRefTPC(); - updateCov(std::pow(trkItsTpc.getTimeMUS().getTimeStampError() * vDrift, 2), o2::track::CovLabels::kSigZ2); // account for time uncertainty by increasing sigmaZ2 + float tmp = trkItsTpc.getTimeMUS().getTimeStampError() * vDrift; + updateCov(tmp * tmp, o2::track::CovLabels::kSigZ2); // account for time uncertainty by increasing sigmaZ2 } trackInterface(const o2::tpc::TrackTPC& trkTpc, float tbWidth, float vDrift, unsigned int iTrk) : GPUTRDO2BaseTrack(trkTpc.getParamOut()) { @@ -177,7 +178,8 @@ class trackInterface : public GPUTRDO2BaseTrack } else { // CE-crossing tracks are not shifted along z, but the time uncertainty is taken into account by increasing sigmaZ2 float timeWindow = (mTimeAddMax + mTimeSubMax) * .5f; - updateCov(std::pow(timeWindow * vDrift, 2), o2::track::CovLabels::kSigZ2); + float tmp = timeWindow * vDrift; + updateCov(tmp * tmp, o2::track::CovLabels::kSigZ2); } } void set(float x, float alpha, const float param[5], const float cov[15]) From ca93dffc544ee0641b2ba376b1b46ff01162b5c6 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 28 Apr 2021 22:53:59 +0200 Subject: [PATCH 337/770] GPU: Workaround for OpenCL template deduction issue --- GPU/GPUTracking/Refit/GPUTrackingRefit.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx b/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx index cfb4daaefd3dd..6857bd88e2d23 100644 --- a/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx +++ b/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx @@ -212,7 +212,7 @@ GPUd() int GPUTrackingRefit::RefitTrack(T& trkX, bool outward, bool resetCov) typename refitTrackTypes::propagator prop; S trk; float TrackParCovChi2 = 0.f; - convertTrack(trk, trkX, prop, &TrackParCovChi2); + convertTrack::propagator>(trk, trkX, prop, &TrackParCovChi2); int begin = 0, count; float tOffset; if constexpr (std::is_same_v) { @@ -379,7 +379,7 @@ GPUd() int GPUTrackingRefit::RefitTrack(T& trkX, bool outward, bool resetCov) static_assert("Invalid template"); } - convertTrack(trkX, trk, prop, &TrackParCovChi2); + convertTrack::propagator>(trkX, trk, prop, &TrackParCovChi2); return nFitted; } From d610a0ff5ded8f40e6a6f8d0a6d89bb9b7781025 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 29 Apr 2021 09:50:27 +0200 Subject: [PATCH 338/770] GPU: Add missing include folder to OpenCL test script --- GPU/GPUTracking/Standalone/tools/testCL.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/GPUTracking/Standalone/tools/testCL.sh b/GPU/GPUTracking/Standalone/tools/testCL.sh index 4f9ad94d4844e..a370266e1e5cf 100755 --- a/GPU/GPUTracking/Standalone/tools/testCL.sh +++ b/GPU/GPUTracking/Standalone/tools/testCL.sh @@ -12,7 +12,7 @@ LLVM_SPIRV=llvm-spirv INCLUDES="-I../. -I../DataTypes -I../Definitions -I../Base -I../SliceTracker -I../Common -I../Merger -I../Refit -I../TRDTracking -I../ITS -I../dEdx -I../TPCConvert -I../TPCFastTransformation -I../DataCompression -I../TPCClusterFinder -I../Global -I ../GPUUtils \ -I$HOME/alice/O2/DataFormats/Detectors/TPC/include -I$HOME/alice/O2/Detectors/Base/include -I$HOME/alice/O2/Detectors/Base/src -I$HOME/alice/O2/Common/MathUtils/include -I$HOME/alice/O2/DataFormats/Headers/include \ -I$HOME/alice/O2/Detectors/TRD/base/include -I$HOME/alice/O2/Detectors/TRD/base/src -I$HOME/alice/O2/Detectors/ITSMFT/ITS/tracking/include -I$HOME/alice/O2/Detectors/ITSMFT/ITS/tracking/cuda/include -I$HOME/alice/O2/Common/Constants/include \ - -I$HOME/alice/O2/DataFormats/common/include -I$HOME/alice/O2/DataFormats/Detectors/TRD/include -I$HOME/alice/O2/DataFormats/Reconstruction/include -I$HOME/alice/O2/DataFormats/Reconstruction/src" + -I$HOME/alice/O2/DataFormats/common/include -I$HOME/alice/O2/DataFormats/Detectors/Common/include -I$HOME/alice/O2/DataFormats/Detectors/TRD/include -I$HOME/alice/O2/DataFormats/Reconstruction/include -I$HOME/alice/O2/DataFormats/Reconstruction/src" DEFINES="-DGPUCA_STANDALONE -DGPUCA_GPULIBRARY=OCL -DNDEBUG -D__OPENCLCPP__ -DHAVE_O2HEADERS -DGPUCA_TPC_GEOMETRY_O2" FLAGS="-Xclang -fdenormal-fp-math-f32=ieee -cl-mad-enable -cl-no-signed-zeros -ferror-limit=1000 -Xclang -finclude-default-header -Dcl_clang_storage_class_specifiers" From 636ba49b2b49c7d1c71839e0d9b3b67bc5fdcea0 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 29 Apr 2021 15:12:06 +0200 Subject: [PATCH 339/770] GPU: Make TrackTPCITS compatible to GPU --- .../ReconstructionDataFormats/TrackTPCITS.h | 42 +++++++++---------- .../include/CommonDataFormat/TimeStamp.h | 8 ++-- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackTPCITS.h b/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackTPCITS.h index 021f65081873a..51d0af81e8b73 100644 --- a/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackTPCITS.h +++ b/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackTPCITS.h @@ -30,37 +30,37 @@ class TrackTPCITS : public o2::track::TrackParCov using timeEst = o2::dataformats::TimeStampWithError; public: - TrackTPCITS() = default; - ~TrackTPCITS() = default; - TrackTPCITS(const TrackTPCITS& src) = default; - TrackTPCITS(const o2::track::TrackParCov& src) : o2::track::TrackParCov(src) {} - TrackTPCITS(const o2::track::TrackParCov& srcIn, const o2::track::TrackParCov& srcOut) : o2::track::TrackParCov(srcIn), mParamOut(srcOut) {} + GPUdDefault() TrackTPCITS() = default; + GPUdDefault() ~TrackTPCITS() = default; + GPUdDefault() TrackTPCITS(const TrackTPCITS& src) = default; + GPUd() TrackTPCITS(const o2::track::TrackParCov& src) : o2::track::TrackParCov(src) {} + GPUd() TrackTPCITS(const o2::track::TrackParCov& srcIn, const o2::track::TrackParCov& srcOut) : o2::track::TrackParCov(srcIn), mParamOut(srcOut) {} - GlobalTrackID getRefTPC() const { return mRefTPC; } - GlobalTrackID getRefITS() const { return mRefITS; } - void setRefTPC(GlobalTrackID id) { mRefTPC = id; } - void setRefITS(GlobalTrackID id) { mRefITS = id; } + GPUd() GlobalTrackID getRefTPC() const { return mRefTPC; } + GPUd() GlobalTrackID getRefITS() const { return mRefITS; } + GPUd() void setRefTPC(GlobalTrackID id) { mRefTPC = id; } + GPUd() void setRefITS(GlobalTrackID id) { mRefITS = id; } - const timeEst& getTimeMUS() const { return mTimeMUS; } - timeEst& getTimeMUS() { return mTimeMUS; } - void setTimeMUS(const timeEst& t) { mTimeMUS = t; } - void setTimeMUS(float t, float te) + GPUd() const timeEst& getTimeMUS() const { return mTimeMUS; } + GPUd() timeEst& getTimeMUS() { return mTimeMUS; } + GPUd() void setTimeMUS(const timeEst& t) { mTimeMUS = t; } + GPUd() void setTimeMUS(float t, float te) { mTimeMUS.setTimeStamp(t); mTimeMUS.setTimeStampError(te); } - void setChi2Refit(float v) { mChi2Refit = v; } - float getChi2Refit() const { return mChi2Refit; } + GPUd() void setChi2Refit(float v) { mChi2Refit = v; } + GPUd() float getChi2Refit() const { return mChi2Refit; } - void setChi2Match(float v) { mChi2Match = v; } - float getChi2Match() const { return mChi2Match; } + GPUd() void setChi2Match(float v) { mChi2Match = v; } + GPUd() float getChi2Match() const { return mChi2Match; } - o2::track::TrackParCov& getParamOut() { return mParamOut; } - const o2::track::TrackParCov& getParamOut() const { return mParamOut; } + GPUd() o2::track::TrackParCov& getParamOut() { return mParamOut; } + GPUd() const o2::track::TrackParCov& getParamOut() const { return mParamOut; } - o2::track::TrackLTIntegral& getLTIntegralOut() { return mLTOut; } - const o2::track::TrackLTIntegral& getLTIntegralOut() const { return mLTOut; } + GPUd() o2::track::TrackLTIntegral& getLTIntegralOut() { return mLTOut; } + GPUd() const o2::track::TrackLTIntegral& getLTIntegralOut() const { return mLTOut; } void print() const; diff --git a/DataFormats/common/include/CommonDataFormat/TimeStamp.h b/DataFormats/common/include/CommonDataFormat/TimeStamp.h index c3420d348c62c..3133c6bc5cda3 100644 --- a/DataFormats/common/include/CommonDataFormat/TimeStamp.h +++ b/DataFormats/common/include/CommonDataFormat/TimeStamp.h @@ -40,10 +40,10 @@ template class TimeStampWithError : public TimeStamp { public: - TimeStampWithError() = default; - TimeStampWithError(T t, E te) : TimeStamp(t), mTimeStampError(te) {} - E getTimeStampError() const { return mTimeStampError; } - void setTimeStampError(E te) { mTimeStampError = te; } + GPUdDefault() TimeStampWithError() = default; + GPUd() TimeStampWithError(T t, E te) : TimeStamp(t), mTimeStampError(te) {} + GPUdi() E getTimeStampError() const { return mTimeStampError; } + GPUdi() void setTimeStampError(E te) { mTimeStampError = te; } private: E mTimeStampError = 0; From e318631bd066e2dcf04c7d5d63a106e1cab19bd5 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 29 Apr 2021 15:17:21 +0200 Subject: [PATCH 340/770] TRD: Fix typo --- GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h index 72b9c3c552434..cf274e7a086d9 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h @@ -238,7 +238,7 @@ class propagatorInterface { if (mParam) { std::array pTmp = {p[0], p[1]}; - std::array covTmp = {cov[0], cov[1], cov[3]}; + std::array covTmp = {cov[0], cov[1], cov[2]}; return mParam->update(pTmp, covTmp); } else { return false; @@ -248,7 +248,7 @@ class propagatorInterface { if (mParam) { std::array pTmp = {p[0], p[1]}; - std::array covTmp = {cov[0], cov[1], cov[3]}; + std::array covTmp = {cov[0], cov[1], cov[2]}; return mParam->getPredictedChi2(pTmp, covTmp); } else { return 99999.f; From 582e9045771302a149bd281c267e37489fff73fa Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 29 Apr 2021 15:19:27 +0200 Subject: [PATCH 341/770] GPU: Make TRDTrack version derived from o2 TrackParCov compatible to GPU --- .../TRDTracking/GPUTRDInterfaces.h | 77 ++++++++++--------- .../TRDTracking/GPUTRDO2BaseTrack.h | 5 +- GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx | 4 +- GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx | 34 +++++--- GPU/GPUTracking/TRDTracking/GPUTRDTracker.h | 3 + 5 files changed, 73 insertions(+), 50 deletions(-) diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h index cf274e7a086d9..42f1a2d329b7f 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h @@ -104,7 +104,8 @@ class propagatorInterface : public AliTrackerBase { public: - propagatorInterface(const void* = nullptr) : AliTrackerBase(), mParam(nullptr){}; + typedef void propagatorParam; + propagatorInterface(const propagatorParam* = nullptr) : AliTrackerBase(), mParam(nullptr){}; propagatorInterface(const propagatorInterface&) CON_DELETE; propagatorInterface& operator=(const propagatorInterface&) CON_DELETE; @@ -133,7 +134,7 @@ class propagatorInterface : public AliTrackerBase #endif // GPUCA_ALIROOT_LIB -#if (defined(GPUCA_O2_LIB) || defined(GPUCA_O2_INTERFACE)) && !defined(GPUCA_GPUCODE) // Interface for O2, build only with O2 +#if defined(HAVE_O2HEADERS) // Interface for O2, build only with O2 #include "ReconstructionDataFormats/Track.h" #include "ReconstructionDataFormats/TrackTPCITS.h" @@ -141,7 +142,9 @@ class propagatorInterface : public AliTrackerBase #include "ReconstructionDataFormats/GlobalTrackID.h" #include "DetectorsBase/Propagator.h" #include "GPUTRDO2BaseTrack.h" +#ifndef GPUCA_GPUCODE_DEVICE #include +#endif namespace GPUCA_NAMESPACE { @@ -153,9 +156,9 @@ template <> class trackInterface : public GPUTRDO2BaseTrack { public: - trackInterface() = default; + GPUdDefault() trackInterface() = default; trackInterface(const GPUTRDO2BaseTrack& param) = delete; - trackInterface(const o2::dataformats::TrackTPCITS& trkItsTpc, float vDrift) : GPUTRDO2BaseTrack(trkItsTpc.getParamOut()) + GPUd() trackInterface(const o2::dataformats::TrackTPCITS& trkItsTpc, float vDrift) : GPUTRDO2BaseTrack(trkItsTpc.getParamOut()) { mTime = trkItsTpc.getTimeMUS().getTimeStamp(); mTimeAddMax = trkItsTpc.getTimeMUS().getTimeStampError(); @@ -165,7 +168,7 @@ class trackInterface : public GPUTRDO2BaseTrack float tmp = trkItsTpc.getTimeMUS().getTimeStampError() * vDrift; updateCov(tmp * tmp, o2::track::CovLabels::kSigZ2); // account for time uncertainty by increasing sigmaZ2 } - trackInterface(const o2::tpc::TrackTPC& trkTpc, float tbWidth, float vDrift, unsigned int iTrk) : GPUTRDO2BaseTrack(trkTpc.getParamOut()) + GPUd() trackInterface(const o2::tpc::TrackTPC& trkTpc, float tbWidth, float vDrift, unsigned int iTrk) : GPUTRDO2BaseTrack(trkTpc.getParamOut()) { mRefTPC = {iTrk, o2::dataformats::GlobalTrackID::TPC}; mTime = trkTpc.getTime0() * tbWidth; @@ -182,7 +185,7 @@ class trackInterface : public GPUTRDO2BaseTrack updateCov(tmp * tmp, o2::track::CovLabels::kSigZ2); } } - void set(float x, float alpha, const float param[5], const float cov[15]) + GPUd() void set(float x, float alpha, const float* param, const float* cov) { setX(x); setAlpha(alpha); @@ -193,19 +196,19 @@ class trackInterface : public GPUTRDO2BaseTrack setCov(cov[i], i); } } - trackInterface(const GPUTPCGMMergedTrack& trk) { set(trk.OuterParam().X, trk.OuterParam().alpha, trk.OuterParam().P, trk.OuterParam().C); } - trackInterface(const GPUTPCGMTrackParam::GPUTPCOuterParam& param) { set(param.X, param.alpha, param.P, param.C); } - - const float* getPar() const { return getParams(); } - float getTime() const { return mTime; } - void setTime(float t) { mTime = t; } - float getTimeMax() const { return mTime + mTimeAddMax; } - float getTimeMin() const { return mTime - mTimeSubMax; } - short getSide() const { return mSide; } - float getZShift() const { return mZShift; } - void setZShift(float z) { mZShift = z; } + GPUdi() trackInterface(const GPUTPCGMMergedTrack& trk) { set(trk.OuterParam().X, trk.OuterParam().alpha, trk.OuterParam().P, trk.OuterParam().C); } + GPUdi() trackInterface(const GPUTPCGMTrackParam::GPUTPCOuterParam& param) { set(param.X, param.alpha, param.P, param.C); } - bool CheckNumericalQuality() const { return true; } + GPUdi() const float* getPar() const { return getParams(); } + GPUdi() float getTime() const { return mTime; } + GPUdi() void setTime(float t) { mTime = t; } + GPUdi() float getTimeMax() const { return mTime + mTimeAddMax; } + GPUdi() float getTimeMin() const { return mTime - mTimeSubMax; } + GPUdi() short getSide() const { return mSide; } + GPUdi() float getZShift() const { return mZShift; } + GPUdi() void setZShift(float z) { mZShift = z; } + + GPUdi() bool CheckNumericalQuality() const { return true; } typedef GPUTRDO2BaseTrack baseClass; @@ -223,47 +226,48 @@ template <> class propagatorInterface { public: - propagatorInterface(const void* = nullptr){}; - propagatorInterface(const propagatorInterface&) = delete; - propagatorInterface& operator=(const propagatorInterface&) = delete; + typedef o2::base::Propagator propagatorParam; + GPUd() propagatorInterface(const propagatorParam* prop) : mProp(prop){}; + GPUd() propagatorInterface(const propagatorInterface&) = delete; + GPUd() propagatorInterface& operator=(const propagatorInterface&) = delete; - bool propagateToX(float x, float maxSnp, float maxStep) { return mProp->PropagateToXBxByBz(*mParam, x, maxSnp, maxStep); } - int getPropagatedYZ(float x, float& projY, float& projZ) { return static_cast(mParam->getYZAt(x, mProp->getNominalBz(), projY, projZ)); } + GPUdi() bool propagateToX(float x, float maxSnp, float maxStep) { return mProp->PropagateToXBxByBz(*mParam, x, maxSnp, maxStep); } + GPUdi() int getPropagatedYZ(float x, float& projY, float& projZ) { return static_cast(mParam->getYZAt(x, mProp->getNominalBz(), projY, projZ)); } - void setTrack(trackInterface* trk) { mParam = trk; } - void setFitInProjections(bool flag) {} + GPUdi() void setTrack(trackInterface* trk) { mParam = trk; } + GPUdi() void setFitInProjections(bool flag) {} - float getAlpha() { return (mParam) ? mParam->getAlpha() : 99999.f; } - bool update(const My_Float p[2], const My_Float cov[3]) + GPUdi() float getAlpha() { return (mParam) ? mParam->getAlpha() : 99999.f; } + GPUdi() bool update(const My_Float p[2], const My_Float cov[3]) { if (mParam) { - std::array pTmp = {p[0], p[1]}; - std::array covTmp = {cov[0], cov[1], cov[2]}; + gpustd::array pTmp = {p[0], p[1]}; + gpustd::array covTmp = {cov[0], cov[1], cov[2]}; return mParam->update(pTmp, covTmp); } else { return false; } } - float getPredictedChi2(const My_Float p[2], const My_Float cov[3]) + GPUdi() float getPredictedChi2(const My_Float p[2], const My_Float cov[3]) { if (mParam) { - std::array pTmp = {p[0], p[1]}; - std::array covTmp = {cov[0], cov[1], cov[2]}; + gpustd::array pTmp = {p[0], p[1]}; + gpustd::array covTmp = {cov[0], cov[1], cov[2]}; return mParam->getPredictedChi2(pTmp, covTmp); } else { return 99999.f; } } - bool rotate(float alpha) { return (mParam) ? mParam->rotate(alpha) : false; } + GPUdi() bool rotate(float alpha) { return (mParam) ? mParam->rotate(alpha) : false; } trackInterface* mParam{nullptr}; - o2::base::Propagator* mProp{o2::base::Propagator::Instance()}; + const o2::base::Propagator* mProp; }; } // namespace gpu } // namespace GPUCA_NAMESPACE -#endif // GPUCA_O2_LIB || GPUCA_O2_INTERFACE +#endif // HAVE_O2HEADERS #include "GPUTPCGMPropagator.h" #include "GPUParam.h" @@ -386,7 +390,8 @@ template <> class propagatorInterface : public GPUTPCGMPropagator { public: - GPUd() propagatorInterface(const GPUTPCGMPolynomialField* pField) : GPUTPCGMPropagator(), mTrack(nullptr) + typedef GPUTPCGMPolynomialField propagatorParam; + GPUd() propagatorInterface(const propagatorParam* pField) : GPUTPCGMPropagator(), mTrack(nullptr) { this->SetMaterialTPC(); this->SetPolynomialField(pField); diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDO2BaseTrack.h b/GPU/GPUTracking/TRDTracking/GPUTRDO2BaseTrack.h index 4f9e13d454cde..d1b18f32e8801 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDO2BaseTrack.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDO2BaseTrack.h @@ -14,6 +14,7 @@ #ifndef GPUTRDO2BASETRACK_H #define GPUTRDO2BASETRACK_H +#include "GPUCommonDef.h" #include "ReconstructionDataFormats/Track.h" namespace GPUCA_NAMESPACE @@ -24,8 +25,8 @@ namespace gpu class GPUTRDO2BaseTrack : public o2::track::TrackParCov { public: - GPUTRDO2BaseTrack() = default; - GPUTRDO2BaseTrack(const o2::track::TrackParCov& t) : o2::track::TrackParCov(t) {} + GPUdDefault() GPUTRDO2BaseTrack() = default; + GPUd() GPUTRDO2BaseTrack(const o2::track::TrackParCov& t) : o2::track::TrackParCov(t) {} private: // dummy class to avoid problems, see https://github.com/AliceO2Group/AliceO2/pull/5969#issuecomment-827475822 diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx index a298ee201ff63..7d9f6e589b49c 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx @@ -222,14 +222,12 @@ namespace GPUCA_NAMESPACE { namespace gpu { -#ifndef GPUCA_GPUCODE #ifdef GPUCA_ALIROOT_LIB // Instantiate AliRoot track version template class GPUTRDTrack_t>; #endif -#ifdef GPUCA_O2_LIB // Instantiate O2 track version +#ifdef HAVE_O2HEADERS // Instantiate O2 track version template class GPUTRDTrack_t>; #endif -#endif template class GPUTRDTrack_t>; // Always instatiate GM track version } // namespace gpu } // namespace GPUCA_NAMESPACE diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx index 4180eb8dee8e0..2884266b2c5c0 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx @@ -34,7 +34,7 @@ class GPUTPCGMPolynomialField; #include "GPUReconstruction.h" #ifdef WITH_OPENMP #include -#endif +#endif // WITH_OPENMP #include #include #ifdef GPUCA_ALIROOT_LIB @@ -42,9 +42,9 @@ class GPUTPCGMPolynomialField; #include "AliMCParticle.h" #include "AliMCEvent.h" //static const float piMass = TDatabasePDG::Instance()->GetParticle(211)->Mass(); -#else +#else // GPUCA_ALIROOT_LIB //static const float piMass = 0.139f; -#endif +#endif // !GPUCA_ALIROOT_LIB #include "GPUChainTracking.h" @@ -279,7 +279,7 @@ void GPUTRDTracker_t::DoTracking(GPUChainTracking* chainTracking) for (int iTrk = 0; iTrk < mNTracks; ++iTrk) { if (mTracks[iTrk].GetNtracklets() > 3) { auto trkCopy = mTracks[iTrk]; - PROP prop(&Param().polynomialField); + PROP prop(getPropagatorParam()); prop.setFitInProjections(true); prop.setTrack(&trkCopy); FillImpactAngleHistograms(&prop, &trkCopy); @@ -447,6 +447,24 @@ GPUd() void GPUTRDTracker_t::CheckTrackRefs(const int trackID, boo } #endif //! GPUCA_GPUCODE +template <> +GPUdi() const GPUTRDPropagatorGPU::propagatorParam* GPUTRDTracker_t::getPropagatorParam() +{ + return &Param().polynomialField; +} + +template +GPUdi() const typename PROP::propagatorParam* GPUTRDTracker_t::getPropagatorParam() +{ +#ifdef GPUCA_GPUCODE + return GetConstantMem()->calibObjects.o2Propagator; +#elif defined GPUCA_ALIROOT_LIB + return nullptr; +#else + return o2::base::Propagator::Instance(); +#endif +} + template GPUd() bool GPUTRDTracker_t::CheckTrackTRDCandidate(const TRDTRK& trk) const { @@ -566,7 +584,7 @@ GPUd() void GPUTRDTracker_t::DoTrackingThread(int iTrk, int thread return; } } - PROP prop(&Param().polynomialField); + PROP prop(getPropagatorParam()); mTracks[iTrk].SetChi2(Param().rec.trdPenaltyChi2); auto trkStart = mTracks[iTrk]; for (int iColl = 0; iColl < nCollisionIds; ++iColl) { @@ -1524,11 +1542,9 @@ namespace GPUCA_NAMESPACE { namespace gpu { -#if !defined(GPUCA_STANDALONE) && !defined(GPUCA_GPUCODE) -// instantiate version for non-GPU data types +// instantiate version for AliExternalTrackParam / o2::TrackParCov data types template class GPUTRDTracker_t; -#endif -// always instantiate version for GPU data types +// always instantiate version for GPU Track Model template class GPUTRDTracker_t; } // namespace gpu } // namespace GPUCA_NAMESPACE diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h index 332b5ceb42b86..5a163a5b484ac 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h @@ -175,6 +175,9 @@ class GPUTRDTracker_t : public GPUProcessor GPUd() GPUTRDTrackletWord* Tracklets() const { return mTracklets; } GPUd() void DumpTracks(); + // utility + GPUd() const typename PROP::propagatorParam* getPropagatorParam(); + protected: float* mR; // radial position of each TRD chamber, alignment taken into account, radial spread within chambers < 7mm bool mIsInitialized; // flag is set upon initialization From a8b51120237aa5f4931dd574d6ebce424df92850 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 29 Apr 2021 15:19:48 +0200 Subject: [PATCH 342/770] GPU: Instantiate 2 TRD Trackers on GPU, for TRD and for o2 track model --- GPU/GPUTracking/Base/GPUConstantMem.h | 3 ++- GPU/GPUTracking/Global/GPUChainTracking.cxx | 9 ++++--- GPU/GPUTracking/Global/GPUChainTracking.h | 2 +- .../Global/GPUChainTrackingTRD.cxx | 10 ++++---- .../TRDTracking/GPUTRDTrackerKernels.cxx | 24 +++++++++++++++---- .../TRDTracking/GPUTRDTrackerKernels.h | 4 ++++ GPU/GPUTracking/display/GPUDisplay.cxx | 2 +- 7 files changed, 39 insertions(+), 15 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUConstantMem.h b/GPU/GPUTracking/Base/GPUConstantMem.h index 8372eaa7a9582..d1a7d0432ef94 100644 --- a/GPU/GPUTracking/Base/GPUConstantMem.h +++ b/GPU/GPUTracking/Base/GPUConstantMem.h @@ -69,7 +69,8 @@ struct GPUConstantMem { GPUTPCConvert tpcConverter; GPUTPCCompression tpcCompressor; GPUTPCGMMerger tpcMerger; - GPUTRDTrackerGPU trdTracker; + GPUTRDTrackerGPU trdTrackerGPU; + GPUTRDTracker trdTrackerO2; GPUTPCClusterFinder tpcClusterer[GPUCA_NSLICES]; GPUITSFitter itsFitter; GPUTrackingRefitProcessor trackingRefit; diff --git a/GPU/GPUTracking/Global/GPUChainTracking.cxx b/GPU/GPUTracking/Global/GPUChainTracking.cxx index 3e2149dd92877..c8319a770e9a4 100644 --- a/GPU/GPUTracking/Global/GPUChainTracking.cxx +++ b/GPU/GPUTracking/Global/GPUChainTracking.cxx @@ -85,7 +85,8 @@ void GPUChainTracking::RegisterPermanentMemoryAndProcessors() mRec->RegisterGPUProcessor(&processors()->tpcMerger, GetRecoStepsGPU() & RecoStep::TPCMerging); } if (GetRecoSteps() & RecoStep::TRDTracking) { - mRec->RegisterGPUProcessor(&processors()->trdTracker, GetRecoStepsGPU() & RecoStep::TRDTracking); + mRec->RegisterGPUProcessor(&processors()->trdTrackerGPU, GetRecoStepsGPU() & RecoStep::TRDTracking); + mRec->RegisterGPUProcessor(&processors()->trdTrackerO2, GetRecoStepsGPU() & RecoStep::TRDTracking); } #ifdef HAVE_O2HEADERS if (GetRecoSteps() & RecoStep::TPCConversion) { @@ -114,7 +115,8 @@ void GPUChainTracking::RegisterGPUProcessors() if (mRec->IsGPU()) { mRec->RegisterGPUDeviceProcessor(mInputsShadow.get(), mInputsHost.get()); } - memcpy((void*)&processorsShadow()->trdTracker, (const void*)&processors()->trdTracker, sizeof(processors()->trdTracker)); + memcpy((void*)&processorsShadow()->trdTrackerGPU, (const void*)&processors()->trdTrackerGPU, sizeof(processors()->trdTrackerGPU)); + memcpy((void*)&processorsShadow()->trdTrackerO2, (const void*)&processors()->trdTrackerO2, sizeof(processors()->trdTrackerO2)); if (GetRecoStepsGPU() & RecoStep::TPCSliceTracking) { for (unsigned int i = 0; i < NSLICES; i++) { mRec->RegisterGPUDeviceProcessor(&processorsShadow()->tpcTrackers[i], &processors()->tpcTrackers[i]); @@ -124,7 +126,8 @@ void GPUChainTracking::RegisterGPUProcessors() mRec->RegisterGPUDeviceProcessor(&processorsShadow()->tpcMerger, &processors()->tpcMerger); } if (GetRecoStepsGPU() & RecoStep::TRDTracking) { - mRec->RegisterGPUDeviceProcessor(&processorsShadow()->trdTracker, &processors()->trdTracker); + mRec->RegisterGPUDeviceProcessor(&processorsShadow()->trdTrackerGPU, &processors()->trdTrackerGPU); + mRec->RegisterGPUDeviceProcessor(&processorsShadow()->trdTrackerO2, &processors()->trdTrackerO2); } #ifdef HAVE_O2HEADERS diff --git a/GPU/GPUTracking/Global/GPUChainTracking.h b/GPU/GPUTracking/Global/GPUChainTracking.h index a85052adfa425..e53b42a0f5376 100644 --- a/GPU/GPUTracking/Global/GPUChainTracking.h +++ b/GPU/GPUTracking/Global/GPUChainTracking.h @@ -136,7 +136,7 @@ class GPUChainTracking : public GPUChain, GPUReconstructionHelpers::helperDelega void ConvertZSFilter(bool zs12bit); // Getters for external usage of tracker classes - GPUTRDTrackerGPU* GetTRDTracker() { return &processors()->trdTracker; } + GPUTRDTrackerGPU* GetTRDTrackerGPU() { return &processors()->trdTrackerGPU; } GPUTPCTracker* GetTPCSliceTrackers() { return processors()->tpcTrackers; } const GPUTPCTracker* GetTPCSliceTrackers() const { return processors()->tpcTrackers; } const GPUTPCGMMerger& GetTPCMerger() const { return processors()->tpcMerger; } diff --git a/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx b/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx index 63c39b0d69474..a65d47128ce93 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx @@ -25,11 +25,11 @@ using namespace o2::trd; int GPUChainTracking::RunTRDTracking() { - if (!processors()->trdTracker.IsInitialized()) { + if (!processors()->trdTrackerGPU.IsInitialized()) { return 1; } - GPUTRDTrackerGPU& Tracker = processors()->trdTracker; + GPUTRDTrackerGPU& Tracker = processors()->trdTrackerGPU; Tracker.Reset(); if (mIOPtrs.nTRDTracklets == 0) { return 0; @@ -72,14 +72,14 @@ int GPUChainTracking::DoTRDGPUTracking() { #ifdef HAVE_O2HEADERS bool doGPU = GetRecoStepsGPU() & RecoStep::TRDTracking; - GPUTRDTrackerGPU& Tracker = processors()->trdTracker; - GPUTRDTrackerGPU& TrackerShadow = doGPU ? processorsShadow()->trdTracker : Tracker; + GPUTRDTrackerGPU& Tracker = processors()->trdTrackerGPU; + GPUTRDTrackerGPU& TrackerShadow = doGPU ? processorsShadow()->trdTrackerGPU : Tracker; const auto& threadContext = GetThreadContext(); SetupGPUProcessor(&Tracker, false); TrackerShadow.OverrideGPUGeometry(reinterpret_cast(mFlatObjectsDevice.mCalibObjects.trdGeometry)); - WriteToConstantMemory(RecoStep::TRDTracking, (char*)&processors()->trdTracker - (char*)processors(), &TrackerShadow, sizeof(TrackerShadow), 0); + WriteToConstantMemory(RecoStep::TRDTracking, (char*)&processors()->trdTrackerGPU - (char*)processors(), &TrackerShadow, sizeof(TrackerShadow), 0); TransferMemoryResourcesToGPU(RecoStep::TRDTracking, &Tracker, 0); runKernel(GetGridAuto(0), krnlRunRangeNone); diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTrackerKernels.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTrackerKernels.cxx index 296407ed2af00..52456089722cc 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTrackerKernels.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTrackerKernels.cxx @@ -21,10 +21,26 @@ using namespace GPUCA_NAMESPACE::gpu; template <> -GPUdii() void GPUTRDTrackerKernels::Thread<0>(int nBlocks, int nThreads, int iBlock, int iThread, GPUsharedref() GPUSharedMemory& smem, processorType& processors) +GPUdi() auto& GPUTRDTrackerKernels::getTracker<0>(processorType& processors) { - GPUCA_OPENMP(parallel for if(!processors.trdTracker.GetRec().GetProcessingSettings().ompKernels) num_threads(processors.trdTracker.GetRec().GetProcessingSettings().ompThreads)) - for (int i = get_global_id(0); i < processors.trdTracker.NTracks(); i += get_global_size(0)) { - processors.trdTracker.DoTrackingThread(i, get_global_id(0)); + return processors.trdTrackerGPU; +} + +template <> +GPUdi() auto& GPUTRDTrackerKernels::getTracker<1>(processorType& processors) +{ + return processors.trdTrackerO2; +} + +template +GPUdii() void GPUTRDTrackerKernels::Thread(int nBlocks, int nThreads, int iBlock, int iThread, GPUsharedref() GPUSharedMemory& smem, processorType& processors) +{ + auto& trdTracker = getTracker(processors); + GPUCA_OPENMP(parallel for if(!trdTracker.GetRec().GetProcessingSettings().ompKernels) num_threads(trdTracker.GetRec().GetProcessingSettings().ompThreads)) + for (int i = get_global_id(0); i < trdTracker.NTracks(); i += get_global_size(0)) { + trdTracker.DoTrackingThread(i, get_global_id(0)); } } + +template GPUd() void GPUTRDTrackerKernels::Thread<0>(int nBlocks, int nThreads, int iBlock, int iThread, GPUsharedref() GPUSharedMemory& smem, processorType& processors); +template GPUd() void GPUTRDTrackerKernels::Thread<1>(int nBlocks, int nThreads, int iBlock, int iThread, GPUsharedref() GPUSharedMemory& smem, processorType& processors); diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTrackerKernels.h b/GPU/GPUTracking/TRDTracking/GPUTRDTrackerKernels.h index 9f19823865ee9..5b7ee0f8d7e85 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTrackerKernels.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTrackerKernels.h @@ -27,6 +27,10 @@ class GPUTRDTrackerKernels : public GPUKernelTemplate GPUhdi() CONSTEXPR static GPUDataTypes::RecoStep GetRecoStep() { return GPUCA_RECO_STEP::TRDTracking; } template GPUd() static void Thread(int nBlocks, int nThreads, int iBlock, int iThread, GPUsharedref() GPUSharedMemory& smem, processorType& processors); + + private: + template + GPUd() static auto& getTracker(processorType& processors); }; } // namespace gpu } // namespace GPUCA_NAMESPACE diff --git a/GPU/GPUTracking/display/GPUDisplay.cxx b/GPU/GPUTracking/display/GPUDisplay.cxx index efce7e90c08dd..3e40c7db47723 100644 --- a/GPU/GPUTracking/display/GPUDisplay.cxx +++ b/GPU/GPUTracking/display/GPUDisplay.cxx @@ -102,7 +102,7 @@ GPUDisplay::GPUDisplay(GPUDisplayBackend* backend, GPUChainTracking* chain, GPUQ inline const GPUTRDGeometry& GPUDisplay::trdGeometry() { return *(GPUTRDGeometry*)mCalib->trdGeometry; } const GPUTPCTracker& GPUDisplay::sliceTracker(int iSlice) { return mChain->GetTPCSliceTrackers()[iSlice]; } -const GPUTRDTrackerGPU& GPUDisplay::trdTracker() { return *mChain->GetTRDTracker(); } +const GPUTRDTrackerGPU& GPUDisplay::trdTracker() { return *mChain->GetTRDTrackerGPU(); } inline int GPUDisplay::getNumThreads() { if (mChain) { From a5621555e5048decd99e37b27e980d95b1880ec1 Mon Sep 17 00:00:00 2001 From: Sandro Wenzel Date: Fri, 30 Apr 2021 13:47:15 +0200 Subject: [PATCH 343/770] Digitization: Prevent race conditions when updating GRP Multiple digitization workflows might execute in parallel and so we need to protect writing to the common GRP file --- .../DigitizerWorkflow/src/GRPUpdaterSpec.cxx | 55 +++++++++++++------ 1 file changed, 37 insertions(+), 18 deletions(-) diff --git a/Steer/DigitizerWorkflow/src/GRPUpdaterSpec.cxx b/Steer/DigitizerWorkflow/src/GRPUpdaterSpec.cxx index 466cec1b3c7f9..cfbd43e31e458 100644 --- a/Steer/DigitizerWorkflow/src/GRPUpdaterSpec.cxx +++ b/Steer/DigitizerWorkflow/src/GRPUpdaterSpec.cxx @@ -23,6 +23,12 @@ #include #include "DetectorsRaw/HBFUtils.h" +// this is for some process synchronization, since +// we need to prevent writing concurrently to the same global GRP file +#include +#include +#include // for the hashing utility + using namespace o2::framework; namespace o2 @@ -50,26 +56,39 @@ class GRPDPLUpdatedTask { const std::string grpName = "GRP"; - TFile flGRP(mGRPFileName.c_str(), "update"); - if (flGRP.IsZombie()) { - LOG(ERROR) << "Failed to open in update mode " << mGRPFileName; - return; - } - std::unique_ptr grp(static_cast(flGRP.GetObjectChecked(grpName.c_str(), GRP::Class()))); - for (auto det : sDetList) { // get readout mode data from different detectors - auto roMode = pc.inputs().get(det.getName()); - if (!(roMode & o2::parameters::GRPObject::PRESENT)) { - LOG(ERROR) << "Detector " << det.getName() << " is read out while processor set ABSENT"; - continue; + // a standardized semaphore convention --> taking the current execution path should be enough + const auto semname = boost::filesystem::current_path().string() + mGRPFileName; + std::hash hasher; + const auto semhashedstring = "alice_grp_" + std::to_string(hasher(semname)); + try { + boost::interprocess::named_semaphore sem(boost::interprocess::open_or_create_t{}, semhashedstring.c_str(), 1); + sem.wait(); // wait until we can enter (no one else there) + + TFile flGRP(mGRPFileName.c_str(), "update"); + if (flGRP.IsZombie()) { + LOG(ERROR) << "Failed to open in update mode " << mGRPFileName; + return; + } + std::unique_ptr grp(static_cast(flGRP.GetObjectChecked(grpName.c_str(), GRP::Class()))); + for (auto det : sDetList) { // get readout mode data from different detectors + auto roMode = pc.inputs().get(det.getName()); + if (!(roMode & o2::parameters::GRPObject::PRESENT)) { + LOG(ERROR) << "Detector " << det.getName() << " is read out while processor set ABSENT"; + continue; + } + grp->setDetROMode(det, roMode); } - grp->setDetROMode(det, roMode); + grp->setFirstOrbit(o2::raw::HBFUtils::Instance().orbitFirst); + grp->setNHBFPerTF(o2::raw::HBFUtils::Instance().nHBFPerTF); + LOG(INFO) << "Updated GRP in " << mGRPFileName << " for detectors RO mode and 1st orbit of the run"; + grp->print(); + flGRP.WriteObjectAny(grp.get(), grp->Class(), grpName.c_str()); + flGRP.Close(); + + sem.post(); // here we are done; put to green for others waiting + } catch (boost::interprocess::interprocess_exception e) { + LOG(ERROR) << "Caught semaphore exception " << e.what(); } - grp->setFirstOrbit(o2::raw::HBFUtils::Instance().orbitFirst); - grp->setNHBFPerTF(o2::raw::HBFUtils::Instance().nHBFPerTF); - LOG(INFO) << "Updated GRP in " << mGRPFileName << " for detectors RO mode and 1st orbit of the run"; - grp->print(); - flGRP.WriteObjectAny(grp.get(), grp->Class(), grpName.c_str()); - flGRP.Close(); pc.services().get().readyToQuit(QuitRequest::Me); } From 8a465043faefcdfbd31bb7ebf41dca15bcb4da7e Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 30 Apr 2021 15:57:07 +0200 Subject: [PATCH 344/770] GPU TPC Clusterizer: Use TPC Pad Gain Correction factor also when processing digits --- .../TPCClusterFinder/GPUTPCCFChargeMapFiller.cxx | 8 +++++--- .../TPCClusterFinder/GPUTPCCFChargeMapFiller.h | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFChargeMapFiller.cxx b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFChargeMapFiller.cxx index 8af28459db03c..0c6a4d0b6a4d5 100644 --- a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFChargeMapFiller.cxx +++ b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFChargeMapFiller.cxx @@ -45,10 +45,10 @@ template <> GPUdii() void GPUTPCCFChargeMapFiller::Thread(int nBlocks, int nThreads, int iBlock, int iThread, GPUSharedMemory& smem, processorType& clusterer) { Array2D chargeMap(reinterpret_cast(clusterer.mPchargeMap)); - fillFromDigitsImpl(get_num_groups(0), get_local_size(0), get_group_id(0), get_local_id(0), clusterer.mPmemory->fragment, clusterer.mPmemory->counters.nPositions, clusterer.mPdigits, clusterer.mPpositions, chargeMap); + fillFromDigitsImpl(get_num_groups(0), get_local_size(0), get_group_id(0), get_local_id(0), clusterer, clusterer.mPmemory->fragment, clusterer.mPmemory->counters.nPositions, clusterer.mPdigits, clusterer.mPpositions, chargeMap); } -GPUd() void GPUTPCCFChargeMapFiller::fillFromDigitsImpl(int nBlocks, int nThreads, int iBlock, int iThread, const CfFragment& fragment, size_t digitNum, +GPUd() void GPUTPCCFChargeMapFiller::fillFromDigitsImpl(int nBlocks, int nThreads, int iBlock, int iThread, processorType& clusterer, const CfFragment& fragment, size_t digitNum, const tpc::Digit* digits, ChargePos* positions, Array2D& chargeMap) @@ -61,7 +61,9 @@ GPUd() void GPUTPCCFChargeMapFiller::fillFromDigitsImpl(int nBlocks, int nThread ChargePos pos(digit.getRow(), digit.getPad(), fragment.toLocal(digit.getTimeStamp())); positions[idx] = pos; - chargeMap[pos] = PackedCharge(digit.getChargeFloat()); + float q = digit.getChargeFloat(); + q *= clusterer.GetConstantMem()->calibObjects.tpcPadGain->getGainCorrection(clusterer.mISlice, digit.getRow(), digit.getPad()); + chargeMap[pos] = PackedCharge(q); } template <> diff --git a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFChargeMapFiller.h b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFChargeMapFiller.h index 40432943fa362..0b84a0603aa35 100644 --- a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFChargeMapFiller.h +++ b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFChargeMapFiller.h @@ -58,7 +58,7 @@ class GPUTPCCFChargeMapFiller : public GPUKernelTemplate static GPUd() void fillIndexMapImpl(int, int, int, int, const CfFragment&, const tpc::Digit*, Array2D&, size_t); - static GPUd() void fillFromDigitsImpl(int, int, int, int, const CfFragment&, size_t, const tpc::Digit*, ChargePos*, Array2D&); + static GPUd() void fillFromDigitsImpl(int, int, int, int, processorType&, const CfFragment&, size_t, const tpc::Digit*, ChargePos*, Array2D&); private: static GPUd() size_t findTransition(int, const tpc::Digit*, size_t, size_t); From 04d306a9738f1d949aff094ff4d82c0c2413bd57 Mon Sep 17 00:00:00 2001 From: shahoian Date: Sat, 1 May 2021 14:59:05 +0200 Subject: [PATCH 345/770] add FT0 recpoints reader to InputHelper --- Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx b/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx index e787f61630858..0751fa1440473 100644 --- a/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx +++ b/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx @@ -20,6 +20,7 @@ #include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" #include "TOFWorkflowUtils/ClusterReaderSpec.h" #include "TOFWorkflow/TOFMatchedReaderSpec.h" +#include "FT0Workflow/RecPointReaderSpec.h" using namespace o2::framework; using namespace o2::globaltracking; @@ -67,5 +68,9 @@ int InputHelper::addInputSpecs(const ConfigContext& configcontext, WorkflowSpec& specs.emplace_back(o2::tof::getTOFMatchedReaderSpec(maskTracksMC[GID::TPCTOF], true, maskTracks[GID::TPCTOF])); } + if (maskTracks[GID::FT0] || maskClusters[GID::FT0]) { + specs.emplace_back(o2::ft0::getRecPointReaderSpec(maskTracksMC[GID::FT0] || maskClustersMC[GID::FT0])); + } + return 0; } From 87ad8a3096fa00ec3a1757610760c08849eb1f98 Mon Sep 17 00:00:00 2001 From: Matteo Concas Date: Sun, 2 May 2021 11:04:27 +0200 Subject: [PATCH 346/770] [ITS tracking] Revert tracking parameters changes Erroneously pushed together with other changes. --- macro/run_trac_ca_its.C | 26 ++++++-------------------- 1 file changed, 6 insertions(+), 20 deletions(-) diff --git a/macro/run_trac_ca_its.C b/macro/run_trac_ca_its.C index acd13ec29992a..12c350f49f857 100644 --- a/macro/run_trac_ca_its.C +++ b/macro/run_trac_ca_its.C @@ -225,30 +225,16 @@ void run_trac_ca_its(bool cosmics = false, memParams[0].CellsMemoryCoefficients[iLayer] = 0.001f; } } else { - // Comment for pp + // PbPb tracking params // ---- trackParams.resize(3); memParams.resize(3); - for (int iParam{0}; iParam < 3; ++iParam) { - for (int iLayer = 0; iLayer < o2::its::constants::its2::TrackletsPerRoad; iLayer++) { - memParams[iParam].TrackletsMemoryCoefficients[iLayer] = 5.f; - memParams[iParam].CellsMemoryCoefficients[iLayer] = 0.1f; - } - } - for (auto i{0}; i < 3; ++i) { - trackParams[i].TrackletMaxDeltaPhi = 3.f; - trackParams[i].CellMaxDeltaPhi = 3.f; - trackParams[i].CellMaxDeltaTanLambda = 1.f; - for (auto j{0}; j < 6; ++j) { - trackParams[i].TrackletMaxDeltaZ[j] = 10.f; - } - for (auto j{0}; j < 5; ++j) { - trackParams[i].CellMaxDeltaZ[j] = 10.f; - } - } + trackParams[0].TrackletMaxDeltaPhi = 0.05f; + trackParams[1].TrackletMaxDeltaPhi = 0.1f; trackParams[2].MinTrackLength = 4; + trackParams[2].TrackletMaxDeltaPhi = 0.3; // --- - // Uncomment for pp + // pp tracking params // trackParams.resize(2); // std::array kmaxDCAxy1 = {1.f * 2.0, 0.4f * 2.0, 0.4f * 2.0, 2.0f * 2.0, 3.f * 2.0}; // std::array kmaxDCAz1 = {1.f * 2.0, 0.4f * 2.0, 0.4f * 2.0, 2.0f * 2.0, 3.f * 2.0}; @@ -344,4 +330,4 @@ void run_trac_ca_its(bool cosmics = false, graph->Draw("AP"); } -#endif \ No newline at end of file +#endif From b3e423c3f18f6bba0f54d781ef219e8006c23fa7 Mon Sep 17 00:00:00 2001 From: shahoian Date: Sun, 2 May 2021 02:49:32 +0200 Subject: [PATCH 347/770] RecoContainer: considers simpler contributors if derived track was rejected If user provided function creator function returns true, then the track is considered as consumed and its contributing simpler tracks will not be provided to the creator. If it returns false, the creator will be called also with this simpler contrubutors. --- .../DataFormatsGlobalTracking/RecoContainer.h | 2 +- .../GlobalTracking/src/RecoContainer.cxx | 49 +++++++++++++------ Detectors/GlobalTracking/src/MatchCosmics.cxx | 5 +- .../src/PrimaryVertexingSpec.cxx | 7 +-- .../Vertexing/src/VertexTrackMatcher.cxx | 5 +- 5 files changed, 44 insertions(+), 24 deletions(-) diff --git a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h index 37bc414b44ef7..3265e1a1fe3a5 100644 --- a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h +++ b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h @@ -77,7 +77,7 @@ struct RecoContainer { std::invoke_result::type inputsTPCclusters; // special struct for TPC clusters access void collectData(o2::framework::ProcessingContext& pc, const DataRequest& request); - void createTracks(std::function const& creator) const; + void createTracks(std::function const& creator) const; void fillTrackMCLabels(const gsl::span gids, std::vector& mcinfo) const; void addITSTracks(o2::framework::ProcessingContext& pc, bool mc); diff --git a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx index 6af87511199eb..a829057524015 100644 --- a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx +++ b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx @@ -356,21 +356,26 @@ void RecoContainer::fillTrackMCLabels(const gsl::span gids, std::vecto } //________________________________________________________ -void RecoContainer::createTracks(std::function const& creator) const +void RecoContainer::createTracks(std::function const& creator) const { // We go from most complete tracks to least complete ones, taking into account that some track times // do not bear their own kinematics but just constrain the time // As we get more track types functional, this method should be completed + // If user provided function creator returns true, then the track is considered as consumed and its contributing + // simpler tracks will not be provided to the creator. If it returns false, the creator will be called also + // with this simpler contrubutors auto start_time = std::chrono::high_resolution_clock::now(); constexpr float PS2MUS = 1e-6; std::array, GTrackID::NSources> usedData; - auto flagUsed = [&usedData](const GTrackID gidx) { auto src = gidx.getSource(); - if (!usedData[src].empty()) { - usedData[gidx.getSource()][gidx.getIndex()] = 1; - } }; - auto isUsed = [&usedData](const GTrackID gidx) { return (!usedData[gidx.getSource()].empty()) && (usedData[gidx.getSource()][gidx.getIndex()] != 0); }; + auto flagUsed2 = [&usedData](int idx, int src) { + if (!usedData[src].empty()) { + usedData[src][idx] = 1; + } + }; + auto flagUsed = [&usedData, &flagUsed2](const GTrackID gidx) { flagUsed2(gidx.getIndex(), gidx.getSource()); }; auto isUsed2 = [&usedData](int idx, int src) { return (!usedData[src].empty()) && (usedData[src][idx] != 0); }; + auto isUsed = [&usedData, isUsed2](const GTrackID gidx) { return isUsed2(gidx.getIndex(), gidx.getSource()); }; // create only for those data types which are used const auto& tracksITS = getITSTracks(); @@ -382,6 +387,7 @@ void RecoContainer::createTracks(std::function().size()); // to flag used ITSTPC-TOF matches // ITS-TPC-TOF matches, may refer to ITS-TPC (TODO: something else?) tracks { @@ -398,8 +404,10 @@ void RecoContainer::createTracks(std::function(gidITS); - creator(trc, t0, 0.5, gidITS); + if (creator(trc, t0, 0.5, gidITS)) { + flagUsed2(it, GTrackID::ITS); + } } } } diff --git a/Detectors/GlobalTracking/src/MatchCosmics.cxx b/Detectors/GlobalTracking/src/MatchCosmics.cxx index c981d738a4283..fb98973975eaa 100644 --- a/Detectors/GlobalTracking/src/MatchCosmics.cxx +++ b/Detectors/GlobalTracking/src/MatchCosmics.cxx @@ -482,10 +482,10 @@ void MatchCosmics::createSeeds(const o2::globaltracking::RecoContainer& data) mSeeds.clear(); - std::function creator = + std::function creator = [this](const o2::track::TrackParCov& _tr, float t0, float terr, GTrackID _origID) { if (std::abs(_tr.getQ2Pt()) > this->mQ2PtCutoff) { - return; + return true; } if (_origID.getSource() == GTrackID::TPC) { // convert TPC bins to \mus t0 *= this->mTPCTBinMUS; @@ -498,6 +498,7 @@ void MatchCosmics::createSeeds(const o2::globaltracking::RecoContainer& data) } terr += this->mMatchParams->timeToleranceMUS; mSeeds.emplace_back(TrackSeed{_tr, {t0 - terr, t0 + terr}, _origID, MinusOne}); + return true; }; data.createTracks(creator); diff --git a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx index dc3d22360cd54..5f34723765dd9 100644 --- a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx @@ -86,20 +86,21 @@ void PrimaryVertexingSpec::run(ProcessingContext& pc) auto halfROFITS = 0.5 * mITSROFrameLengthMUS; auto hw2ErrITS = 2.f / std::sqrt(12.f) * mITSROFrameLengthMUS; // conversion from half-width to error for ITS - std::function creator = + std::function creator = [maxTrackTimeError, hw2ErrITS, halfROFITS, &tracks, &gids](const o2::track::TrackParCov& _tr, float t0, float terr, GTrackID _origID) { if (!_origID.includesDet(DetID::ITS)) { - return; // just in case this selection was not done on RecoContainer filling level + return true; // just in case this selection was not done on RecoContainer filling level } if (_origID.getSource() == GTrackID::ITS) { // error is supplied a half-ROF duration, convert to \mus t0 += halfROFITS; // ITS time is supplied as beginning of ROF terr *= hw2ErrITS; } if (terr > maxTrackTimeError) { - return; + return true; } tracks.emplace_back(TrackWithTimeStamp{_tr, {t0, terr}}); gids.emplace_back(_origID); + return true; }; recoData.createTracks(creator); // create track sample considered for vertexing diff --git a/Detectors/Vertexing/src/VertexTrackMatcher.cxx b/Detectors/Vertexing/src/VertexTrackMatcher.cxx index bfaae5a93b967..a4bad42afac8c 100644 --- a/Detectors/Vertexing/src/VertexTrackMatcher.cxx +++ b/Detectors/Vertexing/src/VertexTrackMatcher.cxx @@ -151,10 +151,10 @@ void VertexTrackMatcher::extractTracks(const o2::globaltracking::RecoContainer& mTBrackets.clear(); - std::function creator = + std::function creator = [this, &vcont](const o2::track::TrackParCov& _tr, float t0, float terr, GIndex _origID) { if (vcont.find(_origID) != vcont.end()) { // track is contributor to vertex, already accounted - return; + return true; } if (_origID.getSource() == GIndex::TPC) { // convert TPC bins to \mus t0 *= this->mTPCBin2MUS; @@ -166,6 +166,7 @@ void VertexTrackMatcher::extractTracks(const o2::globaltracking::RecoContainer& //terr *= this->mMatchParams->nSigmaTError; } mTBrackets.emplace_back(TrackTBracket{{t0 - terr, t0 + terr}, _origID}); + return true; }; data.createTracks(creator); From 79dad23a93b9e4181370099fa37b7f125b8683c8 Mon Sep 17 00:00:00 2001 From: Dmitri Peresunko Date: Sat, 1 May 2021 12:48:03 +0300 Subject: [PATCH 348/770] Raw decoding optimized; Made Mapping singleton; Semigauss raw fitter added --- .../PHOS/base/include/PHOSBase/Mapping.h | 16 +- .../base/include/PHOSBase/PHOSSimParams.h | 13 +- Detectors/PHOS/base/src/Mapping.cxx | 49 ++- Detectors/PHOS/reconstruction/CMakeLists.txt | 10 +- .../include/PHOSReconstruction/AltroDecoder.h | 58 ++-- .../include/PHOSReconstruction/Bunch.h | 103 ------ .../PHOSReconstruction/CaloRawFitter.h | 40 ++- .../PHOSReconstruction/CaloRawFitterGS.h | 67 ++++ .../include/PHOSReconstruction/Channel.h | 160 --------- .../PHOS/reconstruction/run/rawReaderFile.cxx | 122 ------- .../PHOS/reconstruction/src/AltroDecoder.cxx | 270 ++++++++++++--- Detectors/PHOS/reconstruction/src/Bunch.cxx | 19 -- .../PHOS/reconstruction/src/CaloRawFitter.cxx | 205 +++--------- .../reconstruction/src/CaloRawFitterGS.cxx | 314 ++++++++++++++++++ Detectors/PHOS/reconstruction/src/Channel.cxx | 50 --- .../src/PHOSReconstructionLinkDef.h | 2 + .../include/PHOSSimulation/RawWriter.h | 2 - Detectors/PHOS/simulation/src/RawWriter.cxx | 32 +- .../PHOSWorkflow/RawToCellConverterSpec.h | 11 +- .../workflow/src/RawToCellConverterSpec.cxx | 311 +++++------------ 20 files changed, 848 insertions(+), 1006 deletions(-) delete mode 100644 Detectors/PHOS/reconstruction/include/PHOSReconstruction/Bunch.h create mode 100644 Detectors/PHOS/reconstruction/include/PHOSReconstruction/CaloRawFitterGS.h delete mode 100644 Detectors/PHOS/reconstruction/include/PHOSReconstruction/Channel.h delete mode 100644 Detectors/PHOS/reconstruction/run/rawReaderFile.cxx delete mode 100644 Detectors/PHOS/reconstruction/src/Bunch.cxx create mode 100644 Detectors/PHOS/reconstruction/src/CaloRawFitterGS.cxx delete mode 100644 Detectors/PHOS/reconstruction/src/Channel.cxx diff --git a/Detectors/PHOS/base/include/PHOSBase/Mapping.h b/Detectors/PHOS/base/include/PHOSBase/Mapping.h index 8ce067d5438df..e5345d7046241 100644 --- a/Detectors/PHOS/base/include/PHOSBase/Mapping.h +++ b/Detectors/PHOS/base/include/PHOSBase/Mapping.h @@ -50,17 +50,19 @@ class Mapping kLowGain, kTRU }; - Mapping() = default; - Mapping(std::basic_string_view path); ~Mapping() = default; + //Getters for unique instance of Mapping + static Mapping* Instance(); + static Mapping* Instance(std::basic_string_view path); + /// \brief convert hardware address to absId and caloFlag - ErrorStatus hwToAbsId(short ddl, short hw, short& absId, CaloFlag& caloFlag); + ErrorStatus hwToAbsId(short ddl, short hw, short& absId, CaloFlag& caloFlag) const; /// \brief convert absId and caloflag to hardware address and ddl - ErrorStatus absIdTohw(short absId, short caloFlag, short& ddl, short& hwAddr); + ErrorStatus absIdTohw(short absId, short caloFlag, short& ddl, short& hwAddr) const; /// \brief convert ddl number to crorc and link number (TODO!!!) - void ddlToCrorcLink(short iddl, short& crorc, short& link) + static void ddlToCrorcLink(short iddl, short& crorc, short& link) { crorc = iddl / 8; link = iddl % 8; @@ -72,10 +74,14 @@ class Mapping static bool isTRUReadoutchannel(short hwAddress) { return (hwAddress < 112) || (hwAddress > 2048 && hwAddress < 2048 + 112); } protected: + Mapping() = default; + Mapping(std::basic_string_view path); + /// \brief Construct vector for conversion only if necessary ErrorStatus constructAbsToHWMatrix(); private: + static Mapping* sMapping; ///< Pointer to the unique instance of the singleton std::string mPath = ""; ///< path to mapping files bool mInitialized = false; ///< If conversion tables created bool mInvInitialized = false; ///< If inverse conversion tables created diff --git a/Detectors/PHOS/base/include/PHOSBase/PHOSSimParams.h b/Detectors/PHOS/base/include/PHOSBase/PHOSSimParams.h index bba0639e65de7..765936a9eb348 100644 --- a/Detectors/PHOS/base/include/PHOSBase/PHOSSimParams.h +++ b/Detectors/PHOS/base/include/PHOSBase/PHOSSimParams.h @@ -61,11 +61,14 @@ struct PHOSSimParams : public o2::conf::ConfigurableParamHelper { float mSampleDecayTime = 0.091; ///< Time parameter in Gamma2 function (1/tau, 100.e-9/2.1e-6) // //Parameters used in raw data reconstruction - short mSpikeThreshold = 100; ///< Single spike >100 ADC channels - short mBaseLine = 0; ///< - short mPreSamples = 2; ///< number of pre-samples readout before sample (if no pedestal subtrauction) - short mMCOverflow = 970; ///< Overflow level for MC simulations: 1023-(pedestal~50) - float mTimeTick = 100.; ///< ns to PHOS digitization step conversion + short mSpikeThreshold = 100; ///< Single spike >100 ADC channels + short mBaseLine = 0; ///< + short mPreSamples = 2; ///< number of pre-samples readout before sample (if no pedestal subtrauction) + short mMCOverflow = 970; ///< Overflow level for MC simulations: 1023-(pedestal~50) + float mTimeTick = 100.; ///< ns to PHOS digitization step conversion + float mSampleTimeFitAccuracy = 1.e-3; //Abs accuracy of time fit of saturated samples (in 100ns tick units) + float mSampleAmpFitAccuracy = 1.e-2; //Relative accuracy of amp. fit + short mNIterations = 5; ///< maximal number of iterations in oveflow sample fit // bool mSubtractPedestal = false ; ///< subtract pedestals // bool mCreateSampleQualityOutput = false ; ///< Create stream of sample quality diff --git a/Detectors/PHOS/base/src/Mapping.cxx b/Detectors/PHOS/base/src/Mapping.cxx index e4d31b8d1ec61..d9d142062e437 100644 --- a/Detectors/PHOS/base/src/Mapping.cxx +++ b/Detectors/PHOS/base/src/Mapping.cxx @@ -18,13 +18,39 @@ #include "PHOSBase/Geometry.h" using namespace o2::phos; - +Mapping* Mapping::sMapping = nullptr; +//_______________________________________________________ Mapping::Mapping(std::basic_string_view path) : mPath(path), mInitialized(false) { } //_______________________________________________________ -Mapping::ErrorStatus Mapping::hwToAbsId(short ddl, short hwAddr, short& absId, CaloFlag& caloFlag) +Mapping* Mapping::Instance() +{ + if (sMapping) { + return sMapping; + } else { + sMapping = new Mapping(); + sMapping->setMapping(); + return sMapping; + } +} +//_______________________________________________________ +Mapping* Mapping::Instance(std::basic_string_view path) +{ + if (sMapping) { + if (sMapping->mPath == path) { + return sMapping; + } else { + delete sMapping; + } + } + sMapping = new Mapping(path); + sMapping->setMapping(); + return sMapping; +} +//_______________________________________________________ +Mapping::ErrorStatus Mapping::hwToAbsId(short ddl, short hwAddr, short& absId, CaloFlag& caloFlag) const { if (!mInitialized) { @@ -55,7 +81,7 @@ Mapping::ErrorStatus Mapping::hwToAbsId(short ddl, short hwAddr, short& absId, C return kOK; } //_______________________________________________________ -Mapping::ErrorStatus Mapping::absIdTohw(short absId, short caloFlag, short& ddl, short& hwAddr) +Mapping::ErrorStatus Mapping::absIdTohw(short absId, short caloFlag, short& ddl, short& hwAddr) const { if (caloFlag < 0 || caloFlag > 2) { @@ -107,14 +133,13 @@ Mapping::ErrorStatus Mapping::setMapping() short numberOfChannels = 0; short maxHWAddress = 0; - char fname[255]; - snprintf(fname, 255, "%s/Mod%dRCU%d.data", p.data(), m, i); - std::ifstream* fIn = new std::ifstream(fname); - if (!*fIn) { + std::string fname = fmt::format("{:s}/Mod{:d}RCU{:d}.data", p, m, i); + std::ifstream fIn(fname); + if (!fIn.is_open()) { LOG(FATAL) << "Missing mapping file " << p << "/Mod" << m << "RCU" << i << ".data"; return kNotInitialized; } - if (!(*fIn >> numberOfChannels)) { + if (!(fIn >> numberOfChannels)) { LOG(FATAL) << "Syntax of mapping file " << p << "/Mod" << m << "RCU" << i << ".data is wrong: no numberOfChannels"; return kNotInitialized; } @@ -122,7 +147,7 @@ Mapping::ErrorStatus Mapping::setMapping() LOG(FATAL) << "Unexpected number of channels: " << numberOfChannels << " expecting " << NHWPERDDL << " file " << p << "/Mod" << m << "RCU" << i << ".data is wrong: no numberOfChannels"; return kNotInitialized; } - if (!(*fIn >> maxHWAddress)) { + if (!(fIn >> maxHWAddress)) { LOG(FATAL) << "Syntax of mapping file " << p << "/Mod" << m << "RCU" << i << ".data is wrong: no maxHWAddress"; return kNotInitialized; } @@ -132,7 +157,7 @@ Mapping::ErrorStatus Mapping::setMapping() } for (short ich = 0; ich < numberOfChannels; ich++) { // 1792 = 2*896 channels connected to each RCU int hwAddress; - if (!(*fIn >> hwAddress)) { + if (!(fIn >> hwAddress)) { LOG(FATAL) << "Syntax of mapping file " << p << "/Mod" << m << "RCU" << i << ".data is wrong: no HWadd for ch " << ich; return kNotInitialized; } @@ -141,7 +166,7 @@ Mapping::ErrorStatus Mapping::setMapping() return kNotInitialized; } int row, col, caloFlag; - if (!(*fIn >> row >> col >> caloFlag)) { + if (!(fIn >> row >> col >> caloFlag)) { LOG(FATAL) << "Syntax of mapping file " << p << "/Mod" << m << "RCU" << i << ".data is wrong: no (raw col caloFlag)"; return kNotInitialized; } @@ -183,7 +208,7 @@ Mapping::ErrorStatus Mapping::setMapping() mAbsToHW[absId][caloFlag][0] = ddl; mAbsToHW[absId][caloFlag][1] = hwAddress; } - fIn->close(); + fIn.close(); } //RCU } // module mInitialized = true; diff --git a/Detectors/PHOS/reconstruction/CMakeLists.txt b/Detectors/PHOS/reconstruction/CMakeLists.txt index c46283b9d756a..c5691fb408e2c 100644 --- a/Detectors/PHOS/reconstruction/CMakeLists.txt +++ b/Detectors/PHOS/reconstruction/CMakeLists.txt @@ -16,9 +16,8 @@ o2_add_library(PHOSReconstruction src/RawHeaderStream.cxx src/RawPayload.cxx src/AltroDecoder.cxx - src/Bunch.cxx - src/Channel.cxx src/CaloRawFitter.cxx + src/CaloRawFitterGS.cxx src/CTFCoder.cxx src/CTFHelper.cxx PUBLIC_LINK_LIBRARIES O2::PHOSBase @@ -35,15 +34,10 @@ o2_target_root_dictionary(PHOSReconstruction include/PHOSReconstruction/RawHeaderStream.h include/PHOSReconstruction/RawPayload.h include/PHOSReconstruction/RawReaderError.h - include/PHOSReconstruction/Bunch.h include/PHOSReconstruction/RawDecodingError.h include/PHOSReconstruction/AltroDecoder.h - include/PHOSReconstruction/Channel.h include/PHOSReconstruction/CaloRawFitter.h + include/PHOSReconstruction/CaloRawFitterGS.h include/PHOSReconstruction/Clusterer.h include/PHOSReconstruction/FullCluster.h) -o2_add_executable(rawreader-file - COMPONENT_NAME phos - PUBLIC_LINK_LIBRARIES O2::PHOSReconstruction - SOURCES run/rawReaderFile.cxx) diff --git a/Detectors/PHOS/reconstruction/include/PHOSReconstruction/AltroDecoder.h b/Detectors/PHOS/reconstruction/include/PHOSReconstruction/AltroDecoder.h index 42e4f7a2d6cc1..af391bf538da7 100644 --- a/Detectors/PHOS/reconstruction/include/PHOSReconstruction/AltroDecoder.h +++ b/Detectors/PHOS/reconstruction/include/PHOSReconstruction/AltroDecoder.h @@ -13,9 +13,12 @@ #include #include #include +#include #include "PHOSBase/RCUTrailer.h" -#include "PHOSReconstruction/Bunch.h" -#include "PHOSReconstruction/Channel.h" +#include "DataFormatsPHOS/Cell.h" +#include "PHOSBase/Mapping.h" +#include "PHOSReconstruction/RawReaderError.h" +#include "PHOSReconstruction/CaloRawFitter.h" #include "PHOSReconstruction/RawReaderMemory.h" namespace o2 @@ -82,8 +85,7 @@ class AltroDecoder { public: /// \brief Constructor - /// \param reader Raw reader instance to be decoded - AltroDecoder(RawReaderMemory& reader); + AltroDecoder() = default; /// \brief Destructor ~AltroDecoder() = default; @@ -97,35 +99,41 @@ class AltroDecoder /// a reference to the RCU trailer and a vector /// with the decoded chanenels, each containing /// its bunches. - AltroDecoderError::ErrorType_t decode(); + AltroDecoderError::ErrorType_t decode(RawReaderMemory& rawreader, CaloRawFitter* rawFitter, + std::vector& cellContainer, + std::vector& truContainer); /// \brief Get reference to the RCU trailer object /// \return reference to the RCU trailers vector const RCUTrailer& getRCUTrailer() const { return mRCUTrailer; } - /// \brief Get the reference to the channel container - /// \return Reference to the channel container - /// \throw AltroDecoderError with CHANNEL_ERROR if the channel container was not initialized for the current event - const std::vector& getChannels() const; - - /// \brief Read RCU trailer for the current event in the raw buffer - void readRCUTrailer(); - /// \brief Read channels for the current event in the raw buffer - void readChannels(); + void readChannels(const std::vector& payloadwords, CaloRawFitter* rawFitter, + std::vector& cellContainer, + std::vector& truContainer); + void setPedestalRun() + { + mPedestalRun = true; + mCombineGHLG = false; + } + void setCombineHGLG(bool a) { mCombineGHLG = a; } private: - /// \brief run checks on the RCU trailer - /// \throw Error if the RCU trailer has inconsistencies - /// - /// Performing various consistency checks on the RCU trailer - /// In case of failure an exception is thrown. - void checkRCUTrailer(); - - RawReaderMemory& mRawReader; ///< underlying raw reader - RCUTrailer mRCUTrailer; ///< RCU trailer - std::vector mChannels; ///< vector of channels in the raw stream - bool mChannelsInitialized = false; ///< check whether the channels are initialized + //check and convert HW address to absId and caloFlag + bool hwToAbsAddress(short hwaddress, short& absId, Mapping::CaloFlag& caloFlag); + //read trigger digits + void readTRUDigits(short absId, int payloadSize, std::vector& truContainer) const; + //read trigger summary tables + void readTRUFlags(short hwAddress, int payloadSize); + + bool mCombineGHLG = true; ///< Combine or not HG and LG channels (def: combine, LED runs: not combine) + bool mPedestalRun = false; ///< Analyze pedestal run (calculate pedestal mean and RMS) + short mddl; ///< Current DDL + std::vector mBunchwords; ///< (transient) bunch of samples for current channel + std::vector mOutputHWErrors; ///< Errors occured in reading data + std::vector mOutputFitChi; ///< Raw sample fit quality + std::bitset mTRUFlags; ///< trigger summary table + RCUTrailer mRCUTrailer; ///< RCU trailer ClassDefNV(AltroDecoder, 1); }; diff --git a/Detectors/PHOS/reconstruction/include/PHOSReconstruction/Bunch.h b/Detectors/PHOS/reconstruction/include/PHOSReconstruction/Bunch.h deleted file mode 100644 index afda162577293..0000000000000 --- a/Detectors/PHOS/reconstruction/include/PHOSReconstruction/Bunch.h +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. -#ifndef ALICEO2_PHOS_BUNCH_H -#define ALICEO2_PHOS_BUNCH_H - -#include -#include -#include -#include "Rtypes.h" - -namespace o2 -{ - -namespace phos -{ -/// \class Bunch -/// \brief ALTRO bunch information -/// \ingroup PHOSreconstruction -/// -/// The bunch contains the ADC values of a given -/// data bunch for a channel in the ALTRO stream. -/// The ADC values are stored in reversed order in -/// time both in the ALTRO stream and in the bunch -/// object. -/// -/// For iteration one should assume that the end time -/// is 0, however it can also be larger than 0. In this -/// case the first value has to be mapped to the end timebin -/// and the last value to the start timebin, still iterating -/// only over the number of samples. -class Bunch -{ - public: - /// \brief Constructor - Bunch() = default; - - /// \brief Initialize the bunch with start time and bunch length - /// \param length Length of the bunch - /// \param start Start time of the bunch - Bunch(uint8_t length, uint8_t start) : mBunchLength(length), mStartTime(start), mADC() {} - - /// \brief - ~Bunch() = default; - - /// \brief Add ADC value to the bunch - /// \param adc Next ADC value - /// - /// ADC values are stored in reversed order. The next ADC value - /// has to be earlier in time compared to the previous one. - void addADC(uint16_t adc) { mADC.emplace_back(adc); } - - /// \brief Initialize the ADC values in the bunch from a range - /// \param range Range of ADC values - /// - /// The ADC values are stored in reversed order in time. Therefore - /// the last entry is the one earliest in time. - void initFromRange(gsl::span range); - - /// \brief Get range of ADC values in the bunch - /// \return ADC values in the bunch - /// - /// The ADC values are stored in reversed order in time. Therefore - /// the last entry is the one earliest in time. - const std::vector& getADC() const { return mADC; } - - /// \brief Get the length of the bunch (number of time bins) - /// \return Length of the bunch - uint8_t getBunchLength() const { return mBunchLength; } - - /// \brief Get the start time bin - /// \return Start timebin - /// - /// The start timebin is the higher of the two, - /// the samples are in reversed order. - uint8_t getStartTime() const { return mStartTime; } - - /// \brief Get the end time bin - /// \return End timebin - /// - /// The end timebin is the lower of the two, - /// the samples are in reversed order. - uint8_t getEndTime() const { return mStartTime - mBunchLength + 1; } - - private: - uint8_t mBunchLength = 0; ///< Number of ADC samples in buffer - uint8_t mStartTime = 0; ///< Start timebin (larger time bin, samples are in reversed order) - std::vector mADC; ///< ADC samples in bunch - - ClassDefNV(Bunch, 1); -}; - -} // namespace phos - -} // namespace o2 - -#endif diff --git a/Detectors/PHOS/reconstruction/include/PHOSReconstruction/CaloRawFitter.h b/Detectors/PHOS/reconstruction/include/PHOSReconstruction/CaloRawFitter.h index cf36567aaebf9..477ceb921d72d 100644 --- a/Detectors/PHOS/reconstruction/include/PHOSReconstruction/CaloRawFitter.h +++ b/Detectors/PHOS/reconstruction/include/PHOSReconstruction/CaloRawFitter.h @@ -21,13 +21,13 @@ #ifndef PHOSRAWFITTER_H_ #define PHOSRAWFITTER_H_ +#include "Rtypes.h" namespace o2 { namespace phos { -class Bunch; class CaloRawFitter { @@ -45,10 +45,10 @@ class CaloRawFitter public: /// \brief Constructor - CaloRawFitter() = default; + CaloRawFitter(); /// \brief Destructor - ~CaloRawFitter() = default; + virtual ~CaloRawFitter() = default; /// \brief Evaluation Amplitude and TOF /// return status -1: not evaluated/empty bunch; @@ -56,7 +56,7 @@ class CaloRawFitter /// 1: overflow; /// 4: single spikes /// 3: too large RMS; - FitStatus evaluate(const std::vector& bunchvector); + virtual FitStatus evaluate(gsl::span signal); /// \brief Set HighGain/LowGain channel to performe or not fit of saturated samples void setLowGain(bool isLow = false) { mLowGain = isLow; } @@ -65,46 +65,44 @@ class CaloRawFitter void setPedSubtract(bool toSubtruct = false) { mPedSubtract = toSubtruct; } /// \brief amplitude in last fitted sample - float getAmp(int is) { return mAmp[is]; } + float getAmp() const { return mAmp; } /// \brief Chi2/NDF of last performed fit - float getChi2(int is) const { return mChi2[is]; } + float getChi2() const { return mChi2; } /// \brief time in last fitted sample - float getTime(int is) { return mTime[is]; } + float getTime() const { return mTime; } /// \brief is last fitted sample has overflow - bool isOverflow(int is) { return mOverflow[is]; } + bool isOverflow() const { return mOverflow; } /// \brief Forse perform fitting /// Make fit for any sample, not only saturated LowGain samples as by default void forseFitting(bool toRunFit = true) { makeFit = toRunFit; } - /// \brief Number of fit samples (normaly 1, more in case of pileup, noise etc) - short getNsamples() { return mAmp.size(); } - /// \brief Set analysis of pedestal run /// Analyze pedestal run, i.e. calculate mean and RMS of pedestals instead of Amp and Time void setPedestal() { mPedestalRun = true; } protected: - FitStatus evalKLevel(const Bunch& b); - - FitStatus fitGamma2(const Bunch& b); + FitStatus evalKLevel(gsl::span signal); - private: + protected: bool makeFit = false; ///< run (slow) fit with Gamma2 or use fast evaluation with k-level bool mLowGain = false; ///< is current bunch from LowGain channel bool mPedSubtract = false; ///< should one evaluate and subtract pedestals bool mPedestalRun = false; ///< analyze as pedestal run - std::vector mOverflow; ///< is last sample saturated + bool mOverflow; ///< is last sample saturated FitStatus mStatus = kNotEvaluated; ///< status of last evaluated sample: -1: not yet evaluated; 0: OK; 1: overflow; 2: too large RMS; 3: single spikes short mMaxSample = 0; ///< maximal sample - std::vector mAmp; ///< amplitude of last processed sample - std::vector mTime; ///< time of last processed sample - std::vector mChi2; ///< chi2 calculated in last fit - - ClassDefNV(CaloRawFitter, 1); + float mAmp; ///< amplitude of last processed sample + float mTime; ///< time of last processed sample + float mChi2; ///< chi2 calculated in last fit + short mSpikeThreshold; + short mBaseLine; + short mPreSamples; + + ClassDef(CaloRawFitter, 1); }; // End of CaloRawFitter } // namespace phos diff --git a/Detectors/PHOS/reconstruction/include/PHOSReconstruction/CaloRawFitterGS.h b/Detectors/PHOS/reconstruction/include/PHOSReconstruction/CaloRawFitterGS.h new file mode 100644 index 0000000000000..5138bb7c71678 --- /dev/null +++ b/Detectors/PHOS/reconstruction/include/PHOSReconstruction/CaloRawFitterGS.h @@ -0,0 +1,67 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \class CaloRawFitterGSGS +/// \brief Raw data fitting based on NIM A621 (2010) 231–237 +/// +/// Extraction of amplitude and time +/// from CALO raw data using analytical calculation of +/// least square fit with Gamma2 function +/// +/// \author Dmitri Peresunko after M.Bogolybski +/// \since April.2021 +/// + +#ifndef PHOSRAWFITTERGS_H +#define PHOSRAWFITTERGS_H +#include "PHOSReconstruction/CaloRawFitter.h" + +namespace o2 +{ + +namespace phos +{ + +class CaloRawFitterGS : public CaloRawFitter +{ + + public: + static constexpr int NMAXSAMPLES = 40; ///< maximal expected number of samples per bunch + /// \brief Constructor + CaloRawFitterGS(); + + /// \brief Destructor + ~CaloRawFitterGS() final = default; + + /// \brief Evaluation Amplitude and TOF + FitStatus evaluate(gsl::span signal) final; + + protected: + void init(); + FitStatus evalFit(gsl::span signal); + + private: + float mDecTime = 0.058823529; ///< decay time constant + float mTimeAccuracy = 0.; ///< accuracy of iterative fit + float mAmpAccuracy = 0.; ///< accuracy of iterative fit + float ma0[NMAXSAMPLES]; ///< arrays to tabulate Gamma2 function and its momenta + float mb0[NMAXSAMPLES]; ///< arrays to tabulate Gamma2 function and its momenta + float mb1[NMAXSAMPLES]; ///< arrays to tabulate Gamma2 function and its momenta + float mb2[NMAXSAMPLES]; ///< arrays to tabulate Gamma2 function and its momenta + float mb3[NMAXSAMPLES]; ///< arrays to tabulate Gamma2 function and its momenta + float mb4[NMAXSAMPLES]; ///< arrays to tabulate Gamma2 function and its momenta + + ClassDef(CaloRawFitterGS, 1); +}; // End of CaloRawFitterGS + +} // namespace phos + +} // namespace o2 +#endif diff --git a/Detectors/PHOS/reconstruction/include/PHOSReconstruction/Channel.h b/Detectors/PHOS/reconstruction/include/PHOSReconstruction/Channel.h deleted file mode 100644 index 4ce48c910cf0a..0000000000000 --- a/Detectors/PHOS/reconstruction/include/PHOSReconstruction/Channel.h +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. -#ifndef ALICEO2_PHOS_CHANNEL_H -#define ALICEO2_PHOS_CHANNEL_H - -#include -#include -#include -#include "Rtypes.h" -#include "PHOSReconstruction/Bunch.h" - -namespace o2 -{ - -namespace phos -{ - -/// \class Channel -/// \brief ALTRO channel representation -/// \ingroup PHOSreconstruction -/// -/// The channel contains information about -/// a hardware channel in the raw stream. Those -/// information are: -/// - Hardware address -/// - Size of the payload of all bunches in the channel -/// as total number of 10-bit words -/// - Channel status (good or bad) -/// In addition it contains the data of all bunches in the -/// raw stream. -/// -/// The hardware address itself encods -/// - Branch ID (bit 12) -/// - FEC ID (bits 7-10) -/// - ALTRO ID (bits 4-6) -/// - Channel ID (bits 0-3) -class Channel -{ - public: - /// \class HardwareAddressError - /// \brief Handling of uninitialized hardware addresses - class HardwareAddressError : public std::exception - { - public: - /// \brief Constructor - HardwareAddressError() = default; - - /// \brief Destructor - ~HardwareAddressError() noexcept override = default; - - /// \brief Access to error message - /// \return error message - const char* what() const noexcept override - { - return "Hardware address not initialized"; - } - }; - - /// \brief Dummy constructor - Channel() = default; - - /// \brief Constructor initializing hardware address and payload size - /// \param hardwareAddress Harware address - /// \param payloadSize Size of the payload - Channel(int32_t hardwareAddress, uint8_t payloadSize) : mHardwareAddress(hardwareAddress), - mPayloadSize(payloadSize), - mBunches() - { - } - - /// \brief Destructor - ~Channel() = default; - - /// \brief Check whether the channel is bad - /// \return true if the channel is bad, false otherwise - bool isBadChannel() const { return mBadChannel; } - - /// \brief Get the full hardware address - /// \return Hardware address - /// - /// The hardware address contains: - /// - Branch ID (bit 12) - /// - FEC ID (bits 7-10) - /// - ALTRO ID (bits 4-6) - /// - Channel ID (bits 0-3) - uint16_t getHardwareAddress() const { return mHardwareAddress; } - - /// \brief Get the size of the payload - /// \return Size of the payload as number of 10-bit samples (1/3rd words) - uint8_t getPayloadSize() const { return mPayloadSize; } - - /// \brief Get list of bunches in the channel - /// \return List of bunches - const std::vector& getBunches() const { return mBunches; } - - /// \brief Provide the branch index for the current hardware address - /// \return RCU branch index (0 or 1) - /// \throw HadrwareAddressError in case the hardware address is not initialized - int getBranchIndex() const; - - /// \brief Provide the front-end card index for the current hardware address - /// \return Front-end card index for the current hardware address - /// \throw HadrwareAddressError in case the hardware address is not initialized - int getFECIndex() const; - - /// \brief Provide the altro chip index for the current hardware address - /// \return Altro chip index for the current hardware address - /// \throw HadrwareAddressError in case the hardware address is not initialized - int getAltroIndex() const; - - /// \brief Provide the channel index for the current hardware address - /// \return Channel index for the current hardware address - /// \throw HadrwareAddressError in case the hardware address is not initialized - int getChannelIndex() const; - - /// \brief Add bunch to the channel - /// \param bunch Bunch to be added - /// - /// This function will copy the bunch information to the - /// object, which might be expensive. Better use the - /// function createBunch. - void addBunch(const Bunch& bunch) { mBunches.emplace_back(bunch); } - - /// \brief Set the hardware address - /// \param hardwareAddress Hardware address - void setHardwareAddress(uint16_t hardwareAddress) { mHardwareAddress = hardwareAddress; } - - /// \brief Set the size of the payload in number of 10-bit words - /// \param payloadSize Size of the payload - void setPayloadSize(uint8_t payloadSize) { mPayloadSize = payloadSize; } - - /// \brief Mark the channel status - /// \param badchannel Bad channel status (true if bad) - void setBadChannel(bool badchannel) { mBadChannel = badchannel; } - - /// \brief Create and initialize a new bunch and return reference to it - /// \param bunchlength Length of the bunch - /// \param starttime Start time of the bunch - Bunch& createBunch(uint8_t bunchlength, uint8_t starttime); - - private: - int32_t mHardwareAddress = -1; ///< Hardware address - uint8_t mPayloadSize = 0; ///< Payload size - bool mBadChannel; ///< Bad channel status - std::vector mBunches; ///< Bunches in channel; - - ClassDefNV(Channel, 1); -}; - -} // namespace phos -} // namespace o2 - -#endif \ No newline at end of file diff --git a/Detectors/PHOS/reconstruction/run/rawReaderFile.cxx b/Detectors/PHOS/reconstruction/run/rawReaderFile.cxx deleted file mode 100644 index e2a7d78f0207e..0000000000000 --- a/Detectors/PHOS/reconstruction/run/rawReaderFile.cxx +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// \file rawReaderFileNew.cxx -/// \author Markus Fasel , Oak Ridge National Laboratory - -#include -#include - -#include "DetectorsRaw/RawFileReader.h" -#include "PHOSReconstruction/AltroDecoder.h" -#include "PHOSReconstruction/RawReaderMemory.h" -#include "FairLogger.h" - -namespace bpo = boost::program_options; -//using namespace o2::phos; - -int main(int argc, char** argv) -{ - bpo::variables_map vm; - bpo::options_description opt_general("Usage:\n " + std::string(argv[0]) + - " \n" - " Tool will decode the DDLx data for PHOS 0\n" - "Commands / Options"); - bpo::options_description opt_hidden(""); - bpo::options_description opt_all; - bpo::positional_options_description opt_pos; - - try { - auto add_option = opt_general.add_options(); - add_option("help,h", "Print this help message"); - add_option("verbose,v", bpo::value()->default_value(0), "Select verbosity level [0 = no output]"); - add_option("version", "Print version information"); - add_option("input-file,i", bpo::value()->required(), "Specifies input file."); - add_option("debug,d", bpo::value()->default_value(0), "Select debug output level [0 = no debug output]"); - - opt_all.add(opt_general).add(opt_hidden); - bpo::store(bpo::command_line_parser(argc, argv).options(opt_all).positional(opt_pos).run(), vm); - - if (vm.count("help") || argc == 1) { - std::cout << opt_general << std::endl; - exit(0); - } - - if (vm.count("version")) { - //std::cout << GitInfo(); - exit(0); - } - - bpo::notify(vm); - } catch (bpo::error& e) { - std::cerr << "ERROR: " << e.what() << std::endl - << std::endl; - std::cerr << opt_general << std::endl; - exit(1); - } catch (std::exception& e) { - std::cerr << e.what() << ", application will now exit" << std::endl; - exit(2); - } - - auto rawfilename = vm["input-file"].as(); - - o2::raw::RawFileReader reader; - reader.setDefaultDataOrigin(o2::header::gDataOriginPHS); - reader.setDefaultDataDescription(o2::header::gDataDescriptionRawData); - reader.setDefaultReadoutCardType(o2::raw::RawFileReader::RORC); - reader.addFile(rawfilename); - reader.init(); - - while (1) { - int tfID = reader.getNextTFToRead(); - if (tfID >= reader.getNTimeFrames()) { - LOG(INFO) << "nothing left to read after " << tfID << " TFs read"; - break; - } - std::vector dataBuffer; // where to put extracted data - for (int il = 0; il < reader.getNLinks(); il++) { - auto& link = reader.getLink(il); - std::cout << "Decoding link " << il << std::endl; - - auto sz = link.getNextTFSize(); // size in bytes needed for the next TF of this link - dataBuffer.resize(sz); - link.readNextTF(dataBuffer.data()); - - // Parse - o2::phos::RawReaderMemory parser(dataBuffer); - while (parser.hasNext()) { - parser.next(); - // Exclude STU DDLs - if (o2::raw::RDHUtils::getFEEID(parser.getRawHeader()) >= 40) { - continue; - } - o2::phos::AltroDecoder decoder(parser); - decoder.decode(); - - auto& rcu = decoder.getRCUTrailer(); - auto& channellist = decoder.getChannels(); - std::cout << rcu << std::endl; - for (auto& chan : channellist) { - std::cout << "Hw address: " << chan.getHardwareAddress() << std::endl; - for (auto& bunch : chan.getBunches()) { - std::cout << "BunchLength: " << int(bunch.getBunchLength()) << std::endl; - auto adcs = bunch.getADC(); - int time = bunch.getStartTime(); - for (int i = adcs.size() - 1; i >= 0; i--) { - std::cout << "Timebin " << time << ", ADC " << adcs[i] << std::endl; - time--; - } - } - } - } - } - reader.setNextTFToRead(++tfID); - } -} diff --git a/Detectors/PHOS/reconstruction/src/AltroDecoder.cxx b/Detectors/PHOS/reconstruction/src/AltroDecoder.cxx index cfe9e3a325dea..fab3dd0d03581 100644 --- a/Detectors/PHOS/reconstruction/src/AltroDecoder.cxx +++ b/Detectors/PHOS/reconstruction/src/AltroDecoder.cxx @@ -10,6 +10,7 @@ #include #include #include "InfoLogger/InfoLogger.hxx" +#include "PHOSBase/PHOSSimParams.h" #include "PHOSReconstruction/AltroDecoder.h" #include "PHOSReconstruction/RawReaderMemory.h" #include "PHOSReconstruction/RawDecodingError.h" @@ -19,24 +20,29 @@ using namespace o2::phos; -AltroDecoder::AltroDecoder(RawReaderMemory& reader) : mRawReader(reader), - mRCUTrailer(), - mChannels(), - mChannelsInitialized(false) +AltroDecoderError::ErrorType_t AltroDecoder::decode(RawReaderMemory& rawreader, CaloRawFitter* rawFitter, + std::vector& currentCellContainer, std::vector& currentTRUContainer) { -} -AltroDecoderError::ErrorType_t AltroDecoder::decode() -{ + mOutputHWErrors.clear(); + mOutputFitChi.clear(); + + auto& header = rawreader.getRawHeader(); + mddl = o2::raw::RDHUtils::getFEEID(header); + + const std::vector& payloadwords = rawreader.getPayload().getPayloadWords(); + try { - readRCUTrailer(); + gsl::span tmp(payloadwords.data(), payloadwords.size()); + mRCUTrailer.constructFromRawPayload(tmp); } catch (RCUTrailer::Error& e) { LOG(ERROR) << "RCU trailer error" << (int)e.getErrorType(); return AltroDecoderError::RCU_TRAILER_ERROR; } + //TODO checkRCUTrailer(); try { - readChannels(); + readChannels(payloadwords, rawFitter, currentCellContainer, currentTRUContainer); } catch (AltroDecoderError::ErrorType_t e) { LOG(ERROR) << "Altro decoding error " << e; return e; @@ -44,27 +50,17 @@ AltroDecoderError::ErrorType_t AltroDecoder::decode() return AltroDecoderError::kOK; } -void AltroDecoder::readRCUTrailer() +void AltroDecoder::readChannels(const std::vector& buffer, CaloRawFitter* rawFitter, + std::vector& currentCellContainer, std::vector& currentTRUContainer) { - try { - auto payloadwords = mRawReader.getPayload().getPayloadWords(); - gsl::span tmp(payloadwords.data(), payloadwords.size()); - mRCUTrailer.constructFromRawPayload(tmp); - } catch (RCUTrailer::Error& e) { - throw e; - } -} - -void AltroDecoder::checkRCUTrailer() -{ -} - -void AltroDecoder::readChannels() -{ - mChannelsInitialized = false; - mChannels.clear(); int currentpos = 0; - auto& buffer = mRawReader.getPayload().getPayloadWords(); + + // if (err != AltroDecoderError::kOK) { + // //TODO handle severe errors + // //TODO: probably careful conversion of decoder errors to Fitter errors? + // char e = (char)err; + // mOutputHWErrors.emplace_back(ddl, 16, e); //assign general header errors to non-existing FEE 16 + // } int payloadend = buffer.size() - mRCUTrailer.getTrailerSize(); //mRCUTrailer.getPayloadSize() was not updated in case of merged pages. while (currentpos < payloadend) { @@ -76,47 +72,213 @@ void AltroDecoder::readChannels() } continue; } - // starting a new channel - mChannels.emplace_back(int(header.mHardwareAddress), int(header.mPayloadSize)); - auto& currentchannel = mChannels.back(); /// decode all words for channel - int numberofwords = (currentchannel.getPayloadSize() + 2) / 3; + int numberofwords = (header.mPayloadSize + 2) / 3; if (numberofwords > payloadend - currentpos) { LOG(ERROR) << "Channel payload " << numberofwords << " larger than left in total " << payloadend - currentpos; continue; } - std::vector bunchwords; - bunchwords.reserve(3 * numberofwords); - for (int iword = 0; iword < numberofwords; iword++) { + mBunchwords.clear(); + int isample = 0; + while (isample < header.mPayloadSize) { currentword = buffer[currentpos++]; if ((currentword >> 30) != 0) { - LOG(ERROR) << "Unexpected end of payload in altro channel payload! FEE=" << o2::raw::RDHUtils::getFEEID(mRawReader.getRawHeader()) - << ", Address=0x" << std::hex << currentchannel.getHardwareAddress() << ", word=0x" << currentword << std::dec; + LOG(ERROR) << "Unexpected end of payload in altro channel payload! FEE=" << mddl + << ", Address=0x" << std::hex << header.mHardwareAddress << ", word=0x" << currentword << std::dec; currentpos--; - continue; + break; + } + mBunchwords.push_back((currentword >> 20) & 0x3FF); + isample++; + if (isample < header.mPayloadSize) { + mBunchwords.push_back((currentword >> 10) & 0x3FF); + isample++; + if (isample < header.mPayloadSize) { + mBunchwords.push_back(currentword & 0x3FF); + isample++; + } else { + break; + } + } else { + break; + } + } + short absId; + Mapping::CaloFlag caloFlag; + if (!hwToAbsAddress(header.mHardwareAddress, absId, caloFlag)) { + // do not decode, skip to hext channel + continue; + } + + //Get time and amplitude + if (caloFlag != Mapping::kTRU) { //HighGain or LowGain + // decode bunches + int currentsample = 0; + while (currentsample < header.mPayloadSize) { + int bunchlength = mBunchwords[currentsample] - 2, // remove words for bunchlength and starttime + starttime = mBunchwords[currentsample + 1]; + //extract sample properties + CaloRawFitter::FitStatus fitResult = rawFitter->evaluate(gsl::span(&mBunchwords[currentsample + 2], std::min((unsigned long)bunchlength, mBunchwords.size() - currentsample - 2))); + currentsample += bunchlength + 2; + //set output cell + if (fitResult == CaloRawFitter::FitStatus::kNoTime) { + // mOutputHWErrors.emplace_back(ddl, fee, (char)5); //Time evaluation error occured + } + if (!rawFitter->isOverflow()) { //Overflow is will show wrong chi2 + short chiAddr = absId; + chiAddr |= caloFlag << 14; + mOutputFitChi.emplace_back(chiAddr); + mOutputFitChi.emplace_back(short(rawFitter->getChi2())); + } + + if (fitResult == CaloRawFitter::FitStatus::kOK || fitResult == CaloRawFitter::FitStatus::kNoTime) { + if (!mPedestalRun) { + if (caloFlag == Mapping::kHighGain && !rawFitter->isOverflow()) { + currentCellContainer.emplace_back(absId, rawFitter->getAmp(), + (rawFitter->getTime() + starttime) * o2::phos::PHOSSimParams::Instance().mTimeTick, (ChannelType_t)caloFlag); + } + if (caloFlag == Mapping::kLowGain) { + currentCellContainer.emplace_back(absId, rawFitter->getAmp(), + (rawFitter->getTime() + starttime) * o2::phos::PHOSSimParams::Instance().mTimeTick, (ChannelType_t)caloFlag); + } + } else { //pedestal, to store RMS, scale in by 1.e-7 to fit range + currentCellContainer.emplace_back(absId, rawFitter->getAmp(), 1.e-7 * rawFitter->getTime(), (ChannelType_t)caloFlag); + } + } //Successful fit + } //Bunched of a channel + } //HG or LG channel + else { //TRU channel + // Channels in TRU: + // There are 112 readout channels and 12 channels reserved for production flags: + // Channels 0-111: channel data readout + // Channels 112-123: production flags + if (Mapping::isTRUReadoutchannel(header.mHardwareAddress)) { + Mapping::Instance()->hwToAbsId(mddl, header.mHardwareAddress, absId, caloFlag); + readTRUDigits(absId, header.mPayloadSize, currentTRUContainer); + } else { + readTRUFlags(header.mHardwareAddress, header.mPayloadSize); } - bunchwords.push_back((currentword >> 20) & 0x3FF); - bunchwords.push_back((currentword >> 10) & 0x3FF); - bunchwords.push_back(currentword & 0x3FF); + } //TRU channel + } + + //Scan Flags and trigger cells and left only good + //if trigger cell exists and the trigger flag true -add it + bool is4x4Trigger = mTRUFlags[Mapping::NTRUReadoutChannels]; + for (auto rit = currentTRUContainer.rbegin(); rit != currentTRUContainer.rend(); rit++) { + if (mTRUFlags[rit->getTRUId()]) { //there is corresponding flag + if (is4x4Trigger) { + rit->setType(ChannelType_t::TRU4x4); + } else { + rit->setType(ChannelType_t::TRU2x2); + } + } else { //will be removed later + rit->setEnergy(0); } + } +} - // decode bunches - int currentsample = 0; - while (currentsample < currentchannel.getPayloadSize()) { - int bunchlength = bunchwords[currentsample] - 2, // remove words for bunchlength and starttime - starttime = bunchwords[currentsample + 1]; - auto& currentbunch = currentchannel.createBunch(bunchlength, starttime); - currentbunch.initFromRange(gsl::span(&bunchwords[currentsample + 2], std::min((unsigned long)bunchlength, bunchwords.size() - currentsample - 2))); - currentsample += bunchlength + 2; +bool AltroDecoder::hwToAbsAddress(short hwAddr, short& absId, Mapping::CaloFlag& caloFlag) +{ + //check hardware address and convert to absId and caloFlag + + if (mddl < 0 || mddl > o2::phos::Mapping::NDDL) { + return (char)4; + } + // short chan = hwAddr & 0xf; + short chip = hwAddr >> 4 & 0x7; + short fec = hwAddr >> 7 & 0xf; + short branch = hwAddr >> 11 & 0x1; + + short e2 = 0; + if (branch < 0 || branch > 1) { + e2 = 1; + } else { + if (fec < 0 || fec > 15) { + e2 = 2; + } else { + if (fec != 0 && (chip < 0 || chip > 4 || chip == 1)) { //Do not check for TRU (fec=0) + e2 = 3; + } } } - mChannelsInitialized = true; + + if (e2) { + mOutputHWErrors.emplace_back(mddl, fec, e2); + return false; + } + + //correct hw address, try to convert + Mapping::ErrorStatus s = Mapping::Instance()->hwToAbsId(mddl, hwAddr, absId, caloFlag); + if (s != Mapping::ErrorStatus::kOK) { + mOutputHWErrors.emplace_back(mddl, 15, (char)s); //use non-existing FEE 15 for general errors + return false; + } + return true; } -const std::vector& AltroDecoder::getChannels() const +void AltroDecoder::readTRUDigits(short absId, int payloadSize, std::vector& truContainer) const +{ + int currentsample = 0; + while (currentsample < payloadSize) { + int bunchlength = mBunchwords[currentsample] - 2, // remove words for bunchlength and starttime + timeBin = mBunchwords[currentsample + 1]; + currentsample += bunchlength + 2; + int istart = currentsample + 2; + int iend = std::min((unsigned long)bunchlength, mBunchwords.size() - currentsample - 2); + int smax = 0, tmax = 0; + // Loop over all the time steps in the signal + for (int i = iend - 1; i >= istart; i--) { + if (mBunchwords[i] > smax) { + smax = mBunchwords[i]; + tmax = timeBin; + } + timeBin++; + } + truContainer.emplace_back(absId + 14337 + 1, smax, tmax * 1.e-9, TRU2x2); //add TRU cells + } +} +void AltroDecoder::readTRUFlags(short hwAddress, int payloadSize) { - if (!mChannelsInitialized) { - throw AltroDecoderError::ErrorType_t::CHANNEL_ERROR; // "Channels not initizalized"); + // Production flags: + // Production flags are supplied in channels 112 - 123 + // Each of the channels is 10 bit wide + // The bits inside the channel (indexing starting from the first bit of channel 112) is as follows: + // Bits 0-111: Trigger flags for corresponding channel index + // If using 4x4 algorithm, only 91 first bits are used of these + // Bit 112: Marker for 4x4 algorithm (1 active, 0 not active) + // Bit 113: Marker for 2x2 algorithm (1 active, 0 not active) + // Bit 114: Global L0 OR of all patches in the TRU + + int currentsample = 0; + while (currentsample < payloadSize) { + int bunchlength = mBunchwords[currentsample] - 2, // remove words for bunchlength and starttime + timeBin = mBunchwords[currentsample + 1]; + currentsample += bunchlength + 2; + int istart = currentsample + 2; + int iend = std::min((unsigned long)bunchlength, mBunchwords.size() - currentsample - 2); + + for (int i = iend - 1; i >= istart; i--) { + short a = mBunchwords[i]; + // If bit 112 is 1, we are considering 4x4 algorithm + if (hwAddress == Mapping::TRUFinalProductionChannel) { + mTRUFlags[Mapping::NTRUReadoutChannels] = (a & (1 << 2)); // Check the bit number 112 + } + const int kWordLength = 10; // Length of one data word in TRU raw data + + // Assign the bits in the words to corresponding channels + for (Int_t bitIndex = 0; bitIndex < kWordLength; bitIndex++) { + // Find the correct channel number assuming that + // hwAddress 112 = bits 0-9 corresponding trigger flags in channels 0-9 + // hwAddress 113 = bits 10-19 corresponding trigger flags in channels 10-19 + // and so on + short channel; + if (hwAddress < 128) { + channel = (hwAddress - Mapping::NTRUBranchReadoutChannels) * kWordLength + bitIndex; + } else { + channel = 112 + (hwAddress - 2048 - Mapping::NTRUBranchReadoutChannels) * kWordLength + bitIndex; //branch 0 + } + mTRUFlags[channel] = mTRUFlags[channel] | (a & (1 << bitIndex)); + } // Bits in one word + } // Length of signal } - return mChannels; } diff --git a/Detectors/PHOS/reconstruction/src/Bunch.cxx b/Detectors/PHOS/reconstruction/src/Bunch.cxx deleted file mode 100644 index 9c0a483f5a0f0..0000000000000 --- a/Detectors/PHOS/reconstruction/src/Bunch.cxx +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. -#include "PHOSReconstruction/Bunch.h" - -using namespace o2::phos; - -void Bunch::initFromRange(gsl::span adcs) -{ - for (auto adcval : adcs) { - mADC.emplace_back(adcval); - } -} \ No newline at end of file diff --git a/Detectors/PHOS/reconstruction/src/CaloRawFitter.cxx b/Detectors/PHOS/reconstruction/src/CaloRawFitter.cxx index 05e091e5637e9..f9cf0c8f26b39 100644 --- a/Detectors/PHOS/reconstruction/src/CaloRawFitter.cxx +++ b/Detectors/PHOS/reconstruction/src/CaloRawFitter.cxx @@ -11,35 +11,32 @@ /// \file CaloRawFitter.cxx /// \author Dmitri Peresunko -#include "FairLogger.h" #include -#include "PHOSReconstruction/Bunch.h" #include "PHOSReconstruction/CaloRawFitter.h" #include "PHOSBase/PHOSSimParams.h" using namespace o2::phos; -CaloRawFitter::FitStatus CaloRawFitter::evaluate(const std::vector& bunchlist) +CaloRawFitter::CaloRawFitter() { - mAmp.clear(); // used as mean in this mode - mTime.clear(); // used as RMS in pedestal mode - mChi2.clear(); // used as mean in this mode + mSpikeThreshold = o2::phos::PHOSSimParams::Instance().mSpikeThreshold; + mBaseLine = o2::phos::PHOSSimParams::Instance().mBaseLine; + mPreSamples = o2::phos::PHOSSimParams::Instance().mPreSamples; +} + +CaloRawFitter::FitStatus CaloRawFitter::evaluate(gsl::span signal) +{ //Pedestal analysis mode if (mPedestalRun) { - int nPed = 0; + int nPed = signal.size(); float mean = 0.; float rms = 0.; - for (auto b : bunchlist) { - const std::vector& signal = b.getADC(); - for (std::vector::const_reverse_iterator it = signal.rbegin(); it != signal.rend(); ++it) { - uint16_t a = *it; - mean += a; - rms += a * a; - ++nPed; - } + for (auto a : signal) { + mean += a; + rms += a * a; } if (nPed > 0) { mean /= nPed; @@ -48,65 +45,43 @@ CaloRawFitter::FitStatus CaloRawFitter::evaluate(const std::vector& bunch rms = sqrt(rms); } } - mAmp.push_back(mean); - mTime.push_back(rms); - mOverflow.push_back(false); + mAmp = mean; + mTime = rms; // only in Pedestal mode! + mOverflow = false; mStatus = kOK; return kOK; } - for (auto b : bunchlist) { - // Extract amplitude and time using maximum and k-level methods - FitStatus s = evalKLevel(b); - mStatus = s; - - // If this is Low Gain channel or explicitely requested, fit sample with Gamma2 function - if (makeFit || (mLowGain && s == kOverflow)) { - FitStatus s2 = fitGamma2(b); - } - //TODO: should we have separate status: overflow & fit OK, and overflow & fit failed, etc? - } - return mStatus; + // Extract amplitude and time using maximum and k-level methods + return evalKLevel(signal); } -CaloRawFitter::FitStatus CaloRawFitter::evalKLevel(const Bunch& b) //const ushort *signal, int sigStart, int sigLength) +CaloRawFitter::FitStatus CaloRawFitter::evalKLevel(gsl::span signal) //const ushort *signal, int sigStart, int sigLength) { // Calculate signal parameters (energy, time, quality) from array of samples // Energy is a maximum sample minus pedestal 9 // Time is the first time bin // Signal overflows is there are at least 3 samples of the same amplitude above 900 - float amp = 0.; - float time = 0.; - bool overflow = false; - - int sigLength = b.getBunchLength(); + int sigLength = signal.size(); if (sigLength == 0) { return kEmptyBunch; } - const short kSpikeThreshold = o2::phos::PHOSSimParams::Instance().mSpikeThreshold; - const short kBaseLine = o2::phos::PHOSSimParams::Instance().mBaseLine; - const short kPreSamples = o2::phos::PHOSSimParams::Instance().mPreSamples; - float pedMean = 0; - float pedRMS = 0; int nPed = 0; mMaxSample = 0; int nMax = 0; //number of consequitive maximal samples bool spike = false; - - const std::vector& signal = b.getADC(); + mOverflow = false; int ap = -1, app = -1; //remember previous values to evaluate spikes - - for (std::vector::const_reverse_iterator it = signal.rbegin(); it != signal.rend(); ++it) { + for (auto it = signal.rbegin(); it != signal.rend(); ++it) { uint16_t a = *it; if (mPedSubtract) { - if (nPed < kPreSamples) { //inverse signal time order + if (nPed < mPreSamples) { //inverse signal time order nPed++; pedMean += a; - pedRMS += a * a; } } if (a > mMaxSample) { @@ -118,70 +93,61 @@ CaloRawFitter::FitStatus CaloRawFitter::evalKLevel(const Bunch& b) //const ushor } //check if there is a spike if (app >= 0 && ap >= 0) { - spike |= (2 * ap - (a + app) > 2 * kSpikeThreshold); + spike |= (2 * ap - (a + app) > 2 * mSpikeThreshold); } app = ap; ap = a; } - amp = (float)mMaxSample; + mAmp = (float)mMaxSample; if (spike) { - mAmp.push_back(amp); - mTime.push_back(b.getStartTime() - 2); - mOverflow.push_back(false); + mTime = -2; + mOverflow = false; return kSpike; } if (mMaxSample > 900 && nMax > 2) { - overflow = true; + mOverflow = true; } float pedestal = 0; if (mPedSubtract) { if (nPed > 0) { - pedRMS = (pedRMS - pedMean * pedMean / nPed) / nPed; - if (pedRMS > 0.) { - pedRMS = sqrt(pedRMS); - } - pedestal = pedMean / nPed; + pedMean /= nPed; } else { - mAmp.push_back(0); - mTime.push_back(b.getStartTime() - 2); - mOverflow.push_back(false); + mAmp = 0.; + mTime = -2; + mOverflow = false; return kBadPedestal; } + } else { + pedMean = 0.; } - amp -= pedestal; - if (amp < kBaseLine) { - amp = 0; + mAmp -= pedMean; + if (mAmp < mBaseLine) { + mAmp = 0; } //Evaluate time - time = b.getStartTime() - 2; + mTime = -2; const int nLine = 6; //Parameters of fitting const float eMinTOF = 10.; //Choosed from beam-test and cosmic analyis const float kAmp = 0.35; //Result slightly depends on them, so no getters // Avoid too low peak: - if (amp < eMinTOF) { - mAmp.push_back(amp); - mTime.push_back(time); - mOverflow.push_back(false); + if (mAmp < eMinTOF) { return kOK; //use estimated time } // Find index posK (kLevel is a level of "timestamp" point Tk): int posK = sigLength - 1; //last point before crossing k-level - float levelK = pedestal + kAmp * amp; + float levelK = pedestal + kAmp * mAmp; while (signal[posK] <= levelK && posK >= 0) { posK--; } posK++; if (posK == 0 || posK == sigLength - 1) { - mAmp.push_back(amp); - mTime.push_back(time); - mOverflow.push_back(false); return kNoTime; // } @@ -189,8 +155,8 @@ CaloRawFitter::FitStatus CaloRawFitter::evalKLevel(const Bunch& b) //const ushor int np = 0; int iup = posK - 1; int idn = posK; - Double_t sx = 0., sy = 0., sxx = 0., sxy = 0.; - Double_t x, y; + double sx = 0., sy = 0., sxx = 0., sxy = 0.; + double x, y; while (np < nLine) { //point above crossing point @@ -225,104 +191,25 @@ CaloRawFitter::FitStatus CaloRawFitter::evalKLevel(const Bunch& b) //const ushor } } - Double_t det = np * sxx - sx * sx; + double det = np * sxx - sx * sx; if (det == 0) { - mAmp.push_back(amp); - mTime.push_back(time); - mOverflow.push_back(false); return kNoTime; } if (np == 0) { - mAmp.push_back(amp); - mTime.push_back(time); - mOverflow.push_back(false); return kEmptyBunch; } - Double_t c1 = (np * sxy - sx * sy) / det; //slope - Double_t c0 = (sy - c1 * sx) / np; //offset + double c1 = (np * sxy - sx * sy) / det; //slope + double c0 = (sy - c1 * sx) / np; //offset if (c1 == 0) { - mAmp.push_back(amp); - mTime.push_back(time); - mOverflow.push_back(false); return kNoTime; } // Find where the line cross kLevel: - time += (levelK - c0) / c1 - 5.; //5: mean offset between k-Level and start times + mTime += (levelK - c0) / c1 - 5.; //5: mean offset between k-Level and start times - mAmp.push_back(amp); - mTime.push_back(time); - if (overflow) { - mOverflow.push_back(true); + if (mOverflow) { return kOverflow; } else { - mOverflow.push_back(false); return kOK; } } - -CaloRawFitter::FitStatus CaloRawFitter::fitGamma2(const Bunch& b) -{ - // Fit bunch with gamma2 function - // TODO!!! validate method - //initial values - float A = mAmp.back(); - float t0 = mTime.back(); - const std::vector& signal = b.getADC(); - uint16_t tsart = b.getStartTime(); - - const float alpha = 17.; //Decay time in units of 100ns //TODO!!! to be adjusted - const float kEpsilon = 1.e-6; //Accuracy of fit //TODO!!! to be adjusted - const int nIter = 10; //Maximal number of iterations //TODO!!! to be adjusted - - float chi2 = 0; - float derT = 0, derTprev = 0.; - float stepT = 0.1; - int iter = 0, i = 0; - do { - chi2 = 0.; - derTprev = derT; - derT = 0.; - i = 0; - float sA = 0., sB = 0.; - std::vector::const_reverse_iterator it = signal.rbegin(); - while (it != signal.rend()) { - uint16_t si = *it; - float ti = tsart + i - t0; - it++; - i++; - if (mOverflow.back() && si == mMaxSample) { //do not fit saturated samples - continue; - } - float fi = ti * ti * exp(-ti * alpha); - chi2 += (si - A * fi) * (si - A * fi); - sA += si * fi; - sB += fi * fi; - if (ti != 0.) { - derT += (2. / ti - alpha) * fi * (A * fi - si); - } - } - derT *= A; - //calculate time step and next time - if (derTprev != 0. && derT - derTprev != 0.) { - stepT = derT / (derT - derTprev) * stepT; - } - derTprev = derT; - t0 -= stepT; - if (sB > 0.) { - A = sA / sB; - } - } while (fabs(stepT) > kEpsilon && iter < nIter); // if time step is too small, stop - - if (iter >= nIter) { //Fit did not converge, keep old A and t0. - return kFitFailed; - } - - if (i > 0) { //chi2/NDF - chi2 /= i; - } - - mTime.back() = t0; - mAmp.back() = A; - return kOK; -} diff --git a/Detectors/PHOS/reconstruction/src/CaloRawFitterGS.cxx b/Detectors/PHOS/reconstruction/src/CaloRawFitterGS.cxx new file mode 100644 index 0000000000000..238c618f533a5 --- /dev/null +++ b/Detectors/PHOS/reconstruction/src/CaloRawFitterGS.cxx @@ -0,0 +1,314 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file CaloRawFitterGS.cxx +/// \author Dmitri Peresunko + +#include + +#include "PHOSReconstruction/CaloRawFitterGS.h" +#include "PHOSBase/PHOSSimParams.h" + +using namespace o2::phos; +CaloRawFitterGS::CaloRawFitterGS() : CaloRawFitter() +{ + mDecTime = o2::phos::PHOSSimParams::Instance().mSampleDecayTime; + mTimeAccuracy = o2::phos::PHOSSimParams::Instance().mSampleTimeFitAccuracy; + mAmpAccuracy = o2::phos::PHOSSimParams::Instance().mSampleAmpFitAccuracy; + init(); +} + +void CaloRawFitterGS::init() +{ + //prepare fitting arrays, once per lifetime + double k = o2::phos::PHOSSimParams::Instance().mSampleDecayTime; + ma0[0] = 1.; + mb0[0] = 1.; + mb1[0] = 0.; + mb2[0] = 0.; + mb3[0] = 0.; + mb4[0] = 0.; + for (int i = 1; i < NMAXSAMPLES; i++) { + double xi = k * i; + ma0[i] = exp(-xi); + mb0[i] = mb0[i - 1] + ma0[i]; + mb1[i] = 4 * mb1[i - 1] + ma0[i] * xi; + mb2[i] = 6 * mb2[i - 1] + ma0[i] * xi * xi; + mb3[i] = 4 * mb3[i - 1] + ma0[i] * xi * xi * xi; + mb4[i] = mb4[i - 1] + ma0[i] * xi * xi * xi * xi; + } +} + +CaloRawFitterGS::FitStatus CaloRawFitterGS::evaluate(gsl::span signal) +{ + + //Pedestal analysis mode + if (mPedestalRun) { + int nPed = signal.size(); + mAmp = 0.; + mTime = 0.; + for (auto a : signal) { + mAmp += a; + mTime += a * a; + } + if (nPed > 0) { + mAmp /= nPed; + mTime = mTime / nPed - mAmp * mAmp; + if (mTime > 0.) { + mTime = sqrt(mTime); + } + } + mOverflow = false; + mStatus = kOK; + return kOK; + } + + mStatus = kNotEvaluated; + // Extract amplitude and time + mStatus = evalFit(signal); + return mStatus; +} + +CaloRawFitterGS::FitStatus CaloRawFitterGS::evalFit(gsl::span signal) +{ + // Calculate signal parameters (energy, time, quality) from array of samples + // Energy is a maximum sample minus pedestal 9 + // Time is the first time bin + // Signal overflows is there are at least 3 samples of the same amplitude above 900 + + int sigLength = signal.size(); + if (sigLength == 0) { + return kEmptyBunch; + } + mAmp = 0.; + mTime = 0.; + mChi2 = 0.; + mOverflow = false; + FitStatus status = kNotEvaluated; + + //if pedestal should be subtracted first evaluate it + float pedMean = 0; + int nPed = 0; + if (mPedSubtract) { + //remember inverse time order + for (auto it = signal.rbegin(); (nPed < mPreSamples) && it != signal.rend(); ++it) { + nPed++; + pedMean += *it; + } + if (nPed > 0) { + pedMean /= nPed; + } + } + + float maxSample = 0.; //maximal sample value + int nMax = 0; //number of consequitive maximal samples + bool spike = false; //did we observe spike? + int ap = -1, app = -1; //remember previous values to evaluate spikes + double At = 0., Bt = 0., Ct = 0., y2 = 0.; + + int nSamples = signal.size(); + if (mPedSubtract) { + nSamples = -mPreSamples; + } + int firstS = nSamples - 1; + for (int i = 0; i < nSamples; i++) { + float a = signal[firstS - i] - pedMean; //remember inverse order of samples + float xi = i * mDecTime; + if (a > maxSample) { + mMaxSample = a; + nMax = 1; + } + if (a == maxSample) { + nMax++; + } + //check if there was a spike in previous step? + if (app >= 0 && ap >= 0) { + spike = (2 * ap - (a + app) > 2 * mSpikeThreshold); + } + if (spike) { + status = kSpike; + //Try to recover: subtract last point contribution and replace by average of "app" and "a" + float atmp = 0.5 * (app + a); + float xiprev = xi - mDecTime; + float ss = (atmp - ap) * ma0[i - 1]; + At += ss; //spike can not appear at 0-th bin + Bt += ss * xiprev; + Ct += ss * xiprev * xiprev; + y2 += (atmp * atmp - ap * ap); + } else { + app = ap; + ap = a; + } + //Check if in saturation + if (maxSample > 900 && nMax > 3) { + mOverflow = true; + } + + //to calculate time + float st = a * ma0[i]; + At += st; + Bt += st * xi; + Ct += st * xi * xi; + y2 += a * a; + //to calculate amplitude + } //Scanned full sample + + //calculate time, amp and chi2 + double polB = At - Bt; + double polC = Ct - 2. * Bt; + if (At == 0.) { + if (polB == 0.) { + mTime = 999.; + status = kFitFailed; + } else { + mTime = -polC / (2. * polB); + } + } else { + double d = polB * polB - At * polC; + if (d >= 0) { + mTime = (-polB - sqrt(d)) / (At * mDecTime); + } else { + mTime = 999.; + status = kFitFailed; + } + } + if (status == kFitFailed && !mOverflow) { //in case of overflow try to recover + mAmp = 0.; + mTime = 999.; + mChi2 = 999.; + return status; + } + + if (!mOverflow) { //normal sample, calculate amp and chi2 and return + double tt = mTime * mDecTime; + double tt2 = tt * tt; + double expT = exp(tt); + double nom = (At * tt2 - 2. * Bt * tt + Ct) * expT; // 1./(k*k) cancel with denom + int i = nSamples - 1; + double denom = (mb4[i] - tt * (mb3[i] - tt * (mb2[i] - tt * (mb1[i] - tt * mb0[i])))) * + expT * expT / (mDecTime * mDecTime); // 1/(k*k) cancel with nom + if (denom != 0) { + mAmp = nom / denom; + mChi2 = (y2 - (2. * (At * tt2 - 2. * tt * Bt + Ct) - mAmp * denom * expT) * mAmp * expT / (mDecTime * mDecTime)) / (i + 1); + } else { + mAmp = 0.; + status = kFitFailed; + } + return status; + } else { // overflow: try iterative procedure but for lowGain only + if (!mLowGain) { + mAmp = 0.; + mTime = 999.; + mChi2 = 999.; + return kOverflow; + } + + //Try to recalculate parameters replacing overflow/spike values by those expected from the sample shape + short nIter = 0; + double timeOld = mTime; + double ampOld = mAmp; + if (status == kFitFailed) { //could not calculate time, amp: set best guess + timeOld = 0; + ampOld = maxSample; + } + + //Iterative process, not more than NITERATIONS + short nMaxIter = o2::phos::PHOSSimParams::Instance().mNIterations; + for (short nIter = 0; nIter < nMaxIter; nIter++) { + ap = -1; + app = -1; //remember previous values to evaluate spikes + + double expT = exp(mDecTime * timeOld); + for (int i = 0; i < nSamples; i++) { + float a = signal[firstS - i] - pedMean; //remember inverse order of samples + float xi = i * mDecTime; + if (a == maxSample) { //overflow, replace with calculated + a = ampOld * ma0[i] * (timeOld - i) * (timeOld - i) * expT; + } + //check if there was a spike in prev step? + if (app >= 0 && ap >= 0) { + if (2 * ap - (a + app) > 2 * mSpikeThreshold) { + //Try to recover: subtract last point contribution and replace by average of "app" and "a" + float atmp = ampOld * ma0[i] * (timeOld - i + 1) * (timeOld - i + 1) * expT; //0.5*(app+a) ; + float xiprev = xi - mDecTime; + float s = (atmp - ap) * ma0[i - 1]; //spike can not appear at 0-th bin + At += s; + Bt += s * xiprev; + Ct += s * xiprev * xiprev; + y2 += (atmp * atmp - ap * ap); + } + } else { + app = ap; + ap = a; + } + + //to calculate time + float ss = a * ma0[i]; + At += ss; + Bt += ss * xi; + Ct += ss * xi * xi; + y2 += a * a; + } + //evaluate new time and amp + + double polB = At - Bt; + double polC = Ct - 2. * Bt; + if (At == 0.) { + if (polB == 0.) { + mTime = 999.; + status = kFitFailed; + } else { + mTime = -polC / (2. * polB); + } + } else { + double d = polB * polB - At * polC; + if (d >= 0) { + mTime = (-polB - sqrt(d)) / (At * mDecTime); + } else { + mTime = 999.; + status = kFitFailed; + } + } + if (status == kFitFailed) { //Can not improve, give up + mAmp = 0; + mTime = 999.; + mChi2 = 999.; + mOverflow = false; + return status; + } + double tt = mTime * mDecTime; + expT = exp(tt); + double nom = (At * tt * tt - 2. * Bt * tt + Ct) * expT; // 1./(k*k) cancel with denom + int i = nSamples - 1; + double denom = ((mb4[i] - tt * (mb3[i] - tt * (mb2[i] - tt * (mb1[i] - tt * mb0[i]))))) * + expT * expT / (mDecTime * mDecTime); // 1/(k*k) cancel with nom + if (denom != 0) { + mAmp = nom / denom; + mChi2 = (y2 - (2. * (At * tt * tt - 2. * tt * Bt + Ct) - mAmp * denom * expT) * mAmp * expT / (mDecTime * mDecTime)) / (i + 1); + } else { + mAmp = 0; + mTime = 999.; + mChi2 = 999.; + mOverflow = false; + return kFitFailed; + } + + //Check modification and quit if ready + if (abs(mTime - timeOld) < mTimeAccuracy && abs(mAmp - ampOld) < ampOld * mAmpAccuracy) { + break; + } + + timeOld = mTime; + ampOld = mAmp; + } + } + + return status; +} diff --git a/Detectors/PHOS/reconstruction/src/Channel.cxx b/Detectors/PHOS/reconstruction/src/Channel.cxx deleted file mode 100644 index 8bd68a7feff91..0000000000000 --- a/Detectors/PHOS/reconstruction/src/Channel.cxx +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. -#include "PHOSReconstruction/Channel.h" - -using namespace o2::phos; - -int Channel::getBranchIndex() const -{ - if (mHardwareAddress == -1) { - throw HardwareAddressError(); - } - return ((mHardwareAddress >> 11) & 0x1); -} - -int Channel::getFECIndex() const -{ - if (mHardwareAddress == -1) { - throw HardwareAddressError(); - } - return ((mHardwareAddress >> 7) & 0xF); -} - -Int_t Channel::getAltroIndex() const -{ - if (mHardwareAddress == -1) { - throw HardwareAddressError(); - } - return ((mHardwareAddress >> 4) & 0x7); -} - -Int_t Channel::getChannelIndex() const -{ - if (mHardwareAddress == -1) { - throw HardwareAddressError(); - } - return (mHardwareAddress & 0xF); -} - -Bunch& Channel::createBunch(uint8_t bunchlength, uint8_t starttime) -{ - mBunches.emplace_back(bunchlength, starttime); - return mBunches.back(); -} \ No newline at end of file diff --git a/Detectors/PHOS/reconstruction/src/PHOSReconstructionLinkDef.h b/Detectors/PHOS/reconstruction/src/PHOSReconstructionLinkDef.h index ca01087c64297..49fdbb1022c41 100644 --- a/Detectors/PHOS/reconstruction/src/PHOSReconstructionLinkDef.h +++ b/Detectors/PHOS/reconstruction/src/PHOSReconstructionLinkDef.h @@ -14,6 +14,8 @@ #pragma link off all classes; #pragma link off all functions; +#pragma link C++ class o2::phos::CaloRawFitter + ; +#pragma link C++ class o2::phos::CaloRawFitterGS + ; #pragma link C++ class o2::phos::Clusterer + ; #pragma link C++ class o2::phos::FullCluster + ; #pragma link C++ class std::vector < o2::phos::FullCluster> + ; diff --git a/Detectors/PHOS/simulation/include/PHOSSimulation/RawWriter.h b/Detectors/PHOS/simulation/include/PHOSSimulation/RawWriter.h index 9474c64ddb5a7..6b066d2726cad 100644 --- a/Detectors/PHOS/simulation/include/PHOSSimulation/RawWriter.h +++ b/Detectors/PHOS/simulation/include/PHOSSimulation/RawWriter.h @@ -23,7 +23,6 @@ #include "Rtypes.h" #include "DetectorsRaw/RawFileWriter.h" -#include "PHOSBase/Mapping.h" #include "DataFormatsPHOS/Digit.h" #include "DataFormatsPHOS/TriggerRecord.h" #include "PHOSCalib/CalibParams.h" @@ -89,7 +88,6 @@ class RawWriter private: FileFor_t mFileFor = FileFor_t::kFullDet; ///< Granularity of the output files std::string mOutputLocation = "./"; ///< Rawfile name - std::unique_ptr mMapping; ///< Mapping handler std::unique_ptr mCalibParams; ///< PHOS calibration gsl::span mDigits; ///< Digits input vector - must be in digitized format including the time response std::vector mSRUdata; ///< Internal helper of digits assigned to SRUs diff --git a/Detectors/PHOS/simulation/src/RawWriter.cxx b/Detectors/PHOS/simulation/src/RawWriter.cxx index e2caca5344f22..54d0930b14ac3 100644 --- a/Detectors/PHOS/simulation/src/RawWriter.cxx +++ b/Detectors/PHOS/simulation/src/RawWriter.cxx @@ -9,11 +9,13 @@ // or submit itself to any jurisdiction. #include "FairLogger.h" +#include #include #include #include #include "PHOSSimulation/RawWriter.h" +#include "PHOSBase/Mapping.h" #include "PHOSBase/PHOSSimParams.h" #include "CCDB/CcdbApi.h" @@ -26,15 +28,7 @@ void RawWriter::init() mRawWriter->setApplyCarryOverToLastPage(true); // initialize mapping - if (!mMapping) { - mMapping = std::make_unique(); - if (!mMapping) { - LOG(ERROR) << "Failed to initialize mapping"; - } - if (mMapping->setMapping() != o2::phos::Mapping::kOK) { - LOG(ERROR) << "Failed to construct mapping"; - } - } + Mapping::Instance(); for (auto iddl = 0; iddl < o2::phos::Mapping::NDDL; iddl++) { // For PHOS set @@ -47,7 +41,7 @@ void RawWriter::init() rawfilename += fmt::format("/phos_{:d}.raw", iddl); } short crorc, link; - mMapping->ddlToCrorcLink(iddl, crorc, link); + Mapping::ddlToCrorcLink(iddl, crorc, link); mRawWriter->registerLink(iddl, crorc, link, 0, rawfilename.data()); } @@ -108,7 +102,7 @@ bool RawWriter::processTrigger(const gsl::span digitsbranch, co short absId = dig.getTRUId(); short ddl, hwAddr; //get ddl and High Gain hw addresses - if (mMapping->absIdTohw(absId, Mapping::kTRU, ddl, hwAddr) != o2::phos::Mapping::kOK) { + if (Mapping::Instance()->absIdTohw(absId, Mapping::kTRU, ddl, hwAddr) != o2::phos::Mapping::kOK) { LOG(ERROR) << "Wrong truId=" << absId; } //Collect possible several digits (signal+pileup) into one map record @@ -123,7 +117,7 @@ bool RawWriter::processTrigger(const gsl::span digitsbranch, co short absId = dig.getAbsId(); short ddl, hwAddr; //get ddl and High Gain hw addresses - if (mMapping->absIdTohw(absId, Mapping::kHighGain, ddl, hwAddr) != o2::phos::Mapping::kOK) { + if (Mapping::Instance()->absIdTohw(absId, Mapping::kHighGain, ddl, hwAddr) != o2::phos::Mapping::kOK) { LOG(ERROR) << "Wrong AbsId" << absId; } @@ -137,7 +131,6 @@ bool RawWriter::processTrigger(const gsl::span digitsbranch, co } } } - // Create and fill DMA pages for each channel std::vector rawbunches; std::vector payload; @@ -151,7 +144,7 @@ bool RawWriter::processTrigger(const gsl::span digitsbranch, co for (auto ch = mTRUdata[ddl].mChannels.cbegin(); ch != mTRUdata[ddl].mChannels.cend(); ch++) { short truId = ch->first; short hwAddr, iddl; - if ((mMapping->absIdTohw(truId, Mapping::kTRU, iddl, hwAddr) != o2::phos::Mapping::kOK) || iddl != ddl) { + if ((Mapping::Instance()->absIdTohw(truId, Mapping::kTRU, iddl, hwAddr) != o2::phos::Mapping::kOK) || iddl != ddl) { LOG(ERROR) << "Wrong truId=" << truId << ", iDDL=" << iddl << "!=" << ddl; } rawbunchesTRU.clear(); @@ -177,7 +170,6 @@ bool RawWriter::processTrigger(const gsl::span digitsbranch, co for (int iword = 0; iword < sizeof(ChannelHeader) / sizeof(char); iword++) { payload.emplace_back(chanheadwords[iword]); } - char* channelwords = reinterpret_cast(encodedbunches.data()); for (auto iword = 0; iword < encodedbunches.size() * sizeof(int) / sizeof(char); iword++) { payload.emplace_back(channelwords[iword]); @@ -243,7 +235,7 @@ bool RawWriter::processTrigger(const gsl::span digitsbranch, co createRawBunches(ch->first, ch->second, rawbunchesHG, rawbunchesLG, isLGfilled); short hwAddrHG; //High gain always filled - if (mMapping->absIdTohw(ch->first, Mapping::kHighGain, ddl, hwAddrHG) != o2::phos::Mapping::kOK) { + if (Mapping::Instance()->absIdTohw(ch->first, Mapping::kHighGain, ddl, hwAddrHG) != o2::phos::Mapping::kOK) { LOG(ERROR) << "Wrong AbsId" << ch->first; } rawbunches.clear(); @@ -274,7 +266,7 @@ bool RawWriter::processTrigger(const gsl::span digitsbranch, co if (isLGfilled) { //fill both HighGain, and LowGain channels in case of saturation short hwAddrLG; //High gain always filled - if (mMapping->absIdTohw(ch->first, 1, ddl, hwAddrLG) != o2::phos::Mapping::kOK) { + if (Mapping::Instance()->absIdTohw(ch->first, 1, ddl, hwAddrLG) != o2::phos::Mapping::kOK) { LOG(ERROR) << "Wrong AbsId" << ch->first; } @@ -314,7 +306,7 @@ bool RawWriter::processTrigger(const gsl::span digitsbranch, co LOG(DEBUG1) << "Adding payload with size " << payload.size() << " (" << payload.size() / 4 << " ALTRO words)"; short crorc, link; - mMapping->ddlToCrorcLink(ddl, crorc, link); + Mapping::ddlToCrorcLink(ddl, crorc, link); mRawWriter->addData(ddl, crorc, link, 0, trg.getBCData(), payload); } return true; @@ -420,10 +412,10 @@ void RawWriter::fillGamma2(float amp, float time, short* samples) float alpha = o2::phos::PHOSSimParams::Instance().mSampleDecayTime; amp += 0.5; //rounding err for (int i = 0; i < kNPHOSSAMPLES; i++) { - if (i - o2::phos::PHOSSimParams::Instance().mPreSamples < time) { + if (i < time) { continue; } - float x = alpha * (i - o2::phos::PHOSSimParams::Instance().mPreSamples - time); + float x = alpha * (i - time); float y = 0.25 * amp * x * x * std::exp(2. - x); //0.25*exp(-2) normalization to unity samples[i] += short(y); } diff --git a/Detectors/PHOS/workflow/include/PHOSWorkflow/RawToCellConverterSpec.h b/Detectors/PHOS/workflow/include/PHOSWorkflow/RawToCellConverterSpec.h index 6246c89144f51..5ff4ee995c0a1 100644 --- a/Detectors/PHOS/workflow/include/PHOSWorkflow/RawToCellConverterSpec.h +++ b/Detectors/PHOS/workflow/include/PHOSWorkflow/RawToCellConverterSpec.h @@ -16,6 +16,7 @@ #include "DataFormatsPHOS/TriggerRecord.h" #include "PHOSBase/Mapping.h" #include "PHOSCalib/CalibParams.h" +#include "PHOSReconstruction/AltroDecoder.h" #include "PHOSReconstruction/CaloRawFitter.h" #include "PHOSReconstruction/RawReaderError.h" @@ -58,18 +59,16 @@ class RawToCellConverterSpec : public framework::Task void run(framework::ProcessingContext& ctx) final; protected: - /// \brief simple check of HW address - char CheckHWAddress(short ddl, short hwAddress, short& fee); - void readTRUDigit(const std::vector& bunchlist, short absId, short timebin, std::shared_ptr>& currentTRUContainer); - void readTRUFlags(short hwAddress, const std::vector& bunchlist, std::shared_ptr>& currentTRUFlags); - private: bool mFillChi2 = false; ///< Fill output with quality of samples bool mCombineGHLG = true; ///< Combine or not HG and LG channels (def: combine, LED runs: not combine) bool mPedestalRun = false; ///< Analyze pedestal run (calculate pedestal mean and RMS) - std::unique_ptr mMapping; ///< Mapping + int mLastSize = 0; ///< size of last send list of cells to reserve same in next bunch std::unique_ptr mCalibParams; ///! mDecoder; ///! mRawFitter; ///!, 14> mTmpCells; ///< Temporary cells storage to all 14 DLL + std::array, 14> mTmpTRU; ///< Temporary tru cells storage to all 14 DLL std::vector mOutputCells; ///< Container with output cells std::vector mOutputTriggerRecords; ///< Container with output cells std::vector mOutputHWErrors; ///< Errors occured in reading data diff --git a/Detectors/PHOS/workflow/src/RawToCellConverterSpec.cxx b/Detectors/PHOS/workflow/src/RawToCellConverterSpec.cxx index e62447048268d..c2fca6036bf61 100644 --- a/Detectors/PHOS/workflow/src/RawToCellConverterSpec.cxx +++ b/Detectors/PHOS/workflow/src/RawToCellConverterSpec.cxx @@ -20,9 +20,8 @@ #include "CCDB/CcdbApi.h" #include "PHOSBase/Mapping.h" #include "PHOSBase/PHOSSimParams.h" -#include "PHOSReconstruction/Bunch.h" #include "PHOSReconstruction/CaloRawFitter.h" -#include "PHOSReconstruction/AltroDecoder.h" +#include "PHOSReconstruction/CaloRawFitterGS.h" #include "PHOSReconstruction/RawDecodingError.h" #include "PHOSWorkflow/RawToCellConverterSpec.h" @@ -33,15 +32,7 @@ void RawToCellConverterSpec::init(framework::InitContext& ctx) LOG(DEBUG) << "Initialize converter "; auto path = ctx.options().get("mappingpath"); - if (!mMapping) { - mMapping = std::unique_ptr(new o2::phos::Mapping(path)); - if (!mMapping) { - LOG(ERROR) << "Failed to initialize mapping"; - } - if (mMapping->setMapping() != o2::phos::Mapping::kOK) { - LOG(ERROR) << "Failed to construct mapping"; - } - } + Mapping::Instance(path); if (!mCalibParams) { if (o2::phos::PHOSSimParams::Instance().mCCDBPath.compare("localtest") == 0) { @@ -68,9 +59,10 @@ void RawToCellConverterSpec::init(framework::InitContext& ctx) if (fitmethod == "default") { LOG(INFO) << "Using default raw fitter"; mRawFitter = std::unique_ptr(new o2::phos::CaloRawFitter); - //TODO: Configure parameters of fitter from options - // mRawFitter->setAmpCut(mNoiseThreshold); - // mRawFitter->setL1Phase(0.); + } + if (fitmethod == "semigaus") { + LOG(INFO) << "Using SemiGauss raw fitter"; + mRawFitter = std::unique_ptr(new o2::phos::CaloRawFitterGS); } mFillChi2 = (ctx.options().get("fillchi2").compare("on") == 0); @@ -78,25 +70,31 @@ void RawToCellConverterSpec::init(framework::InitContext& ctx) LOG(INFO) << "Fit quality output will be filled"; } - mCombineGHLG = (ctx.options().get("keepHGLG").compare("on") != 0); - if (!mCombineGHLG) { - LOG(INFO) << "Both HighGain and LowGain will be kept"; - } + mDecoder = std::make_unique(); mPedestalRun = (ctx.options().get("pedestal").find("on") != std::string::npos); if (mPedestalRun) { mRawFitter->setPedestal(); + mDecoder->setPedestalRun(); //sets also keeping both HG and LG channels LOG(INFO) << "Pedestal run will be processed"; } + + mCombineGHLG = (ctx.options().get("keepHGLG").compare("on") != 0); + if (!mCombineGHLG) { + mDecoder->setCombineHGLG(false); + LOG(INFO) << "Both HighGain and LowGain will be kept"; + } } void RawToCellConverterSpec::run(framework::ProcessingContext& ctx) { // Cache cells from bunch crossings as the component reads timeframes from many links consecutively - std::map>> cellBuffer; // Internal cell buffer/ - std::map>> truBuffer; // trigger cell buffer/ - std::map>> truFlagBuffer; // - int firstEntry = 0; + std::vector irList; + std::vector> cellTRURanges; // start/end points for cells in mTmpCells[ddl] arrays + for (int iddl = 14; iddl--;) { + mTmpCells[iddl].clear(); + mTmpTRU[iddl].clear(); + } mOutputHWErrors.clear(); if (mFillChi2) { mOutputFitChi.clear(); @@ -128,130 +126,68 @@ void RawToCellConverterSpec::run(framework::ProcessingContext& ctx) auto triggerOrbit = o2::raw::RDHUtils::getTriggerOrbit(header); auto ddl = o2::raw::RDHUtils::getFEEID(header); - o2::InteractionRecord currentIR(triggerBC, triggerOrbit); - std::shared_ptr> currentCellContainer; - auto found = cellBuffer.find(currentIR); - if (found == cellBuffer.end()) { - currentCellContainer = std::make_shared>(); - cellBuffer[currentIR] = currentCellContainer; - } else { - currentCellContainer = found->second; - } - std::shared_ptr> currentTRUContainer; - auto found2 = truBuffer.find(currentIR); - if (found2 == truBuffer.end()) { - currentTRUContainer = std::make_shared>(); - truBuffer[currentIR] = currentTRUContainer; - } else { - currentTRUContainer = found2->second; - } - std::shared_ptr> currentTRUFlags; - auto found3 = truFlagBuffer.find(currentIR); - if (found3 == truFlagBuffer.end()) { - currentTRUFlags = std::make_shared>(); - truFlagBuffer[currentIR] = currentTRUFlags; - } else { - currentTRUFlags = found3->second; - } - - if (ddl > o2::phos::Mapping::NDDL) { //only 14 correct DDLs + if (ddl > o2::phos::Mapping::NDDL || ddl < 0) { //only 14 correct DDLs LOG(ERROR) << "DDL=" << ddl; mOutputHWErrors.emplace_back(15, 16, char(ddl)); //Add non-existing DDL as DDL 15 continue; //skip STU ddl } - // use the altro decoder to decode the raw data, and extract the RCU trailer - o2::phos::AltroDecoder decoder(rawreader); - AltroDecoderError::ErrorType_t err = decoder.decode(); - if (err != AltroDecoderError::kOK) { - //TODO handle severe errors - //TODO: probably careful conversion of decoder errors to Fitter errors? - char e = (char)err; - mOutputHWErrors.emplace_back(ddl, 16, e); //assign general header errors to non-existing FEE 16 + o2::InteractionRecord currentIR(triggerBC, triggerOrbit); + auto irIter = irList.rbegin(); + auto rangeIter = cellTRURanges.rbegin(); + while (irIter != irList.rend() && *irIter != currentIR) { + irIter++; + rangeIter++; } - auto& rcu = decoder.getRCUTrailer(); - auto& channellist = decoder.getChannels(); - // Loop over all the channels for this RCU - for (auto& chan : channellist) { - short absId; - Mapping::CaloFlag caloFlag; - short fee; - char e2 = CheckHWAddress(ddl, chan.getHardwareAddress(), fee); - if (e2) { - mOutputHWErrors.emplace_back(ddl, fee, e2); - continue; - } - Mapping::ErrorStatus s = mMapping->hwToAbsId(ddl, chan.getHardwareAddress(), absId, caloFlag); - if (s != Mapping::ErrorStatus::kOK) { - mOutputHWErrors.emplace_back(ddl, 15, (char)s); //use non-existing FEE 15 for general errors - continue; - } - if (caloFlag != Mapping::kTRU) { //HighGain or LowGain - CaloRawFitter::FitStatus fitResults = mRawFitter->evaluate(chan.getBunches()); - if (fitResults == CaloRawFitter::FitStatus::kNoTime) { - mOutputHWErrors.emplace_back(ddl, fee, (char)5); //Time evaluation error occured - } - if (mFillChi2) { - for (int is = 0; is < mRawFitter->getNsamples(); is++) { - if (!mRawFitter->isOverflow(is)) { //Overflow is will show wrong chi2 - short chiAddr = absId; - chiAddr |= caloFlag << 14; - mOutputFitChi.emplace_back(chiAddr); - mOutputFitChi.emplace_back(short(mRawFitter->getChi2(is))); - } - } - } - if (fitResults == CaloRawFitter::FitStatus::kOK || fitResults == CaloRawFitter::FitStatus::kNoTime) { - //TODO: which results should be accepted? full configurable list - if (!mPedestalRun) { - for (int is = 0; is < mRawFitter->getNsamples(); is++) { - if (caloFlag == Mapping::kHighGain && !mRawFitter->isOverflow(is)) { - currentCellContainer->emplace_back(absId, mRawFitter->getAmp(is), - mRawFitter->getTime(is) * o2::phos::PHOSSimParams::Instance().mTimeTick, (ChannelType_t)caloFlag); - } - if (caloFlag == Mapping::kLowGain) { - currentCellContainer->emplace_back(absId, mRawFitter->getAmp(is), - mRawFitter->getTime(is) * o2::phos::PHOSSimParams::Instance().mTimeTick, (ChannelType_t)caloFlag); - } - } - } else { //pedestal, to store RMS, scale in by 1.e-7 to fit range - currentCellContainer->emplace_back(absId, mRawFitter->getAmp(0), 1.e-7 * mRawFitter->getTime(0), (ChannelType_t)caloFlag); - } - } - } else { //decode TRU digits - // Channels in TRU: - // There are 112 readout channels and 12 channels reserved for production flags: - // Channels 0-111: channel data readout - // Channels 112-123: production flags - if (Mapping::isTRUReadoutchannel(chan.getHardwareAddress())) { - mMapping->hwToAbsId(ddl, chan.getHardwareAddress(), absId, caloFlag); - short timeBin = chan.getBunches().back().getStartTime(); // Find the time bin of the first time step - readTRUDigit(chan.getBunches(), absId, timeBin, currentTRUContainer); - } else { - readTRUFlags(chan.getHardwareAddress(), chan.getBunches(), currentTRUFlags); - } - } + if (irIter != irList.rend()) { //found + (*rangeIter)[2 * ddl] = mTmpCells[ddl].size(); //start of the cell list + (*rangeIter)[28 + 2 * ddl] = mTmpTRU[ddl].size(); //start of the tru list + } else { //create new entry + irList.push_back(currentIR); + cellTRURanges.emplace_back(); + cellTRURanges.back().fill(0); + cellTRURanges.back()[2 * ddl] = mTmpCells[ddl].size(); + cellTRURanges.back()[28 + 2 * ddl] = mTmpTRU[ddl].size(); + rangeIter = cellTRURanges.rbegin(); } + std::vector& currentCellContainer = mTmpCells[ddl]; + std::vector& currentTRUContainer = mTmpTRU[ddl]; + + // use the altro decoder to decode the raw data, and extract the RCU trailer + mDecoder->decode(rawreader, mRawFitter.get(), currentCellContainer, currentTRUContainer); + // Sort cells according to cell ID + (*rangeIter)[2 * ddl + 1] = currentCellContainer.size(); + auto itBegin = currentCellContainer.begin() + (*rangeIter)[2 * ddl]; + std::sort(itBegin, currentCellContainer.end(), [](o2::phos::Cell& lhs, o2::phos::Cell& rhs) { return lhs.getAbsId() < rhs.getAbsId(); }); + auto itTrBegin = currentTRUContainer.begin() + (*rangeIter)[28 + 2 * ddl]; + (*rangeIter)[28 + 2 * ddl + 1] = currentTRUContainer.size(); + std::sort(itTrBegin, currentTRUContainer.end(), [](o2::phos::Cell& lhs, o2::phos::Cell& rhs) { return lhs.getAbsId() < rhs.getAbsId(); }); } //RawReader::hasNext } // Loop over BCs, sort cells with increasing cell ID and write to output containers mOutputCells.clear(); + if (mLastSize > 0) { + mOutputCells.reserve(mLastSize); + } mOutputTriggerRecords.clear(); - for (auto [bc, cells] : cellBuffer) { + auto rangeIter = cellTRURanges.begin(); + for (auto irIter = irList.begin(); irIter != irList.end(); ++irIter, ++rangeIter) { + // find all DDLs for current BC + // sort separately then concatenate int prevCellSize = mOutputCells.size(); - if (cells->size()) { - // Sort cells according to cell ID - std::sort(cells->begin(), cells->end(), [](o2::phos::Cell& lhs, o2::phos::Cell& rhs) { return lhs.getAbsId() < rhs.getAbsId(); }); + for (int iddl = 0; iddl < 14; iddl++) { + auto cbegin = mTmpCells[iddl].begin() + (*rangeIter)[2 * iddl]; + auto cend = mTmpCells[iddl].begin() + (*rangeIter)[2 * iddl + 1]; if (mCombineGHLG && !mPedestalRun) { // combine for normal data, do not combine e.g. for LED run and pedestal //Combine HG and LG sells //Should be next to each other after sorting - auto it1 = cells->begin(); - auto it2 = cells->begin(); + auto it1 = cbegin; + auto it2 = cbegin; it2++; - while (it1 != cells->end()) { - if (it2 != cells->end()) { + while (it1 != cend) { + if (it2 != cend) { if ((*it1).getAbsId() == (*it2).getAbsId()) { //HG and LG channels, if both, copy only HG as more precise if ((*it1).getType() == o2::phos::HIGH_GAIN) { mOutputCells.push_back(*it1); @@ -270,35 +206,24 @@ void RawToCellConverterSpec::run(framework::ProcessingContext& ctx) ++it2; } } else { - for (auto& cell : *cells) { - mOutputCells.push_back(cell); - } + mOutputCells.insert(mOutputCells.end(), cbegin, cend); } - } - - //Add trigger cells - //if trigger cell exists and the trigger flag true -add it - auto found2 = truBuffer.find(bc); - auto found3 = truFlagBuffer.find(bc); - if (found2 != truBuffer.end() && found3 != truFlagBuffer.end()) { - auto currentTRUContainer = found2->second; - auto currentTRUFlags = found3->second; - bool is4x4Trigger = (*currentTRUFlags)[Mapping::NTRUReadoutChannels]; - for (Cell c : *currentTRUContainer) { - if ((*currentTRUFlags)[c.getTRUId()]) { //there is corresponding flag - if (is4x4Trigger) { - c.setType(ChannelType_t::TRU4x4); - } else { - c.setType(ChannelType_t::TRU2x2); - } - mOutputCells.push_back(c); + } //all readout cells + for (int iddl = 0; iddl < 14; iddl++) { + auto trbegin = mTmpTRU[iddl].begin() + (*rangeIter)[28 + 2 * iddl]; + auto trend = mTmpTRU[iddl].begin() + (*rangeIter)[28 + 2 * iddl + 1]; + //Move trigger cells + for (auto tri = trbegin; tri != trend; tri++) { + if (tri->getEnergy() > 0) { + mOutputCells.emplace_back(tri->getAbsId(), tri->getEnergy(), tri->getTime(), tri->getType()); } } } - mOutputTriggerRecords.emplace_back(bc, prevCellSize, mOutputCells.size() - prevCellSize); + mOutputTriggerRecords.emplace_back(*irIter, prevCellSize, mOutputCells.size() - prevCellSize); } - cellBuffer.clear(); + + mLastSize = 1.1 * mOutputCells.size(); LOG(DEBUG) << "[PHOSRawToCellConverter - run] Writing " << mOutputCells.size() << " cells ..."; ctx.outputs().snapshot(o2::framework::Output{"PHS", "CELLS", 0, o2::framework::Lifetime::Timeframe}, mOutputCells); @@ -308,90 +233,6 @@ void RawToCellConverterSpec::run(framework::ProcessingContext& ctx) ctx.outputs().snapshot(o2::framework::Output{"PHS", "CELLFITQA", 0, o2::framework::Lifetime::Timeframe}, mOutputFitChi); } } -void RawToCellConverterSpec::readTRUDigit(const std::vector& bunchlist, short absId, short timebin, std::shared_ptr>& currentTRUContainer) -{ - - // TRU Channel data: - // The channel data is read one channel at a time - int smax = 0, tmax = 0; - for (auto b : bunchlist) { - short timeBin = b.getStartTime(); - const std::vector& signal = b.getADC(); - // Loop over all the time steps in the signal - for (std::vector::const_reverse_iterator it = signal.rbegin(); it != signal.rend(); ++it) { - if (*it > smax) { - smax = *it; - tmax = timeBin; - } - timeBin++; - } - } - currentTRUContainer->emplace_back(absId + 14337 + 1, smax, tmax * 1.e-9, TRU2x2); //add TRU cells -} -void RawToCellConverterSpec::readTRUFlags(short hwAddress, const std::vector& bunchlist, std::shared_ptr>& currentTRUFlags) -{ - // Production flags: - // Production flags are supplied in channels 112 - 123 - // Each of the channels is 10 bit wide - // The bits inside the channel (indexing starting from the first bit of channel 112) is as follows: - // Bits 0-111: Trigger flags for corresponding channel index - // If using 4x4 algorithm, only 91 first bits are used of these - // Bit 112: Marker for 4x4 algorithm (1 active, 0 not active) - // Bit 113: Marker for 2x2 algorithm (1 active, 0 not active) - // Bit 114: Global L0 OR of all patches in the TRU - - for (auto b : bunchlist) { - short timeBin = b.getStartTime(); - const std::vector& signal = b.getADC(); - // Loop over all the time steps in the signal - for (std::vector::const_reverse_iterator it = signal.rbegin(); it != signal.rend(); it++, timeBin++) { - - // If bit 112 is 1, we are considering 4x4 algorithm - if (hwAddress == Mapping::TRUFinalProductionChannel) { - (*currentTRUFlags)[Mapping::NTRUReadoutChannels] = (*it & (1 << 2)); // Check the bit number 112 - } - const int kWordLength = 10; // Length of one data word in TRU raw data - - // Assign the bits in the words to corresponding channels - for (Int_t bitIndex = 0; bitIndex < kWordLength; bitIndex++) { - // Find the correct channel number assuming that - // hwAddress 112 = bits 0-9 corresponding trigger flags in channels 0-9 - // hwAddress 113 = bits 10-19 corresponding trigger flags in channels 10-19 - // and so on - short channel; - if (hwAddress < 128) { - channel = (hwAddress - Mapping::NTRUBranchReadoutChannels) * kWordLength + bitIndex; - } else { - channel = 112 + (hwAddress - 2048 - Mapping::NTRUBranchReadoutChannels) * kWordLength + bitIndex; //branch 0 - } - (*currentTRUFlags)[channel] = (*currentTRUFlags)[channel] | (*it & (1 << bitIndex)); - } // Bits in one word - } // Length of signal - } -} - -char RawToCellConverterSpec::CheckHWAddress(short ddl, short hwAddr, short& fee) -{ - - if (ddl < 0 || ddl > o2::phos::Mapping::NDDL) { - return (char)4; - } - // short chan = hwAddr & 0xf; - short chip = hwAddr >> 4 & 0x7; - short fec = hwAddr >> 7 & 0xf; - short branch = hwAddr >> 11 & 0x1; - - if (branch < 0 || branch > 1) { - return (char)1; - } - if (fec < 0 || fec > 15) { - return (char)2; - } - if (fec != 0 && (chip < 0 || chip > 4 || chip == 1)) { //Do not check for TRU (fec=0) - return (char)3; - } - return (char)0; -} o2::framework::DataProcessorSpec o2::phos::reco_workflow::getRawToCellConverterSpec() { @@ -409,7 +250,7 @@ o2::framework::DataProcessorSpec o2::phos::reco_workflow::getRawToCellConverterS outputs, o2::framework::adaptFromTask(), o2::framework::Options{ - {"fitmethod", o2::framework::VariantType::String, "default", {"Fit method (default or fast)"}}, + {"fitmethod", o2::framework::VariantType::String, "default", {"Fit method (default or semigaus)"}}, {"mappingpath", o2::framework::VariantType::String, "", {"Path to mapping files"}}, {"fillchi2", o2::framework::VariantType::String, "off", {"Fill sample qualities on/off"}}, {"keepHGLG", o2::framework::VariantType::String, "off", {"keep HighGain and Low Gain signals on/off"}}, From 44a04a100c7041dd9a2ac30632817f69ef34ebdf Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 30 Apr 2021 15:34:47 +0200 Subject: [PATCH 349/770] GPU: Workaround to keep the code compiled by AliRoot, be C++11 and CINT compatible --- GPU/GPUTracking/Base/GPUParam.h | 4 ++-- GPU/GPUTracking/DataTypes/GPUDataTypes.h | 2 +- .../TRDTracking/GPUTRDTrackerKernels.cxx | 17 ++++++++++++++--- .../TRDTracking/GPUTRDTrackerKernels.h | 4 ---- GPU/GPUTracking/utils/strtag.h | 5 ++++- 5 files changed, 21 insertions(+), 11 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUParam.h b/GPU/GPUTracking/Base/GPUParam.h index 984fd66258e35..24168186d401e 100644 --- a/GPU/GPUTracking/Base/GPUParam.h +++ b/GPU/GPUTracking/Base/GPUParam.h @@ -21,7 +21,7 @@ #include "GPUTPCGeometry.h" #include "GPUTPCGMPolynomialField.h" -#ifndef GPUCA_GPUCODE +#if !defined(GPUCA_GPUCODE) && defined(GPUCA_NOCOMPAT) namespace o2::base { template @@ -63,7 +63,7 @@ struct GPUParam_t { }; } // namespace internal -#if !(defined(__CINT__) || defined(__ROOTCINT__)) || defined(__CLING__) // Hide from ROOT 5 CINT since it triggers a CINT but +#if !(defined(__CINT__) || defined(__ROOTCINT__)) || defined(__CLING__) // Hide from ROOT 5 CINT MEM_CLASS_PRE() struct GPUParam : public internal::GPUParam_t { diff --git a/GPU/GPUTracking/DataTypes/GPUDataTypes.h b/GPU/GPUTracking/DataTypes/GPUDataTypes.h index cd0b38095dcee..01a5f82054607 100644 --- a/GPU/GPUTracking/DataTypes/GPUDataTypes.h +++ b/GPU/GPUTracking/DataTypes/GPUDataTypes.h @@ -49,7 +49,7 @@ namespace o2 class MCCompLabel; namespace base { -template +template class PropagatorImpl; class MatLayerCylSet; } // namespace base diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTrackerKernels.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTrackerKernels.cxx index 52456089722cc..10b96b3bec3c3 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTrackerKernels.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTrackerKernels.cxx @@ -20,17 +20,26 @@ using namespace GPUCA_NAMESPACE::gpu; +#ifdef HAVE_O2HEADERS +template +GPUd() auto& getTracker(GPUTRDTrackerKernels::processorType& processors); template <> -GPUdi() auto& GPUTRDTrackerKernels::getTracker<0>(processorType& processors) +GPUdi() auto& getTracker<0>(GPUTRDTrackerKernels::processorType& processors) { return processors.trdTrackerGPU; } - template <> -GPUdi() auto& GPUTRDTrackerKernels::getTracker<1>(processorType& processors) +GPUdi() auto& getTracker<1>(GPUTRDTrackerKernels::processorType& processors) { return processors.trdTrackerO2; } +#else +template +GPUdi() GPUTRDTrackerGPU& getTracker(GPUTRDTrackerKernels::processorType& processors) +{ + return processors.trdTrackerGPU; +} +#endif template GPUdii() void GPUTRDTrackerKernels::Thread(int nBlocks, int nThreads, int iBlock, int iThread, GPUsharedref() GPUSharedMemory& smem, processorType& processors) @@ -43,4 +52,6 @@ GPUdii() void GPUTRDTrackerKernels::Thread(int nBlocks, int nThreads, int iBlock } template GPUd() void GPUTRDTrackerKernels::Thread<0>(int nBlocks, int nThreads, int iBlock, int iThread, GPUsharedref() GPUSharedMemory& smem, processorType& processors); +#ifdef HAVE_O2HEADERS template GPUd() void GPUTRDTrackerKernels::Thread<1>(int nBlocks, int nThreads, int iBlock, int iThread, GPUsharedref() GPUSharedMemory& smem, processorType& processors); +#endif diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTrackerKernels.h b/GPU/GPUTracking/TRDTracking/GPUTRDTrackerKernels.h index 5b7ee0f8d7e85..9f19823865ee9 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTrackerKernels.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTrackerKernels.h @@ -27,10 +27,6 @@ class GPUTRDTrackerKernels : public GPUKernelTemplate GPUhdi() CONSTEXPR static GPUDataTypes::RecoStep GetRecoStep() { return GPUCA_RECO_STEP::TRDTracking; } template GPUd() static void Thread(int nBlocks, int nThreads, int iBlock, int iThread, GPUsharedref() GPUSharedMemory& smem, processorType& processors); - - private: - template - GPUd() static auto& getTracker(processorType& processors); }; } // namespace gpu } // namespace GPUCA_NAMESPACE diff --git a/GPU/GPUTracking/utils/strtag.h b/GPU/GPUTracking/utils/strtag.h index 561465a6919ed..c9329963e884a 100644 --- a/GPU/GPUTracking/utils/strtag.h +++ b/GPU/GPUTracking/utils/strtag.h @@ -18,7 +18,10 @@ #include template -constexpr T qStr2Tag(const char* str) +#if defined(__cplusplus) && __cplusplus >= 201402L +constexpr +#endif +T qStr2Tag(const char* str) { if (strlen(str) != sizeof(T)) { throw std::runtime_error("Invalid tag length"); From befe4c839eb10753daf29459fb020251f8ab8462 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sat, 1 May 2021 10:37:16 +0200 Subject: [PATCH 350/770] GPU: Fix uninitialized memory during TPC tracking that can lead to FPE --- GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx index 78c0f9c86893e..4fa2d19cf71ba 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx @@ -456,6 +456,7 @@ GPUd() int GPUTPCGMMerger::RefitSliceTrack(GPUTPCGMSliceTrack& sliceTrack, const trk.QPt() = inTrack->Param().GetQPt(); trk.TZOffset() = Param().par.earlyTpcTransform ? inTrack->Param().GetZOffset() : GetConstantMem()->calibObjects.fastTransform->convZOffsetToVertexTime(slice, inTrack->Param().GetZOffset(), Param().par.continuousMaxTimeBin); trk.ShiftZ(this, slice, sliceTrack.ClusterZT0(), sliceTrack.ClusterZTN()); + sliceTrack.SetX2(0.f); for (int way = 0; way < 2; way++) { if (way) { prop.SetFitInProjections(true); @@ -509,7 +510,6 @@ GPUd() int GPUTPCGMMerger::RefitSliceTrack(GPUTPCGMSliceTrack& sliceTrack, const sliceTrack.SetParam2(trk); } else { sliceTrack.Set(trk, inTrack, alpha, slice); - sliceTrack.SetX2(0.f); } } return 0; From c0385664fd7e36115ecf5bd2850599531395b9df Mon Sep 17 00:00:00 2001 From: shahoian Date: Mon, 3 May 2021 03:06:34 +0200 Subject: [PATCH 351/770] Fix in GlobalTrackID::includesDet method --- .../include/ReconstructionDataFormats/GlobalTrackID.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h b/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h index 57c1c797e31d5..5a161869796f1 100644 --- a/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h +++ b/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h @@ -145,7 +145,7 @@ GPUdi() constexpr GlobalTrackID::mask_t GlobalTrackID::getSourceMask(int s) { re GPUdi() bool GlobalTrackID::includesDet(DetID id, GlobalTrackID::mask_t srcm) { for (int i = 0; i < NSources; i++) { - if (includesSource(i, srcm) && getSourceDetectorsMask(i) == id.getMask()) { + if (includesSource(i, srcm) && (getSourceDetectorsMask(i) & id.getMask()).any()) { return true; } } From d6a26a957c4d61cb928807518d21c17cd0d771f0 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Mon, 3 May 2021 09:17:36 +0200 Subject: [PATCH 352/770] DPL Analysis: preliminary work for multiple process() functions (#6019) --- .../PWGHF/HFDplusToPiKPiCandidateSelector.cxx | 2 +- Analysis/Tutorials/CMakeLists.txt | 6 + .../Tutorials/src/histogramsFullTracks.cxx | 4 +- Analysis/Tutorials/src/multiProcess.cxx | 102 +++++++++++ .../Core/include/Framework/AnalysisTask.h | 159 ++++++++++++------ .../Core/include/Framework/Expressions.h | 3 +- Framework/Core/test/test_AnalysisTask.cxx | 30 ++-- 7 files changed, 231 insertions(+), 75 deletions(-) create mode 100644 Analysis/Tutorials/src/multiProcess.cxx diff --git a/Analysis/Tasks/PWGHF/HFDplusToPiKPiCandidateSelector.cxx b/Analysis/Tasks/PWGHF/HFDplusToPiKPiCandidateSelector.cxx index 08ef9ec15c90b..40c991672d50d 100644 --- a/Analysis/Tasks/PWGHF/HFDplusToPiKPiCandidateSelector.cxx +++ b/Analysis/Tasks/PWGHF/HFDplusToPiKPiCandidateSelector.cxx @@ -251,5 +251,5 @@ struct HFDplusToPiKPiCandidateSelector { WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { return WorkflowSpec{ - adaptAnalysisTask(cfgc, "hf-dplus-topikpi-candidate-selector")}; + adaptAnalysisTask(cfgc, TaskName{"hf-dplus-topikpi-candidate-selector"})}; } diff --git a/Analysis/Tutorials/CMakeLists.txt b/Analysis/Tutorials/CMakeLists.txt index 67c8753593d7c..d12bb011c8bfe 100644 --- a/Analysis/Tutorials/CMakeLists.txt +++ b/Analysis/Tutorials/CMakeLists.txt @@ -209,3 +209,9 @@ o2_add_dpl_workflow(multiplicity-event-track-selection JOB_POOL analysis PUBLIC_LINK_LIBRARIES O2::Framework O2::AnalysisCore O2::AnalysisDataModel COMPONENT_NAME AnalysisTutorial) + +o2_add_dpl_workflow(multiprocess-example + SOURCES src/multiProcess.cxx + JOB_POOL analysis + PUBLIC_LINK_LIBRARIES O2::Framework O2::AnalysisCore O2::AnalysisDataModel + COMPONENT_NAME AnalysisTutorial) diff --git a/Analysis/Tutorials/src/histogramsFullTracks.cxx b/Analysis/Tutorials/src/histogramsFullTracks.cxx index 258e808d2544a..fe16039da4fcd 100644 --- a/Analysis/Tutorials/src/histogramsFullTracks.cxx +++ b/Analysis/Tutorials/src/histogramsFullTracks.cxx @@ -18,7 +18,7 @@ using namespace o2; using namespace o2::framework; using namespace o2::framework::expressions; -struct ATask { +struct EtaAndClsHistograms { OutputObj etaClsH{TH2F("eta_vs_cls", "#eta vs N_{cls}", 102, -2.01, 2.01, 160, -0.5, 159.5)}; void process(aod::FullTracks const& tracks) @@ -32,6 +32,6 @@ struct ATask { WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { return WorkflowSpec{ - adaptAnalysisTask(cfgc, TaskName{"eta-and-cls-histograms"}), + adaptAnalysisTask(cfgc), }; } diff --git a/Analysis/Tutorials/src/multiProcess.cxx b/Analysis/Tutorials/src/multiProcess.cxx new file mode 100644 index 0000000000000..70e0b542c2ef4 --- /dev/null +++ b/Analysis/Tutorials/src/multiProcess.cxx @@ -0,0 +1,102 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. +#include "Framework/AnalysisTask.h" +#include "Framework/AnalysisDataModel.h" +#include "AnalysisCore/MC.h" + +#include +#include + +using namespace o2; +using namespace o2::framework; +using namespace o2::framework::expressions; + +void customize(std::vector& workflowOptions) +{ + ConfigParamSpec optionDoMC{"doMC", VariantType::Bool, false, {"Use MC info"}}; + workflowOptions.push_back(optionDoMC); +} + +#include "Framework/runDataProcessing.h" + +namespace +{ +inline auto normalize(float a) +{ + if (a > M_PI) { + a -= 2 * M_PI; + } + if (a < -M_PI) { + a += 2 * M_PI; + } + return a; +} +} // namespace + +// Analysis task with several process functions with different signatures +struct MultipleProcessExample { + HistogramRegistry registry{ + "registry", + { + {"etaDiff", ";#eta_{MC} - #eta_{Rec}", {HistType::kTH1F, {{100, -2, 2}}}}, + {"phiDiff", ";#phi_{MC} - #phi_{Rec}", {HistType::kTH1F, {{100, -M_PI, M_PI}}}}, + {"etaRec", ";#eta_{Rec}", {HistType::kTH1F, {{100, -2, 2}}}}, + {"phiRec", ";#phi_{Rec}", {HistType::kTH1F, {{100, 0, 2 * M_PI}}}}, + {"etaMC", ";#eta_{MC}", {HistType::kTH1F, {{100, -2, 2}}}}, + {"phiMC", ";#phi_{MC}", {HistType::kTH1F, {{100, 0, 2 * M_PI}}}} /// + } /// + }; + + Filter RecColVtxZ = nabs(aod::collision::posZ) < 10.f; + Filter GenColVtxZ = nabs(aod::mccollision::posZ) < 10.f; + + void processRec(soa::Filtered::iterator const& collision, aod::Tracks const& tracks) + { + for (auto& track : tracks) { + registry.fill(HIST("etaRec"), track.eta()); + registry.fill(HIST("phiRec"), track.phi()); + } + } + + void processGen(soa::Filtered::iterator const& mcCollision, aod::McParticles const& mcParticles) + { + for (auto& particle : mcParticles) { + registry.fill(HIST("etaMC"), particle.eta()); + registry.fill(HIST("phiMC"), particle.phi()); + } + } + + void processResolution(soa::Filtered>::iterator const& collision, soa::Join const& tracks, aod::McParticles const& mcParticles, aod::McCollisions const& mcCollisions) + { + LOGF(info, "vtx-z (data) = %f | vtx-z (MC) = %f", collision.posZ(), collision.mcCollision().posZ()); + for (auto& track : tracks) { + registry.fill(HIST("etaDiff"), track.mcParticle().eta() - track.eta()); + registry.fill(HIST("phiDiff"), normalize(track.mcParticle().phi() - track.phi())); + } + } +}; + +WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) +{ + if (!cfgc.options().get("doMC")) { + return WorkflowSpec{ + // only use rec-level process when MC info is not there + adaptAnalysisTask(cfgc, Processes{&MultipleProcessExample::processRec})}; + } + return WorkflowSpec{ + // use additional process functions when MC info is present + // functions will be executed in the sequence they are listed - allows to use, for example, + // histograms that were filled previously + // produced tables *cannot* be used + // filters will be applied *to all* processes + adaptAnalysisTask(cfgc, Processes{&MultipleProcessExample::processRec, + &MultipleProcessExample::processGen, + &MultipleProcessExample::processResolution})}; +} diff --git a/Framework/Core/include/Framework/AnalysisTask.h b/Framework/Core/include/Framework/AnalysisTask.h index cc688b4221a31..4216e251702b2 100644 --- a/Framework/Core/include/Framework/AnalysisTask.h +++ b/Framework/Core/include/Framework/AnalysisTask.h @@ -102,24 +102,30 @@ struct AnalysisDataProcessorBuilder { (doAppendInputWithMetadata(inputs), ...); } - template - static void appendSomethingWithMetadata(std::vector& inputs, std::vector& eInfos, size_t at) + template + static void appendSomethingWithMetadata(std::vector& inputs, std::vector& eInfos) { using dT = std::decay_t; if constexpr (framework::is_specialization::value) { - eInfos.push_back({at, dT::hashes(), o2::soa::createSchemaFromColumns(typename dT::table_t::persistent_columns_t{}), nullptr}); + eInfos.push_back({AI, PI, dT::hashes(), o2::soa::createSchemaFromColumns(typename dT::table_t::persistent_columns_t{}), nullptr}); } else if constexpr (soa::is_soa_iterator_t
::value) { if constexpr (std::is_same_v) { - eInfos.push_back({at, dT::parent_t::hashes(), o2::soa::createSchemaFromColumns(typename dT::table_t::persistent_columns_t{}), nullptr}); + eInfos.push_back({AI, PI, dT::parent_t::hashes(), o2::soa::createSchemaFromColumns(typename dT::table_t::persistent_columns_t{}), nullptr}); } } doAppendInputWithMetadata(soa::make_originals_from_type
(), inputs); } - template + template + static void inputsFromArgsTuple(std::tuple& processTuple, std::vector& inputs, std::vector& eInfos) + { + (inputsFromArgs(pack{})>(std::get(processTuple), inputs, eInfos), ...); + } + + template static void inputsFromArgs(R (C::*)(Args...), std::vector& inputs, std::vector& eInfos) { - (appendSomethingWithMetadata(inputs, eInfos, o2::framework::has_type_at_v(pack{})), ...); + (appendSomethingWithMetadata(pack{})>(inputs, eInfos), ...); } template @@ -128,13 +134,13 @@ struct AnalysisDataProcessorBuilder { return std::declval>(); } - template + template static auto bindGroupingTable(InputRecord& record, R (C::*)(Grouping, Args...), std::vector const& infos) { - return extractSomethingFromRecord(record, infos, 0); + return extractSomethingFromRecord(record, infos); } - template + template static auto bindGroupingTable(InputRecord&, R (C::*)(), std::vector const&) { static_assert(always_static_assert_v, "Your task process method needs at least one argument"); @@ -176,24 +182,16 @@ struct AnalysisDataProcessorBuilder { } } - template - static auto extractSomethingFromRecord(InputRecord& record, std::vector const infos, size_t at) + template + static auto extractSomethingFromRecord(InputRecord& record, std::vector const infos) { using decayed = std::decay_t; if constexpr (soa::is_soa_filtered_t::value) { - for (auto& info : infos) { - if (info.index == at) { - return extractFilteredFromRecord(record, info, soa::make_originals_from_type()); - } - } + return extractFilteredFromRecord(record, *std::find_if(infos.begin(), infos.end(), [](ExpressionInfo const& i) { return (i.processIndex == PI && i.argumentIndex == AI); }), soa::make_originals_from_type()); } else if constexpr (soa::is_soa_iterator_t::value) { if constexpr (std::is_same_v) { - for (auto& info : infos) { - if (info.index == at) { - return extractFilteredFromRecord(record, info, soa::make_originals_from_type()); - } - } + return extractFilteredFromRecord(record, *std::find_if(infos.begin(), infos.end(), [](ExpressionInfo const& i) { return (i.processIndex == PI && i.argumentIndex == AI); }), soa::make_originals_from_type()); } else { return extractFromRecord(record, soa::make_originals_from_type()); } @@ -203,13 +201,13 @@ struct AnalysisDataProcessorBuilder { O2_BUILTIN_UNREACHABLE(); } - template + template static auto bindAssociatedTables(InputRecord& record, R (C::*)(Grouping, Args...), std::vector const infos) { - return std::make_tuple(extractSomethingFromRecord(record, infos, has_type_at_v(pack{}) + 1u)...); + return std::make_tuple(extractSomethingFromRecord(pack{}) + 1>(record, infos)...); } - template + template static auto bindAssociatedTables(InputRecord&, R (C::*)(), std::vector const) { static_assert(always_static_assert_v, "Your task process method needs at least one argument"); @@ -440,12 +438,18 @@ struct AnalysisDataProcessorBuilder { GroupSlicerIterator mBegin; }; - template - static void invokeProcess(Task& task, InputRecord& inputs, R (C::*)(Grouping, Associated...), std::vector const& infos) + template + static void invokeProcessTuple(Task& task, InputRecord& inputs, std::tuple const& processTuple, std::vector const& infos) + { + (invokeProcess(pack{})>(task, inputs, std::get(processTuple), infos), ...); + } + + template + static void invokeProcess(Task& task, InputRecord& inputs, R (C::*processingFunction)(Grouping, Associated...), std::vector const& infos) { auto tupledTask = o2::framework::to_tuple_refs(task); using G = std::decay_t; - auto groupingTable = AnalysisDataProcessorBuilder::bindGroupingTable(inputs, &C::process, infos); + auto groupingTable = AnalysisDataProcessorBuilder::bindGroupingTable(inputs, processingFunction, infos); // set filtered tables for partitions with grouping std::apply([&groupingTable](auto&... x) { @@ -462,18 +466,18 @@ struct AnalysisDataProcessorBuilder { tupledTask); if constexpr (soa::is_soa_iterator_t::value) { for (auto& element : groupingTable) { - task.process(*element); + std::invoke(processingFunction, task, *element); } } else { static_assert(soa::is_soa_table_like_t::value, "Single argument of process() should be a table-like or an iterator"); - task.process(groupingTable); + std::invoke(processingFunction, task, groupingTable); } } else { // multiple arguments to process static_assert(((soa::is_soa_iterator_t>::value == false) && ...), "Associated arguments of process() should not be iterators"); - auto associatedTables = AnalysisDataProcessorBuilder::bindAssociatedTables(inputs, &C::process, infos); + auto associatedTables = AnalysisDataProcessorBuilder::bindAssociatedTables(inputs, processingFunction, infos); auto binder = [&](auto&& x) { x.bindExternalIndices(&groupingTable, &std::get>(associatedTables)...); std::apply([&x](auto&... t) { @@ -511,7 +515,7 @@ struct AnalysisDataProcessorBuilder { }, tupledTask); - invokeProcessWithArgs(task, slice.groupingElement(), associatedSlices); + invokeProcessWithArgsGeneric(task, processingFunction, slice.groupingElement(), associatedSlices); } } else { // non-grouping case @@ -523,11 +527,17 @@ struct AnalysisDataProcessorBuilder { }, tupledTask); - invokeProcessWithArgs(task, groupingTable, associatedTables); + invokeProcessWithArgsGeneric(task, processingFunction, groupingTable, associatedTables); } } } + template + static void invokeProcessWithArgsGeneric(C& task, T processingFunction, G g, std::tuple& at) + { + std::invoke(processingFunction, task, g, std::get(at)...); + } + template static void invokeProcessWithArgs(T& task, G g, std::tuple& at) { @@ -589,27 +599,59 @@ struct TaskName { std::string value; }; -template -std::tuple> getNameAndTask() +/// +template +struct Processes { + Processes(Ts&&... args) : processes{std::make_tuple(args...)} + { + } + std::tuple processes; +}; + +template +auto getNameTaskProcesses(TaskName first, Processes second, A... args) +{ + auto task = std::make_shared(std::forward(args)...); + return std::make_tuple(first.value, task, second.processes); +} + +template +auto getNameTaskProcesses(Processes first, TaskName second, A... args) +{ + auto task = std::make_shared(std::forward(args)...); + return std::make_tuple(second.value, task, first.processes); +} + +template +auto getNameTaskProcesses(TaskName first, A... args) +{ + auto task = std::make_shared(std::forward(args)...); + if constexpr (has_process_v) { + return std::make_tuple(first.value, task, std::make_tuple(&T::process)); + } else { + return std::make_tuple(first.value, task, std::make_tuple()); + } +} + +template +auto getNameTaskProcesses(Processes first, A... args) { auto type_name_str = type_name(); std::string name = type_to_task_name(type_name_str); - auto task = std::make_shared(); - return std::make_tuple(name, task); + auto task = std::make_shared(std::forward(args)...); + return std::make_tuple(name, task, first.processes); } -template -std::tuple> getNameAndTask(T2&& firstArg, Args&&... args) +template +auto getNameTaskProcesses() { - if constexpr (std::is_same_v::type, TaskName>) { - std::string name = firstArg.value; - auto task = std::make_shared(std::forward(args)...); - return std::make_tuple(name, task); + auto type_name_str = type_name(); + std::string name = type_to_task_name(type_name_str); + auto task = std::make_shared(); + if constexpr (has_process_v) { + return std::make_tuple(name, task, std::make_tuple(&T::process)); } else { - auto type_name_str = type_name(); - std::string name = type_to_task_name(type_name_str); - auto task = std::make_shared(std::forward(firstArg, args)...); - return std::make_tuple(name, task); + return std::make_tuple(name, task, std::make_tuple()); } } @@ -620,7 +662,7 @@ DataProcessorSpec adaptAnalysisTask(ConfigContext const& ctx, Args&&... args) { TH1::AddDirectory(false); - auto [name_str, task] = getNameAndTask(args...); + auto [name_str, task, processTuple] = getNameTaskProcesses(args...); auto suffix = ctx.options().get("workflow-suffix"); if (!suffix.empty()) { @@ -634,7 +676,7 @@ DataProcessorSpec adaptAnalysisTask(ConfigContext const& ctx, Args&&... args) std::vector options; auto tupledTask = o2::framework::to_tuple_refs(*task.get()); - static_assert(has_process_v || has_run_v || has_init_v, + static_assert(std::tuple_size_v> > 0 || has_run_v || has_init_v, "At least one of process(...), T::run(...), init(...) must be defined"); std::vector inputs; @@ -643,10 +685,15 @@ DataProcessorSpec adaptAnalysisTask(ConfigContext const& ctx, Args&&... args) /// make sure options and configurables are set before expression infos are created std::apply([&options, &hash](auto&... x) { return (OptionManager>::appendOption(options, x), ...); }, tupledTask); - if constexpr (has_process_v) { - // this pushes (I,schemaPtr,nullptr) into expressionInfos for arguments that are Filtered/filtered_iterators - AnalysisDataProcessorBuilder::inputsFromArgs(&T::process, inputs, expressionInfos); + if constexpr ((std::tuple_size_v>) > 0) { + // this pushes (argumentIndex,processIndex,schemaPtr,nullptr) into expressionInfos for arguments that are Filtered/filtered_iterators + AnalysisDataProcessorBuilder::inputsFromArgsTuple(processTuple, inputs, expressionInfos); } + // avoid self-forwarding if process methods subscribe to same tables + std::sort(inputs.begin(), inputs.end(), [](InputSpec const& a, InputSpec const& b) { return a.binding < b.binding; }); + auto last = std::unique(inputs.begin(), inputs.end(), [](InputSpec const& a, InputSpec const& b) { return a.binding == b.binding; }); + inputs.erase(last, inputs.end()); + //request base tables for spawnable extended tables std::apply([&inputs](auto&... x) { return (SpawnManager>::requestInputs(inputs, x), ...); @@ -661,7 +708,7 @@ DataProcessorSpec adaptAnalysisTask(ConfigContext const& ctx, Args&&... args) std::apply([&outputs, &hash](auto&... x) { return (OutputManager>::appendOutput(outputs, x, hash), ...); }, tupledTask); - auto algo = AlgorithmSpec::InitCallback{[task = task, expressionInfos](InitContext& ic) mutable { + auto algo = AlgorithmSpec::InitCallback{[task = task, processTuple = processTuple, expressionInfos](InitContext& ic) mutable { auto tupledTask = o2::framework::to_tuple_refs(*task.get()); std::apply([&ic](auto&&... x) { return (OptionManager>::prepare(ic, x), ...); }, tupledTask); std::apply([&ic](auto&&... x) { return (ServiceManager>::prepare(ic, x), ...); }, tupledTask); @@ -674,7 +721,7 @@ DataProcessorSpec adaptAnalysisTask(ConfigContext const& ctx, Args&&... args) }; callbacks.set(CallbackService::Id::EndOfStream, endofdatacb); - if constexpr (has_process_v) { + if constexpr ((std::tuple_size_v>) > 0) { /// update configurables in filters std::apply( [&ic](auto&... x) { return (FilterManager>::updatePlaceholders(x, ic), ...); }, @@ -694,14 +741,14 @@ DataProcessorSpec adaptAnalysisTask(ConfigContext const& ctx, Args&&... args) task->init(ic); } - return [task, expressionInfos](ProcessingContext& pc) { + return [task, processTuple, expressionInfos](ProcessingContext& pc) { auto tupledTask = o2::framework::to_tuple_refs(*task.get()); std::apply([&pc](auto&&... x) { return (OutputManager>::prepare(pc, x), ...); }, tupledTask); if constexpr (has_run_v) { task->run(pc); } - if constexpr (has_process_v) { - AnalysisDataProcessorBuilder::invokeProcess(*(task.get()), pc.inputs(), &T::process, expressionInfos); + if constexpr ((std::tuple_size_v>) > 0) { + AnalysisDataProcessorBuilder::invokeProcessTuple(*(task.get()), pc.inputs(), processTuple, expressionInfos); } std::apply([&pc](auto&&... x) { return (OutputManager>::finalize(pc, x), ...); }, tupledTask); }; diff --git a/Framework/Core/include/Framework/Expressions.h b/Framework/Core/include/Framework/Expressions.h index f4057ddfd2aa0..3edbf718b3ad0 100644 --- a/Framework/Core/include/Framework/Expressions.h +++ b/Framework/Core/include/Framework/Expressions.h @@ -45,7 +45,8 @@ class Filter; using atype = arrow::Type; struct ExpressionInfo { - size_t index; + int argumentIndex; + int processIndex; std::set hashes; gandiva::SchemaPtr schema; gandiva::NodePtr tree; diff --git a/Framework/Core/test/test_AnalysisTask.cxx b/Framework/Core/test/test_AnalysisTask.cxx index 3d500022c7322..336642f265df6 100644 --- a/Framework/Core/test/test_AnalysisTask.cxx +++ b/Framework/Core/test/test_AnalysisTask.cxx @@ -151,32 +151,32 @@ BOOST_AUTO_TEST_CASE(AdaptorCompilation) auto task1 = adaptAnalysisTask(*cfgc, TaskName{"test1"}); BOOST_CHECK_EQUAL(task1.inputs.size(), 2); BOOST_CHECK_EQUAL(task1.outputs.size(), 1); - BOOST_CHECK_EQUAL(task1.inputs[0].binding, std::string("TracksExtension")); - BOOST_CHECK_EQUAL(task1.inputs[1].binding, std::string("Tracks")); + BOOST_CHECK_EQUAL(task1.inputs[1].binding, std::string("TracksExtension")); + BOOST_CHECK_EQUAL(task1.inputs[0].binding, std::string("Tracks")); BOOST_CHECK_EQUAL(task1.outputs[0].binding.value, std::string("FooBars")); auto task2 = adaptAnalysisTask(*cfgc, TaskName{"test2"}); BOOST_CHECK_EQUAL(task2.inputs.size(), 9); - BOOST_CHECK_EQUAL(task2.inputs[0].binding, "Collisions"); - BOOST_CHECK_EQUAL(task2.inputs[1].binding, "TracksExtension"); - BOOST_CHECK_EQUAL(task2.inputs[2].binding, "Tracks"); - BOOST_CHECK_EQUAL(task2.inputs[3].binding, "TracksExtra"); - BOOST_CHECK_EQUAL(task2.inputs[4].binding, "TracksCovExtension"); - BOOST_CHECK_EQUAL(task2.inputs[5].binding, "TracksCov"); - BOOST_CHECK_EQUAL(task2.inputs[6].binding, "UnassignedTracks"); - BOOST_CHECK_EQUAL(task2.inputs[7].binding, "Calos"); - BOOST_CHECK_EQUAL(task2.inputs[8].binding, "CaloTriggers"); + BOOST_CHECK_EQUAL(task2.inputs[0].binding, "CaloTriggers"); + BOOST_CHECK_EQUAL(task2.inputs[1].binding, "Calos"); + BOOST_CHECK_EQUAL(task2.inputs[2].binding, "Collisions"); + BOOST_CHECK_EQUAL(task2.inputs[3].binding, "Tracks"); + BOOST_CHECK_EQUAL(task2.inputs[4].binding, "TracksCov"); + BOOST_CHECK_EQUAL(task2.inputs[5].binding, "TracksCovExtension"); + BOOST_CHECK_EQUAL(task2.inputs[6].binding, "TracksExtension"); + BOOST_CHECK_EQUAL(task2.inputs[7].binding, "TracksExtra"); + BOOST_CHECK_EQUAL(task2.inputs[8].binding, "UnassignedTracks"); auto task3 = adaptAnalysisTask(*cfgc, TaskName{"test3"}); BOOST_CHECK_EQUAL(task3.inputs.size(), 3); BOOST_CHECK_EQUAL(task3.inputs[0].binding, "Collisions"); - BOOST_CHECK_EQUAL(task3.inputs[1].binding, "TracksExtension"); - BOOST_CHECK_EQUAL(task3.inputs[2].binding, "Tracks"); + BOOST_CHECK_EQUAL(task3.inputs[2].binding, "TracksExtension"); + BOOST_CHECK_EQUAL(task3.inputs[1].binding, "Tracks"); auto task4 = adaptAnalysisTask(*cfgc, TaskName{"test4"}); BOOST_CHECK_EQUAL(task4.inputs.size(), 2); - BOOST_CHECK_EQUAL(task4.inputs[0].binding, "TracksExtension"); - BOOST_CHECK_EQUAL(task4.inputs[1].binding, "Tracks"); + BOOST_CHECK_EQUAL(task4.inputs[1].binding, "TracksExtension"); + BOOST_CHECK_EQUAL(task4.inputs[0].binding, "Tracks"); auto task5 = adaptAnalysisTask(*cfgc, TaskName{"test5"}); BOOST_CHECK_EQUAL(task5.inputs.size(), 1); From ed9274820f2fc43cc0efece0da297124a410f635 Mon Sep 17 00:00:00 2001 From: Sandro Wenzel Date: Sun, 2 May 2021 16:48:04 +0200 Subject: [PATCH 353/770] jobutils: More robust return code determination Sometimes the bash wait falsely claims "PID" not a child of this shell. This commit is working around this issue. --- Utilities/Tools/jobutils.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Utilities/Tools/jobutils.sh b/Utilities/Tools/jobutils.sh index f01fa72c0f11d..1791fe5967c50 100644 --- a/Utilities/Tools/jobutils.sh +++ b/Utilities/Tools/jobutils.sh @@ -111,7 +111,7 @@ taskwrapper() { # the command might be a complex block: For the timing measurement below # it is better to execute this as a script SCRIPTNAME="${logfile}_tmp.sh" - echo "${command}" > ${SCRIPTNAME} + echo "${command}; echo \"TASK-EXIT-CODE: $?\"" > ${SCRIPTNAME} chmod +x ${SCRIPTNAME} # this gives some possibility to customize the wrapper @@ -372,9 +372,9 @@ taskwrapper() { # wait for PID and fetch return code # ?? should directly exit here? - wait $PID - # return code - RC=$? + wait $PID || QUERY_RC_FROM_LOG="ON" + # query return code from log (seems to be safer as sometimes the wait issues "PID" not a child of this shell) + RC=$(grep "TASK-EXIT-CODE:" ${logfile} | awk '//{print $2}') RC_ACUM=$((RC_ACUM+RC)) if [ "${RC}" -eq "0" ]; then if [ ! "${JOBUTILS_JOB_SKIPCREATEDONE}" ]; then From 1d7a41cbad87253e087992ce522b3bbfbf3a0be4 Mon Sep 17 00:00:00 2001 From: wiechula Date: Mon, 3 May 2021 11:27:26 +0200 Subject: [PATCH 354/770] fix loading of gain map correction values --- GPU/GPUTracking/DataTypes/TPCPadGainCalib.cxx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/GPU/GPUTracking/DataTypes/TPCPadGainCalib.cxx b/GPU/GPUTracking/DataTypes/TPCPadGainCalib.cxx index 62ca2964a172e..9ce0254f2c089 100644 --- a/GPU/GPUTracking/DataTypes/TPCPadGainCalib.cxx +++ b/GPU/GPUTracking/DataTypes/TPCPadGainCalib.cxx @@ -33,7 +33,8 @@ TPCPadGainCalib::TPCPadGainCalib(const o2::tpc::CalDet& gainMap) : TPCPad { for (int sector = 0; sector < o2::tpc::constants::MAXSECTOR; sector++) { for (int p = 0; p < TPC_PADS_IN_SECTOR; p++) { - mGainCorrection[sector].set(p, gainMap.getValue(sector, p)); + const float gainVal = gainMap.getValue(sector, p); + mGainCorrection[sector].set(p, (gainVal > 1.e-5f) ? 1.f / gainVal : 1.f); } } } From 9cf33c3d012ec4e0063cd798d0ff8495eb5db9e0 Mon Sep 17 00:00:00 2001 From: shahoian Date: Fri, 30 Apr 2021 22:38:49 +0200 Subject: [PATCH 355/770] Ensure MFT digits are decoded in chipID increasing order --- .../ITSMFTReconstruction/RawPixelDecoder.h | 3 +- .../reconstruction/src/RawPixelDecoder.cxx | 66 +++++++++++++++++-- 2 files changed, 61 insertions(+), 8 deletions(-) diff --git a/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/RawPixelDecoder.h b/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/RawPixelDecoder.h index 651be688c6d11..7fd344993abad 100644 --- a/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/RawPixelDecoder.h +++ b/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/RawPixelDecoder.h @@ -54,7 +54,7 @@ class RawPixelDecoder final : public PixelReader void init() final {} bool getNextChipData(ChipPixelData& chipData) final; ChipPixelData* getNextChipData(std::vector& chipDataVec) final; - + void ensureChipOrdering() {} void startNewTF(o2::framework::InputRecord& inputs); int decodeNextTrigger() final; @@ -114,6 +114,7 @@ class RawPixelDecoder final : public PixelReader std::unordered_map mSubsSpec2LinkID; // link subspec to link entry in the pool mapping std::vector mRUDecodeVec; // set of active RUs std::array mRUEntry; // entry of the RU with given SW ID in the mRUDecodeVec + std::vector mOrderedChipsPtr; // special ordering helper used for the MFT (its chipID is not contiguous in RU) std::string mSelfName; // self name header::DataOrigin mUserDataOrigin = o2::header::gDataOriginInvalid; // alternative user-provided data origin to pick header::DataDescription mUserDataDescription = o2::header::gDataDescriptionInvalid; // alternative user-provided description to pick diff --git a/Detectors/ITSMFT/common/reconstruction/src/RawPixelDecoder.cxx b/Detectors/ITSMFT/common/reconstruction/src/RawPixelDecoder.cxx index 545e73c1bd4cc..1283301e5963a 100644 --- a/Detectors/ITSMFT/common/reconstruction/src/RawPixelDecoder.cxx +++ b/Detectors/ITSMFT/common/reconstruction/src/RawPixelDecoder.cxx @@ -114,8 +114,9 @@ int RawPixelDecoder::decodeNextTrigger() } } while (mNLinksDone < mGBTLinks.size()); + + ensureChipOrdering(); mTimerDecode.Stop(); - // LOG(INFO) << "Chips Fired: " << mNChipsFiredROF << " NPixels: " << mNPixelsFiredROF << " at IR " << mInteractionRecord << " of HBF " << mInteractionRecordHB; return nLinksWithData; } @@ -268,9 +269,7 @@ ChipPixelData* RawPixelDecoder::getNextChipData(std::vector::value) { - assert(mLastReadChipID < chipData.getChipID()); - } + assert(mLastReadChipID < chipData.getChipID()); mLastReadChipID = chipData.getChipID(); chipDataVec[mLastReadChipID].swap(chipData); return &chipDataVec[mLastReadChipID]; @@ -292,9 +291,7 @@ bool RawPixelDecoder::getNextChipData(ChipPixelData& chipData) auto& ru = mRUDecodeVec[mCurRUDecodeID]; if (ru.lastChipChecked < ru.nChipsFired) { auto& ruchip = ru.chipsData[ru.lastChipChecked++]; - if constexpr (std::is_same::value) { - assert(mLastReadChipID < chipData.getChipID()); - } + assert(mLastReadChipID < chipData.getChipID()); mLastReadChipID = chipData.getChipID(); chipData.swap(ruchip); return true; @@ -307,6 +304,61 @@ bool RawPixelDecoder::getNextChipData(ChipPixelData& chipData) return getNextChipData(chipData); // is it ok to use recursion here? } +///______________________________________________________________________ +template <> +void RawPixelDecoder::ensureChipOrdering() +{ + // define looping order, if mCurRUDecodeID < mRUDecodeVec.size(), this means that decodeNextTrigger() was called before + if (mCurRUDecodeID < mRUDecodeVec.size()) { // define sort order + for (; mCurRUDecodeID < mRUDecodeVec.size(); mCurRUDecodeID++) { + auto& ru = mRUDecodeVec[mCurRUDecodeID]; + while (ru.lastChipChecked < ru.nChipsFired) { + mOrderedChipsPtr.push_back(&ru.chipsData[ru.lastChipChecked++]); + } + } + // sort in decreasing order + std::sort(mOrderedChipsPtr.begin(), mOrderedChipsPtr.end(), [](const ChipPixelData* a, const ChipPixelData* b) { return a->getChipID() > b->getChipID(); }); + } +} + +///______________________________________________________________________ +template <> +ChipPixelData* RawPixelDecoder::getNextChipData(std::vector& chipDataVec) +{ + if (!mOrderedChipsPtr.empty()) { + auto chipData = *mOrderedChipsPtr.back(); + assert(mLastReadChipID < chipData.getChipID()); + mLastReadChipID = chipData.getChipID(); + chipDataVec[mLastReadChipID].swap(chipData); + mOrderedChipsPtr.pop_back(); + return &chipDataVec[mLastReadChipID]; + } + // will need to decode new trigger + if (!mDecodeNextAuto || !decodeNextTrigger()) { // no more data to decode + return nullptr; + } + return getNextChipData(chipDataVec); +} + +///______________________________________________________________________ +template <> +bool RawPixelDecoder::getNextChipData(ChipPixelData& chipData) +{ + if (!mOrderedChipsPtr.empty()) { + auto ruChip = *mOrderedChipsPtr.back(); + assert(mLastReadChipID < ruChip.getChipID()); + mLastReadChipID = ruChip.getChipID(); + ruChip.swap(chipData); + mOrderedChipsPtr.pop_back(); + return true; + } + // will need to decode new trigger + if (!mDecodeNextAuto || !decodeNextTrigger()) { // no more data to decode + return false; + } + return getNextChipData(chipData); // is it ok to use recursion here? +} + ///______________________________________________________________________ template void RawPixelDecoder::setVerbosity(int v) From 2c473167816a6f85e9919864d2eb564cbe972b26 Mon Sep 17 00:00:00 2001 From: shahoian Date: Sun, 2 May 2021 22:25:56 +0200 Subject: [PATCH 356/770] RecoContainer: add methods to extract ITS,TPC contributor GID from compound GID --- .../DataFormatsGlobalTracking/RecoContainer.h | 10 ++++- .../GlobalTracking/src/RecoContainer.cxx | 44 ++++++++++++++++++- 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h index 3265e1a1fe3a5..14d20020ae267 100644 --- a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h +++ b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h @@ -95,9 +95,17 @@ struct RecoContainer { // custom getters - // get contributors from single detectors + // get contributors from single detectors: return array with sources set to all contributing GTrackIDs GlobalIDSet getSingleDetectorRefs(GTrackID gidx) const; + // get contributing TPC GTrackID to the source. If source gidx is not contributed by TPC, + // returned GTrackID.isSourceSet()==false + GTrackID getTPCContributorGID(GTrackID source) const; + + // get contributing ITS GTrackID to the source. If source gidx is not contributed by ITS, + // returned GTrackID.isSourceSet()==false + GTrackID getITSContributorGID(GTrackID source) const; + // check if track source attached bool isTrackSourceLoaded(int src) const; diff --git a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx index a829057524015..1acd9225b2445 100644 --- a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx +++ b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx @@ -363,7 +363,12 @@ void RecoContainer::createTracks(std::function(gidx); //ITS/TPC : TOF + const auto& parent1 = getTPCITSTrack(parent0.getEvIdxTrack().getIndex()); + return parent1.getRefTPC(); + } else if (src == GTrackID::TPCTOF) { + const auto& parent0 = getTPCTOFMatch(gidx); //TPC : TOF + return parent0.getEvIdxTrack().getIndex(); + } else if (src == GTrackID::ITSTPC) { + const auto& parent0 = getTPCITSTrack(gidx); + return parent0.getRefTPC(); + } + return src == GTrackID::TPC ? gidx : GTrackID{}; +} + +// get contributing ITS GTrackID to the source. If source gidx is not contributed by TPC, +// returned GTrackID.isSourceSet()==false +GTrackID RecoContainer::getITSContributorGID(GTrackID gidx) const +{ + auto src = gidx.getSource(); + if (src == GTrackID::ITSTPCTOF) { + const auto& parent0 = getTOFMatch(gidx); //ITS/TPC : TOF + const auto& parent1 = getTPCITSTrack(parent0.getEvIdxTrack().getIndex()); + return parent1.getRefITS(); + } else if (src == GTrackID::ITSTPC) { + const auto& parent0 = getTPCITSTrack(gidx); + return parent0.getRefITS(); + } + return src == GTrackID::ITS ? gidx : GTrackID{}; +} From 8879e3edd60723474d485b734df6cf049b2defc2 Mon Sep 17 00:00:00 2001 From: shahoian Date: Sun, 28 Mar 2021 23:39:05 +0200 Subject: [PATCH 357/770] Switch to input via RecoContainer --- Detectors/GlobalTracking/CMakeLists.txt | 4 +- .../include/GlobalTracking/MatchTPCITS.h | 192 +++--------- .../src/GlobalTrackingLinkDef.h | 1 - Detectors/GlobalTracking/src/MatchTPCITS.cxx | 281 +++++++++--------- .../GlobalTrackingWorkflow/CMakeLists.txt | 1 - .../TPCITSMatchingSpec.h | 3 +- .../src/CosmicsMatchingSpec.cxx | 1 - .../src/TPCITSMatchingSpec.cxx | 101 +------ .../src/tpcits-match-workflow.cxx | 63 +++- 9 files changed, 266 insertions(+), 381 deletions(-) diff --git a/Detectors/GlobalTracking/CMakeLists.txt b/Detectors/GlobalTracking/CMakeLists.txt index df01cf3f02f11..57bc8532b61a8 100644 --- a/Detectors/GlobalTracking/CMakeLists.txt +++ b/Detectors/GlobalTracking/CMakeLists.txt @@ -7,7 +7,7 @@ # In applying this license CERN does not waive the privileges and immunities # granted to it by virtue of its status as an Intergovernmental Organization or # submit itself to any jurisdiction. - +add_compile_options(-O0 -g -fPIC) o2_add_library( GlobalTracking SOURCES src/MatchTPCITS.cxx src/MatchTOF.cxx @@ -36,5 +36,5 @@ o2_add_library( o2_target_root_dictionary( GlobalTracking - HEADERS include/GlobalTracking/MatchTPCITS.h include/GlobalTracking/MatchTPCITSParams.h + HEADERS include/GlobalTracking/MatchTPCITSParams.h include/GlobalTracking/MatchTOF.h include/GlobalTracking/MatchCosmics.h include/GlobalTracking/MatchCosmicsParams.h) diff --git a/Detectors/GlobalTracking/include/GlobalTracking/MatchTPCITS.h b/Detectors/GlobalTracking/include/GlobalTracking/MatchTPCITS.h index 80735a4a828a2..719c819c247b3 100644 --- a/Detectors/GlobalTracking/include/GlobalTracking/MatchTPCITS.h +++ b/Detectors/GlobalTracking/include/GlobalTracking/MatchTPCITS.h @@ -49,12 +49,18 @@ #include "GPUO2InterfaceRefit.h" #include "GlobalTracking/MatchTPCITSParams.h" #include "CommonDataFormat/FlatHisto2D.h" +#include "DataFormatsITSMFT/TopologyDictionary.h" class TTree; namespace o2 { +namespace globaltracking +{ +class RecoContainer; +} + namespace dataformats { template @@ -104,24 +110,33 @@ enum TrackRejFlag : int { ///< TPC track parameters propagated to reference X, with time bracket and index of ///< original track in the currently loaded TPC reco output struct TrackLocTPC : public o2::track::TrackParCov { - o2::math_utils::Bracketf_t timeBins; ///< bracketing time-bins + enum Constraint_t : uint8_t { Constrained, + ASide, + CSide }; + o2::math_utils::Bracketf_t tBracket; ///< bracketing time in \mus + float time0 = 0; ///< nominal time in \mus int sourceID = 0; ///< track origin id - float zMin = 0; // min possible Z of this track - float zMax = 0; // max possible Z of this track + // float zMin = 0; // min possible Z of this track + // float zMax = 0; // max possible Z of this track int matchID = MinusOne; ///< entry (non if MinusOne) of its matchTPC struct in the mMatchesTPC - TrackLocTPC(const o2::track::TrackParCov& src, int tid) : o2::track::TrackParCov(src), sourceID(tid) {} - TrackLocTPC() = default; + Constraint_t constraint{Constrained}; + + float getCorrectedTime(float dt) const // return time0 corrected for extra drift (to match certain Z) + { + return constraint == Constrained ? time0 : (constraint == ASide ? time0 + dt : time0 - dt); + } + ClassDefNV(TrackLocTPC, 1); }; ///< ITS track outward parameters propagated to reference X, with time bracket and index of ///< original track in the currently loaded ITS reco output struct TrackLocITS : public o2::track::TrackParCov { + o2::math_utils::Bracketf_t tBracket; ///< bracketing time in \mus int sourceID = 0; ///< track origin id int roFrame = MinusOne; ///< ITS readout frame assigned to this track int matchID = MinusOne; ///< entry (non if MinusOne) of its matchCand struct in the mMatchesITS - TrackLocITS(const o2::track::TrackParCov& src, int tid) : o2::track::TrackParCov(src), sourceID(tid) {} - TrackLocITS() = default; + ClassDefNV(TrackLocITS, 1); }; @@ -244,12 +259,12 @@ struct ABClusterLink { }; struct InteractionCandidate : public o2::InteractionRecord { - o2::math_utils::Bracket timeBins; // interaction time (int TPC time bins) + o2::math_utils::Bracketf_t tBracket; // interaction time int rofITS; // corresponding ITS ROF entry (in the ROFRecord vectors) uint32_t flag; // origin, etc. void* clRefPtr = nullptr; // pointer on cluster references container (if any) InteractionCandidate() = default; - InteractionCandidate(const o2::InteractionRecord& ir, float t, float dt, int rof, uint32_t f = 0) : o2::InteractionRecord(ir), timeBins(t - dt, t + dt), rofITS(rof), flag(f) {} + InteractionCandidate(const o2::InteractionRecord& ir, float t, float dt, int rof, uint32_t f = 0) : o2::InteractionRecord(ir), tBracket(t - dt, t + dt), rofITS(rof), flag(f) {} }; struct ITSChipClustersRefs { @@ -294,8 +309,8 @@ class MatchTPCITS static constexpr int MaxSeedsPerLayer = 50; // TODO static constexpr int NITSLayers = o2::its::RecoGeomHelper::getNLayers(); ///< perform matching for provided input - void run(); - + void run(const o2::globaltracking::RecoContainer& inp); + void loadInput(const o2::globaltracking::RecoContainer& inp); // RSTODO void runAfterBurner(); bool runAfterBurner(int tpcWID, int iCStart, int iCEnd); @@ -329,9 +344,6 @@ class MatchTPCITS ///< clear results of previous event reco void clear(); - ///< set InteractionRecods for the beginning of the TF - void setStartIR(const o2::InteractionRecord& ir) { mStartIR = ir; } - ///< set Bunch filling and init helpers for validation by BCs void setBunchFilling(const o2::BunchFilling& bf); @@ -348,6 +360,7 @@ class MatchTPCITS void setITSROFrameLengthInBC(int nbc); // ==================== >> DPL-driven input >> ======================= + void setITSDictionary(const o2::itsmft::TopologyDictionary* d) { mITSDict = d; } ///< set flag to use MC truth void setMCTruthOn(bool v) @@ -364,86 +377,6 @@ class MatchTPCITS ///< get histo for tgl differences for VDrift calibration auto getHistoDTgl() { return mHistoDTgl.get(); } - ///< set input ITS tracks - void setITSTracksInp(const gsl::span inp) - { - mITSTracksArray = inp; - } - - ///< set input ITS tracks cluster indices - void setITSTrackClusIdxInp(const gsl::span inp) - { - mITSTrackClusIdx = inp; - } - - ///< set input ITS tracks ROF records - void setITSTrackROFRecInp(const gsl::span inp) - { - mITSTrackROFRec = inp; - } - - ///< set input ITS clusters - void setITSClustersInp(const gsl::span inp) - { - mITSClustersArray = inp; - } - - ///< set input ITS clusters ROF records - void setITSClusterROFRecInp(const gsl::span inp) - { - mITSClusterROFRec = inp; - } - - ///< set input TPC tracks - void setTPCTracksInp(const gsl::span inp) - { - mTPCTracksArray = inp; - } - - ///< set input TPC tracks cluster indices - void setTPCTrackClusIdxInp(const gsl::span inp) - { - mTPCTrackClusIdx = inp; - } - - ///< set input TPC cluster sharing map - void setTPCClustersSharingMap(const gsl::span inp) - { - mTPCRefitterShMap = inp; - } - - ///< set input TPC clusters - void setTPCClustersInp(const o2::tpc::ClusterNativeAccess* inp) - { - mTPCClusterIdxStruct = inp; - } - - ///< set input ITS track MC labels - void setITSTrkLabelsInp(const MCLabSpan& lbl) - { - mITSTrkLabels = lbl; - } - - ///< set input ITS clusters MC labels - void setITSClsLabelsInp(const MCLabContCl* lbl) - { - mITSClsLabels = lbl; - } - - ///< set input TPC track MC labels - void setTPCTrkLabelsInp(const MCLabSpan& lbl) - { - mTPCTrkLabels = lbl; - } - - ///< set input FIT info - void setFITInfoInp(const gsl::span inp) - { - mFITInfo = inp; - } - - // ===================== << DPL-driven input << ======================== - ///< print settings void print() const; void printCandidatesTPC() const; @@ -539,46 +472,29 @@ class MatchTPCITS ///< get number of matching records for ITS track int getNMatchRecordsITS(const TrackLocITS& tITS) const; - ///< convert TPC timebins bracket to IR bracket - BracketIR tpcTimeBin2IRBracket(const BracketF tbrange); + ///< convert time bracket to IR bracket + BracketIR tBracket2IRBracket(const BracketF tbrange); - ///< convert TPC time bin to ITS ROFrame units - int tpcTimeBin2ITSROFrame(float tbin) const + ///< convert time bin to ITS ROFrame units + int time2ITSROFrame(float t) const { if (mITSTriggered) { - return mITSROFofTPCBin[int(tbin > 0 ? tbin : 0)]; + LOG(ERROR) << "FIXME"; + //return mITSROForTime[int(t > 0 ? t : 0)]; } - int rof = tbin > 0 ? tbin * mTPCBin2ITSROFrame : 0; + int rof = t > 0 ? t * mITSROFrameLengthMUSInv : 0; // the rof is estimated continuous counter but the actual bins might have gaps (e.g. HB rejects etc)-> use mapping return rof < int(mITSTrackROFContMapping.size()) ? mITSTrackROFContMapping[rof] : mITSTrackROFContMapping.back(); } - ///< convert ITS ROFrame to TPC time bin units // TOREMOVE - float itsROFrame2TPCTimeBin(int rof) const { return rof * mITSROFrame2TPCBin; } - - ///< convert time in microseconds to TPC time bin units - float time2TPCTimeBin(float tms) const - { - return tms * mTPCTBinMUSInv; - } + ///< convert TPC time bin to microseconds + float tpcTimeBin2Z(float tbn) const { return tbn * mTPCBin2Z; } ///< convert TPC time bin to microseconds - float tpcTimeBin2MUS(float tbn) const - { - return tbn * mTPCTBinMUS; - } + float tpcTimeBin2MUS(float tbn) const { return tbn * mTPCTBinMUS; } ///< convert TPC time bin to nanoseconds - float tpcTimeBin2NS(float tbn) const - { - return tbn * mTPCTBinNS; - } - - ///< convert Interaction Record for TPC time bin units - float intRecord2TPCTimeBin(const o2::InteractionRecord& bc) const - { - return time2TPCTimeBin(bc.differenceInBC(mStartIR) * o2::constants::lhc::LHCBunchSpacingNS * 1e-3); - } + float tpcTimeBin2NS(float tbn) const { return tbn * mTPCTBinNS; } ///< convert Z interval to TPC time-bins float z2TPCBin(float z) const { return z * mZ2TPCBin; } @@ -592,20 +508,6 @@ class MatchTPCITS return delta > toler ? rejFlag : (delta < -toler ? -rejFlag : Accept); } - ///< correct TPC time0 (int TPC time-bins) - float getTPCTrackCorrectedTimeBin(const o2::tpc::TrackTPC& trc, float delta) const - { - float timeTB = trc.getTime0(); - if (trc.hasASideClustersOnly()) { - timeTB += delta; - } else if (trc.hasCSideClustersOnly()) { - timeTB -= delta; - } else { - // TODO : special treatment of tracks crossing the CE - } - return timeTB; - } - //================================================================ bool mInitDone = false; ///< flag init already done @@ -636,6 +538,7 @@ class MatchTPCITS int mITSROFrameLengthInBC = 0; ///< ITS RO frame in BC (for ITS cont. mode only) float mITSROFrameLengthMUS = -1.; ///< ITS RO frame in \mus + float mITSROFrameLengthMUSInv = -1.; ///< ITS RO frame in \mus inverse float mTPCVDrift0 = -1.; ///< TPC nominal drift speed in cm/microseconds float mTPCVDrift0Inv = -1.; ///< inverse TPC nominal drift speed in cm/microseconds float mTPCTBinMUS = 0.; ///< TPC time bin duration in microseconds @@ -669,12 +572,14 @@ class MatchTPCITS gsl::span mITSTrackROFRec; ///< input ITS tracks ROFRecord span gsl::span mITSTracksArray; ///< input ITS tracks span gsl::span mITSTrackClusIdx; ///< input ITS track cluster indices span - gsl::span mITSClustersArray; ///< input ITS clusters span + std::vector mITSClustersArray; ///< ITS clusters created in loadInput gsl::span mITSClusterROFRec; ///< input ITS clusters ROFRecord span gsl::span mFITInfo; ///< optional input FIT info span gsl::span mTPCRefitterShMap; ///< externally set TPC clusters sharing map + const o2::itsmft::TopologyDictionary* mITSDict{nullptr}; // cluster patterns dictionary + const o2::tpc::ClusterNativeAccess* mTPCClusterIdxStruct = nullptr; ///< struct holding the TPC cluster indices const MCLabContCl* mITSClsLabels = nullptr; ///< input ITS Cluster MC labels @@ -690,8 +595,8 @@ class MatchTPCITS ///< container for reference to MatchRecord involving particular ITS track std::vector mMatchRecordsITS; - std::vector mITSROFofTPCBin; ///< aux structure for mapping of TPC time-bins on ITS ROFs - std::vector mITSROFTimes; ///< min/max times of ITS ROFs in TPC time-bins + //// std::vector mITSROFofTPCBin; ///< aux structure for mapping of TPC time-bins on ITS ROFs + std::vector mITSROFTimes; ///< min/max times of ITS ROFs in \mus std::vector mTPCWork; ///< TPC track params prepared for matching std::vector mITSWork; ///< ITS track params prepared for matching MCLabContTr mTPCLblWork; ///< TPC track labels @@ -718,10 +623,10 @@ class MatchTPCITS ///< indices of 1st entries with time-bin above the value std::vector mTPCABTimeBinStart; - ///< indices of 1st entries with time-bin above the value - std::array, o2::constants::math::NSectors> mTPCTimeBinStart; - ///< indices of 1st entries of ITS tracks with givem ROframe - std::array, o2::constants::math::NSectors> mITSTimeBinStart; + ///< indices of 1st TPC tracks with time above the ITS ROF time + std::array, o2::constants::math::NSectors> mTPCTimeStart; + ///< indices of 1st entries of ITS tracks starting at given ROframe + std::array, o2::constants::math::NSectors> mITSTimeStart; /// mapping for tracks' continuos ROF cycle to actual continuous readout ROFs with eventual gaps std::vector mITSTrackROFContMapping; @@ -758,7 +663,6 @@ class MatchTPCITS static constexpr std::string_view TimerName[] = {"Total", "PrepareITS", "PrepareTPC", "DoMatching", "SelectBest", "Refit", "IO", "Debug"}; TStopwatch mTimer[NStopWatches]; - ClassDefNV(MatchTPCITS, 1); }; //______________________________________________ diff --git a/Detectors/GlobalTracking/src/GlobalTrackingLinkDef.h b/Detectors/GlobalTracking/src/GlobalTrackingLinkDef.h index db180dc9098f9..320efa26d1e27 100644 --- a/Detectors/GlobalTracking/src/GlobalTrackingLinkDef.h +++ b/Detectors/GlobalTracking/src/GlobalTrackingLinkDef.h @@ -14,7 +14,6 @@ #pragma link off all classes; #pragma link off all functions; -#pragma link C++ class o2::globaltracking::MatchTPCITS + ; #pragma link C++ class o2::globaltracking::MatchTOF + ; #pragma link C++ class o2::globaltracking::TrackLocTPC + ; #pragma link C++ class o2::globaltracking::TrackLocITS + ; diff --git a/Detectors/GlobalTracking/src/MatchTPCITS.cxx b/Detectors/GlobalTracking/src/MatchTPCITS.cxx index 6cbbb7aa633b7..50867e8941b91 100644 --- a/Detectors/GlobalTracking/src/MatchTPCITS.cxx +++ b/Detectors/GlobalTracking/src/MatchTPCITS.cxx @@ -41,6 +41,10 @@ #include "ReconstructionDataFormats/Vertex.h" #include "GlobalTracking/MatchTPCITS.h" +#include "DataFormatsGlobalTracking/RecoContainer.h" + +#include "ITStracking/IOUtils.h" + #include "GPUO2Interface.h" // Needed for propper settings in GPUParam.h using namespace o2::globaltracking; @@ -170,7 +174,7 @@ void MatchTPCITS::dumpABTracksDebugTree(const ABTrackLinksList& llist) dbgTrack.trackID = llist.trackID; dbgTrack.tpcLabel = lblTrc; dbgTrack.icCand = lnk.icCandID; - dbgTrack.icTimeBin = mInteractions[lnk.icCandID].timeBins; + dbgTrack.icTimeBin = mInteractions[lnk.icCandID].tBracket; const auto& tpcTrOrig = mTPCTracksArray[mTPCWork[llist.trackID].sourceID]; unsigned nclTPC = tpcTrOrig.getNClusterReferences(); dbgTrack.nClusTPC = nclTPC > 0xff ? 0xff : nclTPC; @@ -238,13 +242,13 @@ MatchTPCITS::MatchTPCITS() = default; MatchTPCITS::~MatchTPCITS() = default; //______________________________________________ -void MatchTPCITS::run() +void MatchTPCITS::run(const o2::globaltracking::RecoContainer& inp) { ///< perform matching for provided input if (!mInitDone) { LOG(FATAL) << "init() was not done yet"; } - + mStartIR = inp.startIR; updateTimeDependentParams(); ProcInfo_t procInfoStart, procInfoStop; @@ -256,6 +260,8 @@ void MatchTPCITS::run() clear(); + loadInput(inp); + if (!prepareITSTracks() || !prepareTPCTracks() || !prepareFITInfo()) { return; } @@ -301,6 +307,38 @@ void MatchTPCITS::run() mTFCount++; } +//______________________________________________ +void MatchTPCITS::loadInput(const o2::globaltracking::RecoContainer& inp) +{ + mITSTracksArray = inp.getITSTracks(); + mITSTrackClusIdx = inp.getITSTracksClusterRefs(); + mITSTrackROFRec = inp.getITSTracksROFRecords(); + + mITSClusterROFRec = inp.getITSClustersROFRecords(); + const auto patterns = inp.getITSClustersPatterns(); + const auto clusITS = inp.getITSClusters(); + auto pattIt = patterns.begin(); + mITSClustersArray.clear(); + mITSClustersArray.reserve(clusITS.size()); + o2::its::ioutils::convertCompactClusters(clusITS, pattIt, mITSClustersArray, *mITSDict); + + mTPCTracksArray = inp.getTPCTracks(); + mTPCTrackClusIdx = inp.getTPCTracksClusterRefs(); + mTPCClusterIdxStruct = &inp.inputsTPCclusters->clusterIndex; + mTPCRefitterShMap = inp.clusterShMapTPC; + if (mMCTruthON) { + mITSTrkLabels = inp.getITSTracksMCLabels(); + mTPCTrkLabels = inp.getTPCTracksMCLabels(); + mITSClsLabels = inp.mcITSClusters.get(); + } + + if (mUseFT0) { + mFITInfo = inp.getFT0RecPoints(); + } + + mTPCRefitter = std::make_unique(mTPCClusterIdxStruct, mTPCTransform.get(), mBz, mTPCTrackClusIdx.data(), mTPCRefitterShMap.data(), nullptr, o2::base::Propagator::Instance()); +} + //______________________________________________ void MatchTPCITS::end() { @@ -407,8 +445,6 @@ void MatchTPCITS::updateTimeDependentParams() mMinTPCTrackPtInv = (mFieldON && mParams->minTPCTrackR > 0) ? 1. / std::abs(mParams->minTPCTrackR * mBz * o2::constants::math::B2C) : 999.; mMinITSTrackPtInv = (mFieldON && mParams->minITSTrackR > 0) ? 1. / std::abs(mParams->minITSTrackR * mBz * o2::constants::math::B2C) : 999.; - mTPCRefitter = std::make_unique(mTPCClusterIdxStruct, mTPCTransform.get(), mBz, mTPCTrackClusIdx.data(), mTPCRefitterShMap.data(), nullptr, o2::base::Propagator::Instance()); - o2::math_utils::Point3D p0(90., 1., 1), p1(90., 100., 100.); auto matbd = o2::base::Propagator::Instance()->getMatBudget(mParams->matCorr, p0, p1); mTPCmeanX0Inv = matbd.meanX2X0 / matbd.length; @@ -529,7 +565,7 @@ bool MatchTPCITS::prepareTPCTracks() for (int sec = o2::constants::math::NSectors; sec--;) { mTPCSectIndexCache[sec].clear(); mTPCSectIndexCache[sec].reserve(100 + 1.2 * ntr / o2::constants::math::NSectors); - mTPCTimeBinStart[sec].clear(); + mTPCTimeStart[sec].clear(); } for (int it = 0; it < ntr; it++) { @@ -544,7 +580,7 @@ bool MatchTPCITS::prepareTPCTracks() if (trcOrig.getNClusterReferences() < mParams->minTPCClusters) { continue; } - // discard tracks w/o certain number of innermost pads (last cluster is innermost one + // discard tracks w/o certain number of innermost pads (last cluster is innermost one) { uint8_t clSect = 0, clRow = 0; uint32_t clIdx = 0; @@ -555,38 +591,29 @@ bool MatchTPCITS::prepareTPCTracks() } // create working copy of track param - mTPCWork.emplace_back(static_cast(trcOrig), it); - auto& trc = mTPCWork.back(); + float tBwd = trcOrig.getDeltaTBwd() + mTPCTimeEdgeTSafeMargin, tFwd = trcOrig.getDeltaTFwd() + mTPCTimeEdgeTSafeMargin; + auto& trc = mTPCWork.emplace_back(TrackLocTPC{trcOrig, + {tpcTimeBin2MUS(trcOrig.getTime0() - tBwd), tpcTimeBin2MUS(trcOrig.getTime0() + tFwd)}, + tpcTimeBin2MUS(trcOrig.getTime0()), + it, + MinusOne, + TrackLocTPC::Constrained}); // propagate to matching Xref if (!propagateToRefX(trc)) { mTPCWork.pop_back(); // discard track whose propagation to XMatchingRef failed continue; } + trc.constraint = trcOrig.hasASideClustersOnly() ? TrackLocTPC::ASide : (trcOrig.hasCSideClustersOnly() ? TrackLocTPC::CSide : TrackLocTPC::Constrained); + if (mMCTruthON) { mTPCLblWork.emplace_back(mTPCTrkLabels[it]); } - float time0 = trcOrig.getTime0(); - trc.timeBins.set(time0 - trcOrig.getDeltaTBwd() - mTPCTimeEdgeTSafeMargin, - time0 + trcOrig.getDeltaTFwd() + mTPCTimeEdgeTSafeMargin); - // assign min max possible Z for this track which still respects the clusters A/C side - if (trcOrig.hasASideClustersOnly()) { - trc.zMin = trc.getZ() - trcOrig.getDeltaTBwd() * mTPCBin2Z; - trc.zMax = trc.getZ() + trcOrig.getDeltaTFwd() * mTPCBin2Z; - } else if (trcOrig.hasCSideClustersOnly()) { - trc.zMin = trc.getZ() - trcOrig.getDeltaTFwd() * mTPCBin2Z; - trc.zMax = trc.getZ() + trcOrig.getDeltaTBwd() * mTPCBin2Z; - } - // TODO : special treatment of tracks crossing the CE - // cache work track index mTPCSectIndexCache[o2::math_utils::angle2Sector(trc.getAlpha())].push_back(mTPCWork.size() - 1); } - /// full drift time + safety margin - float maxTDriftSafe = (mNTPCBinsFullDrift + mParams->safeMarginTPCITSTimeBin + mTPCTimeEdgeTSafeMargin); - - float maxTimeBin = 0; + float maxTime = 0; int nITSROFs = mITSROFTimes.size(); // sort tracks in each sector according to their timeMax for (int sec = o2::constants::math::NSectors; sec--;) { @@ -598,45 +625,48 @@ bool MatchTPCITS::prepareTPCTracks() std::sort(indexCache.begin(), indexCache.end(), [this](int a, int b) { auto& trcA = mTPCWork[a]; auto& trcB = mTPCWork[b]; - return (trcA.timeBins.getMax() - trcB.timeBins.getMax()) < 0.; + return (trcA.tBracket.getMax() - trcB.tBracket.getMax()) < 0.; }); // build array of 1st entries with tmax corresponding to each ITS ROF (or trigger), // TPC tracks below this entry cannot match to ITS tracks of this and higher ROFs - float tmax = mTPCWork[indexCache.back()].timeBins.getMax(); - if (maxTimeBin < tmax) { - maxTimeBin = tmax; + float tmax = mTPCWork[indexCache.back()].tBracket.getMax(); + if (maxTime < tmax) { + maxTime = tmax; } - int nbins = 1 + tpcTimeBin2ITSROFrame(tmax); - auto& tbinStart = mTPCTimeBinStart[sec]; - tbinStart.resize(nbins, -1); + int nbins = 1 + time2ITSROFrame(tmax); + auto& timeStart = mTPCTimeStart[sec]; + timeStart.resize(nbins, -1); int itsROF = 0; - tbinStart[0] = 0; + timeStart[0] = 0; for (int itr = 0; itr < (int)indexCache.size(); itr++) { auto& trc = mTPCWork[indexCache[itr]]; - while (itsROF < nITSROFs && !(trc.timeBins < mITSROFTimes[itsROF])) { // 1st ITS frame afte max allowed time for this TPC track + while (itsROF < nITSROFs && !(trc.tBracket < mITSROFTimes[itsROF])) { // 1st ITS frame afte max allowed time for this TPC track itsROF++; } int itsROFMatch = itsROF; - if (itsROFMatch && tbinStart[--itsROFMatch] == -1) { // register ITSrof preceding the one which exceeds the TPC track tmax - tbinStart[itsROFMatch] = itr; + if (itsROFMatch && timeStart[--itsROFMatch] == -1) { // register ITSrof preceding the one which exceeds the TPC track tmax + timeStart[itsROFMatch] = itr; } } for (int i = 1; i < nbins; i++) { - if (tbinStart[i] == -1) { // fill gaps with preceding indices - tbinStart[i] = tbinStart[i - 1]; + if (timeStart[i] == -1) { // fill gaps with preceding indices + timeStart[i] = timeStart[i - 1]; } } } // loop over tracks of single sector // create mapping from TPC time-bins to ITS ROFs - if (mITSROFTimes.back() < maxTimeBin) { - maxTimeBin = mITSROFTimes.back().getMax(); + if (mITSROFTimes.back() < maxTime) { + maxTime = mITSROFTimes.back().getMax(); } - int nb = int(maxTimeBin) + 1; + + // FIXME + /* + int nb = int(maxTime) + 1; mITSROFofTPCBin.resize(nb, -1); int itsROF = 0; for (int ib = 0; ib < nb; ib++) { @@ -645,6 +675,7 @@ bool MatchTPCITS::prepareTPCTracks() } mITSROFofTPCBin[ib] = itsROF; } +*/ mTimer[SWPrepTPC].Stop(); return true; } @@ -678,19 +709,19 @@ bool MatchTPCITS::prepareITSTracks() for (int sec = o2::constants::math::NSectors; sec--;) { mITSSectIndexCache[sec].clear(); - mITSTimeBinStart[sec].clear(); - mITSTimeBinStart[sec].resize(nROFs, -1); // start of ITS work tracks in every sector + mITSTimeStart[sec].clear(); + mITSTimeStart[sec].resize(nROFs, -1); // start of ITS work tracks in every sector } mITSTrackROFContMapping.clear(); // there might be gaps in the non-empty rofs, this will map continuous ROFs index to non empty ones - setStartIR(mITSTrackROFRec[0].getBCData()); //// TODO: this should be set from external info - for (int irof = 0; irof < nROFs; irof++) { const auto& rofRec = mITSTrackROFRec[irof]; - + int nBC = rofRec.getBCData().differenceInBC(mStartIR); + float tMin = nBC * o2::constants::lhc::LHCBunchSpacingMUS; + float tMax = (nBC + mITSROFrameLengthInBC) * o2::constants::lhc::LHCBunchSpacingMUS; if (!mITSTriggered) { - auto irofCont = (rofRec.getBCData().toLong() - mStartIR.toLong()) / mITSROFrameLengthInBC; + auto irofCont = nBC / mITSROFrameLengthInBC; if (mITSTrackROFContMapping.size() <= irofCont) { mITSTrackROFContMapping.resize((1 + irofCont / 128) * 128, 0); } @@ -698,11 +729,10 @@ bool MatchTPCITS::prepareITSTracks() } int cluROFOffset = mITSClusterROFRec[irof].getFirstEntry(); // clusters of this ROF start at this offset - float tmn = intRecord2TPCTimeBin(rofRec.getBCData()); // ITS track min time in TPC time-bins - mITSROFTimes.emplace_back(tmn, tmn + mITSROFrame2TPCBin); // ITS track min/max time in TPC time-bins + mITSROFTimes.emplace_back(tMin, tMax); // ITS ROF min/max time for (int sec = o2::constants::math::NSectors; sec--;) { // start of sector's tracks for this ROF - mITSTimeBinStart[sec][irof] = mITSSectIndexCache[sec].size(); // The sorting does not affect this + mITSTimeStart[sec][irof] = mITSSectIndexCache[sec].size(); // The sorting does not affect this } int trlim = rofRec.getFirstEntry() + rofRec.getNEntries(); @@ -719,7 +749,7 @@ bool MatchTPCITS::prepareITSTracks() } int nWorkTracks = mITSWork.size(); // working copy of outer track param - auto& trc = mITSWork.emplace_back(static_cast(trcOrig.getParamOut()), it); + auto& trc = mITSWork.emplace_back(TrackLocITS{trcOrig.getParamOut(), {tMin, tMax}, it, irof, MinusOne}); if (!trc.rotate(o2::math_utils::angle2Alpha(trc.getPhiPos()))) { mITSWork.pop_back(); // discard failed track continue; @@ -732,8 +762,6 @@ bool MatchTPCITS::prepareITSTracks() if (mMCTruthON) { mITSLblWork.emplace_back(mITSTrkLabels[it]); } - trc.roFrame = irof; - // cache work track index int sector = o2::math_utils::angle2Sector(trc.getAlpha()); mITSSectIndexCache[sector].push_back(nWorkTracks); @@ -744,16 +772,16 @@ bool MatchTPCITS::prepareITSTracks() // [(Xr*tg(10)-Yr)/(tgPhir+tg70)]^2 / cos(70)^2 // for the next sector // [(Xr*tg(10)+Yr)/(tgPhir-tg70)]^2 / cos(70)^2 // for the prev sector // Distances to the sector edges in neighbourings sectors (at Xref in theit proper frames) - float tgp = trc.getSnp(), trcY = trc.getY(); + float tgp = trc.getSnp(); tgp /= std::sqrt((1.f - tgp) * (1.f + tgp)); // tan of track direction XY // sector up - float dy2Up = (YMaxAtXMatchingRef - trcY) / (tgp + Tan70); + float dy2Up = (YMaxAtXMatchingRef - trc.getY()) / (tgp + Tan70); if ((dy2Up * dy2Up * Cos70I2) < mSectEdgeMargin2) { // need to check this track for matching in sector up addLastTrackCloneForNeighbourSector(sector < (o2::constants::math::NSectors - 1) ? sector + 1 : 0); } // sector down - float dy2Dn = (YMaxAtXMatchingRef + trcY) / (tgp - Tan70); + float dy2Dn = (YMaxAtXMatchingRef + trc.getY()) / (tgp - Tan70); if ((dy2Dn * dy2Dn * Cos70I2) < mSectEdgeMargin2) { // need to check this track for matching in sector down addLastTrackCloneForNeighbourSector(sector > 1 ? sector - 1 : o2::constants::math::NSectors - 1); } @@ -779,9 +807,9 @@ bool MatchTPCITS::prepareITSTracks() std::sort(indexCache.begin(), indexCache.end(), [this](int a, int b) { auto& trackA = mITSWork[a]; auto& trackB = mITSWork[b]; - if (trackA.roFrame < trackB.roFrame) { // ITS tracks have the same time coverage + if (trackA.tBracket < trackB.tBracket) { return true; - } else if (trackA.roFrame > trackB.roFrame) { + } else if (trackA.tBracket > trackB.tBracket) { return false; } return trackA.getTgl() < trackB.getTgl(); @@ -806,8 +834,8 @@ void MatchTPCITS::doMatching(int sec) ///< run matching for currently cached ITS data for given TPC sector auto& cacheITS = mITSSectIndexCache[sec]; // array of cached ITS track indices for this sector auto& cacheTPC = mTPCSectIndexCache[sec]; // array of cached ITS track indices for this sector - auto& tbinStartTPC = mTPCTimeBinStart[sec]; // array of 1st TPC track with timeMax in ITS ROFrame - auto& tbinStartITS = mITSTimeBinStart[sec]; + auto& timeStartTPC = mTPCTimeStart[sec]; // array of 1st TPC track with timeMax in ITS ROFrame + auto& timeStartITS = mITSTimeStart[sec]; int nTracksTPC = cacheTPC.size(), nTracksITS = cacheITS.size(); if (!nTracksTPC || !nTracksITS) { LOG(INFO) << "Matchng sector " << sec << " : N tracks TPC:" << nTracksTPC << " ITS:" << nTracksITS << " in sector " << sec; @@ -815,55 +843,52 @@ void MatchTPCITS::doMatching(int sec) } /// full drift time + safety margin - float maxTDriftSafe = (mNTPCBinsFullDrift + mParams->safeMarginTPCITSTimeBin + mTPCTimeEdgeTSafeMargin); + float maxTDriftSafe = tpcTimeBin2MUS(mNTPCBinsFullDrift + mParams->safeMarginTPCITSTimeBin + mTPCTimeEdgeTSafeMargin); + float vdErrT = tpcTimeBin2MUS(mZ2TPCBin * mParams->maxVDriftUncertainty); - float vdErr2TB = mZ2TPCBin * mParams->maxVDriftUncertainty; - - // get min ROFrame (in TPC time-bins) of ITS tracks currently in cache + // get min ROFrame of ITS tracks currently in cache auto minROFITS = mITSWork[cacheITS.front()].roFrame; - if (minROFITS >= int(tbinStartTPC.size())) { + if (minROFITS >= int(timeStartTPC.size())) { LOG(INFO) << "ITS min ROFrame " << minROFITS << " exceeds all cached TPC track ROF eqiuvalent " << cacheTPC.size() - 1; return; } int nCheckTPCControl = 0, nCheckITSControl = 0, nMatchesControl = 0; // temporary - int idxMinTPC = tbinStartTPC[minROFITS]; // index of 1st cached TPC track within cached ITS ROFrames - auto t2nbs = mZ2TPCBin * mParams->tpcTimeICMatchingNSigma; + int idxMinTPC = timeStartTPC[minROFITS]; // index of 1st cached TPC track within cached ITS ROFrames + auto t2nbs = tpcTimeBin2MUS(mZ2TPCBin * mParams->tpcTimeICMatchingNSigma); // FIXME work directly with time in \mus bool checkInteractionCandidates = mUseFT0 && mParams->validateMatchByFIT != MatchTPCITSParams::Disable; + for (int itpc = idxMinTPC; itpc < nTracksTPC; itpc++) { auto& trefTPC = mTPCWork[cacheTPC[itpc]]; // estimate ITS 1st ROframe bin this track may match to: TPC track are sorted according to their // timeMax, hence the timeMax - MaxmNTPCBinsFullDrift are non-decreasing - int itsROBin = tpcTimeBin2ITSROFrame(trefTPC.timeBins.getMax() - maxTDriftSafe); + int itsROBin = time2ITSROFrame(trefTPC.tBracket.getMax() - maxTDriftSafe); - if (itsROBin >= int(tbinStartITS.size())) { // time of TPC track exceeds the max time of ITS in the cache + if (itsROBin >= int(timeStartITS.size())) { // time of TPC track exceeds the max time of ITS in the cache break; } - int iits0 = tbinStartITS[itsROBin]; + int iits0 = timeStartITS[itsROBin]; nCheckTPCControl++; for (auto iits = iits0; iits < nTracksITS; iits++) { auto& trefITS = mITSWork[cacheITS[iits]]; - const auto& timeITS = mITSROFTimes[trefITS.roFrame]; // compare if the ITS and TPC tracks may overlap in time - if (trefTPC.timeBins < timeITS) { - // since TPC tracks are sorted in timeMax and ITS tracks are sorted in timeMin - // all following ITS tracks also will not match + if (trefTPC.tBracket < trefITS.tBracket) { // since TPC tracks are sorted in timeMax and ITS tracks are sorted in timeMin all following ITS tracks also will not match break; } - if (trefTPC.timeBins > timeITS) { // its bracket precedes TPC bracket + if (trefTPC.tBracket > trefITS.tBracket) { // its bracket precedes TPC bracket continue; } - // is corrected TPC track time compatible with ITS ROF expressed in TPC bins? - auto deltaT = (trefITS.getZ() - trefTPC.getZ()) * mZ2TPCBin; // time difference in TPC time bins corresponding to Z differences - auto timeTB = getTPCTrackCorrectedTimeBin(mTPCTracksArray[trefTPC.sourceID], deltaT); // TPC time required to match to Z of ITS track - auto timeTBErr = std::sqrt(trefITS.getSigmaZ2() + trefTPC.getSigmaZ2()) * t2nbs; // nsigma*error in number of TPC time bins + // is corrected TPC track time compatible with ITS ROF expressed + auto deltaT = (trefITS.getZ() - trefTPC.getZ()) * mTPCVDrift0Inv; // drift time difference corresponding to Z differences + auto timeCorr = trefTPC.getCorrectedTime(deltaT); // TPC time required to match to Z of ITS track + auto timeCorrErr = std::sqrt(trefITS.getSigmaZ2() + trefTPC.getSigmaZ2()) * t2nbs; // nsigma*error if (mVDriftCalibOn) { - timeTBErr += vdErr2TB * (250. - abs(trefITS.getZ())); // account for the extra error from TPC VDrift uncertainty + timeCorrErr += vdErrT * (250. - abs(trefITS.getZ())); // account for the extra error from TPC VDrift uncertainty } - o2::math_utils::Bracket trange(timeTB - timeTBErr, timeTB + timeTBErr); - if (timeITS.isOutside(trange)) { + o2::math_utils::Bracket trange(timeCorr - timeCorrErr, timeCorr + timeCorrErr); + if (trefITS.tBracket.isOutside(trange)) { continue; } @@ -884,12 +909,12 @@ void MatchTPCITS::doMatching(int sec) int rof = trefITS.roFrame; bool stop = false; do { - if (++rof >= int(tbinStartITS.size())) { + if (++rof >= int(timeStartITS.size())) { stop = true; break; // no more ITS ROFrames in cache } - iits = tbinStartITS[rof] - 1; // next track to be checked -1 - } while (iits <= tbinStartITS[trefITS.roFrame]); // skip empty bins + iits = timeStartITS[rof] - 1; // next track to be checked -1 + } while (iits <= timeStartITS[trefITS.roFrame]); // skip empty bins if (stop) { break; } @@ -901,7 +926,7 @@ void MatchTPCITS::doMatching(int sec) int matchedIC = MinusOne; if (!isCosmics()) { // validate by bunch filling scheme - auto irBracket = tpcTimeBin2IRBracket(trange); + auto irBracket = tBracket2IRBracket(trange); if (irBracket.isInvalid()) { continue; } @@ -913,11 +938,11 @@ void MatchTPCITS::doMatching(int sec) if (nic) { int idIC = interactionRefs.getFirstEntry(), maxIC = idIC + nic; for (; idIC < maxIC; idIC++) { - auto cmp = mInteractions[idIC].timeBins.isOutside(trange); - if (cmp == o2::math_utils::Bracket::Above) { // trange is above this interaction candidate, the following ones may match + auto cmp = mInteractions[idIC].tBracket.isOutside(trange); + if (cmp == o2::math_utils::Bracketf_t::Above) { // trange is above this interaction candidate, the following ones may match continue; } - if (cmp == o2::math_utils::Bracket::Inside) { + if (cmp == o2::math_utils::Bracketf_t::Inside) { matchedIC = idIC; } break; // we loop till 1st matching IC or the one above the trange (since IC are ordered, all others will be above too) @@ -1088,7 +1113,7 @@ int MatchTPCITS::compareTPCITSTracks(const TrackLocITS& tITS, const TrackLocTPC& return rejFlag; } - if (mCompareTracksDZ) { // in continuous mode we usually don't use DZ + if (tTPC.constraint == TrackLocTPC::Constrained) { // in continuous only constrained tracks can be compared in Z diff = tITS.getParam(o2::track::kZ) - tTPC.getParam(o2::track::kZ); if ((rejFlag = roughCheckDif(diff, mParams->crudeAbsDiffCut[o2::track::kZ], RejectOnZ))) { return rejFlag; @@ -1097,13 +1122,6 @@ int MatchTPCITS::compareTPCITSTracks(const TrackLocITS& tITS, const TrackLocTPC& if ((rejFlag = roughCheckDif(diff, mParams->crudeNSigma2Cut[o2::track::kZ], RejectOnZ + NSigmaShift))) { return rejFlag; } - } else { // in continuous mode we use special check on allowed Z range - if (tITS.getParam(o2::track::kZ) - tTPC.zMax > mParams->crudeAbsDiffCut[o2::track::kZ]) { - return RejectOnZ; - } - if (tITS.getParam(o2::track::kZ) - tTPC.zMin < -mParams->crudeAbsDiffCut[o2::track::kZ]) { - return -RejectOnZ; - } } diff = tITS.getParam(o2::track::kSnp) - tTPC.getParam(o2::track::kSnp); @@ -1358,8 +1376,7 @@ bool MatchTPCITS::refitTrackTPCITS(int iTPC, int& iITS) if (!mCompareTracksDZ) { trfit.setZ(tITS.getZ()); // fix the seed Z } - auto dzCorr = trfit.getZ() - tTPC.getZ(); - float deltaT = dzCorr * mZ2TPCBin; // time correction in time-bins + float deltaT = (trfit.getZ() - tTPC.getZ()) * mTPCVDrift0Inv; // time correction in \mus // refit TPC track inward into the ITS int nclRefit = 0, ncl = itsTrOrig.getNumberOfClusters(); @@ -1413,25 +1430,12 @@ bool MatchTPCITS::refitTrackTPCITS(int iTPC, int& iITS) LOG(ERROR) << "LTOF integral might be incorrect"; } - /// precise time estimate - const auto& tpcTrOrig = mTPCTracksArray[tTPC.sourceID]; - float timeTB = tpcTrOrig.getTime0(); - if (tpcTrOrig.hasASideClustersOnly()) { - timeTB += deltaT; - } else if (tpcTrOrig.hasCSideClustersOnly()) { - timeTB -= deltaT; - } else { - // TODO : special treatment of tracks crossing the CE - } - // convert time in timebins to time in microseconds - float time = timeTB * mTPCTBinMUS; - // estimate the error on time - float timeErr = std::sqrt(tITS.getSigmaZ2() + tTPC.getSigmaZ2()) * mTPCVDrift0Inv; + float time = tTPC.getCorrectedTime(deltaT); /// precise time estimate + float timeErr = std::sqrt(tITS.getSigmaZ2() + tTPC.getSigmaZ2()) * mTPCVDrift0Inv; // estimate the error on time // outward refit auto& tracOut = trfit.getParamOut(); // this is a clone of ITS outward track already at the matching reference X auto& tofL = trfit.getLTIntegralOut(); - { float xtogo = 0; if (!tracOut.getXatLabR(o2::constants::geom::XTPCInnerRef, xtogo, mBz, o2::track::DirOutward) || @@ -1445,7 +1449,7 @@ bool MatchTPCITS::refitTrackTPCITS(int iTPC, int& iITS) } float chi2Out = 0; auto posStart = tracOut.getXYZGlo(); - int retVal = mTPCRefitter->RefitTrackAsTrackParCov(tracOut, tpcTrOrig.getClusterRef(), timeTB, &chi2Out, true, false); // outward refit + int retVal = mTPCRefitter->RefitTrackAsTrackParCov(tracOut, mTPCTracksArray[tTPC.sourceID].getClusterRef(), time * mTPCTBinMUSInv, &chi2Out, true, false); // outward refit if (retVal < 0) { LOG(DEBUG) << "Refit failed"; mMatchedTracks.pop_back(); // destroy failed track @@ -1556,7 +1560,7 @@ int MatchTPCITS::prepareTPCTracksAfterBurner() std::sort(mTPCABIndexCache.begin(), mTPCABIndexCache.end(), [this](int a, int b) { auto& trcA = mTPCWork[a]; auto& trcB = mTPCWork[b]; - return (trcA.timeBins.getMin() - trcB.timeBins.getMin()) < 0.; + return (trcA.tBracket.getMin() - trcB.tBracket.getMin()) < 0.; }); return mTPCABIndexCache.size(); @@ -1566,7 +1570,7 @@ int MatchTPCITS::prepareTPCTracksAfterBurner() int MatchTPCITS::prepareInteractionTimes() { // guess interaction times from various sources and relate with ITS rofs - float ft0UncertaintyTB = 0.5e-3 * mTPCTBinMUSInv; // assumed T0 time uncertainty (~0.5ns) in TPC timeBins + const float ft0Uncertainty = 0.5e-3; mInteractions.clear(); mITSROFIntCandEntries.clear(); int nITSROFs = mITSROFTimes.size(); @@ -1578,7 +1582,7 @@ int MatchTPCITS::prepareInteractionTimes() if (!mFT0Params->isSelected(ft)) { continue; } - auto fitTime = time2TPCTimeBin(ft.getInteractionRecord().differenceInBCNS(mStartIR) * 1e-3); // FIT time in TPC timebins + auto fitTime = ft.getInteractionRecord().differenceInBCMS(mStartIR); // find corresponding ITS ROF, works both in cont. and trigg. modes (ignore T0 MeanTime within the BC) for (; rof < nITSROFs; rof++) { if (mITSROFTimes[rof] < fitTime) { @@ -1590,7 +1594,7 @@ int MatchTPCITS::prepareInteractionTimes() ref.setFirstEntry(mInteractions.size()); // register entry } ref.changeEntriesBy(1); // increment counter - mInteractions.emplace_back(ft.getInteractionRecord(), fitTime, ft0UncertaintyTB, rof, o2::detectors::DetID::FT0); + mInteractions.emplace_back(ft.getInteractionRecord(), fitTime, ft0Uncertainty, rof, o2::detectors::DetID::FT0); } break; // this or next ITSrof in time is > fitTime } @@ -1617,7 +1621,7 @@ void MatchTPCITS::runAfterBurner() const auto& tTPC = mTPCWork[mTPCABIndexCache[itr]]; // find 1st interaction candidate compatible with time brackets of this track int iCRes; - while ((iCRes = tTPC.timeBins.isOutside(mInteractions[iC].timeBins)) < 0 && ++iC < nIntCand) { // interaction precedes the track time-bracket + while ((iCRes = tTPC.tBracket.isOutside(mInteractions[iC].tBracket)) < 0 && ++iC < nIntCand) { // interaction precedes the track time-bracket cleanAfterBurnerClusRefCache(iC, iCClean); // if possible, clean unneeded cached cluster references } if (iCRes == 0) { @@ -1630,7 +1634,7 @@ void MatchTPCITS::runAfterBurner() int ncl = mITSChipClustersRefs.back().clusterID.size(); printf("loaded %d clusters at cache at %p\n", ncl, mInteractions[iCEnd].clRefPtr); } - } while (++iCEnd < nIntCand && !tTPC.timeBins.isOutside(mInteractions[iCEnd].timeBins)); + } while (++iCEnd < nIntCand && !tTPC.tBracket.isOutside(mInteractions[iCEnd].tBracket)); auto lbl = mTPCLblWork[mTPCABIndexCache[itr]]; // tmp if (runAfterBurner(mTPCABIndexCache[itr], iCStart, iCEnd)) { @@ -1645,7 +1649,7 @@ void MatchTPCITS::runAfterBurner() } else if (iCRes > 0) { continue; // TPC track precedes the interaction (means orphan track?), no need to check it } else { - LOG(INFO) << "All interaction candidates precede track " << itr << " [" << tTPC.timeBins.getMin() << ":" << tTPC.timeBins.getMax() << "]"; + LOG(INFO) << "All interaction candidates precede track " << itr << " [" << tTPC.tBracket.getMin() << ":" << tTPC.tBracket.getMax() << "]"; break; // all interaction candidates precede TPC track } } @@ -1689,8 +1693,8 @@ bool MatchTPCITS::runAfterBurner(int tpcWID, int iCStart, int iCEnd) /* // tmp LOG(INFO) << "Check track TPC mtc=" << tTPC.matchID << " int.cand. " << iCC - << " [" << tTPC.timeBins.getMin() << ":" << tTPC.timeBins.getMax() << "] for interaction " - << " [" << iCCand.timeBins.getMin() << ":" << iCCand.timeBins.getMax() << "]"; + << " [" << tTPC.tBracket.getMin() << ":" << tTPC.tBracket.getMax() << "] for interaction " + << " [" << iCCand.tBracket.getMin() << ":" << iCCand.tBracket.getMax() << "]"; */ if (std::abs(topLink.getZ()) > mITSFiducialZCut) { // we can discard this seed topLink.disable(); @@ -2088,12 +2092,12 @@ float MatchTPCITS::correctTPCTrack(o2::track::TrackParCov& trc, const TrackLocTP // return extra uncertainty in Z due to the interaction time incertainty // TODO: at the moment, apply simple shift, but with Z-dependent calibration we may // need to do corrections on TPC cluster level and refit - auto tpcTrOrig = mTPCTracksArray[tTPC.sourceID]; - if (tpcTrOrig.hasBothSidesClusters()) { - return 0.; + if (tTPC.constraint == TrackLocTPC::Constrained) { + return 0.f; } - float timeIC = cand.timeBins.mean(), timeTrc = tpcTrOrig.getTime0(); - float driftErr = cand.timeBins.delta() * mTPCBin2Z; + auto tpcTrOrig = mTPCTracksArray[tTPC.sourceID]; + float timeIC = cand.tBracket.mean(); + float driftErr = cand.tBracket.delta() * mTPCBin2Z; // we use this for refit /* @@ -2114,14 +2118,14 @@ float MatchTPCITS::correctTPCTrack(o2::track::TrackParCov& trc, const TrackLocTP */ // if interaction time precedes the initial assumption on t0 (i.e. timeIC < timeTrc), // the track actually was drifting longer, i.e. tracks should be shifted closer to the CE - float dDrift = (timeIC - timeTrc) * mTPCBin2Z; + float dDrift = (timeIC - tTPC.time0) * mTPCBin2Z; float zz = tTPC.getZ() + (tpcTrOrig.hasASideClustersOnly() ? dDrift : -dDrift); // tmp - LOG(INFO) << "CorrTrack Z=" << trc.getZ() << " (zold= " << zz << ") at TIC= " << timeIC << " Ttr= " << timeTrc; // tmp + LOG(INFO) << "CorrTrack Z=" << trc.getZ() << " (zold= " << zz << ") at TIC= " << timeIC << " Ttr= " << tTPC.time0; // tmp // we use this w/o refit // /* { - trc.setZ(tTPC.getZ() + (tpcTrOrig.hasASideClustersOnly() ? dDrift : -dDrift)); + trc.setZ(tTPC.getZ() + (tTPC.constraint == TrackLocTPC::ASide ? dDrift : -dDrift)); } // */ trc.setCov(trc.getSigmaZ2() + driftErr * driftErr, o2::track::kSigZ2); @@ -2417,6 +2421,7 @@ void MatchTPCITS::setITSROFrameLengthInBC(int nbc) { mITSROFrameLengthInBC = nbc; mITSROFrameLengthMUS = nbc * o2::constants::lhc::LHCBunchSpacingNS * 1e-3; + mITSROFrameLengthMUSInv = 1. / mITSROFrameLengthMUS; } //___________________________________________________________________ @@ -2445,14 +2450,14 @@ void MatchTPCITS::setBunchFilling(const o2::BunchFilling& bf) } //___________________________________________________________________ -MatchTPCITS::BracketIR MatchTPCITS::tpcTimeBin2IRBracket(const BracketF tbrange) +MatchTPCITS::BracketIR MatchTPCITS::tBracket2IRBracket(const BracketF tbrange) { - // convert TPC timebins bracket to IR bracket + // convert time bracket to IR bracket o2::InteractionRecord irMin(mStartIR), irMax(mStartIR); if (tbrange.getMin() > 0) { - irMin += o2::InteractionRecord(tpcTimeBin2NS(tbrange.getMin())); + irMin += o2::InteractionRecord(tbrange.getMin() * 1000.f); // time in ns is needed } - irMax += o2::InteractionRecord(tpcTimeBin2NS(tbrange.getMax())); + irMax += o2::InteractionRecord(tbrange.getMax() * 1000.f); irMax++; // to account for rounding int bc = mClosestBunchAbove[irMin.bc]; if (bc < irMin.bc) { @@ -2567,7 +2572,7 @@ void MatchTPCITS::cleanAfterBurnerClusRefCache(int currentIC, int& startIC) { // check if some of cached cluster reference from tables startIC to currentIC can be released, // they will be necessarily in front slots of the mITSChipClustersRefs - while (startIC < currentIC && mInteractions[currentIC].timeBins.getMin() - mInteractions[startIC].timeBins.getMax() > MinTBToCleanCache) { + while (startIC < currentIC && mInteractions[currentIC].tBracket.getMin() - mInteractions[startIC].tBracket.getMax() > MinTBToCleanCache) { LOG(INFO) << "CAN REMOVE CACHE FOR " << startIC << " curent IC=" << currentIC; while (mInteractions[startIC].clRefPtr == &mITSChipClustersRefs.front()) { LOG(INFO) << "Reset cache pointer" << mInteractions[startIC].clRefPtr << " for IC=" << startIC; diff --git a/Detectors/GlobalTrackingWorkflow/CMakeLists.txt b/Detectors/GlobalTrackingWorkflow/CMakeLists.txt index 78668d43b4f1b..8d01f6a62a719 100644 --- a/Detectors/GlobalTrackingWorkflow/CMakeLists.txt +++ b/Detectors/GlobalTrackingWorkflow/CMakeLists.txt @@ -13,7 +13,6 @@ o2_add_library(GlobalTrackingWorkflow SOURCES src/TrackWriterTPCITSSpec.cxx src/TPCITSMatchingSpec.cxx - src/MatchTPCITSWorkflow.cxx src/PrimaryVertexingSpec.cxx src/PrimaryVertexWriterSpec.cxx src/VertexTrackMatcherSpec.cxx diff --git a/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/TPCITSMatchingSpec.h b/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/TPCITSMatchingSpec.h index 121973ff294fa..9b4b1679b9c6a 100644 --- a/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/TPCITSMatchingSpec.h +++ b/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/TPCITSMatchingSpec.h @@ -13,6 +13,7 @@ #ifndef O2_MATCHING_TPCITS_SPEC #define O2_MATCHING_TPCITS_SPEC +#include "ReconstructionDataFormats/GlobalTrackID.h" using namespace o2::framework; @@ -21,7 +22,7 @@ namespace o2 namespace globaltracking { /// create a processor spec -framework::DataProcessorSpec getTPCITSMatchingSpec(bool useFT0, bool calib, bool useMC); +framework::DataProcessorSpec getTPCITSMatchingSpec(o2::dataformats::GlobalTrackID::mask_t src, bool useFT0, bool calib, bool useMC); } // namespace globaltracking } // namespace o2 diff --git a/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx index 41c7f94924804..7afa554a02ff1 100644 --- a/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx @@ -140,7 +140,6 @@ void CosmicsMatchingSpec::endOfStream(EndOfStreamContext& ec) DataProcessorSpec getCosmicsMatchingSpec(GTrackID::mask_t src, bool useMC) { - std::vector inputs; std::vector outputs; dataRequestCosm.requestTracks(src, useMC); diff --git a/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx index c34670705e779..a0b2daf04f138 100644 --- a/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx @@ -36,25 +36,25 @@ #include "DetectorsBase/Propagator.h" #include "ITSMFTBase/DPLAlpideParam.h" #include "GlobalTracking/MatchTPCITSParams.h" -#include "ITStracking/IOUtils.h" #include "DetectorsCommonDataFormats/NameConf.h" #include "DataFormatsParameters/GRPObject.h" #include "Headers/DataHeader.h" #include "CommonDataFormat/BunchFilling.h" #include "CommonDataFormat/FlatHisto2D.h" - -// RSTODO to remove once the framework will start propagating the header.firstTForbit -#include "DetectorsRaw/HBFUtils.h" +#include "DataFormatsGlobalTracking/RecoContainer.h" using namespace o2::framework; using MCLabelsCl = o2::dataformats::MCTruthContainer; using MCLabelsTr = gsl::span; +using GTrackID = o2::dataformats::GlobalTrackID; namespace o2 { namespace globaltracking { +DataRequest dataRequestTPCITSMatch; + class TPCITSMatchingDPL : public Task { public: @@ -100,6 +100,7 @@ void TPCITSMatchingDPL::init(InitContext& ic) } else { LOG(INFO) << "Dictionary " << dictFile << " is absent, Matching expects ITS cluster patterns"; } + mMatching.setITSDictionary(&mITSDict); // this is a hack to provide Mat.LUT from the local file, in general will be provided by the framework from CCDB std::string matLUTPath = ic.options().get("material-lut-path"); @@ -126,69 +127,13 @@ void TPCITSMatchingDPL::init(InitContext& ic) void TPCITSMatchingDPL::run(ProcessingContext& pc) { - mTimer.Start(false); - const auto tracksITS = pc.inputs().get>("trackITS"); - const auto trackClIdxITS = pc.inputs().get>("trackClIdx"); - const auto tracksITSROF = pc.inputs().get>("trackITSROF"); - const auto clusITS = pc.inputs().get>("clusITS"); - const auto clusITSROF = pc.inputs().get>("clusITSROF"); - const auto patterns = pc.inputs().get>("clusITSPatt"); - const auto tracksTPC = pc.inputs().get>("trackTPC"); - const auto tracksTPCClRefs = pc.inputs().get>("trackTPCClRefs"); - - const auto clusTPCShmap = pc.inputs().get>("clusTPCshmap"); - - const auto& inputsTPCclusters = o2::tpc::getWorkflowTPCInput(pc); - - // - MCLabelsTr lblITS; - MCLabelsTr lblTPC; - - const MCLabelsCl* lblClusITSPtr = nullptr; - std::unique_ptr lblClusITS; - - if (mUseMC) { - lblITS = pc.inputs().get>("trackITSMCTR"); - lblTPC = pc.inputs().get>("trackTPCMCTR"); - - lblClusITS = pc.inputs().get*>("clusITSMCTR"); - lblClusITSPtr = lblClusITS.get(); - } - // - // create ITS clusters as spacepoints in tracking frame - std::vector> itsSP; - itsSP.reserve(clusITS.size()); - auto pattIt = patterns.begin(); - o2::its::ioutils::convertCompactClusters(clusITS, pattIt, itsSP, mITSDict); - - // pass input data to MatchTPCITS object - mMatching.setITSTracksInp(tracksITS); - mMatching.setITSTrackClusIdxInp(trackClIdxITS); - mMatching.setITSTrackROFRecInp(tracksITSROF); - mMatching.setITSClustersInp(itsSP); - mMatching.setITSClusterROFRecInp(clusITSROF); - mMatching.setTPCTracksInp(tracksTPC); - mMatching.setTPCTrackClusIdxInp(tracksTPCClRefs); - mMatching.setTPCClustersInp(&inputsTPCclusters->clusterIndex); - mMatching.setTPCClustersSharingMap(clusTPCShmap); - - if (mUseMC) { - mMatching.setITSTrkLabelsInp(lblITS); - mMatching.setTPCTrkLabelsInp(lblTPC); - mMatching.setITSClsLabelsInp(lblClusITSPtr); - } - - if (mUseFT0) { - // Note: the particular variable will go out of scope, but the span is passed by copy to the - // worker and the underlying memory is valid throughout the whole computation - auto fitInfo = pc.inputs().get>("fitInfo"); - mMatching.setFITInfoInp(fitInfo); - } - const auto* dh = o2::header::get(pc.inputs().getByPos(0).header); - mMatching.setStartIR({0, dh->firstTForbit}); + LOG(INFO) << " startOrbit: " << dh->firstTForbit; + mTimer.Start(false); + RecoContainer recoData; + recoData.collectData(pc, dataRequestTPCITSMatch); - mMatching.run(); + mMatching.run(recoData); pc.outputs().snapshot(Output{"GLO", "TPCITS", 0, Lifetime::Timeframe}, mMatching.getMatchedTracks()); if (mUseMC) { @@ -200,7 +145,6 @@ void TPCITSMatchingDPL::run(ProcessingContext& pc) pc.outputs().snapshot(Output{"GLO", "TPCITS_VDHDTGL", 0, Lifetime::Timeframe}, (*hdtgl).getBase()); hdtgl->clear(); } - mTimer.Stop(); } @@ -211,25 +155,15 @@ void TPCITSMatchingDPL::endOfStream(EndOfStreamContext& ec) mTimer.CpuTime(), mTimer.RealTime(), mTimer.Counter() - 1); } -DataProcessorSpec getTPCITSMatchingSpec(bool useFT0, bool calib, bool useMC) +DataProcessorSpec getTPCITSMatchingSpec(GTrackID::mask_t src, bool useFT0, bool calib, bool useMC) { - std::vector inputs; std::vector outputs; - inputs.emplace_back("trackITS", "ITS", "TRACKS", 0, Lifetime::Timeframe); - inputs.emplace_back("trackClIdx", "ITS", "TRACKCLSID", 0, Lifetime::Timeframe); - inputs.emplace_back("trackITSROF", "ITS", "ITSTrackROF", 0, Lifetime::Timeframe); - inputs.emplace_back("clusITS", "ITS", "COMPCLUSTERS", 0, Lifetime::Timeframe); - inputs.emplace_back("clusITSPatt", "ITS", "PATTERNS", 0, Lifetime::Timeframe); - inputs.emplace_back("clusITSROF", "ITS", "CLUSTERSROF", 0, Lifetime::Timeframe); - inputs.emplace_back("trackTPC", "TPC", "TRACKS", 0, Lifetime::Timeframe); - inputs.emplace_back("trackTPCClRefs", "TPC", "CLUSREFS", 0, Lifetime::Timeframe); - - inputs.emplace_back("clusTPC", ConcreteDataTypeMatcher{"TPC", "CLUSTERNATIVE"}, Lifetime::Timeframe); - inputs.emplace_back("clusTPCshmap", "TPC", "CLSHAREDMAP", 0, Lifetime::Timeframe); + dataRequestTPCITSMatch.requestTracks(src, useMC); + dataRequestTPCITSMatch.requestClusters(src, false); // no MC labels for clusters needed for refit only if (useFT0) { - inputs.emplace_back("fitInfo", "FT0", "RECPOINTS", 0, Lifetime::Timeframe); + dataRequestTPCITSMatch.requestFT0RecPoints(false); } outputs.emplace_back("GLO", "TPCITS", 0, Lifetime::Timeframe); @@ -239,16 +173,13 @@ DataProcessorSpec getTPCITSMatchingSpec(bool useFT0, bool calib, bool useMC) } if (useMC) { - inputs.emplace_back("trackITSMCTR", "ITS", "TRACKSMCTR", 0, Lifetime::Timeframe); - inputs.emplace_back("trackTPCMCTR", "TPC", "TRACKSMCLBL", 0, Lifetime::Timeframe); - inputs.emplace_back("clusITSMCTR", "ITS", "CLUSTERSMCTR", 0, Lifetime::Timeframe); - // + dataRequestTPCITSMatch.inputs.emplace_back("clusITSMCTR", "ITS", "CLUSTERSMCTR", 0, Lifetime::Timeframe); // for afterburner outputs.emplace_back("GLO", "TPCITS_MC", 0, Lifetime::Timeframe); } return DataProcessorSpec{ "itstpc-track-matcher", - inputs, + dataRequestTPCITSMatch.inputs, outputs, AlgorithmSpec{adaptFromTask(useFT0, calib, useMC)}, Options{ diff --git a/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx index 9cecf4aa08e22..1e41f60908100 100644 --- a/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx @@ -8,14 +8,25 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#include "GlobalTrackingWorkflow/MatchTPCITSWorkflow.h" +#include "ITSMFTWorkflow/ClusterReaderSpec.h" +#include "ITSWorkflow/TrackReaderSpec.h" +#include "TPCWorkflow/TrackReaderSpec.h" +#include "TPCWorkflow/PublisherSpec.h" +#include "TPCWorkflow/ClusterSharingMapSpec.h" +#include "FT0Workflow/RecPointReaderSpec.h" +#include "GlobalTrackingWorkflow/TPCITSMatchingSpec.h" +#include "GlobalTrackingWorkflow/TrackWriterTPCITSSpec.h" +#include "Algorithm/RangeTokenizer.h" + +#include "ReconstructionDataFormats/GlobalTrackID.h" +#include "DetectorsCommonDataFormats/DetID.h" #include "CommonUtils/ConfigurableParam.h" #include "Framework/CompletionPolicy.h" #include "GPUWorkflow/TPCSectorCompletionPolicy.h" #include "DetectorsRaw/HBFUtilsInitializer.h" using namespace o2::framework; - +using GID = o2::dataformats::GlobalTrackID; // ------------------------------------------------------------------ // we need to add workflow options before including Framework/runDataProcessing @@ -27,6 +38,7 @@ void customize(std::vector& workflowOptions) {"disable-mc", o2::framework::VariantType::Bool, false, {"disable MC propagation even if available"}}, {"disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input reader"}}, {"disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writer"}}, + {"track-sources", VariantType::String, std::string{GID::ALL}, {"comma-separated list of sources to use"}}, {"produce-calibration-data", o2::framework::VariantType::Bool, false, {"produce output for TPC vdrift calibration"}}, {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings ..."}}}; @@ -43,30 +55,65 @@ void customize(std::vector& policies) // in addition we require to have input from all other routes policies.push_back(o2::tpc::TPCSectorCompletionPolicy("itstpc-track-matcher", o2::tpc::TPCSectorCompletionPolicy::Config::RequireAll, - InputSpec{"cluster", o2::framework::ConcreteDataTypeMatcher{"TPC", "CLUSTERNATIVE"}})()); + o2::framework::InputSpec{"cluster", o2::framework::ConcreteDataTypeMatcher{"TPC", "CLUSTERNATIVE"}})()); } // ------------------------------------------------------------------ #include "Framework/runDataProcessing.h" -WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) +WorkflowSpec defineDataProcessing(o2::framework::ConfigContext const& configcontext) { // Update the (declared) parameters if changed from the command line o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); // write the configuration used for the workflow o2::conf::ConfigurableParam::writeINI("o2matchtpcits-workflow_configuration.ini"); + GID::mask_t alowedSources = GID::getSourcesMask("ITS,TPC,FT0"); + GID::mask_t src = alowedSources & GID::getSourcesMask(configcontext.options().get("track-sources")); + auto useFT0 = configcontext.options().get("use-ft0"); auto useMC = !configcontext.options().get("disable-mc"); auto disableRootInp = configcontext.options().get("disable-root-input"); auto disableRootOut = configcontext.options().get("disable-root-output"); auto calib = configcontext.options().get("produce-calibration-data"); - auto wf = o2::globaltracking::getMatchTPCITSWorkflow(useFT0, useMC, disableRootInp, disableRootOut, calib); + o2::framework::WorkflowSpec specs; + + std::vector tpcClusSectors = o2::RangeTokenizer::tokenize("0-35"); + std::vector tpcClusLanes = tpcClusSectors; + + if (!disableRootInp) { + + specs.emplace_back(o2::its::getITSTrackReaderSpec(useMC)); // ITS always needed + specs.emplace_back(o2::itsmft::getITSClusterReaderSpec(useMC, true)); + + if (src[GID::TPC]) { + specs.emplace_back(o2::tpc::getTPCTrackReaderSpec(useMC)); + specs.emplace_back(o2::tpc::getPublisherSpec(o2::tpc::PublisherConf{ + "tpc-native-cluster-reader", + "tpc-native-clusters.root", + "tpcrec", + {"clusterbranch", "TPCClusterNative", "Branch with TPC native clusters"}, + {"clustermcbranch", "TPCClusterNativeMCTruth", "MC label branch"}, + OutputSpec{"TPC", "CLUSTERNATIVE"}, + OutputSpec{"TPC", "CLNATIVEMCLBL"}, + tpcClusSectors, + tpcClusLanes}, + useMC)); + specs.emplace_back(o2::tpc::getClusterSharingMapSpec()); + } + + if (useFT0) { + specs.emplace_back(o2::ft0::getRecPointReaderSpec(useMC)); + } + } + + specs.emplace_back(o2::globaltracking::getTPCITSMatchingSpec(src, useFT0, calib, useMC)); - // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit - o2::raw::HBFUtilsInitializer hbfIni(configcontext, wf); + if (!disableRootOut) { + specs.emplace_back(o2::globaltracking::getTrackWriterTPCITSSpec(useMC)); + } - return std::move(wf); + return std::move(specs); } From 957e98a3cdc1dedb15bd244bc6c760db719737c1 Mon Sep 17 00:00:00 2001 From: shahoian Date: Sat, 1 May 2021 02:17:29 +0200 Subject: [PATCH 358/770] Switch to InputHelper + fixes --- Detectors/GlobalTracking/CMakeLists.txt | 1 + Detectors/GlobalTracking/src/MatchTPCITS.cxx | 13 +++--- .../GlobalTrackingWorkflow/CMakeLists.txt | 1 + .../src/tpcits-match-workflow.cxx | 42 ++----------------- 4 files changed, 14 insertions(+), 43 deletions(-) diff --git a/Detectors/GlobalTracking/CMakeLists.txt b/Detectors/GlobalTracking/CMakeLists.txt index 57bc8532b61a8..e3ce5a25b52be 100644 --- a/Detectors/GlobalTracking/CMakeLists.txt +++ b/Detectors/GlobalTracking/CMakeLists.txt @@ -7,6 +7,7 @@ # In applying this license CERN does not waive the privileges and immunities # granted to it by virtue of its status as an Intergovernmental Organization or # submit itself to any jurisdiction. + add_compile_options(-O0 -g -fPIC) o2_add_library( GlobalTracking diff --git a/Detectors/GlobalTracking/src/MatchTPCITS.cxx b/Detectors/GlobalTracking/src/MatchTPCITS.cxx index 50867e8941b91..240868e354a9c 100644 --- a/Detectors/GlobalTracking/src/MatchTPCITS.cxx +++ b/Detectors/GlobalTracking/src/MatchTPCITS.cxx @@ -797,7 +797,8 @@ bool MatchTPCITS::prepareITSTracks() } } - // sort tracks in each sector according to their time, then tgl + // sort tracks in each sector according to their min time, then tgl + // RSTODO: sorting in tgl will be dangerous once the tracks with different time uncertaincies will be added for (int sec = o2::constants::math::NSectors; sec--;) { auto& indexCache = mITSSectIndexCache[sec]; LOG(INFO) << "Sorting sector" << sec << " | " << indexCache.size() << " ITS tracks"; @@ -807,9 +808,9 @@ bool MatchTPCITS::prepareITSTracks() std::sort(indexCache.begin(), indexCache.end(), [this](int a, int b) { auto& trackA = mITSWork[a]; auto& trackB = mITSWork[b]; - if (trackA.tBracket < trackB.tBracket) { + if (trackA.tBracket.getMin() < trackB.tBracket.getMin()) { return true; - } else if (trackA.tBracket > trackB.tBracket) { + } else if (trackA.tBracket.getMin() > trackB.tBracket.getMin()) { return false; } return trackA.getTgl() < trackB.getTgl(); @@ -887,7 +888,7 @@ void MatchTPCITS::doMatching(int sec) if (mVDriftCalibOn) { timeCorrErr += vdErrT * (250. - abs(trefITS.getZ())); // account for the extra error from TPC VDrift uncertainty } - o2::math_utils::Bracket trange(timeCorr - timeCorrErr, timeCorr + timeCorrErr); + o2::math_utils::Bracketf_t trange(timeCorr - timeCorrErr, timeCorr + timeCorrErr); if (trefITS.tBracket.isOutside(trange)) { continue; } @@ -901,7 +902,8 @@ void MatchTPCITS::doMatching(int sec) fillTPCITSmatchTree(cacheITS[iits], cacheTPC[itpc], rejFlag, chi2); } #endif - + /* + // RS: this might be dangerous for ITS tracks with different time coverages. if (rejFlag == RejectOnTgl) { // ITS tracks in each ROFrame are ordered in Tgl, hence if this check failed on Tgl check // (i.e. tgl_its>tgl_tpc+tolerance), then all other ITS tracks in this ROFrame will also have tgl too large. @@ -920,6 +922,7 @@ void MatchTPCITS::doMatching(int sec) } continue; } + */ if (rejFlag != Accept) { continue; } diff --git a/Detectors/GlobalTrackingWorkflow/CMakeLists.txt b/Detectors/GlobalTrackingWorkflow/CMakeLists.txt index 8d01f6a62a719..346711aa8e48d 100644 --- a/Detectors/GlobalTrackingWorkflow/CMakeLists.txt +++ b/Detectors/GlobalTrackingWorkflow/CMakeLists.txt @@ -22,6 +22,7 @@ o2_add_library(GlobalTrackingWorkflow src/TrackCosmicsWriterSpec.cxx PUBLIC_LINK_LIBRARIES O2::GlobalTracking O2::GlobalTrackingWorkflowReaders + O2::GlobalTrackingWorkflowHelpers O2::ITStracking O2::ITSWorkflow O2::TPCWorkflow diff --git a/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx index 1e41f60908100..ee4f46934a692 100644 --- a/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx @@ -8,15 +8,10 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#include "ITSMFTWorkflow/ClusterReaderSpec.h" -#include "ITSWorkflow/TrackReaderSpec.h" -#include "TPCWorkflow/TrackReaderSpec.h" -#include "TPCWorkflow/PublisherSpec.h" #include "TPCWorkflow/ClusterSharingMapSpec.h" -#include "FT0Workflow/RecPointReaderSpec.h" #include "GlobalTrackingWorkflow/TPCITSMatchingSpec.h" #include "GlobalTrackingWorkflow/TrackWriterTPCITSSpec.h" -#include "Algorithm/RangeTokenizer.h" +#include "GlobalTrackingWorkflowHelpers/InputHelper.h" #include "ReconstructionDataFormats/GlobalTrackID.h" #include "DetectorsCommonDataFormats/DetID.h" @@ -74,46 +69,17 @@ WorkflowSpec defineDataProcessing(o2::framework::ConfigContext const& configcont auto useFT0 = configcontext.options().get("use-ft0"); auto useMC = !configcontext.options().get("disable-mc"); - auto disableRootInp = configcontext.options().get("disable-root-input"); - auto disableRootOut = configcontext.options().get("disable-root-output"); auto calib = configcontext.options().get("produce-calibration-data"); o2::framework::WorkflowSpec specs; - std::vector tpcClusSectors = o2::RangeTokenizer::tokenize("0-35"); - std::vector tpcClusLanes = tpcClusSectors; - - if (!disableRootInp) { - - specs.emplace_back(o2::its::getITSTrackReaderSpec(useMC)); // ITS always needed - specs.emplace_back(o2::itsmft::getITSClusterReaderSpec(useMC, true)); - - if (src[GID::TPC]) { - specs.emplace_back(o2::tpc::getTPCTrackReaderSpec(useMC)); - specs.emplace_back(o2::tpc::getPublisherSpec(o2::tpc::PublisherConf{ - "tpc-native-cluster-reader", - "tpc-native-clusters.root", - "tpcrec", - {"clusterbranch", "TPCClusterNative", "Branch with TPC native clusters"}, - {"clustermcbranch", "TPCClusterNativeMCTruth", "MC label branch"}, - OutputSpec{"TPC", "CLUSTERNATIVE"}, - OutputSpec{"TPC", "CLNATIVEMCLBL"}, - tpcClusSectors, - tpcClusLanes}, - useMC)); - specs.emplace_back(o2::tpc::getClusterSharingMapSpec()); - } - - if (useFT0) { - specs.emplace_back(o2::ft0::getRecPointReaderSpec(useMC)); - } - } - specs.emplace_back(o2::globaltracking::getTPCITSMatchingSpec(src, useFT0, calib, useMC)); - if (!disableRootOut) { + if (!configcontext.options().get("disable-root-output")) { specs.emplace_back(o2::globaltracking::getTrackWriterTPCITSSpec(useMC)); } + o2::globaltracking::InputHelper::addInputSpecs(configcontext, specs, src, src, src, useMC); + return std::move(specs); } From 002cd527b0e4a884301d9e98f9759ccbb2aef84f Mon Sep 17 00:00:00 2001 From: shahoian Date: Sat, 1 May 2021 14:59:11 +0200 Subject: [PATCH 359/770] Adapt to combined or separate ITS-(TPC,TPC-TOF) matching --- Detectors/AOD/src/AODProducerWorkflow.cxx | 1 - Detectors/GlobalTracking/CMakeLists.txt | 1 - .../include/GlobalTracking/MatchTPCITS.h | 27 +- .../GlobalTracking/MatchTPCITSParams.h | 2 + Detectors/GlobalTracking/src/MatchTPCITS.cxx | 258 ++++++++++-------- .../MatchTPCITSWorkflow.h | 27 -- .../TPCITSMatchingSpec.h | 2 +- .../src/MatchTPCITSWorkflow.cxx | 56 ---- .../src/TPCITSMatchingSpec.cxx | 28 +- .../src/tpcits-match-workflow.cxx | 18 +- 10 files changed, 188 insertions(+), 232 deletions(-) delete mode 100644 Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/MatchTPCITSWorkflow.h delete mode 100644 Detectors/GlobalTrackingWorkflow/src/MatchTPCITSWorkflow.cxx diff --git a/Detectors/AOD/src/AODProducerWorkflow.cxx b/Detectors/AOD/src/AODProducerWorkflow.cxx index b8bc74dd001a3..a7c1e82795b81 100644 --- a/Detectors/AOD/src/AODProducerWorkflow.cxx +++ b/Detectors/AOD/src/AODProducerWorkflow.cxx @@ -17,7 +17,6 @@ #include "FT0Workflow/DigitReaderSpec.h" #include "FT0Workflow/ReconstructionSpec.h" #include "GlobalTracking/MatchTPCITSParams.h" -#include "GlobalTrackingWorkflow/MatchTPCITSWorkflow.h" #include "GlobalTrackingWorkflow/PrimaryVertexingSpec.h" #include "GlobalTrackingWorkflowReaders/PrimaryVertexReaderSpec.h" #include "GlobalTrackingWorkflow/TPCITSMatchingSpec.h" diff --git a/Detectors/GlobalTracking/CMakeLists.txt b/Detectors/GlobalTracking/CMakeLists.txt index e3ce5a25b52be..5a6f893d43abd 100644 --- a/Detectors/GlobalTracking/CMakeLists.txt +++ b/Detectors/GlobalTracking/CMakeLists.txt @@ -8,7 +8,6 @@ # granted to it by virtue of its status as an Intergovernmental Organization or # submit itself to any jurisdiction. -add_compile_options(-O0 -g -fPIC) o2_add_library( GlobalTracking SOURCES src/MatchTPCITS.cxx src/MatchTOF.cxx diff --git a/Detectors/GlobalTracking/include/GlobalTracking/MatchTPCITS.h b/Detectors/GlobalTracking/include/GlobalTracking/MatchTPCITS.h index 719c819c247b3..5e410e8681d57 100644 --- a/Detectors/GlobalTracking/include/GlobalTracking/MatchTPCITS.h +++ b/Detectors/GlobalTracking/include/GlobalTracking/MatchTPCITS.h @@ -113,11 +113,11 @@ struct TrackLocTPC : public o2::track::TrackParCov { enum Constraint_t : uint8_t { Constrained, ASide, CSide }; - o2::math_utils::Bracketf_t tBracket; ///< bracketing time in \mus - float time0 = 0; ///< nominal time in \mus - int sourceID = 0; ///< track origin id - // float zMin = 0; // min possible Z of this track - // float zMax = 0; // max possible Z of this track + o2::math_utils::Bracketf_t tBracket; ///< bracketing time in \mus + float time0 = 0.f; ///< nominal time in \mus since start of TF (time0 for bare TPC tracks, constrained time for TRD/TOF constrained ones) + float timeErr = 0.f; ///< time sigma (makes sense for constrained tracks only) + int sourceID = 0; ///< TPC track origin in + o2::dataformats::GlobalTrackID gid{}; // global track source ID (TPC track may be part of it) int matchID = MinusOne; ///< entry (non if MinusOne) of its matchTPC struct in the mMatchesTPC Constraint_t constraint{Constrained}; @@ -310,7 +310,7 @@ class MatchTPCITS static constexpr int NITSLayers = o2::its::RecoGeomHelper::getNLayers(); ///< perform matching for provided input void run(const o2::globaltracking::RecoContainer& inp); - void loadInput(const o2::globaltracking::RecoContainer& inp); + // RSTODO void runAfterBurner(); bool runAfterBurner(int tpcWID, int iCStart, int iCEnd); @@ -330,10 +330,9 @@ class MatchTPCITS void buildBestLinksList(int ilink); bool isBetter(float chi2A, float chi2B) { return chi2A < chi2B; } // RS TODO void dumpABTracksDebugTree(const ABTrackLinksList& llist); - int prepareInteractionTimes(); void destroyLastABTrackLinksList(); void refitABTrack(int ibest) const; - + void setSkipTPCOnly(bool v) { mSkipTPCOnly = v; } void setCosmics(bool v) { mCosmics = v; } bool isCosmics() const { return mCosmics; } @@ -430,10 +429,12 @@ class MatchTPCITS int findLaddersToCheckBOff(int ilr, int lad0, const o2::math_utils::IntervalXYf_t& trcLinPar, float errYFrac, std::array& lad2Check) const; + bool prepareTPCData(); + bool prepareITSData(); + bool prepareFITData(); + int prepareInteractionTimes(); int prepareTPCTracksAfterBurner(); - bool prepareTPCTracks(); - bool prepareITSTracks(); - bool prepareFITInfo(); + void addTPCSeed(const o2::track::TrackParCov& _tr, float t0, float terr, o2::dataformats::GlobalTrackID srcGID, int tpcID); int preselectChipClusters(std::vector& clVecOut, const ClusRange& clRange, const ITSChipClustersRefs& clRefs, float trackY, float trackZ, float tolerY, float tolerZ, const o2::MCCompLabel& lblTrc) const; @@ -524,6 +525,7 @@ class MatchTPCITS MatCorrType mUseMatCorrFlag = MatCorrType::USEMatCorrTGeo; + bool mSkipTPCOnly = false; ///< for test only: don't use TPC only tracks, use only external ones bool mITSTriggered = false; ///< ITS readout is triggered bool mUseFT0 = false; ///< FT0 information is available @@ -535,7 +537,7 @@ class MatchTPCITS ///< safety margin in TPC time bins when estimating TPC track tMin and tMax from ///< assigned time0 and its track Z position (converted from mTPCTimeEdgeZSafeMargin) float mTPCTimeEdgeTSafeMargin = 0.f; - + float mTPCExtConstrainedNSigmaInv = 0.f; // inverse for NSigmas for TPC time-interval from external constraint time sigma int mITSROFrameLengthInBC = 0; ///< ITS RO frame in BC (for ITS cont. mode only) float mITSROFrameLengthMUS = -1.; ///< ITS RO frame in \mus float mITSROFrameLengthMUSInv = -1.; ///< ITS RO frame in \mus inverse @@ -565,6 +567,7 @@ class MatchTPCITS std::array mClosestBunchAbove; // closest filled bunch from above std::array mClosestBunchBelow; // closest filled bunch from below + const o2::globaltracking::RecoContainer* mRecoCont = nullptr; ///>>>------ these are input arrays which should not be modified by the matching code // since this info is provided by external device gsl::span mTPCTracksArray; ///< input TPC tracks span diff --git a/Detectors/GlobalTracking/include/GlobalTracking/MatchTPCITSParams.h b/Detectors/GlobalTracking/include/GlobalTracking/MatchTPCITSParams.h index c10f2c13b1621..40ebb93366ac3 100644 --- a/Detectors/GlobalTracking/include/GlobalTracking/MatchTPCITSParams.h +++ b/Detectors/GlobalTracking/include/GlobalTracking/MatchTPCITSParams.h @@ -55,6 +55,8 @@ struct MatchTPCITSParams : public o2::conf::ConfigurableParamHelper>; using MatrixD4 = ROOT::Math::SMatrix>; using NAMES = o2::base::NameConf; +using GTrackID = o2::dataformats::GlobalTrackID; constexpr float MatchTPCITS::XMatchingRef; constexpr float MatchTPCITS::YMaxAtXMatchingRef; @@ -248,6 +249,7 @@ void MatchTPCITS::run(const o2::globaltracking::RecoContainer& inp) if (!mInitDone) { LOG(FATAL) << "init() was not done yet"; } + mRecoCont = &inp; mStartIR = inp.startIR; updateTimeDependentParams(); @@ -260,14 +262,9 @@ void MatchTPCITS::run(const o2::globaltracking::RecoContainer& inp) clear(); - loadInput(inp); - - if (!prepareITSTracks() || !prepareTPCTracks() || !prepareFITInfo()) { + if (!prepareITSData() || !prepareTPCData() || !prepareFITData()) { return; } - if (mUseFT0) { - prepareInteractionTimes(); - } mTimer[SWDoMatching].Start(false); for (int sec = o2::constants::math::NSectors; sec--;) { @@ -307,38 +304,6 @@ void MatchTPCITS::run(const o2::globaltracking::RecoContainer& inp) mTFCount++; } -//______________________________________________ -void MatchTPCITS::loadInput(const o2::globaltracking::RecoContainer& inp) -{ - mITSTracksArray = inp.getITSTracks(); - mITSTrackClusIdx = inp.getITSTracksClusterRefs(); - mITSTrackROFRec = inp.getITSTracksROFRecords(); - - mITSClusterROFRec = inp.getITSClustersROFRecords(); - const auto patterns = inp.getITSClustersPatterns(); - const auto clusITS = inp.getITSClusters(); - auto pattIt = patterns.begin(); - mITSClustersArray.clear(); - mITSClustersArray.reserve(clusITS.size()); - o2::its::ioutils::convertCompactClusters(clusITS, pattIt, mITSClustersArray, *mITSDict); - - mTPCTracksArray = inp.getTPCTracks(); - mTPCTrackClusIdx = inp.getTPCTracksClusterRefs(); - mTPCClusterIdxStruct = &inp.inputsTPCclusters->clusterIndex; - mTPCRefitterShMap = inp.clusterShMapTPC; - if (mMCTruthON) { - mITSTrkLabels = inp.getITSTracksMCLabels(); - mTPCTrkLabels = inp.getTPCTracksMCLabels(); - mITSClsLabels = inp.mcITSClusters.get(); - } - - if (mUseFT0) { - mFITInfo = inp.getFT0RecPoints(); - } - - mTPCRefitter = std::make_unique(mTPCClusterIdxStruct, mTPCTransform.get(), mBz, mTPCTrackClusIdx.data(), mTPCRefitterShMap.data(), nullptr, o2::base::Propagator::Instance()); -} - //______________________________________________ void MatchTPCITS::end() { @@ -355,8 +320,23 @@ void MatchTPCITS::clear() mMatchRecordsITS.clear(); mWinnerChi2Refit.clear(); mMatchedTracks.clear(); + mITSWork.clear(); + mITSROFTimes.clear(); + mITSTrackROFContMapping.clear(); + mITSClustersArray.clear(); + mABClusterLinkIndex.clear(); + + for (int sec = o2::constants::math::NSectors; sec--;) { + mITSSectIndexCache[sec].clear(); + mITSTimeStart[sec].clear(); + mTPCSectIndexCache[sec].clear(); + mTPCTimeStart[sec].clear(); + } + if (mMCTruthON) { mOutLabels.clear(); + mITSROFTimes.clear(); + mTPCLblWork.clear(); } } @@ -438,7 +418,7 @@ void MatchTPCITS::updateTimeDependentParams() mTPCVDrift0Inv = 1. / mTPCVDrift0; mNTPCBinsFullDrift = mTPCZMax * mZ2TPCBin; mTPCTimeEdgeTSafeMargin = z2TPCBin(mParams->safeMarginTPCTimeEdge); - + mTPCExtConstrainedNSigmaInv = 1.f / mParams->tpcExtConstrainedNSigma; mBz = o2::base::Propagator::Instance()->getNominalBz(); mFieldON = std::abs(mBz) > 0.01; @@ -545,73 +525,110 @@ int MatchTPCITS::getNMatchRecordsITS(const TrackLocITS& tTPC) const } //______________________________________________ -bool MatchTPCITS::prepareTPCTracks() +void MatchTPCITS::addTPCSeed(const o2::track::TrackParCov& _tr, float t0, float terr, GTrackID srcGID, int tpcID) { - ///< load next chunk of TPC data and prepare for matching + // account single TPC seed, can be from standalone TPC track or constrained track from match to TRD and/or TOF + const float SQRT12DInv = 2. / sqrt(12.); + const auto& tpcOrig = mTPCTracksArray[tpcID]; + // discard tracks w/o certain number of total or innermost pads (last cluster is innermost one) + if (tpcOrig.getNClusterReferences() < mParams->minTPCClusters) { + return; + } + uint8_t clSect = 0, clRow = 0; + uint32_t clIdx = 0; + tpcOrig.getClusterReference(mTPCTrackClusIdx, tpcOrig.getNClusterReferences() - 1, clSect, clRow, clIdx); + if (clRow > mParams->askMinTPCRow) { + return; + } + // create working copy of track param + bool extConstrained = srcGID.getSource() != GTrackID::TPC; + if (extConstrained) { + terr *= mParams->tpcExtConstrainedNSigma; + } else { + terr += tpcTimeBin2MUS(tpcOrig.hasBothSidesClusters() ? mParams->safeMarginTPCITSTimeBin : mTPCTimeEdgeTSafeMargin); + } + auto& trc = mTPCWork.emplace_back( + TrackLocTPC{_tr, {t0 - terr, t0 + terr}, extConstrained ? t0 : tpcTimeBin2MUS(tpcOrig.getTime0()), + // for A/C constrained tracks the terr is half-interval, for externally constrained tracks it is sigma*Nsigma + terr * (extConstrained ? mTPCExtConstrainedNSigmaInv : SQRT12DInv), + tpcID, + srcGID, + MinusOne, + (extConstrained || tpcOrig.hasBothSidesClusters()) ? TrackLocTPC::Constrained : (tpcOrig.hasASideClustersOnly() ? TrackLocTPC::ASide : TrackLocTPC::CSide)}); + // propagate to matching Xref + if (!propagateToRefX(trc)) { + mTPCWork.pop_back(); // discard track whose propagation to XMatchingRef failed + return; + } + if (mMCTruthON) { + mTPCLblWork.emplace_back(mTPCTrkLabels[tpcID]); + } + // cache work track index + mTPCSectIndexCache[o2::math_utils::angle2Sector(trc.getAlpha())].push_back(mTPCWork.size() - 1); +} + +//______________________________________________ +bool MatchTPCITS::prepareTPCData() +{ + ///< load TPC data and prepare for matching mTimer[SWPrepTPC].Start(false); - mMatchRecordsTPC.clear(); + const auto& inp = *mRecoCont; - int ntr = mTPCTracksArray.size(); - // number of records might be actually more than N tracks! - mMatchRecordsTPC.reserve(mMatchRecordsTPC.size() + mParams->maxMatchCandidates * ntr); + mTPCTracksArray = inp.getTPCTracks(); + mTPCTrackClusIdx = inp.getTPCTracksClusterRefs(); + mTPCClusterIdxStruct = &inp.inputsTPCclusters->clusterIndex; + mTPCRefitterShMap = inp.clusterShMapTPC; + if (mMCTruthON) { + mTPCTrkLabels = inp.getTPCTracksMCLabels(); + } - // copy the track params, propagate to reference X and build sector tables - mTPCWork.clear(); + int ntr = mTPCTracksArray.size(); + mMatchRecordsTPC.reserve(mParams->maxMatchCandidates * ntr); // number of records might be actually more than N tracks! mTPCWork.reserve(ntr); if (mMCTruthON) { - mTPCLblWork.clear(); mTPCLblWork.reserve(ntr); } for (int sec = o2::constants::math::NSectors; sec--;) { - mTPCSectIndexCache[sec].clear(); mTPCSectIndexCache[sec].reserve(100 + 1.2 * ntr / o2::constants::math::NSectors); - mTPCTimeStart[sec].clear(); } - for (int it = 0; it < ntr; it++) { - - const auto& trcOrig = mTPCTracksArray[it]; + mTPCTracksArray = inp.getTPCTracks(); + mTPCTrackClusIdx = inp.getTPCTracksClusterRefs(); + mTPCClusterIdxStruct = &inp.inputsTPCclusters->clusterIndex; + mTPCRefitterShMap = inp.clusterShMapTPC; + if (mMCTruthON) { + mTPCTrkLabels = inp.getTPCTracksMCLabels(); + } - // make sure the track was propagated to inner TPC radius at the ref. radius - if (trcOrig.getX() > o2::constants::geom::XTPCInnerRef + 0.1 || std::abs(trcOrig.getQ2Pt()) > mMinTPCTrackPtInv) { - continue; + std::function creator = [this](const o2::track::TrackParCov& _tr, float t0, float terr, GTrackID _origID) { + auto srcID = _origID.getSource(); + if (srcID == GTrackID::ITS) { // we don't need ITS here + return true; // we don't need TPC tracks } - // discard tracks with too few clusters - if (trcOrig.getNClusterReferences() < mParams->minTPCClusters) { - continue; + // make sure the track was propagated to inner TPC radius at the ref. radius + if (_tr.getX() > o2::constants::geom::XTPCInnerRef + 0.1 || std::abs(_tr.getQ2Pt()) > mMinTPCTrackPtInv) { + return true; } - // discard tracks w/o certain number of innermost pads (last cluster is innermost one) - { - uint8_t clSect = 0, clRow = 0; - uint32_t clIdx = 0; - trcOrig.getClusterReference(mTPCTrackClusIdx, trcOrig.getNClusterReferences() - 1, clSect, clRow, clIdx); - if (clRow > mParams->askMinTPCRow) { - continue; + GTrackID tpcGID{}; + if (srcID == GTrackID::TPC) { + // unconstrained TPC track, with t0 = TrackTPC.getTime0+0.5*(DeltaFwd-DeltaBwd) and terr = 0.5*(DeltaFwd+DeltaBwd) + if (this->mSkipTPCOnly) { + return true; } + tpcGID = _origID; + t0 = this->tpcTimeBin2MUS(t0); // time and error are in TPC bins, convert to \mus + terr = this->tpcTimeBin2MUS(terr); + } else if (srcID == GTrackID::TPCTOF) { + // TPC track is contrained by TOF fit + tpcGID = this->mRecoCont->getTPCContributorGID(_origID); + } else if (srcID == GTrackID::TPCTRD) { + return true; // TODO RS } + addTPCSeed(_tr, t0, terr, _origID, tpcGID.getIndex()); + return true; + }; - // create working copy of track param - float tBwd = trcOrig.getDeltaTBwd() + mTPCTimeEdgeTSafeMargin, tFwd = trcOrig.getDeltaTFwd() + mTPCTimeEdgeTSafeMargin; - auto& trc = mTPCWork.emplace_back(TrackLocTPC{trcOrig, - {tpcTimeBin2MUS(trcOrig.getTime0() - tBwd), tpcTimeBin2MUS(trcOrig.getTime0() + tFwd)}, - tpcTimeBin2MUS(trcOrig.getTime0()), - it, - MinusOne, - TrackLocTPC::Constrained}); - // propagate to matching Xref - if (!propagateToRefX(trc)) { - mTPCWork.pop_back(); // discard track whose propagation to XMatchingRef failed - continue; - } - trc.constraint = trcOrig.hasASideClustersOnly() ? TrackLocTPC::ASide : (trcOrig.hasCSideClustersOnly() ? TrackLocTPC::CSide : TrackLocTPC::Constrained); - - if (mMCTruthON) { - mTPCLblWork.emplace_back(mTPCTrkLabels[it]); - } - - // cache work track index - mTPCSectIndexCache[o2::math_utils::angle2Sector(trc.getAlpha())].push_back(mTPCWork.size() - 1); - } + inp.createTracks(creator); float maxTime = 0; int nITSROFs = mITSROFTimes.size(); @@ -676,45 +693,52 @@ bool MatchTPCITS::prepareTPCTracks() mITSROFofTPCBin[ib] = itsROF; } */ + mTPCRefitter = std::make_unique(mTPCClusterIdxStruct, mTPCTransform.get(), mBz, mTPCTrackClusIdx.data(), mTPCRefitterShMap.data(), nullptr, o2::base::Propagator::Instance()); + mTimer[SWPrepTPC].Stop(); - return true; + return mTPCWork.size() > 0; } //_____________________________________________________ -bool MatchTPCITS::prepareITSTracks() +bool MatchTPCITS::prepareITSData() { - // In the standalone (tree-based) mode load next chunk of ITS data, // Do preparatory work for matching - int nROFs = mITSTrackROFRec.size(); + mTimer[SWPrepITS].Start(false); + const auto& inp = *mRecoCont; - if (!nROFs) { - LOG(INFO) << "Empty TF"; + // ITS clusters + mITSClusterROFRec = inp.getITSClustersROFRecords(); + const auto clusITS = inp.getITSClusters(); + if (mITSClusterROFRec.empty() || clusITS.empty()) { + LOG(INFO) << "No ITS clusters"; return false; } - mTimer[SWPrepITS].Start(false); - mITSWork.clear(); - mITSWork.reserve(mITSTracksArray.size()); - mITSROFTimes.clear(); - // number of records might be actually more than N tracks! - mMatchRecordsITS.clear(); // RS TODO reserve(mMatchRecordsITS.size() + mParams->maxMatchCandidates*ntr); + const auto patterns = inp.getITSClustersPatterns(); + auto pattIt = patterns.begin(); + mITSClustersArray.reserve(clusITS.size()); + o2::its::ioutils::convertCompactClusters(clusITS, pattIt, mITSClustersArray, *mITSDict); if (mMCTruthON) { - mITSLblWork.clear(); + mITSClsLabels = inp.mcITSClusters.get(); } + // ITS tracks + mITSTracksArray = inp.getITSTracks(); + mITSTrackClusIdx = inp.getITSTracksClusterRefs(); + mITSTrackROFRec = inp.getITSTracksROFRecords(); + if (mMCTruthON) { + mITSTrkLabels = inp.getITSTracksMCLabels(); + } + int nROFs = mITSTrackROFRec.size(); + mITSWork.reserve(mITSTracksArray.size()); + // total N ITS clusters in TF const auto& lastClROF = mITSClusterROFRec[nROFs - 1]; //.back(); int nITSClus = lastClROF.getFirstEntry() + lastClROF.getNEntries(); - mABClusterLinkIndex.clear(); mABClusterLinkIndex.resize(nITSClus, MinusOne); - for (int sec = o2::constants::math::NSectors; sec--;) { - mITSSectIndexCache[sec].clear(); - mITSTimeStart[sec].clear(); mITSTimeStart[sec].resize(nROFs, -1); // start of ITS work tracks in every sector } - mITSTrackROFContMapping.clear(); // there might be gaps in the non-empty rofs, this will map continuous ROFs index to non empty ones - for (int irof = 0; irof < nROFs; irof++) { const auto& rofRec = mITSTrackROFRec[irof]; int nBC = rofRec.getBCData().differenceInBC(mStartIR); @@ -722,7 +746,7 @@ bool MatchTPCITS::prepareITSTracks() float tMax = (nBC + mITSROFrameLengthInBC) * o2::constants::lhc::LHCBunchSpacingMUS; if (!mITSTriggered) { auto irofCont = nBC / mITSROFrameLengthInBC; - if (mITSTrackROFContMapping.size() <= irofCont) { + if (mITSTrackROFContMapping.size() <= irofCont) { // there might be gaps in the non-empty rofs, this will map continuous ROFs index to non empty ones mITSTrackROFContMapping.resize((1 + irofCont / 128) * 128, 0); } mITSTrackROFContMapping[irofCont] = irof; @@ -818,14 +842,18 @@ bool MatchTPCITS::prepareITSTracks() } // loop over tracks of single sector mMatchRecordsITS.reserve(mITSWork.size() * mParams->maxMatchCandidates); mTimer[SWPrepITS].Stop(); - return true; + + return nITSClus > 0; } //_____________________________________________________ -bool MatchTPCITS::prepareFITInfo() +bool MatchTPCITS::prepareFITData() { // If available, read FIT Info - + if (mUseFT0) { + mFITInfo = mRecoCont->getFT0RecPoints(); + prepareInteractionTimes(); + } return true; } @@ -1433,8 +1461,8 @@ bool MatchTPCITS::refitTrackTPCITS(int iTPC, int& iITS) LOG(ERROR) << "LTOF integral might be incorrect"; } - float time = tTPC.getCorrectedTime(deltaT); /// precise time estimate - float timeErr = std::sqrt(tITS.getSigmaZ2() + tTPC.getSigmaZ2()) * mTPCVDrift0Inv; // estimate the error on time + float timeC = tTPC.getCorrectedTime(deltaT); /// precise time estimate + float timeErr = tTPC.constraint == TrackLocTPC::Constrained ? tTPC.timeErr : std::sqrt(tITS.getSigmaZ2() + tTPC.getSigmaZ2()) * mTPCVDrift0Inv; // estimate the error on time // outward refit auto& tracOut = trfit.getParamOut(); // this is a clone of ITS outward track already at the matching reference X @@ -1452,7 +1480,7 @@ bool MatchTPCITS::refitTrackTPCITS(int iTPC, int& iITS) } float chi2Out = 0; auto posStart = tracOut.getXYZGlo(); - int retVal = mTPCRefitter->RefitTrackAsTrackParCov(tracOut, mTPCTracksArray[tTPC.sourceID].getClusterRef(), time * mTPCTBinMUSInv, &chi2Out, true, false); // outward refit + int retVal = mTPCRefitter->RefitTrackAsTrackParCov(tracOut, mTPCTracksArray[tTPC.sourceID].getClusterRef(), timeC * mTPCTBinMUSInv, &chi2Out, true, false); // outward refit if (retVal < 0) { LOG(DEBUG) << "Refit failed"; mMatchedTracks.pop_back(); // destroy failed track @@ -1481,7 +1509,7 @@ bool MatchTPCITS::refitTrackTPCITS(int iTPC, int& iITS) trfit.setChi2Match(tpcMatchRec.chi2); trfit.setChi2Refit(chi2); - trfit.setTimeMUS(time, timeErr); + trfit.setTimeMUS(timeC, timeErr); trfit.setRefTPC({unsigned(tTPC.sourceID), o2::dataformats::GlobalTrackID::TPC}); trfit.setRefITS({unsigned(tITS.sourceID), o2::dataformats::GlobalTrackID::ITS}); diff --git a/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/MatchTPCITSWorkflow.h b/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/MatchTPCITSWorkflow.h deleted file mode 100644 index cc9f9d3b7a403..0000000000000 --- a/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/MatchTPCITSWorkflow.h +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -#ifndef O2_MATCHT_TPCITS_WORKFLOW_H -#define O2_MATCHT_TPCITS_WORKFLOW_H - -/// @file RecoWorkflow.h - -#include "Framework/WorkflowSpec.h" - -namespace o2 -{ -namespace globaltracking -{ - -framework::WorkflowSpec getMatchTPCITSWorkflow(bool useFT0, bool calib, bool useMC, bool disableRootInp, bool disableRootOut); - -} // namespace globaltracking -} // namespace o2 -#endif diff --git a/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/TPCITSMatchingSpec.h b/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/TPCITSMatchingSpec.h index 9b4b1679b9c6a..4336be4e4f668 100644 --- a/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/TPCITSMatchingSpec.h +++ b/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/TPCITSMatchingSpec.h @@ -22,7 +22,7 @@ namespace o2 namespace globaltracking { /// create a processor spec -framework::DataProcessorSpec getTPCITSMatchingSpec(o2::dataformats::GlobalTrackID::mask_t src, bool useFT0, bool calib, bool useMC); +framework::DataProcessorSpec getTPCITSMatchingSpec(o2::dataformats::GlobalTrackID::mask_t src, bool useFT0, bool calib, bool skipTPCOnly, bool useMC); } // namespace globaltracking } // namespace o2 diff --git a/Detectors/GlobalTrackingWorkflow/src/MatchTPCITSWorkflow.cxx b/Detectors/GlobalTrackingWorkflow/src/MatchTPCITSWorkflow.cxx deleted file mode 100644 index c183943946da1..0000000000000 --- a/Detectors/GlobalTrackingWorkflow/src/MatchTPCITSWorkflow.cxx +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// @file MatchTPCITSWorkflow.cxx - -#include "ITSMFTWorkflow/ClusterReaderSpec.h" -#include "ITSWorkflow/TrackReaderSpec.h" -#include "TPCWorkflow/TrackReaderSpec.h" -#include "TPCWorkflow/ClusterReaderSpec.h" -#include "TPCWorkflow/ClusterSharingMapSpec.h" -#include "FT0Workflow/RecPointReaderSpec.h" -#include "GlobalTrackingWorkflow/TPCITSMatchingSpec.h" -#include "GlobalTrackingWorkflow/MatchTPCITSWorkflow.h" -#include "GlobalTrackingWorkflow/TrackWriterTPCITSSpec.h" -#include "Algorithm/RangeTokenizer.h" -#include "DataFormatsTPC/Constants.h" -#include "GlobalTracking/MatchTPCITSParams.h" - -namespace o2 -{ -namespace globaltracking -{ - -framework::WorkflowSpec getMatchTPCITSWorkflow(bool useFT0, bool useMC, bool disableRootInp, bool disableRootOut, bool calib) -{ - framework::WorkflowSpec specs; - - if (!disableRootInp) { - specs.emplace_back(o2::its::getITSTrackReaderSpec(useMC)); - specs.emplace_back(o2::itsmft::getITSClusterReaderSpec(useMC, true)); - specs.emplace_back(o2::tpc::getTPCTrackReaderSpec(useMC)); - specs.emplace_back(o2::tpc::getClusterReaderSpec(useMC)); - specs.emplace_back(o2::tpc::getClusterSharingMapSpec()); - - if (useFT0) { - specs.emplace_back(o2::ft0::getRecPointReaderSpec(useMC)); - } - } - - specs.emplace_back(o2::globaltracking::getTPCITSMatchingSpec(useFT0, calib, useMC)); - - if (!disableRootOut) { - specs.emplace_back(o2::globaltracking::getTrackWriterTPCITSSpec(useMC)); - } - return specs; -} - -} // namespace globaltracking -} // namespace o2 diff --git a/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx index a0b2daf04f138..1ae990c85a352 100644 --- a/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/TPCITSMatchingSpec.cxx @@ -53,22 +53,23 @@ namespace o2 namespace globaltracking { -DataRequest dataRequestTPCITSMatch; - class TPCITSMatchingDPL : public Task { public: - TPCITSMatchingDPL(bool useFT0, bool calib, bool useMC) : mUseFT0(useFT0), mCalibMode(calib), mUseMC(useMC) {} + TPCITSMatchingDPL(std::shared_ptr dr, bool useFT0, bool calib, bool skipTPCOnly, bool useMC) + : mDataRequest(dr), mUseFT0(useFT0), mCalibMode(calib), mSkipTPCOnly(skipTPCOnly), mUseMC(useMC) {} ~TPCITSMatchingDPL() override = default; void init(InitContext& ic) final; void run(ProcessingContext& pc) final; void endOfStream(framework::EndOfStreamContext& ec) final; private: + std::shared_ptr mDataRequest; o2::globaltracking::MatchTPCITS mMatching; // matching engine o2::itsmft::TopologyDictionary mITSDict; // cluster patterns dictionary bool mUseFT0 = false; bool mCalibMode = false; + bool mSkipTPCOnly = false; // to use only externally constrained tracks (for test only) bool mUseMC = true; TStopwatch mTimer; }; @@ -81,6 +82,7 @@ void TPCITSMatchingDPL::init(InitContext& ic) o2::base::GeometryManager::loadGeometry(); o2::base::Propagator::initFieldFromGRP(); std::unique_ptr grp{o2::parameters::GRPObject::loadFrom()}; + mMatching.setSkipTPCOnly(mSkipTPCOnly); mMatching.setITSTriggered(!grp->isDetContinuousReadOut(o2::detectors::DetID::ITS)); const auto& alpParams = o2::itsmft::DPLAlpideParam::Instance(); if (mMatching.isITSTriggered()) { @@ -131,7 +133,7 @@ void TPCITSMatchingDPL::run(ProcessingContext& pc) LOG(INFO) << " startOrbit: " << dh->firstTForbit; mTimer.Start(false); RecoContainer recoData; - recoData.collectData(pc, dataRequestTPCITSMatch); + recoData.collectData(pc, *mDataRequest.get()); mMatching.run(recoData); @@ -155,17 +157,17 @@ void TPCITSMatchingDPL::endOfStream(EndOfStreamContext& ec) mTimer.CpuTime(), mTimer.RealTime(), mTimer.Counter() - 1); } -DataProcessorSpec getTPCITSMatchingSpec(GTrackID::mask_t src, bool useFT0, bool calib, bool useMC) +DataProcessorSpec getTPCITSMatchingSpec(GTrackID::mask_t src, bool useFT0, bool calib, bool skipTPCOnly, bool useMC) { - std::vector outputs; - dataRequestTPCITSMatch.requestTracks(src, useMC); - dataRequestTPCITSMatch.requestClusters(src, false); // no MC labels for clusters needed for refit only + auto dataRequest = std::make_shared(); + + dataRequest->requestTracks(src, useMC); + dataRequest->requestClusters(src, false); // no MC labels for clusters needed for refit only if (useFT0) { - dataRequestTPCITSMatch.requestFT0RecPoints(false); + dataRequest->requestFT0RecPoints(false); } - outputs.emplace_back("GLO", "TPCITS", 0, Lifetime::Timeframe); if (calib) { @@ -173,15 +175,15 @@ DataProcessorSpec getTPCITSMatchingSpec(GTrackID::mask_t src, bool useFT0, bool } if (useMC) { - dataRequestTPCITSMatch.inputs.emplace_back("clusITSMCTR", "ITS", "CLUSTERSMCTR", 0, Lifetime::Timeframe); // for afterburner + dataRequest->inputs.emplace_back("clusITSMCTR", "ITS", "CLUSTERSMCTR", 0, Lifetime::Timeframe); // for afterburner outputs.emplace_back("GLO", "TPCITS_MC", 0, Lifetime::Timeframe); } return DataProcessorSpec{ "itstpc-track-matcher", - dataRequestTPCITSMatch.inputs, + dataRequest->inputs, outputs, - AlgorithmSpec{adaptFromTask(useFT0, calib, useMC)}, + AlgorithmSpec{adaptFromTask(dataRequest, useFT0, calib, skipTPCOnly, useMC)}, Options{ {"its-dictionary-path", VariantType::String, "", {"Path of the cluster-topology dictionary file"}}, {"material-lut-path", VariantType::String, "", {"Path of the material LUT file"}}, diff --git a/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx index ee4f46934a692..5e52eb80f006a 100644 --- a/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx @@ -33,7 +33,7 @@ void customize(std::vector& workflowOptions) {"disable-mc", o2::framework::VariantType::Bool, false, {"disable MC propagation even if available"}}, {"disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input reader"}}, {"disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writer"}}, - {"track-sources", VariantType::String, std::string{GID::ALL}, {"comma-separated list of sources to use"}}, + {"track-sources", VariantType::String, "ITS,TPC", {"comma-separated list of sources to use: ITS,TPC,TPC-TOF,TPC-TRD,TPC-TRD-TOF"}}, {"produce-calibration-data", o2::framework::VariantType::Bool, false, {"produce output for TPC vdrift calibration"}}, {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings ..."}}}; @@ -64,22 +64,28 @@ WorkflowSpec defineDataProcessing(o2::framework::ConfigContext const& configcont // write the configuration used for the workflow o2::conf::ConfigurableParam::writeINI("o2matchtpcits-workflow_configuration.ini"); - GID::mask_t alowedSources = GID::getSourcesMask("ITS,TPC,FT0"); + GID::mask_t alowedSources = GID::getSourcesMask("ITS,TPC,TPC-TOF"); GID::mask_t src = alowedSources & GID::getSourcesMask(configcontext.options().get("track-sources")); - auto useFT0 = configcontext.options().get("use-ft0"); + if (useFT0) { + src |= GID::getSourceMask(GID::FT0); + } auto useMC = !configcontext.options().get("disable-mc"); auto calib = configcontext.options().get("produce-calibration-data"); - o2::framework::WorkflowSpec specs; + LOG(INFO) << "Data sources: " << GID::getSourcesNames(src); + auto srcL = src | GID::getSourcesMask("ITS,TPC"); // ITS is neadded always, TPC must be loaded even if bare TPC tracks are not used in matching - specs.emplace_back(o2::globaltracking::getTPCITSMatchingSpec(src, useFT0, calib, useMC)); + o2::framework::WorkflowSpec specs; + specs.emplace_back(o2::globaltracking::getTPCITSMatchingSpec(srcL, useFT0, calib, !GID::includesSource(GID::TPC, src), useMC)); if (!configcontext.options().get("disable-root-output")) { specs.emplace_back(o2::globaltracking::getTrackWriterTPCITSSpec(useMC)); } - o2::globaltracking::InputHelper::addInputSpecs(configcontext, specs, src, src, src, useMC); + // the only clusters MC which is need with useMC is ITS (for afterburner), for the rest we use tracks MC labels + o2::globaltracking::InputHelper::addInputSpecs(configcontext, specs, srcL, srcL, srcL, + useMC, GID::getSourceMask(GID::ITS)); return std::move(specs); } From d96c21feb6dccbc7f0c6eb7c045f6aa7b8233a10 Mon Sep 17 00:00:00 2001 From: Jorge Lopez Date: Mon, 19 Apr 2021 09:49:15 +0200 Subject: [PATCH 360/770] TRD: Better handling of labels at the digitizer --- .../TRD/include/DataFormatsTRD/SignalArray.h | 4 +- .../include/TRDSimulation/Digitizer.h | 19 +++------ Detectors/TRD/simulation/src/Digitizer.cxx | 41 +++++++++---------- 3 files changed, 28 insertions(+), 36 deletions(-) diff --git a/DataFormats/Detectors/TRD/include/DataFormatsTRD/SignalArray.h b/DataFormats/Detectors/TRD/include/DataFormatsTRD/SignalArray.h index 8d4bd8cc9b527..18d716041f4ff 100644 --- a/DataFormats/Detectors/TRD/include/DataFormatsTRD/SignalArray.h +++ b/DataFormats/Detectors/TRD/include/DataFormatsTRD/SignalArray.h @@ -15,7 +15,7 @@ #include "SimulationDataFormat/MCCompLabel.h" #include -#include +#include #include namespace o2 @@ -26,7 +26,7 @@ namespace trd struct SignalArray { double firstTBtime; // first TB time std::array signals{}; // signals - std::unordered_map trackIds; // tracks Ids associated to the signal + std::unordered_set trackIds; // tracks Ids associated to the signal std::vector labels; // labels associated to the signal bool isDigit = false; // flag a signal converted to a digit bool isShared = false; // flag if converted digit is shared (copied) diff --git a/Detectors/TRD/simulation/include/TRDSimulation/Digitizer.h b/Detectors/TRD/simulation/include/TRDSimulation/Digitizer.h index 0864dbd97c998..d1f40758e5d00 100644 --- a/Detectors/TRD/simulation/include/TRDSimulation/Digitizer.h +++ b/Detectors/TRD/simulation/include/TRDSimulation/Digitizer.h @@ -54,6 +54,7 @@ class Digitizer void process(std::vector const&); void flush(DigitContainer&, o2::dataformats::MCTruthContainer&); + void dumpLabels(const SignalContainer&, o2::dataformats::MCTruthContainer&); void pileup(); void setEventTime(double timeNS) { mTime = timeNS; } void setTriggerTime(double t) { mCurrentTriggerTime = t; } @@ -85,16 +86,8 @@ class Digitizer double mTime = 0.; // time in nanoseconds of the hits currently being processed double mCurrentTriggerTime = 0.; // time in nanoseconds of the current trigger - // - int mEventID = 0; - int mSrcID = 0; - - enum EventType { - kFirstEvent, - kPileupEvent, - kTriggerFired, - kEmbeddingEvent - }; + int mEventID = 0; // event id + int mSrcID = 0; // source id // Digitization parameters static constexpr float AmWidth = Geometry::amThick(); // Width of the amplification region @@ -122,9 +115,9 @@ class Digitizer int triggerEventProcessing(DigitContainer&, o2::dataformats::MCTruthContainer&); SignalContainer addSignalsFromPileup(); void clearContainers(); - bool convertHits(const int, const std::vector&, SignalContainer&, int thread = 0); // True if hit-to-signal conversion is successful - bool convertSignalsToADC(SignalContainer&, DigitContainer&, int thread = 0); // True if signal-to-ADC conversion is successful - void addLabel(const o2::trd::Hit& hit, std::vector&, std::unordered_map&); + bool convertHits(const int, const std::vector&, SignalContainer&, int thread = 0); // True if hit-to-signal conversion is successful + bool convertSignalsToADC(SignalContainer&, DigitContainer&, int thread = 0); // True if signal-to-ADC conversion is successful + void addLabel(const int&, std::vector&, std::unordered_set&); // add a MC label, check if trackId is already registered bool diffusion(float, float, float, float, float, float, double&, double&, double&, int thread = 0); // True if diffusion is applied successfully // Helpers for signal handling diff --git a/Detectors/TRD/simulation/src/Digitizer.cxx b/Detectors/TRD/simulation/src/Digitizer.cxx index 78990547d646f..c342a5064387f 100644 --- a/Detectors/TRD/simulation/src/Digitizer.cxx +++ b/Detectors/TRD/simulation/src/Digitizer.cxx @@ -90,6 +90,7 @@ void Digitizer::setSimulationParameters() void Digitizer::flush(DigitContainer& digits, o2::dataformats::MCTruthContainer& labels) { + size_t idx = labels.getIndexedSize(); if (mPileupSignals.size() > 0) { // Add the signals, all chambers are keept in the same signal container SignalContainer smc = addSignalsFromPileup(); @@ -98,14 +99,7 @@ void Digitizer::flush(DigitContainer& digits, o2::dataformats::MCTruthContainer< if (!status) { LOG(WARN) << "TRD conversion of signals to digits failed"; } - for (const auto& iter : smc) { - if (iter.second.isDigit) { - labels.addElements(labels.getIndexedSize(), iter.second.labels); - if (iter.second.isShared) { - labels.addElements(labels.getIndexedSize(), iter.second.labels); // shared digit is a copy of the previous one, need to add the same labels again - } - } - } + dumpLabels(smc, labels); } } else { // since we don't have any pileup signals just flush the signals for each chamber @@ -115,19 +109,24 @@ void Digitizer::flush(DigitContainer& digits, o2::dataformats::MCTruthContainer< if (!status) { LOG(WARN) << "TRD conversion of signals to digits failed"; } - for (const auto& iter : smc) { - if (iter.second.isDigit) { - labels.addElements(labels.getIndexedSize(), iter.second.labels); - if (iter.second.isShared) { - labels.addElements(labels.getIndexedSize(), iter.second.labels); // shared digit is a copy of the previous one, need to add the same labels again - } - } - } + dumpLabels(smc, labels); } } clearContainers(); } +void Digitizer::dumpLabels(const SignalContainer& smc, o2::dataformats::MCTruthContainer& labels) +{ + for (const auto& iter : smc) { + if (iter.second.isDigit) { + labels.addElements(labels.getIndexedSize(), iter.second.labels); + if (iter.second.isShared) { + labels.addElements(labels.getIndexedSize(), iter.second.labels); // shared digit is a copy of the previous one, need to add the same labels again + } + } + } +} + SignalContainer Digitizer::addSignalsFromPileup() { return pileupTool.addSignals(mPileupSignals, mCurrentTriggerTime); @@ -372,7 +371,7 @@ bool Digitizer::convertHits(const int det, const std::vector& hits, SignalC auto& trackIds = currentSignalData.trackIds; auto& labels = currentSignalData.labels; currentSignalData.firstTBtime = mTime; - addLabel(hit, labels, trackIds); // add a label record only if needed + addLabel(hit.GetTrackID(), labels, trackIds); // add a label record only if needed // add signal with crosstalk for the non-central pads only if (colPos != colE) { @@ -395,11 +394,11 @@ bool Digitizer::convertHits(const int det, const std::vector& hits, SignalC return true; } -void Digitizer::addLabel(const o2::trd::Hit& hit, std::vector& labels, std::unordered_map& trackIds) +void Digitizer::addLabel(const int& trackId, std::vector& labels, std::unordered_set& trackIds) { - if (trackIds[hit.GetTrackID()] == 0) { - trackIds[hit.GetTrackID()] = 1; - MCLabel label(hit.GetTrackID(), getEventID(), getSrcID()); + if (trackIds.count(trackId) == 0) { + trackIds.insert(trackId); + MCLabel label(trackId, getEventID(), getSrcID()); labels.push_back(label); } } From 122becaaba73fc289a0835d0ec575fd567f95be8 Mon Sep 17 00:00:00 2001 From: Roberto Preghenella Date: Mon, 11 Jan 2021 16:45:10 +0100 Subject: [PATCH 361/770] Change Tau0 max to 10 mm in Pythia8 configurations --- Generators/share/egconfig/pythia8_hf.cfg | 2 +- Generators/share/egconfig/pythia8_hi.cfg | 2 +- Generators/share/egconfig/pythia8_inel.cfg | 2 +- run/SimExamples/Adaptive_Pythia8/pythia8_inel.cfg | 2 +- run/SimExamples/Custom_EventInfo/pythia8_inel.cfg | 2 +- run/SimExamples/HF_Embedding_Pythia8/pythia8_ccbar.template | 2 +- run/SimExamples/Jet_Embedding_Pythia8/pythia8_hard.cfg | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Generators/share/egconfig/pythia8_hf.cfg b/Generators/share/egconfig/pythia8_hf.cfg index 123c4146c59af..273751f09d718 100644 --- a/Generators/share/egconfig/pythia8_hf.cfg +++ b/Generators/share/egconfig/pythia8_hf.cfg @@ -9,4 +9,4 @@ HardQCD:hardbbbar on # scatterings g-g / q-qbar -> b-bbar ### decays ParticleDecays:limitTau0 on -ParticleDecays:tau0Max 0.001 +ParticleDecays:tau0Max 10. diff --git a/Generators/share/egconfig/pythia8_hi.cfg b/Generators/share/egconfig/pythia8_hi.cfg index 2c9c8b68bdabb..85efe50fb9c5d 100644 --- a/Generators/share/egconfig/pythia8_hi.cfg +++ b/Generators/share/egconfig/pythia8_hi.cfg @@ -12,4 +12,4 @@ HeavyIon:bWidth 15. # impact parameter from 0-x [fm] ### decays ParticleDecays:limitTau0 on -ParticleDecays:tau0Max 0.001 +ParticleDecays:tau0Max 10. diff --git a/Generators/share/egconfig/pythia8_inel.cfg b/Generators/share/egconfig/pythia8_inel.cfg index fdea3cc091984..d5e23efd65139 100644 --- a/Generators/share/egconfig/pythia8_inel.cfg +++ b/Generators/share/egconfig/pythia8_inel.cfg @@ -8,4 +8,4 @@ SoftQCD:inelastic on # all inelastic processes ### decays ParticleDecays:limitTau0 on -ParticleDecays:tau0Max 0.001 +ParticleDecays:tau0Max 10. diff --git a/run/SimExamples/Adaptive_Pythia8/pythia8_inel.cfg b/run/SimExamples/Adaptive_Pythia8/pythia8_inel.cfg index fdea3cc091984..d5e23efd65139 100644 --- a/run/SimExamples/Adaptive_Pythia8/pythia8_inel.cfg +++ b/run/SimExamples/Adaptive_Pythia8/pythia8_inel.cfg @@ -8,4 +8,4 @@ SoftQCD:inelastic on # all inelastic processes ### decays ParticleDecays:limitTau0 on -ParticleDecays:tau0Max 0.001 +ParticleDecays:tau0Max 10. diff --git a/run/SimExamples/Custom_EventInfo/pythia8_inel.cfg b/run/SimExamples/Custom_EventInfo/pythia8_inel.cfg index fdea3cc091984..d5e23efd65139 100644 --- a/run/SimExamples/Custom_EventInfo/pythia8_inel.cfg +++ b/run/SimExamples/Custom_EventInfo/pythia8_inel.cfg @@ -8,4 +8,4 @@ SoftQCD:inelastic on # all inelastic processes ### decays ParticleDecays:limitTau0 on -ParticleDecays:tau0Max 0.001 +ParticleDecays:tau0Max 10. diff --git a/run/SimExamples/HF_Embedding_Pythia8/pythia8_ccbar.template b/run/SimExamples/HF_Embedding_Pythia8/pythia8_ccbar.template index 70c45acc4299b..a01289d6b45bf 100644 --- a/run/SimExamples/HF_Embedding_Pythia8/pythia8_ccbar.template +++ b/run/SimExamples/HF_Embedding_Pythia8/pythia8_ccbar.template @@ -16,4 +16,4 @@ PhaseSpace:pTHatMax ${pTHatMax} # the maximum invariant pT ### decays ParticleDecays:limitTau0 on -ParticleDecays:tau0Max 0.001 +ParticleDecays:tau0Max 10. diff --git a/run/SimExamples/Jet_Embedding_Pythia8/pythia8_hard.cfg b/run/SimExamples/Jet_Embedding_Pythia8/pythia8_hard.cfg index 5460f0eebc57e..14917d7344157 100644 --- a/run/SimExamples/Jet_Embedding_Pythia8/pythia8_hard.cfg +++ b/run/SimExamples/Jet_Embedding_Pythia8/pythia8_hard.cfg @@ -10,4 +10,4 @@ PhaseSpace:pTHatMin 500. # min pT hat ### decays ParticleDecays:limitTau0 on -ParticleDecays:tau0Max 0.001 +ParticleDecays:tau0Max 10. From 390e894a5a733779bd7400f4bde9a7b80948f926 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Mon, 3 May 2021 18:53:58 +0200 Subject: [PATCH 362/770] fix for spawner trying to create a projector for a table with empty schema (#6051) --- Framework/Core/include/Framework/TableBuilder.h | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Framework/Core/include/Framework/TableBuilder.h b/Framework/Core/include/Framework/TableBuilder.h index 31757b1ada93b..1bf04684d7f61 100644 --- a/Framework/Core/include/Framework/TableBuilder.h +++ b/Framework/Core/include/Framework/TableBuilder.h @@ -772,12 +772,11 @@ auto makeEmptyTable() template auto spawner(framework::pack columns, arrow::Table* atable, const char* name) { - static auto new_schema = o2::soa::createSchemaFromColumns(columns); - static auto projectors = framework::expressions::createProjectors(columns, atable->schema()); - if (atable->num_rows() == 0) { return makeEmptyTable>(); } + static auto new_schema = o2::soa::createSchemaFromColumns(columns); + static auto projectors = framework::expressions::createProjectors(columns, atable->schema()); arrow::TableBatchReader reader(*atable); std::shared_ptr batch; From f1e08c08bff521125885cb1bf056ad69ac5cd237 Mon Sep 17 00:00:00 2001 From: Philip Hauer Date: Wed, 17 Mar 2021 17:20:00 +0100 Subject: [PATCH 363/770] Implemented Param file for KrBoxClusterFinder --- Detectors/TPC/reconstruction/CMakeLists.txt | 2 + .../TPCReconstruction/KrBoxClusterFinder.h | 27 +- .../reconstruction/macro/findKrBoxCluster.C | 29 +- .../reconstruction/src/KrBoxClusterFinder.cxx | 259 ++++++++++++++++-- 4 files changed, 286 insertions(+), 31 deletions(-) diff --git a/Detectors/TPC/reconstruction/CMakeLists.txt b/Detectors/TPC/reconstruction/CMakeLists.txt index 15ef66461a963..b87251a7e0b32 100644 --- a/Detectors/TPC/reconstruction/CMakeLists.txt +++ b/Detectors/TPC/reconstruction/CMakeLists.txt @@ -18,6 +18,7 @@ o2_add_library(TPCReconstruction src/HwClusterer.cxx src/HwClustererParam.cxx src/KrBoxClusterFinder.cxx + src/KrBoxClusterFinderParam.cxx src/RawReader.cxx src/RawReaderCRU.cxx src/RawReaderEventSync.cxx @@ -46,6 +47,7 @@ o2_target_root_dictionary( include/TPCReconstruction/HwClusterer.h include/TPCReconstruction/HwClustererParam.h include/TPCReconstruction/KrBoxClusterFinder.h + include/TPCReconstruction/KrBoxClusterFinderParam.h include/TPCReconstruction/KrCluster.h include/TPCReconstruction/RawReader.h include/TPCReconstruction/RawReaderCRU.h diff --git a/Detectors/TPC/reconstruction/include/TPCReconstruction/KrBoxClusterFinder.h b/Detectors/TPC/reconstruction/include/TPCReconstruction/KrBoxClusterFinder.h index 6c859769c54c7..88f62384075d3 100644 --- a/Detectors/TPC/reconstruction/include/TPCReconstruction/KrBoxClusterFinder.h +++ b/Detectors/TPC/reconstruction/include/TPCReconstruction/KrBoxClusterFinder.h @@ -133,6 +133,29 @@ class KrBoxClusterFinder /// ger sector of this instance int getSector() const { return mSector; } + /// Set Function for minimum number of direct neighbours required + void setMinNumberOfNeighbours(int minNumberOfNeighbours) { mMinNumberOfNeighbours = minNumberOfNeighbours; } + + /// Set Function for minimal charge required for maxCharge of a cluster + void setMinQTreshold(int minQThreshold) { mQThresholdMax = minQThreshold; } + + /// Set Function for maximal cluster sizes in different ROCs + void setMaxClusterSize(int maxClusterSizeRowIROC, int maxClusterSizeRowOROC1, int maxClusterSizeRowOROC2, int maxClusterSizeRowOROC3, + int maxClusterSizePadIROC, int maxClusterSizePadOROC1, int maxClusterSizePadOROC2, int maxClusterSizePadOROC3, + int maxClusterSizeTime) { + mMaxClusterSizeRowIROC = maxClusterSizeRowIROC; + mMaxClusterSizeRowOROC1 = maxClusterSizeRowOROC1; + mMaxClusterSizeRowOROC2 = maxClusterSizeRowOROC2; + mMaxClusterSizeRowOROC3 = maxClusterSizeRowOROC3; + + mMaxClusterSizePadIROC = maxClusterSizePadIROC; + mMaxClusterSizePadOROC1 = maxClusterSizePadOROC1; + mMaxClusterSizePadOROC2 = maxClusterSizePadOROC2; + mMaxClusterSizePadOROC3 = maxClusterSizePadOROC3; + + mMaxClusterSizeTime = maxClusterSizeTime; + } + private: // These variables can be varied // They were choses such that the box in each readout chamber is approx. the same size @@ -150,9 +173,9 @@ class KrBoxClusterFinder int mMaxClusterSizePadOROC2 = 3; ///< The "radius" of a cluster in pad direction in OROC2 int mMaxClusterSizePadOROC3 = 3; ///< The "radius" of a cluster in pad direction in OROC3 - float mQThresholdMax = 10.0; ///< the Maximum charge in a cluster must exceed this value or it is discarded + float mQThresholdMax = 50.0; ///< the Maximum charge in a cluster must exceed this value or it is discarded float mQThreshold = 1.0; ///< every charge which is added to a cluster must exceed this value or it is discarded - int mMinNumberOfNeighbours = 1; ///< amount of direct neighbours required for a cluster maximum + int mMinNumberOfNeighbours = 2; ///< amount of direct neighbours required for a cluster maximum int mSector = -1; ///< sector being processed in this instance std::unique_ptr mGainMap; ///< Gain map object diff --git a/Detectors/TPC/reconstruction/macro/findKrBoxCluster.C b/Detectors/TPC/reconstruction/macro/findKrBoxCluster.C index 2429eb3a0417a..507f69de9e314 100644 --- a/Detectors/TPC/reconstruction/macro/findKrBoxCluster.C +++ b/Detectors/TPC/reconstruction/macro/findKrBoxCluster.C @@ -27,16 +27,16 @@ #include #endif -void findKrBoxCluster(int lastTimeBin = 1000, int run = -1, int time = -1, std::string_view gainMapFile = "") +void findKrBoxCluster(int lastTimeBin = 20000, int run = -1, int time = -1, std::string_view gainMapFile = "") { // Read the digits: - TFile* file = new TFile("tpcdigits.root"); + TFile* file = new TFile("data_20210303_0911.digits.root"); TTree* tree = (TTree*)file->Get("o2sim"); Long64_t nEntries = tree->GetEntries(); std::cout << "The Tree has " << nEntries << " Entries." << std::endl; // Initialize File for later writing - TFile* fOut = new TFile("BoxClusters.root", "RECREATE"); + TFile* fOut = new TFile("SpeedTest/BoxClusters_setDigitZero.root", "RECREATE"); TTree* tClusters = new TTree("Clusters", "Clusters"); // Create a Branch for each sector: @@ -57,6 +57,9 @@ void findKrBoxCluster(int lastTimeBin = 1000, int run = -1, int time = -1, std:: clFinder->loadGainMapFromFile(gainMapFile); } + ofstream outFile; + outFile.open("SpeedTest/2Neighbours_setDigitZero.dat"); + // Now everything can get processed // Loop over all events for (int iEvent = 0; iEvent < nEntries; ++iEvent) { @@ -64,6 +67,7 @@ void findKrBoxCluster(int lastTimeBin = 1000, int run = -1, int time = -1, std:: tree->GetEntry(iEvent); // Each event consists of sectors (atm only two) + auto start = std::chrono::high_resolution_clock::now(); for (int i = 0; i < 36; i++) { auto sector = digitizedSignal[i]; if (sector->size() == 0) { @@ -71,12 +75,21 @@ void findKrBoxCluster(int lastTimeBin = 1000, int run = -1, int time = -1, std:: } // Fill map and (if specified) correct with existing gain map + auto startFillMap = std::chrono::high_resolution_clock::now(); clFinder->fillAndCorrectMap(*sector, i); + auto endFillMap = std::chrono::high_resolution_clock::now(); + auto durationFillMap = std::chrono::duration_cast(endFillMap - startFillMap); + std::cout << "Time to fill map: " << durationFillMap.count() << std::endl; // Find all local maxima in sector + auto startFindMaxima = std::chrono::high_resolution_clock::now(); std::vector> localMaxima = clFinder->findLocalMaxima(); - + auto endFindMaxima = std::chrono::high_resolution_clock::now(); + auto durationMaxima = std::chrono::duration_cast(endFindMaxima - startFindMaxima); + std::cout << "Time to find Maxs: " << durationMaxima.count() << std::endl; + // Loop over cluster centers = local maxima + auto startBuildCluster = std::chrono::high_resolution_clock::now(); for (const std::tuple& coords : localMaxima) { int padMax = std::get<0>(coords); int rowMax = std::get<1>(coords); @@ -91,7 +104,14 @@ void findKrBoxCluster(int lastTimeBin = 1000, int run = -1, int time = -1, std:: clusters.emplace_back(tempCluster); } + auto endBuildCluster = std::chrono::high_resolution_clock::now(); + auto durationBuildCluster = std::chrono::duration_cast(endBuildCluster - startBuildCluster); + std::cout << "Time to build cls: " << durationBuildCluster.count() << std::endl; } + auto end = std::chrono::high_resolution_clock::now(); + auto duration = std::chrono::duration_cast(end - start); + std::cout << "Time for all sectors: " << duration.count() << std::endl; + outFile << duration.count() << std::endl; // Fill Tree tClusters->Fill(); clusters.clear(); @@ -99,6 +119,7 @@ void findKrBoxCluster(int lastTimeBin = 1000, int run = -1, int time = -1, std:: // Write Tree to file fOut->Write(); fOut->Close(); + outFile.close(); return; } diff --git a/Detectors/TPC/reconstruction/src/KrBoxClusterFinder.cxx b/Detectors/TPC/reconstruction/src/KrBoxClusterFinder.cxx index e48c99ee8cb8b..423ca3c0e4f3d 100644 --- a/Detectors/TPC/reconstruction/src/KrBoxClusterFinder.cxx +++ b/Detectors/TPC/reconstruction/src/KrBoxClusterFinder.cxx @@ -119,24 +119,36 @@ void KrBoxClusterFinder::fillADCValue(int cru, int rowInSector, int padInRow, in // Function to update the temporal cluster void KrBoxClusterFinder::updateTempClusterFinal() { - const float oneOverQtot = 1. / mTempCluster.totCharge; - mTempCluster.meanPad *= oneOverQtot; - mTempCluster.sigmaPad *= oneOverQtot; - mTempCluster.meanRow *= oneOverQtot; - mTempCluster.sigmaRow *= oneOverQtot; - mTempCluster.meanTime *= oneOverQtot; - mTempCluster.sigmaTime *= oneOverQtot; - mTempCluster.sigmaPad = std::sqrt(std::abs(mTempCluster.sigmaPad - mTempCluster.meanPad * mTempCluster.meanPad)); - mTempCluster.sigmaRow = std::sqrt(std::abs(mTempCluster.sigmaRow - mTempCluster.meanRow * mTempCluster.meanRow)); - mTempCluster.sigmaTime = std::sqrt(std::abs(mTempCluster.sigmaTime - mTempCluster.meanTime * mTempCluster.meanTime)); - - const int corPadsMean = mMapperInstance.getNumberOfPadsInRowSector(int(mTempCluster.meanRow)); - const int corPadsMaxCharge = mMapperInstance.getNumberOfPadsInRowSector(int(mTempCluster.maxChargeRow)); - - // Since every padrow is shifted such that neighbouring pads are indeed neighbours, we have to shift once back: - mTempCluster.meanPad = mTempCluster.meanPad + (corPadsMean / 2.0) - (MaxPads / 2.0); - mTempCluster.maxChargePad = mTempCluster.maxChargePad + (corPadsMaxCharge / 2.0) - (MaxPads / 2.0); - mTempCluster.sector = (decltype(mTempCluster.sector))mSector; + if(mTempCluster.totCharge == 0) { + mTempCluster.reset(); + } else { + const float oneOverQtot = 1. / mTempCluster.totCharge; + mTempCluster.meanPad *= oneOverQtot; + mTempCluster.sigmaPad *= oneOverQtot; + mTempCluster.meanRow *= oneOverQtot; + mTempCluster.sigmaRow *= oneOverQtot; + mTempCluster.meanTime *= oneOverQtot; + mTempCluster.sigmaTime *= oneOverQtot; + mTempCluster.sigmaPad = std::sqrt(std::abs(mTempCluster.sigmaPad - mTempCluster.meanPad * mTempCluster.meanPad)); + mTempCluster.sigmaRow = std::sqrt(std::abs(mTempCluster.sigmaRow - mTempCluster.meanRow * mTempCluster.meanRow)); + mTempCluster.sigmaTime = std::sqrt(std::abs(mTempCluster.sigmaTime - mTempCluster.meanTime * mTempCluster.meanTime)); + // if(int(mTempCluster.size) < 2) { + // std::cout << "QTot: " << mTempCluster.totCharge << std::endl; + // std::cout << "QMax: " << mTempCluster.maxCharge << std::endl; + // std::cout << "size: " << int(mTempCluster.size) << std::endl; + // std::cout << "MeanRow: " << mTempCluster.meanRow << std::endl; + // std::cout << "MeanPad: " << mTempCluster.meanPad << std::endl; + // std::cout << "MeanTime: " << mTempCluster.meanTime << std::endl; + // } + + const int corPadsMean = mMapperInstance.getNumberOfPadsInRowSector(int(mTempCluster.meanRow)); + const int corPadsMaxCharge = mMapperInstance.getNumberOfPadsInRowSector(int(mTempCluster.maxChargeRow)); + + // Since every padrow is shifted such that neighbouring pads are indeed neighbours, we have to shift once back: + mTempCluster.meanPad = mTempCluster.meanPad + (corPadsMean / 2.0) - (MaxPads / 2.0); + mTempCluster.maxChargePad = mTempCluster.maxChargePad + (corPadsMaxCharge / 2.0) - (MaxPads / 2.0); + mTempCluster.sector = (decltype(mTempCluster.sector))mSector; + } } // Function to update the temporal cluster. @@ -146,8 +158,10 @@ void KrBoxClusterFinder::updateTempCluster(float tempCharge, int tempPad, int te LOGP(warning, "Update cluster was called but current charge is below mQThreshold"); return; } + if (mTempCluster.size < 255) { + mTempCluster.size += 1; + } - mTempCluster.size += 1; mTempCluster.totCharge += tempCharge; mTempCluster.meanPad += tempPad * tempCharge; @@ -164,6 +178,12 @@ void KrBoxClusterFinder::updateTempCluster(float tempCharge, int tempPad, int te mTempCluster.maxChargePad = tempPad; mTempCluster.maxChargeRow = tempRow; } + + // Set this digit to 0 + // std::cout << "Pad: " << tempPad << std::endl; + // std::cout << "Time: " << tempTime << std::endl; + // std::cout << "Row: " << tempRow << std::endl; + mMapOfAllDigits[tempTime][tempRow][tempPad] = 0; } // This function finds and evaluates all clusters in a 3D mMapOfAllDigits generated by the @@ -195,21 +215,39 @@ std::vector> KrBoxClusterFinder::findLocalMaxima(bool // with signal in any direction! int noNeighbours = 0; if ((iPad + 1 < MaxPads) && (mMapOfAllDigits[iTime][iRow][iPad + 1] > mQThreshold)) { + if(mMapOfAllDigits[iTime][iRow][iPad + 1] > qMax) { + continue; + } noNeighbours++; } if ((iPad - 1 >= 0) && (mMapOfAllDigits[iTime][iRow][iPad - 1] > mQThreshold)) { + if(mMapOfAllDigits[iTime][iRow][iPad - 1] > qMax) { + continue; + } noNeighbours++; } if ((iTime + 1 < MaxTimes) && (mMapOfAllDigits[iTime + 1][iRow][iPad] > mQThreshold)) { + if(mMapOfAllDigits[iTime + 1][iRow][iPad] > qMax) { + continue; + } noNeighbours++; } if ((iTime - 1 >= 0) && (mMapOfAllDigits[iTime - 1][iRow][iPad] > mQThreshold)) { + if(mMapOfAllDigits[iTime - 1][iRow][iPad] > qMax) { + continue; + } noNeighbours++; } if ((iRow + 1 < MaxRows) && (mMapOfAllDigits[iTime][iRow + 1][iPad] > mQThreshold)) { + if(mMapOfAllDigits[iTime][iRow + 1][iPad] > qMax) { + continue; + } noNeighbours++; } if ((iRow - 1 >= 0) && (mMapOfAllDigits[iTime][iRow - 1][iPad] > mQThreshold)) { + if(mMapOfAllDigits[iTime][iRow - 1][iPad] > qMax) { + continue; + } noNeighbours++; } if (noNeighbours < mMinNumberOfNeighbours) { @@ -223,21 +261,192 @@ std::vector> KrBoxClusterFinder::findLocalMaxima(bool // -> only the maximum with the smalest indices will be accepted bool thisIsMax = true; - for (int i = -mMaxClusterSizePad; (i <= mMaxClusterSizePad) && thisIsMax; i++) { - if ((iPad + i >= MaxPads) || (iPad + i < 0)) { + + // Check diagonals in pad- and row-direction + if(iRow + 1 < MaxRows && iPad + 1 < MaxPads) { + if(mMapOfAllDigits[iTime][iRow + 1][iPad + 1] > qMax) { + continue; + } + } + if(iRow - 1 >= 0 && iPad + 1 < MaxPads) { + if(mMapOfAllDigits[iTime][iRow - 1][iPad + 1] > qMax) { + continue; + } + } + if(iRow + 1 < MaxRows && iPad - 1 >= 0) { + if(mMapOfAllDigits[iTime][iRow + 1][iPad - 1] > qMax) { + continue; + } + } + if(iRow - 1 >= 0 && iPad - 1 >= 0) { + if(mMapOfAllDigits[iTime][iRow - 1][iPad - 1] > qMax) { + continue; + } + } + + // Check diagonals in pad- and time-direction + if(iTime + 1 < MaxTimes && iPad + 1 < MaxPads) { + if(mMapOfAllDigits[iTime + 1][iRow][iPad + 1] > qMax) { + continue; + } + } + if(iTime - 1 >= 0 && iPad + 1 < MaxPads) { + if(mMapOfAllDigits[iTime - 1][iRow][iPad + 1] > qMax) { + continue; + } + } + if(iTime + 1 < MaxTimes && iPad - 1 >= 0) { + if(mMapOfAllDigits[iTime + 1][iRow][iPad - 1] > qMax) { + continue; + } + } + if(iTime - 1 >= 0 && iPad - 1 >= 0) { + if(mMapOfAllDigits[iTime - 1][iRow][iPad - 1] > qMax) { + continue; + } + } + + // Check diagonals in row- and time-direction + if(iTime + 1 < MaxTimes && iRow + 1 < MaxRows) { + if(mMapOfAllDigits[iTime + 1][iRow + 1][iPad] > qMax) { + continue; + } + } + if(iTime - 1 >= 0 && iRow + 1 < MaxRows) { + if(mMapOfAllDigits[iTime - 1][iRow + 1][iPad] > qMax) { + continue; + } + } + if(iTime + 1 < MaxTimes && iRow - 1 >= 0) { + if(mMapOfAllDigits[iTime + 1][iRow - 1][iPad] > qMax) { + continue; + } + } + if(iTime - 1 >= 0 && iRow - 1 >= 0) { + if(mMapOfAllDigits[iTime - 1][iRow - 1][iPad] > qMax) { + continue; + } + } + + // Check diagonals in row-, pad- and time-direction + if(iTime + 1 < MaxTimes && iRow + 1 < MaxRows && iPad + 1 < MaxPads) { + if(mMapOfAllDigits[iTime + 1][iRow + 1][iPad + 1] > qMax) { + continue; + } + } + if(iTime + 1 < MaxTimes && iRow + 1 < MaxRows && iPad - 1 >= 0) { + if(mMapOfAllDigits[iTime + 1][iRow + 1][iPad - 1] > qMax) { + continue; + } + } + if(iTime + 1 < MaxTimes && iRow - 1 >= 0 && iPad + 1 < MaxPads) { + if(mMapOfAllDigits[iTime + 1][iRow - 1][iPad + 1] > qMax) { + continue; + } + } + if(iTime + 1 < MaxTimes && iRow - 1 >= 0 && iPad - 1 >= 0) { + if(mMapOfAllDigits[iTime + 1][iRow - 1][iPad - 1] > qMax) { + continue; + } + } + if(iTime - 1 >= 0 && iRow + 1 < MaxRows && iPad + 1 < MaxPads) { + if(mMapOfAllDigits[iTime - 1][iRow + 1][iPad + 1] > qMax) { + continue; + } + } + if(iTime - 1 >= 0 && iRow + 1 < MaxRows && iPad - 1 >= 0) { + if(mMapOfAllDigits[iTime - 1][iRow + 1][iPad - 1] > qMax) { + continue; + } + } + if(iTime - 1 >= 0 && iRow - 1 >= 0 && iPad + 1 < MaxPads) { + if(mMapOfAllDigits[iTime - 1][iRow - 1][iPad + 1] > qMax) { + continue; + } + } + if(iTime - 1 >= 0 && iRow - 1 >= 0 && iPad - 1 >= 0) { + if(mMapOfAllDigits[iTime - 1][iRow - 1][iPad - 1] > qMax) { + continue; + } + } + + for (int i = 2; (i <= mMaxClusterSizePad) && thisIsMax; i++) { + if (iPad + i >= MaxPads) { continue; } - for (int k = -mMaxClusterSizeRow; (k <= mMaxClusterSizeRow) && thisIsMax; k++) { - if ((iRow + k >= MaxRows) || (iRow + k < 0)) { + for (int k = 2; (k <= mMaxClusterSizeRow) && thisIsMax; k++) { + if (iRow + k >= MaxRows) { continue; } - for (int j = -mMaxClusterSizeTime; (j <= mMaxClusterSizeTime) && thisIsMax; j++) { - if ((iTime + j >= MaxTimes) || (iTime + j < 0)) { + for (int j = 2; (j <= mMaxClusterSizeTime) && thisIsMax; j++) { + if (iTime + j >= MaxTimes) { continue; } if (mMapOfAllDigits[iTime + j][iRow + k][iPad + i] > qMax) { thisIsMax = false; } + if (iTime - j < 0) { + continue; + } + if (mMapOfAllDigits[iTime - j][iRow + k][iPad + i] > qMax) { + thisIsMax = false; + } + } + if (iRow - k < 0) { + continue; + } + for (int j = 2; (j <= mMaxClusterSizeTime) && thisIsMax; j++) { + if (iTime + j >= MaxTimes) { + continue; + } + if (mMapOfAllDigits[iTime + j][iRow - k][iPad + i] > qMax) { + thisIsMax = false; + } + if (iTime - j < 0) { + continue; + } + if (mMapOfAllDigits[iTime - j][iRow - k][iPad + i] > qMax) { + thisIsMax = false; + } + } + } + if (iPad - i < 0) { + continue; + } + for (int k = 2; (k <= mMaxClusterSizeRow) && thisIsMax; k++) { + if (iRow + k >= MaxRows) { + continue; + } + for (int j = 2; (j <= mMaxClusterSizeTime) && thisIsMax; j++) { + if (iTime + j >= MaxTimes) { + continue; + } + if (mMapOfAllDigits[iTime + j][iRow + k][iPad - i] > qMax) { + thisIsMax = false; + } + if (iTime - j < 0) { + continue; + } + if (mMapOfAllDigits[iTime - j][iRow + k][iPad - i] > qMax) { + thisIsMax = false; + } + } + if (iRow - k < 0) { + continue; + } + for (int j = 2; (j <= mMaxClusterSizeTime) && thisIsMax; j++) { + if (iTime + j >= MaxTimes) { + continue; + } + if (mMapOfAllDigits[iTime + j][iRow - k][iPad - i] > qMax) { + thisIsMax = false; + } + if (iTime - j < 0) { + continue; + } + if (mMapOfAllDigits[iTime - j][iRow - k][iPad - i] > qMax) { + thisIsMax = false; + } } } } From 33aa313e45f10c05f91f684c810a362eb9c3e09c Mon Sep 17 00:00:00 2001 From: Philip Hauer Date: Mon, 12 Apr 2021 18:15:55 +0200 Subject: [PATCH 364/770] Update on KrBoxClusterFinder (included Param-Class and a few updates) --- .../TPCReconstruction/KrBoxClusterFinder.h | 36 ++- .../KrBoxClusterFinderParam.h | 51 ++++ .../reconstruction/macro/findKrBoxCluster.C | 29 +- .../reconstruction/src/KrBoxClusterFinder.cxx | 262 ++++-------------- .../src/KrBoxClusterFinderParam.cxx | 18 ++ .../src/TPCReconstructionLinkDef.h | 2 + 6 files changed, 154 insertions(+), 244 deletions(-) create mode 100644 Detectors/TPC/reconstruction/include/TPCReconstruction/KrBoxClusterFinderParam.h create mode 100644 Detectors/TPC/reconstruction/src/KrBoxClusterFinderParam.cxx diff --git a/Detectors/TPC/reconstruction/include/TPCReconstruction/KrBoxClusterFinder.h b/Detectors/TPC/reconstruction/include/TPCReconstruction/KrBoxClusterFinder.h index 88f62384075d3..8ff72ac94d999 100644 --- a/Detectors/TPC/reconstruction/include/TPCReconstruction/KrBoxClusterFinder.h +++ b/Detectors/TPC/reconstruction/include/TPCReconstruction/KrBoxClusterFinder.h @@ -70,6 +70,8 @@ #include "DataFormatsTPC/Digit.h" #include "TPCReconstruction/KrCluster.h" +#include "TPCReconstruction/KrBoxClusterFinderParam.h" + #include "TPCBase/Mapper.h" #include "TPCBase/CalDet.h" @@ -133,6 +135,9 @@ class KrBoxClusterFinder /// ger sector of this instance int getSector() const { return mSector; } + /// initialize the parameters from KrBoxClusterFinderParam + void init(); + /// Set Function for minimum number of direct neighbours required void setMinNumberOfNeighbours(int minNumberOfNeighbours) { mMinNumberOfNeighbours = minNumberOfNeighbours; } @@ -141,20 +146,21 @@ class KrBoxClusterFinder /// Set Function for maximal cluster sizes in different ROCs void setMaxClusterSize(int maxClusterSizeRowIROC, int maxClusterSizeRowOROC1, int maxClusterSizeRowOROC2, int maxClusterSizeRowOROC3, - int maxClusterSizePadIROC, int maxClusterSizePadOROC1, int maxClusterSizePadOROC2, int maxClusterSizePadOROC3, - int maxClusterSizeTime) { - mMaxClusterSizeRowIROC = maxClusterSizeRowIROC; - mMaxClusterSizeRowOROC1 = maxClusterSizeRowOROC1; - mMaxClusterSizeRowOROC2 = maxClusterSizeRowOROC2; - mMaxClusterSizeRowOROC3 = maxClusterSizeRowOROC3; - - mMaxClusterSizePadIROC = maxClusterSizePadIROC; - mMaxClusterSizePadOROC1 = maxClusterSizePadOROC1; - mMaxClusterSizePadOROC2 = maxClusterSizePadOROC2; - mMaxClusterSizePadOROC3 = maxClusterSizePadOROC3; - - mMaxClusterSizeTime = maxClusterSizeTime; - } + int maxClusterSizePadIROC, int maxClusterSizePadOROC1, int maxClusterSizePadOROC2, int maxClusterSizePadOROC3, + int maxClusterSizeTime) + { + mMaxClusterSizeRowIROC = maxClusterSizeRowIROC; + mMaxClusterSizeRowOROC1 = maxClusterSizeRowOROC1; + mMaxClusterSizeRowOROC2 = maxClusterSizeRowOROC2; + mMaxClusterSizeRowOROC3 = maxClusterSizeRowOROC3; + + mMaxClusterSizePadIROC = maxClusterSizePadIROC; + mMaxClusterSizePadOROC1 = maxClusterSizePadOROC1; + mMaxClusterSizePadOROC2 = maxClusterSizePadOROC2; + mMaxClusterSizePadOROC3 = maxClusterSizePadOROC3; + + mMaxClusterSizeTime = maxClusterSizeTime; + } private: // These variables can be varied @@ -173,7 +179,7 @@ class KrBoxClusterFinder int mMaxClusterSizePadOROC2 = 3; ///< The "radius" of a cluster in pad direction in OROC2 int mMaxClusterSizePadOROC3 = 3; ///< The "radius" of a cluster in pad direction in OROC3 - float mQThresholdMax = 50.0; ///< the Maximum charge in a cluster must exceed this value or it is discarded + float mQThresholdMax = 30.0; ///< the Maximum charge in a cluster must exceed this value or it is discarded float mQThreshold = 1.0; ///< every charge which is added to a cluster must exceed this value or it is discarded int mMinNumberOfNeighbours = 2; ///< amount of direct neighbours required for a cluster maximum diff --git a/Detectors/TPC/reconstruction/include/TPCReconstruction/KrBoxClusterFinderParam.h b/Detectors/TPC/reconstruction/include/TPCReconstruction/KrBoxClusterFinderParam.h new file mode 100644 index 0000000000000..2101808472a9e --- /dev/null +++ b/Detectors/TPC/reconstruction/include/TPCReconstruction/KrBoxClusterFinderParam.h @@ -0,0 +1,51 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file KrBoxClusterFinderParam.h +/// \brief Parameter class for the Kr box cluster finder +/// +/// \author Philip Hauer, hauer@hiskp.uni-bonn.de + +#ifndef ALICEO2_TPC_KrBoxClusterFinderParam_H_ +#define ALICEO2_TPC_KrBoxClusterFinderParam_H_ + +#include "CommonUtils/ConfigurableParam.h" +#include "CommonUtils/ConfigurableParamHelper.h" + +#include "DataFormatsTPC/Defs.h" + +namespace o2 +{ +namespace tpc +{ + +struct KrBoxClusterFinderParam : public o2::conf::ConfigurableParamHelper { + int MaxClusterSizeTime{3}; ///< "radius" of a cluster in time direction + + int MaxClusterSizeRowIROC{3}; ///< "radius" of a cluster in row direction in IROC + int MaxClusterSizeRowOROC1{2}; ///< "radius" of a cluster in row direction in OROC1 + int MaxClusterSizeRowOROC2{2}; ///< "radius" of a cluster in row direction in OROC2 + int MaxClusterSizeRowOROC3{1}; ///< "radius" of a cluster in row direction in OROC3 + + int MaxClusterSizePadIROC{5}; ///< "radius" of a cluster in pad direction in IROC + int MaxClusterSizePadOROC1{3}; ///< "radius" of a cluster in pad direction in OROC1 + int MaxClusterSizePadOROC2{3}; ///< "radius" of a cluster in pad direction in OROC2 + int MaxClusterSizePadOROC3{3}; ///< "radius" of a cluster in pad direction in OROC3 + + float QThresholdMax{30.0}; ///< the Maximum charge in a cluster must exceed this value or it is discarded + float QThreshold{1.0}; ///< every charge which is added to a cluster must exceed this value or it is discarded + int MinNumberOfNeighbours{2}; ///< amount of direct neighbours required for a cluster maximum + + O2ParamDef(KrBoxClusterFinderParam, "TPCKrBoxClusterFinder"); +}; +} // namespace tpc +} // namespace o2 + +#endif // ALICEO2_TPC_KrBoxClusterFinderParam_H_ \ No newline at end of file diff --git a/Detectors/TPC/reconstruction/macro/findKrBoxCluster.C b/Detectors/TPC/reconstruction/macro/findKrBoxCluster.C index 507f69de9e314..6212eeb43b5fd 100644 --- a/Detectors/TPC/reconstruction/macro/findKrBoxCluster.C +++ b/Detectors/TPC/reconstruction/macro/findKrBoxCluster.C @@ -27,16 +27,16 @@ #include #endif -void findKrBoxCluster(int lastTimeBin = 20000, int run = -1, int time = -1, std::string_view gainMapFile = "") +void findKrBoxCluster(int lastTimeBin = 1000, int run = -1, int time = -1, std::string_view gainMapFile = "", std::string inputFile = "tpcdigits.root", std::string outputFile = "BoxClusters.root") { // Read the digits: - TFile* file = new TFile("data_20210303_0911.digits.root"); + TFile* file = new TFile(inputFile.c_str()); TTree* tree = (TTree*)file->Get("o2sim"); Long64_t nEntries = tree->GetEntries(); std::cout << "The Tree has " << nEntries << " Entries." << std::endl; // Initialize File for later writing - TFile* fOut = new TFile("SpeedTest/BoxClusters_setDigitZero.root", "RECREATE"); + TFile* fOut = new TFile(outputFile.c_str(), "RECREATE"); TTree* tClusters = new TTree("Clusters", "Clusters"); // Create a Branch for each sector: @@ -57,9 +57,6 @@ void findKrBoxCluster(int lastTimeBin = 20000, int run = -1, int time = -1, std: clFinder->loadGainMapFromFile(gainMapFile); } - ofstream outFile; - outFile.open("SpeedTest/2Neighbours_setDigitZero.dat"); - // Now everything can get processed // Loop over all events for (int iEvent = 0; iEvent < nEntries; ++iEvent) { @@ -67,7 +64,6 @@ void findKrBoxCluster(int lastTimeBin = 20000, int run = -1, int time = -1, std: tree->GetEntry(iEvent); // Each event consists of sectors (atm only two) - auto start = std::chrono::high_resolution_clock::now(); for (int i = 0; i < 36; i++) { auto sector = digitizedSignal[i]; if (sector->size() == 0) { @@ -75,21 +71,12 @@ void findKrBoxCluster(int lastTimeBin = 20000, int run = -1, int time = -1, std: } // Fill map and (if specified) correct with existing gain map - auto startFillMap = std::chrono::high_resolution_clock::now(); clFinder->fillAndCorrectMap(*sector, i); - auto endFillMap = std::chrono::high_resolution_clock::now(); - auto durationFillMap = std::chrono::duration_cast(endFillMap - startFillMap); - std::cout << "Time to fill map: " << durationFillMap.count() << std::endl; // Find all local maxima in sector - auto startFindMaxima = std::chrono::high_resolution_clock::now(); std::vector> localMaxima = clFinder->findLocalMaxima(); - auto endFindMaxima = std::chrono::high_resolution_clock::now(); - auto durationMaxima = std::chrono::duration_cast(endFindMaxima - startFindMaxima); - std::cout << "Time to find Maxs: " << durationMaxima.count() << std::endl; - + // Loop over cluster centers = local maxima - auto startBuildCluster = std::chrono::high_resolution_clock::now(); for (const std::tuple& coords : localMaxima) { int padMax = std::get<0>(coords); int rowMax = std::get<1>(coords); @@ -104,14 +91,7 @@ void findKrBoxCluster(int lastTimeBin = 20000, int run = -1, int time = -1, std: clusters.emplace_back(tempCluster); } - auto endBuildCluster = std::chrono::high_resolution_clock::now(); - auto durationBuildCluster = std::chrono::duration_cast(endBuildCluster - startBuildCluster); - std::cout << "Time to build cls: " << durationBuildCluster.count() << std::endl; } - auto end = std::chrono::high_resolution_clock::now(); - auto duration = std::chrono::duration_cast(end - start); - std::cout << "Time for all sectors: " << duration.count() << std::endl; - outFile << duration.count() << std::endl; // Fill Tree tClusters->Fill(); clusters.clear(); @@ -119,7 +99,6 @@ void findKrBoxCluster(int lastTimeBin = 20000, int run = -1, int time = -1, std: // Write Tree to file fOut->Write(); fOut->Close(); - outFile.close(); return; } diff --git a/Detectors/TPC/reconstruction/src/KrBoxClusterFinder.cxx b/Detectors/TPC/reconstruction/src/KrBoxClusterFinder.cxx index 423ca3c0e4f3d..df4229c36f52c 100644 --- a/Detectors/TPC/reconstruction/src/KrBoxClusterFinder.cxx +++ b/Detectors/TPC/reconstruction/src/KrBoxClusterFinder.cxx @@ -114,12 +114,33 @@ void KrBoxClusterFinder::fillADCValue(int cru, int rowInSector, int padInRow, in mMapOfAllDigits[timeBin][rowInSector][corPad] = adcValue; } +void KrBoxClusterFinder::init() +{ + const auto& param = KrBoxClusterFinderParam::Instance(); + + mMaxClusterSizeTime = param.MaxClusterSizeTime; + + mMaxClusterSizeRowIROC = param.MaxClusterSizeRowIROC; + mMaxClusterSizeRowOROC1 = param.MaxClusterSizeRowOROC1; + mMaxClusterSizeRowOROC2 = param.MaxClusterSizeRowOROC2; + mMaxClusterSizeRowOROC3 = param.MaxClusterSizeRowOROC3; + + mMaxClusterSizePadIROC = param.MaxClusterSizePadIROC; + mMaxClusterSizePadOROC1 = param.MaxClusterSizePadOROC1; + mMaxClusterSizePadOROC2 = param.MaxClusterSizePadOROC2; + mMaxClusterSizePadOROC3 = param.MaxClusterSizePadOROC3; + + mQThresholdMax = param.QThresholdMax; + mQThreshold = param.QThreshold; + mMinNumberOfNeighbours = param.MinNumberOfNeighbours; +} + //################################################# // Function to update the temporal cluster void KrBoxClusterFinder::updateTempClusterFinal() { - if(mTempCluster.totCharge == 0) { + if (mTempCluster.totCharge == 0) { mTempCluster.reset(); } else { const float oneOverQtot = 1. / mTempCluster.totCharge; @@ -132,14 +153,6 @@ void KrBoxClusterFinder::updateTempClusterFinal() mTempCluster.sigmaPad = std::sqrt(std::abs(mTempCluster.sigmaPad - mTempCluster.meanPad * mTempCluster.meanPad)); mTempCluster.sigmaRow = std::sqrt(std::abs(mTempCluster.sigmaRow - mTempCluster.meanRow * mTempCluster.meanRow)); mTempCluster.sigmaTime = std::sqrt(std::abs(mTempCluster.sigmaTime - mTempCluster.meanTime * mTempCluster.meanTime)); - // if(int(mTempCluster.size) < 2) { - // std::cout << "QTot: " << mTempCluster.totCharge << std::endl; - // std::cout << "QMax: " << mTempCluster.maxCharge << std::endl; - // std::cout << "size: " << int(mTempCluster.size) << std::endl; - // std::cout << "MeanRow: " << mTempCluster.meanRow << std::endl; - // std::cout << "MeanPad: " << mTempCluster.meanPad << std::endl; - // std::cout << "MeanTime: " << mTempCluster.meanTime << std::endl; - // } const int corPadsMean = mMapperInstance.getNumberOfPadsInRowSector(int(mTempCluster.meanRow)); const int corPadsMaxCharge = mMapperInstance.getNumberOfPadsInRowSector(int(mTempCluster.maxChargeRow)); @@ -158,6 +171,9 @@ void KrBoxClusterFinder::updateTempCluster(float tempCharge, int tempPad, int te LOGP(warning, "Update cluster was called but current charge is below mQThreshold"); return; } + + // Some extrem ugly shaped clusters (mostly noise) might lead to an overflow. + // Hence, we have to define an upper limit here: if (mTempCluster.size < 255) { mTempCluster.size += 1; } @@ -178,12 +194,6 @@ void KrBoxClusterFinder::updateTempCluster(float tempCharge, int tempPad, int te mTempCluster.maxChargePad = tempPad; mTempCluster.maxChargeRow = tempRow; } - - // Set this digit to 0 - // std::cout << "Pad: " << tempPad << std::endl; - // std::cout << "Time: " << tempTime << std::endl; - // std::cout << "Row: " << tempRow << std::endl; - mMapOfAllDigits[tempTime][tempRow][tempPad] = 0; } // This function finds and evaluates all clusters in a 3D mMapOfAllDigits generated by the @@ -196,7 +206,20 @@ std::vector> KrBoxClusterFinder::findLocalMaxima(bool const auto& mapRow = mMapOfAllDigits[iTime]; for (int iRow = 0; iRow < MaxRows; iRow++) { // mapRow.size() // Since pad size is different for each ROC, we take this into account while looking for maxima: - setMaxClusterSize(iRow); + // setMaxClusterSize(iRow); + if (iRow == 0) { + mMaxClusterSizePad = mMaxClusterSizePadIROC; + mMaxClusterSizeRow = mMaxClusterSizeRowIROC; + } else if (iRow == MaxRowsIROC) { + mMaxClusterSizePad = mMaxClusterSizePadOROC1; + mMaxClusterSizeRow = mMaxClusterSizeRowOROC1; + } else if (iRow == MaxRowsIROC + MaxRowsOROC1) { + mMaxClusterSizePad = mMaxClusterSizePadOROC2; + mMaxClusterSizeRow = mMaxClusterSizeRowOROC2; + } else if (iRow == MaxRowsIROC + MaxRowsOROC1 + MaxRowsOROC2) { + mMaxClusterSizePad = mMaxClusterSizePadOROC3; + mMaxClusterSizeRow = mMaxClusterSizeRowOROC3; + } const auto& mapPad = mapRow[iRow]; const int padsInRow = mMapperInstance.getNumberOfPadsInRowSector(iRow); @@ -215,37 +238,37 @@ std::vector> KrBoxClusterFinder::findLocalMaxima(bool // with signal in any direction! int noNeighbours = 0; if ((iPad + 1 < MaxPads) && (mMapOfAllDigits[iTime][iRow][iPad + 1] > mQThreshold)) { - if(mMapOfAllDigits[iTime][iRow][iPad + 1] > qMax) { + if (mMapOfAllDigits[iTime][iRow][iPad + 1] > qMax) { continue; } noNeighbours++; } if ((iPad - 1 >= 0) && (mMapOfAllDigits[iTime][iRow][iPad - 1] > mQThreshold)) { - if(mMapOfAllDigits[iTime][iRow][iPad - 1] > qMax) { + if (mMapOfAllDigits[iTime][iRow][iPad - 1] > qMax) { continue; } noNeighbours++; } - if ((iTime + 1 < MaxTimes) && (mMapOfAllDigits[iTime + 1][iRow][iPad] > mQThreshold)) { - if(mMapOfAllDigits[iTime + 1][iRow][iPad] > qMax) { + if ((iRow + 1 < MaxRows) && (mMapOfAllDigits[iTime][iRow + 1][iPad] > mQThreshold)) { + if (mMapOfAllDigits[iTime][iRow + 1][iPad] > qMax) { continue; } noNeighbours++; } - if ((iTime - 1 >= 0) && (mMapOfAllDigits[iTime - 1][iRow][iPad] > mQThreshold)) { - if(mMapOfAllDigits[iTime - 1][iRow][iPad] > qMax) { + if ((iRow - 1 >= 0) && (mMapOfAllDigits[iTime][iRow - 1][iPad] > mQThreshold)) { + if (mMapOfAllDigits[iTime][iRow - 1][iPad] > qMax) { continue; } noNeighbours++; } - if ((iRow + 1 < MaxRows) && (mMapOfAllDigits[iTime][iRow + 1][iPad] > mQThreshold)) { - if(mMapOfAllDigits[iTime][iRow + 1][iPad] > qMax) { + if ((iTime + 1 < MaxTimes) && (mMapOfAllDigits[iTime + 1][iRow][iPad] > mQThreshold)) { + if (mMapOfAllDigits[iTime + 1][iRow][iPad] > qMax) { continue; } noNeighbours++; } - if ((iRow - 1 >= 0) && (mMapOfAllDigits[iTime][iRow - 1][iPad] > mQThreshold)) { - if(mMapOfAllDigits[iTime][iRow - 1][iPad] > qMax) { + if ((iTime - 1 >= 0) && (mMapOfAllDigits[iTime - 1][iRow][iPad] > mQThreshold)) { + if (mMapOfAllDigits[iTime - 1][iRow][iPad] > qMax) { continue; } noNeighbours++; @@ -261,192 +284,21 @@ std::vector> KrBoxClusterFinder::findLocalMaxima(bool // -> only the maximum with the smalest indices will be accepted bool thisIsMax = true; - - // Check diagonals in pad- and row-direction - if(iRow + 1 < MaxRows && iPad + 1 < MaxPads) { - if(mMapOfAllDigits[iTime][iRow + 1][iPad + 1] > qMax) { - continue; - } - } - if(iRow - 1 >= 0 && iPad + 1 < MaxPads) { - if(mMapOfAllDigits[iTime][iRow - 1][iPad + 1] > qMax) { - continue; - } - } - if(iRow + 1 < MaxRows && iPad - 1 >= 0) { - if(mMapOfAllDigits[iTime][iRow + 1][iPad - 1] > qMax) { - continue; - } - } - if(iRow - 1 >= 0 && iPad - 1 >= 0) { - if(mMapOfAllDigits[iTime][iRow - 1][iPad - 1] > qMax) { - continue; - } - } - - // Check diagonals in pad- and time-direction - if(iTime + 1 < MaxTimes && iPad + 1 < MaxPads) { - if(mMapOfAllDigits[iTime + 1][iRow][iPad + 1] > qMax) { - continue; - } - } - if(iTime - 1 >= 0 && iPad + 1 < MaxPads) { - if(mMapOfAllDigits[iTime - 1][iRow][iPad + 1] > qMax) { - continue; - } - } - if(iTime + 1 < MaxTimes && iPad - 1 >= 0) { - if(mMapOfAllDigits[iTime + 1][iRow][iPad - 1] > qMax) { - continue; - } - } - if(iTime - 1 >= 0 && iPad - 1 >= 0) { - if(mMapOfAllDigits[iTime - 1][iRow][iPad - 1] > qMax) { - continue; - } - } - - // Check diagonals in row- and time-direction - if(iTime + 1 < MaxTimes && iRow + 1 < MaxRows) { - if(mMapOfAllDigits[iTime + 1][iRow + 1][iPad] > qMax) { - continue; - } - } - if(iTime - 1 >= 0 && iRow + 1 < MaxRows) { - if(mMapOfAllDigits[iTime - 1][iRow + 1][iPad] > qMax) { - continue; - } - } - if(iTime + 1 < MaxTimes && iRow - 1 >= 0) { - if(mMapOfAllDigits[iTime + 1][iRow - 1][iPad] > qMax) { - continue; - } - } - if(iTime - 1 >= 0 && iRow - 1 >= 0) { - if(mMapOfAllDigits[iTime - 1][iRow - 1][iPad] > qMax) { - continue; - } - } - - // Check diagonals in row-, pad- and time-direction - if(iTime + 1 < MaxTimes && iRow + 1 < MaxRows && iPad + 1 < MaxPads) { - if(mMapOfAllDigits[iTime + 1][iRow + 1][iPad + 1] > qMax) { - continue; - } - } - if(iTime + 1 < MaxTimes && iRow + 1 < MaxRows && iPad - 1 >= 0) { - if(mMapOfAllDigits[iTime + 1][iRow + 1][iPad - 1] > qMax) { - continue; - } - } - if(iTime + 1 < MaxTimes && iRow - 1 >= 0 && iPad + 1 < MaxPads) { - if(mMapOfAllDigits[iTime + 1][iRow - 1][iPad + 1] > qMax) { - continue; - } - } - if(iTime + 1 < MaxTimes && iRow - 1 >= 0 && iPad - 1 >= 0) { - if(mMapOfAllDigits[iTime + 1][iRow - 1][iPad - 1] > qMax) { - continue; - } - } - if(iTime - 1 >= 0 && iRow + 1 < MaxRows && iPad + 1 < MaxPads) { - if(mMapOfAllDigits[iTime - 1][iRow + 1][iPad + 1] > qMax) { - continue; - } - } - if(iTime - 1 >= 0 && iRow + 1 < MaxRows && iPad - 1 >= 0) { - if(mMapOfAllDigits[iTime - 1][iRow + 1][iPad - 1] > qMax) { - continue; - } - } - if(iTime - 1 >= 0 && iRow - 1 >= 0 && iPad + 1 < MaxPads) { - if(mMapOfAllDigits[iTime - 1][iRow - 1][iPad + 1] > qMax) { - continue; - } - } - if(iTime - 1 >= 0 && iRow - 1 >= 0 && iPad - 1 >= 0) { - if(mMapOfAllDigits[iTime - 1][iRow - 1][iPad - 1] > qMax) { - continue; - } - } - - for (int i = 2; (i <= mMaxClusterSizePad) && thisIsMax; i++) { - if (iPad + i >= MaxPads) { + for (int j = -mMaxClusterSizeTime; (j <= mMaxClusterSizeTime) && thisIsMax; j++) { + if ((iTime + j >= MaxTimes) || (iTime + j < 0)) { continue; } - for (int k = 2; (k <= mMaxClusterSizeRow) && thisIsMax; k++) { - if (iRow + k >= MaxRows) { + for (int k = -mMaxClusterSizeRow; (k <= mMaxClusterSizeRow) && thisIsMax; k++) { + if ((iRow + k >= MaxRows) || (iRow + k < 0)) { continue; } - for (int j = 2; (j <= mMaxClusterSizeTime) && thisIsMax; j++) { - if (iTime + j >= MaxTimes) { + for (int i = -mMaxClusterSizePad; (i <= mMaxClusterSizePad) && thisIsMax; i++) { + if ((iPad + i >= MaxPads) || (iPad + i < 0)) { continue; } if (mMapOfAllDigits[iTime + j][iRow + k][iPad + i] > qMax) { thisIsMax = false; } - if (iTime - j < 0) { - continue; - } - if (mMapOfAllDigits[iTime - j][iRow + k][iPad + i] > qMax) { - thisIsMax = false; - } - } - if (iRow - k < 0) { - continue; - } - for (int j = 2; (j <= mMaxClusterSizeTime) && thisIsMax; j++) { - if (iTime + j >= MaxTimes) { - continue; - } - if (mMapOfAllDigits[iTime + j][iRow - k][iPad + i] > qMax) { - thisIsMax = false; - } - if (iTime - j < 0) { - continue; - } - if (mMapOfAllDigits[iTime - j][iRow - k][iPad + i] > qMax) { - thisIsMax = false; - } - } - } - if (iPad - i < 0) { - continue; - } - for (int k = 2; (k <= mMaxClusterSizeRow) && thisIsMax; k++) { - if (iRow + k >= MaxRows) { - continue; - } - for (int j = 2; (j <= mMaxClusterSizeTime) && thisIsMax; j++) { - if (iTime + j >= MaxTimes) { - continue; - } - if (mMapOfAllDigits[iTime + j][iRow + k][iPad - i] > qMax) { - thisIsMax = false; - } - if (iTime - j < 0) { - continue; - } - if (mMapOfAllDigits[iTime - j][iRow + k][iPad - i] > qMax) { - thisIsMax = false; - } - } - if (iRow - k < 0) { - continue; - } - for (int j = 2; (j <= mMaxClusterSizeTime) && thisIsMax; j++) { - if (iTime + j >= MaxTimes) { - continue; - } - if (mMapOfAllDigits[iTime + j][iRow - k][iPad - i] > qMax) { - thisIsMax = false; - } - if (iTime - j < 0) { - continue; - } - if (mMapOfAllDigits[iTime - j][iRow - k][iPad - i] > qMax) { - thisIsMax = false; - } } } } @@ -459,6 +311,9 @@ std::vector> KrBoxClusterFinder::findLocalMaxima(bool } else { localMaximaCoords.emplace_back(std::make_tuple(iPad, iRow, iTime)); } + + // If we have found a local maximum, we can also skip the next few entries: + iPad += mMaxClusterSizePad; } } } @@ -539,7 +394,6 @@ KrCluster KrBoxClusterFinder::buildCluster(int clusterCenterPad, int clusterCent if (mMapOfAllDigits[clusterCenterTime + iTime][clusterCenterRow + iRow][clusterCenterPad + iPad] <= mQThreshold) { continue; } - // If not, there are several cases which were explained (for 2D) in the header of the code. // The first one is for the diagonal. So, the digit we are investigating here is on the diagonal: if (std::abs(iTime) == std::abs(iPad) && std::abs(iTime) == std::abs(iRow)) { diff --git a/Detectors/TPC/reconstruction/src/KrBoxClusterFinderParam.cxx b/Detectors/TPC/reconstruction/src/KrBoxClusterFinderParam.cxx new file mode 100644 index 0000000000000..57e5c0633ad87 --- /dev/null +++ b/Detectors/TPC/reconstruction/src/KrBoxClusterFinderParam.cxx @@ -0,0 +1,18 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file KrBoxClusterFinderParam.cxx +/// \brief Parameter class for the Kr box cluster finder +/// +/// \author Philip Hauer, hauer@hiskp.uni-bonn.de + +#include "TPCReconstruction/KrBoxClusterFinderParam.h" + +O2ParamImpl(o2::tpc::KrBoxClusterFinderParam); \ No newline at end of file diff --git a/Detectors/TPC/reconstruction/src/TPCReconstructionLinkDef.h b/Detectors/TPC/reconstruction/src/TPCReconstructionLinkDef.h index 03a3545bcf76b..7b474199c7898 100644 --- a/Detectors/TPC/reconstruction/src/TPCReconstructionLinkDef.h +++ b/Detectors/TPC/reconstruction/src/TPCReconstructionLinkDef.h @@ -35,6 +35,8 @@ #pragma link C++ class o2::tpc::HwClusterer + ; #pragma link C++ class o2::tpc::HwClustererParam + ; #pragma link C++ class o2::conf::ConfigurableParamHelper < o2::tpc::HwClustererParam > +; +#pragma link C++ class o2::tpc::KrBoxClusterFinderParam + ; +#pragma link C++ class o2::conf::ConfigurableParamHelper < o2::tpc::KrBoxClusterFinderParam > +; #pragma link C++ class o2::tpc::TPCFastTransformHelperO2 + ; From bfe4a62adb5486fe89f0c6a45c97e20d56080772 Mon Sep 17 00:00:00 2001 From: rpezzi Date: Mon, 3 May 2021 20:13:31 +0200 Subject: [PATCH 365/770] Update MFT codeowners Add @rpezzi to /Detectors/ITSMFT and /DataFormats/Detectors/ITSMFT --- CODEOWNERS | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CODEOWNERS b/CODEOWNERS index 927cbf9896cf0..429fcb52f0328 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -36,7 +36,7 @@ /DataFormats/Detectors/GlobalTracking @shahor02 /DataFormats/Detectors/GlobalTrackingWorkflow @shahor02 /DataFormats/Detectors/HMPID @gvolpe79 -/DataFormats/Detectors/ITSMFT @iouribelikov @bovulpes +/DataFormats/Detectors/ITSMFT @iouribelikov @bovulpes @rpezzi /DataFormats/Detectors/MUON @aphecetche /DataFormats/Detectors/PHOS @peressounko @kharlov /DataFormats/Detectors/Passive @sawenzel @@ -65,7 +65,7 @@ /Detectors/GlobalTracking @shahor02 /Detectors/GlobalTrackingWorkflow @shahor02 /Detectors/HMPID @gvolpe79 -/Detectors/ITSMFT @iouribelikov @bovulpes +/Detectors/ITSMFT @iouribelikov @bovulpes @rpezzi /Detectors/MUON @aphecetche /Detectors/PHOS @peressounko @kharlov /Detectors/Passive @sawenzel From 5cade799646692573ca1054885361609d1765a1d Mon Sep 17 00:00:00 2001 From: wiechula Date: Mon, 19 Apr 2021 13:56:05 +0200 Subject: [PATCH 366/770] Decoder for integrated digital currents --- DataFormats/Detectors/TPC/CMakeLists.txt | 1 + .../TPC/include/DataFormatsTPC/IDC.h | 119 ++++++++++++++++++ 2 files changed, 120 insertions(+) create mode 100644 DataFormats/Detectors/TPC/include/DataFormatsTPC/IDC.h diff --git a/DataFormats/Detectors/TPC/CMakeLists.txt b/DataFormats/Detectors/TPC/CMakeLists.txt index 698e212afb1f4..d8c38272fc1f0 100644 --- a/DataFormats/Detectors/TPC/CMakeLists.txt +++ b/DataFormats/Detectors/TPC/CMakeLists.txt @@ -46,6 +46,7 @@ o2_target_root_dictionary( include/DataFormatsTPC/dEdxInfo.h include/DataFormatsTPC/CompressedClusters.h include/DataFormatsTPC/CTF.h + include/DataFormatsTPC/IDC.h include/DataFormatsTPC/ZeroSuppression.h include/DataFormatsTPC/ZeroSuppressionLinkBased.h) diff --git a/DataFormats/Detectors/TPC/include/DataFormatsTPC/IDC.h b/DataFormats/Detectors/TPC/include/DataFormatsTPC/IDC.h new file mode 100644 index 0000000000000..ab405ff470ced --- /dev/null +++ b/DataFormats/Detectors/TPC/include/DataFormatsTPC/IDC.h @@ -0,0 +1,119 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file IDC.h +/// \brief Integrated digital currents data format definition +/// @author Jens Wiechula, Jens.Wiechula@ikf.uni-frankfurt.de +/// The data is sent by the CRU as 256bit words. The IDC data layout is as follows: +/// Header [ 256 bits ] +/// Channel-00 [L9][L8][L7][L6][L5][L4][L3][L2][L1][L0] +/// ... +/// Channel-79 [L9][L8][L7][L6][L5][L4][L3][L2][L1][L0] +/// +/// Where [Lx] is a 25bit value for Channel yy link x + +#ifndef ALICEO2_DATAFORMATSTPC_IDC_H +#define ALICEO2_DATAFORMATSTPC_IDC_H + +#include + +namespace o2::tpc::idc +{ +static constexpr uint32_t Links = 10; ///< maximum number of links +static constexpr uint32_t Channels = 80; ///< number of channels +static constexpr uint32_t DataWordSizeBits = 256; ///< size of header word and data words in bits +static constexpr uint32_t DataWordSizeBytes = DataWordSizeBits / 8; ///< size of header word and data words in bytes +static constexpr uint32_t IDCvalueBits = 25; ///< number of bits used for one IDC value +static constexpr uint32_t IDCvalueBitsMask = (uint32_t(1) << IDCvalueBits) - 1; ///< bitmask for 25 bit word + +/// header definition of the IDCs +/// The header is a 256 bit word +struct Header { + static constexpr uint32_t MagicWord = 0xDC; + union { + uint64_t word0 = 0; ///< bits 0 - 63 + struct { /// + uint32_t version : 8; ///< lower bits of the 80 bit bitmask + uint32_t packetID : 8; ///< packet id + uint32_t errorCode : 8; ///< errors + uint32_t magicWord : 8; ///< magic word + uint32_t heartbeatOrbit : 32; ///< heart beat orbit of the IDC value + }; /// + }; /// + /// + union { /// + uint64_t word1 = 0; ///< bits 64 - 127 + struct { /// + uint32_t heartbeatBC : 16; ///< BC id of IDC value + uint32_t integrationTime : 16; ///< integration time used for the IDCs + uint32_t linkMask : 16; ///< mask of active links + uint32_t unused1 : 16; /// + }; /// + }; /// + /// + union { /// + uint64_t word2 = 0; ///< bits 128 - 191 + struct { /// + uint64_t unused2 : 64; ///< lower bits of the 80 bit bitmask + }; /// + }; /// + /// + union { /// + uint64_t word3 = 0; ///< bits 192 - 255 + struct { /// + uint64_t unused3 : 64; ///< lower bits of the 80 bit bitmask + }; /// + }; /// + /// +}; + +/// IDC single channel data container +/// TODO: verify that pointer arithmetics does not run into alignment issues +/// might require different logic +struct Data { + uint8_t dataWords[DataWordSizeBytes] = {0}; ///< 25bit ADC values + + uint32_t getLinkValue(const uint32_t link) const + { + const auto valPtr = dataWords; + const uint32_t offset = link * IDCvalueBits; + const uint32_t selectedWord = offset / 8; + const uint32_t requiredShift = offset % 8; + const uint32_t value = (*(uint32_t*)(dataWords + selectedWord)) >> requiredShift; + return value & IDCvalueBitsMask; + } + + void setLinkValue(const uint32_t link, const uint32_t value) + { + const uint32_t offset = link * IDCvalueBits; + const uint32_t selectedWord = offset / 8; + const uint32_t requiredShift = offset % 8; + auto dataWrite = (uint64_t*)&dataWords[selectedWord]; + *dataWrite = (value & IDCvalueBitsMask) << requiredShift; + } +}; + +/// IDC full data container +struct Container { + Header header; ///< IDC data header + Data channelData[Channels]; ///< data values for all channels in each link + + uint32_t getChannelValue(const uint32_t link, const uint32_t channel) const + { + return channelData[channel].getLinkValue(link); + } + + void setChannelValue(const uint32_t link, const uint32_t channel, uint32_t value) + { + channelData[channel].setLinkValue(link, value); + } +}; +} // namespace o2::tpc::idc +#endif From afc90de318a2ed7fe35223a8984ec0de12df0156 Mon Sep 17 00:00:00 2001 From: wiechula Date: Mon, 3 May 2021 10:55:49 +0200 Subject: [PATCH 367/770] add possibility to draw sector boundaried --- Detectors/TPC/base/include/TPCBase/Painter.h | 3 + Detectors/TPC/base/src/Painter.cxx | 107 +++++++++++++++++++ 2 files changed, 110 insertions(+) diff --git a/Detectors/TPC/base/include/TPCBase/Painter.h b/Detectors/TPC/base/include/TPCBase/Painter.h index 510f37b011b8f..b4b458c27229d 100644 --- a/Detectors/TPC/base/include/TPCBase/Painter.h +++ b/Detectors/TPC/base/include/TPCBase/Painter.h @@ -149,6 +149,9 @@ std::vector makeSummaryCanvases(const CalDet& calDet, int nbins1D = /// \return TCanvas containing CalDet content std::vector makeSummaryCanvases(const std::string_view fileName, const std::string_view calPadNames, int nbins1D = 300, float xMin1D = 0, float xMax1D = 0, bool onlyFilled = true); +/// draw sector boundaris, side name and sector numbers +void drawSectorsXY(Side side, int sectorLineColor = 920, int sectorTextColor = 1); + } // namespace painter } // namespace tpc diff --git a/Detectors/TPC/base/src/Painter.cxx b/Detectors/TPC/base/src/Painter.cxx index 3d6be713fa17d..f79ab4704fe50 100644 --- a/Detectors/TPC/base/src/Painter.cxx +++ b/Detectors/TPC/base/src/Painter.cxx @@ -11,6 +11,7 @@ #include #include #include +#include #include "TString.h" #include "TAxis.h" @@ -18,7 +19,10 @@ #include "TH2.h" #include "TH2Poly.h" #include "TCanvas.h" +#include "TLine.h" +#include "TLatex.h" +#include "DataFormatsTPC/Defs.h" #include "TPCBase/ROC.h" #include "TPCBase/Sector.h" #include "TPCBase/Mapper.h" @@ -138,9 +142,13 @@ TCanvas* painter::draw(const CalDet& calDet, int nbins1D, float xMin1D, float c->cd(1); hAside2D->Draw("colz"); + hAside2D->SetStats(0); + drawSectorsXY(Side::A); c->cd(2); hCside2D->Draw("colz"); + hCside2D->SetStats(0); + drawSectorsXY(Side::C); c->cd(3); hAside1D->Draw(); @@ -438,6 +446,105 @@ void painter::fillPoly2D(TH2Poly& h2D, const CalDet& calDet, Side side) } } +//______________________________________________________________________________ +void painter::drawSectorsXY(Side side, int sectorLineColor, int sectorTextColor) +{ + TLine l; + l.SetLineColor(sectorLineColor); + + TLine l2; + l2.SetLineColor(sectorLineColor); + l2.SetLineStyle(kDotted); + + TLatex latSide; + latSide.SetTextColor(sectorTextColor); + latSide.SetTextAlign(22); + latSide.SetTextSize(0.08); + latSide.DrawLatex(0, 0, (side == Side::C) ? "C" : "A"); + + TLatex lat; + lat.SetTextAlign(22); + lat.SetTextSize(0.03); + lat.SetTextColor(sectorLineColor); + + constexpr float phiWidth = float(SECPHIWIDTH); + const float rFactor = std::cos(phiWidth / 2.); + const float rLow = 83.65 / rFactor; + const float rIROCup = 133.3 / rFactor; + const float rOROClow = 133.5 / rFactor; + const float rOROC12 = 169.75 / rFactor; + const float rOROC23 = 207.85 / rFactor; + const float rOut = 247.7 / rFactor; + const float rText = rLow * rFactor * 3. / 4.; + + for (Int_t isector = 0; isector < 18; ++isector) { + const float sinR = std::sin(phiWidth * isector); + const float cosR = std::cos(phiWidth * isector); + + const float sinL = std::sin(phiWidth * ((isector + 1) % 18)); + const float cosL = std::cos(phiWidth * ((isector + 1) % 18)); + + const float sinText = std::sin(phiWidth * (isector + 0.5)); + const float cosText = std::cos(phiWidth * (isector + 0.5)); + + const float xR1 = rLow * cosR; + const float yR1 = rLow * sinR; + const float xR2 = rOut * cosR; + const float yR2 = rOut * sinR; + + const float xL1 = rLow * cosL; + const float yL1 = rLow * sinL; + const float xL2 = rOut * cosL; + const float yL2 = rOut * sinL; + + const float xOROCmup1 = rOROClow * cosR; + const float yOROCmup1 = rOROClow * sinR; + const float xOROCmup2 = rOROClow * cosL; + const float yOROCmup2 = rOROClow * sinL; + + const float xIROCmup1 = rIROCup * cosR; + const float yIROCmup1 = rIROCup * sinR; + const float xIROCmup2 = rIROCup * cosL; + const float yIROCmup2 = rIROCup * sinL; + + const float xO121 = rOROC12 * cosR; + const float yO121 = rOROC12 * sinR; + const float xO122 = rOROC12 * cosL; + const float yO122 = rOROC12 * sinL; + + const float xO231 = rOROC23 * cosR; + const float yO231 = rOROC23 * sinR; + const float xO232 = rOROC23 * cosL; + const float yO232 = rOROC23 * sinL; + + const float xText = rText * cosText; + const float yText = rText * sinText; + + // left side line + l.DrawLine(xR1, yR1, xR2, yR2); + + // IROC inner line + l.DrawLine(xR1, yR1, xL1, yL1); + + // IROC end line + l.DrawLine(xIROCmup1, yIROCmup1, xIROCmup2, yIROCmup2); + + // OROC start line + l.DrawLine(xOROCmup1, yOROCmup1, xOROCmup2, yOROCmup2); + + // OROC1 - OROC2 line + l.DrawLine(xO121, yO121, xO122, yO122); + + // OROC2 - OROC3 line + l.DrawLine(xO231, yO231, xO232, yO232); + + // IROC inner line + l.DrawLine(xR2, yR2, xL2, yL2); + + // sector numbers + lat.DrawLatex(xText, yText, fmt::format("{}", isector).data()); + } +} // ===| explicit instantiations |=============================================== // this is required to force the compiler to create instances with the types // we usually would like to deal with From d6d47e564e2f3ab3676b7bc69e088ac2c572db20 Mon Sep 17 00:00:00 2001 From: wiechula Date: Mon, 3 May 2021 10:56:56 +0200 Subject: [PATCH 368/770] add missing class --- Detectors/TPC/base/src/TPCBaseLinkDef.h | 1 + 1 file changed, 1 insertion(+) diff --git a/Detectors/TPC/base/src/TPCBaseLinkDef.h b/Detectors/TPC/base/src/TPCBaseLinkDef.h index f63c1fada7ee9..b491ccc535606 100644 --- a/Detectors/TPC/base/src/TPCBaseLinkDef.h +++ b/Detectors/TPC/base/src/TPCBaseLinkDef.h @@ -30,6 +30,7 @@ #pragma link C++ class std::vector < o2::tpc::CalDet < float>*> + ; #pragma link C++ class std::unordered_map < std::string, o2::tpc::CalDet < float>> + ; #pragma link C++ class o2::tpc::CDBInterface; +#pragma link C++ class o2::tpc::CDBStorage; #pragma link C++ class o2::tpc::ContainerFactory; #pragma link C++ class o2::tpc::CRU; #pragma link C++ class o2::tpc::DigitPos; From 0593e46014fa8073c291fd638b0355cbcdb3431f Mon Sep 17 00:00:00 2001 From: wiechula Date: Mon, 3 May 2021 10:58:57 +0200 Subject: [PATCH 369/770] fix setting of branch address --- .../TPC/calibration/include/TPCCalibration/CalibRawBase.h | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Detectors/TPC/calibration/include/TPCCalibration/CalibRawBase.h b/Detectors/TPC/calibration/include/TPCCalibration/CalibRawBase.h index 231fc300154da..6428e2bef93d5 100644 --- a/Detectors/TPC/calibration/include/TPCCalibration/CalibRawBase.h +++ b/Detectors/TPC/calibration/include/TPCCalibration/CalibRawBase.h @@ -506,16 +506,14 @@ inline CalibRawBase::ProcessStatus CalibRawBase::processEventDigitTree(int event mPresentEventNumber = numberOfEvents - 1; } } - LOG(INFO) << "Processing event number " << eventNumber << " (" << mNevents << ")"; + LOG(INFO) << "Processing event number " << mPresentEventNumber << " (" << mNevents << ")"; // set up branches - static bool initialized = false; static std::array*, Sector::MAXSECTOR> digits{}; - if (!initialized) { + if (!mDigitTree->GetBranch("TPCDigit_0")->GetAddress()) { for (int iSec = 0; iSec < Sector::MAXSECTOR; ++iSec) { mDigitTree->SetBranchAddress(Form("TPCDigit_%d", iSec), &digits[iSec]); } - initialized = true; } // loop over digits for selected event From 4ecbd073123c30e30ed7377066fe08ec9b341368 Mon Sep 17 00:00:00 2001 From: Ole Schmidt Date: Wed, 28 Apr 2021 16:08:57 +0200 Subject: [PATCH 370/770] TRD tracking adapt to ioPtr usage for GPU proc. - tracklets are already sorted by HCID - tracklets don't need to be loaded individually anymore - GPUTRDSpacePoint is the same as CalibratedTracklet (not an alias for compatibility with AliRoot, but in principle the same) - always use tracklet transformer to calculate TRD space points (but can still be forced off in the GPUTRDTracker) - fix AliRoot HLT reconstruction and O2 macro for steering the tracking without DPL --- .../DataFormatsTRD/CalibratedTracklet.h | 37 +-- Detectors/TRD/reconstruction/CMakeLists.txt | 2 + .../TRDReconstruction/RecoInputContainer.h | 92 +++++++ .../TRDWorkflow/TRDGlobalTrackingSpec.h | 9 +- .../include/TRDWorkflow/TRDTrackingWorkflow.h | 2 +- .../workflow/src/TRDGlobalTrackingSpec.cxx | 115 ++------ .../TRD/workflow/src/TRDTrackingWorkflow.cxx | 8 +- .../workflow/src/trd-tracking-workflow.cxx | 4 +- GPU/GPUTracking/CMakeLists.txt | 1 + GPU/GPUTracking/DataTypes/GPUDataTypes.h | 10 +- GPU/GPUTracking/Definitions/GPUSettingsList.h | 1 - .../Global/AliHLTGPUDumpComponent.cxx | 2 - GPU/GPUTracking/Global/GPUChainTracking.cxx | 4 +- GPU/GPUTracking/Global/GPUChainTracking.h | 4 +- GPU/GPUTracking/Global/GPUChainTrackingIO.cxx | 2 - .../Global/GPUChainTrackingTRD.cxx | 5 - .../TRDTracking/GPUTRDSpacePoint.h | 71 +++++ GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx | 256 ++++++++---------- GPU/GPUTracking/TRDTracking/GPUTRDTracker.h | 49 +--- .../TRDTracking/GPUTRDTrackerComponent.cxx | 69 ++--- .../TRDTracking/GPUTRDTrackerDebug.h | 16 +- .../TRDTracking/GPUTRDTrackletWord.h | 6 + .../TRDTracking/macros/run_trd_tracker.C | 72 ++--- GPU/GPUTracking/display/GPUDisplay.cxx | 6 +- 24 files changed, 438 insertions(+), 405 deletions(-) create mode 100644 Detectors/TRD/reconstruction/include/TRDReconstruction/RecoInputContainer.h create mode 100644 GPU/GPUTracking/TRDTracking/GPUTRDSpacePoint.h diff --git a/DataFormats/Detectors/TRD/include/DataFormatsTRD/CalibratedTracklet.h b/DataFormats/Detectors/TRD/include/DataFormatsTRD/CalibratedTracklet.h index f4d58849af873..ce761e885b9a0 100644 --- a/DataFormats/Detectors/TRD/include/DataFormatsTRD/CalibratedTracklet.h +++ b/DataFormats/Detectors/TRD/include/DataFormatsTRD/CalibratedTracklet.h @@ -11,6 +11,9 @@ #ifndef O2_TRD_CALIBRATEDTRACKLET_H #define O2_TRD_CALIBRATEDTRACKLET_H +#include "GPUCommonDef.h" +#include "GPUCommonRtypes.h" + namespace o2 { namespace trd @@ -22,26 +25,28 @@ namespace trd class CalibratedTracklet { public: - CalibratedTracklet() = default; - CalibratedTracklet(float x, float y, float z, float dy) - : mx(x), my(y), mz(z), mdy(dy){}; - ~CalibratedTracklet() = default; + GPUdDefault() CalibratedTracklet() = default; + GPUd() CalibratedTracklet(float x, float y, float z, float dy) + : mX(x), mY(y), mZ(z), mDy(dy){}; + GPUdDefault() ~CalibratedTracklet() = default; - float getX() const { return mx; } - float getY() const { return my; } - float getZ() const { return mz; } - float getDy() const { return mdy; } + GPUd() float getX() const { return mX; } + GPUd() float getY() const { return mY; } + GPUd() float getZ() const { return mZ; } + GPUd() float getDy() const { return mDy; } - void setX(float x) { mx = x; } - void setY(float y) { my = y; } - void setZ(float z) { mz = z; } - void setDy(float dy) { mdy = dy; } + GPUd() void setX(float x) { mX = x; } + GPUd() void setY(float y) { mY = y; } + GPUd() void setZ(float z) { mZ = z; } + GPUd() void setDy(float dy) { mDy = dy; } private: - float mx; - float my; - float mz; - float mdy; + float mX; + float mY; + float mZ; + float mDy; + + ClassDefNV(CalibratedTracklet, 1); }; } // namespace trd diff --git a/Detectors/TRD/reconstruction/CMakeLists.txt b/Detectors/TRD/reconstruction/CMakeLists.txt index eb665d63af9b1..9b76aafe2f9a2 100644 --- a/Detectors/TRD/reconstruction/CMakeLists.txt +++ b/Detectors/TRD/reconstruction/CMakeLists.txt @@ -13,6 +13,8 @@ o2_add_library(TRDReconstruction src/CTFHelper.cxx PUBLIC_LINK_LIBRARIES O2::TRDBase O2::DataFormatsTRD + O2::DataFormatsTPC + O2::ReconstructionDataFormats O2::DetectorsRaw O2::rANS ms_gsl::ms_gsl) diff --git a/Detectors/TRD/reconstruction/include/TRDReconstruction/RecoInputContainer.h b/Detectors/TRD/reconstruction/include/TRDReconstruction/RecoInputContainer.h new file mode 100644 index 0000000000000..ea28c15918bfa --- /dev/null +++ b/Detectors/TRD/reconstruction/include/TRDReconstruction/RecoInputContainer.h @@ -0,0 +1,92 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file RecoInputContainer.h +/// \author ole.schmidt@cern.ch +/// \brief Struct for input data required by TRD tracking workflow + +#ifndef O2_TRD_RECOINPUTCONTAINER_H +#define O2_TRD_RECOINPUTCONTAINER_H + +#include "ReconstructionDataFormats/TrackTPCITS.h" +#include "DataFormatsTPC/TrackTPC.h" +#include "DataFormatsTRD/Tracklet64.h" +#include "DataFormatsTRD/CalibratedTracklet.h" +#include "DataFormatsTRD/TriggerRecord.h" +#include "DataFormatsGlobalTracking/RecoContainer.h" +#include "CommonConstants/LHCConstants.h" + +#include "GPUDataTypes.h" + +#include +#include + +namespace o2 +{ +namespace trd +{ + +struct RecoInputContainer { + + gsl::span mTracksTPCITS; + gsl::span mTracksTPC; + gsl::span mTracklets; + gsl::span mSpacePoints; + gsl::span mTriggerRecords; + unsigned int mNTracksTPCITS; + unsigned int mNTracksTPC; + unsigned int mNTracklets; + unsigned int mNSpacePoints; + unsigned int mNTriggerRecords; + std::vector trdTriggerTimes; + std::vector trdTriggerIndices; +}; + +inline auto getRecoInputContainer(o2::framework::ProcessingContext& pc, o2::gpu::GPUTrackingInOutPointers& ptrs, const o2::globaltracking::RecoContainer* inputTracks) +{ + auto retVal = std::make_unique(); + retVal->mTracksTPCITS = inputTracks->getTPCITSTracks(); + retVal->mTracksTPC = inputTracks->getTPCTracks(); + retVal->mTracklets = pc.inputs().get>("trdtracklets"); + retVal->mSpacePoints = pc.inputs().get>("trdctracklets"); + retVal->mTriggerRecords = pc.inputs().get>("trdtriggerrec"); + + retVal->mNTracksTPCITS = retVal->mTracksTPCITS.size(); + retVal->mNTracksTPC = retVal->mTracksTPC.size(); + retVal->mNTracklets = retVal->mTracklets.size(); + retVal->mNSpacePoints = retVal->mSpacePoints.size(); + retVal->mNTriggerRecords = retVal->mTriggerRecords.size(); + + for (unsigned int iEv = 0; iEv < retVal->mNTriggerRecords; ++iEv) { + const auto& trg = retVal->mTriggerRecords[iEv]; + retVal->trdTriggerIndices.push_back(trg.getFirstTracklet()); + int64_t evTime = trg.getBCData().toLong() * o2::constants::lhc::LHCBunchSpacingNS; // event time in ns + retVal->trdTriggerTimes.push_back(evTime / 1000.); // event time in us + } + + // the number of tracks loaded into the TRD tracker depends on the defined input sources + // TPC-only tracks which are already matched to the ITS will not be loaded as seeds for the tracking + // => the maximum number of seeds it the number of TPC-only tracks. If only ITS-TPC matches are considered than that + // of course defines the number of input tracks + ptrs.nMergedTracks = (retVal->mNTracksTPC == 0) ? retVal->mNTracksTPCITS : retVal->mNTracksTPC; + ptrs.nTRDTriggerRecords = retVal->mNTriggerRecords; + ptrs.trdTriggerTimes = &(retVal->trdTriggerTimes[0]); + ptrs.trdTrackletIdxFirst = &(retVal->trdTriggerIndices[0]); + ptrs.nTRDTracklets = retVal->mNTracklets; + ptrs.trdTracklets = reinterpret_cast(retVal->mTracklets.data()); + ptrs.trdSpacePoints = reinterpret_cast(retVal->mSpacePoints.data()); + + return std::move(retVal); +} + +} // namespace trd +} // namespace o2 + +#endif diff --git a/Detectors/TRD/workflow/include/TRDWorkflow/TRDGlobalTrackingSpec.h b/Detectors/TRD/workflow/include/TRDWorkflow/TRDGlobalTrackingSpec.h index 29fdc6ad76821..0855053d0e2ee 100644 --- a/Detectors/TRD/workflow/include/TRDWorkflow/TRDGlobalTrackingSpec.h +++ b/Detectors/TRD/workflow/include/TRDWorkflow/TRDGlobalTrackingSpec.h @@ -20,6 +20,9 @@ #include "TRDCalibration/CalibVDrift.h" #include "GPUO2Interface.h" #include "GPUTRDTracker.h" +#include "ReconstructionDataFormats/GlobalTrackID.h" +#include "DataFormatsGlobalTracking/RecoContainer.h" +#include namespace o2 { @@ -29,7 +32,7 @@ namespace trd class TRDGlobalTracking : public o2::framework::Task { public: - TRDGlobalTracking(bool useMC, bool useTrkltTransf) : mUseMC(useMC), mUseTrackletTransform(useTrkltTransf) {} + TRDGlobalTracking(bool useMC, std::shared_ptr dataRequest) : mUseMC(useMC), mDataRequest(dataRequest) {} ~TRDGlobalTracking() override = default; void init(o2::framework::InitContext& ic) final; void updateTimeDependentParams(); @@ -42,15 +45,15 @@ class TRDGlobalTracking : public o2::framework::Task o2::gpu::GPUChainTracking* mChainTracking{nullptr}; ///< TRD tracker is run in the tracking chain std::unique_ptr mFlatGeo{nullptr}; ///< flat TRD geometry bool mUseMC{false}; ///< MC flag - bool mUseTrackletTransform{false}; ///< if true, output from TrackletTransformer is used instead of uncalibrated Tracklet64 directly float mTPCTBinMUS{.2f}; ///< width of a TPC time bin in us float mTPCVdrift{2.58f}; ///< TPC drift velocity (for shifting TPC tracks along Z) CalibVDrift mCalibVDrift{}; ///< steers the vDrift calibration + std::shared_ptr mDataRequest; ///< seeding input (TPC-only, ITS-TPC or both) TStopwatch mTimer; }; /// create a processor spec -framework::DataProcessorSpec getTRDGlobalTrackingSpec(bool useMC, bool useTrkltTransf, o2::dataformats::GlobalTrackID::mask_t src); +framework::DataProcessorSpec getTRDGlobalTrackingSpec(bool useMC, o2::dataformats::GlobalTrackID::mask_t src); } // namespace trd } // namespace o2 diff --git a/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackingWorkflow.h b/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackingWorkflow.h index 3856a7370220c..6f22715fde603 100644 --- a/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackingWorkflow.h +++ b/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackingWorkflow.h @@ -21,7 +21,7 @@ namespace o2 namespace trd { -framework::WorkflowSpec getTRDTrackingWorkflow(bool disableRootInp, bool disableRootOut, bool useTrackletTransformer, o2::dataformats::GlobalTrackID::mask_t srcTRD); +framework::WorkflowSpec getTRDTrackingWorkflow(bool disableRootInp, bool disableRootOut, o2::dataformats::GlobalTrackID::mask_t srcTRD); } // namespace trd } // namespace o2 diff --git a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx index a5230ccdfb288..fa23fc830889d 100644 --- a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx @@ -11,11 +11,8 @@ /// @file TRDGlobalTrackingSpec.cxx #include "TRDWorkflow/TRDGlobalTrackingSpec.h" - #include "TRDBase/Geometry.h" - #include "DetectorsCommonDataFormats/NameConf.h" -#include "CommonConstants/LHCConstants.h" #include "DetectorsBase/GeometryManager.h" #include "DetectorsBase/Propagator.h" #include "ReconstructionDataFormats/TrackTPCITS.h" @@ -25,7 +22,7 @@ #include "DataFormatsTRD/Constants.h" #include "TPCBase/ParameterElectronics.h" #include "TPCBase/ParameterGas.h" -#include "DataFormatsGlobalTracking/RecoContainer.h" +#include "TRDReconstruction/RecoInputContainer.h" // GPU header #include "GPUReconstruction.h" @@ -40,6 +37,7 @@ using namespace o2::framework; using namespace o2::gpu; +using namespace o2::globaltracking; using GTrackID = o2::dataformats::GlobalTrackID; @@ -48,8 +46,6 @@ namespace o2 namespace trd { -o2::globaltracking::DataRequest dataRequestTRD; - void TRDGlobalTracking::init(InitContext& ic) { @@ -73,9 +69,8 @@ void TRDGlobalTracking::init(InitContext& ic) mTracker = new GPUTRDTracker(); mTracker->SetNCandidates(mRec->GetProcessingSettings().trdNCandidates); // must be set before initialization - mTracker->SetProcessPerTimeFrame(); - mTracker->SetNMaxCollisions(mRec->GetProcessingSettings().trdNMaxCollisions); - mTracker->SetTrkltTransformNeeded(!mUseTrackletTransform); + mTracker->SetProcessPerTimeFrame(true); + mTracker->SetGenerateSpacePoints(false); // set to true to force space point calculation by the TRD tracker itself //mTracker->SetDoImpactAngleHistograms(true); mRec->RegisterGPUProcessor(mTracker, false); @@ -105,72 +100,27 @@ void TRDGlobalTracking::run(ProcessingContext& pc) { mTimer.Start(false); o2::globaltracking::RecoContainer inputTracks; - inputTracks.collectData(pc, dataRequestTRD); - const auto tracksITSTPC = inputTracks.getTPCITSTracks(); - const auto tracksTPC = inputTracks.getTPCTracks(); - const auto trackletsTRD = pc.inputs().get>("trdtracklets"); - const auto triggerRecords = pc.inputs().get>("trdtriggerrec"); - - int nTracksITSTPC = tracksITSTPC.size(); - int nTracksTPC = tracksTPC.size(); - int nCollisions = triggerRecords.size(); - int nTracklets = trackletsTRD.size(); - LOGF(INFO, "There are %i tracklets in total from %i trigger records", nTracklets, nCollisions); - LOGF(INFO, "As input seeds are available: %i ITS-TPC matched tracks and %i TPC tracks", nTracksITSTPC, nTracksTPC); - - const gsl::span* cTrkltsPtr = nullptr; - using cTrkltType = std::decay_t>(""))>; - std::optional cTrklts; - int nTrackletsCal = 0; - - if (mUseTrackletTransform) { - cTrklts.emplace(pc.inputs().get>("trdctracklets")); - cTrkltsPtr = &cTrklts.value(); - nTrackletsCal = cTrkltsPtr->size(); - LOGF(INFO, "Got %i calibrated tracklets as input", nTrackletsCal); - if (nTracklets != nTrackletsCal) { - LOGF(FATAL, "Number of calibrated tracklets (%i) differs from the number of uncalibrated tracklets (%i)", nTrackletsCal, nTracklets); - } - } - - std::vector trdTriggerTimes; - std::vector trdTriggerIndices; - - for (int iEv = 0; iEv < nCollisions; ++iEv) { -#ifdef MS_GSL_V3 - const auto& trg = triggerRecords[iEv]; -#else - const auto& trg = triggerRecords.at(iEv); -#endif - int nTrackletsCurrent = trg.getNumberOfTracklets(); - int iFirstTracklet = trg.getFirstTracklet(); - int64_t evTime = trg.getBCData().toLong() * o2::constants::lhc::LHCBunchSpacingNS; // event time in ns - trdTriggerTimes.push_back(evTime / 1000.); - trdTriggerIndices.push_back(iFirstTracklet); - LOGF(DEBUG, "Event %i: Occured at %li us after SOR, contains %i tracklets, index of first tracklet is %i", iEv, evTime / 1000, nTrackletsCurrent, iFirstTracklet); + inputTracks.collectData(pc, *mDataRequest); + auto tmpInputContainer = getRecoInputContainer(pc, mChainTracking->mIOPtrs, &inputTracks); + LOGF(INFO, "There are %i tracklets in total from %i trigger records", tmpInputContainer->mNTracklets, tmpInputContainer->mNTriggerRecords); + LOGF(INFO, "As input seeds are available: %i ITS-TPC matched tracks and %i TPC tracks", tmpInputContainer->mNTracksTPCITS, tmpInputContainer->mNTracksTPC); + if (tmpInputContainer->mNTracklets != tmpInputContainer->mNSpacePoints) { + LOGF(FATAL, "Number of calibrated tracklets (%i) differs from the number of uncalibrated tracklets (%i)", tmpInputContainer->mNSpacePoints, tmpInputContainer->mNTracklets); } mTracker->Reset(); + mTracker->ResetImpactAngleHistograms(); updateTimeDependentParams(); - - // the number of tracks loaded into the TRD tracker depends on the defined input sources - // TPC-only tracks which are already matched to the ITS will not be loaded as seeds for the tracking - // => the maximum number of seeds it the number of TPC-only tracks. If only ITS-TPC matches are considered than that - // of course defines the number of input tracks - mChainTracking->mIOPtrs.nMergedTracks = (nTracksTPC == 0) ? nTracksITSTPC : nTracksTPC; - mChainTracking->mIOPtrs.nTRDTracklets = nTracklets; - mChainTracking->AllocateIOMemory(); mRec->PrepareEvent(); mRec->SetupGPUProcessor(mTracker, true); - LOG(DEBUG) << "Start loading input into TRD tracker"; - + // load input tracks + LOG(DEBUG) << "Start loading input seeds into TRD tracker"; int nTracksLoadedITSTPC = 0; int nTracksLoadedTPC = 0; std::vector loadedTPCtracks; - // load ITS-TPC matched tracks - for (const auto& match : tracksITSTPC) { + for (const auto& match : tmpInputContainer->mTracksTPCITS) { GPUTRDTrack trkLoad(match, mTPCVdrift); if (mTracker->LoadTrack(trkLoad)) { continue; @@ -179,14 +129,13 @@ void TRDGlobalTracking::run(ProcessingContext& pc) ++nTracksLoadedITSTPC; LOGF(DEBUG, "Loaded ITS-TPC track %i with time %f", nTracksLoadedITSTPC, trkLoad.getTime()); } - // load TPC-only tracks - for (int iTrk = 0; iTrk < tracksTPC.size(); ++iTrk) { + for (int iTrk = 0; iTrk < tmpInputContainer->mNTracksTPC; ++iTrk) { if (std::find(loadedTPCtracks.begin(), loadedTPCtracks.end(), iTrk) != loadedTPCtracks.end()) { // this TPC tracks has already been matched to ITS and the ITS-TPC track has already been loaded in the tracker continue; } - const auto& trkTpc = tracksTPC[iTrk]; + const auto& trkTpc = tmpInputContainer->mTracksTPC[iTrk]; GPUTRDTrack trkLoad(trkTpc, mTPCTBinMUS, mTPCVdrift, iTrk); if (mTracker->LoadTrack(trkLoad)) { continue; @@ -196,27 +145,12 @@ void TRDGlobalTracking::run(ProcessingContext& pc) } LOGF(INFO, "%i tracks are loaded into the TRD tracker. Out of those %i ITS-TPC tracks and %i TPC tracks", nTracksLoadedITSTPC + nTracksLoadedTPC, nTracksLoadedITSTPC, nTracksLoadedTPC); - // load the TRD tracklets - for (int iTrklt = 0; iTrklt < nTracklets; ++iTrklt) { - auto trklt = trackletsTRD[iTrklt]; - GPUTRDTrackletWord trkltLoad(trklt.getTrackletWord()); - if (mTracker->LoadTracklet(trkltLoad) > 0) { - LOG(WARNING) << "Could not load tracklet " << iTrklt; - } - if (mUseTrackletTransform) { - const CalibratedTracklet cTrklt = (cTrkltsPtr->data())[iTrklt]; - mTracker->SetInternalSpacePoint(iTrklt, cTrklt.getX(), cTrklt.getY(), cTrklt.getZ(), cTrklt.getDy()); - } - } - - mTracker->SetTriggerRecordTimes(&(trdTriggerTimes[0])); - mTracker->SetTriggerRecordIndices(&(trdTriggerIndices[0])); - mTracker->SetNCollisions(nCollisions); + // start the tracking //mTracker->DumpTracks(); - mTracker->ResetImpactAngleHistograms(); mTracker->DoTracking(mChainTracking); //mTracker->DumpTracks(); + // finished tracking, now collect the output std::vector tracksOutITSTPC(nTracksLoadedITSTPC); std::vector tracksOutTPC(nTracksLoadedTPC); if (mTracker->NTracks() != nTracksLoadedITSTPC + nTracksLoadedTPC) { @@ -249,16 +183,15 @@ void TRDGlobalTracking::endOfStream(EndOfStreamContext& ec) mTimer.CpuTime(), mTimer.RealTime(), mTimer.Counter() - 1); } -DataProcessorSpec getTRDGlobalTrackingSpec(bool useMC, bool useTrkltTransf, GTrackID::mask_t src) +DataProcessorSpec getTRDGlobalTrackingSpec(bool useMC, GTrackID::mask_t src) { std::vector outputs; - dataRequestTRD.requestTracks(src, false); - auto& inputs = dataRequestTRD.inputs; + std::shared_ptr dataRequest = std::make_shared(); + dataRequest->requestTracks(src, false); + auto& inputs = dataRequest->inputs; - if (useTrkltTransf) { - inputs.emplace_back("trdctracklets", o2::header::gDataOriginTRD, "CTRACKLETS", 0, Lifetime::Timeframe); - } + inputs.emplace_back("trdctracklets", o2::header::gDataOriginTRD, "CTRACKLETS", 0, Lifetime::Timeframe); inputs.emplace_back("trdtracklets", o2::header::gDataOriginTRD, "TRACKLETS", 0, Lifetime::Timeframe); inputs.emplace_back("trdtriggerrec", o2::header::gDataOriginTRD, "TRKTRGRD", 0, Lifetime::Timeframe); @@ -280,7 +213,7 @@ DataProcessorSpec getTRDGlobalTrackingSpec(bool useMC, bool useTrkltTransf, GTra processorName, inputs, outputs, - AlgorithmSpec{adaptFromTask(useMC, useTrkltTransf)}, + AlgorithmSpec{adaptFromTask(useMC, dataRequest)}, Options{}}; } diff --git a/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx b/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx index a1767814f55d9..bdce84c184fd0 100644 --- a/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx +++ b/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx @@ -16,6 +16,7 @@ #include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" #include "TPCWorkflow/TrackReaderSpec.h" #include "TRDWorkflow/TRDTrackletReaderSpec.h" +#include "TRDWorkflow/TRDTrackletTransformerSpec.h" #include "TRDWorkflow/TRDGlobalTrackingSpec.h" #include "TRDWorkflow/TRDTrackWriterSpec.h" #include "TRDWorkflow/TRDTrackingWorkflow.h" @@ -27,7 +28,7 @@ namespace o2 namespace trd { -framework::WorkflowSpec getTRDTrackingWorkflow(bool disableRootInp, bool disableRootOut, bool useTrkltTransf, GTrackID::mask_t srcTRD) +framework::WorkflowSpec getTRDTrackingWorkflow(bool disableRootInp, bool disableRootOut, GTrackID::mask_t srcTRD) { framework::WorkflowSpec specs; bool useMC = false; @@ -38,10 +39,11 @@ framework::WorkflowSpec getTRDTrackingWorkflow(bool disableRootInp, bool disable if (GTrackID::includesSource(GTrackID::Source::TPC, srcTRD)) { specs.emplace_back(o2::tpc::getTPCTrackReaderSpec(useMC)); } - specs.emplace_back(o2::trd::getTRDTrackletReaderSpec(useMC, useTrkltTransf)); + specs.emplace_back(o2::trd::getTRDTrackletReaderSpec(useMC, false)); } - specs.emplace_back(o2::trd::getTRDGlobalTrackingSpec(useMC, useTrkltTransf, srcTRD)); + specs.emplace_back(o2::trd::getTRDTrackletTransformerSpec()); + specs.emplace_back(o2::trd::getTRDGlobalTrackingSpec(useMC, srcTRD)); if (!disableRootOut) { if (GTrackID::includesSource(GTrackID::Source::ITSTPC, srcTRD)) { diff --git a/Detectors/TRD/workflow/src/trd-tracking-workflow.cxx b/Detectors/TRD/workflow/src/trd-tracking-workflow.cxx index 2f0f4cba5897d..86ce6f5f506cf 100644 --- a/Detectors/TRD/workflow/src/trd-tracking-workflow.cxx +++ b/Detectors/TRD/workflow/src/trd-tracking-workflow.cxx @@ -24,7 +24,6 @@ void customize(std::vector& workflowOptions) // option allowing to set parameters std::vector options{ {"disable-mc", o2::framework::VariantType::Bool, false, {"Disable MC labels"}}, - {"use-tracklet-transformer", VariantType::Bool, false, {"Use calibrated tracklets instead raw Tracklet64"}}, {"disable-root-input", o2::framework::VariantType::Bool, false, {"disable root-files input readers"}}, {"disable-root-output", o2::framework::VariantType::Bool, false, {"disable root-files output writers"}}, {"tracking-sources", VariantType::String, std::string{o2::dataformats::GlobalTrackID::ALL}, {"comma-separated list of sources to use for tracking"}}, @@ -48,10 +47,9 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) o2::conf::ConfigurableParam::writeINI("o2trdtracking-workflow_configuration.ini"); auto disableRootInp = configcontext.options().get("disable-root-input"); auto disableRootOut = configcontext.options().get("disable-root-output"); - auto useTrackletTransformer = configcontext.options().get("use-tracklet-transformer"); o2::dataformats::GlobalTrackID::mask_t srcTRD = allowedSources & o2::dataformats::GlobalTrackID::getSourcesMask(configcontext.options().get("tracking-sources")); - auto wf = o2::trd::getTRDTrackingWorkflow(disableRootInp, disableRootOut, useTrackletTransformer, srcTRD); + auto wf = o2::trd::getTRDTrackingWorkflow(disableRootInp, disableRootOut, srcTRD); // configure dpl timer to inject correct firstTFOrbit: start from the 1st orbit of TF containing 1st sampled orbit o2::raw::HBFUtilsInitializer hbfIni(configcontext, wf); diff --git a/GPU/GPUTracking/CMakeLists.txt b/GPU/GPUTracking/CMakeLists.txt index bdfd79d8e21d8..ba895d994a55d 100644 --- a/GPU/GPUTracking/CMakeLists.txt +++ b/GPU/GPUTracking/CMakeLists.txt @@ -109,6 +109,7 @@ set(HDRS_INSTALL DataTypes/GPUSettings.h TRDTracking/GPUTRDTrackPoint.h TRDTracking/GPUTRDTrack.h + TRDTracking/GPUTRDSpacePoint.h TRDTracking/GPUTRDTrackData.h TRDTracking/GPUTRDTrackPoint.h TRDTracking/GPUTRDTrackletLabels.h diff --git a/GPU/GPUTracking/DataTypes/GPUDataTypes.h b/GPU/GPUTracking/DataTypes/GPUDataTypes.h index 01a5f82054607..f7e561128a9e0 100644 --- a/GPU/GPUTracking/DataTypes/GPUDataTypes.h +++ b/GPU/GPUTracking/DataTypes/GPUDataTypes.h @@ -59,6 +59,7 @@ class GeometryFlat; } // namespace trd namespace dataformats { +class TrackTPCITS; template class MCTruthContainer; template @@ -100,6 +101,7 @@ class GPUTPCGMMergedTrack; struct GPUTPCGMMergedTrackHit; struct GPUTPCGMMergedTrackHitXYZ; class GPUTRDTrackletWord; +class GPUTRDSpacePoint; struct GPUTPCMCInfo; struct GPUTPCClusterData; struct GPUTRDTrackletLabels; @@ -243,12 +245,16 @@ struct GPUTrackingInOutPointers { unsigned int nOutputClusRefsTPCO2 = 0; const o2::MCCompLabel* outputTracksTPCO2MC = nullptr; const o2::tpc::CompressedClustersFlat* tpcCompressedClusters = nullptr; + const o2::dataformats::TrackTPCITS* tracksTPCITSO2 = nullptr; + unsigned int nTracksTPCITSO2 = 0; const GPUTRDTrackletWord* trdTracklets = nullptr; + const GPUTRDSpacePoint* trdSpacePoints = nullptr; unsigned int nTRDTracklets = 0; - const GPUTRDTrackletLabels* trdTrackletsMC = nullptr; - unsigned int nTRDTrackletsMC = 0; const GPUTRDTrackGPU* trdTracks = nullptr; unsigned int nTRDTracks = 0; + const float* trdTriggerTimes = nullptr; + const int* trdTrackletIdxFirst = nullptr; + unsigned int nTRDTriggerRecords = 0; const GPUSettingsTF* settingsTF = nullptr; }; #else diff --git a/GPU/GPUTracking/Definitions/GPUSettingsList.h b/GPU/GPUTracking/Definitions/GPUSettingsList.h index 1d49e4b602177..b0176f879692e 100644 --- a/GPU/GPUTracking/Definitions/GPUSettingsList.h +++ b/GPU/GPUTracking/Definitions/GPUSettingsList.h @@ -100,7 +100,6 @@ AddOption(gpuDeviceOnly, bool, false, "", 0, "Use only GPU as device (i.e. no CP AddOption(globalInitMutex, bool, false, "", 0, "Use global mutex to synchronize initialization of multiple GPU instances") AddOption(stuckProtection, int, 0, "", 0, "Timeout in us, When AMD GPU is stuck, just continue processing and skip tracking, do not crash or stall the chain") AddOption(trdNCandidates, int, 1, "", 0, "Number of branching track candidates for single input track during propagation") -AddOption(trdNMaxCollisions, int, 1000, "", 0, "Maximum number of collisions per TF which the TRD tracker can handle") AddOption(debugLevel, int, -1, "debug", 'd', "Set debug level (-1 = silend)") AddOption(allocDebugLevel, int, 0, "allocDebug", 0, "Some debug output for memory allocations (without messing with normal debug level)") AddOption(debugMask, int, -1, "", 0, "Mask for debug output dumps to file") diff --git a/GPU/GPUTracking/Global/AliHLTGPUDumpComponent.cxx b/GPU/GPUTracking/Global/AliHLTGPUDumpComponent.cxx index d88ae53768a2a..a4abc4917a058 100644 --- a/GPU/GPUTracking/Global/AliHLTGPUDumpComponent.cxx +++ b/GPU/GPUTracking/Global/AliHLTGPUDumpComponent.cxx @@ -451,8 +451,6 @@ int AliHLTGPUDumpComponent::DoEvent(const AliHLTComponentEventData& evtData, con fChain->mIOPtrs.nTRDTracklets = nTRDTrackletsTotal; fChain->mIOPtrs.trdTracklets = TRDtracklets; - fChain->mIOPtrs.nTRDTrackletsMC = nTRDTrackletsMCTotal; - fChain->mIOPtrs.trdTrackletsMC = TRDtrackletsMC; HLTDebug("Number of TRD tracklets: %d", (int)nTRDTrackletsTotal); static int nEvent = 0; diff --git a/GPU/GPUTracking/Global/GPUChainTracking.cxx b/GPU/GPUTracking/Global/GPUChainTracking.cxx index c8319a770e9a4..9a52e8d123a32 100644 --- a/GPU/GPUTracking/Global/GPUChainTracking.cxx +++ b/GPU/GPUTracking/Global/GPUChainTracking.cxx @@ -486,7 +486,9 @@ void GPUChainTracking::AllocateIOMemory() AllocateIOMemoryHelper(mIOPtrs.nMergedTrackHits, mIOPtrs.mergedTrackHitsXYZ, mIOMem.mergedTrackHitsXYZ); AllocateIOMemoryHelper(mIOPtrs.nTRDTracks, mIOPtrs.trdTracks, mIOMem.trdTracks); AllocateIOMemoryHelper(mIOPtrs.nTRDTracklets, mIOPtrs.trdTracklets, mIOMem.trdTracklets); - AllocateIOMemoryHelper(mIOPtrs.nTRDTrackletsMC, mIOPtrs.trdTrackletsMC, mIOMem.trdTrackletsMC); + AllocateIOMemoryHelper(mIOPtrs.nTRDTracklets, mIOPtrs.trdSpacePoints, mIOMem.trdSpacePoints); + AllocateIOMemoryHelper(mIOPtrs.nTRDTriggerRecords, mIOPtrs.trdTriggerTimes, mIOMem.trdTriggerTimes); + AllocateIOMemoryHelper(mIOPtrs.nTRDTriggerRecords, mIOPtrs.trdTrackletIdxFirst, mIOMem.trdTrackletIdxFirst); } void GPUChainTracking::LoadClusterErrors() { param().LoadClusterErrors(); } diff --git a/GPU/GPUTracking/Global/GPUChainTracking.h b/GPU/GPUTracking/Global/GPUChainTracking.h index e53b42a0f5376..8fa555d796ef4 100644 --- a/GPU/GPUTracking/Global/GPUChainTracking.h +++ b/GPU/GPUTracking/Global/GPUChainTracking.h @@ -108,7 +108,9 @@ class GPUChainTracking : public GPUChain, GPUReconstructionHelpers::helperDelega std::unique_ptr mergedTrackHits; std::unique_ptr mergedTrackHitsXYZ; std::unique_ptr trdTracklets; - std::unique_ptr trdTrackletsMC; + std::unique_ptr trdSpacePoints; + std::unique_ptr trdTriggerTimes; + std::unique_ptr trdTrackletIdxFirst; std::unique_ptr trdTracks; std::unique_ptr clusterNativeMC; std::unique_ptr> clusterNativeMCView; diff --git a/GPU/GPUTracking/Global/GPUChainTrackingIO.cxx b/GPU/GPUTracking/Global/GPUChainTrackingIO.cxx index fedc3ce906352..3059836202b34 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingIO.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingIO.cxx @@ -134,7 +134,6 @@ void GPUChainTracking::DumpData(const char* filename) DumpData(fp, &mIOPtrs.mergedTrackHits, &mIOPtrs.nMergedTrackHits, InOutPointerType::MERGED_TRACK_HIT); DumpData(fp, &mIOPtrs.trdTracks, &mIOPtrs.nTRDTracks, InOutPointerType::TRD_TRACK); DumpData(fp, &mIOPtrs.trdTracklets, &mIOPtrs.nTRDTracklets, InOutPointerType::TRD_TRACKLET); - DumpData(fp, &mIOPtrs.trdTrackletsMC, &mIOPtrs.nTRDTrackletsMC, InOutPointerType::TRD_TRACKLET_MC); fclose(fp); } @@ -222,7 +221,6 @@ int GPUChainTracking::ReadData(const char* filename) ReadData(fp, &mIOPtrs.mergedTrackHits, &mIOPtrs.nMergedTrackHits, &mIOMem.mergedTrackHits, InOutPointerType::MERGED_TRACK_HIT); ReadData(fp, &mIOPtrs.trdTracks, &mIOPtrs.nTRDTracks, &mIOMem.trdTracks, InOutPointerType::TRD_TRACK); ReadData(fp, &mIOPtrs.trdTracklets, &mIOPtrs.nTRDTracklets, &mIOMem.trdTracklets, InOutPointerType::TRD_TRACKLET); - ReadData(fp, &mIOPtrs.trdTrackletsMC, &mIOPtrs.nTRDTrackletsMC, &mIOMem.trdTrackletsMC, InOutPointerType::TRD_TRACKLET_MC); size_t fptr = ftell(fp); fseek(fp, 0, SEEK_END); diff --git a/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx b/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx index a65d47128ce93..11439a9ab91f5 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx @@ -38,11 +38,6 @@ int GPUChainTracking::RunTRDTracking() mRec->PushNonPersistentMemory(qStr2Tag("TRDTRACK")); SetupGPUProcessor(&Tracker, true); - for (unsigned int iTracklet = 0; iTracklet < mIOPtrs.nTRDTracklets; ++iTracklet) { - if (Tracker.LoadTracklet(mIOPtrs.trdTracklets[iTracklet], mIOPtrs.trdTrackletsMC ? mIOPtrs.trdTrackletsMC[iTracklet].mLabel : nullptr)) { - return 1; - } - } for (unsigned int i = 0; i < mIOPtrs.nMergedTracks; i++) { const GPUTPCGMMergedTrack& trk = mIOPtrs.mergedTracks[i]; diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDSpacePoint.h b/GPU/GPUTracking/TRDTracking/GPUTRDSpacePoint.h new file mode 100644 index 0000000000000..d1c5f8fec67cc --- /dev/null +++ b/GPU/GPUTracking/TRDTracking/GPUTRDSpacePoint.h @@ -0,0 +1,71 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file GPUTRDSpacePoint.h +/// \author Ole Schmidt, ole.schmidt@cern.ch +/// \brief Struct to hold the position/direction information of the tracklets transformed in sector coordinates + +#ifndef GPUTRDSPACEPOINT_H +#define GPUTRDSPACEPOINT_H + +#ifndef GPUCA_TPC_GEOMETRY_O2 // compatibility to Run 2 data types + +namespace GPUCA_NAMESPACE +{ +namespace gpu +{ + +// class to hold the information on the space points +class GPUTRDSpacePoint +{ + public: + GPUd() GPUTRDSpacePoint(float x = 0, float y = 0, float z = 0, float dy = 0) : mX(x), mY(y), mZ(z), mDy(dy) {} + GPUd() float getX() const { return mX; } + GPUd() float getY() const { return mY; } + GPUd() float getZ() const { return mZ; } + GPUd() float getDy() const { return mDy; } + GPUd() void setX(float x) { mX = x; } + GPUd() void setY(float y) { mY = y; } + GPUd() void setZ(float z) { mZ = z; } + GPUd() void setDy(float dy) { mDy = dy; } + + private: + float mX; // x position (3.5 mm above anode wires) - radial offset due to t0 mis-calibration, measured -1 mm for run 245353 + float mY; // y position (sector coordinates) + float mZ; // z position (sector coordinates) + float mDy; // deflection over drift length +}; + +} // namespace gpu +} // namespace GPUCA_NAMESPACE + +#else // compatibility with Run 3 data types + +#include "DataFormatsTRD/CalibratedTracklet.h" + +namespace GPUCA_NAMESPACE +{ +namespace gpu +{ + +class GPUTRDSpacePoint : public o2::trd::CalibratedTracklet +{ +}; + +#ifdef GPUCA_NOCOMPAT +static_assert(sizeof(GPUTRDSpacePoint) == sizeof(o2::trd::CalibratedTracklet), "Incorrect memory layout"); +#endif + +} // namespace gpu +} // namespace GPUCA_NAMESPACE + +#endif // GPUCA_TPC_GEOMETRY_O2 + +#endif // GPUTRDSPACEPOINT_H diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx index 2884266b2c5c0..cea3c19b011de 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx @@ -53,6 +53,7 @@ void GPUTRDTracker_t::SetMaxData(const GPUTrackingInOutPointers& i { mNMaxTracks = io.nMergedTracks; mNMaxSpacePoints = io.nTRDTracklets; + mNMaxCollisions = io.nTRDTriggerRecords; } template @@ -72,7 +73,6 @@ void* GPUTRDTracker_t::SetPointersBase(void* base) //-------------------------------------------------------------------- mMaxThreads = mRec->GetMaxThreads(); computePointerWithAlignment(base, mR, kNChambers); - computePointerWithAlignment(base, mTrackletIndexArray, (kNChambers + 1) * mNMaxCollisions); computePointerWithAlignment(base, mHypothesis, mNCandidates * mMaxThreads); computePointerWithAlignment(base, mCandidates, mNCandidates * 2 * mMaxThreads); computePointerWithAlignment(base, mAngleDiffSums, kNChambers * (mNAngleHistogramBins + 1)); @@ -87,9 +87,10 @@ void* GPUTRDTracker_t::SetPointersTracklets(void* base) // Allocate memory for tracklets and space points // (size might change for different events) //-------------------------------------------------------------------- - computePointerWithAlignment(base, mTracklets, mNMaxSpacePoints * mNMaxCollisions); - computePointerWithAlignment(base, mTrackletIndices, mNMaxSpacePoints * mNMaxCollisions); - computePointerWithAlignment(base, mSpacePoints, mNMaxSpacePoints * mNMaxCollisions); + if (mGenerateSpacePoints) { + computePointerWithAlignment(base, mSpacePoints, mNMaxSpacePoints); + } + computePointerWithAlignment(base, mTrackletIndexArray, (kNChambers + 1) * mNMaxCollisions); computePointerWithAlignment(base, mTrackletLabels, 3 * mNMaxSpacePoints * mNMaxCollisions); return base; } @@ -105,7 +106,7 @@ void* GPUTRDTracker_t::SetPointersTracks(void* base) } template -GPUTRDTracker_t::GPUTRDTracker_t() : mR(nullptr), mIsInitialized(false), mTrkltTransfNeeded(true), mProcessPerTimeFrame(false), mDoImpactAngleHistograms(false), mNAngleHistogramBins(25), mAngleHistogramRange(50), mMemoryPermanent(-1), mMemoryTracklets(-1), mMemoryTracks(-1), mNMaxCollisions(1), mNMaxTracks(0), mNMaxSpacePoints(0), mTracks(nullptr), mNCandidates(1), mNCollisions(1), mNTracks(0), mNEvents(0), mTriggerRecordIndices(nullptr), mTriggerRecordTimes(nullptr), mTracklets(nullptr), mTrackletIndices(nullptr), mMaxThreads(100), mNTracklets(0), mTrackletIndexArray(nullptr), mHypothesis(nullptr), mCandidates(nullptr), mSpacePoints(nullptr), mAngleDiffSums(nullptr), mAngleDiffCounters(nullptr), mTrackletLabels(nullptr), mGeo(nullptr), mRPhiA2(0), mRPhiB(0), mRPhiC2(0), mDyA2(0), mDyB(0), mDyC2(0), mAngleToDyA(0), mAngleToDyB(0), mAngleToDyC(0), mDebugOutput(false), mMaxEta(0.84f), mExtraRoadY(2.f), mRoadZ(18.f), mZCorrCoefNRC(1.4f), mTPCVdrift(2.58f), mMCEvent(nullptr), mDebug(new GPUTRDTrackerDebug()) +GPUTRDTracker_t::GPUTRDTracker_t() : mR(nullptr), mIsInitialized(false), mGenerateSpacePoints(false), mProcessPerTimeFrame(false), mDoImpactAngleHistograms(false), mNAngleHistogramBins(25), mAngleHistogramRange(50), mMemoryPermanent(-1), mMemoryTracklets(-1), mMemoryTracks(-1), mNMaxCollisions(0), mNMaxTracks(0), mNMaxSpacePoints(0), mTracks(nullptr), mNCandidates(1), mNTracks(0), mNEvents(0), mMaxThreads(100), mTrackletIndexArray(nullptr), mHypothesis(nullptr), mCandidates(nullptr), mSpacePoints(nullptr), mAngleDiffSums(nullptr), mAngleDiffCounters(nullptr), mTrackletLabels(nullptr), mGeo(nullptr), mRPhiA2(0), mRPhiB(0), mRPhiC2(0), mDyA2(0), mDyB(0), mDyC2(0), mAngleToDyA(0), mAngleToDyB(0), mAngleToDyC(0), mDebugOutput(false), mMaxEta(0.84f), mExtraRoadY(2.f), mRoadZ(18.f), mZCorrCoefNRC(1.4f), mTPCVdrift(2.58f), mMCEvent(nullptr), mDebug(new GPUTRDTrackerDebug()) { //-------------------------------------------------------------------- // Default constructor @@ -129,7 +130,7 @@ void GPUTRDTracker_t::InitializeProcessor() //-------------------------------------------------------------------- mGeo = (TRD_GEOMETRY_CONST GPUTRDGeometry*)GetConstantMem()->calibObjects.trdGeometry; if (!mGeo) { - Error("Init", "TRD geometry must be provided externally"); + GPUError("TRD geometry must be provided externally"); } float Bz = Param().par.BzkG; @@ -196,7 +197,6 @@ void GPUTRDTracker_t::Reset() //-------------------------------------------------------------------- // Reset tracker //-------------------------------------------------------------------- - mNTracklets = 0; mNTracks = 0; } @@ -207,32 +207,25 @@ void GPUTRDTracker_t::DoTracking(GPUChainTracking* chainTracking) // Steering function for the tracking //-------------------------------------------------------------------- - for (int i = 0; i < mNTracklets; ++i) { - // fill index array (is there something like std::iota() for GPUs?) - mTrackletIndices[i] = i; - } - // sort tracklets and fill index array - for (int iColl = 0; iColl < mNCollisions; ++iColl) { + // fill tracklet index array (tracklets are already sorted) + for (unsigned int iColl = 0; iColl < GetConstantMem()->ioPtrs.nTRDTriggerRecords; ++iColl) { int nTrklts = 0; int idxOffset = 0; if (mProcessPerTimeFrame) { - idxOffset = mTriggerRecordIndices[iColl]; - nTrklts = (iColl < mNCollisions - 1) ? mTriggerRecordIndices[iColl + 1] - mTriggerRecordIndices[iColl] : mNTracklets - mTriggerRecordIndices[iColl]; + idxOffset = GetConstantMem()->ioPtrs.trdTrackletIdxFirst[iColl]; + nTrklts = (iColl < GetConstantMem()->ioPtrs.nTRDTriggerRecords - 1) ? GetConstantMem()->ioPtrs.trdTrackletIdxFirst[iColl + 1] - GetConstantMem()->ioPtrs.trdTrackletIdxFirst[iColl] : GetConstantMem()->ioPtrs.nTRDTracklets - GetConstantMem()->ioPtrs.trdTrackletIdxFirst[iColl]; } else { - nTrklts = mNTracklets; + nTrklts = GetConstantMem()->ioPtrs.nTRDTracklets; } - GPUTRDTrackletWord* tracklets = &(mTracklets[idxOffset]); - int* trkltIndices = &(mTrackletIndices[idxOffset]); - // TODO after the tracklet output of the TRAP simulator in O2 is sorted by HCId this sorting step is not needed anymore for O2 - CAAlgo::sort(trkltIndices, trkltIndices + nTrklts, [=, &tracklets](int a, int b) { return tracklets[a - idxOffset].GetHCId() < tracklets[b - idxOffset].GetHCId(); }); + const GPUTRDTrackletWord* tracklets = &((GetConstantMem()->ioPtrs.trdTracklets)[idxOffset]); int* trkltIndexArray = &mTrackletIndexArray[iColl * (kNChambers + 1) + 1]; trkltIndexArray[-1] = 0; int currDet = 0; int nextDet = 0; int trkltCounter = 0; for (int iTrklt = 0; iTrklt < nTrklts; ++iTrklt) { - if (tracklets[trkltIndices[iTrklt] - idxOffset].GetDetector() > currDet) { - nextDet = tracklets[trkltIndices[iTrklt] - idxOffset].GetDetector(); + if (tracklets[iTrklt].GetDetector() > currDet) { + nextDet = tracklets[iTrklt].GetDetector(); for (int iDet = currDet; iDet < nextDet; ++iDet) { trkltIndexArray[iDet] = trkltCounter; } @@ -243,13 +236,16 @@ void GPUTRDTracker_t::DoTracking(GPUChainTracking* chainTracking) for (int iDet = currDet; iDet <= kNChambers; ++iDet) { trkltIndexArray[iDet] = trkltCounter; } - if (mTrkltTransfNeeded) { + if (mGenerateSpacePoints) { if (!CalculateSpacePoints(iColl)) { GPUError("Space points for at least one chamber could not be calculated (for interaction %i)", iColl); break; } } } + if (mGenerateSpacePoints) { + chainTracking->mIOPtrs.trdSpacePoints = mSpacePoints; + } auto timeStart = std::chrono::high_resolution_clock::now(); @@ -292,7 +288,7 @@ void GPUTRDTracker_t::DoTracking(GPUChainTracking* chainTracking) std::cout << "---> -----> -------> ---------> "; std::cout << "Time for event " << mNEvents << ": " << std::chrono::duration_cast(duration).count() << " us "; std::cout << "nTracks: " << mNTracks; - std::cout << " nTracklets: " << mNTracklets; + std::cout << " nTracklets: " << GetConstantMem()->ioPtrs.nTRDTracklets; std::cout << std::endl; */ //DumpTracks(); @@ -308,7 +304,7 @@ void GPUTRDTracker_t::SetNCandidates(int n) if (!mIsInitialized) { mNCandidates = n; } else { - Error("SetNCandidates", "Cannot change mNCandidates after initialization"); + GPUError("Cannot change mNCandidates after initialization"); } } @@ -511,24 +507,6 @@ GPUd() int GPUTRDTracker_t::LoadTrack(const TRDTRK& trk, const int return (0); } -template -GPUd() int GPUTRDTracker_t::LoadTracklet(const GPUTRDTrackletWord& tracklet, const int* labels) -{ - //-------------------------------------------------------------------- - // Add single tracklet to tracker - //-------------------------------------------------------------------- - if (mNTracklets >= mNMaxSpacePoints * mNMaxCollisions) { - Error("LoadTracklet", "Running out of memory for tracklets, skipping tracklet(s). This should actually never happen."); - return 1; - } - if (labels) { - for (int i = 0; i < 3; ++i) { - mTrackletLabels[3 * mNTracklets + i] = labels[i]; - } - } - mTracklets[mNTracklets++] = tracklet; - return 0; -} template GPUd() void GPUTRDTracker_t::DumpTracks() @@ -536,7 +514,8 @@ GPUd() void GPUTRDTracker_t::DumpTracks() //-------------------------------------------------------------------- // helper function (only for debugging purposes) //-------------------------------------------------------------------- - GPUInfo("There are %i tracks loaded. mNMaxTracks(%i)\n", mNTracks, mNMaxTracks); + GPUInfo("There are in total %i tracklets loaded", GetConstantMem()->ioPtrs.nTRDTracklets); + GPUInfo("There are %i tracks loaded. mNMaxTracks(%i)", mNTracks, mNMaxTracks); for (int i = 0; i < mNTracks; ++i) { auto* trk = &(mTracks[i]); GPUInfo("track %i: x=%f, alpha=%f, nTracklets=%i, pt=%f, time=%f", i, trk->getX(), trk->getAlpha(), trk->GetNtracklets(), trk->getPt(), trk->getTime()); @@ -554,8 +533,8 @@ GPUd() int GPUTRDTracker_t::GetCollisionIDs(TRDTRK& trk, int* coll // and the number of valid entries in the array is returned //-------------------------------------------------------------------- int nColls = 0; - for (int iColl = 0; iColl < mNCollisions; ++iColl) { - if (mTriggerRecordTimes[iColl] > trk.getTimeMin() && mTriggerRecordTimes[iColl] < trk.getTimeMax()) { + for (unsigned int iColl = 0; iColl < GetConstantMem()->ioPtrs.nTRDTriggerRecords; ++iColl) { + if (GetConstantMem()->ioPtrs.trdTriggerTimes[iColl] > trk.getTimeMin() && GetConstantMem()->ioPtrs.trdTriggerTimes[iColl] < trk.getTimeMax()) { if (nColls == 20) { GPUError("Found too many collision candidates for track with tMin(%f) and tMax(%f)", trk.getTimeMin(), trk.getTimeMax()); return nColls; @@ -578,14 +557,14 @@ GPUd() void GPUTRDTracker_t::DoTrackingThread(int iTrk, int thread nCollisionIds = GetCollisionIDs(mTracks[iTrk], collisionIds); if (nCollisionIds == 0) { if (ENABLE_INFO) { - GPUInfo("Did not find TRD data for track with t=%f. tMin(%f), tMax(%f)", mTracks[iTrk].getTime(), mTracks[iTrk].getTimeMin(), mTracks[iTrk].getTimeMax()); + GPUInfo("Did not find TRD data for track %i with t=%f. tMin(%f), tMax(%f)", iTrk, mTracks[iTrk].getTime(), mTracks[iTrk].getTimeMin(), mTracks[iTrk].getTimeMax()); } // no TRD data available for the bunch crossing this track originates from return; } } PROP prop(getPropagatorParam()); - mTracks[iTrk].SetChi2(Param().rec.trdPenaltyChi2); + mTracks[iTrk].SetChi2(Param().rec.trdPenaltyChi2); // TODO check if this should not be higher auto trkStart = mTracks[iTrk]; for (int iColl = 0; iColl < nCollisionIds; ++iColl) { // do track following for each collision candidate and keep best track @@ -601,9 +580,9 @@ GPUd() void GPUTRDTracker_t::DoTrackingThread(int iTrk, int thread #ifndef GPUCA_ALIROOT_LIB // AliRoot TRD geometry functions are non-const, and cannot work with a const geometry template -GPUd() bool GPUTRDTracker_t::ConvertTrkltToSpacePoint(const GPUTRDGeometry& geo, GPUTRDTrackletWord& trklt, GPUTRDSpacePointInternal& sp) +GPUd() bool GPUTRDTracker_t::ConvertTrkltToSpacePoint(const GPUTRDGeometry& geo, GPUTRDTrackletWord& trklt, GPUTRDSpacePoint& sp) { - // converts a single GPUTRDTrackletWord into GPUTRDSpacePointInternal + // converts a single GPUTRDTrackletWord into GPUTRDSpacePoint // returns true if successfull int det = trklt.GetDetector(); if (!geo.ChamberInGeometry(det)) { @@ -621,14 +600,11 @@ GPUd() bool GPUTRDTracker_t::ConvertTrkltToSpacePoint(const GPUTRD xTrkltDet[1] = trklt.GetY(); xTrkltDet[2] = pp->GetRowPos(trkltZbin) - pp->GetRowSize(trkltZbin) / 2.f - pp->GetRowPos(pp->GetNrows() / 2); matrix->LocalToMaster(xTrkltDet, xTrkltSec); - sp.mR = xTrkltSec[0]; - sp.mX[0] = xTrkltSec[1]; - sp.mX[1] = xTrkltSec[2]; - sp.mDy = trklt.GetdY(); - - int modId = geo.GetSector(det) * GPUTRDGeometry::kNstack + geo.GetStack(det); // global TRD stack number - unsigned short volId = geo.GetGeomManagerVolUID(det, modId); - sp.mVolumeId = volId; + sp.setX(xTrkltSec[0]); + sp.setY(xTrkltSec[1]); + sp.setZ(xTrkltSec[2]); + sp.setDy(trklt.GetdY()); + return true; } #endif @@ -644,6 +620,8 @@ GPUd() bool GPUTRDTracker_t::CalculateSpacePoints(int iCollision) bool result = true; int idxOffset = iCollision * (kNChambers + 1); // offset for accessing mTrackletIndexArray for collision iCollision + const GPUTRDTrackletWord* tracklets = GetConstantMem()->ioPtrs.trdTracklets; + for (int iDet = 0; iDet < kNChambers; ++iDet) { int iFirstTrackletInDet = mTrackletIndexArray[idxOffset + iDet]; int iFirstTrackletInNextDet = mTrackletIndexArray[idxOffset + iDet + 1]; @@ -663,31 +641,28 @@ GPUd() bool GPUTRDTracker_t::CalculateSpacePoints(int iCollision) } const GPUTRDpadPlane* pp = mGeo->GetPadPlane(iDet); - int trkltIdxOffset = (mProcessPerTimeFrame) ? mTriggerRecordIndices[iCollision] : 0; // global index of first tracklet (not yet sorted by HCId) in iCollision + int trkltIdxOffset = (mProcessPerTimeFrame) ? GetConstantMem()->ioPtrs.trdTrackletIdxFirst[iCollision] : 0; // global index of first tracklet in iCollision int trkltIdxStart = trkltIdxOffset + iFirstTrackletInDet; for (int trkltIdx = trkltIdxStart; trkltIdx < trkltIdxStart + nTrackletsInDet; ++trkltIdx) { - int trkltIdxGlb = mTrackletIndices[trkltIdx]; // sorted by HCId - int trkltZbin = mTracklets[trkltIdxGlb].GetZbin(); + int trkltZbin = tracklets[trkltIdx].GetZbin(); My_Float xTrkltDet[3] = {0.f}; // trklt position in chamber coordinates My_Float xTrkltSec[3] = {0.f}; // trklt position in sector coordinates xTrkltDet[0] = mGeo->AnodePos() + sRadialOffset; - xTrkltDet[1] = mTracklets[trkltIdxGlb].GetY(); + xTrkltDet[1] = tracklets[trkltIdx].GetY(); xTrkltDet[2] = pp->GetRowPos(trkltZbin) - pp->GetRowSize(trkltZbin) / 2.f - pp->GetRowPos(pp->GetNrows() / 2); - //GPUInfo("Space point local %i: x=%f, y=%f, z=%f", trkltIdxGlb, xTrkltDet[0], xTrkltDet[1], xTrkltDet[2]); + //GPUInfo("Space point local %i: x=%f, y=%f, z=%f", trkltIdx, xTrkltDet[0], xTrkltDet[1], xTrkltDet[2]); matrix->LocalToMaster(xTrkltDet, xTrkltSec); - mSpacePoints[trkltIdxGlb].mR = xTrkltSec[0]; - mSpacePoints[trkltIdxGlb].mX[0] = xTrkltSec[1]; - mSpacePoints[trkltIdxGlb].mX[1] = xTrkltSec[2]; - mSpacePoints[trkltIdxGlb].mDy = mTracklets[trkltIdxGlb].GetdY(); - - int modId = mGeo->GetSector(iDet) * GPUTRDGeometry::kNstack + mGeo->GetStack(iDet); // global TRD stack number - unsigned short volId = mGeo->GetGeomManagerVolUID(iDet, modId); - mSpacePoints[trkltIdxGlb].mVolumeId = volId; - //GPUInfo("Space point global %i: x=%f, y=%f, z=%f", trkltIdxGlb, mSpacePoints[trkltIdxGlb].mR, mSpacePoints[trkltIdxGlb].mX[0], mSpacePoints[trkltIdxGlb].mX[1]); + mSpacePoints[trkltIdx].setX(xTrkltSec[0]); + mSpacePoints[trkltIdx].setY(xTrkltSec[1]); + mSpacePoints[trkltIdx].setZ(xTrkltSec[2]); + mSpacePoints[trkltIdx].setDy(tracklets[trkltIdx].GetdY()); + + //GPUInfo("Space point global %i: x=%f, y=%f, z=%f", trkltIdx, mSpacePoints[trkltIdx].getX(), mSpacePoints[trkltIdx].getY(), mSpacePoints[trkltIdx].getZ()); } } return result; } + template GPUd() void GPUTRDTracker_t::ResetImpactAngleHistograms() { @@ -741,9 +716,9 @@ GPUd() int GPUTRDTracker_t::FillImpactAngleHistograms(PROP* prop, } float radToDeg = 180.f / CAMath::Pi(); float trkAngle = CAMath::ASin(t->getSnp()) * radToDeg; - float trkltAngle = CAMath::ATan(mSpacePoints[t->GetTracklet(iLayer)].mDy / 3.) * radToDeg; + float trkltAngle = CAMath::ATan(GetConstantMem()->ioPtrs.trdSpacePoints[t->GetTracklet(iLayer)].getDy() / 3.) * radToDeg; - int idxOffsetDet = mTracklets[t->GetTracklet(iLayer)].GetDetector() * (mNAngleHistogramBins + 1); + int idxOffsetDet = GetConstantMem()->ioPtrs.trdTracklets[t->GetTracklet(iLayer)].GetDetector() * (mNAngleHistogramBins + 1); int idxOffsetAngle = (trkAngle + .5 * mAngleHistogramRange) * invBinWidth; if (CAMath::Abs(idxOffsetAngle) >= .5 * mAngleHistogramRange) { @@ -767,10 +742,12 @@ GPUd() int GPUTRDTracker_t::PropagateToLayerAndUpdate(PROP* prop, // returns 0 in case of success //-------------------------------------------------------------------- int trackletID = trkWork->GetTracklet(iLayer); - int trackletDet = mTracklets[trackletID].GetDetector(); + int trackletDet = GetConstantMem()->ioPtrs.trdTracklets[trackletID].GetDetector(); int trackletSector = trackletDet / (kNLayers * kNStacks); int trackletStack = (trackletDet % (kNLayers * kNStacks)) / kNLayers; + const GPUTRDSpacePoint* spacePoints = GetConstantMem()->ioPtrs.trdSpacePoints; + if (trackletSector != GetSector(prop->getAlpha())) { if (!prop->rotate(GetAlphaOfSector(trackletSector))) { GPUInfo("Track could not be rotated in tracklet coordinate system"); @@ -778,8 +755,8 @@ GPUd() int GPUTRDTracker_t::PropagateToLayerAndUpdate(PROP* prop, } } - if (!prop->propagateToX(mSpacePoints[trackletID].mR, .8f, 2.f)) { - GPUInfo("Track propagation failed in layer %i (pt=%f, xTrk=%f, xToGo=%f)", iLayer, trkWork->getPt(), trkWork->getX(), mSpacePoints[trackletID].mR); + if (!prop->propagateToX(spacePoints[trackletID].getX(), .8f, 2.f)) { + GPUInfo("Track propagation failed in layer %i (pt=%f, xTrk=%f, xToGo=%f)", iLayer, trkWork->getPt(), trkWork->getX(), spacePoints[trackletID].getX()); return 2; } @@ -790,16 +767,16 @@ GPUd() int GPUTRDTracker_t::PropagateToLayerAndUpdate(PROP* prop, const GPUTRDpadPlane* pad = mGeo->GetPadPlane(iLayer, trackletStack); float tilt = CAMath::Tan(CAMath::Pi() / 180.f * pad->GetTiltingAngle()); // tilt is signed! - float tiltCorrUp = tilt * (mSpacePoints[trackletID].mX[1] - trkWork->getZ()); - float zPosCorrUp = mSpacePoints[trackletID].mX[1] + mZCorrCoefNRC * trkWork->getTgl(); - float padLength = pad->GetRowSize(mTracklets[trackletID].GetZbin()); - if (!((trkWork->getSigmaZ2() < (padLength * padLength / 12.f)) && (CAMath::Abs(mSpacePoints[trackletID].mX[1] - trkWork->getZ()) < padLength))) { + float tiltCorrUp = tilt * (spacePoints[trackletID].getZ() - trkWork->getZ()); + float zPosCorrUp = spacePoints[trackletID].getZ() + mZCorrCoefNRC * trkWork->getTgl(); + float padLength = pad->GetRowSize(GetConstantMem()->ioPtrs.trdTracklets[trackletID].GetZbin()); + if (!((trkWork->getSigmaZ2() < (padLength * padLength / 12.f)) && (CAMath::Abs(spacePoints[trackletID].getZ() - trkWork->getZ()) < padLength))) { tiltCorrUp = 0.f; } - My_Float trkltPosUp[2] = {mSpacePoints[trackletID].mX[0] - tiltCorrUp, zPosCorrUp}; + My_Float trkltPosUp[2] = {spacePoints[trackletID].getY() - tiltCorrUp, zPosCorrUp}; My_Float trkltCovUp[3] = {0.f}; - RecalcTrkltCov(tilt, trkWork->getSnp(), pad->GetRowSize(mTracklets[trackletID].GetZbin()), trkltCovUp); + RecalcTrkltCov(tilt, trkWork->getSnp(), pad->GetRowSize(GetConstantMem()->ioPtrs.trdTracklets[trackletID].GetZbin()), trkltCovUp); if (!prop->update(trkltPosUp, trkltCovUp)) { GPUWarning("Failed to update track with space point in layer %i", iLayer); @@ -821,8 +798,10 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK mDebug->Reset(); int iTrack = t->GetTPCtrackId(); t->SetChi2(0.f); + t->setZShift((t->getTime() - GetConstantMem()->ioPtrs.trdTriggerTimes[collisionId]) * mTPCVdrift * t->getSide()); const GPUTRDpadPlane* pad = nullptr; - t->setZShift((t->getTime() - mTriggerRecordTimes[collisionId]) * mTPCVdrift * t->getSide()); + const GPUTRDTrackletWord* tracklets = GetConstantMem()->ioPtrs.trdTracklets; + const GPUTRDSpacePoint* spacePoints = GetConstantMem()->ioPtrs.trdSpacePoints; #ifdef ENABLE_GPUTRDDEBUG TRDTRK trackNoUp(*t); @@ -844,7 +823,7 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK int candidateIdxOffset = threadId * 2 * mNCandidates; int hypothesisIdxOffset = threadId * mNCandidates; int trkltIdxOffset = collisionId * (kNChambers + 1); // offset for accessing mTrackletIndexArray for given collision - int glbTrkltIdxOffset = (mProcessPerTimeFrame) ? mTriggerRecordIndices[collisionId] : 0; // offset of first tracklet in given collision in global tracklet array + int glbTrkltIdxOffset = (mProcessPerTimeFrame) ? GetConstantMem()->ioPtrs.trdTrackletIdxFirst[collisionId] : 0; // offset of first tracklet in given collision in global tracklet array auto trkWork = t; if (mNCandidates > 1) { @@ -902,7 +881,7 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK // rotate track in new sector in case of sector crossing if (!AdjustSector(prop, trkWork)) { if (ENABLE_INFO) { - GPUInfo("FollowProlongation: Adjusting sector failed for track %i candidate %i in layer %i", iTrack, iCandidate, iLayer); + GPUInfo("Adjusting sector failed for track %i candidate %i in layer %i", iTrack, iCandidate, iLayer); } continue; } @@ -919,7 +898,7 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK // if (CAMath::Abs(trkWork->getZ() + trkWork->getZShift()) - roadZ >= zMaxTRD) { if (ENABLE_INFO) { - GPUInfo("FollowProlongation: Track out of TRD acceptance with z=%f in layer %i (eta=%f)", trkWork->getZ() + trkWork->getZShift(), iLayer, trkWork->getEta()); + GPUInfo("Track out of TRD acceptance with z=%f in layer %i (eta=%f)", trkWork->getZ() + trkWork->getZShift(), iLayer, trkWork->getEta()); } continue; } @@ -941,40 +920,39 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK if (currSec != GetSector(prop->getAlpha())) { if (!prop->rotate(GetAlphaOfSector(currSec))) { if (ENABLE_WARNING) { - Warning("FollowProlongation", "Track could not be rotated in tracklet coordinate system"); + GPUWarning("Track could not be rotated in tracklet coordinate system"); } break; } } if (currSec != GetSector(prop->getAlpha())) { - Error("FollowProlongation", "Track is in sector %i and sector %i is searched for tracklets", GetSector(prop->getAlpha()), currSec); + GPUError("Track is in sector %i and sector %i is searched for tracklets", GetSector(prop->getAlpha()), currSec); continue; } // propagate track to radius of chamber if (!prop->propagateToX(mR[currDet], .8f, .2f)) { if (ENABLE_WARNING) { - Warning("FollowProlongation", "Track parameter for track %i, x=%f at chamber %i x=%f in layer %i cannot be retrieved", iTrack, trkWork->getX(), currDet, mR[currDet], iLayer); + GPUWarning("Track parameter for track %i, x=%f at chamber %i x=%f in layer %i cannot be retrieved", iTrack, trkWork->getX(), currDet, mR[currDet], iLayer); } } // first propagate track to x of tracklet for (int trkltIdx = glbTrkltIdxOffset + mTrackletIndexArray[trkltIdxOffset + currDet]; trkltIdx < glbTrkltIdxOffset + mTrackletIndexArray[trkltIdxOffset + currDet + 1]; ++trkltIdx) { - int trkltIdxGlb = mTrackletIndices[trkltIdx]; - if (CAMath::Abs(trkWork->getY() - mSpacePoints[trkltIdxGlb].mX[0]) > roadY || CAMath::Abs(trkWork->getZ() + trkWork->getZShift() - mSpacePoints[trkltIdxGlb].mX[1]) > roadZ) { + if (CAMath::Abs(trkWork->getY() - spacePoints[trkltIdx].getY()) > roadY || CAMath::Abs(trkWork->getZ() + trkWork->getZShift() - spacePoints[trkltIdx].getZ()) > roadZ) { // skip tracklets which are too far away // although the radii of space points and tracks may differ by ~ few mm the roads are large enough to allow no efficiency loss by this cut continue; } float projY, projZ; - prop->getPropagatedYZ(mSpacePoints[trkltIdxGlb].mR, projY, projZ); + prop->getPropagatedYZ(spacePoints[trkltIdx].getX(), projY, projZ); // correction for tilted pads (only applied if deltaZ < lPad && track z err << lPad) - float tiltCorr = tilt * (mSpacePoints[trkltIdxGlb].mX[1] - projZ); - float lPad = pad->GetRowSize(mTracklets[trkltIdxGlb].GetZbin()); - if (!((CAMath::Abs(mSpacePoints[trkltIdxGlb].mX[1] - projZ) < lPad) && (trkWork->getSigmaZ2() < (lPad * lPad / 12.f)))) { + float tiltCorr = tilt * (spacePoints[trkltIdx].getZ() - projZ); + float lPad = pad->GetRowSize(tracklets[trkltIdx].GetZbin()); + if (!((CAMath::Abs(spacePoints[trkltIdx].getZ() - projZ) < lPad) && (trkWork->getSigmaZ2() < (lPad * lPad / 12.f)))) { tiltCorr = 0.f; // will be zero also for TPC tracks which are shifted in z } // correction for mean z position of tracklet (is not the center of the pad if track eta != 0) - float zPosCorr = mSpacePoints[trkltIdxGlb].mX[1] + mZCorrCoefNRC * trkWork->getTgl(); - float yPosCorr = mSpacePoints[trkltIdxGlb].mX[0] - tiltCorr; + float zPosCorr = spacePoints[trkltIdx].getZ() + mZCorrCoefNRC * trkWork->getTgl(); + float yPosCorr = spacePoints[trkltIdx].getY() - tiltCorr; zPosCorr -= trkWork->getZShift(); // shift tracklet instead of track in order to avoid having to do a re-fit for each collision float deltaY = yPosCorr - projY; float deltaZ = zPosCorr - projZ; @@ -982,12 +960,11 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK My_Float trkltCovTmp[3] = {0.f}; if ((CAMath::Abs(deltaY) < roadY) && (CAMath::Abs(deltaZ) < roadZ)) { // TODO: check if this is still necessary after the cut before propagation of track // tracklet is in windwow: get predicted chi2 for update and store tracklet index if best guess - RecalcTrkltCov(tilt, trkWork->getSnp(), pad->GetRowSize(mTracklets[trkltIdxGlb].GetZbin()), trkltCovTmp); + RecalcTrkltCov(tilt, trkWork->getSnp(), pad->GetRowSize(tracklets[trkltIdx].GetZbin()), trkltCovTmp); float chi2 = prop->getPredictedChi2(trkltPosTmpYZ, trkltCovTmp); - // GPUInfo("layer %i: chi2 = %f", iLayer, chi2); // TODO cut on angular pull should be made stricter when proper v-drift calibration for the TRD tracklets is implemented - if (chi2 < Param().rec.trdMaxChi2 && CAMath::Abs(GetAngularPull(mSpacePoints[trkltIdxGlb].mDy, trkWork->getSnp())) < 4) { - Hypothesis hypo(trkWork->GetNlayers(), iCandidate, trkltIdxGlb, trkWork->GetChi2() + chi2); + if (chi2 < Param().rec.trdMaxChi2 && CAMath::Abs(GetAngularPull(spacePoints[trkltIdx].getDy(), trkWork->getSnp())) < 4) { + Hypothesis hypo(trkWork->GetNlayers(), iCandidate, trkltIdx, trkWork->GetChi2() + chi2); InsertHypothesis(hypo, nCurrHypothesis, hypothesisIdxOffset); } // end tracklet chi2 < Param().rec.trdMaxChi2 } // end tracklet in window @@ -1005,30 +982,30 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK if (matchAvailableAll[iLayer].size() > 0 && mDebugOutput) { mDebug->SetNmatchAvail(matchAvailableAll[iLayer].size(), iLayer); int realTrkltId = matchAvailableAll[iLayer].at(0); - int realTrkltDet = mTracklets[realTrkltId].GetDetector(); + int realTrkltDet = tracklets[realTrkltId].GetDetector(); pad = mGeo->GetPadPlane(realTrkltDet); prop->rotate(GetAlphaOfSector(mGeo->GetSector(realTrkltDet))); - if (!prop->propagateToX(mSpacePoints[realTrkltId].mR, .8f, 2.f) || GetSector(prop->getAlpha()) != mGeo->GetSector(realTrkltDet)) { + if (!prop->propagateToX(spacePoints[realTrkltId].getX(), .8f, 2.f) || GetSector(prop->getAlpha()) != mGeo->GetSector(realTrkltDet)) { if (ENABLE_WARNING) { - Warning("FollowProlongation", "Track parameter at x=%f for track %i at real tracklet x=%f in layer %i cannot be retrieved (pt=%f)", trkWork->getX(), iTrack, mSpacePoints[realTrkltId].mR, iLayer, trkWork->getPt()); + GPUWarning("Track parameter at x=%f for track %i at real tracklet x=%f in layer %i cannot be retrieved (pt=%f)", trkWork->getX(), iTrack, spacePoints[realTrkltId].getX(), iLayer, trkWork->getPt()); } } else { // track could be propagated, rotated and is in the same sector as the MC matching tracklet mDebug->SetTrackParameterReal(*trkWork, iLayer); - float zPosCorrReal = mSpacePoints[realTrkltId].mX[1] + mZCorrCoefNRC * trkWork->getTgl(); + float zPosCorrReal = spacePoints[realTrkltId].getZ() + mZCorrCoefNRC * trkWork->getTgl(); float deltaZReal = zPosCorrReal - trkWork->getZ(); - float tiltCorrReal = tilt * (mSpacePoints[realTrkltId].mX[1] - trkWork->getZ()); - float lPadReal = pad->GetRowSize(mTracklets[realTrkltId].GetZbin()); - if ((trkWork->getSigmaZ2() >= (lPadReal * lPadReal / 12.f)) || (CAMath::Abs(mSpacePoints[realTrkltId].mX[1] - trkWork->getZ()) >= lPadReal)) { + float tiltCorrReal = tilt * (spacePoints[realTrkltId].getZ() - trkWork->getZ()); + float lPadReal = pad->GetRowSize(tracklets[realTrkltId].GetZbin()); + if ((trkWork->getSigmaZ2() >= (lPadReal * lPadReal / 12.f)) || (CAMath::Abs(spacePoints[realTrkltId].getZ() - trkWork->getZ()) >= lPadReal)) { tiltCorrReal = 0; } - My_Float yzPosReal[2] = {mSpacePoints[realTrkltId].mX[0] - tiltCorrReal, zPosCorrReal}; + My_Float yzPosReal[2] = {spacePoints[realTrkltId].getY() - tiltCorrReal, zPosCorrReal}; My_Float covReal[3] = {0.}; - RecalcTrkltCov(tilt, trkWork->getSnp(), pad->GetRowSize(mTracklets[realTrkltId].GetZbin()), covReal); + RecalcTrkltCov(tilt, trkWork->getSnp(), pad->GetRowSize(tracklets[realTrkltId].GetZbin()), covReal); mDebug->SetChi2Real(prop->getPredictedChi2(yzPosReal, covReal), iLayer); - mDebug->SetRawTrackletPositionReal(mSpacePoints[realTrkltId].mR, mSpacePoints[realTrkltId].mX, iLayer); + mDebug->SetRawTrackletPositionReal(spacePoints[realTrkltId].getX(), spacePoints[realTrkltId].getY(), spacePoints[realTrkltId].getZ(), iLayer); mDebug->SetCorrectedTrackletPositionReal(yzPosReal, iLayer); - mDebug->SetTrackletPropertiesReal(mTracklets[realTrkltId].GetDetector(), iLayer); + mDebug->SetTrackletPropertiesReal(tracklets[realTrkltId].GetDetector(), iLayer); } } #endif @@ -1048,7 +1025,7 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK // no more candidates if (iUpdate == 0) { if (ENABLE_WARNING) { - Warning("FollowProlongation", "No valid candidates for track %i in layer %i", iTrack, iLayer); + GPUWarning("No valid candidates for track %i in layer %i", iTrack, iLayer); } nCandidates = 0; } @@ -1076,14 +1053,14 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK if (mNCandidates > 1) { prop->setTrack(trkWork); } - int trkltSec = mGeo->GetSector(mTracklets[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].GetDetector()); + int trkltSec = mGeo->GetSector(tracklets[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].GetDetector()); if (trkltSec != GetSector(prop->getAlpha())) { // if after a matching tracklet was found another sector was searched for tracklets the track needs to be rotated back prop->rotate(GetAlphaOfSector(trkltSec)); } - if (!prop->propagateToX(mSpacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].mR, .8f, 2.f)) { + if (!prop->propagateToX(spacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].getX(), .8f, 2.f)) { if (ENABLE_WARNING) { - Warning("FollowProlongation", "Final track propagation for track %i update %i in layer %i failed", iTrack, iUpdate, iLayer); + GPUWarning("Final track propagation for track %i update %i in layer %i failed", iTrack, iUpdate, iLayer); } trkWork->SetChi2(trkWork->GetChi2() + Param().rec.trdPenaltyChi2); if (trkWork->GetIsFindable(iLayer)) { @@ -1097,23 +1074,23 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK continue; } - pad = mGeo->GetPadPlane(mTracklets[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].GetDetector()); - float tiltCorrUp = tilt * (mSpacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].mX[1] - trkWork->getZ()); - float zPosCorrUp = mSpacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].mX[1] + mZCorrCoefNRC * trkWork->getTgl(); + pad = mGeo->GetPadPlane(tracklets[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].GetDetector()); + float tiltCorrUp = tilt * (spacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].getZ() - trkWork->getZ()); + float zPosCorrUp = spacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].getZ() + mZCorrCoefNRC * trkWork->getTgl(); zPosCorrUp -= trkWork->getZShift(); - float padLength = pad->GetRowSize(mTracklets[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].GetZbin()); - if (!((trkWork->getSigmaZ2() < (padLength * padLength / 12.f)) && (CAMath::Abs(mSpacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].mX[1] - trkWork->getZ()) < padLength))) { + float padLength = pad->GetRowSize(tracklets[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].GetZbin()); + if (!((trkWork->getSigmaZ2() < (padLength * padLength / 12.f)) && (CAMath::Abs(spacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].getZ() - trkWork->getZ()) < padLength))) { tiltCorrUp = 0.f; } - My_Float trkltPosUp[2] = {mSpacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].mX[0] - tiltCorrUp, zPosCorrUp}; + My_Float trkltPosUp[2] = {spacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].getY() - tiltCorrUp, zPosCorrUp}; My_Float trkltCovUp[3] = {0.f}; - RecalcTrkltCov(tilt, trkWork->getSnp(), pad->GetRowSize(mTracklets[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].GetZbin()), trkltCovUp); + RecalcTrkltCov(tilt, trkWork->getSnp(), pad->GetRowSize(tracklets[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].GetZbin()), trkltCovUp); #ifdef ENABLE_GPUTRDDEBUG prop->setTrack(&trackNoUp); prop->rotate(GetAlphaOfSector(trkltSec)); - //prop->propagateToX(mSpacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].mR, .8f, 2.f); - prop->propagateToX(mR[mTracklets[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].GetDetector()], .8f, 2.f); + //prop->propagateToX(spacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].getX(), .8f, 2.f); + prop->propagateToX(mR[tracklets[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].GetDetector()], .8f, 2.f); prop->setTrack(trkWork); #endif @@ -1122,16 +1099,16 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK mDebug->SetTrackParameterNoUp(trackNoUp, iLayer); #endif mDebug->SetTrackParameter(*trkWork, iLayer); - mDebug->SetRawTrackletPosition(mSpacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].mR, mSpacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].mX, iLayer); + mDebug->SetRawTrackletPosition(spacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].getX(), spacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].getY(), spacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].getZ(), iLayer); mDebug->SetCorrectedTrackletPosition(trkltPosUp, iLayer); mDebug->SetTrackletCovariance(trkltCovUp, iLayer); - mDebug->SetTrackletProperties(mSpacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].mDy, mTracklets[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].GetDetector(), iLayer); + mDebug->SetTrackletProperties(spacePoints[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].getDy(), tracklets[mHypothesis[iUpdate + hypothesisIdxOffset].mTrackletId].GetDetector(), iLayer); wasTrackStored = true; } if (!prop->update(trkltPosUp, trkltCovUp)) { if (ENABLE_WARNING) { - Warning("FollowProlongation", "Failed to update track %i with space point in layer %i", iTrack, iLayer); + GPUWarning("Failed to update track %i with space point in layer %i", iTrack, iLayer); } trkWork->SetChi2(trkWork->GetChi2() + Param().rec.trdPenaltyChi2); if (trkWork->GetIsFindable(iLayer)) { @@ -1146,7 +1123,7 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK } if (!trkWork->CheckNumericalQuality()) { if (ENABLE_INFO) { - GPUInfo("FollowProlongation: Track %i has invalid covariance matrix. Aborting track following\n", iTrack); + GPUInfo("Track %i has invalid covariance matrix. Aborting track following\n", iTrack); } return false; } @@ -1160,7 +1137,7 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK if (!isOK) { if (ENABLE_INFO) { - GPUInfo("FollowProlongation: Track %i cannot be followed. Stopped in layer %i", iTrack, iLayer); + GPUInfo("Track %i cannot be followed. Stopped in layer %i", iTrack, iLayer); } return false; } @@ -1241,8 +1218,9 @@ GPUd() bool GPUTRDTracker_t::FollowProlongation(PROP* prop, TRDTRK mDebug->SetUpdates(update); mDebug->Output(); } - //GPUInfo("Ended track following for track %i at x=%f with pt=%f", t->GetTPCtrackId(), t->getX(), t->getPt()); - //GPUInfo("Attached %i tracklets", t->GetNtracklets()); + if (ENABLE_INFO) { + GPUInfo("Ended track following for track %i at x=%f with pt=%f. Attached %i tracklets", t->GetTPCtrackId(), t->getX(), t->getPt(), t->GetNtracklets()); + } return true; } @@ -1524,18 +1502,6 @@ GPUd() bool GPUTRDTracker_t::IsGeoFindable(const TRDTRK* t, const return true; } -template -GPUd() void GPUTRDTracker_t::SetNCollisions(int nColl) -{ - // Set the number of collisions for a given time frame. - // The number is taken from the TRD trigger records - if (nColl < mNMaxCollisions) { - mNCollisions = nColl; - } else { - GPUError("Cannot process more than %i collisions. The last %i collisions will be dropped", mNMaxCollisions, nColl - mNMaxCollisions); - mNCollisions = mNMaxCollisions; - } -} #ifndef GPUCA_GPUCODE namespace GPUCA_NAMESPACE diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h index 5a163a5b484ac..b9f45e541a89a 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h @@ -21,6 +21,7 @@ #include "GPUTRDDef.h" #include "GPUDef.h" #include "GPUTRDTrack.h" +#include "GPUTRDSpacePoint.h" #include "GPULogging.h" #ifndef GPUCA_GPUCODE_DEVICE @@ -78,23 +79,10 @@ class GPUTRDTracker_t : public GPUProcessor kNSectors = 18, kNChambers = 540 }; - // struct to hold the information on the space points - struct GPUTRDSpacePointInternal { - float mR; // x position (3.5 mm above anode wires) - radial offset due to t0 mis-calibration, measured -1 mm for run 245353 - float mX[2]; // y and z position (sector coordinates) - float mDy; // deflection over drift length - unsigned short mVolumeId; // basically derived from TRD chamber number - GPUd() GPUTRDSpacePointInternal(float x, float y, float z, float dy) : mR(x), mDy(dy), mVolumeId(0) - { - mX[0] = y; - mX[1] = z; - } - }; - struct Hypothesis { int mLayers; // number of layers with TRD space point int mCandidateId; // to which track candidate the hypothesis belongs - int mTrackletId; // tracklet index to be used for update (global index within mTracklets array) + int mTrackletId; // tracklet index to be used for update (global index within tracklet array) float mChi2; // predicted chi2 for given space point GPUd() float GetReducedChi2() { return mLayers > 0 ? mChi2 / mLayers : mChi2; } @@ -108,7 +96,6 @@ class GPUTRDTracker_t : public GPUProcessor GPUhd() void OverrideGPUGeometry(TRD_GEOMETRY_CONST GPUTRDGeometry* geo) { mGeo = geo; } void Reset(); - GPUd() int LoadTracklet(const GPUTRDTrackletWord& tracklet, const int* labels = nullptr); template GPUd() bool PreCheckTrackTRDCandidate(const T& trk) const { @@ -120,7 +107,7 @@ class GPUTRDTracker_t : public GPUProcessor GPUd() int GetCollisionIDs(TRDTRK& trk, int* collisionIds) const; GPUd() void DoTrackingThread(int iTrk, int threadId = 0); - static GPUd() bool ConvertTrkltToSpacePoint(const GPUTRDGeometry& geo, GPUTRDTrackletWord& trklt, GPUTRDSpacePointInternal& sp); + static GPUd() bool ConvertTrkltToSpacePoint(const GPUTRDGeometry& geo, GPUTRDTrackletWord& trklt, GPUTRDSpacePoint& sp); GPUd() bool CalculateSpacePoints(int iCollision = 0); GPUd() bool FollowProlongation(PROP* prop, TRDTRK* t, int threadId, int collisionId); GPUd() int FillImpactAngleHistograms(PROP* prop, TRDTRK* t); @@ -140,16 +127,10 @@ class GPUTRDTracker_t : public GPUProcessor GPUd() bool IsGeoFindable(const TRDTRK* t, const int layer, const float alpha) const; GPUd() void InsertHypothesis(Hypothesis hypo, int& nCurrHypothesis, int idxOffset); - // input from TRD trigger record - GPUd() void SetNMaxCollisions(int nColl) { mNMaxCollisions = nColl; } // can this be fixed to a sufficiently large value? - GPUd() void SetNCollisions(int nColl); - GPUd() void SetTriggerRecordIndices(int* indices) { mTriggerRecordIndices = indices; } - GPUd() void SetTriggerRecordTimes(float* times) { mTriggerRecordTimes = times; } - GPUd() void SetInternalSpacePoint(int idx, float x, float y, float z, float dy) { mSpacePoints[idx] = GPUTRDSpacePointInternal(x, y, z, dy); } // settings - GPUd() void SetTrkltTransformNeeded(bool flag) { mTrkltTransfNeeded = flag; } - GPUd() void SetProcessPerTimeFrame() { mProcessPerTimeFrame = true; } + GPUd() void SetGenerateSpacePoints(bool flag) { mGenerateSpacePoints = flag; } + GPUd() void SetProcessPerTimeFrame(bool flag) { mProcessPerTimeFrame = flag; } GPUd() void SetDoImpactAngleHistograms(bool flag) { mDoImpactAngleHistograms = flag; } GPUd() void SetMCEvent(AliMCEvent* mc) { mMCEvent = mc; } GPUd() void EnableDebugOutput() { mDebugOutput = true; } @@ -167,12 +148,10 @@ class GPUTRDTracker_t : public GPUProcessor // output GPUd() int NTracks() const { return mNTracks; } + GPUd() GPUTRDSpacePoint* SpacePoints() const { return mSpacePoints; } GPUd() TRDTRK* Tracks() const { return mTracks; } - GPUd() int NTracklets() const { return mNTracklets; } - GPUd() GPUTRDSpacePointInternal* SpacePoints() const { return mSpacePoints; } GPUd() float* AngleDiffSums() const { return mAngleDiffSums; } GPUd() short* AngleDiffCounters() const { return mAngleDiffCounters; } - GPUd() GPUTRDTrackletWord* Tracklets() const { return mTracklets; } GPUd() void DumpTracks(); // utility @@ -181,7 +160,7 @@ class GPUTRDTracker_t : public GPUProcessor protected: float* mR; // radial position of each TRD chamber, alignment taken into account, radial spread within chambers < 7mm bool mIsInitialized; // flag is set upon initialization - bool mTrkltTransfNeeded; // if the output of the TRDTrackletTransformer is used we don't need to do the coordinate transformation for the tracklets + bool mGenerateSpacePoints; // if true, only tracklets are provided as input and they will be converted into space points by the tracker bool mProcessPerTimeFrame; // if true, tracking is done per time frame instead of on a single events basis bool mDoImpactAngleHistograms; // if true, impact angle vs angle difference histograms are filled short mNAngleHistogramBins; // number of bins per chamber for the angular difference histograms @@ -194,22 +173,16 @@ class GPUTRDTracker_t : public GPUProcessor int mNMaxSpacePoints; // max number of space points hold by the tracker (per event) TRDTRK* mTracks; // array of trd-updated tracks int mNCandidates; // max. track hypothesis per layer - int mNCollisions; // number of collisions with TRD tracklet data int mNTracks; // number of TPC tracks to be matched int mNEvents; // number of processed events - int* mTriggerRecordIndices; // index of first tracklet for each collision within mTracklets array - float* mTriggerRecordTimes; // time in us for each collision - GPUTRDTrackletWord* mTracklets; // array of all tracklets - int* mTrackletIndices; // indices of tracklets sorted by HCId (such that the input array mTracklets is kept const) int mMaxThreads; // maximum number of supported threads - int mNTracklets; // total number of tracklets in event - // index of first tracklet for each chamber within mTracklets array, last entry is total number of tracklets for given collision - // the array has (kNChambers + 1) * mNCollisions entries - // note, that for collision iColl one has to add an offset of mTriggerRecordIndices[iColl] to the index stored in mTrackletIndexArray + // index of first tracklet for each chamber within tracklets array, last entry is total number of tracklets for given collision + // the array has (kNChambers + 1) * numberOfCollisions entries + // note, that for collision iColl one has to add an offset corresponding to the index of the first tracklet of iColl to the index stored in mTrackletIndexArray int* mTrackletIndexArray; Hypothesis* mHypothesis; // array with multiple track hypothesis TRDTRK* mCandidates; // array of tracks for multiple hypothesis tracking - GPUTRDSpacePointInternal* mSpacePoints; // array with tracklet coordinates in global tracking frame + GPUTRDSpacePoint* mSpacePoints; // array with tracklet coordinates in global tracking frame float* mAngleDiffSums; // array with sum of angular differences for a given bin short* mAngleDiffCounters; // array with number of entries for a given bin int* mTrackletLabels; // array with MC tracklet labels diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTrackerComponent.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTrackerComponent.cxx index 7b0deb9ca597a..31cd0c0110bcc 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTrackerComponent.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTrackerComponent.cxx @@ -25,6 +25,7 @@ #include "GPUTRDTracker.h" #include "GPUTRDTrack.h" #include "GPUTRDTrackerComponent.h" +#include "GPUTRDSpacePoint.h" #include "GPUTRDTrackletWord.h" #include "GPUTRDTrackletLabels.h" #include "AliHLTTRDDefinitions.h" @@ -257,9 +258,9 @@ int GPUTRDTrackerComponent::DoEvent(const AliHLTComponentEventData& evtData, con int nBlocks = evtData.fBlockCnt; - AliHLTTracksData* tpcData = nullptr; - AliHLTTracksData* itsData = nullptr; - AliHLTTrackMCData* tpcDataMC = nullptr; + const AliHLTTracksData* tpcData = nullptr; + const AliHLTTracksData* itsData = nullptr; + const AliHLTTrackMCData* tpcDataMC = nullptr; std::vector tracksTPC; std::vector tracksTPCLab; @@ -269,26 +270,26 @@ int GPUTRDTrackerComponent::DoEvent(const AliHLTComponentEventData& evtData, con int nTrackletsTotal = 0; int nTrackletsTotalMC = 0; - GPUTRDTrackletWord* tracklets = nullptr; - GPUTRDTrackletLabels* trackletsMC = nullptr; + const GPUTRDTrackletWord* tracklets = nullptr; + const GPUTRDTrackletLabels* trackletsMC = nullptr; for (int iBlock = 0; iBlock < nBlocks; iBlock++) { if (blocks[iBlock].fDataType == (kAliHLTDataTypeTrack | kAliHLTDataOriginITS) && fRequireITStrack) { - itsData = (AliHLTTracksData*)blocks[iBlock].fPtr; + itsData = (const AliHLTTracksData*)blocks[iBlock].fPtr; fBenchmark.AddInput(blocks[iBlock].fSize); } else if (blocks[iBlock].fDataType == (AliHLTTPCDefinitions::TracksOuterDataType() | kAliHLTDataOriginTPC)) { - tpcData = (AliHLTTracksData*)blocks[iBlock].fPtr; + tpcData = (const AliHLTTracksData*)blocks[iBlock].fPtr; fBenchmark.AddInput(blocks[iBlock].fSize); } else if (blocks[iBlock].fDataType == (kAliHLTDataTypeTrackMC | kAliHLTDataOriginTPC)) { - tpcDataMC = (AliHLTTrackMCData*)blocks[iBlock].fPtr; + tpcDataMC = (const AliHLTTrackMCData*)blocks[iBlock].fPtr; fBenchmark.AddInput(blocks[iBlock].fSize); } else if (blocks[iBlock].fDataType == (AliHLTTRDDefinitions::fgkTRDTrackletDataType)) { - tracklets = reinterpret_cast(blocks[iBlock].fPtr); + tracklets = reinterpret_cast(blocks[iBlock].fPtr); nTrackletsTotal = blocks[iBlock].fSize / sizeof(GPUTRDTrackletWord); fBenchmark.AddInput(blocks[iBlock].fSize); } else if (blocks[iBlock].fDataType == (AliHLTTRDDefinitions::fgkTRDMCTrackletDataType)) { hasMCtracklets = true; - trackletsMC = reinterpret_cast(blocks[iBlock].fPtr); + trackletsMC = reinterpret_cast(blocks[iBlock].fPtr); nTrackletsTotalMC = blocks[iBlock].fSize / sizeof(GPUTRDTrackletLabels); fBenchmark.AddInput(blocks[iBlock].fSize); } @@ -309,12 +310,18 @@ int GPUTRDTrackerComponent::DoEvent(const AliHLTComponentEventData& evtData, con return -EINVAL; } + // copy tracklets into temporary vector to allow for sorting them (the input array is const) + std::vector trackletsTmp(nTrackletsTotal); + for (int iTrklt = 0; iTrklt < nTrackletsTotal; ++iTrklt) { + trackletsTmp[iTrklt] = tracklets[iTrklt]; + } + int nTPCtracks = tpcData->fCount; std::vector itsAvail(nTPCtracks, false); if (itsData) { // look for ITS tracks with >= 2 hits int nITStracks = itsData->fCount; - AliHLTExternalTrackParam* currITStrack = itsData->fTracklets; + const AliHLTExternalTrackParam* currITStrack = itsData->fTracklets; for (int iTrkITS = 0; iTrkITS < nITStracks; iTrkITS++) { if (currITStrack->fNPoints >= 2) { itsAvail.at(currITStrack->fTrackID) = true; @@ -328,11 +335,11 @@ int GPUTRDTrackerComponent::DoEvent(const AliHLTComponentEventData& evtData, con // look for TPC track MC labels int nMCtracks = tpcDataMC->fCount; for (int iMC = 0; iMC < nMCtracks; iMC++) { - AliHLTTrackMCLabel& lab = tpcDataMC->fLabels[iMC]; + const AliHLTTrackMCLabel& lab = tpcDataMC->fLabels[iMC]; mcLabels[lab.fTrackID] = lab.fMCLabel; } } - AliHLTExternalTrackParam* currOutTrackTPC = tpcData->fTracklets; + const AliHLTExternalTrackParam* currOutTrackTPC = tpcData->fTracklets; for (int iTrk = 0; iTrk < nTPCtracks; iTrk++) { // store TPC tracks (if required only the ones with >=2 ITS hits) if (itsData != nullptr && !itsAvail.at(currOutTrackTPC->fTrackID)) { @@ -356,37 +363,29 @@ int GPUTRDTrackerComponent::DoEvent(const AliHLTComponentEventData& evtData, con HLTInfo("TRDTrackerComponent received %i tracklets\n", nTrackletsTotal); } + fTracker->SetGenerateSpacePoints(true); fTracker->Reset(); fChain->mIOPtrs.nMergedTracks = tracksTPC.size(); fChain->mIOPtrs.nTRDTracklets = nTrackletsTotal; - fChain->AllocateIOMemory(); + fChain->mIOPtrs.nTRDTriggerRecords = 1; fRec->PrepareEvent(); fRec->SetupGPUProcessor(fTracker, true); - // loop over all tracklets - for (int iTracklet = 0; iTracklet < nTrackletsTotal; ++iTracklet) { - if (!hasMCtracklets) { - if (fTracker->LoadTracklet(tracklets[iTracklet])) { - return -EINVAL; - } - } else { - if (fTracker->LoadTracklet(tracklets[iTracklet], trackletsMC[iTracklet].mLabel)) { - return -EINVAL; - } - } - } + std::sort(trackletsTmp.begin(), trackletsTmp.end()); + fChain->mIOPtrs.trdTracklets = &(trackletsTmp[0]); + // loop over all tracks for (unsigned int iTrack = 0; iTrack < tracksTPC.size(); ++iTrack) { fTracker->LoadTrack(tracksTPC[iTrack], tracksTPCLab[iTrack]); } fBenchmark.Start(1); - fTracker->DoTracking(NULL); + fTracker->DoTracking(fChain); fBenchmark.Stop(1); GPUTRDTrackGPU* trackArray = fTracker->Tracks(); int nTracks = fTracker->NTracks(); - GPUTRDTrackerGPU::GPUTRDSpacePointInternal* spacePoints = fTracker->SpacePoints(); + GPUTRDSpacePoint* spacePoints = fTracker->SpacePoints(); // TODO delete fTrackList since it only works for TObjects (or use compiler flag after tests with GPU track type) // for (int iTrack=0; iTrackfPoints[i]; - currOutPoint->fX[0] = sp.mR; // x in sector coordinates - currOutPoint->fX[1] = sp.mX[0]; // y in sector coordinates - currOutPoint->fX[2] = sp.mX[1]; // z in sector coordinates - currOutPoint->fVolumeId = sp.mVolumeId; + currOutPoint->fX[0] = sp.getX(); // x in sector coordinates + currOutPoint->fX[1] = sp.getY(); // y in sector coordinates + currOutPoint->fX[2] = sp.getZ(); // z in sector coordinates + int detId = trackletsTmp[i].GetDetector(); + int layer = detId % 6; // TRD layer number for given detector + int modId = (detId / 18) * 5 + ((detId % 30) / 6); // global TRD stack number [0..89] + int volId = (UShort_t(9 + layer) << 11) | UShort_t(modId); // taken from AliGeomManager::LayerToVolUID(). AliGeomManager::ELayerID(AliGeomManager::kTRD1) == 9 + currOutPoint->fVolumeId = volId; } AliHLTComponentBlockData resultDataSP; FillBlockData(resultDataSP); diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTrackerDebug.h b/GPU/GPUTracking/TRDTracking/GPUTRDTrackerDebug.h index 08b453d4f2345..e7a680e4d4030 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTrackerDebug.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTrackerDebug.h @@ -244,11 +244,11 @@ class GPUTRDTrackerDebug } // tracklet parameters - void SetRawTrackletPosition(const float fX, const float* fYZ, int ly) + void SetRawTrackletPosition(const float fX, const float fY, const float fZ, int ly) { fTrackletX(ly) = fX; - fTrackletY(ly) = fYZ[0]; - fTrackletZ(ly) = fYZ[1]; + fTrackletY(ly) = fY; + fTrackletZ(ly) = fZ; } void SetCorrectedTrackletPosition(const My_Float* fYZ, int ly) { @@ -266,11 +266,11 @@ class GPUTRDTrackerDebug fTrackletDy(ly) = dy; fTrackletDet(ly) = det; } - void SetRawTrackletPositionReal(float fX, float* fYZ, int ly) + void SetRawTrackletPositionReal(float fX, float fY, float fZ, int ly) { fTrackletXReal(ly) = fX; - fTrackletYReal(ly) = fYZ[0]; - fTrackletZReal(ly) = fYZ[1]; + fTrackletYReal(ly) = fY; + fTrackletZReal(ly) = fZ; } void SetCorrectedTrackletPositionReal(My_Float* fYZ, int ly) { @@ -490,11 +490,11 @@ class GPUTRDTrackerDebug GPUd() void SetTrack(const T& trk) {} // tracklet parameters - GPUd() void SetRawTrackletPosition(const float fX, const float* fYZ, int ly) {} + GPUd() void SetRawTrackletPosition(const float fX, const float fY, const float fZ, int ly) {} GPUd() void SetCorrectedTrackletPosition(const My_Float* fYZ, int ly) {} GPUd() void SetTrackletCovariance(const My_Float* fCov, int ly) {} GPUd() void SetTrackletProperties(const float dy, const int det, int ly) {} - GPUd() void SetRawTrackletPositionReal(float fX, float* fYZ, int ly) {} + GPUd() void SetRawTrackletPositionReal(float fX, float fY, float fZ, int ly) {} GPUd() void SetCorrectedTrackletPositionReal(My_Float* fYZ, int ly) {} GPUd() void SetTrackletPropertiesReal(const int det, int ly) {} diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTrackletWord.h b/GPU/GPUTracking/TRDTracking/GPUTRDTrackletWord.h index d5901182f2e5a..4ce30cff4c4a5 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTrackletWord.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTrackletWord.h @@ -101,8 +101,14 @@ class GPUTRDTrackletWord : private o2::trd::Tracklet64 GPUd() float GetdY() const { return getUncalibratedDy(); } GPUd() int GetDetector() const { return getDetector(); } GPUd() int GetHCId() const { return getHCID(); } + + // IMPORTANT: Do not add members, this class must keep the same memory layout as o2::trd::Tracklet64 }; +#ifdef GPUCA_NOCOMPAT +static_assert(sizeof(GPUTRDTrackletWord) == sizeof(o2::trd::Tracklet64), "Incorrect memory layout"); +#endif + } // namespace gpu } // namespace GPUCA_NAMESPACE diff --git a/GPU/GPUTracking/TRDTracking/macros/run_trd_tracker.C b/GPU/GPUTracking/TRDTracking/macros/run_trd_tracker.C index c6dcf50f8eb6b..c06418202cadc 100644 --- a/GPU/GPUTracking/TRDTracking/macros/run_trd_tracker.C +++ b/GPU/GPUTracking/TRDTracking/macros/run_trd_tracker.C @@ -23,20 +23,13 @@ #include "ReconstructionDataFormats/TrackTPCITS.h" #include "DataFormatsTRD/Tracklet64.h" #include "DataFormatsTRD/TriggerRecord.h" +#include "TPCBase/ParameterElectronics.h" +#include "TPCBase/ParameterGas.h" #endif using namespace GPUCA_NAMESPACE::gpu; -unsigned int convertTrkltWordToRun2Format(uint64_t trkltWordRun3) -{ - // FIXME: this is currently a dummy function - // need proper functionality to convert the new tracklet data format to - // something compatible with the TRD tracker, but this macro is probably - // not the right place for this - unsigned int trkltWord = 0; - return trkltWord; -} void run_trd_tracker(std::string path = "./", std::string inputTracks = "o2match_itstpc.root", @@ -56,8 +49,13 @@ void run_trd_tracker(std::string path = "./", const o2::trd::GeometryFlat geoFlat(*geo); //-------- init GPU reconstruction --------// + // different settings are defined in GPUSettingsList.h GPUSettingsGRP cfgGRP; // defaults should be ok - GPUSettingsRec cfgRec; // don't care for now, NWaysOuter is set in here for instance + GPUSettingsRec cfgRec; // settings concerning reconstruction + cfgRec.trdMinTrackPt = .5f; + cfgRec.trdMaxChi2 = 15.f; + cfgRec.trdPenaltyChi2 = 12.f; + cfgRec.trdStopTrkAfterNMissLy = 6; GPUSettingsProcessing cfgDeviceProcessing; // also keep defaults here, or adjust debug level cfgDeviceProcessing.debugLevel = 5; GPURecoStepConfiguration cfgRecoStep; @@ -72,7 +70,7 @@ void run_trd_tracker(std::string path = "./", auto tracker = new GPUTRDTracker(); tracker->SetNCandidates(1); // must be set before initialization tracker->SetProcessPerTimeFrame(); - tracker->SetNMaxCollisions(100); + tracker->SetGenerateSpacePoints(true); rec->RegisterGPUProcessor(tracker, false); chainTracking->SetTRDGeometry(&geoFlat); @@ -80,13 +78,15 @@ void run_trd_tracker(std::string path = "./", printf("ERROR: GPUReconstruction not initialized\n"); } + auto& elParam = o2::tpc::ParameterElectronics::Instance(); + auto& gasParam = o2::tpc::ParameterGas::Instance(); + auto tpcTBinMUS = elParam.ZbinWidth; + auto tpcVdrift = gasParam.DriftV; + tracker->SetTPCVdrift(tpcVdrift); + // configure the tracker //tracker->EnableDebugOutput(); //tracker->StartDebugging(); - tracker->SetPtThreshold(0.5); - tracker->SetChi2Threshold(15); - tracker->SetChi2Penalty(12); - tracker->SetStopTrkFollowingAfterNMissingLayers(6); tracker->PrintSettings(); // load input tracks @@ -116,8 +116,8 @@ void run_trd_tracker(std::string path = "./", for (int iEv = 0; iEv < nCollisions; ++iEv) { o2::trd::TriggerRecord& trg = triggerRecordsInArrayPtr->at(iEv); - int nTrackletsCurrent = trg.getNumberOfObjects(); - int iFirstTracklet = trg.getFirstEntry(); + int nTrackletsCurrent = trg.getNumberOfTracklets(); + int iFirstTracklet = trg.getFirstTracklet(); int64_t evTime = trg.getBCData().toLong() * o2::constants::lhc::LHCBunchSpacingNS; // event time in ns trdTriggerTimes.push_back(evTime / 1000.); trdTriggerIndices.push_back(iFirstTracklet); @@ -128,43 +128,21 @@ void run_trd_tracker(std::string path = "./", chainTracking->mIOPtrs.nMergedTracks = nTracks; chainTracking->mIOPtrs.nTRDTracklets = nTracklets; - chainTracking->AllocateIOMemory(); + chainTracking->mIOPtrs.trdTriggerTimes = &(trdTriggerTimes[0]); + chainTracking->mIOPtrs.trdTrackletIdxFirst = &(trdTriggerIndices[0]); + chainTracking->mIOPtrs.nTRDTriggerRecords = nCollisions; + chainTracking->mIOPtrs.trdTracklets = reinterpret_cast(trackletsInArrayPtr->data()); + rec->PrepareEvent(); rec->SetupGPUProcessor(tracker, true); - printf("Start loading input into TRD tracker\n"); + printf("Start loading input tracks into TRD tracker\n"); // load everything into the tracker - for (int iTrk = 0; iTrk < nTracks; ++iTrk) { - const auto& match = (*tracksInArrayPtr)[iTrk]; - const auto& trk = match.getParamOut(); - GPUTRDTrack trkLoad; - trkLoad.setX(trk.getX()); - trkLoad.setAlpha(trk.getAlpha()); - for (int i = 0; i < 5; ++i) { - trkLoad.setParam(trk.getParam(i), i); - } - for (int i = 0; i < 15; ++i) { - trkLoad.setCov(trk.getCov()[i], i); - } - trkLoad.setTime(match.getTimeMUS().getTimeStamp()); + for (const auto& trkITSTPC : *tracksInArrayPtr) { + GPUTRDTrack trkLoad(trkITSTPC, tpcVdrift); tracker->LoadTrack(trkLoad); - printf("Loaded track %i with time %f\n", iTrk, trkLoad.getTime()); } - for (int iTrklt = 0; iTrklt < nTracklets; ++iTrklt) { - auto trklt = trackletsInArrayPtr->at(iTrklt); - unsigned int trkltWord = convertTrkltWordToRun2Format(trklt.getTrackletWord()); - GPUTRDTrackletWord trkltLoad; - trkltLoad.SetId(iTrklt); - trkltLoad.SetHCId(trklt.getHCID()); - trkltLoad.SetTrackletWord(trkltWord); - if (tracker->LoadTracklet(trkltLoad) > 0) { - printf("Could not load tracklet %i\n", iTrklt); - } - } - tracker->SetTriggerRecordTimes(&(trdTriggerTimes[0])); - tracker->SetTriggerRecordIndices(&(trdTriggerIndices[0])); - tracker->SetNCollisions(nCollisions); tracker->DumpTracks(); tracker->DoTracking(chainTracking); tracker->DumpTracks(); diff --git a/GPU/GPUTracking/display/GPUDisplay.cxx b/GPU/GPUTracking/display/GPUDisplay.cxx index 3e40c7db47723..d9cc7a780367e 100644 --- a/GPU/GPUTracking/display/GPUDisplay.cxx +++ b/GPU/GPUTracking/display/GPUDisplay.cxx @@ -1399,10 +1399,10 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) GPUCA_OPENMP(parallel for num_threads(getNumThreads()) reduction(max : mMaxClusterZ)) for (int i = 0; i < mCurrentSpacePointsTRD; i++) { - const auto& sp = trdTracker().SpacePoints()[i]; + const auto& sp = mIOPtrs->trdSpacePoints[i]; int iSec = trdGeometry().GetSector(mIOPtrs->trdTracklets[i].GetDetector()); float4* ptr = &mGlobalPosTRD[i]; - mParam->Slice2Global(iSec, sp.mR + mXadd, sp.mX[0], sp.mX[1], &ptr->x, &ptr->y, &ptr->z); + mParam->Slice2Global(iSec, sp.getX() + mXadd, sp.getY(), sp.getZ(), &ptr->x, &ptr->y, &ptr->z); ptr->x /= GL_SCALE_FACTOR; ptr->y /= GL_SCALE_FACTOR; ptr->z /= GL_SCALE_FACTOR; @@ -1411,7 +1411,7 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) } ptr->w = tTRDCLUSTER; ptr = &mGlobalPosTRD2[i]; - mParam->Slice2Global(iSec, sp.mR + mXadd + 4.5f, sp.mX[0] + 1.5f * sp.mDy, sp.mX[1], &ptr->x, &ptr->y, &ptr->z); + mParam->Slice2Global(iSec, sp.getX() + mXadd + 4.5f, sp.getY() + 1.5f * sp.getDy(), sp.getZ(), &ptr->x, &ptr->y, &ptr->z); ptr->x /= GL_SCALE_FACTOR; ptr->y /= GL_SCALE_FACTOR; ptr->z /= GL_SCALE_FACTOR; From 0d2624164467faeead57f01b9080d1dac6f00a88 Mon Sep 17 00:00:00 2001 From: shahoian Date: Mon, 3 May 2021 02:13:10 +0200 Subject: [PATCH 371/770] Fix in AODProducerWorkflowSpec: dont include 3d party code to profit from its aliases --- .../AODProducerWorkflowSpec.h | 4 +-- Detectors/AOD/src/AODProducerWorkflowSpec.cxx | 25 +++++++++++-------- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/Detectors/AOD/include/AODProducerWorkflow/AODProducerWorkflowSpec.h b/Detectors/AOD/include/AODProducerWorkflow/AODProducerWorkflowSpec.h index 206f3e687262f..0599ced4f6caa 100644 --- a/Detectors/AOD/include/AODProducerWorkflow/AODProducerWorkflowSpec.h +++ b/Detectors/AOD/include/AODProducerWorkflow/AODProducerWorkflowSpec.h @@ -18,11 +18,11 @@ #include "Framework/AnalysisHelpers.h" #include "Framework/DataProcessorSpec.h" #include "Framework/Task.h" -#include "GlobalTrackingWorkflow/PrimaryVertexingSpec.h" #include "TStopwatch.h" #include "CCDB/BasicCCDBManager.h" #include "Steer/MCKinematicsReader.h" #include "SimulationDataFormat/MCCompLabel.h" +#include "ReconstructionDataFormats/PrimaryVertex.h" #include #include @@ -179,7 +179,7 @@ class AODProducerWorkflowDPL : public Task uint64_t maxGlBC = 0; uint64_t minGlBC = INT64_MAX; - void findMinMaxBc(gsl::span& ft0RecPoints, gsl::span& primVertices, const std::vector& mcRecords); + void findMinMaxBc(gsl::span& ft0RecPoints, gsl::span& primVertices, const std::vector& mcRecords); uint64_t getTFNumber(uint64_t firstVtxGlBC, int runNumber); template diff --git a/Detectors/AOD/src/AODProducerWorkflowSpec.cxx b/Detectors/AOD/src/AODProducerWorkflowSpec.cxx index e9b54cd6b2971..dd164953b78ca 100644 --- a/Detectors/AOD/src/AODProducerWorkflowSpec.cxx +++ b/Detectors/AOD/src/AODProducerWorkflowSpec.cxx @@ -26,6 +26,8 @@ #include "GlobalTracking/MatchTOF.h" #include "GlobalTrackingWorkflow/PrimaryVertexingSpec.h" #include "ReconstructionDataFormats/TrackTPCITS.h" +#include "ReconstructionDataFormats/VtxTrackRef.h" +#include "ReconstructionDataFormats/VtxTrackIndex.h" #include "SimulationDataFormat/DigitizationContext.h" #include "SimulationDataFormat/MCTrack.h" #include "SimulationDataFormat/MCTruthContainer.h" @@ -37,11 +39,14 @@ using namespace o2::framework; using namespace o2::math_utils::detail; +using PVertex = o2::dataformats::PrimaryVertex; +using V2TRef = o2::dataformats::VtxTrackRef; +using GIndex = o2::dataformats::VtxTrackIndex; namespace o2::aodproducer { -void AODProducerWorkflowDPL::findMinMaxBc(gsl::span& ft0RecPoints, gsl::span& primVertices, const std::vector& mcRecords) +void AODProducerWorkflowDPL::findMinMaxBc(gsl::span& ft0RecPoints, gsl::span& primVertices, const std::vector& mcRecords) { for (auto& ft0RecPoint : ft0RecPoints) { uint64_t bc = ft0RecPoint.getInteractionRecord().orbit * o2::constants::lhc::LHCMaxBunches + ft0RecPoint.getInteractionRecord().bc; @@ -412,9 +417,9 @@ void AODProducerWorkflowDPL::run(ProcessingContext& pc) auto ft0ChData = pc.inputs().get>("ft0ChData"); auto ft0RecPoints = pc.inputs().get>("ft0RecPoints"); - auto primVer2TRefs = pc.inputs().get>("primVer2TRefs"); - auto primVerGIs = pc.inputs().get>("primVerGIs"); - auto primVertices = pc.inputs().get>("primVertices"); + auto primVer2TRefs = pc.inputs().get>("primVer2TRefs"); + auto primVerGIs = pc.inputs().get>("primVerGIs"); + auto primVertices = pc.inputs().get>("primVertices"); auto primVerLabels = pc.inputs().get>("primVerLabels"); auto tracksITS = pc.inputs().get>("trackITS"); auto tracksITSTPC = pc.inputs().get>("tracksITSTPC"); @@ -733,11 +738,11 @@ void AODProducerWorkflowDPL::run(ProcessingContext& pc) auto trackIndex = primVerGIs[start + ti]; const auto source = trackIndex.getSource(); // setting collisionID for tracks attached to vertices - if (source == o2::vertexing::GIndex::Source::TPC) { + if (source == GIndex::Source::TPC) { vCollRefsTPC[trackIndex.getIndex()] = collisionID; - } else if (source == o2::vertexing::GIndex::Source::ITS) { + } else if (source == GIndex::Source::ITS) { vCollRefsITS[trackIndex.getIndex()] = collisionID; - } else if (source == o2::vertexing::GIndex::Source::ITSTPC) { + } else if (source == GIndex::Source::ITSTPC) { vCollRefsTPCITS[trackIndex.getIndex()] = collisionID; } else { LOG(WARNING) << "Unsupported track type!"; @@ -799,7 +804,7 @@ void AODProducerWorkflowDPL::run(ProcessingContext& pc) uint16_t labelMask; if (mFillTracksITS) { - fillTracksTable(tracksITS, vCollRefsITS, tracksCursor, tracksCovCursor, tracksExtraCursor, o2::vertexing::GIndex::Source::ITS); + fillTracksTable(tracksITS, vCollRefsITS, tracksCursor, tracksCovCursor, tracksExtraCursor, GIndex::Source::ITS); for (auto& mcTruthITS : tracksITSMCTruth) { labelID = std::numeric_limits::max(); // TODO: fill label mask @@ -820,7 +825,7 @@ void AODProducerWorkflowDPL::run(ProcessingContext& pc) } if (mFillTracksTPC) { - fillTracksTable(tracksTPC, vCollRefsTPC, tracksCursor, tracksCovCursor, tracksExtraCursor, o2::vertexing::GIndex::Source::TPC); + fillTracksTable(tracksTPC, vCollRefsTPC, tracksCursor, tracksCovCursor, tracksExtraCursor, GIndex::Source::TPC); for (auto& mcTruthTPC : tracksTPCMCTruth) { labelID = std::numeric_limits::max(); // TODO: fill label mask @@ -841,7 +846,7 @@ void AODProducerWorkflowDPL::run(ProcessingContext& pc) } if (mFillTracksITSTPC) { - fillTracksTable(tracksITSTPC, vCollRefsTPCITS, tracksCursor, tracksCovCursor, tracksExtraCursor, o2::vertexing::GIndex::Source::ITSTPC); + fillTracksTable(tracksITSTPC, vCollRefsTPCITS, tracksCursor, tracksCovCursor, tracksExtraCursor, GIndex::Source::ITSTPC); for (int i = 0; i < tracksITSTPC.size(); i++) { const auto& trc = tracksITSTPC[i]; auto mcTruthITS = tracksITSMCTruth[trc.getRefITS()]; From fa0db762eba812c619cc6aa3f56cd6cfa91e27f8 Mon Sep 17 00:00:00 2001 From: shahoian Date: Mon, 3 May 2021 01:39:29 +0200 Subject: [PATCH 372/770] cosmic-matcher: use InputHelper, avoid global DataRequest var. --- .../src/CosmicsMatchingSpec.cxx | 18 ++++----- .../src/cosmics-match-workflow.cxx | 39 ++----------------- 2 files changed, 13 insertions(+), 44 deletions(-) diff --git a/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx index 7afa554a02ff1..247dc1253b406 100644 --- a/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/CosmicsMatchingSpec.cxx @@ -54,18 +54,17 @@ namespace o2 namespace globaltracking { -DataRequest dataRequestCosm; - class CosmicsMatchingSpec : public Task { public: - CosmicsMatchingSpec(bool useMC) : mUseMC(useMC) {} + CosmicsMatchingSpec(std::shared_ptr dr, bool useMC) : mDataRequest(dr), mUseMC(useMC) {} ~CosmicsMatchingSpec() override = default; void init(InitContext& ic) final; void run(ProcessingContext& pc) final; void endOfStream(framework::EndOfStreamContext& ec) final; private: + std::shared_ptr mDataRequest; o2::globaltracking::MatchCosmics mMatching; // matching engine bool mUseMC = true; TStopwatch mTimer; @@ -121,7 +120,8 @@ void CosmicsMatchingSpec::run(ProcessingContext& pc) mTimer.Start(false); RecoContainer recoData; - recoData.collectData(pc, dataRequestCosm); + recoData.collectData(pc, *mDataRequest.get()); + mMatching.process(recoData); pc.outputs().snapshot(Output{"GLO", "COSMICTRC", 0, Lifetime::Timeframe}, mMatching.getCosmicTracks()); if (mUseMC) { @@ -139,11 +139,11 @@ void CosmicsMatchingSpec::endOfStream(EndOfStreamContext& ec) DataProcessorSpec getCosmicsMatchingSpec(GTrackID::mask_t src, bool useMC) { - std::vector outputs; + auto dataRequest = std::make_shared(); - dataRequestCosm.requestTracks(src, useMC); - dataRequestCosm.requestClusters(src, false); // no MC labels for clusters needed for refit only + dataRequest->requestTracks(src, useMC); + dataRequest->requestClusters(src, false); // no MC labels for clusters needed for refit only outputs.emplace_back("GLO", "COSMICTRC", 0, Lifetime::Timeframe); if (useMC) { @@ -152,9 +152,9 @@ DataProcessorSpec getCosmicsMatchingSpec(GTrackID::mask_t src, bool useMC) return DataProcessorSpec{ "cosmics-matcher", - dataRequestCosm.inputs, + dataRequest->inputs, outputs, - AlgorithmSpec{adaptFromTask(useMC)}, + AlgorithmSpec{adaptFromTask(dataRequest, useMC)}, Options{ {"its-dictionary-path", VariantType::String, "", {"Path of the cluster-topology dictionary file"}}, {"material-lut-path", VariantType::String, "", {"Path of the material LUT file"}}, diff --git a/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx index 47a4c6a17d50f..0219756728cf1 100644 --- a/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx @@ -26,6 +26,7 @@ #include "GlobalTrackingWorkflow/TrackCosmicsWriterSpec.h" #include "Algorithm/RangeTokenizer.h" #include "DetectorsRaw/HBFUtilsInitializer.h" +#include "GlobalTrackingWorkflowHelpers/InputHelper.h" using namespace o2::framework; using DetID = o2::detectors::DetID; @@ -75,46 +76,14 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) o2::conf::ConfigurableParam::writeINI("o2match-cosmics-workflow_configuration.ini"); auto useMC = !configcontext.options().get("disable-mc"); - auto disableRootInp = configcontext.options().get("disable-root-input"); auto disableRootOut = configcontext.options().get("disable-root-output"); GID::mask_t src = alowedSources & GID::getSourcesMask(configcontext.options().get("track-sources")); - - if (!disableRootInp) { - - if (src[GID::ITS]) { - specs.emplace_back(o2::its::getITSTrackReaderSpec(useMC)); - } - - if (src[GID::TPC]) { - specs.emplace_back(o2::tpc::getTPCTrackReaderSpec(useMC)); - } - - if (src[GID::ITSTPC] || src[GID::ITSTPCTOF]) { // ITSTPCTOF does not provide tracks, only matchInfo - specs.emplace_back(o2::globaltracking::getTrackTPCITSReaderSpec(useMC)); - } - - if (src[GID::ITSTPCTOF]) { - specs.emplace_back(o2::tof::getTOFMatchedReaderSpec(useMC, false, false)); // MC, MatchInfo_glo, no TOF_TPCtracks - specs.emplace_back(o2::tof::getClusterReaderSpec(false)); // RSTODO Needed just to set the time of ITSTPC track, consider moving to MatchInfoTOF - } - - if (src[GID::TPCTOF]) { - specs.emplace_back(o2::tof::getTOFMatchedReaderSpec(useMC, true, true)); // mc, MatchInfo_TPC, TOF_TPCtracks - } - - // clusters for refit - if (GID::includesDet(DetID::ITS, src)) { - specs.emplace_back(o2::itsmft::getITSClusterReaderSpec(false, true)); // mc not neaded - } - if (GID::includesDet(DetID::TPC, src)) { - specs.emplace_back(o2::tpc::getClusterReaderSpec(false)); - specs.emplace_back(o2::tpc::getClusterSharingMapSpec()); - } - } - + GID::mask_t dummy; specs.emplace_back(o2::globaltracking::getCosmicsMatchingSpec(src, useMC)); + o2::globaltracking::InputHelper::addInputSpecs(configcontext, specs, src, src, src, useMC, dummy); // clusters MC is not needed + if (!disableRootOut) { specs.emplace_back(o2::globaltracking::getTrackCosmicsWriterSpec(useMC)); } From 5297f3952669e3bf422ed30a9f10f82d1dd3c1db Mon Sep 17 00:00:00 2001 From: shahoian Date: Mon, 3 May 2021 03:09:05 +0200 Subject: [PATCH 373/770] PVertexer: use InputHelper, avoid global DataRequest var. --- .../PrimaryVertexingSpec.h | 28 ++----------- .../VertexTrackMatcherSpec.h | 22 +---------- .../src/PrimaryVertexingSpec.cxx | 37 +++++++++++++++--- .../src/VertexTrackMatcherSpec.cxx | 39 ++++++++++++++----- .../src/primary-vertexing-workflow.cxx | 35 +++-------------- 5 files changed, 70 insertions(+), 91 deletions(-) diff --git a/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/PrimaryVertexingSpec.h b/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/PrimaryVertexingSpec.h index 046f95683bcfe..7c849e4cf256d 100644 --- a/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/PrimaryVertexingSpec.h +++ b/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/PrimaryVertexingSpec.h @@ -13,39 +13,17 @@ /// @file PrimaryVertexingSpec.h -#include "DetectorsVertexing/PVertexer.h" -#include "DetectorsCommonDataFormats/DetID.h" -#include "Framework/DataProcessorSpec.h" +#include "ReconstructionDataFormats/GlobalTrackID.h" #include "Framework/Task.h" -#include "TStopwatch.h" +#include "Framework/DataProcessorSpec.h" namespace o2 { namespace vertexing { -using namespace o2::framework; -using DetID = o2::detectors::DetID; - -class PrimaryVertexingSpec : public Task -{ - public: - PrimaryVertexingSpec(bool validateWithIR, bool useMC) : mUseMC(useMC), mValidateWithIR(validateWithIR) {} - ~PrimaryVertexingSpec() override = default; - void init(InitContext& ic) final; - void run(ProcessingContext& pc) final; - void endOfStream(EndOfStreamContext& ec) final; - - private: - o2::vertexing::PVertexer mVertexer; - bool mUseMC{false}; ///< MC flag - bool mValidateWithIR{false}; ///< require vertex validation with IR (e.g. from FT0) - float mITSROFrameLengthMUS = 0.; - TStopwatch mTimer; -}; - /// create a processor spec -DataProcessorSpec getPrimaryVertexingSpec(GTrackID::mask_t src, bool validateWithFT0, bool useMC); +o2::framework::DataProcessorSpec getPrimaryVertexingSpec(o2::dataformats::GlobalTrackID::mask_t src, bool validateWithFT0, bool useMC); } // namespace vertexing } // namespace o2 diff --git a/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/VertexTrackMatcherSpec.h b/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/VertexTrackMatcherSpec.h index 1cc2c81eb7036..a7b7d51be7561 100644 --- a/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/VertexTrackMatcherSpec.h +++ b/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/VertexTrackMatcherSpec.h @@ -15,35 +15,17 @@ /// @brief Specs for vertex track association device /// @author ruben.shahoyan@cern.ch -#include "DetectorsVertexing/VertexTrackMatcher.h" +#include "ReconstructionDataFormats/GlobalTrackID.h" #include "Framework/DataProcessorSpec.h" #include "Framework/Task.h" -#include "TStopwatch.h" namespace o2 { namespace vertexing { -using namespace o2::framework; -using GTrackID = o2::dataformats::GlobalTrackID; - -class VertexTrackMatcherSpec : public Task -{ - public: - VertexTrackMatcherSpec() = default; - ~VertexTrackMatcherSpec() override = default; - void init(InitContext& ic) final; - void run(ProcessingContext& pc) final; - void endOfStream(EndOfStreamContext& ec) final; - - private: - o2::vertexing::VertexTrackMatcher mMatcher; - TStopwatch mTimer; -}; - /// create a processor spec -DataProcessorSpec getVertexTrackMatcherSpec(GTrackID::mask_t src); +o2::framework::DataProcessorSpec getVertexTrackMatcherSpec(o2::dataformats::GlobalTrackID::mask_t src); } // namespace vertexing } // namespace o2 diff --git a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx index 5f34723765dd9..9b64096768e77 100644 --- a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx @@ -11,6 +11,7 @@ /// @file PrimaryVertexingSpec.cxx #include +#include #include "DataFormatsGlobalTracking/RecoContainer.h" #include "ReconstructionDataFormats/TrackTPCITS.h" #include "ReconstructionDataFormats/GlobalTrackID.h" @@ -25,16 +26,39 @@ #include "Framework/ConfigParamRegistry.h" #include "FT0Reconstruction/InteractionTag.h" #include "ITSMFTBase/DPLAlpideParam.h" +#include "DetectorsCommonDataFormats/DetID.h" +#include "DetectorsVertexing/PVertexer.h" using namespace o2::framework; +using DetID = o2::detectors::DetID; +using DataRequest = o2::globaltracking::DataRequest; namespace o2 { namespace vertexing { -o2::globaltracking::DataRequest dataRequestPV; + namespace o2d = o2::dataformats; +class PrimaryVertexingSpec : public Task +{ + public: + PrimaryVertexingSpec(std::shared_ptr dr, bool validateWithIR, bool useMC) + : mDataRequest(dr), mUseMC(useMC), mValidateWithIR(validateWithIR) {} + ~PrimaryVertexingSpec() override = default; + void init(InitContext& ic) final; + void run(ProcessingContext& pc) final; + void endOfStream(EndOfStreamContext& ec) final; + + private: + std::shared_ptr mDataRequest; + o2::vertexing::PVertexer mVertexer; + bool mUseMC{false}; ///< MC flag + bool mValidateWithIR{false}; ///< require vertex validation with IR (e.g. from FT0) + float mITSROFrameLengthMUS = 0.; + TStopwatch mTimer; +}; + void PrimaryVertexingSpec::init(InitContext& ic) { //-------- init geometry and field --------// @@ -76,7 +100,7 @@ void PrimaryVertexingSpec::run(ProcessingContext& pc) mTimer.Start(false); o2::globaltracking::RecoContainer recoData; - recoData.collectData(pc, dataRequestPV); + recoData.collectData(pc, *mDataRequest.get()); // select tracks of needed type, with minimal cuts, the real selected will be done in the vertexer std::vector tracks; @@ -149,10 +173,11 @@ void PrimaryVertexingSpec::endOfStream(EndOfStreamContext& ec) DataProcessorSpec getPrimaryVertexingSpec(GTrackID::mask_t src, bool validateWithFT0, bool useMC) { std::vector outputs; + auto dataRequest = std::make_shared(); - dataRequestPV.requestTracks(src, useMC); + dataRequest->requestTracks(src, useMC); if (validateWithFT0 && src[GTrackID::FT0]) { - dataRequestPV.requestFT0RecPoints(false); + dataRequest->requestFT0RecPoints(false); } outputs.emplace_back("GLO", "PVTX", 0, Lifetime::Timeframe); @@ -165,9 +190,9 @@ DataProcessorSpec getPrimaryVertexingSpec(GTrackID::mask_t src, bool validateWit return DataProcessorSpec{ "primary-vertexing", - dataRequestPV.inputs, + dataRequest->inputs, outputs, - AlgorithmSpec{adaptFromTask(validateWithFT0, useMC)}, + AlgorithmSpec{adaptFromTask(dataRequest, validateWithFT0, useMC)}, Options{{"material-lut-path", VariantType::String, "", {"Path of the material LUT file"}}}}; } diff --git a/Detectors/GlobalTrackingWorkflow/src/VertexTrackMatcherSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/VertexTrackMatcherSpec.cxx index 9ae478814ce9f..40518fe7f0646 100644 --- a/Detectors/GlobalTrackingWorkflow/src/VertexTrackMatcherSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/VertexTrackMatcherSpec.cxx @@ -17,15 +17,33 @@ #include "ITSMFTBase/DPLAlpideParam.h" #include "DetectorsCommonDataFormats/NameConf.h" #include "DataFormatsGlobalTracking/RecoContainer.h" +#include "DetectorsVertexing/VertexTrackMatcher.h" +#include "TStopwatch.h" using namespace o2::framework; using DetID = o2::detectors::DetID; +using GTrackID = o2::dataformats::GlobalTrackID; +using DataRequest = o2::globaltracking::DataRequest; namespace o2 { namespace vertexing { -o2::globaltracking::DataRequest dataRequestV2T; + +class VertexTrackMatcherSpec : public Task +{ + public: + VertexTrackMatcherSpec(std::shared_ptr dr) : mDataRequest(dr){}; + ~VertexTrackMatcherSpec() override = default; + void init(InitContext& ic) final; + void run(ProcessingContext& pc) final; + void endOfStream(EndOfStreamContext& ec) final; + + private: + std::shared_ptr mDataRequest; + o2::vertexing::VertexTrackMatcher mMatcher; + TStopwatch mTimer; +}; void VertexTrackMatcherSpec::init(InitContext& ic) { @@ -46,7 +64,7 @@ void VertexTrackMatcherSpec::run(ProcessingContext& pc) // RS FIXME this will not have effect until the 1st orbit is propagated, until that will work only for TF starting at orbit 0 const auto* dh = o2::header::get(pc.inputs().getByPos(0).header); mMatcher.setStartIR({0, dh->firstTForbit}); - recoData.collectData(pc, dataRequestV2T); + recoData.collectData(pc, *mDataRequest.get()); const auto vertices = pc.inputs().get>("vertices"); const auto vtxTracks = pc.inputs().get>("vtxTracks"); @@ -74,25 +92,26 @@ void VertexTrackMatcherSpec::endOfStream(EndOfStreamContext& ec) DataProcessorSpec getVertexTrackMatcherSpec(GTrackID::mask_t src) { std::vector outputs; + auto dataRequest = std::make_shared(); if (src[GTrackID::ITS]) { - dataRequestV2T.requestITSTracks(false); + dataRequest->requestITSTracks(false); } if (src[GTrackID::TPC]) { - dataRequestV2T.requestTPCTracks(false); + dataRequest->requestTPCTracks(false); } if (src[GTrackID::ITSTPC] || src[GTrackID::ITSTPCTOF]) { // ITSTPCTOF does not provide tracks, only matchInfo - dataRequestV2T.requestITSTPCTracks(false); + dataRequest->requestITSTPCTracks(false); } if (src[GTrackID::ITSTPCTOF]) { - dataRequestV2T.requestTOFMatches(false); - dataRequestV2T.requestTOFClusters(false); + dataRequest->requestTOFMatches(false); + dataRequest->requestTOFClusters(false); } if (src[GTrackID::TPCTOF]) { - dataRequestV2T.requestTPCTOFTracks(false); + dataRequest->requestTPCTOFTracks(false); } - auto& inputs = dataRequestV2T.inputs; + auto& inputs = dataRequest->inputs; inputs.emplace_back("vertices", "GLO", "PVTX", 0, Lifetime::Timeframe); inputs.emplace_back("vtxTracks", "GLO", "PVTX_CONTID", 0, Lifetime::Timeframe); inputs.emplace_back("vtxTrackRefs", "GLO", "PVTX_CONTIDREFS", 0, Lifetime::Timeframe); @@ -104,7 +123,7 @@ DataProcessorSpec getVertexTrackMatcherSpec(GTrackID::mask_t src) "pvertex-track-matching", inputs, outputs, - AlgorithmSpec{adaptFromTask()}, + AlgorithmSpec{adaptFromTask(dataRequest)}, Options{}}; } diff --git a/Detectors/GlobalTrackingWorkflow/src/primary-vertexing-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/primary-vertexing-workflow.cxx index 8123aa72c6730..008d1bdaa111b 100644 --- a/Detectors/GlobalTrackingWorkflow/src/primary-vertexing-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/primary-vertexing-workflow.cxx @@ -8,6 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +#include "GlobalTrackingWorkflowHelpers/InputHelper.h" #include "GlobalTrackingWorkflow/PrimaryVertexingSpec.h" #include "GlobalTrackingWorkflow/PrimaryVertexWriterSpec.h" #include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" @@ -65,48 +66,22 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) auto useMC = !configcontext.options().get("disable-mc"); - auto disableRootInp = configcontext.options().get("disable-root-input"); auto disableRootOut = configcontext.options().get("disable-root-output"); auto validateWithFT0 = configcontext.options().get("validate-with-ft0"); GID::mask_t srcPV = alowedSourcesPV & GID::getSourcesMask(configcontext.options().get("vertexing-sources")); GID::mask_t srcVT = alowedSourcesVT & GID::getSourcesMask(configcontext.options().get("vetex-track-matching-sources")); GID::mask_t srcComb = srcPV | srcVT; - - // decide what to read, MC is needed (if requested) only for P.Vertexing - if (!disableRootInp) { - - if (srcComb[GID::ITS]) { - specs.emplace_back(o2::its::getITSTrackReaderSpec(useMC && srcPV[GID::ITS])); - } - - if (srcComb[GID::TPC]) { - specs.emplace_back(o2::tpc::getTPCTrackReaderSpec(useMC && srcPV[GID::TPC])); - } - - if (srcComb[GID::ITSTPC] || srcComb[GID::ITSTPCTOF]) { // ITSTPCTOF does not provide tracks, only matchInfo - specs.emplace_back(o2::globaltracking::getTrackTPCITSReaderSpec(useMC && (srcPV[GID::ITSTPC] || srcPV[GID::ITSTPCTOF]))); - } - - if (srcComb[GID::ITSTPCTOF]) { - specs.emplace_back(o2::tof::getTOFMatchedReaderSpec(useMC && srcPV[GID::ITSTPCTOF], false, false)); // MC, MatchInfo_glo, no TOF_TPCtracks - specs.emplace_back(o2::tof::getClusterReaderSpec(false)); // RSTODO Needed just to set the time of ITSTPC track, consider moving to MatchInfoTOF - } - - if (srcComb[GID::TPCTOF]) { - specs.emplace_back(o2::tof::getTOFMatchedReaderSpec(srcPV[GID::TPCTOF], true, true)); // mc, MatchInfo_TPC, TOF_TPCtracks - } - - if (validateWithFT0) { - specs.emplace_back(o2::ft0::getRecPointReaderSpec(false)); - } - } + GID::mask_t dummy, srcClus = GID::includesDet(DetID::TOF, srcComb) ? GID::getSourceMask(GID::TOF) : dummy; specs.emplace_back(o2::vertexing::getPrimaryVertexingSpec(srcPV, validateWithFT0, useMC)); if (!srcVT.none()) { specs.emplace_back(o2::vertexing::getVertexTrackMatcherSpec(srcVT)); } + // only TOF clusters are needed if TOF is involved, no clusters MC needed + o2::globaltracking::InputHelper::addInputSpecs(configcontext, specs, srcClus, srcComb, srcComb, useMC, dummy); + if (!disableRootOut) { specs.emplace_back(o2::vertexing::getPrimaryVertexWriterSpec(srcVT.none(), useMC)); } From 3aa934e4dc1e1fb3fff883713d607855c75c06b6 Mon Sep 17 00:00:00 2001 From: shahoian Date: Mon, 3 May 2021 03:57:37 +0200 Subject: [PATCH 374/770] SVertexer: use InputHelper, avoid global DataRequest var. --- .../SecondaryVertexingSpec.h | 22 ++---------- .../src/SecondaryVertexingSpec.cxx | 34 ++++++++++++++++--- .../src/secondary-vertexing-workflow.cxx | 33 ++++++------------ 3 files changed, 42 insertions(+), 47 deletions(-) diff --git a/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/SecondaryVertexingSpec.h b/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/SecondaryVertexingSpec.h index 6269fee03a27e..7fcb91640cf44 100644 --- a/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/SecondaryVertexingSpec.h +++ b/Detectors/GlobalTrackingWorkflow/include/GlobalTrackingWorkflow/SecondaryVertexingSpec.h @@ -13,35 +13,17 @@ /// @file SecondaryVertexingSpec.h -#include "DetectorsVertexing/SVertexer.h" +#include "ReconstructionDataFormats/GlobalTrackID.h" #include "Framework/DataProcessorSpec.h" #include "Framework/Task.h" -#include "TStopwatch.h" namespace o2 { namespace vertexing { -using namespace o2::framework; - -class SecondaryVertexingSpec : public Task -{ - public: - SecondaryVertexingSpec(bool enabCasc) : mEnableCascades(enabCasc) {} - ~SecondaryVertexingSpec() override = default; - void init(InitContext& ic) final; - void run(ProcessingContext& pc) final; - void endOfStream(EndOfStreamContext& ec) final; - - private: - bool mEnableCascades = false; - o2::vertexing::SVertexer mVertexer; - TStopwatch mTimer; -}; - /// create a processor spec -DataProcessorSpec getSecondaryVertexingSpec(o2::dataformats::GlobalTrackID::mask_t src, bool enableCasc); +o2::framework::DataProcessorSpec getSecondaryVertexingSpec(o2::dataformats::GlobalTrackID::mask_t src, bool enableCasc); } // namespace vertexing } // namespace o2 diff --git a/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexingSpec.cxx index 3509cb3eb3833..c439ecea383c1 100644 --- a/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/SecondaryVertexingSpec.cxx @@ -13,6 +13,7 @@ #include #include "DataFormatsGlobalTracking/RecoContainer.h" #include "ReconstructionDataFormats/TrackTPCITS.h" +#include "ReconstructionDataFormats/GlobalTrackID.h" #include "DataFormatsTPC/TrackTPC.h" #include "DataFormatsITS/TrackITS.h" #include "DetectorsBase/Propagator.h" @@ -22,6 +23,9 @@ #include "CommonDataFormat/BunchFilling.h" #include "SimulationDataFormat/DigitizationContext.h" #include "DetectorsCommonDataFormats/NameConf.h" +#include "DetectorsVertexing/SVertexer.h" +#include "TStopwatch.h" + #include "Framework/ConfigParamRegistry.h" using namespace o2::framework; @@ -33,15 +37,31 @@ using PVertex = const o2::dataformats::PrimaryVertex; using V0 = o2::dataformats::V0; using Cascade = o2::dataformats::Cascade; using RRef = o2::dataformats::RangeReference; +using DataRequest = o2::globaltracking::DataRequest; namespace o2 { namespace vertexing { -o2::globaltracking::DataRequest dataRequestSV; namespace o2d = o2::dataformats; +class SecondaryVertexingSpec : public Task +{ + public: + SecondaryVertexingSpec(std::shared_ptr dr, bool enabCasc) : mDataRequest(dr), mEnableCascades(enabCasc) {} + ~SecondaryVertexingSpec() override = default; + void init(InitContext& ic) final; + void run(ProcessingContext& pc) final; + void endOfStream(EndOfStreamContext& ec) final; + + private: + std::shared_ptr mDataRequest; + bool mEnableCascades = false; + o2::vertexing::SVertexer mVertexer; + TStopwatch mTimer; +}; + void SecondaryVertexingSpec::init(InitContext& ic) { //-------- init geometry and field --------// @@ -70,7 +90,7 @@ void SecondaryVertexingSpec::run(ProcessingContext& pc) mTimer.Start(false); o2::globaltracking::RecoContainer recoData; - recoData.collectData(pc, dataRequestSV); + recoData.collectData(pc, *mDataRequest.get()); const auto pvertices = pc.inputs().get>("pvtx"); const auto pvtxTracks = pc.inputs().get>("pvtx_cont"); @@ -98,9 +118,13 @@ void SecondaryVertexingSpec::endOfStream(EndOfStreamContext& ec) DataProcessorSpec getSecondaryVertexingSpec(GTrackID::mask_t src, bool enableCasc) { std::vector outputs; + auto dataRequest = std::make_shared(); + bool useMC = false; - dataRequestSV.requestTracks(src, false); - auto& inputs = dataRequestSV.inputs; + dataRequest->requestTracks(src, false); + + auto& inputs = dataRequest->inputs; + inputs.emplace_back("pvtx", "GLO", "PVTX", 0, Lifetime::Timeframe); // prim.vertices inputs.emplace_back("pvtx_cont", "GLO", "PVTX_TRMTC", 0, Lifetime::Timeframe); // global ids of associated tracks inputs.emplace_back("pvtx_tref", "GLO", "PVTX_TRMTCREFS", 0, Lifetime::Timeframe); // vertex - trackID refs @@ -114,7 +138,7 @@ DataProcessorSpec getSecondaryVertexingSpec(GTrackID::mask_t src, bool enableCas "secondary-vertexing", inputs, outputs, - AlgorithmSpec{adaptFromTask(enableCasc)}, + AlgorithmSpec{adaptFromTask(dataRequest, enableCasc)}, Options{{"material-lut-path", VariantType::String, "", {"Path of the material LUT file"}}, {"threads", VariantType::Int, 1, {"Number of threads"}}}}; } diff --git a/Detectors/GlobalTrackingWorkflow/src/secondary-vertexing-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/secondary-vertexing-workflow.cxx index 1b0607894aef3..ca481de0887bc 100644 --- a/Detectors/GlobalTrackingWorkflow/src/secondary-vertexing-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/secondary-vertexing-workflow.cxx @@ -12,6 +12,7 @@ #include "GlobalTrackingWorkflow/SecondaryVertexWriterSpec.h" #include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" #include "GlobalTrackingWorkflowReaders/PrimaryVertexReaderSpec.h" +#include "GlobalTrackingWorkflowHelpers/InputHelper.h" #include "ITSWorkflow/TrackReaderSpec.h" #include "TPCWorkflow/TrackReaderSpec.h" #include "TOFWorkflow/TOFMatchedReaderSpec.h" @@ -50,7 +51,7 @@ void customize(std::vector& workflowOptions) WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) { - GID::mask_t alowedSourcesSV = GID::getSourcesMask("ITS,ITS-TPC,ITS-TPC-TOF,TPC-TOF"); + GID::mask_t alowedSources = GID::getSourcesMask("ITS,ITS-TPC,ITS-TPC-TOF,TPC-TOF"); // Update the (declared) parameters if changed from the command line o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); @@ -61,30 +62,18 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) auto disableRootOut = configcontext.options().get("disable-root-output"); auto enableCasc = !configcontext.options().get("disable-cascade-finder"); - GID::mask_t srcSV = alowedSourcesSV & GID::getSourcesMask(configcontext.options().get("vertexing-sources")); + GID::mask_t src = alowedSources & GID::getSourcesMask(configcontext.options().get("vertexing-sources")); + GID::mask_t dummy, srcClus = GID::includesDet(DetID::TOF, src) ? GID::getSourceMask(GID::TOF) : dummy; + WorkflowSpec specs; - if (!disableRootInp) { - if (srcSV[GID::ITS]) { - specs.emplace_back(o2::its::getITSTrackReaderSpec(useMC)); - } - if (srcSV[GID::TPC]) { - specs.emplace_back(o2::tpc::getTPCTrackReaderSpec(useMC)); - } - if (srcSV[GID::ITSTPC] || srcSV[GID::ITSTPCTOF]) { // ITSTPCTOF does not provide tracks, only matchInfo - specs.emplace_back(o2::globaltracking::getTrackTPCITSReaderSpec(useMC)); - } - if (srcSV[GID::ITSTPCTOF]) { - specs.emplace_back(o2::tof::getTOFMatchedReaderSpec(useMC, false, false)); // MC, MatchInfo_glo, no TOF_TPCtracks - specs.emplace_back(o2::tof::getClusterReaderSpec(false)); // RSTODO Needed just to set the time of ITSTPC track, consider moving to MatchInfoTOF - } - if (srcSV[GID::TPCTOF]) { - specs.emplace_back(o2::tof::getTOFMatchedReaderSpec(useMC, true, true)); // mc, MatchInfo_TPC, TOF_TPCtracks - } - specs.emplace_back(o2::vertexing::getPrimaryVertexReaderSpec(useMC)); - } - specs.emplace_back(o2::vertexing::getSecondaryVertexingSpec(srcSV, enableCasc)); + specs.emplace_back(o2::vertexing::getSecondaryVertexingSpec(src, enableCasc)); + // only TOF clusters are needed if TOF is involved, no clusters MC needed + o2::globaltracking::InputHelper::addInputSpecs(configcontext, specs, srcClus, src, src, useMC, srcClus); + if (!disableRootInp) { + specs.emplace_back(o2::vertexing::getPrimaryVertexReaderSpec(useMC)); // consider moving to RecoContainer + } if (!disableRootOut) { specs.emplace_back(o2::vertexing::getSecondaryVertexWriterSpec()); } From 75e6ab76fbe82eab95866c6672cc0a4b1ce0bd0e Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 4 May 2021 09:19:47 +0200 Subject: [PATCH 375/770] Add missing header to ROOTMAP --- DataFormats/simulation/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/DataFormats/simulation/CMakeLists.txt b/DataFormats/simulation/CMakeLists.txt index 9ed5155633744..5d3a8aeeaef07 100644 --- a/DataFormats/simulation/CMakeLists.txt +++ b/DataFormats/simulation/CMakeLists.txt @@ -29,6 +29,7 @@ o2_target_root_dictionary( include/SimulationDataFormat/MCTrack.h include/SimulationDataFormat/BaseHits.h include/SimulationDataFormat/MCTruthContainer.h + include/SimulationDataFormat/ConstMCTruthContainer.h include/SimulationDataFormat/MCCompLabel.h include/SimulationDataFormat/MCEventLabel.h include/SimulationDataFormat/TrackReference.h From 5877f603ef8414bd44102ef72f12f8c56fe1031d Mon Sep 17 00:00:00 2001 From: Ole Schmidt Date: Mon, 3 May 2021 22:20:50 +0200 Subject: [PATCH 376/770] Move TRD readers/writers into independent lib - Remove obsolete TRD MCLabel alias --- DataFormats/Detectors/TRD/CMakeLists.txt | 2 +- Detectors/TRD/base/CMakeLists.txt | 1 - Detectors/TRD/base/include/TRDBase/MCLabel.h | 26 ------------ Detectors/TRD/base/src/TRDBaseLinkDef.h | 5 --- .../TRD/macros/convertRun2ToRun3Digits.C | 3 +- .../include/TRDSimulation/Digitizer.h | 2 +- .../include/TRDSimulation/TrapConfigHandler.h | 2 - Detectors/TRD/simulation/src/Digitizer.cxx | 2 +- Detectors/TRD/simulation/src/PileupTool.cxx | 1 - Detectors/TRD/workflow/CMakeLists.txt | 10 ++--- Detectors/TRD/workflow/io/CMakeLists.txt | 18 ++++++++ .../TRDCalibratedTrackletWriterSpec.h | 0 .../TRDWorkflowIO}/TRDDigitReaderSpec.h | 15 +++---- .../TRDWorkflowIO}/TRDDigitWriterSpec.h | 0 .../TRDWorkflowIO}/TRDTrackletReaderSpec.h | 0 .../TRDWorkflowIO}/TRDTrackletWriterSpec.h | 7 ---- .../TRDWorkflowIO}/TRDTrapRawWriterSpec.h | 0 .../src/TRDCalibratedTrackletWriterSpec.cxx | 2 +- .../{ => io}/src/TRDDigitReaderSpec.cxx | 42 +++---------------- .../{ => io}/src/TRDDigitWriterSpec.cxx | 3 +- .../{ => io}/src/TRDTrackletReaderSpec.cxx | 3 +- .../{ => io}/src/TRDTrackletWriterSpec.cxx | 7 ++-- .../{ => io}/src/TRDTrapRawWriterSpec.cxx | 2 +- .../TRD/workflow/src/TRDDigitizerSpec.cxx | 6 +-- .../TRD/workflow/src/TRDTrackingWorkflow.cxx | 2 +- .../src/TRDTrackletTransformerWorkflow.cxx | 4 +- .../workflow/src/TRDTrapSimulatorWorkFlow.cxx | 5 +-- Steer/DigitizerWorkflow/CMakeLists.txt | 1 + .../src/SimpleDigitizerWorkflow.cxx | 4 +- macro/analyzeDigitLabels.C | 1 - 30 files changed, 53 insertions(+), 123 deletions(-) delete mode 100644 Detectors/TRD/base/include/TRDBase/MCLabel.h create mode 100644 Detectors/TRD/workflow/io/CMakeLists.txt rename Detectors/TRD/workflow/{include/TRDWorkflow => io/include/TRDWorkflowIO}/TRDCalibratedTrackletWriterSpec.h (100%) rename Detectors/TRD/workflow/{include/TRDWorkflow => io/include/TRDWorkflowIO}/TRDDigitReaderSpec.h (79%) rename Detectors/TRD/workflow/{include/TRDWorkflow => io/include/TRDWorkflowIO}/TRDDigitWriterSpec.h (100%) rename Detectors/TRD/workflow/{include/TRDWorkflow => io/include/TRDWorkflowIO}/TRDTrackletReaderSpec.h (100%) rename Detectors/TRD/workflow/{include/TRDWorkflow => io/include/TRDWorkflowIO}/TRDTrackletWriterSpec.h (82%) rename Detectors/TRD/workflow/{include/TRDWorkflow => io/include/TRDWorkflowIO}/TRDTrapRawWriterSpec.h (100%) rename Detectors/TRD/workflow/{ => io}/src/TRDCalibratedTrackletWriterSpec.cxx (95%) rename Detectors/TRD/workflow/{ => io}/src/TRDDigitReaderSpec.cxx (76%) rename Detectors/TRD/workflow/{ => io}/src/TRDDigitWriterSpec.cxx (98%) rename Detectors/TRD/workflow/{ => io}/src/TRDTrackletReaderSpec.cxx (98%) rename Detectors/TRD/workflow/{ => io}/src/TRDTrackletWriterSpec.cxx (90%) rename Detectors/TRD/workflow/{ => io}/src/TRDTrapRawWriterSpec.cxx (97%) diff --git a/DataFormats/Detectors/TRD/CMakeLists.txt b/DataFormats/Detectors/TRD/CMakeLists.txt index e239f3c4e4946..d4675e3a156d8 100644 --- a/DataFormats/Detectors/TRD/CMakeLists.txt +++ b/DataFormats/Detectors/TRD/CMakeLists.txt @@ -36,4 +36,4 @@ o2_add_test(Digit SOURCES test/testDigit.cxx ENVIRONMENT O2_ROOT=${CMAKE_BINARY_DIR}/stage LABELS trd -) \ No newline at end of file +) diff --git a/Detectors/TRD/base/CMakeLists.txt b/Detectors/TRD/base/CMakeLists.txt index 82fc328cf7214..3b7c8eb85bee7 100644 --- a/Detectors/TRD/base/CMakeLists.txt +++ b/Detectors/TRD/base/CMakeLists.txt @@ -47,7 +47,6 @@ o2_target_root_dictionary(TRDBase include/TRDBase/SimParam.h include/TRDBase/CommonParam.h include/TRDBase/PadResponse.h - include/TRDBase/MCLabel.h include/TRDBase/CalDet.h include/TRDBase/CalROC.h include/TRDBase/FeeParam.h diff --git a/Detectors/TRD/base/include/TRDBase/MCLabel.h b/Detectors/TRD/base/include/TRDBase/MCLabel.h deleted file mode 100644 index d0cc90f020a99..0000000000000 --- a/Detectors/TRD/base/include/TRDBase/MCLabel.h +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -// Declaration of a transient MC label class for TRD - -#ifndef ALICEO2_TRD_MCLABEL_H_ -#define ALICEO2_TRD_MCLABEL_H_ - -#include "SimulationDataFormat/MCCompLabel.h" - -namespace o2 -{ -namespace trd -{ -using MCLabel = o2::MCCompLabel; -} // namespace trd -} // namespace o2 - -#endif diff --git a/Detectors/TRD/base/src/TRDBaseLinkDef.h b/Detectors/TRD/base/src/TRDBaseLinkDef.h index ba7c9fc9093a7..b6b29be35ede2 100644 --- a/Detectors/TRD/base/src/TRDBaseLinkDef.h +++ b/Detectors/TRD/base/src/TRDBaseLinkDef.h @@ -43,10 +43,5 @@ #pragma link C++ class o2::trd::Tracklet + ; #pragma link C++ class std::vector < o2::trd::Tracklet > +; -#include "SimulationDataFormat/MCTruthContainer.h" -#include "SimulationDataFormat/ConstMCTruthContainer.h" - -// this is just needed to please the DPL ROOTTreeWriter facility -#pragma link C++ class o2::dataformats::ConstMCTruthContainer < o2::trd::MCLabel> + ; #endif diff --git a/Detectors/TRD/macros/convertRun2ToRun3Digits.C b/Detectors/TRD/macros/convertRun2ToRun3Digits.C index f25c548f810cb..17a41cb27c88d 100644 --- a/Detectors/TRD/macros/convertRun2ToRun3Digits.C +++ b/Detectors/TRD/macros/convertRun2ToRun3Digits.C @@ -25,7 +25,6 @@ #include "TRDBase/Digit.h" #include "DataFormatsTRD/TriggerRecord.h" #include "DataFormatsTRD/Constants.h" -#include "TRDBase/MCLabel.h" #include "SimulationDataFormat/MCCompLabel.h" #include "SimulationDataFormat/ConstMCTruthContainer.h" @@ -49,7 +48,7 @@ void convertRun2ToRun3Digits(TString qaOutPath = "", { vector run3Digits; vector triggerRecords; - o2::dataformats::MCTruthContainer mcLabels; + o2::dataformats::MCTruthContainer mcLabels; TH1F* hAdc = new TH1F("hADC", "ADC spectrum", 1024, -0.5, 1023.5); TH1F* hTBsum = new TH1F("hTBsum", "TBsum", 3000, -0.5, 2999.5); diff --git a/Detectors/TRD/simulation/include/TRDSimulation/Digitizer.h b/Detectors/TRD/simulation/include/TRDSimulation/Digitizer.h index d1f40758e5d00..480eada2b84dd 100644 --- a/Detectors/TRD/simulation/include/TRDSimulation/Digitizer.h +++ b/Detectors/TRD/simulation/include/TRDSimulation/Digitizer.h @@ -14,7 +14,6 @@ #include "TRDSimulation/Detector.h" #include "TRDBase/Calibrations.h" -#include "TRDBase/MCLabel.h" #include "TRDBase/CommonParam.h" #include "TRDBase/DiffAndTimeStructEstimator.h" #include "TRDSimulation/PileupTool.h" @@ -44,6 +43,7 @@ class PadResponse; using DigitContainer = std::vector; using SignalContainer = std::unordered_map; +using MCLabel = o2::MCCompLabel; class Digitizer { diff --git a/Detectors/TRD/simulation/include/TRDSimulation/TrapConfigHandler.h b/Detectors/TRD/simulation/include/TRDSimulation/TrapConfigHandler.h index bd3738fbc1529..0d20a63c6eb46 100644 --- a/Detectors/TRD/simulation/include/TRDSimulation/TrapConfigHandler.h +++ b/Detectors/TRD/simulation/include/TRDSimulation/TrapConfigHandler.h @@ -19,8 +19,6 @@ #include #include "TRDBase/CalOnlineGainTables.h" -#include "SimulationDataFormat/MCTruthContainer.h" -#include "TRDBase/MCLabel.h" namespace o2 { diff --git a/Detectors/TRD/simulation/src/Digitizer.cxx b/Detectors/TRD/simulation/src/Digitizer.cxx index c342a5064387f..2053be4b39070 100644 --- a/Detectors/TRD/simulation/src/Digitizer.cxx +++ b/Detectors/TRD/simulation/src/Digitizer.cxx @@ -394,7 +394,7 @@ bool Digitizer::convertHits(const int det, const std::vector& hits, SignalC return true; } -void Digitizer::addLabel(const int& trackId, std::vector& labels, std::unordered_set& trackIds) +void Digitizer::addLabel(const int& trackId, std::vector& labels, std::unordered_set& trackIds) { if (trackIds.count(trackId) == 0) { trackIds.insert(trackId); diff --git a/Detectors/TRD/simulation/src/PileupTool.cxx b/Detectors/TRD/simulation/src/PileupTool.cxx index 82faee8b5fd7d..8fea3bd1aa357 100644 --- a/Detectors/TRD/simulation/src/PileupTool.cxx +++ b/Detectors/TRD/simulation/src/PileupTool.cxx @@ -9,7 +9,6 @@ // or submit itself to any jurisdiction. #include "TRDSimulation/PileupTool.h" -#include "TRDBase/MCLabel.h" using namespace o2::trd; using namespace o2::trd::constants; diff --git a/Detectors/TRD/workflow/CMakeLists.txt b/Detectors/TRD/workflow/CMakeLists.txt index 59e86a5a3754d..67f62a2ce2d99 100644 --- a/Detectors/TRD/workflow/CMakeLists.txt +++ b/Detectors/TRD/workflow/CMakeLists.txt @@ -10,15 +10,11 @@ #add_compile_options(-O0 -pg -fPIC) +add_subdirectory(io) + o2_add_library(TRDWorkflow TARGETVARNAME targetName SOURCES src/TRDDigitizerSpec.cxx - src/TRDDigitWriterSpec.cxx - src/TRDDigitReaderSpec.cxx - src/TRDTrackletWriterSpec.cxx - src/TRDCalibratedTrackletWriterSpec.cxx - src/TRDTrackletReaderSpec.cxx - src/TRDTrapRawWriterSpec.cxx src/TRDTrapSimulatorSpec.cxx src/TRDTrackletTransformerSpec.cxx src/TRDGlobalTrackingSpec.cxx @@ -26,7 +22,7 @@ o2_add_library(TRDWorkflow src/TRDTrackingWorkflow.cxx src/EntropyDecoderSpec.cxx src/EntropyEncoderSpec.cxx - PUBLIC_LINK_LIBRARIES O2::Framework O2::DPLUtils O2::Steer O2::Algorithm O2::DataFormatsTRD O2::TRDSimulation O2::TRDReconstruction O2::DetectorsBase O2::SimulationDataFormat O2::TRDBase O2::TRDCalibration O2::GPUTracking O2::GlobalTrackingWorkflowReaders O2::ReconstructionDataFormats O2::TPCWorkflow) + PUBLIC_LINK_LIBRARIES O2::Framework O2::DPLUtils O2::Steer O2::Algorithm O2::DataFormatsTRD O2::TRDSimulation O2::TRDReconstruction O2::DetectorsBase O2::SimulationDataFormat O2::TRDBase O2::TRDCalibration O2::GPUTracking O2::GlobalTrackingWorkflowReaders O2::ReconstructionDataFormats O2::TPCWorkflow O2::TRDWorkflowIO) #o2_target_root_dictionary(TRDWorkflow # HEADERS include/TRDWorkflow/TRDTrapSimulatorSpec.h) diff --git a/Detectors/TRD/workflow/io/CMakeLists.txt b/Detectors/TRD/workflow/io/CMakeLists.txt new file mode 100644 index 0000000000000..227a500ec549b --- /dev/null +++ b/Detectors/TRD/workflow/io/CMakeLists.txt @@ -0,0 +1,18 @@ +# Copyright CERN and copyright holders of ALICE O2. This software is distributed +# under the terms of the GNU General Public License v3 (GPL Version 3), copied +# verbatim in the file "COPYING". +# +# See http://alice-o2.web.cern.ch/license for full licensing information. +# +# In applying this license CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization or +# submit itself to any jurisdiction. + +o2_add_library(TRDWorkflowIO + SOURCES src/TRDDigitReaderSpec.cxx + src/TRDTrackletReaderSpec.cxx + src/TRDDigitWriterSpec.cxx + src/TRDTrackletWriterSpec.cxx + src/TRDTrapRawWriterSpec.cxx + src/TRDCalibratedTrackletWriterSpec.cxx + PUBLIC_LINK_LIBRARIES O2::DataFormatsTRD O2::SimulationDataFormat O2::DPLUtils) diff --git a/Detectors/TRD/workflow/include/TRDWorkflow/TRDCalibratedTrackletWriterSpec.h b/Detectors/TRD/workflow/io/include/TRDWorkflowIO/TRDCalibratedTrackletWriterSpec.h similarity index 100% rename from Detectors/TRD/workflow/include/TRDWorkflow/TRDCalibratedTrackletWriterSpec.h rename to Detectors/TRD/workflow/io/include/TRDWorkflowIO/TRDCalibratedTrackletWriterSpec.h diff --git a/Detectors/TRD/workflow/include/TRDWorkflow/TRDDigitReaderSpec.h b/Detectors/TRD/workflow/io/include/TRDWorkflowIO/TRDDigitReaderSpec.h similarity index 79% rename from Detectors/TRD/workflow/include/TRDWorkflow/TRDDigitReaderSpec.h rename to Detectors/TRD/workflow/io/include/TRDWorkflowIO/TRDDigitReaderSpec.h index 0e4b5da6c360c..ef5a1aef95cf0 100644 --- a/Detectors/TRD/workflow/include/TRDWorkflow/TRDDigitReaderSpec.h +++ b/Detectors/TRD/workflow/io/include/TRDWorkflowIO/TRDDigitReaderSpec.h @@ -11,16 +11,15 @@ #ifndef O2_TRDTRAPSIMULATORRAWREADERSPEC_H #define O2_TRDTRAPSIMULATORRAWREADERSPEC_H -#include "Framework/ConfigParamRegistry.h" -#include "Framework/ControlService.h" #include "Framework/DataProcessorSpec.h" -#include "Framework/DataRefUtils.h" -#include "Framework/Lifetime.h" #include "Framework/Task.h" -#include "TRDBase/MCLabel.h" + #include "TFile.h" #include "TTree.h" +#include +#include + namespace o2 { namespace trd @@ -29,19 +28,15 @@ namespace trd class TRDDigitReaderSpec : public o2::framework::Task { public: - TRDDigitReaderSpec(int channels, bool useMC) : mChannels(channels), mUseMC(useMC) {} + TRDDigitReaderSpec(int channels, bool useMC) : mUseMC(useMC) {} ~TRDDigitReaderSpec() override = default; void init(o2::framework::InitContext& ic) override; void run(o2::framework::ProcessingContext& pc) override; private: - bool mFinished = false; int mState = 0; - bool mUseRun2 = false; - int mChannels; bool mUseMC = false; std::unique_ptr mFile = nullptr; - //std::unique_ptr DPLTree; std::string mInputFileName = ""; std::string mDigitTreeName = "o2sim"; std::string mDigitBranchName = "TRDDigit"; diff --git a/Detectors/TRD/workflow/include/TRDWorkflow/TRDDigitWriterSpec.h b/Detectors/TRD/workflow/io/include/TRDWorkflowIO/TRDDigitWriterSpec.h similarity index 100% rename from Detectors/TRD/workflow/include/TRDWorkflow/TRDDigitWriterSpec.h rename to Detectors/TRD/workflow/io/include/TRDWorkflowIO/TRDDigitWriterSpec.h diff --git a/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackletReaderSpec.h b/Detectors/TRD/workflow/io/include/TRDWorkflowIO/TRDTrackletReaderSpec.h similarity index 100% rename from Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackletReaderSpec.h rename to Detectors/TRD/workflow/io/include/TRDWorkflowIO/TRDTrackletReaderSpec.h diff --git a/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackletWriterSpec.h b/Detectors/TRD/workflow/io/include/TRDWorkflowIO/TRDTrackletWriterSpec.h similarity index 82% rename from Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackletWriterSpec.h rename to Detectors/TRD/workflow/io/include/TRDWorkflowIO/TRDTrackletWriterSpec.h index 6039ade93a13d..be73582adbe2e 100644 --- a/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackletWriterSpec.h +++ b/Detectors/TRD/workflow/io/include/TRDWorkflowIO/TRDTrackletWriterSpec.h @@ -11,13 +11,6 @@ #ifndef O2_TRDTRAPSIMULATORTRACKLETWRITER_H #define O2_TRDTRAPSIMULATORTRACKLETWRITER_H -#include "DataFormatsTRD/Digit.h" -#include -#include "TRDBase/MCLabel.h" -#include "TRDBase/Tracklet.h" -#include -#include - namespace o2 { namespace framework diff --git a/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrapRawWriterSpec.h b/Detectors/TRD/workflow/io/include/TRDWorkflowIO/TRDTrapRawWriterSpec.h similarity index 100% rename from Detectors/TRD/workflow/include/TRDWorkflow/TRDTrapRawWriterSpec.h rename to Detectors/TRD/workflow/io/include/TRDWorkflowIO/TRDTrapRawWriterSpec.h diff --git a/Detectors/TRD/workflow/src/TRDCalibratedTrackletWriterSpec.cxx b/Detectors/TRD/workflow/io/src/TRDCalibratedTrackletWriterSpec.cxx similarity index 95% rename from Detectors/TRD/workflow/src/TRDCalibratedTrackletWriterSpec.cxx rename to Detectors/TRD/workflow/io/src/TRDCalibratedTrackletWriterSpec.cxx index 94f919cf4064e..35143374c978b 100644 --- a/Detectors/TRD/workflow/src/TRDCalibratedTrackletWriterSpec.cxx +++ b/Detectors/TRD/workflow/io/src/TRDCalibratedTrackletWriterSpec.cxx @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#include "TRDWorkflow/TRDCalibratedTrackletWriterSpec.h" +#include "TRDWorkflowIO/TRDCalibratedTrackletWriterSpec.h" #include "DataFormatsTRD/CalibratedTracklet.h" #include "DPLUtils/MakeRootTreeWriterSpec.h" diff --git a/Detectors/TRD/workflow/src/TRDDigitReaderSpec.cxx b/Detectors/TRD/workflow/io/src/TRDDigitReaderSpec.cxx similarity index 76% rename from Detectors/TRD/workflow/src/TRDDigitReaderSpec.cxx rename to Detectors/TRD/workflow/io/src/TRDDigitReaderSpec.cxx index e9711a140ef0a..887dc604e3a56 100644 --- a/Detectors/TRD/workflow/src/TRDDigitReaderSpec.cxx +++ b/Detectors/TRD/workflow/io/src/TRDDigitReaderSpec.cxx @@ -8,54 +8,22 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#include "TRDWorkflow/TRDDigitReaderSpec.h" +#include "TRDWorkflowIO/TRDDigitReaderSpec.h" -#include // this is somewhat assuming that a DPL workflow will run on one node #include "Framework/ConfigParamRegistry.h" #include "Framework/ControlService.h" -#include "Framework/DataProcessorSpec.h" -#include "Framework/DataRefUtils.h" -#include "Framework/Lifetime.h" -#include "DPLUtils/RootTreeReader.h" -#include "Headers/DataHeader.h" -#include "TStopwatch.h" -#include "Steer/HitProcessingManager.h" // for DigitizationContext -#include "TChain.h" +#include "fairlogger/Logger.h" + #include #include #include -#include "Framework/Task.h" -#include "DataFormatsParameters/GRPObject.h" -#include "DataFormatsTRD/Digit.h" // for the Digit type -#include "TRDSimulation/TrapSimulator.h" -#include "TRDSimulation/Digitizer.h" -#include "TRDSimulation/Detector.h" // for the Hit type - -#include "DetectorsBase/GeometryManager.h" +#include "DataFormatsTRD/Digit.h" #include "DataFormatsTRD/TriggerRecord.h" -#include -#include -#include -#include - -#include -#include -#include // for getppid -#include // object serialization -#include // std::unique_ptr -#include // memcpy -#include // std::string -#include -#include -#include -#include - using namespace o2::framework; -using SubSpecificationType = o2::framework::DataAllocator::SubSpecificationType; namespace o2 { @@ -100,7 +68,7 @@ void TRDDigitReaderSpec::run(ProcessingContext& pc) if (mUseMC) { getFromBranch(mMCLabelsBranchName.c_str(), (void**)&ioLabels); // publish labels in shared memory - auto& sharedlabels = pc.outputs().make>(Output{"TRD", "LABELS", 0, Lifetime::Timeframe}); + auto& sharedlabels = pc.outputs().make>(Output{"TRD", "LABELS", 0, Lifetime::Timeframe}); ioLabels->copyandflatten(sharedlabels); LOG(info) << "TRDDigitReader labels size (in bytes) = " << sharedlabels.size(); } diff --git a/Detectors/TRD/workflow/src/TRDDigitWriterSpec.cxx b/Detectors/TRD/workflow/io/src/TRDDigitWriterSpec.cxx similarity index 98% rename from Detectors/TRD/workflow/src/TRDDigitWriterSpec.cxx rename to Detectors/TRD/workflow/io/src/TRDDigitWriterSpec.cxx index 647da43894553..26d803c14d7bd 100644 --- a/Detectors/TRD/workflow/src/TRDDigitWriterSpec.cxx +++ b/Detectors/TRD/workflow/io/src/TRDDigitWriterSpec.cxx @@ -18,8 +18,7 @@ #include "DataFormatsTRD/TriggerRecord.h" #include #include -#include "TRDBase/MCLabel.h" -#include "TRDWorkflow/TRDDigitWriterSpec.h" +#include "TRDWorkflowIO/TRDDigitWriterSpec.h" namespace o2 { diff --git a/Detectors/TRD/workflow/src/TRDTrackletReaderSpec.cxx b/Detectors/TRD/workflow/io/src/TRDTrackletReaderSpec.cxx similarity index 98% rename from Detectors/TRD/workflow/src/TRDTrackletReaderSpec.cxx rename to Detectors/TRD/workflow/io/src/TRDTrackletReaderSpec.cxx index 80186031c2fc8..741d80536d489 100644 --- a/Detectors/TRD/workflow/src/TRDTrackletReaderSpec.cxx +++ b/Detectors/TRD/workflow/io/src/TRDTrackletReaderSpec.cxx @@ -10,9 +10,8 @@ /// @file TRDTrackletReaderSpec.cxx -#include "TRDWorkflow/TRDTrackletReaderSpec.h" +#include "TRDWorkflowIO/TRDTrackletReaderSpec.h" -#include "Headers/DataHeader.h" #include "Framework/ControlService.h" #include "Framework/ConfigParamRegistry.h" #include "fairlogger/Logger.h" diff --git a/Detectors/TRD/workflow/src/TRDTrackletWriterSpec.cxx b/Detectors/TRD/workflow/io/src/TRDTrackletWriterSpec.cxx similarity index 90% rename from Detectors/TRD/workflow/src/TRDTrackletWriterSpec.cxx rename to Detectors/TRD/workflow/io/src/TRDTrackletWriterSpec.cxx index 887715886df93..1295db005658f 100644 --- a/Detectors/TRD/workflow/src/TRDTrackletWriterSpec.cxx +++ b/Detectors/TRD/workflow/io/src/TRDTrackletWriterSpec.cxx @@ -14,10 +14,9 @@ #include "Framework/DataProcessorSpec.h" #include "DPLUtils/MakeRootTreeWriterSpec.h" #include "Framework/InputSpec.h" -#include "TRDWorkflow/TRDTrackletWriterSpec.h" -#include "DataFormatsTRD/Digit.h" +#include "TRDWorkflowIO/TRDTrackletWriterSpec.h" #include -#include "TRDBase/MCLabel.h" +#include #include "DataFormatsTRD/TriggerRecord.h" #include "DataFormatsTRD/Tracklet64.h" @@ -52,7 +51,7 @@ o2::framework::DataProcessorSpec getTRDTrackletWriterSpec(bool useMC) "trdtracklets.root", "o2sim", BranchDefinition>{InputSpec{"tracklets", "TRD", "TRACKLETS"}, "Tracklet"}, - BranchDefinition>{InputSpec{"trklabels", "TRD", "TRKLABELS"}, "TRKLabels", (useMC ? 1 : 0), "TRKLABELS"}, + BranchDefinition>{InputSpec{"trklabels", "TRD", "TRKLABELS"}, "TRKLabels", (useMC ? 1 : 0), "TRKLABELS"}, BranchDefinition>{InputSpec{"tracklettrigs", "TRD", "TRKTRGRD"}, "TrackTrg"})(); }; diff --git a/Detectors/TRD/workflow/src/TRDTrapRawWriterSpec.cxx b/Detectors/TRD/workflow/io/src/TRDTrapRawWriterSpec.cxx similarity index 97% rename from Detectors/TRD/workflow/src/TRDTrapRawWriterSpec.cxx rename to Detectors/TRD/workflow/io/src/TRDTrapRawWriterSpec.cxx index eb6bc89354737..80ba9f9dff0ff 100644 --- a/Detectors/TRD/workflow/src/TRDTrapRawWriterSpec.cxx +++ b/Detectors/TRD/workflow/io/src/TRDTrapRawWriterSpec.cxx @@ -14,7 +14,7 @@ #include "Framework/DataProcessorSpec.h" #include "DPLUtils/MakeRootTreeWriterSpec.h" #include "Framework/InputSpec.h" -#include "TRDWorkflow/TRDTrapRawWriterSpec.h" +#include "TRDWorkflowIO/TRDTrapRawWriterSpec.h" #include "DataFormatsTRD/RawData.h" #include "DataFormatsTRD/TriggerRecord.h" #include "DataFormatsTRD/LinkRecord.h" diff --git a/Detectors/TRD/workflow/src/TRDDigitizerSpec.cxx b/Detectors/TRD/workflow/src/TRDDigitizerSpec.cxx index e33dc4708f4e8..522da864b85f9 100644 --- a/Detectors/TRD/workflow/src/TRDDigitizerSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDDigitizerSpec.cxx @@ -75,11 +75,11 @@ class TRDDPLDigitizerTask : public o2::base::BaseDPLDigitizer auto& eventParts = context->getEventParts(); std::vector digitsAccum; // accumulator for digits - o2::dataformats::MCTruthContainer labelsAccum; + o2::dataformats::MCTruthContainer labelsAccum; std::vector triggers; std::vector digits; // digits which get filled - o2::dataformats::MCTruthContainer labels; // labels which get filled + o2::dataformats::MCTruthContainer labels; // labels which get filled o2::InteractionTimeRecord currentTime; // the current time o2::InteractionTimeRecord triggerTime; // the time at which the TRD start reading out a signal @@ -153,7 +153,7 @@ class TRDDPLDigitizerTask : public o2::base::BaseDPLDigitizer if (mctruth) { LOG(INFO) << "TRD: Sending " << labelsAccum.getNElements() << " labels"; // we are flattening the labels and write to managed shared memory container for further communication - auto& sharedlabels = pc.outputs().make>(Output{"TRD", "LABELS", 0, Lifetime::Timeframe}); + auto& sharedlabels = pc.outputs().make>(Output{"TRD", "LABELS", 0, Lifetime::Timeframe}); labelsAccum.flatten_to(sharedlabels); } LOG(INFO) << "TRD: Sending ROMode= " << mROMode << " to GRPUpdater"; diff --git a/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx b/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx index bdce84c184fd0..9b41af4f68eb6 100644 --- a/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx +++ b/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx @@ -15,7 +15,7 @@ #include "Framework/WorkflowSpec.h" #include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" #include "TPCWorkflow/TrackReaderSpec.h" -#include "TRDWorkflow/TRDTrackletReaderSpec.h" +#include "TRDWorkflowIO/TRDTrackletReaderSpec.h" #include "TRDWorkflow/TRDTrackletTransformerSpec.h" #include "TRDWorkflow/TRDGlobalTrackingSpec.h" #include "TRDWorkflow/TRDTrackWriterSpec.h" diff --git a/Detectors/TRD/workflow/src/TRDTrackletTransformerWorkflow.cxx b/Detectors/TRD/workflow/src/TRDTrackletTransformerWorkflow.cxx index 5b0b3cdde6ab1..dfcccaa8fadb3 100644 --- a/Detectors/TRD/workflow/src/TRDTrackletTransformerWorkflow.cxx +++ b/Detectors/TRD/workflow/src/TRDTrackletTransformerWorkflow.cxx @@ -9,8 +9,8 @@ // or submit itself to any jurisdiction. #include "TRDWorkflow/TRDTrackletTransformerSpec.h" -#include "TRDWorkflow/TRDCalibratedTrackletWriterSpec.h" -#include "TRDWorkflow/TRDTrackletReaderSpec.h" +#include "TRDWorkflowIO/TRDCalibratedTrackletWriterSpec.h" +#include "TRDWorkflowIO/TRDTrackletReaderSpec.h" #include "CommonUtils/ConfigurableParam.h" #include "Framework/CompletionPolicy.h" diff --git a/Detectors/TRD/workflow/src/TRDTrapSimulatorWorkFlow.cxx b/Detectors/TRD/workflow/src/TRDTrapSimulatorWorkFlow.cxx index 61e4a047206ed..9c4fe038f0000 100644 --- a/Detectors/TRD/workflow/src/TRDTrapSimulatorWorkFlow.cxx +++ b/Detectors/TRD/workflow/src/TRDTrapSimulatorWorkFlow.cxx @@ -19,9 +19,8 @@ // for TRD #include "TRDWorkflow/TRDTrapSimulatorSpec.h" -#include "TRDWorkflow/TRDTrackletWriterSpec.h" -#include "TRDWorkflow/TRDTrapRawWriterSpec.h" -#include "TRDWorkflow/TRDDigitReaderSpec.h" +#include "TRDWorkflowIO/TRDTrackletWriterSpec.h" +#include "TRDWorkflowIO/TRDDigitReaderSpec.h" #include "DataFormatsParameters/GRPObject.h" diff --git a/Steer/DigitizerWorkflow/CMakeLists.txt b/Steer/DigitizerWorkflow/CMakeLists.txt index 60a487738a5ce..82bb4b7ec7d71 100644 --- a/Steer/DigitizerWorkflow/CMakeLists.txt +++ b/Steer/DigitizerWorkflow/CMakeLists.txt @@ -56,6 +56,7 @@ o2_add_executable(digitizer-workflow O2::TPCSimulation O2::TRDSimulation O2::TRDWorkflow + O2::TRDWorkflowIO O2::DataFormatsTRD O2::ZDCSimulation O2::ZDCWorkflow diff --git a/Steer/DigitizerWorkflow/src/SimpleDigitizerWorkflow.cxx b/Steer/DigitizerWorkflow/src/SimpleDigitizerWorkflow.cxx index f4f1ed67a1538..8519a83c09558 100644 --- a/Steer/DigitizerWorkflow/src/SimpleDigitizerWorkflow.cxx +++ b/Steer/DigitizerWorkflow/src/SimpleDigitizerWorkflow.cxx @@ -65,9 +65,9 @@ // for TRD #include "TRDWorkflow/TRDDigitizerSpec.h" -#include "TRDWorkflow/TRDDigitWriterSpec.h" +#include "TRDWorkflowIO/TRDDigitWriterSpec.h" #include "TRDWorkflow/TRDTrapSimulatorSpec.h" -#include "TRDWorkflow/TRDTrackletWriterSpec.h" +#include "TRDWorkflowIO/TRDTrackletWriterSpec.h" //for MUON MCH #include "MCHDigitizerSpec.h" diff --git a/macro/analyzeDigitLabels.C b/macro/analyzeDigitLabels.C index dcd23a970597b..58439fee9e016 100644 --- a/macro/analyzeDigitLabels.C +++ b/macro/analyzeDigitLabels.C @@ -12,7 +12,6 @@ #include "DataFormatsFV0/MCLabel.h" #include "DataFormatsZDC/MCLabel.h" #include "MIDSimulation/MCLabel.h" -#include "TRDBase/MCLabel.h" #include // for guideline support library; array_view #include From f2c6739ecdef516654b9766574b133d4600a3039 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sat, 1 May 2021 09:35:59 +0200 Subject: [PATCH 377/770] GPU: Work on dumping / loading TRD tracklets for standalone benchmark: Support O2 tracklets, sort tracklets from AliRoot, add dummy trigger record for AliRoot --- GPU/GPUTracking/Base/GPUReconstruction.h | 7 ++++-- .../Global/AliHLTGPUDumpComponent.cxx | 23 ++++++++++++------- GPU/GPUTracking/Global/GPUChainTrackingIO.cxx | 9 ++++++++ .../Global/GPUChainTrackingTRD.cxx | 1 + GPU/GPUTracking/Interface/GPUO2Interface.cxx | 4 +--- 5 files changed, 31 insertions(+), 13 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstruction.h b/GPU/GPUTracking/Base/GPUReconstruction.h index 66ad660e542c6..5fc60b3e52834 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.h +++ b/GPU/GPUTracking/Base/GPUReconstruction.h @@ -101,9 +101,12 @@ class GPUReconstruction TPC_DIGIT = 13, TPC_ZS = 14, CLUSTER_NATIVE_MC = 15, - TPC_DIGIT_MC = 16 }; + TPC_DIGIT_MC = 16, + TRD_SPACEPOINT = 17, + TRD_TRIGGERRECORDS = 18 }; static constexpr const char* const IOTYPENAMES[] = {"TPC HLT Clusters", "TPC Slice Tracks", "TPC Slice Track Clusters", "TPC Cluster MC Labels", "TPC Track MC Informations", "TPC Tracks", "TPC Track Clusters", "TRD Tracks", "TRD Tracklets", - "TPC Raw Clusters", "TPC Native Clusters", "TRD Tracklet MC Labels", "TPC Compressed Clusters", "TPC Digit", "TPC ZS Page", "TPC Native Clusters MC Labels", "TPC Digit MC Labeels"}; + "TPC Raw Clusters", "TPC Native Clusters", "TRD Tracklet MC Labels", "TPC Compressed Clusters", "TPC Digit", "TPC ZS Page", "TPC Native Clusters MC Labels", "TPC Digit MC Labeels", + "TRD Spacepoints", "TRD Triggerrecords"}; static unsigned int getNIOTypeMultiplicity(InOutPointerType type) { return (type == CLUSTER_DATA || type == SLICE_OUT_TRACK || type == SLICE_OUT_CLUSTER || type == RAW_CLUSTERS || type == TPC_DIGIT || type == TPC_DIGIT_MC) ? NSLICES : 1; } // Functionality to create an instance of GPUReconstruction for the desired device diff --git a/GPU/GPUTracking/Global/AliHLTGPUDumpComponent.cxx b/GPU/GPUTracking/Global/AliHLTGPUDumpComponent.cxx index a4abc4917a058..2f785416052f8 100644 --- a/GPU/GPUTracking/Global/AliHLTGPUDumpComponent.cxx +++ b/GPU/GPUTracking/Global/AliHLTGPUDumpComponent.cxx @@ -175,10 +175,8 @@ int AliHLTGPUDumpComponent::DoEvent(const AliHLTComponentEventData& evtData, con const AliHLTTPCClusterXYZData* clustersXYZ[NSLICES][NPATCHES] = {nullptr}; const AliHLTTPCRawClusterData* clustersRaw[NSLICES][NPATCHES] = {nullptr}; bool labelsPresent = false; - GPUTRDTrackletWord* TRDtracklets = nullptr; - GPUTRDTrackletLabels* TRDtrackletsMC = nullptr; + const GPUTRDTrackletWord* TRDtracklets = nullptr; int nTRDTrackletsTotal = 0; - int nTRDTrackletsMCTotal = 0; for (unsigned long ndx = 0; ndx < evtData.fBlockCnt; ndx++) { const AliHLTComponentBlockData& pBlock = blocks[ndx]; @@ -192,11 +190,8 @@ int AliHLTGPUDumpComponent::DoEvent(const AliHLTComponentEventData& evtData, con clusterLabels[slice][patch] = (const AliHLTTPCClusterMCData*)pBlock.fPtr; labelsPresent = true; } else if (pBlock.fDataType == AliHLTTRDDefinitions::fgkTRDTrackletDataType) { - TRDtracklets = reinterpret_cast(pBlock.fPtr); + TRDtracklets = reinterpret_cast(pBlock.fPtr); nTRDTrackletsTotal = pBlock.fSize / sizeof(GPUTRDTrackletWord); - } else if (pBlock.fDataType == (AliHLTTRDDefinitions::fgkTRDMCTrackletDataType)) { - TRDtrackletsMC = reinterpret_cast(pBlock.fPtr); - nTRDTrackletsMCTotal = pBlock.fSize / sizeof(GPUTRDTrackletLabels); } } @@ -450,7 +445,19 @@ int AliHLTGPUDumpComponent::DoEvent(const AliHLTComponentEventData& evtData, con } fChain->mIOPtrs.nTRDTracklets = nTRDTrackletsTotal; - fChain->mIOPtrs.trdTracklets = TRDtracklets; + std::vector tracklets(nTRDTrackletsTotal); + for (int i = 0; i < nTRDTrackletsTotal; i++) { + tracklets[i] = TRDtracklets[i]; + } + std::sort(tracklets.data(), tracklets.data() + nTRDTrackletsTotal); + fChain->mIOPtrs.trdTracklets = tracklets.data(); + + fChain->mIOPtrs.nTRDTriggerRecords = 1; + static float t = 0.f; + static int o = 0; + fChain->mIOPtrs.trdTriggerTimes = &t; + fChain->mIOPtrs.trdTrackletIdxFirst = &o; + HLTDebug("Number of TRD tracklets: %d", (int)nTRDTrackletsTotal); static int nEvent = 0; diff --git a/GPU/GPUTracking/Global/GPUChainTrackingIO.cxx b/GPU/GPUTracking/Global/GPUChainTrackingIO.cxx index 3059836202b34..2c8ac80807c24 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingIO.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingIO.cxx @@ -134,6 +134,11 @@ void GPUChainTracking::DumpData(const char* filename) DumpData(fp, &mIOPtrs.mergedTrackHits, &mIOPtrs.nMergedTrackHits, InOutPointerType::MERGED_TRACK_HIT); DumpData(fp, &mIOPtrs.trdTracks, &mIOPtrs.nTRDTracks, InOutPointerType::TRD_TRACK); DumpData(fp, &mIOPtrs.trdTracklets, &mIOPtrs.nTRDTracklets, InOutPointerType::TRD_TRACKLET); + if (mIOPtrs.trdSpacePoints) { + DumpData(fp, &mIOPtrs.trdSpacePoints, &mIOPtrs.nTRDTracklets, InOutPointerType::TRD_SPACEPOINT); + } + DumpData(fp, &mIOPtrs.trdTriggerTimes, &mIOPtrs.nTRDTriggerRecords, InOutPointerType::TRD_TRIGGERRECORDS); + DumpData(fp, &mIOPtrs.trdTrackletIdxFirst, &mIOPtrs.nTRDTriggerRecords, InOutPointerType::TRD_TRIGGERRECORDS); fclose(fp); } @@ -221,6 +226,10 @@ int GPUChainTracking::ReadData(const char* filename) ReadData(fp, &mIOPtrs.mergedTrackHits, &mIOPtrs.nMergedTrackHits, &mIOMem.mergedTrackHits, InOutPointerType::MERGED_TRACK_HIT); ReadData(fp, &mIOPtrs.trdTracks, &mIOPtrs.nTRDTracks, &mIOMem.trdTracks, InOutPointerType::TRD_TRACK); ReadData(fp, &mIOPtrs.trdTracklets, &mIOPtrs.nTRDTracklets, &mIOMem.trdTracklets, InOutPointerType::TRD_TRACKLET); + unsigned int dummy = 0; + ReadData(fp, &mIOPtrs.trdSpacePoints, &dummy, &mIOMem.trdSpacePoints, InOutPointerType::TRD_SPACEPOINT); + ReadData(fp, &mIOPtrs.trdTriggerTimes, &mIOPtrs.nTRDTriggerRecords, &mIOMem.trdTriggerTimes, InOutPointerType::TRD_TRIGGERRECORDS); + ReadData(fp, &mIOPtrs.trdTrackletIdxFirst, &mIOPtrs.nTRDTriggerRecords, &mIOMem.trdTrackletIdxFirst, InOutPointerType::TRD_TRIGGERRECORDS); size_t fptr = ftell(fp); fseek(fp, 0, SEEK_END); diff --git a/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx b/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx index 11439a9ab91f5..cdf0b40a730b2 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx @@ -34,6 +34,7 @@ int GPUChainTracking::RunTRDTracking() if (mIOPtrs.nTRDTracklets == 0) { return 0; } + Tracker.SetGenerateSpacePoints(mIOPtrs.trdSpacePoints == nullptr); mRec->PushNonPersistentMemory(qStr2Tag("TRDTRACK")); SetupGPUProcessor(&Tracker, true); diff --git a/GPU/GPUTracking/Interface/GPUO2Interface.cxx b/GPU/GPUTracking/Interface/GPUO2Interface.cxx index 78717ca32fc5a..ea8e4da72bc07 100644 --- a/GPU/GPUTracking/Interface/GPUO2Interface.cxx +++ b/GPU/GPUTracking/Interface/GPUO2Interface.cxx @@ -91,9 +91,7 @@ int GPUO2Interface::RunTracking(GPUTrackingInOutPointers* data, GPUInterfaceOutp if (mConfig->configInterface.dumpEvents) { static int nEvent = 0; mChain->ClearIOPointers(); - mChain->mIOPtrs.clustersNative = data->clustersNative; - mChain->mIOPtrs.tpcPackedDigits = data->tpcPackedDigits; - mChain->mIOPtrs.tpcZS = data->tpcZS; + mChain->mIOPtrs = *data; char fname[1024]; sprintf(fname, "event.%d.dump", nEvent); From ad7efa181941b5d80bc1eff2bfc9ffc31da697c1 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 3 May 2021 20:34:05 +0200 Subject: [PATCH 378/770] GPU: Use a common dummy file for header only libraries --- GPU/Common/CMakeLists.txt | 8 ++------ GPU/GPUTracking/Standalone/CMakeLists.txt | 2 +- GPU/GPUTracking/Standalone/dummy.cxx | 9 --------- .../utils/EmptyFile.cxx} | 4 ++-- GPU/Utils/CMakeLists.txt | 8 ++------ GPU/Utils/GPUUtils.cxx | 14 -------------- 6 files changed, 7 insertions(+), 38 deletions(-) delete mode 100644 GPU/GPUTracking/Standalone/dummy.cxx rename GPU/{Common/GPUCommon.cxx => GPUTracking/utils/EmptyFile.cxx} (87%) delete mode 100644 GPU/Utils/GPUUtils.cxx diff --git a/GPU/Common/CMakeLists.txt b/GPU/Common/CMakeLists.txt index 0c56ec4221d53..7d47fc61b771c 100644 --- a/GPU/Common/CMakeLists.txt +++ b/GPU/Common/CMakeLists.txt @@ -26,7 +26,7 @@ set(HDRS_INSTALL if(ALIGPU_BUILD_TYPE STREQUAL "O2") o2_add_library(${MODULE} - SOURCES GPUCommon.cxx + SOURCES ../GPUTracking/utils/EmptyFile.cxx TARGETVARNAME targetName PUBLIC_LINK_LIBRARIES O2::FrameworkLogger) target_include_directories(${targetName} @@ -51,7 +51,7 @@ endif() if(ALIGPU_BUILD_TYPE STREQUAL "ALIROOT") add_definitions(-DGPUCA_ALIROOT_LIB) - set(SRCS ${SRCS} GPUCommon.cxx) + set(SRCS ${SRCS} ../GPUTracking/utils/EmptyFile.cxx) # Add a library to the project using the specified source files add_library_tested(Ali${MODULE} SHARED ${SRCS}) @@ -70,7 +70,3 @@ if(ALIGPU_BUILD_TYPE STREQUAL "ALIROOT") install(FILES ${HDRS_INSTALL} DESTINATION include) endif() - -if(ALIGPU_BUILD_TYPE STREQUAL "Standalone") - -endif() diff --git a/GPU/GPUTracking/Standalone/CMakeLists.txt b/GPU/GPUTracking/Standalone/CMakeLists.txt index 8dfe7f02155c5..bf0211f27b999 100644 --- a/GPU/GPUTracking/Standalone/CMakeLists.txt +++ b/GPU/GPUTracking/Standalone/CMakeLists.txt @@ -169,7 +169,7 @@ endif() # Create main targets add_subdirectory(../../ GPU) -add_library(standalone_support SHARED dummy.cxx) +add_library(standalone_support SHARED ${GPUTRACKING_DIR}/utils/EmptyFile.cxx) target_link_libraries(GPUTracking PUBLIC TPCFastTransformation standalone_support dl) target_link_libraries(ca PUBLIC GPUTracking) diff --git a/GPU/GPUTracking/Standalone/dummy.cxx b/GPU/GPUTracking/Standalone/dummy.cxx deleted file mode 100644 index ab2179b8eb11c..0000000000000 --- a/GPU/GPUTracking/Standalone/dummy.cxx +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. diff --git a/GPU/Common/GPUCommon.cxx b/GPU/GPUTracking/utils/EmptyFile.cxx similarity index 87% rename from GPU/Common/GPUCommon.cxx rename to GPU/GPUTracking/utils/EmptyFile.cxx index 555ae492214d1..f38500b40717a 100644 --- a/GPU/Common/GPUCommon.cxx +++ b/GPU/GPUTracking/utils/EmptyFile.cxx @@ -8,7 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -/// \file GPUCommon.cxx +/// \file EmptyFile.cxx /// \author David Rohr -// Empty file, needed for AliRoot +// Empty file, needed for header only libraries diff --git a/GPU/Utils/CMakeLists.txt b/GPU/Utils/CMakeLists.txt index a5aacd93b801f..d618dce2c9a01 100644 --- a/GPU/Utils/CMakeLists.txt +++ b/GPU/Utils/CMakeLists.txt @@ -19,7 +19,7 @@ set(HDRS_INSTALL if(ALIGPU_BUILD_TYPE STREQUAL "O2") o2_add_library(${MODULE} - SOURCES GPUUtils.cxx + SOURCES ../GPUTracking/utils/EmptyFile.cxx TARGETVARNAME targetName PUBLIC_LINK_LIBRARIES O2::GPUCommon ROOT::RIO) target_include_directories(${targetName} @@ -39,7 +39,7 @@ endif() if(ALIGPU_BUILD_TYPE STREQUAL "ALIROOT") add_definitions(-DGPUCA_ALIROOT_LIB) - set(SRCS ${SRCS} GPUCommon.cxx) + set(SRCS ${SRCS} ../GPUTracking/utils/EmptyFile.cxx) # Add a library to the project using the specified source files add_library_tested(Ali${MODULE} SHARED ${SRCS}) @@ -58,7 +58,3 @@ if(ALIGPU_BUILD_TYPE STREQUAL "ALIROOT") install(FILES ${HDRS_CINT} ${HDRS_INSTALL} DESTINATION include) endif() - -if(ALIGPU_BUILD_TYPE STREQUAL "Standalone") - -endif() diff --git a/GPU/Utils/GPUUtils.cxx b/GPU/Utils/GPUUtils.cxx deleted file mode 100644 index 5de5e03f34a45..0000000000000 --- a/GPU/Utils/GPUUtils.cxx +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// \file GPUUtils.cxx -/// \author David Rohr - -// Empty file, needed for AliRoot From afa998170063340d52957b8de42913285f577f95 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 3 May 2021 20:29:23 +0200 Subject: [PATCH 379/770] Get rid of symlinks in GPU standalone folder --- GPU/GPUTracking/Standalone/Base | 1 - GPU/GPUTracking/Standalone/Benchmark | 1 - GPU/GPUTracking/Standalone/CMakeLists.txt | 146 +++++++++--------- GPU/GPUTracking/Standalone/Common | 1 - GPU/GPUTracking/Standalone/DataCompression | 1 - GPU/GPUTracking/Standalone/DataTypes | 1 - GPU/GPUTracking/Standalone/Debug | 1 - GPU/GPUTracking/Standalone/Definitions | 1 - GPU/GPUTracking/Standalone/GPUUtils | 1 - GPU/GPUTracking/Standalone/Global | 1 - GPU/GPUTracking/Standalone/HLTHeaders | 1 - GPU/GPUTracking/Standalone/ITS | 1 - GPU/GPUTracking/Standalone/Merger | 1 - GPU/GPUTracking/Standalone/Refit | 1 - GPU/GPUTracking/Standalone/SliceTracker | 1 - GPU/GPUTracking/Standalone/TPCClusterFinder | 1 - GPU/GPUTracking/Standalone/TPCConvert | 1 - .../Standalone/TPCFastTransformation | 1 - GPU/GPUTracking/Standalone/TRDTracking | 1 - GPU/GPUTracking/Standalone/dEdx | 1 - GPU/GPUTracking/Standalone/dependencies | 1 - GPU/GPUTracking/Standalone/display | 1 - GPU/GPUTracking/Standalone/qa | 1 - GPU/GPUTracking/Standalone/qconfigoptions.h | 1 - GPU/GPUTracking/Standalone/utils | 1 - 25 files changed, 75 insertions(+), 95 deletions(-) delete mode 120000 GPU/GPUTracking/Standalone/Base delete mode 120000 GPU/GPUTracking/Standalone/Benchmark delete mode 120000 GPU/GPUTracking/Standalone/Common delete mode 120000 GPU/GPUTracking/Standalone/DataCompression delete mode 120000 GPU/GPUTracking/Standalone/DataTypes delete mode 120000 GPU/GPUTracking/Standalone/Debug delete mode 120000 GPU/GPUTracking/Standalone/Definitions delete mode 120000 GPU/GPUTracking/Standalone/GPUUtils delete mode 120000 GPU/GPUTracking/Standalone/Global delete mode 120000 GPU/GPUTracking/Standalone/HLTHeaders delete mode 120000 GPU/GPUTracking/Standalone/ITS delete mode 120000 GPU/GPUTracking/Standalone/Merger delete mode 120000 GPU/GPUTracking/Standalone/Refit delete mode 120000 GPU/GPUTracking/Standalone/SliceTracker delete mode 120000 GPU/GPUTracking/Standalone/TPCClusterFinder delete mode 120000 GPU/GPUTracking/Standalone/TPCConvert delete mode 120000 GPU/GPUTracking/Standalone/TPCFastTransformation delete mode 120000 GPU/GPUTracking/Standalone/TRDTracking delete mode 120000 GPU/GPUTracking/Standalone/dEdx delete mode 120000 GPU/GPUTracking/Standalone/dependencies delete mode 120000 GPU/GPUTracking/Standalone/display delete mode 120000 GPU/GPUTracking/Standalone/qa delete mode 120000 GPU/GPUTracking/Standalone/qconfigoptions.h delete mode 120000 GPU/GPUTracking/Standalone/utils diff --git a/GPU/GPUTracking/Standalone/Base b/GPU/GPUTracking/Standalone/Base deleted file mode 120000 index e87748e1ef7fc..0000000000000 --- a/GPU/GPUTracking/Standalone/Base +++ /dev/null @@ -1 +0,0 @@ -../Base \ No newline at end of file diff --git a/GPU/GPUTracking/Standalone/Benchmark b/GPU/GPUTracking/Standalone/Benchmark deleted file mode 120000 index b49517d5aba90..0000000000000 --- a/GPU/GPUTracking/Standalone/Benchmark +++ /dev/null @@ -1 +0,0 @@ -../Benchmark \ No newline at end of file diff --git a/GPU/GPUTracking/Standalone/CMakeLists.txt b/GPU/GPUTracking/Standalone/CMakeLists.txt index bf0211f27b999..7834259d045af 100644 --- a/GPU/GPUTracking/Standalone/CMakeLists.txt +++ b/GPU/GPUTracking/Standalone/CMakeLists.txt @@ -16,7 +16,11 @@ set(CMAKE_INSTALL_BINDIR "${CMAKE_INSTALL_PREFIX}") set(CMAKE_INSTALL_LIBDIR "${CMAKE_INSTALL_PREFIX}") set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}") -set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/dependencies ${CMAKE_MODULE_PATH}) +set(GPU_DIR "${CMAKE_SOURCE_DIR}/../../") +set(GPUTRACKING_DIR "${GPU_DIR}/GPUTracking") +set(O2_DIR "${CMAKE_SOURCE_DIR}/../../../") + +set(CMAKE_MODULE_PATH ${O2_DIR}/dependencies ${CMAKE_MODULE_PATH}) # Copy and include Config File if(NOT EXISTS "${CMAKE_BINARY_DIR}/config.cmake") @@ -117,54 +121,54 @@ endif() find_package(O2GPU) # Global include directories -include_directories(${CMAKE_SOURCE_DIR} - ${CMAKE_SOURCE_DIR}/Debug - ${CMAKE_SOURCE_DIR}/Definitions - ${CMAKE_SOURCE_DIR}/DataTypes - ${CMAKE_SOURCE_DIR}/Base - ${CMAKE_SOURCE_DIR}/Base/opencl-common - ${CMAKE_SOURCE_DIR}/Common - ${CMAKE_SOURCE_DIR}/GPUUtils - ${CMAKE_SOURCE_DIR}/dEdx - ${CMAKE_SOURCE_DIR}/TPCConvert - ${CMAKE_SOURCE_DIR}/TPCFastTransformation - ${CMAKE_SOURCE_DIR}/display - ${CMAKE_SOURCE_DIR}/Global - ${CMAKE_SOURCE_DIR}/HLTHeaders - ${CMAKE_SOURCE_DIR}/Merger - ${CMAKE_SOURCE_DIR}/Refit - ${CMAKE_SOURCE_DIR}/qa - ${CMAKE_SOURCE_DIR}/SliceTracker - ${CMAKE_SOURCE_DIR}/DataCompression - ${CMAKE_SOURCE_DIR}/TRDTracking) +include_directories(${GPU_DIR}/Common + ${GPU_DIR}/Utils + ${GPU_DIR}/TPCFastTransformation + ${GPUTRACKING_DIR} + ${GPUTRACKING_DIR}/Debug + ${GPUTRACKING_DIR}/Definitions + ${GPUTRACKING_DIR}/DataTypes + ${GPUTRACKING_DIR}/Base + ${GPUTRACKING_DIR}/Base/opencl-common + ${GPUTRACKING_DIR}/dEdx + ${GPUTRACKING_DIR}/TPCConvert + ${GPUTRACKING_DIR}/display + ${GPUTRACKING_DIR}/Global + ${GPUTRACKING_DIR}/HLTHeaders + ${GPUTRACKING_DIR}/Merger + ${GPUTRACKING_DIR}/Refit + ${GPUTRACKING_DIR}/qa + ${GPUTRACKING_DIR}/SliceTracker + ${GPUTRACKING_DIR}/DataCompression + ${GPUTRACKING_DIR}/TRDTracking) if(CONFIG_O2_EXTENSIONS) -include_directories(${CMAKE_SOURCE_DIR}/TPCClusterFinder - ${CMAKE_SOURCE_DIR}/ITS - ${CMAKE_SOURCE_DIR}/../../../Common/Field/include - ${CMAKE_SOURCE_DIR}/../../../Common/Constants/include - ${CMAKE_SOURCE_DIR}/../../../Common/MathUtils/include - ${CMAKE_SOURCE_DIR}/../../../DataFormats/common/include - ${CMAKE_SOURCE_DIR}/../../../DataFormats/Detectors/Common/include - ${CMAKE_SOURCE_DIR}/../../../DataFormats/Detectors/ITSMFT/ITS/include - ${CMAKE_SOURCE_DIR}/../../../DataFormats/Detectors/TPC/include - ${CMAKE_SOURCE_DIR}/../../../DataFormats/Detectors/TRD/include - ${CMAKE_SOURCE_DIR}/../../../DataFormats/Headers/include - ${CMAKE_SOURCE_DIR}/../../../DataFormats/MemoryResources/include - ${CMAKE_SOURCE_DIR}/../../../DataFormats/Reconstruction/include - ${CMAKE_SOURCE_DIR}/../../../DataFormats/Reconstruction/src - ${CMAKE_SOURCE_DIR}/../../../DataFormats/simulation/include - ${CMAKE_SOURCE_DIR}/../../../Detectors/Base/include - ${CMAKE_SOURCE_DIR}/../../../Detectors/Base/src - ${CMAKE_SOURCE_DIR}/../../../Detectors/ITSMFT/ITS/tracking/include - ${CMAKE_SOURCE_DIR}/../../../Detectors/ITSMFT/ITS/tracking/cuda/include - ${CMAKE_SOURCE_DIR}/../../../Detectors/ITSMFT/ITS/tracking/cuda/src - ${CMAKE_SOURCE_DIR}/../../../Detectors/ITSMFT/ITS/tracking/hip/include - ${CMAKE_SOURCE_DIR}/../../../Detectors/ITSMFT/ITS/tracking/hip/src - ${CMAKE_SOURCE_DIR}/../../../Detectors/Raw/include - ${CMAKE_SOURCE_DIR}/../../../Detectors/TPC/base/include - ${CMAKE_SOURCE_DIR}/../../../Detectors/TRD/base/include - ${CMAKE_SOURCE_DIR}/../../../Detectors/TRD/base/src) +include_directories(${GPUTRACKING_DIR}/TPCClusterFinder + ${GPUTRACKING_DIR}/ITS + ${O2_DIR}/Common/Field/include + ${O2_DIR}/Common/Constants/include + ${O2_DIR}/Common/MathUtils/include + ${O2_DIR}/DataFormats/common/include + ${O2_DIR}/DataFormats/Detectors/Common/include + ${O2_DIR}/DataFormats/Detectors/ITSMFT/ITS/include + ${O2_DIR}/DataFormats/Detectors/TPC/include + ${O2_DIR}/DataFormats/Detectors/TRD/include + ${O2_DIR}/DataFormats/Headers/include + ${O2_DIR}/DataFormats/MemoryResources/include + ${O2_DIR}/DataFormats/Reconstruction/include + ${O2_DIR}/DataFormats/Reconstruction/src + ${O2_DIR}/DataFormats/simulation/include + ${O2_DIR}/Detectors/Base/include + ${O2_DIR}/Detectors/Base/src + ${O2_DIR}/Detectors/ITSMFT/ITS/tracking/include + ${O2_DIR}/Detectors/ITSMFT/ITS/tracking/cuda/include + ${O2_DIR}/Detectors/ITSMFT/ITS/tracking/cuda/src + ${O2_DIR}/Detectors/ITSMFT/ITS/tracking/hip/include + ${O2_DIR}/Detectors/ITSMFT/ITS/tracking/hip/src + ${O2_DIR}/Detectors/Raw/include + ${O2_DIR}/Detectors/TPC/base/include + ${O2_DIR}/Detectors/TRD/base/include + ${O2_DIR}/Detectors/TRD/base/src) endif() # Create main targets @@ -180,29 +184,29 @@ target_compile_definitions(standalone_support PUBLIC $ Date: Mon, 3 May 2021 20:54:37 +0200 Subject: [PATCH 380/770] Add missing headers --- Detectors/Vertexing/include/DetectorsVertexing/SVertexer.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Detectors/Vertexing/include/DetectorsVertexing/SVertexer.h b/Detectors/Vertexing/include/DetectorsVertexing/SVertexer.h index 22f196e9a1b8d..a1b792951a0a7 100644 --- a/Detectors/Vertexing/include/DetectorsVertexing/SVertexer.h +++ b/Detectors/Vertexing/include/DetectorsVertexing/SVertexer.h @@ -25,6 +25,8 @@ #include "DetectorsVertexing/DCAFitterN.h" #include "DetectorsVertexing/SVertexerParams.h" #include "DetectorsVertexing/SVertexHypothesis.h" +#include +#include namespace o2 { From 8d6321b4277f0bf99b4c7babda541e456a482d98 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 3 May 2021 21:02:42 +0200 Subject: [PATCH 381/770] GPU: Add extra library with GPU external data types --- GPU/GPUTracking/CMakeLists.txt | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/GPU/GPUTracking/CMakeLists.txt b/GPU/GPUTracking/CMakeLists.txt index ba895d994a55d..176b3bd3c8d43 100644 --- a/GPU/GPUTracking/CMakeLists.txt +++ b/GPU/GPUTracking/CMakeLists.txt @@ -266,6 +266,13 @@ if (TARGET AliceO2::DebugGUI) endif() # Main CMake part for O2 if(ALIGPU_BUILD_TYPE STREQUAL "O2") + o2_add_library(GPUDataTypeHeaders + PUBLIC_INCLUDE_DIRECTORIES . + Definitions + DataTypes + PUBLIC_LINK_LIBRARIES O2::GPUCommon + SOURCES utils/EmptyFile.cxx) + o2_add_library(${MODULE} TARGETVARNAME targetName PUBLIC_LINK_LIBRARIES O2::GPUCommon @@ -361,7 +368,7 @@ if(ALIGPU_BUILD_TYPE STREQUAL "ALIROOT") ${CMAKE_SOURCE_DIR}/GPU/GPUTracking/TPCConvert ${CMAKE_SOURCE_DIR}/GPU/GPUTracking/dEdx ${CMAKE_SOURCE_DIR}/GPU/GPUTracking/TRDTracking - ${CMAKE_SOURCE_DIR}/GPU/GPUTracking/Standalone + ${CMAKE_SOURCE_DIR}/GPU/GPUTracking/utils ${CMAKE_SOURCE_DIR}/GPU/GPUTracking/Base/cuda ${CMAKE_SOURCE_DIR}/GPU/GPUTracking/Base/hip ${CMAKE_SOURCE_DIR}/GPU/GPUTracking/Base/opencl-common From 5590e27227de3aee35914a02358247f8b8030796 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 3 May 2021 21:06:14 +0200 Subject: [PATCH 382/770] RecoContainer / DataRequest / InputHelper support TRDTracklets --- .../Detectors/GlobalTracking/CMakeLists.txt | 4 ++- .../DataFormatsGlobalTracking/RecoContainer.h | 27 ++++++++++++++++--- .../GlobalTracking/src/RecoContainer.cxx | 20 ++++++++++++++ .../include/DataFormatsTPC/WorkflowHelper.h | 2 +- Detectors/GlobalTracking/src/MatchCosmics.cxx | 1 + Detectors/GlobalTracking/src/MatchTPCITS.cxx | 2 +- .../helpers/CMakeLists.txt | 1 + .../helpers/src/InputHelper.cxx | 4 +++ 8 files changed, 55 insertions(+), 6 deletions(-) diff --git a/DataFormats/Detectors/GlobalTracking/CMakeLists.txt b/DataFormats/Detectors/GlobalTracking/CMakeLists.txt index eb98c4e67fc9a..4ea9381e6fc3c 100644 --- a/DataFormats/Detectors/GlobalTracking/CMakeLists.txt +++ b/DataFormats/Detectors/GlobalTracking/CMakeLists.txt @@ -19,4 +19,6 @@ o2_add_library( O2::DataFormatsFT0 O2::DataFormatsTOF O2::DataFormatsFT0 - O2::ReconstructionDataFormats) + O2::ReconstructionDataFormats + O2::TRDReconstruction + O2::GPUDataTypeHeaders) diff --git a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h index 14d20020ae267..680b7cc01c772 100644 --- a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h +++ b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h @@ -21,13 +21,29 @@ #include "ReconstructionDataFormats/GlobalTrackAccessor.h" #include "ReconstructionDataFormats/GlobalTrackID.h" #include "CommonDataFormat/AbstractRefAccessor.h" -#include "DataFormatsTPC/WorkflowHelper.h" #include "SimulationDataFormat/MCCompLabel.h" +#include "SimulationDataFormat/MCTruthContainer.h" +#include "SimulationDataFormat/ConstMCTruthContainer.h" #include +#include -namespace o2 +// We forward declare the internal structures, to reduce header dependencies. +// Please include headers for TPC Hits or TRD tracklets directly (DataFormatsTPC/WorkflowHelper.h / TRDReconstruction/RecoInputContainer.h) +namespace o2::tpc +{ +using TPCClRefElem = uint32_t; +namespace internal +{ +struct getWorkflowTPCInput_ret; +} // namespace internal +} // namespace o2::tpc +namespace o2::trd { +struct RecoInputContainer; +} // namespace o2::trd +namespace o2 +{ namespace globaltracking { @@ -49,9 +65,12 @@ struct DataRequest { void requestITSClusters(bool mc); void requestTPCClusters(bool mc); void requestTOFClusters(bool mc); + void requestTRDTracklets(); }; struct RecoContainer { + RecoContainer(); + ~RecoContainer(); using TracksAccessor = o2::dataformats::GlobalTrackAccessor; using VariaAccessor = o2::dataformats::AbstractRefAccessor; // there is no unique structure, so the default return type is dummy (int) using MCAccessor = o2::dataformats::AbstractRefAccessor; @@ -74,7 +93,8 @@ struct RecoContainer { gsl::span clusterShMapTPC; ///< externally set TPC clusters sharing map - std::invoke_result::type inputsTPCclusters; // special struct for TPC clusters access + std::unique_ptr inputsTPCclusters; // special struct for TPC clusters access + std::unique_ptr inputsTRD; // special struct for TRD tracklets, trigger records void collectData(o2::framework::ProcessingContext& pc, const DataRequest& request); void createTracks(std::function const& creator) const; @@ -90,6 +110,7 @@ struct RecoContainer { void addITSClusters(o2::framework::ProcessingContext& pc, bool mc); void addTPCClusters(o2::framework::ProcessingContext& pc, bool mc); void addTOFClusters(o2::framework::ProcessingContext& pc, bool mc); + void addTRDTracklets(o2::framework::ProcessingContext& pc); void addFT0RecPoints(o2::framework::ProcessingContext& pc, bool mc); diff --git a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx index 1acd9225b2445..ba2d121fa5d5c 100644 --- a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx +++ b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx @@ -15,6 +15,8 @@ #include #include #include "DetectorsCommonDataFormats/DetID.h" +#include "DataFormatsTPC/WorkflowHelper.h" +#include "TRDReconstruction/RecoInputContainer.h" #include "DataFormatsGlobalTracking/RecoContainer.h" #include "DataFormatsITSMFT/CompCluster.h" #include "DataFormatsITS/TrackITS.h" @@ -33,6 +35,9 @@ namespace o2d = o2::dataformats; using GTrackID = o2d::GlobalTrackID; using DetID = o2::detectors::DetID; +RecoContainer::RecoContainer() = default; +RecoContainer::~RecoContainer() = default; + void DataRequest::addInput(const InputSpec&& isp) { if (std::find(inputs.begin(), inputs.end(), isp) == inputs.end()) { @@ -119,6 +124,13 @@ void DataRequest::requestTOFClusters(bool mc) requestMap["clusTOF"] = mc; } +void DataRequest::requestTRDTracklets() +{ + addInput({"trdtracklets", o2::header::gDataOriginTRD, "TRACKLETS", 0, Lifetime::Timeframe}); + addInput({"trdctracklets", o2::header::gDataOriginTRD, "CTRACKLETS", 0, Lifetime::Timeframe}); + addInput({"trdtriggerrec", o2::header::gDataOriginTRD, "TRKTRGRD", 0, Lifetime::Timeframe}); +} + void DataRequest::requestFT0RecPoints(bool mc) { addInput({"ft0recpoints", "FT0", "RECPOINTS", 0, Lifetime::Timeframe}); @@ -163,6 +175,9 @@ void DataRequest::requestClusters(GTrackID::mask_t src, bool useMC) if (GTrackID::includesDet(DetID::TOF, src)) { requestTOFClusters(useMC); } + if (GTrackID::includesDet(DetID::TRD, src)) { + requestTRDTracklets(); + } } //__________________________________________________________________ @@ -286,6 +301,11 @@ void RecoContainer::addTPCClusters(ProcessingContext& pc, bool mc) clusterShMapTPC = pc.inputs().get>("clusTPCshmap"); } +void RecoContainer::addTRDTracklets(ProcessingContext& pc) +{ + inputsTRD = o2::trd::getRecoInputContainer(pc, nullptr, this); +} + //__________________________________________________________ void RecoContainer::addTOFClusters(ProcessingContext& pc, bool mc) { diff --git a/DataFormats/Detectors/TPC/include/DataFormatsTPC/WorkflowHelper.h b/DataFormats/Detectors/TPC/include/DataFormatsTPC/WorkflowHelper.h index 9db5fb507c0cf..ebc4f97f3992f 100644 --- a/DataFormats/Detectors/TPC/include/DataFormatsTPC/WorkflowHelper.h +++ b/DataFormats/Detectors/TPC/include/DataFormatsTPC/WorkflowHelper.h @@ -180,7 +180,7 @@ static auto getWorkflowTPCInput(o2::framework::ProcessingContext& pc, int verbos ClusterNativeHelper::Reader::fillIndex(retVal->clusterIndex, retVal->internal.clusterBuffer, retVal->internal.clustersMCBuffer, retVal->internal.inputs, retVal->internal.mcInputs, tpcSectorMask); } - return retVal; + return std::move(retVal); } } // namespace tpc diff --git a/Detectors/GlobalTracking/src/MatchCosmics.cxx b/Detectors/GlobalTracking/src/MatchCosmics.cxx index fb98973975eaa..409686c8ea812 100644 --- a/Detectors/GlobalTracking/src/MatchCosmics.cxx +++ b/Detectors/GlobalTracking/src/MatchCosmics.cxx @@ -28,6 +28,7 @@ #include "TPCReconstruction/TPCFastTransformHelperO2.h" #include "GlobalTracking/MatchTPCITS.h" #include "CommonConstants/GeomConstants.h" +#include "DataFormatsTPC/WorkflowHelper.h" #include #include diff --git a/Detectors/GlobalTracking/src/MatchTPCITS.cxx b/Detectors/GlobalTracking/src/MatchTPCITS.cxx index 92c3147c6e7f9..ab350fa0fc9ea 100644 --- a/Detectors/GlobalTracking/src/MatchTPCITS.cxx +++ b/Detectors/GlobalTracking/src/MatchTPCITS.cxx @@ -40,7 +40,7 @@ #include "DetectorsCommonDataFormats/NameConf.h" #include "ReconstructionDataFormats/Vertex.h" #include "GlobalTracking/MatchTPCITS.h" - +#include "DataFormatsTPC/WorkflowHelper.h" #include "DataFormatsGlobalTracking/RecoContainer.h" #include "ITStracking/IOUtils.h" diff --git a/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt b/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt index b94b5fe6b37e6..256d970b9a209 100644 --- a/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt +++ b/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt @@ -19,6 +19,7 @@ o2_add_library(GlobalTrackingWorkflowHelpers O2::TOFWorkflow O2::FT0Workflow O2::ITSMFTWorkflow + O2::TRDWorkflowIO O2::SimulationDataFormat) o2_add_executable(track-cluster-reader diff --git a/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx b/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx index 0751fa1440473..00784618968aa 100644 --- a/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx +++ b/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx @@ -21,6 +21,7 @@ #include "TOFWorkflowUtils/ClusterReaderSpec.h" #include "TOFWorkflow/TOFMatchedReaderSpec.h" #include "FT0Workflow/RecPointReaderSpec.h" +#include "TRDWorkflowIO/TRDTrackletReaderSpec.h" using namespace o2::framework; using namespace o2::globaltracking; @@ -71,6 +72,9 @@ int InputHelper::addInputSpecs(const ConfigContext& configcontext, WorkflowSpec& if (maskTracks[GID::FT0] || maskClusters[GID::FT0]) { specs.emplace_back(o2::ft0::getRecPointReaderSpec(maskTracksMC[GID::FT0] || maskClustersMC[GID::FT0])); } + if (maskClusters[GID::TRD]) { + specs.emplace_back(o2::trd::getTRDTrackletReaderSpec(maskClustersMC[GID::TRD], true)); + } return 0; } From 969702c17b7b283007e2ccf9bffcc6c82484e6ed Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 3 May 2021 21:40:41 +0200 Subject: [PATCH 383/770] TPC: Move raw encoder to workflow, since it depends on GPU code --- Detectors/TPC/simulation/CMakeLists.txt | 5 ----- Detectors/TPC/workflow/CMakeLists.txt | 5 +++++ .../run => workflow/src}/convertDigitsToRawZS.cxx | 0 3 files changed, 5 insertions(+), 5 deletions(-) rename Detectors/TPC/{simulation/run => workflow/src}/convertDigitsToRawZS.cxx (100%) diff --git a/Detectors/TPC/simulation/CMakeLists.txt b/Detectors/TPC/simulation/CMakeLists.txt index 92764ade94c57..f707194ea8320 100644 --- a/Detectors/TPC/simulation/CMakeLists.txt +++ b/Detectors/TPC/simulation/CMakeLists.txt @@ -39,11 +39,6 @@ o2_target_root_dictionary(TPCSimulation include/TPCSimulation/Point.h include/TPCSimulation/SAMPAProcessing.h) -o2_add_executable(digits-to-rawzs - COMPONENT_NAME tpc - PUBLIC_LINK_LIBRARIES O2::TPCBase O2::SimulationDataFormat O2::GPUO2Interface O2::GPUTracking O2::DetectorsRaw - SOURCES run/convertDigitsToRawZS.cxx) - o2_data_file(COPY files DESTINATION Detectors/TPC) o2_data_file(COPY data DESTINATION Detectors/TPC/simulation) diff --git a/Detectors/TPC/workflow/CMakeLists.txt b/Detectors/TPC/workflow/CMakeLists.txt index 2d22b18cd1f59..674dc451fa9b3 100644 --- a/Detectors/TPC/workflow/CMakeLists.txt +++ b/Detectors/TPC/workflow/CMakeLists.txt @@ -90,3 +90,8 @@ if(GPUCA_EVENT_DISPLAY OR AND NOT CMAKE_SYSTEM_NAME STREQUAL "Darwin")) target_compile_definitions(${targetName} PRIVATE GPUCA_BUILD_EVENT_DISPLAY) endif() + +o2_add_executable(digits-to-rawzs + COMPONENT_NAME tpc + PUBLIC_LINK_LIBRARIES O2::TPCBase O2::SimulationDataFormat O2::GPUO2Interface O2::GPUTracking O2::DetectorsRaw + SOURCES src/convertDigitsToRawZS.cxx) diff --git a/Detectors/TPC/simulation/run/convertDigitsToRawZS.cxx b/Detectors/TPC/workflow/src/convertDigitsToRawZS.cxx similarity index 100% rename from Detectors/TPC/simulation/run/convertDigitsToRawZS.cxx rename to Detectors/TPC/workflow/src/convertDigitsToRawZS.cxx From fc459d8e5b035fbadaf5d518a4260ad8de7e123e Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 3 May 2021 21:57:07 +0200 Subject: [PATCH 384/770] TPC Workflow: Move TPC readers into separate TPCReaderWorkflow library --- Detectors/AOD/src/AODProducerWorkflow.cxx | 4 +-- .../helpers/CMakeLists.txt | 1 + .../helpers/src/InputHelper.cxx | 4 +-- .../src/cosmics-match-workflow.cxx | 6 ++--- .../src/primary-vertexing-workflow.cxx | 2 +- .../src/secondary-vertexing-workflow.cxx | 2 +- .../src/tpcits-match-workflow.cxx | 2 +- .../tofworkflow/src/tof-matcher-tpc.cxx | 4 +-- .../src/TrackInterpolationWorkflow.cxx | 4 +-- .../src/tpc-interpolation-workflow.cxx | 2 +- Detectors/TPC/workflow/CMakeLists.txt | 8 +++--- Detectors/TPC/workflow/readers/CMakeLists.txt | 26 +++++++++++++++++++ .../TPCReaderWorkflow}/ClusterReaderSpec.h | 0 .../TPCReaderWorkflow}/PublisherSpec.h | 0 .../TPCSectorCompletionPolicy.h | 0 .../TPCReaderWorkflow}/TrackReaderSpec.h | 0 .../{ => readers}/src/ClusterReaderSpec.cxx | 2 +- .../{ => readers}/src/PublisherSpec.cxx | 2 +- .../{ => readers}/src/TrackReaderSpec.cxx | 2 +- .../TPC/workflow/src/FileReaderWorkflow.cxx | 4 +-- Detectors/TPC/workflow/src/RecoWorkflow.cxx | 4 +-- .../TPC/workflow/src/TrackReaderWorkflow.cxx | 2 +- .../TPC/workflow/src/tpc-reco-workflow.cxx | 2 +- .../TRD/workflow/src/TRDTrackingWorkflow.cxx | 2 +- GPU/Workflow/CMakeLists.txt | 13 +++++++--- GPU/Workflow/src/gpu-reco-workflow.cxx | 2 +- doc/data/2021-01-o2_prs.json | 2 +- 27 files changed, 67 insertions(+), 35 deletions(-) create mode 100644 Detectors/TPC/workflow/readers/CMakeLists.txt rename Detectors/TPC/workflow/{include/TPCWorkflow => readers/include/TPCReaderWorkflow}/ClusterReaderSpec.h (100%) rename Detectors/TPC/workflow/{include/TPCWorkflow => readers/include/TPCReaderWorkflow}/PublisherSpec.h (100%) rename {GPU/Workflow/include/GPUWorkflow => Detectors/TPC/workflow/readers/include/TPCReaderWorkflow}/TPCSectorCompletionPolicy.h (100%) rename Detectors/TPC/workflow/{include/TPCWorkflow => readers/include/TPCReaderWorkflow}/TrackReaderSpec.h (100%) rename Detectors/TPC/workflow/{ => readers}/src/ClusterReaderSpec.cxx (98%) rename Detectors/TPC/workflow/{ => readers}/src/PublisherSpec.cxx (99%) rename Detectors/TPC/workflow/{ => readers}/src/TrackReaderSpec.cxx (99%) diff --git a/Detectors/AOD/src/AODProducerWorkflow.cxx b/Detectors/AOD/src/AODProducerWorkflow.cxx index a7c1e82795b81..d5439d7e1ae6e 100644 --- a/Detectors/AOD/src/AODProducerWorkflow.cxx +++ b/Detectors/AOD/src/AODProducerWorkflow.cxx @@ -24,8 +24,8 @@ #include "GlobalTrackingWorkflow/TrackWriterTPCITSSpec.h" #include "ITSMFTWorkflow/ClusterReaderSpec.h" #include "ITSWorkflow/TrackReaderSpec.h" -#include "TPCWorkflow/PublisherSpec.h" -#include "TPCWorkflow/TrackReaderSpec.h" +#include "TPCReaderWorkflow/PublisherSpec.h" +#include "TPCReaderWorkflow/TrackReaderSpec.h" namespace o2::aodproducer { diff --git a/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt b/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt index 256d970b9a209..d1dfea441788d 100644 --- a/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt +++ b/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt @@ -20,6 +20,7 @@ o2_add_library(GlobalTrackingWorkflowHelpers O2::FT0Workflow O2::ITSMFTWorkflow O2::TRDWorkflowIO + O2::TPCReaderWorkflow O2::SimulationDataFormat) o2_add_executable(track-cluster-reader diff --git a/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx b/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx index 00784618968aa..a510f0dd763ff 100644 --- a/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx +++ b/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx @@ -14,8 +14,8 @@ #include "Framework/ConfigParamRegistry.h" #include "ITSMFTWorkflow/ClusterReaderSpec.h" #include "ITSWorkflow/TrackReaderSpec.h" -#include "TPCWorkflow/TrackReaderSpec.h" -#include "TPCWorkflow/ClusterReaderSpec.h" +#include "TPCReaderWorkflow/TrackReaderSpec.h" +#include "TPCReaderWorkflow/ClusterReaderSpec.h" #include "TPCWorkflow/ClusterSharingMapSpec.h" #include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" #include "TOFWorkflowUtils/ClusterReaderSpec.h" diff --git a/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx index 0219756728cf1..090f38c88d37b 100644 --- a/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/cosmics-match-workflow.cxx @@ -10,11 +10,11 @@ #include "CommonUtils/ConfigurableParam.h" #include "Framework/CompletionPolicy.h" -#include "GPUWorkflow/TPCSectorCompletionPolicy.h" +#include "TPCReaderWorkflow/TPCSectorCompletionPolicy.h" #include "ITSWorkflow/TrackReaderSpec.h" #include "ITSMFTWorkflow/ClusterReaderSpec.h" -#include "TPCWorkflow/TrackReaderSpec.h" -#include "TPCWorkflow/ClusterReaderSpec.h" +#include "TPCReaderWorkflow/TrackReaderSpec.h" +#include "TPCReaderWorkflow/ClusterReaderSpec.h" #include "TPCWorkflow/ClusterSharingMapSpec.h" #include "TOFWorkflowUtils/ClusterReaderSpec.h" #include "TOFWorkflow/TOFMatchedReaderSpec.h" diff --git a/Detectors/GlobalTrackingWorkflow/src/primary-vertexing-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/primary-vertexing-workflow.cxx index 008d1bdaa111b..8588c65e6eb4e 100644 --- a/Detectors/GlobalTrackingWorkflow/src/primary-vertexing-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/primary-vertexing-workflow.cxx @@ -14,7 +14,7 @@ #include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" #include "GlobalTrackingWorkflow/VertexTrackMatcherSpec.h" #include "ITSWorkflow/TrackReaderSpec.h" -#include "TPCWorkflow/TrackReaderSpec.h" +#include "TPCReaderWorkflow/TrackReaderSpec.h" #include "TOFWorkflow/TOFMatchedReaderSpec.h" #include "TOFWorkflowUtils/ClusterReaderSpec.h" #include "FT0Workflow/RecPointReaderSpec.h" diff --git a/Detectors/GlobalTrackingWorkflow/src/secondary-vertexing-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/secondary-vertexing-workflow.cxx index ca481de0887bc..150b884d3fdc2 100644 --- a/Detectors/GlobalTrackingWorkflow/src/secondary-vertexing-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/secondary-vertexing-workflow.cxx @@ -14,7 +14,7 @@ #include "GlobalTrackingWorkflowReaders/PrimaryVertexReaderSpec.h" #include "GlobalTrackingWorkflowHelpers/InputHelper.h" #include "ITSWorkflow/TrackReaderSpec.h" -#include "TPCWorkflow/TrackReaderSpec.h" +#include "TPCReaderWorkflow/TrackReaderSpec.h" #include "TOFWorkflow/TOFMatchedReaderSpec.h" #include "TOFWorkflowUtils/ClusterReaderSpec.h" #include "ReconstructionDataFormats/GlobalTrackID.h" diff --git a/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx b/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx index 5e52eb80f006a..eb1e792f07300 100644 --- a/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/tpcits-match-workflow.cxx @@ -17,7 +17,7 @@ #include "DetectorsCommonDataFormats/DetID.h" #include "CommonUtils/ConfigurableParam.h" #include "Framework/CompletionPolicy.h" -#include "GPUWorkflow/TPCSectorCompletionPolicy.h" +#include "TPCReaderWorkflow/TPCSectorCompletionPolicy.h" #include "DetectorsRaw/HBFUtilsInitializer.h" using namespace o2::framework; diff --git a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-tpc.cxx b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-tpc.cxx index a7256d388e2e4..74846ee296bbd 100644 --- a/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-tpc.cxx +++ b/Detectors/GlobalTrackingWorkflow/tofworkflow/src/tof-matcher-tpc.cxx @@ -24,8 +24,8 @@ #include "FairLogger.h" #include "CommonUtils/ConfigurableParam.h" #include "DetectorsCommonDataFormats/NameConf.h" -#include "TPCWorkflow/TrackReaderSpec.h" -#include "TPCWorkflow/ClusterReaderSpec.h" +#include "TPCReaderWorkflow/TrackReaderSpec.h" +#include "TPCReaderWorkflow/ClusterReaderSpec.h" #include "TPCWorkflow/ClusterSharingMapSpec.h" #include "DetectorsRaw/HBFUtilsInitializer.h" diff --git a/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TrackInterpolationWorkflow.cxx b/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TrackInterpolationWorkflow.cxx index 985b30532ef34..60154d0af13c2 100644 --- a/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TrackInterpolationWorkflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/TrackInterpolationWorkflow.cxx @@ -13,8 +13,8 @@ #include #include "ITSWorkflow/TrackReaderSpec.h" -#include "TPCWorkflow/TrackReaderSpec.h" -#include "TPCWorkflow/ClusterReaderSpec.h" +#include "TPCReaderWorkflow/TrackReaderSpec.h" +#include "TPCReaderWorkflow/ClusterReaderSpec.h" #include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" #include "TOFWorkflowUtils/ClusterReaderSpec.h" #include "TOFWorkflow/TOFMatchedReaderSpec.h" diff --git a/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/tpc-interpolation-workflow.cxx b/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/tpc-interpolation-workflow.cxx index b49410add2878..1205f53bf00b9 100644 --- a/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/tpc-interpolation-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/tpcinterpolationworkflow/src/tpc-interpolation-workflow.cxx @@ -11,7 +11,7 @@ #include "TPCInterpolationWorkflow/TrackInterpolationWorkflow.h" #include "CommonUtils/ConfigurableParam.h" #include "Framework/CompletionPolicy.h" -#include "GPUWorkflow/TPCSectorCompletionPolicy.h" +#include "TPCReaderWorkflow/TPCSectorCompletionPolicy.h" #include "DetectorsRaw/HBFUtilsInitializer.h" using namespace o2::framework; diff --git a/Detectors/TPC/workflow/CMakeLists.txt b/Detectors/TPC/workflow/CMakeLists.txt index 674dc451fa9b3..07f0ad6b6a943 100644 --- a/Detectors/TPC/workflow/CMakeLists.txt +++ b/Detectors/TPC/workflow/CMakeLists.txt @@ -10,13 +10,10 @@ o2_add_library(TPCWorkflow SOURCES src/RecoWorkflow.cxx - src/ClusterReaderSpec.cxx - src/PublisherSpec.cxx src/ClustererSpec.cxx src/ClusterDecoderRawSpec.cxx src/EntropyEncoderSpec.cxx src/EntropyDecoderSpec.cxx - src/TrackReaderSpec.cxx src/RawToDigitsSpec.cxx src/LinkZSToDigitsSpec.cxx src/ZSSpec.cxx @@ -30,8 +27,9 @@ o2_add_library(TPCWorkflow O2::DPLUtils O2::TPCReconstruction O2::TPCCalibration O2::TPCSimulation O2::TPCQC O2::DetectorsCalibration - O2::GPUWorkflow + O2::TPCReaderWorkflow PRIVATE_LINK_LIBRARIES O2::GPUTracking # For the Zero Suppression includes + O2::GPUWorkflow ) @@ -95,3 +93,5 @@ o2_add_executable(digits-to-rawzs COMPONENT_NAME tpc PUBLIC_LINK_LIBRARIES O2::TPCBase O2::SimulationDataFormat O2::GPUO2Interface O2::GPUTracking O2::DetectorsRaw SOURCES src/convertDigitsToRawZS.cxx) + +add_subdirectory(readers) diff --git a/Detectors/TPC/workflow/readers/CMakeLists.txt b/Detectors/TPC/workflow/readers/CMakeLists.txt new file mode 100644 index 0000000000000..a1a5293e440b4 --- /dev/null +++ b/Detectors/TPC/workflow/readers/CMakeLists.txt @@ -0,0 +1,26 @@ +# Copyright CERN and copyright holders of ALICE O2. This software is distributed +# under the terms of the GNU General Public License v3 (GPL Version 3), copied +# verbatim in the file "COPYING". +# +# See http://alice-o2.web.cern.ch/license for full licensing information. +# +# In applying this license CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization or +# submit itself to any jurisdiction. + +o2_add_library(TPCReaderWorkflow + SOURCES src/ClusterReaderSpec.cxx + src/PublisherSpec.cxx + src/TrackReaderSpec.cxx + TARGETVARNAME targetName + PUBLIC_LINK_LIBRARIES O2::Framework + O2::DataFormatsTPC + O2::DPLUtils + O2::TPCBase + ) + +if(OpenMP_CXX_FOUND) + # Must be private, depending libraries might be compiled by compiler not understanding -fopenmp + target_compile_definitions(${mergertargetName} PRIVATE WITH_OPENMP) + target_link_libraries(${mergertargetName} PRIVATE OpenMP::OpenMP_CXX) +endif() diff --git a/Detectors/TPC/workflow/include/TPCWorkflow/ClusterReaderSpec.h b/Detectors/TPC/workflow/readers/include/TPCReaderWorkflow/ClusterReaderSpec.h similarity index 100% rename from Detectors/TPC/workflow/include/TPCWorkflow/ClusterReaderSpec.h rename to Detectors/TPC/workflow/readers/include/TPCReaderWorkflow/ClusterReaderSpec.h diff --git a/Detectors/TPC/workflow/include/TPCWorkflow/PublisherSpec.h b/Detectors/TPC/workflow/readers/include/TPCReaderWorkflow/PublisherSpec.h similarity index 100% rename from Detectors/TPC/workflow/include/TPCWorkflow/PublisherSpec.h rename to Detectors/TPC/workflow/readers/include/TPCReaderWorkflow/PublisherSpec.h diff --git a/GPU/Workflow/include/GPUWorkflow/TPCSectorCompletionPolicy.h b/Detectors/TPC/workflow/readers/include/TPCReaderWorkflow/TPCSectorCompletionPolicy.h similarity index 100% rename from GPU/Workflow/include/GPUWorkflow/TPCSectorCompletionPolicy.h rename to Detectors/TPC/workflow/readers/include/TPCReaderWorkflow/TPCSectorCompletionPolicy.h diff --git a/Detectors/TPC/workflow/include/TPCWorkflow/TrackReaderSpec.h b/Detectors/TPC/workflow/readers/include/TPCReaderWorkflow/TrackReaderSpec.h similarity index 100% rename from Detectors/TPC/workflow/include/TPCWorkflow/TrackReaderSpec.h rename to Detectors/TPC/workflow/readers/include/TPCReaderWorkflow/TrackReaderSpec.h diff --git a/Detectors/TPC/workflow/src/ClusterReaderSpec.cxx b/Detectors/TPC/workflow/readers/src/ClusterReaderSpec.cxx similarity index 98% rename from Detectors/TPC/workflow/src/ClusterReaderSpec.cxx rename to Detectors/TPC/workflow/readers/src/ClusterReaderSpec.cxx index 23a3b9d4353c4..7e6f38d1e88cb 100644 --- a/Detectors/TPC/workflow/src/ClusterReaderSpec.cxx +++ b/Detectors/TPC/workflow/readers/src/ClusterReaderSpec.cxx @@ -13,7 +13,7 @@ #include "Framework/WorkflowSpec.h" #include "DPLUtils/RootTreeReader.h" -#include "TPCWorkflow/PublisherSpec.h" +#include "TPCReaderWorkflow/PublisherSpec.h" #include "SimulationDataFormat/IOMCTruthContainerView.h" #include "SimulationDataFormat/ConstMCTruthContainer.h" #include "SimulationDataFormat/MCCompLabel.h" diff --git a/Detectors/TPC/workflow/src/PublisherSpec.cxx b/Detectors/TPC/workflow/readers/src/PublisherSpec.cxx similarity index 99% rename from Detectors/TPC/workflow/src/PublisherSpec.cxx rename to Detectors/TPC/workflow/readers/src/PublisherSpec.cxx index 619c6ad7a3d57..f5a0bc7ba0174 100644 --- a/Detectors/TPC/workflow/src/PublisherSpec.cxx +++ b/Detectors/TPC/workflow/readers/src/PublisherSpec.cxx @@ -15,7 +15,7 @@ #include "Framework/ConfigParamRegistry.h" #include "Framework/ControlService.h" -#include "TPCWorkflow/PublisherSpec.h" +#include "TPCReaderWorkflow/PublisherSpec.h" #include "Headers/DataHeader.h" #include "TPCBase/Sector.h" #include "DetectorsCommonDataFormats/NameConf.h" diff --git a/Detectors/TPC/workflow/src/TrackReaderSpec.cxx b/Detectors/TPC/workflow/readers/src/TrackReaderSpec.cxx similarity index 99% rename from Detectors/TPC/workflow/src/TrackReaderSpec.cxx rename to Detectors/TPC/workflow/readers/src/TrackReaderSpec.cxx index dd860bd5cc6cf..c01c606ebdca3 100644 --- a/Detectors/TPC/workflow/src/TrackReaderSpec.cxx +++ b/Detectors/TPC/workflow/readers/src/TrackReaderSpec.cxx @@ -13,7 +13,7 @@ #include #include "Framework/ControlService.h" #include "Framework/ConfigParamRegistry.h" -#include "TPCWorkflow/TrackReaderSpec.h" +#include "TPCReaderWorkflow/TrackReaderSpec.h" #include "DetectorsCommonDataFormats/NameConf.h" using namespace o2::framework; diff --git a/Detectors/TPC/workflow/src/FileReaderWorkflow.cxx b/Detectors/TPC/workflow/src/FileReaderWorkflow.cxx index fc860708eeb65..052485f66d3e8 100644 --- a/Detectors/TPC/workflow/src/FileReaderWorkflow.cxx +++ b/Detectors/TPC/workflow/src/FileReaderWorkflow.cxx @@ -10,8 +10,8 @@ /// @file FileReaderWorkflow.cxx -#include "TPCWorkflow/ClusterReaderSpec.h" -#include "TPCWorkflow/TrackReaderSpec.h" +#include "TPCReaderWorkflow/ClusterReaderSpec.h" +#include "TPCReaderWorkflow/TrackReaderSpec.h" #include "Algorithm/RangeTokenizer.h" diff --git a/Detectors/TPC/workflow/src/RecoWorkflow.cxx b/Detectors/TPC/workflow/src/RecoWorkflow.cxx index 1a798c6f0760d..7c9b81827f9e1 100644 --- a/Detectors/TPC/workflow/src/RecoWorkflow.cxx +++ b/Detectors/TPC/workflow/src/RecoWorkflow.cxx @@ -18,7 +18,7 @@ #include "Framework/Logger.h" #include "DPLUtils/MakeRootTreeWriterSpec.h" #include "TPCWorkflow/RecoWorkflow.h" -#include "TPCWorkflow/PublisherSpec.h" +#include "TPCReaderWorkflow/PublisherSpec.h" #include "TPCWorkflow/ClustererSpec.h" #include "TPCWorkflow/ClusterDecoderRawSpec.h" #include "GPUWorkflow/GPUWorkflowSpec.h" @@ -37,7 +37,7 @@ #include "SimulationDataFormat/MCCompLabel.h" #include "DataFormatsTPC/Helpers.h" #include "DataFormatsTPC/ZeroSuppression.h" -#include "TPCWorkflow/ClusterReaderSpec.h" +#include "TPCReaderWorkflow/ClusterReaderSpec.h" #include #include diff --git a/Detectors/TPC/workflow/src/TrackReaderWorkflow.cxx b/Detectors/TPC/workflow/src/TrackReaderWorkflow.cxx index d24c8343091ca..8bfa355446f4a 100644 --- a/Detectors/TPC/workflow/src/TrackReaderWorkflow.cxx +++ b/Detectors/TPC/workflow/src/TrackReaderWorkflow.cxx @@ -23,7 +23,7 @@ #include "CommonUtils/ConfigurableParam.h" #include "Headers/DataHeaderHelpers.h" -#include "TPCWorkflow/TrackReaderSpec.h" +#include "TPCReaderWorkflow/TrackReaderSpec.h" #include #include diff --git a/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx b/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx index e1c404e999b83..069b48896ea71 100644 --- a/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx +++ b/Detectors/TPC/workflow/src/tpc-reco-workflow.cxx @@ -21,7 +21,7 @@ #include "Framework/PartRef.h" #include "Framework/ConcreteDataMatcher.h" #include "TPCWorkflow/RecoWorkflow.h" -#include "GPUWorkflow/TPCSectorCompletionPolicy.h" +#include "TPCReaderWorkflow/TPCSectorCompletionPolicy.h" #include "DataFormatsTPC/TPCSectorHeader.h" #include "Algorithm/RangeTokenizer.h" #include "CommonUtils/ConfigurableParam.h" diff --git a/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx b/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx index 9b41af4f68eb6..bd8f4344f348e 100644 --- a/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx +++ b/Detectors/TRD/workflow/src/TRDTrackingWorkflow.cxx @@ -14,8 +14,8 @@ #include "Framework/WorkflowSpec.h" #include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" -#include "TPCWorkflow/TrackReaderSpec.h" #include "TRDWorkflowIO/TRDTrackletReaderSpec.h" +#include "TPCReaderWorkflow/TrackReaderSpec.h" #include "TRDWorkflow/TRDTrackletTransformerSpec.h" #include "TRDWorkflow/TRDGlobalTrackingSpec.h" #include "TRDWorkflow/TRDTrackWriterSpec.h" diff --git a/GPU/Workflow/CMakeLists.txt b/GPU/Workflow/CMakeLists.txt index 4ba0580d59f1d..e8bea668df0cf 100644 --- a/GPU/Workflow/CMakeLists.txt +++ b/GPU/Workflow/CMakeLists.txt @@ -11,10 +11,15 @@ o2_add_library(GPUWorkflow SOURCES src/GPUWorkflowSpec.cxx TARGETVARNAME targetName - PUBLIC_LINK_LIBRARIES O2::Framework O2::DataFormatsTPC - O2::DPLUtils O2::TPCReconstruction - O2::TPCCalibration O2::TPCSimulation - O2::TPCQC O2::DetectorsCalibration + PUBLIC_LINK_LIBRARIES O2::Framework + O2::DataFormatsTPC + O2::DPLUtils + O2::TPCReconstruction + O2::TPCCalibration + O2::TPCSimulation + O2::TPCQC + O2::DetectorsCalibration + O2::TPCReaderWorkflow PRIVATE_LINK_LIBRARIES O2::GPUTracking) o2_add_executable(reco-workflow diff --git a/GPU/Workflow/src/gpu-reco-workflow.cxx b/GPU/Workflow/src/gpu-reco-workflow.cxx index c667536e7dac8..7f1d9a5278fea 100644 --- a/GPU/Workflow/src/gpu-reco-workflow.cxx +++ b/GPU/Workflow/src/gpu-reco-workflow.cxx @@ -16,7 +16,7 @@ #include "Framework/CompletionPolicyHelpers.h" #include "Framework/DispatchPolicy.h" #include "Framework/ConcreteDataMatcher.h" -#include "GPUWorkflow/TPCSectorCompletionPolicy.h" +#include "TPCReaderWorkflow/TPCSectorCompletionPolicy.h" #include "GPUWorkflow/GPUWorkflowSpec.h" #include "CommonUtils/ConfigurableParam.h" #include "DetectorsRaw/HBFUtilsInitializer.h" diff --git a/doc/data/2021-01-o2_prs.json b/doc/data/2021-01-o2_prs.json index 14c35a44cf296..12a0ea55f0699 100644 --- a/doc/data/2021-01-o2_prs.json +++ b/doc/data/2021-01-o2_prs.json @@ -4570,7 +4570,7 @@ }, { "node": { - "path": "Detectors/TPC/workflow/include/TPCWorkflow/PublisherSpec.h" + "path": "Detectors/TPC/workflow/include/TPCReaderWorkflow/PublisherSpec.h" } }, { From 7a6668424f308f7d702b448c09eeab7c6b2984d9 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 3 May 2021 21:43:45 +0200 Subject: [PATCH 385/770] Move TRD RecoInputContainer to TRD DataFormats --- .../include/DataFormatsGlobalTracking/RecoContainer.h | 2 +- DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx | 2 +- .../Detectors/TRD/include/DataFormatsTRD}/RecoInputContainer.h | 0 Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx | 2 +- 4 files changed, 3 insertions(+), 3 deletions(-) rename {Detectors/TRD/reconstruction/include/TRDReconstruction => DataFormats/Detectors/TRD/include/DataFormatsTRD}/RecoInputContainer.h (100%) diff --git a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h index 680b7cc01c772..6441e761feaa9 100644 --- a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h +++ b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h @@ -28,7 +28,7 @@ #include // We forward declare the internal structures, to reduce header dependencies. -// Please include headers for TPC Hits or TRD tracklets directly (DataFormatsTPC/WorkflowHelper.h / TRDReconstruction/RecoInputContainer.h) +// Please include headers for TPC Hits or TRD tracklets directly (DataFormatsTPC/WorkflowHelper.h / DataFormatsTRD/RecoInputContainer.h) namespace o2::tpc { using TPCClRefElem = uint32_t; diff --git a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx index ba2d121fa5d5c..1622e21db99e1 100644 --- a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx +++ b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx @@ -16,7 +16,7 @@ #include #include "DetectorsCommonDataFormats/DetID.h" #include "DataFormatsTPC/WorkflowHelper.h" -#include "TRDReconstruction/RecoInputContainer.h" +#include "DataFormatsTRD/RecoInputContainer.h" #include "DataFormatsGlobalTracking/RecoContainer.h" #include "DataFormatsITSMFT/CompCluster.h" #include "DataFormatsITS/TrackITS.h" diff --git a/Detectors/TRD/reconstruction/include/TRDReconstruction/RecoInputContainer.h b/DataFormats/Detectors/TRD/include/DataFormatsTRD/RecoInputContainer.h similarity index 100% rename from Detectors/TRD/reconstruction/include/TRDReconstruction/RecoInputContainer.h rename to DataFormats/Detectors/TRD/include/DataFormatsTRD/RecoInputContainer.h diff --git a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx index fa23fc830889d..7c3b57e901e88 100644 --- a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx @@ -22,7 +22,7 @@ #include "DataFormatsTRD/Constants.h" #include "TPCBase/ParameterElectronics.h" #include "TPCBase/ParameterGas.h" -#include "TRDReconstruction/RecoInputContainer.h" +#include "DataFormatsTRD/RecoInputContainer.h" // GPU header #include "GPUReconstruction.h" From 3bc7a6d562ab6b443d7219abb777141f76e5e208 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 3 May 2021 11:47:04 +0200 Subject: [PATCH 386/770] GPU: Read TRD tracklets for GPUWorkflow and GPU event display --- .../DataFormatsTRD/RecoInputContainer.h | 29 ++++++++------- Detectors/GlobalTracking/src/MatchTPCITS.cxx | 2 +- Detectors/TPC/workflow/CMakeLists.txt | 6 ---- .../workflow/src/TRDGlobalTrackingSpec.cxx | 2 +- .../Global/GPUChainTrackingTRD.cxx | 1 - GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx | 2 +- GPU/Workflow/CMakeLists.txt | 9 ++++- .../include/GPUWorkflow/GPUWorkflowSpec.h | 1 + GPU/Workflow/src/GPUWorkflowSpec.cxx | 33 +++++++++++++---- GPU/Workflow/src/O2GPUDPLDisplay.cxx | 36 +++++++++++++------ GPU/Workflow/src/gpu-reco-workflow.cxx | 7 ++-- 11 files changed, 86 insertions(+), 42 deletions(-) diff --git a/DataFormats/Detectors/TRD/include/DataFormatsTRD/RecoInputContainer.h b/DataFormats/Detectors/TRD/include/DataFormatsTRD/RecoInputContainer.h index ea28c15918bfa..407a1369891d6 100644 --- a/DataFormats/Detectors/TRD/include/DataFormatsTRD/RecoInputContainer.h +++ b/DataFormats/Detectors/TRD/include/DataFormatsTRD/RecoInputContainer.h @@ -49,7 +49,7 @@ struct RecoInputContainer { std::vector trdTriggerIndices; }; -inline auto getRecoInputContainer(o2::framework::ProcessingContext& pc, o2::gpu::GPUTrackingInOutPointers& ptrs, const o2::globaltracking::RecoContainer* inputTracks) +inline auto getRecoInputContainer(o2::framework::ProcessingContext& pc, o2::gpu::GPUTrackingInOutPointers* ptrs, const o2::globaltracking::RecoContainer* inputTracks) { auto retVal = std::make_unique(); retVal->mTracksTPCITS = inputTracks->getTPCITSTracks(); @@ -71,17 +71,22 @@ inline auto getRecoInputContainer(o2::framework::ProcessingContext& pc, o2::gpu: retVal->trdTriggerTimes.push_back(evTime / 1000.); // event time in us } - // the number of tracks loaded into the TRD tracker depends on the defined input sources - // TPC-only tracks which are already matched to the ITS will not be loaded as seeds for the tracking - // => the maximum number of seeds it the number of TPC-only tracks. If only ITS-TPC matches are considered than that - // of course defines the number of input tracks - ptrs.nMergedTracks = (retVal->mNTracksTPC == 0) ? retVal->mNTracksTPCITS : retVal->mNTracksTPC; - ptrs.nTRDTriggerRecords = retVal->mNTriggerRecords; - ptrs.trdTriggerTimes = &(retVal->trdTriggerTimes[0]); - ptrs.trdTrackletIdxFirst = &(retVal->trdTriggerIndices[0]); - ptrs.nTRDTracklets = retVal->mNTracklets; - ptrs.trdTracklets = reinterpret_cast(retVal->mTracklets.data()); - ptrs.trdSpacePoints = reinterpret_cast(retVal->mSpacePoints.data()); + if (ptrs) { + if (ptrs->nOutputTracksTPCO2 == 0 && retVal->mNTracksTPC) { + ptrs->nOutputTracksTPCO2 = retVal->mNTracksTPC; + ptrs->outputTracksTPCO2 = retVal->mTracksTPC.data(); + } + if (ptrs->nTracksTPCITSO2 == 0 && retVal->mNTracksTPCITS) { + ptrs->nTracksTPCITSO2 = retVal->mNTracksTPCITS; + ptrs->tracksTPCITSO2 = retVal->mTracksTPCITS.data(); + } + ptrs->nTRDTriggerRecords = retVal->mNTriggerRecords; + ptrs->trdTriggerTimes = &(retVal->trdTriggerTimes[0]); + ptrs->trdTrackletIdxFirst = &(retVal->trdTriggerIndices[0]); + ptrs->nTRDTracklets = retVal->mNTracklets; + ptrs->trdTracklets = reinterpret_cast(retVal->mTracklets.data()); + ptrs->trdSpacePoints = reinterpret_cast(retVal->mSpacePoints.data()); + } return std::move(retVal); } diff --git a/Detectors/GlobalTracking/src/MatchTPCITS.cxx b/Detectors/GlobalTracking/src/MatchTPCITS.cxx index ab350fa0fc9ea..fc7ae1cc009b5 100644 --- a/Detectors/GlobalTracking/src/MatchTPCITS.cxx +++ b/Detectors/GlobalTracking/src/MatchTPCITS.cxx @@ -40,8 +40,8 @@ #include "DetectorsCommonDataFormats/NameConf.h" #include "ReconstructionDataFormats/Vertex.h" #include "GlobalTracking/MatchTPCITS.h" -#include "DataFormatsTPC/WorkflowHelper.h" #include "DataFormatsGlobalTracking/RecoContainer.h" +#include "DataFormatsTPC/WorkflowHelper.h" #include "ITStracking/IOUtils.h" diff --git a/Detectors/TPC/workflow/CMakeLists.txt b/Detectors/TPC/workflow/CMakeLists.txt index 07f0ad6b6a943..b7f71050ee394 100644 --- a/Detectors/TPC/workflow/CMakeLists.txt +++ b/Detectors/TPC/workflow/CMakeLists.txt @@ -83,12 +83,6 @@ o2_add_test(workflow PUBLIC_LINK_LIBRARIES O2::TPCWorkflow ENVIRONMENT O2_ROOT=${CMAKE_BINARY_DIR}/stage) -if(GPUCA_EVENT_DISPLAY OR - (OPENGL_FOUND AND GLFW_FOUND AND TARGET AliceO2::DebugGUI AND OPENGL_GLU_FOUND - AND NOT CMAKE_SYSTEM_NAME STREQUAL "Darwin")) - target_compile_definitions(${targetName} PRIVATE GPUCA_BUILD_EVENT_DISPLAY) -endif() - o2_add_executable(digits-to-rawzs COMPONENT_NAME tpc PUBLIC_LINK_LIBRARIES O2::TPCBase O2::SimulationDataFormat O2::GPUO2Interface O2::GPUTracking O2::DetectorsRaw diff --git a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx index 7c3b57e901e88..e44d9ece665b4 100644 --- a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx @@ -101,7 +101,7 @@ void TRDGlobalTracking::run(ProcessingContext& pc) mTimer.Start(false); o2::globaltracking::RecoContainer inputTracks; inputTracks.collectData(pc, *mDataRequest); - auto tmpInputContainer = getRecoInputContainer(pc, mChainTracking->mIOPtrs, &inputTracks); + auto tmpInputContainer = getRecoInputContainer(pc, &mChainTracking->mIOPtrs, &inputTracks); LOGF(INFO, "There are %i tracklets in total from %i trigger records", tmpInputContainer->mNTracklets, tmpInputContainer->mNTriggerRecords); LOGF(INFO, "As input seeds are available: %i ITS-TPC matched tracks and %i TPC tracks", tmpInputContainer->mNTracksTPCITS, tmpInputContainer->mNTracksTPC); if (tmpInputContainer->mNTracklets != tmpInputContainer->mNSpacePoints) { diff --git a/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx b/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx index cdf0b40a730b2..9d087ee3176e6 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx @@ -39,7 +39,6 @@ int GPUChainTracking::RunTRDTracking() mRec->PushNonPersistentMemory(qStr2Tag("TRDTRACK")); SetupGPUProcessor(&Tracker, true); - for (unsigned int i = 0; i < mIOPtrs.nMergedTracks; i++) { const GPUTPCGMMergedTrack& trk = mIOPtrs.mergedTracks[i]; if (!Tracker.PreCheckTrackTRDCandidate(trk)) { diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx index cea3c19b011de..83a1c84a12184 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx @@ -51,7 +51,7 @@ class GPUTPCGMPolynomialField; template void GPUTRDTracker_t::SetMaxData(const GPUTrackingInOutPointers& io) { - mNMaxTracks = io.nMergedTracks; + mNMaxTracks = std::max(std::max(io.nOutputTracksTPCO2, io.nTracksTPCITSO2), io.nMergedTracks); mNMaxSpacePoints = io.nTRDTracklets; mNMaxCollisions = io.nTRDTriggerRecords; } diff --git a/GPU/Workflow/CMakeLists.txt b/GPU/Workflow/CMakeLists.txt index e8bea668df0cf..047582e4700c1 100644 --- a/GPU/Workflow/CMakeLists.txt +++ b/GPU/Workflow/CMakeLists.txt @@ -20,8 +20,16 @@ o2_add_library(GPUWorkflow O2::TPCQC O2::DetectorsCalibration O2::TPCReaderWorkflow + O2::DataFormatsGlobalTracking + O2::DataFormatsTRD PRIVATE_LINK_LIBRARIES O2::GPUTracking) +if(GPUCA_EVENT_DISPLAY OR + (OPENGL_FOUND AND GLFW_FOUND AND TARGET AliceO2::DebugGUI AND OPENGL_GLU_FOUND + AND NOT CMAKE_SYSTEM_NAME STREQUAL "Darwin")) + target_compile_definitions(${targetName} PRIVATE GPUCA_BUILD_EVENT_DISPLAY) +endif() + o2_add_executable(reco-workflow COMPONENT_NAME gpu TARGETVARNAME targetName @@ -29,7 +37,6 @@ o2_add_executable(reco-workflow PUBLIC_LINK_LIBRARIES O2::GPUWorkflow O2::GlobalTrackingWorkflowHelpers) - if(ALIGPU_BUILD_TYPE STREQUAL "O2" AND OPENGL_FOUND AND GLFW_FOUND diff --git a/GPU/Workflow/include/GPUWorkflow/GPUWorkflowSpec.h b/GPU/Workflow/include/GPUWorkflow/GPUWorkflowSpec.h index 0a021f13c6114..96805df659e6e 100644 --- a/GPU/Workflow/include/GPUWorkflow/GPUWorkflowSpec.h +++ b/GPU/Workflow/include/GPUWorkflow/GPUWorkflowSpec.h @@ -46,6 +46,7 @@ struct Config { bool processMC = false; bool sendClustersPerSector = false; bool askDISTSTF = true; + bool readTRDtracklets = false; }; using CompletionPolicyData = std::vector; } // namespace gpuworkflow diff --git a/GPU/Workflow/src/GPUWorkflowSpec.cxx b/GPU/Workflow/src/GPUWorkflowSpec.cxx index 6968ea170c7df..01ebb53273b31 100644 --- a/GPU/Workflow/src/GPUWorkflowSpec.cxx +++ b/GPU/Workflow/src/GPUWorkflowSpec.cxx @@ -56,6 +56,10 @@ #include "SimulationDataFormat/ConstMCTruthContainer.h" #include "SimulationDataFormat/MCCompLabel.h" #include "Algorithm/Parser.h" +#include "DataFormatsGlobalTracking/RecoContainer.h" +#include "DataFormatsTRD/RecoInputContainer.h" +#include "TRDBase/Geometry.h" +#include "TRDBase/GeometryFlat.h" #include #include // for make_shared #include @@ -101,6 +105,7 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli std::unique_ptr fastTransform; std::unique_ptr dEdxSplines; std::unique_ptr tpcPadGainCalib; + std::unique_ptr trdGeometry; std::unique_ptr config; int qaTaskMask = 0; std::unique_ptr qa; @@ -258,12 +263,13 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli config.configCalib.o2Propagator = Propagator::Instance(); - // Sample code what needs to be done for the TRD Geometry, when we extend this to TRD tracking. - /* o2::trd::Geometry gm; - gm.createPadPlaneArray(); - gm.createClusterMatrixArray(); - std::unique_ptr gf(gm); - config.trdGeometry = gf.get();*/ + if (specconfig.readTRDtracklets) { + auto gm = o2::trd::Geometry::instance(); + gm->createPadPlaneArray(); + gm->createClusterMatrixArray(); + processAttributes->trdGeometry = std::make_unique(*gm); + config.configCalib.trdGeometry = processAttributes->trdGeometry.get(); + } // Configuration is prepared, initialize the tracker. if (tracker->Initialize(config) != 0) { @@ -480,9 +486,17 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli } const auto& inputsClustersDigits = getWorkflowTPCInput(pc, verbosity, getWorkflowTPCInput_mc, getWorkflowTPCInput_clusters, processAttributes->tpcSectorMask, getWorkflowTPCInput_digits); - GPUTrackingInOutPointers ptrs; + o2::globaltracking::RecoContainer inputTracksTRD; + decltype(o2::trd::getRecoInputContainer(pc, &ptrs, &inputTracksTRD)) trdInputContainer; + if (specconfig.readTRDtracklets) { + o2::globaltracking::DataRequest dataRequestTRD; + dataRequestTRD.requestTracks(o2::dataformats::GlobalTrackID::getSourcesMask(o2::dataformats::GlobalTrackID::NONE), false); + inputTracksTRD.collectData(pc, dataRequestTRD); + trdInputContainer = std::move(o2::trd::getRecoInputContainer(pc, &ptrs, &inputTracksTRD)); + } + void* ptrEp[NSectors * NEndpoints] = {}; bool doInputDigits = false, doInputDigitsMC = false; if (specconfig.decompressTPC) { @@ -769,6 +783,11 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli inputs.emplace_back(InputSpec{"zsinput", ConcreteDataTypeMatcher{"TPC", "TPCZS"}, Lifetime::Timeframe}); inputs.emplace_back(InputSpec{"zsinputsizes", ConcreteDataTypeMatcher{"TPC", "ZSSIZES"}, Lifetime::Timeframe}); } + if (specconfig.readTRDtracklets) { + inputs.emplace_back("trdctracklets", o2::header::gDataOriginTRD, "CTRACKLETS", 0, Lifetime::Timeframe); + inputs.emplace_back("trdtracklets", o2::header::gDataOriginTRD, "TRACKLETS", 0, Lifetime::Timeframe); + inputs.emplace_back("trdtriggerrec", o2::header::gDataOriginTRD, "TRKTRGRD", 0, Lifetime::Timeframe); + } return inputs; }; diff --git a/GPU/Workflow/src/O2GPUDPLDisplay.cxx b/GPU/Workflow/src/O2GPUDPLDisplay.cxx index e0135d977e5f9..9caab2f814c9d 100644 --- a/GPU/Workflow/src/O2GPUDPLDisplay.cxx +++ b/GPU/Workflow/src/O2GPUDPLDisplay.cxx @@ -22,6 +22,8 @@ #include "TPCFastTransform.h" #include "TPCReconstruction/TPCFastTransformHelperO2.h" #include "GlobalTrackingWorkflowHelpers/InputHelper.h" +#include "DataFormatsTPC/WorkflowHelper.h" +#include "DataFormatsTRD/RecoInputContainer.h" using namespace o2::framework; using namespace o2::dataformats; @@ -34,7 +36,7 @@ void customize(std::vector& workflowOptions) { std::vector options{ {"enable-mc", o2::framework::VariantType::Bool, false, {"enable visualization of MC data"}}, - {"display-clusters", VariantType::String, "TPC", {"comma-separated list of clusters to display"}}, + {"display-clusters", VariantType::String, "TPC,TRD", {"comma-separated list of clusters to display"}}, {"display-tracks", VariantType::String, "TPC", {"comma-separated list of tracks to display"}}, {"read-from-files", o2::framework::VariantType::Bool, false, {"comma-separated list of tracks to display"}}, {"disable-root-input", o2::framework::VariantType::Bool, false, {"Disable root input overriding read-from-files"}}, @@ -79,15 +81,29 @@ void O2GPUDPLDisplaySpec::run(ProcessingContext& pc) } GPUTrackingInOutPointers ptrs; - recoData.addTPCClusters(pc, false); - recoData.addTPCTracks(pc, mUseMC); - ptrs.clustersNative = &recoData.inputsTPCclusters->clusterIndex; - const auto& tpcTracks = recoData.getTPCTracks(); - const auto& tpcClusRefs = recoData.getTPCTracksClusterRefs(); - ptrs.outputTracksTPCO2 = tpcTracks.data(); - ptrs.nOutputTracksTPCO2 = tpcTracks.size(); - ptrs.outputClusRefsTPCO2 = tpcClusRefs.data(); - ptrs.nOutputClusRefsTPCO2 = tpcClusRefs.size(); + if (mClMask[GlobalTrackID::TPC]) { + recoData.addTPCClusters(pc, false); + } + if (mTrkMask[GlobalTrackID::TPC]) { + recoData.addTPCTracks(pc, mUseMC); + } + if (mClMask[GlobalTrackID::TRD]) { + recoData.addTRDTracklets(pc); + } + if (mClMask[GlobalTrackID::TPC]) { + ptrs.clustersNative = &recoData.inputsTPCclusters->clusterIndex; + } + if (mTrkMask[GlobalTrackID::TPC]) { + const auto& tpcTracks = recoData.getTPCTracks(); + const auto& tpcClusRefs = recoData.getTPCTracksClusterRefs(); + ptrs.outputTracksTPCO2 = tpcTracks.data(); + ptrs.nOutputTracksTPCO2 = tpcTracks.size(); + ptrs.outputClusRefsTPCO2 = tpcClusRefs.data(); + ptrs.nOutputClusRefsTPCO2 = tpcClusRefs.size(); + } + if (mClMask[GlobalTrackID::TRD]) { + o2::trd::getRecoInputContainer(pc, &ptrs, &recoData); + } if (mUseMC) { const auto& tpcTracksMC = recoData.getTPCTracksMCLabels(); ptrs.outputTracksTPCO2MC = tpcTracksMC.data(); diff --git a/GPU/Workflow/src/gpu-reco-workflow.cxx b/GPU/Workflow/src/gpu-reco-workflow.cxx index 7f1d9a5278fea..6cb3f1179327c 100644 --- a/GPU/Workflow/src/gpu-reco-workflow.cxx +++ b/GPU/Workflow/src/gpu-reco-workflow.cxx @@ -37,7 +37,7 @@ void customize(std::vector& workflowOptions) { std::vector options{ - {"input-type", VariantType::String, "digits", {"digitizer, digits, zsraw, zsonthefly, clustersnative, compressed-clusters-root, compressed-clusters-ctf"}}, + {"input-type", VariantType::String, "digits", {"digitizer, digits, zsraw, zsonthefly, clustersnative, compressed-clusters-root, compressed-clusters-ctf, trd-tracklets"}}, {"output-type", VariantType::String, "tracks", {"clustersnative, tracks, compressed-clusters-ctf, qa, no-shared-cluster-map"}}, {"disable-root-input", VariantType::Bool, true, {"disable root-files input reader"}}, {"disable-mc", VariantType::Bool, false, {"disable sending of MC information"}}, @@ -74,6 +74,7 @@ enum struct ioType { Digits, CompClustCTF, Tracks, QA, + TRDTracklets, NoSharedMap }; static const std::unordered_map InputMap{ @@ -82,7 +83,8 @@ static const std::unordered_map InputMap{ {"zsraw", ioType::ZSRaw}, {"zsonthefly", ioType::ZSRawOTF}, {"compressed-clusters-root", ioType::CompClustROOT}, - {"compressed-clusters-ctf", ioType::CompClustCTF}}; + {"compressed-clusters-ctf", ioType::CompClustCTF}, + {"trd-tracklets", ioType::TRDTracklets}}; static const std::unordered_map OutputMap{ {"clusters", ioType::Clusters}, @@ -131,6 +133,7 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) cfg.processMC = doMC; cfg.sendClustersPerSector = false; cfg.askDISTSTF = !cfgc.options().get("ignore-dist-stf"); + cfg.readTRDtracklets = isEnabled(inputTypes, ioType::TRDTracklets); specs.emplace_back(o2::gpu::getGPURecoWorkflowSpec(&gPolicyData, cfg, tpcSectors, gTpcSectorMask, "gpu-reconstruction")); if (!cfgc.options().get("ignore-dist-stf")) { From ff82c1462846100f65978d3b7430d4dca01d8b8d Mon Sep 17 00:00:00 2001 From: shahoian Date: Tue, 4 May 2021 13:24:03 +0200 Subject: [PATCH 387/770] export C locale in full_system_test.sh --- prodtests/full_system_test.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/prodtests/full_system_test.sh b/prodtests/full_system_test.sh index 2900bdd2ced4f..14faff963d621 100755 --- a/prodtests/full_system_test.sh +++ b/prodtests/full_system_test.sh @@ -24,7 +24,8 @@ fi . ${O2_ROOT}/share/scripts/jobutils.sh # make sure that correct format will be used irrespecive of the locale -LC_NUMERIC=C +export LC_NUMERIC=C +export LC_ALL=C NEvents=${NEvents:-10} #550 for full TF (the number of PbPb events) NEventsQED=${NEventsQED:-1000} #35000 for full TF From 20ea6e66fff3723b52fbea360c961b0dd7089812 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B2=20Jacazio?= Date: Tue, 4 May 2021 14:50:04 +0200 Subject: [PATCH 388/770] PWGLF: Clean spectra tasks (#6032) - Remove split spectra tasks PID: - Print configuration in PID tasks (i.e. priting enabled tables) - Rename tiny PID tasks (remove '_') - Add cut on min number of contributors in TOF QA on MC --- Analysis/Tasks/PID/CMakeLists.txt | 4 +- Analysis/Tasks/PID/pidTOF.cxx | 15 +++- .../PID/{pidTOF_tiny.cxx => pidTOFtiny.cxx} | 19 +++-- Analysis/Tasks/PID/pidTPC.cxx | 22 ++++- .../PID/{pidTPC_tiny.cxx => pidTPCtiny.cxx} | 24 ++++-- Analysis/Tasks/PID/qaTOFMC.cxx | 4 + Analysis/Tasks/PWGLF/CMakeLists.txt | 18 +--- Analysis/Tasks/PWGLF/spectraTOF.cxx | 28 ++++--- Analysis/Tasks/PWGLF/spectraTOF_split.cxx | 83 ------------------ ...spectraTOF_tiny.cxx => spectraTOFtiny.cxx} | 27 +++--- Analysis/Tasks/PWGLF/spectraTPC.cxx | 57 +++++++------ ...PCsplitPiKaPr.cxx => spectraTPCPiKaPr.cxx} | 27 +++--- Analysis/Tasks/PWGLF/spectraTPC_split.cxx | 84 ------------------- ...spectraTPC_tiny.cxx => spectraTPCtiny.cxx} | 27 +++--- Analysis/Tasks/PWGLF/spectraTPCtinyPiKaPr.cxx | 27 +++--- 15 files changed, 191 insertions(+), 275 deletions(-) rename Analysis/Tasks/PID/{pidTOF_tiny.cxx => pidTOFtiny.cxx} (94%) rename Analysis/Tasks/PID/{pidTPC_tiny.cxx => pidTPCtiny.cxx} (91%) delete mode 100644 Analysis/Tasks/PWGLF/spectraTOF_split.cxx rename Analysis/Tasks/PWGLF/{spectraTOF_tiny.cxx => spectraTOFtiny.cxx} (84%) rename Analysis/Tasks/PWGLF/{spectraTPCsplitPiKaPr.cxx => spectraTPCPiKaPr.cxx} (85%) delete mode 100644 Analysis/Tasks/PWGLF/spectraTPC_split.cxx rename Analysis/Tasks/PWGLF/{spectraTPC_tiny.cxx => spectraTPCtiny.cxx} (87%) diff --git a/Analysis/Tasks/PID/CMakeLists.txt b/Analysis/Tasks/PID/CMakeLists.txt index ebe0493dde5f9..7013bbd8072b0 100644 --- a/Analysis/Tasks/PID/CMakeLists.txt +++ b/Analysis/Tasks/PID/CMakeLists.txt @@ -26,7 +26,7 @@ o2_add_dpl_workflow(pid-tof-qa-mc COMPONENT_NAME Analysis) o2_add_dpl_workflow(pid-tof-tiny - SOURCES pidTOF_tiny.cxx + SOURCES pidTOFtiny.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore COMPONENT_NAME Analysis) @@ -38,7 +38,7 @@ o2_add_dpl_workflow(pid-tpc COMPONENT_NAME Analysis) o2_add_dpl_workflow(pid-tpc-tiny - SOURCES pidTPC_tiny.cxx + SOURCES pidTPCtiny.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel O2::AnalysisCore COMPONENT_NAME Analysis) diff --git a/Analysis/Tasks/PID/pidTOF.cxx b/Analysis/Tasks/PID/pidTOF.cxx index 5727eefcfcaf7..4775ea7aed618 100644 --- a/Analysis/Tasks/PID/pidTOF.cxx +++ b/Analysis/Tasks/PID/pidTOF.cxx @@ -58,6 +58,7 @@ struct tofPid { Configurable paramfile{"param-file", "", "Path to the parametrization object, if emtpy the parametrization is not taken from file"}; Configurable sigmaname{"param-sigma", "TOFReso", "Name of the parametrization for the expected sigma, used in both file and CCDB mode"}; Configurable url{"ccdb-url", "http://ccdb-test.cern.ch:8080", "url of the ccdb repository"}; + Configurable ccdbPath{"ccdbPath", "Analysis/PID/TOF", "Path of the TOF parametrization on the CCDB"}; Configurable timestamp{"ccdb-timestamp", -1, "timestamp of the object"}; // Configuration flags to include and exclude particle hypotheses Configurable pidEl{"pid-el", -1, {"Produce PID information for the Electron mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; @@ -77,9 +78,15 @@ struct tofPid { for (DeviceSpec device : workflows.devices) { for (auto input : device.inputs) { auto enableFlag = [&input](const std::string particle, Configurable& flag) { - if (input.matcher.binding == "pidRespTOF" + particle) { + const std::string table = "pidRespTOF" + particle; + if (input.matcher.binding == table) { if (flag < 0) { flag.value = 1; + LOG(INFO) << "Auto-enabling table: " + table; + } else if (flag > 0) { + LOG(INFO) << "Table enabled: " + table; + } else { + LOG(INFO) << "Table disabled: " + table; } } }; @@ -106,10 +113,12 @@ struct tofPid { response.SetParameters(DetectorResponse::kSigma, p); const std::string fname = paramfile.value; if (!fname.empty()) { // Loading the parametrization from file + LOG(INFO) << "Loading exp. sigma parametrization from file" << fname << ", using param: " << sigmaname.value; response.LoadParamFromFile(fname.data(), sigmaname.value, DetectorResponse::kSigma); } else { // Loading it from CCDB - const std::string path = "Analysis/PID/TOF"; - response.LoadParam(DetectorResponse::kSigma, ccdb->getForTimeStamp(path + "/" + sigmaname.value, timestamp.value)); + std::string path = ccdbPath.value + "/" + sigmaname.value; + LOG(INFO) << "Loading exp. sigma parametrization from CCDB, using path: " << path << " for timestamp " << timestamp.value; + response.LoadParam(DetectorResponse::kSigma, ccdb->getForTimeStamp(path, timestamp.value)); } } diff --git a/Analysis/Tasks/PID/pidTOF_tiny.cxx b/Analysis/Tasks/PID/pidTOFtiny.cxx similarity index 94% rename from Analysis/Tasks/PID/pidTOF_tiny.cxx rename to Analysis/Tasks/PID/pidTOFtiny.cxx index b25a67375de2a..ac5d0a35a2d39 100644 --- a/Analysis/Tasks/PID/pidTOF_tiny.cxx +++ b/Analysis/Tasks/PID/pidTOFtiny.cxx @@ -9,7 +9,7 @@ // or submit itself to any jurisdiction. /// -/// \file pidTOF_tiny.cxx +/// \file pidTOFtiny.cxx /// \author Nicolo' Jacazio /// \brief Task to produce PID tables for TOF split for each particle with only the Nsigma information. /// Only the tables for the mass hypotheses requested are filled, the others are sent empty. @@ -58,6 +58,7 @@ struct tofPidTiny { Configurable paramfile{"param-file", "", "Path to the parametrization object, if emtpy the parametrization is not taken from file"}; Configurable sigmaname{"param-sigma", "TOFReso", "Name of the parametrization for the expected sigma, used in both file and CCDB mode"}; Configurable url{"ccdb-url", "http://ccdb-test.cern.ch:8080", "url of the ccdb repository"}; + Configurable ccdbPath{"ccdbPath", "Analysis/PID/TOF", "Path of the TOF parametrization on the CCDB"}; Configurable timestamp{"ccdb-timestamp", -1, "timestamp of the object"}; // Configuration flags to include and exclude particle hypotheses Configurable pidEl{"pid-el", -1, {"Produce PID information for the Electron mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; @@ -77,9 +78,15 @@ struct tofPidTiny { for (DeviceSpec device : workflows.devices) { for (auto input : device.inputs) { auto enableFlag = [&input](const std::string particle, Configurable& flag) { - if (input.matcher.binding == "pidRespTOFT" + particle) { + const std::string table = "pidRespTOFT" + particle; + if (input.matcher.binding == table) { if (flag < 0) { flag.value = 1; + LOG(INFO) << "Auto-enabling table: " + table; + } else if (flag > 0) { + LOG(INFO) << "Table enabled: " + table; + } else { + LOG(INFO) << "Table disabled: " + table; } } }; @@ -106,10 +113,12 @@ struct tofPidTiny { response.SetParameters(DetectorResponse::kSigma, p); const std::string fname = paramfile.value; if (!fname.empty()) { // Loading the parametrization from file + LOG(INFO) << "Loading exp. sigma parametrization from file" << fname << ", using param: " << sigmaname.value; response.LoadParamFromFile(fname.data(), sigmaname.value, DetectorResponse::kSigma); } else { // Loading it from CCDB - const std::string path = "Analysis/PID/TOF"; - response.LoadParam(DetectorResponse::kSigma, ccdb->getForTimeStamp(path + "/" + sigmaname.value, timestamp.value)); + std::string path = ccdbPath.value + "/" + sigmaname.value; + LOG(INFO) << "Loading exp. sigma parametrization from CCDB, using path: " << path << " for timestamp " << timestamp.value; + response.LoadParam(DetectorResponse::kSigma, ccdb->getForTimeStamp(path, timestamp.value)); } } @@ -292,4 +301,4 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) workflow.push_back(adaptAnalysisTask(cfgc)); } return workflow; -} \ No newline at end of file +} diff --git a/Analysis/Tasks/PID/pidTPC.cxx b/Analysis/Tasks/PID/pidTPC.cxx index 4486a3508cb38..07ddb70c72e9a 100644 --- a/Analysis/Tasks/PID/pidTPC.cxx +++ b/Analysis/Tasks/PID/pidTPC.cxx @@ -59,6 +59,7 @@ struct tpcPid { Configurable signalname{"param-signal", "BetheBloch", "Name of the parametrization for the expected signal, used in both file and CCDB mode"}; Configurable sigmaname{"param-sigma", "TPCReso", "Name of the parametrization for the expected sigma, used in both file and CCDB mode"}; Configurable url{"ccdb-url", "http://ccdb-test.cern.ch:8080", "url of the ccdb repository"}; + Configurable ccdbPath{"ccdbPath", "Analysis/PID/TPC", "Path of the TPC parametrization on the CCDB"}; Configurable timestamp{"ccdb-timestamp", -1, "timestamp of the object"}; // Configuration flags to include and exclude particle hypotheses Configurable pidEl{"pid-el", -1, {"Produce PID information for the Electron mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; @@ -78,9 +79,15 @@ struct tpcPid { for (DeviceSpec device : workflows.devices) { for (auto input : device.inputs) { auto enableFlag = [&input](const std::string particle, Configurable& flag) { - if (input.matcher.binding == "pidRespTPC" + particle) { + const std::string table = "pidRespTPC" + particle; + if (input.matcher.binding == table) { if (flag < 0) { flag.value = 1; + LOG(INFO) << "Auto-enabling table: " + table; + } else if (flag > 0) { + LOG(INFO) << "Table enabled: " + table; + } else { + LOG(INFO) << "Table disabled: " + table; } } }; @@ -105,12 +112,19 @@ struct tpcPid { // const std::string fname = paramfile.value; if (!fname.empty()) { // Loading the parametrization from file + LOG(INFO) << "Loading exp. signal parametrization from file" << fname << ", using param: " << signalname.value; response.LoadParamFromFile(fname.data(), signalname.value, DetectorResponse::kSignal); + + LOG(INFO) << "Loading exp. sigma parametrization from file" << fname << ", using param: " << sigmaname.value; response.LoadParamFromFile(fname.data(), sigmaname.value, DetectorResponse::kSigma); } else { // Loading it from CCDB - const std::string path = "Analysis/PID/TPC"; - response.LoadParam(DetectorResponse::kSignal, ccdb->getForTimeStamp(path + "/" + signalname.value, timestamp.value)); - response.LoadParam(DetectorResponse::kSigma, ccdb->getForTimeStamp(path + "/" + sigmaname.value, timestamp.value)); + std::string path = ccdbPath.value + "/" + signalname.value; + LOG(INFO) << "Loading exp. signal parametrization from CCDB, using path: " << path << " for timestamp " << timestamp.value; + response.LoadParam(DetectorResponse::kSignal, ccdb->getForTimeStamp(path, timestamp.value)); + + path = ccdbPath.value + "/" + sigmaname.value; + LOG(INFO) << "Loading exp. sigma parametrization from CCDB, using path: " << path << " for timestamp " << timestamp.value; + response.LoadParam(DetectorResponse::kSigma, ccdb->getForTimeStamp(path, timestamp.value)); } } diff --git a/Analysis/Tasks/PID/pidTPC_tiny.cxx b/Analysis/Tasks/PID/pidTPCtiny.cxx similarity index 91% rename from Analysis/Tasks/PID/pidTPC_tiny.cxx rename to Analysis/Tasks/PID/pidTPCtiny.cxx index 4eee848c81f25..6d7e2e86a12d8 100644 --- a/Analysis/Tasks/PID/pidTPC_tiny.cxx +++ b/Analysis/Tasks/PID/pidTPCtiny.cxx @@ -9,7 +9,7 @@ // or submit itself to any jurisdiction. /// -/// \file pidTPC_tiny.cxx +/// \file pidTPCtiny.cxx /// \author Nicolo' Jacazio /// \brief Task to produce PID tables for TPC split for each particle with only the Nsigma information. /// Only the tables for the mass hypotheses requested are filled, the others are sent empty. @@ -59,6 +59,7 @@ struct tpcPidTiny { Configurable signalname{"param-signal", "BetheBloch", "Name of the parametrization for the expected signal, used in both file and CCDB mode"}; Configurable sigmaname{"param-sigma", "TPCReso", "Name of the parametrization for the expected sigma, used in both file and CCDB mode"}; Configurable url{"ccdb-url", "http://ccdb-test.cern.ch:8080", "url of the ccdb repository"}; + Configurable ccdbPath{"ccdbPath", "Analysis/PID/TPC", "Path of the TPC parametrization on the CCDB"}; Configurable timestamp{"ccdb-timestamp", -1, "timestamp of the object"}; // Configuration flags to include and exclude particle hypotheses Configurable pidEl{"pid-el", -1, {"Produce PID information for the Electron mass hypothesis, overrides the automatic setup: the corresponding table can be set off (0) or on (1)"}}; @@ -78,9 +79,15 @@ struct tpcPidTiny { for (DeviceSpec device : workflows.devices) { for (auto input : device.inputs) { auto enableFlag = [&input](const std::string particle, Configurable& flag) { - if (input.matcher.binding == "pidRespTPCT" + particle) { + const std::string table = "pidRespTPCT" + particle; + if (input.matcher.binding == table) { if (flag < 0) { flag.value = 1; + LOG(INFO) << "Auto-enabling table: " + table; + } else if (flag > 0) { + LOG(INFO) << "Table enabled: " + table; + } else { + LOG(INFO) << "Table disabled: " + table; } } }; @@ -105,12 +112,19 @@ struct tpcPidTiny { // const std::string fname = paramfile.value; if (!fname.empty()) { // Loading the parametrization from file + LOG(INFO) << "Loading exp. signal parametrization from file" << fname << ", using param: " << signalname.value; response.LoadParamFromFile(fname.data(), signalname.value, DetectorResponse::kSignal); + + LOG(INFO) << "Loading exp. sigma parametrization from file" << fname << ", using param: " << sigmaname.value; response.LoadParamFromFile(fname.data(), sigmaname.value, DetectorResponse::kSigma); } else { // Loading it from CCDB - const std::string path = "Analysis/PID/TPC"; - response.LoadParam(DetectorResponse::kSignal, ccdb->getForTimeStamp(path + "/" + signalname.value, timestamp.value)); - response.LoadParam(DetectorResponse::kSigma, ccdb->getForTimeStamp(path + "/" + sigmaname.value, timestamp.value)); + std::string path = ccdbPath.value + "/" + signalname.value; + LOG(INFO) << "Loading exp. signal parametrization from CCDB, using path: " << path << " for timestamp " << timestamp.value; + response.LoadParam(DetectorResponse::kSignal, ccdb->getForTimeStamp(path, timestamp.value)); + + path = ccdbPath.value + "/" + sigmaname.value; + LOG(INFO) << "Loading exp. sigma parametrization from CCDB, using path: " << path << " for timestamp " << timestamp.value; + response.LoadParam(DetectorResponse::kSigma, ccdb->getForTimeStamp(path, timestamp.value)); } } diff --git a/Analysis/Tasks/PID/qaTOFMC.cxx b/Analysis/Tasks/PID/qaTOFMC.cxx index eb3caad2fe49b..ceddd3afec517 100644 --- a/Analysis/Tasks/PID/qaTOFMC.cxx +++ b/Analysis/Tasks/PID/qaTOFMC.cxx @@ -68,6 +68,7 @@ struct pidTOFTaskQA { Configurable MaxP{"MaxP", 5, "Maximum momentum in range"}; Configurable MinEta{"MinEta", -0.8, "Minimum eta in range"}; Configurable MaxEta{"MaxEta", 0.8, "Maximum eta in range"}; + Configurable nMinNumberOfContributors{"nMinNumberOfContributors", 2, "Minimum required number of contributors to the vertex"}; template void makelogaxis(T h) @@ -148,6 +149,9 @@ struct pidTOFTaskQA { aod::McTrackLabels, aod::pidRespTOFbeta> const& tracks, aod::McParticles& mcParticles) { + if (collision.numContrib() < nMinNumberOfContributors) { + return; + } const float collisionTime_ps = collision.collisionTime() * 1000.f; unsigned int nTracksWithTOF = 0; for (auto t : tracks) { diff --git a/Analysis/Tasks/PWGLF/CMakeLists.txt b/Analysis/Tasks/PWGLF/CMakeLists.txt index 3103556034c03..61bb29cdb7d01 100644 --- a/Analysis/Tasks/PWGLF/CMakeLists.txt +++ b/Analysis/Tasks/PWGLF/CMakeLists.txt @@ -18,13 +18,8 @@ o2_add_dpl_workflow(spectra-tof PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel COMPONENT_NAME Analysis) -o2_add_dpl_workflow(spectra-tof-split - SOURCES spectraTOF_split.cxx - PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel - COMPONENT_NAME Analysis) - o2_add_dpl_workflow(spectra-tof-tiny - SOURCES spectraTOF_tiny.cxx + SOURCES spectraTOFtiny.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel COMPONENT_NAME Analysis) @@ -33,18 +28,13 @@ o2_add_dpl_workflow(spectra-tpc PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel COMPONENT_NAME Analysis) -o2_add_dpl_workflow(spectra-tpc-split - SOURCES spectraTPC_split.cxx - PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel - COMPONENT_NAME Analysis) - -o2_add_dpl_workflow(spectra-tpc-split-pikapr - SOURCES spectraTPCsplitPiKaPr.cxx +o2_add_dpl_workflow(spectra-tpc-pikapr + SOURCES spectraTPCPiKaPr.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel COMPONENT_NAME Analysis) o2_add_dpl_workflow(spectra-tpc-tiny - SOURCES spectraTPC_tiny.cxx + SOURCES spectraTPCtiny.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DetectorsBase O2::AnalysisDataModel COMPONENT_NAME Analysis) diff --git a/Analysis/Tasks/PWGLF/spectraTOF.cxx b/Analysis/Tasks/PWGLF/spectraTOF.cxx index 87f0cecb4f666..99563eff5daa7 100644 --- a/Analysis/Tasks/PWGLF/spectraTOF.cxx +++ b/Analysis/Tasks/PWGLF/spectraTOF.cxx @@ -8,12 +8,18 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +/// +/// \file spectraTOF.h +/// \author Nicolo' Jacazio +/// +/// \brief Task for the analysis of the spectra with the TOF detector +/// + // O2 includes #include "ReconstructionDataFormats/Track.h" #include "Framework/runDataProcessing.h" #include "Framework/AnalysisTask.h" -#include "Framework/AnalysisDataModel.h" -#include "Framework/ASoAHelpers.h" +#include "Framework/HistogramRegistry.h" #include "AnalysisDataModel/PID/PIDResponse.h" #include "AnalysisDataModel/TrackSelectionTables.h" @@ -21,7 +27,8 @@ using namespace o2; using namespace o2::framework; using namespace o2::framework::expressions; -struct TOFSpectraTask { +// Spectra task +struct tofSpectra { static constexpr int Np = 9; static constexpr const char* pT[Np] = {"e", "#mu", "#pi", "K", "p", "d", "t", "^{3}He", "#alpha"}; static constexpr std::string_view hp[Np] = {"p/El", "p/Mu", "p/Pi", "p/Ka", "p/Pr", "p/De", "p/Tr", "p/He", "p/Al"}; @@ -47,24 +54,26 @@ struct TOFSpectraTask { template void fillParticleHistos(const T& track, const float& nsigma) { - if (abs(nsigma) > nsigmacut.value) { + if (abs(nsigma) > cfgNSigmaCut) { return; } histos.fill(HIST(hp[i]), track.p()); histos.fill(HIST(hpt[i]), track.pt()); } + //Defining filters and input + Configurable cfgNSigmaCut{"cfgNSigmaCut", 3, "Value of the Nsigma cut"}; Configurable cfgCutVertex{"cfgCutVertex", 10.0f, "Accepted z-vertex range"}; Configurable cfgCutEta{"cfgCutEta", 0.8f, "Eta range for tracks"}; - Configurable nsigmacut{"nsigmacut", 3, "Value of the Nsigma cut"}; - Filter collisionFilter = nabs(aod::collision::posZ) < cfgCutVertex; - Filter trackFilter = (nabs(aod::track::eta) < cfgCutEta) && (aod::track::isGlobalTrack == (uint8_t) true) && (aod::track::tofSignal > 0.f); + Filter trackFilter = (nabs(aod::track::eta) < cfgCutEta) && (aod::track::isGlobalTrack == (uint8_t) true); + Filter trackFilterTOF = (aod::track::tofSignal > 0.f); // Skip tracks without TOF using TrackCandidates = soa::Filtered>; + void process(TrackCandidates::iterator const& track) { histos.fill(HIST("p/Unselected"), track.p()); @@ -89,11 +98,10 @@ struct TOFSpectraTask { histos.fill(HIST("electronbeta/hp_beta_El"), track.p(), track.diffbetael()); histos.fill(HIST("electronbeta/hp_betasigma_El"), track.p(), track.separationbetael()); } - } + } // end of the process function }; WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { - WorkflowSpec workflow{adaptAnalysisTask(cfgc, TaskName{"tofspectra-task"})}; - return workflow; + return WorkflowSpec{adaptAnalysisTask(cfgc)}; } diff --git a/Analysis/Tasks/PWGLF/spectraTOF_split.cxx b/Analysis/Tasks/PWGLF/spectraTOF_split.cxx deleted file mode 100644 index 141d3244d8408..0000000000000 --- a/Analysis/Tasks/PWGLF/spectraTOF_split.cxx +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -// O2 includes -#include "ReconstructionDataFormats/Track.h" -#include "Framework/runDataProcessing.h" -#include "Framework/AnalysisTask.h" -#include "Framework/AnalysisDataModel.h" -#include "Framework/ASoAHelpers.h" -#include "AnalysisDataModel/PID/PIDResponse.h" -#include "AnalysisDataModel/TrackSelectionTables.h" - -using namespace o2; -using namespace o2::framework; -using namespace o2::framework::expressions; - -struct TOFSpectraTaskSplit { - static constexpr int Np = 9; - static constexpr const char* pT[Np] = {"e", "#mu", "#pi", "K", "p", "d", "t", "^{3}He", "#alpha"}; - static constexpr std::string_view hp[Np] = {"p/El", "p/Mu", "p/Pi", "p/Ka", "p/Pr", "p/De", "p/Tr", "p/He", "p/Al"}; - static constexpr std::string_view hpt[Np] = {"pt/El", "pt/Mu", "pt/Pi", "pt/Ka", "pt/Pr", "pt/De", "pt/Tr", "pt/He", "pt/Al"}; - HistogramRegistry histos{"Histos", {}, OutputObjHandlingPolicy::AnalysisObject}; - - void init(o2::framework::InitContext&) - { - histos.add("p/Unselected", "Unselected;#it{p} (GeV/#it{c})", kTH1F, {{100, 0, 20}}); - histos.add("pt/Unselected", "Unselected;#it{p}_{T} (GeV/#it{c})", kTH1F, {{100, 0, 20}}); - for (int i = 0; i < Np; i++) { - histos.add(hp[i].data(), Form("%s;#it{p} (GeV/#it{c})", pT[i]), kTH1F, {{100, 0, 20}}); - histos.add(hpt[i].data(), Form("%s;#it{p}_{T} (GeV/#it{c})", pT[i]), kTH1F, {{100, 0, 20}}); - } - } - - template - void fillParticleHistos(const T& track, const float& nsigma) - { - if (abs(nsigma) > nsigmacut.value) { - return; - } - histos.fill(HIST(hp[i]), track.p()); - histos.fill(HIST(hpt[i]), track.pt()); - } - - Configurable cfgCutVertex{"cfgCutVertex", 10.0f, "Accepted z-vertex range"}; - Configurable cfgCutEta{"cfgCutEta", 0.8f, "Eta range for tracks"}; - Configurable nsigmacut{"nsigmacut", 3, "Value of the Nsigma cut"}; - - Filter collisionFilter = nabs(aod::collision::posZ) < cfgCutVertex; - Filter trackFilter = (nabs(aod::track::eta) < cfgCutEta) && (aod::track::isGlobalTrack == (uint8_t) true) && (aod::track::tofSignal > 0.f); - using TrackCandidates = soa::Filtered>; - void process(TrackCandidates::iterator const& track) - { - histos.fill(HIST("p/Unselected"), track.p()); - histos.fill(HIST("pt/Unselected"), track.pt()); - - fillParticleHistos<0>(track, track.tofNSigmaEl()); - fillParticleHistos<1>(track, track.tofNSigmaMu()); - fillParticleHistos<2>(track, track.tofNSigmaPi()); - fillParticleHistos<3>(track, track.tofNSigmaKa()); - fillParticleHistos<4>(track, track.tofNSigmaPr()); - fillParticleHistos<5>(track, track.tofNSigmaDe()); - fillParticleHistos<6>(track, track.tofNSigmaTr()); - fillParticleHistos<7>(track, track.tofNSigmaHe()); - fillParticleHistos<8>(track, track.tofNSigmaAl()); - } -}; - -WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) -{ - WorkflowSpec workflow{adaptAnalysisTask(cfgc, TaskName{"tofspectra-split-task"})}; - return workflow; -} diff --git a/Analysis/Tasks/PWGLF/spectraTOF_tiny.cxx b/Analysis/Tasks/PWGLF/spectraTOFtiny.cxx similarity index 84% rename from Analysis/Tasks/PWGLF/spectraTOF_tiny.cxx rename to Analysis/Tasks/PWGLF/spectraTOFtiny.cxx index 5690bfc492ee6..5c20a89690621 100644 --- a/Analysis/Tasks/PWGLF/spectraTOF_tiny.cxx +++ b/Analysis/Tasks/PWGLF/spectraTOFtiny.cxx @@ -8,12 +8,18 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +/// +/// \file spectraTOFtiny.h +/// \author Nicolo' Jacazio +/// +/// \brief Task for the analysis of the spectra with the TOF detector using the tiny tables +/// + // O2 includes #include "ReconstructionDataFormats/Track.h" #include "Framework/runDataProcessing.h" #include "Framework/AnalysisTask.h" -#include "Framework/AnalysisDataModel.h" -#include "Framework/ASoAHelpers.h" +#include "Framework/HistogramRegistry.h" #include "AnalysisDataModel/PID/PIDResponse.h" #include "AnalysisDataModel/TrackSelectionTables.h" @@ -21,7 +27,8 @@ using namespace o2; using namespace o2::framework; using namespace o2::framework::expressions; -struct TOFSpectraTaskTiny { +// Spectra task +struct tofSpectraTiny { static constexpr int Np = 9; static constexpr const char* pT[Np] = {"e", "#mu", "#pi", "K", "p", "d", "t", "^{3}He", "#alpha"}; static constexpr std::string_view hp[Np] = {"p/El", "p/Mu", "p/Pi", "p/Ka", "p/Pr", "p/De", "p/Tr", "p/He", "p/Al"}; @@ -41,19 +48,20 @@ struct TOFSpectraTaskTiny { template void fillParticleHistos(const T& track, const float& nsigma) { - if (abs(nsigma) > nsigmacut.value) { + if (abs(nsigma) > cfgNSigmaCut) { return; } histos.fill(HIST(hp[i]), track.p()); histos.fill(HIST(hpt[i]), track.pt()); } + //Defining filters and input + Configurable cfgNSigmaCut{"cfgNSigmaCut", 3, "Value of the Nsigma cut"}; Configurable cfgCutVertex{"cfgCutVertex", 10.0f, "Accepted z-vertex range"}; Configurable cfgCutEta{"cfgCutEta", 0.8f, "Eta range for tracks"}; - Configurable nsigmacut{"nsigmacut", 3, "Value of the Nsigma cut"}; - Filter collisionFilter = nabs(aod::collision::posZ) < cfgCutVertex; - Filter trackFilter = (nabs(aod::track::eta) < cfgCutEta) && (aod::track::isGlobalTrack == (uint8_t) true) && (aod::track::tofSignal > 0.f); + Filter trackFilter = (nabs(aod::track::eta) < cfgCutEta) && (aod::track::isGlobalTrack == (uint8_t) true); + Filter trackFilterTOF = (aod::track::tofSignal > 0.f); // Skip tracks without TOF using TrackCandidates = soa::Filtered(track, track.tofNSigmaTr()); fillParticleHistos<7>(track, track.tofNSigmaHe()); fillParticleHistos<8>(track, track.tofNSigmaAl()); - } + } // end of the process function }; WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { - WorkflowSpec workflow{adaptAnalysisTask(cfgc, TaskName{"tofspectra-tiny-task"})}; - return workflow; + return WorkflowSpec{adaptAnalysisTask(cfgc)}; } diff --git a/Analysis/Tasks/PWGLF/spectraTPC.cxx b/Analysis/Tasks/PWGLF/spectraTPC.cxx index aaeec55ed0a62..4f738eb17b758 100644 --- a/Analysis/Tasks/PWGLF/spectraTPC.cxx +++ b/Analysis/Tasks/PWGLF/spectraTPC.cxx @@ -8,11 +8,18 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +/// +/// \file spectraTPC.h +/// \author Nicolo' Jacazio +/// +/// \brief Task for the analysis of the spectra with the TPC detector +/// In addition the task makes histograms of the TPC signal with TOF selections. +/// + // O2 includes #include "ReconstructionDataFormats/Track.h" #include "Framework/AnalysisTask.h" -#include "Framework/AnalysisDataModel.h" -#include "Framework/ASoAHelpers.h" +#include "Framework/HistogramRegistry.h" #include "AnalysisDataModel/PID/PIDResponse.h" #include "AnalysisDataModel/TrackSelectionTables.h" @@ -29,13 +36,6 @@ void customize(std::vector& workflowOptions) #include "Framework/runDataProcessing.h" -#define CANDIDATE_SELECTION \ - Configurable cfgCutVertex{"cfgCutVertex", 10.0f, "Accepted z-vertex range"}; \ - Configurable cfgCutEta{"cfgCutEta", 0.8f, "Eta range for tracks"}; \ - Filter collisionFilter = nabs(aod::collision::posZ) < cfgCutVertex; \ - Filter trackFilter = (nabs(aod::track::eta) < cfgCutEta) && (aod::track::isGlobalTrack == (uint8_t) true); - -// FIXME: we should put this function in some common header so it has to be defined only once template void makelogaxis(T h) { @@ -55,8 +55,9 @@ void makelogaxis(T h) h->GetXaxis()->Set(nbins, binp); } -constexpr int Np = 9; -struct TPCSpectraTask { +// Spectra task +struct tpcSpectra { + static constexpr int Np = 9; static constexpr const char* pT[Np] = {"e", "#mu", "#pi", "K", "p", "d", "t", "^{3}He", "#alpha"}; static constexpr std::string_view hp[Np] = {"p/El", "p/Mu", "p/Pi", "p/Ka", "p/Pr", "p/De", "p/Tr", "p/He", "p/Al"}; static constexpr std::string_view hpt[Np] = {"pt/El", "pt/Mu", "pt/Pi", "pt/Ka", "pt/Pr", "pt/De", "pt/Tr", "pt/He", "pt/Al"}; @@ -72,26 +73,28 @@ struct TPCSpectraTask { } } - //Defining filters and input - CANDIDATE_SELECTION - - Configurable nsigmacut{"nsigmacut", 3, "Value of the Nsigma cut"}; - template void fillParticleHistos(const T& track, const float& nsigma) { - if (abs(nsigma) > nsigmacut.value) { + if (abs(nsigma) > cfgNSigmaCut) { return; } histos.fill(HIST(hp[i]), track.p()); histos.fill(HIST(hpt[i]), track.pt()); } + //Defining filters and input + Configurable cfgNSigmaCut{"cfgNSigmaCut", 3, "Value of the Nsigma cut"}; + Configurable cfgCutVertex{"cfgCutVertex", 10.0f, "Accepted z-vertex range"}; + Configurable cfgCutEta{"cfgCutEta", 0.8f, "Eta range for tracks"}; + Filter collisionFilter = nabs(aod::collision::posZ) < cfgCutVertex; + Filter trackFilter = (nabs(aod::track::eta) < cfgCutEta) && (aod::track::isGlobalTrack == (uint8_t) true); using TrackCandidates = soa::Filtered>; + void process(TrackCandidates::iterator const& track) { histos.fill(HIST("p/Unselected"), track.p()); @@ -106,10 +109,12 @@ struct TPCSpectraTask { fillParticleHistos<6>(track, track.tpcNSigmaTr()); fillParticleHistos<7>(track, track.tpcNSigmaHe()); fillParticleHistos<8>(track, track.tpcNSigmaAl()); - } + + } // end of the process function }; -struct TPCPIDQASignalwTOFTask { +struct tpcPidQaSignalwTof { + static constexpr int Np = 9; static constexpr const char* pT[Np] = {"e", "#mu", "#pi", "K", "p", "d", "t", "^{3}He", "#alpha"}; static constexpr std::string_view htpcsignal[Np] = {"tpcsignal/El", "tpcsignal/Mu", "tpcsignal/Pi", "tpcsignal/Ka", "tpcsignal/Pr", "tpcsignal/De", @@ -137,9 +142,12 @@ struct TPCPIDQASignalwTOFTask { } // Filters - CANDIDATE_SELECTION - + Configurable cfgCutVertex{"cfgCutVertex", 10.0f, "Accepted z-vertex range"}; + Configurable cfgCutEta{"cfgCutEta", 0.8f, "Eta range for tracks"}; + Filter collisionFilter = nabs(aod::collision::posZ) < cfgCutVertex; + Filter trackFilter = (nabs(aod::track::eta) < cfgCutEta) && (aod::track::isGlobalTrack == (uint8_t) true); Filter trackFilterTOF = (aod::track::tofSignal > 0.f); // Skip tracks without TOF + using TrackCandidates = soa::Filtered("add-tof-histos"); - WorkflowSpec workflow{adaptAnalysisTask(cfgc, TaskName{"tpcspectra-task"})}; - if (TPCwTOF) { - workflow.push_back(adaptAnalysisTask(cfgc, TaskName{"TPCpidqa-signalwTOF-task"})); + WorkflowSpec workflow{adaptAnalysisTask(cfgc)}; + if (cfgc.options().get("add-tof-histos")) { + workflow.push_back(adaptAnalysisTask(cfgc)); } return workflow; } diff --git a/Analysis/Tasks/PWGLF/spectraTPCsplitPiKaPr.cxx b/Analysis/Tasks/PWGLF/spectraTPCPiKaPr.cxx similarity index 85% rename from Analysis/Tasks/PWGLF/spectraTPCsplitPiKaPr.cxx rename to Analysis/Tasks/PWGLF/spectraTPCPiKaPr.cxx index 82a5ad9461e69..da206c899442b 100644 --- a/Analysis/Tasks/PWGLF/spectraTPCsplitPiKaPr.cxx +++ b/Analysis/Tasks/PWGLF/spectraTPCPiKaPr.cxx @@ -8,12 +8,18 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +/// +/// \file spectraTPCPiKaPr.h +/// \author Nicolo' Jacazio +/// +/// \brief Task for the analysis of the spectra of Pi Ka Pr with the TPC detector +/// + // O2 includes #include "ReconstructionDataFormats/Track.h" -#include "Framework/runDataProcessing.h" #include "Framework/AnalysisTask.h" -#include "Framework/AnalysisDataModel.h" -#include "Framework/ASoAHelpers.h" +#include "Framework/runDataProcessing.h" +#include "Framework/HistogramRegistry.h" #include "AnalysisDataModel/PID/PIDResponse.h" #include "AnalysisDataModel/TrackSelectionTables.h" @@ -21,7 +27,8 @@ using namespace o2; using namespace o2::framework; using namespace o2::framework::expressions; -struct TPCSpectraTaskSplitPiKaPr { +// Spectra task +struct tpcSpectraPiKaPr { static constexpr int Np = 9; static constexpr const char* pT[Np] = {"e", "#mu", "#pi", "K", "p", "d", "t", "^{3}He", "#alpha"}; static constexpr std::string_view hp[Np] = {"p/El", "p/Mu", "p/Pi", "p/Ka", "p/Pr", "p/De", "p/Tr", "p/He", "p/Al"}; @@ -41,17 +48,17 @@ struct TPCSpectraTaskSplitPiKaPr { template void fillParticleHistos(const T& track, const float& nsigma) { - if (abs(nsigma) > nsigmacut.value) { + if (abs(nsigma) > cfgNSigmaCut) { return; } histos.fill(HIST(hp[i]), track.p()); histos.fill(HIST(hpt[i]), track.pt()); } + //Defining filters and input + Configurable cfgNSigmaCut{"cfgNSigmaCut", 3, "Value of the Nsigma cut"}; Configurable cfgCutVertex{"cfgCutVertex", 10.0f, "Accepted z-vertex range"}; Configurable cfgCutEta{"cfgCutEta", 0.8f, "Eta range for tracks"}; - Configurable nsigmacut{"nsigmacut", 3, "Value of the Nsigma cut"}; - Filter collisionFilter = nabs(aod::collision::posZ) < cfgCutVertex; Filter trackFilter = (nabs(aod::track::eta) < cfgCutEta) && (aod::track::isGlobalTrack == (uint8_t) true); using TrackCandidates = soa::Filtered(track, track.tpcNSigmaPi()); fillParticleHistos<3>(track, track.tpcNSigmaKa()); fillParticleHistos<4>(track, track.tpcNSigmaPr()); - } + + } // end of the process function }; WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { - WorkflowSpec workflow{adaptAnalysisTask(cfgc, TaskName{"tpcspectra-split-pikapr-task"})}; - return workflow; + return WorkflowSpec{adaptAnalysisTask(cfgc)}; } diff --git a/Analysis/Tasks/PWGLF/spectraTPC_split.cxx b/Analysis/Tasks/PWGLF/spectraTPC_split.cxx deleted file mode 100644 index 5b83892f61129..0000000000000 --- a/Analysis/Tasks/PWGLF/spectraTPC_split.cxx +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -// O2 includes -#include "ReconstructionDataFormats/Track.h" -#include "Framework/runDataProcessing.h" -#include "Framework/AnalysisTask.h" -#include "Framework/AnalysisDataModel.h" -#include "Framework/ASoAHelpers.h" -#include "AnalysisDataModel/PID/PIDResponse.h" -#include "AnalysisDataModel/TrackSelectionTables.h" - -using namespace o2; -using namespace o2::framework; -using namespace o2::framework::expressions; - -struct TPCSpectraTaskSplit { - static constexpr int Np = 9; - static constexpr const char* pT[Np] = {"e", "#mu", "#pi", "K", "p", "d", "t", "^{3}He", "#alpha"}; - static constexpr std::string_view hp[Np] = {"p/El", "p/Mu", "p/Pi", "p/Ka", "p/Pr", "p/De", "p/Tr", "p/He", "p/Al"}; - static constexpr std::string_view hpt[Np] = {"pt/El", "pt/Mu", "pt/Pi", "pt/Ka", "pt/Pr", "pt/De", "pt/Tr", "pt/He", "pt/Al"}; - HistogramRegistry histos{"Histos", {}, OutputObjHandlingPolicy::AnalysisObject}; - - void init(o2::framework::InitContext&) - { - histos.add("p/Unselected", "Unselected;#it{p} (GeV/#it{c})", kTH1F, {{100, 0, 20}}); - histos.add("pt/Unselected", "Unselected;#it{p}_{T} (GeV/#it{c})", kTH1F, {{100, 0, 20}}); - for (int i = 0; i < Np; i++) { - histos.add(hp[i].data(), Form("%s;#it{p} (GeV/#it{c})", pT[i]), kTH1F, {{100, 0, 20}}); - histos.add(hpt[i].data(), Form("%s;#it{p}_{T} (GeV/#it{c})", pT[i]), kTH1F, {{100, 0, 20}}); - } - } - - template - void fillParticleHistos(const T& track, const float& nsigma) - { - if (abs(nsigma) > nsigmacut.value) { - return; - } - histos.fill(HIST(hp[i]), track.p()); - histos.fill(HIST(hpt[i]), track.pt()); - } - - Configurable cfgCutVertex{"cfgCutVertex", 10.0f, "Accepted z-vertex range"}; - Configurable cfgCutEta{"cfgCutEta", 0.8f, "Eta range for tracks"}; - Configurable nsigmacut{"nsigmacut", 3, "Value of the Nsigma cut"}; - - Filter collisionFilter = nabs(aod::collision::posZ) < cfgCutVertex; - Filter trackFilter = (nabs(aod::track::eta) < cfgCutEta) && (aod::track::isGlobalTrack == (uint8_t) true); - using TrackCandidates = soa::Filtered>; - - void process(TrackCandidates::iterator const& track) - { - histos.fill(HIST("p/Unselected"), track.p()); - histos.fill(HIST("pt/Unselected"), track.pt()); - - fillParticleHistos<0>(track, track.tpcNSigmaEl()); - fillParticleHistos<1>(track, track.tpcNSigmaMu()); - fillParticleHistos<2>(track, track.tpcNSigmaPi()); - fillParticleHistos<3>(track, track.tpcNSigmaKa()); - fillParticleHistos<4>(track, track.tpcNSigmaPr()); - fillParticleHistos<5>(track, track.tpcNSigmaDe()); - fillParticleHistos<6>(track, track.tpcNSigmaTr()); - fillParticleHistos<7>(track, track.tpcNSigmaHe()); - fillParticleHistos<8>(track, track.tpcNSigmaAl()); - } -}; - -WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) -{ - WorkflowSpec workflow{adaptAnalysisTask(cfgc, TaskName{"tpcspectra-split-task"})}; - return workflow; -} diff --git a/Analysis/Tasks/PWGLF/spectraTPC_tiny.cxx b/Analysis/Tasks/PWGLF/spectraTPCtiny.cxx similarity index 87% rename from Analysis/Tasks/PWGLF/spectraTPC_tiny.cxx rename to Analysis/Tasks/PWGLF/spectraTPCtiny.cxx index 97afac161e199..5a90dfc706579 100644 --- a/Analysis/Tasks/PWGLF/spectraTPC_tiny.cxx +++ b/Analysis/Tasks/PWGLF/spectraTPCtiny.cxx @@ -8,12 +8,18 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +/// +/// \file spectraTPCtiny.h +/// \author Nicolo' Jacazio +/// +/// \brief Task for the analysis of the spectra with the TPC detector using the tiny tables +/// + // O2 includes #include "ReconstructionDataFormats/Track.h" -#include "Framework/runDataProcessing.h" #include "Framework/AnalysisTask.h" -#include "Framework/AnalysisDataModel.h" -#include "Framework/ASoAHelpers.h" +#include "Framework/runDataProcessing.h" +#include "Framework/HistogramRegistry.h" #include "AnalysisDataModel/PID/PIDResponse.h" #include "AnalysisDataModel/TrackSelectionTables.h" @@ -21,7 +27,8 @@ using namespace o2; using namespace o2::framework; using namespace o2::framework::expressions; -struct TPCSpectraTaskTiny { +// Spectra task +struct tpcSpectraTiny { static constexpr int Np = 9; static constexpr const char* pT[Np] = {"e", "#mu", "#pi", "K", "p", "d", "t", "^{3}He", "#alpha"}; static constexpr std::string_view hp[Np] = {"p/El", "p/Mu", "p/Pi", "p/Ka", "p/Pr", "p/De", "p/Tr", "p/He", "p/Al"}; @@ -41,17 +48,17 @@ struct TPCSpectraTaskTiny { template void fillParticleHistos(const T& track, const float& nsigma) { - if (abs(nsigma) > nsigmacut.value) { + if (abs(nsigma) > cfgNSigmaCut) { return; } histos.fill(HIST(hp[i]), track.p()); histos.fill(HIST(hpt[i]), track.pt()); } + //Defining filters and input + Configurable cfgNSigmaCut{"cfgNSigmaCut", 3, "Value of the Nsigma cut"}; Configurable cfgCutVertex{"cfgCutVertex", 10.0f, "Accepted z-vertex range"}; Configurable cfgCutEta{"cfgCutEta", 0.8f, "Eta range for tracks"}; - Configurable nsigmacut{"nsigmacut", 3, "Value of the Nsigma cut"}; - Filter collisionFilter = nabs(aod::collision::posZ) < cfgCutVertex; Filter trackFilter = (nabs(aod::track::eta) < cfgCutEta) && (aod::track::isGlobalTrack == (uint8_t) true); using TrackCandidates = soa::Filtered(track, track.tpcNSigmaTr()); fillParticleHistos<7>(track, track.tpcNSigmaHe()); fillParticleHistos<8>(track, track.tpcNSigmaAl()); - } + + } // end of the process function }; WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { - WorkflowSpec workflow{adaptAnalysisTask(cfgc, TaskName{"tpcspectra-tiny-task"})}; - return workflow; + return WorkflowSpec{adaptAnalysisTask(cfgc)}; } diff --git a/Analysis/Tasks/PWGLF/spectraTPCtinyPiKaPr.cxx b/Analysis/Tasks/PWGLF/spectraTPCtinyPiKaPr.cxx index c39b9ff599a9b..67c4c04f5d888 100644 --- a/Analysis/Tasks/PWGLF/spectraTPCtinyPiKaPr.cxx +++ b/Analysis/Tasks/PWGLF/spectraTPCtinyPiKaPr.cxx @@ -8,12 +8,18 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +/// +/// \file spectraTPCtinyPiKaPr.h +/// \author Nicolo' Jacazio +/// +/// \brief Task for the analysis of the spectra of Pi Ka Pr with the TPC detector using the tiny tables +/// + // O2 includes #include "ReconstructionDataFormats/Track.h" -#include "Framework/runDataProcessing.h" #include "Framework/AnalysisTask.h" -#include "Framework/AnalysisDataModel.h" -#include "Framework/ASoAHelpers.h" +#include "Framework/runDataProcessing.h" +#include "Framework/HistogramRegistry.h" #include "AnalysisDataModel/PID/PIDResponse.h" #include "AnalysisDataModel/TrackSelectionTables.h" @@ -21,7 +27,8 @@ using namespace o2; using namespace o2::framework; using namespace o2::framework::expressions; -struct TPCSpectraTaskTinyPiKaPr { +// Spectra task +struct tpcSpectraTinyPiKaPr { static constexpr int Np = 9; static constexpr const char* pT[Np] = {"e", "#mu", "#pi", "K", "p", "d", "t", "^{3}He", "#alpha"}; static constexpr std::string_view hp[Np] = {"p/El", "p/Mu", "p/Pi", "p/Ka", "p/Pr", "p/De", "p/Tr", "p/He", "p/Al"}; @@ -41,17 +48,17 @@ struct TPCSpectraTaskTinyPiKaPr { template void fillParticleHistos(const T& track, const float& nsigma) { - if (abs(nsigma) > nsigmacut.value) { + if (abs(nsigma) > cfgNSigmaCut) { return; } histos.fill(HIST(hp[i]), track.p()); histos.fill(HIST(hpt[i]), track.pt()); } + //Defining filters and input + Configurable cfgNSigmaCut{"cfgNSigmaCut", 3, "Value of the Nsigma cut"}; Configurable cfgCutVertex{"cfgCutVertex", 10.0f, "Accepted z-vertex range"}; Configurable cfgCutEta{"cfgCutEta", 0.8f, "Eta range for tracks"}; - Configurable nsigmacut{"nsigmacut", 3, "Value of the Nsigma cut"}; - Filter collisionFilter = nabs(aod::collision::posZ) < cfgCutVertex; Filter trackFilter = (nabs(aod::track::eta) < cfgCutEta) && (aod::track::isGlobalTrack == (uint8_t) true); using TrackCandidates = soa::Filtered(track, track.tpcNSigmaPi()); fillParticleHistos<3>(track, track.tpcNSigmaKa()); fillParticleHistos<4>(track, track.tpcNSigmaPr()); - } + + } // end of the process function }; WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { - WorkflowSpec workflow{adaptAnalysisTask(cfgc, TaskName{"tpcspectra-tiny-pikapr-task"})}; - return workflow; + return WorkflowSpec{adaptAnalysisTask(cfgc)}; } From 069001f5be0ab883c601338f27d0bd535bfa26fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B2=20Jacazio?= Date: Tue, 4 May 2021 15:00:29 +0200 Subject: [PATCH 389/770] Rename option in TOF MC QA (#6058) --- Analysis/Tasks/PID/qaTOFMC.cxx | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Analysis/Tasks/PID/qaTOFMC.cxx b/Analysis/Tasks/PID/qaTOFMC.cxx index ceddd3afec517..d8d38115a90eb 100644 --- a/Analysis/Tasks/PID/qaTOFMC.cxx +++ b/Analysis/Tasks/PID/qaTOFMC.cxx @@ -28,10 +28,10 @@ using namespace o2::track; void customize(std::vector& workflowOptions) { std::vector options{ - {"pid-el", VariantType::Int, 0, {"Produce PID information for the electron mass hypothesis"}}, - {"pid-mu", VariantType::Int, 0, {"Produce PID information for the muon mass hypothesis"}}, - {"pid-pikapr", VariantType::Int, 1, {"Produce PID information for the Pion, Kaon, Proton mass hypothesis"}}, - {"pid-nuclei", VariantType::Int, 0, {"Produce PID information for the Deuteron, Triton, Alpha mass hypothesis"}}}; + {"qa-el", VariantType::Int, 0, {"Produce PID information for the electron mass hypothesis"}}, + {"qa-mu", VariantType::Int, 0, {"Produce PID information for the muon mass hypothesis"}}, + {"qa-pikapr", VariantType::Int, 1, {"Produce PID information for the Pion, Kaon, Proton mass hypothesis"}}, + {"qa-nuclei", VariantType::Int, 0, {"Produce PID information for the Deuteron, Triton, Alpha mass hypothesis"}}}; std::swap(workflowOptions, options); } @@ -212,18 +212,18 @@ struct pidTOFTaskQA { WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { auto workflow = WorkflowSpec{}; - if (cfgc.options().get("pid-el")) { + if (cfgc.options().get("qa-el")) { workflow.push_back(adaptAnalysisTask>(cfgc, TaskName{"pidTOF-qa-El"})); } - if (cfgc.options().get("pid-mu")) { + if (cfgc.options().get("qa-mu")) { workflow.push_back(adaptAnalysisTask>(cfgc, TaskName{"pidTOF-qa-Mu"})); } - if (cfgc.options().get("pid-pikapr")) { + if (cfgc.options().get("qa-pikapr")) { workflow.push_back(adaptAnalysisTask>(cfgc, TaskName{"pidTOF-qa-Pi"})); workflow.push_back(adaptAnalysisTask>(cfgc, TaskName{"pidTOF-qa-Ka"})); workflow.push_back(adaptAnalysisTask>(cfgc, TaskName{"pidTOF-qa-Pr"})); } - if (cfgc.options().get("pid-nuclei")) { + if (cfgc.options().get("qa-nuclei")) { workflow.push_back(adaptAnalysisTask>(cfgc, TaskName{"pidTOF-qa-De"})); workflow.push_back(adaptAnalysisTask>(cfgc, TaskName{"pidTOF-qa-Tr"})); workflow.push_back(adaptAnalysisTask>(cfgc, TaskName{"pidTOF-qa-He"})); From 17442cc405c377568796e68d0ebdbf4d22ac1c7b Mon Sep 17 00:00:00 2001 From: Gian Michele Innocenti Date: Tue, 4 May 2021 15:01:29 +0200 Subject: [PATCH 390/770] Add pt dependent mass hisograms for mc task (#6041) --- Analysis/Tasks/PWGHF/taskJpsi.cxx | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Analysis/Tasks/PWGHF/taskJpsi.cxx b/Analysis/Tasks/PWGHF/taskJpsi.cxx index fb2bf1b0e4345..fe395c8dcf6a7 100644 --- a/Analysis/Tasks/PWGHF/taskJpsi.cxx +++ b/Analysis/Tasks/PWGHF/taskJpsi.cxx @@ -108,6 +108,13 @@ struct TaskJpsiMC { Configurable d_selectionFlagJpsi{"d_selectionFlagJpsi", 1, "Selection Flag for Jpsi"}; Configurable cutYCandMax{"cutYCandMax", -1., "max. cand. rapidity"}; + Configurable> bins{"pTBins", std::vector{hf_cuts_jpsi_toee::pTBins_v}, "pT bin limits"}; + + void init(o2::framework::InitContext&) + { + registry.add("hmassSig", "2-prong candidates (rec matched);inv. mass (e^{#plus} e^{#minus}) (GeV/#it{c}^{2});entries", {HistType::kTH2F, {{500, 0., 5.}, {(std::vector)bins, "#it{p}_{T} (GeV/#it{c})"}}}); + registry.add("hmassBkg", "2-prong candidates (rec unmatched);inv. mass (e^{#plus} e^{#minus}) (GeV/#it{c}^{2});entries", {HistType::kTH2F, {{500, 0., 5.}, {(std::vector)bins, "#it{p}_{T} (GeV/#it{c})"}}}); + } Filter filterSelectCandidates = (aod::hf_selcandidate_jpsi::isSelJpsiToEE >= d_selectionFlagJpsi); @@ -131,10 +138,12 @@ struct TaskJpsiMC { registry.fill(HIST("hPtRecSig"), candidate.pt()); // rec. level pT registry.fill(HIST("hCPARecSig"), candidate.cpa()); registry.fill(HIST("hEtaRecSig"), candidate.eta()); + registry.fill(HIST("hmassSig"), InvMassJpsiToEE(candidate), candidate.pt()); } else { registry.fill(HIST("hPtRecBg"), candidate.pt()); registry.fill(HIST("hCPARecBg"), candidate.cpa()); registry.fill(HIST("hEtaRecBg"), candidate.eta()); + registry.fill(HIST("hmassBkg"), InvMassJpsiToEE(candidate), candidate.pt()); } } // MC gen. From 6c6cf07b032e619ce77e6dd4ff617b140efdc178 Mon Sep 17 00:00:00 2001 From: aferrero2707 Date: Tue, 4 May 2021 21:58:37 +0200 Subject: [PATCH 391/770] [MCH] adapted page reader output spec to three-letters standard (#6060) --- .../MUON/MCH/Workflow/src/cru-page-reader-workflow.cxx | 6 +++--- .../MUON/MCH/Workflow/src/cru-page-to-digits-workflow.cxx | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Detectors/MUON/MCH/Workflow/src/cru-page-reader-workflow.cxx b/Detectors/MUON/MCH/Workflow/src/cru-page-reader-workflow.cxx index 9f0431b6bc61e..2a20136176323 100644 --- a/Detectors/MUON/MCH/Workflow/src/cru-page-reader-workflow.cxx +++ b/Detectors/MUON/MCH/Workflow/src/cru-page-reader-workflow.cxx @@ -407,7 +407,7 @@ class FileReaderTask } auto freefct = [](void* data, void* /*hint*/) { free(data); }; - pc.outputs().adoptChunk(Output{"ROUT", "RAWDATA"}, tfQueue.front().buf, tfQueue.front().totalSize, freefct, nullptr); + pc.outputs().adoptChunk(Output{"RDT", "RAWDATA"}, tfQueue.front().buf, tfQueue.front().totalSize, freefct, nullptr); TFid += 1; } tfQueue.pop(); @@ -513,7 +513,7 @@ class FileReaderTask if ((stopBit != 0) || (mFullHBF == false)) { // create the output message auto freefct = [](void* data, void* /*hint*/) { free(data); }; - pc.outputs().adoptChunk(Output{"ROUT", "RAWDATA"}, buf, bufSize, freefct, nullptr); + pc.outputs().adoptChunk(Output{"RDT", "RAWDATA"}, buf, bufSize, freefct, nullptr); // stop the readout loop break; @@ -538,7 +538,7 @@ o2::framework::DataProcessorSpec getFileReaderSpec() return DataProcessorSpec{ "FileReader", Inputs{}, - Outputs{OutputSpec{"ROUT", "RAWDATA", 0, Lifetime::Timeframe}}, + Outputs{OutputSpec{"RDT", "RAWDATA", 0, Lifetime::Timeframe}}, AlgorithmSpec{adaptFromTask()}, Options{{"infile", VariantType::String, "", {"input file name"}}, {"nframes", VariantType::Int, -1, {"number of frames to process"}}, diff --git a/Detectors/MUON/MCH/Workflow/src/cru-page-to-digits-workflow.cxx b/Detectors/MUON/MCH/Workflow/src/cru-page-to-digits-workflow.cxx index 2c73d33108a41..9e95dad1744c8 100644 --- a/Detectors/MUON/MCH/Workflow/src/cru-page-to-digits-workflow.cxx +++ b/Detectors/MUON/MCH/Workflow/src/cru-page-to-digits-workflow.cxx @@ -33,7 +33,7 @@ WorkflowSpec defineDataProcessing(const ConfigContext&) { WorkflowSpec specs; - DataProcessorSpec producer = o2::mch::raw::getDecodingSpec("readout:ROUT/RAWDATA"); + DataProcessorSpec producer = o2::mch::raw::getDecodingSpec("readout:RDT/RAWDATA"); specs.push_back(producer); return specs; From 61db11e4f2b04627a60ad29de8d128a58c43cf11 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Wed, 5 May 2021 07:12:41 +0200 Subject: [PATCH 392/770] DPL: add a DataTakingContext to be filled with run related constants (#6062) --- .../Core/include/Framework/CommonServices.h | 1 + .../include/Framework/DataTakingContext.h | 30 ++++++++++++ Framework/Core/src/CommonServices.cxx | 47 +++++++++++++++++++ .../TestWorkflows/src/o2DiamondWorkflow.cxx | 3 +- 4 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 Framework/Core/include/Framework/DataTakingContext.h diff --git a/Framework/Core/include/Framework/CommonServices.h b/Framework/Core/include/Framework/CommonServices.h index b9c210ed49d0a..435761aa5fc92 100644 --- a/Framework/Core/include/Framework/CommonServices.h +++ b/Framework/Core/include/Framework/CommonServices.h @@ -49,6 +49,7 @@ struct CommonServices { static ServiceSpec driverClientSpec(); static ServiceSpec monitoringSpec(); + static ServiceSpec datatakingContextSpec(); static ServiceSpec infologgerContextSpec(); static ServiceSpec infologgerSpec(); static ServiceSpec configurationSpec(); diff --git a/Framework/Core/include/Framework/DataTakingContext.h b/Framework/Core/include/Framework/DataTakingContext.h new file mode 100644 index 0000000000000..0fe5a4c401788 --- /dev/null +++ b/Framework/Core/include/Framework/DataTakingContext.h @@ -0,0 +1,30 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. +#ifndef O2_FRAMEWORK_DATATAKINGCONTEXT_H_ +#define O2_FRAMEWORK_DATATAKINGCONTEXT_H_ + +#include +#include + +namespace o2::framework +{ + +struct DataTakingContext { + /// The current run number + std::string runNumber = "unknown"; + /// How many orbits in a timeframe + uint64_t nOrbitsPerTF = 128; + /// The start time of the first orbit + uint64_t orbitResetTime = 490917600; +}; + +} // namespace o2::framework + +#endif // O2_FRAMEWORK_DATATAKINGCONTEXT_H_ diff --git a/Framework/Core/src/CommonServices.cxx b/Framework/Core/src/CommonServices.cxx index 55757c16b5d2d..b280c9c33a7f3 100644 --- a/Framework/Core/src/CommonServices.cxx +++ b/Framework/Core/src/CommonServices.cxx @@ -13,6 +13,7 @@ #include "Framework/DriverClient.h" #include "Framework/CallbackService.h" #include "Framework/TimesliceIndex.h" +#include "Framework/DataTakingContext.h" #include "Framework/ServiceRegistry.h" #include "Framework/DeviceSpec.h" #include "Framework/LocalRootFileService.h" @@ -107,6 +108,51 @@ o2::framework::ServiceSpec CommonServices::monitoringSpec() ServiceKind::Serial}; } +o2::framework::ServiceSpec CommonServices::datatakingContextSpec() +{ + return ServiceSpec{"datataking-contex", + simpleServiceInit(), + noConfiguration(), + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + [](ServiceRegistry& services, void* service) { + auto& context = services.get(); + context.runNumber = services.get().device()->fConfig->GetProperty("runNumber", "unspecified"); + // FIXME: we actually need to get the orbit, not only to know where it is + std::string orbitResetTimeUrl = services.get().device()->fConfig->GetProperty("orbit-reset-time", "ccdb://CTP/Calib/OrbitResetTime"); + auto is_number = [](const std::string& s) -> bool { + return !s.empty() && std::all_of(s.begin(), s.end(), ::isdigit); + }; + + if (orbitResetTimeUrl.rfind("file://") == 0) { + // FIXME: read it from a file + context.orbitResetTime = 490917600; + } else if (orbitResetTimeUrl.rfind("http://") == 0) { + // FIXME: read it from ccdb + context.orbitResetTime = 490917600; + } else if (is_number(orbitResetTimeUrl)) { + context.orbitResetTime = std::stoull(orbitResetTimeUrl.data()); + // FIXME: specify it from the command line + } else { + context.orbitResetTime = 490917600; + } + context.nOrbitsPerTF = services.get().device()->fConfig->GetProperty("Norbits_per_TF", 128); + }, + nullptr, + ServiceKind::Serial}; +} + o2::framework::ServiceSpec CommonServices::infologgerContextSpec() { return ServiceSpec{"infologger-contex", @@ -637,6 +683,7 @@ std::vector CommonServices::defaultServices(int numThreads) timesliceIndex(), driverClientSpec(), monitoringSpec(), + datatakingContextSpec(), infologgerContextSpec(), infologgerSpec(), configurationSpec(), diff --git a/Framework/TestWorkflows/src/o2DiamondWorkflow.cxx b/Framework/TestWorkflows/src/o2DiamondWorkflow.cxx index 6ca214f31dcb0..5724defc63948 100644 --- a/Framework/TestWorkflows/src/o2DiamondWorkflow.cxx +++ b/Framework/TestWorkflows/src/o2DiamondWorkflow.cxx @@ -8,6 +8,7 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. #include "Framework/ConfigParamSpec.h" +#include "Framework/DataTakingContext.h" #include "Framework/CompletionPolicyHelpers.h" #include "Framework/DeviceSpec.h" #include "Framework/RawDeviceService.h" @@ -62,7 +63,7 @@ WorkflowSpec defineDataProcessing(ConfigContext const& specs) {OutputSpec{{"a1"}, "TST", "A1"}, OutputSpec{{"a2"}, "TST", "A2"}}, AlgorithmSpec{adaptStateless( - [](DataAllocator& outputs, InfoLogger& logger, RawDeviceService& device) { + [](DataAllocator& outputs, InfoLogger& logger, RawDeviceService& device, DataTakingContext& context) { device.device()->WaitFor(std::chrono::seconds(rand() % 2)); auto& aData = outputs.make(OutputRef{"a1"}, 1); auto& bData = outputs.make(OutputRef{"a2"}, 1); From 24a69fb3e09e1ff4788b651b60d7f622c9a4c283 Mon Sep 17 00:00:00 2001 From: Jason Barrella Date: Thu, 25 Feb 2021 11:06:21 +0200 Subject: [PATCH 393/770] new coordinate transformation functions in PadPlane with CMake tests --- Detectors/TRD/base/CMakeLists.txt | 7 + Detectors/TRD/base/include/TRDBase/PadPlane.h | 42 +++++- .../include/TRDBase/TrackletTransformer.h | 2 + Detectors/TRD/base/src/PadPlane.cxx | 58 +++++++- .../TRD/base/src/TrackletTransformer.cxx | 20 +++ .../base/test/testCoordinateTransforms.cxx | 135 ++++++++++++++++++ Detectors/TRD/simulation/src/Digitizer.cxx | 4 +- 7 files changed, 259 insertions(+), 9 deletions(-) create mode 100644 Detectors/TRD/base/test/testCoordinateTransforms.cxx diff --git a/Detectors/TRD/base/CMakeLists.txt b/Detectors/TRD/base/CMakeLists.txt index 3b7c8eb85bee7..eccd1f494a909 100644 --- a/Detectors/TRD/base/CMakeLists.txt +++ b/Detectors/TRD/base/CMakeLists.txt @@ -86,3 +86,10 @@ o2_add_test(RawData ENVIRONMENT O2_ROOT=${CMAKE_BINARY_DIR}/stage LABELS trd ) +o2_add_test(Transformations + COMPONENT_NAME trd + PUBLIC_LINK_LIBRARIES O2::TRDBase O2::DataFormatsTRD + SOURCES test/testCoordinateTransforms.cxx + ENVIRONMENT O2_ROOT=${CMAKE_BINARY_DIR}/stage + LABELS trd + ) diff --git a/Detectors/TRD/base/include/TRDBase/PadPlane.h b/Detectors/TRD/base/include/TRDBase/PadPlane.h index 7e72d508c0e03..c81053a97cee4 100644 --- a/Detectors/TRD/base/include/TRDBase/PadPlane.h +++ b/Detectors/TRD/base/include/TRDBase/PadPlane.h @@ -13,7 +13,6 @@ //Forwards to standard header with protection for GPU compilation #include "GPUCommonRtypes.h" // for ClassDef - #include "GPUCommonDef.h" //////////////////////////////////////////////////////////////////////////// @@ -61,19 +60,44 @@ class PadPlane }; void setLength(double l) { mLength = l; }; void setWidth(double w) { mWidth = w; }; - void setLengthOPad(double l) { mLengthOPad = l; }; - void setWidthOPad(double w) { mWidthOPad = w; }; - void setLengthIPad(double l) { mLengthIPad = l; }; - void setWidthIPad(double w) { mWidthIPad = w; }; + void setLengthOPad(double l) + { + mLengthOPad = l; + mInverseLengthOPad = 1.0 / l; + }; + void setWidthOPad(double w) + { + mWidthOPad = w; + mInverseWidthOPad = 1.0 / w; + }; + void setLengthIPad(double l) + { + mLengthIPad = l; + mInverseLengthIPad = 1.0 / l; + }; + void setWidthIPad(double w) + { + mWidthIPad = w; + mInverseWidthIPad = 1.0 / w; + }; void setPadRowSMOffset(double o) { mPadRowSMOffset = o; }; void setAnodeWireOffset(float o) { mAnodeWireOffset = o; }; void setTiltingAngle(double t); GPUd() int getPadRowNumber(double z) const; GPUd() int getPadRowNumberROC(double z) const; + GPUd() double getPadRow(double z) const; GPUd() int getPadColNumber(double rphi) const; + GPUd() double getPad(double y, double z) const; - GPUd() double getTiltOffset(double rowOffset) const { return mTiltingTan * (rowOffset - 0.5 * mLengthIPad); }; + GPUd() double getTiltOffset(int row, double rowOffset) const + { + if (row == 0 || row == mNrows - 1) { + return mTiltingTan * (rowOffset - 0.5 * mLengthOPad); + } else { + return mTiltingTan * (rowOffset - 0.5 * mLengthIPad); + } + }; GPUd() double getPadRowOffset(int row, double z) const { if ((row < 0) || (row >= mNrows)) { @@ -174,6 +198,12 @@ class PadPlane double mAnodeWireOffset; // Distance of first anode wire from pad edge + double mInverseLengthIPad; // 1 / mLengthIPad + double mInverseLengthOPad; // 1 / mLengthOPad + + double mInverseWidthIPad; // 1 / mWidthIPad + double mInverseWidthOPad; // 1 / mWidthOPad + private: ClassDefNV(PadPlane, 1); // TRD ROC pad plane }; diff --git a/Detectors/TRD/base/include/TRDBase/TrackletTransformer.h b/Detectors/TRD/base/include/TRDBase/TrackletTransformer.h index 80614fb2df6d8..51588c36146b4 100644 --- a/Detectors/TRD/base/include/TRDBase/TrackletTransformer.h +++ b/Detectors/TRD/base/include/TRDBase/TrackletTransformer.h @@ -50,6 +50,8 @@ class TrackletTransformer CalibratedTracklet transformTracklet(Tracklet64 tracklet); + double getTimebin(double x); + private: o2::trd::Geometry* mGeo; const o2::trd::PadPlane* mPadPlane; diff --git a/Detectors/TRD/base/src/PadPlane.cxx b/Detectors/TRD/base/src/PadPlane.cxx index bc8a65c485869..cbbf67258d5cd 100644 --- a/Detectors/TRD/base/src/PadPlane.cxx +++ b/Detectors/TRD/base/src/PadPlane.cxx @@ -24,8 +24,10 @@ #include "TRDBase/PadPlane.h" #include #include +#include "DataFormatsTRD/Constants.h" using namespace o2::trd; +using namespace o2::trd::constants; //_____________________________________________________________________________ void PadPlane::setTiltingAngle(double t) @@ -35,7 +37,7 @@ void PadPlane::setTiltingAngle(double t) // mTiltingAngle = t; - mTiltingTan = TMath::Tan(TMath::Pi() / 180.0 * mTiltingAngle); + mTiltingTan = TMath::Tan(TMath::DegToRad() * mTiltingAngle); } //_____________________________________________________________________________ @@ -158,3 +160,57 @@ void PadPlane::setNrows(int n) } mNrows = n; }; + +double PadPlane::getPadRow(double z) const +{ + double lengthCorr = mLengthIPad * mInverseLengthOPad; + + // calculate position based on inner pad length + double padrow = -z * mInverseLengthIPad + mNrows * 0.5; + + // correct row for outer pad rows + if (padrow <= 1.0) { + padrow = 1.0 - (1.0 - padrow) * lengthCorr; + } + + if (padrow >= double(mNrows - 1)) { + padrow = double(mNrows - 1) + (padrow - double(mNrows - 1)) * lengthCorr; + } + + // sanity check: is the padrow coordinate reasonable? + assert(!(padrow < 0.0 || padrow > double(mNrows))); + + return padrow; +} + +double PadPlane::getPad(double y, double z) const +{ + int padrow = getPadRow(z); + double padrowOffset = getPadRowOffsetROC(padrow, z); + double tiltOffsetY = getTiltOffset(padrow, padrowOffset); + + double pad = y * mInverseWidthIPad + mNcols * 0.5; + + double lengthCorr = mWidthIPad * mInverseWidthOPad; + // correct row for outer pad rows + if (pad <= 1.0) { + pad = 1.0 - (1.0 - pad) * lengthCorr; + } + + if (pad >= double(mNcols - 1)) { + pad = double(mNcols - 1) + (pad - double(mNcols - 1)) * lengthCorr; + } + + double tiltOffsetPad; + if (pad <= 1.0 || pad >= double(mNcols - 1)) { + tiltOffsetPad = tiltOffsetY * mInverseWidthOPad; + pad += tiltOffsetPad; + } else { + tiltOffsetPad = tiltOffsetY * mInverseWidthIPad; + pad += tiltOffsetPad; + } + + assert(!(pad < 0.0 || pad > double(mNcols))); + + return pad; +} diff --git a/Detectors/TRD/base/src/TrackletTransformer.cxx b/Detectors/TRD/base/src/TrackletTransformer.cxx index 741e6d85ec5fc..a1a546a4faad6 100644 --- a/Detectors/TRD/base/src/TrackletTransformer.cxx +++ b/Detectors/TRD/base/src/TrackletTransformer.cxx @@ -165,3 +165,23 @@ CalibratedTracklet TrackletTransformer::transformTracklet(Tracklet64 tracklet) return CalibratedTracklet(sectorSpacePoint[0], sectorSpacePoint[1], sectorSpacePoint[2], dy); } + +double TrackletTransformer::getTimebin(double x) +{ + // calculate timebin from x position within chamber + // calibration parameters need to be extracted from CCDB in the future + double vDrift = 1.5625; // in cm/us + double t0 = 4.0; // time (in timebins) of start of drift region + + double timebin; + // x = 0 at anode plane and points toward pad plane. + if (x < -mGeo->camHght() / 2) { + // drift region + timebin = t0 - (x + mGeo->camHght() / 2) / (vDrift * 0.1); + } else { + // anode region: very rough guess + timebin = t0 - 1.0 + fabs(x); + } + + return timebin; +} diff --git a/Detectors/TRD/base/test/testCoordinateTransforms.cxx b/Detectors/TRD/base/test/testCoordinateTransforms.cxx new file mode 100644 index 0000000000000..1bcfbd56314ed --- /dev/null +++ b/Detectors/TRD/base/test/testCoordinateTransforms.cxx @@ -0,0 +1,135 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file testCoordinateTransformscxx +/// \brief Test local to row-column (float) coordinate transformations in PadPlane class +/// \author Jason Barrella - jbarrell@cern.ch, Sean Murray - murrays@cern.ch + +#define BOOST_TEST_MODULE Test CoordinateTransforms +#define BOOST_TEST_MAIN +#define BOOST_TEST_DYN_LINK +#include +#include +#include + +#include "DataFormatsTRD/Constants.h" +#include "TRDBase/TrackletTransformer.h" + +#include "TRDBase/PadPlane.h" +#include "DetectorsBase/GeometryManager.h" +#include "TRDBase/Geometry.h" + +namespace o2 +{ +namespace trd +{ + +using namespace o2::trd::constants; +using namespace std; + +void testRCPoint(double calculatedPoint, double predictedPoint) +{ + float e = 0.000001; + BOOST_CHECK(fabs(predictedPoint - calculatedPoint) <= e); +} + +BOOST_AUTO_TEST_CASE(LocaltoRCTest) +{ + auto mGeo = o2::trd::Geometry::instance(); + mGeo->createPadPlaneArray(); + mGeo->createClusterMatrixArray(); + + int hcid = 776; + // This C1 chamber has 16 pad rows with I pad length = 90mm and O pad length = 75mm + int detector = hcid / 2; + int stack = mGeo->getStack(detector); + int layer = mGeo->getLayer(detector); + + auto padPlane = mGeo->getPadPlane(layer, stack); + double lengthIPad = padPlane->getLengthIPad(); + double lengthOPad = padPlane->getLengthOPad(); + + double padIWidth = padPlane->getWidthIPad(); + double padOWidth = padPlane->getWidthOPad(); + + double tiltingAngle = padPlane->getTiltingAngle(); + + // Test padrows + auto p1 = padPlane->getPadRow(0); + // Center of the chamber. This should return the lower edge of padrow 8. + // Since we are using float values, the lower edge of padrow 8 correspond with float value 8.0. + testRCPoint(p1, 8.); + + auto p2 = padPlane->getPadRow(lengthIPad / 2.); + // With an I pad length of 9 cm, 9. / 2. should put us half way into the preceeding pad (pad 7) since padrow number + // decreses in positive z direction. + testRCPoint(p2, 7.5); + + auto p3 = padPlane->getPadRow(-lengthIPad / 2.); + // Same as above but in the other direction. + testRCPoint(p3, 8.5); + + auto p4 = padPlane->getPadRow(lengthIPad * 4.2); + // Arbitrary distance in z. + testRCPoint(p4, 8 - 4.2); + + auto p5 = padPlane->getPadRow(lengthIPad * 7 + lengthOPad); + // Lower border case. Take center and add 7 pads * 9 cm + 1 pad * 7.5 cm. + testRCPoint(p5, 0); + + auto p6 = padPlane->getPadRow(-lengthIPad * 7 - lengthOPad); + // Upper border case. Take center and subtract 7 pads * 9 cm - 1 pad * 7.5 cm. + testRCPoint(p6, 16); + + // Test pads with pad tilting + double p13 = padPlane->getPad(0, 0.01); + // Center of chamber plus epsilon (in z). Note the discontinuity in pad vs. z at z=0. This puts us at a point on the lower + // (in z direction) end of padrow 7. Since we have a pad tilt of -2 deg (pads tilted clockwise for particle coming + // from interaction vertex). After a lot thought and doodles on Miro (https://miro.com/app/board/o9J_lKgybMc=/) we + // find that we expect a small negative offset which would place us in the upper half of pad 71. + // To calculate that offset, we multiply the tangent of the tilting angle by the distance that our point is away + // from the center of its local padrow. Some unit conversions are also neccessary... + testRCPoint(p13, 72 + TMath::Tan(TMath::DegToRad() * tiltingAngle) * (0.5 * lengthIPad - 0.01) / padIWidth); + + double p14 = padPlane->getPad(0, -lengthIPad / 2.); + // Move from center of chamber to to center of padrow 8 = 8.5. + // This should now place us as edge of pad 72 = 72.0 since no offset is applied from pad tilt. + testRCPoint(p14, 72); + + double p15 = padPlane->getPad(0, lengthIPad / 2.); + // Should be the same in the other direction at padrow = 7.5 + testRCPoint(p15, 72); + + double p16 = padPlane->getPad(padIWidth * 42, lengthIPad / 2.); + // Adding an arbitrary number of pads should just increase position by same number + testRCPoint(p16, 72 + 42); + + double p17 = padPlane->getPad(padIWidth * 42, -lengthIPad * 4 - 2.3); + // Moving to arbitrary point in both y and z. In y, we are 42 pads from the center which would be 72 + 42 = 114 + // if we were in the center of the padrow and no pad tilting is considered. However, we are not in the center of + // a padrow, but rather 2.3 cm into padrow 8 + 4 = 12. This puts us below the center which is at 4.5 cm + // into the padrow and therefore, we expect a small postiive offset since the pad tilting angle is -2 deg. + testRCPoint(p17, 72 + 42 + TMath::Tan(TMath::DegToRad() * tiltingAngle) * (2.3 - 0.5 * lengthIPad) / padIWidth); + + double p18 = padPlane->getPad(padIWidth * 71 + padOWidth, lengthIPad / 2.); + // Border case right on the upper edge of the padrow in y direction and at the center of the padrow in z + testRCPoint(p18, 144); + + double p19 = padPlane->getPad(-padIWidth * 71 - padOWidth, lengthIPad / 2.); + // Border case right on the lower edge of the padrow in y direction and at the center of the padrow in z + testRCPoint(p19, 0); + + double p20 = padPlane->getPad(0, lengthIPad * 7 + 1.5); + // Ensure that shorter length of outer padrows is considered correctly + testRCPoint(p20, 72 + TMath::Tan(TMath::DegToRad() * tiltingAngle) * (0.5 * lengthOPad - 1.5) / padIWidth); +} + +} // namespace trd +} // namespace o2 diff --git a/Detectors/TRD/simulation/src/Digitizer.cxx b/Detectors/TRD/simulation/src/Digitizer.cxx index 2053be4b39070..c51de1cf7f2db 100644 --- a/Detectors/TRD/simulation/src/Digitizer.cxx +++ b/Detectors/TRD/simulation/src/Digitizer.cxx @@ -251,7 +251,7 @@ bool Digitizer::convertHits(const int det, const std::vector& hits, SignalC } double rowOffset = padPlane->getPadRowOffsetROC(rowE, locR); - double offsetTilt = padPlane->getTiltOffset(rowOffset); + double offsetTilt = padPlane->getTiltOffset(rowE, rowOffset); int colE = padPlane->getPadColNumber(locC + offsetTilt); if (colE < 0) { continue; @@ -295,7 +295,7 @@ bool Digitizer::convertHits(const int det, const std::vector& hits, SignalC } rowOffset = padPlane->getPadRowOffsetROC(rowE, locRd); // The pad column (rphi-direction) - offsetTilt = padPlane->getTiltOffset(rowOffset); + offsetTilt = padPlane->getTiltOffset(rowE, rowOffset); colE = padPlane->getPadColNumber(locCd + offsetTilt); if (colE < 0) { continue; From 33ced2586c9cac4f8b988f35b3871b3140f40962 Mon Sep 17 00:00:00 2001 From: jgrosseo Date: Wed, 5 May 2021 15:21:05 +0200 Subject: [PATCH 394/770] Split HistogramRegistry headers + AxisConfigurables in Correlations (#6063) * Using AxisConfigurables in correlation code * Split headers of HistogramRegistry --- .../AnalysisCore/CorrelationContainer.h | 10 +- Analysis/Core/src/CorrelationContainer.cxx | 360 ++---------------- Analysis/Tasks/PWGCF/correlations.cxx | 46 ++- Analysis/Tasks/PWGCF/correlationsFiltered.cxx | 37 +- Analysis/Tasks/PWGCF/correlationsMixed.cxx | 38 +- .../include/Framework/HistogramRegistry.h | 185 +-------- .../Core/include/Framework/HistogramSpec.h | 203 ++++++++++ Framework/Core/include/Framework/StepTHn.h | 2 +- 8 files changed, 319 insertions(+), 562 deletions(-) create mode 100644 Framework/Core/include/Framework/HistogramSpec.h diff --git a/Analysis/Core/include/AnalysisCore/CorrelationContainer.h b/Analysis/Core/include/AnalysisCore/CorrelationContainer.h index 5591193f104df..91094cfb667fd 100644 --- a/Analysis/Core/include/AnalysisCore/CorrelationContainer.h +++ b/Analysis/Core/include/AnalysisCore/CorrelationContainer.h @@ -15,6 +15,7 @@ #include "TNamed.h" #include "TString.h" +#include "Framework/HistogramSpec.h" class TH1; class TH1F; @@ -33,7 +34,7 @@ class CorrelationContainer : public TNamed { public: CorrelationContainer(); - CorrelationContainer(const char* name, const char* objTitle, const char* reqHist = "", const char* binning = nullptr); + CorrelationContainer(const char* name, const char* objTitle, const std::vector& axisList); virtual ~CorrelationContainer(); // NOLINT: Making this override breaks compilation for unknown reason static const Int_t fgkCFSteps; @@ -123,8 +124,6 @@ class CorrelationContainer : public TNamed void setWeightPerEvent(Bool_t flag) { mWeightPerEvent = flag; } void setSkipScaleMixedEvent(Bool_t flag) { mSkipScaleMixedEvent = flag; } - void setHistogramType(const char* histogramType) { mHistogramType = histogramType; } - void countEmptyBins(CorrelationContainer::CFStep step, Float_t ptTriggerMin, Float_t ptTriggerMax); void symmetrizepTBins(); @@ -142,10 +141,7 @@ class CorrelationContainer : public TNamed void Reset(); THnBase* changeToThn(THnBase* sparse); - static TString combineBinning(TString defaultBinning, TString customBinning); - protected: - std::vector getBinning(const char* configuration, const char* tag, Int_t& nBins); void weightHistogram(TH3* hist1, TH1* hist2); void multiplyHistograms(THnBase* grid, THnBase* target, TH1* histogram, Int_t var1, Int_t var2); @@ -176,8 +172,6 @@ class CorrelationContainer : public TNamed Bool_t mGetMultCacheOn; //! cache for getHistsZVtxMult function active THnBase* mGetMultCache; //! cache for getHistsZVtxMult function - TString mHistogramType; // what is stored in this histogram - ClassDef(CorrelationContainer, 1) // underlying event histogram container }; diff --git a/Analysis/Core/src/CorrelationContainer.cxx b/Analysis/Core/src/CorrelationContainer.cxx index 60c014d643044..96eaaa7187819 100644 --- a/Analysis/Core/src/CorrelationContainer.cxx +++ b/Analysis/Core/src/CorrelationContainer.cxx @@ -26,6 +26,9 @@ #include "TCanvas.h" #include "TF1.h" #include "THn.h" +#include "Framework/HistogramRegistry.h" + +using namespace o2::framework; ClassImp(CorrelationContainer) @@ -52,332 +55,50 @@ CorrelationContainer::CorrelationContainer() : TNamed(), mSkipScaleMixedEvent(kFALSE), mCache(nullptr), mGetMultCacheOn(kFALSE), - mGetMultCache(nullptr), - mHistogramType() + mGetMultCache(nullptr) { // Default constructor } -CorrelationContainer::CorrelationContainer(const char* name, const char* objTitle, const char* reqHist, const char* binning) : TNamed(name, objTitle), - mPairHist(nullptr), - mTriggerHist(nullptr), - mTrackHistEfficiency(nullptr), - mEventCount(nullptr), - mEtaMin(0), - mEtaMax(0), - mPtMin(0), - mPtMax(0), - mPartSpecies(-1), - mCentralityMin(0), - mCentralityMax(0), - mZVtxMin(0), - mZVtxMax(0), - mPt2Min(0), - mPt2Max(0), - mTrackEtaCut(0), - mWeightPerEvent(0), - mSkipScaleMixedEvent(kFALSE), - mCache(nullptr), - mGetMultCacheOn(kFALSE), - mGetMultCache(nullptr), - mHistogramType(reqHist) +CorrelationContainer::CorrelationContainer(const char* name, const char* objTitle, const std::vector& axisList) : TNamed(name, objTitle), + mPairHist(nullptr), + mTriggerHist(nullptr), + mTrackHistEfficiency(nullptr), + mEventCount(nullptr), + mEtaMin(0), + mEtaMax(0), + mPtMin(0), + mPtMax(0), + mPartSpecies(-1), + mCentralityMin(0), + mCentralityMax(0), + mZVtxMin(0), + mZVtxMax(0), + mPt2Min(0), + mPt2Max(0), + mTrackEtaCut(0), + mWeightPerEvent(0), + mSkipScaleMixedEvent(kFALSE), + mCache(nullptr), + mGetMultCacheOn(kFALSE), + mGetMultCache(nullptr) { // Constructor + // + // axisList has to provide a 8 length list of AxisSpec which contain: + // delta_eta, pt_assoc, pt_trig, multiplicity/centrality, delta_phi, vertex, eta (for efficiency), pt (for efficiency), vertex (for efficiency) - using BinList = std::vector; - - if (strlen(reqHist) == 0) { + if (strlen(name) == 0) { return; } - LOGF(info, "Creating CorrelationContainer with %s (binning: %s)", reqHist, binning); - - const char* title = ""; - - // track level - Int_t nTrackVars = 4; // eta vs pT vs pT,lead (vs delta phi) vs multiplicity - Int_t iTrackBin[7]; - BinList trackBins[7]; - const char* trackAxisTitle[7]; - - // eta - Int_t nEtaBins = -1; - BinList etaBins = getBinning(binning, "eta", nEtaBins); - const char* etaTitle = "#eta"; - - iTrackBin[0] = nEtaBins; - trackBins[0] = etaBins; - trackAxisTitle[0] = etaTitle; - - // delta eta - Int_t nDeltaEtaBins = -1; - BinList deltaEtaBins = getBinning(binning, "delta_eta", nDeltaEtaBins); - - // pT - trackBins[1] = getBinning(binning, "p_t_assoc", iTrackBin[1]); - trackAxisTitle[1] = "p_{T} (GeV/c)"; - - // pT, fine - Int_t npTBinsFine = -1; - BinList pTBinsFine = getBinning(binning, "p_t_eff", npTBinsFine); - - // pT,lead binning 1 - Int_t nLeadingpTBins = -1; - BinList leadingpTBins = getBinning(binning, "p_t_leading", nLeadingpTBins); - - // pT,lead binning 2 - Int_t nLeadingpTBins2 = -1; - BinList leadingpTBins2 = getBinning(binning, "p_t_leading_course", nLeadingpTBins2); - - // phi,lead - Int_t nLeadingPhiBins = -1; - BinList leadingPhiBins = getBinning(binning, "delta_phi", nLeadingPhiBins); - - trackBins[3] = getBinning(binning, "multiplicity", iTrackBin[3]); - trackAxisTitle[3] = "multiplicity"; - - // particle species - const Int_t kNSpeciesBins = 4; // pi, K, p, rest - BinList speciesBins = {-0.5, 0.5, 1.5, 2.5, 3.5}; - - // vtx-z axis - const char* vertexTitle = "z-vtx (cm)"; - Int_t nVertexBins = -1; - BinList vertexBins = getBinning(binning, "vertex", nVertexBins); - Int_t nVertexBinsEff = -1; - BinList vertexBinsEff = getBinning(binning, "vertex_eff", nVertexBinsEff); - - Int_t useVtxAxis = 0; - Int_t useAliTHn = 1; // 0 = don't use | 1 = with float | 2 = with double - - if (TString(reqHist).Contains("Sparse")) { - useAliTHn = 0; - } - if (TString(reqHist).Contains("Double")) { - useAliTHn = 2; - } - - // selection depending on requested histogram - Int_t axis = -1; // 0 = pT,lead, 1 = phi,lead - if (strcmp(reqHist, "NumberDensitypT") == 0) { - axis = 0; - title = "d^{2}N_{ch}/d#varphid#eta"; - } else if (strcmp(reqHist, "NumberDensityPhi") == 0) { - axis = 1; - title = "d^{2}N_{ch}/d#varphid#eta"; - } else if (TString(reqHist).BeginsWith("NumberDensityPhiCentrality")) { - if (TString(reqHist).Contains("Vtx")) { - useVtxAxis = 1; - } - - reqHist = "NumberDensityPhiCentrality"; - mHistogramType = reqHist; - axis = 2; - title = "d^{2}N_{ch}/d#varphid#eta"; - } else if (strcmp(reqHist, "SumpT") == 0) { - axis = 0; - title = "d^{2}#Sigma p_{T}/d#varphid#eta"; - } else if (TString(reqHist).BeginsWith("TwoPlusOne")) { - useVtxAxis = 1; - - reqHist = "TwoPlusOne"; - mHistogramType = reqHist; - axis = 3; - title = "d^{2}N_{ch}/d#varphid#eta"; - } else { - LOGF(fatal, "Invalid histogram requested: %s", reqHist); - } - - UInt_t nSteps = fgkCFSteps; - - if (axis == 0) { - trackBins[2] = leadingpTBins; - iTrackBin[2] = nLeadingpTBins; - trackAxisTitle[2] = "leading p_{T} (GeV/c)"; - - } else if (axis == 1) { - nTrackVars = 5; - - iTrackBin[2] = nLeadingpTBins2; - trackBins[2] = leadingpTBins2; - trackAxisTitle[2] = "leading p_{T} (GeV/c)"; - - iTrackBin[4] = nLeadingPhiBins; - trackBins[4] = leadingPhiBins; - trackAxisTitle[4] = "#Delta #varphi w.r.t. leading track"; - } else if (axis == 2) { - nTrackVars = 5; - - iTrackBin[0] = nDeltaEtaBins; - trackBins[0] = deltaEtaBins; - trackAxisTitle[0] = "#Delta#eta"; - - iTrackBin[2] = nLeadingpTBins2; - trackBins[2] = leadingpTBins2; - trackAxisTitle[2] = "leading p_{T} (GeV/c)"; - - trackAxisTitle[3] = "centrality"; - - iTrackBin[4] = nLeadingPhiBins; - trackBins[4] = leadingPhiBins; - trackAxisTitle[4] = "#Delta#varphi (rad)"; - - if (useVtxAxis > 0) { - nTrackVars = 6; - iTrackBin[5] = nVertexBins; - trackBins[5] = vertexBins; - trackAxisTitle[5] = vertexTitle; - } - } else if (axis == 3) { - nTrackVars = 7; - nSteps = 15; - - iTrackBin[0] = nDeltaEtaBins; - trackBins[0] = deltaEtaBins; - trackAxisTitle[0] = "#Delta#eta"; - - iTrackBin[2] = nLeadingpTBins; - trackBins[2] = leadingpTBins; - trackAxisTitle[2] = "Trigger 1 p_{T} (GeV/c)"; - - trackAxisTitle[3] = "centrality"; - - iTrackBin[4] = nLeadingPhiBins; - trackBins[4] = leadingPhiBins; - trackAxisTitle[4] = "#Delta#varphi (rad)"; - - iTrackBin[5] = nVertexBins; - trackBins[5] = vertexBins; - trackAxisTitle[5] = vertexTitle; - - iTrackBin[6] = nLeadingpTBins2; - trackBins[6] = leadingpTBins2; - trackAxisTitle[6] = "Trigger 2 p_{T} (GeV/c)"; - } - - if (axis >= 2 && useAliTHn == 1) { - mPairHist = new StepTHnF("mPairHist", title, nSteps, nTrackVars, iTrackBin, trackBins, trackAxisTitle); - } else if (axis >= 2 && useAliTHn == 2) { - mPairHist = new StepTHnD("mPairHist", title, nSteps, nTrackVars, iTrackBin, trackBins, trackAxisTitle); - } - - // event level - Int_t nEventVars = 2; - Int_t iEventBin[4] = {0}; - BinList eventBins[4]; - const char* eventAxisTitle[4] = {nullptr}; - - // track 3rd and 4th axis --> event 1st and 2nd axis - iEventBin[0] = iTrackBin[2]; - eventBins[0] = trackBins[2]; - eventAxisTitle[0] = trackAxisTitle[2]; - - iEventBin[1] = iTrackBin[3]; - eventBins[1] = trackBins[3]; - eventAxisTitle[1] = trackAxisTitle[3]; - - // plus track 5th axis (in certain cases) - if (axis >= 2 && useVtxAxis) { - nEventVars = 3; - iEventBin[2] = iTrackBin[5]; - eventBins[2] = trackBins[5]; - eventAxisTitle[2] = trackAxisTitle[5]; - } - if (axis >= 3) { - nEventVars = 4; - iEventBin[3] = iTrackBin[6]; - eventBins[3] = trackBins[6]; - eventAxisTitle[3] = trackAxisTitle[6]; - } - mTriggerHist = new StepTHnF("mTriggerHist", title, nSteps, nEventVars, iEventBin, eventBins, eventAxisTitle); - - // Efficiency histogram - - iTrackBin[0] = nEtaBins; - trackBins[0] = etaBins; - trackAxisTitle[0] = etaTitle; - - iTrackBin[1] = npTBinsFine; - trackBins[1] = pTBinsFine; - //trackAxisTitle[1] = trackAxisTitle[1]; + LOGF(info, "Creating CorrelationContainer"); - iTrackBin[2] = kNSpeciesBins; - trackBins[2] = speciesBins; - trackAxisTitle[2] = "particle species"; - - iTrackBin[4] = nVertexBinsEff; - trackBins[4] = vertexBinsEff; - trackAxisTitle[4] = vertexTitle; - - mTrackHistEfficiency = new StepTHnD("mTrackHistEfficiency", "Tracking efficiency", 6, 5, iTrackBin, trackBins, trackAxisTitle); - - mEventCount = new TH2F("mEventCount", ";step;centrality;count", fgkCFSteps + 2, -2.5, -0.5 + fgkCFSteps, iEventBin[1], &(eventBins[1])[0]); -} - -TString CorrelationContainer::combineBinning(TString defaultBinning, TString customBinning) -{ - // combine default binning with custom binning - // replaces binnings in default binning if it is defined in custom binning - - TString binningStr; - - TObjArray* lines = defaultBinning.Tokenize("\n"); - for (Int_t i = 0; i < lines->GetEntriesFast(); i++) { - TString line(lines->At(i)->GetName()); - TString tag = line(0, line.Index(":") + 1); - if (!customBinning.BeginsWith(tag) && !customBinning.Contains(TString("\n") + tag)) { - binningStr += line + "\n"; - } else { - LOGF(info, "Using custom binning for %s", tag.Data()); - } - } - delete lines; - binningStr += customBinning; - - return binningStr; -} - -std::vector CorrelationContainer::getBinning(const char* configuration, const char* tag, Int_t& nBins) -{ - // takes the binning from identified by - // configuration syntax example: - // equidistant binning: - // eta: 48 | -2.4, 2.4 - // variable-width binning: - // eta: -2.4, -2.3, -2.2, -2.1, -2.0, -1.9, -1.8, -1.7, -1.6, -1.5, -1.4, -1.3, -1.2, -1.1, -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4 - // - // returns bin edges which have to be deleted by the caller - - std::vector bins; - TString config(configuration); - TObjArray* lines = config.Tokenize("\n"); - for (Int_t i = 0; i < lines->GetEntriesFast(); i++) { - TString line(lines->At(i)->GetName()); - if (line.BeginsWith(TString(tag) + ":")) { - line.Remove(0, strlen(tag) + 1); - line.ReplaceAll(" ", ""); - if (line.Contains("|")) { - // equidistant binning - nBins = TString(line(0, line.Index("|"))).Atoi(); - line.Remove(0, line.Index("|") + 1); - } else { - // variable-width binning - nBins = line.CountChar(','); - } - TObjArray* binning = line.Tokenize(","); - //Double_t* bins = new Double_t[binning->GetEntriesFast()]; - for (Int_t j = 0; j < binning->GetEntriesFast(); j++) { - bins.push_back(TString(binning->At(j)->GetName()).Atof()); - } - delete binning; - delete lines; - return bins; - } - } - - delete lines; - LOGF(fatal, "Tag %s not found in %s", tag, configuration); - return bins; + // TODO Remove Clone() pending change in HistogramRegistry + mPairHist = (StepTHnF*)HistFactory::createHist({"mPairHist", "d^{2}N_{ch}/d#varphid#eta", {HistType::kStepTHnF, {axisList[0], axisList[1], axisList[2], axisList[3], axisList[4], axisList[5]}, fgkCFSteps}})->Clone(); + mTriggerHist = (StepTHnF*)HistFactory::createHist({"mTriggerHist", "d^{2}N_{ch}/d#varphid#eta", {HistType::kStepTHnF, {axisList[2], axisList[3], axisList[5]}, fgkCFSteps}})->Clone(); + mTrackHistEfficiency = (StepTHnD*)HistFactory::createHist({"mTrackHistEfficiency", "Tracking efficiency", {HistType::kStepTHnD, {axisList[6], axisList[7], {4, -0.5, 3.5, "species"}, axisList[3], axisList[8]}, fgkCFSteps}})->Clone(); + mEventCount = (TH2F*)(HistFactory::createHist({"mEventCount", ";step;centrality;count", {HistType::kTH2F, {{fgkCFSteps + 2, -2.5, -0.5 + fgkCFSteps, "step"}, axisList[3]}}})->Clone()); } //_____________________________________________________________________________ @@ -401,8 +122,7 @@ CorrelationContainer::CorrelationContainer(const CorrelationContainer& c) : TNam mSkipScaleMixedEvent(kFALSE), mCache(nullptr), mGetMultCacheOn(kFALSE), - mGetMultCache(nullptr), - mHistogramType() + mGetMultCache(nullptr) { // // CorrelationContainer copy constructor @@ -431,6 +151,11 @@ CorrelationContainer::~CorrelationContainer() mTrackHistEfficiency = nullptr; } + if (mEventCount) { + delete mEventCount; + mEventCount = nullptr; + } + if (mCache) { delete mCache; mCache = nullptr; @@ -482,7 +207,6 @@ void CorrelationContainer::Copy(TObject& c) const target.mTrackEtaCut = mTrackEtaCut; target.mWeightPerEvent = mWeightPerEvent; target.mSkipScaleMixedEvent = mSkipScaleMixedEvent; - target.mHistogramType = mHistogramType; } //____________________________________________________________________ diff --git a/Analysis/Tasks/PWGCF/correlations.cxx b/Analysis/Tasks/PWGCF/correlations.cxx index d83454a2c3962..722c0e541dc16 100644 --- a/Analysis/Tasks/PWGCF/correlations.cxx +++ b/Analysis/Tasks/PWGCF/correlations.cxx @@ -56,6 +56,17 @@ struct CorrelationTask { O2_DEFINE_CONFIGURABLE(cfgEfficiencyTrigger, std::string, "", "CCDB path to efficiency object for trigger particles") O2_DEFINE_CONFIGURABLE(cfgEfficiencyAssociated, std::string, "", "CCDB path to efficiency object for associated particles") + ConfigurableAxis axisVertex{"axisVertex", {7, -7, 7}, "vertex axis for histograms"}; + ConfigurableAxis axisDeltaPhi{"axisDeltaPhi", {72, -M_PI / 2, M_PI / 2 * 3}, "delta phi axis for histograms"}; + ConfigurableAxis axisDeltaEta{"axisDeltaEta", {40, -2, 2}, "delta eta axis for histograms"}; + ConfigurableAxis axisPtTrigger{"axisPtTrigger", {VARIABLE_WIDTH, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 10.0}, "pt trigger axis for histograms"}; + ConfigurableAxis axisPtAssoc{"axisPtAssoc", {VARIABLE_WIDTH, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0}, "pt associated axis for histograms"}; + ConfigurableAxis axisMultiplicity{"axisMultiplicity", {VARIABLE_WIDTH, 0, 5, 10, 20, 30, 40, 50, 100.1}, "multiplicity / centrality axis for histograms"}; + + ConfigurableAxis axisVertexEfficiency{"axisVertexEfficiency", {10, -10, 10}, "vertex axis for efficiency histograms"}; + ConfigurableAxis axisEtaEfficiency{"axisEtaEfficiency", {20, -1.0, 1.0}, "eta axis for efficiency histograms"}; + ConfigurableAxis axisPtEfficiency{"axisPtEfficiency", {VARIABLE_WIDTH, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75, 4.0, 4.5, 5.0, 6.0, 7.0, 8.0}, "pt axis for efficiency histograms"}; + // Filters and input definitions Filter collisionFilter = nabs(aod::collision::posZ) < cfgCutVertex; // TODO bitwise operations not supported, yet @@ -73,30 +84,15 @@ struct CorrelationTask { THn* mEfficiencyAssociated = nullptr; } cfg; - HistogramRegistry registry{"registry", { - {"yields", "centrality vs pT vs eta", {HistType::kTH3F, {{100, 0, 100, "centrality"}, {40, 0, 20, "p_{T}"}, {100, -2, 2, "#eta"}}}}, // - {"etaphi", "centrality vs eta vs phi", {HistType::kTH3F, {{100, 0, 100, "centrality"}, {100, -2, 2, "#eta"}, {200, 0, 2 * M_PI, "#varphi"}}}} // - }}; - + HistogramRegistry registry{"registry"}; PairCuts mPairCuts; Service ccdb; void init(o2::framework::InitContext&) { - // --- CONFIGURATION --- - const char* binning = - "vertex: 7 | -7, 7\n" - "delta_phi: 72 | -1.570796, 4.712389\n" - "delta_eta: 40 | -2.0, 2.0\n" - "p_t_assoc: 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0\n" - "p_t_trigger: 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 10.0\n" - "multiplicity: 0, 5, 10, 20, 30, 40, 50, 100.1\n" - "eta: 20 | -1.0, 1.0\n" - "p_t_leading: 100 | 0.0, 50.0\n" - "p_t_leading_course: 0.5, 1.0, 2.0, 3.0, 4.0, 6.0, 8.0\n" - "p_t_eff: 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75, 4.0, 4.5, 5.0, 6.0, 7.0, 8.0\n" - "vertex_eff: 10 | -10, 10\n"; + registry.add("yields", "centrality vs pT vs eta", {HistType::kTH3F, {{100, 0, 100, "centrality"}, {40, 0, 20, "p_{T}"}, {100, -2, 2, "#eta"}}}); + registry.add("etaphi", "centrality vs eta vs phi", {HistType::kTH3F, {{100, 0, 100, "centrality"}, {100, -2, 2, "#eta"}, {200, 0, 2 * M_PI, "#varphi"}}}); mPairCuts.SetHistogramRegistry(®istry); @@ -114,8 +110,18 @@ struct CorrelationTask { } // --- OBJECT INIT --- - same.setObject(new CorrelationContainer("sameEvent", "sameEvent", "NumberDensityPhiCentralityVtx", binning)); - mixed.setObject(new CorrelationContainer("mixedEvent", "mixedEvent", "NumberDensityPhiCentralityVtx", binning)); + + std::vector axisList = {{axisDeltaEta, "#Delta#eta"}, + {axisPtAssoc, "p_{T} (GeV/c)"}, + {axisPtTrigger, "p_{T} (GeV/c)"}, + {axisMultiplicity, "multiplicity / centrality"}, + {axisDeltaPhi, "#Delta#varphi (rad)"}, + {axisVertex, "z-vtx (cm)"}, + {axisEtaEfficiency, "#eta"}, + {axisPtEfficiency, "p_{T} (GeV/c)"}, + {axisVertexEfficiency, "z-vtx (cm)"}}; + same.setObject(new CorrelationContainer("sameEvent", "sameEvent", axisList)); + mixed.setObject(new CorrelationContainer("mixedEvent", "mixedEvent", axisList)); // o2-ccdb-upload -p Users/jgrosseo/correlations/LHC15o -f /tmp/correction_2011_global.root -k correction diff --git a/Analysis/Tasks/PWGCF/correlationsFiltered.cxx b/Analysis/Tasks/PWGCF/correlationsFiltered.cxx index 883ec9fe00ce8..e84b818d138d3 100644 --- a/Analysis/Tasks/PWGCF/correlationsFiltered.cxx +++ b/Analysis/Tasks/PWGCF/correlationsFiltered.cxx @@ -57,6 +57,17 @@ struct CorrelationTask { O2_DEFINE_CONFIGURABLE(cfgEfficiencyTrigger, std::string, "", "CCDB path to efficiency object for trigger particles") O2_DEFINE_CONFIGURABLE(cfgEfficiencyAssociated, std::string, "", "CCDB path to efficiency object for associated particles") + ConfigurableAxis axisVertex{"axisVertex", {7, -7, 7}, "vertex axis for histograms"}; + ConfigurableAxis axisDeltaPhi{"axisDeltaPhi", {72, -M_PI / 2, M_PI / 2 * 3}, "delta phi axis for histograms"}; + ConfigurableAxis axisDeltaEta{"axisDeltaEta", {40, -2, 2}, "delta eta axis for histograms"}; + ConfigurableAxis axisPtTrigger{"axisPtTrigger", {VARIABLE_WIDTH, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 10.0}, "pt trigger axis for histograms"}; + ConfigurableAxis axisPtAssoc{"axisPtAssoc", {VARIABLE_WIDTH, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0}, "pt associated axis for histograms"}; + ConfigurableAxis axisMultiplicity{"axisMultiplicity", {VARIABLE_WIDTH, 0, 5, 10, 20, 30, 40, 50, 100.1}, "multiplicity / centrality axis for histograms"}; + + ConfigurableAxis axisVertexEfficiency{"axisVertexEfficiency", {10, -10, 10}, "vertex axis for efficiency histograms"}; + ConfigurableAxis axisEtaEfficiency{"axisEtaEfficiency", {20, -1.0, 1.0}, "eta axis for efficiency histograms"}; + ConfigurableAxis axisPtEfficiency{"axisPtEfficiency", {VARIABLE_WIDTH, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75, 4.0, 4.5, 5.0, 6.0, 7.0, 8.0}, "pt axis for efficiency histograms"}; + // Filters and input definitions Filter collisionFilter = nabs(aod::collision::posZ) < cfgCutVertex; Filter trackFilter = (nabs(aod::cftrack::eta) < cfgCutEta) && (aod::cftrack::pt > cfgCutPt); @@ -83,19 +94,6 @@ struct CorrelationTask { void init(o2::framework::InitContext&) { // --- CONFIGURATION --- - const char* binning = - "vertex: 7 | -7, 7\n" - "delta_phi: 72 | -1.570796, 4.712389\n" - "delta_eta: 40 | -2.0, 2.0\n" - "p_t_assoc: 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0\n" - "p_t_trigger: 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 10.0\n" - "multiplicity: 0, 5, 10, 20, 30, 40, 50, 100.1\n" - "eta: 20 | -1.0, 1.0\n" - "p_t_leading: 100 | 0.0, 50.0\n" - "p_t_leading_course: 0.5, 1.0, 2.0, 3.0, 4.0, 6.0, 8.0\n" - "p_t_eff: 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75, 4.0, 4.5, 5.0, 6.0, 7.0, 8.0\n" - "vertex_eff: 10 | -10, 10\n"; - mPairCuts.SetHistogramRegistry(®istry); if (cfgPairCutPhoton > 0 || cfgPairCutK0 > 0 || cfgPairCutLambda > 0 || cfgPairCutPhi > 0 || cfgPairCutRho > 0) { @@ -112,8 +110,17 @@ struct CorrelationTask { } // --- OBJECT INIT --- - same.setObject(new CorrelationContainer("sameEvent", "sameEvent", "NumberDensityPhiCentralityVtx", binning)); - mixed.setObject(new CorrelationContainer("mixedEvent", "mixedEvent", "NumberDensityPhiCentralityVtx", binning)); + std::vector axisList = {{axisDeltaEta, "#Delta#eta"}, + {axisPtAssoc, "p_{T} (GeV/c)"}, + {axisPtTrigger, "p_{T} (GeV/c)"}, + {axisMultiplicity, "multiplicity / centrality"}, + {axisDeltaPhi, "#Delta#varphi (rad)"}, + {axisVertex, "z-vtx (cm)"}, + {axisEtaEfficiency, "#eta"}, + {axisPtEfficiency, "p_{T} (GeV/c)"}, + {axisVertexEfficiency, "z-vtx (cm)"}}; + same.setObject(new CorrelationContainer("sameEvent", "sameEvent", axisList)); + mixed.setObject(new CorrelationContainer("mixedEvent", "mixedEvent", axisList)); // o2-ccdb-upload -p Users/jgrosseo/correlations/LHC15o -f /tmp/correction_2011_global.root -k correction diff --git a/Analysis/Tasks/PWGCF/correlationsMixed.cxx b/Analysis/Tasks/PWGCF/correlationsMixed.cxx index 130d78ec21337..bfc6a6695dd13 100644 --- a/Analysis/Tasks/PWGCF/correlationsMixed.cxx +++ b/Analysis/Tasks/PWGCF/correlationsMixed.cxx @@ -105,6 +105,17 @@ struct CorrelationTaskMixed { O2_DEFINE_CONFIGURABLE(cfgPairCutPhi, float, -1, "Pair cut on Phi: -1 = off; >0 otherwise distance value") O2_DEFINE_CONFIGURABLE(cfgPairCutRho, float, -1, "Pair cut on Rho: -1 = off; >0 otherwise distance value") + ConfigurableAxis axisVertex{"axisVertex", {7, -7, 7}, "vertex axis for histograms"}; + ConfigurableAxis axisDeltaPhi{"axisDeltaPhi", {72, -M_PI / 2, M_PI / 2 * 3}, "delta phi axis for histograms"}; + ConfigurableAxis axisDeltaEta{"axisDeltaEta", {40, -2, 2}, "delta eta axis for histograms"}; + ConfigurableAxis axisPtTrigger{"axisPtTrigger", {VARIABLE_WIDTH, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 10.0}, "pt trigger axis for histograms"}; + ConfigurableAxis axisPtAssoc{"axisPtAssoc", {VARIABLE_WIDTH, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0}, "pt associated axis for histograms"}; + ConfigurableAxis axisMultiplicity{"axisMultiplicity", {VARIABLE_WIDTH, 0, 5, 10, 20, 30, 40, 50, 100.1}, "multiplicity / centrality axis for histograms"}; + + ConfigurableAxis axisVertexEfficiency{"axisVertexEfficiency", {10, -10, 10}, "vertex axis for efficiency histograms"}; + ConfigurableAxis axisEtaEfficiency{"axisEtaEfficiency", {20, -1.0, 1.0}, "eta axis for efficiency histograms"}; + ConfigurableAxis axisPtEfficiency{"axisPtEfficiency", {VARIABLE_WIDTH, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75, 4.0, 4.5, 5.0, 6.0, 7.0, 8.0}, "pt axis for efficiency histograms"}; + enum PairCuts { Photon = 0, K0, Lambda, @@ -124,27 +135,22 @@ struct CorrelationTaskMixed { void init(o2::framework::InitContext&) { // --- CONFIGURATION --- - const char* binning = - "vertex: -7, -5, -3, -1, 1, 3, 5, 7\n" - "delta_phi: -1.570796, -1.483530, -1.396263, -1.308997, -1.221730, -1.134464, -1.047198, -0.959931, -0.872665, -0.785398, -0.698132, -0.610865, -0.523599, -0.436332, -0.349066, -0.261799, -0.174533, -0.087266, 0.0, 0.087266, 0.174533, 0.261799, 0.349066, 0.436332, 0.523599, 0.610865, 0.698132, 0.785398, 0.872665, 0.959931, 1.047198, 1.134464, 1.221730, 1.308997, 1.396263, 1.483530, 1.570796, 1.658063, 1.745329, 1.832596, 1.919862, 2.007129, 2.094395, 2.181662, 2.268928, 2.356194, 2.443461, 2.530727, 2.617994, 2.705260, 2.792527, 2.879793, 2.967060, 3.054326, 3.141593, 3.228859, 3.316126, 3.403392, 3.490659, 3.577925, 3.665191, 3.752458, 3.839724, 3.926991, 4.014257, 4.101524, 4.188790, 4.276057, 4.363323, 4.450590, 4.537856, 4.625123, 4.712389\n" - "delta_eta: -2.0, -1.9, -1.8, -1.7, -1.6, -1.5, -1.4, -1.3, -1.2, -1.1, -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0\n" - "p_t_assoc: 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0\n" - "p_t_trigger: 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 10.0\n" - "multiplicity: 0, 5, 10, 20, 30, 40, 50, 100.1\n" - "eta: -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0\n" - "p_t_leading: 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0, 10.5, 11.0, 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 14.5, 15.0, 15.5, 16.0, 16.5, 17.0, 17.5, 18.0, 18.5, 19.0, 19.5, 20.0, 20.5, 21.0, 21.5, 22.0, 22.5, 23.0, 23.5, 24.0, 24.5, 25.0, 25.5, 26.0, 26.5, 27.0, 27.5, 28.0, 28.5, 29.0, 29.5, 30.0, 30.5, 31.0, 31.5, 32.0, 32.5, 33.0, 33.5, 34.0, 34.5, 35.0, 35.5, 36.0, 36.5, 37.0, 37.5, 38.0, 38.5, 39.0, 39.5, 40.0, 40.5, 41.0, 41.5, 42.0, 42.5, 43.0, 43.5, 44.0, 44.5, 45.0, 45.5, 46.0, 46.5, 47.0, 47.5, 48.0, 48.5, 49.0, 49.5, 50.0\n" - "p_t_leading_course: 0.5, 1.0, 2.0, 3.0, 4.0, 6.0, 8.0\n" - "p_t_eff: 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75, 4.0, 4.5, 5.0, 6.0, 7.0, 8.0\n" - "vertex_eff: -10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10\n"; - if (cfgPairCutPhoton > 0 || cfgPairCutK0 > 0 || cfgPairCutLambda > 0 || cfgPairCutPhi > 0 || cfgPairCutRho > 0) { cfg.mPairCuts = true; } // --- OBJECT INIT --- - same.setObject(new CorrelationContainer("sameEvent", "sameEvent", "NumberDensityPhiCentrality", binning)); - mixed.setObject(new CorrelationContainer("mixedEvent", "mixedEvent", "NumberDensityPhiCentrality", binning)); - //qaOutput.setObject(new TDirectory("qa", "qa")); + std::vector axisList = {{axisDeltaEta, "#Delta#eta"}, + {axisPtAssoc, "p_{T} (GeV/c)"}, + {axisPtTrigger, "p_{T} (GeV/c)"}, + {axisMultiplicity, "multiplicity / centrality"}, + {axisDeltaPhi, "#Delta#varphi (rad)"}, + {axisVertex, "z-vtx (cm)"}, + {axisEtaEfficiency, "#eta"}, + {axisPtEfficiency, "p_{T} (GeV/c)"}, + {axisVertexEfficiency, "z-vtx (cm)"}}; + same.setObject(new CorrelationContainer("sameEvent", "sameEvent", axisList)); + mixed.setObject(new CorrelationContainer("mixedEvent", "mixedEvent", axisList)); if (cfgTwoTrackCut > 0) { qa.mTwoTrackDistancePt[0] = new TH3F("TwoTrackDistancePt[0]", ";#Delta#eta;#Delta#varphi^{*}_{min};#Delta p_{T}", 100, -0.15, 0.15, 100, -0.05, 0.05, 20, 0, 10); diff --git a/Framework/Core/include/Framework/HistogramRegistry.h b/Framework/Core/include/Framework/HistogramRegistry.h index 1838558c43036..b7ec8f4d189f8 100644 --- a/Framework/Core/include/Framework/HistogramRegistry.h +++ b/Framework/Core/include/Framework/HistogramRegistry.h @@ -11,6 +11,7 @@ #ifndef FRAMEWORK_HISTOGRAMREGISTRY_H_ #define FRAMEWORK_HISTOGRAMREGISTRY_H_ +#include "Framework/HistogramSpec.h" #include "Framework/ASoA.h" #include "Framework/FunctionalHelpers.h" #include "Framework/Logger.h" @@ -18,197 +19,13 @@ #include "Framework/OutputObjHeader.h" #include "Framework/OutputSpec.h" #include "Framework/SerializationMethods.h" -#include "Framework/StringHelpers.h" #include "Framework/TableBuilder.h" #include "Framework/RuntimeError.h" -#include "Framework/StepTHn.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include #define HIST(name) CONST_STR(name) namespace o2::framework { -// Available root histogram types -enum HistType : unsigned int { - kUndefinedHist = 0, - kTH1D, - kTH1F, - kTH1I, - kTH1C, - kTH1S, - kTH2D, - kTH2F, - kTH2I, - kTH2C, - kTH2S, - kTH3D, - kTH3F, - kTH3I, - kTH3C, - kTH3S, - kTHnD, - kTHnF, - kTHnI, - kTHnC, - kTHnS, - kTHnL, - kTHnSparseD, - kTHnSparseF, - kTHnSparseI, - kTHnSparseC, - kTHnSparseS, - kTHnSparseL, - kTProfile, - kTProfile2D, - kTProfile3D, - kStepTHnF, - kStepTHnD -}; - -// variant of all possible root pointers; here we use only the interface types since the underlying data representation (int,float,double,long,char) is irrelevant -using HistPtr = std::variant, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr>; - -//************************************************************************************************** -/** - * Specification of an Axis. - */ -//************************************************************************************************** -// Flag to mark variable bin size in configurable bin edges -constexpr int VARIABLE_WIDTH = 0; - -struct AxisSpec { - AxisSpec(std::vector binEdges_, std::optional title_ = std::nullopt, std::optional name_ = std::nullopt) - : nBins(std::nullopt), - binEdges(binEdges_), - title(title_), - name(name_) - { - } - - AxisSpec(int nBins_, double binMin_, double binMax_, std::optional title_ = std::nullopt, std::optional name_ = std::nullopt) - : nBins(nBins_), - binEdges({binMin_, binMax_}), - title(title_), - name(name_) - { - } - - // first entry is assumed to be the number of bins; in case of variable size binning it must be set to zero - AxisSpec(ConfigurableAxis binEdges_, std::optional title_ = std::nullopt, std::optional name_ = std::nullopt) - : nBins(std::nullopt), - binEdges(std::vector(binEdges_)), - title(title_), - name(name_) - { - if (binEdges.empty()) { - return; - } - if (binEdges[0] != VARIABLE_WIDTH) { - nBins = static_cast(binEdges[0]); - binEdges.resize(3); // nBins, lowerBound, upperBound, disregard whatever else is stored in vecotr - } - binEdges.erase(binEdges.begin()); // remove first entry that we assume to be number of bins - } - - std::optional nBins{}; - std::vector binEdges{}; - std::optional title{}; - std::optional name{}; // optional axis name for ndim histograms -}; - -//************************************************************************************************** -/** - * Specification of a histogram configuration. - */ -//************************************************************************************************** -struct HistogramConfigSpec { - HistogramConfigSpec(HistType type_, std::vector axes_, uint8_t nSteps_ = 1) - : type(type_), - axes(axes_), - nSteps(nSteps_) - { - } - HistogramConfigSpec() = default; - HistogramConfigSpec(HistogramConfigSpec const& other) = default; - HistogramConfigSpec(HistogramConfigSpec&& other) = default; - - void addAxis(const AxisSpec& axis) - { - axes.push_back(axis); - } - - void addAxis(int nBins_, double binMin_, double binMax_, std::optional title_ = std::nullopt, std::optional name_ = std::nullopt) - { - axes.push_back({nBins_, binMin_, binMax_, title_, name_}); - } - - void addAxis(std::vector binEdges_, std::optional title_ = std::nullopt, std::optional name_ = std::nullopt) - { - axes.push_back({binEdges_, title_, name_}); - } - - void addAxes(std::vector axes_) - { - axes.insert(axes.end(), axes_.begin(), axes_.end()); - } - - // add axes defined in other HistogramConfigSpec object - void addAxes(const HistogramConfigSpec& other) - { - axes.insert(axes.end(), other.axes.begin(), other.axes.end()); - } - - HistType type{HistType::kUndefinedHist}; - std::vector axes{}; - uint32_t nSteps{1}; // variable used only in StepTHn -}; - -//************************************************************************************************** -/** - * Specification of a histogram. - */ -//************************************************************************************************** -struct HistogramSpec { - HistogramSpec(char const* const name_, char const* const title_, HistogramConfigSpec config_, bool callSumw2_ = false) - : name(name_), - hash(compile_time_hash(name_)), - title(title_), - config(config_), - callSumw2(callSumw2_) - { - } - - HistogramSpec() - : name(""), - hash(0), - config() - { - } - HistogramSpec(HistogramSpec const& other) = default; - HistogramSpec(HistogramSpec&& other) = default; - - std::string name{}; - uint32_t hash{}; - std::string title{}; - HistogramConfigSpec config{}; - bool callSumw2{}; // wether or not hist needs heavy error structure produced by Sumw2() -}; - //************************************************************************************************** /** * Static helper class to generate histograms from the specifications. diff --git a/Framework/Core/include/Framework/HistogramSpec.h b/Framework/Core/include/Framework/HistogramSpec.h new file mode 100644 index 0000000000000..b391dc8b91802 --- /dev/null +++ b/Framework/Core/include/Framework/HistogramSpec.h @@ -0,0 +1,203 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef FRAMEWORK_HISTOGRAMSPEC_H_ +#define FRAMEWORK_HISTOGRAMSPEC_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "Framework/StepTHn.h" +#include "Framework/Configurable.h" +#include "Framework/StringHelpers.h" + +namespace o2::framework +{ +// Available root histogram types +enum HistType : unsigned int { + kUndefinedHist = 0, + kTH1D, + kTH1F, + kTH1I, + kTH1C, + kTH1S, + kTH2D, + kTH2F, + kTH2I, + kTH2C, + kTH2S, + kTH3D, + kTH3F, + kTH3I, + kTH3C, + kTH3S, + kTHnD, + kTHnF, + kTHnI, + kTHnC, + kTHnS, + kTHnL, + kTHnSparseD, + kTHnSparseF, + kTHnSparseI, + kTHnSparseC, + kTHnSparseS, + kTHnSparseL, + kTProfile, + kTProfile2D, + kTProfile3D, + kStepTHnF, + kStepTHnD +}; + +// variant of all possible root pointers; here we use only the interface types since the underlying data representation (int,float,double,long,char) is irrelevant +using HistPtr = std::variant, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr>; + +//************************************************************************************************** +/** + * Specification of an Axis. + */ +//************************************************************************************************** +// Flag to mark variable bin size in configurable bin edges +constexpr int VARIABLE_WIDTH = 0; + +struct AxisSpec { + AxisSpec(std::vector binEdges_, std::optional title_ = std::nullopt, std::optional name_ = std::nullopt) + : nBins(std::nullopt), + binEdges(binEdges_), + title(title_), + name(name_) + { + } + + AxisSpec(int nBins_, double binMin_, double binMax_, std::optional title_ = std::nullopt, std::optional name_ = std::nullopt) + : nBins(nBins_), + binEdges({binMin_, binMax_}), + title(title_), + name(name_) + { + } + + // first entry is assumed to be the number of bins; in case of variable size binning it must be set to zero + AxisSpec(ConfigurableAxis binEdges_, std::optional title_ = std::nullopt, std::optional name_ = std::nullopt) + : nBins(std::nullopt), + binEdges(std::vector(binEdges_)), + title(title_), + name(name_) + { + if (binEdges.empty()) { + return; + } + if (binEdges[0] != VARIABLE_WIDTH) { + nBins = static_cast(binEdges[0]); + binEdges.resize(3); // nBins, lowerBound, upperBound, disregard whatever else is stored in vecotr + } + binEdges.erase(binEdges.begin()); // remove first entry that we assume to be number of bins + } + + std::optional nBins{}; + std::vector binEdges{}; + std::optional title{}; + std::optional name{}; // optional axis name for ndim histograms +}; + +//************************************************************************************************** +/** + * Specification of a histogram configuration. + */ +//************************************************************************************************** +struct HistogramConfigSpec { + HistogramConfigSpec(HistType type_, std::vector axes_, uint8_t nSteps_ = 1) + : type(type_), + axes(axes_), + nSteps(nSteps_) + { + } + HistogramConfigSpec() = default; + HistogramConfigSpec(HistogramConfigSpec const& other) = default; + HistogramConfigSpec(HistogramConfigSpec&& other) = default; + + void addAxis(const AxisSpec& axis) + { + axes.push_back(axis); + } + + void addAxis(int nBins_, double binMin_, double binMax_, std::optional title_ = std::nullopt, std::optional name_ = std::nullopt) + { + axes.push_back({nBins_, binMin_, binMax_, title_, name_}); + } + + void addAxis(std::vector binEdges_, std::optional title_ = std::nullopt, std::optional name_ = std::nullopt) + { + axes.push_back({binEdges_, title_, name_}); + } + + void addAxes(std::vector axes_) + { + axes.insert(axes.end(), axes_.begin(), axes_.end()); + } + + // add axes defined in other HistogramConfigSpec object + void addAxes(const HistogramConfigSpec& other) + { + axes.insert(axes.end(), other.axes.begin(), other.axes.end()); + } + + HistType type{HistType::kUndefinedHist}; + std::vector axes{}; + uint32_t nSteps{1}; // variable used only in StepTHn +}; + +//************************************************************************************************** +/** + * Specification of a histogram. + */ +//************************************************************************************************** +struct HistogramSpec { + HistogramSpec(char const* const name_, char const* const title_, HistogramConfigSpec config_, bool callSumw2_ = false) + : name(name_), + hash(compile_time_hash(name_)), + title(title_), + config(config_), + callSumw2(callSumw2_) + { + } + + HistogramSpec() + : name(""), + hash(0), + config() + { + } + HistogramSpec(HistogramSpec const& other) = default; + HistogramSpec(HistogramSpec&& other) = default; + + std::string name{}; + uint32_t hash{}; + std::string title{}; + HistogramConfigSpec config{}; + bool callSumw2{}; // wether or not hist needs heavy error structure produced by Sumw2() +}; + +} // namespace o2::framework +#endif // FRAMEWORK_HISTOGRAMSPEC_H_ diff --git a/Framework/Core/include/Framework/StepTHn.h b/Framework/Core/include/Framework/StepTHn.h index 71f1288b06533..52da955c9866f 100644 --- a/Framework/Core/include/Framework/StepTHn.h +++ b/Framework/Core/include/Framework/StepTHn.h @@ -89,7 +89,7 @@ class StepTHnT : public StepTHn { public: StepTHnT() : StepTHn() {} - StepTHnT(const Char_t* name, const Char_t* title, const Int_t nSteps, const Int_t nAxes, Int_t* nBins, std::vector binLimits[], const char** axisTitles); + StepTHnT(const Char_t* name, const Char_t* title, const Int_t nSteps, const Int_t nAxes, Int_t* nBins, std::vector binEdges[], const char** axisTitles); StepTHnT(const char* name, const char* title, const int nSteps, const int nAxes, const int* nBins, const double* xmin, const double* xmax); ~StepTHnT() override = default; From 452897e0dc470204bc638eb0f422851ee768cf12 Mon Sep 17 00:00:00 2001 From: Piotr Konopka Date: Wed, 5 May 2021 15:46:37 +0200 Subject: [PATCH 395/770] AliECS dump: parametrize session id (#6071) --- Framework/Core/src/O2ControlHelpers.cxx | 3 ++- .../Core/test/test_FrameworkDataFlowToO2Control.cxx | 9 +++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/Framework/Core/src/O2ControlHelpers.cxx b/Framework/Core/src/O2ControlHelpers.cxx index 19709cd007449..6edbf28e76467 100644 --- a/Framework/Core/src/O2ControlHelpers.cxx +++ b/Framework/Core/src/O2ControlHelpers.cxx @@ -168,7 +168,7 @@ void dumpCommand(std::ostream& dumpOut, const DeviceExecution& execution, std::s dumpOut << indLevel << indScheme << "- \"--monitoring-backend\"\n"; dumpOut << indLevel << indScheme << "- \"'{{ monitoring_dpl_url }}'\"\n"; dumpOut << indLevel << indScheme << "- \"--session\"\n"; - dumpOut << indLevel << indScheme << "- \"'default'\"\n"; + dumpOut << indLevel << indScheme << "- \"'{{ session_id }}'\"\n"; dumpOut << indLevel << indScheme << "- \"--infologger-severity\"\n"; dumpOut << indLevel << indScheme << "- \"'{{ infologger_severity }}'\"\n"; dumpOut << indLevel << indScheme << "- \"--infologger-mode\"\n"; @@ -322,6 +322,7 @@ void dumpWorkflow(std::ostream& dumpOut, const std::vector& specs, c dumpOut << indLevel << indScheme << "fmq_rate_logging: 0\n"; dumpOut << indLevel << indScheme << "shm_segment_size: 10000000000\n"; dumpOut << indLevel << indScheme << "shm_throw_bad_alloc: false\n"; + dumpOut << indLevel << indScheme << "session_id: default\n"; dumpOut << indLevel << "roles:\n"; for (size_t di = 0; di < specs.size(); di++) { diff --git a/Framework/Core/test/test_FrameworkDataFlowToO2Control.cxx b/Framework/Core/test/test_FrameworkDataFlowToO2Control.cxx index fac2145b0bdcd..68e80a79d9e62 100644 --- a/Framework/Core/test/test_FrameworkDataFlowToO2Control.cxx +++ b/Framework/Core/test/test_FrameworkDataFlowToO2Control.cxx @@ -74,6 +74,7 @@ const auto expectedWorkflow = R"EXPECTED(name: testwf fmq_rate_logging: 0 shm_segment_size: 10000000000 shm_throw_bad_alloc: false + session_id: default roles: - name: "A" connect: @@ -145,7 +146,7 @@ const std::vector expectedTasks{ - "--monitoring-backend" - "'{{ monitoring_dpl_url }}'" - "--session" - - "'default'" + - "'{{ session_id }}'" - "--infologger-severity" - "'{{ infologger_severity }}'" - "--infologger-mode" @@ -203,7 +204,7 @@ const std::vector expectedTasks{ - "--monitoring-backend" - "'{{ monitoring_dpl_url }}'" - "--session" - - "'default'" + - "'{{ session_id }}'" - "--infologger-severity" - "'{{ infologger_severity }}'" - "--infologger-mode" @@ -261,7 +262,7 @@ const std::vector expectedTasks{ - "--monitoring-backend" - "'{{ monitoring_dpl_url }}'" - "--session" - - "'default'" + - "'{{ session_id }}'" - "--infologger-severity" - "'{{ infologger_severity }}'" - "--infologger-mode" @@ -314,7 +315,7 @@ const std::vector expectedTasks{ - "--monitoring-backend" - "'{{ monitoring_dpl_url }}'" - "--session" - - "'default'" + - "'{{ session_id }}'" - "--infologger-severity" - "'{{ infologger_severity }}'" - "--infologger-mode" From f44153159e87c76eee6793fefb484e01d3fc7142 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Wed, 5 May 2021 21:38:15 +0200 Subject: [PATCH 396/770] DPL: drop unneeded header. (#6068) --- Framework/AnalysisSupport/src/AODJAlienReaderHelpers.cxx | 1 - 1 file changed, 1 deletion(-) diff --git a/Framework/AnalysisSupport/src/AODJAlienReaderHelpers.cxx b/Framework/AnalysisSupport/src/AODJAlienReaderHelpers.cxx index 30b3c2770ea07..d56c126a4b1cd 100644 --- a/Framework/AnalysisSupport/src/AODJAlienReaderHelpers.cxx +++ b/Framework/AnalysisSupport/src/AODJAlienReaderHelpers.cxx @@ -25,7 +25,6 @@ #include "Framework/ChannelInfo.h" #include "Framework/Logger.h" -#include #if __has_include() #include #endif From b27e2757f14ae92bac73e0dc470882fcec475f03 Mon Sep 17 00:00:00 2001 From: jgrosseo Date: Thu, 6 May 2021 09:44:55 +0200 Subject: [PATCH 397/770] Merging same and mixed event correlation analysis (#6073) --- Analysis/Tasks/PWGCF/CMakeLists.txt | 5 - Analysis/Tasks/PWGCF/correlations.cxx | 232 ++++++++-- Analysis/Tasks/PWGCF/correlationsMixed.cxx | 512 --------------------- 3 files changed, 191 insertions(+), 558 deletions(-) delete mode 100644 Analysis/Tasks/PWGCF/correlationsMixed.cxx diff --git a/Analysis/Tasks/PWGCF/CMakeLists.txt b/Analysis/Tasks/PWGCF/CMakeLists.txt index e7eb33cb131ab..231412e64baa3 100644 --- a/Analysis/Tasks/PWGCF/CMakeLists.txt +++ b/Analysis/Tasks/PWGCF/CMakeLists.txt @@ -26,11 +26,6 @@ o2_add_dpl_workflow(correlations PUBLIC_LINK_LIBRARIES O2::Framework O2::AnalysisCore COMPONENT_NAME Analysis) -o2_add_dpl_workflow(correlations-mixed - SOURCES correlationsMixed.cxx - PUBLIC_LINK_LIBRARIES O2::Framework O2::AnalysisCore - COMPONENT_NAME Analysis) - o2_add_dpl_workflow(filter-cf SOURCES filterCF.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::AnalysisCore diff --git a/Analysis/Tasks/PWGCF/correlations.cxx b/Analysis/Tasks/PWGCF/correlations.cxx index 722c0e541dc16..1272c0f330506 100644 --- a/Analysis/Tasks/PWGCF/correlations.cxx +++ b/Analysis/Tasks/PWGCF/correlations.cxx @@ -14,6 +14,7 @@ #include #include "Framework/StepTHn.h" #include "Framework/HistogramRegistry.h" +#include "Framework/RunningWorkflowInfo.h" #include "AnalysisDataModel/EventSelection.h" #include "AnalysisDataModel/TrackSelectionTables.h" @@ -26,6 +27,17 @@ #include #include +namespace o2::aod +{ +namespace hash +{ +DECLARE_SOA_COLUMN(Bin, bin, int); +} // namespace hash +DECLARE_SOA_TABLE(Hashes, "AOD", "HASH", hash::Bin); + +using Hash = Hashes::iterator; +} // namespace o2::aod + using namespace o2; using namespace o2::framework; using namespace o2::framework::expressions; @@ -56,6 +68,8 @@ struct CorrelationTask { O2_DEFINE_CONFIGURABLE(cfgEfficiencyTrigger, std::string, "", "CCDB path to efficiency object for trigger particles") O2_DEFINE_CONFIGURABLE(cfgEfficiencyAssociated, std::string, "", "CCDB path to efficiency object for associated particles") + O2_DEFINE_CONFIGURABLE(cfgNoMixedEvents, int, 5, "Number of mixed events per event") + ConfigurableAxis axisVertex{"axisVertex", {7, -7, 7}, "vertex axis for histograms"}; ConfigurableAxis axisDeltaPhi{"axisDeltaPhi", {72, -M_PI / 2, M_PI / 2 * 3}, "delta phi axis for histograms"}; ConfigurableAxis axisDeltaEta{"axisDeltaEta", {40, -2, 2}, "delta eta axis for histograms"}; @@ -142,31 +156,13 @@ struct CorrelationTask { } } - // Version with explicit nested loop - void process(soa::Filtered>::iterator const& collision, aod::BCsWithTimestamps const&, myTracks const& tracks) + template + bool fillCollision(TTarget target, TCollision collision, float centrality) { - auto bc = collision.bc_as(); - if (cfgEfficiencyTrigger.value.empty() == false) { - cfg.mEfficiencyTrigger = ccdb->getForTimeStamp>(cfgEfficiencyTrigger, bc.timestamp()); - LOGF(info, "Loaded efficiency histogram for trigger particles from %s (%p)", cfgEfficiencyTrigger.value.c_str(), (void*)cfg.mEfficiencyTrigger); - } - if (cfgEfficiencyAssociated.value.empty() == false) { - cfg.mEfficiencyAssociated = ccdb->getForTimeStamp>(cfgEfficiencyAssociated, bc.timestamp()); - LOGF(info, "Loaded efficiency histogram for associated particles from %s (%p)", cfgEfficiencyAssociated.value.c_str(), (void*)cfg.mEfficiencyAssociated); - } - - LOGF(info, "Tracks for collision: %d | Vertex: %.1f | INT7: %d | V0M: %.1f", tracks.size(), collision.posZ(), collision.sel7(), collision.centV0M()); - - if (std::abs(collision.posZ()) > cfgCutVertex) { - LOGF(warning, "Unexpected: Vertex %f outside of cut %f", collision.posZ(), cfgCutVertex); - } - - const auto centrality = collision.centV0M(); - same->fillEvent(centrality, CorrelationContainer::kCFStepAll); if (!collision.alias()[kINT7] || !collision.sel7()) { - return; + return false; } same->fillEvent(centrality, CorrelationContainer::kCFStepTriggered); @@ -174,45 +170,44 @@ struct CorrelationTask { // vertex range already checked as filter, but bitwise operations not yet supported // TODO (collision.flags() != 0) can be removed with next conversion (AliPhysics >= 20210305) if ((collision.flags() != 0) && ((collision.flags() & aod::collision::CollisionFlagsRun2::Run2VertexerTracks) != aod::collision::CollisionFlagsRun2::Run2VertexerTracks)) { - return; + return false; } same->fillEvent(centrality, CorrelationContainer::kCFStepVertex); - same->fillEvent(centrality, CorrelationContainer::kCFStepReconstructed); - int bSign = 1; // TODO magnetic field from CCDB + return true; + } + template + void fillCorrelations(TTarget target, TTracks tracks1, TTracks tracks2, float centrality, float posZ, int bSign) + { // Cache efficiency for particles (too many FindBin lookups) float* efficiencyAssociated = nullptr; if (cfg.mEfficiencyAssociated) { - efficiencyAssociated = new float[tracks.size()]; + efficiencyAssociated = new float[tracks2.size()]; int i = 0; - for (auto& track1 : tracks) { - efficiencyAssociated[i++] = getEfficiency(cfg.mEfficiencyAssociated, track1.eta(), track1.pt(), centrality, collision.posZ()); + for (auto& track : tracks2) { + efficiencyAssociated[i++] = getEfficiency(cfg.mEfficiencyAssociated, track.eta(), track.pt(), centrality, posZ); } } - for (auto& track1 : tracks) { + for (auto& track1 : tracks1) { // LOGF(info, "Track %f | %f | %f %d %d", track1.eta(), track1.phi(), track1.pt(), track1.isGlobalTrack(), track1.isGlobalTrackSDD()); - registry.fill(HIST("yields"), centrality, track1.pt(), track1.eta()); - registry.fill(HIST("etaphi"), centrality, track1.eta(), track1.phi()); - if (cfgTriggerCharge != 0 && cfgTriggerCharge * track1.sign() < 0) { continue; } float triggerWeight = 1.0; if (cfg.mEfficiencyTrigger) { - triggerWeight = getEfficiency(cfg.mEfficiencyTrigger, track1.eta(), track1.pt(), centrality, collision.posZ()); + triggerWeight = getEfficiency(cfg.mEfficiencyTrigger, track1.eta(), track1.pt(), centrality, posZ); } - same->getTriggerHist()->Fill(CorrelationContainer::kCFStepReconstructed, track1.pt(), centrality, collision.posZ(), triggerWeight); - //mixed->getTriggerHist()->Fill(eventValues, CorrelationContainer::kCFStepReconstructed); + target->getTriggerHist()->Fill(CorrelationContainer::kCFStepReconstructed, track1.pt(), centrality, posZ, triggerWeight); int i = -1; - for (auto& track2 : tracks) { + for (auto& track2 : tracks2) { i++; // HACK if (track1 == track2) { continue; @@ -250,18 +245,97 @@ struct CorrelationTask { deltaPhi += M_PI * 2; } - same->getPairHist()->Fill(CorrelationContainer::kCFStepReconstructed, - track1.eta() - track2.eta(), track2.pt(), track1.pt(), centrality, deltaPhi, collision.posZ(), - triggerWeight * associatedWeight); - //mixed->getPairHist()->Fill(values, CorrelationContainer::kCFStepReconstructed); + target->getPairHist()->Fill(CorrelationContainer::kCFStepReconstructed, + track1.eta() - track2.eta(), track2.pt(), track1.pt(), centrality, deltaPhi, posZ, + triggerWeight * associatedWeight); } } delete[] efficiencyAssociated; } + // Version with explicit nested loop + void processSame(soa::Filtered>::iterator const& collision, aod::BCsWithTimestamps const&, myTracks const& tracks) + { + auto bc = collision.bc_as(); + if (cfgEfficiencyTrigger.value.empty() == false) { + cfg.mEfficiencyTrigger = ccdb->getForTimeStamp>(cfgEfficiencyTrigger, bc.timestamp()); + LOGF(info, "Loaded efficiency histogram for trigger particles from %s (%p)", cfgEfficiencyTrigger.value.c_str(), (void*)cfg.mEfficiencyTrigger); + } + if (cfgEfficiencyAssociated.value.empty() == false) { + cfg.mEfficiencyAssociated = ccdb->getForTimeStamp>(cfgEfficiencyAssociated, bc.timestamp()); + LOGF(info, "Loaded efficiency histogram for associated particles from %s (%p)", cfgEfficiencyAssociated.value.c_str(), (void*)cfg.mEfficiencyAssociated); + } + + LOGF(info, "Tracks for collision: %d | Vertex: %.1f | INT7: %d | V0M: %.1f", tracks.size(), collision.posZ(), collision.sel7(), collision.centV0M()); + + if (std::abs(collision.posZ()) > cfgCutVertex) { + LOGF(warning, "Unexpected: Vertex %f outside of cut %f", collision.posZ(), cfgCutVertex); + } + + int bSign = 1; // TODO magnetic field from CCDB + const auto centrality = collision.centV0M(); + + if (fillCollision(same, collision, centrality) == false) { + return; + } + + for (auto& track1 : tracks) { + registry.fill(HIST("yields"), centrality, track1.pt(), track1.eta()); + registry.fill(HIST("etaphi"), centrality, track1.eta(), track1.phi()); + } + + fillCorrelations(same, tracks, tracks, centrality, collision.posZ(), bSign); + } + + void processMixed(soa::Join& collisions, myTracks const& tracks) + { + // TODO loading of efficiency histogram missing here, because it will happen somehow in the CCDBConfigurable + + int bSign = 1; // TODO magnetic field from CCDB + + collisions.bindExternalIndices(&tracks); + auto tracksTuple = std::make_tuple(tracks); + AnalysisDataProcessorBuilder::GroupSlicer slicer(collisions, tracksTuple); + + // Strictly upper categorised collisions, for cfgNoMixedEvents combinations per bin, skipping those in entry -1 + for (auto& [collision1, collision2] : selfCombinations("fBin", cfgNoMixedEvents, -1, collisions, collisions)) { + + LOGF(info, "Mixed collisions bin: %d pair: %d (%f), %d (%f)", collision1.bin(), collision1.index(), collision1.posZ(), collision2.index(), collision2.posZ()); + + // TODO in principle these should be already checked on hash level, because in this way we don't check collision 2 + if (fillCollision(mixed, collision1, collision1.centV0M()) == false) { + continue; + } + + auto it1 = slicer.begin(); + auto it2 = slicer.begin(); + for (auto& slice : slicer) { + if (slice.groupingElement().index() == collision1.index()) { + it1 = slice; + break; + } + } + for (auto& slice : slicer) { + if (slice.groupingElement().index() == collision2.index()) { + it2 = slice; + break; + } + } + + auto tracks1 = std::get(it1.associatedTables()); + tracks1.bindExternalIndices(&collisions); + auto tracks2 = std::get(it2.associatedTables()); + tracks2.bindExternalIndices(&collisions); + + // LOGF(info, "Tracks: %d and %d entries", tracks1.size(), tracks2.size()); + + fillCorrelations(mixed, tracks1, tracks2, collision1.centV0M(), collision1.posZ(), bSign); + } + } + // Version with combinations - void process2(soa::Join::iterator const& collision, soa::Filtered const& tracks) + void processWithCombinations(soa::Join::iterator const& collision, soa::Filtered const& tracks) { LOGF(info, "Tracks for collision (Combination run): %d", tracks.size()); @@ -327,8 +401,84 @@ struct CorrelationTask { } }; +struct CorrelationHashTask { + // TODO sync configurables with main task + std::vector vtxBins{0.0f}; + std::vector multBins{0.0f}; + + Produces hashes; + + void fillArray(int length, double* source, std::vector& target) + { + // Expand binning from Configurable. Can we let some code in AxisSpec do this? + + target.clear(); + if (source[0] == VARIABLE_WIDTH) { + for (int i = 1; i < length; i++) { + target.push_back(source[i]); + } + } else { + for (int i = 0; i <= source[0]; i++) { + target.push_back(source[1] + (source[2] - source[1]) / source[0] * i); + } + } + } + + void init(o2::framework::InitContext& initContext) + { + // get axis config from CorrelationTask + auto& workflows = initContext.services().get(); + for (DeviceSpec device : workflows.devices) { + for (auto option : device.options) { + if (option.name == "axisVertex") { + fillArray(option.defaultValue.size(), option.defaultValue.get(), vtxBins); + LOGF(info, "Initialized vertex binning for mixing from configurable %s", option.name); + } + if (option.name == "axisMultiplicity") { + fillArray(option.defaultValue.size(), option.defaultValue.get(), multBins); + LOGF(info, "Initialized multiplicity binning for mixing from configurable %s", option.name); + } + } + } + } + + // Calculate hash for an element based on 2 properties and their bins. + int getHash(std::vector const& vtxBins, std::vector const& multBins, float vtx, float mult) + { + // underflow + if (vtx < vtxBins[0]) { + return -1; + } + if (mult < multBins[0]) { + return -1; + } + + for (int i = 1; i < vtxBins.size(); i++) { + if (vtx < vtxBins[i]) { + for (int j = 1; j < multBins.size(); j++) { + if (mult < multBins[j]) { + return i + j * (vtxBins.size() + 1); + } + } + } + } + // overflow + return -1; + } + + void process(soa::Join const& collisions) + { + for (auto& collision : collisions) { + int hash = getHash(vtxBins, multBins, collision.posZ(), collision.centV0M()); + LOGF(info, "Collision: %d (%f, %f) hash: %d", collision.index(), collision.posZ(), collision.centV0M(), hash); + hashes(hash); + } + } +}; + WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { return WorkflowSpec{ - adaptAnalysisTask(cfgc)}; + adaptAnalysisTask(cfgc), + adaptAnalysisTask(cfgc, Processes{&CorrelationTask::processSame, &CorrelationTask::processMixed})}; } diff --git a/Analysis/Tasks/PWGCF/correlationsMixed.cxx b/Analysis/Tasks/PWGCF/correlationsMixed.cxx deleted file mode 100644 index bfc6a6695dd13..0000000000000 --- a/Analysis/Tasks/PWGCF/correlationsMixed.cxx +++ /dev/null @@ -1,512 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. -#include "Framework/runDataProcessing.h" -#include "Framework/AnalysisTask.h" -#include "Framework/AnalysisDataModel.h" -#include "Framework/ASoAHelpers.h" -#include "Framework/StepTHn.h" - -#include "AnalysisDataModel/EventSelection.h" -#include "AnalysisDataModel/Centrality.h" -#include "AnalysisCore/CorrelationContainer.h" -#include "AnalysisDataModel/TrackSelectionTables.h" - -#include -#include -#include - -namespace o2::aod -{ -namespace hash -{ -DECLARE_SOA_COLUMN(Bin, bin, int); -} // namespace hash -DECLARE_SOA_TABLE(Hashes, "AOD", "HASH", hash::Bin); - -using Hash = Hashes::iterator; -} // namespace o2::aod - -using namespace o2; -using namespace o2::framework; -using namespace o2::framework::expressions; - -struct HashTask { - std::vector vtxBins{-7.0f, -5.0f, -3.0f, -1.0f, 1.0f, 3.0f, 5.0f, 7.0f}; - std::vector multBins{0.0f, 20.0f, 40.0f, 60.0f, 80.0f, 100.0f}; - Produces hashes; - - // Calculate hash for an element based on 2 properties and their bins. - int getHash(std::vector const& vtxBins, std::vector const& multBins, float vtx, float mult) - { - // underflow - if (vtx < vtxBins[0]) { - return -1; - } - if (mult < multBins[0]) { - return -1; - } - - for (int i = 1; i < vtxBins.size(); i++) { - if (vtx < vtxBins[i]) { - for (int j = 1; j < multBins.size(); j++) { - if (mult < multBins[j]) { - return i + j * (vtxBins.size() + 1); - } - } - } - } - // overflow - return -1; - } - - void process(soa::Join const& collisions) - { - for (auto& collision : collisions) { - int hash = getHash(vtxBins, multBins, collision.posZ(), collision.centV0M()); - LOGF(info, "Collision: %d (%f, %f) hash: %d", collision.index(), collision.posZ(), collision.centV0M(), hash); - hashes(hash); - } - } -}; - -#define O2_DEFINE_CONFIGURABLE(NAME, TYPE, DEFAULT, HELP) Configurable NAME{#NAME, DEFAULT, HELP}; - -struct CorrelationTaskMixed { - - // Input definitions - using myTracks = soa::Filtered; - - // Filters - Filter trackFilter = (aod::track::eta > -0.8f) && (aod::track::eta < 0.8f) && (aod::track::pt > 1.0f); - - // Output definitions - OutputObj same{"sameEvent"}; - OutputObj mixed{"mixedEvent"}; - //OutputObj qaOutput{"qa"}; - - // Configuration - O2_DEFINE_CONFIGURABLE(cfgTriggerCharge, int, 0, "Select on charge of trigger particle: 0 = all; 1 = positive; -1 = negative"); - O2_DEFINE_CONFIGURABLE(cfgAssociatedCharge, int, 0, "Select on charge of associated particle: 0 = all; 1 = positive; -1 = negative"); - O2_DEFINE_CONFIGURABLE(cfgPairCharge, int, 0, "Select on charge of particle pair: 0 = all; 1 = like sign; -1 = unlike sign"); - - O2_DEFINE_CONFIGURABLE(cfgTwoTrackCut, float, -1, "Two track cut: -1 = off; >0 otherwise distance value"); - O2_DEFINE_CONFIGURABLE(cfgTwoTrackCutMinRadius, float, 0.8f, "Two track cut: radius in m from which two track cuts are applied"); - - O2_DEFINE_CONFIGURABLE(cfgPairCutPhoton, float, -1, "Pair cut on photons: -1 = off; >0 otherwise distance value (suggested: 0.004)") - O2_DEFINE_CONFIGURABLE(cfgPairCutK0, float, -1, "Pair cut on K0s: -1 = off; >0 otherwise distance value (suggested: 0.005)") - O2_DEFINE_CONFIGURABLE(cfgPairCutLambda, float, -1, "Pair cut on Lambda: -1 = off; >0 otherwise distance value (suggested: 0.005)") - O2_DEFINE_CONFIGURABLE(cfgPairCutPhi, float, -1, "Pair cut on Phi: -1 = off; >0 otherwise distance value") - O2_DEFINE_CONFIGURABLE(cfgPairCutRho, float, -1, "Pair cut on Rho: -1 = off; >0 otherwise distance value") - - ConfigurableAxis axisVertex{"axisVertex", {7, -7, 7}, "vertex axis for histograms"}; - ConfigurableAxis axisDeltaPhi{"axisDeltaPhi", {72, -M_PI / 2, M_PI / 2 * 3}, "delta phi axis for histograms"}; - ConfigurableAxis axisDeltaEta{"axisDeltaEta", {40, -2, 2}, "delta eta axis for histograms"}; - ConfigurableAxis axisPtTrigger{"axisPtTrigger", {VARIABLE_WIDTH, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 10.0}, "pt trigger axis for histograms"}; - ConfigurableAxis axisPtAssoc{"axisPtAssoc", {VARIABLE_WIDTH, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0}, "pt associated axis for histograms"}; - ConfigurableAxis axisMultiplicity{"axisMultiplicity", {VARIABLE_WIDTH, 0, 5, 10, 20, 30, 40, 50, 100.1}, "multiplicity / centrality axis for histograms"}; - - ConfigurableAxis axisVertexEfficiency{"axisVertexEfficiency", {10, -10, 10}, "vertex axis for efficiency histograms"}; - ConfigurableAxis axisEtaEfficiency{"axisEtaEfficiency", {20, -1.0, 1.0}, "eta axis for efficiency histograms"}; - ConfigurableAxis axisPtEfficiency{"axisPtEfficiency", {VARIABLE_WIDTH, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75, 4.0, 4.5, 5.0, 6.0, 7.0, 8.0}, "pt axis for efficiency histograms"}; - - enum PairCuts { Photon = 0, - K0, - Lambda, - Phi, - Rho }; - struct Config { - bool mPairCuts = false; - //THn* mEfficiencyTrigger = nullptr; - //THn* mEfficiencyAssociated = nullptr; - } cfg; - - struct QA { - TH3F* mTwoTrackDistancePt[2] = {nullptr}; // control histograms for two-track efficiency study: dphi*_min vs deta (0 = before cut, 1 = after cut) - TH2F* mControlConvResoncances = nullptr; // control histograms for cuts on conversions and resonances - } qa; - - void init(o2::framework::InitContext&) - { - // --- CONFIGURATION --- - if (cfgPairCutPhoton > 0 || cfgPairCutK0 > 0 || cfgPairCutLambda > 0 || cfgPairCutPhi > 0 || cfgPairCutRho > 0) { - cfg.mPairCuts = true; - } - - // --- OBJECT INIT --- - std::vector axisList = {{axisDeltaEta, "#Delta#eta"}, - {axisPtAssoc, "p_{T} (GeV/c)"}, - {axisPtTrigger, "p_{T} (GeV/c)"}, - {axisMultiplicity, "multiplicity / centrality"}, - {axisDeltaPhi, "#Delta#varphi (rad)"}, - {axisVertex, "z-vtx (cm)"}, - {axisEtaEfficiency, "#eta"}, - {axisPtEfficiency, "p_{T} (GeV/c)"}, - {axisVertexEfficiency, "z-vtx (cm)"}}; - same.setObject(new CorrelationContainer("sameEvent", "sameEvent", axisList)); - mixed.setObject(new CorrelationContainer("mixedEvent", "mixedEvent", axisList)); - - if (cfgTwoTrackCut > 0) { - qa.mTwoTrackDistancePt[0] = new TH3F("TwoTrackDistancePt[0]", ";#Delta#eta;#Delta#varphi^{*}_{min};#Delta p_{T}", 100, -0.15, 0.15, 100, -0.05, 0.05, 20, 0, 10); - qa.mTwoTrackDistancePt[1] = (TH3F*)qa.mTwoTrackDistancePt[0]->Clone("TwoTrackDistancePt[1]"); - //qaOutput->Add(qa.mTwoTrackDistancePt[0]); - //qaOutput->Add(qa.mTwoTrackDistancePt[1]); - } - - if (cfg.mPairCuts) { - qa.mControlConvResoncances = new TH2F("ControlConvResoncances", ";id;delta mass", 6, -0.5, 5.5, 500, -0.5, 0.5); - //qaOutput->Add(qa.mControlConvResoncances); - } - } - - void process(soa::Join& collisions, myTracks const& tracks) - { - int bSign = 1; // TODO magnetic field from CCDB - const float pTCut = 2.0; - - collisions.bindExternalIndices(&tracks); - auto tracksTuple = std::make_tuple(tracks); - AnalysisDataProcessorBuilder::GroupSlicer slicer(collisions, tracksTuple); - - // Strictly upper categorised collisions, for 5 combinations per bin, skipping those in entry -1 - for (auto& [collision1, collision2] : selfCombinations("fBin", 5, -1, collisions, collisions)) { - - LOGF(info, "Collisions bin: %d pair: %d (%f), %d (%f)", collision1.bin(), collision1.index(), collision1.posZ(), collision2.index(), collision2.posZ()); - - auto it1 = slicer.begin(); - auto it2 = slicer.begin(); - for (auto& slice : slicer) { - if (slice.groupingElement().index() == collision1.index()) { - it1 = slice; - break; - } - } - for (auto& slice : slicer) { - if (slice.groupingElement().index() == collision2.index()) { - it2 = slice; - break; - } - } - - auto tracks1 = std::get(it1.associatedTables()); - tracks1.bindExternalIndices(&collisions); - auto tracks2 = std::get(it2.associatedTables()); - tracks2.bindExternalIndices(&collisions); - - // LOGF(info, "Tracks: %d and %d entries", tracks1.size(), tracks2.size()); - - for (auto& track1 : tracks1) { - - if (cfgTriggerCharge != 0 && cfgTriggerCharge * track1.sign() < 0) { - continue; - } - - //LOGF(info, "TRACK %f %f | %f %f | %f %f", track1.eta(), track1.eta(), track1.phi(), track1.phi(), track1.pt(), track1.pt()); - - mixed->getTriggerHist()->Fill(CorrelationContainer::kCFStepReconstructed, track1.pt(), collision1.centV0M(), collision1.posZ()); - - for (auto& track2 : tracks2) { - - if (cfgAssociatedCharge != 0 && cfgAssociatedCharge * track2.sign() < 0) { - continue; - } - if (cfgPairCharge != 0 && cfgPairCharge * track1.sign() * track2.sign() < 0) { - continue; - } - - if (cfg.mPairCuts && conversionCuts(track1, track2)) { - continue; - } - - if (cfgTwoTrackCut > 0 && twoTrackCut(track1, track2, bSign)) { - continue; - } - - float deltaPhi = track1.phi() - track2.phi(); - if (deltaPhi > 1.5 * M_PI) { - deltaPhi -= M_PI * 2; - } - if (deltaPhi < -0.5 * M_PI) { - deltaPhi += M_PI * 2; - } - - mixed->getPairHist()->Fill(CorrelationContainer::kCFStepReconstructed, - track1.eta() - track2.eta(), track2.pt(), track1.pt(), collision1.centV0M(), deltaPhi, collision1.posZ()); - } - } - } - } - - template - bool conversionCuts(T const& track1, T const& track2) - { - // skip if like sign - if (track1.sign() * track2.sign() > 0) { - return false; - } - - bool decision = false; - - if (conversionCut(track1, track2, Photon, cfgPairCutPhoton)) { - decision = true; - } - if (conversionCut(track1, track2, K0, cfgPairCutK0)) { - decision = true; - } - if (conversionCut(track1, track2, Lambda, cfgPairCutLambda)) { - decision = true; - } - if (conversionCut(track2, track1, Lambda, cfgPairCutLambda)) { - decision = true; - } - if (conversionCut(track1, track2, Phi, cfgPairCutPhi)) { - decision = true; - } - if (conversionCut(track1, track2, Rho, cfgPairCutRho)) { - decision = true; - } - - return decision; - } - - template - bool conversionCut(T const& track1, T const& track2, PairCuts conv, double cut) - { - //LOGF(info, "pt is %f %f", track1.pt(), track2.pt()); - - if (cut < 0) { - return false; - } - - double massD1, massD2, massM; - - switch (conv) { - case Photon: - massD1 = 0.51e-3; - massD2 = 0.51e-3; - massM = 0; - break; - case K0: - massD1 = 0.1396; - massD2 = 0.1396; - massM = 0.4976; - break; - case Lambda: - massD1 = 0.9383; - massD2 = 0.1396; - massM = 1.115; - break; - case Phi: - massD1 = 0.4937; - massD2 = 0.4937; - massM = 1.019; - break; - case Rho: - massD1 = 0.1396; - massD2 = 0.1396; - massM = 0.770; - break; - } - - auto massC = getInvMassSquaredFast(track1, massD1, track2, massD2); - - if (TMath::Abs(massC - massM * massM) > cut * 5) { - return false; - } - - massC = getInvMassSquared(track1, massD1, track2, massD2); - qa.mControlConvResoncances->Fill(static_cast(conv), massC - massM * massM); - if (massC > (massM - cut) * (massM - cut) && massC < (massM + cut) * (massM + cut)) { - return true; - } - - return false; - } - - template - double getInvMassSquared(T const& track1, double m0_1, T const& track2, double m0_2) - { - // calculate inv mass squared - // same can be achieved, but with more computing time with - /*TLorentzVector photon, p1, p2; - p1.SetPtEtaPhiM(triggerParticle->Pt(), triggerEta, triggerParticle->Phi(), 0.510e-3); - p2.SetPtEtaPhiM(particle->Pt(), eta[j], particle->Phi(), 0.510e-3); - photon = p1+p2; - photon.M()*/ - - float tantheta1 = 1e10; - - if (track1.eta() < -1e-10 || track1.eta() > 1e-10) { - float expTmp = TMath::Exp(-track1.eta()); - tantheta1 = 2.0 * expTmp / (1.0 - expTmp * expTmp); - } - - float tantheta2 = 1e10; - if (track2.eta() < -1e-10 || track2.eta() > 1e-10) { - float expTmp = TMath::Exp(-track2.eta()); - tantheta2 = 2.0 * expTmp / (1.0 - expTmp * expTmp); - } - - float e1squ = m0_1 * m0_1 + track1.pt() * track1.pt() * (1.0 + 1.0 / tantheta1 / tantheta1); - float e2squ = m0_2 * m0_2 + track2.pt() * track2.pt() * (1.0 + 1.0 / tantheta2 / tantheta2); - - float mass2 = m0_1 * m0_1 + m0_2 * m0_2 + 2 * (TMath::Sqrt(e1squ * e2squ) - (track1.pt() * track2.pt() * (TMath::Cos(track1.phi() - track2.phi()) + 1.0 / tantheta1 / tantheta2))); - - // Printf(Form("%f %f %f %f %f %f %f %f %f", pt1, eta1, phi1, pt2, eta2, phi2, m0_1, m0_2, mass2)); - - return mass2; - } - - template - double getInvMassSquaredFast(T const& track1, double m0_1, T const& track2, double m0_2) - { - // calculate inv mass squared approximately - - const float eta1 = track1.eta(); - const float eta2 = track2.eta(); - const float phi1 = track1.phi(); - const float phi2 = track2.phi(); - const float pt1 = track1.pt(); - const float pt2 = track2.pt(); - - float tantheta1 = 1e10; - - if (eta1 < -1e-10 || eta1 > 1e-10) { - float expTmp = 1.0 - eta1 + eta1 * eta1 / 2 - eta1 * eta1 * eta1 / 6 + eta1 * eta1 * eta1 * eta1 / 24; - tantheta1 = 2.0 * expTmp / (1.0 - expTmp * expTmp); - } - - float tantheta2 = 1e10; - if (eta2 < -1e-10 || eta2 > 1e-10) { - float expTmp = 1.0 - eta2 + eta2 * eta2 / 2 - eta2 * eta2 * eta2 / 6 + eta2 * eta2 * eta2 * eta2 / 24; - tantheta2 = 2.0 * expTmp / (1.0 - expTmp * expTmp); - } - - float e1squ = m0_1 * m0_1 + pt1 * pt1 * (1.0 + 1.0 / tantheta1 / tantheta1); - float e2squ = m0_2 * m0_2 + pt2 * pt2 * (1.0 + 1.0 / tantheta2 / tantheta2); - - // fold onto 0...pi - float deltaPhi = TMath::Abs(phi1 - phi2); - while (deltaPhi > M_PI * 2) { - deltaPhi -= M_PI * 2; - } - if (deltaPhi > M_PI) { - deltaPhi = M_PI * 2 - deltaPhi; - } - - float cosDeltaPhi = 0; - if (deltaPhi < M_PI / 3) { - cosDeltaPhi = 1.0 - deltaPhi * deltaPhi / 2 + deltaPhi * deltaPhi * deltaPhi * deltaPhi / 24; - } else if (deltaPhi < 2 * M_PI / 3) { - cosDeltaPhi = -(deltaPhi - M_PI / 2) + 1.0 / 6 * TMath::Power((deltaPhi - M_PI / 2), 3); - } else { - cosDeltaPhi = -1.0 + 1.0 / 2.0 * (deltaPhi - M_PI) * (deltaPhi - M_PI) - 1.0 / 24.0 * TMath::Power(deltaPhi - M_PI, 4); - } - - double mass2 = m0_1 * m0_1 + m0_2 * m0_2 + 2 * (TMath::Sqrt(e1squ * e2squ) - (pt1 * pt2 * (cosDeltaPhi + 1.0 / tantheta1 / tantheta2))); - - // Printf(Form("%f %f %f %f %f %f %f %f %f", pt1, eta1, phi1, pt2, eta2, phi2, m0_1, m0_2, mass2)); - - return mass2; - } - - template - bool twoTrackCut(T const& track1, T const& track2, int bSign) - { - // the variables & cuthave been developed by the HBT group - // see e.g. https://indico.cern.ch/materialDisplay.py?contribId=36&sessionId=6&materialId=slides&confId=142700 - - auto deta = track1.eta() - track2.eta(); - - // optimization - if (TMath::Abs(deta) < cfgTwoTrackCut * 2.5 * 3) { - // check first boundaries to see if is worth to loop and find the minimum - float dphistar1 = getDPhiStar(track1, track2, cfgTwoTrackCutMinRadius, bSign); - float dphistar2 = getDPhiStar(track1, track2, 2.5, bSign); - - const float kLimit = cfgTwoTrackCut * 3; - - if (TMath::Abs(dphistar1) < kLimit || TMath::Abs(dphistar2) < kLimit || dphistar1 * dphistar2 < 0) { - float dphistarminabs = 1e5; - float dphistarmin = 1e5; - for (Double_t rad = cfgTwoTrackCutMinRadius; rad < 2.51; rad += 0.01) { - float dphistar = getDPhiStar(track1, track2, rad, bSign); - - float dphistarabs = TMath::Abs(dphistar); - - if (dphistarabs < dphistarminabs) { - dphistarmin = dphistar; - dphistarminabs = dphistarabs; - } - } - - qa.mTwoTrackDistancePt[0]->Fill(deta, dphistarmin, TMath::Abs(track1.pt() - track2.pt())); - - if (dphistarminabs < cfgTwoTrackCut && TMath::Abs(deta) < cfgTwoTrackCut) { - //Printf("Removed track pair %ld %ld with %f %f %f %f %d %f %f %d %d", track1.index(), track2.index(), deta, dphistarminabs, track1.phi(), track1.pt(), track1.sign(), track2.phi(), track2.pt(), track2.sign(), bSign); - return true; - } - - qa.mTwoTrackDistancePt[1]->Fill(deta, dphistarmin, TMath::Abs(track1.pt() - track2.pt())); - } - } - - return false; - } - - template - float getDPhiStar(T const& track1, T const& track2, float radius, float bSign) - { - // - // calculates dphistar - // - - auto phi1 = track1.phi(); - auto pt1 = track1.pt(); - auto charge1 = track1.sign(); - - auto phi2 = track2.phi(); - auto pt2 = track2.pt(); - auto charge2 = track2.sign(); - - float dphistar = phi1 - phi2 - charge1 * bSign * TMath::ASin(0.075 * radius / pt1) + charge2 * bSign * TMath::ASin(0.075 * radius / pt2); - - if (dphistar > M_PI) { - dphistar = M_PI * 2 - dphistar; - } - if (dphistar < -M_PI) { - dphistar = -M_PI * 2 - dphistar; - } - if (dphistar > M_PI) { // might look funny but is needed - dphistar = M_PI * 2 - dphistar; - } - - return dphistar; - } - - // template - // unsigned int getFilterBit(soa::Table::iterator const& track) - // { - // if constexpr(!has_type_v>) - // static_assert("Need to pass aod::track"); - // - // - // // LOGF(info, "pt %f", track1.pt()); - // return false; - // } - - // float getInvMassSquared(float pt1, float eta1, float phi1, float pt2, float eta2, float phi2, float m0_1, float m0_2) -}; - -WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) -{ - return WorkflowSpec{ - adaptAnalysisTask(cfgc), - adaptAnalysisTask(cfgc)}; -} From e00c79ffa5a182933f3242439fe51a08f0f64867 Mon Sep 17 00:00:00 2001 From: shahoian Date: Thu, 6 May 2021 11:27:45 +0200 Subject: [PATCH 398/770] FT0,FDD Fix copy-paste errors in ini files --- Detectors/FIT/FDD/workflow/src/fdd-reco-workflow.cxx | 2 +- Detectors/FIT/FT0/workflow/src/ft0-reco-workflow.cxx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Detectors/FIT/FDD/workflow/src/fdd-reco-workflow.cxx b/Detectors/FIT/FDD/workflow/src/fdd-reco-workflow.cxx index 35ea032f8c5cb..bb05f2caf64d7 100644 --- a/Detectors/FIT/FDD/workflow/src/fdd-reco-workflow.cxx +++ b/Detectors/FIT/FDD/workflow/src/fdd-reco-workflow.cxx @@ -41,7 +41,7 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) // Update the (declared) parameters if changed from the command line o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); // write the configuration used for the digitizer workflow - o2::conf::ConfigurableParam::writeINI("o2tpcits-match-recoflow_configuration.ini"); + o2::conf::ConfigurableParam::writeINI("o2-fdd-recoflow_configuration.ini"); auto useMC = !configcontext.options().get("disable-mc"); auto disableRootInp = configcontext.options().get("disable-root-input"); diff --git a/Detectors/FIT/FT0/workflow/src/ft0-reco-workflow.cxx b/Detectors/FIT/FT0/workflow/src/ft0-reco-workflow.cxx index a63dee708bac4..f1618913d7388 100644 --- a/Detectors/FIT/FT0/workflow/src/ft0-reco-workflow.cxx +++ b/Detectors/FIT/FT0/workflow/src/ft0-reco-workflow.cxx @@ -41,7 +41,7 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) // Update the (declared) parameters if changed from the command line o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); // write the configuration used for the digitizer workflow - o2::conf::ConfigurableParam::writeINI("o2tpcits-match-recoflow_configuration.ini"); + o2::conf::ConfigurableParam::writeINI("o2-ft0-recoflow_configuration.ini"); auto useMC = !configcontext.options().get("disable-mc"); auto disableRootInp = configcontext.options().get("disable-root-input"); From 962fe2c8e96c3847c47e63405edf83196c742a2b Mon Sep 17 00:00:00 2001 From: Ole Schmidt Date: Tue, 4 May 2021 21:41:34 +0200 Subject: [PATCH 399/770] TRD track readers + requested changes from PR6057 --- Detectors/TRD/workflow/CMakeLists.txt | 7 + .../include/TRDWorkflow/TRDTrackReaderSpec.h | 69 ++++++++++ .../workflow/src/TRDGlobalTrackingSpec.cxx | 15 ++- .../TRD/workflow/src/TRDTrackReaderSpec.cxx | 104 +++++++++++++++ .../src/trd-track-reader-workflow.cxx | 60 +++++++++ GPU/GPUTracking/CMakeLists.txt | 3 +- .../DataTypes/GPUTRDInterfaceO2Track.h | 110 +++++++++++++++ .../TRDTracking/GPUTRDInterfaces.h | 126 +++++------------- GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx | 105 ++++++++------- GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx | 18 ++- GPU/GPUTracking/TRDTracking/GPUTRDTracker.h | 1 + 11 files changed, 464 insertions(+), 154 deletions(-) create mode 100644 Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackReaderSpec.h create mode 100644 Detectors/TRD/workflow/src/TRDTrackReaderSpec.cxx create mode 100644 Detectors/TRD/workflow/src/trd-track-reader-workflow.cxx create mode 100644 GPU/GPUTracking/DataTypes/GPUTRDInterfaceO2Track.h diff --git a/Detectors/TRD/workflow/CMakeLists.txt b/Detectors/TRD/workflow/CMakeLists.txt index 67f62a2ce2d99..5e25dd8dd272a 100644 --- a/Detectors/TRD/workflow/CMakeLists.txt +++ b/Detectors/TRD/workflow/CMakeLists.txt @@ -19,6 +19,7 @@ o2_add_library(TRDWorkflow src/TRDTrackletTransformerSpec.cxx src/TRDGlobalTrackingSpec.cxx src/TRDTrackWriterSpec.cxx + src/TRDTrackReaderSpec.cxx src/TRDTrackingWorkflow.cxx src/EntropyDecoderSpec.cxx src/EntropyEncoderSpec.cxx @@ -47,6 +48,12 @@ o2_add_executable(tracklet-transformer SOURCES src/TRDTrackletTransformerWorkflow.cxx PUBLIC_LINK_LIBRARIES O2::TRDWorkflow) +o2_add_executable(track-reader + COMPONENT_NAME trd + SOURCES src/trd-track-reader-workflow.cxx + PUBLIC_LINK_LIBRARIES O2::TRDWorkflow) + + if (OpenMP_CXX_FOUND) target_compile_definitions(${targetName} PRIVATE WITH_OPENMP) diff --git a/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackReaderSpec.h b/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackReaderSpec.h new file mode 100644 index 0000000000000..19b5e722054e0 --- /dev/null +++ b/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackReaderSpec.h @@ -0,0 +1,69 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_TRD_TRACK_READER_H +#define O2_TRD_TRACK_READER_H + +/// @file TRDTrackReaderSpec.h + +#include "GPUO2Interface.h" +#include "GPUTRDDef.h" +#include "GPUTRDTrack.h" + +#include "Framework/DataProcessorSpec.h" +#include "Framework/Task.h" + +#include "TFile.h" +#include "TTree.h" + +#include +#include +#include + +using namespace o2::framework; + +namespace o2 +{ +namespace trd +{ + +class TRDTrackReader : public Task +{ + public: + enum Mode : int { + ITSTPCTRD, + TPCTRD + }; + + TRDTrackReader(bool useMC, Mode mode) : mUseMC(useMC), mMode(mode) {} + ~TRDTrackReader() override = default; + void init(InitContext& ic) final; + void run(ProcessingContext& pc) final; + + private: + void connectTree(const std::string& filename); + bool mUseMC = false; + Mode mMode; + std::unique_ptr mFile; + std::unique_ptr mTree; + std::string mFileName = ""; + std::vector mTracks, *mTracksPtr = &mTracks; +}; + +/// read TPC-TRD matched tracks from a root file +framework::DataProcessorSpec getTRDTPCTrackReaderSpec(bool useMC); + +/// read ITS-TPC-TRD matched tracks from a root file +framework::DataProcessorSpec getTRDGlobalTrackReaderSpec(bool useMC); + +} // namespace trd +} // namespace o2 + +#endif diff --git a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx index e44d9ece665b4..aa6a73ba65d6e 100644 --- a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx @@ -102,8 +102,8 @@ void TRDGlobalTracking::run(ProcessingContext& pc) o2::globaltracking::RecoContainer inputTracks; inputTracks.collectData(pc, *mDataRequest); auto tmpInputContainer = getRecoInputContainer(pc, &mChainTracking->mIOPtrs, &inputTracks); - LOGF(INFO, "There are %i tracklets in total from %i trigger records", tmpInputContainer->mNTracklets, tmpInputContainer->mNTriggerRecords); - LOGF(INFO, "As input seeds are available: %i ITS-TPC matched tracks and %i TPC tracks", tmpInputContainer->mNTracksTPCITS, tmpInputContainer->mNTracksTPC); + LOGF(INFO, "There are %i tracklets in total from %i trigger records", mChainTracking->mIOPtrs.nTRDTracklets, mChainTracking->mIOPtrs.nTRDTriggerRecords); + LOGF(INFO, "As input seeds are available: %i ITS-TPC matched tracks and %i TPC tracks", mChainTracking->mIOPtrs.nTracksTPCITSO2, mChainTracking->mIOPtrs.nOutputTracksTPCO2); if (tmpInputContainer->mNTracklets != tmpInputContainer->mNSpacePoints) { LOGF(FATAL, "Number of calibrated tracklets (%i) differs from the number of uncalibrated tracklets (%i)", tmpInputContainer->mNSpacePoints, tmpInputContainer->mNTracklets); } @@ -120,22 +120,23 @@ void TRDGlobalTracking::run(ProcessingContext& pc) int nTracksLoadedTPC = 0; std::vector loadedTPCtracks; // load ITS-TPC matched tracks - for (const auto& match : tmpInputContainer->mTracksTPCITS) { - GPUTRDTrack trkLoad(match, mTPCVdrift); + for (int iTrk = 0; iTrk < mChainTracking->mIOPtrs.nTracksTPCITSO2; ++iTrk) { + const auto& trkITSTPC = mChainTracking->mIOPtrs.tracksTPCITSO2[iTrk]; + GPUTRDTrack trkLoad(trkITSTPC, mTPCVdrift); if (mTracker->LoadTrack(trkLoad)) { continue; } - loadedTPCtracks.push_back(match.getRefTPC()); + loadedTPCtracks.push_back(trkITSTPC.getRefTPC()); ++nTracksLoadedITSTPC; LOGF(DEBUG, "Loaded ITS-TPC track %i with time %f", nTracksLoadedITSTPC, trkLoad.getTime()); } // load TPC-only tracks - for (int iTrk = 0; iTrk < tmpInputContainer->mNTracksTPC; ++iTrk) { + for (int iTrk = 0; iTrk < mChainTracking->mIOPtrs.nOutputTracksTPCO2; ++iTrk) { if (std::find(loadedTPCtracks.begin(), loadedTPCtracks.end(), iTrk) != loadedTPCtracks.end()) { // this TPC tracks has already been matched to ITS and the ITS-TPC track has already been loaded in the tracker continue; } - const auto& trkTpc = tmpInputContainer->mTracksTPC[iTrk]; + const auto& trkTpc = mChainTracking->mIOPtrs.outputTracksTPCO2[iTrk]; GPUTRDTrack trkLoad(trkTpc, mTPCTBinMUS, mTPCVdrift, iTrk); if (mTracker->LoadTrack(trkLoad)) { continue; diff --git a/Detectors/TRD/workflow/src/TRDTrackReaderSpec.cxx b/Detectors/TRD/workflow/src/TRDTrackReaderSpec.cxx new file mode 100644 index 0000000000000..d1b6fe0f6072e --- /dev/null +++ b/Detectors/TRD/workflow/src/TRDTrackReaderSpec.cxx @@ -0,0 +1,104 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// @file TRDTrackReaderSpec.cxx + +#include "TRDWorkflow/TRDTrackReaderSpec.h" +#include "Framework/ConfigParamRegistry.h" +#include "Framework/ControlService.h" +#include "Framework/SerializationMethods.h" +#include "CommonUtils/StringUtils.h" + +using GTrackID = o2::dataformats::GlobalTrackID; + +namespace o2 +{ +namespace trd +{ + +void TRDTrackReader::init(InitContext& ic) +{ + + mFileName = o2::utils::Str::concat_string(o2::utils::Str::rectifyDirectory(ic.options().get("input-dir")), + ic.options().get("track-infile")); + + connectTree(mFileName); +} + +void TRDTrackReader::run(ProcessingContext& pc) +{ + auto ent = mTree->GetReadEntry() + 1; + assert(ent < mTree->GetEntries()); // this should not happen + mTree->GetEntry(ent); + LOG(INFO) << "Pushing " << mTracks.size() << " tracks at entry " << ent; + + if (mMode == Mode::TPCTRD) { + pc.outputs().snapshot(Output{o2::header::gDataOriginTRD, "MATCHTRD_TPC", 0, Lifetime::Timeframe}, mTracks); + } else if (mMode == Mode::ITSTPCTRD) { + pc.outputs().snapshot(Output{o2::header::gDataOriginTRD, "MATCHTRD_GLO", 0, Lifetime::Timeframe}, mTracks); + } + + if (mTree->GetReadEntry() + 1 >= mTree->GetEntries()) { + pc.services().get().endOfStream(); + pc.services().get().readyToQuit(QuitRequest::Me); + } +} + +void TRDTrackReader::connectTree(const std::string& filename) +{ + mTree.reset(nullptr); // in case it was already loaded + mFile.reset(TFile::Open(filename.c_str())); + assert(mFile && !mFile->IsZombie()); + mTree.reset((TTree*)mFile->Get("tracksTRD")); + assert(mTree); + mTree->SetBranchAddress("tracks", &mTracksPtr); + LOG(INFO) << "Loaded tree from " << filename << " with " << mTree->GetEntries() << " entries"; +} + +DataProcessorSpec getTRDTPCTrackReaderSpec(bool useMC) +{ + std::vector outputs; + outputs.emplace_back(o2::header::gDataOriginTRD, "MATCHTRD_TPC", 0, Lifetime::Timeframe); + + if (useMC) { + LOG(FATAL) << "TRD track reader cannot read MC data (yet)"; + } + + return DataProcessorSpec{ + "tpctrd-track-reader", + Inputs{}, + outputs, + AlgorithmSpec{adaptFromTask(useMC, TRDTrackReader::Mode::TPCTRD)}, + Options{ + {"track-infile", VariantType::String, "trdmatches_tpc.root", {"Name of the input file for TPC-TRD matches"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; +} + +DataProcessorSpec getTRDGlobalTrackReaderSpec(bool useMC) +{ + std::vector outputs; + outputs.emplace_back(o2::header::gDataOriginTRD, "MATCHTRD_GLO", 0, Lifetime::Timeframe); + + if (useMC) { + LOG(FATAL) << "TRD track reader cannot read MC data (yet)"; + } + + return DataProcessorSpec{ + "itstpctrd-track-reader", + Inputs{}, + outputs, + AlgorithmSpec{adaptFromTask(useMC, TRDTrackReader::Mode::ITSTPCTRD)}, + Options{ + {"track-infile", VariantType::String, "trdmatches_itstpc.root", {"Name of the input file for ITS-TPC-TRD matches"}}, + {"input-dir", VariantType::String, "none", {"Input directory"}}}}; +} + +} // namespace trd +} // namespace o2 diff --git a/Detectors/TRD/workflow/src/trd-track-reader-workflow.cxx b/Detectors/TRD/workflow/src/trd-track-reader-workflow.cxx new file mode 100644 index 0000000000000..d3e42893cb706 --- /dev/null +++ b/Detectors/TRD/workflow/src/trd-track-reader-workflow.cxx @@ -0,0 +1,60 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "CommonUtils/ConfigurableParam.h" +#include "Framework/CompletionPolicy.h" +#include "Framework/ConfigParamSpec.h" +#include "TRDWorkflow/TRDTrackReaderSpec.h" +#include "ReconstructionDataFormats/GlobalTrackID.h" + +using namespace o2::framework; +using GTrackID = o2::dataformats::GlobalTrackID; + +// ------------------------------------------------------------------ + +// we need to add workflow options before including Framework/runDataProcessing +void customize(std::vector& workflowOptions) +{ + // option allowing to set parameters + std::vector options{ + {"disable-mc", o2::framework::VariantType::Bool, true, {"disable MC propagation"}}, + {"track-types", VariantType::String, std::string{GTrackID::ALL}, {"comma-separated list of sources to use for tracking"}}, + {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings ..."}}}; + + std::swap(workflowOptions, options); +} + +// ------------------------------------------------------------------ + +#include "Framework/runDataProcessing.h" + +WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) +{ + // Update the (declared) parameters if changed from the command line + o2::conf::ConfigurableParam::updateFromString(configcontext.options().get("configKeyValues")); + + auto useMC = !configcontext.options().get("disable-mc"); + if (useMC) { + LOG(WARNING) << "TRD track reader cannot read MC labels, useMC = false will be enforced"; + useMC = false; + } + + GTrackID::mask_t allowedSources = GTrackID::getSourcesMask("ITS-TPC-TRD,TPC-TRD"); + GTrackID::mask_t srcTRD = allowedSources & GTrackID::getSourcesMask(configcontext.options().get("track-types")); + + WorkflowSpec specs; + if (GTrackID::includesSource(GTrackID::Source::ITSTPCTRD, srcTRD)) { + specs.emplace_back(o2::trd::getTRDGlobalTrackReaderSpec(useMC)); + } + if (GTrackID::includesSource(GTrackID::Source::TPCTRD, srcTRD)) { + specs.emplace_back(o2::trd::getTRDTPCTrackReaderSpec(useMC)); + } + return std::move(specs); +} diff --git a/GPU/GPUTracking/CMakeLists.txt b/GPU/GPUTracking/CMakeLists.txt index 176b3bd3c8d43..204a68228444f 100644 --- a/GPU/GPUTracking/CMakeLists.txt +++ b/GPU/GPUTracking/CMakeLists.txt @@ -133,6 +133,7 @@ set(HDRS_INSTALL DataTypes/GPUHostDataTypes.h DataTypes/GPURawData.h DataTypes/GPUdEdxInfo.h + DataTypes/GPUTRDInterfaceO2Track.h Base/GPUParam.inc Merger/GPUTPCGMMergerTypes.h Global/GPUErrorCodes.h @@ -272,7 +273,7 @@ if(ALIGPU_BUILD_TYPE STREQUAL "O2") DataTypes PUBLIC_LINK_LIBRARIES O2::GPUCommon SOURCES utils/EmptyFile.cxx) - + o2_add_library(${MODULE} TARGETVARNAME targetName PUBLIC_LINK_LIBRARIES O2::GPUCommon diff --git a/GPU/GPUTracking/DataTypes/GPUTRDInterfaceO2Track.h b/GPU/GPUTracking/DataTypes/GPUTRDInterfaceO2Track.h new file mode 100644 index 0000000000000..4a14e185d25da --- /dev/null +++ b/GPU/GPUTracking/DataTypes/GPUTRDInterfaceO2Track.h @@ -0,0 +1,110 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file GPUTRDInterfaceO2Track.h +/// \author Ole Schmidt + +#ifndef GPUTRDINTERFACEO2TRACK_H +#define GPUTRDINTERFACEO2TRACK_H + +// This is the interface for the GPUTRDTrack based on the O2 track type + +namespace GPUCA_NAMESPACE +{ +namespace gpu +{ +template +class trackInterface; +} // namespace gpu +} // namespace GPUCA_NAMESPACE + +#include "ReconstructionDataFormats/Track.h" +#include "ReconstructionDataFormats/TrackTPCITS.h" +#include "DataFormatsTPC/TrackTPC.h" +#include "ReconstructionDataFormats/GlobalTrackID.h" +#include "GPUTRDO2BaseTrack.h" + +namespace GPUCA_NAMESPACE +{ + +namespace gpu +{ + +template <> +class trackInterface : public GPUTRDO2BaseTrack +{ + public: + GPUdDefault() trackInterface() = default; + trackInterface(const GPUTRDO2BaseTrack& param) = delete; + GPUd() trackInterface(const o2::dataformats::TrackTPCITS& trkItsTpc, float vDrift) : GPUTRDO2BaseTrack(trkItsTpc.getParamOut()) + { + mTime = trkItsTpc.getTimeMUS().getTimeStamp(); + mTimeAddMax = trkItsTpc.getTimeMUS().getTimeStampError(); + mTimeSubMax = trkItsTpc.getTimeMUS().getTimeStampError(); + mRefITS = trkItsTpc.getRefITS(); + mRefTPC = trkItsTpc.getRefTPC(); + float tmp = trkItsTpc.getTimeMUS().getTimeStampError() * vDrift; + updateCov(tmp * tmp, o2::track::CovLabels::kSigZ2); // account for time uncertainty by increasing sigmaZ2 + } + GPUd() trackInterface(const o2::tpc::TrackTPC& trkTpc, float tbWidth, float vDrift, unsigned int iTrk) : GPUTRDO2BaseTrack(trkTpc.getParamOut()) + { + mRefTPC = {iTrk, o2::dataformats::GlobalTrackID::TPC}; + mTime = trkTpc.getTime0() * tbWidth; + mTimeAddMax = trkTpc.getDeltaTFwd() * tbWidth; + mTimeSubMax = trkTpc.getDeltaTBwd() * tbWidth; + if (trkTpc.hasASideClustersOnly()) { + mSide = -1; + } else if (trkTpc.hasCSideClustersOnly()) { + mSide = 1; + } else { + // CE-crossing tracks are not shifted along z, but the time uncertainty is taken into account by increasing sigmaZ2 + float timeWindow = (mTimeAddMax + mTimeSubMax) * .5f; + float tmp = timeWindow * vDrift; + updateCov(tmp * tmp, o2::track::CovLabels::kSigZ2); + } + } + GPUd() void set(float x, float alpha, const float* param, const float* cov) + { + setX(x); + setAlpha(alpha); + for (int i = 0; i < 5; i++) { + setParam(param[i], i); + } + for (int i = 0; i < 15; i++) { + setCov(cov[i], i); + } + } + GPUdi() trackInterface(const GPUTPCGMMergedTrack& trk) { set(trk.OuterParam().X, trk.OuterParam().alpha, trk.OuterParam().P, trk.OuterParam().C); } + GPUdi() trackInterface(const GPUTPCGMTrackParam::GPUTPCOuterParam& param) { set(param.X, param.alpha, param.P, param.C); } + + GPUdi() const float* getPar() const { return getParams(); } + GPUdi() float getTime() const { return mTime; } + GPUdi() void setTime(float t) { mTime = t; } + GPUdi() float getTimeMax() const { return mTime + mTimeAddMax; } + GPUdi() float getTimeMin() const { return mTime - mTimeSubMax; } + GPUdi() short getSide() const { return mSide; } + GPUdi() float getZShift() const { return mZShift; } + GPUdi() void setZShift(float z) { mZShift = z; } + + GPUdi() bool CheckNumericalQuality() const { return true; } + + typedef GPUTRDO2BaseTrack baseClass; + + private: + o2::dataformats::GlobalTrackID mRefTPC; // reference on TPC track entry in its original container + o2::dataformats::GlobalTrackID mRefITS; // reference on ITS track entry in its original container + float mTime{-1.f}; // time estimate for this track in us + float mTimeAddMax{0.f}; // max. time that can be added to this track in us + float mTimeSubMax{0.f}; // max. time that can be subtracted to this track in us + short mSide{0}; // -1 : A-side, +1 : C-side (relevant only for TPC-only tracks) + float mZShift{0.f}; // calculated new for each TRD trigger candidate for this track +}; + +#endif diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h index 42f1a2d329b7f..6602356d54fd8 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h @@ -136,91 +136,8 @@ class propagatorInterface : public AliTrackerBase #if defined(HAVE_O2HEADERS) // Interface for O2, build only with O2 -#include "ReconstructionDataFormats/Track.h" -#include "ReconstructionDataFormats/TrackTPCITS.h" -#include "DataFormatsTPC/TrackTPC.h" -#include "ReconstructionDataFormats/GlobalTrackID.h" -#include "DetectorsBase/Propagator.h" -#include "GPUTRDO2BaseTrack.h" -#ifndef GPUCA_GPUCODE_DEVICE -#include -#endif - -namespace GPUCA_NAMESPACE -{ - -namespace gpu -{ - -template <> -class trackInterface : public GPUTRDO2BaseTrack -{ - public: - GPUdDefault() trackInterface() = default; - trackInterface(const GPUTRDO2BaseTrack& param) = delete; - GPUd() trackInterface(const o2::dataformats::TrackTPCITS& trkItsTpc, float vDrift) : GPUTRDO2BaseTrack(trkItsTpc.getParamOut()) - { - mTime = trkItsTpc.getTimeMUS().getTimeStamp(); - mTimeAddMax = trkItsTpc.getTimeMUS().getTimeStampError(); - mTimeSubMax = trkItsTpc.getTimeMUS().getTimeStampError(); - mRefITS = trkItsTpc.getRefITS(); - mRefTPC = trkItsTpc.getRefTPC(); - float tmp = trkItsTpc.getTimeMUS().getTimeStampError() * vDrift; - updateCov(tmp * tmp, o2::track::CovLabels::kSigZ2); // account for time uncertainty by increasing sigmaZ2 - } - GPUd() trackInterface(const o2::tpc::TrackTPC& trkTpc, float tbWidth, float vDrift, unsigned int iTrk) : GPUTRDO2BaseTrack(trkTpc.getParamOut()) - { - mRefTPC = {iTrk, o2::dataformats::GlobalTrackID::TPC}; - mTime = trkTpc.getTime0() * tbWidth; - mTimeAddMax = trkTpc.getDeltaTFwd() * tbWidth; - mTimeSubMax = trkTpc.getDeltaTBwd() * tbWidth; - if (trkTpc.hasASideClustersOnly()) { - mSide = -1; - } else if (trkTpc.hasCSideClustersOnly()) { - mSide = 1; - } else { - // CE-crossing tracks are not shifted along z, but the time uncertainty is taken into account by increasing sigmaZ2 - float timeWindow = (mTimeAddMax + mTimeSubMax) * .5f; - float tmp = timeWindow * vDrift; - updateCov(tmp * tmp, o2::track::CovLabels::kSigZ2); - } - } - GPUd() void set(float x, float alpha, const float* param, const float* cov) - { - setX(x); - setAlpha(alpha); - for (int i = 0; i < 5; i++) { - setParam(param[i], i); - } - for (int i = 0; i < 15; i++) { - setCov(cov[i], i); - } - } - GPUdi() trackInterface(const GPUTPCGMMergedTrack& trk) { set(trk.OuterParam().X, trk.OuterParam().alpha, trk.OuterParam().P, trk.OuterParam().C); } - GPUdi() trackInterface(const GPUTPCGMTrackParam::GPUTPCOuterParam& param) { set(param.X, param.alpha, param.P, param.C); } - - GPUdi() const float* getPar() const { return getParams(); } - GPUdi() float getTime() const { return mTime; } - GPUdi() void setTime(float t) { mTime = t; } - GPUdi() float getTimeMax() const { return mTime + mTimeAddMax; } - GPUdi() float getTimeMin() const { return mTime - mTimeSubMax; } - GPUdi() short getSide() const { return mSide; } - GPUdi() float getZShift() const { return mZShift; } - GPUdi() void setZShift(float z) { mZShift = z; } - - GPUdi() bool CheckNumericalQuality() const { return true; } - - typedef GPUTRDO2BaseTrack baseClass; - - private: - o2::dataformats::GlobalTrackID mRefTPC; // reference on TPC track entry in its original container - o2::dataformats::GlobalTrackID mRefITS; // reference on ITS track entry in its original container - float mTime{-1.f}; // time estimate for this track in us - float mTimeAddMax{0.f}; // max. time that can be added to this track in us - float mTimeSubMax{0.f}; // max. time that can be subtracted to this track in us - short mSide{0}; // -1 : A-side, +1 : C-side (relevant only for TPC-only tracks) - float mZShift{0.f}; // calculated new for each TRD trigger candidate for this track -}; +#include "DetectorsBase/Propagator.h" // when included after GPUTRDInterfaceO2Track.h the build fails +#include "GPUTRDInterfaceO2Track.h" template <> class propagatorInterface @@ -274,6 +191,7 @@ class propagatorInterface #include "GPUDef.h" #ifdef GPUCA_O2_LIB #include "DataFormatsTPC/TrackTPC.h" +#include "ReconstructionDataFormats/TrackTPCITS.h" #endif namespace GPUCA_NAMESPACE @@ -328,6 +246,11 @@ class trackInterface : public GPUTPCGMTrackParam for (int i = 0; i < 15; i++) { SetCov(i, param.getParamOut().getCov()[i]); } + mTime = param.getTimeMUS().getTimeStamp(); + mTimeAddMax = param.getTimeMUS().getTimeStampError(); + mTimeSubMax = param.getTimeMUS().getTimeStampError(); + float tmp = param.getTimeMUS().getTimeStampError() * 2.58f; // TPCvDrift = 2.58 cm/us fixed for now, should come from CCDB + Cov()[2] += tmp * tmp; // account for time uncertainty by increasing sigmaZ2 } trackInterface(const o2::tpc::TrackTPC& param, float, float, unsigned int) : GPUTPCGMTrackParam(), mAlpha(param.getParamOut().getAlpha()) { @@ -340,6 +263,20 @@ class trackInterface : public GPUTPCGMTrackParam for (int i = 0; i < 15; i++) { SetCov(i, param.getParamOut().getCov()[i]); } + const float tpcZBinWidth = 0.199606f; + mTime = param.getTime0() * tpcZBinWidth; + mTimeAddMax = param.getDeltaTFwd() * tpcZBinWidth; + mTimeSubMax = param.getDeltaTBwd() * tpcZBinWidth; + if (param.hasASideClustersOnly()) { + mSide = -1; + } else if (param.hasCSideClustersOnly()) { + mSide = 1; + } else { + // CE-crossing tracks are not shifted along z, but the time uncertainty is taken into account by increasing sigmaZ2 + float timeWindow = (mTimeAddMax + mTimeSubMax) * .5f; + float tmp = timeWindow * 2.58f; // TPCvDrift = 2.58 cm/us fixed for now, should come from CCDB + Cov()[2] += tmp * tmp; + } } #endif @@ -360,12 +297,12 @@ class trackInterface : public GPUTPCGMTrackParam GPUd() const float* getPar() const { return GetPar(); } GPUd() const float* getCov() const { return GetCov(); } - GPUd() float getTime() const { return -1.f; } - GPUd() float getTimeMax() const { return 0.f; } - GPUd() float getTimeMin() const { return 0.f; } - GPUd() short getSide() const { return 0; } - GPUd() void setZShift(float) {} - GPUd() float getZShift() const { return 0.f; } + GPUd() float getTime() const { return mTime; } + GPUd() float getTimeMax() const { return mTime + mTimeAddMax; } + GPUd() float getTimeMin() const { return mTime - mTimeSubMax; } + GPUd() short getSide() const { return mSide; } + GPUd() void setZShift(float zShift) { mZShift = zShift; } + GPUd() float getZShift() const { return mZShift; } GPUd() void resetCovariance(float s) { ResetCovariance(); } GPUd() void setAlpha(float alpha) { mAlpha = alpha; } GPUd() void set(float x, float alpha, const float param[5], const float cov[15]) @@ -383,7 +320,12 @@ class trackInterface : public GPUTPCGMTrackParam typedef GPUTPCGMTrackParam baseClass; private: - float mAlpha = 0.f; + float mAlpha = 0.f; // rotation along phi wrt global coordinate system + float mTime = -1.f; // time estimate for this track in us + float mTimeAddMax = 0.f; // max. time that can be added to this track in us + float mTimeSubMax = 0.f; // max. time that can be subtracted to this track in us + short mSide = 0; // -1 : A-side, +1 : C-side (relevant only for TPC-only tracks) + float mZShift = 0.f; // calculated new for each TRD trigger candidate for this track }; template <> diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx index 7d9f6e589b49c..0e3f49eebacd1 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx @@ -12,7 +12,6 @@ /// \author Ole Schmidt, Sergey Gorbunov #include "GPUTRDTrack.h" -#include "GPUTRDTrackData.h" using namespace GPUCA_NAMESPACE::gpu; @@ -48,26 +47,81 @@ GPUd() void GPUTRDTrack_t::Initialize() #ifdef GPUCA_ALIROOT_LIB #include "AliHLTExternalTrackParam.h" +#include "GPUTRDTrackData.h" + template GPUd() GPUTRDTrack_t::GPUTRDTrack_t(const AliHLTExternalTrackParam& t) : T(t) { Initialize(); } + +template +GPUd() void GPUTRDTrack_t::ConvertTo(GPUTRDTrackDataRecord& t) const +{ + //------------------------------------------------------------------ + // convert to GPU structure + //------------------------------------------------------------------ + t.mAlpha = T::getAlpha(); + t.fX = T::getX(); + t.fY = T::getY(); + t.fZ = T::getZ(); + t.fq1Pt = T::getQ2Pt(); + t.mSinPhi = T::getSnp(); + t.fTgl = T::getTgl(); + for (int i = 0; i < 15; i++) { + t.fC[i] = T::getCov()[i]; + } + t.fTPCTrackID = GetTPCtrackId(); + for (int i = 0; i < kNLayers; i++) { + t.fAttachedTracklets[i] = GetTracklet(i); + } +} + +template +GPUd() void GPUTRDTrack_t::ConvertFrom(const GPUTRDTrackDataRecord& t) +{ + //------------------------------------------------------------------ + // convert from GPU structure + //------------------------------------------------------------------ + T::set(t.fX, t.mAlpha, &(t.fY), t.fC); + SetTPCtrackId(t.fTPCTrackID); + mChi2 = 0.f; + mMass = 0.13957f; + mLabel = -1; + mNTracklets = 0; + mNMissingConsecLayers = 0; + mLabelOffline = -1; + mIsStopped = false; + for (int iLayer = 0; iLayer < kNLayers; iLayer++) { + mAttachedTracklets[iLayer] = t.fAttachedTracklets[iLayer]; + mIsFindable[iLayer] = 0; + if (mAttachedTracklets[iLayer] >= 0) { + mNTracklets++; + } + } + for (int j = 0; j < 4; ++j) { + mNTrackletsOffline[j] = 0; + } +} + #endif #if defined(GPUCA_O2_LIB) && !defined(GPUCA_GPUCODE) #include "ReconstructionDataFormats/TrackTPCITS.h" #include "DataFormatsTPC/TrackTPC.h" + template GPUd() GPUTRDTrack_t::GPUTRDTrack_t(const o2::dataformats::TrackTPCITS& t, float vDrift) : T(t, vDrift) { Initialize(); } + template GPUd() GPUTRDTrack_t::GPUTRDTrack_t(const o2::tpc::TrackTPC& t, float tbWidth, float vDrift, unsigned int iTrk) : T(t, tbWidth, vDrift, iTrk) { Initialize(); } + #endif template @@ -168,55 +222,6 @@ GPUd() int GPUTRDTrack_t::GetNmissingConsecLayers(int iLayer) const return res; } -template -GPUd() void GPUTRDTrack_t::ConvertTo(GPUTRDTrackDataRecord& t) const -{ - //------------------------------------------------------------------ - // convert to GPU structure - //------------------------------------------------------------------ - t.mAlpha = T::getAlpha(); - t.fX = T::getX(); - t.fY = T::getY(); - t.fZ = T::getZ(); - t.fq1Pt = T::getQ2Pt(); - t.mSinPhi = T::getSnp(); - t.fTgl = T::getTgl(); - for (int i = 0; i < 15; i++) { - t.fC[i] = T::getCov()[i]; - } - t.fTPCTrackID = GetTPCtrackId(); - for (int i = 0; i < kNLayers; i++) { - t.fAttachedTracklets[i] = GetTracklet(i); - } -} - -template -GPUd() void GPUTRDTrack_t::ConvertFrom(const GPUTRDTrackDataRecord& t) -{ - //------------------------------------------------------------------ - // convert from GPU structure - //------------------------------------------------------------------ - T::set(t.fX, t.mAlpha, &(t.fY), t.fC); - SetTPCtrackId(t.fTPCTrackID); - mChi2 = 0.f; - mMass = 0.13957f; - mLabel = -1; - mNTracklets = 0; - mNMissingConsecLayers = 0; - mLabelOffline = -1; - mIsStopped = false; - for (int iLayer = 0; iLayer < kNLayers; iLayer++) { - mAttachedTracklets[iLayer] = t.fAttachedTracklets[iLayer]; - mIsFindable[iLayer] = 0; - if (mAttachedTracklets[iLayer] >= 0) { - mNTracklets++; - } - } - for (int j = 0; j < 4; ++j) { - mNTrackletsOffline[j] = 0; - } -} - #ifndef GPUCA_GPUCODE namespace GPUCA_NAMESPACE { diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx index 83a1c84a12184..862888276fead 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx @@ -201,13 +201,13 @@ void GPUTRDTracker_t::Reset() } template -void GPUTRDTracker_t::DoTracking(GPUChainTracking* chainTracking) +void GPUTRDTracker_t::PrepareTracking(GPUChainTracking* chainTracking) { //-------------------------------------------------------------------- - // Steering function for the tracking + // Prepare tracklet index array and if requested calculate space points + // in part duplicated from DoTracking() method to allow for calling + // this function on the host prior to GPU processing //-------------------------------------------------------------------- - - // fill tracklet index array (tracklets are already sorted) for (unsigned int iColl = 0; iColl < GetConstantMem()->ioPtrs.nTRDTriggerRecords; ++iColl) { int nTrklts = 0; int idxOffset = 0; @@ -246,6 +246,16 @@ void GPUTRDTracker_t::DoTracking(GPUChainTracking* chainTracking) if (mGenerateSpacePoints) { chainTracking->mIOPtrs.trdSpacePoints = mSpacePoints; } +} + +template +void GPUTRDTracker_t::DoTracking(GPUChainTracking* chainTracking) +{ + //-------------------------------------------------------------------- + // Steering function for the tracking + //-------------------------------------------------------------------- + + PrepareTracking(chainTracking); auto timeStart = std::chrono::high_resolution_clock::now(); diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h index b9f45e541a89a..1ed22277f5d1d 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h @@ -67,6 +67,7 @@ class GPUTRDTracker_t : public GPUProcessor void* SetPointersTracks(void* base); void CountMatches(const int trackID, std::vector* matches) const; + void PrepareTracking(GPUChainTracking* chainTracking); void DoTracking(GPUChainTracking* chainTracking); void SetNCandidates(int n); void PrintSettings() const; From 1afec3a0ea5174c75de70c587d30dca1a7aef592 Mon Sep 17 00:00:00 2001 From: Ole Schmidt Date: Wed, 5 May 2021 17:58:24 +0200 Subject: [PATCH 400/770] TRD tracklets can have MC labels --- Detectors/TRD/workflow/io/src/TRDTrackletReaderSpec.cxx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Detectors/TRD/workflow/io/src/TRDTrackletReaderSpec.cxx b/Detectors/TRD/workflow/io/src/TRDTrackletReaderSpec.cxx index 741d80536d489..04229b530a285 100644 --- a/Detectors/TRD/workflow/io/src/TRDTrackletReaderSpec.cxx +++ b/Detectors/TRD/workflow/io/src/TRDTrackletReaderSpec.cxx @@ -59,7 +59,7 @@ void TRDTrackletReader::connectTree() mTreeTrklt->SetBranchAddress("Tracklet", &mTrackletsPtr); mTreeTrklt->SetBranchAddress("TrackTrg", &mTriggerRecordsPtr); if (mUseMC) { - LOG(FATAL) << "MC information not yet included for TRD tracklets"; + mTreeTrklt->SetBranchAddress("TRKLabels", &mLabelsPtr); } LOG(INFO) << "Loaded tree from " << mInFileNameTrklt << " with " << mTreeTrklt->GetEntries() << " entries"; } @@ -81,7 +81,7 @@ void TRDTrackletReader::run(ProcessingContext& pc) pc.outputs().snapshot(Output{o2::header::gDataOriginTRD, "TRKTRGRD", 0, Lifetime::Timeframe}, mTriggerRecords); if (mUseMC) { - LOG(FATAL) << "MC information not yet included for TRD tracklets"; + pc.outputs().snapshot(Output{"TRD", "TRKLABELS", 0, Lifetime::Timeframe}, mLabels); } if (mTreeTrklt->GetReadEntry() + 1 >= mTreeTrklt->GetEntries()) { @@ -99,7 +99,7 @@ DataProcessorSpec getTRDTrackletReaderSpec(bool useMC, bool useCalibratedTrackle outputs.emplace_back(o2::header::gDataOriginTRD, "TRACKLETS", 0, Lifetime::Timeframe); outputs.emplace_back(o2::header::gDataOriginTRD, "TRKTRGRD", 0, Lifetime::Timeframe); if (useMC) { - LOG(FATAL) << "MC information not yet included for TRD tracklets"; + outputs.emplace_back("TRD", "TRKLABELS", 0, Lifetime::Timeframe); } return DataProcessorSpec{ From 9d1aad9e364ac6a9eafc951e0f04c5c6045c6f1f Mon Sep 17 00:00:00 2001 From: shahoian Date: Tue, 4 May 2021 19:57:47 +0200 Subject: [PATCH 401/770] Multiple fixes for FlatHisto classes --- .../include/CommonDataFormat/FlatHisto1D.h | 148 +++++------- .../include/CommonDataFormat/FlatHisto2D.h | 226 +++++++----------- DataFormats/common/src/FlatHisto1D.cxx | 91 ++++++- DataFormats/common/src/FlatHisto2D.cxx | 132 ++++++++++ DataFormats/common/test/testFlatHisto.cxx | 16 +- 5 files changed, 386 insertions(+), 227 deletions(-) diff --git a/DataFormats/common/include/CommonDataFormat/FlatHisto1D.h b/DataFormats/common/include/CommonDataFormat/FlatHisto1D.h index 18407f295cbf4..21d5d21c6b15a 100644 --- a/DataFormats/common/include/CommonDataFormat/FlatHisto1D.h +++ b/DataFormats/common/include/CommonDataFormat/FlatHisto1D.h @@ -18,8 +18,11 @@ #include #include #include -#include #include +#include +#include + +class TH1F; namespace o2 { @@ -50,34 +53,39 @@ class FlatHisto1D XMin, XMax, BinSize, - BinSizeInv, NServiceSlots }; FlatHisto1D() = default; + FlatHisto1D(int nb, T xmin, T xmax); + FlatHisto1D(const gsl::span ext) { adoptExternal(ext); } + void adoptExternal(const gsl::span ext); + void init() + { + // when reading from file, need to call this method to make it operational + assert(mContainer.size() > NServiceSlots); + init(gsl::span(mContainer.data(), mContainer.size())); + } - FlatHisto1D(int nb, T xmin, T xmax) + int getNBins() const { return mNBins; } + T getXMin() const { return mXMin; } + T getXMax() const { return mXMax; } + T getBinSize() const { return mBinSize; } + T getBinSizeInv() const { return mBinSizeInv; } + + T getBinContent(uint32_t ib) const { - assert(nb > 0 && xmin < xmax); - mData.resize(nb + NServiceSlots, 0.); - mData[NBins] = nb; - mData[XMin] = xmin; - mData[XMax] = xmax; - mData[BinSize] = (xmax - xmin) / nb; - mData[BinSizeInv] = nb / (xmax - xmin); - init(); + assert(ib < getNBins()); + return mDataPtr[ib]; } - FlatHisto1D(const gsl::span ext) + T getBinContentForX(T x) const { - adoptExternal(ext); + auto bin = getBin(x); + return isValidBin(bin) ? getBinContent(bin) : 0; } - int getNBins() const { return mNBins; } - T getXMin() const { return mDataView[XMin]; } - T getXMax() const { return mDataView[XMax]; } - T getBinSize() const { return mDataView[BinSize]; } - T getBinContent(uint32_t ib) const { return ib < mNBins ? mDataView[ib + NServiceSlots] : 0.; } - T getBinContentForX(T x) const { getBinContent(getBin(x)); } + bool isValidBin(uint32_t bin) const { return bin < getNBins(); } + bool isBinEmpty(uint32_t bin) const { return getBinContent(bin) == 0; } T getBinStart(int i) const { @@ -97,75 +105,48 @@ class FlatHisto1D return getXMin() + (i + 1) * getBinSize(); } - void add(const FlatHisto1D& other) - { - assert(getNBins() == other.getNBins() && getXMin() == other.getXMin() && getXMax() == other.getXMax() && canFill()); - int last = NServiceSlots + getNBins(); - const auto& otherView = other.getView(); - for (int i = NServiceSlots; i < last; i++) { - mData[i] += otherView[i]; - } - } + void add(const FlatHisto1D& other); - void subtract(const FlatHisto1D& other) - { - assert(getNBins() == other.getNBins() && getXMin() == other.getXMin() && getXMax() == other.getXMax() && canFill()); - int last = NServiceSlots + getNBins(); - const auto& otherView = other.getView(); - for (int i = NServiceSlots; i < last; i++) { - mData[i] -= otherView[i]; - } - } + void subtract(const FlatHisto1D& other); void setBinContent(uint32_t bin, T w) { - assert(canFill() && bin < mNBins); - mData[bin + NServiceSlots] = w; + assert(canFill() && isValidBin(bin)); + mDataPtr[bin] = w; } void clear() { assert(canFill()); - memset(mData.data() + NServiceSlots, 0, sizeof(T) * getNBins()); + memset(mDataPtr, 0, sizeof(T) * getNBins()); } - T getSum() const - { - T sum = 0; - for (int i = getNBins(); i--;) { - sum += getBinContent(i); - } - return sum; - } + T getSum() const; - void adoptExternal(const gsl::span ext) + int fill(T x) { - assert(ext.size() > NServiceSlots); - mData.clear(); - mDataView = ext; - mNBins = (int)mDataView[NBins]; - } - - void init() - { // when reading from file, need to call this method to make it operational - assert(mData.size() > NServiceSlots); - mDataView = gsl::span(mData.data(), mData.size()); - mNBins = (int)mData[NBins]; + uint32_t bin = getBin(x); + if (isValidBin(bin)) { + mDataPtr[bin]++; + return bin; + } + return -1; } - void fill(T x) + int fill(T x, T w) { uint32_t bin = getBin(x); - if (bin < mNBins) { - mData[NServiceSlots + bin]++; + if (isValidBin(bin)) { + mDataPtr[bin] += w; + return bin; } + return -1; } - void fill(T x, T w) + void fillBin(uint32_t bin, T w) { - uint32_t bin = getBin(x); - if (bin < mNBins) { - mData[NServiceSlots + bin] += w; + if (isValidBin(bin)) { + mDataPtr[bin] += w; } } @@ -178,30 +159,25 @@ class FlatHisto1D bool canFill() const { // histo can be filled only if hase its own data, otherwise only query can be done on the view - return mData.size() > NServiceSlots; + return mContainer.size() > NServiceSlots; } - TH1F createTH1F(const std::string& name = "histo1d") - { - TH1F h(name.c_str(), name.c_str(), getNBins(), getXMin(), getXMax()); - for (int i = getNBins(); i--;) { - auto w = getBinContent(i); - if (w) { - h.SetBinContent(i + 1, w); - } - } - return h; - } + std::unique_ptr createTH1F(const std::string& name = "histo1d"); - const std::vector& getBase() const { return mData; } - gsl::span getView() const { return mDataView; } + const std::vector& getBase() const { return mContainer; } + gsl::span getView() const { return mContainerView; } protected: - T getBinSizeInv() const { return mDataView[BinSizeInv]; } - - std::vector mData; // data to fill - gsl::span mDataView; //! - int mNBins = 0; //! + void init(const gsl::span ext); + + std::vector mContainer; // global container + gsl::span mContainerView{}; //! pointer on container + T* mDataPtr{}; //! histo data + T mXMin{}; //! + T mXMax{}; //! + T mBinSize{}; //! + T mBinSizeInv{}; //! + int mNBins{}; //! ClassDefNV(FlatHisto1D, 1); }; diff --git a/DataFormats/common/include/CommonDataFormat/FlatHisto2D.h b/DataFormats/common/include/CommonDataFormat/FlatHisto2D.h index 8da1daf658162..e6db141deb59e 100644 --- a/DataFormats/common/include/CommonDataFormat/FlatHisto2D.h +++ b/DataFormats/common/include/CommonDataFormat/FlatHisto2D.h @@ -18,8 +18,12 @@ #include #include #include -#include #include +#include +#include + +class TH1F; +class TH2F; namespace o2 { @@ -54,172 +58,140 @@ class FlatHisto2D YMax, BinSizeX, BinSizeY, - BinSizeXInv, - BinSizeYInv, NServiceSlots }; FlatHisto2D() = default; - - FlatHisto2D(int nbx, T xmin, T xmax, int nby, T ymin, T ymax) + FlatHisto2D(int nbx, T xmin, T xmax, int nby, T ymin, T ymax); + FlatHisto2D(const gsl::span ext) { adoptExternal(ext); } + void adoptExternal(const gsl::span ext); + void init() { - assert(nbx > 0 && xmin < xmax); - assert(nby > 0 && ymin < ymax); - mData.resize(nbx * nby + NServiceSlots, 0.); - mData[NBinsX] = nbx; - mData[NBinsY] = nby; - mData[XMin] = xmin; - mData[XMax] = xmax; - mData[YMin] = ymin; - mData[YMax] = ymax; - mData[BinSizeX] = (xmax - xmin) / nbx; - mData[BinSizeXInv] = nbx / (xmax - xmin); - mData[BinSizeY] = (ymax - ymin) / nby; - mData[BinSizeYInv] = nby / (ymax - ymin); - init(); + // when reading from file, need to call this method to make it operational + assert(mContainer.size() > NServiceSlots); + init(gsl::span(mContainer.data(), mContainer.size())); } - FlatHisto2D(const gsl::span ext) + int getNBinsX() const { return mNBinsX; } + int getNBinsY() const { return mNBinsY; } + int getNBins() const { return getNBinsX() * getNBinsY(); } + + T getXMin() const { return mXMin; } + T getXMax() const { return mXMax; } + T getYMin() const { return mYMin; } + T getYMax() const { return mYMax; } + T getBinSizeX() const { return mBinSizeX; } + T getBinSizeY() const { return mBinSizeY; } + T getBinSizeXInv() const { return mBinSizeXInv; } + T getBinSizeYInv() const { return mBinSizeYInv; } + + T getBinContent(uint32_t ib) const { - adoptExternal(ext); + assert(ib < getNBins()); + return mDataPtr[ib]; } - int getNBinsX() const { return mNBinsX; } - int getNBinsY() const { return mNBinsY; } - int getNBins() const { return mNBins; } - T getXMin() const { return mDataView[XMin]; } - T getXMax() const { return mDataView[XMax]; } - T getYMin() const { return mDataView[YMin]; } - T getYMax() const { return mDataView[YMax]; } - T getBinSizeX() const { return mDataView[BinSizeX]; } - T getBinSizeY() const { return mDataView[BinSizeY]; } - T getBinContent(uint32_t ib) const { return ib < mNBins ? mDataView[ib + NServiceSlots] : 0.; } T getBinContent(uint32_t ibx, uint32_t iby) const { return getBinContent(getGlobalBin(ibx, iby)); } + T getBinContentForXY(T x, T y) const { return getBinContent(getBinX(x), getBinY(y)); } - T getBinStartX(int i) const + bool isValidBin(uint32_t bin) const { return bin < getNBins(); } + bool isBinEmpty(uint32_t bin) const { return getBinContent(bin) == 0; } + + T getBinXStart(int i) const { assert(i < getNBinsX()); return getXMin() + i * getBinSizeX(); } - T getBinCenterX(int i) const + T getBinXCenter(int i) const { assert(i < getNBinsX()); return getXMin() + (i + 0.5) * getBinSizeX(); } - T getBinEndX(int i) const + T getBinXEnd(int i) const { assert(i < getNBinsX()); return getXMin() + (i + 1) * getBinSizeX(); } - T getBinStartY(int i) const + T getBinYStart(int i) const { assert(i < getNBinsY()); return getYMin() + i * getBinSizeY(); } - T getBinCenterY(int i) const + T getBinYCenter(int i) const { assert(i < getNBinsY()); return getYMin() + (i + 0.5) * getBinSizeY(); } - T getBinEndY(int i) const + T getBinYEnd(int i) const { assert(i < getNBinsY()); return getYMin() + (i + 1) * getBinSizeY(); } - void add(const FlatHisto2D& other) - { - assert(getNBinsX() == other.getNBinsX() && getXMin() == other.getXMin() && getXMax() == other.getXMax() && - getNBinsY() == other.getNBinsY() && getYMin() == other.getYMin() && getYMax() == other.getYMax() && - canFill()); - int last = NServiceSlots + getNBins(); - const auto& otherView = other.getView(); - for (int i = NServiceSlots; i < last; i++) { - mData[i] += otherView[i]; - } - } + int getXBin(uint32_t i) const { return i / getNBinsY(); } + int getYBin(uint32_t i) const { return i % getNBinsY(); } - void subtract(const FlatHisto2D& other) - { - assert(getNBinsX() == other.getNBinsX() && getXMin() == other.getXMin() && getXMax() == other.getXMax() && - getNBinsY() == other.getNBinsY() && getYMin() == other.getYMin() && getYMax() == other.getYMax() && - canFill()); - int last = NServiceSlots + getNBins(); - const auto& otherView = other.getView(); - for (int i = NServiceSlots; i < last; i++) { - mData[i] -= otherView[i]; - } - } + void add(const FlatHisto2D& other); + + void subtract(const FlatHisto2D& other); void setBinContent(uint32_t bin, T w) { - assert(canFill()); - if (bin < getNBins()) { - mData[bin + NServiceSlots] = w; - } + assert(canFill() && isValidBin(bin)); + mDataPtr[bin] = w; } void setBinContent(uint32_t binX, uint32_t binY, T w) { - assert(canFill()); auto bin = getGlobalBin(binX, binY); - if (bin < getNBins()) { - mData[+NServiceSlots] = w; - } + setBinContent(bin, w); } void clear() { assert(canFill()); - memset(mData.data() + NServiceSlots, 0, sizeof(T) * getNBins()); + memset(mDataPtr, 0, sizeof(T) * getNBins()); } - T getSum() const + T getSum() const; + + int fill(T x, T y) { - T sum = 0; - for (int i = getNBins(); i--;) { - sum += getBinContent(i); + uint32_t bin = getBin(x, y); + if (isValidBin(bin)) { + mDataPtr[bin]++; + return bin; } - return sum; + return -1; } - void adoptExternal(const gsl::span ext) + int fill(T x, T y, T w) { - assert(ext.size() > NServiceSlots); - mData.clear(); - mDataView = ext; - mNBinsX = (int)mDataView[NBinsX]; - mNBinsY = (int)mDataView[NBinsY]; - mNBins = mNBinsX * mNBinsY; - } - - void init() - { // when reading from file, need to call this method to make it operational - assert(mData.size() > NServiceSlots); - mDataView = gsl::span(mData.data(), mData.size()); - mNBinsX = (int)mData[NBinsX]; - mNBinsY = (int)mData[NBinsY]; - mNBins = mNBinsX * mNBinsY; + uint32_t bin = getBin(x, y); + if (isValidBin(bin)) { + mDataPtr[bin] += w; + return bin; + } + return -1; } - void fill(T x, T y) + void fillBin(uint32_t bin, T w) { - uint32_t bin = getBin(x, y); - if (bin < mNBins) { - mData[NServiceSlots + bin]++; + if (isValidBin(bin)) { + mDataPtr[bin] += w; } } - void fill(T x, T y, T w) + void fillBin(uint32_t bx, uint32_t by, T w) { - uint32_t bin = getBin(x, y); - if (bin < mNBins) { - mData[NServiceSlots + bin] += w; + auto bin = getGlobalBin(bx, by); + if (isValidBin(bin)) { + mDataPtr[bin] += w; } } @@ -244,54 +216,42 @@ class FlatHisto2D bool canFill() const { // histo can be filled only if hase its own data, otherwise only query can be done on the view - return mData.size() > NServiceSlots; + return mContainer.size() > NServiceSlots; } gsl::span getSliceY(uint32_t binX) const { - int offs = NServiceSlots + binX * getNBinsY(); - return binX < getNBinsX() ? gsl::span(&mDataView[offs], getNBinsY()) : gsl::span(); + int offs = binX * getNBinsY(); + return binX < getNBinsX() ? gsl::span(&mDataPtr[offs], getNBinsY()) : gsl::span(); } - TH1F createSliceYTH1F(uint32_t binX, const std::string& name = "histo2dslice") const - { - TH1F h(name.c_str(), name.c_str(), getNBinsY(), getYMin(), getYMax()); - if (binX < getNBinsX()) { - for (int i = getNBinsY(); i--;) { - h.SetBinContent(i + 1, getBinContent(binX, i)); - } - } - return h; - } + std::unique_ptr createTH2F(const std::string& name = "histo2d"); - TH2F createTH2F(const std::string& name = "histo2d") - { - TH2F h(name.c_str(), name.c_str(), getNBinsX(), getXMin(), getXMax(), getNBinsY(), getYMin(), getYMax()); - for (int i = getNBinsX(); i--;) { - for (int j = getNBinsY(); j--;) { - auto w = getBinContent(i, j); - if (w) { - h.SetBinContent(i + 1, j + 1, w); - } - } - } - return h; - } + std::unique_ptr createSliceXTH1F(uint32_t binX, const std::string& name = "histo2dsliceX") const; + std::unique_ptr createSliceYTH1F(uint32_t binX, const std::string& name = "histo2dsliceY") const; - const std::vector& getBase() const { return mData; } - gsl::span getView() const { return mDataView; } + const std::vector& getBase() const { return mContainer; } + gsl::span getView() const { return mContainerView; } int getGlobalBin(uint32_t binX, uint32_t binY) const { return binX * getNBinsY() + binY; } protected: - T getBinSizeXInv() const { return mDataView[BinSizeXInv]; } - T getBinSizeYInv() const { return mDataView[BinSizeYInv]; } - - std::vector mData; // data to fill - gsl::span mDataView; //! - int mNBinsX = 0; //! - int mNBinsY = 0; //! - int mNBins = 0; //! + void init(const gsl::span ext); + + std::vector mContainer; // data to fill + gsl::span mContainerView; //! + T* mDataPtr{}; //! histo data + T mXMin{}; //! + T mXMax{}; //! + T mYMin{}; //! + T mYMax{}; //! + T mBinSizeX{}; //! + T mBinSizeY{}; //! + T mBinSizeXInv{}; //! + T mBinSizeYInv{}; //! + int mNBinsX{}; //! + int mNBinsY{}; //! + int mNBins{}; //! ClassDefNV(FlatHisto2D, 1); }; diff --git a/DataFormats/common/src/FlatHisto1D.cxx b/DataFormats/common/src/FlatHisto1D.cxx index 0b59cd2b8259d..e9ff348fbe6de 100644 --- a/DataFormats/common/src/FlatHisto1D.cxx +++ b/DataFormats/common/src/FlatHisto1D.cxx @@ -13,5 +13,94 @@ /// \author ruben.shahoyan@cern.ch #include "CommonDataFormat/FlatHisto1D.h" +#include -using namespace o2::dataformats; +namespace o2 +{ +namespace dataformats +{ + +template +FlatHisto1D::FlatHisto1D(int nb, T xmin, T xmax) +{ + assert(nb > 0 && xmin < xmax); + mContainer.resize(nb + NServiceSlots, 0.); + mContainer[NBins] = nb; + mContainer[XMin] = xmin; + mContainer[XMax] = xmax; + mContainer[BinSize] = (xmax - xmin) / nb; + init(gsl::span(mContainer.data(), mContainer.size())); +} + +template +void FlatHisto1D::adoptExternal(const gsl::span ext) +{ + assert(ext.size() > NServiceSlots); + mContainer.clear(); + mContainerView = ext; + init(mContainerView); +} + +template +void FlatHisto1D::add(const FlatHisto1D& other) +{ + if (!(getNBins() == other.getNBins() && getXMin() == other.getXMin() && getXMax() == other.getXMax() && canFill())) { + throw std::runtime_error("adding incompatible histos or destination histo is const"); + } + for (int i = getNBins(); i--;) { + mDataPtr[i] += other.mDataPtr[i]; + } +} + +template +void FlatHisto1D::subtract(const FlatHisto1D& other) +{ + if (!(getNBins() == other.getNBins() && getXMin() == other.getXMin() && getXMax() == other.getXMax() && canFill())) { + throw std::runtime_error("subtracting incompatible histos or destination histo is const"); + } + for (int i = getNBins(); i--;) { + mDataPtr[i] -= other.mDataPtr[i]; + } +} + +template +T FlatHisto1D::getSum() const +{ + T sum = 0; + for (int i = getNBins(); i--;) { + sum += getBinContent(i); + } + return sum; +} + +template +void FlatHisto1D::init(const gsl::span ext) +{ // when reading from file, need to call this method to make it operational + assert(ext.size() > NServiceSlots); + mContainerView = ext; + mDataPtr = const_cast(&ext[NServiceSlots]); + mNBins = (int)ext[NBins]; + mXMin = ext[XMin]; + mXMax = ext[XMax]; + mBinSize = ext[BinSize]; + mBinSizeInv = 1. / mBinSize; +} + +template +std::unique_ptr FlatHisto1D::createTH1F(const std::string& name) +{ + auto h = std::make_unique(name.c_str(), name.c_str(), getNBins(), getXMin(), getXMax()); + for (int i = getNBins(); i--;) { + auto w = getBinContent(i); + if (w) { + h->SetBinContent(i + 1, w); + } + } + return std::move(h); +} + +template class FlatHisto1D; +template class FlatHisto1D; + +} // namespace dataformats +} // namespace o2 \ No newline at end of file diff --git a/DataFormats/common/src/FlatHisto2D.cxx b/DataFormats/common/src/FlatHisto2D.cxx index 3266a23b81fd3..cea96d3c1a502 100644 --- a/DataFormats/common/src/FlatHisto2D.cxx +++ b/DataFormats/common/src/FlatHisto2D.cxx @@ -13,5 +13,137 @@ /// \author ruben.shahoyan@cern.ch #include "CommonDataFormat/FlatHisto2D.h" +#include +#include + +namespace o2 +{ +namespace dataformats +{ using namespace o2::dataformats; + +template +FlatHisto2D::FlatHisto2D(int nbx, T xmin, T xmax, int nby, T ymin, T ymax) +{ + assert(nbx > 0 && xmin < xmax); + assert(nby > 0 && ymin < ymax); + mContainer.resize(nbx * nby + NServiceSlots, 0.); + mContainer[NBinsX] = nbx; + mContainer[NBinsY] = nby; + mContainer[XMin] = xmin; + mContainer[XMax] = xmax; + mContainer[YMin] = ymin; + mContainer[YMax] = ymax; + mContainer[BinSizeX] = (xmax - xmin) / nbx; + mContainer[BinSizeY] = (ymax - ymin) / nby; + init(gsl::span(mContainer.data(), mContainer.size())); +} + +template +void FlatHisto2D::adoptExternal(const gsl::span ext) +{ + assert(ext.size() > NServiceSlots); + mContainer.clear(); + mContainerView = ext; + init(mContainerView); +} + +template +void FlatHisto2D::add(const FlatHisto2D& other) +{ + if (!(getNBinsX() == other.getNBinsX() && getXMin() == other.getXMin() && getXMax() == other.getXMax() && + getNBinsY() == other.getNBinsY() && getYMin() == other.getYMin() && getYMax() == other.getYMax() && + canFill())) { + throw std::runtime_error("adding incompatible histos or destination histo is const"); + } + for (int i = getNBins(); i--;) { + mDataPtr[i] += other.mDataPtr[i]; + } +} + +template +void FlatHisto2D::subtract(const FlatHisto2D& other) +{ + if (!(getNBinsX() == other.getNBinsX() && getXMin() == other.getXMin() && getXMax() == other.getXMax() && + getNBinsY() == other.getNBinsY() && getYMin() == other.getYMin() && getYMax() == other.getYMax() && + canFill())) { + throw std::runtime_error("subtracting incompatible histos or destination histo is const"); + } + for (int i = getNBins(); i--;) { + mDataPtr[i] -= other.mDataPtr[i]; + } +} + +template +T FlatHisto2D::getSum() const +{ + T sum = 0; + for (int i = getNBins(); i--;) { + sum += getBinContent(i); + } + return sum; +} + +template +void FlatHisto2D::init(const gsl::span ext) +{ // when reading from file, need to call this method to make it operational + assert(ext.size() > NServiceSlots); + mContainerView = ext; + mDataPtr = const_cast(&ext[NServiceSlots]); + mNBinsX = (int)ext[NBinsX]; + mNBinsY = (int)ext[NBinsY]; + mXMin = ext[XMin]; + mXMax = ext[XMax]; + mYMin = ext[YMin]; + mYMax = ext[YMax]; + mBinSizeX = ext[BinSizeX]; + mBinSizeY = ext[BinSizeY]; + mBinSizeXInv = 1. / mBinSizeX; + mBinSizeYInv = 1. / mBinSizeY; +} + +template +std::unique_ptr FlatHisto2D::createTH2F(const std::string& name) +{ + auto h = std::make_unique(name.c_str(), name.c_str(), getNBinsX(), getXMin(), getXMax(), getNBinsY(), getYMin(), getYMax()); + for (int i = getNBinsX(); i--;) { + for (int j = getNBinsY(); j--;) { + auto w = getBinContent(i, j); + if (w) { + h->SetBinContent(i + 1, j + 1, w); + } + } + } + return std::move(h); +} + +template +std::unique_ptr FlatHisto2D::createSliceYTH1F(uint32_t binX, const std::string& name) const +{ + auto h = std::make_unique(name.c_str(), name.c_str(), getNBinsY(), getYMin(), getYMax()); + if (binX < getNBinsX()) { + for (int i = getNBinsY(); i--;) { + h->SetBinContent(i + 1, getBinContent(binX, i)); + } + } + return h; +} + +template +std::unique_ptr FlatHisto2D::createSliceXTH1F(uint32_t binY, const std::string& name) const +{ + auto h = std::make_unique(name.c_str(), name.c_str(), getNBinsX(), getXMin(), getXMax()); + if (binY < getNBinsY()) { + for (int i = getNBinsX(); i--;) { + h->SetBinContent(i + 1, getBinContent(i, binY)); + } + } + return h; +} + +template class FlatHisto2D; +template class FlatHisto2D; + +} // namespace dataformats +} // namespace o2 \ No newline at end of file diff --git a/DataFormats/common/test/testFlatHisto.cxx b/DataFormats/common/test/testFlatHisto.cxx index d1f9a56cdfd05..44ae3b3c2a520 100644 --- a/DataFormats/common/test/testFlatHisto.cxx +++ b/DataFormats/common/test/testFlatHisto.cxx @@ -17,6 +17,8 @@ #include #include #include +#include +#include namespace o2 { @@ -33,23 +35,23 @@ BOOST_AUTO_TEST_CASE(FlatHisto) for (int i = 0; i < 10000000; i++) { auto x = gRandom->Gaus(10, 40), y = gRandom->Gaus(10, 10); h2.fill(x, y); - h2ref.Fill(x, y); + h2ref->Fill(x, y); } auto th1f = h1.createTH1F(); - auto res = th1f.Fit("gaus", "S"); + auto res = th1f->Fit("gaus", "S"); BOOST_CHECK_CLOSE(res->GetParams()[1], 10, 0.2); - printf("%e %e\n", h2.getSum(), h2ref.Integral()); - BOOST_CHECK(h2.getSum() == h2ref.Integral()); + printf("%e %e\n", h2.getSum(), h2ref->Integral()); + BOOST_CHECK(h2.getSum() == h2ref->Integral()); o2::dataformats::FlatHisto1D_f h1v(h1); BOOST_CHECK_CLOSE(h1.getBinStart(0), -100, 1e-5); BOOST_CHECK_CLOSE(h1.getBinEnd(h1.getNBins() - 1), 100, 1e-5); - BOOST_CHECK_CLOSE(h2.getBinStartX(0), -100, 1e-5); - BOOST_CHECK_CLOSE(h2.getBinEndY(h2.getNBinsY() - 1), 45, 1e-5); - BOOST_CHECK_CLOSE(h2.getBinStartY(h2.getNBinsY() - 1), 45 - h2.getBinSizeY(), 1e-5); + BOOST_CHECK_CLOSE(h2.getBinXStart(0), -100, 1e-5); + BOOST_CHECK_CLOSE(h2.getBinYEnd(h2.getNBinsY() - 1), 45, 1e-5); + BOOST_CHECK_CLOSE(h2.getBinYStart(h2.getNBinsY() - 1), 45 - h2.getBinSizeY(), 1e-5); BOOST_CHECK(h1.canFill() && h1v.canFill()); BOOST_CHECK(h1.getSum() == h1v.getSum()); From 8b7ce4f75940df861518d209863a449fb5957f70 Mon Sep 17 00:00:00 2001 From: shahoian Date: Wed, 5 May 2021 03:27:12 +0200 Subject: [PATCH 402/770] Improve P-vertex seeding, add debris reduction, optional debug output --- .../src/PrimaryVertexingSpec.cxx | 1 + .../include/DetectorsVertexing/PVertexer.h | 45 ++- .../DetectorsVertexing/PVertexerHelpers.h | 112 +++---- .../DetectorsVertexing/PVertexerParams.h | 23 +- .../Vertexing/src/DetectorsVertexingLinkDef.h | 6 + Detectors/Vertexing/src/PVertexer.cxx | 276 ++++++++++++++---- Detectors/Vertexing/src/PVertexerHelpers.cxx | 21 ++ 7 files changed, 343 insertions(+), 141 deletions(-) diff --git a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx index 9b64096768e77..186296cdc2cb2 100644 --- a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx @@ -166,6 +166,7 @@ void PrimaryVertexingSpec::run(ProcessingContext& pc) void PrimaryVertexingSpec::endOfStream(EndOfStreamContext& ec) { + mVertexer.end(); LOGF(INFO, "Primary vertexing total timing: Cpu: %.3e Real: %.3e s in %d slots", mTimer.CpuTime(), mTimer.RealTime(), mTimer.Counter() - 1); } diff --git a/Detectors/Vertexing/include/DetectorsVertexing/PVertexer.h b/Detectors/Vertexing/include/DetectorsVertexing/PVertexer.h index 9dc6d53c05cc3..a97523cef8fef 100644 --- a/Detectors/Vertexing/include/DetectorsVertexing/PVertexer.h +++ b/Detectors/Vertexing/include/DetectorsVertexing/PVertexer.h @@ -31,6 +31,12 @@ #include "ReconstructionDataFormats/GlobalTrackID.h" #include "gsl/span" #include +#include +#include + +//TODO: MeanVertex and parameters input from CCDB + +//#define _PV_DEBUG_TREE_ // if enabled, produce dbscan and vertex comparison dump namespace o2 { @@ -50,18 +56,13 @@ class PVertexer OK }; void init(); + void end(); template int process(const TR& tracks, const gsl::span gids, const gsl::span bcData, std::vector& vertices, std::vector& vertexTrackIDs, std::vector& v2tRefs, const gsl::span lblTracks, std::vector& lblVtx); - int runVertexing(gsl::span gids, const gsl::span bcData, - std::vector& vertices, std::vector& vertexTrackIDs, std::vector& v2tRefs, - gsl::span lblTracks, std::vector& lblVtx); - - static void createMCLabels(gsl::span lblTracks, const std::vector vertices, - const std::vector trackIDs, const std::vector v2tRefs, std::vector& lblVtx); bool findVertex(const VertexingInput& input, PVertex& vtx); void setStartIR(const o2::InteractionRecord& ir) { mStartIR = ir; } ///< set InteractionRecods for the beginning of the TF @@ -72,7 +73,6 @@ class PVertexer } float getTukey() const; - void finalizeVertex(const VertexingInput& input, const PVertex& vtx, std::vector& vertices, std::vector& v2tRefs, std::vector& trackIDs, SeedHisto& histo); bool setCompatibleIR(PVertex& vtx); void setBunchFilling(const o2::BunchFilling& bf); @@ -92,16 +92,17 @@ class PVertexer initMeanVertexConstraint(); } - float estimateScale2() - { - auto sc = mPVParams->zHistoBinSize * mPVParams->zHistoBinSize * mTukey2I / (mStatZErr.getMean() * mStatZErr.getMean()); - return sc; - } - private: static constexpr int DBS_UNDEF = -2, DBS_NOISE = -1, DBS_INCHECK = -10; + SeedHistoTZ buildHistoTZ(const VertexingInput& input); + int runVertexing(gsl::span gids, const gsl::span bcData, + std::vector& vertices, std::vector& vertexTrackIDs, std::vector& v2tRefs, + gsl::span lblTracks, std::vector& lblVtx); + static void createMCLabels(gsl::span lblTracks, const std::vector& trackIDs, const std::vector& v2tRefs, std::vector& lblVtx); + void reduceDebris(std::vector& vertices, std::vector& timeSort, const std::vector& lblVtx); FitStatus fitIteration(const VertexingInput& input, VertexSeed& vtxSeed); + void finalizeVertex(const VertexingInput& input, const PVertex& vtx, std::vector& vertices, std::vector& v2tRefs, std::vector& trackIDs, SeedHistoTZ& histo); void accountTrack(TrackVF& trc, VertexSeed& vtxSeed) const; bool solveVertex(VertexSeed& vtxSeed) const; FitStatus evalIterations(VertexSeed& vtxSeed, PVertex& vtx) const; @@ -120,6 +121,7 @@ class PVertexer int dbscan_RangeQuery(int idxs, std::vector& cand, std::vector& status); void dbscan_clusterize(); + void doDBScanDump(const VertexingInput& input, const gsl::span gids, gsl::span lblTracks); o2::BunchFilling mBunchFilling; std::array mClosestBunchAbove; // closest filled bunch from above @@ -147,6 +149,17 @@ class PVertexer static constexpr float kAlmost0F = 1e-12; ///< tiny float static constexpr double kAlmost0D = 1e-16; ///< tiny double +#ifdef _PV_DEBUG_TREE_ + std::unique_ptr mDebugDumpFile; + std::unique_ptr mDebugDBScanTree; + std::unique_ptr mDebugVtxCompTree; + std::vector mDebugDumpTrc; + std::vector mDebugDumpGID; + std::vector mDebugDumpTrcMC; + std::vector mDebugDumpPVComp; + std::vector mDebugDumpPVCompLbl0; // for some reason the added as a class member + std::vector mDebugDumpPVCompLbl1; // gets stored as simple uint +#endif }; //___________________________________________________________________ @@ -193,7 +206,11 @@ void PVertexer::createTracksPool(const TR& tracks, gsl::span mPVParams->pullIniCut) { continue; } - auto& tvf = mTracksPool.emplace_back(trc, tracks[i].getTimeMUS(), i); + + // if (std::abs(tracks[i].getTimeMUS().getTimeStamp() - 732.) > 11.) + // continue; // RS TMP + + auto& tvf = mTracksPool.emplace_back(trc, tracks[i].getTimeMUS(), i, mPVParams->addTimeSigma2, mPVParams->addZSigma2); mStatZErr.add(std::sqrt(trc.getSigmaZ2())); mStatTErr.add(tvf.timeEst.getTimeStampError()); } diff --git a/Detectors/Vertexing/include/DetectorsVertexing/PVertexerHelpers.h b/Detectors/Vertexing/include/DetectorsVertexing/PVertexerHelpers.h index 7d1a243de4924..60ae2eea188b7 100644 --- a/Detectors/Vertexing/include/DetectorsVertexing/PVertexerHelpers.h +++ b/Detectors/Vertexing/include/DetectorsVertexing/PVertexerHelpers.h @@ -21,6 +21,8 @@ #include "ReconstructionDataFormats/VtxTrackIndex.h" #include "ReconstructionDataFormats/VtxTrackRef.h" #include "CommonDataFormat/TimeStamp.h" +#include "CommonDataFormat/FlatHisto2D.h" +#include "SimulationDataFormat/MCEventLabel.h" namespace o2 { @@ -103,8 +105,9 @@ struct TrackVF { TimeEst timeEst; float wgh = 0.; ///< track weight wrt current vertex seed + float wghHisto = 0.; // weight based on track errors, used for histogramming int entry; ///< track entry in the input vector - int16_t bin = -1; // seeds histo bin + int32_t bin = -1; // seeds histo bin uint8_t flags = 0; int vtxID = kNoVtx; ///< assigned vertex // @@ -150,7 +153,7 @@ struct TrackVF { } TrackVF() = default; - TrackVF(const o2::track::TrackParCov& src, const TimeEst& t_est, int _entry) + TrackVF(const o2::track::TrackParCov& src, const TimeEst& t_est, int _entry, float addHTErr2 = 0., float addHZErr2 = 0.) : x(src.getX()), y(src.getY()), z(src.getZ()), tgL(src.getTgl()), tgP(src.getSnp() / std::sqrt(1. - src.getSnp()) * (1. + src.getSnp())), timeEst(t_est), entry(_entry) { o2::math_utils::sincos(src.getAlpha(), sinAlp, cosAlp); @@ -159,6 +162,7 @@ struct TrackVF { sig2YI = src.getSigmaZ2() * detI; sig2ZI = src.getSigmaY2() * detI; sigYZI = -src.getSigmaZY() * detI; + wghHisto = 1. / ((src.getSigmaZ2() + addHZErr2) * (t_est.getTimeStampError() * t_est.getTimeStampError() + addHTErr2)); } }; @@ -170,84 +174,33 @@ struct VertexingInput { bool fillErrors = true; }; -struct SeedHisto { - float range = 20; - float binSize = 0.5; - float binSizeInv = 0.; - int nFilled = 0; - std::vector data; +struct SeedHistoTZ : public o2::dataformats::FlatHisto2D_f { + using o2::dataformats::FlatHisto2D::FlatHisto2D; - SeedHisto() = delete; - SeedHisto(float _range = 20., float _binsize = 0.5) : range(_range), binSize(_binsize) + int fillAndFlagBin(float x, float y, float w) { - auto zr = 2 * range; - int nzb = zr / binSize; - if (nzb * binSize < zr - 1e-9) { - nzb++; - } - binSizeInv = 1. / binSize; - range = nzb * binSize / 2.; - data.resize(nzb); - } - - int size() const { return data.size(); } - - void fill(float z) - { - incrementBin(findBin(z)); - } - - void incrementBin(int bin) - { - data[bin]++; - nFilled++; - } - - void decrementBin(int bin) - { - data[bin]--; - nFilled--; - } - - int findBin(float z) - { - auto d = z + range; - if (d < 0.) { - return 0; - } - uint32_t n = d * binSizeInv; - return n < data.size() ? n : data.size() - 1; - } - - int findHighestPeakBin() const - { - if (nFilled < 2) { - return -1; - } - int n = data.size(), maxBin = -1, maxv = 0; - for (int i = 0; i < n; i++) { - if (data[i] > maxv) { - maxv = data[(maxBin = i)]; + uint32_t bin = getBin(x, y); + if (isValidBin(bin)) { + if (isBinEmpty(bin)) { + filledBins.push_back(bin); } + fillBin(bin, w); + nEntries++; + return bin; } - return maxBin; + return -1; } - bool isValidBin(int ib) const + void clear() { - return static_cast(ib) < data.size(); + o2::dataformats::FlatHisto2D::clear(); + filledBins.clear(); } - float getBinCenter(int ib) const - { - return (ib + 0.5) * binSize - range; // no check for being in the range!!! - } + int findPeakBin(); - void discardBin(int ib) - { // no check for being in the range!!! - nFilled -= data[ib]; - data[ib] = 0; - } + std::vector filledBins; + int nEntries{}; }; struct TimeZCluster { @@ -323,6 +276,25 @@ struct TimeZCluster { } }; +// structure to produce debug dump for neighbouring vertices comparison +struct PVtxCompDump { + PVertex vtx0{}; + PVertex vtx1{}; + float chi2z{0}; + float chi2t{0}; + ClassDefNV(PVtxCompDump, 1); +}; + +// structure to produce debug dump for DBSCAN clusters +struct TrackVFDump { + float z = 0; + float ze2i = 0.; + float t = 0; + float te = 0; + float wh = 0.; + ClassDefNV(TrackVFDump, 1); +}; + } // namespace vertexing } // namespace o2 diff --git a/Detectors/Vertexing/include/DetectorsVertexing/PVertexerParams.h b/Detectors/Vertexing/include/DetectorsVertexing/PVertexerParams.h index 7fcfc733bfc34..ca47c7422b3e1 100644 --- a/Detectors/Vertexing/include/DetectorsVertexing/PVertexerParams.h +++ b/Detectors/Vertexing/include/DetectorsVertexing/PVertexerParams.h @@ -30,31 +30,40 @@ struct PVertexerParams : public o2::conf::ConfigurableParamHelper this value in \mus + float maxZDiffDebris = 0.7; ///< don't consider vertices separated by Z > this value in cm + float maxMultRatDebris = 0.05; ///< don't consider vertices with multiplicity ratio above this + float maxChi2TZDebris = 1200.; ///< don't consider vertices with mutual chi2 exceeding this (for pp should be ~10) + // validation with externally provided InteractionRecords (e.g. from FT0) int minNContributorsForIRcut = 4; ///< do not apply IR cut to vertices below IR tagging efficiency threshold float maxTError = 0.2; ///< use min of vertex time error or this for nsigma evaluation float minTError = 0.003; ///< don't use error smaller than that (~BC/2/minNContributorsForFT0cut) float nSigmaTimeCut = 4.; ///< eliminate vertex if there is no FT0 signal within this cut float timeBiasMS = 0; ///< relative bias in ms to add to TPCITS-based time stamp - // // stopping condition params float maxChi2Mean = 10.; ///< max mean chi2 of vertex to accept diff --git a/Detectors/Vertexing/src/DetectorsVertexingLinkDef.h b/Detectors/Vertexing/src/DetectorsVertexingLinkDef.h index c400fd6047213..18226a237995c 100644 --- a/Detectors/Vertexing/src/DetectorsVertexingLinkDef.h +++ b/Detectors/Vertexing/src/DetectorsVertexingLinkDef.h @@ -32,4 +32,10 @@ #pragma link C++ function o2::vertexing::DCAFitter2::process(const o2::track::TrackParCov&, const o2::track::TrackParCov&); #pragma link C++ function o2::vertexing::DCAFitter3::process(const o2::track::TrackParCov&, const o2::track::TrackParCov&, const o2::track::TrackParCov&); +#pragma link C++ class o2::vertexing::TrackVFDump + ; +#pragma link C++ class std::vector < o2::vertexing::TrackVFDump> + ; + +#pragma link C++ class o2::vertexing::PVtxCompDump + ; +#pragma link C++ class std::vector < o2::vertexing::PVtxCompDump> + ; + #endif diff --git a/Detectors/Vertexing/src/PVertexer.cxx b/Detectors/Vertexing/src/PVertexer.cxx index 7666a0c39d0f9..67c8e767a506b 100644 --- a/Detectors/Vertexing/src/PVertexer.cxx +++ b/Detectors/Vertexing/src/PVertexer.cxx @@ -18,6 +18,8 @@ #include "Math/SVector.h" #include #include +#include "CommonUtils/StringUtils.h" // RS REM +#include using namespace o2::vertexing; @@ -39,10 +41,12 @@ int PVertexer::runVertexing(const gsl::span gids, const gsl: for (auto tc : mTimeZClusters) { VertexingInput inp; - // inp.idRange = gsl::span((int*)&mSortedTrackID[tc.first], tc.count); inp.idRange = gsl::span((int*)&mClusterTrackIDs[tc.first], tc.count); - inp.scaleSigma2 = 3. * estimateScale2(); + inp.scaleSigma2 = mPVParams->iniScale2; inp.timeEst = tc.timeEst; +#ifdef _PV_DEBUG_TREE_ + doDBScanDump(inp, gids, lblTracks); +#endif findVertices(inp, verticesLoc, trackIDs, v2tRefsLoc); } @@ -52,6 +56,10 @@ int PVertexer::runVertexing(const gsl::span gids, const gsl: std::sort(vtTimeSortID.begin(), vtTimeSortID.end(), [&verticesLoc](int i, int j) { return verticesLoc[i].getTimeStamp().getTimeStamp() < verticesLoc[j].getTimeStamp().getTimeStamp(); }); + if (lblTracks.size()) { + createMCLabels(lblTracks, trackIDs, v2tRefsLoc, lblVtxLoc); + } + reduceDebris(verticesLoc, vtTimeSortID, lblVtxLoc); vertices.clear(); v2tRefs.clear(); @@ -60,12 +68,11 @@ int PVertexer::runVertexing(const gsl::span gids, const gsl: v2tRefs.reserve(v2tRefsLoc.size()); vertexTrackIDs.reserve(trackIDs.size()); - if (lblTracks.size()) { - createMCLabels(lblTracks, vertices, trackIDs, v2tRefsLoc, lblVtxLoc); - } - int trCopied = 0, count = 0, vtimeID = 0; for (auto i : vtTimeSortID) { + if (i < 0) { + continue; // vertex was suppressed + } auto& vtx = verticesLoc[i]; bool irSet = setCompatibleIR(vtx); @@ -108,49 +115,49 @@ int PVertexer::findVertices(const VertexingInput& input, std::vector& v // find vertices using tracks with indices (sorted in time) from idRange from "tracks" pool. The pool may containt arbitrary number of tracks, // only those which are in the idRange and have canUse()==true, will be used. // Results are placed in vertices and v2tRefs vectors - int nfound = 0, ntr = input.idRange.size(); - if (ntr < mPVParams->minTracksPerVtx) { - return nfound; - } - // - SeedHisto seedHisto(mPVParams->zHistoRange, mPVParams->zHistoBinSize); - for (int i : input.idRange) { - if (mTracksPool[i].canUse()) { - mTracksPool[i].bin = seedHisto.findBin(mTracksPool[i].getZForXY(mMeanVertex.getX(), mMeanVertex.getY())); - seedHisto.incrementBin(mTracksPool[i].bin); - } - } - if (seedHisto.nFilled < mPVParams->minTracksPerVtx) { - return nfound; - } - LOG(DEBUG) << "New cluster: times: " << mTracksPool[input.idRange[0]].timeEst.getTimeStamp() << " : " << mTracksPool[input.idRange[ntr - 1]].timeEst.getTimeStamp() << " nfound " << nfound << " of " << ntr; // RSTMP + int nfound = 0, ntr = 0; + auto seedHistoTZ = buildHistoTZ(input); // histo for seeding peak finding + +#ifdef _PV_DEBUG_TREE_ + static int dbsCount = -1; + dbsCount++; + int trialCount = 0; // TODO REM + auto hh = seedHistoTZ.createTH2F(o2::utils::Str::concat_string("htz", std::to_string(dbsCount))); + hh->SetDirectory(nullptr); + mDebugDumpFile->cd(); + hh->Write(); +#endif + int nTrials = 0; while (nfound < mPVParams->maxVerticesPerCluster && nTrials < mPVParams->maxTrialsPerCluster) { - int peakBin = seedHisto.findHighestPeakBin(); // find next seed - if (!seedHisto.isValidBin(peakBin)) { + int peakBin = seedHistoTZ.findPeakBin(); + if (!seedHistoTZ.isValidBin(peakBin)) { break; } - float zv = seedHisto.getBinCenter(peakBin); - LOG(DEBUG) << "Seeding with Z=" << zv << " bin " << peakBin << " on trial " << nTrials << " for vertex " << nfound; + int peakBinT = seedHistoTZ.getXBin(peakBin), peakBinZ = seedHistoTZ.getYBin(peakBin); + float tv = seedHistoTZ.getBinXCenter(peakBinT); + float zv = seedHistoTZ.getBinYCenter(peakBinZ); + LOG(DEBUG) << "Seeding with T=" << tv << " Z=" << zv << " bin " << peakBin << " on trial " << nTrials << " for vertex " << nfound; + PVertex vtx; vtx.setXYZ(mMeanVertex.getX(), mMeanVertex.getY(), zv); - vtx.setTimeStamp(input.timeEst); + vtx.setTimeStamp({tv, 0.f}); if (findVertex(input, vtx)) { - finalizeVertex(input, vtx, vertices, v2tRefs, trackIDs, seedHisto); + finalizeVertex(input, vtx, vertices, v2tRefs, trackIDs, seedHistoTZ); nfound++; nTrials = 0; } else { // suppress failed seeding bin and its proximities - auto delta = std::sqrt(vtx.getChi2()) * mStatZErr.getMean() * getTukey(); // largest scale used will be transferred as chi2 - int proximity = delta * seedHisto.binSizeInv; - int bmin = std::max(0, peakBin - proximity), bmax = std::min(peakBin + proximity + 1, seedHisto.size()); - LOG(DEBUG) << "suppress bins for delta=" << delta << " (" << std::sqrt(vtx.getChi2()) << "*" << mStatZErr.getMean() << "*" << getTukey() << ")" - << " bins " << bmin << " : " << bmax - 1; - for (int i = bmin; i < bmax; i++) { - seedHisto.discardBin(i); - } - nTrials++; + seedHistoTZ.setBinContent(peakBin, -1); } + nTrials++; + +#ifdef _PV_DEBUG_TREE_ + auto hh1 = seedHistoTZ.createTH2F(o2::utils::Str::concat_string("htz", std::to_string(dbsCount), "_", std::to_string(trialCount++))); + hh1->SetDirectory(nullptr); + mDebugDumpFile->cd(); + hh1->Write(); +#endif } return nfound; } @@ -162,6 +169,8 @@ bool PVertexer::findVertex(const VertexingInput& input, PVertex& vtx) // tracks pool may contain arbitrary number of tracks, only those which are in // the idRange (indices of tracks sorted in time) will be used. + int ntr = input.idRange.size(); // RSREM + VertexSeed vtxSeed(vtx, input.useConstraint, input.fillErrors); vtxSeed.setScale(input.scaleSigma2, mTukey2I); vtxSeed.scaleSigma2Prev = input.scaleSigma2; @@ -174,7 +183,8 @@ bool PVertexer::findVertex(const VertexingInput& input, PVertex& vtx) while (result == FitStatus::IterateFurther) { vtxSeed.resetForNewIteration(); vtxSeed.nIterations++; - LOG(DEBUG) << "iter " << vtxSeed.nIterations << " with scale=" << vtxSeed.scaleSigma2 << " prevScale=" << vtxSeed.scaleSigma2Prev; + LOG(DEBUG) << "iter " << vtxSeed.nIterations << " with scale=" << vtxSeed.scaleSigma2 << " prevScale=" << vtxSeed.scaleSigma2Prev + << " ntr=" << ntr << " Zv=" << vtxSeed.getZ() << " Tv=" << vtxSeed.getTimeStamp().getTimeStamp(); result = fitIteration(input, vtxSeed); if (result == FitStatus::OK) { @@ -193,7 +203,7 @@ bool PVertexer::findVertex(const VertexingInput& input, PVertex& vtx) LOG(FATAL) << "Unknown fit status " << int(result); } } - LOG(DEBUG) << "Stopped with scale=" << vtxSeed.scaleSigma2 << " prevScale=" << vtxSeed.scaleSigma2Prev << " result = " << int(result); + LOG(DEBUG) << "Stopped with scale=" << vtxSeed.scaleSigma2 << " prevScale=" << vtxSeed.scaleSigma2Prev << " result = " << int(result) << " ntr=" << ntr; if (result != FitStatus::OK) { vtx.setChi2(vtxSeed.maxScaleSigma2Tested); @@ -209,10 +219,13 @@ PVertexer::FitStatus PVertexer::fitIteration(const VertexingInput& input, Vertex int nTested = 0; for (int i : input.idRange) { if (mTracksPool[i].canUse()) { - nTested++; accountTrack(mTracksPool[i], vtxSeed); + // printf("#%d z:%f t:%f te:%f w:%f wh:%f\n", nTested, mTracksPool[i].z, mTracksPool[i].timeEst.getTimeStamp(), + // mTracksPool[i].timeEst.getTimeStampError(), mTracksPool[i].wgh, mTracksPool[i].wghHisto); + nTested++; } } + vtxSeed.maxScaleSigma2Tested = vtxSeed.scaleSigma2; if (vtxSeed.getNContributors() < mPVParams->minTracksPerVtx) { return nTested < mPVParams->minTracksPerVtx ? FitStatus::PoolEmpty : FitStatus::NotEnoughTracks; @@ -381,6 +394,82 @@ PVertexer::FitStatus PVertexer::evalIterations(VertexSeed& vtxSeed, PVertex& vtx return result; } +//___________________________________________________________________ +void PVertexer::reduceDebris(std::vector& vertices, std::vector& timeSort, const std::vector& lblVtx) +{ + // eliminate low multiplicity vertices in the close proximity of high mult ones, assuming that these are their debries + // The timeSort vector indicates the time ordering of the vertices + int nv = vertices.size(); + std::vector multSort(nv); // sort time indices in multiplicity + std::iota(multSort.begin(), multSort.end(), 0); + std::sort(multSort.begin(), multSort.end(), [&timeSort, vertices](int i, int j) { + return vertices[timeSort[i]].getNContributors() > vertices[timeSort[j]].getNContributors(); + }); + + // suppress vertex pointed by j if needed + auto checkPair = [&vertices, &timeSort, &lblVtx, this](int i, int j) { + auto &vtI = vertices[timeSort[i]], &vtJ = vertices[timeSort[j]]; + auto tDiff = std::abs(vtI.getTimeStamp().getTimeStamp() - vtJ.getTimeStamp().getTimeStamp()); + if (tDiff > this->mPVParams->maxTDiffDebris) { + return false; // don't continue checking other neighbours in time + } + float zDiff = std::abs(vtI.getZ() - vtJ.getZ()); + if (zDiff > this->mPVParams->maxZDiffDebris) { + return true; // cannot be reduced as too far in Z + } + float multRat = float(vtJ.getNContributors()) / float(vtI.getNContributors()); + if (multRat > this->mPVParams->maxMultRatDebris) { + return true; + } + float tiE = vtI.getTimeStamp().getTimeStampError(), tjE = vtJ.getTimeStamp().getTimeStampError(); + float chi2z = zDiff * zDiff / (vtI.getSigmaZ2() + vtJ.getSigmaZ2()), chi2t = tDiff * tDiff / (tiE * tiE + tjE * tjE); + if (chi2z + chi2t > this->mPVParams->maxChi2TZDebris) { + return true; + } + // all veto cuts passed, declare as fake! +#ifdef _PV_DEBUG_TREE_ + o2::MCEventLabel dummyLbl; + this->mDebugDumpPVComp.emplace_back(PVtxCompDump{vtI, vtJ, chi2z, chi2t}); + if (!lblVtx.empty()) { + this->mDebugDumpPVCompLbl0.push_back(lblVtx[timeSort[i]]); + this->mDebugDumpPVCompLbl1.push_back(lblVtx[timeSort[j]]); + } +#endif + timeSort[j] = -1; + return true; + }; + + for (int im = 0; im < nv; im++) { // loop from highest multiplicity to lowest one + int it = multSort[im]; + if (it < 0) { // if <0, the vertex was already discarded + continue; + } + + int itL = it; // look for vertices with smaller time + while (itL) { + if (timeSort[--itL] >= 0) { // if <0, the vertex was already discarded + if (checkPair(it, itL)) { // if too far in time, don't compare further + break; + } + } + } // itL loop + int itH = it; // look for vertices with higher time + while (++itH < nv) { + if (timeSort[itH] >= 0) { // if <0, the vertex was already discarded + if (checkPair(it, itH)) { // if too far in time, don't compare further + break; + } + } + } // itH loop + } +#ifdef _PV_DEBUG_TREE_ + mDebugVtxCompTree->Fill(); + mDebugDumpPVComp.clear(); + mDebugDumpPVCompLbl0.clear(); + mDebugDumpPVCompLbl1.clear(); +#endif +} + //___________________________________________________________________ void PVertexer::initMeanVertexConstraint() { @@ -427,35 +516,60 @@ void PVertexer::init() auto* prop = o2::base::Propagator::Instance(); setBz(prop->getNominalBz()); + +#ifdef _PV_DEBUG_TREE_ + mDebugDumpFile = std::make_unique("pvtxDebug.root", "recreate"); + mDebugDBScanTree = std::make_unique("pvtxDBScan", "PVertexer DBScan debug output"); + mDebugDBScanTree->Branch("trc", &mDebugDumpTrc); + mDebugDBScanTree->Branch("gid", &mDebugDumpGID); + mDebugDBScanTree->Branch("mc", &mDebugDumpTrcMC); + mDebugVtxCompTree = std::make_unique("pvtxComp", "PVertexer neighbouring vertices debud output"); + mDebugVtxCompTree->Branch("vtxComp", &mDebugDumpPVComp); + mDebugVtxCompTree->Branch("vtxCompLbl0", &mDebugDumpPVCompLbl0); + mDebugVtxCompTree->Branch("vtxCompLbl1", &mDebugDumpPVCompLbl1); +#endif +} + +//___________________________________________________________________ +void PVertexer::end() +{ +#ifdef _PV_DEBUG_TREE_ + mDebugDBScanTree->Write(); + mDebugVtxCompTree->Write(); + mDebugDBScanTree.reset(); + mDebugVtxCompTree.reset(); + mDebugDumpFile->Close(); + mDebugDumpFile.reset(); +#endif } //___________________________________________________________________ void PVertexer::finalizeVertex(const VertexingInput& input, const PVertex& vtx, std::vector& vertices, std::vector& v2tRefs, std::vector& trackIDs, - SeedHisto& histo) + SeedHistoTZ& histo) { int lastID = vertices.size(); vertices.emplace_back(vtx); auto& ref = v2tRefs.emplace_back(trackIDs.size(), 0); for (int i : input.idRange) { - if (mTracksPool[i].canAssign()) { - trackIDs.push_back(mTracksPool[i].entry); - mTracksPool[i].vtxID = lastID; - - // remove track from ZSeeds histo - histo.decrementBin(mTracksPool[i].bin); + auto& trc = mTracksPool[i]; + if (trc.canAssign()) { + trackIDs.push_back(trc.entry); + trc.vtxID = lastID; + if (trc.bin >= 0) { + histo.setBinContent(trc.bin, -1.f); // discard used bin + } } } ref.setEntries(trackIDs.size() - ref.getFirstEntry()); } //___________________________________________________________________ -void PVertexer::createMCLabels(gsl::span lblTracks, const std::vector vertices, - const std::vector trackIDs, const std::vector v2tRefs, +void PVertexer::createMCLabels(gsl::span lblTracks, + const std::vector& trackIDs, const std::vector& v2tRefs, std::vector& lblVtx) { lblVtx.clear(); - int nv = vertices.size(); if (!lblTracks.size()) { LOG(ERROR) << "Track labels are not provided"; return; @@ -700,3 +814,65 @@ std::pair PVertexer::getBestIR(const PVertex& vtx, const gsl::span hZMax) { + hZMax = trc.z; + } + if (trc.z < hZMin) { + hZMin = trc.z; + } + if (trc.timeEst.getTimeStamp() > hTMax) { + hTMax = trc.timeEst.getTimeStamp(); + } + if (trc.timeEst.getTimeStamp() < hTMin) { + hTMin = trc.timeEst.getTimeStamp(); + } + } + } + + float dz = hZMax - hZMin, dt = hTMax - hTMin; + int nbz = 1 + int((dz) / mPVParams->histoBinZSize), nbt = 1 + int((dt) / mPVParams->histoBinTSize); + float dzh = 0.5f * (nbz * mPVParams->histoBinZSize - dz), dth = 0.5f * (nbt * mPVParams->histoBinTSize - dt); + SeedHistoTZ seedHistoTZ(nbt, hTMin - dth, hTMax + dth, nbz, hZMin - dzh, hZMax + dzh); + + for (int i : input.idRange) { + auto& trc = mTracksPool[i]; + if (trc.canUse()) { + trc.bin = seedHistoTZ.fillAndFlagBin(trc.timeEst.getTimeStamp(), trc.z, trc.wghHisto); + } + } + + return std::move(seedHistoTZ); +} + +//______________________________________________ +void PVertexer::doDBScanDump(const VertexingInput& input, const gsl::span gids, gsl::span lblTracks) +{ + // dump tracks for T-Z clusters identified by the DBScan +#ifdef _PV_DEBUG_TREE_ + for (int i : input.idRange) { + const auto& trc = mTracksPool[i]; + if (trc.canUse()) { + mDebugDumpTrc.emplace_back(TrackVFDump{trc.z, trc.sig2ZI, trc.timeEst.getTimeStamp(), trc.timeEst.getTimeStampError(), trc.wghHisto}); + mDebugDumpGID.push_back(gids[trc.entry]); + if (lblTracks.size()) { + mDebugDumpTrcMC.push_back(lblTracks[trc.entry]); + } + } + } + mDebugDBScanTree->Fill(); + mDebugDumpTrc.clear(); + mDebugDumpGID.clear(); + mDebugDumpTrcMC.clear(); +#endif +} diff --git a/Detectors/Vertexing/src/PVertexerHelpers.cxx b/Detectors/Vertexing/src/PVertexerHelpers.cxx index d3cf1756172cc..5fc734ac68d7b 100644 --- a/Detectors/Vertexing/src/PVertexerHelpers.cxx +++ b/Detectors/Vertexing/src/PVertexerHelpers.cxx @@ -25,3 +25,24 @@ void VertexSeed::print() const double dZ, rmsZ, dT, rmsT; PVertex::print(); } + +int SeedHistoTZ::findPeakBin() +{ + if (nEntries < 2) { + return -1; + } + int maxBin = -1, ib = filledBins.size(), last = ib; + float maxv = 0.; + while (ib--) { + auto bin = filledBins[ib]; + auto v = getBinContent(bin); + if (v > maxv) { + maxv = v; + maxBin = bin; + } else if (v <= 0.) { // bin was emptied + filledBins[ib] = filledBins[--last]; // move last non-empty bin in place of emptied one + } + } + filledBins.resize(last); + return maxBin; +} From bb2234a9eba656bd8f457d11bc1e0410ede26097 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 4 May 2021 09:40:00 +0200 Subject: [PATCH 403/770] Add direct getters for tpc clusters / trd tracklets --- .../DataFormatsGlobalTracking/RecoContainer.h | 12 +++++++++++ .../GlobalTracking/src/RecoContainer.cxx | 20 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h index 6441e761feaa9..b6ba0677728aa 100644 --- a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h +++ b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h @@ -32,6 +32,7 @@ namespace o2::tpc { using TPCClRefElem = uint32_t; +struct ClusterNativeAccess; namespace internal { struct getWorkflowTPCInput_ret; @@ -39,6 +40,9 @@ struct getWorkflowTPCInput_ret; } // namespace o2::tpc namespace o2::trd { +class Tracklet64; +class CalibratedTracklet; +class TriggerRecord; struct RecoInputContainer; } // namespace o2::trd @@ -240,6 +244,14 @@ struct RecoContainer { return miscPool.get_as(id); } + // TPC clusters + const o2::tpc::ClusterNativeAccess& getTPCClusters() const; + + // TRD tracklets + gsl::span getTRDTracklets() const; + gsl::span getTRDCalibratedTracklets() const; + gsl::span getTRDTriggerRecords() const; + // ITS clusters template // o2::itsmft::ROFRecord auto getITSClustersROFRecords() const diff --git a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx index 1622e21db99e1..69fa917f8d4a1 100644 --- a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx +++ b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx @@ -324,6 +324,26 @@ void RecoContainer::addFT0RecPoints(ProcessingContext& pc, bool mc) } } +const o2::tpc::ClusterNativeAccess& RecoContainer::getTPCClusters() const +{ + return inputsTPCclusters->clusterIndex; +} + +gsl::span RecoContainer::getTRDTracklets() const +{ + return inputsTRD->mTracklets; +} + +gsl::span RecoContainer::getTRDCalibratedTracklets() const +{ + return inputsTRD->mSpacePoints; +} + +gsl::span RecoContainer::getTRDTriggerRecords() const +{ + return inputsTRD->mTriggerRecords; +} + //__________________________________________________________ const o2::track::TrackParCov& RecoContainer::getTrackParamOut(GTrackID gidx) const { From ce2784e542aff35ad58db82e2f3923e4a52195fb Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 4 May 2021 16:31:17 +0200 Subject: [PATCH 404/770] DataFormats should ideally not depend on Framework, and if so than please only as PRIVATE --- DataFormats/Detectors/GlobalTracking/CMakeLists.txt | 7 ++++--- .../include/DataFormatsGlobalTracking/RecoContainer.h | 7 +++++-- DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx | 2 ++ GPU/Workflow/src/GPUWorkflowSpec.cxx | 2 +- 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/DataFormats/Detectors/GlobalTracking/CMakeLists.txt b/DataFormats/Detectors/GlobalTracking/CMakeLists.txt index 4ea9381e6fc3c..243904b753758 100644 --- a/DataFormats/Detectors/GlobalTracking/CMakeLists.txt +++ b/DataFormats/Detectors/GlobalTracking/CMakeLists.txt @@ -12,7 +12,6 @@ o2_add_library( DataFormatsGlobalTracking SOURCES src/RecoContainer.cxx PUBLIC_LINK_LIBRARIES - O2::Framework O2::DataFormatsTPC O2::DataFormatsITSMFT O2::DataFormatsITS @@ -20,5 +19,7 @@ o2_add_library( O2::DataFormatsTOF O2::DataFormatsFT0 O2::ReconstructionDataFormats - O2::TRDReconstruction - O2::GPUDataTypeHeaders) + O2::DataFormatsTRD + O2::GPUDataTypeHeaders + PRIVATE_LINK_LIBRARIES + O2::Framework) diff --git a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h index b6ba0677728aa..d10fb2fdcca96 100644 --- a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h +++ b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h @@ -15,8 +15,6 @@ #ifndef ALICEO2_RECO_CONTAINER #define ALICEO2_RECO_CONTAINER -#include "Framework/ProcessingContext.h" -#include "Framework/InputSpec.h" #include "CommonDataFormat/InteractionRecord.h" #include "ReconstructionDataFormats/GlobalTrackAccessor.h" #include "ReconstructionDataFormats/GlobalTrackID.h" @@ -45,6 +43,11 @@ class CalibratedTracklet; class TriggerRecord; struct RecoInputContainer; } // namespace o2::trd +namespace o2::framework +{ +class ProcessingContext; +struct InputSpec; +} // namespace o2::framework namespace o2 { diff --git a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx index 69fa917f8d4a1..074c14915e23a 100644 --- a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx +++ b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx @@ -14,6 +14,8 @@ #include #include +#include "Framework/ProcessingContext.h" +#include "Framework/InputSpec.h" #include "DetectorsCommonDataFormats/DetID.h" #include "DataFormatsTPC/WorkflowHelper.h" #include "DataFormatsTRD/RecoInputContainer.h" diff --git a/GPU/Workflow/src/GPUWorkflowSpec.cxx b/GPU/Workflow/src/GPUWorkflowSpec.cxx index 01ebb53273b31..d6db7d904ea21 100644 --- a/GPU/Workflow/src/GPUWorkflowSpec.cxx +++ b/GPU/Workflow/src/GPUWorkflowSpec.cxx @@ -735,7 +735,7 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli processAttributes->qa->cleanup(); } timer.Stop(); - LOG(INFO) << "TPC CATracker time for this TF " << timer.CpuTime() - cput << " s (cpu), " << timer.RealTime() - realt << " s (wall)"; + LOG(INFO) << "GPU Reoncstruction time for this TF " << timer.CpuTime() - cput << " s (cpu), " << timer.RealTime() - realt << " s (wall)"; }; return processingFct; From 30caa94d26099516d1430a5d267ff1f9bb69cf70 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 4 May 2021 16:48:45 +0200 Subject: [PATCH 405/770] GPU Workflow: Add helper class to fill GPUIOPtr from RecoContainer (ITS Clusters / Tracks, TOF Clusters / Matches) --- .../ReconstructionDataFormats/GlobalTrackID.h | 1 + .../Reconstruction/src/GlobalTrackID.cxx | 2 +- GPU/GPUTracking/DataTypes/GPUDataTypes.h | 53 ++++++++++- GPU/Workflow/CMakeLists.txt | 2 + GPU/Workflow/helper/CMakeLists.txt | 18 ++++ .../GPUWorkflowHelper/GPUWorkflowHelper.h | 33 +++++++ GPU/Workflow/helper/src/GPUWorkflowHelper.cxx | 91 +++++++++++++++++++ 7 files changed, 196 insertions(+), 4 deletions(-) create mode 100644 GPU/Workflow/helper/CMakeLists.txt create mode 100644 GPU/Workflow/helper/include/GPUWorkflowHelper/GPUWorkflowHelper.h create mode 100644 GPU/Workflow/helper/src/GPUWorkflowHelper.cxx diff --git a/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h b/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h index 5a161869796f1..a02abedece89e 100644 --- a/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h +++ b/DataFormats/Reconstruction/include/ReconstructionDataFormats/GlobalTrackID.h @@ -71,6 +71,7 @@ class GlobalTrackID : public AbstractRef<25, 5, 2> static constexpr std::string_view NONE{"none"}; ///< keywork for no sources static constexpr std::string_view ALL{"all"}; ///< keywork for all sources #endif + static constexpr mask_t MASK_ALL = (1u << NSources) - 1; // methods for detector level manipulations GPUd() static constexpr DetID::mask_t getSourceDetectorsMask(int i); diff --git a/DataFormats/Reconstruction/src/GlobalTrackID.cxx b/DataFormats/Reconstruction/src/GlobalTrackID.cxx index d8dad6551fe23..d62f88f55ca78 100644 --- a/DataFormats/Reconstruction/src/GlobalTrackID.cxx +++ b/DataFormats/Reconstruction/src/GlobalTrackID.cxx @@ -35,7 +35,7 @@ GlobalTrackID::mask_t GlobalTrackID::getSourcesMask(const std::string_view srcLi return mask; } if (ss.find(ALL) != std::string::npos) { - mask = (0x1u << NSources) - 1; + mask = MASK_ALL; return mask; } std::replace(ss.begin(), ss.end(), ' ', ','); diff --git a/GPU/GPUTracking/DataTypes/GPUDataTypes.h b/GPU/GPUTracking/DataTypes/GPUDataTypes.h index f7e561128a9e0..adcf79011fc67 100644 --- a/GPU/GPUTracking/DataTypes/GPUDataTypes.h +++ b/GPU/GPUTracking/DataTypes/GPUDataTypes.h @@ -47,6 +47,8 @@ namespace constants namespace o2 { class MCCompLabel; +template +class BaseCluster; namespace base { template @@ -60,11 +62,26 @@ class GeometryFlat; namespace dataformats { class TrackTPCITS; +class MatchInfoTOF; template class MCTruthContainer; template class ConstMCTruthContainerView; } // namespace dataformats +namespace itsmft +{ +class CompClusterExt; +class ROFRecord; +class TopologyDictionary; +} // namespace itsmft +namespace its +{ +class TrackITS; +} // namespace its +namespace tof +{ +class Cluster; +} // namespace tof } // namespace o2 namespace GPUCA_NAMESPACE @@ -183,6 +200,7 @@ struct GPUCalibObjectsTemplate { typename S::type* dEdxSplines = nullptr; typename S::type* tpcPadGain = nullptr; typename S>::type* o2Propagator = nullptr; + typename S::type* itsPatternDict = nullptr; }; typedef GPUCalibObjectsTemplate GPUCalibObjects; // NOTE: These 2 must have identical layout since they are memcopied typedef GPUCalibObjectsTemplate GPUCalibObjectsConst; @@ -215,8 +233,9 @@ struct GPUTrackingInOutDigits { struct GPUTrackingInOutPointers { GPUTrackingInOutPointers() = default; GPUTrackingInOutPointers(const GPUTrackingInOutPointers&) = default; - static constexpr unsigned int NSLICES = GPUDataTypes::NSLICES; + // TPC + static constexpr unsigned int NSLICES = GPUDataTypes::NSLICES; const GPUTrackingInOutZS* tpcZS = nullptr; const GPUTrackingInOutDigits* tpcPackedDigits = nullptr; const GPUTPCClusterData* clusterData[NSLICES] = {nullptr}; @@ -245,8 +264,8 @@ struct GPUTrackingInOutPointers { unsigned int nOutputClusRefsTPCO2 = 0; const o2::MCCompLabel* outputTracksTPCO2MC = nullptr; const o2::tpc::CompressedClustersFlat* tpcCompressedClusters = nullptr; - const o2::dataformats::TrackTPCITS* tracksTPCITSO2 = nullptr; - unsigned int nTracksTPCITSO2 = 0; + + // TRD const GPUTRDTrackletWord* trdTracklets = nullptr; const GPUTRDSpacePoint* trdSpacePoints = nullptr; unsigned int nTRDTracklets = 0; @@ -255,6 +274,34 @@ struct GPUTrackingInOutPointers { const float* trdTriggerTimes = nullptr; const int* trdTrackletIdxFirst = nullptr; unsigned int nTRDTriggerRecords = 0; + + // TOF + const o2::tof::Cluster* tofClusters = nullptr; + unsigned int nTOFClusters = 0; + const o2::dataformats::MatchInfoTOF* tofMatches = nullptr; + unsigned int nTOFMatches = 0; + const o2::dataformats::MatchInfoTOF* tpctofMatches = nullptr; + unsigned int nTPCTOFMatches = 0; + + // ITS + const o2::itsmft::CompClusterExt* itsCompClusters = nullptr; + const o2::dataformats::MCTruthContainer* itsClusterMC = nullptr; + const o2::BaseCluster* itsClusters = nullptr; + unsigned int nItsClusters = 0; + const o2::itsmft::ROFRecord* itsClusterROF = nullptr; + unsigned int nItsClusterROF = 0; + const o2::its::TrackITS* itsTracks = nullptr; + const o2::MCCompLabel* itsTrackMC = nullptr; + unsigned int nItsTracks = 0; + const int* itsTrackClusIdx = nullptr; + const o2::itsmft::ROFRecord* itsTrackROF = nullptr; + unsigned int nItsTrackROF = 0; + + // TPC-ITS + const o2::dataformats::TrackTPCITS* tracksTPCITSO2 = nullptr; + unsigned int nTracksTPCITSO2 = 0; + + // Common const GPUSettingsTF* settingsTF = nullptr; }; #else diff --git a/GPU/Workflow/CMakeLists.txt b/GPU/Workflow/CMakeLists.txt index 047582e4700c1..466edb284c8e3 100644 --- a/GPU/Workflow/CMakeLists.txt +++ b/GPU/Workflow/CMakeLists.txt @@ -56,3 +56,5 @@ if(ALIGPU_BUILD_TYPE STREQUAL "O2" O2::GlobalTrackingWorkflowHelpers) target_include_directories(${targetName} PUBLIC "include") endif() + +add_subdirectory(helper) diff --git a/GPU/Workflow/helper/CMakeLists.txt b/GPU/Workflow/helper/CMakeLists.txt new file mode 100644 index 0000000000000..9ab191adb97e8 --- /dev/null +++ b/GPU/Workflow/helper/CMakeLists.txt @@ -0,0 +1,18 @@ +# Copyright CERN and copyright holders of ALICE O2. This software is distributed +# under the terms of the GNU General Public License v3 (GPL Version 3), copied +# verbatim in the file "COPYING". +# +# See http://alice-o2.web.cern.ch/license for full licensing information. +# +# In applying this license CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization or +# submit itself to any jurisdiction. + +o2_add_library(GPUWorkflowHelper + SOURCES src/GPUWorkflowHelper.cxx + TARGETVARNAME targetName + PUBLIC_LINK_LIBRARIES O2::Framework + O2::DataFormatsGlobalTracking + O2::GPUDataTypeHeaders + O2::GPUO2Interface + O2::ITStracking) diff --git a/GPU/Workflow/helper/include/GPUWorkflowHelper/GPUWorkflowHelper.h b/GPU/Workflow/helper/include/GPUWorkflowHelper/GPUWorkflowHelper.h new file mode 100644 index 0000000000000..c5a15a7a368c0 --- /dev/null +++ b/GPU/Workflow/helper/include/GPUWorkflowHelper/GPUWorkflowHelper.h @@ -0,0 +1,33 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_GPU_WORKFLOW_HELPER_H +#define O2_GPU_WORKFLOW_HELPER_H + +#include "ReconstructionDataFormats/GlobalTrackID.h" +#include "DataFormatsGlobalTracking/RecoContainer.h" +#include "GPUDataTypes.h" +#include + +namespace o2::gpu +{ + +class GPUWorkflowHelper +{ + using GID = o2::dataformats::GlobalTrackID; + + public: + struct tmpDataContainer; + static std::unique_ptr fillIOPtr(GPUTrackingInOutPointers& ioPtr, const o2::globaltracking::RecoContainer& recoCont, const GPUCalibObjectsConst* calib = nullptr, GID::mask_t maskCl = GID::MASK_ALL, GID::mask_t maskTrk = GID::MASK_ALL, GID::mask_t maskMatch = GID::MASK_ALL); +}; + +} // namespace o2::gpu + +#endif diff --git a/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx b/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx new file mode 100644 index 0000000000000..650c0e0c40eb1 --- /dev/null +++ b/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx @@ -0,0 +1,91 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "GPUWorkflowHelper/GPUWorkflowHelper.h" +#include "ITStracking/IOUtils.h" +using namespace o2::globaltracking; +using namespace o2::gpu; + +struct GPUWorkflowHelper::tmpDataContainer { + std::vector> ITSClustersArray; +}; + +std::unique_ptr GPUWorkflowHelper::fillIOPtr(GPUTrackingInOutPointers& ioPtr, const o2::globaltracking::RecoContainer& recoCont, const GPUCalibObjectsConst* calib, o2::dataformats::GlobalTrackID::mask_t maskCl, o2::dataformats::GlobalTrackID::mask_t maskTrk, o2::dataformats::GlobalTrackID::mask_t maskMatch) +{ + auto retVal = std::make_unique(); + + if (maskCl[GID::ITS] && ioPtr.nItsClusters == 0) { + const auto& ITSClusterROFRec = recoCont.getITSClustersROFRecords(); + const auto& clusITS = recoCont.getITSClusters(); + if (clusITS.size() && ITSClusterROFRec.size()) { + if (calib && calib->itsPatternDict) { + const auto& patterns = recoCont.getITSClustersPatterns(); + auto pattIt = patterns.begin(); + retVal->ITSClustersArray.reserve(clusITS.size()); + o2::its::ioutils::convertCompactClusters(clusITS, pattIt, retVal->ITSClustersArray, *calib->itsPatternDict); + ioPtr.itsClusters = retVal->ITSClustersArray.data(); + } + const auto& ITSClsLabels = recoCont.mcITSClusters.get(); + ioPtr.nItsClusters = clusITS.size(); + ioPtr.itsCompClusters = clusITS.data(); + ioPtr.nItsClusterROF = ITSClusterROFRec.size(); + ioPtr.itsClusterROF = ITSClusterROFRec.data(); + ioPtr.itsClusterMC = ITSClsLabels; + } + } + if (maskTrk[GID::ITS] && ioPtr.nItsTracks == 0) { + const auto& ITSTracksArray = recoCont.getITSTracks(); + const auto& ITSTrackROFRec = recoCont.getITSTracksROFRecords(); + if (ITSTracksArray.size() && ITSTrackROFRec.size()) { + const auto& ITSTrackClusIdx = recoCont.getITSTracksClusterRefs(); + const auto& ITSTrkLabels = recoCont.getITSTracksMCLabels(); + ioPtr.nItsTracks = ITSTracksArray.size(); + ioPtr.itsTracks = ITSTracksArray.data(); + ioPtr.itsTrackClusIdx = ITSTrackClusIdx.data(); + ioPtr.nItsTrackROF = ITSTrackROFRec.size(); + ioPtr.itsTrackROF = ITSTrackROFRec.data(); + ioPtr.itsTrackMC = ITSTrkLabels.data(); + } + } + + if (maskTrk[GID::ITSTPC] && ioPtr.nTracksTPCITSO2 == 0) { + const auto& trkITSTPC = recoCont.getTPCITSTracks(); + if (trkITSTPC.size()) { + ioPtr.nTracksTPCITSO2 = trkITSTPC.size(); + ioPtr.tracksTPCITS = trkITSTPC.data(); + } + } + + if (maskCl[GID::TOF] && ioPtr.nTOFClusters == 0) { + const auto& tofClusters = recoCont.getTOFClusters(); + if (tofClusters.size()) { + ioPtr.nTOFClusters = tofClusters.size(); + ioPtr.tofClusters = tofClusters.data(); + } + } + + if (maskMatch[GID::TOF] && ioPtr.nTOFMatches == 0) { + const auto& tofMatches = recoCont.getTOFMatches(); + if (tofMatches.size()) { + ioPtr.nTOFMatches = tofMatches.size(); + ioPtr.tofMatches = tofMatches.data(); + } + } + + if (maskMatch[GID::TPCTOF] && ioPtr.nTPCTOFMatches == 0) { + const auto& tpctofMatches = recoCont.getTPCTOFMatches(); + if (tpctofMatches.size()) { + ioPtr.nTPCTOFMatches = tpctofMatches.size(); + ioPtr.tpctofMatches = tpctofMatches.data(); + } + } + + return std::move(retVal); +} From 5a708e7cb0908a5cafa77031b7a1cbd7696d3801 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 4 May 2021 22:23:20 +0200 Subject: [PATCH 406/770] GPU DPL Display: Use fillIOPtr in O2GPUDPLDisplay --- .../GlobalTracking/src/RecoContainer.cxx | 6 +++ .../DataFormatsTRD/RecoInputContainer.h | 2 + .../Interface/GPUO2InterfaceConfiguration.h | 2 +- .../Interface/GPUO2InterfaceDisplay.cxx | 2 +- GPU/Workflow/CMakeLists.txt | 1 + .../GPUWorkflowHelper/GPUWorkflowHelper.h | 2 +- GPU/Workflow/helper/src/GPUWorkflowHelper.cxx | 43 +++++++++++++++---- GPU/Workflow/src/O2GPUDPLDisplay.cxx | 32 +++----------- 8 files changed, 52 insertions(+), 38 deletions(-) diff --git a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx index 074c14915e23a..b918125e50018 100644 --- a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx +++ b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx @@ -131,6 +131,7 @@ void DataRequest::requestTRDTracklets() addInput({"trdtracklets", o2::header::gDataOriginTRD, "TRACKLETS", 0, Lifetime::Timeframe}); addInput({"trdctracklets", o2::header::gDataOriginTRD, "CTRACKLETS", 0, Lifetime::Timeframe}); addInput({"trdtriggerrec", o2::header::gDataOriginTRD, "TRKTRGRD", 0, Lifetime::Timeframe}); + requestMap["trackletTRD"] = false; } void DataRequest::requestFT0RecPoints(bool mc) @@ -234,6 +235,11 @@ void RecoContainer::collectData(ProcessingContext& pc, const DataRequest& reques if (req != reqMap.end()) { addFT0RecPoints(pc, req->second); } + + req = reqMap.find("trackletTRD"); + if (req != reqMap.end()) { + addTRDTracklets(pc); + } } //____________________________________________________________ diff --git a/DataFormats/Detectors/TRD/include/DataFormatsTRD/RecoInputContainer.h b/DataFormats/Detectors/TRD/include/DataFormatsTRD/RecoInputContainer.h index 407a1369891d6..3a2727d55efd9 100644 --- a/DataFormats/Detectors/TRD/include/DataFormatsTRD/RecoInputContainer.h +++ b/DataFormats/Detectors/TRD/include/DataFormatsTRD/RecoInputContainer.h @@ -22,6 +22,8 @@ #include "DataFormatsTRD/TriggerRecord.h" #include "DataFormatsGlobalTracking/RecoContainer.h" #include "CommonConstants/LHCConstants.h" +#include "Framework/ProcessingContext.h" +#include "Framework/InputRecord.h" #include "GPUDataTypes.h" diff --git a/GPU/GPUTracking/Interface/GPUO2InterfaceConfiguration.h b/GPU/GPUTracking/Interface/GPUO2InterfaceConfiguration.h index d83040c1a9c83..7b0348b0499d8 100644 --- a/GPU/GPUTracking/Interface/GPUO2InterfaceConfiguration.h +++ b/GPU/GPUTracking/Interface/GPUO2InterfaceConfiguration.h @@ -88,7 +88,7 @@ struct GPUO2InterfaceConfiguration { GPUSettingsQA configQA; GPUInterfaceSettings configInterface; GPURecoStepConfiguration configWorkflow; - GPUCalibObjects configCalib; + GPUCalibObjectsConst configCalib; GPUSettingsO2 ReadConfigurableParam(); diff --git a/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx index 91c4faeec8812..8945c9dce1420 100644 --- a/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx +++ b/GPU/GPUTracking/Interface/GPUO2InterfaceDisplay.cxx @@ -31,7 +31,7 @@ GPUO2InterfaceDisplay::GPUO2InterfaceDisplay(const GPUO2InterfaceConfiguration* mParam.reset(new GPUParam); mParam->SetDefaults(&config->configGRP, &config->configReconstruction, &config->configProcessing, nullptr); mParam->par.earlyTpcTransform = 0; - mDisplay.reset(new GPUDisplay(mBackend.get(), nullptr, nullptr, mParam.get(), (const GPUCalibObjectsConst*)&mConfig->configCalib, &mConfig->configDisplay)); + mDisplay.reset(new GPUDisplay(mBackend.get(), nullptr, nullptr, mParam.get(), &mConfig->configCalib, &mConfig->configDisplay)); } GPUO2InterfaceDisplay::~GPUO2InterfaceDisplay() = default; diff --git a/GPU/Workflow/CMakeLists.txt b/GPU/Workflow/CMakeLists.txt index 466edb284c8e3..eb29b31e3f229 100644 --- a/GPU/Workflow/CMakeLists.txt +++ b/GPU/Workflow/CMakeLists.txt @@ -49,6 +49,7 @@ if(ALIGPU_BUILD_TYPE STREQUAL "O2" TARGETVARNAME targetName SOURCES src/O2GPUDPLDisplay.cxx PUBLIC_LINK_LIBRARIES O2::GPUO2Interface + O2::GPUWorkflowHelper O2::DataFormatsGlobalTracking O2::TPCFastTransformation O2::TRDBase diff --git a/GPU/Workflow/helper/include/GPUWorkflowHelper/GPUWorkflowHelper.h b/GPU/Workflow/helper/include/GPUWorkflowHelper/GPUWorkflowHelper.h index c5a15a7a368c0..7e0cb87f03360 100644 --- a/GPU/Workflow/helper/include/GPUWorkflowHelper/GPUWorkflowHelper.h +++ b/GPU/Workflow/helper/include/GPUWorkflowHelper/GPUWorkflowHelper.h @@ -25,7 +25,7 @@ class GPUWorkflowHelper public: struct tmpDataContainer; - static std::unique_ptr fillIOPtr(GPUTrackingInOutPointers& ioPtr, const o2::globaltracking::RecoContainer& recoCont, const GPUCalibObjectsConst* calib = nullptr, GID::mask_t maskCl = GID::MASK_ALL, GID::mask_t maskTrk = GID::MASK_ALL, GID::mask_t maskMatch = GID::MASK_ALL); + static std::shared_ptr fillIOPtr(GPUTrackingInOutPointers& ioPtr, const o2::globaltracking::RecoContainer& recoCont, bool useMC, const GPUCalibObjectsConst* calib = nullptr, GID::mask_t maskCl = GID::MASK_ALL, GID::mask_t maskTrk = GID::MASK_ALL, GID::mask_t maskMatch = GID::MASK_ALL); }; } // namespace o2::gpu diff --git a/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx b/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx index 650c0e0c40eb1..4ee92258ab865 100644 --- a/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx +++ b/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx @@ -9,7 +9,9 @@ // or submit itself to any jurisdiction. #include "GPUWorkflowHelper/GPUWorkflowHelper.h" +#include "DataFormatsTRD/RecoInputContainer.h" #include "ITStracking/IOUtils.h" +#include "DataFormatsTPC/WorkflowHelper.h" using namespace o2::globaltracking; using namespace o2::gpu; @@ -17,9 +19,9 @@ struct GPUWorkflowHelper::tmpDataContainer { std::vector> ITSClustersArray; }; -std::unique_ptr GPUWorkflowHelper::fillIOPtr(GPUTrackingInOutPointers& ioPtr, const o2::globaltracking::RecoContainer& recoCont, const GPUCalibObjectsConst* calib, o2::dataformats::GlobalTrackID::mask_t maskCl, o2::dataformats::GlobalTrackID::mask_t maskTrk, o2::dataformats::GlobalTrackID::mask_t maskMatch) +std::shared_ptr GPUWorkflowHelper::fillIOPtr(GPUTrackingInOutPointers& ioPtr, const o2::globaltracking::RecoContainer& recoCont, bool useMC, const GPUCalibObjectsConst* calib, o2::dataformats::GlobalTrackID::mask_t maskCl, o2::dataformats::GlobalTrackID::mask_t maskTrk, o2::dataformats::GlobalTrackID::mask_t maskMatch) { - auto retVal = std::make_unique(); + auto retVal = std::make_shared(); if (maskCl[GID::ITS] && ioPtr.nItsClusters == 0) { const auto& ITSClusterROFRec = recoCont.getITSClustersROFRecords(); @@ -32,12 +34,14 @@ std::unique_ptr GPUWorkflowHelper::fi o2::its::ioutils::convertCompactClusters(clusITS, pattIt, retVal->ITSClustersArray, *calib->itsPatternDict); ioPtr.itsClusters = retVal->ITSClustersArray.data(); } - const auto& ITSClsLabels = recoCont.mcITSClusters.get(); ioPtr.nItsClusters = clusITS.size(); ioPtr.itsCompClusters = clusITS.data(); ioPtr.nItsClusterROF = ITSClusterROFRec.size(); ioPtr.itsClusterROF = ITSClusterROFRec.data(); - ioPtr.itsClusterMC = ITSClsLabels; + if (useMC) { + const auto& ITSClsLabels = recoCont.mcITSClusters.get(); + ioPtr.itsClusterMC = ITSClsLabels; + } } } if (maskTrk[GID::ITS] && ioPtr.nItsTracks == 0) { @@ -45,21 +49,23 @@ std::unique_ptr GPUWorkflowHelper::fi const auto& ITSTrackROFRec = recoCont.getITSTracksROFRecords(); if (ITSTracksArray.size() && ITSTrackROFRec.size()) { const auto& ITSTrackClusIdx = recoCont.getITSTracksClusterRefs(); - const auto& ITSTrkLabels = recoCont.getITSTracksMCLabels(); ioPtr.nItsTracks = ITSTracksArray.size(); ioPtr.itsTracks = ITSTracksArray.data(); ioPtr.itsTrackClusIdx = ITSTrackClusIdx.data(); ioPtr.nItsTrackROF = ITSTrackROFRec.size(); ioPtr.itsTrackROF = ITSTrackROFRec.data(); - ioPtr.itsTrackMC = ITSTrkLabels.data(); + if (useMC) { + const auto& ITSTrkLabels = recoCont.getITSTracksMCLabels(); + ioPtr.itsTrackMC = ITSTrkLabels.data(); + } } } if (maskTrk[GID::ITSTPC] && ioPtr.nTracksTPCITSO2 == 0) { - const auto& trkITSTPC = recoCont.getTPCITSTracks(); + const auto& trkITSTPC = recoCont.getTPCITSTracks(); if (trkITSTPC.size()) { ioPtr.nTracksTPCITSO2 = trkITSTPC.size(); - ioPtr.tracksTPCITS = trkITSTPC.data(); + ioPtr.tracksTPCITSO2 = trkITSTPC.data(); } } @@ -87,5 +93,26 @@ std::unique_ptr GPUWorkflowHelper::fi } } + if (maskCl[GID::TPC] && ioPtr.clustersNative == nullptr) { + ioPtr.clustersNative = &recoCont.inputsTPCclusters->clusterIndex; + } + + if (maskTrk[GID::TPC] && ioPtr.nOutputTracksTPCO2 == 0) { + const auto& tpcTracks = recoCont.getTPCTracks(); + const auto& tpcClusRefs = recoCont.getTPCTracksClusterRefs(); + ioPtr.outputTracksTPCO2 = tpcTracks.data(); + ioPtr.nOutputTracksTPCO2 = tpcTracks.size(); + ioPtr.outputClusRefsTPCO2 = tpcClusRefs.data(); + ioPtr.nOutputClusRefsTPCO2 = tpcClusRefs.size(); + if (useMC) { + const auto& tpcTracksMC = recoCont.getTPCTracksMCLabels(); + ioPtr.outputTracksTPCO2MC = tpcTracksMC.data(); + } + } + + if (maskCl[GID::TRD]) { + // o2::trd::getRecoInputContainer(pc, &ioPtr, &recoCont); // TODO: use this helper here + } + return std::move(retVal); } diff --git a/GPU/Workflow/src/O2GPUDPLDisplay.cxx b/GPU/Workflow/src/O2GPUDPLDisplay.cxx index 9caab2f814c9d..976e1cfb80e20 100644 --- a/GPU/Workflow/src/O2GPUDPLDisplay.cxx +++ b/GPU/Workflow/src/O2GPUDPLDisplay.cxx @@ -24,6 +24,7 @@ #include "GlobalTrackingWorkflowHelpers/InputHelper.h" #include "DataFormatsTPC/WorkflowHelper.h" #include "DataFormatsTRD/RecoInputContainer.h" +#include "GPUWorkflowHelper/GPUWorkflowHelper.h" using namespace o2::framework; using namespace o2::dataformats; @@ -71,8 +72,6 @@ void O2GPUDPLDisplaySpec::init(InitContext& ic) void O2GPUDPLDisplaySpec::run(ProcessingContext& pc) { - o2::globaltracking::RecoContainer recoData; - recoData.collectData(pc, *mDataRequest); static bool first = false; if (first == false) { if (mDisplay->startDisplay()) { @@ -80,33 +79,12 @@ void O2GPUDPLDisplaySpec::run(ProcessingContext& pc) } } + o2::globaltracking::RecoContainer recoData; + recoData.collectData(pc, *mDataRequest); GPUTrackingInOutPointers ptrs; - if (mClMask[GlobalTrackID::TPC]) { - recoData.addTPCClusters(pc, false); - } - if (mTrkMask[GlobalTrackID::TPC]) { - recoData.addTPCTracks(pc, mUseMC); - } + GPUWorkflowHelper::fillIOPtr(ptrs, recoData, mUseMC, &(mConfig->configCalib), mClMask, mTrkMask, mTrkMask); if (mClMask[GlobalTrackID::TRD]) { - recoData.addTRDTracklets(pc); - } - if (mClMask[GlobalTrackID::TPC]) { - ptrs.clustersNative = &recoData.inputsTPCclusters->clusterIndex; - } - if (mTrkMask[GlobalTrackID::TPC]) { - const auto& tpcTracks = recoData.getTPCTracks(); - const auto& tpcClusRefs = recoData.getTPCTracksClusterRefs(); - ptrs.outputTracksTPCO2 = tpcTracks.data(); - ptrs.nOutputTracksTPCO2 = tpcTracks.size(); - ptrs.outputClusRefsTPCO2 = tpcClusRefs.data(); - ptrs.nOutputClusRefsTPCO2 = tpcClusRefs.size(); - } - if (mClMask[GlobalTrackID::TRD]) { - o2::trd::getRecoInputContainer(pc, &ptrs, &recoData); - } - if (mUseMC) { - const auto& tpcTracksMC = recoData.getTPCTracksMCLabels(); - ptrs.outputTracksTPCO2MC = tpcTracksMC.data(); + o2::trd::getRecoInputContainer(pc, &ptrs, &recoData); // TODO: Get rid of this, to be done inside the fillIOPtr, but first needs some changes in RecoInputContainer } mDisplay->show(&ptrs); From 2b179f84c33139e06c47dffa339e47c6b025ca7b Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 4 May 2021 23:02:50 +0200 Subject: [PATCH 407/770] GPU DPL Display: Bugfix: Was not parsing configKeyValues --- GPU/Workflow/src/O2GPUDPLDisplay.cxx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/GPU/Workflow/src/O2GPUDPLDisplay.cxx b/GPU/Workflow/src/O2GPUDPLDisplay.cxx index 976e1cfb80e20..60dbd0106cbf1 100644 --- a/GPU/Workflow/src/O2GPUDPLDisplay.cxx +++ b/GPU/Workflow/src/O2GPUDPLDisplay.cxx @@ -99,6 +99,8 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { WorkflowSpec specs; + o2::conf::ConfigurableParam::updateFromString(cfgc.options().get("configKeyValues")); + bool useMC = cfgc.options().get("enable-mc"); GlobalTrackID::mask_t srcTrk = GlobalTrackID::getSourcesMask(cfgc.options().get("display-tracks")); GlobalTrackID::mask_t srcCl = GlobalTrackID::getSourcesMask(cfgc.options().get("display-clusters")); From 5754babd149ec2e2c21b4a19fc015d27313e9f8d Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 4 May 2021 23:57:47 +0200 Subject: [PATCH 408/770] Some work to make TOF cluster and BaseCluster compatible to GPU --- Common/MathUtils/include/MathUtils/Cartesian.h | 6 +++--- DataFormats/Detectors/TOF/CMakeLists.txt | 4 ++-- .../TOF/include/DataFormatsTOF/Cluster.h | 16 ++++++++++------ DataFormats/Detectors/TOF/src/Cluster.cxx | 4 ++-- .../ReconstructionDataFormats/BaseCluster.h | 10 ++++++++-- Detectors/TOF/reconstruction/src/Clusterer.cxx | 6 +++--- GPU/Common/GPUCommonRtypes.h | 1 + GPU/Common/GPUROOTCartesianFwd.h | 2 +- GPU/GPUTracking/display/GPUDisplay.cxx | 4 ++++ GPU/GPUTracking/qa/GPUQA.cxx | 2 +- 10 files changed, 35 insertions(+), 20 deletions(-) diff --git a/Common/MathUtils/include/MathUtils/Cartesian.h b/Common/MathUtils/include/MathUtils/Cartesian.h index ef51fa4a9203b..1308c0bd496eb 100644 --- a/Common/MathUtils/include/MathUtils/Cartesian.h +++ b/Common/MathUtils/include/MathUtils/Cartesian.h @@ -17,7 +17,7 @@ #include "GPUCommonDef.h" #include "GPUCommonRtypes.h" -#if !defined(GPUCA_STANDALONE) && !defined(GPUCA_GPUCODE) +#if (!defined(GPUCA_STANDALONE) || !defined(DGPUCA_NO_ROOT)) && !defined(GPUCA_GPUCODE) && !defined(GPUCOMMONRTYPES_H_ACTIVE) #include #include #include @@ -150,7 +150,7 @@ class Rotation2D using Rotation2Df_t = Rotation2D; using Rotation2Dd_t = Rotation2D; -#if !defined(GPUCA_STANDALONE) && !defined(GPUCA_ALIGPUCODE) +#if (!defined(GPUCA_STANDALONE) || !defined(DGPUCA_NO_ROOT)) && !defined(GPUCA_GPUCODE) && !defined(GPUCOMMONRTYPES_H_ACTIVE) class Transform3D : public ROOT::Math::Transform3D { @@ -249,7 +249,7 @@ class Transform3D : public ROOT::Math::Transform3D } // namespace math_utils } // namespace o2 -#if !defined(GPUCA_STANDALONE) && !defined(GPUCA_ALIGPUCODE) +#if (!defined(GPUCA_STANDALONE) || !defined(DGPUCA_NO_ROOT)) && !defined(GPUCA_GPUCODE) && !defined(GPUCOMMONRTYPES_H_ACTIVE) std::ostream& operator<<(std::ostream& os, const o2::math_utils::Rotation2Df_t& t); std::ostream& operator<<(std::ostream& os, const o2::math_utils::Rotation2Dd_t& t); diff --git a/DataFormats/Detectors/TOF/CMakeLists.txt b/DataFormats/Detectors/TOF/CMakeLists.txt index f929af63f27bb..52e6f593f25db 100644 --- a/DataFormats/Detectors/TOF/CMakeLists.txt +++ b/DataFormats/Detectors/TOF/CMakeLists.txt @@ -18,6 +18,7 @@ o2_add_library(DataFormatsTOF src/CalibInfoCluster.cxx src/CosmicInfo.cxx PUBLIC_LINK_LIBRARIES O2::ReconstructionDataFormats + O2::GPUCommon Boost::serialization) o2_target_root_dictionary(DataFormatsTOF @@ -30,5 +31,4 @@ o2_target_root_dictionary(DataFormatsTOF include/DataFormatsTOF/CompressedDataFormat.h include/DataFormatsTOF/CTF.h include/DataFormatsTOF/CalibInfoCluster.h - include/DataFormatsTOF/CosmicInfo.h - ) + include/DataFormatsTOF/CosmicInfo.h) diff --git a/DataFormats/Detectors/TOF/include/DataFormatsTOF/Cluster.h b/DataFormats/Detectors/TOF/include/DataFormatsTOF/Cluster.h index 0658241c7841e..03f515c3692c7 100644 --- a/DataFormats/Detectors/TOF/include/DataFormatsTOF/Cluster.h +++ b/DataFormats/Detectors/TOF/include/DataFormatsTOF/Cluster.h @@ -14,13 +14,15 @@ #ifndef ALICEO2_TOF_CLUSTER_H #define ALICEO2_TOF_CLUSTER_H +#include "GPUCommonRtypes.h" +#include "GPUCommonMath.h" #include "ReconstructionDataFormats/BaseCluster.h" +#include "CommonConstants/LHCConstants.h" +#ifndef GPUCA_GPUCODE #include // for base_object -#include #include -#include "CommonConstants/LHCConstants.h" #include -#include "Rtypes.h" +#endif namespace o2 { @@ -36,7 +38,7 @@ class Cluster : public o2::BaseCluster static constexpr float PhiOutOfRange = 9999; // used to check if phi was already calculated or not static constexpr int NPADSXSECTOR = 8736; - static constexpr Double_t BC_TIME_INPS_INV = 1.E-3 / o2::constants::lhc::LHCBunchSpacingNS; + static constexpr double BC_TIME_INPS_INV = 1.E-3 / o2::constants::lhc::LHCBunchSpacingNS; public: enum { kUpLeft = 0, // 2^0, 1st bit @@ -75,7 +77,7 @@ class Cluster : public o2::BaseCluster float getR() // Cluster Radius (it is the same in sector and global frame) { if (mR == RadiusOutOfRange) { - mR = TMath::Sqrt(getX() * getX() + getY() * getY() + getZ() * getZ()); + mR = o2::gpu::CAMath::Sqrt(getX() * getX() + getY() * getY() + getZ() * getZ()); } return mR; } @@ -83,7 +85,7 @@ class Cluster : public o2::BaseCluster float getPhi() // Cluster Phi in sector frame { if (mPhi == PhiOutOfRange) { - mPhi = TMath::ATan2(getY(), getX()); + mPhi = o2::gpu::CAMath::ATan2(getY(), getX()); } return mPhi; } @@ -138,7 +140,9 @@ class Cluster : public o2::BaseCluster ClassDefNV(Cluster, 4); }; +#ifndef GPUCA_GPUCODE std::ostream& operator<<(std::ostream& os, Cluster& c); +#endif } // namespace tof /// Defining o2::tof::Cluster explicitly as messageable diff --git a/DataFormats/Detectors/TOF/src/Cluster.cxx b/DataFormats/Detectors/TOF/src/Cluster.cxx index 1bf4096bef7fc..d783a86923fde 100644 --- a/DataFormats/Detectors/TOF/src/Cluster.cxx +++ b/DataFormats/Detectors/TOF/src/Cluster.cxx @@ -26,8 +26,8 @@ Cluster::Cluster(std::int16_t sensid, float x, float y, float z, float sy2, floa { // caching R and phi - mR = TMath::Sqrt(x * x + y * y); - mPhi = TMath::ATan2(y, x); + mR = o2::gpu::CAMath::Sqrt(x * x + y * y); + mPhi = o2::gpu::CAMath::ATan2(y, x); } //______________________________________________________________________ int Cluster::getNumOfContributingChannels() const diff --git a/DataFormats/Reconstruction/include/ReconstructionDataFormats/BaseCluster.h b/DataFormats/Reconstruction/include/ReconstructionDataFormats/BaseCluster.h index a202249016824..64eff7054044b 100644 --- a/DataFormats/Reconstruction/include/ReconstructionDataFormats/BaseCluster.h +++ b/DataFormats/Reconstruction/include/ReconstructionDataFormats/BaseCluster.h @@ -12,12 +12,14 @@ #define ALICEO2_BASE_BASECLUSTER_H #include -#include +#include "GPUCommonRtypes.h" +#ifndef GPUCA_GPUCODE +#include "DetectorsCommonDataFormats/DetMatrixCache.h" #include #include #include #include -#include "DetectorsCommonDataFormats/DetMatrixCache.h" +#endif namespace o2 { @@ -64,6 +66,7 @@ class BaseCluster T getSigmaYZ() const { return mSigmaYZ; } math_utils::Point3D getXYZ() const { return mPos; } math_utils::Point3D& getXYZ() { return mPos; } +#ifndef GPUCA_GPUCODE // position in local frame, no check for matrices cache validity math_utils::Point3D getXYZLoc(const o2::detectors::DetMatrixCache& dm) const { return dm.getMatrixT2L(mSensorID)(mPos); } // position in global frame, no check for matrices cache validity @@ -72,6 +75,7 @@ class BaseCluster // much faster for barrel detectors than using full 3D matrix. // no check for matrices cache validity math_utils::Point3D getXYZGloRot(const o2::detectors::DetMatrixCache& dm) const { return dm.getMatrixT2GRot(mSensorID)(mPos); } +#endif // get sensor id std::int16_t getSensorID() const { return mSensorID; } // get count field @@ -116,6 +120,7 @@ class BaseCluster ClassDefNV(BaseCluster, 2); }; +#ifndef GPUCA_GPUCODE template std::ostream& operator<<(std::ostream& os, const BaseCluster& c) { @@ -126,5 +131,6 @@ std::ostream& operator<<(std::ostream& os, const BaseCluster& c) << ") cnt:" << std::setw(4) << +c.getCount() << " bits:" << std::bitset<8>(c.getBits()); return os; } +#endif } // namespace o2 #endif diff --git a/Detectors/TOF/reconstruction/src/Clusterer.cxx b/Detectors/TOF/reconstruction/src/Clusterer.cxx index a9f4cc6645978..3081b2fc5ea0a 100644 --- a/Detectors/TOF/reconstruction/src/Clusterer.cxx +++ b/Detectors/TOF/reconstruction/src/Clusterer.cxx @@ -108,7 +108,7 @@ void Clusterer::processStrip(std::vector& clusters, MCLabelContainer co // check if the fired pad are close in space LOG(DEBUG) << "phi difference = " << iphi - iphi2; LOG(DEBUG) << "eta difference = " << ieta - ieta2; - if ((TMath::Abs(iphi - iphi2) > 1) || (TMath::Abs(ieta - ieta2) > 1)) { + if ((std::abs(iphi - iphi2) > 1) || (std::abs(ieta - ieta2) > 1)) { continue; } @@ -271,8 +271,8 @@ void Clusterer::buildCluster(Cluster& c, MCLabelContainer const* digitMCTruth) Geo::rotateToSector(pos, c.getSector()); c.setXYZ(pos[2], pos[0], pos[1]); // storing coordinates in sector frame: note that the rotation above puts z in pos[1], the radial coordinate in pos[2], and the tangent coordinate in pos[0] (this is to match the TOF residual system, where we don't use the radial component), so we swap their positions. - c.setR(TMath::Sqrt(pos[0] * pos[0] + pos[1] * pos[1])); // it is the R in the sector frame - c.setPhi(TMath::ATan2(pos[1], pos[0])); + c.setR(std::sqrt(pos[0] * pos[0] + pos[1] * pos[1])); // it is the R in the sector frame + c.setPhi(std::atan2(pos[1], pos[0])); float errY2 = Geo::XPAD * Geo::XPAD * inv12; float errZ2 = Geo::ZPAD * Geo::ZPAD * inv12; diff --git a/GPU/Common/GPUCommonRtypes.h b/GPU/Common/GPUCommonRtypes.h index e03108f3e12c6..64dba1ad8289e 100644 --- a/GPU/Common/GPUCommonRtypes.h +++ b/GPU/Common/GPUCommonRtypes.h @@ -16,6 +16,7 @@ #if defined(GPUCA_STANDALONE) || (defined(GPUCA_O2_LIB) && !defined(GPUCA_O2_INTERFACE)) || defined(GPUCA_GPULIBRARY) // clang-format off #if !defined(ROOT_Rtypes) && !defined(__CLING__) + #define GPUCOMMONRTYPES_H_ACTIVE #define ClassDef(name,id) #define ClassDefNV(name, id) #define ClassDefOverride(name, id) diff --git a/GPU/Common/GPUROOTCartesianFwd.h b/GPU/Common/GPUROOTCartesianFwd.h index dd8b9b53bbcb8..c9136bca932b9 100644 --- a/GPU/Common/GPUROOTCartesianFwd.h +++ b/GPU/Common/GPUROOTCartesianFwd.h @@ -58,7 +58,7 @@ template struct GPUPoint3D; } // namespace detail -#if !defined(GPUCA_STANDALONE) && !defined(GPUCA_GPUCODE) +#if (!defined(GPUCA_STANDALONE) || !defined(DGPUCA_NO_ROOT)) && !defined(GPUCA_GPUCODE) && !defined(GPUCOMMONRTYPES_H_ACTIVE) template using Point2D = ROOT::Math::PositionVector2D, ROOT::Math::DefaultCoordinateSystemTag>; template diff --git a/GPU/GPUTracking/display/GPUDisplay.cxx b/GPU/GPUTracking/display/GPUDisplay.cxx index d9cc7a780367e..884ddd74c46ee 100644 --- a/GPU/GPUTracking/display/GPUDisplay.cxx +++ b/GPU/GPUTracking/display/GPUDisplay.cxx @@ -11,6 +11,10 @@ /// \file GPUDisplay.cxx /// \author David Rohr +#ifndef GPUCA_NO_ROOT +#include "Rtypes.h" // Include ROOT header first, to use ROOT and disable replacements +#endif + #include "GPUDisplay.h" #ifdef GPUCA_BUILD_EVENT_DISPLAY diff --git a/GPU/GPUTracking/qa/GPUQA.cxx b/GPU/GPUTracking/qa/GPUQA.cxx index 4d3617b6dec41..81e473284d708 100644 --- a/GPU/GPUTracking/qa/GPUQA.cxx +++ b/GPU/GPUTracking/qa/GPUQA.cxx @@ -14,7 +14,7 @@ #define QA_DEBUG 0 #define QA_TIMING 0 -#include "Rtypes.h" +#include "Rtypes.h" // Include ROOT header first, to use ROOT and disable replacements #include "TH1F.h" #include "TH2F.h" From 7635eb823951e61a2ebb16664c1cabc6a5481eb0 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 5 May 2021 13:05:28 +0200 Subject: [PATCH 409/770] GPU: TRDTracker should use GPUInfo(...) instead of ROOT Info(...) --- GPU/GPUTracking/DataTypes/GPUTRDDef.h | 5 ----- GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx | 2 +- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/GPU/GPUTracking/DataTypes/GPUTRDDef.h b/GPU/GPUTracking/DataTypes/GPUTRDDef.h index 2d2c294353e94..7c57dc18ccb30 100644 --- a/GPU/GPUTracking/DataTypes/GPUTRDDef.h +++ b/GPU/GPUTracking/DataTypes/GPUTRDDef.h @@ -89,11 +89,6 @@ class GPUTRDTracker_t; typedef GPUTRDTracker_t GPUTRDTracker; typedef GPUTRDTracker_t GPUTRDTrackerGPU; -#if defined(GPUCA_ALIGPUCODE) && !defined(GPUCA_ALIROOT_LIB) && !defined(__CLING__) && !defined(__ROOTCLING__) && !defined(G__ROOT) -#define Error(...) -#define Warning(...) -#define Info(...) -#endif } // namespace gpu } // namespace GPUCA_NAMESPACE diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx index 862888276fead..abb80959432cc 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx @@ -1310,7 +1310,7 @@ GPUd() bool GPUTRDTracker_t::AdjustSector(PROP* prop, TRDTRK* t) c if (CAMath::Abs(y) > 2.f * yMax) { if (ENABLE_INFO) { - Info("AdjustSector", "Track %i with pT = %f crossing two sector boundaries at x = %f", t->GetTPCtrackId(), t->getPt(), t->getX()); + GPUInfo("AdjustSector: Track %i with pT = %f crossing two sector boundaries at x = %f", t->GetTPCtrackId(), t->getPt(), t->getX()); } return false; } From 369ce4969b6f50ba834dfe7a7543c16898b71378 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 5 May 2021 13:07:06 +0200 Subject: [PATCH 410/770] TOF Cluster: Add const getters for R / Phi --- .../TOF/include/DataFormatsTOF/Cluster.h | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/DataFormats/Detectors/TOF/include/DataFormatsTOF/Cluster.h b/DataFormats/Detectors/TOF/include/DataFormatsTOF/Cluster.h index 03f515c3692c7..65c199781279c 100644 --- a/DataFormats/Detectors/TOF/include/DataFormatsTOF/Cluster.h +++ b/DataFormats/Detectors/TOF/include/DataFormatsTOF/Cluster.h @@ -89,6 +89,21 @@ class Cluster : public o2::BaseCluster } return mPhi; } + float getR() const // Cluster Radius (it is the same in sector and global frame) + { + if (mR == RadiusOutOfRange) { + return o2::gpu::CAMath::Sqrt(getX() * getX() + getY() * getY() + getZ() * getZ()); + } + return mR; + } + + float getPhi() const // Cluster Phi in sector frame + { + if (mPhi == PhiOutOfRange) { + return o2::gpu::CAMath::ATan2(getY(), getX()); + } + return mPhi; + } void setR(float value) { mR = value; } void setPhi(float value) { mPhi = value; } From 1c5ba95d947cb332f154ecaa47c553731dee7746 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Wed, 5 May 2021 13:50:33 +0200 Subject: [PATCH 411/770] TOF Geometry: Add possibility to initialize it manually --- Detectors/TOF/base/include/TOFBase/Geo.h | 2 +- Detectors/TOF/base/src/Geo.cxx | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/Detectors/TOF/base/include/TOFBase/Geo.h b/Detectors/TOF/base/include/TOFBase/Geo.h index f98be5d4d012d..5270fce6075d4 100644 --- a/Detectors/TOF/base/include/TOFBase/Geo.h +++ b/Detectors/TOF/base/include/TOFBase/Geo.h @@ -279,9 +279,9 @@ class Geo static Int_t getECHFromCH(int chan) { return CHAN_TO_ELCHAN[chan]; } static Int_t getCHFromECH(int echan) { return ELCHAN_TO_CHAN[echan]; } - private: static void Init(); + private: static Int_t getSector(const Float_t* pos); static Int_t getPlate(const Float_t* pos); static Int_t getPadZ(const Float_t* pos); diff --git a/Detectors/TOF/base/src/Geo.cxx b/Detectors/TOF/base/src/Geo.cxx index 6bad7895f0c09..ccdb62eead474 100644 --- a/Detectors/TOF/base/src/Geo.cxx +++ b/Detectors/TOF/base/src/Geo.cxx @@ -31,6 +31,9 @@ Float_t Geo::mPadPosition[NSECTORS][NPLATES][NMAXNSTRIP][NPADZ][NPADX][3]; void Geo::Init() { + if (!mToBeIntit) { + return; + } LOG(INFO) << "tof::Geo: Initialization of TOF rotation parameters"; if (!gGeoManager) { From 3c25378466a4b1d4d9691258fbde91f4186c0854 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 6 May 2021 10:41:40 +0200 Subject: [PATCH 412/770] Remove unused include --- Detectors/TOF/base/include/TOFBase/Geo.h | 2 +- .../TOF/calibration/include/TOFCalibration/TOFFEElightConfig.h | 1 + .../TOF/calibration/include/TOFCalibration/TOFFEElightReader.h | 2 +- .../include/TOFWorkflowUtils/TOFDigitWriterSplitterSpec.h | 1 + 4 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Detectors/TOF/base/include/TOFBase/Geo.h b/Detectors/TOF/base/include/TOFBase/Geo.h index 5270fce6075d4..b80b678b9391f 100644 --- a/Detectors/TOF/base/include/TOFBase/Geo.h +++ b/Detectors/TOF/base/include/TOFBase/Geo.h @@ -13,7 +13,7 @@ #include "Rtypes.h" #include "CommonConstants/LHCConstants.h" -#include "DetectorsRaw/HBFUtils.h" +//#include "DetectorsRaw/HBFUtils.h" namespace o2 { diff --git a/Detectors/TOF/calibration/include/TOFCalibration/TOFFEElightConfig.h b/Detectors/TOF/calibration/include/TOFCalibration/TOFFEElightConfig.h index ec22c967c39cb..493e4752ff45f 100644 --- a/Detectors/TOF/calibration/include/TOFCalibration/TOFFEElightConfig.h +++ b/Detectors/TOF/calibration/include/TOFCalibration/TOFFEElightConfig.h @@ -13,6 +13,7 @@ #include "Rtypes.h" #include "TOFBase/Geo.h" +#include using namespace o2::tof; diff --git a/Detectors/TOF/calibration/include/TOFCalibration/TOFFEElightReader.h b/Detectors/TOF/calibration/include/TOFCalibration/TOFFEElightReader.h index b9adbdacb04fa..eac643dce3157 100644 --- a/Detectors/TOF/calibration/include/TOFCalibration/TOFFEElightReader.h +++ b/Detectors/TOF/calibration/include/TOFCalibration/TOFFEElightReader.h @@ -49,7 +49,7 @@ struct TOFFEElightInfo { bool getChannelEnabled(int idx) { return idx < Geo::NCHANNELS ? mChannelEnabled[idx] : false; } int getMatchingWindow(int idx) { return idx < Geo::NCHANNELS ? mMatchingWindow[idx] : 0; } int getLatencyWindow(int idx) { return idx < Geo::NCHANNELS ? mLatencyWindow[idx] : 0; } - uint getTriggerMask(int ddl) { return ddl < TOFFEElightConfig::NTRIGGERMAPS ? mTriggerMask[ddl] : 0; } + uint64_t getTriggerMask(int ddl) { return ddl < TOFFEElightConfig::NTRIGGERMAPS ? mTriggerMask[ddl] : 0; } ClassDefNV(TOFFEElightInfo, 1); }; diff --git a/Detectors/TOF/workflow/include/TOFWorkflowUtils/TOFDigitWriterSplitterSpec.h b/Detectors/TOF/workflow/include/TOFWorkflowUtils/TOFDigitWriterSplitterSpec.h index e2ad14c1a49a1..9be1ed64361e7 100644 --- a/Detectors/TOF/workflow/include/TOFWorkflowUtils/TOFDigitWriterSplitterSpec.h +++ b/Detectors/TOF/workflow/include/TOFWorkflowUtils/TOFDigitWriterSplitterSpec.h @@ -21,6 +21,7 @@ #include "TOFBase/Digit.h" #include "Framework/Logger.h" #include +#include #include using namespace o2::framework; From 1d2b1dcd7f52ae4596d37871a88eaf457c586ad4 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 6 May 2021 10:42:35 +0200 Subject: [PATCH 413/770] Minor modifications such that ITS geometry does not break GPU Standalone compilation when headers are included --- Detectors/Base/include/DetectorsBase/GeometryManager.h | 2 +- Detectors/ITSMFT/ITS/base/include/ITSBase/GeometryTGeo.h | 8 +++++++- Detectors/ITSMFT/ITS/base/src/GeometryTGeo.cxx | 1 + 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/Detectors/Base/include/DetectorsBase/GeometryManager.h b/Detectors/Base/include/DetectorsBase/GeometryManager.h index 17d92ee2097df..8aeac0457b3e6 100644 --- a/Detectors/Base/include/DetectorsBase/GeometryManager.h +++ b/Detectors/Base/include/DetectorsBase/GeometryManager.h @@ -22,7 +22,7 @@ #include // for TObject #include #include "DetectorsCommonDataFormats/DetID.h" -#include "FairLogger.h" // for LOG +#include "GPUCommonLogger.h" // for LOG #include "MathUtils/Cartesian.h" #include "DetectorsBase/MatCell.h" #include diff --git a/Detectors/ITSMFT/ITS/base/include/ITSBase/GeometryTGeo.h b/Detectors/ITSMFT/ITS/base/include/ITSBase/GeometryTGeo.h index 02b46cb982050..e9ec3cfd1e7ca 100644 --- a/Detectors/ITSMFT/ITS/base/include/ITSBase/GeometryTGeo.h +++ b/Detectors/ITSMFT/ITS/base/include/ITSBase/GeometryTGeo.h @@ -53,10 +53,14 @@ class GeometryTGeo : public o2::itsmft::GeometryTGeo static GeometryTGeo* Instance() { // get (create if needed) a unique instance of the object +#ifdef GPUCA_STANDALONE + return nullptr; // TODO: DR: Obviously wrong, but to make it compile for now +#else if (!sInstance) { sInstance = std::unique_ptr(new GeometryTGeo(true, 0)); } return sInstance.get(); +#endif } // adopt the unique instance from external raw pointer (to be used only to read saved instance from file) @@ -74,7 +78,7 @@ class GeometryTGeo : public o2::itsmft::GeometryTGeo ); /// Default destructor - ~GeometryTGeo() override = default; + ~GeometryTGeo() override; GeometryTGeo(const GeometryTGeo& src) = delete; GeometryTGeo& operator=(const GeometryTGeo& geom) = delete; @@ -345,7 +349,9 @@ class GeometryTGeo : public o2::itsmft::GeometryTGeo static std::string sWrapperVolumeName; ///< Wrapper volume name private: +#ifndef GPUCA_STANDALONE static std::unique_ptr sInstance; ///< singletone instance +#endif ClassDefOverride(GeometryTGeo, 1); // ITS geometry based on TGeo }; diff --git a/Detectors/ITSMFT/ITS/base/src/GeometryTGeo.cxx b/Detectors/ITSMFT/ITS/base/src/GeometryTGeo.cxx index eeb3917886377..750557981c643 100644 --- a/Detectors/ITSMFT/ITS/base/src/GeometryTGeo.cxx +++ b/Detectors/ITSMFT/ITS/base/src/GeometryTGeo.cxx @@ -49,6 +49,7 @@ using Segmentation = o2::itsmft::SegmentationAlpide; ClassImp(o2::its::GeometryTGeo); std::unique_ptr GeometryTGeo::sInstance; +o2::its::GeometryTGeo::~GeometryTGeo() = default; std::string GeometryTGeo::sVolumeName = "ITSV"; ///< Mother volume name std::string GeometryTGeo::sLayerName = "ITSULayer"; ///< Layer name From 51b3e840e0b15941f8b93b21c2c7e91d5df5daeb Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 4 May 2021 23:03:10 +0200 Subject: [PATCH 414/770] GPU Display: Show ITS and TOF Clusters --- GPU/GPUTracking/CMakeLists.txt | 3 + GPU/GPUTracking/Definitions/GPUSettingsList.h | 2 + GPU/GPUTracking/Standalone/CMakeLists.txt | 4 + GPU/GPUTracking/display/GPUDisplay.cxx | 144 ++++++++++++++++-- GPU/GPUTracking/display/GPUDisplay.h | 21 ++- GPU/GPUTracking/display/GPUDisplayKeys.cxx | 6 +- GPU/Workflow/CMakeLists.txt | 1 + .../include/GPUWorkflow/O2GPUDPLDisplay.h | 5 + GPU/Workflow/src/O2GPUDPLDisplay.cxx | 16 +- 9 files changed, 186 insertions(+), 16 deletions(-) diff --git a/GPU/GPUTracking/CMakeLists.txt b/GPU/GPUTracking/CMakeLists.txt index 204a68228444f..d18b95d256b5b 100644 --- a/GPU/GPUTracking/CMakeLists.txt +++ b/GPU/GPUTracking/CMakeLists.txt @@ -279,8 +279,11 @@ if(ALIGPU_BUILD_TYPE STREQUAL "O2") PUBLIC_LINK_LIBRARIES O2::GPUCommon O2::GPUUtils O2::DataFormatsTPC + O2::DataFormatsTOF O2::TPCBase O2::TRDBase + O2::TOFBase + O2::ITSBase O2::ITStracking O2::TPCFastTransformation O2::DetectorsRaw diff --git a/GPU/GPUTracking/Definitions/GPUSettingsList.h b/GPU/GPUTracking/Definitions/GPUSettingsList.h index b0176f879692e..da62ecb1d66bb 100644 --- a/GPU/GPUTracking/Definitions/GPUSettingsList.h +++ b/GPU/GPUTracking/Definitions/GPUSettingsList.h @@ -183,6 +183,8 @@ AddOption(pointSize, float, 2.0f, "", 0, "Set point size") AddOption(lineWidth, float, 1.4f, "", 0, "Set line width") AddOption(drawTPC, bool, true, "", 0, "Enable drawing TPC data") AddOption(drawTRD, bool, true, "", 0, "Enabale drawing TRD data") +AddOption(drawTOF, bool, true, "", 0, "Enabale drawing TOF data") +AddOption(drawITS, bool, true, "", 0, "Enabale drawing ITS data") AddHelp("help", 'h') EndConfig() diff --git a/GPU/GPUTracking/Standalone/CMakeLists.txt b/GPU/GPUTracking/Standalone/CMakeLists.txt index 7834259d045af..85d27e3e586a9 100644 --- a/GPU/GPUTracking/Standalone/CMakeLists.txt +++ b/GPU/GPUTracking/Standalone/CMakeLists.txt @@ -151,6 +151,7 @@ include_directories(${GPUTRACKING_DIR}/TPCClusterFinder ${O2_DIR}/DataFormats/common/include ${O2_DIR}/DataFormats/Detectors/Common/include ${O2_DIR}/DataFormats/Detectors/ITSMFT/ITS/include + ${O2_DIR}/DataFormats/Detectors/TOF/include ${O2_DIR}/DataFormats/Detectors/TPC/include ${O2_DIR}/DataFormats/Detectors/TRD/include ${O2_DIR}/DataFormats/Headers/include @@ -160,12 +161,15 @@ include_directories(${GPUTRACKING_DIR}/TPCClusterFinder ${O2_DIR}/DataFormats/simulation/include ${O2_DIR}/Detectors/Base/include ${O2_DIR}/Detectors/Base/src + ${O2_DIR}/Detectors/ITSMFT/common/base/include + ${O2_DIR}/Detectors/ITSMFT/ITS/base/include ${O2_DIR}/Detectors/ITSMFT/ITS/tracking/include ${O2_DIR}/Detectors/ITSMFT/ITS/tracking/cuda/include ${O2_DIR}/Detectors/ITSMFT/ITS/tracking/cuda/src ${O2_DIR}/Detectors/ITSMFT/ITS/tracking/hip/include ${O2_DIR}/Detectors/ITSMFT/ITS/tracking/hip/src ${O2_DIR}/Detectors/Raw/include + ${O2_DIR}/Detectors/TOF/base/include ${O2_DIR}/Detectors/TPC/base/include ${O2_DIR}/Detectors/TRD/base/include ${O2_DIR}/Detectors/TRD/base/src) diff --git a/GPU/GPUTracking/display/GPUDisplay.cxx b/GPU/GPUTracking/display/GPUDisplay.cxx index 884ddd74c46ee..b25cd2abb7f4f 100644 --- a/GPU/GPUTracking/display/GPUDisplay.cxx +++ b/GPU/GPUTracking/display/GPUDisplay.cxx @@ -58,6 +58,9 @@ #ifdef HAVE_O2HEADERS #include "DataFormatsTPC/TrackTPC.h" +#include "DataFormatsTOF/Cluster.h" +#include "TOFBase/Geo.h" +#include "ITSBase/GeometryTGeo.h" #endif #include "GPUDisplayShaders.h" @@ -362,6 +365,30 @@ inline void GPUDisplay::SetColorTRD() } ActivateColor(); } +inline void GPUDisplay::SetColorITS() +{ + if (mCfg.colorCollisions) { + return; + } + if (mInvertColors) { + mDrawColor = {1.00, 0.1, 0.1}; + } else { + mDrawColor = {1.00, 0.3, 0.3}; + } + ActivateColor(); +} +inline void GPUDisplay::SetColorTOF() +{ + if (mCfg.colorCollisions) { + return; + } + if (mInvertColors) { + mDrawColor = {0.1, 1.0, 0.1}; + } else { + mDrawColor = {0.5, 1.0, 0.5}; + } + ActivateColor(); +} inline void GPUDisplay::SetColorInitLinks() { if (mInvertColors) { @@ -737,6 +764,36 @@ GPUDisplay::vboList GPUDisplay::DrawSpacePointsTRD(int iSlice, int select, int i return (vboList(startCount, mVertexBufferStart[iSlice].size() - startCount, iSlice)); } +GPUDisplay::vboList GPUDisplay::DrawSpacePointsTOF(int iSlice, int select, int iCol) +{ + size_t startCount = mVertexBufferStart[iSlice].size(); + size_t startCountInner = mVertexBuffer[iSlice].size(); + + if (iCol == 0 && iSlice == 0) { + for (unsigned int i = 0; i < mIOPtrs->nTOFClusters; i++) { + mVertexBuffer[iSlice].emplace_back(mGlobalPosTOF[i].x, mGlobalPosTOF[i].y, mProjectXY ? 0 : mGlobalPosTOF[i].z); + } + } + + insertVertexList(iSlice, startCountInner, mVertexBuffer[iSlice].size()); + return (vboList(startCount, mVertexBufferStart[iSlice].size() - startCount, iSlice)); +} + +GPUDisplay::vboList GPUDisplay::DrawSpacePointsITS(int iSlice, int select, int iCol) +{ + size_t startCount = mVertexBufferStart[iSlice].size(); + size_t startCountInner = mVertexBuffer[iSlice].size(); + + if (iCol == 0 && iSlice == 0 && mIOPtrs->itsClusters) { + for (unsigned int i = 0; i < mIOPtrs->nItsClusters; i++) { + mVertexBuffer[iSlice].emplace_back(mGlobalPosITS[i].x, mGlobalPosITS[i].y, mProjectXY ? 0 : mGlobalPosITS[i].z); + } + } + + insertVertexList(iSlice, startCountInner, mVertexBuffer[iSlice].size()); + return (vboList(startCount, mVertexBufferStart[iSlice].size() - startCount, iSlice)); +} + GPUDisplay::vboList GPUDisplay::DrawClusters(int iSlice, int select, int iCol) { size_t startCount = mVertexBufferStart[iSlice].size(); @@ -1330,6 +1387,21 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) mGlobalPosTRD = mGlobalPosPtrTRD.get(); mGlobalPosTRD2 = mGlobalPosPtrTRD2.get(); } + + mCurrentClustersITS = mIOPtrs->itsClusters ? mIOPtrs->nItsClusters : 0; + if (mNMaxClustersITS < mCurrentClustersITS) { + mNMaxClustersITS = mCurrentClustersITS; + mGlobalPosPtrITS.reset(new float4[mNMaxClustersITS]); + mGlobalPosITS = mGlobalPosPtrITS.get(); + } + + mCurrentClustersTOF = mIOPtrs->nTOFClusters; + if (mNMaxClustersTOF < mCurrentClustersTOF) { + mNMaxClustersTOF = mCurrentClustersTOF; + mGlobalPosPtrTOF.reset(new float4[mNMaxClustersTOF]); + mGlobalPosTOF = mGlobalPosPtrTOF.get(); + } + unsigned int nTpcMergedTracks = mConfig.showTPCTracksFromO2Format ? mIOPtrs->nOutputTracksTPCO2 : mIOPtrs->nMergedTracks; if ((size_t)nTpcMergedTracks > mTRDTrackIds.size()) { mTRDTrackIds.resize(nTpcMergedTracks); @@ -1344,12 +1416,8 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) } mMaxClusterZ = 0; - bool error = false; GPUCA_OPENMP(parallel for num_threads(getNumThreads()) reduction(max : mMaxClusterZ)) for (int iSlice = 0; iSlice < NSLICES; iSlice++) { - if (error) { - continue; - } int row = 0; unsigned int nCls = mParam->par.earlyTpcTransform ? mIOPtrs->nClusterData[iSlice] : mIOPtrs->clustersNative->nClustersSector[iSlice]; for (unsigned int i = 0; i < nCls; i++) { @@ -1365,9 +1433,7 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) } } if (cid >= mNMaxClusters) { - GPUError("Cluster Buffer Size exceeded (id %d max %d)", cid, mNMaxClusters); - error = true; - break; + throw std::runtime_error("Cluster Buffer Size exceeded"); } float4* ptr = &mGlobalPos[cid]; if (mParam->par.earlyTpcTransform) { @@ -1397,9 +1463,6 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) ptr->w = tCLUSTER; } } - if (error) { - return (1); - } GPUCA_OPENMP(parallel for num_threads(getNumThreads()) reduction(max : mMaxClusterZ)) for (int i = 0; i < mCurrentSpacePointsTRD; i++) { @@ -1425,6 +1488,41 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) ptr->w = tTRDCLUSTER; } + GPUCA_OPENMP(parallel for num_threads(getNumThreads()) reduction(max : mMaxClusterZ)) + for (int i = 0; i < mCurrentClustersTOF; i++) { + float4* ptr = &mGlobalPosTOF[i]; +#ifdef HAVE_O2HEADERS + mParam->Slice2Global(mIOPtrs->tofClusters[i].getSector(), mIOPtrs->tofClusters[i].getX() + mXadd, mIOPtrs->tofClusters[i].getY(), mIOPtrs->tofClusters[i].getZ(), &ptr->x, &ptr->y, &ptr->z); + ptr->x /= GL_SCALE_FACTOR; + ptr->y /= GL_SCALE_FACTOR; + ptr->z /= GL_SCALE_FACTOR; +#endif + if (fabsf(ptr->z) > mMaxClusterZ) { + mMaxClusterZ = fabsf(ptr->z); + } + ptr->w = tTOFCLUSTER; + } + + //GPUCA_OPENMP(parallel for num_threads(getNumThreads()) reduction(max : mMaxClusterZ)) + for (int i = 0; i < mCurrentClustersITS; i++) { + float4* ptr = &mGlobalPosITS[i]; +#ifdef HAVE_O2HEADERS + const auto& cl = mIOPtrs->itsClusters[i]; + auto* itsGeo = o2::its::GeometryTGeo::Instance(); + auto p = cl.getXYZGlo(*itsGeo); + ptr->x = p.X(); + ptr->y = p.Y(); + ptr->z = p.Z(); + ptr->x /= GL_SCALE_FACTOR; + ptr->y /= GL_SCALE_FACTOR; + ptr->z /= GL_SCALE_FACTOR; +#endif + if (fabsf(ptr->z) > mMaxClusterZ) { + mMaxClusterZ = fabsf(ptr->z); + } + ptr->w = tITSCLUSTER; + } + mTimerFPS.ResetStart(); mFramesDoneFPS = 0; mFPSScaleadjust = 0; @@ -1913,6 +2011,24 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) } } + for (int iSlice = 0; iSlice < NSLICES; iSlice++) { + for (int i = N_POINTS_TYPE_TPC + N_POINTS_TYPE_TRD; i < N_POINTS_TYPE_TPC + N_POINTS_TYPE_TRD + N_POINTS_TYPE_TOF; i++) { + for (int iCol = 0; iCol < mNCollissions; iCol++) { + mGlDLPoints[iSlice][i][iCol] = DrawSpacePointsTOF(iSlice, i, iCol); + } + } + break; // TODO: Only slice 0 filled for now + } + + for (int iSlice = 0; iSlice < NSLICES; iSlice++) { + for (int i = N_POINTS_TYPE_TPC + N_POINTS_TYPE_TRD + N_POINTS_TYPE_TOF; i < N_POINTS_TYPE_TPC + N_POINTS_TYPE_TRD + N_POINTS_TYPE_TOF + N_POINTS_TYPE_ITS; i++) { + for (int iCol = 0; iCol < mNCollissions; iCol++) { + mGlDLPoints[iSlice][i][iCol] = DrawSpacePointsITS(iSlice, i, iCol); + } + } + break; // TODO: Only slice 0 filled for now + } + mGlDLrecent = 1; size_t totalVertizes = 0; for (int i = 0; i < NSLICES; i++) { @@ -2026,6 +2142,14 @@ int GPUDisplay::DrawGLScene_internal(bool mixAnimation, float mAnimateTime) LOOP_SLICE LOOP_COLLISION_COL(drawVertices(mGlDLPoints[iSlice][tTRDATTACHED][iCol], GL_LINES)); } } + if (mCfg.drawTOF) { + SetColorTOF(); + LOOP_SLICE LOOP_COLLISION_COL(drawVertices(mGlDLPoints[0][tTOFCLUSTER][0], GL_POINTS)); + } + if (mCfg.drawITS) { + SetColorITS(); + LOOP_SLICE LOOP_COLLISION_COL(drawVertices(mGlDLPoints[0][tITSCLUSTER][0], GL_POINTS)); + } if (mCfg.drawTPC) { SetColorClusters(); LOOP_SLICE LOOP_COLLISION_COL(drawVertices(mGlDLPoints[iSlice][tCLUSTER][iCol], GL_POINTS)); diff --git a/GPU/GPUTracking/display/GPUDisplay.h b/GPU/GPUTracking/display/GPUDisplay.h index d0d68a4ed0673..5070cbadd5cd8 100644 --- a/GPU/GPUTracking/display/GPUDisplay.h +++ b/GPU/GPUTracking/display/GPUDisplay.h @@ -105,9 +105,11 @@ class GPUDisplay private: static constexpr int NSLICES = GPUChainTracking::NSLICES; - static constexpr const int N_POINTS_TYPE = 11; + static constexpr const int N_POINTS_TYPE = 13; static constexpr const int N_POINTS_TYPE_TPC = 9; static constexpr const int N_POINTS_TYPE_TRD = 2; + static constexpr const int N_POINTS_TYPE_TOF = 1; + static constexpr const int N_POINTS_TYPE_ITS = 1; static constexpr const int N_LINES_TYPE = 7; static constexpr const int N_FINAL_TYPE = 4; static constexpr int TRACK_TYPE_ID_LIMIT = 100; @@ -121,7 +123,9 @@ class GPUDisplay tFINALTRACK = 7, tMARKED = 8, tTRDCLUSTER = 9, - tTRDATTACHED = 10 }; + tTRDATTACHED = 10, + tTOFCLUSTER = 11, + tITSCLUSTER = 12 }; enum LineTypes { RESERVED = 0 /*1 -- 6 = INITLINK to GLOBALTRACK*/ }; typedef std::tuple vboList; @@ -210,6 +214,8 @@ class GPUDisplay void showInfo(const char* info); void ActivateColor(); void SetColorTRD(); + void SetColorTOF(); + void SetColorITS(); void SetColorClusters(); void SetColorInitLinks(); void SetColorLinks(); @@ -234,7 +240,8 @@ class GPUDisplay void drawPointLinestrip(int iSlice, int cid, int id, int id_limit = TRACK_TYPE_ID_LIMIT); vboList DrawClusters(int iSlice, int select, int iCol); vboList DrawSpacePointsTRD(int iSlice, int select, int iCol); - vboList DrawSpacePointsTRD(const GPUTPCTracker& tracker, int select, int iCol); + vboList DrawSpacePointsTOF(int iSlice, int select, int iCol); + vboList DrawSpacePointsITS(int iSlice, int select, int iCol); vboList DrawLinks(const GPUTPCTracker& tracker, int id, bool dodown = false); vboList DrawSeeds(const GPUTPCTracker& tracker); vboList DrawTracklets(const GPUTPCTracker& tracker); @@ -330,13 +337,21 @@ class GPUDisplay std::unique_ptr mGlobalPosPtr; std::unique_ptr mGlobalPosPtrTRD; std::unique_ptr mGlobalPosPtrTRD2; + std::unique_ptr mGlobalPosPtrITS; + std::unique_ptr mGlobalPosPtrTOF; float4* mGlobalPos; float4* mGlobalPosTRD; float4* mGlobalPosTRD2; + float4* mGlobalPosITS; + float4* mGlobalPosTOF; int mNMaxClusters = 0; int mNMaxSpacePointsTRD = 0; + int mNMaxClustersITS = 0; + int mNMaxClustersTOF = 0; int mCurrentClusters = 0; int mCurrentSpacePointsTRD = 0; + int mCurrentClustersITS = 0; + int mCurrentClustersTOF = 0; std::vector mTRDTrackIds; int mGlDLrecent = 0; diff --git a/GPU/GPUTracking/display/GPUDisplayKeys.cxx b/GPU/GPUTracking/display/GPUDisplayKeys.cxx index 1dde4f82eb397..b2755ccd02ebe 100644 --- a/GPU/GPUTracking/display/GPUDisplayKeys.cxx +++ b/GPU/GPUTracking/display/GPUDisplayKeys.cxx @@ -60,7 +60,7 @@ const char* HelpText[] = { "[ALT] / [CTRL] / [m] Focus camera on origin / orient y-axis upwards (combine with [SHIFT] to lock) / Cycle through modes", "[RCTRL] / [RALT] Rotate model instead of camera / rotate TPC around beamline", "[1] ... [8] / [N] Enable display of clusters, preseeds, seeds, starthits, tracklets, tracks, global tracks, merged tracks / Show assigned clusters in colors" - "[F1] / [F2] Enable / disable drawing of TPC / TRD" + "[F1] / [F2] / [F3] / [F4] Enable / disable drawing of TPC / TRD / TOF / ITS" // FREE: none // Test setting: ^ --> mHideUnmatchedClusters }; @@ -324,6 +324,10 @@ void GPUDisplay::HandleKeyRelease(unsigned char key) mCfg.drawTPC ^= 1; } else if (key == mBackend->KEY_F2) { mCfg.drawTRD ^= 1; + } else if (key == mBackend->KEY_F3) { + mCfg.drawTOF ^= 1; + } else if (key == mBackend->KEY_F4) { + mCfg.drawITS ^= 1; } else if (key == 't') { GPUInfo("Taking screenshot"); static int nScreenshot = 1; diff --git a/GPU/Workflow/CMakeLists.txt b/GPU/Workflow/CMakeLists.txt index eb29b31e3f229..3d1941aa0a494 100644 --- a/GPU/Workflow/CMakeLists.txt +++ b/GPU/Workflow/CMakeLists.txt @@ -53,6 +53,7 @@ if(ALIGPU_BUILD_TYPE STREQUAL "O2" O2::DataFormatsGlobalTracking O2::TPCFastTransformation O2::TRDBase + O2::TOFBase O2::TPCReconstruction O2::GlobalTrackingWorkflowHelpers) target_include_directories(${targetName} PUBLIC "include") diff --git a/GPU/Workflow/include/GPUWorkflow/O2GPUDPLDisplay.h b/GPU/Workflow/include/GPUWorkflow/O2GPUDPLDisplay.h index 2211dedb65793..b7fdfc163919b 100644 --- a/GPU/Workflow/include/GPUWorkflow/O2GPUDPLDisplay.h +++ b/GPU/Workflow/include/GPUWorkflow/O2GPUDPLDisplay.h @@ -23,6 +23,10 @@ namespace o2::globaltracking { struct DataRequest; } +namespace o2::itsmft +{ +class TopologyDictionary; +} namespace o2::gpu { @@ -47,6 +51,7 @@ class O2GPUDPLDisplaySpec : public o2::framework::Task std::unique_ptr mConfig; std::unique_ptr mFastTransform; std::unique_ptr mTrdGeo; + std::unique_ptr mITSDict; std::shared_ptr mDataRequest; }; diff --git a/GPU/Workflow/src/O2GPUDPLDisplay.cxx b/GPU/Workflow/src/O2GPUDPLDisplay.cxx index 60dbd0106cbf1..f37e795abe97e 100644 --- a/GPU/Workflow/src/O2GPUDPLDisplay.cxx +++ b/GPU/Workflow/src/O2GPUDPLDisplay.cxx @@ -16,6 +16,8 @@ #include "DetectorsBase/GeometryManager.h" #include "TRDBase/GeometryFlat.h" #include "TRDBase/Geometry.h" +#include "TOFBase/Geo.h" +#include "ITSBase/GeometryTGeo.h" #include "DetectorsBase/Propagator.h" #include "GPUO2InterfaceDisplay.h" #include "GPUO2InterfaceConfiguration.h" @@ -25,6 +27,7 @@ #include "DataFormatsTPC/WorkflowHelper.h" #include "DataFormatsTRD/RecoInputContainer.h" #include "GPUWorkflowHelper/GPUWorkflowHelper.h" +#include "DataFormatsITSMFT/TopologyDictionary.h" using namespace o2::framework; using namespace o2::dataformats; @@ -67,6 +70,13 @@ void O2GPUDPLDisplaySpec::init(InitContext& ic) mTrdGeo.reset(new o2::trd::GeometryFlat(*gm)); mConfig->configCalib.trdGeometry = mTrdGeo.get(); + mITSDict = std::make_unique(); + mConfig->configCalib.itsPatternDict = mITSDict.get(); + + o2::tof::Geo::Init(); + + o2::its::GeometryTGeo::Instance()->fillMatrixCache(o2::math_utils::bit2Mask(o2::math_utils::TransformType::T2GRot, o2::math_utils::TransformType::T2G, o2::math_utils::TransformType::L2G, o2::math_utils::TransformType::T2L)); + mDisplay.reset(new GPUO2InterfaceDisplay(mConfig.get())); } @@ -82,9 +92,11 @@ void O2GPUDPLDisplaySpec::run(ProcessingContext& pc) o2::globaltracking::RecoContainer recoData; recoData.collectData(pc, *mDataRequest); GPUTrackingInOutPointers ptrs; - GPUWorkflowHelper::fillIOPtr(ptrs, recoData, mUseMC, &(mConfig->configCalib), mClMask, mTrkMask, mTrkMask); + auto tmpContainer = GPUWorkflowHelper::fillIOPtr(ptrs, recoData, mUseMC, &(mConfig->configCalib), mClMask, mTrkMask, mTrkMask); + + decltype(o2::trd::getRecoInputContainer(pc, &ptrs, &recoData)) trdInputContainer; if (mClMask[GlobalTrackID::TRD]) { - o2::trd::getRecoInputContainer(pc, &ptrs, &recoData); // TODO: Get rid of this, to be done inside the fillIOPtr, but first needs some changes in RecoInputContainer + trdInputContainer = std::move(o2::trd::getRecoInputContainer(pc, &ptrs, &recoData)); // TODO: Get rid of this, to be done inside the fillIOPtr, but first needs some changes in RecoInputContainer } mDisplay->show(&ptrs); From bcac62df45bedf208ccf18c5112308b5eb0881e9 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Thu, 6 May 2021 17:55:17 +0200 Subject: [PATCH 415/770] Code cleanup --- .../ZDC/include/DataFormatsZDC/RecEvent.h | 75 ++- .../Detectors/ZDC/src/DataFormatsZDCLinkDef.h | 1 + .../ZDC/base/include/ZDCBase/Constants.h | 12 + Detectors/ZDC/macro/CMakeLists.txt | 5 + Detectors/ZDC/macro/CreateIntegrationParam.C | 75 +++ Detectors/ZDC/reconstruction/CMakeLists.txt | 15 +- .../include/ZDCReconstruction/DigiReco.h | 72 +- .../include/ZDCReconstruction/RecoParamZDC.h | 32 +- .../ZDCReconstruction/ZDCIntegrationParam.h | 14 +- Detectors/ZDC/reconstruction/src/DigiReco.cxx | 626 ++++++++---------- .../src/ZDCIntegrationParam.cxx | 4 +- 11 files changed, 496 insertions(+), 435 deletions(-) create mode 100644 Detectors/ZDC/macro/CreateIntegrationParam.C diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h index 6e13d1489a15c..6e7ae27776f27 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h @@ -16,6 +16,7 @@ #include "ZDCBase/Constants.h" #include #include +#include /// \file RecEvent.h /// \brief Class to describe reconstructed ZDC event (single BC with signal in one of detectors) @@ -25,38 +26,66 @@ namespace o2 { namespace zdc { - struct RecEvent { //using TDCChannel = std::array; //using TDCAmplitude = std::array; //using TDCChannel = std::vector; //using TDCAmplitude = std::vector; o2::InteractionRecord ir; - uint32_t flags; /// reconstruction flags -// std::array energyZEM; /// signal in the electromagnetic ZDCs -// std::array energyZNA; /// reco E in 5 ZNA sectors + sum -// std::array energyZNC; /// reco E in 5 ZNC sectors + sum -// std::array energyZPA; /// reco E in 5 ZPA sectors + sum -// std::array energyZPC; /// reco E in 5 ZPC sectors + sum - float energyZEM[NChannelsZEM]; /// signal in the electromagnetic ZDCs - float energyZNA[NChannelsZN]; /// reco E in 5 ZNA sectors + sum - float energyZNC[NChannelsZN]; /// reco E in 5 ZNC sectors + sum - float energyZPA[NChannelsZP]; /// reco E in 5 ZPA sectors + sum - float energyZPC[NChannelsZP]; /// reco E in 5 ZPC sectors + sum - math_utils::Point2D centroidZNA; /// centroid coordinates for ZNA - math_utils::Point2D centroidZNC; /// centroid coordinates for ZNC - //std::array tdcChannels; /// At most MaxTDCValues Values in ns per TDC channel - //std::array tdcAmplitudes; /// At most MaxTDCValues Values in ns per TDC channel - int16_t tdcChannels[NTDCChannels][MaxTDCValues]; /// TdcChannels - float tdcAmplitudes[NTDCChannels][MaxTDCValues]; /// TdcAmplitudes - int ntdc[NTDCChannels]={0}; - std::array pattern; /// Pattern of TDC - uint16_t fired[NTDCChannels] = {0}; /// Position at which the trigger algorithm is fired - float inter[NTDCChannels][NTimeBinsPerBC * TSN] = {0}; /// Interpolated samples - uint32_t ref[NChannels]={O2_ZDC_REF_INIT}; /// Cache of references + uint32_t flags; /// reconstruction flags + std::map ezdc; /// signal in ZDCs + float energy[NChannels] = {O2_ZDC_FLT_INIT}; /// ZDC signal + math_utils::Point2D centroidZNA; /// centroid coordinates for ZNA + math_utils::Point2D centroidZNC; /// centroid coordinates for ZNC + int16_t tdcVal[NTDCChannels][MaxTDCValues]; /// TdcChannels + float tdcAmp[NTDCChannels][MaxTDCValues]; /// TdcAmplitudes + int ntdc[NTDCChannels] = {0}; + std::array pattern; /// Pattern of TDC + uint16_t fired[NTDCChannels] = {0}; /// Position at which the trigger algorithm is fired + float inter[NTDCChannels][NTimeBinsPerBC * TSN] = {0}; /// Interpolated samples + uint32_t ref[NChannels] = {O2_ZDC_REF_INIT}; /// Cache of references void print() const; + float EZDC(uint8_t ich) + { + std::map::iterator it = ezdc.find(ich); + if (it != ezdc.end()) { + return it->second; + } else { + return -std::numeric_limits::infinity(); + } + } + + float EZNAC() { return EZDC(IdZNAC); } + float EZNA1() { return EZDC(IdZNA1); } + float EZNA2() { return EZDC(IdZNA2); } + float EZNA3() { return EZDC(IdZNA3); } + float EZNA4() { return EZDC(IdZNA4); } + float EZNASum() { return EZDC(IdZNASum); } + + float EZPAC() { return EZDC(IdZPAC); } + float EZPA1() { return EZDC(IdZPA1); } + float EZPA2() { return EZDC(IdZPA2); } + float EZPA3() { return EZDC(IdZPA3); } + float EZPA4() { return EZDC(IdZPA4); } + float EZPASum() { return EZDC(IdZPASum); } + + float EZEM1() { return EZDC(IdZEM1); } + float EZEM2() { return EZDC(IdZEM2); } + + float EZNCC() { return EZDC(IdZNCC); } + float EZNC1() { return EZDC(IdZNC1); } + float EZNC2() { return EZDC(IdZNC2); } + float EZNC3() { return EZDC(IdZNC3); } + float EZNC4() { return EZDC(IdZNC4); } + float EZNCSum() { return EZDC(IdZNCSum); } + float EZPCC() { return EZDC(IdZPCC); } + float EZPC1() { return EZDC(IdZPC1); } + float EZPC2() { return EZDC(IdZPC2); } + float EZPC3() { return EZDC(IdZPC3); } + float EZPC4() { return EZDC(IdZPC4); } + float EZPCSum() { return EZDC(IdZPCSum); } ClassDefNV(RecEvent, 1); }; diff --git a/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h b/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h index 386e6426b00ca..bcac26d11c23a 100644 --- a/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h +++ b/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h @@ -24,6 +24,7 @@ #pragma link C++ class o2::zdc::ChannelData + ; #pragma link C++ class o2::zdc::BCData + ; #pragma link C++ class o2::zdc::OrbitData + ; +#pragma link C++ class o2::zdc::RecEvent + ; #pragma link C++ class std::vector < o2::zdc::ChannelData> + ; #pragma link C++ class std::vector < o2::zdc::BCData> + ; #pragma link C++ class std::vector < o2::zdc::OrbitData> + ; diff --git a/Detectors/ZDC/base/include/ZDCBase/Constants.h b/Detectors/ZDC/base/include/ZDCBase/Constants.h index 583542fdf4b30..eebbec2e3bf6a 100644 --- a/Detectors/ZDC/base/include/ZDCBase/Constants.h +++ b/Detectors/ZDC/base/include/ZDCBase/Constants.h @@ -13,6 +13,7 @@ #include "CommonConstants/PhysicsConstants.h" #include +#include #include #include #include @@ -56,6 +57,11 @@ constexpr int NChannels = 2 * (NChannelsZN + NChannelsZP) + NChannelsZEM; #define O2_ZDC_REF_INIT_ZDC O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL, O2_ZDC_REF_INIT_VAL #define O2_ZDC_REF_INIT O2_ZDC_REF_INIT_ZDC, O2_ZDC_REF_INIT_ZDC, O2_ZDC_REF_INIT_ZEM, O2_ZDC_REF_INIT_ZDC, O2_ZDC_REF_INIT_ZDC +#define O2_ZDC_FLT_INIT_VAL -INFINITY +#define O2_ZDC_FLT_INIT_ZEM O2_ZDC_FLT_INIT_VAL, O2_ZDC_FLT_INIT_VAL +#define O2_ZDC_FLT_INIT_ZDC O2_ZDC_FLT_INIT_VAL, O2_ZDC_FLT_INIT_VAL, O2_ZDC_FLT_INIT_VAL, O2_ZDC_FLT_INIT_VAL, O2_ZDC_FLT_INIT_VAL, O2_ZDC_FLT_INIT_VAL +#define O2_ZDC_FLT_INIT O2_ZDC_FLT_INIT_ZDC, O2_ZDC_FLT_INIT_ZDC, O2_ZDC_FLT_INIT_ZEM, O2_ZDC_FLT_INIT_ZDC, O2_ZDC_FLT_INIT_ZDC + constexpr uint8_t ALICETriggerMask = 0x1; constexpr int NModules = 8; @@ -190,6 +196,12 @@ constexpr int DbgFull = 3; const std::string CCDBPathConfigSim = "ZDC/Config/Sim"; const std::string CCDBPathConfigModule = "ZDC/Config/Module"; +const std::string CCDBPathConfigReco= "ZDC/Calib/RecoParam"; +const std::string CCDBPathConfigIntegration= "ZDC/Calib/IntegrationParam"; +const std::string CCDBPathTDCCalib= "ZDC/Calib/TDCCalib"; + +// Placeholders +constexpr int DummyIntRange = -NTimeBinsPerBC -1; constexpr std::string_view DummyName = "Dumm"; constexpr std::string_view VoidName = " NA "; diff --git a/Detectors/ZDC/macro/CMakeLists.txt b/Detectors/ZDC/macro/CMakeLists.txt index 46f4575ceaf36..23143ec9aad44 100644 --- a/Detectors/ZDC/macro/CMakeLists.txt +++ b/Detectors/ZDC/macro/CMakeLists.txt @@ -20,3 +20,8 @@ o2_add_test_root_macro(CreateModuleConfig.C o2_add_test_root_macro(readZDCDigits.C PUBLIC_LINK_LIBRARIES O2::ZDCSimulation O2::CCDB LABELS zdc) + +o2_add_test_root_macro(CreateIntegrationParam.C + PUBLIC_LINK_LIBRARIES O2::ZDCBase O2::ZDCReconstruction + O2::SimulationDataFormat O2::CCDB + LABELS zdc) diff --git a/Detectors/ZDC/macro/CreateIntegrationParam.C b/Detectors/ZDC/macro/CreateIntegrationParam.C new file mode 100644 index 0000000000000..df8ba52bfc70d --- /dev/null +++ b/Detectors/ZDC/macro/CreateIntegrationParam.C @@ -0,0 +1,75 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#if !defined(__CLING__) || defined(__ROOTCLING__) + +#include "FairLogger.h" +#include "CCDB/CcdbApi.h" +#include "ZDCReconstruction/ZDCIntegrationParam.h" +#include "ZDCBase/Constants.h" +#include +#include +#include + +#endif + +using namespace o2::zdc; +using namespace std; + +void CreateIntegrationParam(long tmin = 0, long tmax = -1, + std::string ccdbHost = "http://ccdb-test.cern.ch:8080") +{ + + ZDCIntegrationParam conf; + + // Integration limits for all signals + // Values should be in range -12..11 + // Channel ID, signal begin, end, pedestal begin, end + conf.setIntegration(IdZNAC, 5, 9, -12, -8); + conf.setIntegration(IdZNA1, 5, 9, -12, -8); + conf.setIntegration(IdZNA2, 5, 9, -12, -8); + conf.setIntegration(IdZNA3, 5, 9, -12, -8); + conf.setIntegration(IdZNA4, 5, 9, -12, -8); + conf.setIntegration(IdZNASum, 5, 9, -12, -8); + // + conf.setIntegration(IdZPAC, 5, 9, -12, -8); + conf.setIntegration(IdZPA1, 5, 9, -12, -8); + conf.setIntegration(IdZPA2, 5, 9, -12, -8); + conf.setIntegration(IdZPA3, 5, 9, -12, -8); + conf.setIntegration(IdZPA4, 5, 9, -12, -8); + conf.setIntegration(IdZPASum, 5, 9, -12, -8); + // + conf.setIntegration(IdZEM1, 5, 9, -12, -8); + conf.setIntegration(IdZEM2, 5, 9, -12, -8); + // + conf.setIntegration(IdZNCC, 5, 9, -12, -8); + conf.setIntegration(IdZNC1, 5, 9, -12, -8); + conf.setIntegration(IdZNC2, 5, 9, -12, -8); + conf.setIntegration(IdZNC3, 5, 9, -12, -8); + conf.setIntegration(IdZNC4, 5, 9, -12, -8); + conf.setIntegration(IdZNCSum, 5, 9, -12, -8); + // + conf.setIntegration(IdZPCC, 5, 9, -12, -8); + conf.setIntegration(IdZPC1, 5, 9, -12, -8); + conf.setIntegration(IdZPC2, 5, 9, -12, -8); + conf.setIntegration(IdZPC3, 5, 9, -12, -8); + conf.setIntegration(IdZPC4, 5, 9, -12, -8); + conf.setIntegration(IdZPCSum, 5, 9, -12, -8); + + conf.print(); + + o2::ccdb::CcdbApi api; + map metadata; // can be empty + api.init(ccdbHost.c_str()); // or http://localhost:8080 for a local installation + // store abitrary user object in strongly typed manner + api.storeAsTFileAny(&conf, CCDBPathConfigIntegration, metadata, tmin, tmax); + + // return conf; +} diff --git a/Detectors/ZDC/reconstruction/CMakeLists.txt b/Detectors/ZDC/reconstruction/CMakeLists.txt index cde859dd602ce..fa310cfd0e2bb 100644 --- a/Detectors/ZDC/reconstruction/CMakeLists.txt +++ b/Detectors/ZDC/reconstruction/CMakeLists.txt @@ -1,12 +1,12 @@ -#Copyright CERN and copyright holders of ALICE O2.This software is distributed -#under the terms of the GNU General Public License v3(GPL Version 3), copied -#verbatim in the file "COPYING". +# Copyright CERN and copyright holders of ALICE O2.This software is distributed +# under the terms of the GNU General Public License v3(GPL Version 3), copied +# verbatim in the file "COPYING". # -#See http: //alice-o2.web.cern.ch/license for full licensing information. +# See http: //alice-o2.web.cern.ch/license for full licensing information. # -#In applying this license CERN does not waive the privileges and immunities -#granted to it by virtue of its status as an Intergovernmental Organization or -#submit itself to any jurisdiction. +# In applying this license CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization or +# submit itself to any jurisdiction. o2_add_library(ZDCReconstruction SOURCES src/CTFCoder.cxx @@ -14,6 +14,7 @@ o2_add_library(ZDCReconstruction src/DigiReco.cxx src/RecoParamZDC.cxx src/ZDCTDCParam.cxx + src/ZDCIntegrationParam.cxx PUBLIC_LINK_LIBRARIES O2::ZDCBase O2::DataFormatsZDC O2::ZDCSimulation diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h index 7ebdf7357a0ab..79d638e948b86 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h @@ -1,4 +1,14 @@ -#include +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include #include #include #include "ZDCBase/Constants.h" @@ -22,18 +32,25 @@ class DigiReco { public: DigiReco() = default; - ~DigiReco() { - mTDbg->Write(); - mDbg->Close(); + ~DigiReco() + { + if (mTreeDbg) { + mTDbg->Write(); + mDbg->Close(); + } } void init(); - int process(const std::vector *orbitdata, const std::vector *bcdata, const std::vector *chdata); + int process(const std::vector* orbitdata, const std::vector* bcdata, const std::vector* chdata); int write(); void setVerbosity(int v) { mVerbosity = v; } int getVerbosity() const { return mVerbosity; } + void setDebugOutput(bool state = true) + { + mTreeDbg = state; + } void setModuleConfig(const ModuleConfig* moduleConfig) { mModuleConfig = moduleConfig; }; const ModuleConfig* getModuleConfig() { return mModuleConfig; }; @@ -41,32 +58,33 @@ class DigiReco const ZDCTDCParam* getTDCParam() { return mTDCParam; }; void setIntegrationParam(const ZDCIntegrationParam* param) { mIntParam = param; }; const ZDCIntegrationParam* getIntegrationParam() { return mIntParam; }; - const ModuleConfig* mModuleConfig = nullptr; /// Trigger/readout configuration object private: - int reconstruct(int seq_beg, int seq_end); /// Main method for data reconstruction - void processTrigger(int itdc, int ibeg, int iend); /// Replay of trigger algorithm on acquired data - void interpolate(int itdc, int ibeg, int iend); /// Interpolation of samples to evaluate signal amplitude and arrival time + const ModuleConfig* mModuleConfig = nullptr; /// Trigger/readout configuration object + int reconstruct(int seq_beg, int seq_end); /// Main method for data reconstruction + void processTrigger(int itdc, int ibeg, int iend); /// Replay of trigger algorithm on acquired data + void interpolate(int itdc, int ibeg, int iend); /// Interpolation of samples to evaluate signal amplitude and arrival time void assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float amp); // Set reconstructed TDC values - bool mIsContinuous = true; /// continuous (self-triggered) or externally-triggered readout - int mNBCAHead = 0; /// when storing triggered BC, store also mNBCAHead BCs - const ZDCTDCParam* mTDCParam = nullptr; /// TDC calibration object - uint32_t mTDCMask[NTDCChannels]={0}; /// Identify TDC channels in trigger mask - const ZDCIntegrationParam* mIntParam = nullptr; /// Configuration of integration - bool mVerbosity=DbgFull; - Double_t mTS[NTS]; /// Tapered sinc function - TFile* mDbg = nullptr; /// Debug output - TTree* mTDbg = nullptr; /// Debug tree - const std::vector *mOrbitData; /// Reconstructed data - const std::vector *mBCData; /// BC info - const std::vector *mChData; /// Payload - std::vector mReco; /// Reconstructed data - std::map mOrbit; /// Information about orbit - static constexpr int mNSB = TSN * NTimeBinsPerBC; /// Total number of interpolated points per bunch crossing - RecEvent mRec; /// Debug reconstruction event + bool mIsContinuous = true; /// continuous (self-triggered) or externally-triggered readout + int mNBCAHead = 0; /// when storing triggered BC, store also mNBCAHead BCs + const ZDCTDCParam* mTDCParam = nullptr; /// TDC calibration object + uint32_t mTDCMask[NTDCChannels] = {0}; /// Identify TDC channels in trigger mask + const ZDCIntegrationParam* mIntParam = nullptr; /// Configuration of integration + bool mVerbosity = DbgFull; + Double_t mTS[NTS]; /// Tapered sinc function + bool mTreeDbg = false; /// Write reconstructed data in debug output file + TFile* mDbg = nullptr; /// Debug output file + TTree* mTDbg = nullptr; /// Debug tree + const std::vector* mOrbitData; /// Reconstructed data + const std::vector* mBCData; /// BC info + const std::vector* mChData; /// Payload + std::vector mReco; /// Reconstructed data + std::map mOrbit; /// Information about orbit + static constexpr int mNSB = TSN * NTimeBinsPerBC; /// Total number of interpolated points per bunch crossing + RecEvent mRec; /// Debug reconstruction event int mNBC = 0; - int16_t tdc_shift[NTDCChannels] = {0}; /// TDC correction (units of 1/96 ns) - constexpr static uint16_t mMask[NTimeBinsPerBC]={0x0001,0x002,0x004,0x008, 0x0010,0x0020,0x0040,0x0080, 0x0100,0x0200,0x0400,0x0800}; + int16_t tdc_shift[NTDCChannels] = {0}; /// TDC correction (units of 1/96 ns) + constexpr static uint16_t mMask[NTimeBinsPerBC] = {0x0001, 0x002, 0x004, 0x008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200, 0x0400, 0x0800}; }; } // namespace zdc } // namespace o2 diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h index 1bb44d1de0371..b7932ce353b7b 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/RecoParamZDC.h @@ -8,8 +8,8 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef O2_ZDC_RECOPARAMZDC_H_ -#define O2_ZDC_RECOPARAMZDC_H_ +#ifndef O2_ZDC_RECOPARAMZDC_H +#define O2_ZDC_RECOPARAMZDC_H #include #include "CommonUtils/ConfigurableParam.h" @@ -27,19 +27,21 @@ namespace zdc // parameters of ZDC reconstruction struct RecoParamZDC : public o2::conf::ConfigurableParamHelper { - Int_t tsh[NTDCChannels] = {4, 4, 4, 4, 4, 4, 4, 4, 4, 4}; // Trigger shift - Int_t tth[NTDCChannels] = {8, 8, 8, 8, 8, 8, 8, 8, 8, 8}; // Trigger threshold - Int_t tmod[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of TDC channel in raw data - Int_t tch[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of TDC channel in raw data - Int_t amod[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of ADC channel in raw data - Int_t ach[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of ADC channel in raw data - float tdc_shift[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Correction of TDC position (0-25 ns, units of ~10 ps) - float tdc_search[NTDCChannels] = {250, 250, 250, 250, 250, 250, 250, 250, 250, 250}; // Search zone for a TDC signal ideally 2.5 ns (units of ~10 ps) - Int_t beg_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Start integration - signal - Int_t end_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // End integration - signal - Int_t beg_ped_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Start integration - pedestal - Int_t end_ped_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // End integration - pedestal - std::array bitset = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Set bits in coincidence + Int_t tsh[NTDCChannels] = {4, 4, 4, 4, 4, 4, 4, 4, 4, 4}; // Trigger shift + Int_t tth[NTDCChannels] = {8, 8, 8, 8, 8, 8, 8, 8, 8, 8}; // Trigger threshold + Int_t tmod[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of TDC channel in raw data + Int_t tch[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of TDC channel in raw data + Int_t amod[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of ADC channel in raw data + Int_t ach[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Position of ADC channel in raw data + float tdc_shift[NTDCChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Correction of TDC position (0-25 ns, units of ~10 ps) + float tdc_search[NTDCChannels] = {250, 250, 250, 250, 250, 250, 250, 250, 250, 250}; // Search zone for a TDC signal ideally 2.5 ns (units of ~10 ps) + // Beginning and end of integration range: signal + Int_t beg_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; + Int_t end_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; + // Beginning and end of integration range: pedestal + Int_t beg_ped_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; + Int_t end_ped_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; + std::array bitset = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Set bits in coincidence public: void setBit(uint32_t ibit, bool val = true); O2ParamDef(RecoParamZDC, "RecoParamZDC"); diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCIntegrationParam.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCIntegrationParam.h index 5e62533d37a63..9dfd55dfaa218 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCIntegrationParam.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCIntegrationParam.h @@ -8,8 +8,8 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef O2_ZDC_INTEGRATIONPARAM_H_ -#define O2_ZDC_INTEGRATIONPARAM_H_ +#ifndef O2_ZDC_INTEGRATIONPARAM_H +#define O2_ZDC_INTEGRATIONPARAM_H #include "ZDCBase/Constants.h" #include @@ -27,10 +27,12 @@ namespace zdc struct ZDCIntegrationParam { public: - Int_t beg_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Start integration - signal - Int_t end_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // End integration - signal - Int_t beg_ped_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // Start integration - pedestal - Int_t end_ped_int[NChannels] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; // End integration - pedestal + // Beginning and end of integration range: signal + Int_t beg_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; + Int_t end_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; + // Beginning and end of integration range: pedestal + Int_t beg_ped_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; + Int_t end_ped_int[NChannels] = {DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange, DummyIntRange}; void setIntegration(uint32_t ich, int beg, int end, int beg_ped, int end_ped); void print(); diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index f8a420dc441f5..72f0394cd05c1 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -1,14 +1,27 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + #include #include "FairLogger.h" #include "ZDCReconstruction/DigiReco.h" #include "ZDCReconstruction/RecoParamZDC.h" +#define O2_ZDC_DIGIRECO_FLT float + namespace o2 { namespace zdc { - -void DigiReco::init(){ + +void DigiReco::init() +{ // Load configuration parameters auto& sopt = ZDCSimParam::Instance(); mIsContinuous = sopt.continuous; @@ -21,52 +34,55 @@ void DigiReco::init(){ // Prepare tapered sinc function // tsc/TSN =3.75 (~ 4) and TSL*TSN*sqrt(2)/tsc >> 1 (n. of sigma) - const Double_t tsc = 750; - Int_t n = TSL * TSN; - for (Int_t tsi = 0; tsi <= n; tsi++) { - Double_t arg1 = TMath::Pi() * Double_t(tsi) / Double_t(TSN); - Double_t fs = 1; + const O2_ZDC_DIGIRECO_FLT tsc = 750; + int n = TSL * TSN; + for (int tsi = 0; tsi <= n; tsi++) { + O2_ZDC_DIGIRECO_FLT arg1 = TMath::Pi() * O2_ZDC_DIGIRECO_FLT(tsi) / O2_ZDC_DIGIRECO_FLT(TSN); + O2_ZDC_DIGIRECO_FLT fs = 1; if (arg1 != 0) fs = TMath::Sin(arg1) / arg1; - Double_t arg2 = Double_t(tsi) / tsc; - Double_t fg = TMath::Exp(-arg2 * arg2); + O2_ZDC_DIGIRECO_FLT arg2 = O2_ZDC_DIGIRECO_FLT(tsi) / tsc; + O2_ZDC_DIGIRECO_FLT fg = TMath::Exp(-arg2 * arg2); mTS[n + tsi] = fs * fg; mTS[n - tsi] = mTS[n + tsi]; // Function is even } - // Open debug file - mDbg = new TFile("ZDCReco.root", "recreate"); - mTDbg = new TTree("zdcr", "ZDCReco"); - mTDbg->Branch("zdcr", "RecEvent", &mRec); + if (mTreeDbg) { + // Open debug file + mDbg = new TFile("ZDCReco.root", "recreate"); + mTDbg = new TTree("zdcr", "ZDCReco"); + mTDbg->Branch("zdcr", "RecEvent", &mRec); + } // Update reconstruction parameters //auto& ropt=RecoParamZDC::Instance(); o2::zdc::RecoParamZDC& ropt = const_cast(RecoParamZDC::Instance()); - // Fill maps - for (Int_t itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { + // Fill maps to decode the pattern of channels with hit + for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { // If the reconstruction parameters were not manually set if (ropt.tmod[itdc] < 0 || ropt.tch[itdc] < 0) { - Int_t isig = TDCSignal[itdc]; - for (Int_t im = 0; im < NModules; im++) { - for (UInt_t ic = 0; ic < NChPerModule; ic++) { + int isig = TDCSignal[itdc]; + for (int im = 0; im < NModules; im++) { + for (uint32_t ic = 0; ic < NChPerModule; ic++) { if (mModuleConfig->modules[im].channelID[ic] == isig && mModuleConfig->modules[im].readChannel[ic]) { //ropt.updateFromString(TString::Format("RecoParamZDC.tmod[%d]=%d;",itdc,im)); //ropt.updateFromString(TString::Format("RecoParamZDC.tch[%d]=%d;",itdc,ic)); ropt.tmod[itdc] = im; ropt.tch[itdc] = ic; - // Fill mask to identify TDC channels - mTDCMask[itdc]=(0x1<<(4*im+ic)); + // Fill mask to identify TDC channels + mTDCMask[itdc] = (0x1 << (4 * im + ic)); goto next_itdc; } } } } next_itdc:; - LOG(INFO) << "TDC " << itdc << "(" << ChannelNames[TDCSignal[itdc]] << ")" << " mod " << ropt.tmod[itdc] << " ch " << ropt.tch[itdc]; + LOG(INFO) << "TDC " << itdc << "(" << ChannelNames[TDCSignal[itdc]] << ")" + << " mod " << ropt.tmod[itdc] << " ch " << ropt.tch[itdc]; } // TDC calibration - for (Int_t itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { + for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { float fval = ropt.tdc_shift[itdc]; // If the reconstruction parameters were not manually set if (fval < 0) { @@ -89,16 +105,16 @@ void DigiReco::init(){ } // TDC search zone // TODO: override with configuration object - for (Int_t itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { + for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << ropt.tdc_search[itdc] << " i.s. = " << ropt.tdc_search[itdc] / 96. << " ns"; } // Fill maps channel maps for integration - for (Int_t ich = 0; ich < NChannels; ich++) { + for (int ich = 0; ich < NChannels; ich++) { // If the reconstruction parameters were not manually set if (ropt.amod[ich] < 0 || ropt.ach[ich] < 0) { - for (Int_t im = 0; im < NModules; im++) { - for (UInt_t ic = 0; ic < NChPerModule; ic++) { + for (int im = 0; im < NModules; im++) { + for (uint32_t ic = 0; ic < NChPerModule; ic++) { if (mModuleConfig->modules[im].channelID[ic] == ich && mModuleConfig->modules[im].readChannel[ic]) { ropt.amod[ich] = im; ropt.ach[ich] = ic; @@ -112,9 +128,9 @@ void DigiReco::init(){ } // Integration ranges - for (Int_t ich = 0; ich < NChannels; ich++) { + for (int ich = 0; ich < NChannels; ich++) { // If the reconstruction parameters were not manually set - if (ropt.beg_int[ich] < 0 || ropt.end_int[ich] < 0) { + if (ropt.beg_int[ich] <= DummyIntRange || ropt.end_int[ich] <= DummyIntRange) { if (!mIntParam) { LOG(ERROR) << "Integration for signal " << ich << " missing configuration object and no manual override"; } else { @@ -122,7 +138,7 @@ void DigiReco::init(){ ropt.end_int[ich] = mIntParam->end_int[ich]; } } - if (ropt.beg_ped_int[ich] < 0 || ropt.end_ped_int[ich] < 0) { + if (ropt.beg_ped_int[ich] <= DummyIntRange || ropt.end_ped_int[ich] <= DummyIntRange) { if (!mIntParam) { LOG(ERROR) << "Integration for pedestal " << ich << " missing configuration object and no manual override"; } else { @@ -130,89 +146,92 @@ void DigiReco::init(){ ropt.end_ped_int[ich] = mIntParam->end_ped_int[ich]; } } - LOG(INFO) << ChannelNames[ich] << " integration: signal=[" << ropt.beg_int[ich] << "-" << ropt.end_int[ich] << "] pedestal=[" << ropt.beg_ped_int[ich] << "-" << ropt.end_ped_int[ich] <<"]"; + LOG(INFO) << ChannelNames[ich] << " integration: signal=[" << ropt.beg_int[ich] << "-" << ropt.end_int[ich] << "] pedestal=[" << ropt.beg_ped_int[ich] << "-" << ropt.end_ped_int[ich] << "]"; } } -int DigiReco::process(const std::vector *orbitdata, const std::vector *bcdata, const std::vector *chdata){ +int DigiReco::process(const std::vector* orbitdata, const std::vector* bcdata, const std::vector* chdata) +{ // We assume that vectors contain data from a full time frame - mOrbitData=orbitdata; - mBCData=bcdata; - mChData=chdata; - - const std::vector &OrbitData=*orbitdata; - const std::vector &BCData=*bcdata; - const std::vector &ChData=*chdata; - + mOrbitData = orbitdata; + mBCData = bcdata; + mChData = chdata; + + const std::vector& OrbitData = *orbitdata; + const std::vector& BCData = *bcdata; + const std::vector& ChData = *chdata; + // Initialization of lookup structure for pedestals mOrbit.clear(); - int norb=OrbitData.size(); - for(Int_t iorb=0; iorb=DbgFull){ + int norb = OrbitData.size(); + for (int iorb = 0; iorb < norb; iorb++) { + mOrbit[OrbitData[iorb].ir.orbit] = iorb; + if (mVerbosity >= DbgFull) { LOG(INFO) << "OrbitData[" << OrbitData[iorb].ir.orbit << "] = " << iorb; } } - mNBC=BCData.size(); + mNBC = BCData.size(); mReco.clear(); - mReco.reserve(mNBC); + mReco.resize(mNBC); // Initialization of reco structure - for(Int_t ibc=0; ibcIdDummy && chd.id IdDummy && chd.id < NChannels) { + bcr.ref[chd.id] = chEnt; } chEnt++; } } - + // Probably this is not necessary -// for(Int_t itdc=0; itdc1){ + } else if (bcd > 1) { // Detected a gap reconstruct(seq_beg, seq_end); - seq_beg=ibc; - seq_end=ibc; - }else if(ibc==(mNBC-1)){ + seq_beg = ibc; + seq_end = ibc; + } else if (ibc == (mNBC - 1)) { // Last bunch - seq_end=ibc; + seq_end = ibc; reconstruct(seq_beg, seq_end); - seq_beg=mNBC; - seq_end=mNBC; - }else{ + seq_beg = mNBC; + seq_end = mNBC; + } else { // Look for another bunch - seq_end=ibc; + seq_end = ibc; } } -/* + /* std::map::iterator it; @@ -228,7 +247,8 @@ std::map::iterator it; return 0; } -int DigiReco::reconstruct(int ibeg, int iend){ +int DigiReco::reconstruct(int ibeg, int iend) +{ // Process consecutive BCs if (ibeg == iend) { LOG(INFO) << "Lonely bunch " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc; @@ -236,35 +256,22 @@ int DigiReco::reconstruct(int ibeg, int iend){ } LOG(INFO) << __func__ << "(" << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; // Get references to arrays - const std::vector &OrbitData=*mOrbitData; - const std::vector &BCData=*mBCData; - const std::vector &ChData=*mChData; + const std::vector& OrbitData = *mOrbitData; + const std::vector& BCData = *mBCData; + const std::vector& ChData = *mChData; // Get reconstruction parameters auto& ropt = RecoParamZDC::Instance(); -// int chEnt = bcd.ref.getFirstEntry(); -// for (int ic = 0; ic < bcd.ref.getEntries(); ic++) { -// const auto& chd = zdcChData[chEnt++]; -// chd.print(); -// UShort_t bc=bcd.ir.bc; -// UInt_t orbit=bcd.ir.orbit; -// for(Int_t is=0; isGetN(); -// gr[chd.id]->SetPoint(ip,3564.*orbit+bc+is/12.,myval); -// } -// } - // Apply differential discrimination with triple condition - for (Int_t itdc = 0; itdc < NTDCChannels; itdc++) { + for (int itdc = 0; itdc < NTDCChannels; itdc++) { // Check if channel has valid data for consecutive bunches in current bunch range // N.B. there are events recorded from ibeg-iend but we are not sure if it is the // case for every TDC channel int istart = -1, istop = -1; // Loop allows for gaps in the data sequence for each TDC channel for (int ibun = ibeg; ibun <= iend; ibun++) { - if (BCData[ibun].channels&mTDCMask[itdc]) { // TDC channel has data for this event + if (BCData[ibun].channels & mTDCMask[itdc]) { // TDC channel has data for this event if (istart < 0) { istart = ibun; } @@ -289,56 +296,56 @@ int DigiReco::reconstruct(int ibeg, int iend){ // Reconstruct integrated charges and fill output tree // TODO: compare average pedestal with estimation from current event // TODO: failover in case of discrepancy - for (Int_t ibun = ibeg; ibun <= iend; ibun++) { + for (int ibun = ibeg; ibun <= iend; ibun++) { // Look for offset float pbun[NChannels]; - auto orbit=BCData[ibun].ir.orbit; - std::map::iterator it = mOrbit.find(orbit); - if (it != mOrbit.end()){ + auto orbit = BCData[ibun].ir.orbit; + std::map::iterator it = mOrbit.find(orbit); + if (it != mOrbit.end()) { // Subtract pedestal - auto &orbitdata=OrbitData[it->second]; - for(int ich=0; ichsecond]; + for (int ich = 0; ich < NChannels; ich++) { + pbun[ich] = orbitdata.asFloat(ich); } - }else{ + } else { LOG(ERROR) << "Missing pedestal for bunch " << ibun; - for(int ich=0; ich::infinity(); + for (int ich = 0; ich < NChannels; ich++) { + pbun[ich] = std::numeric_limits::infinity(); } } // Debug dump of pedestal - if(mVerbosity>=DbgFull){ - for(int ich=0; ich= DbgFull) { + for (int ich = 0; ich < NChannels; ich++) { + LOG(INFO) << "bunch: " << ibun << " ch: " << ich << " " << ChannelNames[ich] << " offset: " << pbun[ich]; } } - RecEvent &rec = mReco[ibun]; - for (Int_t itdc = 0; itdc < NTDCChannels; itdc++) { - if(rec.fired[itdc]!=0x0){ - printf("%d %u.%u TDC %d %x", ibun, rec.ir.orbit, rec.ir.bc, itdc,rec.fired[itdc]); - for (Int_t isam = 0; isam < NTimeBinsPerBC; isam++) { - printf("%d", rec.fired[itdc]&mMask[isam]?1:0); - } - printf("\n"); + RecEvent& rec = mReco[ibun]; + for (int itdc = 0; itdc < NTDCChannels; itdc++) { + if (rec.fired[itdc] != 0x0) { + printf("%d %u.%u TDC %d %x", ibun, rec.ir.orbit, rec.ir.bc, itdc, rec.fired[itdc]); + for (int isam = 0; isam < NTimeBinsPerBC; isam++) { + printf("%d", rec.fired[itdc] & mMask[isam] ? 1 : 0); + } + printf("\n"); } -// for (Int_t i = 0; i < MaxTDCValues; i++) { -// rec.tdcChannels[itdc][i] = kMinShort; -// rec.tdcAmplitudes[itdc][i] = -999; -// } + // for (int i = 0; i < MaxTDCValues; i++) { + // rec.tdcVal[itdc][i] = kMinShort; + // rec.tdcAmp[itdc][i] = -999; + // } rec.pattern[itdc] = 0; - for(int32_t i=0; iFill(); + } } // Loop on bunches } @@ -498,48 +414,48 @@ void DigiReco::processTrigger(int itdc, int ibeg, int iend) { LOG(INFO) << __func__ << "(itdc=" << itdc << "[" << ChannelNames[TDCSignal[itdc]] << "] ," << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; - const std::vector &OrbitData=*mOrbitData; - const std::vector &BCData=*mBCData; - const std::vector &ChData=*mChData; + const std::vector& OrbitData = *mOrbitData; + const std::vector& BCData = *mBCData; + const std::vector& ChData = *mChData; // Get reconstruction parameters auto& ropt = RecoParamZDC::Instance(); -// int chEnt = bcd.ref.getFirstEntry(); -// for (int ic = 0; ic < bcd.ref.getEntries(); ic++) { -// const auto& chd = zdcChData[chEnt++]; -// chd.print(); -// UShort_t bc=bcd.ir.bc; -// UInt_t orbit=bcd.ir.orbit; -// for(Int_t is=0; isGetN(); -// gr[chd.id]->SetPoint(ip,3564.*orbit+bc+is/12.,myval); -// } -// } - - Int_t nbun = iend - ibeg + 1; - Int_t maxs2 = NTimeBinsPerBC * nbun - 1; - Int_t shift = ropt.tsh[itdc]; - Int_t thr = ropt.tth[itdc]; - - Int_t is1 = 0, is2 = 1; - Int_t isfired[3] = {0}; - Int_t it1=0,it2=0,ib1=-1,ib2=-1; + // int chEnt = bcd.ref.getFirstEntry(); + // for (int ic = 0; ic < bcd.ref.getEntries(); ic++) { + // const auto& chd = zdcChData[chEnt++]; + // chd.print(); + // auto bc=bcd.ir.bc; + // auto orbit=bcd.ir.orbit; + // for(int is=0; isGetN(); + // gr[chd.id]->SetPoint(ip,3564.*orbit+bc+is/12.,myval); + // } + // } + + int nbun = iend - ibeg + 1; + int maxs2 = NTimeBinsPerBC * nbun - 1; + int shift = ropt.tsh[itdc]; + int thr = ropt.tth[itdc]; + + int is1 = 0, is2 = 1; + int isfired[3] = {0}; + int it1 = 0, it2 = 0, ib1 = -1, ib2 = -1; for (;;) { // Shift data - for (Int_t i = 1; i < 3; i++) { + for (int i = 1; i < 3; i++) { isfired[i] = isfired[i - 1]; } // Bunches and samples that are used in the difference - Int_t b1 = ibeg + is1 / NTimeBinsPerBC; - Int_t b2 = ibeg + is2 / NTimeBinsPerBC; - Int_t s1 = is1 % NTimeBinsPerBC; - Int_t s2 = is2 % NTimeBinsPerBC; + int b1 = ibeg + is1 / NTimeBinsPerBC; + int b2 = ibeg + is2 / NTimeBinsPerBC; + int s1 = is1 % NTimeBinsPerBC; + int s2 = is2 % NTimeBinsPerBC; auto ref_m = mReco[b1].ref[TDCSignal[itdc]]; auto ref_s = mReco[b2].ref[TDCSignal[itdc]]; // Check data consistency before computing difference - if(ref_m == O2_ZDC_REF_INIT_VAL || ref_s == O2_ZDC_REF_INIT_VAL){ + if (ref_m == O2_ZDC_REF_INIT_VAL || ref_s == O2_ZDC_REF_INIT_VAL) { LOG(FATAL) << "Missing information for bunch crossing"; return; } @@ -551,7 +467,7 @@ void DigiReco::processTrigger(int itdc, int ibeg, int iend) if (isfired[1] == 1 && isfired[2] == 1) { // Fired bit is assigned to the second sample, i.e. to the one that can identify the // signal peak position - mReco[b2].fired[itdc]|=mMask[s2]; + mReco[b2].fired[itdc] |= mMask[s2]; //LOG(INFO) << itdc << " Fired @ " << mReco[b2].ir.orbit << "." << mReco[b2].ir.bc << " " << b2 - ibeg << "." << s2 << "=" << NTimeBinsPerBC * (b2 - ibeg) + s2; LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " Fired @ " << mReco[b2].ir.orbit << "." << mReco[b2].ir.bc << ".s" << s2; } @@ -573,60 +489,60 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) { LOG(INFO) << __func__ << "(itdc=" << itdc << "[" << ChannelNames[TDCSignal[itdc]] << "] ," << ibeg << "," << iend << "): " << mReco[ibeg].ir.orbit << "." << mReco[ibeg].ir.bc << " - " << mReco[iend].ir.orbit << "." << mReco[iend].ir.bc; // TODO: get data from preceding time frame - constexpr int MaxTimeBin = NTimeBinsPerBC - 1; //< number of samples per BC - constexpr int tsnh = TSN / 2; // Half number of points in interpolation - constexpr int nsbun = TSN * NTimeBinsPerBC; // Total number of interpolated points per bunch crossing - Int_t nbun = iend - ibeg + 1; // Number of adjacent bunches - Int_t nsam = nbun * NTimeBinsPerBC; // Number of acquired samples - Int_t ntot = nsam * TSN; // Total number of points in the interpolated arrays - Int_t nint = (nbun * NTimeBinsPerBC - 1) * TSN; // Total points in the interpolation region (-1) - constexpr int nsp = 5; // Number of points to be searched - - const std::vector &OrbitData=*mOrbitData; - const std::vector &BCData=*mBCData; - const std::vector &ChData=*mChData; + constexpr int MaxTimeBin = NTimeBinsPerBC - 1; //< number of samples per BC + constexpr int tsnh = TSN / 2; // Half number of points in interpolation + constexpr int nsbun = TSN * NTimeBinsPerBC; // Total number of interpolated points per bunch crossing + int nbun = iend - ibeg + 1; // Number of adjacent bunches + int nsam = nbun * NTimeBinsPerBC; // Number of acquired samples + int ntot = nsam * TSN; // Total number of points in the interpolated arrays + int nint = (nbun * NTimeBinsPerBC - 1) * TSN; // Total points in the interpolation region (-1) + constexpr int nsp = 5; // Number of points to be searched + + const std::vector& OrbitData = *mOrbitData; + const std::vector& BCData = *mBCData; + const std::vector& ChData = *mChData; // At this level there should be no need to check if the TDC channel is connected // since a fatal should have been raised already - for(int ibun=ibeg; ibun<=iend; ibun++){ + for (int ibun = ibeg; ibun <= iend; ibun++) { auto ref = mReco[ibun].ref[TDCSignal[itdc]]; - if(ref == O2_ZDC_REF_INIT_VAL){ + if (ref == O2_ZDC_REF_INIT_VAL) { LOG(FATAL) << "Missing information for bunch crossing"; } } - + // Get reconstruction parameters auto& ropt = RecoParamZDC::Instance(); - Int_t imod = ropt.tmod[itdc]; // Module corresponding to TDC channel - Int_t ich = ropt.tch[itdc]; // Hardware channel corresponding to TDC channel + int imod = ropt.tmod[itdc]; // Module corresponding to TDC channel + int ich = ropt.tch[itdc]; // Hardware channel corresponding to TDC channel auto ref_beg = mReco[ibeg].ref[TDCSignal[itdc]]; auto ref_end = mReco[iend].ref[TDCSignal[itdc]]; - Double_t first_sample = ChData[ref_beg].data[0]; - Double_t last_sample = ChData[ref_end].data[NTimeBinsPerBC - 1]; + O2_ZDC_DIGIRECO_FLT first_sample = ChData[ref_beg].data[0]; + O2_ZDC_DIGIRECO_FLT last_sample = ChData[ref_end].data[NTimeBinsPerBC - 1]; // Constant extrapolation at the beginning and at the end of the array // Assign value of first sample - for (Int_t i = 0; i < tsnh; i++) { + for (int i = 0; i < tsnh; i++) { mReco[ibeg].inter[itdc][i] = first_sample; } // Assign value of last sample - for (Int_t i = ntot - tsnh; i < ntot; i++) { - Int_t isam = i % nsbun; + for (int i = ntot - tsnh; i < ntot; i++) { + int isam = i % nsbun; mReco[iend].inter[itdc][isam] = last_sample; } // Interpolation between acquired points (n.b. loop from 0 to nint) - for (Int_t i = 0; i < nint; i++) { + for (int i = 0; i < nint; i++) { // Identification of the point to be assigned (need to add tsnh to identify the point) - Int_t ibun = ibeg + (i + tsnh) / nsbun; - Int_t isam = (i + tsnh) % nsbun; - Int_t im = i % TSN; + int ibun = ibeg + (i + tsnh) / nsbun; + int isam = (i + tsnh) % nsbun; + int im = i % TSN; if (im == 0) { // This is an acquired point - Int_t ip = (i / TSN) % NTimeBinsPerBC; - Int_t ib = ibeg + (i / TSN) / NTimeBinsPerBC; + int ip = (i / TSN) % NTimeBinsPerBC; + int ib = ibeg + (i / TSN) / NTimeBinsPerBC; if (ib != ibun) { LOG(FATAL) << "ib=" << ib << " ibun=" << ibun; return; @@ -634,17 +550,17 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) mReco[ibun].inter[itdc][isam] = ChData[mReco[ibun].ref[TDCSignal[itdc]]].data[ip]; } else { // Do the actual interpolation - Double_t y = 0; - Int_t ip = i / TSN; - Double_t sum = 0; - for (Int_t is = TSN - im, ii = ip - TSL + 1; is < NTS; is += TSN, ii++) { + O2_ZDC_DIGIRECO_FLT y = 0; + int ip = i / TSN; + O2_ZDC_DIGIRECO_FLT sum = 0; + for (int is = TSN - im, ii = ip - TSL + 1; is < NTS; is += TSN, ii++) { // Default is first point in the array - Double_t yy = first_sample; + O2_ZDC_DIGIRECO_FLT yy = first_sample; if (ii > 0) { if (ii < nsam) { - Int_t ip = ii % NTimeBinsPerBC; - Int_t ib = ibeg + ii / NTimeBinsPerBC; - yy = ChData[mReco[ib].ref[TDCSignal[itdc]]].data[ip]; + int ip = ii % NTimeBinsPerBC; + int ib = ibeg + ii / NTimeBinsPerBC; + yy = ChData[mReco[ib].ref[TDCSignal[itdc]]].data[ip]; } else { // Last acquired point yy = last_sample; @@ -659,16 +575,16 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) } // Looking for a local maximum in a searching zone float amp = std::numeric_limits::infinity(); // Amplitude to be stored - Int_t isam_amp = 0; // Sample at maximum amplitude (relative to beginning of group) - Int_t ip_old = -1, ip_cur = -1, ib_cur = -1; // Current and old points + int isam_amp = 0; // Sample at maximum amplitude (relative to beginning of group) + int ip_old = -1, ip_cur = -1, ib_cur = -1; // Current and old points bool is_searchable = false; // Flag for point in the search zone for maximum amplitude bool was_searchable = false; // Flag for point in the search zone for maximum amplitude - Int_t ib[nsp] = {-1, -1, -1, -1, -1}; - Int_t ip[nsp] = {-1, -1, -1, -1, -1}; + int ib[nsp] = {-1, -1, -1, -1, -1}; + int ip[nsp] = {-1, -1, -1, -1, -1}; // N.B. Points at the extremes are constant therefore no local maximum // can occur in these two regions - for (Int_t i = 0; i < nint; i++) { - Int_t isam = i + tsnh; + for (int i = 0; i < nint; i++) { + int isam = i + tsnh; // Check if trigger is fired for this point // For the moment we don't take into account possible extensions of the search zone // ip_cur can span several bunches and is used just to identify transitions @@ -676,7 +592,7 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) // Speed up computation if (ip_cur != ip_old) { ip_old = ip_cur; - for (Int_t j = 0; j < 5; j++) { + for (int j = 0; j < 5; j++) { ib[j] = -1; ip[j] = -1; } @@ -724,10 +640,10 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) was_searchable = is_searchable; // Search conditions with list of allowed patterns // No need to double check ib[?] and ip[?] because either we assign both or none - uint16_t triggered=0x0000; - for (Int_t j = 0; j < 5; j++) { - if (ib[j] >= 0 && (mReco[ib[j]].fired[itdc]&mMask[ip[j]]) > 0) { - triggered |= (0x1<= 0 && (mReco[ib[j]].fired[itdc] & mMask[ip[j]]) > 0) { + triggered |= (0x1 << j); } } // Reject conditions: @@ -736,7 +652,7 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) // One among 10000 and 00001 // Accept conditions: constexpr uint16_t accept[14] = { -// 0x01, // 00001 extend search zone before maximum + // 0x01, // 00001 extend search zone before maximum 0x02, // 00010 0x04, // 00100 0x08, // 01000 @@ -751,16 +667,16 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) 0x0f, // 01111 0x1e, // 11110 0x1f // 11111 - }; + }; // All other are not correct (->reject) is_searchable = 0; - if(triggered!=0){ - for(Int_t j=0; j<14; j++){ - if(triggered==accept[j]){ + if (triggered != 0) { + for (int j = 0; j < 14; j++) { + if (triggered == accept[j]) { is_searchable = 1; - break; - } - } + break; + } + } } } // We do not restrict search zone around expected main-main collision @@ -771,19 +687,19 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) if (was_searchable && !is_searchable) { if (amp <= ADCMax) { // Store identified peak - Int_t ibun = ibeg + isam_amp / nsbun; - Int_t tdc = isam_amp % nsbun; - // Look for offset - auto orbit=BCData[ibun].ir.orbit; - std::map::iterator it = mOrbit.find(orbit); - if (it != mOrbit.end()){ - // Subtract pedestal - auto &orbitdata=OrbitData[it->second]; + int ibun = ibeg + isam_amp / nsbun; + int tdc = isam_amp % nsbun; + // Look for offset + auto orbit = BCData[ibun].ir.orbit; + std::map::iterator it = mOrbit.find(orbit); + if (it != mOrbit.end()) { + // Subtract pedestal + auto& orbitdata = OrbitData[it->second]; amp = orbitdata.asFloat(ich) - amp; - }else{ - LOG(ERROR) << "Missing pedestal"; - amp = std::numeric_limits::infinity(); - } + } else { + LOG(ERROR) << "Missing pedestal"; + amp = std::numeric_limits::infinity(); + } assignTDC(ibun, ibeg, iend, itdc, tdc, amp); } amp = std::numeric_limits::infinity(); @@ -791,7 +707,7 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) was_searchable = 0; } if (is_searchable) { - Int_t mysam = isam % nsbun; + int mysam = isam % nsbun; if (mReco[ib_cur].inter[itdc][mysam] < amp) { amp = mReco[ib_cur].inter[itdc][mysam]; isam_amp = isam; @@ -803,18 +719,18 @@ void DigiReco::interpolate(int itdc, int ibeg, int iend) // Add last identified peak if (amp <= ADCMax) { // Store identified peak - Int_t ibun = ibeg + isam_amp / nsbun; - Int_t tdc = isam_amp % nsbun; + int ibun = ibeg + isam_amp / nsbun; + int tdc = isam_amp % nsbun; // Look for offset - auto orbit=BCData[ibun].ir.orbit; - std::map::iterator it = mOrbit.find(orbit); - if (it != mOrbit.end()){ - // Subtract pedestal - auto &orbitdata=OrbitData[it->second]; + auto orbit = BCData[ibun].ir.orbit; + std::map::iterator it = mOrbit.find(orbit); + if (it != mOrbit.end()) { + // Subtract pedestal + auto& orbitdata = OrbitData[it->second]; amp = orbitdata.asFloat(ich) - amp; - }else{ - LOG(ERROR) << "Missing pedestal"; - amp = std::numeric_limits::infinity(); + } else { + LOG(ERROR) << "Missing pedestal"; + amp = std::numeric_limits::infinity(); } assignTDC(ibun, ibeg, iend, itdc, tdc, amp); } @@ -828,7 +744,7 @@ void DigiReco::assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float constexpr int tdc_min = -tdc_max; // Apply tdc shift correction - Int_t tdc_cor = tdc - tdc_shift[itdc]; + int tdc_cor = tdc - tdc_shift[itdc]; // Correct bunch assignment if (tdc_cor < tdc_min && ibun >= ibeg) { // Assign to preceding bunch @@ -848,16 +764,16 @@ void DigiReco::assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float tdc_cor = kMaxShort; } // Assign to correct bunch - int &ihit=mReco[ibun].ntdc[itdc]; - if(ihit Date: Thu, 6 May 2021 19:54:41 +0200 Subject: [PATCH 416/770] DPL: allow for custom channel selection in multi output proxy (#6072) --- .../Framework/ExternalFairMQDeviceProxy.h | 7 ++++++- .../Core/src/ExternalFairMQDeviceProxy.cxx | 18 ++++++++---------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/Framework/Core/include/Framework/ExternalFairMQDeviceProxy.h b/Framework/Core/include/Framework/ExternalFairMQDeviceProxy.h index 6640b940556d6..0db292cc3a80f 100644 --- a/Framework/Core/include/Framework/ExternalFairMQDeviceProxy.h +++ b/Framework/Core/include/Framework/ExternalFairMQDeviceProxy.h @@ -24,6 +24,7 @@ namespace o2::framework /// messages of the specified OutputSpec using ChannelRetriever = std::function; using InjectorFunction = std::function; +using ChannelSelector = std::function>& channels)>; struct InputChannelSpec; struct OutputChannelSpec; @@ -64,6 +65,9 @@ InjectorFunction dplModelAdaptor(std::vector const& specs = {{header /// The default connection method for the custom source static auto gDefaultConverter = incrementalConverter(OutputSpec{"TST", "TEST", 0}, 0, 1); +/// Default way to select an output channel for multi-output proxy. +std::string defaultOutputProxyChannelSelector(InputSpec const& input, const std::unordered_map>& channels); + /// Create a DataProcessorSpec which can be used to inject /// messages in the DPL. /// @param label is the label of the DataProcessorSpec associated and name of the input channel. @@ -103,7 +107,8 @@ DataProcessorSpec specifyFairMQDeviceOutputProxy(char const* label, /// name tag is not yet in the configuration DataProcessorSpec specifyFairMQDeviceMultiOutputProxy(char const* label, Inputs const& inputSpecs, - const char* defaultChannelConfig); + const char* defaultChannelConfig, + ChannelSelector channelSelector = defaultOutputProxyChannelSelector); } // namespace o2 diff --git a/Framework/Core/src/ExternalFairMQDeviceProxy.cxx b/Framework/Core/src/ExternalFairMQDeviceProxy.cxx index 4ae84d48cd733..18811b4c316e2 100644 --- a/Framework/Core/src/ExternalFairMQDeviceProxy.cxx +++ b/Framework/Core/src/ExternalFairMQDeviceProxy.cxx @@ -393,15 +393,12 @@ DataProcessorSpec specifyExternalFairMQDeviceProxy(char const* name, return spec; } -namespace -{ static char const* gDefaultChannel = "downstream"; // Decide where to sent the output. Everything to "downstream" if there is such a channel. -std::string decideChannel(InputSpec const& input, const std::unordered_map>& channels) +std::string defaultOutputProxyChannelSelector(InputSpec const& input, const std::unordered_map>& channels) { return channels.count("downstream") ? "downstream" : input.binding; } -} // namespace DataProcessorSpec specifyFairMQDeviceOutputProxy(char const* name, Inputs const& inputSpecs, @@ -471,28 +468,29 @@ DataProcessorSpec specifyFairMQDeviceOutputProxy(char const* name, DataProcessorSpec specifyFairMQDeviceMultiOutputProxy(char const* name, Inputs const& inputSpecs, - const char* defaultChannelConfig) + const char* defaultChannelConfig, + ChannelSelector channelSelector) { DataProcessorSpec spec; spec.name = name; spec.inputs = inputSpecs; spec.outputs = {}; - spec.algorithm = adaptStateful([inputSpecs](CallbackService& callbacks, RawDeviceService& rds) { + spec.algorithm = adaptStateful([inputSpecs, channelSelector](CallbackService& callbacks, RawDeviceService& rds) { auto device = rds.device(); // check that the input spec bindings have corresponding output channels // FairMQDevice calls the custom init before the channels have been configured // so we do the check before starting in a dedicated callback - auto channelConfigurationChecker = [inputSpecs = std::move(inputSpecs), device]() { + auto channelConfigurationChecker = [inputSpecs = std::move(inputSpecs), device, channelSelector]() { LOG(INFO) << "checking channel configuration"; for (auto const& spec : inputSpecs) { - auto channel = decideChannel(spec, device->fChannels); + auto channel = channelSelector(spec, device->fChannels); if (device->fChannels.count(channel) == 0) { throw std::runtime_error("no corresponding output channel found for input '" + channel + "'"); } } }; callbacks.set(CallbackService::Id::Start, channelConfigurationChecker); - return adaptStateless([](RawDeviceService& rds, InputRecord& inputs) { + return adaptStateless([channelSelector](RawDeviceService& rds, InputRecord& inputs) { std::unordered_map outputs; auto& device = *rds.device(); for (size_t ii = 0; ii != inputs.size(); ++ii) { @@ -518,7 +516,7 @@ DataProcessorSpec specifyFairMQDeviceMultiOutputProxy(char const* name, } size_t payloadMsgSize = dh->payloadSize; - auto channel = decideChannel(*first.spec, device.fChannels); + auto channel = channelSelector(*first.spec, device.fChannels); auto headerMessage = device.NewMessageFor(channel, index, headerMsgSize); memcpy(headerMessage->GetData(), part.header, headerMsgSize); auto payloadMessage = device.NewMessageFor(channel, index, payloadMsgSize); From 5e30e05e69e4efcfe3b671af27365fea8a4fcacf Mon Sep 17 00:00:00 2001 From: sevdokim Date: Wed, 5 May 2021 08:24:08 +0200 Subject: [PATCH 417/770] New CPV data format --- .../CPV/include/DataFormatsCPV/RawFormats.h | 70 ++++- Detectors/CPV/base/CMakeLists.txt | 4 +- .../CPV/base/include/CPVBase/RCUTrailer.h | 186 ------------- Detectors/CPV/base/src/RCUTrailer.cxx | 249 ------------------ .../src/CPVGainCalibDevice.cxx | 8 +- .../src/CPVPedestalCalibDevice.cxx | 8 +- .../include/CPVReconstruction/RawDecoder.h | 45 ++-- .../CPVReconstruction/RawReaderMemory.h | 32 ++- .../CPV/reconstruction/src/RawDecoder.cxx | 165 +++++++----- .../reconstruction/src/RawReaderMemory.cxx | 93 ++++--- .../include/CPVSimulation/RawWriter.h | 4 +- Detectors/CPV/simulation/src/RawWriter.cxx | 199 ++++++++++---- .../workflow/src/RawToDigitConverterSpec.cxx | 78 +++--- 13 files changed, 435 insertions(+), 706 deletions(-) delete mode 100644 Detectors/CPV/base/include/CPVBase/RCUTrailer.h delete mode 100644 Detectors/CPV/base/src/RCUTrailer.cxx diff --git a/DataFormats/Detectors/CPV/include/DataFormatsCPV/RawFormats.h b/DataFormats/Detectors/CPV/include/DataFormatsCPV/RawFormats.h index 38a5e14b244a7..1e107c9df482d 100644 --- a/DataFormats/Detectors/CPV/include/DataFormatsCPV/RawFormats.h +++ b/DataFormats/Detectors/CPV/include/DataFormatsCPV/RawFormats.h @@ -11,6 +11,9 @@ #ifndef ALICEO2_CPV_RAWFORMATS_H #define ALICEO2_CPV_RAWFORMATS_H +#include +#include "CommonDataFormat/InteractionRecord.h" + namespace o2 { @@ -62,29 +65,78 @@ class cpvword unsigned char bytes[16] = {0}; }; +class cpvheader +{ + public: + cpvheader() = default; + cpvheader(std::vector::const_iterator b, std::vector::const_iterator e) + { //reading header from file + for (int i = 0; i < 16 && b != e; i++, b++) { //read up to 16 bytes + bytes[i] = *b; + } + } + cpvheader(InteractionRecord orbitBC, bool isNoDataExpected, bool isDataContinued) + { //writing header + //header is 128-bit word. + //|127-120|119-112|111-104|103-96|95-88 |87-80 |79-72|71-64|63-56|55-48|47-40|39-32|31-24|23-16|15-8 |7-0 | + // byte15 byte14 byte13 byte12 byte11 byte10 byte9 byte8 byte7 byte6 byte5 byte4 byte3 byte2 byte1 byte0 + //byte = |76543210| + bytes[0] = (0x010 & 0x0ff); //bits 11 - 0 trigger id (0x010 = physics trigger) + bytes[1] = ((0x010 & 0xf00) >> 8) //bits 11 - 0 trigger id (0x010 = physics trigger) + + 0b00100000 * isNoDataExpected + 0b0100000 * isDataContinued; //bit 13 (no data for this trigger) + bit 14 (payload continues from previous page) + bytes[2] = (orbitBC.bc & 0x00ff); //bits 27 - 16 bunch crossing + bytes[3] = (orbitBC.bc & 0x0f00) >> 8; //bits 27 - 16 bunch crossing + bytes[4] = (orbitBC.orbit & 0x000000ff); //bits 63 - 32 orbit + bytes[5] = (orbitBC.orbit & 0x0000ff00) >> 8; //bits 63 - 32 orbit + bytes[6] = (orbitBC.orbit & 0x00ff0000) >> 16; //bits 63 - 32 orbit + bytes[7] = (orbitBC.orbit & 0xff000000) >> 24; //bits 63 - 32 orbit + bytes[8] = 0x00; //bits 64-71 reserved + bytes[9] = 0xe0; //word ID of cpv header (bits 79 - 72) + for (int i = 10; i < 16; i++) { + bytes[i] = 0; //bits 127-80 must be zeros + } + } + ~cpvheader() = default; + bool isOK() const { return (bytes[9] == 0xe0) && (bytes[10] == 0) && (bytes[11] == 0) && (bytes[12] == 0) && (bytes[13] == 0) && (bytes[14] == 0) && (bytes[15] == 0); } + bool isNoDataExpected() const { return bytes[1] & 0b00100000; } + bool isDataContinued() const { return bytes[1] & 0b0100000; } + uint16_t bc() const { return bytes[2] + ((bytes[3] & 0x0f) << 8); } + uint32_t orbit() const { return bytes[4] + (bytes[5] << 8) + (bytes[6] << 16) + (bytes[7] << 24); } + + public: + unsigned char bytes[16] = {0}; //0 - 127 bits (16 bytes) +}; + class cpvtrailer { public: cpvtrailer() = default; cpvtrailer(std::vector::const_iterator b, std::vector::const_iterator e) - { //reading - for (int i = 0; i < 16 && b != e; i++, b++) { + { //reading + for (int i = 0; i < 16 && b != e; i++, b++) { //read up to 16 bytes bytes[i] = *b; } } - cpvtrailer(unsigned short wordCounter) - { //writing + cpvtrailer(unsigned short wordCounter, uint16_t bunchCrossing, bool isAllDataSent) + { //writing + bytes[0] = bunchCrossing & 0x00ff; //bits 11 - 0 bunch crossing + bytes[1] = ((bunchCrossing & 0x0f00) >> 8) //bits 11 - 0 bunch crossing + + ((wordCounter & 0x0f) << 4); //bits 20 - 12 wordCounter + bytes[2] = (wordCounter & 0b111110000) >> 4; //bits 20 - 12 wordCounter + for (int i = 3; i < 8; i++) { + bytes[i] = 0; //bits 70 - 21 reserved + } + bytes[8] = isAllDataSent * 0b10000000; //bit 71 all data is sent for current trigger + bytes[9] = char(0xf0); //word ID of cpv trailer for (int i = 10; i < 16; i++) { bytes[i] = 0; } - bytes[9] = char(0xf0); - bytes[1] = (wordCounter & 0xff00) >> 8; - bytes[0] = (wordCounter & 0x00ff); } ~cpvtrailer() = default; bool isOK() const { return (bytes[9] == 0xf0) && (bytes[10] == 0) && (bytes[11] == 0) && (bytes[12] == 0) && (bytes[13] == 0) && (bytes[14] == 0) && (bytes[15] == 0); } - short status() const { return short(bytes[8]); } - unsigned short wordCounter() const { return bytes[0] + (bytes[1] << 8); } + uint16_t wordCounter() const { return (bytes[1] >> 4) + ((bytes[2] & 0b00011111) << 4); } + bool isAllDataSent() const { return (bytes[8] & 0b10000000); } + uint16_t bc() const { return bytes[0] + ((bytes[1] & 0x0f) << 8); } public: unsigned char bytes[16] = {0}; diff --git a/Detectors/CPV/base/CMakeLists.txt b/Detectors/CPV/base/CMakeLists.txt index 40286d5f9f733..3d0dd482329b8 100644 --- a/Detectors/CPV/base/CMakeLists.txt +++ b/Detectors/CPV/base/CMakeLists.txt @@ -12,11 +12,9 @@ o2_add_library(CPVBase SOURCES src/Geometry.cxx src/Hit.cxx src/CPVSimParams.cxx - src/RCUTrailer.cxx PUBLIC_LINK_LIBRARIES O2::SimulationDataFormat) o2_target_root_dictionary(CPVBase HEADERS include/CPVBase/Geometry.h include/CPVBase/Hit.h - include/CPVBase/CPVSimParams.h - include/CPVBase/RCUTrailer.h) + include/CPVBase/CPVSimParams.h) diff --git a/Detectors/CPV/base/include/CPVBase/RCUTrailer.h b/Detectors/CPV/base/include/CPVBase/RCUTrailer.h deleted file mode 100644 index d6f8967c108e9..0000000000000 --- a/Detectors/CPV/base/include/CPVBase/RCUTrailer.h +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. -#ifndef ALICEO2_CPV_RCUTRAILER_H -#define ALICEO2_CPV_RCUTRAILER_H - -#include -#include -#include -#include -#include -#include "Rtypes.h" - -namespace o2 -{ - -namespace cpv -{ - -/// \class RCUTrailer -/// \brief Information stored in the RCU trailer -/// \ingroup CPVbase -/// -/// The RCU trailer can be found at the end of -/// the payload and contains general information -/// sent by the SRU. -class RCUTrailer -{ - public: - /// \class Error - /// \brief Error handling of the - class Error : public std::exception - { - public: - /// \enum ErrorType_t - /// \brief Error codes for different error types - enum class ErrorType_t { - DECODING_INVALID, ///< Invalid words during decoding - SIZE_INVALID, ///< Invalid trailer size - SAMPLINGFREQ_INVALID, ///< Invalid sampling frequency - L1PHASE_INVALID ///< Invalid L1 phase - }; - - /// \brief Constructor - /// \param errtype Code of the error type - /// \param message corresponding error message - /// - /// Initializing the error with error code and message. - /// To be called when the exception is raised. - Error(ErrorType_t errtype, const char* message) : mErrorType(errtype), mErrorMessage(message) {} - - /// \brief Destructor - ~Error() noexcept override = default; - - /// \brief Access to the error message - /// \return Error message related to the exception type - const char* what() const noexcept override { return mErrorMessage.data(); } - - /// \brief Access to error code - /// \return Error code of the exception type - ErrorType_t getErrorType() const noexcept { return mErrorType; } - - private: - ErrorType_t mErrorType; ///< Type of the error - std::string mErrorMessage; ///< Error Message - }; - - /// \brief Constructor - RCUTrailer() = default; - - /// \brief destructor - ~RCUTrailer() = default; - - /// \brief Reset the RCU trailer - /// - /// Setting all values to 0 - void reset(); - - /// \brief Prints the contents of the RCU trailer data - /// \param stream stream the trailer has to be put on - void printStream(std::ostream& stream) const; - - /// \brief Decode RCU trailer from the 32-bit words in the raw buffer - /// \param buffer Raw buffer from which to read the trailer - /// - /// Read the RCU trailer according to the RCU formware version - /// specified in CDH. - void constructFromRawPayload(const gsl::span payload); - - unsigned int getFECErrorsA() const { return mFECERRA; } - unsigned int getFECErrorsB() const { return mFECERRB; } - unsigned short getErrorsG2() const { return mERRREG2; } - unsigned int getErrorsG3() const { return mERRREG3; } - unsigned short getActiveFECsA() const { return mActiveFECsA; } - unsigned short getActiveFECsB() const { return mActiveFECsB; } - unsigned int getAltroCFGReg1() const { return mAltroCFG1; } - unsigned int getAltroCFGReg2() const { return mAltroCFG2; } - int getRCUID() const { return mRCUId; } - unsigned int getTrailerSize() const { return mTrailerSize; } - unsigned int getPayloadSize() const { return mPayloadSize; } - unsigned char getFirmwareVersion() const { return mFirmwareVersion; } - - unsigned short getNumberOfChannelAddressMismatch() const { return (mERRREG3 & 0xFFF); } - unsigned short getNumberOfChannelLengthMismatch() const { return ((mERRREG3 >> 12) & 0x1FFF); } - unsigned char getBaselineCorrection() const { return mAltroCFG1 & 0xF; } - bool getPolarity() const { return (mAltroCFG1 >> 4) & 0x1; } - unsigned char getNumberOfPresamples() const { return (mAltroCFG1 >> 5) & 0x3; } - unsigned char getNumberOfPostsamples() const { return (mAltroCFG1 >> 7) & 0xF; } - bool hasSecondBaselineCorr() const { return (mAltroCFG1 >> 11) & 0x1; } - unsigned char getGlitchFilter() const { return (mAltroCFG1 >> 12) & 0x3; } - unsigned char getNumberOfNonZeroSuppressedPostsamples() const { return (mAltroCFG1 >> 14) & 0x7; } - unsigned char getNumberOfNonZeroSuppressedPresamples() const { return (mAltroCFG1 >> 17) & 0x3; } - bool hasZeroSuppression() const { return (mAltroCFG1 >> 19) & 0x1; } - bool getNumberOfAltroBuffers() const { return (mAltroCFG2 >> 24) & 0x1; } - unsigned char getNumberOfPretriggerSamples() const { return (mAltroCFG2 >> 20) & 0xF; } - unsigned short getNumberOfSamplesPerChannel() const { return (mAltroCFG2 >> 10) & 0x3FF; } - bool isSparseReadout() const { return (mAltroCFG2 >> 9) & 0x1; } - - /// \brief Access to the sampling time - /// \return Sampling time in seconds. - /// \throw Error if the RCU trailer was not properly initializied - double getTimeSample() const; - - /// \brief set time sample - /// \param timesample Time sample (in ns) - void setTimeSample(double timesample); - - /// \brief Access to the L1 phase - /// \return L1 phase w.r.t to the LHC clock - double getL1Phase() const; - - /// \brief Set the L1 phase - /// \param l1phase L1 phase (in ns) - void setL1Phase(double l1phase); - - void setFECErrorsA(unsigned int value) { mFECERRA = value; } - void setFECErrorsB(unsigned int value) { mFECERRB = value; } - void setErrorsG2(unsigned short value) { mERRREG2 = value; } - void setErrorsG3(unsigned int value) { mERRREG3 = value; } - void setActiveFECsA(unsigned short value) { mActiveFECsA = value; } - void setActiveFECsB(unsigned short value) { mActiveFECsB = value; } - void setAltroCFGReg1(unsigned int value) { mAltroCFG1 = value; } - void setAltroCFGReg2(unsigned int value) { mAltroCFG2 = value; } - void setFirmwareVersion(unsigned char version) { mFirmwareVersion = version; } - void setPayloadSize(unsigned int size) { mPayloadSize = size; } - - /// \brief checlks whether the RCU trailer is initialzied - /// \return True if the trailer is initialized, false otherwise - bool isInitialized() const { return mIsInitialized; } - - std::vector encode() const; - - static RCUTrailer constructFromPayloadWords(const gsl::span payloadwords); - static RCUTrailer constructFromPayload(const gsl::span payload); - - private: - int mRCUId = -1; ///< current RCU identifier - unsigned char mFirmwareVersion = 0; ///< RCU firmware version - unsigned int mTrailerSize = 0; ///< Size of the trailer (in number of 32 bit words) - unsigned int mPayloadSize = 0; ///< Size of the payload (in nunber of 32 bit words) - unsigned int mFECERRA = 0; ///< contains errors related to ALTROBUS transactions - unsigned int mFECERRB = 0; ///< contains errors related to ALTROBUS transactions - unsigned short mERRREG2 = 0; ///< contains errors related to ALTROBUS transactions or trailer of ALTRO channel block - unsigned int mERRREG3 = 0; ///< contains number of altro channels skipped due to an address mismatch - unsigned short mActiveFECsA = 0; ///< bit pattern of active FECs in branch A - unsigned short mActiveFECsB = 0; ///< bit pattern of active FECs in branch B - unsigned int mAltroCFG1 = 0; ///< ALTROCFG1 register - unsigned int mAltroCFG2 = 0; ///< ALTROCFG2 and ALTROIF register - bool mIsInitialized = false; ///< Flag whether RCU trailer is initialized for the given raw event - - ClassDefNV(RCUTrailer, 1); -}; - -std::ostream& operator<<(std::ostream& stream, const RCUTrailer& trailer); - -} // namespace cpv - -} // namespace o2 - -#endif \ No newline at end of file diff --git a/Detectors/CPV/base/src/RCUTrailer.cxx b/Detectors/CPV/base/src/RCUTrailer.cxx deleted file mode 100644 index a7c8e075a2065..0000000000000 --- a/Detectors/CPV/base/src/RCUTrailer.cxx +++ /dev/null @@ -1,249 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. -#include -#include -#include -#include -#include "CommonConstants/LHCConstants.h" -#include "CPVBase/RCUTrailer.h" - -using namespace o2::cpv; - -void RCUTrailer::reset() -{ - mRCUId = -1; - mFirmwareVersion = 0; - mTrailerSize = 0; - mPayloadSize = 0; - mFECERRA = 0; - mFECERRB = 0; - mERRREG2 = 0; - mERRREG3 = 0; - mActiveFECsA = 0; - mActiveFECsB = 0; - mAltroCFG1 = 0; - mAltroCFG2 = 0; - mIsInitialized = false; -} - -void RCUTrailer::constructFromRawPayload(const gsl::span payloadwords) -{ - - // Code below assumes uint32_t span instead of current char!!!!!! - // reset(); - // int index = payloadwords.size(); - // auto word = payloadwords[--index]; - // if ((word >> 30) != 3) { - // throw Error(Error::ErrorType_t::DECODING_INVALID, "Last RCU trailer word not found!"); - // } - // mFirmwareVersion = (word >> 16) & 0xFF; - - // mRCUId = (int)((word >> 7) & 0x1FF); - // int trailerSize = (word & 0x7F); - - // if (trailerSize < 2) { - // throw Error(Error::ErrorType_t::SIZE_INVALID, fmt::format("Invalid trailer size found (%d bytes) !", trailerSize * 4).data()); - // } - // mTrailerSize = trailerSize; - - // trailerSize -= 2; // Cut first and last trailer words as they are handled separately - // for (; trailerSize > 0; trailerSize--) { - // word = payloadwords[--index]; - // if ((word >> 30) != 2) { - // std::cerr << "Missing RCU trailer identifier pattern!\n"; - // continue; - // } - // int parCode = (word >> 26) & 0xF; - // int parData = word & 0x3FFFFFF; - // switch (parCode) { - // case 1: - // // ERR_REG1 - // mFECERRA = ((parData >> 13) & 0x1FFF) << 7; - // mFECERRB = ((parData & 0x1FFF)) << 7; - // break; - // case 2: - // // ERR_REG2 - // mERRREG2 = parData & 0x1FF; - // break; - // case 3: - // // ERR_REG3 - // mERRREG3 = parData & 0x1FFFFFF; - // break; - // case 4: - // // FEC_RO_A - // mActiveFECsA = parData & 0xFFFF; - // break; - // case 5: - // // FEC_RO_B - // mActiveFECsB = parData & 0xFFFF; - // break; - // case 6: - // // RDO_CFG1 - // mAltroCFG1 = parData & 0xFFFFF; - // break; - // case 7: - // // RDO_CFG2 - // mAltroCFG2 = parData & 0x1FFFFFF; - // break; - // default: - // std::cerr << "Undefined parameter code " << parCode << ", ignore it !\n"; - // break; - // } - // } - // mPayloadSize = payloadwords[--index] & 0x3FFFFFF; - mIsInitialized = true; -} - -double RCUTrailer::getTimeSample() const -{ - unsigned char fq = (mAltroCFG2 >> 5) & 0xF; - double tSample; - switch (fq) { - case 0: - // 20 MHz - tSample = 2.0; - break; - case 1: - // 10 Mhz - tSample = 4.0; - break; - case 2: - // 5 MHz - tSample = 8.; - break; - default: - throw Error(Error::ErrorType_t::SAMPLINGFREQ_INVALID, fmt::format("Invalid sampling frequency value %d !", int(fq)).data()); - } - - return tSample * o2::constants::lhc::LHCBunchSpacingNS * 1.e-9; -} - -void RCUTrailer::setTimeSample(double timesample) -{ - int fq = 0; - if (std::abs(timesample - 50) < DBL_EPSILON) { - fq = 0; - } else if (std::abs(timesample - 100) < DBL_EPSILON) { - fq = 1; - } else if (std::abs(timesample - 200) < DBL_EPSILON) { - fq = 2; - } else { - throw Error(Error::ErrorType_t::SAMPLINGFREQ_INVALID, fmt::format("invalid time sample: %f", timesample).data()); - } - mAltroCFG2 = (mAltroCFG2 & 0x1F) | fq << 5; -} - -double RCUTrailer::getL1Phase() const -{ - double tSample = getTimeSample(), - phase = ((double)(mAltroCFG2 & 0x1F)) * o2::constants::lhc::LHCBunchSpacingNS * 1.e-9; - if (phase >= tSample) { - throw Error(Error::ErrorType_t::L1PHASE_INVALID, fmt::format("Invalid L1 trigger phase (%e s (phase) >= %e s (sampling time)) !", phase, tSample).data()); - } - return phase; -} - -void RCUTrailer::setL1Phase(double l1phase) -{ - int phase = l1phase / 25.; - mAltroCFG2 = (mAltroCFG2 & 0x1E0) | phase; -} - -std::vector RCUTrailer::encode() const -{ - std::vector encoded; - encoded.emplace_back(mPayloadSize | 2 << 30); - encoded.emplace_back(mAltroCFG2 | 7 << 26 | 2 << 30); - encoded.emplace_back(mAltroCFG1 | 6 << 26 | 2 << 30); - encoded.emplace_back(mActiveFECsB | 5 << 26 | 2 << 30); - encoded.emplace_back(mActiveFECsA | 4 << 26 | 2 << 30); - encoded.emplace_back(mERRREG3 | 3 << 26 | 2 << 30); - encoded.emplace_back(mERRREG2 | 2 << 26 | 2 << 30); - encoded.emplace_back(mFECERRB >> 7 | (mFECERRA >> 7) << 13 | 1 << 26 | 2 << 30); - - uint32_t lasttrailerword = 3 << 30 | mFirmwareVersion << 16 | mRCUId << 7 | (encoded.size() + 1); - encoded.emplace_back(lasttrailerword); - - return encoded; -} - -void RCUTrailer::printStream(std::ostream& stream) const -{ - std::vector errors; - double timesample = -1., l1phase = -1.; - try { - timesample = getTimeSample(); - } catch (Error& e) { - errors.push_back(e.what()); - } - try { - l1phase = getL1Phase(); - } catch (Error& e) { - errors.push_back(e.what()); - } - - stream << "RCU trailer (Format version 2):\n" - << "==================================================\n" - << "RCU ID: " << mRCUId << "\n" - << "Firmware version: " << int(mFirmwareVersion) << "\n" - << "Trailer size: " << mTrailerSize << "\n" - << "Payload size: " << mPayloadSize << "\n" - << "FECERRA: 0x" << std::hex << mFECERRA << "\n" - << "FECERRB: 0x" << std::hex << mFECERRB << "\n" - << "ERRREG2: 0x" << std::hex << mERRREG2 << "\n" - << "#channels skipped due to address mismatch: " << std::dec << getNumberOfChannelAddressMismatch() << "\n" - << "#channels skipped due to bad block length: " << std::dec << getNumberOfChannelLengthMismatch() << "\n" - << "Active FECs (branch A): 0x" << std::hex << mActiveFECsA << "\n" - << "Active FECs (branch B): 0x" << std::hex << mActiveFECsB << "\n" - << "Baseline corr: 0x" << std::hex << int(getBaselineCorrection()) << "\n" - << "Number of presamples: " << std::dec << int(getNumberOfPresamples()) << "\n" - << "Number of postsamples: " << std::dec << int(getNumberOfPostsamples()) << "\n" - << "Second baseline corr: " << (hasSecondBaselineCorr() ? "yes" : "no") << "\n" - << "GlitchFilter: " << std::dec << int(getGlitchFilter()) << "\n" - << "Number of non-ZS postsamples: " << std::dec << int(getNumberOfNonZeroSuppressedPostsamples()) << "\n" - << "Number of non-ZS presamples: " << std::dec << int(getNumberOfNonZeroSuppressedPresamples()) << "\n" - << "Number of ALTRO buffers: " << std::dec << getNumberOfAltroBuffers() << "\n" - << "Number of pretrigger samples: " << std::dec << int(getNumberOfPretriggerSamples()) << "\n" - << "Number of samples per channel: " << std::dec << getNumberOfSamplesPerChannel() << "\n" - << "Sparse readout: " << (isSparseReadout() ? "yes" : "no") << "\n" - << "AltroCFG1: 0x" << std::hex << mAltroCFG1 << "\n" - << "AltroCFG2: 0x" << std::hex << mAltroCFG2 << "\n" - << "Sampling time: " << std::scientific << timesample << " s\n" - << "L1 Phase: " << std::scientific << l1phase << " s\n" - << std::dec << std::fixed; - if (errors.size()) { - stream << "Errors: \n" - << "-------------------------------------------------\n"; - for (const auto& e : errors) { - stream << e << "\n"; - } - } - stream << "==================================================\n"; -} - -RCUTrailer RCUTrailer::constructFromPayloadWords(const gsl::span payloadwords) -{ - RCUTrailer result; - auto tmp = gsl::span(reinterpret_cast(payloadwords.data()), payloadwords.size() * sizeof(uint32_t)); - result.constructFromRawPayload(tmp); - return result; -} -RCUTrailer RCUTrailer::constructFromPayload(const gsl::span payloadwords) -{ - RCUTrailer result; - result.constructFromRawPayload(payloadwords); - return result; -} - -std::ostream& o2::cpv::operator<<(std::ostream& stream, const o2::cpv::RCUTrailer& trailer) -{ - trailer.printStream(stream); - return stream; -} diff --git a/Detectors/CPV/calib/CPVCalibWorkflow/src/CPVGainCalibDevice.cxx b/Detectors/CPV/calib/CPVCalibWorkflow/src/CPVGainCalibDevice.cxx index 25f77e2cf9f70..2e347f99bd1b9 100644 --- a/Detectors/CPV/calib/CPVCalibWorkflow/src/CPVGainCalibDevice.cxx +++ b/Detectors/CPV/calib/CPVCalibWorkflow/src/CPVGainCalibDevice.cxx @@ -59,9 +59,7 @@ void CPVGainCalibDevice::run(o2::framework::ProcessingContext& ctx) } catch (RawErrorType_t e) { LOG(ERROR) << "Raw decoding error " << (int)e; //if problem in header, abandon this page - if (e == RawErrorType_t::kPAGE_NOTFOUND || - e == RawErrorType_t::kHEADER_DECODING || - e == RawErrorType_t::kHEADER_INVALID) { + if (e == RawErrorType_t::kRDH_DECODING) { break; } //if problem in payload, try to continue @@ -78,8 +76,8 @@ void CPVGainCalibDevice::run(o2::framework::ProcessingContext& ctx) continue; } // Loop over all the channels - for (uint32_t adch : decoder.getDigits()) { - AddressCharge ac = {adch}; + for (std::pair adchbc : decoder.getDigits()) { + AddressCharge ac = {adchbc.first}; unsigned short absId = ac.Address; mMean->Fill(absId, ac.Charge); } diff --git a/Detectors/CPV/calib/CPVCalibWorkflow/src/CPVPedestalCalibDevice.cxx b/Detectors/CPV/calib/CPVCalibWorkflow/src/CPVPedestalCalibDevice.cxx index bb953292c948b..d6e23ed027e13 100644 --- a/Detectors/CPV/calib/CPVCalibWorkflow/src/CPVPedestalCalibDevice.cxx +++ b/Detectors/CPV/calib/CPVCalibWorkflow/src/CPVPedestalCalibDevice.cxx @@ -51,9 +51,7 @@ void CPVPedestalCalibDevice::run(o2::framework::ProcessingContext& ctx) } catch (RawErrorType_t e) { LOG(ERROR) << "Raw decoding error " << (int)e; //if problem in header, abandon this page - if (e == RawErrorType_t::kPAGE_NOTFOUND || - e == RawErrorType_t::kHEADER_DECODING || - e == RawErrorType_t::kHEADER_INVALID) { + if (e == RawErrorType_t::kRDH_DECODING) { break; } //if problem in payload, try to continue @@ -70,8 +68,8 @@ void CPVPedestalCalibDevice::run(o2::framework::ProcessingContext& ctx) continue; } // Loop over all the channels - for (uint32_t adch : decoder.getDigits()) { - AddressCharge ac = {adch}; + for (std::pair adchbc : decoder.getDigits()) { + AddressCharge ac = {adchbc.first}; unsigned short absId = ac.Address; mMean->Fill(absId, ac.Charge); } diff --git a/Detectors/CPV/reconstruction/include/CPVReconstruction/RawDecoder.h b/Detectors/CPV/reconstruction/include/CPVReconstruction/RawDecoder.h index 4dd770c007a55..2c3a0e600fb03 100644 --- a/Detectors/CPV/reconstruction/include/CPVReconstruction/RawDecoder.h +++ b/Detectors/CPV/reconstruction/include/CPVReconstruction/RawDecoder.h @@ -13,7 +13,7 @@ #include #include #include -#include "CPVBase/RCUTrailer.h" +#include #include "DataFormatsCPV/Digit.h" #include "CPVReconstruction/RawReaderMemory.h" class Digits; @@ -54,6 +54,10 @@ union AddressCharge { /// \since Dec, 2020 /// /// This is a base class for reading raw data digits. +/// It takes raw cpv payload from RawReaderMemory and produces +/// std::vector> mDigits +/// mDigits[i].first is AddressCharge word and +/// mDigits[i].second is bc number in current HBF class RawDecoder { @@ -65,33 +69,28 @@ class RawDecoder /// \brief Destructor ~RawDecoder() = default; - /// \brief Decode the ALTRO stream - /// \throw RawDecoderError if the RCUTrailer or ALTRO payload cannot be decoded + /// \brief Decode the raw cpv payload stream + /// \throw RawDecoderError if the RCUTrailer or raw cpv payload cannot be decoded /// - /// Decoding and checking the RCUTtrailer and - /// all channels and bunches in the ALTRO stream. + /// Decoding and checking the cpvheader, + /// cpvwords and cpvtrailer. /// After successfull decoding the Decoder can provide - /// a reference to the RCU trailer and a vector + /// a reference to a vector /// with the decoded chanenels, each containing - /// its bunches. + /// its BC numbers. RawErrorType_t decode(); - /// \brief Get reference to the RCU trailer object - /// \return const reference to the RCU trailer - const RCUTrailer& getRCUTrailer() const; - /// \brief Get the reference to the digits container /// \return Reference to the digits container - const std::vector& getDigits() const; + const std::vector>& getDigits() const; + + /// \brief Get the reference to the BC /// \brief Get the reference to the list of decoding errors /// \return Reference to the list of decoding errors const std::vector& getErrors() const { return mErrors; } protected: - /// \brief Read RCU trailer for the current event in the raw buffer - RawErrorType_t readRCUTrailer(); - /// \brief Read channels for the current event in the raw buffer RawErrorType_t readChannels(); @@ -101,17 +100,17 @@ class RawDecoder /// /// Performing various consistency checks on the RCU trailer /// In case of failure an exception is thrown. - void checkRCUTrailer(); + //void checkRCUTrailer(); - void addDigit(uint32_t padWord, short ddl); + void addDigit(uint32_t padWord, short ddl, uint16_t bc); + void removeLastNDigits(int n); - RawReaderMemory& mRawReader; ///< underlying raw reader - RCUTrailer mRCUTrailer; ///< RCU trailer - std::vector mDigits; ///< vector of channels in the raw stream - std::vector mErrors; ///< vector of decoding errors - bool mChannelsInitialized = false; ///< check whether the channels are initialized + RawReaderMemory& mRawReader; ///< underlying raw reader + std::vector> mDigits; ///< vector of channels and BCs in the raw stream + std::vector mErrors; ///< vector of decoding errors + bool mChannelsInitialized = false; ///< check whether the channels are initialized - ClassDefNV(RawDecoder, 1); + ClassDefNV(RawDecoder, 2); }; } // namespace cpv diff --git a/Detectors/CPV/reconstruction/include/CPVReconstruction/RawReaderMemory.h b/Detectors/CPV/reconstruction/include/CPVReconstruction/RawReaderMemory.h index 711c2371d7f7c..31b63f9c0a557 100644 --- a/Detectors/CPV/reconstruction/include/CPVReconstruction/RawReaderMemory.h +++ b/Detectors/CPV/reconstruction/include/CPVReconstruction/RawReaderMemory.h @@ -13,7 +13,6 @@ #include #include -#include "CPVBase/RCUTrailer.h" #include "Headers/RAWDataHeader.h" #include "Headers/RDHAny.h" @@ -24,19 +23,23 @@ namespace cpv { enum RawErrorType_t { - kOK, ///< NoError - kNO_PAYLOAD, ///< No payload per ddl - kHEADER_DECODING, + kOK, ///< NoError + kOK_NO_PAYLOAD, ///< No payload per ddl (not error) + kRDH_DECODING, + kRDH_INVALID, + kNOT_CPV_RDH, + kSTOPBIT_NOTFOUND, kPAGE_NOTFOUND, - kPAYLOAD_DECODING, - kHEADER_INVALID, - kRCU_TRAILER_ERROR, ///< RCU trailer cannot be decoded or invalid - kRCU_VERSION_ERROR, ///< RCU trailer version not matching with the version in the raw header - kRCU_TRAILER_SIZE_ERROR, ///< RCU trailer size length + kPAYLOAD_INCOMPLETE, + kNO_CPVHEADER, + kNO_CPVTRAILER, + kCPVHEADER_INVALID, + kCPVTRAILER_INVALID, kSEGMENT_HEADER_ERROR, kROW_HEADER_ERROR, kEOE_HEADER_ERROR, kPADERROR, + kUNKNOWN_WORD, kPadAddress }; @@ -46,7 +49,7 @@ enum RawErrorType_t { /// \author Dmitri Peresunko after Markus Fasel /// \since Sept. 25, 2020 /// -/// +///It reads one HBF, stores HBF orbit number in getCurrentHBFOrbit() and produces digits in AddressChargeBC format class RawReaderMemory { public: @@ -95,6 +98,9 @@ class RawReaderMemory /// \return true if there is a next page bool hasNext() const { return mCurrentPosition < mRawMemoryBuffer.size(); } + /// \return HeartBeatFrame orbit number + uint32_t getCurrentHBFOrbit() const { return mCurrentHBFOrbit; } + protected: /// \brief Initialize the raw stream /// @@ -107,13 +113,13 @@ class RawReaderMemory gsl::span mRawMemoryBuffer; ///< Memory block with multiple DMA pages o2::header::RDHAny mRawHeader; ///< Raw header std::vector mRawPayload; ///< Raw payload (can consist of multiple pages) - RCUTrailer mCurrentTrailer; ///< RCU trailer - uint64_t mTrailerPayloadWords = 0; ///< Payload words in common trailer int mCurrentPosition = 0; ///< Current page in file bool mRawHeaderInitialized = false; ///< RDH for current page initialized bool mPayloadInitialized = false; ///< Payload for current page initialized + uint32_t mCurrentHBFOrbit = 0; ///< Current orbit of HBF + bool mStopBitWasNotFound; ///< True if StopBit was not found but HBF orbit changed - ClassDefNV(RawReaderMemory, 1); + ClassDefNV(RawReaderMemory, 2); }; } // namespace cpv diff --git a/Detectors/CPV/reconstruction/src/RawDecoder.cxx b/Detectors/CPV/reconstruction/src/RawDecoder.cxx index 0f3f3f371159d..b3aa49a4466a6 100644 --- a/Detectors/CPV/reconstruction/src/RawDecoder.cxx +++ b/Detectors/CPV/reconstruction/src/RawDecoder.cxx @@ -18,7 +18,6 @@ using namespace o2::cpv; RawDecoder::RawDecoder(RawReaderMemory& reader) : mRawReader(reader), - mRCUTrailer(), mChannelsInitialized(false) { } @@ -26,98 +25,114 @@ RawDecoder::RawDecoder(RawReaderMemory& reader) : mRawReader(reader), RawErrorType_t RawDecoder::decode() { - auto& header = mRawReader.getRawHeader(); - short ddl = o2::raw::RDHUtils::getFEEID(header); + auto& rdh = mRawReader.getRawHeader(); + short linkID = o2::raw::RDHUtils::getLinkID(rdh); mDigits.clear(); - auto payloadwords = mRawReader.getPayload(); - if (payloadwords.size() == 0) { - mErrors.emplace_back(ddl, 0, 0, 0, kNO_PAYLOAD); //add error - LOG(ERROR) << "Empty payload for DDL=" << ddl; - return kNO_PAYLOAD; + auto payloadWords = mRawReader.getPayload(); + if (payloadWords.size() == 0) { + return kOK_NO_PAYLOAD; } - // if(readRCUTrailer()!=kOK){ - // LOG(ERROR) << "can not read RCU trailer for DDL " << ddl ; - // return kRCU_TRAILER_ERROR; - // } - return readChannels(); } -RawErrorType_t RawDecoder::readRCUTrailer() -{ - gsl::span payload(reinterpret_cast(mRawReader.getPayload().data()), mRawReader.getPayload().size() * sizeof(uint32_t)); - mRCUTrailer.constructFromRawPayload(payload); - return kOK; -} - RawErrorType_t RawDecoder::readChannels() { mChannelsInitialized = false; - auto& header = mRawReader.getRawHeader(); - // short ddl = o2::raw::RDHUtils::getLinkID(header) ; //Current module - auto& payloadwords = mRawReader.getPayload(); - uint32_t wc = 0; - auto b = payloadwords.cbegin(); - auto e = payloadwords.cend(); - while (b != e) { - cpvword w(b, e); - if (w.isOK()) { - for (int i = 0; i < 3; i++) { - PadWord pw = {w.cpvPadWord(i)}; - if (pw.zero == 0) { - addDigit(pw.mDataWord, w.ccId()); - } else { - if (pw.mDataWord != 0xffffff) { //not empty pad - LOG(ERROR) << "no zero bit in data word " << pw.mDataWord; - mErrors.emplace_back(w.ccId(), 0, 0, 0, kPADERROR); //add error for non-existing row + auto& payloadWords = mRawReader.getPayload(); + uint32_t wordCountFromLastHeader = 1; //header word is included + int nDigitsAddedFromLastHeader = 0; + bool isHeaderExpected = true; //true if we expect to read header, false otherwise + bool skipUntilNextHeader = true; //true if something wrong with data format, try to read next header + uint16_t currentBC; + uint32_t currentOrbit = mRawReader.getCurrentHBFOrbit(); + auto b = payloadWords.cbegin(); + auto e = payloadWords.cend(); + while (b != e) { //payload must start with cpvheader folowed by cpvwords and finished with cpvtrailer + cpvheader header(b, e); + if (header.isOK()) { + if (!isHeaderExpected) { //actually, header was not expected + LOG(ERROR) << "RawDecoder::readChannels() : " + << "header was not expected"; + removeLastNDigits(nDigitsAddedFromLastHeader); //remove previously added digits as they are bad + mErrors.emplace_back(5, 0, 0, 0, kNO_CPVTRAILER); + } + skipUntilNextHeader = false; + currentBC = header.bc(); + wordCountFromLastHeader = 0; + nDigitsAddedFromLastHeader = 0; + if (currentOrbit != header.orbit()) { //bad cpvheader + LOG(ERROR) << "RawDecoder::readChannels() : " + << "currentOrbit != header.orbit()"; + mErrors.emplace_back(5, 0, 0, 0, kCPVHEADER_INVALID); //5 is non-existing link with general errors + skipUntilNextHeader = true; + } + } else { + if (skipUntilNextHeader) { + b += 16; + continue; //continue while'ing until it's not header + } + cpvword word(b, e); + if (word.isOK()) { + wordCountFromLastHeader++; + for (int i = 0; i < 3; i++) { + PadWord pw = {word.cpvPadWord(i)}; + if (pw.zero == 0) { + addDigit(pw.mDataWord, word.ccId(), currentBC); + nDigitsAddedFromLastHeader++; } } - } - } else { //this may be trailer - cpvtrailer tr(b, e); - if (tr.isOK()) { - if (tr.wordCounter() != wc) { - //some words lost? - LOG(ERROR) << "Read " << wc << " words, expected " << tr.wordCounter(); - mErrors.emplace_back(w.ccId(), 0, 0, 0, kPAYLOAD_DECODING); - //TODO! should we continuew or brake? + } else { //this may be trailer + cpvtrailer trailer(b, e); + if (trailer.isOK()) { + int diffInCount = wordCountFromLastHeader - trailer.wordCounter(); + if (diffInCount > 1 || + diffInCount < -1) { + //some words lost? + LOG(ERROR) << "RawDecoder::readChannels() : " + << "Read " << wordCountFromLastHeader << " words, expected " << trailer.wordCounter(); + mErrors.emplace_back(5, 0, 0, 0, kCPVTRAILER_INVALID); + //throw all previous data and go to next header + removeLastNDigits(nDigitsAddedFromLastHeader); + skipUntilNextHeader = true; + } + if (trailer.bc() != currentBC) { + //trailer does not fit header + LOG(ERROR) << "RawDecoder::readChannels() : " + << "CPVHeader BC is " << currentBC << " but CPVTrailer BC is " << trailer.bc(); + mErrors.emplace_back(5, 0, 0, 0, kCPVTRAILER_INVALID); + removeLastNDigits(nDigitsAddedFromLastHeader); + skipUntilNextHeader = true; + } + isHeaderExpected = true; + } else { + wordCountFromLastHeader++; + //error + LOG(ERROR) << "RawDecoder::readChannels() : " + << "Read unknown word"; + mErrors.emplace_back(5, 0, 0, 0, kUNKNOWN_WORD); //add error for non-existing row + //what to do? } - } else { - //error - LOG(ERROR) << "Read neither data nor trailer word"; - mErrors.emplace_back(w.ccId(), 0, 0, 0, kPADERROR); //add error for non-existing row } } b += 16; - wc++; } - mChannelsInitialized = true; return kOK; } -const RCUTrailer& RawDecoder::getRCUTrailer() const -{ - if (!mRCUTrailer.isInitialized()) { - LOG(ERROR) << "RCU trailer not initialized"; - } - return mRCUTrailer; -} - -const std::vector& RawDecoder::getDigits() const +const std::vector>& RawDecoder::getDigits() const { - if (!mChannelsInitialized) { - LOG(ERROR) << "Channels not initialized"; - } + /*if (!mChannelsInitialized) { + LOG(ERROR) << "RawDecoder::getDigits() : Channels not initialized"; + }*/ return mDigits; } -void RawDecoder::addDigit(uint32_t w, short ccId) +void RawDecoder::addDigit(uint32_t w, short ccId, uint16_t bc) { - PadWord pad = {w}; unsigned short absId; o2::cpv::Geometry::hwaddressToAbsId(ccId, pad.dil, pad.gas, pad.address, absId); @@ -125,5 +140,21 @@ void RawDecoder::addDigit(uint32_t w, short ccId) AddressCharge ac = {0}; ac.Address = absId; ac.Charge = pad.charge; - mDigits.push_back(ac.mDataWord); + //std::pair digitAndBC + mDigits.push_back(std::pair(ac.mDataWord, bc)); +} + +void RawDecoder::removeLastNDigits(int n) +{ + if (n < 0) + return; + int nRemoved = 0; + while (nRemoved < n) { + if (mDigits.size() > 0) { // still has digits to remove + mDigits.pop_back(); + nRemoved++; + } else { // has nothing to remove already + break; + } + } } \ No newline at end of file diff --git a/Detectors/CPV/reconstruction/src/RawReaderMemory.cxx b/Detectors/CPV/reconstruction/src/RawReaderMemory.cxx index 0947166ea0854..53424f830c9ab 100644 --- a/Detectors/CPV/reconstruction/src/RawReaderMemory.cxx +++ b/Detectors/CPV/reconstruction/src/RawReaderMemory.cxx @@ -39,9 +39,8 @@ o2::header::RDHAny RawReaderMemory::decodeRawHeader(const void* payloadwords) } else if (headerversion == 6) { return o2::header::RDHAny(*reinterpret_cast(payloadwords)); } - LOG(ERROR) << "Unknown RDH version"; + LOG(ERROR) << "RawReaderMemory::decodeRawHeader() : Unknown RDH version"; return o2::header::RDHAny(*reinterpret_cast(payloadwords)); - ; } void RawReaderMemory::init() @@ -49,48 +48,32 @@ void RawReaderMemory::init() mCurrentPosition = 0; mRawHeaderInitialized = false; mPayloadInitialized = false; + mCurrentHBFOrbit = 0; + mStopBitWasNotFound = false; } +//Read the next pages until the stop bit is found or new HBF reached +//it means we read 1 HBF per next() call RawErrorType_t RawReaderMemory::next() { mRawPayload.clear(); - mCurrentTrailer.reset(); - bool isDataTerminated = false; + bool isStopBitFound = false; do { RawErrorType_t e = nextPage(); - if (e != RawErrorType_t::kOK) { - return e; + if (e == RawErrorType_t::kPAGE_NOTFOUND || // nothing left to read... + e == RawErrorType_t::kRDH_DECODING || // incorrect rdh -> fatal error + e == RawErrorType_t::kPAYLOAD_INCOMPLETE || // we reached end of mRawMemoryBuffer but payload size from rdh tells to read more + e == RawErrorType_t::kSTOPBIT_NOTFOUND) { //new HBF orbit started but no stop bit found, need to return + return e; //some principal error occured -> stop reading. } - if (hasNext()) { - auto nextheader = decodeRawHeader(mRawMemoryBuffer.data() + mCurrentPosition); - // check continuing payload based on the bc/orbit ID - auto currentbc = RDHDecoder::getTriggerBC(mRawHeader), - nextbc = RDHDecoder::getTriggerBC(nextheader); - auto currentorbit = RDHDecoder::getTriggerOrbit(mRawHeader), - nextorbit = RDHDecoder::getTriggerOrbit(nextheader); - if (currentbc != nextbc || currentorbit != nextorbit) { - isDataTerminated = true; - } else { - auto nextpagecounter = RDHDecoder::getPageCounter(nextheader); - if (nextpagecounter == 0) { - isDataTerminated = true; - } else { - isDataTerminated = false; - } - } - } else { - isDataTerminated = true; - } - // Check if the data continues - } while (!isDataTerminated); - try { - mCurrentTrailer.constructFromPayloadWords(gsl::span(reinterpret_cast(mRawPayload.data()), mRawPayload.size() / sizeof(uint32_t))); - } catch (...) { - return RawErrorType_t::kHEADER_DECODING; - } + isStopBitFound = RDHDecoder::getStop(mRawHeader); + } while (!isStopBitFound); + return RawErrorType_t::kOK; } +//Read the next ONLY ONE page from the stream (single DMA page) +//note: 1 raw header per page RawErrorType_t RawReaderMemory::nextPage() { if (!hasNext()) { @@ -100,32 +83,46 @@ RawErrorType_t RawReaderMemory::nextPage() mPayloadInitialized = false; // Read RDH header + o2::header::RDHAny rawHeader; try { - mRawHeader = decodeRawHeader(mRawMemoryBuffer.data() + mCurrentPosition); - while (RDHDecoder::getOffsetToNext(mRawHeader) == RDHDecoder::getHeaderSize(mRawHeader) && - mCurrentPosition < mRawMemoryBuffer.size()) { - // No Payload - jump to next rawheader - // This will eventually move, depending on whether for events without payload in the SRU we send the RCU trailer - mCurrentPosition += RDHDecoder::getHeaderSize(mRawHeader); - mRawHeader = decodeRawHeader(mRawMemoryBuffer.data() + mCurrentPosition); - } - mRawHeaderInitialized = true; + rawHeader = decodeRawHeader(mRawMemoryBuffer.data() + mCurrentPosition); } catch (...) { - return RawErrorType_t::kHEADER_DECODING; + return RawErrorType_t::kRDH_DECODING; //this is fatal error } - if (mCurrentPosition + RDHDecoder::getMemorySize(mRawHeader) > mRawMemoryBuffer.size()) { - // Payload incomplete - return RawErrorType_t::kPAYLOAD_DECODING; + if (RDHDecoder::getSourceID(rawHeader) != 0x8) { + // Not a CPV RDH + mCurrentPosition += RDHDecoder::getOffsetToNext(rawHeader); //moving on + return RawErrorType_t::kNOT_CPV_RDH; + } + if (mCurrentHBFOrbit != 0 || mStopBitWasNotFound) { //reading first time after init() or stopbit was not found + mCurrentHBFOrbit = RDHDecoder::getHeartBeatOrbit(rawHeader); + mRawHeader = rawHeader; //save RDH of first page as mRawHeader + mRawHeaderInitialized = true; + mStopBitWasNotFound = false; //reset this flag as we start to read again + } else if (mCurrentHBFOrbit != RDHDecoder::getHeartBeatOrbit(rawHeader)) { + //next HBF started but we didn't find stop bit. + mStopBitWasNotFound = true; + return RawErrorType_t::kSTOPBIT_NOTFOUND; //Stop reading, this will be read again by calling next() } + mRawHeader = rawHeader; //save RDH of current page as mRawHeader + mRawHeaderInitialized = true; auto tmp = mRawMemoryBuffer.data(); int start = (mCurrentPosition + RDHDecoder::getHeaderSize(mRawHeader)); - int end = start + (RDHDecoder::getMemorySize(mRawHeader) - RDHDecoder::getHeaderSize(mRawHeader)); + int end = (mCurrentPosition + RDHDecoder::getMemorySize(mRawHeader)); + bool isPayloadIncomplete = false; + if (mCurrentPosition + RDHDecoder::getMemorySize(mRawHeader) > mRawMemoryBuffer.size()) { + // Payload incomplete + end = mRawMemoryBuffer.size(); //OK, lets read it anyway. Maybe there still are some completed events... + } for (auto iword = start; iword < end; iword++) { mRawPayload.push_back(tmp[iword]); } + mPayloadInitialized = true; mCurrentPosition += RDHDecoder::getOffsetToNext(mRawHeader); /// Assume fixed 8 kB page size - + if (isPayloadIncomplete) { + return RawErrorType_t::kPAYLOAD_INCOMPLETE; //return error so we can it handle later + } return RawErrorType_t::kOK; } diff --git a/Detectors/CPV/simulation/include/CPVSimulation/RawWriter.h b/Detectors/CPV/simulation/include/CPVSimulation/RawWriter.h index ec407f91bf0dd..e4f21a1dd388b 100644 --- a/Detectors/CPV/simulation/include/CPVSimulation/RawWriter.h +++ b/Detectors/CPV/simulation/include/CPVSimulation/RawWriter.h @@ -27,6 +27,7 @@ #include "DataFormatsCPV/TriggerRecord.h" #include "CPVCalib/CalibParams.h" #include "CPVCalib/Pedestals.h" +#include "CPVCalib/BadChannelMap.h" namespace o2 { @@ -68,7 +69,7 @@ class RawWriter void init(); void digitsToRaw(gsl::span digits, gsl::span triggers); - bool processTrigger(const gsl::span digitsbranch, const o2::cpv::TriggerRecord& trg); + bool processOrbit(const gsl::span digitsbranch, const gsl::span trgs); int carryOverMethod(const header::RDHAny* rdh, const gsl::span data, const char* ptr, int maxSize, int splitID, @@ -80,6 +81,7 @@ class RawWriter std::string mOutputLocation = "./"; ///< Rawfile name std::unique_ptr mCalibParams; ///< CPV calibration std::unique_ptr mPedestals; ///< CPV pedestals + std::unique_ptr mBadMap; ///< CPV bad channel map std::vector mPayload; ///< Payload to be written gsl::span mDigits; ///< Digits input vector - must be in digitized format including the time response std::unique_ptr mRawWriter; ///< Raw writer diff --git a/Detectors/CPV/simulation/src/RawWriter.cxx b/Detectors/CPV/simulation/src/RawWriter.cxx index ce77135949549..2801a17ca8ec5 100644 --- a/Detectors/CPV/simulation/src/RawWriter.cxx +++ b/Detectors/CPV/simulation/src/RawWriter.cxx @@ -13,10 +13,10 @@ #include #include #include +#include "DetectorsRaw/RDHUtils.h" #include "DataFormatsCPV/RawFormats.h" #include "CPVSimulation/RawWriter.h" #include "CPVBase/CPVSimParams.h" -#include "CPVBase/RCUTrailer.h" #include "CPVBase/Geometry.h" #include "CCDB/CcdbApi.h" @@ -24,7 +24,7 @@ using namespace o2::cpv; void RawWriter::init() { - mRawWriter = std::make_unique(o2::header::gDataOriginCPV, false); + mRawWriter = std::make_unique(o2::header::gDataOriginCPV, true); //true = cru detector mRawWriter->setCarryOverCallBack(this); mRawWriter->setApplyCarryOverToLastPage(true); @@ -38,6 +38,9 @@ void RawWriter::init() void RawWriter::digitsToRaw(gsl::span digitsbranch, gsl::span triggerbranch) { + if (triggerbranch.begin() == triggerbranch.end()) { //do we have any data? + return; + } if (!mCalibParams) { if (o2::cpv::CPVSimParams::Instance().mCCDBPath.compare("localtest") == 0) { mCalibParams = std::make_unique(1); // test default calibration @@ -82,14 +85,26 @@ void RawWriter::digitsToRaw(gsl::span digitsbranch, gsl::span digitsbranch, const o2::cpv::TriggerRecord& trg) +//prepare preformatted data for one orbit and send it to RawFileWriter +bool RawWriter::processOrbit(const gsl::span digitsbranch, const gsl::span trgs) { - //Array used to sort properly digits for (int i = kNcc; i--;) { for (int j = kNDilogic; j--;) { @@ -98,73 +113,143 @@ bool RawWriter::processTrigger(const gsl::span digitsbranch, con } } } + //clear payload + mPayload.clear(); + + //we're going to prepare preformatted pages + int feeid = 0, cru = 0, link = 0, endpoint = 0; + bool preformatted = true; + + int gbtWordCounter = 0; + int gbtWordCounterBeforeCPVTrailer = 0; + int nMaxGbtWordsPerPage = o2::raw::RDHUtils::MAXCRUPage / o2::raw::RDHUtils::GBTWord; //512*16/16 = 512; + nMaxGbtWordsPerPage -= 4; //rdh size = 4 gbt words + for (auto& trg : trgs) { + gbtWordCounterBeforeCPVTrailer = 0; //every trigger we start this counter from 0 - for (auto& dig : gsl::span(digitsbranch.data() + trg.getFirstEntry(), trg.getNumberOfObjects())) { + //make payload for current trigger + int nDigsInTrg = 0; + for (auto& dig : gsl::span(digitsbranch.data() + trg.getFirstEntry(), trg.getNumberOfObjects())) { - short absId = dig.getAbsId(); - short ccId, dil, gas, pad; - o2::cpv::Geometry::absIdToHWaddress(absId, ccId, dil, gas, pad); + short absId = dig.getAbsId(); + short ccId, dil, gas, pad; + o2::cpv::Geometry::absIdToHWaddress(absId, ccId, dil, gas, pad); - //Convert Amp to ADC counts - short charge = dig.getAmplitude() / mCalibParams->getGain(absId) + mPedestals->getPedestal(absId); - if (charge > 4095) { - charge = 4095; + //Convert Amp to ADC counts + short charge = dig.getAmplitude() / mCalibParams->getGain(absId) + mPedestals->getPedestal(absId); + if (charge > 4095) { + charge = 4095; + } + mPadCharge[ccId][dil][gas].emplace_back(charge, pad); + nDigsInTrg++; } - mPadCharge[ccId][dil][gas].emplace_back(charge, pad); - } - //Do through DLLs and fill raw words in proper order - mPayload.clear(); + //we need to write header + trailer + at least 1 payload word + if (nMaxGbtWordsPerPage - gbtWordCounter < 3) { //otherwise flush already prepared data to file + LOG(DEBUG) << "RawWriter::processOrbit() : before header: adding preformatted dma page of size " << mPayload.size(); + mRawWriter->addData(feeid, cru, link, endpoint, trg.getBCData(), gsl::span(mPayload.data(), mPayload.size()), preformatted); + mPayload.clear(); + gbtWordCounter = 0; + gbtWordCounterBeforeCPVTrailer = 0; + } - int ccWordCounter = 0; - int gbtWordCounter = 0; - for (char ccId = 0; ccId < kNcc; ccId++) { - for (char dil = 0; dil < kNDilogic; dil++) { - for (char gas = 0; gas < kNGasiplex; gas++) { - for (padCharge& pc : mPadCharge[ccId][dil][gas]) { - // Generate 3 CC words, add CC header and empty bits to complete 128 bits; - PadWord currentword = {0}; - currentword.charge = pc.charge; - currentword.address = pc.pad; - currentword.gas = gas; - currentword.dil = dil; - mPayload.push_back(currentword.bytes[0]); - mPayload.push_back(currentword.bytes[1]); - mPayload.push_back(currentword.bytes[2]); - ccWordCounter++; - if (ccWordCounter % 3 == 0) { // complete 3 channels (72 bit) + CC index (8 bits) + 6 empty bits = Generate 128 bits of data + //first, header goes + cpvheader header(trg.getBCData(), false, false); + for (int i = 0; i < 16; i++) { + mPayload.push_back(header.bytes[i]); + } + gbtWordCounter++; + gbtWordCounterBeforeCPVTrailer++; + + int ccWordCounter = 0; + for (char ccId = 0; ccId < kNcc; ccId++) { + for (char dil = 0; dil < kNDilogic; dil++) { + for (char gas = 0; gas < kNGasiplex; gas++) { + for (padCharge& pc : mPadCharge[ccId][dil][gas]) { + // Generate 3 CC words, add CC header and empty bits to complete 128 bits; + PadWord currentword = {0}; + currentword.charge = pc.charge; + currentword.address = pc.pad; + currentword.gas = gas; + currentword.dil = dil; + mPayload.push_back(currentword.bytes[0]); + mPayload.push_back(currentword.bytes[1]); + mPayload.push_back(currentword.bytes[2]); + ccWordCounter++; + if (ccWordCounter % 3 == 0) { // complete 3 channels (72 bit) + CC index (8 bits) + 6 empty bits = Generate 128 bits of data + mPayload.push_back(ccId); + for (int i = 6; i--;) { + mPayload.push_back(char(0)); + } + gbtWordCounter++; + gbtWordCounterBeforeCPVTrailer++; + if (nMaxGbtWordsPerPage - gbtWordCounter < 2) { //the only space for trailer left on current page + cpvtrailer tr(gbtWordCounterBeforeCPVTrailer, trg.getBCData().bc, true); //add trailer and flush page to file + for (int i = 0; i < 16; i++) { + mPayload.push_back(tr.bytes[i]); + } + LOG(DEBUG) << "RawWriter::processOrbit() : middle of payload: adding preformatted dma page of size " << mPayload.size(); + mRawWriter->addData(feeid, cru, link, endpoint, trg.getBCData(), gsl::span(mPayload.data(), mPayload.size()), preformatted); + mPayload.clear(); + gbtWordCounter = 0; + gbtWordCounterBeforeCPVTrailer = 0; + if (nDigsInTrg > gbtWordCounterBeforeCPVTrailer - 1) { //some digits left for writing + for (int i = 0; i < 16; i++) { //so put a new header and continue + mPayload.push_back(header.bytes[i]); + } + gbtWordCounter++; + gbtWordCounterBeforeCPVTrailer++; + } + } + } + } + if (ccWordCounter % 3 != 0) { + while (ccWordCounter % 3 != 0) { + mPayload.push_back(char(255)); + mPayload.push_back(char(255)); + mPayload.push_back(char(255)); + ccWordCounter++; + } mPayload.push_back(ccId); for (int i = 6; i--;) { mPayload.push_back(char(0)); } gbtWordCounter++; + gbtWordCounterBeforeCPVTrailer++; + if (nMaxGbtWordsPerPage - gbtWordCounter < 2) { //the only space for trailer left on current page + cpvtrailer tr(gbtWordCounterBeforeCPVTrailer, trg.getBCData().bc, true); //add trailer and flush page to file + for (int i = 0; i < 16; i++) { + mPayload.push_back(tr.bytes[i]); + } + LOG(DEBUG) << "RawWriter::processOrbit() : middle of payload (after filling empty words): adding preformatted dma page of size " << mPayload.size(); + mRawWriter->addData(feeid, cru, link, endpoint, trg.getBCData(), gsl::span(mPayload.data(), mPayload.size()), preformatted); + mPayload.clear(); + gbtWordCounter = 0; + gbtWordCounterBeforeCPVTrailer = 0; + if (nDigsInTrg > gbtWordCounterBeforeCPVTrailer - 1) { //some digits left for writing + for (int i = 0; i < 16; i++) { //so put a new header and continue + mPayload.push_back(header.bytes[i]); + } + gbtWordCounter++; + gbtWordCounterBeforeCPVTrailer++; + } + } } } - if (ccWordCounter % 3 != 0) { - while (ccWordCounter % 3 != 0) { - mPayload.push_back(char(255)); - mPayload.push_back(char(255)); - mPayload.push_back(char(255)); - ccWordCounter++; - } - mPayload.push_back(ccId); - for (int i = 6; i--;) { - mPayload.push_back(char(0)); - } - gbtWordCounter++; - } } } + cpvtrailer tr(gbtWordCounterBeforeCPVTrailer, trg.getBCData().bc, true); //cout GBT words + for (int i = 0; i < 16; i++) { + mPayload.push_back(tr.bytes[i]); + } + gbtWordCounterBeforeCPVTrailer++; + gbtWordCounter++; + } //end of for (auto& trg : trgs) + if (mPayload.size()) { //flush payload to file (if any) + LOG(DEBUG) << "RawWriter::processOrbit() : final payload: adding preformatted dma page of size " << mPayload.size(); + mRawWriter->addData(feeid, cru, link, endpoint, trgs.back().getBCData(), gsl::span(mPayload.data(), mPayload.size()), preformatted); + mPayload.clear(); } - cpvtrailer tr(gbtWordCounter); //cout GBT words - for (int i = 0; i < 16; i++) { - mPayload.push_back(tr.bytes[i]); - } - - // register output data - LOG(DEBUG1) << "Adding payload with size " << mPayload.size() << " char words)"; - - mRawWriter->addData(0, 0, 0, 0, trg.getBCData(), gsl::span(mPayload.data(), mPayload.size())); return true; } int RawWriter::carryOverMethod(const header::RDHAny* rdh, const gsl::span data, diff --git a/Detectors/CPV/workflow/src/RawToDigitConverterSpec.cxx b/Detectors/CPV/workflow/src/RawToDigitConverterSpec.cxx index 365421ed4c066..8c9cd27e7904a 100644 --- a/Detectors/CPV/workflow/src/RawToDigitConverterSpec.cxx +++ b/Detectors/CPV/workflow/src/RawToDigitConverterSpec.cxx @@ -113,24 +113,21 @@ void RawToDigitConverterSpec::run(framework::ProcessingContext& ctx) } for (const auto& rawData : framework::InputRecordWalker(ctx.inputs())) { - - // enum RawErrorType_t { - // kOK, ///< NoError - // kNO_PAYLOAD, ///< No payload per ddl - // kHEADER_DECODING, - // kPAGE_NOTFOUND, - // kPAYLOAD_DECODING, - // kHEADER_INVALID, - // kRCU_TRAILER_ERROR, ///< RCU trailer cannot be decoded or invalid - // kRCU_VERSION_ERROR, ///< RCU trailer version not matching with the version in the raw header - // kRCU_TRAILER_SIZE_ERROR, ///< RCU trailer size length - // kSEGMENT_HEADER_ERROR, - // kROW_HEADER_ERROR, - // kEOE_HEADER_ERROR, - // kPADERROR, - // kPadAddress - // }; - + /* enum RawErrorType_t { + kOK, ///< NoError + kNO_PAYLOAD, ///< No payload per ddl + kRDH_DECODING, + kNOT_CPV_RDH, + kPAGE_NOTFOUND, + kPAYLOAD_INCOMPLETE, + kCPVHEADER_INVALID, + kCPVTRAILER_INVALID, + kSEGMENT_HEADER_ERROR, + kROW_HEADER_ERROR, + kEOE_HEADER_ERROR, + kPADERROR, + kPadAddress + */ o2::cpv::RawReaderMemory rawreader(o2::framework::DataRefUtils::as(rawData)); // loop over all the DMA pages while (rawreader.hasNext()) { @@ -141,37 +138,23 @@ void RawToDigitConverterSpec::run(framework::ProcessingContext& ctx) //add error list mOutputHWErrors.emplace_back(5, 0, 0, 0, e); //Put general errors to non-existing DDL5 //if problem in header, abandon this page - if (e == RawErrorType_t::kPAGE_NOTFOUND || - e == RawErrorType_t::kHEADER_DECODING || - e == RawErrorType_t::kHEADER_INVALID) { + if (e == RawErrorType_t::kRDH_DECODING) { break; } //if problem in payload, try to continue continue; } - auto& header = rawreader.getRawHeader(); - auto triggerBC = o2::raw::RDHUtils::getTriggerBC(header); - auto triggerOrbit = o2::raw::RDHUtils::getTriggerOrbit(header); + auto& rdh = rawreader.getRawHeader(); + auto triggerOrbit = o2::raw::RDHUtils::getTriggerOrbit(rdh); // auto ddl = o2::raw::RDHUtils::getFEEID(header); - auto mod = o2::raw::RDHUtils::getLinkID(header) + 2; //ddl=0,1,2 -> mod=2,3,4 + auto mod = o2::raw::RDHUtils::getLinkID(rdh) + 2; //link=0,1,2 -> mod=2,3,4 // if(ddl != mDDL){ // LOG(ERROR) << "DDL from header "<< ddl << " != configured DDL=" << mDDL; // } - - o2::InteractionRecord currentIR(triggerBC, triggerOrbit); - std::shared_ptr> currentDigitContainer; - auto found = digitBuffer.find(currentIR); - if (found == digitBuffer.end()) { - currentDigitContainer = std::make_shared>(); - digitBuffer[currentIR] = currentDigitContainer; - } else { - currentDigitContainer = found->second; - } - // if (mod > o2::cpv::Geometry::kNMod) { //only 3 correct modules:2,3,4 LOG(ERROR) << "module=" << mod << "do not exist"; - mOutputHWErrors.emplace_back(6, mod, 0, 0, kHEADER_INVALID); //Add non-existing DDL as DDL 5 - continue; //skip STU mod + mOutputHWErrors.emplace_back(6, mod, 0, 0, kRDH_INVALID); //Add non-existing DDL as DDL 5 + continue; //skip STU mod } // use the altro decoder to decode the raw data, and extract the RCU trailer o2::cpv::RawDecoder decoder(rawreader); @@ -182,9 +165,24 @@ void RawToDigitConverterSpec::run(framework::ProcessingContext& ctx) //TODO: probably careful conversion of decoder errors to Fitter errors? mOutputHWErrors.emplace_back(mod, 1, 0, 0, err); //assign general header errors to non-existing FEE 16 } + + std::shared_ptr> currentDigitContainer; + o2::InteractionRecord currentIR(0, triggerOrbit); // Loop over all the channels - for (uint32_t adch : decoder.getDigits()) { - AddressCharge ac = {adch}; + for (std::pair adchbc : decoder.getDigits()) { + uint16_t triggerBC = adchbc.second; + if (triggerBC != currentIR.bc) { + currentIR.bc = triggerBC; + } + auto found = digitBuffer.find(currentIR); + if (found == digitBuffer.end()) { + currentDigitContainer = std::make_shared>(); + digitBuffer[currentIR] = currentDigitContainer; + } else { + currentDigitContainer = found->second; + } + + AddressCharge ac = {adchbc.first}; unsigned short absId = ac.Address; //if we deal with non-pedestal data? if (!mIsPedestalData) { //not a pedestal data From ec0e287d6fefd0ac6eb3bc7f0be98daefc9b4813 Mon Sep 17 00:00:00 2001 From: sevdokim Date: Wed, 5 May 2021 21:04:01 +0200 Subject: [PATCH 418/770] Renamed classes in DataFormatsCPV/RawFormats.h --- .../CPV/include/DataFormatsCPV/RawFormats.h | 120 +++++++++--------- .../src/CPVGainCalibDevice.cxx | 4 +- .../src/CPVPedestalCalibDevice.cxx | 4 +- .../include/CPVReconstruction/RawDecoder.h | 38 +++--- .../CPV/reconstruction/src/RawDecoder.cxx | 34 +++-- Detectors/CPV/simulation/src/RawWriter.cxx | 27 ++-- .../workflow/src/RawToDigitConverterSpec.cxx | 56 ++++---- 7 files changed, 148 insertions(+), 135 deletions(-) diff --git a/DataFormats/Detectors/CPV/include/DataFormatsCPV/RawFormats.h b/DataFormats/Detectors/CPV/include/DataFormatsCPV/RawFormats.h index 1e107c9df482d..335b7baf506ed 100644 --- a/DataFormats/Detectors/CPV/include/DataFormatsCPV/RawFormats.h +++ b/DataFormats/Detectors/CPV/include/DataFormatsCPV/RawFormats.h @@ -28,118 +28,118 @@ union PadWord { uint32_t address : 6; ///< Bits 12 - 17 : address (0..47) uint32_t gas : 3; ///< Bits 18 - 20 : gasiplex (1..10) uint32_t dil : 2; ///< Bits 21 - 22 : dilogic (1..24) - uint32_t zero : 1; ///< Bits 23 - 23 : zeroed + uint32_t zero : 1; ///< Bits 23 - 23 : control bit (0 -> pad word, 1 -> FEE control word) }; - char bytes[4]; + char mBytes[4]; }; -class cpvword +class CpvWord { public: - cpvword() = default; - cpvword(std::vector::const_iterator b, std::vector::const_iterator e) + CpvWord() = default; + CpvWord(std::vector::const_iterator b, std::vector::const_iterator e) { //Reading //resposibility of coller to esure that //array will not end while reading for (int i = 0; i < 16 && b != e; i++, b++) { - bytes[i] = *b; + mBytes[i] = *b; } } - ~cpvword() = default; + ~CpvWord() = default; bool isOK() const { - return (bytes[9] < static_cast(24)) && - (bytes[15] == 0) && (bytes[14] == 0) && (bytes[13] == 0) && (bytes[12] == 0) && (bytes[11] == 0) && (bytes[10] == 0); + return (mBytes[9] < static_cast(24)) && + (mBytes[15] == 0) && (mBytes[14] == 0) && (mBytes[13] == 0) && (mBytes[12] == 0) && (mBytes[11] == 0) && (mBytes[10] == 0); } - short ccId() const { return short(bytes[9]); } + short ccId() const { return short(mBytes[9]); } uint32_t cpvPadWord(int i) const { PadWord p = {0}; - p.bytes[0] = bytes[3 * i]; - p.bytes[1] = bytes[3 * i + 1]; - p.bytes[2] = bytes[3 * i + 2]; + p.mBytes[0] = mBytes[3 * i]; + p.mBytes[1] = mBytes[3 * i + 1]; + p.mBytes[2] = mBytes[3 * i + 2]; return p.mDataWord; } public: - unsigned char bytes[16] = {0}; + unsigned char mBytes[16] = {0}; }; -class cpvheader +class CpvHeader { public: - cpvheader() = default; - cpvheader(std::vector::const_iterator b, std::vector::const_iterator e) + CpvHeader() = default; + CpvHeader(std::vector::const_iterator b, std::vector::const_iterator e) { //reading header from file - for (int i = 0; i < 16 && b != e; i++, b++) { //read up to 16 bytes - bytes[i] = *b; + for (int i = 0; i < 16 && b != e; i++, b++) { //read up to 16 mBytes + mBytes[i] = *b; } } - cpvheader(InteractionRecord orbitBC, bool isNoDataExpected, bool isDataContinued) + CpvHeader(InteractionRecord orbitBC, bool isNoDataExpected, bool isDataContinued) { //writing header //header is 128-bit word. //|127-120|119-112|111-104|103-96|95-88 |87-80 |79-72|71-64|63-56|55-48|47-40|39-32|31-24|23-16|15-8 |7-0 | // byte15 byte14 byte13 byte12 byte11 byte10 byte9 byte8 byte7 byte6 byte5 byte4 byte3 byte2 byte1 byte0 //byte = |76543210| - bytes[0] = (0x010 & 0x0ff); //bits 11 - 0 trigger id (0x010 = physics trigger) - bytes[1] = ((0x010 & 0xf00) >> 8) //bits 11 - 0 trigger id (0x010 = physics trigger) - + 0b00100000 * isNoDataExpected + 0b0100000 * isDataContinued; //bit 13 (no data for this trigger) + bit 14 (payload continues from previous page) - bytes[2] = (orbitBC.bc & 0x00ff); //bits 27 - 16 bunch crossing - bytes[3] = (orbitBC.bc & 0x0f00) >> 8; //bits 27 - 16 bunch crossing - bytes[4] = (orbitBC.orbit & 0x000000ff); //bits 63 - 32 orbit - bytes[5] = (orbitBC.orbit & 0x0000ff00) >> 8; //bits 63 - 32 orbit - bytes[6] = (orbitBC.orbit & 0x00ff0000) >> 16; //bits 63 - 32 orbit - bytes[7] = (orbitBC.orbit & 0xff000000) >> 24; //bits 63 - 32 orbit - bytes[8] = 0x00; //bits 64-71 reserved - bytes[9] = 0xe0; //word ID of cpv header (bits 79 - 72) + mBytes[0] = (0x010 & 0x0ff); //bits 11 - 0 trigger id (0x010 = physics trigger) + mBytes[1] = ((0x010 & 0xf00) >> 8) //bits 11 - 0 trigger id (0x010 = physics trigger) + + 0b00100000 * isNoDataExpected + 0b0100000 * isDataContinued; //bit 13 (no data for this trigger) + bit 14 (payload continues from previous page) + mBytes[2] = (orbitBC.bc & 0x00ff); //bits 27 - 16 bunch crossing + mBytes[3] = (orbitBC.bc & 0x0f00) >> 8; //bits 27 - 16 bunch crossing + mBytes[4] = (orbitBC.orbit & 0x000000ff); //bits 63 - 32 orbit + mBytes[5] = (orbitBC.orbit & 0x0000ff00) >> 8; //bits 63 - 32 orbit + mBytes[6] = (orbitBC.orbit & 0x00ff0000) >> 16; //bits 63 - 32 orbit + mBytes[7] = (orbitBC.orbit & 0xff000000) >> 24; //bits 63 - 32 orbit + mBytes[8] = 0x00; //bits 64-71 reserved + mBytes[9] = 0xe0; //word ID of cpv header (bits 79 - 72) for (int i = 10; i < 16; i++) { - bytes[i] = 0; //bits 127-80 must be zeros + mBytes[i] = 0; //bits 127-80 must be zeros } } - ~cpvheader() = default; - bool isOK() const { return (bytes[9] == 0xe0) && (bytes[10] == 0) && (bytes[11] == 0) && (bytes[12] == 0) && (bytes[13] == 0) && (bytes[14] == 0) && (bytes[15] == 0); } - bool isNoDataExpected() const { return bytes[1] & 0b00100000; } - bool isDataContinued() const { return bytes[1] & 0b0100000; } - uint16_t bc() const { return bytes[2] + ((bytes[3] & 0x0f) << 8); } - uint32_t orbit() const { return bytes[4] + (bytes[5] << 8) + (bytes[6] << 16) + (bytes[7] << 24); } + ~CpvHeader() = default; + bool isOK() const { return (mBytes[9] == 0xe0) && (mBytes[10] == 0) && (mBytes[11] == 0) && (mBytes[12] == 0) && (mBytes[13] == 0) && (mBytes[14] == 0) && (mBytes[15] == 0); } + bool isNoDataExpected() const { return mBytes[1] & 0b00100000; } + bool isDataContinued() const { return mBytes[1] & 0b0100000; } + uint16_t bc() const { return mBytes[2] + ((mBytes[3] & 0x0f) << 8); } + uint32_t orbit() const { return mBytes[4] + (mBytes[5] << 8) + (mBytes[6] << 16) + (mBytes[7] << 24); } public: - unsigned char bytes[16] = {0}; //0 - 127 bits (16 bytes) + unsigned char mBytes[16] = {0}; //0 - 127 bits (16 bytes) }; -class cpvtrailer +class CpvTrailer { public: - cpvtrailer() = default; - cpvtrailer(std::vector::const_iterator b, std::vector::const_iterator e) + CpvTrailer() = default; + CpvTrailer(std::vector::const_iterator b, std::vector::const_iterator e) { //reading - for (int i = 0; i < 16 && b != e; i++, b++) { //read up to 16 bytes - bytes[i] = *b; + for (int i = 0; i < 16 && b != e; i++, b++) { //read up to 16 mBytes + mBytes[i] = *b; } } - cpvtrailer(unsigned short wordCounter, uint16_t bunchCrossing, bool isAllDataSent) - { //writing - bytes[0] = bunchCrossing & 0x00ff; //bits 11 - 0 bunch crossing - bytes[1] = ((bunchCrossing & 0x0f00) >> 8) //bits 11 - 0 bunch crossing - + ((wordCounter & 0x0f) << 4); //bits 20 - 12 wordCounter - bytes[2] = (wordCounter & 0b111110000) >> 4; //bits 20 - 12 wordCounter + CpvTrailer(unsigned short wordCounter, uint16_t bunchCrossing, bool isAllDataSent) + { //writing + mBytes[0] = bunchCrossing & 0x00ff; //bits 11 - 0 bunch crossing + mBytes[1] = ((bunchCrossing & 0x0f00) >> 8) //bits 11 - 0 bunch crossing + + ((wordCounter & 0x0f) << 4); //bits 20 - 12 wordCounter + mBytes[2] = (wordCounter & 0b111110000) >> 4; //bits 20 - 12 wordCounter for (int i = 3; i < 8; i++) { - bytes[i] = 0; //bits 70 - 21 reserved + mBytes[i] = 0; //bits 70 - 21 reserved } - bytes[8] = isAllDataSent * 0b10000000; //bit 71 all data is sent for current trigger - bytes[9] = char(0xf0); //word ID of cpv trailer + mBytes[8] = isAllDataSent * 0b10000000; //bit 71 all data is sent for current trigger + mBytes[9] = char(0xf0); //word ID of cpv trailer for (int i = 10; i < 16; i++) { - bytes[i] = 0; + mBytes[i] = 0; } } - ~cpvtrailer() = default; - bool isOK() const { return (bytes[9] == 0xf0) && (bytes[10] == 0) && (bytes[11] == 0) && (bytes[12] == 0) && (bytes[13] == 0) && (bytes[14] == 0) && (bytes[15] == 0); } - uint16_t wordCounter() const { return (bytes[1] >> 4) + ((bytes[2] & 0b00011111) << 4); } - bool isAllDataSent() const { return (bytes[8] & 0b10000000); } - uint16_t bc() const { return bytes[0] + ((bytes[1] & 0x0f) << 8); } + ~CpvTrailer() = default; + bool isOK() const { return (mBytes[9] == 0xf0) && (mBytes[10] == 0) && (mBytes[11] == 0) && (mBytes[12] == 0) && (mBytes[13] == 0) && (mBytes[14] == 0) && (mBytes[15] == 0); } + uint16_t wordCounter() const { return (mBytes[1] >> 4) + ((mBytes[2] & 0b00011111) << 4); } + bool isAllDataSent() const { return (mBytes[8] & 0b10000000); } + uint16_t bc() const { return mBytes[0] + ((mBytes[1] & 0x0f) << 8); } public: - unsigned char bytes[16] = {0}; + unsigned char mBytes[16] = {0}; }; } // namespace cpv diff --git a/Detectors/CPV/calib/CPVCalibWorkflow/src/CPVGainCalibDevice.cxx b/Detectors/CPV/calib/CPVCalibWorkflow/src/CPVGainCalibDevice.cxx index 2e347f99bd1b9..84982d81bb5cc 100644 --- a/Detectors/CPV/calib/CPVCalibWorkflow/src/CPVGainCalibDevice.cxx +++ b/Detectors/CPV/calib/CPVCalibWorkflow/src/CPVGainCalibDevice.cxx @@ -76,8 +76,8 @@ void CPVGainCalibDevice::run(o2::framework::ProcessingContext& ctx) continue; } // Loop over all the channels - for (std::pair adchbc : decoder.getDigits()) { - AddressCharge ac = {adchbc.first}; + for (auto adch : decoder.getDigits()) { + AddressCharge ac = {adch}; unsigned short absId = ac.Address; mMean->Fill(absId, ac.Charge); } diff --git a/Detectors/CPV/calib/CPVCalibWorkflow/src/CPVPedestalCalibDevice.cxx b/Detectors/CPV/calib/CPVCalibWorkflow/src/CPVPedestalCalibDevice.cxx index d6e23ed027e13..84acb59ed37e1 100644 --- a/Detectors/CPV/calib/CPVCalibWorkflow/src/CPVPedestalCalibDevice.cxx +++ b/Detectors/CPV/calib/CPVCalibWorkflow/src/CPVPedestalCalibDevice.cxx @@ -68,8 +68,8 @@ void CPVPedestalCalibDevice::run(o2::framework::ProcessingContext& ctx) continue; } // Loop over all the channels - for (std::pair adchbc : decoder.getDigits()) { - AddressCharge ac = {adchbc.first}; + for (auto adch : decoder.getDigits()) { + AddressCharge ac = {adch}; unsigned short absId = ac.Address; mMean->Fill(absId, ac.Charge); } diff --git a/Detectors/CPV/reconstruction/include/CPVReconstruction/RawDecoder.h b/Detectors/CPV/reconstruction/include/CPVReconstruction/RawDecoder.h index 2c3a0e600fb03..ac4c4a1416d4e 100644 --- a/Detectors/CPV/reconstruction/include/CPVReconstruction/RawDecoder.h +++ b/Detectors/CPV/reconstruction/include/CPVReconstruction/RawDecoder.h @@ -47,6 +47,15 @@ union AddressCharge { }; }; +/// BC reference to digits +struct BCRecord { + BCRecord() = default; + BCRecord(uint16_t bunchCrossing, unsigned int first, unsigned int last) : bc(bunchCrossing), firstDigit(first), lastDigit(last) {} + uint16_t bc; + unsigned int firstDigit; + unsigned int lastDigit; +}; + /// \class RawDecoder /// \brief Decoder of the ALTRO data in the raw page /// \ingroup CPVreconstruction @@ -55,9 +64,7 @@ union AddressCharge { /// /// This is a base class for reading raw data digits. /// It takes raw cpv payload from RawReaderMemory and produces -/// std::vector> mDigits -/// mDigits[i].first is AddressCharge word and -/// mDigits[i].second is bc number in current HBF +/// std::vector mDigits and std::vector mBCRecords class RawDecoder { @@ -76,15 +83,16 @@ class RawDecoder /// cpvwords and cpvtrailer. /// After successfull decoding the Decoder can provide /// a reference to a vector - /// with the decoded chanenels, each containing - /// its BC numbers. + /// with the decoded chanenels and their bc reference RawErrorType_t decode(); /// \brief Get the reference to the digits container /// \return Reference to the digits container - const std::vector>& getDigits() const; + const std::vector& getDigits() const { return mDigits; }; - /// \brief Get the reference to the BC + /// \brief Get the reference to the BC records + /// \return reference to the BC records + const std::vector& getBCRecords() const { return mBCRecords; }; /// \brief Get the reference to the list of decoding errors /// \return Reference to the list of decoding errors @@ -95,20 +103,14 @@ class RawDecoder RawErrorType_t readChannels(); private: - /// \brief run checks on the RCU trailer - /// \throw Error if the RCU trailer has inconsistencies - /// - /// Performing various consistency checks on the RCU trailer - /// In case of failure an exception is thrown. - //void checkRCUTrailer(); - void addDigit(uint32_t padWord, short ddl, uint16_t bc); void removeLastNDigits(int n); - RawReaderMemory& mRawReader; ///< underlying raw reader - std::vector> mDigits; ///< vector of channels and BCs in the raw stream - std::vector mErrors; ///< vector of decoding errors - bool mChannelsInitialized = false; ///< check whether the channels are initialized + RawReaderMemory& mRawReader; ///< underlying raw reader + std::vector mDigits; ///< vector of channels and BCs in the raw stream + std::vector mBCRecords; ///< vector of bc references to digits + std::vector mErrors; ///< vector of decoding errors + bool mChannelsInitialized = false; ///< check whether the channels are initialized ClassDefNV(RawDecoder, 2); }; diff --git a/Detectors/CPV/reconstruction/src/RawDecoder.cxx b/Detectors/CPV/reconstruction/src/RawDecoder.cxx index b3aa49a4466a6..998ed5053f8fb 100644 --- a/Detectors/CPV/reconstruction/src/RawDecoder.cxx +++ b/Detectors/CPV/reconstruction/src/RawDecoder.cxx @@ -28,6 +28,7 @@ RawErrorType_t RawDecoder::decode() auto& rdh = mRawReader.getRawHeader(); short linkID = o2::raw::RDHUtils::getLinkID(rdh); mDigits.clear(); + mBCRecords.clear(); auto payloadWords = mRawReader.getPayload(); if (payloadWords.size() == 0) { @@ -51,7 +52,7 @@ RawErrorType_t RawDecoder::readChannels() auto b = payloadWords.cbegin(); auto e = payloadWords.cend(); while (b != e) { //payload must start with cpvheader folowed by cpvwords and finished with cpvtrailer - cpvheader header(b, e); + CpvHeader header(b, e); if (header.isOK()) { if (!isHeaderExpected) { //actually, header was not expected LOG(ERROR) << "RawDecoder::readChannels() : " @@ -74,7 +75,7 @@ RawErrorType_t RawDecoder::readChannels() b += 16; continue; //continue while'ing until it's not header } - cpvword word(b, e); + CpvWord word(b, e); if (word.isOK()) { wordCountFromLastHeader++; for (int i = 0; i < 3; i++) { @@ -85,7 +86,7 @@ RawErrorType_t RawDecoder::readChannels() } } } else { //this may be trailer - cpvtrailer trailer(b, e); + CpvTrailer trailer(b, e); if (trailer.isOK()) { int diffInCount = wordCountFromLastHeader - trailer.wordCounter(); if (diffInCount > 1 || @@ -123,16 +124,16 @@ RawErrorType_t RawDecoder::readChannels() return kOK; } -const std::vector>& RawDecoder::getDigits() const -{ - /*if (!mChannelsInitialized) { - LOG(ERROR) << "RawDecoder::getDigits() : Channels not initialized"; - }*/ - return mDigits; -} - void RawDecoder::addDigit(uint32_t w, short ccId, uint16_t bc) { + //new bc -> add bc reference + if (mBCRecords.empty() || (mBCRecords.back().bc != bc)) { + mBCRecords.push_back(BCRecord(bc, mDigits.size(), mDigits.size())); + } else { + mBCRecords.back().lastDigit++; + } + + //add digit PadWord pad = {w}; unsigned short absId; o2::cpv::Geometry::hwaddressToAbsId(ccId, pad.dil, pad.gas, pad.address, absId); @@ -140,18 +141,23 @@ void RawDecoder::addDigit(uint32_t w, short ccId, uint16_t bc) AddressCharge ac = {0}; ac.Address = absId; ac.Charge = pad.charge; - //std::pair digitAndBC - mDigits.push_back(std::pair(ac.mDataWord, bc)); + mDigits.push_back(ac.mDataWord); } void RawDecoder::removeLastNDigits(int n) { - if (n < 0) + if (n < 0) { return; + } int nRemoved = 0; while (nRemoved < n) { if (mDigits.size() > 0) { // still has digits to remove mDigits.pop_back(); + if (mBCRecords.back().lastDigit == mBCRecords.back().firstDigit) { + mBCRecords.pop_back(); + } else { + mBCRecords.back().lastDigit--; + } nRemoved++; } else { // has nothing to remove already break; diff --git a/Detectors/CPV/simulation/src/RawWriter.cxx b/Detectors/CPV/simulation/src/RawWriter.cxx index 2801a17ca8ec5..c632eb795abcb 100644 --- a/Detectors/CPV/simulation/src/RawWriter.cxx +++ b/Detectors/CPV/simulation/src/RawWriter.cxx @@ -154,9 +154,9 @@ bool RawWriter::processOrbit(const gsl::span digitsbranch, const } //first, header goes - cpvheader header(trg.getBCData(), false, false); + CpvHeader header(trg.getBCData(), false, false); for (int i = 0; i < 16; i++) { - mPayload.push_back(header.bytes[i]); + mPayload.push_back(header.mBytes[i]); } gbtWordCounter++; gbtWordCounterBeforeCPVTrailer++; @@ -172,9 +172,9 @@ bool RawWriter::processOrbit(const gsl::span digitsbranch, const currentword.address = pc.pad; currentword.gas = gas; currentword.dil = dil; - mPayload.push_back(currentword.bytes[0]); - mPayload.push_back(currentword.bytes[1]); - mPayload.push_back(currentword.bytes[2]); + mPayload.push_back(currentword.mBytes[0]); + mPayload.push_back(currentword.mBytes[1]); + mPayload.push_back(currentword.mBytes[2]); ccWordCounter++; if (ccWordCounter % 3 == 0) { // complete 3 channels (72 bit) + CC index (8 bits) + 6 empty bits = Generate 128 bits of data mPayload.push_back(ccId); @@ -184,9 +184,9 @@ bool RawWriter::processOrbit(const gsl::span digitsbranch, const gbtWordCounter++; gbtWordCounterBeforeCPVTrailer++; if (nMaxGbtWordsPerPage - gbtWordCounter < 2) { //the only space for trailer left on current page - cpvtrailer tr(gbtWordCounterBeforeCPVTrailer, trg.getBCData().bc, true); //add trailer and flush page to file + CpvTrailer tr(gbtWordCounterBeforeCPVTrailer, trg.getBCData().bc, true); //add trailer and flush page to file for (int i = 0; i < 16; i++) { - mPayload.push_back(tr.bytes[i]); + mPayload.push_back(tr.mBytes[i]); } LOG(DEBUG) << "RawWriter::processOrbit() : middle of payload: adding preformatted dma page of size " << mPayload.size(); mRawWriter->addData(feeid, cru, link, endpoint, trg.getBCData(), gsl::span(mPayload.data(), mPayload.size()), preformatted); @@ -195,7 +195,7 @@ bool RawWriter::processOrbit(const gsl::span digitsbranch, const gbtWordCounterBeforeCPVTrailer = 0; if (nDigsInTrg > gbtWordCounterBeforeCPVTrailer - 1) { //some digits left for writing for (int i = 0; i < 16; i++) { //so put a new header and continue - mPayload.push_back(header.bytes[i]); + mPayload.push_back(header.mBytes[i]); } gbtWordCounter++; gbtWordCounterBeforeCPVTrailer++; @@ -217,9 +217,9 @@ bool RawWriter::processOrbit(const gsl::span digitsbranch, const gbtWordCounter++; gbtWordCounterBeforeCPVTrailer++; if (nMaxGbtWordsPerPage - gbtWordCounter < 2) { //the only space for trailer left on current page - cpvtrailer tr(gbtWordCounterBeforeCPVTrailer, trg.getBCData().bc, true); //add trailer and flush page to file + CpvTrailer tr(gbtWordCounterBeforeCPVTrailer, trg.getBCData().bc, true); //add trailer and flush page to file for (int i = 0; i < 16; i++) { - mPayload.push_back(tr.bytes[i]); + mPayload.push_back(tr.mBytes[i]); } LOG(DEBUG) << "RawWriter::processOrbit() : middle of payload (after filling empty words): adding preformatted dma page of size " << mPayload.size(); mRawWriter->addData(feeid, cru, link, endpoint, trg.getBCData(), gsl::span(mPayload.data(), mPayload.size()), preformatted); @@ -228,7 +228,7 @@ bool RawWriter::processOrbit(const gsl::span digitsbranch, const gbtWordCounterBeforeCPVTrailer = 0; if (nDigsInTrg > gbtWordCounterBeforeCPVTrailer - 1) { //some digits left for writing for (int i = 0; i < 16; i++) { //so put a new header and continue - mPayload.push_back(header.bytes[i]); + mPayload.push_back(header.mBytes[i]); } gbtWordCounter++; gbtWordCounterBeforeCPVTrailer++; @@ -238,9 +238,9 @@ bool RawWriter::processOrbit(const gsl::span digitsbranch, const } } } - cpvtrailer tr(gbtWordCounterBeforeCPVTrailer, trg.getBCData().bc, true); //cout GBT words + CpvTrailer tr(gbtWordCounterBeforeCPVTrailer, trg.getBCData().bc, true); //cout GBT words for (int i = 0; i < 16; i++) { - mPayload.push_back(tr.bytes[i]); + mPayload.push_back(tr.mBytes[i]); } gbtWordCounterBeforeCPVTrailer++; gbtWordCounter++; @@ -252,6 +252,7 @@ bool RawWriter::processOrbit(const gsl::span digitsbranch, const } return true; } +//carryover method is not used as we write preformatted pages int RawWriter::carryOverMethod(const header::RDHAny* rdh, const gsl::span data, const char* ptr, int maxSize, int splitID, std::vector& trailer, std::vector& header) const diff --git a/Detectors/CPV/workflow/src/RawToDigitConverterSpec.cxx b/Detectors/CPV/workflow/src/RawToDigitConverterSpec.cxx index 8c9cd27e7904a..381cfcaabba42 100644 --- a/Detectors/CPV/workflow/src/RawToDigitConverterSpec.cxx +++ b/Detectors/CPV/workflow/src/RawToDigitConverterSpec.cxx @@ -167,35 +167,39 @@ void RawToDigitConverterSpec::run(framework::ProcessingContext& ctx) } std::shared_ptr> currentDigitContainer; - o2::InteractionRecord currentIR(0, triggerOrbit); - // Loop over all the channels - for (std::pair adchbc : decoder.getDigits()) { - uint16_t triggerBC = adchbc.second; - if (triggerBC != currentIR.bc) { - currentIR.bc = triggerBC; - } - auto found = digitBuffer.find(currentIR); - if (found == digitBuffer.end()) { - currentDigitContainer = std::make_shared>(); - digitBuffer[currentIR] = currentDigitContainer; - } else { - currentDigitContainer = found->second; - } + auto digilets = decoder.getDigits(); + if (digilets.empty()) { //no digits -> continue to next pages + continue; + } + o2::InteractionRecord currentIR(0, triggerOrbit); //(bc, orbit) + // Loop over all the BCs + for (auto itBCRecords : decoder.getBCRecords()) { + currentIR.bc = itBCRecords.bc; + for (int iDig = itBCRecords.firstDigit; iDig <= itBCRecords.lastDigit; iDig++) { + auto adch = digilets[iDig]; + auto found = digitBuffer.find(currentIR); + if (found == digitBuffer.end()) { + currentDigitContainer = std::make_shared>(); + digitBuffer[currentIR] = currentDigitContainer; + } else { + currentDigitContainer = found->second; + } - AddressCharge ac = {adchbc.first}; - unsigned short absId = ac.Address; - //if we deal with non-pedestal data? - if (!mIsPedestalData) { //not a pedestal data - //test bad map - if (mBadMap->isChannelGood(absId)) { - //we need to subtract pedestal from amplidute and calibrate it - float amp = mCalibParams->getGain(absId) * (ac.Charge - mPedestals->getPedestal(absId)); - if (amp > 0) { - currentDigitContainer->emplace_back(absId, amp, -1); + AddressCharge ac = {adch}; + unsigned short absId = ac.Address; + //if we deal with non-pedestal data? + if (!mIsPedestalData) { //not a pedestal data + //test bad map + if (mBadMap->isChannelGood(absId)) { + //we need to subtract pedestal from amplidute and calibrate it + float amp = mCalibParams->getGain(absId) * (ac.Charge - mPedestals->getPedestal(absId)); + if (amp > 0) { + currentDigitContainer->emplace_back(absId, amp, -1); + } } + } else { //pedestal data, no calibration needed. + currentDigitContainer->emplace_back(absId, (float)ac.Charge, -1); } - } else { //pedestal data, no calibration needed. - currentDigitContainer->emplace_back(absId, (float)ac.Charge, -1); } } //Check and send list of hwErrors From 31f404f651fa5ad57a1631f53c6a29c08f7249bb Mon Sep 17 00:00:00 2001 From: Sandro Wenzel Date: Thu, 6 May 2021 13:03:49 +0200 Subject: [PATCH 419/770] digitization: Add option to disable config writing In cases, in which we digitize in stages (multiple invocations), only one of the digitizers should really write the configuration file for later stages. --- Steer/DigitizerWorkflow/src/SimpleDigitizerWorkflow.cxx | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Steer/DigitizerWorkflow/src/SimpleDigitizerWorkflow.cxx b/Steer/DigitizerWorkflow/src/SimpleDigitizerWorkflow.cxx index 8519a83c09558..ccf2b259c5c06 100644 --- a/Steer/DigitizerWorkflow/src/SimpleDigitizerWorkflow.cxx +++ b/Steer/DigitizerWorkflow/src/SimpleDigitizerWorkflow.cxx @@ -170,6 +170,9 @@ void customize(std::vector& workflowOptions) // option to disable MC truth workflowOptions.push_back(ConfigParamSpec{"disable-mc", o2::framework::VariantType::Bool, false, {"disable mc-truth"}}); + // option to disable INI file writing + workflowOptions.push_back(ConfigParamSpec{"disable-write-ini", o2::framework::VariantType::Bool, false, {"disable INI config write"}}); + // option to use/not use CCDB for TOF workflowOptions.push_back(ConfigParamSpec{"use-ccdb-tof", o2::framework::VariantType::Bool, false, {"enable access to ccdb tof calibration objects"}}); @@ -392,8 +395,12 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) ConfigurableParam::setValue("DigiParams", "mctruth", mctruth); // write the configuration used for the digitizer workflow + // (In the case, in which we call multiple processes to do digitization, + // only one of them should write this file ... but take the complete configKeyValue line) if (ismaster) { - o2::conf::ConfigurableParam::writeINI(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)); + if (!configcontext.options().get("disable-write-ini")) { + o2::conf::ConfigurableParam::writeINI(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)); + } } // onlyDet takes precedence on skipDet From d80638ec3c6c15bf9e7724c9879f17f599fd2113 Mon Sep 17 00:00:00 2001 From: Sandro Wenzel Date: Thu, 6 May 2021 13:06:53 +0200 Subject: [PATCH 420/770] GRPWriter: Use semaphore only when asked --- .../DigitizerWorkflow/src/GRPUpdaterSpec.cxx | 32 +++++++++++++++---- 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/Steer/DigitizerWorkflow/src/GRPUpdaterSpec.cxx b/Steer/DigitizerWorkflow/src/GRPUpdaterSpec.cxx index cfbd43e31e458..e18803c25e778 100644 --- a/Steer/DigitizerWorkflow/src/GRPUpdaterSpec.cxx +++ b/Steer/DigitizerWorkflow/src/GRPUpdaterSpec.cxx @@ -57,16 +57,36 @@ class GRPDPLUpdatedTask const std::string grpName = "GRP"; // a standardized semaphore convention --> taking the current execution path should be enough - const auto semname = boost::filesystem::current_path().string() + mGRPFileName; - std::hash hasher; - const auto semhashedstring = "alice_grp_" + std::to_string(hasher(semname)); + // (the user enables this via O2_USEGRP_SEMA environment) + bool use_sema = false; + boost::interprocess::named_semaphore* sem = nullptr; + if (auto semaname = getenv("O2_USEGRP_SEMA")) { + try { + const auto semname = boost::filesystem::current_path().string() + mGRPFileName; + std::hash hasher; + const auto semhashedstring = "alice_grp_" + std::to_string(hasher(semname)); + sem = new boost::interprocess::named_semaphore(boost::interprocess::open_or_create_t{}, semhashedstring.c_str(), 1); + } catch (std::exception e) { + LOG(WARN) << "Exception occurred during GRP semaphore setup; Continuing without"; + sem = nullptr; + } + } try { - boost::interprocess::named_semaphore sem(boost::interprocess::open_or_create_t{}, semhashedstring.c_str(), 1); - sem.wait(); // wait until we can enter (no one else there) + if (sem) { + sem->wait(); // wait until we can enter (no one else there) + } + + auto postSem = [sem] { + if (sem) { + sem->post(); + delete sem; + } + }; TFile flGRP(mGRPFileName.c_str(), "update"); if (flGRP.IsZombie()) { LOG(ERROR) << "Failed to open in update mode " << mGRPFileName; + postSem(); return; } std::unique_ptr grp(static_cast(flGRP.GetObjectChecked(grpName.c_str(), GRP::Class()))); @@ -85,7 +105,7 @@ class GRPDPLUpdatedTask flGRP.WriteObjectAny(grp.get(), grp->Class(), grpName.c_str()); flGRP.Close(); - sem.post(); // here we are done; put to green for others waiting + postSem(); } catch (boost::interprocess::interprocess_exception e) { LOG(ERROR) << "Caught semaphore exception " << e.what(); } From a0ab150317d29e8b0cfa6609e924ce6f3203381d Mon Sep 17 00:00:00 2001 From: Andreas Morsch Date: Tue, 4 May 2021 19:17:46 +0200 Subject: [PATCH 421/770] fluka input data filename corrected --- Detectors/gconfig/src/FlukaConfig.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Detectors/gconfig/src/FlukaConfig.cxx b/Detectors/gconfig/src/FlukaConfig.cxx index a2f329fd4e3fc..cac933c5f35ad 100644 --- a/Detectors/gconfig/src/FlukaConfig.cxx +++ b/Detectors/gconfig/src/FlukaConfig.cxx @@ -40,7 +40,7 @@ void linkFlukaFiles() gSystem->Exec("ln -s $FLUKADATA/fluodt.dat ."); gSystem->Exec("ln -s $FLUKADATA/random.dat ."); gSystem->Exec("ln -s $FLUKADATA/dnr.dat ."); - gSystem->Exec("ln -s $FLUKADATA/nunstab.dat ."); + gSystem->Exec("ln -s $FLUKADATA/nunstab.data ."); // Give some meaningfull name to the output gSystem->Exec("ln -s fluka.out fort.11"); gSystem->Exec("ln -s fluka.err fort.15"); From 2899cb679f02d1af40497f31a70b3b18e2e11473 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 6 May 2021 23:59:42 +0200 Subject: [PATCH 422/770] Use new clang version, enable more OpenCL extensions, revert workarounds (#6086) * GPU: Clang has renamed the OpenCL extension name compared to the fix in the bug report * GPU: This OpenCL option is no longer needed since it defaults to true in clang * GPU: Do not include default OpenCL headers when only preprocessing (leads to double-include later) * GPU: Use clang OpenCL extension for bitfields * GPU: add some more type_trait functionality to GPUCommonTypeTraits * GPU: Use RDHUtils also with C++4OpenCL * GPU: Drop now obsolete GPURawData.h --- Detectors/Raw/include/DetectorsRaw/RDHUtils.h | 7 +- Detectors/TPC/workflow/src/ZSSpec.cxx | 4 +- .../TPC/workflow/src/convertDigitsToRawZS.cxx | 4 +- GPU/Common/GPUCommonTypeTraits.h | 50 +++++++++++ .../Base/GPUReconstructionConvert.cxx | 30 +++---- .../opencl-common/GPUReconstructionOCL.cl | 7 +- GPU/GPUTracking/Base/opencl2/CMakeLists.txt | 4 +- GPU/GPUTracking/CMakeLists.txt | 1 - GPU/GPUTracking/DataTypes/GPURawData.h | 82 ------------------- .../Global/GPUChainTrackingClusterizer.cxx | 23 +++--- GPU/GPUTracking/Standalone/tools/testCL.sh | 6 +- .../TPCClusterFinder/GPUTPCCFDecodeZS.cxx | 10 +-- 12 files changed, 98 insertions(+), 130 deletions(-) delete mode 100644 GPU/GPUTracking/DataTypes/GPURawData.h diff --git a/Detectors/Raw/include/DetectorsRaw/RDHUtils.h b/Detectors/Raw/include/DetectorsRaw/RDHUtils.h index 181ce7c5aca5c..6636d625c4737 100644 --- a/Detectors/Raw/include/DetectorsRaw/RDHUtils.h +++ b/Detectors/Raw/include/DetectorsRaw/RDHUtils.h @@ -18,7 +18,7 @@ #include "GPUCommonRtypes.h" #include "Headers/RAWDataHeader.h" #include "Headers/RDHAny.h" - +#include "GPUCommonTypeTraits.h" #if !defined(GPUCA_GPUCODE) #include "CommonDataFormat/InteractionRecord.h" #endif @@ -35,7 +35,7 @@ using LinkSubSpec_t = uint32_t; struct RDHUtils { // disable is the type is a pointer -#define NOTPTR(T) typename std::enable_if::value>::type* = 0 +#define NOTPTR(T) typename std::enable_if::value>::type* = 0 // dereference SRC pointer as DST type reference #define TOREF(DST, SRC) *reinterpret_cast(SRC) // dereference SRC pointer as DST type const reference @@ -692,7 +692,8 @@ struct RDHUtils { private: static uint32_t fletcher32(const uint16_t* data, int len); #if defined(GPUCA_GPUCODE_DEVICE) || defined(GPUCA_STANDALONE) - GPUhdi() static void processError(int v, const char* field) + template + GPUhdi() static void processError(int v, const T* field) { } #else diff --git a/Detectors/TPC/workflow/src/ZSSpec.cxx b/Detectors/TPC/workflow/src/ZSSpec.cxx index 14afe6e458732..9634bf7bb21b2 100644 --- a/Detectors/TPC/workflow/src/ZSSpec.cxx +++ b/Detectors/TPC/workflow/src/ZSSpec.cxx @@ -34,7 +34,6 @@ #include #include "GPUParam.h" #include "GPUReconstructionConvert.h" -#include "GPURawData.h" #include "DetectorsRaw/RawFileWriter.h" #include "DetectorsRaw/HBFUtils.h" #include "DetectorsRaw/RDHUtils.h" @@ -44,6 +43,7 @@ #include "DataFormatsParameters/GRPObject.h" #include "DetectorsCommonDataFormats/NameConf.h" #include "DataFormatsTPC/WorkflowHelper.h" +#include "DetectorsRaw/RDHUtils.h" using namespace o2::framework; using namespace o2::header; @@ -124,7 +124,7 @@ DataProcessorSpec getZSEncoderSpec(std::vector const& tpcSectors, bool outR const auto grp = o2::parameters::GRPObject::loadFrom(inputGRP); o2::raw::RawFileWriter writer{"TPC"}; // to set the RDHv6.sourceID if V6 is used writer.setContinuousReadout(grp->isDetContinuousReadOut(o2::detectors::DetID::TPC)); // must be set explicitly - uint32_t rdhV = o2::raw::RDHUtils::getVersion(); + uint32_t rdhV = o2::raw::RDHUtils::getVersion(); writer.useRDHVersion(rdhV); std::string outDir = "./"; const unsigned int defaultLink = rdh_utils::UserLogicLinkID; diff --git a/Detectors/TPC/workflow/src/convertDigitsToRawZS.cxx b/Detectors/TPC/workflow/src/convertDigitsToRawZS.cxx index cb299b8fd55a0..e2649ccb5d119 100644 --- a/Detectors/TPC/workflow/src/convertDigitsToRawZS.cxx +++ b/Detectors/TPC/workflow/src/convertDigitsToRawZS.cxx @@ -27,7 +27,6 @@ #include "GPUReconstructionConvert.h" #include "GPUHostDataTypes.h" #include "GPUParam.h" -#include "GPURawData.h" #include "Framework/Logger.h" #include "DetectorsRaw/RawFileWriter.h" @@ -43,6 +42,7 @@ #include "CommonUtils/ConfigurableParam.h" #include "DataFormatsParameters/GRPObject.h" #include "DetectorsCommonDataFormats/NameConf.h" +#include "DetectorsRaw/RDHUtils.h" namespace bpo = boost::program_options; @@ -226,7 +226,7 @@ int main(int argc, char** argv) add_option("file-for,f", bpo::value()->default_value("sector"), "single file per: link,sector,all"); add_option("stop-page,p", bpo::value()->default_value(false)->implicit_value(true), "HBF stop on separate CRU page"); add_option("no-padding", bpo::value()->default_value(false)->implicit_value(true), "Don't pad pages to 8kb"); - uint32_t defRDH = o2::raw::RDHUtils::getVersion(); + uint32_t defRDH = o2::raw::RDHUtils::getVersion(); add_option("hbfutils-config,u", bpo::value()->default_value(std::string(o2::base::NameConf::DIGITIZATIONCONFIGFILE)), "config file for HBFUtils (or none)"); add_option("rdh-version,r", bpo::value()->default_value(defRDH), "RDH version to use"); add_option("configKeyValues", bpo::value()->default_value(""), "comma-separated configKeyValues"); diff --git a/GPU/Common/GPUCommonTypeTraits.h b/GPU/Common/GPUCommonTypeTraits.h index 2c34e9e2d8e95..93f7dcb73185c 100644 --- a/GPU/Common/GPUCommonTypeTraits.h +++ b/GPU/Common/GPUCommonTypeTraits.h @@ -40,6 +40,56 @@ struct is_same { }; template static constexpr bool is_same_v = is_same::value; +template +struct enable_if { +}; +template +struct enable_if { + typedef T type; +}; +template +struct remove_cv { + typedef T type; +}; +template +struct remove_cv { + typedef T type; +}; +template +struct remove_cv { + typedef T type; +}; +template +struct remove_cv { + typedef T type; +}; +template +struct remove_const { + typedef T type; +}; +template +struct remove_const { + typedef T type; +}; +template +struct remove_volatile { + typedef T type; +}; +template +struct remove_volatile { + typedef T type; +}; +template +struct is_pointer_t { + static constexpr bool value = false; +}; +template +struct is_pointer_t { + static constexpr bool value = true; +}; +template +struct is_pointer : is_pointer_t::type> { +}; } // namespace std #endif diff --git a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx index 65ae3019e41d0..d7bdf38b67f60 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx @@ -31,10 +31,10 @@ #include "clusterFinderDefs.h" #include "DataFormatsTPC/ZeroSuppression.h" #include "DataFormatsTPC/Constants.h" -#include "GPURawData.h" #include "CommonConstants/LHCConstants.h" #include "DataFormatsTPC/Digit.h" #include "TPCBase/RDHUtils.h" +#include "DetectorsRaw/RDHUtils.h" #endif using namespace GPUCA_NAMESPACE::gpu; @@ -153,13 +153,13 @@ int GPUReconstructionConvert::GetMaxTimeBin(const GPUTrackingInOutZS& zspages) #ifdef HAVE_O2HEADERS float retVal = 0; for (unsigned int i = 0; i < NSLICES; i++) { - int firstHBF = zspages.slice[i].count[0] ? o2::raw::RDHUtils::getHeartBeatOrbit(*(const RAWDataHeaderGPU*)zspages.slice[i].zsPtr[0][0]) : 0; + int firstHBF = zspages.slice[i].count[0] ? o2::raw::RDHUtils::getHeartBeatOrbit(*(const o2::header::RAWDataHeader*)zspages.slice[i].zsPtr[0][0]) : 0; for (unsigned int j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) { for (unsigned int k = 0; k < zspages.slice[i].count[j]; k++) { const char* page = (const char*)zspages.slice[i].zsPtr[j][k]; for (unsigned int l = 0; l < zspages.slice[i].nZSPtr[j][k]; l++) { - RAWDataHeaderGPU* rdh = (RAWDataHeaderGPU*)(page + l * TPCZSHDR::TPC_ZS_PAGE_SIZE); - TPCZSHDR* hdr = (TPCZSHDR*)(page + l * TPCZSHDR::TPC_ZS_PAGE_SIZE + sizeof(RAWDataHeaderGPU)); + o2::header::RAWDataHeader* rdh = (o2::header::RAWDataHeader*)(page + l * TPCZSHDR::TPC_ZS_PAGE_SIZE); + TPCZSHDR* hdr = (TPCZSHDR*)(page + l * TPCZSHDR::TPC_ZS_PAGE_SIZE + sizeof(o2::header::RAWDataHeader)); unsigned int timeBin = (hdr->timeOffset + (o2::raw::RDHUtils::getHeartBeatOrbit(*rdh) - firstHBF) * o2::constants::lhc::LHCMaxBunches) / LHCBCPERTIMEBIN + hdr->nTimeBins; if (timeBin > retVal) { retVal = timeBin; @@ -196,11 +196,11 @@ void GPUReconstructionConvert::ZSstreamOut(unsigned short* bufIn, unsigned int& #ifdef HAVE_O2HEADERS void GPUReconstructionConvert::ZSfillEmpty(void* ptr, int shift, unsigned int feeId, int orbit) { - RAWDataHeaderGPU* rdh = (RAWDataHeaderGPU*)ptr; + o2::header::RAWDataHeader* rdh = (o2::header::RAWDataHeader*)ptr; o2::raw::RDHUtils::setHeartBeatOrbit(*rdh, orbit); o2::raw::RDHUtils::setHeartBeatBC(*rdh, shift); - o2::raw::RDHUtils::setMemorySize(*rdh, sizeof(RAWDataHeaderGPU)); - o2::raw::RDHUtils::setVersion(*rdh, o2::raw::RDHUtils::getVersion()); + o2::raw::RDHUtils::setMemorySize(*rdh, sizeof(o2::header::RAWDataHeader)); + o2::raw::RDHUtils::setVersion(*rdh, o2::raw::RDHUtils::getVersion()); o2::raw::RDHUtils::setFEEID(*rdh, feeId); } @@ -355,15 +355,15 @@ void GPUReconstructionConvert::RunZSEncoder(const S& in, std::unique_ptr(size); - raw->addData(rawfeeid, rawcru, rawlnk, rawendpoint, *ir + (hbf - orbitShift) * o2::constants::lhc::LHCMaxBunches, gsl::span((char*)page + sizeof(RAWDataHeaderGPU), (char*)page + size), true); + raw->addData(rawfeeid, rawcru, rawlnk, rawendpoint, *ir + (hbf - orbitShift) * o2::constants::lhc::LHCMaxBunches, gsl::span((char*)page + sizeof(o2::header::RAWDataHeader), (char*)page + size), true); } else #endif { - RAWDataHeaderGPU* rdh = (RAWDataHeaderGPU*)page; + o2::header::RAWDataHeader* rdh = (o2::header::RAWDataHeader*)page; o2::raw::RDHUtils::setHeartBeatOrbit(*rdh, hbf); o2::raw::RDHUtils::setHeartBeatBC(*rdh, bcShiftInFirstHBF); o2::raw::RDHUtils::setMemorySize(*rdh, TPCZSHDR::TPC_ZS_PAGE_SIZE); - o2::raw::RDHUtils::setVersion(*rdh, o2::raw::RDHUtils::getVersion()); + o2::raw::RDHUtils::setVersion(*rdh, o2::raw::RDHUtils::getVersion()); o2::raw::RDHUtils::setFEEID(*rdh, rawfeeid); } } @@ -387,7 +387,7 @@ void GPUReconstructionConvert::RunZSEncoder(const S& in, std::unique_ptr(page); std::fill(page->begin(), page->end(), 0); - pagePtr += sizeof(RAWDataHeaderGPU); + pagePtr += sizeof(o2::header::RAWDataHeader); hdr = reinterpret_cast(pagePtr); pagePtr += sizeof(*hdr); hdr->version = zs12bit ? 2 : 1; @@ -450,15 +450,15 @@ void GPUReconstructionConvert::RunZSEncoder(const S& in, std::unique_ptr compareBuffer; compareBuffer.reserve(tmpBuffer.size()); for (unsigned int j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) { - unsigned int firstOrbit = o2::raw::RDHUtils::getHeartBeatOrbit(*(const RAWDataHeaderGPU*)buffer[i][j].data()); + unsigned int firstOrbit = o2::raw::RDHUtils::getHeartBeatOrbit(*(const o2::header::RAWDataHeader*)buffer[i][j].data()); for (unsigned int k = 0; k < buffer[i][j].size(); k++) { page = &buffer[i][j][k]; pagePtr = reinterpret_cast(page); - const RAWDataHeaderGPU* rdh = (const RAWDataHeaderGPU*)pagePtr; - if (o2::raw::RDHUtils::getMemorySize(*rdh) == sizeof(RAWDataHeaderGPU)) { + const o2::header::RAWDataHeader* rdh = (const o2::header::RAWDataHeader*)pagePtr; + if (o2::raw::RDHUtils::getMemorySize(*rdh) == sizeof(o2::header::RAWDataHeader)) { continue; } - pagePtr += sizeof(RAWDataHeaderGPU); + pagePtr += sizeof(o2::header::RAWDataHeader); hdr = reinterpret_cast(pagePtr); pagePtr += sizeof(*hdr); if (hdr->version != 1 && hdr->version != 2) { diff --git a/GPU/GPUTracking/Base/opencl-common/GPUReconstructionOCL.cl b/GPU/GPUTracking/Base/opencl-common/GPUReconstructionOCL.cl index 29aff13247e25..46ef2708b0288 100644 --- a/GPU/GPUTracking/Base/opencl-common/GPUReconstructionOCL.cl +++ b/GPU/GPUTracking/Base/opencl-common/GPUReconstructionOCL.cl @@ -22,9 +22,10 @@ #pragma OPENCL EXTENSION cl_khr_fp64 : enable // Allow double precision variables #pragma OPENCL EXTENSION cl_khr_fp16 : enable // Allow half precision #ifdef __clang__ - #pragma OPENCL EXTENSION cl_clang_storage_class_specifiers : enable // - #pragma OPENCL EXTENSION __cl_clang_function_pointers : enable // Allow function pointers - #pragma OPENCL EXTENSION __cl_clang_allow_unsafe_kernel_parameters : enable // Allow pointers to non-standard types as kernel arguments + #pragma OPENCL EXTENSION cl_clang_storage_class_specifiers : enable // + #pragma OPENCL EXTENSION __cl_clang_function_pointers : enable // Allow function pointers + #pragma OPENCL EXTENSION __cl_clang_non_portable_kernel_param_types : enable // Allow pointers to non-standard types as kernel arguments + #pragma OPENCL EXTENSION __cl_clang_bitfields : enable // Allow usage of bitfields #define global __global #define local __local #define constant __constant diff --git a/GPU/GPUTracking/Base/opencl2/CMakeLists.txt b/GPU/GPUTracking/Base/opencl2/CMakeLists.txt index 812a9c180714a..527419ee2dd0f 100644 --- a/GPU/GPUTracking/Base/opencl2/CMakeLists.txt +++ b/GPU/GPUTracking/Base/opencl2/CMakeLists.txt @@ -25,7 +25,7 @@ endif() set(CL_SRC ${GPUDIR}/Base/opencl-common/GPUReconstructionOCL.cl) set(CL_BIN ${CMAKE_CURRENT_BINARY_DIR}/GPUReconstructionOCL2Code) -set(OCL_FLAGS -Xclang -fdenormal-fp-math-f32=ieee -cl-mad-enable -cl-no-signed-zeros -ferror-limit=1000 -Xclang -finclude-default-header -Dcl_clang_storage_class_specifiers -Wno-invalid-constexpr -Wno-unused-command-line-argument -cl-std=clc++) +set(OCL_FLAGS -Xclang -fdenormal-fp-math-f32=ieee -cl-mad-enable -cl-no-signed-zeros -ferror-limit=1000 -Dcl_clang_storage_class_specifiers -Wno-invalid-constexpr -Wno-unused-command-line-argument -cl-std=clc++) set(OCL_DEFINECL "-D$,$-D>" "-I$,EXCLUDE,^/usr/include/?>,$-I>" -I${CMAKE_SOURCE_DIR}/Detectors/TRD/base/src @@ -124,7 +124,7 @@ if(OPENCL2_ENABLED) # BUILD OpenCL2 source code for runtime compilation target add_custom_command( OUTPUT ${CL_BIN}.src COMMAND clang - ${OCL_DEFINECL} + ${OCL_DEFINECL} -cl-no-stdinc -E ${CL_SRC} > ${CL_BIN}.src MAIN_DEPENDENCY ${CL_SRC} IMPLICIT_DEPENDS CXX ${CL_SRC} diff --git a/GPU/GPUTracking/CMakeLists.txt b/GPU/GPUTracking/CMakeLists.txt index d18b95d256b5b..11eef4e81d129 100644 --- a/GPU/GPUTracking/CMakeLists.txt +++ b/GPU/GPUTracking/CMakeLists.txt @@ -131,7 +131,6 @@ set(HDRS_INSTALL DataTypes/GPUOutputControl.h DataTypes/GPUO2DataTypes.h DataTypes/GPUHostDataTypes.h - DataTypes/GPURawData.h DataTypes/GPUdEdxInfo.h DataTypes/GPUTRDInterfaceO2Track.h Base/GPUParam.inc diff --git a/GPU/GPUTracking/DataTypes/GPURawData.h b/GPU/GPUTracking/DataTypes/GPURawData.h deleted file mode 100644 index 734947014246a..0000000000000 --- a/GPU/GPUTracking/DataTypes/GPURawData.h +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright CERN and copyright holders of ALICE O2. This software is -// distributed under the terms of the GNU General Public License v3 (GPL -// Version 3), copied verbatim in the file "COPYING". -// -// See http://alice-o2.web.cern.ch/license for full licensing information. -// -// In applying this license CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -/// \file GPURawData.h -/// \author David Rohr - -#ifndef O2_GPU_RAW_DATA_H -#define O2_GPU_RAW_DATA_H - -// Raw data parser is not accessible from GPU, therefore we use this header to wrap direct access to the current RDH -// Since OpenCL currently doesn't support bit fields, we have to access the members directly - -#include "GPUCommonDef.h" -#ifndef __OPENCL__ -#include "Headers/RAWDataHeader.h" -#include "DetectorsRaw/RDHUtils.h" -#else -namespace o2 -{ -namespace header -{ -struct RAWDataHeader { - union { - unsigned int words[8]; - }; -}; -} // namespace header -} // namespace o2 -#endif - -namespace GPUCA_NAMESPACE -{ -namespace gpu -{ -typedef o2::header::RAWDataHeader RAWDataHeaderGPU; - -class GPURawDataUtils -{ - public: - static GPUd() unsigned int getOrbit(const RAWDataHeaderGPU* rdh); - static GPUd() unsigned int getBC(const RAWDataHeaderGPU* rdh); - static GPUd() unsigned int getSize(const RAWDataHeaderGPU* rdh); -}; - -GPUdi() unsigned int GPURawDataUtils::getOrbit(const RAWDataHeaderGPU* rdh) -{ -#ifndef __OPENCL__ - return o2::raw::RDHUtils::getHeartBeatOrbit(*rdh); -#else - return (rdh->words[2] >> 32); // TODO: Ad-hoc implementation for OpenCL, RDHV4, to be moved to RDHUtils -#endif -} - -GPUdi() unsigned int GPURawDataUtils::getBC(const RAWDataHeaderGPU* rdh) -{ -#ifndef __OPENCL__ - return o2::raw::RDHUtils::getHeartBeatBC(*rdh); -#else - return (rdh->words[2] & 0xFFF); // TODO: Ad-hoc implementation for OpenCL, RDHV4, to be moved to RDHUtils -#endif -} - -GPUdi() unsigned int GPURawDataUtils::getSize(const RAWDataHeaderGPU* rdh) -{ -#ifndef __OPENCL__ - return o2::raw::RDHUtils::getMemorySize(*rdh); -#else - return ((rdh->words[1] >> 16) & 0xFFFF); // TODO: Ad-hoc implementation for OpenCL, RDHV4, to be moved to RDHUtils -#endif -} - -} // namespace gpu -} // namespace GPUCA_NAMESPACE - -#endif diff --git a/GPU/GPUTracking/Global/GPUChainTrackingClusterizer.cxx b/GPU/GPUTracking/Global/GPUChainTrackingClusterizer.cxx index a7dc5a92bdb14..d450705d03e9a 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingClusterizer.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingClusterizer.cxx @@ -25,7 +25,6 @@ #ifdef HAVE_O2HEADERS #include "GPUHostDataTypes.h" #include "GPUTPCCFChainContext.h" -#include "GPURawData.h" #include "DataFormatsTPC/ZeroSuppression.h" #include "DetectorsRaw/RDHUtils.h" #include "DataFormatsTPC/Digit.h" @@ -91,7 +90,7 @@ std::pair GPUChainTracking::TPCClusterizerDecodeZSCo unsigned int nDigits = 0; unsigned int nPages = 0; bool doGPU = mRec->GetRecoStepsGPU() & GPUDataTypes::RecoStep::TPCClusterFinding; - int firstHBF = (mIOPtrs.settingsTF && mIOPtrs.settingsTF->hasTfStartOrbit) ? mIOPtrs.settingsTF->tfStartOrbit : (mIOPtrs.tpcZS->slice[iSlice].count[0] && mIOPtrs.tpcZS->slice[iSlice].nZSPtr[0][0]) ? o2::raw::RDHUtils::getHeartBeatOrbit(*(const RAWDataHeaderGPU*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[0][0]) : 0; + int firstHBF = (mIOPtrs.settingsTF && mIOPtrs.settingsTF->hasTfStartOrbit) ? mIOPtrs.settingsTF->tfStartOrbit : (mIOPtrs.tpcZS->slice[iSlice].count[0] && mIOPtrs.tpcZS->slice[iSlice].nZSPtr[0][0]) ? o2::raw::RDHUtils::getHeartBeatOrbit(*(const o2::header::RAWDataHeader*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[0][0]) : 0; for (unsigned short j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) { #ifndef GPUCA_NO_VC @@ -99,7 +98,7 @@ std::pair GPUChainTracking::TPCClusterizerDecodeZSCo for (unsigned int k = 0; k < mIOPtrs.tpcZS->slice[iSlice].count[j + 1]; k++) { for (unsigned int l = 0; l < mIOPtrs.tpcZS->slice[iSlice].nZSPtr[j + 1][k]; l++) { Vc::Common::prefetchMid(((const unsigned char*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[j + 1][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE); - Vc::Common::prefetchMid(((const unsigned char*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[j + 1][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE + sizeof(RAWDataHeaderGPU)); + Vc::Common::prefetchMid(((const unsigned char*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[j + 1][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE + sizeof(o2::header::RAWDataHeader)); } } } @@ -120,16 +119,16 @@ std::pair GPUChainTracking::TPCClusterizerDecodeZSCo #ifndef GPUCA_NO_VC if (GetProcessingSettings().prefetchTPCpageScan >= 2 && l + 1 < mIOPtrs.tpcZS->slice[iSlice].nZSPtr[j][k]) { Vc::Common::prefetchForOneRead(((const unsigned char*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[j][k]) + (l + 1) * TPCZSHDR::TPC_ZS_PAGE_SIZE); - Vc::Common::prefetchForOneRead(((const unsigned char*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[j][k]) + (l + 1) * TPCZSHDR::TPC_ZS_PAGE_SIZE + sizeof(RAWDataHeaderGPU)); + Vc::Common::prefetchForOneRead(((const unsigned char*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[j][k]) + (l + 1) * TPCZSHDR::TPC_ZS_PAGE_SIZE + sizeof(o2::header::RAWDataHeader)); } #endif const unsigned char* const page = ((const unsigned char*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[j][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE; - const RAWDataHeaderGPU* rdh = (const RAWDataHeaderGPU*)page; - if (o2::raw::RDHUtils::getMemorySize(*rdh) == sizeof(RAWDataHeaderGPU)) { + const o2::header::RAWDataHeader* rdh = (const o2::header::RAWDataHeader*)page; + if (o2::raw::RDHUtils::getMemorySize(*rdh) == sizeof(o2::header::RAWDataHeader)) { emptyPages++; continue; } - const TPCZSHDR* const hdr = (const TPCZSHDR*)(page + sizeof(RAWDataHeaderGPU)); + const TPCZSHDR* const hdr = (const TPCZSHDR*)(page + sizeof(o2::header::RAWDataHeader)); nDigits += hdr->nADCsamples; unsigned int timeBin = (hdr->timeOffset + (o2::raw::RDHUtils::getHeartBeatOrbit(*rdh) - firstHBF) * o2::constants::lhc::LHCMaxBunches) / LHCBCPERTIMEBIN; if (timeBin + hdr->nTimeBins > mCFContext->tpcMaxTimeBin) { @@ -256,7 +255,7 @@ std::pair GPUChainTracking::RunTPCClusterizer_transf const unsigned int max = (k + 1 == clusterer.mMinMaxCN[j].maxC) ? clusterer.mMinMaxCN[j].maxN : mIOPtrs.tpcZS->slice[iSlice].nZSPtr[j][k]; if (max > min) { char* src = (char*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[j][k] + min * TPCZSHDR::TPC_ZS_PAGE_SIZE; - size_t size = o2::raw::RDHUtils::getMemorySize(*(const RAWDataHeaderGPU*)src); + size_t size = o2::raw::RDHUtils::getMemorySize(*(const o2::header::RAWDataHeader*)src); size = (max - min - 1) * TPCZSHDR::TPC_ZS_PAGE_SIZE + (size ? TPCZSHDR::TPC_ZS_PAGE_SIZE : size); GPUMemCpy(RecoStep::TPCClusterFinding, clustererShadow.mPzs + (nPagesSector + nPages) * TPCZSHDR::TPC_ZS_PAGE_SIZE, src, size, lane, true); } @@ -296,8 +295,8 @@ int GPUChainTracking::RunTPCClusterizer_prepare(bool restorePointers) for (unsigned int iSlice = 0; iSlice < NSLICES; iSlice++) { if (mIOPtrs.tpcZS->slice[iSlice].count[0]) { const void* rdh = mIOPtrs.tpcZS->slice[iSlice].zsPtr[0][0]; - if (rdh && o2::raw::RDHUtils::getVersion() != o2::raw::RDHUtils::getVersion(rdh)) { - GPUError("Data has invalid RDH version %d, %d required\n", o2::raw::RDHUtils::getVersion(rdh), o2::raw::RDHUtils::getVersion()); + if (rdh && o2::raw::RDHUtils::getVersion() != o2::raw::RDHUtils::getVersion(rdh)) { + GPUError("Data has invalid RDH version %d, %d required\n", o2::raw::RDHUtils::getVersion(rdh), o2::raw::RDHUtils::getVersion()); return 1; } } @@ -307,7 +306,7 @@ int GPUChainTracking::RunTPCClusterizer_prepare(bool restorePointers) for (unsigned int k = 0; k < mIOPtrs.tpcZS->slice[iSlice].count[j]; k++) { for (unsigned int l = 0; l < mIOPtrs.tpcZS->slice[iSlice].nZSPtr[j][k]; l++) { Vc::Common::prefetchFar(((const unsigned char*)mIOPtrs.tpcZS->slice[iSlice + 1].zsPtr[j][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE); - Vc::Common::prefetchFar(((const unsigned char*)mIOPtrs.tpcZS->slice[iSlice + 1].zsPtr[j][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE + sizeof(RAWDataHeaderGPU)); + Vc::Common::prefetchFar(((const unsigned char*)mIOPtrs.tpcZS->slice[iSlice + 1].zsPtr[j][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE + sizeof(o2::header::RAWDataHeader)); } } } @@ -508,7 +507,7 @@ int GPUChainTracking::RunTPCClusterizer(bool synchronizeOutput) } if (mIOPtrs.tpcZS) { - int firstHBF = (mIOPtrs.settingsTF && mIOPtrs.settingsTF->hasTfStartOrbit) ? mIOPtrs.settingsTF->tfStartOrbit : (mIOPtrs.tpcZS->slice[iSlice].count[0] && mIOPtrs.tpcZS->slice[iSlice].nZSPtr[0][0]) ? o2::raw::RDHUtils::getHeartBeatOrbit(*(const RAWDataHeaderGPU*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[0][0]) : 0; + int firstHBF = (mIOPtrs.settingsTF && mIOPtrs.settingsTF->hasTfStartOrbit) ? mIOPtrs.settingsTF->tfStartOrbit : (mIOPtrs.tpcZS->slice[iSlice].count[0] && mIOPtrs.tpcZS->slice[iSlice].nZSPtr[0][0]) ? o2::raw::RDHUtils::getHeartBeatOrbit(*(const o2::header::RAWDataHeader*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[0][0]) : 0; runKernel(GetGridBlk(doGPU ? clusterer.mPmemory->counters.nPagesSubslice : GPUTrackingInOutZS::NENDPOINTS, lane), {iSlice}, {}, firstHBF); TransferMemoryResourceLinkToHost(RecoStep::TPCClusterFinding, clusterer.mMemoryId, lane); } diff --git a/GPU/GPUTracking/Standalone/tools/testCL.sh b/GPU/GPUTracking/Standalone/tools/testCL.sh index a370266e1e5cf..576e4ceb94e52 100755 --- a/GPU/GPUTracking/Standalone/tools/testCL.sh +++ b/GPU/GPUTracking/Standalone/tools/testCL.sh @@ -14,11 +14,11 @@ INCLUDES="-I../. -I../DataTypes -I../Definitions -I../Base -I../SliceTracker -I. -I$HOME/alice/O2/Detectors/TRD/base/include -I$HOME/alice/O2/Detectors/TRD/base/src -I$HOME/alice/O2/Detectors/ITSMFT/ITS/tracking/include -I$HOME/alice/O2/Detectors/ITSMFT/ITS/tracking/cuda/include -I$HOME/alice/O2/Common/Constants/include \ -I$HOME/alice/O2/DataFormats/common/include -I$HOME/alice/O2/DataFormats/Detectors/Common/include -I$HOME/alice/O2/DataFormats/Detectors/TRD/include -I$HOME/alice/O2/DataFormats/Reconstruction/include -I$HOME/alice/O2/DataFormats/Reconstruction/src" DEFINES="-DGPUCA_STANDALONE -DGPUCA_GPULIBRARY=OCL -DNDEBUG -D__OPENCLCPP__ -DHAVE_O2HEADERS -DGPUCA_TPC_GEOMETRY_O2" -FLAGS="-Xclang -fdenormal-fp-math-f32=ieee -cl-mad-enable -cl-no-signed-zeros -ferror-limit=1000 -Xclang -finclude-default-header -Dcl_clang_storage_class_specifiers" +FLAGS="-Xclang -fdenormal-fp-math-f32=ieee -cl-mad-enable -cl-no-signed-zeros -ferror-limit=1000 -Dcl_clang_storage_class_specifiers" echo Test1 - Preprocess -echo $COMPILER -cl-std=clc++ -x cl $INCLUDES $DEFINES -Dcl_clang_storage_class_specifiers -E ../Base/opencl-common/GPUReconstructionOCL.cl > test.cl - $COMPILER -cl-std=clc++ -x cl $INCLUDES $DEFINES -Dcl_clang_storage_class_specifiers -E ../Base/opencl-common/GPUReconstructionOCL.cl > test.cl +echo $COMPILER -cl-std=clc++ -x cl $INCLUDES $DEFINES -Dcl_clang_storage_class_specifiers -cl-no-stdinc -E ../Base/opencl-common/GPUReconstructionOCL.cl > test.cl + $COMPILER -cl-std=clc++ -x cl $INCLUDES $DEFINES -Dcl_clang_storage_class_specifiers -cl-no-stdinc -E ../Base/opencl-common/GPUReconstructionOCL.cl > test.cl if [ $? != 0 ]; then exit 1; fi #Test 1A - Compile Preprocessed #echo $COMPILER -cl-std=clc++ -x cl -emit-llvm --target=spir64-unknown-unknown $FLAGS -c test.cl -o test.bc diff --git a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFDecodeZS.cxx b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFDecodeZS.cxx index ff68e6794e7a7..5bd56210213d6 100644 --- a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFDecodeZS.cxx +++ b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFDecodeZS.cxx @@ -18,8 +18,8 @@ #include "PackedCharge.h" #include "DataFormatsTPC/ZeroSuppression.h" #include "CommonConstants/LHCConstants.h" -#include "GPURawData.h" #include "GPUCommonAlgorithm.h" +#include "DetectorsRaw/RDHUtils.h" using namespace GPUCA_NAMESPACE::gpu; using namespace GPUCA_NAMESPACE::gpu::tpccf; @@ -73,22 +73,22 @@ GPUdii() void GPUTPCCFDecodeZS::decode(GPUTPCClusterFinder& clusterer, GPUShared CA_SHARED_CACHE_REF(&s.ZSPage[0], pageSrc, TPCZSHDR::TPC_ZS_PAGE_SIZE, unsigned int, pageCache); GPUbarrier(); const unsigned char* page = (const unsigned char*)pageCache; - const RAWDataHeaderGPU* rdh = (const RAWDataHeaderGPU*)page; - if (GPURawDataUtils::getSize(rdh) == sizeof(RAWDataHeaderGPU)) { + const o2::header::RAWDataHeader* rdh = (const o2::header::RAWDataHeader*)page; + if (o2::raw::RDHUtils::getMemorySize(*rdh) == sizeof(o2::header::RAWDataHeader)) { #ifdef GPUCA_GPUCODE return; #else continue; #endif } - const unsigned char* pagePtr = page + sizeof(RAWDataHeaderGPU); + const unsigned char* pagePtr = page + sizeof(o2::header::RAWDataHeader); const TPCZSHDR* hdr = reinterpret_cast(pagePtr); pagePtr += sizeof(*hdr); const bool decode12bit = hdr->version == 2; const unsigned int decodeBits = decode12bit ? TPCZSHDR::TPC_ZS_NBITS_V2 : TPCZSHDR::TPC_ZS_NBITS_V1; const float decodeBitsFactor = 1.f / (1 << (decodeBits - 10)); unsigned int mask = (1 << decodeBits) - 1; - int timeBin = (hdr->timeOffset + (GPURawDataUtils::getOrbit(rdh) - firstHBF) * o2::constants::lhc::LHCMaxBunches) / LHCBCPERTIMEBIN; + int timeBin = (hdr->timeOffset + (o2::raw::RDHUtils::getHeartBeatOrbit(*rdh) - firstHBF) * o2::constants::lhc::LHCMaxBunches) / LHCBCPERTIMEBIN; const int rowOffset = s.regionStartRow + ((endpoint & 1) ? (s.nRowsRegion / 2) : 0); const int nRows = (endpoint & 1) ? (s.nRowsRegion - s.nRowsRegion / 2) : (s.nRowsRegion / 2); From 4e24eaf7936b268e11772c10d0100a6b1f2329cd Mon Sep 17 00:00:00 2001 From: jgrosseo Date: Fri, 7 May 2021 08:27:59 +0200 Subject: [PATCH 423/770] improving configuration harvesting (#6080) --- Analysis/Tasks/PWGCF/correlations.cxx | 39 ++++++++++++++++++--------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/Analysis/Tasks/PWGCF/correlations.cxx b/Analysis/Tasks/PWGCF/correlations.cxx index 1272c0f330506..5c1992684dd85 100644 --- a/Analysis/Tasks/PWGCF/correlations.cxx +++ b/Analysis/Tasks/PWGCF/correlations.cxx @@ -402,9 +402,8 @@ struct CorrelationTask { }; struct CorrelationHashTask { - // TODO sync configurables with main task - std::vector vtxBins{0.0f}; - std::vector multBins{0.0f}; + std::vector vtxBins; + std::vector multBins; Produces hashes; @@ -426,24 +425,38 @@ struct CorrelationHashTask { void init(o2::framework::InitContext& initContext) { + // get own suffix. Is there a better way? + auto& deviceSpec = initContext.services().get(); + std::string suffix(deviceSpec.name); + suffix.replace(0, strlen("correlation-hash-task"), ""); + // get axis config from CorrelationTask auto& workflows = initContext.services().get(); for (DeviceSpec device : workflows.devices) { - for (auto option : device.options) { - if (option.name == "axisVertex") { - fillArray(option.defaultValue.size(), option.defaultValue.get(), vtxBins); - LOGF(info, "Initialized vertex binning for mixing from configurable %s", option.name); - } - if (option.name == "axisMultiplicity") { - fillArray(option.defaultValue.size(), option.defaultValue.get(), multBins); - LOGF(info, "Initialized multiplicity binning for mixing from configurable %s", option.name); + if (device.name == "correlation-task" + suffix) { + for (auto option : device.options) { + if (option.name == "axisVertex") { + fillArray(option.defaultValue.size(), option.defaultValue.get(), vtxBins); + LOGF(info, "Initialized vertex binning for mixing from configurable %s", option.name); + } + if (option.name == "axisMultiplicity") { + fillArray(option.defaultValue.size(), option.defaultValue.get(), multBins); + LOGF(info, "Initialized multiplicity binning for mixing from configurable %s", option.name); + } } } } + + if (vtxBins.size() == 0) { + LOGF(fatal, "vtxBins not configured. Check configuration."); + } + if (multBins.size() == 0) { + LOGF(fatal, "multBins not configured. Check configuration."); + } } // Calculate hash for an element based on 2 properties and their bins. - int getHash(std::vector const& vtxBins, std::vector const& multBins, float vtx, float mult) + int getHash(float vtx, float mult) { // underflow if (vtx < vtxBins[0]) { @@ -469,7 +482,7 @@ struct CorrelationHashTask { void process(soa::Join const& collisions) { for (auto& collision : collisions) { - int hash = getHash(vtxBins, multBins, collision.posZ(), collision.centV0M()); + int hash = getHash(collision.posZ(), collision.centV0M()); LOGF(info, "Collision: %d (%f, %f) hash: %d", collision.index(), collision.posZ(), collision.centV0M(), hash); hashes(hash); } From 35a445396ab00bf7b00f2a1066b8cfb650a7b3e6 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Fri, 7 May 2021 09:02:19 +0200 Subject: [PATCH 424/770] Use a per workflow startTime... (#5873) This is a clear violation of our DataModel, however I do not see how we can do it without copying and rewriting all the headers passed by DD to DPL. --- Framework/Core/src/ExternalFairMQDeviceProxy.cxx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Framework/Core/src/ExternalFairMQDeviceProxy.cxx b/Framework/Core/src/ExternalFairMQDeviceProxy.cxx index 18811b4c316e2..d4a89c71ae2d8 100644 --- a/Framework/Core/src/ExternalFairMQDeviceProxy.cxx +++ b/Framework/Core/src/ExternalFairMQDeviceProxy.cxx @@ -216,6 +216,8 @@ InjectorFunction dplModelAdaptor(std::vector const& filterSpecs, boo std::vector unmatchedDescriptions; int lastSplitPartIndex = -1; std::string channelNameForSplitParts; + static int64_t dplCounter = -1; + dplCounter++; for (size_t msgidx = 0; msgidx < parts.Size() / 2; ++msgidx) { if (indicesDone[msgidx]) { continue; @@ -226,11 +228,12 @@ InjectorFunction dplModelAdaptor(std::vector const& filterSpecs, boo LOG(ERROR) << "data on input " << msgidx << " does not follow the O2 data model, DataHeader missing"; continue; } - const auto dph = o2::header::get(parts.At(msgidx * 2)->GetData()); + auto dph = o2::header::get(parts.At(msgidx * 2)->GetData()); if (!dph) { LOG(ERROR) << "data on input " << msgidx << " does not follow the O2 data model, DataProcessingHeader missing"; continue; } + const_cast(dph)->startTime = dplCounter; LOG(DEBUG) << msgidx << ": " << DataSpecUtils::describe(OutputSpec{dh->dataOrigin, dh->dataDescription, dh->subSpecification}) << " part " << dh->splitPayloadIndex << " of " << dh->splitPayloadParts << " payload " << parts.At(msgidx * 2 + 1)->GetSize(); OutputSpec query{dh->dataOrigin, dh->dataDescription, dh->subSpecification}; From 822ee419dfa71aca072104c3423b0e4dd44f2220 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 6 May 2021 13:30:59 +0200 Subject: [PATCH 425/770] Add TRD Tracks, Tracklet MC labels to generic reader / RecoContainer --- .../DataFormatsGlobalTracking/RecoContainer.h | 32 +++++++++- .../GlobalTracking/src/RecoContainer.cxx | 59 ++++++++++++++++++- .../DataFormatsTRD/RecoInputContainer.h | 8 ++- .../helpers/CMakeLists.txt | 1 + .../helpers/src/InputHelper.cxx | 8 ++- .../TRDWorkflowIO/TRDTrackletReaderSpec.h | 3 +- GPU/GPUTracking/DataTypes/GPUDataTypes.h | 4 ++ GPU/Workflow/helper/src/GPUWorkflowHelper.cxx | 17 +++++- 8 files changed, 123 insertions(+), 9 deletions(-) diff --git a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h index d10fb2fdcca96..6ec19b5463492 100644 --- a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h +++ b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h @@ -66,13 +66,15 @@ struct DataRequest { void requestTPCTracks(bool mc); void requestITSTPCTracks(bool mc); void requestTPCTOFTracks(bool mc); + void requestITSTPCTRDTracks(bool mc); + void requestTPCTRDTracks(bool mc); void requestTOFMatches(bool mc); void requestFT0RecPoints(bool mc); void requestITSClusters(bool mc); void requestTPCClusters(bool mc); void requestTOFClusters(bool mc); - void requestTRDTracklets(); + void requestTRDTracklets(bool mc); }; struct RecoContainer { @@ -110,6 +112,8 @@ struct RecoContainer { void addITSTracks(o2::framework::ProcessingContext& pc, bool mc); void addTPCTracks(o2::framework::ProcessingContext& pc, bool mc); + void addITSTPCTRDTracks(o2::framework::ProcessingContext& pc, bool mc); + void addTPCTRDTracks(o2::framework::ProcessingContext& pc, bool mc); void addITSTPCTracks(o2::framework::ProcessingContext& pc, bool mc); void addTPCTOFTracks(o2::framework::ProcessingContext& pc, bool mc); void addTOFMatches(o2::framework::ProcessingContext& pc, bool mc); @@ -203,6 +207,31 @@ struct RecoContainer { return tracksPool.get_as(id); } + // TRD + template // o2::dataformats::TrackTRD + auto getITSTPCTRDTracks() const + { + return tracksPool.getSpan(GTrackID::ITSTPCTRD); + } + + template // o2::dataformats::TrackTRD + auto getTPCTRDTracks() const + { + return tracksPool.getSpan(GTrackID::TPCTRD); + } + + template // o2::dataformats::TrackTRD or TrackParCov + auto getITSTPCTRDTrack(GTrackID id) const + { + return tracksPool.get_as(id); + } + + template // o2::dataformats::TrackTRD or TrackParCov + auto getTPCTRDTrack(GTrackID id) const + { + return tracksPool.get_as(id); + } + auto getTPCITSTracksMCLabels() const { return tracksMCPool.getSpan(GTrackID::ITSTPC); } auto getTPCITSTrackMCLabel(GTrackID id) const { return tracksMCPool.get_as(id); } @@ -254,6 +283,7 @@ struct RecoContainer { gsl::span getTRDTracklets() const; gsl::span getTRDCalibratedTracklets() const; gsl::span getTRDTriggerRecords() const; + const o2::dataformats::MCTruthContainer& getTRDTrackletLabels() const; // ITS clusters template // o2::itsmft::ROFRecord diff --git a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx index b918125e50018..0fb16c1362406 100644 --- a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx +++ b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx @@ -87,6 +87,24 @@ void DataRequest::requestTPCTOFTracks(bool mc) requestMap["trackTPCTOF"] = mc; } +void DataRequest::requestITSTPCTRDTracks(bool mc) +{ + addInput({"trackTRDTPCITS", "TRD", "MATCHTRD_GLO", 0, Lifetime::Timeframe}); + if (mc) { + LOG(ERROR) << "TRD Tracks does not support MC truth"; + } + requestMap["trackTRDTPCITS"] = false; +} + +void DataRequest::requestTPCTRDTracks(bool mc) +{ + addInput({"trackTRDTPC", "TRD", "MATCHTRD_TPC", 0, Lifetime::Timeframe}); + if (mc) { + LOG(ERROR) << "TRD Tracks does not support MC truth"; + } + requestMap["trackTRDTPC"] = false; +} + void DataRequest::requestTOFMatches(bool mc) { addInput({"matchITSTPCTOF", "TOF", "MATCHINFOS", 0, Lifetime::Timeframe}); @@ -126,12 +144,15 @@ void DataRequest::requestTOFClusters(bool mc) requestMap["clusTOF"] = mc; } -void DataRequest::requestTRDTracklets() +void DataRequest::requestTRDTracklets(bool mc) { addInput({"trdtracklets", o2::header::gDataOriginTRD, "TRACKLETS", 0, Lifetime::Timeframe}); addInput({"trdctracklets", o2::header::gDataOriginTRD, "CTRACKLETS", 0, Lifetime::Timeframe}); addInput({"trdtriggerrec", o2::header::gDataOriginTRD, "TRKTRGRD", 0, Lifetime::Timeframe}); - requestMap["trackletTRD"] = false; + if (mc) { + addInput({"trdtrackletlabels", o2::header::gDataOriginTRD, "TRKLABELS", 0, Lifetime::Timeframe}); + } + requestMap["trackletTRD"] = mc; } void DataRequest::requestFT0RecPoints(bool mc) @@ -162,6 +183,12 @@ void DataRequest::requestTracks(GTrackID::mask_t src, bool useMC) requestTOFMatches(useMC); requestTOFClusters(false); // RSTODO Needed just to set the time of ITSTPC track, consider moving to MatchInfoTOF } + if (src[GTrackID::ITSTPCTRD]) { + requestITSTPCTRDTracks(useMC); + } + if (src[GTrackID::TPCTRD]) { + requestTPCTRDTracks(useMC); + } } void DataRequest::requestClusters(GTrackID::mask_t src, bool useMC) @@ -179,7 +206,7 @@ void DataRequest::requestClusters(GTrackID::mask_t src, bool useMC) requestTOFClusters(useMC); } if (GTrackID::includesDet(DetID::TRD, src)) { - requestTRDTracklets(); + requestTRDTracklets(useMC); } } @@ -206,6 +233,16 @@ void RecoContainer::collectData(ProcessingContext& pc, const DataRequest& reques addITSTPCTracks(pc, req->second); } + req = reqMap.find("trackITSTPCTRD"); + if (req != reqMap.end()) { + addITSTPCTRDTracks(pc, req->second); + } + + req = reqMap.find("trackTPCTRD"); + if (req != reqMap.end()) { + addTPCTRDTracks(pc, req->second); + } + req = reqMap.find("trackTPCTOF"); if (req != reqMap.end()) { addTPCTOFTracks(pc, req->second); @@ -272,6 +309,17 @@ void RecoContainer::addITSTPCTracks(ProcessingContext& pc, bool mc) } } +void RecoContainer::addITSTPCTRDTracks(ProcessingContext& pc, bool mc) +{ +#warning fix TrackParCov + tracksPool.registerContainer(pc.inputs().get>("trackITSTPCTRD"), GTrackID::ITSTPCTRD); +} + +void RecoContainer::addTPCTRDTracks(ProcessingContext& pc, bool mc) +{ + tracksPool.registerContainer(pc.inputs().get>("trackTPCTRD"), GTrackID::TPCTRD); +} + //__________________________________________________________ void RecoContainer::addTPCTOFTracks(ProcessingContext& pc, bool mc) { @@ -352,6 +400,11 @@ gsl::span RecoContainer::getTRDTriggerRecords() co return inputsTRD->mTriggerRecords; } +const o2::dataformats::MCTruthContainer& RecoContainer::getTRDTrackletLabels() const +{ + return *inputsTRD->mTrackletLabels; +} + //__________________________________________________________ const o2::track::TrackParCov& RecoContainer::getTrackParamOut(GTrackID gidx) const { diff --git a/DataFormats/Detectors/TRD/include/DataFormatsTRD/RecoInputContainer.h b/DataFormats/Detectors/TRD/include/DataFormatsTRD/RecoInputContainer.h index 3a2727d55efd9..0f3b9378a4286 100644 --- a/DataFormats/Detectors/TRD/include/DataFormatsTRD/RecoInputContainer.h +++ b/DataFormats/Detectors/TRD/include/DataFormatsTRD/RecoInputContainer.h @@ -24,6 +24,7 @@ #include "CommonConstants/LHCConstants.h" #include "Framework/ProcessingContext.h" #include "Framework/InputRecord.h" +#include "SimulationDataFormat/MCTruthContainer.h" #include "GPUDataTypes.h" @@ -49,9 +50,10 @@ struct RecoInputContainer { unsigned int mNTriggerRecords; std::vector trdTriggerTimes; std::vector trdTriggerIndices; + std::unique_ptr> mTrackletLabels; }; -inline auto getRecoInputContainer(o2::framework::ProcessingContext& pc, o2::gpu::GPUTrackingInOutPointers* ptrs, const o2::globaltracking::RecoContainer* inputTracks) +inline auto getRecoInputContainer(o2::framework::ProcessingContext& pc, o2::gpu::GPUTrackingInOutPointers* ptrs, const o2::globaltracking::RecoContainer* inputTracks, bool mc = false) { auto retVal = std::make_unique(); retVal->mTracksTPCITS = inputTracks->getTPCITSTracks(); @@ -66,6 +68,10 @@ inline auto getRecoInputContainer(o2::framework::ProcessingContext& pc, o2::gpu: retVal->mNSpacePoints = retVal->mSpacePoints.size(); retVal->mNTriggerRecords = retVal->mTriggerRecords.size(); + if (mc) { + retVal->mTrackletLabels = pc.inputs().get*>("trdtrackletlabels"); + } + for (unsigned int iEv = 0; iEv < retVal->mNTriggerRecords; ++iEv) { const auto& trg = retVal->mTriggerRecords[iEv]; retVal->trdTriggerIndices.push_back(trg.getFirstTracklet()); diff --git a/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt b/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt index d1dfea441788d..858500ea85ea0 100644 --- a/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt +++ b/Detectors/GlobalTrackingWorkflow/helpers/CMakeLists.txt @@ -20,6 +20,7 @@ o2_add_library(GlobalTrackingWorkflowHelpers O2::FT0Workflow O2::ITSMFTWorkflow O2::TRDWorkflowIO + O2::TRDWorkflow O2::TPCReaderWorkflow O2::SimulationDataFormat) diff --git a/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx b/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx index a510f0dd763ff..451b4071cd093 100644 --- a/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx +++ b/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx @@ -22,6 +22,7 @@ #include "TOFWorkflow/TOFMatchedReaderSpec.h" #include "FT0Workflow/RecPointReaderSpec.h" #include "TRDWorkflowIO/TRDTrackletReaderSpec.h" +#include "TRDWorkflow/TRDTrackReaderSpec.h" using namespace o2::framework; using namespace o2::globaltracking; @@ -68,13 +69,18 @@ int InputHelper::addInputSpecs(const ConfigContext& configcontext, WorkflowSpec& if (maskMatches[GID::TPCTOF]) { specs.emplace_back(o2::tof::getTOFMatchedReaderSpec(maskTracksMC[GID::TPCTOF], true, maskTracks[GID::TPCTOF])); } - if (maskTracks[GID::FT0] || maskClusters[GID::FT0]) { specs.emplace_back(o2::ft0::getRecPointReaderSpec(maskTracksMC[GID::FT0] || maskClustersMC[GID::FT0])); } if (maskClusters[GID::TRD]) { specs.emplace_back(o2::trd::getTRDTrackletReaderSpec(maskClustersMC[GID::TRD], true)); } + if (maskTracks[GID::ITSTPCTRD]) { + specs.emplace_back(o2::trd::getTRDGlobalTrackReaderSpec(false)); + } + if (maskTracks[GID::TPCTRD]) { + specs.emplace_back(o2::trd::getTRDTPCTrackReaderSpec(false)); + } return 0; } diff --git a/Detectors/TRD/workflow/io/include/TRDWorkflowIO/TRDTrackletReaderSpec.h b/Detectors/TRD/workflow/io/include/TRDWorkflowIO/TRDTrackletReaderSpec.h index 24f67cd21069c..8445f505356ce 100644 --- a/Detectors/TRD/workflow/io/include/TRDWorkflowIO/TRDTrackletReaderSpec.h +++ b/Detectors/TRD/workflow/io/include/TRDWorkflowIO/TRDTrackletReaderSpec.h @@ -22,6 +22,7 @@ #include "DataFormatsTRD/CalibratedTracklet.h" #include "DataFormatsTRD/TriggerRecord.h" #include "SimulationDataFormat/MCCompLabel.h" +#include "SimulationDataFormat/MCTruthContainer.h" namespace o2 { @@ -50,7 +51,7 @@ class TRDTrackletReader : public o2::framework::Task std::vector mTrackletsCal, *mTrackletsCalPtr = &mTrackletsCal; std::vector mTracklets, *mTrackletsPtr = &mTracklets; std::vector mTriggerRecords, *mTriggerRecordsPtr = &mTriggerRecords; - std::vector mLabels, *mLabelsPtr = &mLabels; + o2::dataformats::MCTruthContainer mLabels, *mLabelsPtr = &mLabels; }; /// create a processor spec diff --git a/GPU/GPUTracking/DataTypes/GPUDataTypes.h b/GPU/GPUTracking/DataTypes/GPUDataTypes.h index adcf79011fc67..d42e727e4724d 100644 --- a/GPU/GPUTracking/DataTypes/GPUDataTypes.h +++ b/GPU/GPUTracking/DataTypes/GPUDataTypes.h @@ -274,6 +274,10 @@ struct GPUTrackingInOutPointers { const float* trdTriggerTimes = nullptr; const int* trdTrackletIdxFirst = nullptr; unsigned int nTRDTriggerRecords = 0; + const GPUTRDTrack* trdTracksITSTPCTRD = nullptr; + unsigned int nTRDTracksITSTPCTRD = 0; + const GPUTRDTrack* trdTracksTPCTRD = nullptr; + unsigned int nTRDTracksTPCTRD = 0; // TOF const o2::tof::Cluster* tofClusters = nullptr; diff --git a/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx b/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx index 4ee92258ab865..6a0866a37eeb7 100644 --- a/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx +++ b/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx @@ -94,7 +94,7 @@ std::shared_ptr GPUWorkflowHelper::fi } if (maskCl[GID::TPC] && ioPtr.clustersNative == nullptr) { - ioPtr.clustersNative = &recoCont.inputsTPCclusters->clusterIndex; + ioPtr.clustersNative = &recoCont.getTPCClusters(); } if (maskTrk[GID::TPC] && ioPtr.nOutputTracksTPCO2 == 0) { @@ -111,7 +111,20 @@ std::shared_ptr GPUWorkflowHelper::fi } if (maskCl[GID::TRD]) { - // o2::trd::getRecoInputContainer(pc, &ioPtr, &recoCont); // TODO: use this helper here + // o2::trd::getRecoInputContainer(pc, &ioPtr, &recoCont, useMC); // TODO: use this helper here + } + + if (maskTrk[GID::ITSTPCTRD] && ioPtr.nTRDTracksITSTPCTRD == 0) { + const auto& trdTracks = recoCont.getITSTPCTRDTracks(); + ioPtr.nTRDTracksITSTPCTRD = trdTracks.size(); +#warning fixme + //ioPtr.trdTracksITSTPCTRD = trdTracks.data(); + } + + if (maskTrk[GID::TPCTRD] && ioPtr.nTRDTracksTPCTRD == 0) { + const auto& trdTracks = recoCont.getTPCTRDTracks(); + ioPtr.nTRDTracksTPCTRD = trdTracks.size(); + //ioPtr.trdTracksTPCTRD = trdTracks.data(); } return std::move(retVal); From 4f88b7ee121828ce35059140681ba9bef75950b4 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 6 May 2021 13:53:17 +0200 Subject: [PATCH 426/770] GPU: Move GPUTRDTrack from TRDTracking into DataTypes --- .../TRD/include/DataFormatsTRD/TrackTRD.h | 24 +++++++++++++++++++ GPU/GPUTracking/CMakeLists.txt | 19 +++++++++++---- .../DataTypes/GPUTRDInterfaceO2Track.h | 15 ++++++++---- .../GPUTRDO2BaseTrack.h | 0 .../GPUTRDTrack.cxx | 7 ++++-- .../{TRDTracking => DataTypes}/GPUTRDTrack.h | 10 ++++---- GPU/GPUTracking/DataTypes/GPUTRDTrackO2.cxx | 20 ++++++++++++++++ .../Definitions/GPUDefConstantsAndSettings.h | 15 +++++++----- GPU/GPUTracking/ITS/GPUITSTrack.h | 3 ++- GPU/GPUTracking/Merger/GPUTPCGMMergedTrack.h | 6 ++--- GPU/GPUTracking/Merger/GPUTPCGMMergerTypes.h | 6 +++++ GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx | 2 +- GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h | 9 ++----- .../Merger/GPUTPCGMTracksToTPCSeeds.cxx | 3 ++- .../TRDTracking/GPUTRDInterfaces.h | 12 ++++++++-- GPU/GPUTracking/TRDTracking/GPUTRDTracker.h | 1 + 16 files changed, 115 insertions(+), 37 deletions(-) create mode 100644 DataFormats/Detectors/TRD/include/DataFormatsTRD/TrackTRD.h rename GPU/GPUTracking/{TRDTracking => DataTypes}/GPUTRDO2BaseTrack.h (100%) rename GPU/GPUTracking/{TRDTracking => DataTypes}/GPUTRDTrack.cxx (96%) rename GPU/GPUTracking/{TRDTracking => DataTypes}/GPUTRDTrack.h (97%) create mode 100644 GPU/GPUTracking/DataTypes/GPUTRDTrackO2.cxx diff --git a/DataFormats/Detectors/TRD/include/DataFormatsTRD/TrackTRD.h b/DataFormats/Detectors/TRD/include/DataFormatsTRD/TrackTRD.h new file mode 100644 index 0000000000000..77ffbfbd133ee --- /dev/null +++ b/DataFormats/Detectors/TRD/include/DataFormatsTRD/TrackTRD.h @@ -0,0 +1,24 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file TrackTRD.h +/// \author David Rohr + +#ifndef O2_DATAFORMATS_TRACK_TRD_H +#define O2_DATAFORMATS_TRACK_TRD_H + +#include "GPUTRDTrack.h" + +namespace o2::trd +{ + using TrackTRD = o2::gpu::GPUTRDTrack; +} // namespace o2::trd + +#endif // O2_DATAFORMATS_TRACK_TRD_H diff --git a/GPU/GPUTracking/CMakeLists.txt b/GPU/GPUTracking/CMakeLists.txt index 11eef4e81d129..a05bc8c9e5915 100644 --- a/GPU/GPUTracking/CMakeLists.txt +++ b/GPU/GPUTracking/CMakeLists.txt @@ -55,12 +55,15 @@ set(SRCS Merger/GPUTPCGMPhysicalTrackModel.cxx Merger/GPUTPCGMPolynomialField.cxx Merger/GPUTPCGMPolynomialFieldManager.cxx - TRDTracking/GPUTRDTrack.cxx + DataTypes/GPUTRDTrack.cxx TRDTracking/GPUTRDTracker.cxx TRDTracking/GPUTRDTrackletWord.cxx TRDTracking/GPUTRDTrackerKernels.cxx Base/GPUParam.cxx) +set(SRCS_O2_DATATYPES + DataTypes/GPUTRDTrackO2.cxx) + set(SRCS_NO_CINT DataTypes/GPUDataTypes.cxx DataTypes/GPUMemorySizeScalers.cxx @@ -108,7 +111,6 @@ set(HDRS_INSTALL DataTypes/GPUTRDDef.h DataTypes/GPUSettings.h TRDTracking/GPUTRDTrackPoint.h - TRDTracking/GPUTRDTrack.h TRDTracking/GPUTRDSpacePoint.h TRDTracking/GPUTRDTrackData.h TRDTracking/GPUTRDTrackPoint.h @@ -154,7 +156,7 @@ set(HDRS_INSTALL if(ALIGPU_BUILD_TYPE STREQUAL "O2") set(SRCS ${SRCS} Interface/GPUO2InterfaceConfigurableParam.cxx) set(HDRS_CINT_O2 ${HDRS_CINT_O2} DataTypes/TPCdEdxCalibrationSplines.h Interface/GPUO2InterfaceConfigurableParam.h) - set(HDRS_CINT_O2_ADDITIONAL DataTypes/GPUSettings.h Definitions/GPUSettingsList.h DataTypes/GPUDataTypes.h TRDTracking/GPUTRDTrack.h TRDTracking/GPUTRDO2BaseTrack.h) # Manual dependencies for ROOT dictionary generation + set(HDRS_CINT_O2_ADDITIONAL DataTypes/GPUSettings.h Definitions/GPUSettingsList.h DataTypes/GPUDataTypes.h DataTypes/GPUTRDTrack.h DataTypes/GPUTRDO2BaseTrack.h) # Manual dependencies for ROOT dictionary generation endif() # Sources for O2 and for Standalone if requested in config file @@ -208,7 +210,7 @@ if(ALIGPU_BUILD_TYPE STREQUAL "O2" OR CONFIG_O2_EXTENSIONS) TPCClusterFinder/GPUTPCClusterFinderKernels.h TPCClusterFinder/PackedCharge.h TPCClusterFinder/GPUTPCCFChainContext.h - TRDTracking/GPUTRDO2BaseTrack.h) + DataTypes/GPUTRDO2BaseTrack.h) endif() # Sources only for AliRoot @@ -267,16 +269,23 @@ endif() # Main CMake part for O2 if(ALIGPU_BUILD_TYPE STREQUAL "O2") o2_add_library(GPUDataTypeHeaders + TARGETVARNAME targetName PUBLIC_INCLUDE_DIRECTORIES . Definitions DataTypes PUBLIC_LINK_LIBRARIES O2::GPUCommon - SOURCES utils/EmptyFile.cxx) + O2::ReconstructionDataFormats + PRIVATE_LINK_LIBRARIES O2::DataFormatsTPC + SOURCES ${SRCS_O2_DATATYPES}) +target_compile_definitions(${targetName} PRIVATE GPUCA_O2_LIB + GPUCA_TPC_GEOMETRY_O2 HAVE_O2HEADERS) + o2_add_library(${MODULE} TARGETVARNAME targetName PUBLIC_LINK_LIBRARIES O2::GPUCommon O2::GPUUtils + O2::GPUDataTypeHeaders O2::DataFormatsTPC O2::DataFormatsTOF O2::TPCBase diff --git a/GPU/GPUTracking/DataTypes/GPUTRDInterfaceO2Track.h b/GPU/GPUTracking/DataTypes/GPUTRDInterfaceO2Track.h index 4a14e185d25da..36fdb23f1a4e5 100644 --- a/GPU/GPUTracking/DataTypes/GPUTRDInterfaceO2Track.h +++ b/GPU/GPUTracking/DataTypes/GPUTRDInterfaceO2Track.h @@ -15,13 +15,18 @@ #define GPUTRDINTERFACEO2TRACK_H // This is the interface for the GPUTRDTrack based on the O2 track type - +#include "GPUCommonDef.h" namespace GPUCA_NAMESPACE { namespace gpu { template class trackInterface; +class GPUTPCGMMergedTrack; +namespace gputpcgmmergertypes +{ +struct GPUTPCOuterParam; +} // namespace gputpcgmmergertypes } // namespace gpu } // namespace GPUCA_NAMESPACE @@ -33,7 +38,6 @@ class trackInterface; namespace GPUCA_NAMESPACE { - namespace gpu { @@ -81,8 +85,8 @@ class trackInterface : public GPUTRDO2BaseTrack setCov(cov[i], i); } } - GPUdi() trackInterface(const GPUTPCGMMergedTrack& trk) { set(trk.OuterParam().X, trk.OuterParam().alpha, trk.OuterParam().P, trk.OuterParam().C); } - GPUdi() trackInterface(const GPUTPCGMTrackParam::GPUTPCOuterParam& param) { set(param.X, param.alpha, param.P, param.C); } + GPUd() trackInterface(const GPUTPCGMMergedTrack& trk); + GPUd() trackInterface(const gputpcgmmergertypes::GPUTPCOuterParam& param); GPUdi() const float* getPar() const { return getParams(); } GPUdi() float getTime() const { return mTime; } @@ -107,4 +111,7 @@ class trackInterface : public GPUTRDO2BaseTrack float mZShift{0.f}; // calculated new for each TRD trigger candidate for this track }; +} // namespace gpu +} // namespace GPUCA_NAMESPACE + #endif diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDO2BaseTrack.h b/GPU/GPUTracking/DataTypes/GPUTRDO2BaseTrack.h similarity index 100% rename from GPU/GPUTracking/TRDTracking/GPUTRDO2BaseTrack.h rename to GPU/GPUTracking/DataTypes/GPUTRDO2BaseTrack.h diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx b/GPU/GPUTracking/DataTypes/GPUTRDTrack.cxx similarity index 96% rename from GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx rename to GPU/GPUTracking/DataTypes/GPUTRDTrack.cxx index 0e3f49eebacd1..949f9a053ea7f 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTrack.cxx +++ b/GPU/GPUTracking/DataTypes/GPUTRDTrack.cxx @@ -12,6 +12,9 @@ /// \author Ole Schmidt, Sergey Gorbunov #include "GPUTRDTrack.h" +#if !defined(GPU_TRD_TRACK_O2) +#include "GPUTRDInterfaces.h" +#endif using namespace GPUCA_NAMESPACE::gpu; @@ -222,7 +225,7 @@ GPUd() int GPUTRDTrack_t::GetNmissingConsecLayers(int iLayer) const return res; } -#ifndef GPUCA_GPUCODE +#if !defined(GPUCA_GPUCODE) && !defined(GPU_TRD_TRACK_O2) namespace GPUCA_NAMESPACE { namespace gpu @@ -230,7 +233,7 @@ namespace gpu #ifdef GPUCA_ALIROOT_LIB // Instantiate AliRoot track version template class GPUTRDTrack_t>; #endif -#ifdef HAVE_O2HEADERS // Instantiate O2 track version +#if defined(HAVE_O2HEADERS) && !defined(GPUCA_O2_LIB) // Instantiate O2 track version, for O2 this happens in GPUTRDTrackO2.cxx template class GPUTRDTrack_t>; #endif template class GPUTRDTrack_t>; // Always instatiate GM track version diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTrack.h b/GPU/GPUTracking/DataTypes/GPUTRDTrack.h similarity index 97% rename from GPU/GPUTracking/TRDTracking/GPUTRDTrack.h rename to GPU/GPUTracking/DataTypes/GPUTRDTrack.h index a526b1d770eea..89a3c05a86725 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTrack.h +++ b/GPU/GPUTracking/DataTypes/GPUTRDTrack.h @@ -15,7 +15,7 @@ #define GPUTRDTRACK_H #include "GPUTRDDef.h" -#include "GPUDef.h" +#include "GPUCommonDef.h" struct GPUTRDTrackDataRecord; class AliHLTExternalTrackParam; @@ -25,11 +25,11 @@ namespace o2 namespace tpc { class TrackTPC; -} +} // namespace tpc namespace dataformats { class TrackTPCITS; -} +} // namespace dataformats } // namespace o2 //_____________________________________________________________________________ @@ -40,10 +40,10 @@ namespace gpu { template class GPUTRDTrack_t; -} +} // namespace gpu } // namespace GPUCA_NAMESPACE #else -#include "GPUTRDInterfaces.h" +#include "GPUTRDInterfaceO2Track.h" namespace GPUCA_NAMESPACE { diff --git a/GPU/GPUTracking/DataTypes/GPUTRDTrackO2.cxx b/GPU/GPUTracking/DataTypes/GPUTRDTrackO2.cxx new file mode 100644 index 0000000000000..169895d497034 --- /dev/null +++ b/GPU/GPUTracking/DataTypes/GPUTRDTrackO2.cxx @@ -0,0 +1,20 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file GPUTRDTrackO2.cxx +/// \author David Rohr + +#define GPU_TRD_TRACK_O2 +#include "GPUTRDTrack.cxx" + +namespace o2::gpu +{ +template class GPUTRDTrack_t>; +} // namespace o2::gpu diff --git a/GPU/GPUTracking/Definitions/GPUDefConstantsAndSettings.h b/GPU/GPUTracking/Definitions/GPUDefConstantsAndSettings.h index e298cb51e8631..21857483dad79 100644 --- a/GPU/GPUTracking/Definitions/GPUDefConstantsAndSettings.h +++ b/GPU/GPUTracking/Definitions/GPUDefConstantsAndSettings.h @@ -58,12 +58,15 @@ #define GPUCA_TPC_COMP_CHUNK_SIZE 1024 // Chunk size of sorted unattached TPC cluster in compression -#if defined(HAVE_O2HEADERS) && (!defined(__OPENCL__) || defined(__OPENCLCPP__)) && !(defined(ROOT_VERSION_CODE) && ROOT_VERSION_CODE < 393216) - //Use definitions from the O2 headers if available for nicer code and type safety - #include "DataFormatsTPC/Constants.h" - #define GPUCA_NSLICES o2::tpc::constants::MAXSECTOR - #define GPUCA_ROW_COUNT o2::tpc::constants::MAXGLOBALPADROW -#else +#if defined(HAVE_O2HEADERS) && (!defined(__OPENCL__) || defined(__OPENCLCPP__)) && !(defined(ROOT_VERSION_CODE) && ROOT_VERSION_CODE < 393216) && defined(__has_include) + #if __has_include("DataFormatsTPC/Constants.h") + //Use definitions from the O2 headers if available for nicer code and type safety + #include "DataFormatsTPC/Constants.h" + #define GPUCA_NSLICES o2::tpc::constants::MAXSECTOR + #define GPUCA_ROW_COUNT o2::tpc::constants::MAXGLOBALPADROW + #endif +#endif +#ifndef GPUCA_NSLICES //Define it manually, if O2 headers not available, ROOT5, and OpenCL 1.2, which do not know C++11. #define GPUCA_NSLICES 36 #ifdef GPUCA_TPC_GEOMETRY_O2 diff --git a/GPU/GPUTracking/ITS/GPUITSTrack.h b/GPU/GPUTracking/ITS/GPUITSTrack.h index 3ced243587ba5..c801f4f96ad48 100644 --- a/GPU/GPUTracking/ITS/GPUITSTrack.h +++ b/GPU/GPUTracking/ITS/GPUITSTrack.h @@ -14,6 +14,7 @@ #ifndef GPUITSTRACK_H #define GPUITSTRACK_H +#include "GPUTPCGMMergerTypes.h" #include "GPUTPCGMTrackParam.h" namespace GPUCA_NAMESPACE::gpu @@ -21,7 +22,7 @@ namespace GPUCA_NAMESPACE::gpu class GPUITSTrack : public GPUTPCGMTrackParam { public: - GPUTPCGMTrackParam::GPUTPCOuterParam mOuterParam; + gputpcgmmergertypes::GPUTPCOuterParam mOuterParam; float mAlpha; int mClusters[7]; }; diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMergedTrack.h b/GPU/GPUTracking/Merger/GPUTPCGMMergedTrack.h index eeed5d24cc82f..af48eea088347 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMergedTrack.h +++ b/GPU/GPUTracking/Merger/GPUTPCGMMergedTrack.h @@ -103,12 +103,12 @@ class GPUTPCGMMergedTrack GPUd() void SetLegs(unsigned char v) { mLegs = v; } GPUd() unsigned char Legs() const { return mLegs; } - GPUd() const GPUTPCGMTrackParam::GPUTPCOuterParam& OuterParam() const { return mOuterParam; } - GPUd() GPUTPCGMTrackParam::GPUTPCOuterParam& OuterParam() { return mOuterParam; } + GPUd() const gputpcgmmergertypes::GPUTPCOuterParam& OuterParam() const { return mOuterParam; } + GPUd() gputpcgmmergertypes::GPUTPCOuterParam& OuterParam() { return mOuterParam; } private: GPUTPCGMTrackParam mParam; //* fitted track parameters - GPUTPCGMTrackParam::GPUTPCOuterParam mOuterParam; //* outer param + gputpcgmmergertypes::GPUTPCOuterParam mOuterParam; //* outer param float mAlpha; //* alpha angle float mLastX; //* outer X diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMergerTypes.h b/GPU/GPUTracking/Merger/GPUTPCGMMergerTypes.h index 709023a4037da..85b337c140648 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMergerTypes.h +++ b/GPU/GPUTracking/Merger/GPUTPCGMMergerTypes.h @@ -52,6 +52,12 @@ struct GPUTPCGMBorderRange { float fMin, fMax; }; +struct GPUTPCOuterParam { + float X, alpha; + float P[5]; + float C[15]; +}; + } // namespace gputpcgmmergertypes } // namespace gpu } // namespace GPUCA_NAMESPACE diff --git a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx index 415fa6414d5bb..2a564136a3ac2 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx @@ -58,7 +58,7 @@ using namespace o2::tpc; static constexpr float kDeg2Rad = M_PI / 180.f; static constexpr float kSectAngle = 2 * M_PI / 18.f; -GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger* GPUrestrict() merger, int iTrk, GPUTPCGMMergedTrackHit* GPUrestrict() clusters, GPUTPCGMMergedTrackHitXYZ* GPUrestrict() clustersXYZ, int& GPUrestrict() N, int& GPUrestrict() NTolerated, float& GPUrestrict() Alpha, int attempt, float maxSinPhi, GPUTPCOuterParam* GPUrestrict() outerParam) +GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger* GPUrestrict() merger, int iTrk, GPUTPCGMMergedTrackHit* GPUrestrict() clusters, GPUTPCGMMergedTrackHitXYZ* GPUrestrict() clustersXYZ, int& GPUrestrict() N, int& GPUrestrict() NTolerated, float& GPUrestrict() Alpha, int attempt, float maxSinPhi, gputpcgmmergertypes::GPUTPCOuterParam* GPUrestrict() outerParam) { const GPUParam& GPUrestrict() param = merger->Param(); diff --git a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h index 5993bcac1d4f7..9f2b4a1a0bef1 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h +++ b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h @@ -16,6 +16,7 @@ #include "GPUTPCDef.h" #include "GPUTPCGMMergedTrackHit.h" +#include "GPUTPCGMMergerTypes.h" #include "GPUCommonMath.h" #include "GPUdEdxInfo.h" @@ -47,12 +48,6 @@ class GPUTPCGMPropagator; class GPUTPCGMTrackParam { public: - struct GPUTPCOuterParam { - float X, alpha; - float P[5]; - float C[15]; - }; - GPUd() float& X() { return mX; @@ -147,7 +142,7 @@ class GPUTPCGMTrackParam GPUd() bool CheckNumericalQuality(float overrideCovYY = -1.f) const; GPUd() bool CheckCov() const; - GPUd() bool Fit(GPUTPCGMMerger* merger, int iTrk, GPUTPCGMMergedTrackHit* clusters, GPUTPCGMMergedTrackHitXYZ* clustersXYZ, int& N, int& NTolerated, float& Alpha, int attempt = 0, float maxSinPhi = GPUCA_MAX_SIN_PHI, GPUTPCOuterParam* outerParam = nullptr); + GPUd() bool Fit(GPUTPCGMMerger* merger, int iTrk, GPUTPCGMMergedTrackHit* clusters, GPUTPCGMMergedTrackHitXYZ* clustersXYZ, int& N, int& NTolerated, float& Alpha, int attempt = 0, float maxSinPhi = GPUCA_MAX_SIN_PHI, gputpcgmmergertypes::GPUTPCOuterParam* outerParam = nullptr); GPUd() void MoveToReference(GPUTPCGMPropagator& prop, const GPUParam& param, float& alpha); GPUd() void MirrorTo(GPUTPCGMPropagator& prop, float toY, float toZ, bool inFlyDirection, const GPUParam& param, unsigned char row, unsigned char clusterState, bool mirrorParameters); GPUd() int MergeDoubleRowClusters(int& ihit, int wayDirection, GPUTPCGMMergedTrackHit* clusters, GPUTPCGMMergedTrackHitXYZ* clustersXYZ, const GPUTPCGMMerger* merger, GPUTPCGMPropagator& prop, float& xx, float& yy, float& zz, int maxN, float clAlpha, unsigned char& clusterState, bool rejectChi2); diff --git a/GPU/GPUTracking/Merger/GPUTPCGMTracksToTPCSeeds.cxx b/GPU/GPUTracking/Merger/GPUTPCGMTracksToTPCSeeds.cxx index 472edf9719d77..1b2ed2271f29b 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMTracksToTPCSeeds.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMTracksToTPCSeeds.cxx @@ -13,6 +13,7 @@ #include "GPUTPCGMTracksToTPCSeeds.h" #include "GPUTPCGlobalMergerComponent.h" +#include "GPUTPCGMMergerTypes.h" #include "GPUTPCGMMerger.h" #include "GPULogging.h" #include "AliTPCtracker.h" @@ -120,7 +121,7 @@ void GPUTPCGMTracksToTPCSeeds::UpdateParamsOuter(TObjArray* seeds) return; } AliTPCseed* seed = (AliTPCseed*)seeds->UncheckedAt(index++); - const GPUTPCGMTrackParam::GPUTPCGMTrackParam::GPUTPCOuterParam& param = track.OuterParam(); + const gputpcgmmergertypes::GPUTPCOuterParam& param = track.OuterParam(); seed->Set(param.X, param.alpha, param.P, param.C); } } diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h index 6602356d54fd8..d655a1da80a14 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h @@ -60,7 +60,7 @@ class trackInterface : public AliExternalTrackParam { Set(trk.GetParam().GetX(), trk.GetAlpha(), trk.GetParam().GetPar(), trk.GetParam().GetCov()); } - trackInterface(const GPUTPCGMTrackParam::GPUTPCOuterParam& param) : AliExternalTrackParam() + trackInterface(const gputpcgmmergertypes::GPUTPCOuterParam& param) : AliExternalTrackParam() { Set(param.X, param.alpha, param.P, param.C); } @@ -139,6 +139,14 @@ class propagatorInterface : public AliTrackerBase #include "DetectorsBase/Propagator.h" // when included after GPUTRDInterfaceO2Track.h the build fails #include "GPUTRDInterfaceO2Track.h" +namespace GPUCA_NAMESPACE +{ +namespace gpu +{ + +GPUdi() trackInterface::trackInterface(const GPUTPCGMMergedTrack& trk) { set(trk.OuterParam().X, trk.OuterParam().alpha, trk.OuterParam().P, trk.OuterParam().C); } +GPUdi() trackInterface::trackInterface(const gputpcgmmergertypes::GPUTPCOuterParam& param) { set(param.X, param.alpha, param.P, param.C); } + template <> class propagatorInterface { @@ -206,7 +214,7 @@ class trackInterface : public GPUTPCGMTrackParam GPUdDefault() trackInterface() = default; GPUd() trackInterface(const GPUTPCGMTrackParam& param) CON_DELETE; GPUd() trackInterface(const GPUTPCGMMergedTrack& trk) : GPUTPCGMTrackParam(trk.GetParam()), mAlpha(trk.GetAlpha()) {} - GPUd() trackInterface(const GPUTPCGMTrackParam::GPUTPCOuterParam& param) : GPUTPCGMTrackParam(), mAlpha(param.alpha) + GPUd() trackInterface(const gputpcgmmergertypes::GPUTPCOuterParam& param) : GPUTPCGMTrackParam(), mAlpha(param.alpha) { SetX(param.X); for (int i = 0; i < 5; i++) { diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h index 1ed22277f5d1d..0bd19213b4f1c 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.h @@ -23,6 +23,7 @@ #include "GPUTRDTrack.h" #include "GPUTRDSpacePoint.h" #include "GPULogging.h" +#include "GPUTRDInterfaces.h" #ifndef GPUCA_GPUCODE_DEVICE #include From fb09c9c92c9289887d37af52e55f64a524c918ca Mon Sep 17 00:00:00 2001 From: David Rohr Date: Thu, 6 May 2021 15:24:15 +0200 Subject: [PATCH 427/770] Add o2::trd::TrackTRD class as alias to GPUTRDTrack --- .../GlobalTracking/src/RecoContainer.cxx | 6 +++--- .../TRD/include/DataFormatsTRD/TrackTRD.h | 17 ++++++++++++++--- GPU/Workflow/helper/src/GPUWorkflowHelper.cxx | 10 +++++----- 3 files changed, 22 insertions(+), 11 deletions(-) diff --git a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx index 0fb16c1362406..596457f7f4385 100644 --- a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx +++ b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx @@ -26,6 +26,7 @@ #include "DataFormatsTOF/Cluster.h" #include "DataFormatsITSMFT/ROFRecord.h" #include "DataFormatsFT0/RecPoints.h" +#include "DataFormatsTRD/TrackTRD.h" #include "ReconstructionDataFormats/TrackTPCITS.h" #include "ReconstructionDataFormats/TrackTPCTOF.h" #include "ReconstructionDataFormats/MatchInfoTOF.h" @@ -311,13 +312,12 @@ void RecoContainer::addITSTPCTracks(ProcessingContext& pc, bool mc) void RecoContainer::addITSTPCTRDTracks(ProcessingContext& pc, bool mc) { -#warning fix TrackParCov - tracksPool.registerContainer(pc.inputs().get>("trackITSTPCTRD"), GTrackID::ITSTPCTRD); + tracksPool.registerContainer(pc.inputs().get>("trackITSTPCTRD"), GTrackID::ITSTPCTRD); } void RecoContainer::addTPCTRDTracks(ProcessingContext& pc, bool mc) { - tracksPool.registerContainer(pc.inputs().get>("trackTPCTRD"), GTrackID::TPCTRD); + tracksPool.registerContainer(pc.inputs().get>("trackTPCTRD"), GTrackID::TPCTRD); } //__________________________________________________________ diff --git a/DataFormats/Detectors/TRD/include/DataFormatsTRD/TrackTRD.h b/DataFormats/Detectors/TRD/include/DataFormatsTRD/TrackTRD.h index 77ffbfbd133ee..eeab3e4e4dc18 100644 --- a/DataFormats/Detectors/TRD/include/DataFormatsTRD/TrackTRD.h +++ b/DataFormats/Detectors/TRD/include/DataFormatsTRD/TrackTRD.h @@ -16,9 +16,20 @@ #include "GPUTRDTrack.h" -namespace o2::trd +namespace o2 { - using TrackTRD = o2::gpu::GPUTRDTrack; -} // namespace o2::trd +namespace trd +{ +using TrackTRD = o2::gpu::GPUTRDTrack; +} // namespace trd +namespace framework +{ +template +struct is_messageable; +template <> +struct is_messageable : std::true_type { +}; +} // namespace framework +} // namespace o2 #endif // O2_DATAFORMATS_TRACK_TRD_H diff --git a/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx b/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx index 6a0866a37eeb7..084215dcf3c59 100644 --- a/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx +++ b/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx @@ -10,6 +10,7 @@ #include "GPUWorkflowHelper/GPUWorkflowHelper.h" #include "DataFormatsTRD/RecoInputContainer.h" +#include "DataFormatsTRD/TrackTRD.h" #include "ITStracking/IOUtils.h" #include "DataFormatsTPC/WorkflowHelper.h" using namespace o2::globaltracking; @@ -115,16 +116,15 @@ std::shared_ptr GPUWorkflowHelper::fi } if (maskTrk[GID::ITSTPCTRD] && ioPtr.nTRDTracksITSTPCTRD == 0) { - const auto& trdTracks = recoCont.getITSTPCTRDTracks(); + const auto& trdTracks = recoCont.getITSTPCTRDTracks(); ioPtr.nTRDTracksITSTPCTRD = trdTracks.size(); -#warning fixme - //ioPtr.trdTracksITSTPCTRD = trdTracks.data(); + ioPtr.trdTracksITSTPCTRD = trdTracks.data(); } if (maskTrk[GID::TPCTRD] && ioPtr.nTRDTracksTPCTRD == 0) { - const auto& trdTracks = recoCont.getTPCTRDTracks(); + const auto& trdTracks = recoCont.getTPCTRDTracks(); ioPtr.nTRDTracksTPCTRD = trdTracks.size(); - //ioPtr.trdTracksTPCTRD = trdTracks.data(); + ioPtr.trdTracksTPCTRD = trdTracks.data(); } return std::move(retVal); From 32bd6248a1dcf9e0ce9a25552f526408f01b5e22 Mon Sep 17 00:00:00 2001 From: Fabio Catalano Date: Fri, 7 May 2021 10:16:55 +0200 Subject: [PATCH 428/770] Fix file name building --- DataFormats/Detectors/Common/src/NameConf.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DataFormats/Detectors/Common/src/NameConf.cxx b/DataFormats/Detectors/Common/src/NameConf.cxx index ebebcabee0e04..04c90f55d5fd6 100644 --- a/DataFormats/Detectors/Common/src/NameConf.cxx +++ b/DataFormats/Detectors/Common/src/NameConf.cxx @@ -21,7 +21,7 @@ std::string NameConf::buildFileName(const std::string_view prefix, const std::st const std::string_view extension, const std::string_view optDir) { if (o2::utils::Str::pathIsDirectory(prefix)) { // if path is directory, just add to default name, ignoring optional directory optDir argument - return o2::utils::Str::concat_string(prefix, "/", defPrefix, delimiter, defName, extension); + return o2::utils::Str::concat_string(prefix, "/", defPrefix, delimiter, defName, '.', extension); } else if (!prefix.empty() && o2::utils::Str::pathExists(prefix)) { // explicit file path is provided, use it directly return std::string(prefix); } From 2fee5d768eb08dfd2e9b34c8f87414583122c86b Mon Sep 17 00:00:00 2001 From: shahoian Date: Thu, 6 May 2021 13:31:40 +0200 Subject: [PATCH 429/770] LOG only 1st instance of new Alpide decoding error, show full report in the end Direct logging of decoding errors from AlpideCoder is changed to DEBUG level. Instead, each time a new Alpid decoding error type on the given GBT link is encountered for the 1st time, a LOG(ERROR) will be produced. The decoded->printReport in the EOS of STFDecoder will be now called with per link decoding statistics with skipEmpy option, showing statistics and errors only for links which registered some error. --- .../ITSMFTReconstruction/AlpideCoder.h | 9 ++- .../ITSMFTReconstruction/DecodingStat.h | 21 ++---- .../include/ITSMFTReconstruction/PixelData.h | 12 ++-- .../ITSMFTReconstruction/RawPixelDecoder.h | 2 +- .../ITSMFTReconstruction/RawPixelReader.h | 4 +- .../common/reconstruction/src/AlpideCoder.cxx | 9 --- .../reconstruction/src/DecodingStat.cxx | 66 ++++++++++++------- .../common/reconstruction/src/GBTLink.cxx | 7 +- .../reconstruction/src/RUDecodeData.cxx | 2 +- .../reconstruction/src/RawPixelDecoder.cxx | 9 ++- 10 files changed, 73 insertions(+), 68 deletions(-) diff --git a/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/AlpideCoder.h b/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/AlpideCoder.h index 57de757a01253..cb80bfebc791c 100644 --- a/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/AlpideCoder.h +++ b/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/AlpideCoder.h @@ -273,8 +273,7 @@ class AlpideCoder #ifdef ALPIDE_DECODING_STAT chipData.setError(ChipStat::NoDataFound); #endif - LOG(ERROR) << "Expected DataShort or DataLong mask, got : " << dataS; - return Error; + return unexpectedEOF(fmt::format("Expected DataShort or DataLong mask, got {:x}", dataS)); } expectInp = ExpectChipTrailer | ExpectData | ExpectRegion; continue; // end of DATA(SHORT or LONG) processing @@ -415,7 +414,11 @@ class AlpideCoder void resetMap(); ///< error message on unexpected EOF - static int unexpectedEOF(const std::string& message); + static int unexpectedEOF(const std::string& message) + { + LOG(DEBUG) << message; + return Error; + } // ===================================================================== // diff --git a/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/DecodingStat.h b/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/DecodingStat.h index 260160052ab2d..21bab6057ad9c 100644 --- a/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/DecodingStat.h +++ b/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/DecodingStat.h @@ -57,11 +57,11 @@ struct ChipStat { "Unknow word" // UnknownWord }; - uint16_t chipID = 0; + uint16_t id = -1; size_t nHits = 0; std::array errorCounts = {}; ChipStat() = default; - ChipStat(uint16_t id) : chipID(id) {} + ChipStat(uint16_t _id) : id(id) {} void clear() { @@ -70,19 +70,8 @@ struct ChipStat { } uint32_t getNErrors() const; - - void addErrors(uint32_t mask) - { - if (mask) { - for (int i = NErrorsDefined; i--;) { - if (mask & (0x1 << i)) { - errorCounts[i]++; - } - } - } - } - - void print(bool skipEmpty = true) const; + void addErrors(uint32_t mask, uint16_t chID); + void print(bool skipNoErr = true, const std::string& pref = "FEEID") const; ClassDefNV(ChipStat, 1); }; @@ -151,7 +140,7 @@ struct GBTLinkDecodingStat { packetStates.fill(0); } - void print(bool skipEmpty = true) const; + void print(bool skipNoErr = true) const; ClassDefNV(GBTLinkDecodingStat, 2); }; diff --git a/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/PixelData.h b/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/PixelData.h index 9472b40263bfd..24764e5432af3 100644 --- a/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/PixelData.h +++ b/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/PixelData.h @@ -135,15 +135,15 @@ class ChipPixelData void swap(ChipPixelData& other) { // swap content of two objects - mPixels.swap(other.mPixels); - std::swap(mROFrame, other.mROFrame); std::swap(mROFlags, other.mROFlags); + std::swap(mChipID, other.mChipID); + std::swap(mROFrame, other.mROFrame); + std::swap(mFirstUnmasked, other.mFirstUnmasked); // strictly speaking, not needed + std::swap(mStartID, other.mStartID); // strictly speaking, not needed std::swap(mTrigger, other.mTrigger); + std::swap(mErrors, other.mErrors); std::swap(mInteractionRecord, other.mInteractionRecord); - std::swap(mChipID, other.mChipID); - // strictly speaking, swapping the data below is not needed - std::swap(mStartID, other.mStartID); - std::swap(mFirstUnmasked, other.mFirstUnmasked); + mPixels.swap(other.mPixels); } void maskFiredInSample(const ChipPixelData& sample) diff --git a/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/RawPixelDecoder.h b/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/RawPixelDecoder.h index 7fd344993abad..9eadeeac76b39 100644 --- a/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/RawPixelDecoder.h +++ b/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/RawPixelDecoder.h @@ -85,7 +85,7 @@ class RawPixelDecoder final : public PixelReader void setVerbosity(int v); int getVerbosity() const { return mVerbosity; } - void printReport(bool decstat = false, bool skipEmpty = true) const; + void printReport(bool decstat = true, bool skipNoErr = true) const; void clearStat(); diff --git a/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/RawPixelReader.h b/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/RawPixelReader.h index baca178dfd0f6..3e8e036377538 100644 --- a/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/RawPixelReader.h +++ b/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/RawPixelReader.h @@ -85,7 +85,7 @@ struct RawDecodingStat { errorCounts.fill(0); } - void print(bool skipEmpty = true) const + void print(bool skipNoErr = true) const { printf("\nDecoding statistics\n"); printf("%llu bytes for %llu RUs processed in %llu pages for %llu triggers\n", (ULL)nBytesProcessed, (ULL)nRUsProcessed, @@ -97,7 +97,7 @@ struct RawDecodingStat { } printf("Decoding errors: %d\n", nErr); for (int i = 0; i < NErrorsDefined; i++) { - if (!skipEmpty || errorCounts[i]) { + if (!skipNoErr || errorCounts[i]) { printf("%-70s: %d\n", ErrNames[i].data(), errorCounts[i]); } } diff --git a/Detectors/ITSMFT/common/reconstruction/src/AlpideCoder.cxx b/Detectors/ITSMFT/common/reconstruction/src/AlpideCoder.cxx index 8008767b69d08..4a39c6674bfbb 100644 --- a/Detectors/ITSMFT/common/reconstruction/src/AlpideCoder.cxx +++ b/Detectors/ITSMFT/common/reconstruction/src/AlpideCoder.cxx @@ -12,8 +12,6 @@ /// \brief Implementation of the ALPIDE data decoding/encoding #include "ITSMFTReconstruction/AlpideCoder.h" -#include -#include using namespace o2::itsmft; @@ -146,10 +144,3 @@ void AlpideCoder::resetMap() mFirstInRow.clear(); mPix2Encode.clear(); } - -//_____________________________________ -int AlpideCoder::unexpectedEOF(const std::string& message) -{ - LOG(ERROR) << message; - return Error; -} diff --git a/Detectors/ITSMFT/common/reconstruction/src/DecodingStat.cxx b/Detectors/ITSMFT/common/reconstruction/src/DecodingStat.cxx index 295a458cc9a46..0cc702f1f1567 100644 --- a/Detectors/ITSMFT/common/reconstruction/src/DecodingStat.cxx +++ b/Detectors/ITSMFT/common/reconstruction/src/DecodingStat.cxx @@ -19,50 +19,70 @@ using namespace o2::itsmft; constexpr std::array ChipStat::ErrNames; ///_________________________________________________________________ -/// print chip decoding statistics -void ChipStat::print(bool skipEmpty) const +uint32_t ChipStat::getNErrors() const { - uint32_t nErr = 0; + uint32_t nerr = 0; for (int i = NErrorsDefined; i--;) { - nErr += errorCounts[i]; + nerr += errorCounts[i]; } - LOGF(INFO, "Chip#%5d NHits: %9zu errors: %u", chipID, nHits, nErr); - for (int i = 0; i < NErrorsDefined; i++) { - if (!skipEmpty || errorCounts[i]) { - LOGF(INFO, "%-70s: %u", ErrNames[i].data(), errorCounts[i]); + return nerr; +} + +///_________________________________________________________________ +/// print link decoding statistics +void ChipStat::addErrors(uint32_t mask, uint16_t id) +{ + if (mask) { + for (int i = NErrorsDefined; i--;) { + if (mask & (0x1 << i)) { + if (!errorCounts[i]) { + LOGP(ERROR, "New error registered on the link: chip#{}: {}", id, ErrNames[i]); + } + errorCounts[i]++; + } } } } ///_________________________________________________________________ -uint32_t ChipStat::getNErrors() const +/// print chip decoding statistics +void ChipStat::print(bool skipNoErr, const std::string& pref) const { - uint32_t nerr = 0; + uint32_t nErr = 0; for (int i = NErrorsDefined; i--;) { - nerr += errorCounts[i]; + nErr += errorCounts[i]; + } + if (!skipNoErr || nErr) { + LOGP(INFO, "{}#{:x} NHits: {} errors: {}", pref.c_str(), id, nHits, nErr); + for (int i = 0; i < NErrorsDefined; i++) { + if (!skipNoErr || errorCounts[i]) { + LOGP(INFO, "Err.: {}: {}", ErrNames[i].data(), errorCounts[i]); + } + } } - return nerr; } ///_________________________________________________________________ /// print link decoding statistics -void GBTLinkDecodingStat::print(bool skipEmpty) const +void GBTLinkDecodingStat::print(bool skipNoErr) const { int nErr = 0; for (int i = NErrorsDefined; i--;) { nErr += errorCounts[i]; } - LOGF(INFO, "GBTLink#0x%d Packet States Statistics (total packets: %d, triggers: %d)", ruLinkID, nPackets, nTriggers); - for (int i = 0; i < GBTDataTrailer::MaxStateCombinations; i++) { - if (packetStates[i]) { - std::bitset patt(i); - LOGF(INFO, "counts for triggers B[%s] : %d", patt.to_string().c_str(), packetStates[i]); + if (!skipNoErr || nErr) { + LOGP(INFO, "FEEID#{%s} Packet States Statistics (total packets: {}, triggers: {})", ruLinkID, nPackets, nTriggers); + for (int i = 0; i < GBTDataTrailer::MaxStateCombinations; i++) { + if (packetStates[i]) { + std::bitset patt(i); + LOGP(INFO, "counts for triggers B{:s}: {}", patt.to_string().c_str(), packetStates[i]); + } } - } - LOGF(INFO, "Decoding errors: %u", nErr); - for (int i = 0; i < NErrorsDefined; i++) { - if (!skipEmpty || errorCounts[i]) { - LOGF(INFO, "%-70s: %u", ErrNames[i].data(), errorCounts[i]); + LOGP(INFO, "Decoding errors: {}", nErr); + for (int i = 0; i < NErrorsDefined; i++) { + if (!skipNoErr || errorCounts[i]) { + LOGF(INFO, "{<}: {}", ErrNames[i].data(), errorCounts[i]); + } } } } diff --git a/Detectors/ITSMFT/common/reconstruction/src/GBTLink.cxx b/Detectors/ITSMFT/common/reconstruction/src/GBTLink.cxx index efafcf3422abc..bcc2db9410d64 100644 --- a/Detectors/ITSMFT/common/reconstruction/src/GBTLink.cxx +++ b/Detectors/ITSMFT/common/reconstruction/src/GBTLink.cxx @@ -32,6 +32,7 @@ using RDH = o2::header::RAWDataHeader; /// create link with given ids GBTLink::GBTLink(uint16_t _cru, uint16_t _fee, uint8_t _ep, uint8_t _idInCru, uint16_t _chan) : idInCRU(_idInCru), cruID(_cru), feeID(_fee), endPointID(_ep), channelID(_chan) { + chipStat.id = _fee; } ///_________________________________________________________________ @@ -40,8 +41,10 @@ std::string GBTLink::describe() const { std::stringstream ss; ss << "Link cruID=0x" << std::hex << std::setw(4) << std::setfill('0') << cruID << std::dec - << "/lID=" << int(idInCRU) << "/feeID=0x" << std::hex << std::setw(4) << std::setfill('0') << feeID << std::dec - << " lanes: " << std::bitset<28>(lanes).to_string(); + << "/lID=" << int(idInCRU) << "/feeID=0x" << std::hex << std::setw(4) << std::setfill('0') << feeID << std::dec; + if (lanes) { + ss << " lanes: " << std::bitset<28>(lanes).to_string(); + } return ss.str(); } diff --git a/Detectors/ITSMFT/common/reconstruction/src/RUDecodeData.cxx b/Detectors/ITSMFT/common/reconstruction/src/RUDecodeData.cxx index 19f504e48b90e..8bbc2e1929288 100644 --- a/Detectors/ITSMFT/common/reconstruction/src/RUDecodeData.cxx +++ b/Detectors/ITSMFT/common/reconstruction/src/RUDecodeData.cxx @@ -53,7 +53,7 @@ void RUDecodeData::setROFInfo(ChipPixelData* chipData, const GBTLink* lnk) void RUDecodeData::fillChipStatistics(int icab, const ChipPixelData* chipData) { cableLinkPtr[icab]->chipStat.nHits += chipData->getData().size(); - cableLinkPtr[icab]->chipStat.addErrors(chipData->getErrorFlags()); + cableLinkPtr[icab]->chipStat.addErrors(chipData->getErrorFlags(), chipData->getChipID()); } } // namespace itsmft diff --git a/Detectors/ITSMFT/common/reconstruction/src/RawPixelDecoder.cxx b/Detectors/ITSMFT/common/reconstruction/src/RawPixelDecoder.cxx index 1283301e5963a..d4b41cabfe559 100644 --- a/Detectors/ITSMFT/common/reconstruction/src/RawPixelDecoder.cxx +++ b/Detectors/ITSMFT/common/reconstruction/src/RawPixelDecoder.cxx @@ -40,7 +40,7 @@ RawPixelDecoder::RawPixelDecoder() ///______________________________________________________________ /// template -void RawPixelDecoder::printReport(bool decstat, bool skipEmpty) const +void RawPixelDecoder::printReport(bool decstat, bool skipNoErr) const { LOGF(INFO, "%s Decoded %zu hits in %zu non-empty chips in %u ROFs with %d threads", mSelfName, mNPixelsFired, mNChipsFired, mROFCounter, mNThreads); double cpu = 0, real = 0; @@ -60,11 +60,10 @@ void RawPixelDecoder::printReport(bool decstat, bool skipEmpty) const mDecodeNextAuto ? "AutoDecode" : "ExternalCall"); if (decstat) { - LOG(INFO) << "GBT Links decoding statistics"; + LOG(INFO) << "GBT Links decoding statistics" << (skipNoErr ? " (only links with errors are reported)" : ""); for (auto& lnk : mGBTLinks) { - LOG(INFO) << lnk.describe(); - lnk.statistics.print(skipEmpty); - lnk.chipStat.print(skipEmpty); + lnk.statistics.print(skipNoErr); + lnk.chipStat.print(skipNoErr); } } } From 11dcfbc2637664dbba306bbcbd07194af67183f5 Mon Sep 17 00:00:00 2001 From: shahoian Date: Thu, 6 May 2021 15:51:17 +0200 Subject: [PATCH 430/770] Log only 1st instance of new GBT link decoding error Error message will be produces at 1st encounter of given error type on given GBT link. The full error summary with error counts will be printed on EOS. --- .../ITSMFTReconstruction/DecodingStat.h | 2 +- .../common/reconstruction/src/GBTLink.cxx | 60 ++++++++++--------- 2 files changed, 32 insertions(+), 30 deletions(-) diff --git a/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/DecodingStat.h b/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/DecodingStat.h index 21bab6057ad9c..67cf2e592c3ff 100644 --- a/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/DecodingStat.h +++ b/Detectors/ITSMFT/common/reconstruction/include/ITSMFTReconstruction/DecodingStat.h @@ -61,7 +61,7 @@ struct ChipStat { size_t nHits = 0; std::array errorCounts = {}; ChipStat() = default; - ChipStat(uint16_t _id) : id(id) {} + ChipStat(uint16_t _id) : id(_id) {} void clear() { diff --git a/Detectors/ITSMFT/common/reconstruction/src/GBTLink.cxx b/Detectors/ITSMFT/common/reconstruction/src/GBTLink.cxx index bcc2db9410d64..088a2358d561e 100644 --- a/Detectors/ITSMFT/common/reconstruction/src/GBTLink.cxx +++ b/Detectors/ITSMFT/common/reconstruction/src/GBTLink.cxx @@ -140,7 +140,7 @@ GBTLink::ErrorType GBTLink::checkErrorsRDH(const RDH& rdh) ErrorType err = NoError; if (!RDHUtils::checkRDH(rdh, true)) { statistics.errorCounts[GBTLinkDecodingStat::ErrNoRDHAtStart]++; - if (verbosity >= VerboseErrors) { + if (verbosity >= VerboseErrors || statistics.errorCounts[GBTLinkDecodingStat::ErrNoRDHAtStart] == 1) { LOG(ERROR) << describe() << ' ' << statistics.ErrNames[GBTLinkDecodingStat::ErrNoRDHAtStart]; } errorBits |= 0x1 << int(GBTLinkDecodingStat::ErrNoRDHAtStart); @@ -157,7 +157,7 @@ GBTLink::ErrorType GBTLink::checkErrorsRDH(const RDH& rdh) } if ((RDHUtils::getPacketCounter(rdh) > packetCounter + 1) && packetCounter >= 0) { statistics.errorCounts[GBTLinkDecodingStat::ErrPacketCounterJump]++; - if (verbosity >= VerboseErrors) { + if (verbosity >= VerboseErrors || statistics.errorCounts[GBTLinkDecodingStat::ErrPacketCounterJump] == 1) { LOG(ERROR) << describe() << ' ' << statistics.ErrNames[GBTLinkDecodingStat::ErrPacketCounterJump] << " : jump from " << int(packetCounter) << " to " << int(RDHUtils::getPacketCounter(rdh)); } @@ -175,7 +175,7 @@ GBTLink::ErrorType GBTLink::checkErrorsRDHStop(const RDH& rdh) if (format == NewFormat && lastRDH && RDHUtils::getHeartBeatOrbit(*lastRDH) != RDHUtils::getHeartBeatOrbit(rdh) // new HB starts && !RDHUtils::getStop(*lastRDH)) { statistics.errorCounts[GBTLinkDecodingStat::ErrPageNotStopped]++; - if (verbosity >= VerboseErrors) { + if (verbosity >= VerboseErrors || statistics.errorCounts[GBTLinkDecodingStat::ErrPageNotStopped] == 1) { LOG(ERROR) << describe() << ' ' << statistics.ErrNames[GBTLinkDecodingStat::ErrPageNotStopped]; RDHUtils::printRDH(*lastRDH); RDHUtils::printRDH(rdh); @@ -192,7 +192,7 @@ GBTLink::ErrorType GBTLink::checkErrorsRDHStopPageEmpty(const RDH& rdh) { if (format == NewFormat && RDHUtils::getStop(rdh) && RDHUtils::getMemorySize(rdh) != sizeof(RDH) + sizeof(GBTDiagnostic)) { statistics.errorCounts[GBTLinkDecodingStat::ErrStopPageNotEmpty]++; - if (verbosity >= VerboseErrors) { + if (verbosity >= VerboseErrors || statistics.errorCounts[GBTLinkDecodingStat::ErrStopPageNotEmpty] == 1) { LOG(ERROR) << describe() << ' ' << statistics.ErrNames[GBTLinkDecodingStat::ErrStopPageNotEmpty]; RDHUtils::printRDH(rdh); } @@ -207,9 +207,9 @@ GBTLink::ErrorType GBTLink::checkErrorsRDHStopPageEmpty(const RDH& rdh) GBTLink::ErrorType GBTLink::checkErrorsTriggerWord(const GBTTrigger* gbtTrg) { if (!gbtTrg->isTriggerWord()) { // check trigger word - gbtTrg->printX(); statistics.errorCounts[GBTLinkDecodingStat::ErrMissingGBTTrigger]++; - if (verbosity >= VerboseErrors) { + if (verbosity >= VerboseErrors || statistics.errorCounts[GBTLinkDecodingStat::ErrMissingGBTTrigger] == 1) { + gbtTrg->printX(); LOG(ERROR) << describe() << ' ' << statistics.ErrNames[GBTLinkDecodingStat::ErrMissingGBTTrigger]; } errorBits |= 0x1 << int(GBTLinkDecodingStat::ErrMissingGBTTrigger); @@ -232,8 +232,8 @@ GBTLink::ErrorType GBTLink::checkErrorsHeaderWord(const GBTDataHeader* gbtH) { if (!gbtH->isDataHeader()) { // check header word statistics.errorCounts[GBTLinkDecodingStat::ErrMissingGBTHeader]++; - gbtH->printX(); - if (verbosity >= VerboseErrors) { + if (verbosity >= VerboseErrors || statistics.errorCounts[GBTLinkDecodingStat::ErrMissingGBTHeader] == 1) { + gbtH->printX(); LOG(ERROR) << describe() << ' ' << statistics.ErrNames[GBTLinkDecodingStat::ErrMissingGBTHeader]; } errorBits |= 0x1 << int(GBTLinkDecodingStat::ErrMissingGBTHeader); @@ -248,8 +248,8 @@ GBTLink::ErrorType GBTLink::checkErrorsHeaderWord(const GBTDataHeaderL* gbtH) { if (!gbtH->isDataHeader()) { // check header word statistics.errorCounts[GBTLinkDecodingStat::ErrMissingGBTHeader]++; - gbtH->printX(); if (verbosity >= VerboseErrors) { + gbtH->printX(); LOG(ERROR) << describe() << ' ' << statistics.ErrNames[GBTLinkDecodingStat::ErrMissingGBTHeader]; } errorBits |= 0x1 << int(GBTLinkDecodingStat::ErrMissingGBTHeader); @@ -259,7 +259,7 @@ GBTLink::ErrorType GBTLink::checkErrorsHeaderWord(const GBTDataHeaderL* gbtH) // RSTODO: this makes sense only for old format, where every trigger has its RDH if (gbtH->packetIdx != cnt) { statistics.errorCounts[GBTLinkDecodingStat::ErrRDHvsGBTHPageCnt]++; - if (verbosity >= VerboseErrors) { + if (verbosity >= VerboseErrors || statistics.errorCounts[GBTLinkDecodingStat::ErrRDHvsGBTHPageCnt] == 1) { LOG(ERROR) << describe() << ' ' << statistics.ErrNames[GBTLinkDecodingStat::ErrRDHvsGBTHPageCnt] << ": diff in GBT header " << gbtH->packetIdx << " and RDH page " << cnt << " counters"; } @@ -271,7 +271,7 @@ GBTLink::ErrorType GBTLink::checkErrorsHeaderWord(const GBTDataHeaderL* gbtH) //if (cnt) { // makes sens for old format only if (gbtH->packetIdx) { statistics.errorCounts[GBTLinkDecodingStat::ErrNonZeroPageAfterStop]++; - if (verbosity >= VerboseErrors) { + if (verbosity >= VerboseErrors || statistics.errorCounts[GBTLinkDecodingStat::ErrNonZeroPageAfterStop] == 1) { LOG(ERROR) << describe() << ' ' << statistics.ErrNames[GBTLinkDecodingStat::ErrNonZeroPageAfterStop] << ": Non-0 page counter (" << cnt << ") while all lanes were stopped"; } @@ -288,8 +288,8 @@ GBTLink::ErrorType GBTLink::checkErrorsActiveLanes(int cbl) { if (~cbl & lanesActive) { // are there wrong lanes? statistics.errorCounts[GBTLinkDecodingStat::ErrInvalidActiveLanes]++; - std::bitset<32> expectL(cbl), gotL(lanesActive); - if (verbosity >= VerboseErrors) { + if (verbosity >= VerboseErrors || statistics.errorCounts[GBTLinkDecodingStat::ErrInvalidActiveLanes] == 1) { + std::bitset<32> expectL(cbl), gotL(lanesActive); LOG(ERROR) << describe() << ' ' << statistics.ErrNames[GBTLinkDecodingStat::ErrInvalidActiveLanes] << ' ' << gotL << " vs " << expectL << " skip page"; } @@ -306,7 +306,7 @@ GBTLink::ErrorType GBTLink::checkErrorsGBTData(int cablePos) lanesWithData |= 0x1 << cablePos; // flag that the data was seen on this lane if (lanesStop & (0x1 << cablePos)) { // make sure stopped lanes do not transmit the data statistics.errorCounts[GBTLinkDecodingStat::ErrDataForStoppedLane]++; - if (verbosity >= VerboseErrors) { + if (verbosity >= VerboseErrors || statistics.errorCounts[GBTLinkDecodingStat::ErrDataForStoppedLane] == 1) { LOG(ERROR) << describe() << ' ' << statistics.ErrNames[GBTLinkDecodingStat::ErrDataForStoppedLane] << cablePos; } @@ -324,14 +324,16 @@ GBTLink::ErrorType GBTLink::checkErrorsGBTDataID(const GBTData* gbtD) if (gbtD->isData()) { return NoError; } - if (gbtD->isCableDiagnostic()) { - printCableDiagnostic((GBTCableDiagnostic*)gbtD); - } else if (gbtD->isStatus()) { - printCableStatus((GBTCableStatus*)gbtD); - } - LOG(ERROR) << describe() << ' ' << statistics.ErrNames[GBTLinkDecodingStat::ErrGBTWordNotRecognized]; - gbtD->printX(true); statistics.errorCounts[GBTLinkDecodingStat::ErrGBTWordNotRecognized]++; + if (verbosity >= VerboseErrors || statistics.errorCounts[GBTLinkDecodingStat::ErrGBTWordNotRecognized] == 1) { + if (gbtD->isCableDiagnostic()) { + printCableDiagnostic((GBTCableDiagnostic*)gbtD); + } else if (gbtD->isStatus()) { + printCableStatus((GBTCableStatus*)gbtD); + } + gbtD->printX(true); + LOG(ERROR) << describe() << ' ' << statistics.ErrNames[GBTLinkDecodingStat::ErrGBTWordNotRecognized]; + } return Skip; } @@ -342,7 +344,7 @@ GBTLink::ErrorType GBTLink::checkErrorsTrailerWord(const GBTDataTrailer* gbtT) if (!gbtT->isDataTrailer()) { gbtT->printX(); statistics.errorCounts[GBTLinkDecodingStat::ErrMissingGBTTrailer]++; - if (verbosity >= VerboseErrors) { + if (verbosity >= VerboseErrors || statistics.errorCounts[GBTLinkDecodingStat::ErrMissingGBTTrailer] == 1) { LOG(ERROR) << describe() << ' ' << statistics.ErrNames[GBTLinkDecodingStat::ErrMissingGBTTrailer]; } errorBits |= 0x1 << int(GBTLinkDecodingStat::ErrMissingGBTTrailer); @@ -359,7 +361,7 @@ GBTLink::ErrorType GBTLink::checkErrorsPacketDoneMissing(const GBTDataTrailer* g { if (!gbtT->packetDone && notEnd) { // Done may be missing only in case of carry-over to new CRU page statistics.errorCounts[GBTLinkDecodingStat::ErrPacketDoneMissing]++; - if (verbosity >= VerboseErrors) { + if (verbosity >= VerboseErrors || statistics.errorCounts[GBTLinkDecodingStat::ErrPacketDoneMissing] == 1) { LOG(ERROR) << describe() << ' ' << statistics.ErrNames[GBTLinkDecodingStat::ErrPacketDoneMissing]; } errorBits |= 0x1 << int(GBTLinkDecodingStat::ErrPacketDoneMissing); @@ -377,8 +379,8 @@ GBTLink::ErrorType GBTLink::checkErrorsLanesStops() if ((lanesActive & ~lanesStop)) { if (RDHUtils::getTriggerType(*lastRDH) != o2::trigger::SOT) { // only SOT trigger allows unstopped lanes? statistics.errorCounts[GBTLinkDecodingStat::ErrUnstoppedLanes]++; - std::bitset<32> active(lanesActive), stopped(lanesStop); - if (verbosity >= VerboseErrors) { + if (verbosity >= VerboseErrors || statistics.errorCounts[GBTLinkDecodingStat::ErrUnstoppedLanes] == 1) { + std::bitset<32> active(lanesActive), stopped(lanesStop); LOG(ERROR) << describe() << ' ' << statistics.ErrNames[GBTLinkDecodingStat::ErrUnstoppedLanes] << " | active: " << active << " stopped: " << stopped; } @@ -388,9 +390,9 @@ GBTLink::ErrorType GBTLink::checkErrorsLanesStops() } // make sure all active lanes (except those in time-out) have sent some data if ((~lanesWithData & lanesActive) != lanesTimeOut) { - std::bitset<32> withData(lanesWithData), active(lanesActive), timeOut(lanesTimeOut); statistics.errorCounts[GBTLinkDecodingStat::ErrNoDataForActiveLane]++; - if (verbosity >= VerboseErrors) { + if (verbosity >= VerboseErrors || statistics.errorCounts[GBTLinkDecodingStat::ErrNoDataForActiveLane] == 1) { + std::bitset<32> withData(lanesWithData), active(lanesActive), timeOut(lanesTimeOut); LOG(ERROR) << describe() << ' ' << statistics.ErrNames[GBTLinkDecodingStat::ErrNoDataForActiveLane] << " | with data: " << withData << " active: " << active << " timeOut: " << timeOut; } @@ -406,8 +408,8 @@ GBTLink::ErrorType GBTLink::checkErrorsDiagnosticWord(const GBTDiagnostic* gbtD) { if (RDHUtils::getMemorySize(lastRDH) != sizeof(RDH) + sizeof(GBTDiagnostic) || !gbtD->isDiagnosticWord()) { // statistics.errorCounts[GBTLinkDecodingStat::ErrMissingDiagnosticWord]++; - gbtD->printX(); - if (verbosity >= VerboseErrors) { + if (verbosity >= VerboseErrors || statistics.errorCounts[GBTLinkDecodingStat::ErrMissingDiagnosticWord] == 1) { + gbtD->printX(); LOG(ERROR) << describe() << ' ' << statistics.ErrNames[GBTLinkDecodingStat::ErrMissingDiagnosticWord]; } errorBits |= 0x1 << int(GBTLinkDecodingStat::ErrMissingDiagnosticWord); From 97d016767e1479577a7e3502ac809e8ad0140066 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 7 May 2021 13:46:15 +0200 Subject: [PATCH 431/770] avoid to store some floats --- .../ZDC/include/DataFormatsZDC/RecEvent.h | 17 +++++++------- Detectors/ZDC/reconstruction/src/DigiReco.cxx | 22 ++++++++++--------- 2 files changed, 20 insertions(+), 19 deletions(-) diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h index 6e7ae27776f27..887e95b479c68 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h @@ -27,24 +27,23 @@ namespace o2 namespace zdc { struct RecEvent { - //using TDCChannel = std::array; - //using TDCAmplitude = std::array; - //using TDCChannel = std::vector; - //using TDCAmplitude = std::vector; o2::InteractionRecord ir; uint32_t flags; /// reconstruction flags std::map ezdc; /// signal in ZDCs float energy[NChannels] = {O2_ZDC_FLT_INIT}; /// ZDC signal - math_utils::Point2D centroidZNA; /// centroid coordinates for ZNA - math_utils::Point2D centroidZNC; /// centroid coordinates for ZNC - - int16_t tdcVal[NTDCChannels][MaxTDCValues]; /// TdcChannels - float tdcAmp[NTDCChannels][MaxTDCValues]; /// TdcAmplitudes + constexpr static float fAmp = 1. / 8.; /// Multiplication factor in conversion from integer + constexpr static float fVal = 1. / TSNS; /// Multiplication factor in conversion from integer + int16_t tdcVal[NTDCChannels][MaxTDCValues]; /// TdcChannels + int16_t tdcAmp[NTDCChannels][MaxTDCValues]; /// TdcAmplitudes int ntdc[NTDCChannels] = {0}; + + // Internal variables std::array pattern; /// Pattern of TDC uint16_t fired[NTDCChannels] = {0}; /// Position at which the trigger algorithm is fired float inter[NTDCChannels][NTimeBinsPerBC * TSN] = {0}; /// Interpolated samples uint32_t ref[NChannels] = {O2_ZDC_REF_INIT}; /// Cache of references + + // Functions void print() const; float EZDC(uint8_t ich) { diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index 72f0394cd05c1..567d63ca110e6 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -90,7 +90,7 @@ void DigiReco::init() if (!mTDCParam) { LOG(FATAL) << "TDC " << itdc << " missing configuration object and no manual override"; } else { - fval = mTDCParam->getShift(itdc) * 96.; + fval = mTDCParam->getShift(itdc) / RecEvent::fVal; } } auto val = std::nearbyint(fval); @@ -101,12 +101,12 @@ void DigiReco::init() LOG(FATAL) << "Shift for TDC " << itdc << " " << val << " is out of range"; } tdc_shift[itdc] = val; - LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " shift= " << tdc_shift[itdc] << " i.s. = " << val / 96. << " ns"; + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " shift= " << tdc_shift[itdc] << " i.s. = " << val*RecEvent::fVal << " ns"; } // TDC search zone // TODO: override with configuration object for (int itdc = 0; itdc < o2::zdc::NTDCChannels; itdc++) { - LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << ropt.tdc_search[itdc] << " i.s. = " << ropt.tdc_search[itdc] / 96. << " ns"; + LOG(INFO) << itdc << " " << ChannelNames[TDCSignal[itdc]] << " search= " << ropt.tdc_search[itdc] << " i.s. = " << ropt.tdc_search[itdc]*RecEvent::fVal << " ns"; } // Fill maps channel maps for integration @@ -176,6 +176,12 @@ int DigiReco::process(const std::vector* orbitdata, const st // Initialization of reco structure for (int ibc = 0; ibc < mNBC; ibc++) { auto& bcr = mReco[ibc]; + for (int itdc = 0; itdc < NTDCChannels; itdc++) { + for (int i = 0; i < MaxTDCValues; i++) { + bcr.tdcVal[itdc][i] = kMinShort; + bcr.tdcAmp[itdc][i] = kMinShort; + } + } auto& bcd = BCData[ibc]; bcr.ir = bcd.ir; int chEnt = bcd.ref.getFirstEntry(); @@ -329,10 +335,6 @@ int DigiReco::reconstruct(int ibeg, int iend) } printf("\n"); } - // for (int i = 0; i < MaxTDCValues; i++) { - // rec.tdcVal[itdc][i] = kMinShort; - // rec.tdcAmp[itdc][i] = -999; - // } rec.pattern[itdc] = 0; for (int32_t i = 0; i < rec.ntdc[itdc]; i++) { LOG(INFO) << "tdc " << i << " [" << ChannelNames[TDCSignal[itdc]] << "] " << rec.tdcAmp[itdc][i] << " @ " << rec.tdcVal[itdc][i]; @@ -767,13 +769,13 @@ void DigiReco::assignTDC(int ibun, int ibeg, int iend, int itdc, int tdc, float int& ihit = mReco[ibun].ntdc[itdc]; if (ihit < MaxTDCValues) { mReco[ibun].tdcVal[itdc][ihit] = tdc_cor; - mReco[ibun].tdcAmp[itdc][ihit] = amp; + mReco[ibun].tdcAmp[itdc][ihit] = std::nearbyint(amp/RecEvent::fAmp); ihit++; LOG(INFO) << mReco[ibun].ir.orbit << "." << mReco[ibun].ir.bc << " " - << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor << " amp=" << amp; + << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor*RecEvent::fVal << " amp=" << amp*RecEvent::fAmp; } else { LOG(ERROR) << mReco[ibun].ir.orbit << "." << mReco[ibun].ir.bc << " " - << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor << " amp=" << amp << " OVERFLOW"; + << "ibun=" << ibun << " itdc=" << itdc << " tdc=" << tdc << " tdc_cor=" << tdc_cor*RecEvent::fVal << " amp=" << amp*RecEvent::fAmp << " OVERFLOW"; } } From f227a70aab2fbf83417ad1c4f238bc1a3b526203 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Fri, 7 May 2021 15:27:48 +0200 Subject: [PATCH 432/770] DPL GUI: improve profiler / debugger support (#6087) On macOS: * do not open two terminals when launching debugger / profiler * avoid spurious opening the wrong profiler stacktrace * Use xcrun for compatibility with new XCode --- .../GUISupport/src/FrameworkGUIDebugger.cxx | 19 +++++++++++-------- .../src/FrameworkGUIDeviceInspector.cxx | 17 ++++++++++------- 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/Framework/GUISupport/src/FrameworkGUIDebugger.cxx b/Framework/GUISupport/src/FrameworkGUIDebugger.cxx index 2fbd286107dff..2922931f26164 100644 --- a/Framework/GUISupport/src/FrameworkGUIDebugger.cxx +++ b/Framework/GUISupport/src/FrameworkGUIDebugger.cxx @@ -725,8 +725,10 @@ void displayDriverInfo(DriverInfo const& driverInfo, DriverControl& driverContro setenv("O2DEBUGGEDPID", pidStr.c_str(), 1); #ifdef __APPLE__ std::string defaultAppleDebugCommand = - "osascript -e 'tell application \"Terminal\" to activate'" - " -e 'tell application \"Terminal\" to do script \"lldb -p \" & (system attribute \"O2DEBUGGEDPID\")'"; + "osascript -e 'tell application \"Terminal\"'" + " -e 'activate'" + " -e 'do script \"lldb -p \" & (system attribute \"O2DEBUGGEDPID\") & \"; exit\"'" + " -e 'end tell'"; setenv("O2DPLDEBUG", defaultAppleDebugCommand.c_str(), 0); #else setenv("O2DPLDEBUG", "xterm -hold -e gdb attach $O2DEBUGGEDPID &", 0); @@ -741,12 +743,13 @@ void displayDriverInfo(DriverInfo const& driverInfo, DriverControl& driverContro setenv("O2PROFILEDPID", pidStr.c_str(), 1); #ifdef __APPLE__ auto defaultAppleProfileCommand = fmt::format( - "osascript -e 'tell application \"Terminal\" to activate'" - " -e 'tell application \"Terminal\" to do script \"xcrun xctrace record --output dpl-profile-{}.trace" - " --time-limit 30s --template Time\\\\ Profiler --attach {} " - " && open dpl-profile-{}.trace && exit\"'" - " && open dpl-driver-profile-{}.trace", - pid, pid, pid, pid); + "osascript -e 'tell application \"Terminal\"'" + " -e 'activate'" + " -e 'do script \"xcrun xctrace record --output dpl-profile-{0}.trace" + " --time-limit 30s --template Time\\\\ Profiler --attach {0} " + " && open dpl-profile-{0}.trace && exit\"'" + " -e 'end tell'", + pid); std::cout << defaultAppleProfileCommand << std::endl; setenv("O2DPLPROFILE", defaultAppleProfileCommand.c_str(), 0); #else diff --git a/Framework/GUISupport/src/FrameworkGUIDeviceInspector.cxx b/Framework/GUISupport/src/FrameworkGUIDeviceInspector.cxx index 7a7d4d300e3bd..1c2312bd9bfa5 100644 --- a/Framework/GUISupport/src/FrameworkGUIDeviceInspector.cxx +++ b/Framework/GUISupport/src/FrameworkGUIDeviceInspector.cxx @@ -205,7 +205,7 @@ void displayDeviceInspector(DeviceSpec const& spec, #ifdef __APPLE__ std::string defaultAppleDebugCommand = "osascript -e 'tell application \"Terminal\" to activate'" - " -e 'tell application \"Terminal\" to do script \"lldb -p \" & (system attribute \"O2DEBUGGEDPID\")'"; + " -e 'tell application \"Terminal\" to do script \"lldb -p \" & (system attribute \"O2DEBUGGEDPID\") & \"; exit\"'"; setenv("O2DPLDEBUG", defaultAppleDebugCommand.c_str(), 0); #else setenv("O2DPLDEBUG", "xterm -hold -e gdb attach $O2DEBUGGEDPID &", 0); @@ -219,12 +219,15 @@ void displayDeviceInspector(DeviceSpec const& spec, std::string pid = std::to_string(info.pid); setenv("O2PROFILEDPID", pid.c_str(), 1); #ifdef __APPLE__ - std::string defaultAppleProfileCommand = - "osascript -e 'tell application \"Terminal\" to activate'" - " -e 'tell application \"Terminal\" to do script \"instruments -D dpl-profile-" + - pid + - ".trace -l 30000 -t Time\\\\ Profiler -p " + - pid + " && open dpl-profile-" + pid + ".trace && exit\"'"; + auto defaultAppleProfileCommand = fmt::format( + "osascript -e 'tell application \"Terminal\"'" + " -e 'activate'" + " -e 'do script \"xcrun xctrace record --output dpl-profile-{0}.trace" + " --time-limit 30s --template Time\\\\ Profiler --attach {0} " + " && open dpl-profile-{0}.trace && exit\"'" + " -e 'end tell'", + pid); + setenv("O2DPLPROFILE", defaultAppleProfileCommand.c_str(), 0); #else setenv("O2DPLPROFILE", "xterm -hold -e perf record -a -g -p $O2PROFILEDPID > perf-$O2PROFILEDPID.data &", 0); From a16384b7530e8b1d7fe6951cbaa24703eccd3bdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADt=20Ku=C4=8Dera?= Date: Fri, 7 May 2021 15:50:12 +0200 Subject: [PATCH 433/770] PWGHF: Add PID track selector class. (#6043) --- .../include/AnalysisCore/HFSelectorCuts.h | 2 +- .../include/AnalysisCore/TrackSelectorPID.h | 295 +++++++++++++++ .../Tasks/PWGHF/HFD0CandidateSelector.cxx | 301 ++++++--------- .../PWGHF/HFDplusToPiKPiCandidateSelector.cxx | 192 +++------- .../PWGHF/HFJpsiToEECandidateSelector.cxx | 109 ++---- .../Tasks/PWGHF/HFLcCandidateSelector.cxx | 268 +++++-------- .../PWGHF/HFXicToPKPiCandidateSelector.cxx | 358 +++++------------- 7 files changed, 683 insertions(+), 842 deletions(-) create mode 100644 Analysis/Core/include/AnalysisCore/TrackSelectorPID.h diff --git a/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h b/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h index 6909a9de4069d..a1e3945b506df 100644 --- a/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h +++ b/Analysis/Core/include/AnalysisCore/HFSelectorCuts.h @@ -249,7 +249,7 @@ constexpr double pTBins[npTBins + 1] = { auto pTBins_v = std::vector{pTBins, pTBins + npTBins + 1}; // default values for the cuts -// selections from pp at 5 TeV 2017 analysis https://alice−notes.web.cern.ch/node/808 +// selections from pp at 5 TeV 2017 analysis https://alice-notes.web.cern.ch/node/808 constexpr double cuts[npTBins][nCutVars] = {{0.2, 0.3, 0.3, 0.07, 6., 0.96, 0.985, 2.5}, /* 1 < pT < 2 */ {0.2, 0.3, 0.3, 0.07, 5., 0.96, 0.985, 2.5}, /* 2 < pT < 3 */ {0.2, 0.3, 0.3, 0.10, 5., 0.96, 0.980, 2.5}, /* 3 < pT < 4 */ diff --git a/Analysis/Core/include/AnalysisCore/TrackSelectorPID.h b/Analysis/Core/include/AnalysisCore/TrackSelectorPID.h new file mode 100644 index 0000000000000..1c9cf29269dcf --- /dev/null +++ b/Analysis/Core/include/AnalysisCore/TrackSelectorPID.h @@ -0,0 +1,295 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file TrackSelectorPID.h +/// \brief PID track selector class +/// +/// \author Vít Kučera , CERN + +#ifndef O2_ANALYSIS_TRACKSELECTORPID_H_ +#define O2_ANALYSIS_TRACKSELECTORPID_H_ + +#include + +#include "Framework/Logger.h" + +/// Class for track selection using PID detectors + +class TrackSelectorPID +{ + public: + /// Default constructor + TrackSelectorPID() = default; + + /// Standard constructor with PDG code initialisation + explicit TrackSelectorPID(int pdg) + : mPdg(std::abs(pdg)) + { + } + + /// Default destructor + ~TrackSelectorPID() = default; + + /// Selection status + enum Status { + PIDNotApplicable = 0, + PIDRejected, + PIDConditional, + PIDAccepted + }; + + void setPDG(int pdg) { mPdg = std::abs(pdg); } + + // TPC + + /// Set pT range where TPC PID is applicable. + void setRangePtTPC(float ptMin, float ptMax) + { + mPtTPCMin = ptMin; + mPtTPCMax = ptMax; + } + + /// Set TPC nσ range in which a track should be accepted. + void setRangeNSigmaTPC(float nsMin, float nsMax) + { + mNSigmaTPCMin = nsMin; + mNSigmaTPCMax = nsMax; + } + + /// Set TPC nσ range in which a track should be conditionally accepted if combined with TOF. + void setRangeNSigmaTPCCondTOF(float nsMin, float nsMax) + { + mNSigmaTPCMinCondTOF = nsMin; + mNSigmaTPCMaxCondTOF = nsMax; + } + + /// Checks if track is OK for TPC PID. + /// \param track track + /// \return true if track is OK for TPC PID + template + bool isValidTrackPIDTPC(const T& track) + { + auto pt = track.pt(); + return mPtTPCMin <= pt && pt <= mPtTPCMax; + } + + /// Checks if track is compatible with given particle species hypothesis within given TPC nσ range. + /// \param track track + /// \param conditionalTOF variable to store the result of selection with looser cuts for conditional accepting of track if combined with TOF + /// \return true if track satisfies TPC PID hypothesis for given TPC nσ range + template + bool isSelectedTrackPIDTPC(const T& track, bool& conditionalTOF) + { + // Accept if selection is disabled via large values. + if (mNSigmaTPCMin < -999. && mNSigmaTPCMax > 999.) { + return true; + } + + // Get nσ for a given particle hypothesis. + double nSigma = 100.; + switch (mPdg) { + case kElectron: { + nSigma = track.tpcNSigmaEl(); + break; + } + case kMuonMinus: { + nSigma = track.tpcNSigmaMu(); + break; + } + case kPiPlus: { + nSigma = track.tpcNSigmaPi(); + break; + } + case kKPlus: { + nSigma = track.tpcNSigmaKa(); + break; + } + case kProton: { + nSigma = track.tpcNSigmaPr(); + break; + } + default: { + LOGF(error, "ERROR: TPC PID not implemented for PDG %d", mPdg); + assert(false); + } + } + + if (mNSigmaTPCMinCondTOF < -999. && mNSigmaTPCMaxCondTOF > 999.) { + conditionalTOF = true; + } else { + conditionalTOF = mNSigmaTPCMinCondTOF <= nSigma && nSigma <= mNSigmaTPCMaxCondTOF; + } + return mNSigmaTPCMin <= nSigma && nSigma <= mNSigmaTPCMax; + } + + /// Returns status of TPC PID selection for a given track. + /// \param track track + /// \return TPC selection status (see TrackSelectorPID::Status) + template + int getStatusTrackPIDTPC(const T& track) + { + if (isValidTrackPIDTPC(track)) { + bool condTOF = false; + if (isSelectedTrackPIDTPC(track, condTOF)) { + return Status::PIDAccepted; // accepted + } else if (condTOF) { + return Status::PIDConditional; // potential to be accepted if combined with TOF + } else { + return Status::PIDRejected; // rejected + } + } else { + return Status::PIDNotApplicable; // PID not applicable + } + } + + // TOF + + /// Set pT range where TOF PID is applicable. + void setRangePtTOF(float ptMin, float ptMax) + { + mPtTOFMin = ptMin; + mPtTOFMax = ptMax; + } + + /// Set TOF nσ range in which a track should be accepted. + void setRangeNSigmaTOF(float nsMin, float nsMax) + { + mNSigmaTOFMin = nsMin; + mNSigmaTOFMax = nsMax; + } + + /// Set TOF nσ range in which a track should be conditionally accepted if combined with TPC. + void setRangeNSigmaTOFCondTPC(float nsMin, float nsMax) + { + mNSigmaTOFMinCondTPC = nsMin; + mNSigmaTOFMaxCondTPC = nsMax; + } + + /// Checks if track is OK for TOF PID. + /// \param track track + /// \return true if track is OK for TOF PID + template + bool isValidTrackPIDTOF(const T& track) + { + auto pt = track.pt(); + return mPtTOFMin <= pt && pt <= mPtTOFMax; + } + + /// Checks if track is compatible with given particle species hypothesis within given TOF nσ range. + /// \param track track + /// \param conditionalTPC variable to store the result of selection with looser cuts for conditional accepting of track if combined with TPC + /// \return true if track satisfies TOF PID hypothesis for given TOF nσ range + template + bool isSelectedTrackPIDTOF(const T& track, bool& conditionalTPC) + { + // Accept if selection is disabled via large values. + if (mNSigmaTOFMin < -999. && mNSigmaTOFMax > 999.) { + return true; + } + + // Get nσ for a given particle hypothesis. + double nSigma = 100.; + switch (mPdg) { + case kElectron: { + nSigma = track.tofNSigmaEl(); + break; + } + case kMuonMinus: { + nSigma = track.tofNSigmaMu(); + break; + } + case kPiPlus: { + nSigma = track.tofNSigmaPi(); + break; + } + case kKPlus: { + nSigma = track.tofNSigmaKa(); + break; + } + case kProton: { + nSigma = track.tofNSigmaPr(); + break; + } + default: { + LOGF(error, "ERROR: TOF PID not implemented for PDG %d", mPdg); + assert(false); + } + } + + if (mNSigmaTOFMinCondTPC < -999. && mNSigmaTOFMaxCondTPC > 999.) { + conditionalTPC = true; + } else { + conditionalTPC = mNSigmaTOFMinCondTPC <= nSigma && nSigma <= mNSigmaTOFMaxCondTPC; + } + return mNSigmaTOFMin <= nSigma && nSigma <= mNSigmaTOFMax; + } + + /// Returns status of TOF PID selection for a given track. + /// \param track track + /// \return TOF selection status (see TrackSelectorPID::Status) + template + int getStatusTrackPIDTOF(const T& track) + { + if (isValidTrackPIDTOF(track)) { + bool condTPC = false; + if (isSelectedTrackPIDTOF(track, condTPC)) { + return Status::PIDAccepted; // accepted + } else if (condTPC) { + return Status::PIDConditional; // potential to be accepted if combined with TPC + } else { + return Status::PIDRejected; // rejected + } + } else { + return Status::PIDNotApplicable; // PID not applicable + } + } + + /// Returns status of combined PID selection for a given track. + /// \param track track + /// \return combined-selection status (see TrackSelectorPID::Status) + template + int getStatusTrackPIDAll(const T& track) + { + int statusTPC = getStatusTrackPIDTPC(track); + int statusTOF = getStatusTrackPIDTOF(track); + + if (statusTPC == Status::PIDAccepted || statusTOF == Status::PIDAccepted) { + return Status::PIDAccepted; // what if we have Accepted for one and Rejected for the other? + } + if (statusTPC == Status::PIDConditional && statusTOF == Status::PIDConditional) { + return Status::PIDAccepted; + } + if (statusTPC == Status::PIDRejected || statusTOF == Status::PIDRejected) { + return Status::PIDRejected; + } + return Status::PIDNotApplicable; // (NotApplicable for one detector) and (NotApplicable or Conditional for the other) + } + + private: + uint mPdg = kPiPlus; ///< PDG code of the expected particle + + // TPC + float mPtTPCMin = 0.; ///< minimum pT for TPC PID [GeV/c] + float mPtTPCMax = 100.; ///< maximum pT for TPC PID [GeV/c] + float mNSigmaTPCMin = -3.; ///< minimum number of TPC σ + float mNSigmaTPCMax = 3.; ///< maximum number of TPC σ + float mNSigmaTPCMinCondTOF = -1000.; ///< minimum number of TPC σ if combined with TOF + float mNSigmaTPCMaxCondTOF = 1000.; ///< maximum number of TPC σ if combined with TOF + + // TOF + float mPtTOFMin = 0.; ///< minimum pT for TOF PID [GeV/c] + float mPtTOFMax = 100.; ///< maximum pT for TOF PID [GeV/c] + float mNSigmaTOFMin = -3.; ///< minimum number of TOF σ + float mNSigmaTOFMax = 3.; ///< maximum number of TOF σ + float mNSigmaTOFMinCondTPC = -1000.; ///< minimum number of TOF σ if combined with TPC + float mNSigmaTOFMaxCondTPC = 1000.; ///< maximum number of TOF σ if combined with TPC +}; + +#endif // O2_ANALYSIS_TRACKSELECTORPID_H_ diff --git a/Analysis/Tasks/PWGHF/HFD0CandidateSelector.cxx b/Analysis/Tasks/PWGHF/HFD0CandidateSelector.cxx index 2abe0b7bb10a0..c680783f9289a 100644 --- a/Analysis/Tasks/PWGHF/HFD0CandidateSelector.cxx +++ b/Analysis/Tasks/PWGHF/HFD0CandidateSelector.cxx @@ -9,14 +9,16 @@ // or submit itself to any jurisdiction. /// \file HFD0CandidateSelector.cxx -/// \brief D0 selection task +/// \brief D0(bar) → π± K∓ selection task /// /// \author Nima Zardoshti , CERN +/// \author Vít Kučera , CERN #include "Framework/runDataProcessing.h" #include "Framework/AnalysisTask.h" #include "AnalysisDataModel/HFSecondaryVertex.h" #include "AnalysisDataModel/HFCandidateSelectionTables.h" +#include "AnalysisCore/TrackSelectorPID.h" using namespace o2; using namespace o2::framework; @@ -24,27 +26,27 @@ using namespace o2::aod::hf_cand_prong2; using namespace o2::analysis::hf_cuts_d0_topik; /// Struct for applying D0 selection cuts - struct HFD0CandidateSelector { Produces hfSelD0Candidate; Configurable d_pTCandMin{"d_pTCandMin", 0., "Lower bound of candidate pT"}; Configurable d_pTCandMax{"d_pTCandMax", 50., "Upper bound of candidate pT"}; - + // TPC Configurable d_pidTPCMinpT{"d_pidTPCMinpT", 0.15, "Lower bound of track pT for TPC PID"}; Configurable d_pidTPCMaxpT{"d_pidTPCMaxpT", 5., "Upper bound of track pT for TPC PID"}; - Configurable d_pidTOFMinpT{"d_pidTOFMinpT", 0.15, "Lower bound of track pT for TOF PID"}; - Configurable d_pidTOFMaxpT{"d_pidTOFMaxpT", 5., "Upper bound of track pT for TOF PID"}; - - Configurable d_TPCNClsFindablePIDCut{"d_TPCNClsFindablePIDCut", 50., "Lower bound of TPC findable clusters for good PID"}; Configurable d_nSigmaTPC{"d_nSigmaTPC", 3., "Nsigma cut on TPC only"}; Configurable d_nSigmaTPCCombined{"d_nSigmaTPCCombined", 5., "Nsigma cut on TPC combined with TOF"}; + //Configurable d_TPCNClsFindablePIDCut{"d_TPCNClsFindablePIDCut", 50., "Lower bound of TPC findable clusters for good PID"}; + // TOF + Configurable d_pidTOFMinpT{"d_pidTOFMinpT", 0.15, "Lower bound of track pT for TOF PID"}; + Configurable d_pidTOFMaxpT{"d_pidTOFMaxpT", 5., "Upper bound of track pT for TOF PID"}; Configurable d_nSigmaTOF{"d_nSigmaTOF", 3., "Nsigma cut on TOF only"}; Configurable d_nSigmaTOFCombined{"d_nSigmaTOFCombined", 5., "Nsigma cut on TOF combined with TPC"}; - + // topological cuts Configurable> pTBins{"pTBins", std::vector{hf_cuts_d0_topik::pTBins_v}, "pT bin limits"}; Configurable> cuts{"D0_to_pi_K_cuts", {hf_cuts_d0_topik::cuts[0], npTBins, nCutVars, pTBinLabels, cutVarLabels}, "D0 candidate selection per pT bin"}; + /* /// Selection on goodness of daughter tracks /// \note should be applied at candidate selection /// \param track is daughter track @@ -52,98 +54,106 @@ struct HFD0CandidateSelector { template bool daughterSelection(const T& track) { - if (track.sign() == 0) { - return false; - } - /* if (track.tpcNClsFound() == 0) { + if (track.tpcNClsFound() == 0) { return false; //is it clusters findable or found - need to check - }*/ + } return true; } + */ /// Conjugate-independent topological cuts - /// \param hfCandProng2 is candidate + /// \param candidate is candidate /// \return true if candidate passes all cuts template - bool selectionTopol(const T& hfCandProng2) + bool selectionTopol(const T& candidate) { - auto candpT = hfCandProng2.pt(); + auto candpT = candidate.pt(); auto pTBin = findBin(pTBins, candpT); if (pTBin == -1) { return false; } + // check that the candidate pT is within the analysis range if (candpT < d_pTCandMin || candpT >= d_pTCandMax) { - return false; //check that the candidate pT is within the analysis range + return false; } - if (hfCandProng2.impactParameterProduct() > cuts->get(pTBin, "d0d0")) { - return false; //product of daughter impact parameters + // product of daughter impact parameters + if (candidate.impactParameterProduct() > cuts->get(pTBin, "d0d0")) { + return false; } - if (hfCandProng2.cpa() < cuts->get(pTBin, "cos pointing angle")) { - return false; //cosine of pointing angle + // cosine of pointing angle + if (candidate.cpa() < cuts->get(pTBin, "cos pointing angle")) { + return false; } - if (hfCandProng2.cpaXY() < cuts->get(pTBin, "cos pointing angle xy")) { - return false; //cosine of pointing angle XY + // cosine of pointing angle XY + if (candidate.cpaXY() < cuts->get(pTBin, "cos pointing angle xy")) { + return false; } - if (hfCandProng2.decayLengthXYNormalised() < cuts->get(pTBin, "normalized decay length XY")) { - return false; //normalised decay length in XY plane + // normalised decay length in XY plane + if (candidate.decayLengthXYNormalised() < cuts->get(pTBin, "normalized decay length XY")) { + return false; } - // if (hfCandProng2.dca() > cuts[pTBin][1]) return false; //candidate DCA - //if (hfCandProng2.chi2PCA() > cuts[pTBin][1]) return false; //candidate DCA + // candidate DCA + //if (candidate.chi2PCA() > cuts[pTBin][1]) return false; - //decay exponentail law, with tau = beta*gamma*ctau - //decay length > ctau retains (1-1/e) - if (std::abs(hfCandProng2.impactParameterNormalised0()) < 0.5 || std::abs(hfCandProng2.impactParameterNormalised1()) < 0.5) { + // decay exponentail law, with tau = beta*gamma*ctau + // decay length > ctau retains (1-1/e) + if (std::abs(candidate.impactParameterNormalised0()) < 0.5 || std::abs(candidate.impactParameterNormalised1()) < 0.5) { return false; } - double decayLengthCut = std::min((hfCandProng2.p() * 0.0066) + 0.01, 0.06); - if (hfCandProng2.decayLength() * hfCandProng2.decayLength() < decayLengthCut * decayLengthCut) { + double decayLengthCut = std::min((candidate.p() * 0.0066) + 0.01, 0.06); + if (candidate.decayLength() * candidate.decayLength() < decayLengthCut * decayLengthCut) { return false; } - if (hfCandProng2.decayLengthNormalised() * hfCandProng2.decayLengthNormalised() < 1.0) { - //return false; //add back when getter fixed + if (candidate.decayLengthNormalised() * candidate.decayLengthNormalised() < 1.0) { + //return false; // add back when getter fixed } return true; } /// Conjugate-dependent topological cuts - /// \param hfCandProng2 is candidate + /// \param candidate is candidate /// \param trackPion is the track with the pion hypothesis /// \param trackKaon is the track with the kaon hypothesis /// \note trackPion = positive and trackKaon = negative for D0 selection and inverse for D0bar /// \return true if candidate passes all cuts for the given Conjugate template - bool selectionTopolConjugate(const T1& hfCandProng2, const T2& trackPion, const T2& trackKaon) + bool selectionTopolConjugate(const T1& candidate, const T2& trackPion, const T2& trackKaon) { - auto candpT = hfCandProng2.pt(); + auto candpT = candidate.pt(); auto pTBin = findBin(pTBins, candpT); if (pTBin == -1) { return false; } - if (trackPion.sign() > 0) { //invariant mass cut - if (std::abs(InvMassD0(hfCandProng2) - RecoDecay::getMassPDG(pdg::Code::kD0)) > cuts->get(pTBin, "m")) { + // invariant-mass cut + if (trackPion.sign() > 0) { + if (std::abs(InvMassD0(candidate) - RecoDecay::getMassPDG(pdg::Code::kD0)) > cuts->get(pTBin, "m")) { return false; } } else { - if (std::abs(InvMassD0bar(hfCandProng2) - RecoDecay::getMassPDG(pdg::Code::kD0)) > cuts->get(pTBin, "m")) { + if (std::abs(InvMassD0bar(candidate) - RecoDecay::getMassPDG(pdg::Code::kD0)) > cuts->get(pTBin, "m")) { return false; } } + // cut on daughter pT if (trackPion.pt() < cuts->get(pTBin, "pT Pi") || trackKaon.pt() < cuts->get(pTBin, "pT K")) { - return false; //cut on daughter pT + return false; } + + // cut on daughter DCA - need to add secondary vertex constraint here if (std::abs(trackPion.dcaPrim0()) > cuts->get(pTBin, "d0pi") || std::abs(trackKaon.dcaPrim0()) > cuts->get(pTBin, "d0K")) { - return false; //cut on daughter dca - need to add secondary vertex constraint here + return false; } - if (trackPion.sign() > 0) { //cut on cos(theta *) - if (std::abs(CosThetaStarD0(hfCandProng2)) > cuts->get(pTBin, "cos theta*")) { + // cut on cos(theta*) + if (trackPion.sign() > 0) { + if (std::abs(CosThetaStarD0(candidate)) > cuts->get(pTBin, "cos theta*")) { return false; } } else { - if (std::abs(CosThetaStarD0bar(hfCandProng2)) > cuts->get(pTBin, "cos theta*")) { + if (std::abs(CosThetaStarD0bar(candidate)) > cuts->get(pTBin, "cos theta*")) { return false; } } @@ -151,184 +161,87 @@ struct HFD0CandidateSelector { return true; } - /// Check if track is ok for TPC PID - /// \param track is the track - /// \note function to be expanded - /// \return true if track is ok for TPC PID - template - bool validTPCPID(const T& track) - { - if (track.pt() < d_pidTPCMinpT || track.pt() >= d_pidTPCMaxpT) { - return false; - } - //if (track.TPCNClsFindable() < d_TPCNClsFindablePIDCut) return false; - return true; - } - - /// Check if track is ok for TOF PID - /// \param track is the track - /// \note function to be expanded - /// \return true if track is ok for TOF PID - template - bool validTOFPID(const T& track) - { - if (track.pt() < d_pidTOFMinpT || track.pt() >= d_pidTOFMaxpT) { - return false; - } - return true; - } - - /// Check if track is compatible with given TPC Nsigma cut for a given flavour hypothesis - /// \param track is the track - /// \param nPDG is the flavour hypothesis PDG number - /// \param nSigmaCut is the nsigma threshold to test against - /// \return true if track satisfies TPC PID hypothesis for given Nsigma cut - template - bool selectionPIDTPC(const T& track, int nPDG, double nSigmaCut) + void process(aod::HfCandProng2 const& candidates, aod::BigTracksPID const&) { - double nSigma = 100.0; //arbitarily large value - nPDG = std::abs(nPDG); - if (nPDG == kPiPlus) { - nSigma = track.tpcNSigmaPi(); - } else if (nPDG == kKPlus) { - nSigma = track.tpcNSigmaKa(); - } else { - return false; - } - return std::abs(nSigma) < nSigmaCut; - } + TrackSelectorPID selectorPion(kPiPlus); + selectorPion.setRangePtTPC(d_pidTPCMinpT, d_pidTPCMaxpT); + selectorPion.setRangeNSigmaTPC(-d_nSigmaTPC, d_nSigmaTPC); + selectorPion.setRangeNSigmaTPCCondTOF(-d_nSigmaTPCCombined, d_nSigmaTPCCombined); + selectorPion.setRangePtTOF(d_pidTOFMinpT, d_pidTOFMaxpT); + selectorPion.setRangeNSigmaTOF(-d_nSigmaTOF, d_nSigmaTOF); + selectorPion.setRangeNSigmaTOFCondTPC(-d_nSigmaTOFCombined, d_nSigmaTOFCombined); - /// Check if track is compatible with given TOF NSigma cut for a given flavour hypothesis - /// \param track is the track - /// \param nPDG is the flavour hypothesis PDG number - /// \param nSigmaCut is the nSigma threshold to test against - /// \return true if track satisfies TOF PID hypothesis for given NSigma cut - template - bool selectionPIDTOF(const T& track, int nPDG, double nSigmaCut) - { - double nSigma = 100.0; //arbitarily large value - nPDG = std::abs(nPDG); - if (nPDG == kPiPlus) { - nSigma = track.tofNSigmaPi(); - } else if (nPDG == kKPlus) { - nSigma = track.tofNSigmaKa(); - } else { - return false; - } - return std::abs(nSigma) < nSigmaCut; - } + TrackSelectorPID selectorKaon(selectorPion); + selectorKaon.setPDG(kKPlus); - /// PID selection on daughter track - /// \param track is the daughter track - /// \param nPDG is the PDG code of the flavour hypothesis - /// \return 1 if successful PID match, 0 if successful PID rejection, -1 if no PID info - template - int selectionPID(const T& track, int nPDG) - { - int statusTPC = -1; - int statusTOF = -1; - - if (validTPCPID(track)) { - if (!selectionPIDTPC(track, nPDG, d_nSigmaTPC)) { - if (!selectionPIDTPC(track, nPDG, d_nSigmaTPCCombined)) { - statusTPC = 0; //rejected by PID - } else { - statusTPC = 1; //potential to be acceepted if combined with TOF - } - } else { - statusTPC = 2; //positive PID - } - } else { - statusTPC = -1; //no PID info - } + // looping over 2-prong candidates + for (auto& candidate : candidates) { - if (validTOFPID(track)) { - if (!selectionPIDTOF(track, nPDG, d_nSigmaTOF)) { - if (!selectionPIDTOF(track, nPDG, d_nSigmaTOFCombined)) { - statusTOF = 0; //rejected by PID - } else { - statusTOF = 1; //potential to be acceepted if combined with TOF - } - } else { - statusTOF = 2; //positive PID - } - } else { - statusTOF = -1; //no PID info - } - - if (statusTPC == 2 || statusTOF == 2) { - return 1; //what if we have 2 && 0 ? - } else if (statusTPC == 1 && statusTOF == 1) { - return 1; - } else if (statusTPC == 0 || statusTOF == 0) { - return 0; - } else { - return -1; - } - } - - void process(aod::HfCandProng2 const& hfCandProng2s, aod::BigTracksPID const&) - { - for (auto& hfCandProng2 : hfCandProng2s) { //looping over 2 prong candidates - - // final selection flag : 0-rejected 1-accepted + // final selection flag: 0 - rejected, 1 - accepted int statusD0 = 0; int statusD0bar = 0; - if (!(hfCandProng2.hfflag() & 1 << DecayType::D0ToPiK)) { + if (!(candidate.hfflag() & 1 << DecayType::D0ToPiK)) { hfSelD0Candidate(statusD0, statusD0bar); continue; } - auto trackPos = hfCandProng2.index0_as(); //positive daughter - if (!daughterSelection(trackPos)) { - hfSelD0Candidate(statusD0, statusD0bar); - continue; - } - auto trackNeg = hfCandProng2.index1_as(); //negative daughter - if (!daughterSelection(trackNeg)) { + auto trackPos = candidate.index0_as(); // positive daughter + auto trackNeg = candidate.index1_as(); // negative daughter + + /* + if (!daughterSelection(trackPos) || !daughterSelection(trackNeg)) { hfSelD0Candidate(statusD0, statusD0bar); continue; } + */ - //conjugate-independent topological selection - if (!selectionTopol(hfCandProng2)) { + // conjugate-independent topological selection + if (!selectionTopol(candidate)) { hfSelD0Candidate(statusD0, statusD0bar); continue; } - //implement filter bit 4 cut - should be done before this task at the track selection level - //need to add special cuts (additional cuts on decay length and d0 norm) + // implement filter bit 4 cut - should be done before this task at the track selection level + // need to add special cuts (additional cuts on decay length and d0 norm) - //conjugate-dependent topological selection for D0 - bool topolD0 = selectionTopolConjugate(hfCandProng2, trackPos, trackNeg); - //conjugate-dependent topological selection for D0bar - bool topolD0bar = selectionTopolConjugate(hfCandProng2, trackNeg, trackPos); + // conjugate-dependent topological selection for D0 + bool topolD0 = selectionTopolConjugate(candidate, trackPos, trackNeg); + // conjugate-dependent topological selection for D0bar + bool topolD0bar = selectionTopolConjugate(candidate, trackNeg, trackPos); if (!topolD0 && !topolD0bar) { hfSelD0Candidate(statusD0, statusD0bar); continue; } - int pionPlus = selectionPID(trackPos, kPiPlus); - int kaonMinus = selectionPID(trackNeg, kKPlus); - int pionMinus = selectionPID(trackNeg, kPiPlus); - int kaonPlus = selectionPID(trackPos, kKPlus); + // track-level PID selection + int pidTrackPosKaon = selectorKaon.getStatusTrackPIDAll(trackPos); + int pidTrackPosPion = selectorPion.getStatusTrackPIDAll(trackPos); + int pidTrackNegKaon = selectorKaon.getStatusTrackPIDAll(trackNeg); + int pidTrackNegPion = selectorPion.getStatusTrackPIDAll(trackNeg); int pidD0 = -1; int pidD0bar = -1; - if (pionPlus == 0 || kaonMinus == 0 || pionMinus == 1 || kaonPlus == 1) { - pidD0 = 0; //exclude D0 - } - if (pionPlus == 1 || kaonMinus == 1 || pionMinus == 0 || kaonPlus == 0) { - pidD0bar = 0; //exclude D0bar + if (pidTrackPosPion == TrackSelectorPID::Status::PIDAccepted && + pidTrackNegKaon == TrackSelectorPID::Status::PIDAccepted) { + pidD0 = 1; // accept D0 + } else if (pidTrackPosPion == TrackSelectorPID::Status::PIDRejected || + pidTrackNegKaon == TrackSelectorPID::Status::PIDRejected || + pidTrackNegPion == TrackSelectorPID::Status::PIDAccepted || + pidTrackPosKaon == TrackSelectorPID::Status::PIDAccepted) { + pidD0 = 0; // exclude D0 } - if (pionPlus == 1 && kaonMinus == 1) { - pidD0 = 1; //accept D0 - } - if (pionMinus == 1 && kaonPlus == 1) { - pidD0bar = 1; //accept D0bar + + if (pidTrackNegPion == TrackSelectorPID::Status::PIDAccepted && + pidTrackPosKaon == TrackSelectorPID::Status::PIDAccepted) { + pidD0bar = 1; // accept D0bar + } else if (pidTrackPosPion == TrackSelectorPID::Status::PIDAccepted || + pidTrackNegKaon == TrackSelectorPID::Status::PIDAccepted || + pidTrackNegPion == TrackSelectorPID::Status::PIDRejected || + pidTrackPosKaon == TrackSelectorPID::Status::PIDRejected) { + pidD0bar = 0; // exclude D0bar } if (pidD0 == 0 && pidD0bar == 0) { @@ -337,10 +250,10 @@ struct HFD0CandidateSelector { } if ((pidD0 == -1 || pidD0 == 1) && topolD0) { - statusD0 = 1; //identified as D0 + statusD0 = 1; // identified as D0 } if ((pidD0bar == -1 || pidD0bar == 1) && topolD0bar) { - statusD0bar = 1; //identified as D0bar + statusD0bar = 1; // identified as D0bar } hfSelD0Candidate(statusD0, statusD0bar); diff --git a/Analysis/Tasks/PWGHF/HFDplusToPiKPiCandidateSelector.cxx b/Analysis/Tasks/PWGHF/HFDplusToPiKPiCandidateSelector.cxx index 40c991672d50d..41ce2de0c324f 100644 --- a/Analysis/Tasks/PWGHF/HFDplusToPiKPiCandidateSelector.cxx +++ b/Analysis/Tasks/PWGHF/HFDplusToPiKPiCandidateSelector.cxx @@ -9,14 +9,16 @@ // or submit itself to any jurisdiction. /// \file HFDplusToPiKPiCandidateSelector.cxx -/// \brief Dplus->piKpi selection task +/// \brief D± → π± K∓ π± selection task /// /// \author Fabio Catalano , Politecnico and INFN Torino +/// \author Vít Kučera , CERN #include "Framework/runDataProcessing.h" #include "Framework/AnalysisTask.h" #include "AnalysisDataModel/HFSecondaryVertex.h" #include "AnalysisDataModel/HFCandidateSelectionTables.h" +#include "AnalysisCore/TrackSelectorPID.h" using namespace o2; using namespace o2::framework; @@ -29,20 +31,21 @@ struct HFDplusToPiKPiCandidateSelector { Configurable d_pTCandMin{"d_pTCandMin", 1., "Lower bound of candidate pT"}; Configurable d_pTCandMax{"d_pTCandMax", 36., "Upper bound of candidate pT"}; - + // TPC + Configurable b_requireTPC{"b_requireTPC", true, "Flag to require a positive Number of found clusters in TPC"}; Configurable d_pidTPCMinpT{"d_pidTPCMinpT", 0.15, "Lower bound of track pT for TPC PID"}; Configurable d_pidTPCMaxpT{"d_pidTPCMaxpT", 20., "Upper bound of track pT for TPC PID"}; + Configurable d_nSigmaTPC{"d_nSigmaTPC", 3., "Nsigma cut on TPC"}; + //Configurable d_TPCNClsFindablePIDCut{"d_TPCNClsFindablePIDCut", 50., "Lower bound of TPC findable clusters for good PID"}; + // TOF Configurable d_pidTOFMinpT{"d_pidTOFMinpT", 0.15, "Lower bound of track pT for TOF PID"}; Configurable d_pidTOFMaxpT{"d_pidTOFMaxpT", 20., "Upper bound of track pT for TOF PID"}; - - Configurable d_TPCNClsFindablePIDCut{"d_TPCNClsFindablePIDCut", 50., "Lower bound of TPC findable clusters for good PID"}; - Configurable b_requireTPC{"b_requireTPC", true, "Flag to require a positive Number of found clusters in TPC"}; - Configurable d_nSigmaTPC{"d_nSigmaTPC", 3., "Nsigma cut on TPC"}; Configurable d_nSigmaTOF{"d_nSigmaTOF", 3., "Nsigma cut on TOF"}; - + // topological cuts Configurable> pTBins{"pTBins", std::vector{hf_cuts_dplus_topikpi::pTBins_v}, "pT bin limits"}; Configurable> cuts{"DPlus_to_Pi_K_Pi_cuts", {hf_cuts_dplus_topikpi::cuts[0], npTBins, nCutVars, pTBinLabels, cutVarLabels}, "Dplus candidate selection per pT bin"}; + /* /// Selection on goodness of daughter tracks /// \note should be applied at candidate selection /// \param track is daughter track @@ -50,194 +53,107 @@ struct HFDplusToPiKPiCandidateSelector { template bool daughterSelection(const T& track) { - if (b_requireTPC.value && track.tpcNClsFound() == 0) { + if (track.tpcNClsFound() == 0) { return false; //is it clusters findable or found - need to check } return true; } + */ /// Candidate selections - /// \param hfCandProng3 is candidate + /// \param candidate is candidate /// \param trackPion1 is the first track with the pion hypothesis /// \param trackKaon is the track with the kaon hypothesis /// \param trackPion2 is the second track with the pion hypothesis /// \return true if candidate passes all cuts template - bool selection(const T1& hfCandProng3, const T2& trackPion1, const T2& trackKaon, const T2& trackPion2) + bool selection(const T1& candidate, const T2& trackPion1, const T2& trackKaon, const T2& trackPion2) { - auto candpT = hfCandProng3.pt(); + auto candpT = candidate.pt(); int pTBin = findBin(pTBins, candpT); if (pTBin == -1) { return false; } + // check that the candidate pT is within the analysis range if (candpT < d_pTCandMin || candpT > d_pTCandMax) { - return false; //check that the candidate pT is within the analysis range + return false; } + // cut on daughter pT if (trackPion1.pt() < cuts->get(pTBin, "pT Pi") || trackKaon.pt() < cuts->get(pTBin, "pT K") || trackPion2.pt() < cuts->get(pTBin, "pT Pi")) { - return false; // cut on daughter pT - } - if (std::abs(InvMassDPlus(hfCandProng3) - RecoDecay::getMassPDG(pdg::Code::kDPlus)) > cuts->get(pTBin, "deltaM")) { - return false; // invariant mass cut - } - if (hfCandProng3.decayLength() < cuts->get(pTBin, "decay length")) { return false; } - if (hfCandProng3.decayLengthXYNormalised() < cuts->get(pTBin, "normalized decay length XY")) { + // invariant-mass cut + if (std::abs(InvMassDPlus(candidate) - RecoDecay::getMassPDG(pdg::Code::kDPlus)) > cuts->get(pTBin, "deltaM")) { return false; } - if (hfCandProng3.cpa() < cuts->get(pTBin, "cos pointing angle")) { + if (candidate.decayLength() < cuts->get(pTBin, "decay length")) { return false; } - if (hfCandProng3.cpaXY() < cuts->get(pTBin, "cos pointing angle XY")) { + if (candidate.decayLengthXYNormalised() < cuts->get(pTBin, "normalized decay length XY")) { return false; } - if (std::abs(hfCandProng3.maxNormalisedDeltaIP()) > cuts->get(pTBin, "max normalized deltaIP")) { + if (candidate.cpa() < cuts->get(pTBin, "cos pointing angle")) { return false; } - return true; - } - - /// Check if track is ok for TPC PID - /// \param track is the track - /// \note function to be expanded - /// \return true if track is ok for TPC PID - template - bool validTPCPID(const T& track) - { - if (track.pt() < d_pidTPCMinpT || track.pt() >= d_pidTPCMaxpT) { + if (candidate.cpaXY() < cuts->get(pTBin, "cos pointing angle XY")) { return false; } - //if (track.TPCNClsFindable() < d_TPCNClsFindablePIDCut) { - // return false; - //} - return true; - } - - /// Check if track is ok for TOF PID - /// \param track is the track - /// \note function to be expanded - /// \return true if track is ok for TOF PID - template - bool validTOFPID(const T& track) - { - if (track.pt() < d_pidTOFMinpT || track.pt() >= d_pidTOFMaxpT) { + if (std::abs(candidate.maxNormalisedDeltaIP()) > cuts->get(pTBin, "max normalized deltaIP")) { return false; } return true; } - /// Check if track is compatible with given TPC Nsigma cut for a given flavour hypothesis - /// \param track is the track - /// \param nPDG is the flavour hypothesis PDG number - /// \param nSigmaCut is the nsigma threshold to test against - /// \note nPDG=211 pion nPDG=321 kaon - /// \return true if track satisfies TPC PID hypothesis for given Nsigma cut - template - bool selectionPIDTPC(const T& track, int nPDG, int nSigmaCut) + void process(aod::HfCandProng3 const& candidates, aod::BigTracksPID const&) { - double nSigma = 100.0; //arbitarily large value - nPDG = std::abs(nPDG); - if (nPDG == kPiPlus) { - nSigma = track.tpcNSigmaPi(); - } else if (nPDG == kKPlus) { - nSigma = track.tpcNSigmaKa(); - } else { - return false; - } - return std::abs(nSigma) < nSigmaCut; - } - - /// Check if track is compatible with given TOF NSigma cut for a given flavour hypothesis - /// \param track is the track - /// \param nPDG is the flavour hypothesis PDG number - /// \param nSigmaCut is the nSigma threshold to test against - /// \note nPDG=211 pion nPDG=321 kaon - /// \return true if track satisfies TOF PID hypothesis for given NSigma cut - template - bool selectionPIDTOF(const T& track, int nPDG, int nSigmaCut) - { - double nSigma = 100.0; //arbitarily large value - nPDG = std::abs(nPDG); - if (nPDG == kPiPlus) { - nSigma = track.tofNSigmaPi(); - } else if (nPDG == kKPlus) { - nSigma = track.tofNSigmaKa(); - } else { - return false; - } - return std::abs(nSigma) < nSigmaCut; - } - - /// PID selection on daughter track - /// \param track is the daughter track - /// \param nPDG is the PDG code of the flavour hypothesis - /// \note nPDG=211 pion nPDG=321 kaon - /// \return 1 if successful PID match, 0 if successful PID rejection, -1 if no PID info - template - int selectionPID(const T& track, int nPDG) - { - int statusTPC = -1; //no PID info - int statusTOF = -1; //no PID info - - if (validTPCPID(track)) { - if (!selectionPIDTPC(track, nPDG, d_nSigmaTPC)) { - statusTPC = 0; //rejected by PID - } else { - statusTPC = 1; //positive PID - } - } - - if (validTOFPID(track)) { - if (!selectionPIDTOF(track, nPDG, d_nSigmaTOF)) { - statusTOF = 0; //rejected by PID - } else { - statusTOF = 1; //positive PID - } - } + TrackSelectorPID selectorPion(kPiPlus); + selectorPion.setRangePtTPC(d_pidTPCMinpT, d_pidTPCMaxpT); + selectorPion.setRangeNSigmaTPC(-d_nSigmaTPC, d_nSigmaTPC); + selectorPion.setRangePtTOF(d_pidTOFMinpT, d_pidTOFMaxpT); + selectorPion.setRangeNSigmaTOF(-d_nSigmaTOF, d_nSigmaTOF); - //conservative PID strategy - if (statusTPC == 1 && statusTOF != 0) { - return 1; - } else if (statusTPC == 0 || statusTOF == 0) { - return 0; - } else { - return -1; - } - } + TrackSelectorPID selectorKaon(selectorPion); + selectorKaon.setPDG(kKPlus); - void process(aod::HfCandProng3 const& hfCandProng3s, aod::BigTracksPID const&) - { - for (auto& hfCandProng3 : hfCandProng3s) { //looping over 3 prong candidates + // looping over 3-prong candidates + for (auto& candidate : candidates) { - auto statusDplusToPiKPi = 0; // final selection flag : 0-rejected 1-accepted + // final selection flag: 0 - rejected, 1 - accepted + auto statusDplusToPiKPi = 0; - if (!(hfCandProng3.hfflag() & 1 << DecayType::DPlusToPiKPi)) { + if (!(candidate.hfflag() & 1 << DecayType::DPlusToPiKPi)) { hfSelDplusToPiKPiCandidate(statusDplusToPiKPi); continue; } - auto trackPos1 = hfCandProng3.index0_as(); //positive daughter (negative for the antiparticles) - auto trackNeg1 = hfCandProng3.index1_as(); //negative daughter (positive for the antiparticles) - auto trackPos2 = hfCandProng3.index2_as(); //positive daughter (negative for the antiparticles) + auto trackPos1 = candidate.index0_as(); // positive daughter (negative for the antiparticles) + auto trackNeg = candidate.index1_as(); // negative daughter (positive for the antiparticles) + auto trackPos2 = candidate.index2_as(); // positive daughter (negative for the antiparticles) + /* // daughter track validity selection - if (!daughterSelection(trackPos1) || !daughterSelection(trackNeg1) || !daughterSelection(trackPos2)) { + if (!daughterSelection(trackPos1) || + !daughterSelection(trackNeg) || + !daughterSelection(trackPos2)) { hfSelDplusToPiKPiCandidate(statusDplusToPiKPi); continue; } + */ // topological selection - if (!selection(hfCandProng3, trackPos1, trackNeg1, trackPos2)) { + if (!selection(candidate, trackPos1, trackNeg, trackPos2)) { hfSelDplusToPiKPiCandidate(statusDplusToPiKPi); continue; } - // pid selection - auto pionPlus1 = selectionPID(trackPos1, kPiPlus); - auto kaonMinus = selectionPID(trackNeg1, kKPlus); - auto pionPlus2 = selectionPID(trackPos2, kPiPlus); + // track-level PID selection + int pidTrackPos1Pion = selectorPion.getStatusTrackPIDAll(trackPos1); + int pidTrackNegKaon = selectorKaon.getStatusTrackPIDAll(trackNeg); + int pidTrackPos2Pion = selectorPion.getStatusTrackPIDAll(trackPos2); - if (pionPlus1 == 0 || kaonMinus == 0 || pionPlus2 == 0) { //exclude Dplus for PID + if (pidTrackPos1Pion == TrackSelectorPID::Status::PIDRejected || + pidTrackNegKaon == TrackSelectorPID::Status::PIDRejected || + pidTrackPos2Pion == TrackSelectorPID::Status::PIDRejected) { // exclude D± hfSelDplusToPiKPiCandidate(statusDplusToPiKPi); continue; } diff --git a/Analysis/Tasks/PWGHF/HFJpsiToEECandidateSelector.cxx b/Analysis/Tasks/PWGHF/HFJpsiToEECandidateSelector.cxx index 16d8fba506e57..13afe1ffe232d 100644 --- a/Analysis/Tasks/PWGHF/HFJpsiToEECandidateSelector.cxx +++ b/Analysis/Tasks/PWGHF/HFJpsiToEECandidateSelector.cxx @@ -13,11 +13,13 @@ /// /// \author Biao Zhang , CCNU /// \author Nima Zardoshti , CERN +/// \author Vít Kučera , CERN #include "Framework/runDataProcessing.h" #include "Framework/AnalysisTask.h" #include "AnalysisDataModel/HFSecondaryVertex.h" #include "AnalysisDataModel/HFCandidateSelectionTables.h" +#include "AnalysisCore/TrackSelectorPID.h" using namespace o2; using namespace o2::framework; @@ -30,15 +32,16 @@ struct HFJpsiToEECandidateSelector { Configurable d_pTCandMin{"d_pTCandMin", 0., "Lower bound of candidate pT"}; Configurable d_pTCandMax{"d_pTCandMax", 50., "Upper bound of candidate pT"}; - + // TPC Configurable d_pidTPCMinpT{"d_pidTPCMinpT", 0.15, "Lower bound of track pT for TPC PID"}; Configurable d_pidTPCMaxpT{"d_pidTPCMaxpT", 10., "Upper bound of track pT for TPC PID"}; - - Configurable d_TPCNClsFindablePIDCut{"d_TPCNClsFindablePIDCut", 70., "Lower bound of TPC findable clusters for good PID"}; Configurable d_nSigmaTPC{"d_nSigmaTPC", 3., "Nsigma cut on TPC only"}; + //Configurable d_TPCNClsFindablePIDCut{"d_TPCNClsFindablePIDCut", 70., "Lower bound of TPC findable clusters for good PID"}; + // topological cuts Configurable> pTBins{"pTBins", std::vector{hf_cuts_jpsi_toee::pTBins_v}, "pT bin limits"}; Configurable> cuts{"Jpsi_to_ee_cuts", {hf_cuts_jpsi_toee::cuts[0], npTBins, nCutVars, pTBinLabels, cutVarLabels}, "Jpsi candidate selection per pT bin"}; + /* /// Selection on goodness of daughter tracks /// \note should be applied at candidate selection /// \param track is daughter track @@ -46,121 +49,91 @@ struct HFJpsiToEECandidateSelector { template bool daughterSelection(const T& track) { - /*if (track.tpcNClsFound() == 0) { + if (track.tpcNClsFound() == 0) { return false; //is it clusters findable or found - need to check - }*/ + } return true; } + */ /// Conjugate-independent topological cuts - /// \param hfCandProng2 is candidate + /// \param candidate is candidate /// \param trackPositron is the track with the positron hypothesis /// \param trackElectron is the track with the electron hypothesis /// \return true if candidate passes all cuts template - bool selectionTopol(const T1& hfCandProng2, const T2& trackPositron, const T2& trackElectron) + bool selectionTopol(const T1& candidate, const T2& trackPositron, const T2& trackElectron) { - auto candpT = hfCandProng2.pt(); + auto candpT = candidate.pt(); auto pTBin = findBin(pTBins, candpT); if (pTBin == -1) { return false; } + // check that the candidate pT is within the analysis range if (candpT < d_pTCandMin || candpT >= d_pTCandMax) { - return false; //check that the candidate pT is within the analysis range + return false; } - if (std::abs(InvMassJpsiToEE(hfCandProng2) - RecoDecay::getMassPDG(pdg::Code::kJpsi)) > cuts->get(pTBin, "m")) { + // cut on invariant mass + if (std::abs(InvMassJpsiToEE(candidate) - RecoDecay::getMassPDG(pdg::Code::kJpsi)) > cuts->get(pTBin, "m")) { return false; } + // cut on daughter pT if (trackElectron.pt() < cuts->get(pTBin, "pT El") || trackPositron.pt() < cuts->get(pTBin, "pT El")) { - return false; //cut on daughter pT - } - if (std::abs(trackElectron.dcaPrim0()) > cuts->get(pTBin, "DCA_xy") || std::abs(trackPositron.dcaPrim0()) > cuts->get(pTBin, "DCA_xy")) { - return false; //cut on daughter dca - need to add secondary vertex constraint here - } - if (std::abs(trackElectron.dcaPrim1()) > cuts->get(pTBin, "DCA_z") || std::abs(trackPositron.dcaPrim1()) > cuts->get(pTBin, "DCA_z")) { - return false; //cut on daughter dca - need to add secondary vertex constraint here + return false; } - return true; - } - - /// Check if track is ok for TPC PID - /// \param track is the track - /// \note function to be expanded - /// \return true if track is ok for TPC PID - template - bool validTPCPID(const T& track) - { - if (track.pt() < d_pidTPCMinpT || track.pt() >= d_pidTPCMaxpT) { + // cut on daughter DCA - need to add secondary vertex constraint here + if (std::abs(trackElectron.dcaPrim0()) > cuts->get(pTBin, "DCA_xy") || std::abs(trackPositron.dcaPrim0()) > cuts->get(pTBin, "DCA_xy")) { return false; } - //if (track.TPCNClsFindable() < d_TPCNClsFindablePIDCut) return false; - return true; - } - /// Check if track is compatible with given TPC Nsigma cut for the electron hypothesis - /// \param track is the track - /// \param nSigmaCut is the nsigma threshold to test against - /// \return true if track satisfies TPC PID hypothesis for given Nsigma cut - template - bool selectionPIDTPC(const T& track, int nSigmaCut) - { - if (nSigmaCut > 999.) { - return true; + // cut on daughter DCA - need to add secondary vertex constraint here + if (std::abs(trackElectron.dcaPrim1()) > cuts->get(pTBin, "DCA_z") || std::abs(trackPositron.dcaPrim1()) > cuts->get(pTBin, "DCA_z")) { + return false; } - return std::abs(track.tpcNSigmaEl()) < nSigmaCut; - } - /// PID selection on daughter track - /// \param track is the daughter track - /// \return 1 if successful PID match, 0 if successful PID rejection, -1 if no PID info - template - int selectionPID(const T& track) - { - - if (validTPCPID(track)) { - if (!selectionPIDTPC(track, d_nSigmaTPC)) { - - return 0; //rejected by PID - } else { - return 1; //positive PID - } - } else { - return -1; //no PID info - } + return true; } - void process(aod::HfCandProng2 const& hfCandProng2s, aod::BigTracksPID const&) + void process(aod::HfCandProng2 const& candidates, aod::BigTracksPID const&) { + TrackSelectorPID selectorElectron(kElectron); + selectorElectron.setRangePtTPC(d_pidTPCMinpT, d_pidTPCMaxpT); + selectorElectron.setRangeNSigmaTPC(-d_nSigmaTPC, d_nSigmaTPC); - for (auto& hfCandProng2 : hfCandProng2s) { //looping over 2 prong candidates + // looping over 2-prong candidates + for (auto& candidate : candidates) { - auto trackPos = hfCandProng2.index0_as(); //positive daughter - auto trackNeg = hfCandProng2.index1_as(); //negative daughter + auto trackPos = candidate.index0_as(); // positive daughter + auto trackNeg = candidate.index1_as(); // negative daughter - if (!(hfCandProng2.hfflag() & 1 << DecayType::JpsiToEE)) { + if (!(candidate.hfflag() & 1 << DecayType::JpsiToEE)) { hfSelJpsiToEECandidate(0); continue; } + /* // daughter track validity selection if (!daughterSelection(trackPos) || !daughterSelection(trackNeg)) { hfSelJpsiToEECandidate(0); continue; } + */ - //implement filter bit 4 cut - should be done before this task at the track selection level - //need to add special cuts (additional cuts on decay length and d0 norm) + // implement filter bit 4 cut - should be done before this task at the track selection level + // need to add special cuts (additional cuts on decay length and d0 norm) - if (!selectionTopol(hfCandProng2, trackPos, trackNeg)) { + if (!selectionTopol(candidate, trackPos, trackNeg)) { hfSelJpsiToEECandidate(0); continue; } - if (selectionPID(trackPos) == 0 || selectionPID(trackNeg) == 0) { + // track-level PID selection + if (selectorElectron.getStatusTrackPIDTPC(trackPos) == TrackSelectorPID::Status::PIDRejected || + selectorElectron.getStatusTrackPIDTPC(trackNeg) == TrackSelectorPID::Status::PIDRejected) { hfSelJpsiToEECandidate(0); continue; } diff --git a/Analysis/Tasks/PWGHF/HFLcCandidateSelector.cxx b/Analysis/Tasks/PWGHF/HFLcCandidateSelector.cxx index 2ac20fbc01ad5..08446527b1b2a 100644 --- a/Analysis/Tasks/PWGHF/HFLcCandidateSelector.cxx +++ b/Analysis/Tasks/PWGHF/HFLcCandidateSelector.cxx @@ -13,11 +13,13 @@ /// /// \author Luigi Dello Stritto , University and INFN SALERNO /// \author Nima Zardoshti , CERN +/// \author Vít Kučera , CERN #include "Framework/runDataProcessing.h" #include "Framework/AnalysisTask.h" #include "AnalysisDataModel/HFSecondaryVertex.h" #include "AnalysisDataModel/HFCandidateSelectionTables.h" +#include "AnalysisCore/TrackSelectorPID.h" using namespace o2; using namespace o2::framework; @@ -30,22 +32,23 @@ struct HFLcCandidateSelector { Configurable d_pTCandMin{"d_pTCandMin", 0., "Lower bound of candidate pT"}; Configurable d_pTCandMax{"d_pTCandMax", 36., "Upper bound of candidate pT"}; - + Configurable d_FilterPID{"d_FilterPID", true, "Bool to use or not the PID at filtering level"}; + // TPC Configurable d_pidTPCMinpT{"d_pidTPCMinpT", 0.1, "Lower bound of track pT for TPC PID"}; Configurable d_pidTPCMaxpT{"d_pidTPCMaxpT", 1., "Upper bound of track pT for TPC PID"}; - Configurable d_pidTOFMinpT{"d_pidTOFMinpT", 0.5, "Lower bound of track pT for TOF PID"}; - Configurable d_pidTOFMaxpT{"d_pidTOFMaxpT", 2.5, "Upper bound of track pT for TOF PID"}; - - Configurable d_FilterPID{"d_FilterPID", true, "Bool to use or not the PID at filtering level"}; - Configurable d_TPCNClsFindablePIDCut{"d_TPCNClsFindablePIDCut", 70., "Lower bound of TPC findable clusters for good PID"}; Configurable d_nSigmaTPC{"d_nSigmaTPC", 3., "Nsigma cut on TPC only"}; Configurable d_nSigmaTPCCombined{"d_nSigmaTPCCombined", 5., "Nsigma cut on TPC combined with TOF"}; + //Configurable d_TPCNClsFindablePIDCut{"d_TPCNClsFindablePIDCut", 70., "Lower bound of TPC findable clusters for good PID"}; + // TOF + Configurable d_pidTOFMinpT{"d_pidTOFMinpT", 0.5, "Lower bound of track pT for TOF PID"}; + Configurable d_pidTOFMaxpT{"d_pidTOFMaxpT", 2.5, "Upper bound of track pT for TOF PID"}; Configurable d_nSigmaTOF{"d_nSigmaTOF", 3., "Nsigma cut on TOF only"}; Configurable d_nSigmaTOFCombined{"d_nSigmaTOFCombined", 5., "Nsigma cut on TOF combined with TPC"}; - + // topological cuts Configurable> pTBins{"pTBins", std::vector{hf_cuts_lc_topkpi::pTBins_v}, "pT bin limits"}; Configurable> cuts{"Lc_to_p_K_pi_cuts", {hf_cuts_lc_topkpi::cuts[0], npTBins, nCutVars, pTBinLabels, cutVarLabels}, "Lc candidate selection per pT bin"}; + /* /// Selection on goodness of daughter tracks /// \note should be applied at candidate selection /// \param track is daughter track @@ -53,72 +56,74 @@ struct HFLcCandidateSelector { template bool daughterSelection(const T& track) { - if (track.sign() == 0) { - return false; - } - /*if (track.tpcNClsFound() == 0) { + if (track.tpcNClsFound() == 0) { return false; //is it clusters findable or found - need to check - }*/ + } return true; } + */ /// Conjugate-independent topological cuts - /// \param hfCandProng3 is candidate + /// \param candidate is candidate /// \return true if candidate passes all cuts template - bool selectionTopol(const T& hfCandProng3) + bool selectionTopol(const T& candidate) { - auto candpT = hfCandProng3.pt(); + auto candpT = candidate.pt(); int pTBin = findBin(pTBins, candpT); if (pTBin == -1) { return false; } + // check that the candidate pT is within the analysis range if (candpT < d_pTCandMin || candpT >= d_pTCandMax) { - return false; //check that the candidate pT is within the analysis range + return false; } - if (hfCandProng3.cpa() <= cuts->get(pTBin, "cos pointing angle")) { - return false; //cosine of pointing angle + // cosine of pointing angle + if (candidate.cpa() <= cuts->get(pTBin, "cos pointing angle")) { + return false; } - /* if (hfCandProng3.chi2PCA() > cuts[pTBin][5]) { //candidate DCA + //candidate DCA + /* if (candidate.chi2PCA() > cuts[pTBin][5]) { return false; }*/ - if (hfCandProng3.decayLength() <= cuts->get(pTBin, "decay length")) { + if (candidate.decayLength() <= cuts->get(pTBin, "decay length")) { return false; } return true; } /// Conjugate-dependent topological cuts - /// \param hfCandProng3 is candidate + /// \param candidate is candidate /// \param trackProton is the track with the proton hypothesis /// \param trackPion is the track with the pion hypothesis /// \param trackKaon is the track with the kaon hypothesis /// \return true if candidate passes all cuts for the given Conjugate template - bool selectionTopolConjugate(const T1& hfCandProng3, const T2& trackProton, const T2& trackKaon, const T2& trackPion) + bool selectionTopolConjugate(const T1& candidate, const T2& trackProton, const T2& trackKaon, const T2& trackPion) { - auto candpT = hfCandProng3.pt(); + auto candpT = candidate.pt(); int pTBin = findBin(pTBins, candpT); if (pTBin == -1) { return false; } + // cut on daughter pT if (trackProton.pt() < cuts->get(pTBin, "pT p") || trackKaon.pt() < cuts->get(pTBin, "pT K") || trackPion.pt() < cuts->get(pTBin, "pT Pi")) { - return false; //cut on daughter pT + return false; } - if (trackProton.globalIndex() == hfCandProng3.index0Id()) { - if (std::abs(InvMassLcpKpi(hfCandProng3) - RecoDecay::getMassPDG(pdg::Code::kLambdaCPlus)) > cuts->get(pTBin, "m")) { + if (trackProton.globalIndex() == candidate.index0Id()) { + if (std::abs(InvMassLcpKpi(candidate) - RecoDecay::getMassPDG(pdg::Code::kLambdaCPlus)) > cuts->get(pTBin, "m")) { return false; } } else { - if (std::abs(InvMassLcpiKp(hfCandProng3) - RecoDecay::getMassPDG(pdg::Code::kLambdaCPlus)) > cuts->get(pTBin, "m")) { + if (std::abs(InvMassLcpiKp(candidate) - RecoDecay::getMassPDG(pdg::Code::kLambdaCPlus)) > cuts->get(pTBin, "m")) { return false; } } @@ -126,191 +131,96 @@ struct HFLcCandidateSelector { return true; } - /// Check if track is ok for TPC PID - /// \param track is the track - /// \note function to be expanded - /// \return true if track is ok for TPC PID - template - bool validTPCPID(const T& track) + void process(aod::HfCandProng3 const& candidates, aod::BigTracksPID const&) { - if (track.pt() < d_pidTPCMinpT || track.pt() >= d_pidTPCMaxpT) { - return false; - } - //if (track.TPCNClsFindable() < d_TPCNClsFindablePIDCut) return false; - return true; - } + TrackSelectorPID selectorPion(kPiPlus); + selectorPion.setRangePtTPC(d_pidTPCMinpT, d_pidTPCMaxpT); + selectorPion.setRangeNSigmaTPC(-d_nSigmaTPC, d_nSigmaTPC); + selectorPion.setRangeNSigmaTPCCondTOF(-d_nSigmaTPCCombined, d_nSigmaTPCCombined); + selectorPion.setRangePtTOF(d_pidTOFMinpT, d_pidTOFMaxpT); + selectorPion.setRangeNSigmaTOF(-d_nSigmaTOF, d_nSigmaTOF); + selectorPion.setRangeNSigmaTOFCondTPC(-d_nSigmaTOFCombined, d_nSigmaTOFCombined); - /// Check if track is ok for TOF PID - /// \param track is the track - /// \note function to be expanded - /// \return true if track is ok for TOF PID - template - bool validTOFPID(const T& track) - { - if (track.pt() < d_pidTOFMinpT || track.pt() >= d_pidTOFMaxpT) { - return false; - } - return true; - } + TrackSelectorPID selectorKaon(selectorPion); + selectorKaon.setPDG(kKPlus); - /// Check if track is compatible with given TPC Nsigma cut for a given flavour hypothesis - /// \param track is the track - /// \param nPDG is the flavour hypothesis PDG number - /// \param nSigmaCut is the nsigma threshold to test against - /// \return true if track satisfies TPC PID hypothesis for given Nsigma cut - template - bool selectionPIDTPC(const T& track, int nPDG, int nSigmaCut) - { - double nSigma = 100.; //arbitarily large value - nPDG = std::abs(nPDG); - if (nPDG == kProton) { - nSigma = track.tpcNSigmaPr(); - } else if (nPDG == kKPlus) { - nSigma = track.tpcNSigmaKa(); - } else if (nPDG == kPiPlus) { - nSigma = track.tpcNSigmaPi(); - } else { - return false; - } - return std::abs(nSigma) < nSigmaCut; - } + TrackSelectorPID selectorProton(selectorPion); + selectorProton.setPDG(kProton); - /// Check if track is compatible with given TOF NSigma cut for a given flavour hypothesis - /// \param track is the track - /// \param nPDG is the flavour hypothesis PDG number - /// \param nSigmaCut is the nSigma threshold to test against - /// \return true if track satisfies TOF PID hypothesis for given NSigma cut - template - bool selectionPIDTOF(const T& track, int nPDG, int nSigmaCut) - { - double nSigma = 100.; //arbitarily large value - nPDG = std::abs(nPDG); - if (nPDG == kProton) { - nSigma = track.tofNSigmaPr(); - } else if (nPDG == kKPlus) { - nSigma = track.tofNSigmaKa(); - } else if (nPDG == kPiPlus) { - nSigma = track.tofNSigmaPi(); - } else { - return false; - } - return std::abs(nSigma) < nSigmaCut; - } + // looping over 3-prong candidates + for (auto& candidate : candidates) { - /// PID selection on daughter track - /// \param track is the daughter track - /// \param nPDG is the PDG code of the flavour hypothesis - /// \note nPDG=2212 nPDG=211 pion nPDG=321 kaon - /// \return 1 if successful PID match, 0 if successful PID rejection, -1 if no PID info - template - int selectionPID(const T& track, int nPDG) - { - int statusTPC = -1; - int statusTOF = -1; - - if (validTPCPID(track)) { - if (!selectionPIDTPC(track, nPDG, d_nSigmaTPC)) { - if (!selectionPIDTPC(track, nPDG, d_nSigmaTPCCombined)) { - statusTPC = 0; //rejected by PID - } else { - statusTPC = 1; //potential to be acceepted if combined with TOF - } - } else { - statusTPC = 2; //positive PID - } - } else { - statusTPC = -1; //no PID info - } - - if (validTOFPID(track)) { - if (!selectionPIDTOF(track, nPDG, d_nSigmaTOF)) { - if (!selectionPIDTOF(track, nPDG, d_nSigmaTOFCombined)) { - statusTOF = 0; //rejected by PID - } else { - statusTOF = 1; //potential to be acceepted if combined with TOF - } - } else { - statusTOF = 2; //positive PID - } - } else { - statusTOF = -1; //no PID info - } - - if (statusTPC == 2 || statusTOF == 2) { - return 1; //what if we have 2 && 0 ? - } else if (statusTPC == 1 && statusTOF == 1) { - return 1; - } else if (statusTPC == 0 || statusTOF == 0) { - return 0; - } else { - return -1; - } - } - - void process(aod::HfCandProng3 const& hfCandProng3s, aod::BigTracksPID const&) - { - for (auto& hfCandProng3 : hfCandProng3s) { - // final selection flag : 0-rejected 1-accepted + // final selection flag: 0 - rejected, 1 - accepted auto statusLcpKpi = 0; auto statusLcpiKp = 0; - if (!(hfCandProng3.hfflag() & 1 << DecayType::LcToPKPi)) { + if (!(candidate.hfflag() & 1 << DecayType::LcToPKPi)) { hfSelLcCandidate(statusLcpKpi, statusLcpiKp); continue; } - auto trackPos1 = hfCandProng3.index0_as(); //positive daughter (negative for the antiparticles) - auto trackNeg1 = hfCandProng3.index1_as(); //negative daughter (positive for the antiparticles) - auto trackPos2 = hfCandProng3.index2_as(); //positive daughter (negative for the antiparticles) + auto trackPos1 = candidate.index0_as(); // positive daughter (negative for the antiparticles) + auto trackNeg = candidate.index1_as(); // negative daughter (positive for the antiparticles) + auto trackPos2 = candidate.index2_as(); // positive daughter (negative for the antiparticles) + + /* // daughter track validity selection - if (!daughterSelection(trackPos1) || !daughterSelection(trackNeg1) || !daughterSelection(trackPos2)) { + if (!daughterSelection(trackPos1) || !daughterSelection(trackNeg) || !daughterSelection(trackPos2)) { hfSelLcCandidate(statusLcpKpi, statusLcpiKp); continue; } + */ - auto pidLcpKpi = -1; - auto pidLcpiKp = -1; + // implement filter bit 4 cut - should be done before this task at the track selection level - //implement filter bit 4 cut - should be done before this task at the track selection level - - //conjugate-independent topological selection - if (!selectionTopol(hfCandProng3)) { + // conjugate-independent topological selection + if (!selectionTopol(candidate)) { hfSelLcCandidate(statusLcpKpi, statusLcpiKp); continue; } - //conjugate-dependent topological selection for Lc + // conjugate-dependent topological selection for Lc - bool topolLcpKpi = selectionTopolConjugate(hfCandProng3, trackPos1, trackNeg1, trackPos2); - bool topolLcpiKp = selectionTopolConjugate(hfCandProng3, trackPos2, trackNeg1, trackPos1); + bool topolLcpKpi = selectionTopolConjugate(candidate, trackPos1, trackNeg, trackPos2); + bool topolLcpiKp = selectionTopolConjugate(candidate, trackPos2, trackNeg, trackPos1); if (!topolLcpKpi && !topolLcpiKp) { hfSelLcCandidate(statusLcpKpi, statusLcpiKp); continue; } + auto pidLcpKpi = -1; + auto pidLcpiKp = -1; + if (!d_FilterPID) { // PID non applied pidLcpKpi = 1; pidLcpiKp = 1; } else { - int proton1 = selectionPID(trackPos1, kProton); - int proton2 = selectionPID(trackPos2, kProton); - int kaonMinus = selectionPID(trackNeg1, kKPlus); - int pionPlus1 = selectionPID(trackPos1, kPiPlus); - int pionPlus2 = selectionPID(trackPos2, kPiPlus); - - if (proton1 == 0 || kaonMinus == 0 || pionPlus2 == 0) { - pidLcpKpi = 0; //exclude LcpKpi - } - if (proton1 == 1 && kaonMinus == 1 && pionPlus2 == 1) { - pidLcpKpi = 1; //accept LcpKpi - } - if (proton2 == 0 || kaonMinus == 0 || pionPlus1 == 0) { - pidLcpiKp = 0; //exclude LcpiKp + // track-level PID selection + int pidTrackPos1Proton = selectorProton.getStatusTrackPIDAll(trackPos1); + int pidTrackPos2Proton = selectorProton.getStatusTrackPIDAll(trackPos2); + int pidTrackPos1Pion = selectorPion.getStatusTrackPIDAll(trackPos1); + int pidTrackPos2Pion = selectorPion.getStatusTrackPIDAll(trackPos2); + int pidTrackNegKaon = selectorKaon.getStatusTrackPIDAll(trackNeg); + + if (pidTrackPos1Proton == TrackSelectorPID::Status::PIDAccepted && + pidTrackNegKaon == TrackSelectorPID::Status::PIDAccepted && + pidTrackPos2Pion == TrackSelectorPID::Status::PIDAccepted) { + pidLcpKpi = 1; // accept LcpKpi + } else if (pidTrackPos1Proton == TrackSelectorPID::Status::PIDRejected || + pidTrackNegKaon == TrackSelectorPID::Status::PIDRejected || + pidTrackPos2Pion == TrackSelectorPID::Status::PIDRejected) { + pidLcpKpi = 0; // exclude LcpKpi } - if (proton2 == 1 && kaonMinus == 1 && pionPlus1 == 1) { - pidLcpiKp = 1; //accept LcpiKp + if (pidTrackPos2Proton == TrackSelectorPID::Status::PIDAccepted && + pidTrackNegKaon == TrackSelectorPID::Status::PIDAccepted && + pidTrackPos1Pion == TrackSelectorPID::Status::PIDAccepted) { + pidLcpiKp = 1; // accept LcpiKp + } else if (pidTrackPos1Pion == TrackSelectorPID::Status::PIDRejected || + pidTrackNegKaon == TrackSelectorPID::Status::PIDRejected || + pidTrackPos2Proton == TrackSelectorPID::Status::PIDRejected) { + pidLcpiKp = 0; // exclude LcpiKp } } @@ -320,10 +230,10 @@ struct HFLcCandidateSelector { } if ((pidLcpKpi == -1 || pidLcpKpi == 1) && topolLcpKpi) { - statusLcpKpi = 1; //identified as LcpKpi + statusLcpKpi = 1; // identified as LcpKpi } if ((pidLcpiKp == -1 || pidLcpiKp == 1) && topolLcpiKp) { - statusLcpiKp = 1; //identified as LcpiKp + statusLcpiKp = 1; // identified as LcpiKp } hfSelLcCandidate(statusLcpKpi, statusLcpiKp); diff --git a/Analysis/Tasks/PWGHF/HFXicToPKPiCandidateSelector.cxx b/Analysis/Tasks/PWGHF/HFXicToPKPiCandidateSelector.cxx index 43d655e55ed8b..8d38d47fa50d0 100644 --- a/Analysis/Tasks/PWGHF/HFXicToPKPiCandidateSelector.cxx +++ b/Analysis/Tasks/PWGHF/HFXicToPKPiCandidateSelector.cxx @@ -13,12 +13,13 @@ /// \note Inspired from HFLcCandidateSelector.cxx /// /// \author Mattia Faggin , University and INFN PADOVA +/// \author Vít Kučera , CERN #include "Framework/runDataProcessing.h" #include "Framework/AnalysisTask.h" #include "AnalysisDataModel/HFSecondaryVertex.h" #include "AnalysisDataModel/HFCandidateSelectionTables.h" -#include "AnalysisCore/HFSelectorCuts.h" +#include "AnalysisCore/TrackSelectorPID.h" using namespace o2; using namespace o2::framework; @@ -27,28 +28,27 @@ using namespace o2::analysis::hf_cuts_xic_topkpi; /// Struct for applying Xic selection cuts struct HFXicToPKPiCandidateSelector { - Produces hfSelXicToPKPiCandidate; - Configurable d_FilterPID{"d_FilterPID", true, "Bool to use or not the PID at filtering level"}; - Configurable d_pTCandMin{"d_pTCandMin", 0., "Lower bound of candidate pT"}; Configurable d_pTCandMax{"d_pTCandMax", 36., "Upper bound of candidate pT"}; - + Configurable d_FilterPID{"d_FilterPID", true, "Bool to use or not the PID at filtering level"}; + // TPC Configurable d_pidTPCMinpT{"d_pidTPCMinpT", 0.15, "Lower bound of track pT for TPC PID"}; Configurable d_pidTPCMaxpT{"d_pidTPCMaxpT", 1., "Upper bound of track pT for TPC PID"}; - Configurable d_pidTOFMinpT{"d_pidTOFMinpT", 0.5, "Lower bound of track pT for TOF PID"}; - Configurable d_pidTOFMaxpT{"d_pidTOFMaxpT", 4., "Upper bound of track pT for TOF PID"}; - - Configurable d_TPCNClsFindablePIDCut{"d_TPCNClsFindablePIDCut", 70., "Lower bound of TPC findable clusters for good PID"}; Configurable d_nSigmaTPC{"d_nSigmaTPC", 3., "Nsigma cut on TPC only"}; Configurable d_nSigmaTPCCombined{"d_nSigmaTPCCombined", 5., "Nsigma cut on TPC combined with TOF"}; + //Configurable d_TPCNClsFindablePIDCut{"d_TPCNClsFindablePIDCut", 70., "Lower bound of TPC findable clusters for good PID"}; + // TOF + Configurable d_pidTOFMinpT{"d_pidTOFMinpT", 0.5, "Lower bound of track pT for TOF PID"}; + Configurable d_pidTOFMaxpT{"d_pidTOFMaxpT", 4., "Upper bound of track pT for TOF PID"}; Configurable d_nSigmaTOF{"d_nSigmaTOF", 3., "Nsigma cut on TOF only"}; Configurable d_nSigmaTOFCombined{"d_nSigmaTOFCombined", 5., "Nsigma cut on TOF combined with TPC"}; - + // topological cuts Configurable> pTBins{"pTBins", std::vector{hf_cuts_xic_topkpi::pTBins_v}, "pT bin limits"}; Configurable> cuts{"Xic_to_p_K_pi_cuts", {hf_cuts_xic_topkpi::cuts[0], npTBins, nCutVars, pTBinLabels, cutVarLabels}, "Xic candidate selection per pT bin"}; + /* /// Selection on goodness of daughter tracks /// \note should be applied at candidate selection /// \param track is daughter track @@ -56,68 +56,73 @@ struct HFXicToPKPiCandidateSelector { template bool daughterSelection(const T& track) { - /*if (track.tpcNClsFound() == 0) { + if (track.tpcNClsFound() == 0) { return false; //is it clusters findable or found - need to check - }*/ + } return true; } + */ /// Conjugate-independent topological cuts - /// \param hfCandProng3 is candidate + /// \param candidate is candidate /// \return true if candidate passes all cuts template - bool selectionTopol(const T& hfCandProng3) + bool selectionTopol(const T& candidate) { - auto candpT = hfCandProng3.pt(); + auto candpT = candidate.pt(); int pTBin = findBin(pTBins, candpT); if (pTBin == -1) { return false; } + // check that the candidate pT is within the analysis range if (candpT < d_pTCandMin || candpT >= d_pTCandMax) { - return false; //check that the candidate pT is within the analysis range + return false; } - if (hfCandProng3.cpa() <= cuts->get(pTBin, "cos pointing angle")) { - return false; //cosine of pointing angle + // cosine of pointing angle + if (candidate.cpa() <= cuts->get(pTBin, "cos pointing angle")) { + return false; } - /* if (hfCandProng3.chi2PCA() > cuts->get(pTBin, "DCA")) { //candidate DCA + // candidate DCA + /* if (candidate.chi2PCA() > cuts->get(pTBin, "DCA")) { return false; }*/ - if (hfCandProng3.decayLength() <= cuts->get(pTBin, "decay length")) { + if (candidate.decayLength() <= cuts->get(pTBin, "decay length")) { return false; } return true; } /// Conjugate-dependent topological cuts - /// \param hfCandProng3 is candidate + /// \param candidate is candidate /// \param trackProton is the track with the proton hypothesis /// \param trackPion is the track with the pion hypothesis /// \param trackKaon is the track with the kaon hypothesis /// \return true if candidate passes all cuts for the given Conjugate template - bool selectionTopolConjugate(const T1& hfCandProng3, const T2& trackProton, const T2& trackKaon, const T2& trackPion) + bool selectionTopolConjugate(const T1& candidate, const T2& trackProton, const T2& trackKaon, const T2& trackPion) { - auto candpT = hfCandProng3.pt(); + auto candpT = candidate.pt(); int pTBin = findBin(pTBins, candpT); if (pTBin == -1) { return false; } + // cut on daughter pT if (trackProton.pt() < cuts->get(pTBin, "pT p") || trackKaon.pt() < cuts->get(pTBin, "pT K") || trackPion.pt() < cuts->get(pTBin, "pT Pi")) { - return false; //cut on daughter pT + return false; } - if (trackProton.globalIndex() == hfCandProng3.index0Id()) { - if (std::abs(InvMassXicToPKPi(hfCandProng3) - RecoDecay::getMassPDG(pdg::Code::kXiCPlus)) > cuts->get(pTBin, "m")) { + if (trackProton.globalIndex() == candidate.index0Id()) { + if (std::abs(InvMassXicToPKPi(candidate) - RecoDecay::getMassPDG(pdg::Code::kXiCPlus)) > cuts->get(pTBin, "m")) { return false; } } else { - if (std::abs(InvMassXicToPiKP(hfCandProng3) - RecoDecay::getMassPDG(pdg::Code::kXiCPlus)) > cuts->get(pTBin, "m")) { + if (std::abs(InvMassXicToPiKP(candidate) - RecoDecay::getMassPDG(pdg::Code::kXiCPlus)) > cuts->get(pTBin, "m")) { return false; } } @@ -125,280 +130,109 @@ struct HFXicToPKPiCandidateSelector { return true; } - /// Check if track is ok for TPC PID - /// \param track is the track - /// \note function to be expanded - /// \return true if track is ok for TPC PID - template - bool validTPCPID(const T& track) - { - if (track.pt() < d_pidTPCMinpT || track.pt() >= d_pidTPCMaxpT) { - return false; - } - //if (track.TPCNClsFindable() < d_TPCNClsFindablePIDCut) return false; - return true; - } - - /// Check if track is ok for TOF PID - /// \param track is the track - /// \note function to be expanded - /// \return true if track is ok for TOF PID - template - bool validTOFPID(const T& track) - { - if (track.pt() < d_pidTOFMinpT || track.pt() >= d_pidTOFMaxpT) { - return false; - } - return true; - } - - /// Check if track is compatible with given TPC Nsigma cut for a given flavour hypothesis - /// \param track is the track - /// \param nPDG is the flavour hypothesis PDG number - /// \param nSigmaCut is the nsigma threshold to test against - /// \note nPDG=2212 proton nPDG=211 pion nPDG=321 kaon - /// \return true if track satisfies TPC PID hypothesis for given Nsigma cut - template - bool selectionPIDTPC(const T& track, int nPDG, int nSigmaCut) + void process(aod::HfCandProng3 const& candidates, aod::BigTracksPID const&) { - double nSigma = 99.; //arbitarily large value - nPDG = std::abs(nPDG); - if (nPDG == kProton) { - nSigma = track.tpcNSigmaPr(); - } else if (nPDG == kKPlus) { - nSigma = track.tpcNSigmaKa(); - } else if (nPDG == kPiPlus) { - nSigma = track.tpcNSigmaPi(); - } else { - return false; - } + TrackSelectorPID selectorPion(kPiPlus); + selectorPion.setRangePtTPC(d_pidTPCMinpT, d_pidTPCMaxpT); + selectorPion.setRangeNSigmaTPC(-d_nSigmaTPC, d_nSigmaTPC); + selectorPion.setRangeNSigmaTPCCondTOF(-d_nSigmaTPCCombined, d_nSigmaTPCCombined); + selectorPion.setRangePtTOF(d_pidTOFMinpT, d_pidTOFMaxpT); + selectorPion.setRangeNSigmaTOF(-d_nSigmaTOF, d_nSigmaTOF); + selectorPion.setRangeNSigmaTOFCondTPC(-d_nSigmaTOFCombined, d_nSigmaTOFCombined); - return std::abs(nSigma) < nSigmaCut; - } - - /// Check if track is compatible with given TOF NSigma cut for a given flavour hypothesis - /// \param track is the track - /// \param nPDG is the flavour hypothesis PDG number - /// \param nSigmaCut is the nSigma threshold to test against - /// \note nPDG=2212 proton nPDG=211 pion nPDG=321 kaon - /// \return true if track satisfies TOF PID hypothesis for given NSigma cut - template - bool selectionPIDTOF(const T& track, int nPDG, int nSigmaCut) - { - double nSigma = 99.; //arbitarily large value - nPDG = std::abs(nPDG); - if (nPDG == kProton) { - nSigma = track.tofNSigmaPr(); - } else if (nPDG == kKPlus) { - nSigma = track.tofNSigmaKa(); - } else if (nPDG == kPiPlus) { - nSigma = track.tofNSigmaPi(); - } else { - return false; - } + TrackSelectorPID selectorKaon(selectorPion); + selectorKaon.setPDG(kKPlus); - return std::abs(nSigma) < nSigmaCut; - } + TrackSelectorPID selectorProton(selectorPion); + selectorProton.setPDG(kProton); - /// PID selection on daughter track - /// \param track is the daughter track - /// \param nPDG is the PDG code of the flavour hypothesis - /// \note nPDG=2212 nPDG=211 pion nPDG=321 kaon - /// \return 1 if successful PID match, 0 if successful PID rejection, -1 if no PID info - template - int selectionPID(const T& track, int nPDG) - { - int statusTPC = -1; - int statusTOF = -1; - - if (validTPCPID(track)) { - if (!selectionPIDTPC(track, nPDG, d_nSigmaTPC)) { - if (!selectionPIDTPC(track, nPDG, d_nSigmaTPCCombined)) { - statusTPC = 0; //rejected by PID - } else { - statusTPC = 1; //potential to be acceepted if combined with TOF - } - } else { - statusTPC = 2; //positive PID - } - } else { - statusTPC = -1; //no PID info - } + // looping over 3-prong candidates + for (auto& candidate : candidates) { - if (validTOFPID(track)) { - if (!selectionPIDTOF(track, nPDG, d_nSigmaTOF)) { - if (!selectionPIDTOF(track, nPDG, d_nSigmaTOFCombined)) { - statusTOF = 0; //rejected by PID - } else { - statusTOF = 1; //potential to be acceepted if combined with TOF - } - } else { - statusTOF = 2; //positive PID - } - } else { - statusTOF = -1; //no PID info - } - - if (statusTPC == 2 || statusTOF == 2) { - return 1; //what if we have 2 && 0 ? - } else if (statusTPC == 1 && statusTOF == 1) { - return 1; - } else if (statusTPC == 0 || statusTOF == 0) { - return 0; - } else { - return -1; - } - - /* - /// alternative: conservative PID - - /// TPC - if (validTPCPID(track)) { - if (!selectionPIDTPC(track, nPDG, d_nSigmaTPC)) { - statusTPC = 0; //rejected by PID - } else { - statusTPC = 2; //positive PID - } - } - else{ - statusTPC = -1; //no PID info - } - - /// TOF - if (validTOFPID(track)) { - if (!selectionPIDTOF(track, nPDG, d_nSigmaTOF)) { - statusTOF = 0; //rejected by PID - } else { - statusTOF = 2; //positive PID - } - } - else statusTOF = -1; //no PID info - - /// Conservative PID (no need to combine TPC and TOF) - /// case 1. if both PID dectectors info is missing: keep for analysis - /// case 2. if one of the PID detector info is missing: consider the other detector only - /// * the detector accepts the track: keep - /// * the detector does not accept the track: reject - /// case 3. if either at least TPC or TOF accept the track: keep - /// (even if the other would reject it) - if( statusTPC==-1 && statusTOF==-1 ) return -1; // case 1. - else{ - if( statusTPC==0 && statusTOF==0 ) return 0; - else if( statusTPC==-1 && statusTOF==0 ) return 0; - else if( statusTPC==0 && statusTOF==-1 ) return 0; - else return 1; - } - */ - } - - void process(aod::HfCandProng3 const& hfCandProng3s, aod::BigTracksPID const&) - { - for (auto& hfCandProng3 : hfCandProng3s) { //looping over 3 prong candidates - - // final selection flag : 0-rejected 1-accepted + // final selection flag: 0 - rejected, 1 - accepted auto statusXicToPKPi = 0; auto statusXicToPiKP = 0; - if (!(hfCandProng3.hfflag() & 1 << DecayType::XicToPKPi)) { + if (!(candidate.hfflag() & 1 << DecayType::XicToPKPi)) { hfSelXicToPKPiCandidate(statusXicToPKPi, statusXicToPiKP); continue; } - auto trackPos1 = hfCandProng3.index0_as(); //positive daughter (negative for the antiparticles) - auto trackNeg1 = hfCandProng3.index1_as(); //negative daughter (positive for the antiparticles) - auto trackPos2 = hfCandProng3.index2_as(); //positive daughter (negative for the antiparticles) - - bool topolXicToPKPi = true; - bool topolXicToPiKP = true; - auto pidXicToPKPi = -1; - auto pidXicToPiKP = -1; - auto kaonNeg = -1; - auto prot1 = -1; - auto prot2 = -1; - auto pion1 = -1; - auto pion2 = -1; - //proton = -1; - //kaonMinus = -1; - //pionPlus = -1; + auto trackPos1 = candidate.index0_as(); // positive daughter (negative for the antiparticles) + auto trackNeg = candidate.index1_as(); // negative daughter (positive for the antiparticles) + auto trackPos2 = candidate.index2_as(); // positive daughter (negative for the antiparticles) + /* // daughter track validity selection - if (!daughterSelection(trackPos1) || !daughterSelection(trackNeg1) || !daughterSelection(trackPos2)) { + if (!daughterSelection(trackPos1) || !daughterSelection(trackNeg) || !daughterSelection(trackPos2)) { hfSelXicToPKPiCandidate(statusXicToPKPi, statusXicToPiKP); continue; } + */ - //implement filter bit 4 cut - should be done before this task at the track selection level + // implement filter bit 4 cut - should be done before this task at the track selection level - //conjugate-independent topological selection - if (!selectionTopol(hfCandProng3)) { + // conjugate-independent topological selection + if (!selectionTopol(candidate)) { hfSelXicToPKPiCandidate(statusXicToPKPi, statusXicToPiKP); continue; } - //conjugate-dependent topplogical selection for Xic + // conjugate-dependent topplogical selection for Xic - topolXicToPKPi = selectionTopolConjugate(hfCandProng3, trackPos1, trackNeg1, trackPos2); - topolXicToPiKP = selectionTopolConjugate(hfCandProng3, trackPos2, trackNeg1, trackPos1); + bool topolXicToPKPi = selectionTopolConjugate(candidate, trackPos1, trackNeg, trackPos2); + bool topolXicToPiKP = selectionTopolConjugate(candidate, trackPos2, trackNeg, trackPos1); if (!topolXicToPKPi && !topolXicToPiKP) { hfSelXicToPKPiCandidate(statusXicToPKPi, statusXicToPiKP); continue; } - /* - proton = selectionPID(trackPos1, 2212); - kaonMinus = selectionPID(trackNeg1, 321); - pionPlus = selectionPID(trackPos2, 211); - - if (proton == 0 || kaonMinus == 0 || pionPlus == 0) { - pidLc = 0; //exclude Lc - } - if (proton == 1 && kaonMinus == 1 && pionPlus == 1) { - pidLc = 1; //accept Lc - } - - if (pidLc == 0) { - hfSelLcCandidate(statusLcpKpi, statusLcpiKp); - continue; - } - - if ((pidLc == -1 || pidLc == 1) && topolLcpKpi) { - statusLcpKpi = 1; //identified as Lc - } - if ((pidLc == -1 || pidLc == 1) && topolLcpiKp) { - statusLcpiKp = 1; //identified as Lc - } - */ - - kaonNeg = selectionPID(trackNeg1, kKPlus); - prot1 = selectionPID(trackPos1, kProton); - prot2 = selectionPID(trackPos2, kProton); - pion1 = selectionPID(trackPos1, kPiPlus); - pion2 = selectionPID(trackPos2, kPiPlus); + auto pidXicToPKPi = -1; + auto pidXicToPiKP = -1; if (!d_FilterPID) { - /// PID not applied at filtering level - /// set the PID flags to 1 + // PID non applied pidXicToPKPi = 1; pidXicToPiKP = 1; } else { - /// PID applied at filtering level - /// Accept only candidates recognised either at least as pKpi or as piKp - if (std::abs(kaonNeg) == 1) { - if (std::abs(prot1) == 1 && std::abs(pion2) == 1) { - pidXicToPKPi = 1; - } - if (std::abs(pion1) == 1 && std::abs(prot2) == 1) { - pidXicToPiKP = 1; - } + // track-level PID selection + int pidTrackPos1Proton = selectorProton.getStatusTrackPIDAll(trackPos1); + int pidTrackPos2Proton = selectorProton.getStatusTrackPIDAll(trackPos2); + int pidTrackPos1Pion = selectorPion.getStatusTrackPIDAll(trackPos1); + int pidTrackPos2Pion = selectorPion.getStatusTrackPIDAll(trackPos2); + int pidTrackNegKaon = selectorKaon.getStatusTrackPIDAll(trackNeg); + + if (pidTrackPos1Proton == TrackSelectorPID::Status::PIDAccepted && + pidTrackNegKaon == TrackSelectorPID::Status::PIDAccepted && + pidTrackPos2Pion == TrackSelectorPID::Status::PIDAccepted) { + pidXicToPKPi = 1; // accept LcpKpi + } else if (pidTrackPos1Proton == TrackSelectorPID::Status::PIDRejected || + pidTrackNegKaon == TrackSelectorPID::Status::PIDRejected || + pidTrackPos2Pion == TrackSelectorPID::Status::PIDRejected) { + pidXicToPKPi = 0; // exclude LcpKpi } + if (pidTrackPos2Proton == TrackSelectorPID::Status::PIDAccepted && + pidTrackNegKaon == TrackSelectorPID::Status::PIDAccepted && + pidTrackPos1Pion == TrackSelectorPID::Status::PIDAccepted) { + pidXicToPiKP = 1; // accept LcpiKp + } else if (pidTrackPos1Pion == TrackSelectorPID::Status::PIDRejected || + pidTrackNegKaon == TrackSelectorPID::Status::PIDRejected || + pidTrackPos2Proton == TrackSelectorPID::Status::PIDRejected) { + pidXicToPiKP = 0; // exclude LcpiKp + } + } + + if (pidXicToPKPi == 0 && pidXicToPiKP == 0) { + hfSelXicToPKPiCandidate(statusXicToPKPi, statusXicToPiKP); + continue; } - if ((pidXicToPKPi == 1) && topolXicToPKPi) { - statusXicToPKPi = 1; //identified as Xic->pKpi + if ((pidXicToPKPi == -1 || pidXicToPKPi == 1) && topolXicToPKPi) { + statusXicToPKPi = 1; // identified as Xic->pKpi } - if ((pidXicToPiKP == 1) && topolXicToPiKP) { - statusXicToPiKP = 1; //identified as Xic->piKp + if ((pidXicToPiKP == -1 || pidXicToPiKP == 1) && topolXicToPiKP) { + statusXicToPiKP = 1; // identified as Xic->piKp } hfSelXicToPKPiCandidate(statusXicToPKPi, statusXicToPiKP); From 438515cbc4f35173c953daa42065f4290e6dee42 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Fri, 7 May 2021 16:15:15 +0200 Subject: [PATCH 434/770] DPL GUI: vastly improved metric display (#5976) * Use ImPlot in place of the old sparklines * Sparklines now have time correspondence and properly scroll * Use the new ImGUI Table API, so that we can handle large scrolling tables. * It is now possible to show different metrics together or to select only a subset of devices to be shown. --- .../GUISupport/src/FrameworkGUIDebugger.cxx | 892 +++++++++++------- Framework/GUISupport/src/FrameworkGUIState.h | 11 +- 2 files changed, 533 insertions(+), 370 deletions(-) diff --git a/Framework/GUISupport/src/FrameworkGUIDebugger.cxx b/Framework/GUISupport/src/FrameworkGUIDebugger.cxx index 2922931f26164..2004da0f12db3 100644 --- a/Framework/GUISupport/src/FrameworkGUIDebugger.cxx +++ b/Framework/GUISupport/src/FrameworkGUIDebugger.cxx @@ -36,33 +36,24 @@ template class std::vector; static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); } static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); } -namespace o2 -{ -namespace framework -{ -namespace gui +namespace o2::framework::gui { // Type erased information for the plotting struct MultiplotData { int mod; size_t first; size_t size; - const void* Y; - const void* X; + const void* Y = nullptr; + const void* X = nullptr; MetricType type; + const char* legend = nullptr; }; -} // namespace gui -} // namespace framework -} // namespace o2 +} // namespace o2::framework::gui template class std::vector; -namespace o2 -{ -namespace framework -{ -namespace gui +namespace o2::framework::gui { ImVec4 colorForLogLevel(LogParsingHelpers::LogLevel logLevel) @@ -162,12 +153,13 @@ void displayHistory(const DeviceInfo& info, DeviceControl& control) } } -template struct HistoData { int mod; size_t first; size_t size; - const T* points; + void* points = nullptr; + const size_t* time = nullptr; + char const* legend = nullptr; }; enum struct MetricsDisplayStyle : int { @@ -178,109 +170,212 @@ enum struct MetricsDisplayStyle : int { Stems = 4 }; -void displayDeviceMetrics(const char* label, std::string const& selectedMetricName, +/// Information associated to a node in the topology +struct TopologyNodeInfo { + std::string label; +}; + +struct MetricDisplayState { + bool visible = false; + bool selected = false; + std::string legend; +}; + +struct MetricIndex { + size_t storeIndex; + size_t deviceIndex; + size_t metricIndex; + size_t stateIndex; +}; + +enum MetricTypes { + DEVICE_METRICS = 0, + DRIVER_METRICS, + TOTAL_TYPES_OF_METRICS +}; + +// We use this to keep together all the kind of metrics +// so that we can display driver and device metrics in the same plot +// without an if. +struct AllMetricsStore { + std::vector const* metrics[TOTAL_TYPES_OF_METRICS]; + std::vector const* specs[TOTAL_TYPES_OF_METRICS]; +}; + +void displaySparks( + double startTime, + std::vector& visibleMetricsIndex, + std::vector& metricDisplayStates, + AllMetricsStore const& metricStore) +{ + static bool locked = false; + ImGui::Checkbox("Lock scrolling", &locked); + ImGui::BeginTable("##sparks table", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY, ImVec2{-1, -1}); + ImGui::TableSetupColumn("##close button", ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthFixed, 25); + ImGui::TableSetupColumn("##plot name", ImGuiTableColumnFlags_WidthFixed, 200); + ImGui::TableSetupColumn("##plot", ImGuiTableColumnFlags_WidthFixed, 0); + ImGui::TableSetupScrollFreeze(2, 0); + for (size_t i = 0; i < visibleMetricsIndex.size(); ++i) { + auto& index = visibleMetricsIndex[i]; + auto& metricsInfos = *metricStore.metrics[index.storeIndex]; + auto& nodes = *metricStore.specs[index.storeIndex]; + auto& metricsInfo = metricsInfos[index.deviceIndex]; + auto& label = metricsInfo.metricLabels[index.metricIndex]; + auto& metric = metricsInfo.metrics[index.metricIndex]; + auto& state = metricDisplayStates[index.stateIndex]; + + ImGui::TableNextColumn(); + ImGui::PushID(index.stateIndex); + state.visible = !ImGui::Button("-"); + ImGui::PopID(); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(state.legend.c_str()); + ImGui::TableNextColumn(); + static ImPlotAxisFlags rtx_axis = ImPlotAxisFlags_NoTickLabels | ImPlotAxisFlags_NoLabel | ImPlotAxisFlags_NoTickMarks; + static ImPlotAxisFlags rty_axis = ImPlotAxisFlags_NoTickLabels | ImPlotAxisFlags_NoLabel | ImPlotAxisFlags_NoTickMarks; + ImGui::PushID(index.stateIndex); + HistoData data; + data.mod = metricsInfo.timestamps[index.metricIndex].size(); + data.size = std::min((size_t)data.mod, metric.filledMetrics); + data.first = metric.pos - data.size; + data.time = metricsInfo.timestamps[index.metricIndex].data(); + data.legend = state.legend.c_str(); + + if (!locked) { + ImPlot::SetNextPlotLimitsX((startTime + ImGui::GetTime() - 100) * 1000, (startTime + ImGui::GetTime()) * 1000, ImGuiCond_Always); + ImPlot::SetNextPlotLimitsY(metricsInfo.min[index.metricIndex], metricsInfo.max[index.metricIndex] * 1.1, ImGuiCond_Always); + rty_axis |= ImPlotAxisFlags_LockMin; + } + if (ImPlot::BeginPlot("##sparks", "time", "value", ImVec2(700, 100), 0, rtx_axis, rty_axis)) { + switch (metric.type) { + case MetricType::Int: { + data.points = (void*)metricsInfo.intMetrics[metric.storeIdx].data(); + + auto getter = [](void* hData, int idx) -> ImPlotPoint { + auto histoData = reinterpret_cast(hData); + size_t pos = (histoData->first + static_cast(idx)) % histoData->mod; + assert(pos >= 0 && pos < 1024); + return ImPlotPoint(histoData->time[pos], ((int*)(histoData->points))[pos]); + }; + ImPlot::PlotLineG("##plot", getter, &data, data.size); + } break; + case MetricType::Uint64: { + data.points = (void*)metricsInfo.uint64Metrics[metric.storeIdx].data(); + + auto getter = [](void* hData, int idx) -> ImPlotPoint { + auto histoData = reinterpret_cast(hData); + size_t pos = (histoData->first + static_cast(idx)) % histoData->mod; + assert(pos >= 0 && pos < 1024); + return ImPlotPoint(idx, ((uint64_t*)histoData->points)[pos]); + }; + ImPlot::PlotLineG("##plot", getter, &data, data.size, 0); + } break; + case MetricType::Float: { + data.points = (void*)metricsInfo.floatMetrics[metric.storeIdx].data(); + + auto getter = [](void* hData, int idx) -> ImPlotPoint { + auto histoData = reinterpret_cast(hData); + size_t pos = (histoData->first + static_cast(idx)) % histoData->mod; + assert(pos >= 0 && pos < 1024); + return ImPlotPoint(idx, ((float*)histoData->points)[pos]); + }; + ImPlot::PlotLineG("##plot", getter, &data, data.size, 0); + } break; + default: + return; + break; + } + ImPlot::EndPlot(); + } + ImGui::PopID(); + } + ImGui::EndTable(); +} + +void displayDeviceMetrics(const char* label, size_t rangeBegin, size_t rangeEnd, size_t bins, MetricsDisplayStyle displayType, - std::vector const& specs, - std::vector const& metricsInfos, - DeviceMetricsInfo const& driverMetric) + std::vector& state, + AllMetricsStore const& metricStore) { std::vector metricsToDisplay; std::vector deviceNames; std::vector userData; MetricType metricType; size_t metricSize = 0; - assert(specs.size() == metricsInfos.size()); +#ifdef NDEBUG + for (size_t si = 0; si < TOTAL_TYPES_OF_METRICS; ++si) { + assert(metricsStore.metrics[si].size() == metricStore.specs[si].size()); + } +#endif float maxValue = std::numeric_limits::lowest(); float minValue = 0; size_t maxDomain = std::numeric_limits::lowest(); size_t minDomain = std::numeric_limits::max(); + size_t gmi = 0; + + for (size_t si = 0; si < TOTAL_TYPES_OF_METRICS; ++si) { + std::vector const& metricsInfos = *metricStore.metrics[si]; + auto const& specs = *metricStore.specs[si]; + for (int di = 0; di < metricsInfos.size(); ++di) { + for (size_t mi = 0; mi < metricsInfos[di].metrics.size(); ++mi) { + auto& label = metricsInfos[di].metricLabels[mi]; + if (state[gmi].visible == false) { + gmi++; + continue; + } + auto& metric = metricsInfos[di].metrics[mi]; + deviceNames.push_back(specs[di].label.c_str()); + metricType = metric.type; + MultiplotData data; + data.mod = metricsInfos[di].timestamps[mi].size(); + data.first = metric.pos - data.mod; + data.X = metricsInfos[di].timestamps[mi].data(); + data.legend = state[gmi].legend.c_str(); + minValue = std::min(minValue, metricsInfos[di].min[mi]); + maxValue = std::max(maxValue, metricsInfos[di].max[mi]); + minDomain = std::min(minDomain, metricsInfos[di].minDomain[mi]); + maxDomain = std::max(maxDomain, metricsInfos[di].maxDomain[mi]); + metricType = metric.type; + data.type = metric.type; + switch (metric.type) { + case MetricType::Int: { + data.size = metricsInfos[di].intMetrics[metric.storeIdx].size(); + data.Y = metricsInfos[di].intMetrics[metric.storeIdx].data(); + } break; + case MetricType::Uint64: { + data.size = metricsInfos[di].uint64Metrics[metric.storeIdx].size(); + data.Y = metricsInfos[di].uint64Metrics[metric.storeIdx].data(); + } break; + case MetricType::Float: { + data.size = metricsInfos[di].floatMetrics[metric.storeIdx].size(); + data.Y = metricsInfos[di].floatMetrics[metric.storeIdx].data(); + } break; + case MetricType::Unknown: + case MetricType::String: { + data.size = metricsInfos[di].stringMetrics[metric.storeIdx].size(); + data.Y = nullptr; + data.type = MetricType::String; + metricType = MetricType::String; + } break; + } + metricSize = data.size; - for (int mi = 0; mi < metricsInfos.size(); ++mi) { - auto vi = DeviceMetricsHelper::metricIdxByName(selectedMetricName, metricsInfos[mi]); - if (vi == metricsInfos[mi].metricLabels.size()) { - continue; - } - auto& metric = metricsInfos[mi].metrics[vi]; - deviceNames.push_back(specs[mi].name.c_str()); - metricType = metric.type; - MultiplotData data; - data.mod = metricsInfos[mi].timestamps[vi].size(); - data.first = metric.pos - data.mod; - data.X = metricsInfos[mi].timestamps[vi].data(); - minValue = std::min(minValue, metricsInfos[mi].min[vi]); - maxValue = std::max(maxValue, metricsInfos[mi].max[vi]); - minDomain = std::min(minDomain, metricsInfos[mi].minDomain[vi]); - maxDomain = std::max(maxDomain, metricsInfos[mi].maxDomain[vi]); - metricType = metric.type; - data.type = metric.type; - switch (metric.type) { - case MetricType::Int: { - data.size = metricsInfos[mi].intMetrics[metric.storeIdx].size(); - data.Y = metricsInfos[mi].intMetrics[metric.storeIdx].data(); - } break; - case MetricType::Uint64: { - data.size = metricsInfos[mi].uint64Metrics[metric.storeIdx].size(); - data.Y = metricsInfos[mi].uint64Metrics[metric.storeIdx].data(); - } break; - case MetricType::Float: { - data.size = metricsInfos[mi].floatMetrics[metric.storeIdx].size(); - data.Y = metricsInfos[mi].floatMetrics[metric.storeIdx].data(); - } break; - case MetricType::Unknown: - case MetricType::String: { - data.size = metricsInfos[mi].stringMetrics[metric.storeIdx].size(); - data.Y = nullptr; - data.type = MetricType::String; - metricType = MetricType::String; - } break; - } - metricSize = data.size; - userData.emplace_back(data); - } - if (true) { - auto vi = DeviceMetricsHelper::metricIdxByName(selectedMetricName, driverMetric); - if (vi < driverMetric.metricLabels.size()) { - auto& metric = driverMetric.metrics[vi]; - deviceNames.push_back("driver"); - metricType = metric.type; - MultiplotData data; - data.mod = driverMetric.timestamps[vi].size(); - data.first = metric.pos - data.mod; - data.X = driverMetric.timestamps[vi].data(); - minValue = std::min(minValue, driverMetric.min[vi]); - maxValue = std::max(maxValue, driverMetric.max[vi]); - minDomain = std::min(minDomain, driverMetric.minDomain[vi]); - maxDomain = std::max(maxDomain, driverMetric.maxDomain[vi]); - metricType = metric.type; - data.type = metric.type; - switch (metric.type) { - case MetricType::Int: { - data.size = driverMetric.intMetrics[metric.storeIdx].size(); - data.Y = driverMetric.intMetrics[metric.storeIdx].data(); - } break; - case MetricType::Uint64: { - data.size = driverMetric.uint64Metrics[metric.storeIdx].size(); - data.Y = driverMetric.uint64Metrics[metric.storeIdx].data(); - } break; - case MetricType::Float: { - data.size = driverMetric.floatMetrics[metric.storeIdx].size(); - data.Y = driverMetric.floatMetrics[metric.storeIdx].data(); - } break; - case MetricType::Unknown: - case MetricType::String: { - data.size = driverMetric.stringMetrics[metric.storeIdx].size(); - data.Y = nullptr; - data.type = MetricType::String; - metricType = MetricType::String; - } break; + userData.emplace_back(data); + gmi++; } - metricSize = data.size; - userData.emplace_back(data); } } maxDomain = std::max(minDomain + 1024, maxDomain); + maxValue = std::max(minValue + 1.f, maxValue); + static size_t lastMinRange = minDomain; + static size_t lastMaxRange = maxDomain; + + // Nothing to show. + if (userData.empty()) { + return; + } for (size_t ui = 0; ui < userData.size(); ++ui) { metricsToDisplay.push_back(&(userData[ui])); } @@ -298,31 +393,41 @@ void displayDeviceMetrics(const char* label, std::string const& selectedMetricNa } return ImPlotPoint{x, y}; }; + static bool logScale = false; + ImGui::Checkbox("Log scale", &logScale); switch (displayType) { case MetricsDisplayStyle::Histos: ImPlot::SetNextPlotLimitsX(minDomain, maxDomain, ImGuiCond_Once); ImPlot::SetNextPlotLimitsY(minValue, maxValue, ImGuiCond_Always); ImPlot::SetNextPlotTicksX(minDomain, maxDomain, 5); - if (ImPlot::BeginPlot(selectedMetricName.c_str(), "time", "value")) { + if (ImPlot::BeginPlot("##Some plot", "time", "value")) { for (size_t pi = 0; pi < metricsToDisplay.size(); ++pi) { - ImPlot::PlotBarsG(deviceNames[pi], getterXY, metricsToDisplay[pi], metricSize, 1, 0); + ImGui::PushID(pi); + const char* label = ((MultiplotData*)metricsToDisplay[pi])->legend; + ImPlot::PlotBarsG(label, getterXY, metricsToDisplay[pi], metricSize, 1, 0); + ImGui::PopID(); } ImPlot::EndPlot(); } break; - case MetricsDisplayStyle::Lines: + case MetricsDisplayStyle::Lines: { ImPlot::SetNextPlotLimitsX(minDomain, maxDomain, ImGuiCond_Once); - ImPlot::SetNextPlotLimitsY(minValue, maxValue * 1.2, ImGuiCond_Always); + ImPlot::SetNextPlotLimitsY(minValue - (maxValue - minValue) * 0.2, maxValue * (logScale ? 10. : 1.2), ImGuiCond_Always); ImPlot::SetNextPlotTicksX(minDomain, maxDomain, 5); - if (ImPlot::BeginPlot("##Some plot", "time", "value")) { + auto xAxisFlags = ImPlotAxisFlags_None; + auto yAxisFlags = logScale ? ImPlotAxisFlags_LogScale : ImPlotAxisFlags_None; + if (ImPlot::BeginPlot("##Some plot", "time", "value", {-1, -1}, ImPlotFlags_None, xAxisFlags, yAxisFlags)) { for (size_t pi = 0; pi < metricsToDisplay.size(); ++pi) { - ImPlot::PlotLineG(deviceNames[pi], getterXY, metricsToDisplay[pi], metricSize, 0); + ImGui::PushID(pi); + const char* label = ((MultiplotData*)metricsToDisplay[pi])->legend; + ImPlot::PlotLineG(((MultiplotData*)metricsToDisplay[pi])->legend, getterXY, metricsToDisplay[pi], metricSize, 0); + ImGui::PopID(); } ImPlot::EndPlot(); } - break; + } break; case MetricsDisplayStyle::Stems: ImPlot::SetNextPlotLimitsX(minDomain, maxDomain, ImGuiCond_Once); ImPlot::SetNextPlotLimitsY(minValue, maxValue * 1.2, ImGuiCond_Always); @@ -332,7 +437,9 @@ void displayDeviceMetrics(const char* label, std::string const& selectedMetricNa auto stemsData = reinterpret_cast(metricsToDisplay[pi]); // FIXME: display a message for other metrics if (stemsData->type == MetricType::Uint64) { - ImPlot::PlotStems(deviceNames[pi], (const ImU64*)stemsData->X, (const ImU64*)stemsData->Y, metricSize); + ImGui::PushID(pi); + ImPlot::PlotScatterG(((MultiplotData*)metricsToDisplay[pi])->legend, getterXY, metricsToDisplay[pi], metricSize, 0); + ImGui::PopID(); } } ImPlot::EndPlot(); @@ -348,196 +455,194 @@ struct ColumnInfo { int index; }; -void metricsTableRow(std::vector columnInfos, - std::vector const& metricsInfos, +void metricsTableRow(std::vector metricIndex, + AllMetricsStore const& metricsStore, int row) { + ImGui::TableNextColumn(); ImGui::Text("%d", row); - ImGui::NextColumn(); - for (size_t j = 0; j < columnInfos.size(); j++) { - auto& info = columnInfos[j]; - auto& metricsInfo = metricsInfos[j]; + for (auto index : metricIndex) { + auto& metricsInfos = *metricsStore.metrics[index.storeIndex]; + auto& metricsInfo = metricsInfos[index.deviceIndex]; + auto& info = metricsInfos[index.deviceIndex].metrics[index.metricIndex]; - if (info.index == -1) { - ImGui::TextUnformatted("-"); - ImGui::NextColumn(); - continue; - } + ImGui::TableNextColumn(); switch (info.type) { case MetricType::Int: { - ImGui::Text("%i (%i)", metricsInfo.intMetrics[info.index][row], info.index); - ImGui::NextColumn(); + ImGui::Text("%i", metricsInfo.intMetrics[info.storeIdx][row]); } break; case MetricType::Uint64: { - ImGui::Text("%" PRIu64 " (%i)", metricsInfo.uint64Metrics[info.index][row], info.index); - ImGui::NextColumn(); + ImGui::Text("%" PRIu64, metricsInfo.uint64Metrics[info.storeIdx][row]); } break; case MetricType::Float: { - ImGui::Text("%f (%i)", metricsInfo.floatMetrics[info.index][row], info.index); - ImGui::NextColumn(); + ImGui::Text("%f", metricsInfo.floatMetrics[info.storeIdx][row]); } break; case MetricType::String: { - ImGui::Text("%s (%i)", metricsInfo.stringMetrics[info.index][row].data, info.index); - ImGui::NextColumn(); + ImGui::Text("%s", metricsInfo.stringMetrics[info.storeIdx][row].data); } break; default: - ImGui::NextColumn(); break; } } } -void historyBar(gui::WorkspaceGUIState& globalGUIState, - size_t rangeBegin, size_t rangeEnd, - gui::DeviceGUIState& state, - DriverInfo const& driverInfo, - DeviceSpec const& spec, - DeviceMetricsInfo const& metricsInfo) +bool hasAll(const char* s, const char* q) { - bool open = ImGui::TreeNode(state.label.c_str()); - if (open) { - ImGui::Text("# channels: %lu", spec.outputChannels.size() + spec.inputChannels.size()); - ImGui::TreePop(); + /* base case: empty query */ + if (*q == 0) { + return true; } - ImGui::NextColumn(); + do { + s = strchr(s, (int)*q); + if (s == nullptr) { + return false; + } + s++; + q++; + } while ((int)*q != 0); + return true; +} - if (globalGUIState.selectedMetric == -1) { - ImGui::NextColumn(); - return; - } +void TextCenter(char const* text) +{ + float font_size = ImGui::GetFontSize() * strlen(text) / 2; + ImGui::Dummy(ImVec2( + ImGui::GetWindowSize().x / 2 - + font_size + (font_size / 2), + 120)); - auto currentMetricName = driverInfo.availableMetrics[globalGUIState.selectedMetric]; + ImGui::TextUnformatted(text); +} - size_t i = DeviceMetricsHelper::metricIdxByName(currentMetricName, metricsInfo); - // We did not find any plot, skipping this. - if (i == metricsInfo.metricLabels.size()) { - ImGui::NextColumn(); +void displayMetrics(gui::WorkspaceGUIState& state, + DriverInfo const& driverInfo, + std::vector const& infos, + std::vector const& metadata, + std::vector& controls, + AllMetricsStore const& metricsStore) +{ + if (state.bottomPaneVisible == false) { return; } - auto& metric = metricsInfo.metrics[i]; - - switch (metric.type) { - case MetricType::Int: { - HistoData data; - data.mod = metricsInfo.timestamps[i].size(); - data.first = metric.pos - data.mod; - data.size = metricsInfo.intMetrics[metric.storeIdx].size(); - data.points = metricsInfo.intMetrics[metric.storeIdx].data(); - - auto getter = [](void* hData, int idx) -> float { - auto histoData = reinterpret_cast*>(hData); - size_t pos = (histoData->first + static_cast(idx)) % histoData->mod; - assert(pos >= 0 && pos < 1024); - return histoData->points[pos]; - }; - ImGui::PlotLines(("##" + currentMetricName).c_str(), getter, &data, data.size); - ImGui::NextColumn(); - } break; - case MetricType::Uint64: { - HistoData data; - data.mod = metricsInfo.timestamps[i].size(); - data.first = metric.pos - data.mod; - data.size = metricsInfo.uint64Metrics[metric.storeIdx].size(); - data.points = metricsInfo.uint64Metrics[metric.storeIdx].data(); - - auto getter = [](void* hData, int idx) -> float { - auto histoData = reinterpret_cast*>(hData); - size_t pos = (histoData->first + static_cast(idx)) % histoData->mod; - assert(pos >= 0 && pos < 1024); - return histoData->points[pos]; - }; - ImGui::PlotLines(("##" + currentMetricName).c_str(), getter, &data, data.size); - ImGui::NextColumn(); - } break; - case MetricType::Float: { - HistoData data; - data.mod = metricsInfo.timestamps[i].size(); - data.first = metric.pos - data.mod; - data.size = metricsInfo.floatMetrics[metric.storeIdx].size(); - data.points = metricsInfo.floatMetrics[metric.storeIdx].data(); - - auto getter = [](void* hData, int idx) -> float { - auto histoData = reinterpret_cast*>(hData); - size_t pos = (histoData->first + static_cast(idx)) % histoData->mod; - assert(pos >= 0 && pos < 1024); - return histoData->points[pos]; - }; - ImGui::PlotLines(("##" + currentMetricName).c_str(), getter, &data, data.size); - ImGui::NextColumn(); - } break; - default: - ImGui::NextColumn(); - return; - break; - } -} + auto metricDisplayPos = 0; + static bool metricSelectorVisible = true; + static std::vector metricDisplayState; + static bool showInternalMetrics = false; -/// Calculate where to find the coliumns for a give metric -std::vector calculateTableIndex(gui::WorkspaceGUIState& globalGUIState, - int selectedMetric, - DriverInfo const& driverInfo, - std::vector const& metricsInfos) -{ - std::vector columns; - for (size_t j = 0; j < globalGUIState.devices.size(); ++j) { - const DeviceMetricsInfo& metricsInfo = metricsInfos[j]; - /// Nothing to draw, if no metric selected. - if (selectedMetric == -1) { - columns.push_back({MetricType::Int, -1}); - continue; + // Calculate the full timestamp range for the selected metric + size_t minTime = -1; + size_t maxTime = 0; + constexpr size_t MAX_QUERY_SIZE = 256; + static char query[MAX_QUERY_SIZE]; + static char lastSelectedQuery[MAX_QUERY_SIZE]; + + size_t totalMetrics = 0; + for (auto& metricsInfos : metricsStore.metrics) { + for (auto& metricInfo : *metricsInfos) { + totalMetrics += metricInfo.metrics.size(); } - auto currentMetricName = driverInfo.availableMetrics[selectedMetric]; - size_t idx = DeviceMetricsHelper::metricIdxByName(currentMetricName, metricsInfo); + } - // We did not find any plot, skipping this. - if (idx == metricsInfo.metricLabels.size()) { - columns.push_back({MetricType::Int, -1}); - continue; + if (totalMetrics != metricDisplayState.size() || strcmp(lastSelectedQuery, query)) { + size_t gmi = 0; + std::vector newMetricDisplayStates; + newMetricDisplayStates.resize(totalMetrics); + for (size_t si = 0; si < TOTAL_TYPES_OF_METRICS; ++si) { + auto& metricsInfos = *metricsStore.metrics[si]; + auto& specs = *metricsStore.specs[si]; + for (size_t di = 0; di < metricsInfos.size(); ++di) { + auto& metricInfo = metricsInfos[di]; + auto& spec = specs[di]; + for (size_t li = 0; li != metricInfo.metricLabels.size(); ++li) { + char const* metricLabel = metricInfo.metricLabels[li].label; + std::string legend = fmt::format("{}/{}", spec.label, metricLabel); + auto old = std::find_if(metricDisplayState.begin(), metricDisplayState.end(), [&legend](MetricDisplayState const& state) { return state.legend == legend; }); + if (old != metricDisplayState.end()) { + newMetricDisplayStates[gmi].visible = old->visible; + } else { + newMetricDisplayStates[gmi].visible = false; + } + + newMetricDisplayStates[gmi].selected = hasAll(metricLabel, query); + newMetricDisplayStates[gmi].legend = legend; + gmi++; + } + } } - auto metric = metricsInfos[j].metrics[idx]; - columns.push_back({metric.type, static_cast(metric.storeIdx)}); + metricDisplayState.swap(newMetricDisplayStates); + strcpy(lastSelectedQuery, query); } - return columns; -}; -void displayDeviceHistograms(gui::WorkspaceGUIState& state, - DriverInfo const& driverInfo, - std::vector const& infos, - std::vector const& devices, - std::vector const& metadata, - std::vector& controls, - std::vector const& metricsInfos) -{ - showTopologyNodeGraph(state, infos, devices, metadata, controls, metricsInfos); - if (state.bottomPaneVisible == false) { - return; + static std::vector selectedMetricIndex; + + if (metricSelectorVisible) { + selectedMetricIndex.clear(); + size_t gmi = 0; + for (size_t si = 0; si < TOTAL_TYPES_OF_METRICS; ++si) { + auto& metricsInfos = *metricsStore.metrics[si]; + auto& devices = metricsStore.specs[si]; + + for (size_t di = 0; di < metricsInfos.size(); ++di) { + auto& metricInfo = metricsInfos[di]; + auto& deviceSpec = devices[di]; + for (size_t li = 0; li != metricInfo.metricLabels.size(); ++li) { + auto& label = metricInfo.metricLabels[li]; + auto& state = metricDisplayState[gmi]; + if (state.selected) { + selectedMetricIndex.push_back(MetricIndex{si, di, li, gmi}); + } + gmi++; + } + } + } + + metricDisplayPos = ImGui::GetIO().DisplaySize.x / 4; + ImGui::SetNextWindowPos(ImVec2(0, ImGui::GetIO().DisplaySize.y - state.bottomPaneSize), 0); + ImGui::SetNextWindowSize(ImVec2(metricDisplayPos, state.bottomPaneSize), 0); + ImGui::Begin("Available metrics", nullptr, ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize); + + ImGui::Text("Find metrics: "); + ImGui::SameLine(); + ImGui::InputText("##query-metrics", query, MAX_QUERY_SIZE); + if (ImGui::BeginTable("##metrics-table", 2, ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY, ImVec2{-1, -1})) { + ImGui::TableSetupColumn("##close button", ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthFixed, 20); + ImGui::TableSetupScrollFreeze(1, 0); + ImGuiListClipper clipper; + clipper.Begin(selectedMetricIndex.size()); + while (clipper.Step()) { + for (size_t i = clipper.DisplayStart; i < clipper.DisplayEnd; ++i) { + auto& index = selectedMetricIndex[i]; + auto& metricsInfos = *metricsStore.metrics[index.storeIndex]; + auto& nodes = *metricsStore.specs[index.storeIndex]; + auto& metricInfo = metricsInfos[index.deviceIndex]; + auto& node = nodes[index.deviceIndex]; + auto& label = metricInfo.metricLabels[index.metricIndex]; + auto& metric = metricInfo.metrics[index.metricIndex]; + auto& state = metricDisplayState[index.stateIndex]; + ImGui::PushID(index.stateIndex); + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::Checkbox("##checkbox", &metricDisplayState[index.stateIndex].visible); + ImGui::TableNextColumn(); + ImGui::Text("%s/%s", node.label.c_str(), label.label); + ImGui::PopID(); + } + } + ImGui::EndTable(); + } + ImGui::End(); } - ImGui::SetNextWindowPos(ImVec2(0, ImGui::GetIO().DisplaySize.y - state.bottomPaneSize), 0); - ImGui::SetNextWindowSize(ImVec2(ImGui::GetIO().DisplaySize.x, state.bottomPaneSize), 0); + ImGui::SetNextWindowPos(ImVec2(metricDisplayPos, ImGui::GetIO().DisplaySize.y - state.bottomPaneSize), 0); + ImGui::SetNextWindowSize(ImVec2(ImGui::GetIO().DisplaySize.x - metricDisplayPos, state.bottomPaneSize), 0); ImGui::Begin("Devices", nullptr, ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize); - ImGui::BeginGroup(); - char const* currentMetric = nullptr; - if (state.selectedMetric != -1) { - currentMetric = driverInfo.availableMetrics[state.selectedMetric].c_str(); + + if (!metricSelectorVisible) { + metricSelectorVisible = ImGui::Button(">> Show metric selector"); } else { - currentMetric = "Click to select metric"; + metricSelectorVisible = !ImGui::Button("<< Hide metric selector"); } - if (ImGui::BeginCombo("###Select metric", currentMetric, 0)) { - for (size_t mi = 0; mi < driverInfo.availableMetrics.size(); ++mi) { - auto metric = driverInfo.availableMetrics[mi]; - bool isSelected = mi == state.selectedMetric; - if (ImGui::Selectable(driverInfo.availableMetrics[mi].c_str(), isSelected)) { - state.selectedMetric = mi; - } - if (isSelected) { - ImGui::SetItemDefaultFocus(); - } - } - ImGui::EndCombo(); - }; - static char const* plotStyles[] = { "lines", "histograms", @@ -546,108 +651,161 @@ void displayDeviceHistograms(gui::WorkspaceGUIState& state, "stems"}; ImGui::SameLine(); static enum MetricsDisplayStyle currentStyle = MetricsDisplayStyle::Lines; - ImGui::Combo("##Select style", reinterpret_cast(¤tStyle), plotStyles, IM_ARRAYSIZE(plotStyles)); - - // Calculate the full timestamp range for the selected metric - size_t minTime = -1; - size_t maxTime = 0; - std::string currentMetricName; - if (state.selectedMetric >= 0) { - currentMetricName = driverInfo.availableMetrics[state.selectedMetric]; - for (auto& metricInfo : metricsInfos) { - size_t mi = DeviceMetricsHelper::metricIdxByName(currentMetricName, metricInfo); - if (mi == metricInfo.metricLabels.size()) { - continue; + static char const* currentStyleStr = plotStyles[0]; + ImGui::TextUnformatted("Metric display style:"); + ImGui::SameLine(); + ImGui::PushItemWidth(100); + if (ImGui::BeginCombo("##Select style", currentStyleStr)) { + for (int n = 0; n < IM_ARRAYSIZE(plotStyles); n++) { + bool is_selected = (currentStyleStr == plotStyles[n]); // You can store your selection however you want, outside or inside your objects + if (ImGui::Selectable(plotStyles[n], is_selected)) { + currentStyleStr = plotStyles[n]; + currentStyle = (MetricsDisplayStyle)n; } - auto& metric = metricInfo.metrics[mi]; - auto& timestamps = metricInfo.timestamps[mi]; - - for (size_t ti = 0; ti != metricInfo.timestamps.size(); ++ti) { - size_t minRangePos = (metric.pos + ti) % metricInfo.timestamps.size(); - size_t curMinTime = timestamps[minRangePos]; - if (curMinTime == 0) { - continue; - } - minTime = minTime < curMinTime ? minTime : curMinTime; - if (minTime != 0 && minTime != -1) { - break; + if (is_selected) { + ImGui::SetItemDefaultFocus(); // You may set the initial focus when opening the combo (scrolling + for keyboard navigation support) + } + } + ImGui::EndCombo(); + } + ImGui::PopItemWidth(); + bool locked = false; + + size_t gmi = 0; + int visibleMetrics = 0; + static std::vector visibleDevicesIndex; + static std::vector visibleMetricsIndex; + + visibleDevicesIndex.reserve(totalMetrics); + visibleDevicesIndex.clear(); + visibleMetricsIndex.clear(); + + for (size_t si = 0; si < TOTAL_TYPES_OF_METRICS; ++si) { + auto& metricsInfos = *metricsStore.metrics[si]; + for (size_t di = 0; di < metricsInfos.size(); ++di) { + auto& metricInfo = metricsInfos[di]; + bool deviceVisible = false; + for (size_t mi = 0; mi < metricInfo.metrics.size(); ++mi) { + auto& label = metricInfo.metricLabels[mi]; + auto& state = metricDisplayState[gmi]; + if (state.visible) { + deviceVisible = true; + visibleMetrics++; + auto& metric = metricInfo.metrics[mi]; + auto& timestamps = metricInfo.timestamps[mi]; + + for (size_t ti = 0; ti != metricInfo.timestamps.size(); ++ti) { + size_t minRangePos = (metric.pos + ti) % metricInfo.timestamps.size(); + size_t curMinTime = timestamps[minRangePos]; + if (curMinTime == 0) { + continue; + } + minTime = minTime < curMinTime ? minTime : curMinTime; + if (minTime != 0 && minTime != -1) { + break; + } + } + size_t maxRangePos = (size_t)(metric.pos) - 1 % metricInfo.timestamps.size(); + size_t curMaxTime = timestamps[maxRangePos]; + maxTime = std::max(maxTime, curMaxTime); + visibleMetricsIndex.push_back(MetricIndex{si, di, mi, gmi}); } + gmi++; + } + if (deviceVisible) { + visibleDevicesIndex.push_back(di); } - size_t maxRangePos = (size_t)(metric.pos) - 1 % metricInfo.timestamps.size(); - size_t curMaxTime = timestamps[maxRangePos]; - maxTime = maxTime > curMaxTime ? maxTime : curMaxTime; } } - ImGui::EndGroup(); - if (!currentMetricName.empty()) { - switch (currentStyle) { - case MetricsDisplayStyle::Stems: - case MetricsDisplayStyle::Histos: - case MetricsDisplayStyle::Lines: { - displayDeviceMetrics("Metrics", - currentMetricName, minTime, maxTime, 1024, - currentStyle, devices, metricsInfos, driverInfo.metrics); - } break; - case MetricsDisplayStyle::Sparks: { -#if defined(ImGuiCol_ChildWindowBg) - ImGui::BeginChild("##ScrollingRegion", ImVec2(ImGui::GetIO().DisplaySize.x + state.leftPaneSize + state.rightPaneSize - 10, -ImGui::GetItemsLineHeightWithSpacing()), false, - ImGuiWindowFlags_HorizontalScrollbar); -#else - ImGui::BeginChild("##ScrollingRegion", ImVec2(ImGui::GetIO().DisplaySize.x + state.leftPaneSize + state.rightPaneSize - 10, -ImGui::GetTextLineHeightWithSpacing()), false, - ImGuiWindowFlags_HorizontalScrollbar); -#endif - ImGui::Columns(2); - ImGui::SetColumnOffset(1, 300); - for (size_t i = 0; i < state.devices.size(); ++i) { - gui::DeviceGUIState& deviceGUIState = state.devices[i]; - const DeviceSpec& spec = devices[i]; - const DeviceMetricsInfo& metricsInfo = metricsInfos[i]; - - historyBar(state, minTime, maxTime, deviceGUIState, driverInfo, spec, metricsInfo); + if (visibleMetricsIndex.empty()) { + TextCenter("Please enable some metric."); + ImGui::End(); + return; + }; + + switch (currentStyle) { + case MetricsDisplayStyle::Stems: + case MetricsDisplayStyle::Histos: + case MetricsDisplayStyle::Lines: { + displayDeviceMetrics("Metrics", + minTime, maxTime, 1024, + currentStyle, metricDisplayState, metricsStore); + } break; + case MetricsDisplayStyle::Sparks: { + displaySparks(state.startTime, visibleMetricsIndex, metricDisplayState, metricsStore); + } break; + case MetricsDisplayStyle::Table: { + static std::vector visibleDevicesOffsets; + visibleDevicesOffsets.clear(); + visibleDevicesOffsets.resize(visibleDevicesIndex.size()); + + size_t lastDevice = -1; + int visibleDeviceCount = -1; + /// Calculate the size of all the metrics for a given device + for (auto index : visibleMetricsIndex) { + auto& metricsInfos = *metricsStore.metrics[index.storeIndex]; + if (lastDevice != index.deviceIndex) { + visibleDeviceCount++; + lastDevice = index.deviceIndex; } - ImGui::Columns(1); - ImGui::EndChild(); - } break; - case MetricsDisplayStyle::Table: { -#if defined(ImGuiCol_ChildWindowBg) - ImGui::BeginChild("##ScrollingRegion", ImVec2(ImGui::GetIO().DisplaySize.x + state.leftPaneSize + state.rightPaneSize - 10, -ImGui::GetItemsLineHeightWithSpacing()), false, - ImGuiWindowFlags_HorizontalScrollbar); -#else - ImGui::BeginChild("##ScrollingRegion", ImVec2(ImGui::GetIO().DisplaySize.x + state.leftPaneSize + state.rightPaneSize - 10, -ImGui::GetTextLineHeightWithSpacing()), false, - ImGuiWindowFlags_HorizontalScrollbar); -#endif + auto label = metricsInfos[index.deviceIndex].metricLabels[index.metricIndex].label; + visibleDevicesOffsets[visibleDeviceCount] += ImGui::CalcTextSize(label, nullptr, true).x; + } + // The Device name header. + if (ImGui::BeginTable("##metrics-table", visibleMetricsIndex.size() + 1, ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY | ImGuiTableFlags_ScrollX, ImVec2{-1, -1})) { + ImGui::TableSetupColumn("##close button", ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthFixed, 20); + for (auto index : visibleMetricsIndex) { + ImGui::TableSetupColumn("##device-header", ImGuiTableColumnFlags_WidthFixed, 100); + } + ImGui::TableSetupScrollFreeze(1, 2); + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(""); + visibleDeviceCount = -1; + lastDevice = -1; + for (auto index : visibleMetricsIndex) { + ImGui::TableNextColumn(); + auto& metricsInfos = *metricsStore.metrics[index.storeIndex]; + auto& devices = *metricsStore.specs[index.storeIndex]; + auto& metric = metricsInfos[index.deviceIndex]; + auto label = metricsInfos[index.deviceIndex].metricLabels[index.metricIndex].label; + if (lastDevice == index.deviceIndex) { + continue; + } + visibleDeviceCount++; + lastDevice = index.deviceIndex; + auto& spec = devices[index.deviceIndex]; - // The +1 is for the timestamp column - ImGui::Columns(state.devices.size() + 1); - ImGui::TextUnformatted("entry"); - ImGui::NextColumn(); - ImVec2 textsize = ImGui::CalcTextSize("extry", nullptr, true); - float offset = 0.f; - offset += std::max(100.f, textsize.x); - for (size_t j = 0; j < state.devices.size(); ++j) { - gui::DeviceGUIState& deviceGUIState = state.devices[j]; - const DeviceSpec& spec = devices[j]; - - ImGui::SetColumnOffset(-1, offset); - textsize = ImGui::CalcTextSize(spec.name.c_str(), nullptr, true); - offset += std::max(100.f, textsize.x); - ImGui::TextUnformatted(spec.name.c_str()); - ImGui::NextColumn(); + ImGui::TextUnformatted(spec.label.c_str()); } - ImGui::Separator(); - auto columns = calculateTableIndex(state, state.selectedMetric, driverInfo, metricsInfos); + // The metrics headers + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::TextUnformatted("#"); + lastDevice = -1; + for (auto index : visibleMetricsIndex) { + ImGui::TableNextColumn(); + auto& metricsInfos = *metricsStore.metrics[index.storeIndex]; + auto& metric = metricsInfos[index.deviceIndex]; + auto label = metricsInfos[index.deviceIndex].metricLabels[index.metricIndex].label; + ImGui::TextUnformatted(label); + } // Calculate which columns we want to see. - // FIXME: only one column for now. - for (size_t i = 0; i < 10; ++i) { - metricsTableRow(columns, metricsInfos, i); + ImGuiListClipper clipper; + // For now + clipper.Begin(1024); + + while (clipper.Step()) { + for (size_t i = clipper.DisplayStart; i < clipper.DisplayEnd; ++i) { + ImGui::TableNextRow(); + metricsTableRow(visibleMetricsIndex, metricsStore, i); + } } - ImGui::Columns(1); - - ImGui::EndChild(); - } break; - } + ImGui::EndTable(); + } + } break; } ImGui::End(); } @@ -796,15 +954,32 @@ std::function getGUIDebugger(std::vector const& infos, guiState.bottomPaneVisible = true; guiState.leftPaneVisible = true; guiState.rightPaneVisible = true; + timespec now; + clock_gettime(CLOCK_REALTIME, &now); + guiState.startTime = now.tv_sec - ImGui::GetTime(); + std::vector deviceNodesInfos; + for (auto& device : devices) { + deviceNodesInfos.push_back(TopologyNodeInfo{device.name}); + } + std::vector driverNodesInfos; + driverNodesInfos.push_back(TopologyNodeInfo{"driver"}); - return [&guiState, &infos, &devices, &metadata, &controls, &metricsInfos, &driverInfo, &driverControl]() { + return [&guiState, &infos, &devices, &metadata, &controls, &metricsInfos, &driverInfo, &driverControl, deviceNodesInfos, driverNodesInfos]() { ImGuiStyle& style = ImGui::GetStyle(); style.FrameRounding = 0.; style.WindowRounding = 0.; style.Colors[ImGuiCol_WindowBg] = ImVec4(0x1b / 255.f, 0x1b / 255.f, 0x1b / 255.f, 1.00f); style.Colors[ImGuiCol_ScrollbarBg] = ImVec4(0x1b / 255.f, 0x1b / 255.f, 0x1b / 255.f, 1.00f); - displayDeviceHistograms(guiState, driverInfo, infos, devices, metadata, controls, metricsInfos); + showTopologyNodeGraph(guiState, infos, devices, metadata, controls, metricsInfos); + + AllMetricsStore metricsStore; + std::vector driverMetrics{driverInfo.metrics}; + metricsStore.metrics[DEVICE_METRICS] = &metricsInfos; + metricsStore.metrics[DRIVER_METRICS] = &driverMetrics; + metricsStore.specs[DEVICE_METRICS] = &deviceNodesInfos; + metricsStore.specs[DRIVER_METRICS] = &driverNodesInfos; + displayMetrics(guiState, driverInfo, infos, metadata, controls, metricsStore); displayDriverInfo(driverInfo, driverControl); int windowPosStepping = (ImGui::GetIO().DisplaySize.y - 500) / guiState.devices.size(); @@ -836,13 +1011,8 @@ std::function getGUIDebugger(std::vector const& infos, (int)LogParsingHelpers::LogLevel::Size, 5); ImGui::Separator(); -#if defined(ImGuiCol_ChildWindowBg) - ImGui::BeginChild("ScrollingRegion", ImVec2(0, -ImGui::GetItemsLineHeightWithSpacing()), false, - ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_NoMove); -#else ImGui::BeginChild("ScrollingRegion", ImVec2(0, -ImGui::GetTextLineHeightWithSpacing()), false, ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_NoMove); -#endif displayHistory(info, control); ImGui::EndChild(); ImGui::End(); @@ -852,6 +1022,4 @@ std::function getGUIDebugger(std::vector const& infos, }; } -} // namespace gui -} // namespace framework -} // namespace o2 +} // namespace o2::framework::gui diff --git a/Framework/GUISupport/src/FrameworkGUIState.h b/Framework/GUISupport/src/FrameworkGUIState.h index 245029d88a589..44f6e9e717a7d 100644 --- a/Framework/GUISupport/src/FrameworkGUIState.h +++ b/Framework/GUISupport/src/FrameworkGUIState.h @@ -13,11 +13,7 @@ #include #include -namespace o2 -{ -namespace framework -{ -namespace gui +namespace o2::framework::gui { /// State for the Device specific inspector @@ -37,8 +33,7 @@ struct WorkspaceGUIState { bool leftPaneVisible; bool rightPaneVisible; bool bottomPaneVisible; + double startTime; }; -} // namespace gui -} // namespace framework -} // namespace o2 +} // namespace o2::framework::gui From 67e7978ec7189dfbc18bafdc7404ceea4a312211 Mon Sep 17 00:00:00 2001 From: Pietro Cortese Date: Fri, 7 May 2021 17:09:44 +0200 Subject: [PATCH 435/770] Start reworking rec event structure --- DataFormats/Detectors/ZDC/CMakeLists.txt | 7 +- .../ZDC/include/DataFormatsZDC/BCRecData.h | 57 ++++++++++ .../ZDC/include/DataFormatsZDC/RecEvent.h | 6 +- .../ZDC/include/DataFormatsZDC/RecEventAux.h | 106 ++++++++++++++++++ .../ZDC/include/DataFormatsZDC/TDCData.h | 48 ++++++++ DataFormats/Detectors/ZDC/src/BCRecData.cxx | 27 +++++ .../Detectors/ZDC/src/DataFormatsZDCLinkDef.h | 1 + DataFormats/Detectors/ZDC/src/RecEventAux.cxx | 18 +++ DataFormats/Detectors/ZDC/src/TDCData.cxx | 18 +++ .../include/ZDCReconstruction/DigiReco.h | 7 +- .../include/ZDCReconstruction/ZDCTDCParam.h | 2 +- Detectors/ZDC/reconstruction/src/DigiReco.cxx | 5 +- 12 files changed, 289 insertions(+), 13 deletions(-) create mode 100644 DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h create mode 100644 DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h create mode 100644 DataFormats/Detectors/ZDC/include/DataFormatsZDC/TDCData.h create mode 100644 DataFormats/Detectors/ZDC/src/BCRecData.cxx create mode 100644 DataFormats/Detectors/ZDC/src/RecEventAux.cxx create mode 100644 DataFormats/Detectors/ZDC/src/TDCData.cxx diff --git a/DataFormats/Detectors/ZDC/CMakeLists.txt b/DataFormats/Detectors/ZDC/CMakeLists.txt index 4db60534f04f4..936a9edcd2592 100644 --- a/DataFormats/Detectors/ZDC/CMakeLists.txt +++ b/DataFormats/Detectors/ZDC/CMakeLists.txt @@ -9,8 +9,8 @@ # submit itself to any jurisdiction. o2_add_library(DataFormatsZDC - SOURCES src/ChannelData.cxx src/BCData.cxx src/RecEvent.cxx src/RawEventData.cxx - src/OrbitRawData.cxx src/OrbitRecData.cxx src/OrbitData.cxx + SOURCES src/ChannelData.cxx src/BCData.cxx src/RecEvent.cxx src/RecEventAux.cxx src/RawEventData.cxx + src/OrbitRawData.cxx src/OrbitRecData.cxx src/OrbitData.cxx src/TDCData.cxx src/CTF.cxx PUBLIC_LINK_LIBRARIES O2::CommonConstants O2::CommonDataFormat O2::ZDCBase ROOT::MathCore FairRoot::Base @@ -21,5 +21,6 @@ o2_target_root_dictionary(DataFormatsZDC HEADERS include/DataFormatsZDC/Hit.h include/DataFormatsZDC/MCLabel.h include/DataFormatsZDC/BCData.h include/DataFormatsZDC/ChannelData.h include/DataFormatsZDC/OrbitData.h include/DataFormatsZDC/CTF.h - include/DataFormatsZDC/RecEvent.h include/DataFormatsZDC/OrbitRawData.h + include/DataFormatsZDC/RecEvent.h include/DataFormatsZDC/RecEventAux.h + include/DataFormatsZDC/OrbitRawData.h include/DataFormatsZDC/TDCData.h include/DataFormatsZDC/OrbitRecData.h include/DataFormatsZDC/RawEventData.h) diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h new file mode 100644 index 0000000000000..e67f54d7b5444 --- /dev/null +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/BCRecData.h @@ -0,0 +1,57 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef _ZDC_BC_REC_DATA_H +#define _ZDC_BC_REC_DATA_H + +#include "CommonDataFormat/InteractionRecord.h" +#include "CommonDataFormat/RangeReference.h" +#include "ZDCBase/Constants.h" +#include +#include + +/// \file BCData.h +/// \brief Class to describe reconstructed data and refer to channel data +/// \author ruben.shahoyan@cern.ch, pietro.cortese@cern.ch + +namespace o2 +{ +namespace zdc +{ +class ChannelData; + + +struct BCRecData { + /// we are going to refer to at most 26 channels, so 5 bits for the NChannels and 27 for the reference + o2::dataformats::RangeRefComp<5> refe; + o2::dataformats::RangeRefComp<5> reft; + o2::InteractionRecord ir; + uint32_t flags; + + BCRecData() = default; + BCRecData(int firste, int ne, int firstt, int nt, o2::InteractionRecord iRec, uint32_t fl) + { + refe.setFirstEntry(firste); + refe.setEntries(ne); + reft.setFirstEntry(firstt); + reft.setEntries(nt); + ir = iRec; + flags = fl; + } + + gsl::span getBunchChannelData(const gsl::span tfdata) const; + void print() const; + + ClassDefNV(BCRecData, 1 b); +}; +} // namespace zdc +} // namespace o2 + +#endif diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h index 887e95b479c68..6d3240bd775e1 100644 --- a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEvent.h @@ -8,8 +8,8 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. -#ifndef _ZDC_RECEVENT_H_ -#define _ZDC_RECEVENT_H_ +#ifndef _ZDC_RECEVENT_H +#define _ZDC_RECEVENT_H #include "CommonDataFormat/InteractionRecord.h" #include "MathUtils/Cartesian.h" @@ -29,7 +29,6 @@ namespace zdc struct RecEvent { o2::InteractionRecord ir; uint32_t flags; /// reconstruction flags - std::map ezdc; /// signal in ZDCs float energy[NChannels] = {O2_ZDC_FLT_INIT}; /// ZDC signal constexpr static float fAmp = 1. / 8.; /// Multiplication factor in conversion from integer constexpr static float fVal = 1. / TSNS; /// Multiplication factor in conversion from integer @@ -38,6 +37,7 @@ struct RecEvent { int ntdc[NTDCChannels] = {0}; // Internal variables + std::map ezdc; /// signal in ZDCs std::array pattern; /// Pattern of TDC uint16_t fired[NTDCChannels] = {0}; /// Position at which the trigger algorithm is fired float inter[NTDCChannels][NTimeBinsPerBC * TSN] = {0}; /// Interpolated samples diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h new file mode 100644 index 0000000000000..908ce5ae490e1 --- /dev/null +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/RecEventAux.h @@ -0,0 +1,106 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef _ZDC_RECEVENT_AUX_H +#define _ZDC_RECEVENT_AUX_H + +#include "CommonDataFormat/InteractionRecord.h" +#include "MathUtils/Cartesian.h" +#include "ZDCBase/Constants.h" +#include +#include +#include + +/// \file RecEvent.h +/// \brief Class to describe reconstructed ZDC event (single BC with signal in one of detectors) during the reconstruction stage +/// \author cortese@to.infn.it, ruben.shahoyan@cern.ch + +namespace o2 +{ +namespace zdc +{ + +struct RecEventAux { + o2::InteractionRecord ir; + uint32_t flags; /// reconstruction flags + constexpr static float fAmp = 1. / 8.; /// Multiplication factor in conversion from integer + constexpr static float fVal = 1. / TSNS; /// Multiplication factor in conversion from integer + std::map ezdc; /// signal in ZDCs + int16_t tdcVal[NTDCChannels][MaxTDCValues]; /// TdcChannels + int16_t tdcAmp[NTDCChannels][MaxTDCValues]; /// TdcAmplitudes + int ntdc[NTDCChannels] = {0}; /// Number of hits in TDC + std::array pattern; /// Pattern of TDC + uint16_t fired[NTDCChannels] = {0}; /// Position at which the trigger algorithm is fired + float inter[NTDCChannels][NTimeBinsPerBC * TSN] = {0}; /// Interpolated samples + uint32_t ref[NChannels] = {O2_ZDC_REF_INIT}; /// Cache of references + + // Functions + void print() const; + float EZDC(uint8_t ich) + { + std::map::iterator it = ezdc.find(ich); + if (it != ezdc.end()) { + return it->second; + } else { + return -std::numeric_limits::infinity(); + } + } + + float EZNAC() { return EZDC(IdZNAC); } + float EZNA1() { return EZDC(IdZNA1); } + float EZNA2() { return EZDC(IdZNA2); } + float EZNA3() { return EZDC(IdZNA3); } + float EZNA4() { return EZDC(IdZNA4); } + float EZNASum() { return EZDC(IdZNASum); } + + float EZPAC() { return EZDC(IdZPAC); } + float EZPA1() { return EZDC(IdZPA1); } + float EZPA2() { return EZDC(IdZPA2); } + float EZPA3() { return EZDC(IdZPA3); } + float EZPA4() { return EZDC(IdZPA4); } + float EZPASum() { return EZDC(IdZPASum); } + + float EZEM1() { return EZDC(IdZEM1); } + float EZEM2() { return EZDC(IdZEM2); } + + float EZNCC() { return EZDC(IdZNCC); } + float EZNC1() { return EZDC(IdZNC1); } + float EZNC2() { return EZDC(IdZNC2); } + float EZNC3() { return EZDC(IdZNC3); } + float EZNC4() { return EZDC(IdZNC4); } + float EZNCSum() { return EZDC(IdZNCSum); } + + float EZPCC() { return EZDC(IdZPCC); } + float EZPC1() { return EZDC(IdZPC1); } + float EZPC2() { return EZDC(IdZPC2); } + float EZPC3() { return EZDC(IdZPC3); } + float EZPC4() { return EZDC(IdZPC4); } + float EZPCSum() { return EZDC(IdZPCSum); } + ClassDefNV(RecEventAux, 1); +}; + +} // namespace zdc + +/// Defining RecEventAux explicitly as messageable +/// +/// It does not fulfill is_messageable because the underlying ROOT +/// classes of Point2D are note trivially copyable. +namespace framework +{ +template +struct is_messageable; +template <> +struct is_messageable : std::true_type { +}; +} // namespace framework + +} // namespace o2 + +#endif diff --git a/DataFormats/Detectors/ZDC/include/DataFormatsZDC/TDCData.h b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/TDCData.h new file mode 100644 index 0000000000000..bfb617cf09ab2 --- /dev/null +++ b/DataFormats/Detectors/ZDC/include/DataFormatsZDC/TDCData.h @@ -0,0 +1,48 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef _ZDC_TDC_DATA_H +#define _ZDC_TDC_DATA_H + +#include "ZDCBase/Constants.h" +#include +#include + +/// \file TDCData.h +/// \brief Container class to store a TDC hit in a ZDC channel +/// \author pietro.cortese@cern.ch + +namespace o2 +{ +namespace zdc +{ + +struct TDCData { + + int8_t id = IdDummy; // channel ID + int16_t val; // tdc value + int16_t amp; // tdc amplitude + + TDCData() = default; + TDCData(int8_t ida, int16_t vala, int16_t ampa) + { + id = ida; + val = vala; + amp = ampa; + } + + void print() const; + + ClassDefNV(TDCData, 1); +}; +} // namespace zdc +} // namespace o2 + +#endif diff --git a/DataFormats/Detectors/ZDC/src/BCRecData.cxx b/DataFormats/Detectors/ZDC/src/BCRecData.cxx new file mode 100644 index 0000000000000..e47be2b42e573 --- /dev/null +++ b/DataFormats/Detectors/ZDC/src/BCRecData.cxx @@ -0,0 +1,27 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "DataFormatsZDC/BCData.h" +#include "DataFormatsZDC/ChannelData.h" +#include + +using namespace o2::zdc; + +void BCData::print() const +{ + printf("Orbit %9u bc %4u nch %2d pos %d ntdc %2d pos %d\n", ir.orbit, ir.bc, + refe.getEntries(), refe.getFirstEntry(),reft.getEntries(), reft.getFirstEntry()); +} + +gsl::span BCData::getBunchChannelData(const gsl::span tfdata) const +{ + // extract the span of channel data for this bunch from the whole TF data + return ref.getEntries() ? gsl::span(&tfdata[ref.getFirstEntry()], ref.getEntries()) : gsl::span(); +} diff --git a/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h b/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h index bcac26d11c23a..7408376032e37 100644 --- a/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h +++ b/DataFormats/Detectors/ZDC/src/DataFormatsZDCLinkDef.h @@ -30,6 +30,7 @@ #pragma link C++ class std::vector < o2::zdc::OrbitData> + ; #pragma link C++ class std::vector < o2::zdc::RecEvent> + ; +#pragma link C++ class std::vector < o2::zdc::RecEventAux> + ; #pragma link C++ class std::vector < o2::zdc::OrbitRawData> + ; #pragma link C++ class std::vector < o2::zdc::OrbitRecData> + ; diff --git a/DataFormats/Detectors/ZDC/src/RecEventAux.cxx b/DataFormats/Detectors/ZDC/src/RecEventAux.cxx new file mode 100644 index 0000000000000..7e774ff4ec6fe --- /dev/null +++ b/DataFormats/Detectors/ZDC/src/RecEventAux.cxx @@ -0,0 +1,18 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "DataFormatsZDC/RecEventAux.h" + +using namespace o2::zdc; + +void RecEventAux::print() const +{ + ir.print(); +} diff --git a/DataFormats/Detectors/ZDC/src/TDCData.cxx b/DataFormats/Detectors/ZDC/src/TDCData.cxx new file mode 100644 index 0000000000000..9a51c5eb32efd --- /dev/null +++ b/DataFormats/Detectors/ZDC/src/TDCData.cxx @@ -0,0 +1,18 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "DataFormatsZDC/TDCData.h" + +using namespace o2::zdc; + +void TDCData::print() const +{ + printf("%2d (%s) %d @ %d\n", id, channelName(id), amp, val); +} diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h index 79d638e948b86..b38c031ffcbdd 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/DigiReco.h @@ -21,6 +21,7 @@ #include "DataFormatsZDC/ChannelData.h" #include "DataFormatsZDC/OrbitData.h" #include "DataFormatsZDC/RecEvent.h" +#include "DataFormatsZDC/RecEventAux.h" #ifndef ALICEO2_ZDC_DIGI_RECO_H #define ALICEO2_ZDC_DIGI_RECO_H @@ -60,7 +61,7 @@ class DigiReco const ZDCIntegrationParam* getIntegrationParam() { return mIntParam; }; private: - const ModuleConfig* mModuleConfig = nullptr; /// Trigger/readout configuration object + const ModuleConfig* mModuleConfig = nullptr; /// Trigger/readout configuration object int reconstruct(int seq_beg, int seq_end); /// Main method for data reconstruction void processTrigger(int itdc, int ibeg, int iend); /// Replay of trigger algorithm on acquired data void interpolate(int itdc, int ibeg, int iend); /// Interpolation of samples to evaluate signal amplitude and arrival time @@ -78,10 +79,10 @@ class DigiReco const std::vector* mOrbitData; /// Reconstructed data const std::vector* mBCData; /// BC info const std::vector* mChData; /// Payload - std::vector mReco; /// Reconstructed data + std::vector mReco; /// Reconstructed data std::map mOrbit; /// Information about orbit static constexpr int mNSB = TSN * NTimeBinsPerBC; /// Total number of interpolated points per bunch crossing - RecEvent mRec; /// Debug reconstruction event + RecEventAux mRec; /// Debug reconstruction event int mNBC = 0; int16_t tdc_shift[NTDCChannels] = {0}; /// TDC correction (units of 1/96 ns) constexpr static uint16_t mMask[NTimeBinsPerBC] = {0x0001, 0x002, 0x004, 0x008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200, 0x0400, 0x0800}; diff --git a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h index 312c949e252e9..e6dc0c6472c89 100644 --- a/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h +++ b/Detectors/ZDC/reconstruction/include/ZDCReconstruction/ZDCTDCParam.h @@ -26,8 +26,8 @@ namespace zdc // parameters of ZDC reconstruction struct ZDCTDCParam { + //std::array tdcShift{} float tdc_shift[NTDCChannels] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Correction of TDC position (ns) - public: void setShift(uint32_t ich, float val); float getShift(uint32_t ich) const; void print(); diff --git a/Detectors/ZDC/reconstruction/src/DigiReco.cxx b/Detectors/ZDC/reconstruction/src/DigiReco.cxx index 567d63ca110e6..c94bbcfc5c1d9 100644 --- a/Detectors/ZDC/reconstruction/src/DigiReco.cxx +++ b/Detectors/ZDC/reconstruction/src/DigiReco.cxx @@ -13,12 +13,12 @@ #include "ZDCReconstruction/DigiReco.h" #include "ZDCReconstruction/RecoParamZDC.h" -#define O2_ZDC_DIGIRECO_FLT float namespace o2 { namespace zdc { +using O2_ZDC_DIGIRECO_FLT=float; void DigiReco::init() { @@ -326,7 +326,7 @@ int DigiReco::reconstruct(int ibeg, int iend) } } - RecEvent& rec = mReco[ibun]; + auto &rec = mReco[ibun]; for (int itdc = 0; itdc < NTDCChannels; itdc++) { if (rec.fired[itdc] != 0x0) { printf("%d %u.%u TDC %d %x", ibun, rec.ir.orbit, rec.ir.bc, itdc, rec.fired[itdc]); @@ -399,7 +399,6 @@ int DigiReco::reconstruct(int ibeg, int iend) sum += (pbun[ich] - float(ChData[ref].data[is])); } printf("CH %d %s: %f\n", ich, ChannelNames[ich].data(), sum); - rec.energy[ich] = sum; rec.ezdc[ich] = sum; } } From af2192a79552587ab18d37fa04db5850f404f05e Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 7 May 2021 10:35:22 +0200 Subject: [PATCH 436/770] GPU: Clean up OpenCL test script --- GPU/GPUTracking/Standalone/tools/testCL.sh | 53 ++++++++++++---------- 1 file changed, 30 insertions(+), 23 deletions(-) diff --git a/GPU/GPUTracking/Standalone/tools/testCL.sh b/GPU/GPUTracking/Standalone/tools/testCL.sh index 576e4ceb94e52..1eff97082d2e8 100755 --- a/GPU/GPUTracking/Standalone/tools/testCL.sh +++ b/GPU/GPUTracking/Standalone/tools/testCL.sh @@ -3,46 +3,53 @@ COMPILER=clang++ LLVM_SPIRV=llvm-spirv +echo "Testing using clang `which clang++`, spirv `which llvm-spirv`" + #COMPILER=/usr/lib/llvm/roc-2.1.0/bin/clang++ #COMPILER=/usr/lib/llvm/9/bin/clang++ #COMPILER=/home/qon/alice/llvm-project/build/bin/clang++ #LLVM_SPIRV=/home/qon/alice/llvm-project/build/bin/llvm-spirv -INCLUDES="-I../. -I../DataTypes -I../Definitions -I../Base -I../SliceTracker -I../Common -I../Merger -I../Refit -I../TRDTracking -I../ITS -I../dEdx -I../TPCConvert -I../TPCFastTransformation -I../DataCompression -I../TPCClusterFinder -I../Global -I ../GPUUtils \ - -I$HOME/alice/O2/DataFormats/Detectors/TPC/include -I$HOME/alice/O2/Detectors/Base/include -I$HOME/alice/O2/Detectors/Base/src -I$HOME/alice/O2/Common/MathUtils/include -I$HOME/alice/O2/DataFormats/Headers/include \ - -I$HOME/alice/O2/Detectors/TRD/base/include -I$HOME/alice/O2/Detectors/TRD/base/src -I$HOME/alice/O2/Detectors/ITSMFT/ITS/tracking/include -I$HOME/alice/O2/Detectors/ITSMFT/ITS/tracking/cuda/include -I$HOME/alice/O2/Common/Constants/include \ - -I$HOME/alice/O2/DataFormats/common/include -I$HOME/alice/O2/DataFormats/Detectors/Common/include -I$HOME/alice/O2/DataFormats/Detectors/TRD/include -I$HOME/alice/O2/DataFormats/Reconstruction/include -I$HOME/alice/O2/DataFormats/Reconstruction/src" +O2_DIR=${HOME}/alice/O2 +GPU_DIR=${HOME}/alice/O2/GPU/GPUTracking + +INCLUDES="-I${GPU_DIR}/. -I${GPU_DIR}/DataTypes -I${GPU_DIR}/Definitions -I${GPU_DIR}/Base -I${GPU_DIR}/SliceTracker -I${O2_DIR}/GPU/Common -I${GPU_DIR}/Merger -I${GPU_DIR}/Refit -I${GPU_DIR}/TRDTracking -I${GPU_DIR}/ITS -I${GPU_DIR}/dEdx \ + -I${GPU_DIR}/TPCConvert -I${O2_DIR}/GPU/TPCFastTransformation -I${GPU_DIR}/DataCompression -I${GPU_DIR}/TPCClusterFinder -I${GPU_DIR}/Global -I ${O2_DIR}/GPU/Utils \ + -I${O2_DIR}/DataFormats/Detectors/TPC/include -I${O2_DIR}/Detectors/Base/include -I${O2_DIR}/Detectors/Base/src -I${O2_DIR}/Common/MathUtils/include -I${O2_DIR}/DataFormats/Headers/include \ + -I${O2_DIR}/Detectors/TRD/base/include -I${O2_DIR}/Detectors/TRD/base/src -I${O2_DIR}/Detectors/ITSMFT/ITS/tracking/include -I${O2_DIR}/Detectors/ITSMFT/ITS/tracking/cuda/include -I${O2_DIR}/Common/Constants/include \ + -I${O2_DIR}/DataFormats/common/include -I${O2_DIR}/DataFormats/Detectors/Common/include -I${O2_DIR}/DataFormats/Detectors/TRD/include -I${O2_DIR}/DataFormats/Reconstruction/include -I${O2_DIR}/DataFormats/Reconstruction/src \ + -I${O2_DIR}/Detectors/Raw/include" DEFINES="-DGPUCA_STANDALONE -DGPUCA_GPULIBRARY=OCL -DNDEBUG -D__OPENCLCPP__ -DHAVE_O2HEADERS -DGPUCA_TPC_GEOMETRY_O2" FLAGS="-Xclang -fdenormal-fp-math-f32=ieee -cl-mad-enable -cl-no-signed-zeros -ferror-limit=1000 -Dcl_clang_storage_class_specifiers" echo Test1 - Preprocess -echo $COMPILER -cl-std=clc++ -x cl $INCLUDES $DEFINES -Dcl_clang_storage_class_specifiers -cl-no-stdinc -E ../Base/opencl-common/GPUReconstructionOCL.cl > test.cl - $COMPILER -cl-std=clc++ -x cl $INCLUDES $DEFINES -Dcl_clang_storage_class_specifiers -cl-no-stdinc -E ../Base/opencl-common/GPUReconstructionOCL.cl > test.cl -if [ $? != 0 ]; then exit 1; fi -#Test 1A - Compile Preprocessed -#echo $COMPILER -cl-std=clc++ -x cl -emit-llvm --target=spir64-unknown-unknown $FLAGS -c test.cl -o test.bc -# $COMPILER -cl-std=clc++ -x cl -emit-llvm --target=spir64-unknown-unknown $FLAGS -c test.cl -o test.bc -#exit - -echo -echo Test2 - Clang OCL -echo clang-ocl -O3 -cl-std=clc++ -mcpu=gfx906 $FLAGS $INCLUDES $DEFINES -o test-clang-ocl.o ../Base/opencl-common/GPUReconstructionOCL.cl - clang-ocl -O3 -cl-std=clc++ -mcpu=gfx906 $FLAGS $INCLUDES $DEFINES -o test-clang-ocl.o ../Base/opencl-common/GPUReconstructionOCL.cl -rm -f test-clang-ocl.o.* +echo $COMPILER -cl-std=clc++ -x cl $INCLUDES $DEFINES -Dcl_clang_storage_class_specifiers -cl-no-stdinc -E ${GPU_DIR}/Base/opencl-common/GPUReconstructionOCL.cl > test.cl + $COMPILER -cl-std=clc++ -x cl $INCLUDES $DEFINES -Dcl_clang_storage_class_specifiers -cl-no-stdinc -E ${GPU_DIR}/Base/opencl-common/GPUReconstructionOCL.cl > test.cl if [ $? != 0 ]; then exit 1; fi +echo Test 1A - Compile Preprocessed +echo $COMPILER -cl-std=clc++ -x cl -emit-llvm --target=spir64-unknown-unknown $FLAGS -c test.cl -o test.bc + $COMPILER -cl-std=clc++ -x cl -emit-llvm --target=spir64-unknown-unknown $FLAGS -c test.cl -o test.bc echo -echo Test3 - SPIR-V -echo $COMPILER -O0 -cl-std=clc++ -x cl -emit-llvm --target=spir64-unknown-unknown $FLAGS $INCLUDES $DEFINES -c ../Base/opencl-common/GPUReconstructionOCL.cl -o test.bc - $COMPILER -O0 -cl-std=clc++ -x cl -emit-llvm --target=spir64-unknown-unknown $FLAGS $INCLUDES $DEFINES -c ../Base/opencl-common/GPUReconstructionOCL.cl -o test.bc +echo Test2 - SPIR-V +echo $COMPILER -O0 -cl-std=clc++ -x cl -emit-llvm --target=spir64-unknown-unknown $FLAGS $INCLUDES $DEFINES -c ${GPU_DIR}/Base/opencl-common/GPUReconstructionOCL.cl -o test.bc + $COMPILER -O0 -cl-std=clc++ -x cl -emit-llvm --target=spir64-unknown-unknown $FLAGS $INCLUDES $DEFINES -c ${GPU_DIR}/Base/opencl-common/GPUReconstructionOCL.cl -o test.bc if [ $? != 0 ]; then exit 1; fi echo $LLVM_SPIRV test.bc -o test.spirv $LLVM_SPIRV test.bc -o test.spirv if [ $? != 0 ]; then exit 1; fi echo -echo Test4 - amdgcn -echo $COMPILER -O3 -cl-std=clc++ -x cl --target=amdgcn-amd-amdhsa -mcpu=gfx906 $FLAGS $INCLUDES $DEFINES -c ../Base/opencl-common/GPUReconstructionOCL.cl -o test.o - $COMPILER -O3 -cl-std=clc++ -x cl --target=amdgcn-amd-amdhsa -mcpu=gfx906 $FLAGS $INCLUDES $DEFINES -c ../Base/opencl-common/GPUReconstructionOCL.cl -o test.o +echo Test3 - amdgcn +echo $COMPILER -O3 -cl-std=clc++ -x cl --target=amdgcn-amd-amdhsa -mcpu=gfx906 $FLAGS $INCLUDES $DEFINES -c ${GPU_DIR}/Base/opencl-common/GPUReconstructionOCL.cl -o test.o + $COMPILER -O3 -cl-std=clc++ -x cl --target=amdgcn-amd-amdhsa -mcpu=gfx906 $FLAGS $INCLUDES $DEFINES -c ${GPU_DIR}/Base/opencl-common/GPUReconstructionOCL.cl -o test.o if [ $? != 0 ]; then exit 1; fi + +echo +echo Test4 - Clang OCL +echo clang-ocl -O3 -cl-std=clc++ -mcpu=gfx906 $FLAGS $INCLUDES $DEFINES -o test-clang-ocl.o ${GPU_DIR}/Base/opencl-common/GPUReconstructionOCL.cl + clang-ocl -O3 -cl-std=clc++ -mcpu=gfx906 $FLAGS $INCLUDES $DEFINES -o test-clang-ocl.o ${GPU_DIR}/Base/opencl-common/GPUReconstructionOCL.cl +rm -f test-clang-ocl.o.* +if [ $? != 0 ]; then exit 1; fi + From f471f388d99997061b9369cef004048514b6c506 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 7 May 2021 10:53:01 +0200 Subject: [PATCH 437/770] Add ClassDef for TrackTRD and fix AliRoot compilation --- GPU/GPUTracking/DataTypes/GPUTRDInterfaceO2Track.h | 2 ++ GPU/GPUTracking/DataTypes/GPUTRDTrack.h | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/GPU/GPUTracking/DataTypes/GPUTRDInterfaceO2Track.h b/GPU/GPUTracking/DataTypes/GPUTRDInterfaceO2Track.h index 36fdb23f1a4e5..112a50d91b165 100644 --- a/GPU/GPUTracking/DataTypes/GPUTRDInterfaceO2Track.h +++ b/GPU/GPUTracking/DataTypes/GPUTRDInterfaceO2Track.h @@ -109,6 +109,8 @@ class trackInterface : public GPUTRDO2BaseTrack float mTimeSubMax{0.f}; // max. time that can be subtracted to this track in us short mSide{0}; // -1 : A-side, +1 : C-side (relevant only for TPC-only tracks) float mZShift{0.f}; // calculated new for each TRD trigger candidate for this track + + ClassDefNV(trackInterface, 1); }; } // namespace gpu diff --git a/GPU/GPUTracking/DataTypes/GPUTRDTrack.h b/GPU/GPUTracking/DataTypes/GPUTRDTrack.h index 89a3c05a86725..191a1cea84c27 100644 --- a/GPU/GPUTracking/DataTypes/GPUTRDTrack.h +++ b/GPU/GPUTracking/DataTypes/GPUTRDTrack.h @@ -16,6 +16,7 @@ #include "GPUTRDDef.h" #include "GPUCommonDef.h" +#include "GPUCommonRtypes.h" struct GPUTRDTrackDataRecord; class AliHLTExternalTrackParam; @@ -43,7 +44,10 @@ class GPUTRDTrack_t; } // namespace gpu } // namespace GPUCA_NAMESPACE #else +#if (!defined(GPUCA_STANDALONE) && !defined(GPUCA_ALIROOT_LIB)) || defined(HAVE_O2HEADERS) +#include "GPUTRDO2BaseTrack.h" #include "GPUTRDInterfaceO2Track.h" +#endif namespace GPUCA_NAMESPACE { @@ -118,6 +122,9 @@ class GPUTRDTrack_t : public T private: GPUd() void Initialize(); +#if !defined(GPUCA_STANDALONE) && !defined(GPUCA_ALIROOT_LIB) + ClassDefNV(GPUTRDTrack_t, 1); +#endif }; } // namespace gpu } // namespace GPUCA_NAMESPACE From 8b671b126fba9c5a0348796730bfddb2ace1203a Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sat, 8 May 2021 00:24:45 +0200 Subject: [PATCH 438/770] Fix typos --- .../Detectors/GlobalTracking/src/RecoContainer.cxx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx index 596457f7f4385..42dade5038310 100644 --- a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx +++ b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx @@ -90,20 +90,20 @@ void DataRequest::requestTPCTOFTracks(bool mc) void DataRequest::requestITSTPCTRDTracks(bool mc) { - addInput({"trackTRDTPCITS", "TRD", "MATCHTRD_GLO", 0, Lifetime::Timeframe}); + addInput({"trackITSTPCTRD", "TRD", "MATCHTRD_GLO", 0, Lifetime::Timeframe}); if (mc) { LOG(ERROR) << "TRD Tracks does not support MC truth"; } - requestMap["trackTRDTPCITS"] = false; + requestMap["trackITSTPCTRD"] = false; } void DataRequest::requestTPCTRDTracks(bool mc) { - addInput({"trackTRDTPC", "TRD", "MATCHTRD_TPC", 0, Lifetime::Timeframe}); + addInput({"trackTPCTRD", "TRD", "MATCHTRD_TPC", 0, Lifetime::Timeframe}); if (mc) { LOG(ERROR) << "TRD Tracks does not support MC truth"; } - requestMap["trackTRDTPC"] = false; + requestMap["trackTPCTRD"] = false; } void DataRequest::requestTOFMatches(bool mc) From 0fc11b5fce98310c2611a601962620bcd6fcddfa Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sat, 8 May 2021 00:26:19 +0200 Subject: [PATCH 439/770] TRD Tracking: Use TrackTRD as datatype in the workflows instead of GPUTRDTrack --- .../include/TRDWorkflow/TRDTrackReaderSpec.h | 6 ++-- .../workflow/src/TRDGlobalTrackingSpec.cxx | 5 ++-- .../TRD/workflow/src/TRDTrackWriterSpec.cxx | 28 +++++++++---------- 3 files changed, 18 insertions(+), 21 deletions(-) diff --git a/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackReaderSpec.h b/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackReaderSpec.h index 19b5e722054e0..9fcd607d3424b 100644 --- a/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackReaderSpec.h +++ b/Detectors/TRD/workflow/include/TRDWorkflow/TRDTrackReaderSpec.h @@ -13,9 +13,7 @@ /// @file TRDTrackReaderSpec.h -#include "GPUO2Interface.h" -#include "GPUTRDDef.h" -#include "GPUTRDTrack.h" +#include "DataFormatsTRD/TrackTRD.h" #include "Framework/DataProcessorSpec.h" #include "Framework/Task.h" @@ -54,7 +52,7 @@ class TRDTrackReader : public Task std::unique_ptr mFile; std::unique_ptr mTree; std::string mFileName = ""; - std::vector mTracks, *mTracksPtr = &mTracks; + std::vector mTracks, *mTracksPtr = &mTracks; }; /// read TPC-TRD matched tracks from a root file diff --git a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx index aa6a73ba65d6e..aa3c68c884a1d 100644 --- a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx @@ -23,6 +23,7 @@ #include "TPCBase/ParameterElectronics.h" #include "TPCBase/ParameterGas.h" #include "DataFormatsTRD/RecoInputContainer.h" +#include "DataFormatsTRD/TrackTRD.h" // GPU header #include "GPUReconstruction.h" @@ -152,8 +153,8 @@ void TRDGlobalTracking::run(ProcessingContext& pc) //mTracker->DumpTracks(); // finished tracking, now collect the output - std::vector tracksOutITSTPC(nTracksLoadedITSTPC); - std::vector tracksOutTPC(nTracksLoadedTPC); + std::vector tracksOutITSTPC(nTracksLoadedITSTPC); + std::vector tracksOutTPC(nTracksLoadedTPC); if (mTracker->NTracks() != nTracksLoadedITSTPC + nTracksLoadedTPC) { LOGF(FATAL, "Got %i matched tracks in total whereas %i ITS-TPC + %i TPC = %i tracks were loaded as input", mTracker->NTracks(), nTracksLoadedITSTPC, nTracksLoadedTPC, nTracksLoadedITSTPC + nTracksLoadedTPC); } diff --git a/Detectors/TRD/workflow/src/TRDTrackWriterSpec.cxx b/Detectors/TRD/workflow/src/TRDTrackWriterSpec.cxx index c8dfc3c39b133..d54cc00b9aa75 100644 --- a/Detectors/TRD/workflow/src/TRDTrackWriterSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDTrackWriterSpec.cxx @@ -11,9 +11,7 @@ /// @file TRDTrackWriterSpec.cxx #include -#include "GPUO2Interface.h" -#include "GPUTRDDef.h" -#include "GPUTRDTrack.h" +#include "DataFormatsTRD/TrackTRD.h" #include "DPLUtils/MakeRootTreeWriterSpec.h" #include "TRDWorkflow/TRDTrackWriterSpec.h" @@ -41,18 +39,18 @@ DataProcessorSpec getTRDGlobalTrackWriterSpec(bool useMC) // A spectator to store the size of the data array for the logger below auto tracksSize = std::make_shared(); - auto tracksLogger = [tracksSize](std::vector const& tracks) { + auto tracksLogger = [tracksSize](std::vector const& tracks) { *tracksSize = tracks.size(); }; return MakeRootTreeWriterSpec("trd-track-writer-tpcits", "trdmatches_itstpc.root", "tracksTRD", - BranchDefinition>{InputSpec{"tracks", o2::header::gDataOriginTRD, "MATCHTRD_GLO", 0}, - "tracks", - "tracks-branch-name", - 1, - tracksLogger}, + BranchDefinition>{InputSpec{"tracks", o2::header::gDataOriginTRD, "MATCHTRD_GLO", 0}, + "tracks", + "tracks-branch-name", + 1, + tracksLogger}, // NOTE: this branch template is to show how the conditional MC labels can // be defined, the '0' disables the branch for the moment BranchDefinition{InputSpec{"matchtpclabels", "GLO", "SOME_LABELS", 0}, @@ -72,18 +70,18 @@ DataProcessorSpec getTRDTPCTrackWriterSpec(bool useMC) // A spectator to store the size of the data array for the logger below auto tracksSize = std::make_shared(); - auto tracksLogger = [tracksSize](std::vector const& tracks) { + auto tracksLogger = [tracksSize](std::vector const& tracks) { *tracksSize = tracks.size(); }; return MakeRootTreeWriterSpec("trd-track-writer-tpc", "trdmatches_tpc.root", "tracksTRD", - BranchDefinition>{InputSpec{"tracks", o2::header::gDataOriginTRD, "MATCHTRD_TPC", 0}, - "tracks", - "tracks-branch-name", - 1, - tracksLogger}, + BranchDefinition>{InputSpec{"tracks", o2::header::gDataOriginTRD, "MATCHTRD_TPC", 0}, + "tracks", + "tracks-branch-name", + 1, + tracksLogger}, // NOTE: this branch template is to show how the conditional MC labels can // be defined, the '0' disables the branch for the moment BranchDefinition{InputSpec{"matchtpclabels", "GLO", "SOME_LABELS", 0}, From 872431936eedcb6264aaded3c2b5e17125d8efe0 Mon Sep 17 00:00:00 2001 From: pillot Date: Sat, 8 May 2021 09:26:24 +0200 Subject: [PATCH 440/770] [MCH] add optional protections against high-occupancy DE and/or event (#6085) * add optional protections against high-occupancy DE and/or event * change option name --- .../MCHPreClustering/PreClusterFinder.h | 4 + .../PreClustering/src/PreClusterFinder.cxx | 83 ++++++++++++++----- .../MCH/Workflow/src/PreClusterFinderSpec.cxx | 19 ++++- 3 files changed, 84 insertions(+), 22 deletions(-) diff --git a/Detectors/MUON/MCH/PreClustering/include/MCHPreClustering/PreClusterFinder.h b/Detectors/MUON/MCH/PreClustering/include/MCHPreClustering/PreClusterFinder.h index 65f0e3363e960..c706efc6d0ed2 100644 --- a/Detectors/MUON/MCH/PreClustering/include/MCHPreClustering/PreClusterFinder.h +++ b/Detectors/MUON/MCH/PreClustering/include/MCHPreClustering/PreClusterFinder.h @@ -49,6 +49,8 @@ class PreClusterFinder void loadDigits(gsl::span digits); void loadDigit(const Digit& digit); + int discardHighOccupancy(bool perDE, bool perEvent); + int run(); void getPreClusters(std::vector& preClusters, std::vector& digits); @@ -64,6 +66,8 @@ class PreClusterFinder bool storeMe; // true if precluster to be saved (merging result) }; + void reset(int deIndex); + void preClusterizeRecursive(); void addPad(DetectionElement& de, uint16_t iPad, PreCluster& cluster); diff --git a/Detectors/MUON/MCH/PreClustering/src/PreClusterFinder.cxx b/Detectors/MUON/MCH/PreClustering/src/PreClusterFinder.cxx index 4852504284350..409e0773d01ea 100644 --- a/Detectors/MUON/MCH/PreClustering/src/PreClusterFinder.cxx +++ b/Detectors/MUON/MCH/PreClustering/src/PreClusterFinder.cxx @@ -74,36 +74,40 @@ void PreClusterFinder::deinit() void PreClusterFinder::reset() { /// reset fired pad and precluster information - - Mapping::MpPad* pad(nullptr); - - // loop over DEs for (int iDE = 0; iDE < SNDEs; ++iDE) { + reset(iDE); + } +} - DetectionElement& de(*(mDEs[iDE])); +//_________________________________________________________________________________________________ +void PreClusterFinder::reset(int deIndex) +{ + /// reset fired pad and precluster information of this DE - // loop over planes - for (int iPlane = 0; iPlane < 2; ++iPlane) { + Mapping::MpPad* pad(nullptr); + DetectionElement& de(*(mDEs[deIndex])); - // clear number of preclusters - mNPreClusters[iDE][iPlane] = 0; + // loop over planes + for (int iPlane = 0; iPlane < 2; ++iPlane) { - // loop over fired pads - for (int iFiredPad = 0; iFiredPad < de.nFiredPads[iPlane]; ++iFiredPad) { + // clear number of preclusters + mNPreClusters[deIndex][iPlane] = 0; - pad = &de.mapping->pads[de.firedPads[iPlane][iFiredPad]]; - pad->iDigit = 0; - pad->useMe = false; - } + // loop over fired pads + for (int iFiredPad = 0; iFiredPad < de.nFiredPads[iPlane]; ++iFiredPad) { - // clear number of fired pads - de.nFiredPads[iPlane] = 0; + pad = &de.mapping->pads[de.firedPads[iPlane][iFiredPad]]; + pad->iDigit = 0; + pad->useMe = false; } - // clear ordered number of fired pads - de.nOrderedPads[0] = 0; - de.nOrderedPads[1] = 0; + // clear number of fired pads + de.nFiredPads[iPlane] = 0; } + + // clear ordered number of fired pads + de.nOrderedPads[0] = 0; + de.nOrderedPads[1] = 0; } //_________________________________________________________________________________________________ @@ -147,6 +151,45 @@ void PreClusterFinder::loadDigit(const Digit& digit) ++de.nFiredPads[iPlane]; } +//_________________________________________________________________________________________________ +int PreClusterFinder::discardHighOccupancy(bool perDE, bool perEvent) +{ + /// discard high-occupancy (noisy) DE and/or event + + static constexpr double maxOccupancy = 0.2; + static constexpr int maxHighOccupancyDE = 4; + + if (!perDE && !perEvent) { + return 0; + } + + // discard DE with high occupancy in either bending or non-bending plane on stations 3-4-5 + int nDigits(0); + int nRemovedDigits(0); + int nHighOccupancyDE(0); + for (int iDE = 0; iDE < SNDEs; ++iDE) { + DetectionElement& de(*(mDEs[iDE])); + nDigits += de.nFiredPads[0] + de.nFiredPads[1]; + if (de.mapping->uid >= 500 && + (de.nFiredPads[0] > maxOccupancy * de.mapping->nPads[0] || + de.nFiredPads[1] > maxOccupancy * de.mapping->nPads[1])) { + ++nHighOccupancyDE; + if (perDE) { + nRemovedDigits += de.nFiredPads[0] + de.nFiredPads[1]; + reset(iDE); + } + } + } + + // discard events with too many high-occupancy DE + if (perEvent && nHighOccupancyDE > maxHighOccupancyDE) { + nRemovedDigits = nDigits; + reset(); + } + + return nRemovedDigits; +} + //_________________________________________________________________________________________________ int PreClusterFinder::run() { diff --git a/Detectors/MUON/MCH/Workflow/src/PreClusterFinderSpec.cxx b/Detectors/MUON/MCH/Workflow/src/PreClusterFinderSpec.cxx index a53b6565c5d10..639c1d476c1ff 100644 --- a/Detectors/MUON/MCH/Workflow/src/PreClusterFinderSpec.cxx +++ b/Detectors/MUON/MCH/Workflow/src/PreClusterFinderSpec.cxx @@ -65,6 +65,7 @@ class PreClusterFinderTask auto stop = [this]() { LOG(INFO) << "reset precluster finder duration = " << mTimeResetPreClusterFinder.count() << " ms"; LOG(INFO) << "load digits duration = " << mTimeLoadDigits.count() << " ms"; + LOG(INFO) << "discard high occupancy duration = " << mTimeDiscardHighOccupancy.count() << " ms"; LOG(INFO) << "precluster finder duration = " << mTimePreClusterFinder.count() << " ms"; LOG(INFO) << "store precluster duration = " << mTimeStorePreClusters.count() << " ms"; /// Clear the preclusterizer @@ -84,6 +85,8 @@ class PreClusterFinderTask } else if (checkNoLeftoverDigits == "fatal") { mCheckNoLeftoverDigits = CHECK_NO_LEFTOVER_DIGITS_FATAL; } + mDiscardHighOccDEs = ic.options().get("discard-high-occupancy-des"); + mDiscardHighOccEvents = ic.options().get("discard-high-occupancy-events"); } //_________________________________________________________________________________________________ @@ -105,6 +108,7 @@ class PreClusterFinderTask mPreClusters.clear(); mUsedDigits.clear(); mUsedDigits.reserve(digits.size()); + int nRemovedDigits(0); for (const auto& digitROF : digitROFs) { @@ -122,6 +126,12 @@ class PreClusterFinderTask tEnd = std::chrono::high_resolution_clock::now(); mTimeLoadDigits += tEnd - tStart; + // discard high-occupancy (noisy) DEs and/or events + tStart = std::chrono::high_resolution_clock::now(); + nRemovedDigits += mPreClusterFinder.discardHighOccupancy(mDiscardHighOccDEs, mDiscardHighOccEvents); + tEnd = std::chrono::high_resolution_clock::now(); + mTimeDiscardHighOccupancy += tEnd - tStart; + // preclusterize tStart = std::chrono::high_resolution_clock::now(); int nPreClusters = mPreClusterFinder.run(); @@ -137,7 +147,7 @@ class PreClusterFinderTask } // check sizes of input and output digits vectors - bool digitsSizesDiffer = (mUsedDigits.size() != digits.size()); + bool digitsSizesDiffer = (nRemovedDigits + mUsedDigits.size() != digits.size()); switch (mCheckNoLeftoverDigits) { case CHECK_NO_LEFTOVER_DIGITS_OFF: break; @@ -164,9 +174,12 @@ class PreClusterFinderTask std::vector mUsedDigits{}; ///< vector of digits in the preclusters int mCheckNoLeftoverDigits{CHECK_NO_LEFTOVER_DIGITS_ERROR}; ///< digits vector size check option + bool mDiscardHighOccDEs = false; ///< discard DEs with occupancy > 20% + bool mDiscardHighOccEvents = false; ///< discard events with >= 5 DEs above 20% occupancy std::chrono::duration mTimeResetPreClusterFinder{}; ///< timer std::chrono::duration mTimeLoadDigits{}; ///< timer + std::chrono::duration mTimeDiscardHighOccupancy{}; ///< timer std::chrono::duration mTimePreClusterFinder{}; ///< timer std::chrono::duration mTimeStorePreClusters{}; ///< timer }; @@ -183,7 +196,9 @@ o2::framework::DataProcessorSpec getPreClusterFinderSpec() OutputSpec{{"preclusters"}, "MCH", "PRECLUSTERS", 0, Lifetime::Timeframe}, OutputSpec{{"preclusterdigits"}, "MCH", "PRECLUSTERDIGITS", 0, Lifetime::Timeframe}}, AlgorithmSpec{adaptFromTask()}, - Options{{"check-no-leftover-digits", VariantType::String, "error", {helpstr}}}}; + Options{{"check-no-leftover-digits", VariantType::String, "error", {helpstr}}, + {"discard-high-occupancy-des", VariantType::Bool, false, {"discard DEs with occupancy > 20%"}}, + {"discard-high-occupancy-events", VariantType::Bool, false, {"discard events with >= 5 DEs above 20% occupancy"}}}}; } } // end namespace mch From 1ebb7f251474c42be05f473d337e011d92b216e3 Mon Sep 17 00:00:00 2001 From: Piotr Konopka Date: Sat, 8 May 2021 09:26:42 +0200 Subject: [PATCH 441/770] [QC-579] Fix detecting overlapping inputs in DataSpecUtils::includes and Data Sampling (#6078) --- Framework/Core/src/DataSpecUtils.cxx | 2 +- .../Core/test/unittest_DataSpecUtils.cxx | 4 ++++ .../DataSampling/test/test_DataSampling.cxx | 21 +++++++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/Framework/Core/src/DataSpecUtils.cxx b/Framework/Core/src/DataSpecUtils.cxx index 0111b8282a0f8..df0333d53ad79 100644 --- a/Framework/Core/src/DataSpecUtils.cxx +++ b/Framework/Core/src/DataSpecUtils.cxx @@ -643,7 +643,7 @@ bool DataSpecUtils::includes(const InputSpec& left, const InputSpec& right) auto leftInfo = extractMatcherInfo(leftMatcher); return (!leftInfo.hasOrigin || (rightInfo.hasOrigin && leftInfo.origin == rightInfo.origin)) && (!leftInfo.hasDescription || (rightInfo.hasDescription && leftInfo.description == rightInfo.description)) && - (!leftInfo.hasSubSpec || (rightInfo.hasSubSpec && leftInfo.subSpec == rightInfo.hasSubSpec)); + (!leftInfo.hasSubSpec || (rightInfo.hasSubSpec && leftInfo.subSpec == rightInfo.subSpec)); }}, left.matcher); }}, diff --git a/Framework/Core/test/unittest_DataSpecUtils.cxx b/Framework/Core/test/unittest_DataSpecUtils.cxx index d354732e7e3d7..7412c72124b10 100644 --- a/Framework/Core/test/unittest_DataSpecUtils.cxx +++ b/Framework/Core/test/unittest_DataSpecUtils.cxx @@ -341,4 +341,8 @@ BOOST_AUTO_TEST_CASE(Includes) BOOST_CHECK(DataSpecUtils::includes(wildcardInput1, wildcardInput1)); BOOST_CHECK(!DataSpecUtils::includes(wildcardInput1, wildcardInput2)); BOOST_CHECK(!DataSpecUtils::includes(wildcardInput2, wildcardInput1)); + + auto inputsFromQuery = DataDescriptorQueryBuilder::parse("b0:TST/FOO/0;b1:TST/FOO/1"); + BOOST_CHECK(!DataSpecUtils::includes(inputsFromQuery[0], inputsFromQuery[1])); + BOOST_CHECK(!DataSpecUtils::includes(inputsFromQuery[1], inputsFromQuery[0])); } diff --git a/Utilities/DataSampling/test/test_DataSampling.cxx b/Utilities/DataSampling/test/test_DataSampling.cxx index e3eff2d236310..9f3d7f3655130 100644 --- a/Utilities/DataSampling/test/test_DataSampling.cxx +++ b/Utilities/DataSampling/test/test_DataSampling.cxx @@ -300,4 +300,25 @@ BOOST_AUTO_TEST_CASE(DataSamplingOverlappingInputs) BOOST_CHECK_EQUAL(inputs[2], (InputSpec{"asdf", {"TST", "CCCC"}})); BOOST_CHECK_EQUAL(inputs[3], (InputSpec{"timer-stats", "DS", "TIMER-dispatcher", 0, Lifetime::Timer})); } + + { + // two policies with one common concrete data spec + Dispatcher dispatcher("dispatcher", ""); + auto policy1 = std::make_unique("policy1"); + policy1->registerPath({"random", "TST", "AAAA", 0}, {{"erwv"}, "DS", "XYZ", 0}); + + auto policy2 = std::make_unique("policy2"); + policy2->registerPath({"random0", "TST", "AAAA", 0}, {{"fdsf"}, "DS", "BBBB", 0}); + policy2->registerPath({"random1", "TST", "AAAA", 1}, {{"fdsf"}, "DS", "BBBB", 1}); + + dispatcher.registerPolicy(std::move(policy1)); + dispatcher.registerPolicy(std::move(policy2)); + + auto inputs = dispatcher.getInputSpecs(); + + BOOST_REQUIRE_EQUAL(inputs.size(), 3); + BOOST_CHECK_EQUAL(inputs[0], (InputSpec{"random0", "TST", "AAAA", 0})); + BOOST_CHECK_EQUAL(inputs[1], (InputSpec{"random1", "TST", "AAAA", 1})); + BOOST_CHECK_EQUAL(inputs[2], (InputSpec{"timer-stats", "DS", "TIMER-dispatcher", 0, Lifetime::Timer})); + } } From cc8b8a496f088b5f3e34614d378bcc8cf09c36a1 Mon Sep 17 00:00:00 2001 From: matthias-kleiner <48915672+matthias-kleiner@users.noreply.github.com> Date: Sat, 8 May 2021 09:27:19 +0200 Subject: [PATCH 442/770] Reducing granularity in PoissonSolver test (#6070) --- Detectors/TPC/spacecharge/test/testO2TPCPoissonSolver.cxx | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Detectors/TPC/spacecharge/test/testO2TPCPoissonSolver.cxx b/Detectors/TPC/spacecharge/test/testO2TPCPoissonSolver.cxx index 61d615b252d99..fddd0377db334 100644 --- a/Detectors/TPC/spacecharge/test/testO2TPCPoissonSolver.cxx +++ b/Detectors/TPC/spacecharge/test/testO2TPCPoissonSolver.cxx @@ -29,8 +29,10 @@ using DataT = double; // using float actually takes alot l static constexpr DataT TOLERANCE = 3; // relative tolerance for 3D (maximum large error is at phi=90 since there the potential is 0!) static constexpr DataT TOLERANCE2D = 8.5; // relative tolerance for 2D TODO check why the difference between numerical and analyticial is larger than for 3D! static constexpr DataT ABSTOLERANCE = 0.01; // absolute tolerance is taken at small values near 0 -static constexpr int NR = 129; // grid in r -static constexpr int NZ = 129; // grid in z +static constexpr int NR = 65; // grid in r +static constexpr int NZ = 65; // grid in z +static constexpr int NR2D = 129; // grid in r +static constexpr int NZ2D = 129; // grid in z static constexpr int NPHI = 180; // grid in phi /// Get phi vertex position for index in phi direction @@ -233,7 +235,7 @@ BOOST_AUTO_TEST_CASE(PoissonSolver3D2D_test) BOOST_AUTO_TEST_CASE(PoissonSolver2D_test) { const int Nphi = 1; - poissonSolver2D(); + poissonSolver2D(); } } // namespace tpc From 7b8ac7097c371aa9a7409bb68722e32d9ab93a30 Mon Sep 17 00:00:00 2001 From: rpezzi Date: Sat, 8 May 2021 09:30:13 +0200 Subject: [PATCH 443/770] [MFT] Adds configuration methods to the MFT track fitter (#6053) * [MFT] Adds configuration methods to the mft track fitter Changes in this PR allows one to instanciate and configure the fitter in standalone macros, for debugging and development purposes Co-authored-by: ALICE Action Bot --- .../include/MFTTracking/TrackFitter.h | 14 +++++-- .../ITSMFT/MFT/tracking/src/TrackFitter.cxx | 41 ++++++------------- Detectors/ITSMFT/MFT/tracking/src/Tracker.cxx | 4 ++ 3 files changed, 26 insertions(+), 33 deletions(-) diff --git a/Detectors/ITSMFT/MFT/tracking/include/MFTTracking/TrackFitter.h b/Detectors/ITSMFT/MFT/tracking/include/MFTTracking/TrackFitter.h index 91601db595087..613cb75d46068 100644 --- a/Detectors/ITSMFT/MFT/tracking/include/MFTTracking/TrackFitter.h +++ b/Detectors/ITSMFT/MFT/tracking/include/MFTTracking/TrackFitter.h @@ -44,7 +44,10 @@ class TrackFitter TrackFitter(TrackFitter&&) = delete; TrackFitter& operator=(TrackFitter&&) = delete; - void setBz(float bZ); + void setBz(float bZ) { mBZField = bZ; } + void setMFTRadLength(float x2X0) { mMFTRadLength = x2X0; } + void setVerbosity(float v) { mVerbose = v; } + void setTrackModel(float m) { mTrackModel = m; } bool initTrack(TrackLTF& track, bool outward = false); bool fit(TrackLTF& track, bool outward = false); @@ -55,13 +58,16 @@ class TrackFitter private: bool computeCluster(TrackLTF& track, int cluster); - Float_t mBZField; // kiloGauss. + bool mFieldON = true; + Float_t mBZField; // kiloGauss. + Float_t mMFTRadLength = 0.1; + Int_t mTrackModel = MFTTrackModel::Helix; + static constexpr double SMaxChi2 = 2.e10; ///< maximum chi2 above which the track can be considered as abnormal /// default layer thickness in X0 for reconstruction //FIXME: set values for the MFT static constexpr double SLayerThicknessInX0[10] = {0.065, 0.065, 0.075, 0.075, 0.035, 0.035, 0.035, 0.035, 0.035, 0.035}; - - bool mFieldON = true; + bool mVerbose = false; }; // Functions to estimate momentum and charge from track curvature diff --git a/Detectors/ITSMFT/MFT/tracking/src/TrackFitter.cxx b/Detectors/ITSMFT/MFT/tracking/src/TrackFitter.cxx index e21d0bc11c2bd..23dbc8bed039b 100644 --- a/Detectors/ITSMFT/MFT/tracking/src/TrackFitter.cxx +++ b/Detectors/ITSMFT/MFT/tracking/src/TrackFitter.cxx @@ -36,19 +36,6 @@ namespace o2 namespace mft { -//_________________________________________________________________________________________________ -void TrackFitter::setBz(float bZ) -{ - auto& mftTrackingParam = MFTTrackingParam::Instance(); - - /// Set the magnetic field for the MFT - mBZField = bZ; - - if (mftTrackingParam.verbose) { - LOG(INFO) << "Setting Fitter field = " << bZ; - } -} - //_________________________________________________________________________________________________ bool TrackFitter::fit(TrackLTF& track, bool outward) { @@ -56,10 +43,9 @@ bool TrackFitter::fit(TrackLTF& track, bool outward) /// Fit a track using its attached clusters /// Returns false in case of failure - auto& mftTrackingParam = MFTTrackingParam::Instance(); auto nClusters = track.getNumberOfPoints(); - if (mftTrackingParam.verbose) { + if (mVerbose) { std::cout << "Seed covariances: \n" << track.getCovariances() << std::endl << std::endl; @@ -82,7 +68,7 @@ bool TrackFitter::fit(TrackLTF& track, bool outward) ncl++; } } - if (mftTrackingParam.verbose) { + if (mVerbose) { // Print final covariances? std::cout << "Track covariances:"; track->getCovariances().Print(); std::cout << "Track Chi2 = " << track.getTrackChi2() << std::endl; std::cout << " ***************************** Done fitting *****************************\n"; @@ -95,8 +81,6 @@ bool TrackFitter::fit(TrackLTF& track, bool outward) bool TrackFitter::initTrack(TrackLTF& track, bool outward) { - auto& mftTrackingParam = MFTTrackingParam::Instance(); - // initialize the starting track parameters and cluster double sigmainvQPtsq; double chi2invqptquad; @@ -105,7 +89,7 @@ bool TrackFitter::initTrack(TrackLTF& track, bool outward) auto k = TMath::Abs(o2::constants::math::B2C * mBZField); auto Hz = std::copysign(1, mBZField); - if (mftTrackingParam.verbose) { + if (mVerbose) { std::cout << "\n ***************************** Start Fitting new track ***************************** \n"; std::cout << "N Clusters = " << nPoints << std::endl; } @@ -149,9 +133,9 @@ bool TrackFitter::initTrack(TrackLTF& track, bool outward) track.setPhi(phi0); track.setTanl(tanl0); - if (mftTrackingParam.verbose) { + if (mVerbose) { std::cout << " Init " << (track.isCA() ? "CA Track " : "LTF Track") << std::endl; - auto model = (mftTrackingParam.trackmodel == Helix) ? "Helix" : (mftTrackingParam.trackmodel == Quadratic) ? "Quadratic" : "Linear"; + auto model = (mTrackModel == Helix) ? "Helix" : (mTrackModel == Quadratic) ? "Quadratic" : "Linear"; std::cout << "Track Model: " << model << std::endl; std::cout << " initTrack: X = " << x0 << " Y = " << y0 << " Z = " << z0 << " Tgl = " << tanl0 << " Phi = " << phi0 << " pz = " << track.getPz() << " qpt = " << 1.0 / track.getInvQPt() << std::endl; std::cout << " Variances: sigma2_x0 = " << TMath::Sqrt(sigmax0sq) << " sigma2_y0 = " << TMath::Sqrt(sigmay0sq) << " sigma2_q/pt = " << TMath::Sqrt(sigmainvQPtsq) << std::endl; @@ -229,7 +213,6 @@ bool TrackFitter::computeCluster(TrackLTF& track, int cluster) /// Recompute the parameters adding the cluster constraint with the Kalman filter /// Returns false in case of failure - auto& mftTrackingParam = MFTTrackingParam::Instance(); const auto& clx = track.getXCoordinates()[cluster]; const auto& cly = track.getYCoordinates()[cluster]; const auto& clz = track.getZCoordinates()[cluster]; @@ -241,7 +224,7 @@ bool TrackFitter::computeCluster(TrackLTF& track, int cluster) LOG(INFO) << "track.getZ() = " << track.getZ() << " ; newClusterZ = " << clz << " ==> Skipping point."; return true; } - if (mftTrackingParam.verbose) { + if (mVerbose) { std::cout << "computeCluster: X = " << clx << " Y = " << cly << " Z = " << clz << " nCluster = " << cluster << std::endl; } @@ -269,8 +252,8 @@ bool TrackFitter::computeCluster(TrackLTF& track, int cluster) NDisksMS = (startingLayerID % 2 == 0) ? (newLayerID - startingLayerID + 1) / 2 : (newLayerID - startingLayerID) / 2; } - auto MFTDiskThicknessInX0 = mftTrackingParam.MFTRadLength / 5.0; - if (mftTrackingParam.verbose) { + auto MFTDiskThicknessInX0 = mMFTRadLength / 5.0; + if (mVerbose) { std::cout << "startingLayerID = " << startingLayerID << " ; " << "newLayerID = " << newLayerID << " ; "; std::cout << "cl.getZ() = " << clz << " ; "; @@ -282,12 +265,12 @@ bool TrackFitter::computeCluster(TrackLTF& track, int cluster) track.addMCSEffect(-1, NDisksMS * MFTDiskThicknessInX0); } - if (mftTrackingParam.verbose) { + if (mVerbose) { std::cout << " BeforeExtrap: X = " << track.getX() << " Y = " << track.getY() << " Z = " << track.getZ() << " Tgl = " << track.getTanl() << " Phi = " << track.getPhi() << " pz = " << track.getPz() << " qpt = " << 1.0 / track.getInvQPt() << std::endl; } // Propagate track to the z position of the new cluster - switch (mftTrackingParam.trackmodel) { + switch (mTrackModel) { case Linear: track.propagateToZlinear(clz); break; @@ -303,7 +286,7 @@ bool TrackFitter::computeCluster(TrackLTF& track, int cluster) break; } - if (mftTrackingParam.verbose) { + if (mVerbose) { std::cout << " AfterExtrap: X = " << track.getX() << " Y = " << track.getY() << " Z = " << track.getZ() << " Tgl = " << track.getTanl() << " Phi = " << track.getPhi() << " pz = " << track.getPz() << " qpt = " << 1.0 / track.getInvQPt() << std::endl; } @@ -312,7 +295,7 @@ bool TrackFitter::computeCluster(TrackLTF& track, int cluster) const std::array& cov = {sigmaX2, sigmaY2}; if (track.update(pos, cov)) { - if (mftTrackingParam.verbose) { + if (mVerbose) { std::cout << " New Cluster: X = " << clx << " Y = " << cly << " Z = " << clz << std::endl; std::cout << " AfterKalman: X = " << track.getX() << " Y = " << track.getY() << " Z = " << track.getZ() << " Tgl = " << track.getTanl() << " Phi = " << track.getPhi() << " pz = " << track.getPz() << " qpt = " << 1.0 / track.getInvQPt() << std::endl; std::cout << std::endl; diff --git a/Detectors/ITSMFT/MFT/tracking/src/Tracker.cxx b/Detectors/ITSMFT/MFT/tracking/src/Tracker.cxx index e6fa83846be88..73d614911d2eb 100644 --- a/Detectors/ITSMFT/MFT/tracking/src/Tracker.cxx +++ b/Detectors/ITSMFT/MFT/tracking/src/Tracker.cxx @@ -44,6 +44,10 @@ void Tracker::initConfig(const MFTTrackingParam& trkParam, bool printConfig) { /// initialize from MFTTrackingParam (command line configuration parameters) + mTrackFitter->setMFTRadLength(trkParam.MFTRadLength); + mTrackFitter->setVerbosity(trkParam.verbose); + mTrackFitter->setTrackModel(trkParam.trackmodel); + mMinTrackPointsLTF = trkParam.MinTrackPointsLTF; mMinTrackPointsCA = trkParam.MinTrackPointsCA; mMinTrackStationsLTF = trkParam.MinTrackStationsLTF; From dd744371f6f00d8974820447ed8ad8fbebd50fc6 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 7 May 2021 21:55:35 +0200 Subject: [PATCH 444/770] Use a template argument for the lambda to allow passing in different track types --- .../DataFormatsGlobalTracking/RecoContainer.h | 5 +- .../RecoContainerCreateTracksVariadic.h | 164 ++++++++++++++++++ .../GlobalTracking/src/RecoContainer.cxx | 156 +---------------- Detectors/GlobalTracking/src/MatchCosmics.cxx | 6 +- Detectors/GlobalTracking/src/MatchTPCITS.cxx | 4 +- .../src/PrimaryVertexingSpec.cxx | 6 +- .../Vertexing/src/VertexTrackMatcher.cxx | 6 +- 7 files changed, 188 insertions(+), 159 deletions(-) create mode 100644 DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainerCreateTracksVariadic.h diff --git a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h index 6ec19b5463492..d66fab5f92d84 100644 --- a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h +++ b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h @@ -106,7 +106,10 @@ struct RecoContainer { std::unique_ptr inputsTRD; // special struct for TRD tracklets, trigger records void collectData(o2::framework::ProcessingContext& pc, const DataRequest& request); - void createTracks(std::function const& creator) const; + void createTracks(std::function const& creator) const; + void createTracksWithMatchingTimeInfo(std::function const& creator) const; + template + void createTracksVariadic(T creator) const; void fillTrackMCLabels(const gsl::span gids, std::vector& mcinfo) const; void addITSTracks(o2::framework::ProcessingContext& pc, bool mc); diff --git a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainerCreateTracksVariadic.h b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainerCreateTracksVariadic.h new file mode 100644 index 0000000000000..42163443cb552 --- /dev/null +++ b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainerCreateTracksVariadic.h @@ -0,0 +1,164 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file RecoContainerCreateTracksVariadic.h +/// \brief Wrapper container for different reconstructed object types +/// \author ruben.shahoyan@cern.ch + +#include "Framework/ProcessingContext.h" +#include "Framework/InputSpec.h" +#include "DetectorsCommonDataFormats/DetID.h" +#include "DataFormatsTPC/WorkflowHelper.h" +#include "DataFormatsTRD/RecoInputContainer.h" +#include "DataFormatsGlobalTracking/RecoContainer.h" +#include "DataFormatsITSMFT/CompCluster.h" +#include "DataFormatsITS/TrackITS.h" +#include "DataFormatsTPC/TrackTPC.h" +#include "DataFormatsTOF/Cluster.h" +#include "DataFormatsITSMFT/ROFRecord.h" +#include "DataFormatsFT0/RecPoints.h" +#include "DataFormatsTRD/TrackTRD.h" +#include "ReconstructionDataFormats/TrackTPCITS.h" +#include "ReconstructionDataFormats/TrackTPCTOF.h" +#include "ReconstructionDataFormats/MatchInfoTOF.h" + +//________________________________________________________ +template +void o2::globaltracking::RecoContainer::createTracksVariadic(T creator) const +{ + // We go from most complete tracks to least complete ones, taking into account that some track times + // do not bear their own kinematics but just constrain the time + // As we get more track types functional, this method should be completed + // If user provided function creator returns true, then the track is considered as consumed and its contributing + // simpler tracks will not be provided to the creator. If it returns false, the creator will be called also + // with this simpler contrubutors. + // The creator function is called with track kinematics, track GlobalTrackID and track timing information as 2 floats + // which depends on the track time: + // 1) For track types containing TimeStampWithError ts it is ts.getTimeStamp(), getTimeStampError() + // 2) For tracks with asymmetric time uncertainty, e.g. TPC: as mean time of t0-errBwd,t+errFwd and 0.5(errBwd+errFwd), all in TPC time bins + // 3) For tracks whose timing is provided as RO frame: as time in \mus for RO frame start since the start of TF, half-duration of RO window and 0. + + auto start_time = std::chrono::high_resolution_clock::now(); + constexpr float PS2MUS = 1e-6; + std::array, GTrackID::NSources> usedData; + auto flagUsed2 = [&usedData](int idx, int src) { + if (!usedData[src].empty()) { + usedData[src][idx] = 1; + } + }; + auto flagUsed = [&usedData, &flagUsed2](const GTrackID gidx) { flagUsed2(gidx.getIndex(), gidx.getSource()); }; + auto isUsed2 = [&usedData](int idx, int src) { return (!usedData[src].empty()) && (usedData[src][idx] != 0); }; + auto isUsed = [&usedData, isUsed2](const GTrackID gidx) { return isUsed2(gidx.getIndex(), gidx.getSource()); }; + + // create only for those data types which are used + const auto& tracksITS = getITSTracks(); + const auto& tracksTPC = getTPCTracks(); + const auto& tracksTPCITS = getTPCITSTracks(); + const auto& tracksTPCTOF = getTPCTOFTracks(); + const auto& matchesTPCTOF = getTPCTOFMatches(); + + usedData[GTrackID::ITS].resize(tracksITS.size()); // to flag used ITS tracks + usedData[GTrackID::TPC].resize(tracksTPC.size()); // to flag used TPC tracks + usedData[GTrackID::ITSTPC].resize(tracksTPCITS.size()); // to flag used ITSTPC tracks + usedData[GTrackID::TOF].resize(getTOFMatches().size()); // to flag used ITSTPC-TOF matches + + // ITS-TPC-TOF matches, may refer to ITS-TPC (TODO: something else?) tracks + { + auto matches = getTOFMatches(); // thes are just MatchInfoTOF objects, pointing on ITS-TPC match and TOF cl. + auto tofClusters = getTOFClusters(); + if (matches.size() && (!tofClusters.size() || !tracksTPCITS.size())) { + throw std::runtime_error(fmt::format("Global-TOF tracks ({}) require ITS-TPC tracks ({}) and TOF clusters ({})", + matches.size(), tracksTPCITS.size(), tofClusters.size())); + } + for (unsigned i = 0; i < matches.size(); i++) { + const auto& match = matches[i]; + const auto& tofCl = tofClusters[match.getTOFClIndex()]; + float timeTOFMUS = (tofCl.getTime() - match.getLTIntegralOut().getTOF(o2::track::PID::Pion)) * PS2MUS; // tof time in \mus, FIXME: account for time of flight to R TOF + const float timeErr = 0.010f; // assume 10 ns error FIXME + + auto gidx = match.getEvIdxTrack().getIndex(); // this should be corresponding ITS-TPC track + if (creator(tracksPool.get(gidx), {i, GTrackID::ITSTPCTOF}, timeTOFMUS, timeErr)) { + flagUsed2(i, GTrackID::TOF); + flagUsed(gidx); // flag used ITS-TPC tracks + } + } + } + + // ITS-TPC matches, may refer to ITS, TPC (TODO: something else?) tracks + { + for (unsigned i = 0; i < tracksTPCITS.size(); i++) { + const auto& matchTr = tracksTPCITS[i]; + if (isUsed2(i, GTrackID::ITSTPC)) { + flagUsed(matchTr.getRefITS()); // flag used ITS tracks + flagUsed(matchTr.getRefTPC()); // flag used TPC tracks + continue; + } + if (creator(matchTr, {i, GTrackID::ITSTPC}, matchTr.getTimeMUS().getTimeStamp(), matchTr.getTimeMUS().getTimeStampError())) { + flagUsed2(i, GTrackID::ITSTPC); + flagUsed(matchTr.getRefITS()); // flag used ITS tracks + flagUsed(matchTr.getRefTPC()); // flag used TPC tracks + } + } + } + + // TPC-TOF matches, may refer to TPC (TODO: something else?) tracks + { + if (matchesTPCTOF.size() && !tracksTPCTOF.size()) { + throw std::runtime_error(fmt::format("TPC-TOF matched tracks ({}) require TPCTOF matches ({}) and TPCTOF tracks ({})", + matchesTPCTOF.size(), tracksTPCTOF.size())); + } + for (unsigned i = 0; i < matchesTPCTOF.size(); i++) { + const auto& match = matchesTPCTOF[i]; + const auto& gidx = match.getEvIdxTrack().getIndex(); // TPC (or other? but w/o ITS) track global idx (FIXME: TOF has to git rid of EvIndex stuff) + if (isUsed(gidx)) { // is TPC track already used + continue; + } + const auto& trc = tracksTPCTOF[i]; + if (creator(trc, {i, GTrackID::TPCTOF}, trc.getTimeMUS().getTimeStamp(), trc.getTimeMUS().getTimeStampError())) { + flagUsed(gidx); // flag used TPC tracks + } + } + } + + // TPC only tracks + { + for (unsigned i = 0; i < tracksTPC.size(); i++) { + if (isUsed2(i, GTrackID::TPC)) { // skip used tracks + continue; + } + const auto& trc = tracksTPC[i]; + if (creator(trc, {i, GTrackID::TPC}, trc.getTime0() + 0.5 * (trc.getDeltaTFwd() - trc.getDeltaTBwd()), 0.5 * (trc.getDeltaTFwd() + trc.getDeltaTBwd()))) { + flagUsed2(i, GTrackID::TPC); // flag used TPC tracks + } + } + } + + // ITS only tracks + { + const auto& rofrs = getITSTracksROFRecords(); + for (unsigned irof = 0; irof < rofrs.size(); irof++) { + const auto& rofRec = rofrs[irof]; + float t0 = rofRec.getBCData().differenceInBC(startIR) * o2::constants::lhc::LHCBunchSpacingNS * 1e-3; + int trlim = rofRec.getFirstEntry() + rofRec.getNEntries(); + for (int it = rofRec.getFirstEntry(); it < trlim; it++) { + if (isUsed2(it, GTrackID::ITS)) { // skip used tracks + continue; + } + GTrackID gidITS(it, GTrackID::ITS); + const auto& trc = getITSTrack(gidITS); + if (creator(trc, gidITS, t0, 0.5)) { + flagUsed2(it, GTrackID::ITS); + } + } + } + } + auto current_time = std::chrono::high_resolution_clock::now(); + LOG(INFO) << "RecoContainer::createTracks took " << std::chrono::duration_cast(current_time - start_time).count() * 1e-6 << " CPU s."; +} diff --git a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx index 42dade5038310..b935cab4d2ecc 100644 --- a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx +++ b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx @@ -14,22 +14,7 @@ #include #include -#include "Framework/ProcessingContext.h" -#include "Framework/InputSpec.h" -#include "DetectorsCommonDataFormats/DetID.h" -#include "DataFormatsTPC/WorkflowHelper.h" -#include "DataFormatsTRD/RecoInputContainer.h" -#include "DataFormatsGlobalTracking/RecoContainer.h" -#include "DataFormatsITSMFT/CompCluster.h" -#include "DataFormatsITS/TrackITS.h" -#include "DataFormatsTPC/TrackTPC.h" -#include "DataFormatsTOF/Cluster.h" -#include "DataFormatsITSMFT/ROFRecord.h" -#include "DataFormatsFT0/RecPoints.h" -#include "DataFormatsTRD/TrackTRD.h" -#include "ReconstructionDataFormats/TrackTPCITS.h" -#include "ReconstructionDataFormats/TrackTPCTOF.h" -#include "ReconstructionDataFormats/MatchInfoTOF.h" +#include "DataFormatsGlobalTracking/RecoContainerCreateTracksVariadic.h" using namespace o2::globaltracking; using namespace o2::framework; @@ -456,137 +441,14 @@ void RecoContainer::fillTrackMCLabels(const gsl::span gids, std::vecto } } -//________________________________________________________ -void RecoContainer::createTracks(std::function const& creator) const -{ - // We go from most complete tracks to least complete ones, taking into account that some track times - // do not bear their own kinematics but just constrain the time - // As we get more track types functional, this method should be completed - // If user provided function creator returns true, then the track is considered as consumed and its contributing - // simpler tracks will not be provided to the creator. If it returns false, the creator will be called also - // with this simpler contrubutors. - // The creator function is called with track kinematics, track GlobalTrackID and track timing information as 2 floats - // which depends on the track time: - // 1) For track types containing TimeStampWithError ts it is ts.getTimeStamp(), getTimeStampError() - // 2) For tracks with asymmetric time uncertainty, e.g. TPC: as mean time of t0-errBwd,t+errFwd and 0.5(errBwd+errFwd), all in TPC time bins - // 3) For tracks whose timing is provided as RO frame: as time in \mus for RO frame start since the start of TF, half-duration of RO window and 0. - - auto start_time = std::chrono::high_resolution_clock::now(); - constexpr float PS2MUS = 1e-6; - std::array, GTrackID::NSources> usedData; - auto flagUsed2 = [&usedData](int idx, int src) { - if (!usedData[src].empty()) { - usedData[src][idx] = 1; - } - }; - auto flagUsed = [&usedData, &flagUsed2](const GTrackID gidx) { flagUsed2(gidx.getIndex(), gidx.getSource()); }; - auto isUsed2 = [&usedData](int idx, int src) { return (!usedData[src].empty()) && (usedData[src][idx] != 0); }; - auto isUsed = [&usedData, isUsed2](const GTrackID gidx) { return isUsed2(gidx.getIndex(), gidx.getSource()); }; - - // create only for those data types which are used - const auto& tracksITS = getITSTracks(); - const auto& tracksTPC = getTPCTracks(); - const auto& tracksTPCITS = getTPCITSTracks(); - const auto& tracksTPCTOF = getTPCTOFTracks(); - const auto& matchesTPCTOF = getTPCTOFMatches(); - - usedData[GTrackID::ITS].resize(tracksITS.size()); // to flag used ITS tracks - usedData[GTrackID::TPC].resize(tracksTPC.size()); // to flag used TPC tracks - usedData[GTrackID::ITSTPC].resize(tracksTPCITS.size()); // to flag used ITSTPC tracks - usedData[GTrackID::TOF].resize(getTOFMatches().size()); // to flag used ITSTPC-TOF matches - - // ITS-TPC-TOF matches, may refer to ITS-TPC (TODO: something else?) tracks - { - auto matches = getTOFMatches(); // thes are just MatchInfoTOF objects, pointing on ITS-TPC match and TOF cl. - auto tofClusters = getTOFClusters(); - if (matches.size() && (!tofClusters.size() || !tracksTPCITS.size())) { - throw std::runtime_error(fmt::format("Global-TOF tracks ({}) require ITS-TPC tracks ({}) and TOF clusters ({})", - matches.size(), tracksTPCITS.size(), tofClusters.size())); - } - for (unsigned i = 0; i < matches.size(); i++) { - const auto& match = matches[i]; - const auto& tofCl = tofClusters[match.getTOFClIndex()]; - float timeTOFMUS = (tofCl.getTime() - match.getLTIntegralOut().getTOF(o2::track::PID::Pion)) * PS2MUS; // tof time in \mus, FIXME: account for time of flight to R TOF - const float timeErr = 0.010f; // assume 10 ns error FIXME - - auto gidx = match.getEvIdxTrack().getIndex(); // this should be corresponding ITS-TPC track - if (creator(tracksPool.get(gidx), timeTOFMUS, timeErr, {i, GTrackID::ITSTPCTOF})) { - flagUsed2(i, GTrackID::TOF); - flagUsed(gidx); // flag used ITS-TPC tracks - } - } - } - - // ITS-TPC matches, may refer to ITS, TPC (TODO: something else?) tracks - { - for (unsigned i = 0; i < tracksTPCITS.size(); i++) { - const auto& matchTr = tracksTPCITS[i]; - if (isUsed2(i, GTrackID::ITSTPC)) { - flagUsed(matchTr.getRefITS()); // flag used ITS tracks - flagUsed(matchTr.getRefTPC()); // flag used TPC tracks - continue; - } - if (creator(matchTr, matchTr.getTimeMUS().getTimeStamp(), matchTr.getTimeMUS().getTimeStampError(), {i, GTrackID::ITSTPC})) { - flagUsed2(i, GTrackID::ITSTPC); - flagUsed(matchTr.getRefITS()); // flag used ITS tracks - flagUsed(matchTr.getRefTPC()); // flag used TPC tracks - } - } - } - - // TPC-TOF matches, may refer to TPC (TODO: something else?) tracks - { - if (matchesTPCTOF.size() && !tracksTPCTOF.size()) { - throw std::runtime_error(fmt::format("TPC-TOF matched tracks ({}) require TPCTOF matches ({}) and TPCTOF tracks ({})", - matchesTPCTOF.size(), tracksTPCTOF.size())); - } - for (unsigned i = 0; i < matchesTPCTOF.size(); i++) { - const auto& match = matchesTPCTOF[i]; - const auto& gidx = match.getEvIdxTrack().getIndex(); // TPC (or other? but w/o ITS) track global idx (FIXME: TOF has to git rid of EvIndex stuff) - if (isUsed(gidx)) { // is TPC track already used - continue; - } - const auto& trc = tracksTPCTOF[i]; - if (creator(trc, trc.getTimeMUS().getTimeStamp(), trc.getTimeMUS().getTimeStampError(), {i, GTrackID::TPCTOF})) { - flagUsed(gidx); // flag used TPC tracks - } - } - } - - // TPC only tracks - { - for (unsigned i = 0; i < tracksTPC.size(); i++) { - if (isUsed2(i, GTrackID::TPC)) { // skip used tracks - continue; - } - const auto& trc = tracksTPC[i]; - if (creator(trc, trc.getTime0() + 0.5 * (trc.getDeltaTFwd() - trc.getDeltaTBwd()), 0.5 * (trc.getDeltaTFwd() + trc.getDeltaTBwd()), {i, GTrackID::TPC})) { - flagUsed2(i, GTrackID::TPC); // flag used TPC tracks - } - } - } - - // ITS only tracks - { - const auto& rofrs = getITSTracksROFRecords(); - for (unsigned irof = 0; irof < rofrs.size(); irof++) { - const auto& rofRec = rofrs[irof]; - float t0 = rofRec.getBCData().differenceInBC(startIR) * o2::constants::lhc::LHCBunchSpacingNS * 1e-3; - int trlim = rofRec.getFirstEntry() + rofRec.getNEntries(); - for (int it = rofRec.getFirstEntry(); it < trlim; it++) { - if (isUsed2(it, GTrackID::ITS)) { // skip used tracks - continue; - } - GTrackID gidITS(it, GTrackID::ITS); - const auto& trc = getITSTrack(gidITS); - if (creator(trc, t0, 0.5, gidITS)) { - flagUsed2(it, GTrackID::ITS); - } - } - } - } - auto current_time = std::chrono::high_resolution_clock::now(); - LOG(INFO) << "RecoContainer::createTracks took " << std::chrono::duration_cast(current_time - start_time).count() * 1e-6 << " CPU s."; +void o2::globaltracking::RecoContainer::createTracks(std::function const& creator) const +{ + createTracksVariadic([&creator](const o2::track::TrackParCov& _tr, GTrackID _origID, float t0, float terr) { return creator(_tr, _origID); }); +} + +void o2::globaltracking::RecoContainer::createTracksWithMatchingTimeInfo(std::function const& creator) const +{ + createTracksVariadic([&creator](const o2::track::TrackParCov& _tr, GTrackID _origID, float t0, float terr) { return creator(_tr, _origID, t0, terr); }); } // get contributors from single detectors diff --git a/Detectors/GlobalTracking/src/MatchCosmics.cxx b/Detectors/GlobalTracking/src/MatchCosmics.cxx index 409686c8ea812..9a6ff6d1d5f07 100644 --- a/Detectors/GlobalTracking/src/MatchCosmics.cxx +++ b/Detectors/GlobalTracking/src/MatchCosmics.cxx @@ -483,8 +483,8 @@ void MatchCosmics::createSeeds(const o2::globaltracking::RecoContainer& data) mSeeds.clear(); - std::function creator = - [this](const o2::track::TrackParCov& _tr, float t0, float terr, GTrackID _origID) { + auto creator = + [this](const o2::track::TrackParCov& _tr, GTrackID _origID, float t0, float terr) { if (std::abs(_tr.getQ2Pt()) > this->mQ2PtCutoff) { return true; } @@ -502,7 +502,7 @@ void MatchCosmics::createSeeds(const o2::globaltracking::RecoContainer& data) return true; }; - data.createTracks(creator); + data.createTracksWithMatchingTimeInfo(creator); LOG(INFO) << "collected " << mSeeds.size() << " seeds"; } diff --git a/Detectors/GlobalTracking/src/MatchTPCITS.cxx b/Detectors/GlobalTracking/src/MatchTPCITS.cxx index fc7ae1cc009b5..3934f284d1b48 100644 --- a/Detectors/GlobalTracking/src/MatchTPCITS.cxx +++ b/Detectors/GlobalTracking/src/MatchTPCITS.cxx @@ -600,7 +600,7 @@ bool MatchTPCITS::prepareTPCData() mTPCTrkLabels = inp.getTPCTracksMCLabels(); } - std::function creator = [this](const o2::track::TrackParCov& _tr, float t0, float terr, GTrackID _origID) { + auto creator = [this](const o2::track::TrackParCov& _tr, GTrackID _origID, float t0, float terr) { auto srcID = _origID.getSource(); if (srcID == GTrackID::ITS) { // we don't need ITS here return true; // we don't need TPC tracks @@ -628,7 +628,7 @@ bool MatchTPCITS::prepareTPCData() return true; }; - inp.createTracks(creator); + inp.createTracksWithMatchingTimeInfo(creator); float maxTime = 0; int nITSROFs = mITSROFTimes.size(); diff --git a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx index 186296cdc2cb2..d3de4cb6a7467 100644 --- a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx @@ -110,8 +110,8 @@ void PrimaryVertexingSpec::run(ProcessingContext& pc) auto halfROFITS = 0.5 * mITSROFrameLengthMUS; auto hw2ErrITS = 2.f / std::sqrt(12.f) * mITSROFrameLengthMUS; // conversion from half-width to error for ITS - std::function creator = - [maxTrackTimeError, hw2ErrITS, halfROFITS, &tracks, &gids](const o2::track::TrackParCov& _tr, float t0, float terr, GTrackID _origID) { + auto creator = + [maxTrackTimeError, hw2ErrITS, halfROFITS, &tracks, &gids](const o2::track::TrackParCov& _tr, GTrackID _origID, float t0, float terr) { if (!_origID.includesDet(DetID::ITS)) { return true; // just in case this selection was not done on RecoContainer filling level } @@ -127,7 +127,7 @@ void PrimaryVertexingSpec::run(ProcessingContext& pc) return true; }; - recoData.createTracks(creator); // create track sample considered for vertexing + recoData.createTracksWithMatchingTimeInfo(creator); // create track sample considered for vertexing if (mUseMC) { recoData.fillTrackMCLabels(gids, tracksMCInfo); } diff --git a/Detectors/Vertexing/src/VertexTrackMatcher.cxx b/Detectors/Vertexing/src/VertexTrackMatcher.cxx index a4bad42afac8c..aa29cd8e2c58e 100644 --- a/Detectors/Vertexing/src/VertexTrackMatcher.cxx +++ b/Detectors/Vertexing/src/VertexTrackMatcher.cxx @@ -151,8 +151,8 @@ void VertexTrackMatcher::extractTracks(const o2::globaltracking::RecoContainer& mTBrackets.clear(); - std::function creator = - [this, &vcont](const o2::track::TrackParCov& _tr, float t0, float terr, GIndex _origID) { + auto creator = + [this, &vcont](const o2::track::TrackParCov& _tr, GIndex _origID, float t0, float terr) { if (vcont.find(_origID) != vcont.end()) { // track is contributor to vertex, already accounted return true; } @@ -169,7 +169,7 @@ void VertexTrackMatcher::extractTracks(const o2::globaltracking::RecoContainer& return true; }; - data.createTracks(creator); + data.createTracksWithMatchingTimeInfo(creator); // sort in increasing min.time std::sort(mTBrackets.begin(), mTBrackets.end(), [](const TrackTBracket& a, const TrackTBracket& b) { return a.tBracket.getMin() < b.tBracket.getMin(); }); From d2706efa98dbac16c97328f4400fb1978f78c0d3 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 7 May 2021 21:01:06 +0200 Subject: [PATCH 445/770] Use createTracks to parse tracks in input for GPU workflow --- GPU/GPUTracking/DataTypes/GPUDataTypes.h | 18 ++++++ GPU/Workflow/helper/src/GPUWorkflowHelper.cxx | 60 ++++++++++++++----- 2 files changed, 63 insertions(+), 15 deletions(-) diff --git a/GPU/GPUTracking/DataTypes/GPUDataTypes.h b/GPU/GPUTracking/DataTypes/GPUDataTypes.h index d42e727e4724d..22e09401d7504 100644 --- a/GPU/GPUTracking/DataTypes/GPUDataTypes.h +++ b/GPU/GPUTracking/DataTypes/GPUDataTypes.h @@ -55,6 +55,16 @@ template class PropagatorImpl; class MatLayerCylSet; } // namespace base +namespace track +{ +#ifdef GPUCA_NOCOMPAT +template +class TrackParametrizationWithError; +using TrackParCov = TrackParametrizationWithError; +#else +class TrackParCov; +#endif +} // namespace track namespace trd { class GeometryFlat; @@ -265,6 +275,14 @@ struct GPUTrackingInOutPointers { const o2::MCCompLabel* outputTracksTPCO2MC = nullptr; const o2::tpc::CompressedClustersFlat* tpcCompressedClusters = nullptr; + // TPC links + int* tpcLinkITS = nullptr; + int* tpcLinkTRD = nullptr; + int* tpcLinkTOF = nullptr; + const o2::track::TrackParCov** globalTracks = nullptr; + float* globalTrackTimes = nullptr; + unsigned int nGlobalTracks = 0; + // TRD const GPUTRDTrackletWord* trdTracklets = nullptr; const GPUTRDSpacePoint* trdSpacePoints = nullptr; diff --git a/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx b/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx index 084215dcf3c59..cad4e48fcf019 100644 --- a/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx +++ b/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx @@ -13,11 +13,17 @@ #include "DataFormatsTRD/TrackTRD.h" #include "ITStracking/IOUtils.h" #include "DataFormatsTPC/WorkflowHelper.h" +#include "DataFormatsGlobalTracking/RecoContainerCreateTracksVariadic.h" +#include + using namespace o2::globaltracking; using namespace o2::gpu; struct GPUWorkflowHelper::tmpDataContainer { std::vector> ITSClustersArray; + std::vector tpcLinkITS, tpcLinkTRD, tpcLinkTOF; + std::vector globalTracks; + std::vector globalTrackTimes; }; std::shared_ptr GPUWorkflowHelper::fillIOPtr(GPUTrackingInOutPointers& ioPtr, const o2::globaltracking::RecoContainer& recoCont, bool useMC, const GPUCalibObjectsConst* calib, o2::dataformats::GlobalTrackID::mask_t maskCl, o2::dataformats::GlobalTrackID::mask_t maskTrk, o2::dataformats::GlobalTrackID::mask_t maskMatch) @@ -94,6 +100,22 @@ std::shared_ptr GPUWorkflowHelper::fi } } + if (maskCl[GID::TRD]) { + // o2::trd::getRecoInputContainer(pc, &ioPtr, &recoCont, useMC); // TODO: use this helper here + } + + if (maskTrk[GID::ITSTPCTRD] && ioPtr.nTRDTracksITSTPCTRD == 0) { + const auto& trdTracks = recoCont.getITSTPCTRDTracks(); + ioPtr.nTRDTracksITSTPCTRD = trdTracks.size(); + ioPtr.trdTracksITSTPCTRD = trdTracks.data(); + } + + if (maskTrk[GID::TPCTRD] && ioPtr.nTRDTracksTPCTRD == 0) { + const auto& trdTracks = recoCont.getTPCTRDTracks(); + ioPtr.nTRDTracksTPCTRD = trdTracks.size(); + ioPtr.trdTracksTPCTRD = trdTracks.data(); + } + if (maskCl[GID::TPC] && ioPtr.clustersNative == nullptr) { ioPtr.clustersNative = &recoCont.getTPCClusters(); } @@ -109,23 +131,31 @@ std::shared_ptr GPUWorkflowHelper::fi const auto& tpcTracksMC = recoCont.getTPCTracksMCLabels(); ioPtr.outputTracksTPCO2MC = tpcTracksMC.data(); } + if (ioPtr.nItsTracks && ioPtr.nTracksTPCITSO2) { + retVal->tpcLinkITS.resize(ioPtr.nOutputTracksTPCO2, -1); + ioPtr.tpcLinkITS = retVal->tpcLinkITS.data(); + } + if (ioPtr.nTOFClusters && (ioPtr.nTOFMatches || ioPtr.nTPCTOFMatches)) { + retVal->tpcLinkTRD.resize(ioPtr.nOutputTracksTPCO2, -1); + ioPtr.tpcLinkTRD = retVal->tpcLinkTRD.data(); + } + if (ioPtr.nTRDTracksITSTPCTRD || ioPtr.nTRDTracksTPCTRD) { + retVal->tpcLinkTOF.resize(ioPtr.nOutputTracksTPCO2, -1); + ioPtr.tpcLinkTOF = retVal->tpcLinkTOF.data(); + } } - if (maskCl[GID::TRD]) { - // o2::trd::getRecoInputContainer(pc, &ioPtr, &recoCont, useMC); // TODO: use this helper here - } - - if (maskTrk[GID::ITSTPCTRD] && ioPtr.nTRDTracksITSTPCTRD == 0) { - const auto& trdTracks = recoCont.getITSTPCTRDTracks(); - ioPtr.nTRDTracksITSTPCTRD = trdTracks.size(); - ioPtr.trdTracksITSTPCTRD = trdTracks.data(); - } - - if (maskTrk[GID::TPCTRD] && ioPtr.nTRDTracksTPCTRD == 0) { - const auto& trdTracks = recoCont.getTPCTRDTracks(); - ioPtr.nTRDTracksTPCTRD = trdTracks.size(); - ioPtr.trdTracksTPCTRD = trdTracks.data(); - } + auto creator = [&recoCont, &retVal](auto& trk, GID gid, float time, float) { + if constexpr (std::is_same_v, o2::tpc::TrackTPC>) { + time = trk.getTime0(); + } + retVal->globalTracks.emplace_back(&trk); + retVal->globalTrackTimes.emplace_back(time); + return true; + }; + recoCont.createTracksVariadic(creator); + ioPtr.globalTracks = retVal->globalTracks.data(); + ioPtr.globalTrackTimes = retVal->globalTrackTimes.data(); return std::move(retVal); } From e7ff8966de8a835459bb32ca24eb5f01df3570d4 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sat, 8 May 2021 01:12:59 +0200 Subject: [PATCH 446/770] TRD Bugfix: TPC track id is overwritten during loading --- Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx index aa3c68c884a1d..7466a28076a1a 100644 --- a/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx +++ b/Detectors/TRD/workflow/src/TRDGlobalTrackingSpec.cxx @@ -124,7 +124,7 @@ void TRDGlobalTracking::run(ProcessingContext& pc) for (int iTrk = 0; iTrk < mChainTracking->mIOPtrs.nTracksTPCITSO2; ++iTrk) { const auto& trkITSTPC = mChainTracking->mIOPtrs.tracksTPCITSO2[iTrk]; GPUTRDTrack trkLoad(trkITSTPC, mTPCVdrift); - if (mTracker->LoadTrack(trkLoad)) { + if (mTracker->LoadTrack(trkLoad, -1, nullptr, -1, iTrk)) { continue; } loadedTPCtracks.push_back(trkITSTPC.getRefTPC()); @@ -139,7 +139,7 @@ void TRDGlobalTracking::run(ProcessingContext& pc) } const auto& trkTpc = mChainTracking->mIOPtrs.outputTracksTPCO2[iTrk]; GPUTRDTrack trkLoad(trkTpc, mTPCTBinMUS, mTPCVdrift, iTrk); - if (mTracker->LoadTrack(trkLoad)) { + if (mTracker->LoadTrack(trkLoad, -1, nullptr, -1, iTrk)) { continue; } ++nTracksLoadedTPC; From 3534e14fd959e6c18856c24225b2a22084c864a9 Mon Sep 17 00:00:00 2001 From: shahoian Date: Fri, 7 May 2021 14:45:36 +0200 Subject: [PATCH 447/770] Multithread version of populateCCDB used at MW2 --- Detectors/Calibration/testMacros/populateCCDB.C | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Detectors/Calibration/testMacros/populateCCDB.C b/Detectors/Calibration/testMacros/populateCCDB.C index 589baeffb790c..d38fedf3a2397 100644 --- a/Detectors/Calibration/testMacros/populateCCDB.C +++ b/Detectors/Calibration/testMacros/populateCCDB.C @@ -7,7 +7,9 @@ #include #include #include +#include #include +#include #include "Framework/Logger.h" #include "CCDB/CcdbApi.h" @@ -48,7 +50,14 @@ void populateCCDB(const std::string& fname = "cdbSizeV0.txt", const std::string& if (elapsedSeconds.count() > o.validity || !o.count) { std::cout << "Storing entry: " << o.path << " copy " << o.count << " after " << (o.count ? elapsedSeconds.count() : 0.) << "s\n"; - pushObject(api, o); + + auto uploadStart = std::chrono::high_resolution_clock::now(); + std::thread th(pushObject, std::ref(api), std::cref(o)); + th.detach(); + //pushObject(api, o); + auto uploadEnd = std::chrono::high_resolution_clock::now(); + DurSec uploadTime = uploadEnd - uploadStart; + LOG(INFO) << "Took " << uploadTime.count() << " to load " << o.sz << " bytes object"; o.count++; o.lastUpdate = timeLoopStart; if (minTLeft < 0.9 * o.validity) { From 552b4106d53cc5f235e7bc09dabd7575ae14f971 Mon Sep 17 00:00:00 2001 From: Roman Lietava Date: Sat, 8 May 2021 12:58:09 +0200 Subject: [PATCH 448/770] Ctp configuration mostly (#6040) * CTP digitizer bug fix * CTP configuration added * clang format * naming and comment conventions applied * clang format * fixes suggested by Ruben * clang format * Digitizer code simplification * clang format * uint->uint32_t; braces added to for loops * clang format --- DataFormats/Detectors/CTP/CMakeLists.txt | 7 +- .../include/DataFormatsCTP/Configuration.h | 97 +++++++++++++++++++ .../CTP/include/DataFormatsCTP/Digits.h | 33 ++++--- .../Detectors/CTP/src/Configuration.cxx | 97 +++++++++++++++++++ .../Detectors/CTP/src/DataFormatsCTPLinkDef.h | 13 +++ DataFormats/Detectors/CTP/src/Digits.cxx | 9 +- .../include/CTPSimulation/Digitizer.h | 4 + Detectors/CTP/simulation/src/Digitizer.cxx | 28 +++--- .../include/CTPWorkflow/CTPDigitWriterSpec.h | 3 + .../CTP/workflow/src/CTPDigitWriterSpec.cxx | 3 + GPU/Workflow/src/GPUWorkflowSpec.cxx | 3 +- .../src/CTPDigitizerSpec.cxx | 6 +- 12 files changed, 261 insertions(+), 42 deletions(-) create mode 100644 DataFormats/Detectors/CTP/include/DataFormatsCTP/Configuration.h create mode 100644 DataFormats/Detectors/CTP/src/Configuration.cxx diff --git a/DataFormats/Detectors/CTP/CMakeLists.txt b/DataFormats/Detectors/CTP/CMakeLists.txt index 5fb16dad4f15f..3fd7f106a9386 100644 --- a/DataFormats/Detectors/CTP/CMakeLists.txt +++ b/DataFormats/Detectors/CTP/CMakeLists.txt @@ -9,11 +9,14 @@ # submit itself to any jurisdiction. o2_add_library(DataFormatsCTP - SOURCES src/Digits.cxx + SOURCES src/Digits.cxx + SOURCES src/Configuration.cxx PUBLIC_LINK_LIBRARIES O2::CommonDataFormat O2::Headers O2::SimulationDataFormat + O2::CommonConstants O2::DataFormatsFT0) o2_target_root_dictionary(DataFormatsCTP - HEADERS include/DataFormatsCTP/Digits.h) + HEADERS include/DataFormatsCTP/Digits.h + include/DataFormatsCTP/Configuration.h) diff --git a/DataFormats/Detectors/CTP/include/DataFormatsCTP/Configuration.h b/DataFormats/Detectors/CTP/include/DataFormatsCTP/Configuration.h new file mode 100644 index 0000000000000..6cb7da279c9fe --- /dev/null +++ b/DataFormats/Detectors/CTP/include/DataFormatsCTP/Configuration.h @@ -0,0 +1,97 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file Configuration.h +/// \brief definition of CTPConfiguration and related CTP structures +/// \author Roman Lietava + +#ifndef _CTP_CONFIGURATION_H_ +#define _CTP_CONFIGURATION_H_ +#include "DetectorsCommonDataFormats/DetID.h" +#include "CommonConstants/LHCConstants.h" +#include +#include +#include +namespace o2 +{ +namespace ctp +{ +struct BCMask { + BCMask() = default; + std::string name; + std::bitset BCmask; + void printStream(std::ostream& strem) const; + ClassDefNV(BCMask, 1); +}; +struct CTPInput { + CTPInput() = default; + std::string name; + o2::detectors::DetID::ID detID; + std::uint64_t inputMask; + void printStream(std::ostream& strem) const; + ClassDefNV(CTPInput, 1); +}; +struct CTPDescriptor { + CTPDescriptor() = default; + std::string name; + std::uint64_t inputsMask; + std::vector inputsNames; + void printStream(std::ostream& strem) const; + ClassDefNV(CTPDescriptor, 1) +}; +/// The main part is Local Trigger Generator (LTG) +struct CTPDetector { + CTPDetector() = default; + o2::detectors::DetID::ID detID; + uint32_t HBaccepted; /// Number of HB frames in TF to be accepted + void printStream(std::ostream& strem) const; +}; +struct CTPCluster { + CTPCluster() = default; + std::string name; + uint32_t detectorsMask; + std::vector detectorsNames; + void printStream(std::ostream& strem) const; + ClassDefNV(CTPCluster, 1) +}; +struct CTPClass { + CTPClass() = default; + std::string name; + std::uint64_t classMask; + CTPDescriptor* descriptor; + CTPCluster* cluster; + void printStream(std::ostream& strem) const; + ClassDefNV(CTPClass, 1); +}; +class CTPConfiguration +{ + public: + CTPConfiguration() = default; + void addBCMask(const BCMask& bcmask); + void addCTPInput(const CTPInput& input); + void addCTPDescriptor(const CTPDescriptor& descriptor); + void addCTPDetector(const CTPDetector& detector); + void addCTPCluster(const CTPCluster& cluster); + void addCTPClass(const CTPClass& ctpclass); + void printStream(std::ostream& stream) const; + + private: + std::string mName; + std::vector mBCMasks; + std::vector mInputs; + std::vector mDescriptors; + std::vector mDetectors; + std::vector mClusters; + std::vector mCTPClasses; + ClassDefNV(CTPConfiguration, 1); +}; +} // namespace ctp +} // namespace o2 +#endif //_CTP_CONFIGURATION_H_ diff --git a/DataFormats/Detectors/CTP/include/DataFormatsCTP/Digits.h b/DataFormats/Detectors/CTP/include/DataFormatsCTP/Digits.h index 1c2de16b31b92..e8c1d6b6c8670 100644 --- a/DataFormats/Detectors/CTP/include/DataFormatsCTP/Digits.h +++ b/DataFormats/Detectors/CTP/include/DataFormatsCTP/Digits.h @@ -8,6 +8,10 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +/// \file Digits.h +/// \brief definition of CTPDigit, CTPInputDigit +/// \author Roman Lietava + #ifndef _CTP_DIGITS_H_ #define _CTP_DIGITS_H_ #include "DetectorsCommonDataFormats/DetID.h" @@ -20,31 +24,28 @@ namespace o2 { namespace ctp { -static constexpr uint32_t CTP_NINPUTS = 46; -static constexpr uint32_t CTP_NCLASSES = 64; -static constexpr uint32_t CTP_MAXL0PERDET = 5; -// Positions of CTP Detector inputs in CTPInputMask +/// CTP related constants +static constexpr std::uint32_t NumOfHBInTF = 256; +static constexpr std::uint32_t CTP_NINPUTS = 46; /// Max number of CTP inputs for all levels +static constexpr std::uint32_t CTP_NCLASSES = 64; /// Number of classes in hardware +static constexpr std::uint32_t CTP_MAXL0PERDET = 5; /// Max number of LM/L0inputs per detector +/// Positions of CTP Detector inputs in CTPInputMask static constexpr std::pair> CTP_INPUTMASK_FV0(0, 0x1f); static constexpr std::pair> CTP_INPUTMASK_FT0(5, 0x1f); +/// struct CTPDigit { - o2::InteractionRecord mIntRecord; - std::bitset mCTPInputMask; - std::bitset mCTPClassMask; + o2::InteractionRecord intRecord; + std::bitset CTPInputMask; + std::bitset CTPClassMask; CTPDigit() = default; void printStream(std::ostream& stream) const; ClassDefNV(CTPDigit, 1); }; struct CTPInputDigit { - o2::InteractionRecord mIntRecord; - std::bitset mInputsMask; - std::int32_t mDetector; + o2::InteractionRecord intRecord; + std::bitset inputsMask; + o2::detectors::DetID::ID detector; CTPInputDigit() = default; - CTPInputDigit(o2::InteractionRecord IntRecord, std::bitset InputsMask, uint32_t DetID) - { - mIntRecord = IntRecord; - mInputsMask = InputsMask; - mDetector = DetID; - } ClassDefNV(CTPInputDigit, 1) }; } // namespace ctp diff --git a/DataFormats/Detectors/CTP/src/Configuration.cxx b/DataFormats/Detectors/CTP/src/Configuration.cxx new file mode 100644 index 0000000000000..8d40dd1f505d1 --- /dev/null +++ b/DataFormats/Detectors/CTP/src/Configuration.cxx @@ -0,0 +1,97 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file Configuration.cxx +/// \author Roman Lietava + +#include "DataFormatsCTP/Configuration.h" +#include + +using namespace o2::ctp; + +void BCMask::printStream(std::ostream& stream) const +{ + stream << "CTP BC mask:" << name << std::endl; + /// << ":" << BCmask << std::endl; +} +void CTPInput::printStream(std::ostream& stream) const +{ + stream << "CTP Input:" << name << "Detector:" << detID << " Hardware mask:" << inputMask << std::endl; +} +void CTPDescriptor::printStream(std::ostream& stream) const +{ + stream << "CTP Descriptor:" << name << " Inputs:" << inputsMask << std::endl; +} +void CTPDetector::printStream(std::ostream& stream) const +{ + o2::detectors::DetID det(detID); + stream << "CTP Detector:" << det.getName() << " HBaccepted:" << HBaccepted << std::endl; +} +void CTPCluster::printStream(std::ostream& stream) const +{ + stream << "CTP Cluster:" << name << " Inputs:" << detectorsMask << std::endl; +} +void CTPClass::printStream(std::ostream& stream) const +{ + stream << "CTP Class:" << name << " Hardware mask:" << classMask << std::endl; +} +/// CTP configuration +void CTPConfiguration::addBCMask(const BCMask& bcmask) +{ + mBCMasks.push_back(bcmask); +} +void CTPConfiguration::addCTPInput(const CTPInput& input) +{ + mInputs.push_back(input); +} +void CTPConfiguration::addCTPDescriptor(const CTPDescriptor& descriptor) +{ + mDescriptors.push_back(descriptor); +} +void CTPConfiguration::addCTPDetector(const CTPDetector& detector) +{ + mDetectors.push_back(detector); +} +void CTPConfiguration::addCTPCluster(const CTPCluster& cluster) +{ + mClusters.push_back(cluster); +} +void CTPConfiguration::addCTPClass(const CTPClass& ctpclass) +{ + mCTPClasses.push_back(ctpclass); +} +void CTPConfiguration::printStream(std::ostream& stream) const +{ + stream << "Configuration:" << mName << std::endl; + stream << "CTP BC masks:" << std::endl; + for (const auto i : mBCMasks) { + i.printStream(stream); + } + stream << "CTP inputs:" << std::endl; + for (const auto i : mInputs) { + i.printStream(stream); + } + stream << "CTP descriptors:" << std::endl; + for (const auto i : mDescriptors) { + i.printStream(stream); + } + stream << "CTP detectors:" << std::endl; + for (const auto i : mDetectors) { + i.printStream(stream); + } + stream << "CTP clusters:" << std::endl; + for (const auto i : mClusters) { + i.printStream(stream); + } + stream << "CTP classes:" << std::endl; + for (const auto i : mCTPClasses) { + i.printStream(stream); + } +} diff --git a/DataFormats/Detectors/CTP/src/DataFormatsCTPLinkDef.h b/DataFormats/Detectors/CTP/src/DataFormatsCTPLinkDef.h index c155641020168..96c13210669db 100644 --- a/DataFormats/Detectors/CTP/src/DataFormatsCTPLinkDef.h +++ b/DataFormats/Detectors/CTP/src/DataFormatsCTPLinkDef.h @@ -17,4 +17,17 @@ #pragma link C++ class vector < o2::ctp::CTPDigit> + ; #pragma link C++ class o2::ctp::CTPInputDigit + ; #pragma link C++ class vector < o2::ctp::CTPInputDigit> + ; +#pragma link C++ class o2::ctp::BCMask + ; +#pragma link C++ class vector < o2::ctp::BCMask> + ; +#pragma link C++ class o2::ctp::CTPInput + ; +#pragma link C++ class vector < o2::ctp::CTPInput> + ; +#pragma link C++ class o2::ctp::CTPDescriptor + ; +#pragma link C++ class vector < o2::ctp::CTPDescriptor> + ; +#pragma link C++ class o2::ctp::CTPDetector + ; +#pragma link C++ class vector < o2::ctp::CTPDetector> + ; +#pragma link C++ class o2::ctp::CTPCluster + ; +#pragma link C++ class vector < o2::ctp::CTPCluster> + ; +#pragma link C++ class o2::ctp::CTPClass + ; +#pragma link C++ class vector < o2::ctp::CTPClass> + ; +#pragma link C++ class o2::ctp::CTPConfiguration + ; #endif diff --git a/DataFormats/Detectors/CTP/src/Digits.cxx b/DataFormats/Detectors/CTP/src/Digits.cxx index 7b02a59f6312c..b92d765875482 100644 --- a/DataFormats/Detectors/CTP/src/Digits.cxx +++ b/DataFormats/Detectors/CTP/src/Digits.cxx @@ -8,6 +8,9 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +/// \file Digits.cxx +/// \author Roman Lietava + #include "DataFormatsCTP/Digits.h" #include @@ -15,6 +18,6 @@ using namespace o2::ctp; void CTPDigit::printStream(std::ostream& stream) const { - stream << "CTP Digit: BC " << mIntRecord.bc << " orbit " << mIntRecord.orbit << std::endl; - stream << "Input Mask: " << mCTPInputMask << " Class Mask: " << mCTPClassMask << std::endl; -} \ No newline at end of file + stream << "CTP Digit: BC " << intRecord.bc << " orbit " << intRecord.orbit << std::endl; + stream << "Input Mask: " << CTPInputMask << " Class Mask: " << CTPClassMask << std::endl; +} diff --git a/Detectors/CTP/simulation/include/CTPSimulation/Digitizer.h b/Detectors/CTP/simulation/include/CTPSimulation/Digitizer.h index 6bcfb29467da1..3606f470c40c7 100644 --- a/Detectors/CTP/simulation/include/CTPSimulation/Digitizer.h +++ b/Detectors/CTP/simulation/include/CTPSimulation/Digitizer.h @@ -7,6 +7,10 @@ // In applying this license CERN does not waive the privileges and immunities // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. + +/// \file Digitizer.h +/// \author Roman Lietava + #ifndef ALICEO2_CTP_DIGITIZER_H #define ALICEO2_CTP_DIGITIZER_H diff --git a/Detectors/CTP/simulation/src/Digitizer.cxx b/Detectors/CTP/simulation/src/Digitizer.cxx index dceb22d2efb4d..232fc9e1ec308 100644 --- a/Detectors/CTP/simulation/src/Digitizer.cxx +++ b/Detectors/CTP/simulation/src/Digitizer.cxx @@ -8,6 +8,9 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +/// \file Digitizer.cxx +/// \author Roman Lietava + #include "CTPSimulation/Digitizer.h" #include "TRandom.h" #include @@ -22,42 +25,35 @@ std::vector Digitizer::process(const gsl::span { std::map> prerawdata; for (auto const& inp : digits) { - auto res = prerawdata.find(inp.mIntRecord); - if (res == prerawdata.end()) { - std::vector inputs; - inputs.push_back(&inp); - prerawdata[inp.mIntRecord] = inputs; - } else { - res->second.push_back(&inp); - } + prerawdata[inp.intRecord].push_back(&inp); } std::vector vrawdata; for (auto const& coll : prerawdata) { CTPDigit data; - data.mIntRecord = coll.first; + data.intRecord = coll.first; std::bitset inpmaskcoll = 0; for (auto const inp : coll.second) { - switch (inp->mDetector) { + switch (inp->detector) { case o2::detectors::DetID::FT0: { std::bitset inpmask = std::bitset( - (inp->mInputsMask & CTP_INPUTMASK_FT0.second).to_ullong()); + (inp->inputsMask & CTP_INPUTMASK_FT0.second).to_ullong()); inpmaskcoll |= inpmask << CTP_INPUTMASK_FT0.first; break; } case o2::detectors::DetID::FV0: { std::bitset inpmask = std::bitset( - (inp->mInputsMask & CTP_INPUTMASK_FT0.second).to_ullong()); - inpmaskcoll |= inpmask << CTP_INPUTMASK_FT0.first; + (inp->inputsMask & CTP_INPUTMASK_FV0.second).to_ullong()); + inpmaskcoll |= inpmask << CTP_INPUTMASK_FV0.first; break; } default: // Error - LOG(ERROR) << "CTP Digitizer: unknown detector:" << inp->mDetector; + LOG(ERROR) << "CTP Digitizer: unknown detector:" << inp->detector; break; } } - data.mCTPInputMask = inpmaskcoll; - calculateClassMask(coll.second, data.mCTPClassMask); + data.CTPInputMask = inpmaskcoll; + calculateClassMask(coll.second, data.CTPClassMask); vrawdata.emplace_back(data); } return std::move(vrawdata); diff --git a/Detectors/CTP/workflow/include/CTPWorkflow/CTPDigitWriterSpec.h b/Detectors/CTP/workflow/include/CTPWorkflow/CTPDigitWriterSpec.h index bf41c076e385b..7288a9be4608f 100644 --- a/Detectors/CTP/workflow/include/CTPWorkflow/CTPDigitWriterSpec.h +++ b/Detectors/CTP/workflow/include/CTPWorkflow/CTPDigitWriterSpec.h @@ -8,6 +8,9 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +/// \file CTPDigitWriterSpec.h +/// \author Roman Lietava + #ifndef O2_CTPDIGITWRITERSPEC_H #define O2_CTPDIGITWRITERSPEC_H diff --git a/Detectors/CTP/workflow/src/CTPDigitWriterSpec.cxx b/Detectors/CTP/workflow/src/CTPDigitWriterSpec.cxx index 7b956954bfe79..19e963056b4d3 100644 --- a/Detectors/CTP/workflow/src/CTPDigitWriterSpec.cxx +++ b/Detectors/CTP/workflow/src/CTPDigitWriterSpec.cxx @@ -8,6 +8,9 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +/// \file CTPDigitWriterSpec.cxx +/// \author Roman Lietava + #include "CTPWorkflow/CTPDigitWriterSpec.h" namespace o2 diff --git a/GPU/Workflow/src/GPUWorkflowSpec.cxx b/GPU/Workflow/src/GPUWorkflowSpec.cxx index d6db7d904ea21..1daaf32000762 100644 --- a/GPU/Workflow/src/GPUWorkflowSpec.cxx +++ b/GPU/Workflow/src/GPUWorkflowSpec.cxx @@ -566,7 +566,8 @@ DataProcessorSpec getGPURecoWorkflowSpec(gpuworkflow::CompletionPolicyData* poli if (verbosity) { end = std::chrono::high_resolution_clock::now(); std::chrono::duration elapsed_seconds = end - start; - LOG(INFO) << "Allocation time for " << name << " (" << size << " bytes)" << ": " << elapsed_seconds.count() << "s"; + LOG(INFO) << "Allocation time for " << name << " (" << size << " bytes)" + << ": " << elapsed_seconds.count() << "s"; } return (buffer.second = buffer.first->get().data()) + offset; }; diff --git a/Steer/DigitizerWorkflow/src/CTPDigitizerSpec.cxx b/Steer/DigitizerWorkflow/src/CTPDigitizerSpec.cxx index 38e36e91a35ee..9201bf6800cc2 100644 --- a/Steer/DigitizerWorkflow/src/CTPDigitizerSpec.cxx +++ b/Steer/DigitizerWorkflow/src/CTPDigitizerSpec.cxx @@ -55,12 +55,10 @@ class CTPDPLDigitizerTask : public o2::base::BaseDPLDigitizer timer.Start(); LOG(INFO) << "CALLING CTP DIGITIZATION"; for (const auto& inp : ft0inputs) { - CTPInputDigit finpdigit(inp.mIntRecord, inp.mInputs, o2::detectors::DetID::FT0); - finputs.emplace_back(finpdigit); + finputs.emplace_back(CTPInputDigit{inp.mIntRecord, inp.mInputs, o2::detectors::DetID::FT0}); } for (const auto& inp : fv0inputs) { - CTPInputDigit finpdigit(inp.mIntRecord, inp.mInputs, o2::detectors::DetID::FT0); - finputs.emplace_back(finpdigit); + finputs.emplace_back(CTPInputDigit{inp.mIntRecord, inp.mInputs, o2::detectors::DetID::FT0}); } gsl::span ginputs(finputs); auto digits = mDigitizer.process(ginputs); From 4dbd239451f63c190a763c547159f13e080af7c5 Mon Sep 17 00:00:00 2001 From: Sandro Wenzel Date: Sat, 8 May 2021 15:03:45 +0200 Subject: [PATCH 449/770] jobutils: Fix propagation of return codes A recently introduced bug is fix. Unfortunately, $? was not escaped correctly, leading to a premature expansion if is value. --- Utilities/Tools/jobutils.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Utilities/Tools/jobutils.sh b/Utilities/Tools/jobutils.sh index 1791fe5967c50..efa7e0704e4d5 100644 --- a/Utilities/Tools/jobutils.sh +++ b/Utilities/Tools/jobutils.sh @@ -111,7 +111,8 @@ taskwrapper() { # the command might be a complex block: For the timing measurement below # it is better to execute this as a script SCRIPTNAME="${logfile}_tmp.sh" - echo "${command}; echo \"TASK-EXIT-CODE: $?\"" > ${SCRIPTNAME} + echo "${command};" > ${SCRIPTNAME} + echo 'RC=$?; echo "TASK-EXIT-CODE: ${RC}"; exit ${RC}' >> ${SCRIPTNAME} chmod +x ${SCRIPTNAME} # this gives some possibility to customize the wrapper From 88e0858eb5f74b26a1207e2872860ab2eea5db1d Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Sat, 8 May 2021 19:54:59 +0200 Subject: [PATCH 450/770] DPL GUI: add support for multiple axis (#6100) * Several other cleanups --- .../GUISupport/src/FrameworkGUIDebugger.cxx | 128 ++++++++++++------ 1 file changed, 84 insertions(+), 44 deletions(-) diff --git a/Framework/GUISupport/src/FrameworkGUIDebugger.cxx b/Framework/GUISupport/src/FrameworkGUIDebugger.cxx index 2004da0f12db3..776d1f3d9cb89 100644 --- a/Framework/GUISupport/src/FrameworkGUIDebugger.cxx +++ b/Framework/GUISupport/src/FrameworkGUIDebugger.cxx @@ -47,6 +47,7 @@ struct MultiplotData { const void* X = nullptr; MetricType type; const char* legend = nullptr; + int axis = 0; }; } // namespace o2::framework::gui @@ -176,9 +177,11 @@ struct TopologyNodeInfo { }; struct MetricDisplayState { + int axis = 0; // The Axis to use for Y bool visible = false; bool selected = false; std::string legend; + size_t legendHash = -1; }; struct MetricIndex { @@ -235,9 +238,9 @@ void displaySparks( static ImPlotAxisFlags rty_axis = ImPlotAxisFlags_NoTickLabels | ImPlotAxisFlags_NoLabel | ImPlotAxisFlags_NoTickMarks; ImGui::PushID(index.stateIndex); HistoData data; - data.mod = metricsInfo.timestamps[index.metricIndex].size(); - data.size = std::min((size_t)data.mod, metric.filledMetrics); - data.first = metric.pos - data.size; + data.mod = std::min(metric.filledMetrics, metricsInfo.timestamps[index.metricIndex].size()); + data.first = metric.pos - data.mod; + data.size = metric.filledMetrics; data.time = metricsInfo.timestamps[index.metricIndex].data(); data.legend = state.legend.c_str(); @@ -247,6 +250,7 @@ void displaySparks( rty_axis |= ImPlotAxisFlags_LockMin; } if (ImPlot::BeginPlot("##sparks", "time", "value", ImVec2(700, 100), 0, rtx_axis, rty_axis)) { + ImPlot::SetPlotYAxis(state.axis); switch (metric.type) { case MetricType::Int: { data.points = (void*)metricsInfo.intMetrics[metric.storeIdx].data(); @@ -266,7 +270,7 @@ void displaySparks( auto histoData = reinterpret_cast(hData); size_t pos = (histoData->first + static_cast(idx)) % histoData->mod; assert(pos >= 0 && pos < 1024); - return ImPlotPoint(idx, ((uint64_t*)histoData->points)[pos]); + return ImPlotPoint(histoData->time[pos], ((uint64_t*)histoData->points)[pos]); }; ImPlot::PlotLineG("##plot", getter, &data, data.size, 0); } break; @@ -277,7 +281,7 @@ void displaySparks( auto histoData = reinterpret_cast(hData); size_t pos = (histoData->first + static_cast(idx)) % histoData->mod; assert(pos >= 0 && pos < 1024); - return ImPlotPoint(idx, ((float*)histoData->points)[pos]); + return ImPlotPoint(histoData->time[pos], ((float*)histoData->points)[pos]); }; ImPlot::PlotLineG("##plot", getter, &data, data.size, 0); } break; @@ -301,18 +305,19 @@ void displayDeviceMetrics(const char* label, std::vector deviceNames; std::vector userData; MetricType metricType; - size_t metricSize = 0; #ifdef NDEBUG for (size_t si = 0; si < TOTAL_TYPES_OF_METRICS; ++si) { assert(metricsStore.metrics[si].size() == metricStore.specs[si].size()); } #endif - float maxValue = std::numeric_limits::lowest(); - float minValue = 0; + float maxValue[3] = {std::numeric_limits::lowest(), std::numeric_limits::lowest(), std::numeric_limits::lowest()}; + float minValue[3] = {0, 0, 0}; size_t maxDomain = std::numeric_limits::lowest(); size_t minDomain = std::numeric_limits::max(); size_t gmi = 0; + ImPlotFlags axisFlags = 0; + for (size_t si = 0; si < TOTAL_TYPES_OF_METRICS; ++si) { std::vector const& metricsInfos = *metricStore.metrics[si]; auto const& specs = *metricStore.specs[si]; @@ -327,38 +332,36 @@ void displayDeviceMetrics(const char* label, deviceNames.push_back(specs[di].label.c_str()); metricType = metric.type; MultiplotData data; - data.mod = metricsInfos[di].timestamps[mi].size(); + data.size = metric.filledMetrics; + data.mod = std::min(metric.filledMetrics, metricsInfos[di].timestamps[mi].size()); data.first = metric.pos - data.mod; data.X = metricsInfos[di].timestamps[mi].data(); data.legend = state[gmi].legend.c_str(); - minValue = std::min(minValue, metricsInfos[di].min[mi]); - maxValue = std::max(maxValue, metricsInfos[di].max[mi]); + data.type = metric.type; + data.axis = state[gmi].axis; + minValue[data.axis] = std::min(minValue[data.axis], metricsInfos[di].min[mi]); + maxValue[data.axis] = std::max(maxValue[data.axis], metricsInfos[di].max[mi]); minDomain = std::min(minDomain, metricsInfos[di].minDomain[mi]); maxDomain = std::max(maxDomain, metricsInfos[di].maxDomain[mi]); - metricType = metric.type; - data.type = metric.type; + axisFlags |= data.axis == 1 ? ImPlotFlags_YAxis2 : ImPlotFlags_None; + axisFlags |= data.axis == 2 ? ImPlotFlags_YAxis3 : ImPlotFlags_None; switch (metric.type) { case MetricType::Int: { - data.size = metricsInfos[di].intMetrics[metric.storeIdx].size(); data.Y = metricsInfos[di].intMetrics[metric.storeIdx].data(); } break; case MetricType::Uint64: { - data.size = metricsInfos[di].uint64Metrics[metric.storeIdx].size(); data.Y = metricsInfos[di].uint64Metrics[metric.storeIdx].data(); } break; case MetricType::Float: { - data.size = metricsInfos[di].floatMetrics[metric.storeIdx].size(); data.Y = metricsInfos[di].floatMetrics[metric.storeIdx].data(); } break; case MetricType::Unknown: case MetricType::String: { - data.size = metricsInfos[di].stringMetrics[metric.storeIdx].size(); data.Y = nullptr; data.type = MetricType::String; metricType = MetricType::String; } break; } - metricSize = data.size; userData.emplace_back(data); gmi++; @@ -367,7 +370,9 @@ void displayDeviceMetrics(const char* label, } maxDomain = std::max(minDomain + 1024, maxDomain); - maxValue = std::max(minValue + 1.f, maxValue); + for (size_t ai = 0; ai < 3; ++ai) { + maxValue[ai] = std::max(minValue[ai] + 1.f, maxValue[ai]); + } static size_t lastMinRange = minDomain; static size_t lastMaxRange = maxDomain; @@ -379,6 +384,7 @@ void displayDeviceMetrics(const char* label, for (size_t ui = 0; ui < userData.size(); ++ui) { metricsToDisplay.push_back(&(userData[ui])); } + auto getterXY = [](void* hData, int idx) -> ImPlotPoint { auto histoData = reinterpret_cast(hData); size_t pos = (histoData->first + static_cast(idx)) % histoData->mod; @@ -391,21 +397,32 @@ void displayDeviceMetrics(const char* label, } else if (histoData->type == MetricType::Float) { y = static_cast(histoData->Y)[pos]; } - return ImPlotPoint{x, y}; + auto point = ImPlotPoint{x, y}; + return point; }; static bool logScale = false; ImGui::Checkbox("Log scale", &logScale); + ImPlot::SetNextPlotLimitsX(minDomain, maxDomain, ImGuiCond_Once); + ImPlot::SetNextPlotTicksX(minDomain, maxDomain, 5); + auto axisPadding = 0.; + if (displayType == MetricsDisplayStyle::Lines) { + axisPadding = 0.2; + } + + for (size_t ai = 0; ai < 3; ++ai) { + ImPlot::SetNextPlotLimitsY(minValue[ai] - (maxValue[ai] - minValue[ai]) * axisPadding, + maxValue[ai] * (1. + axisPadding), ImGuiCond_Always, ai); + } + switch (displayType) { case MetricsDisplayStyle::Histos: - ImPlot::SetNextPlotLimitsX(minDomain, maxDomain, ImGuiCond_Once); - ImPlot::SetNextPlotLimitsY(minValue, maxValue, ImGuiCond_Always); - ImPlot::SetNextPlotTicksX(minDomain, maxDomain, 5); if (ImPlot::BeginPlot("##Some plot", "time", "value")) { for (size_t pi = 0; pi < metricsToDisplay.size(); ++pi) { ImGui::PushID(pi); + auto data = (const MultiplotData*)metricsToDisplay[pi]; const char* label = ((MultiplotData*)metricsToDisplay[pi])->legend; - ImPlot::PlotBarsG(label, getterXY, metricsToDisplay[pi], metricSize, 1, 0); + ImPlot::PlotBarsG(label, getterXY, metricsToDisplay[pi], data->size, 1, 0); ImGui::PopID(); } ImPlot::EndPlot(); @@ -413,32 +430,29 @@ void displayDeviceMetrics(const char* label, break; case MetricsDisplayStyle::Lines: { - ImPlot::SetNextPlotLimitsX(minDomain, maxDomain, ImGuiCond_Once); - ImPlot::SetNextPlotLimitsY(minValue - (maxValue - minValue) * 0.2, maxValue * (logScale ? 10. : 1.2), ImGuiCond_Always); - ImPlot::SetNextPlotTicksX(minDomain, maxDomain, 5); auto xAxisFlags = ImPlotAxisFlags_None; - auto yAxisFlags = logScale ? ImPlotAxisFlags_LogScale : ImPlotAxisFlags_None; - if (ImPlot::BeginPlot("##Some plot", "time", "value", {-1, -1}, ImPlotFlags_None, xAxisFlags, yAxisFlags)) { + auto yAxisFlags = ImPlotAxisFlags_LockMin; + //ImPlot::FitNextPlotAxes(true, true, true, true); + if (ImPlot::BeginPlot("##Some plot", "time", "value", {-1, -1}, axisFlags, xAxisFlags, yAxisFlags)) { for (size_t pi = 0; pi < metricsToDisplay.size(); ++pi) { ImGui::PushID(pi); - const char* label = ((MultiplotData*)metricsToDisplay[pi])->legend; - ImPlot::PlotLineG(((MultiplotData*)metricsToDisplay[pi])->legend, getterXY, metricsToDisplay[pi], metricSize, 0); + auto data = (const MultiplotData*)metricsToDisplay[pi]; + const char* label = data->legend; + ImPlot::SetPlotYAxis(data->axis); + ImPlot::PlotLineG(data->legend, getterXY, metricsToDisplay[pi], data->size, 0); ImGui::PopID(); } ImPlot::EndPlot(); } } break; case MetricsDisplayStyle::Stems: - ImPlot::SetNextPlotLimitsX(minDomain, maxDomain, ImGuiCond_Once); - ImPlot::SetNextPlotLimitsY(minValue, maxValue * 1.2, ImGuiCond_Always); - ImPlot::SetNextPlotTicksX(minDomain, maxDomain, 5); if (ImPlot::BeginPlot("##Some plot", "time", "value")) { for (size_t pi = 0; pi < userData.size(); ++pi) { - auto stemsData = reinterpret_cast(metricsToDisplay[pi]); + auto data = reinterpret_cast(metricsToDisplay[pi]); // FIXME: display a message for other metrics - if (stemsData->type == MetricType::Uint64) { + if (data->type == MetricType::Uint64) { ImGui::PushID(pi); - ImPlot::PlotScatterG(((MultiplotData*)metricsToDisplay[pi])->legend, getterXY, metricsToDisplay[pi], metricSize, 0); + ImPlot::PlotScatterG(((MultiplotData*)metricsToDisplay[pi])->legend, getterXY, metricsToDisplay[pi], data->size, 0); ImGui::PopID(); } } @@ -468,18 +482,19 @@ void metricsTableRow(std::vector metricIndex, auto& info = metricsInfos[index.deviceIndex].metrics[index.metricIndex]; ImGui::TableNextColumn(); + auto time = metricsInfo.timestamps[index.metricIndex][row]; switch (info.type) { case MetricType::Int: { - ImGui::Text("%i", metricsInfo.intMetrics[info.storeIdx][row]); + ImGui::Text("%i, %" PRIu64, metricsInfo.intMetrics[info.storeIdx][row], (uint64_t)time); } break; case MetricType::Uint64: { - ImGui::Text("%" PRIu64, metricsInfo.uint64Metrics[info.storeIdx][row]); + ImGui::Text("%" PRIu64 ", %" PRIu64, metricsInfo.uint64Metrics[info.storeIdx][row], (uint64_t)time); } break; case MetricType::Float: { - ImGui::Text("%f", metricsInfo.floatMetrics[info.storeIdx][row]); + ImGui::Text("%f, %" PRIu64, metricsInfo.floatMetrics[info.storeIdx][row], (uint64_t)time); } break; case MetricType::String: { - ImGui::Text("%s", metricsInfo.stringMetrics[info.storeIdx][row].data); + ImGui::Text("%s, %" PRIu64, metricsInfo.stringMetrics[info.storeIdx][row].data, (uint64_t)time); } break; default: break; @@ -557,15 +572,19 @@ void displayMetrics(gui::WorkspaceGUIState& state, for (size_t li = 0; li != metricInfo.metricLabels.size(); ++li) { char const* metricLabel = metricInfo.metricLabels[li].label; std::string legend = fmt::format("{}/{}", spec.label, metricLabel); - auto old = std::find_if(metricDisplayState.begin(), metricDisplayState.end(), [&legend](MetricDisplayState const& state) { return state.legend == legend; }); + auto hasher = std::hash(); + size_t legendHash = hasher(legend); + auto old = std::find_if(metricDisplayState.begin(), metricDisplayState.end(), [&legend, &legendHash](MetricDisplayState const& state) { return state.legendHash == legendHash && state.legend == legend; }); if (old != metricDisplayState.end()) { newMetricDisplayStates[gmi].visible = old->visible; + newMetricDisplayStates[gmi].axis = old->axis; } else { newMetricDisplayStates[gmi].visible = false; } newMetricDisplayStates[gmi].selected = hasAll(metricLabel, query); newMetricDisplayStates[gmi].legend = legend; + newMetricDisplayStates[gmi].legendHash = legendHash; gmi++; } } @@ -605,8 +624,14 @@ void displayMetrics(gui::WorkspaceGUIState& state, ImGui::Text("Find metrics: "); ImGui::SameLine(); ImGui::InputText("##query-metrics", query, MAX_QUERY_SIZE); - if (ImGui::BeginTable("##metrics-table", 2, ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY, ImVec2{-1, -1})) { + static const char* possibleAxis[] = { + "Y", + "Y1", + "Y2", + }; + if (ImGui::BeginTable("##metrics-table", 3, ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY, ImVec2{-1, -1})) { ImGui::TableSetupColumn("##close button", ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthFixed, 20); + ImGui::TableSetupColumn("##axis kind", ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthFixed, 30); ImGui::TableSetupScrollFreeze(1, 0); ImGuiListClipper clipper; clipper.Begin(selectedMetricIndex.size()); @@ -625,6 +650,21 @@ void displayMetrics(gui::WorkspaceGUIState& state, ImGui::TableNextColumn(); ImGui::Checkbox("##checkbox", &metricDisplayState[index.stateIndex].visible); ImGui::TableNextColumn(); + if (metricDisplayState[index.stateIndex].visible) { + if (ImGui::BeginCombo("##Select style", possibleAxis[metricDisplayState[index.stateIndex].axis], ImGuiComboFlags_NoArrowButton)) { + for (int n = 0; n < IM_ARRAYSIZE(possibleAxis); n++) { + bool is_selected = (metricDisplayState[index.stateIndex].axis == n); + if (ImGui::Selectable(possibleAxis[n], is_selected)) { + metricDisplayState[index.stateIndex].axis = n; + } + if (is_selected) { + ImGui::SetItemDefaultFocus(); // You may set the initial focus when opening the combo (scrolling + for keyboard navigation support) + } + } + ImGui::EndCombo(); + } + } + ImGui::TableNextColumn(); ImGui::Text("%s/%s", node.label.c_str(), label.label); ImGui::PopID(); } @@ -789,7 +829,7 @@ void displayMetrics(gui::WorkspaceGUIState& state, auto& metricsInfos = *metricsStore.metrics[index.storeIndex]; auto& metric = metricsInfos[index.deviceIndex]; auto label = metricsInfos[index.deviceIndex].metricLabels[index.metricIndex].label; - ImGui::TextUnformatted(label); + ImGui::Text("%s (%" PRIu64 ")", label, (uint64_t)metric.metrics[index.metricIndex].filledMetrics); } // Calculate which columns we want to see. From 4e14cbbfd488c336157035efbaf07a8e2a90e73e Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sat, 8 May 2021 13:54:50 +0200 Subject: [PATCH 451/770] RecoContainer should create sharedClusterMap only if both clusters and tracks are requested --- .../DataFormatsGlobalTracking/RecoContainer.h | 2 +- .../GlobalTracking/src/RecoContainer.cxx | 15 +++++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h index d66fab5f92d84..de4b1ee33fed0 100644 --- a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h +++ b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h @@ -122,7 +122,7 @@ struct RecoContainer { void addTOFMatches(o2::framework::ProcessingContext& pc, bool mc); void addITSClusters(o2::framework::ProcessingContext& pc, bool mc); - void addTPCClusters(o2::framework::ProcessingContext& pc, bool mc); + void addTPCClusters(o2::framework::ProcessingContext& pc, bool mc, bool shmap); void addTOFClusters(o2::framework::ProcessingContext& pc, bool mc); void addTRDTracklets(o2::framework::ProcessingContext& pc); diff --git a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx index b935cab4d2ecc..eeb0f1762ba42 100644 --- a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx +++ b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx @@ -48,6 +48,9 @@ void DataRequest::requestTPCTracks(bool mc) { addInput({"trackTPC", "TPC", "TRACKS", 0, Lifetime::Timeframe}); addInput({"trackTPCClRefs", "TPC", "CLUSREFS", 0, Lifetime::Timeframe}); + if (requestMap.find("clusTPC") != requestMap.end()) { + addInput({"clusTPCshmap", "TPC", "CLSHAREDMAP", 0, Lifetime::Timeframe}); + } if (mc) { addInput({"trackTPCMCTR", "TPC", "TRACKSMCLBL", 0, Lifetime::Timeframe}); } @@ -114,7 +117,9 @@ void DataRequest::requestITSClusters(bool mc) void DataRequest::requestTPCClusters(bool mc) { addInput({"clusTPC", ConcreteDataTypeMatcher{"TPC", "CLUSTERNATIVE"}, Lifetime::Timeframe}); - addInput({"clusTPCshmap", "TPC", "CLSHAREDMAP", 0, Lifetime::Timeframe}); + if (requestMap.find("trackTPC") != requestMap.end()) { + addInput({"clusTPCshmap", "TPC", "CLSHAREDMAP", 0, Lifetime::Timeframe}); + } if (mc) { addInput({"clusITSMC", "ITS", "CLUSTERSMCTR", 0, Lifetime::Timeframe}); } @@ -246,7 +251,7 @@ void RecoContainer::collectData(ProcessingContext& pc, const DataRequest& reques req = reqMap.find("clusTPC"); if (req != reqMap.end()) { - addTPCClusters(pc, req->second); + addTPCClusters(pc, req->second, reqMap.find("trackTPC") != reqMap.end()); } req = reqMap.find("clusTOF"); @@ -336,10 +341,12 @@ void RecoContainer::addITSClusters(ProcessingContext& pc, bool mc) } //__________________________________________________________ -void RecoContainer::addTPCClusters(ProcessingContext& pc, bool mc) +void RecoContainer::addTPCClusters(ProcessingContext& pc, bool mc, bool shmap) { inputsTPCclusters = o2::tpc::getWorkflowTPCInput(pc, 0, mc); - clusterShMapTPC = pc.inputs().get>("clusTPCshmap"); + if (shmap) { + clusterShMapTPC = pc.inputs().get>("clusTPCshmap"); + } } void RecoContainer::addTRDTracklets(ProcessingContext& pc) From 05e773669049fb9deb547b1763fcbb92206de768 Mon Sep 17 00:00:00 2001 From: shahoian Date: Sat, 8 May 2021 19:25:54 +0200 Subject: [PATCH 452/770] Add some isXXXTrack template aliases to RecoContainerCreateTracksVariadic + fix to use isTPCTrack alias in GPUWorkflowHelper --- .../RecoContainerCreateTracksVariadic.h | 46 ++++++++++++++++++- GPU/Workflow/helper/src/GPUWorkflowHelper.cxx | 2 +- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainerCreateTracksVariadic.h b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainerCreateTracksVariadic.h index 42163443cb552..b1061aa45db20 100644 --- a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainerCreateTracksVariadic.h +++ b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainerCreateTracksVariadic.h @@ -43,7 +43,7 @@ void o2::globaltracking::RecoContainer::createTracksVariadic(T creator) const // which depends on the track time: // 1) For track types containing TimeStampWithError ts it is ts.getTimeStamp(), getTimeStampError() // 2) For tracks with asymmetric time uncertainty, e.g. TPC: as mean time of t0-errBwd,t+errFwd and 0.5(errBwd+errFwd), all in TPC time bins - // 3) For tracks whose timing is provided as RO frame: as time in \mus for RO frame start since the start of TF, half-duration of RO window and 0. + // 3) For tracks whose timing is provided as RO frame: as time in \mus for RO frame start since the start of TF, half-duration of RO window. auto start_time = std::chrono::high_resolution_clock::now(); constexpr float PS2MUS = 1e-6; @@ -84,7 +84,7 @@ void o2::globaltracking::RecoContainer::createTracksVariadic(T creator) const const float timeErr = 0.010f; // assume 10 ns error FIXME auto gidx = match.getEvIdxTrack().getIndex(); // this should be corresponding ITS-TPC track - if (creator(tracksPool.get(gidx), {i, GTrackID::ITSTPCTOF}, timeTOFMUS, timeErr)) { + if (creator(tracksTPCITS[gidx.getIndex()], {i, GTrackID::ITSTPCTOF}, timeTOFMUS, timeErr)) { flagUsed2(i, GTrackID::TOF); flagUsed(gidx); // flag used ITS-TPC tracks } @@ -162,3 +162,45 @@ void o2::globaltracking::RecoContainer::createTracksVariadic(T creator) const auto current_time = std::chrono::high_resolution_clock::now(); LOG(INFO) << "RecoContainer::createTracks took " << std::chrono::duration_cast(current_time - start_time).count() * 1e-6 << " CPU s."; } + +template +inline constexpr auto isITSTrack() +{ + return std::is_same_v, o2::its::TrackITS>; +} + +template +inline constexpr auto isTPCTrack() +{ + return std::is_same_v, o2::tpc::TrackTPC>; +} + +template +inline constexpr auto isTRDTrack() +{ + return std::is_same_v, o2::trd::TrackTRD>; +} + +template +inline constexpr auto isTPCTOFTrack() +{ + return std::is_same_v, o2::dataformats::TrackTPCTOF>; +} + +template +inline constexpr auto isTPCITSTrack() +{ + return std::is_same_v, o2::dataformats::TrackTPCITS>; +} + +template +inline constexpr auto isTPCTRDTOFTrack() +{ + return false; +} // to be implemented + +template +inline constexpr auto isITSTPCTRDTOFTrack() +{ + return false; +} // to be implemented diff --git a/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx b/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx index cad4e48fcf019..9e94fd6734396 100644 --- a/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx +++ b/GPU/Workflow/helper/src/GPUWorkflowHelper.cxx @@ -146,7 +146,7 @@ std::shared_ptr GPUWorkflowHelper::fi } auto creator = [&recoCont, &retVal](auto& trk, GID gid, float time, float) { - if constexpr (std::is_same_v, o2::tpc::TrackTPC>) { + if constexpr (isTPCTrack()) { time = trk.getTime0(); } retVal->globalTracks.emplace_back(&trk); From d962124dac61b6f28a84cac6c75594c14d43bf32 Mon Sep 17 00:00:00 2001 From: shahoian Date: Sat, 8 May 2021 19:28:01 +0200 Subject: [PATCH 453/770] Use createTracksVariadic instead of createTracksWithMatchingTimeInfo TPC-ITS matcher Cosmics matcher PVertexer PVertex - track matcher --- .../include/GlobalTracking/MatchTPCITS.h | 1 - Detectors/GlobalTracking/src/MatchCosmics.cxx | 37 +++++++------- Detectors/GlobalTracking/src/MatchTPCITS.cxx | 48 +++++++++---------- .../src/PrimaryVertexingSpec.cxx | 31 ++++++------ .../include/DetectorsVertexing/PVertexer.h | 1 - .../Vertexing/src/VertexTrackMatcher.cxx | 34 ++++++------- 6 files changed, 76 insertions(+), 76 deletions(-) diff --git a/Detectors/GlobalTracking/include/GlobalTracking/MatchTPCITS.h b/Detectors/GlobalTracking/include/GlobalTracking/MatchTPCITS.h index 5e410e8681d57..cf7b16b923e66 100644 --- a/Detectors/GlobalTracking/include/GlobalTracking/MatchTPCITS.h +++ b/Detectors/GlobalTracking/include/GlobalTracking/MatchTPCITS.h @@ -428,7 +428,6 @@ class MatchTPCITS std::array& lad2Check) const; int findLaddersToCheckBOff(int ilr, int lad0, const o2::math_utils::IntervalXYf_t& trcLinPar, float errYFrac, std::array& lad2Check) const; - bool prepareTPCData(); bool prepareITSData(); bool prepareFITData(); diff --git a/Detectors/GlobalTracking/src/MatchCosmics.cxx b/Detectors/GlobalTracking/src/MatchCosmics.cxx index 9a6ff6d1d5f07..4c3302b2110de 100644 --- a/Detectors/GlobalTracking/src/MatchCosmics.cxx +++ b/Detectors/GlobalTracking/src/MatchCosmics.cxx @@ -10,6 +10,7 @@ #include "GlobalTracking/MatchCosmics.h" #include "DataFormatsGlobalTracking/RecoContainer.h" +#include "DataFormatsGlobalTracking/RecoContainerCreateTracksVariadic.h" #include "GPUO2InterfaceRefit.h" #include "ReconstructionDataFormats/GlobalTrackAccessor.h" #include "DataFormatsITSMFT/CompCluster.h" @@ -483,26 +484,26 @@ void MatchCosmics::createSeeds(const o2::globaltracking::RecoContainer& data) mSeeds.clear(); - auto creator = - [this](const o2::track::TrackParCov& _tr, GTrackID _origID, float t0, float terr) { - if (std::abs(_tr.getQ2Pt()) > this->mQ2PtCutoff) { - return true; - } - if (_origID.getSource() == GTrackID::TPC) { // convert TPC bins to \mus - t0 *= this->mTPCTBinMUS; - terr *= this->mTPCTBinMUS; - } else if (_origID.getSource() == GTrackID::ITS) { // error is supplied a half-ROF duration, convert to \mus - t0 += 0.5 * mITSROFrameLengthMUS; // time 0 is supplied as beginning of ROF - terr *= mITSROFrameLengthMUS; - } else { - terr *= this->mMatchParams->nSigmaTError; - } - terr += this->mMatchParams->timeToleranceMUS; - mSeeds.emplace_back(TrackSeed{_tr, {t0 - terr, t0 + terr}, _origID, MinusOne}); + auto creator = [this](auto& _tr, GTrackID _origID, float t0, float terr) { + if (std::abs(_tr.getQ2Pt()) > this->mQ2PtCutoff) { return true; - }; + } + if constexpr (isTPCTrack()) { + // unconstrained TPC track, with t0 = TrackTPC.getTime0+0.5*(DeltaFwd-DeltaBwd) and terr = 0.5*(DeltaFwd+DeltaBwd) in TimeBins + t0 *= this->mTPCTBinMUS; + terr *= this->mTPCTBinMUS; + } else if (isITSTrack()) { + t0 += 0.5 * this->mITSROFrameLengthMUS; // time 0 is supplied as beginning of ROF in \mus + terr *= this->mITSROFrameLengthMUS; // error is supplied a half-ROF duration, convert to \mus + } else { // all other tracks are provided with time and its gaussian error in \mus + terr *= this->mMatchParams->nSigmaTError; + } + terr += this->mMatchParams->timeToleranceMUS; + mSeeds.emplace_back(TrackSeed{_tr, {t0 - terr, t0 + terr}, _origID, MinusOne}); + return true; + }; - data.createTracksWithMatchingTimeInfo(creator); + data.createTracksVariadic(creator); LOG(INFO) << "collected " << mSeeds.size() << " seeds"; } diff --git a/Detectors/GlobalTracking/src/MatchTPCITS.cxx b/Detectors/GlobalTracking/src/MatchTPCITS.cxx index 3934f284d1b48..5b1902e0f4933 100644 --- a/Detectors/GlobalTracking/src/MatchTPCITS.cxx +++ b/Detectors/GlobalTracking/src/MatchTPCITS.cxx @@ -41,6 +41,7 @@ #include "ReconstructionDataFormats/Vertex.h" #include "GlobalTracking/MatchTPCITS.h" #include "DataFormatsGlobalTracking/RecoContainer.h" +#include "DataFormatsGlobalTracking/RecoContainerCreateTracksVariadic.h" #include "DataFormatsTPC/WorkflowHelper.h" #include "ITStracking/IOUtils.h" @@ -529,6 +530,9 @@ void MatchTPCITS::addTPCSeed(const o2::track::TrackParCov& _tr, float t0, float { // account single TPC seed, can be from standalone TPC track or constrained track from match to TRD and/or TOF const float SQRT12DInv = 2. / sqrt(12.); + if (_tr.getX() > o2::constants::geom::XTPCInnerRef + 0.1 || std::abs(_tr.getQ2Pt()) > mMinTPCTrackPtInv) { + return; + } const auto& tpcOrig = mTPCTracksArray[tpcID]; // discard tracks w/o certain number of total or innermost pads (last cluster is innermost one) if (tpcOrig.getNClusterReferences() < mParams->minTPCClusters) { @@ -600,35 +604,31 @@ bool MatchTPCITS::prepareTPCData() mTPCTrkLabels = inp.getTPCTracksMCLabels(); } - auto creator = [this](const o2::track::TrackParCov& _tr, GTrackID _origID, float t0, float terr) { - auto srcID = _origID.getSource(); - if (srcID == GTrackID::ITS) { // we don't need ITS here - return true; // we don't need TPC tracks + auto creator = [this](auto& trk, GTrackID gid, float time0, float terr) { + if constexpr (isITSTrack()) { + // do nothing, ITS tracks will be processed in a direct loop over ROFs } - // make sure the track was propagated to inner TPC radius at the ref. radius - if (_tr.getX() > o2::constants::geom::XTPCInnerRef + 0.1 || std::abs(_tr.getQ2Pt()) > mMinTPCTrackPtInv) { - return true; - } - GTrackID tpcGID{}; - if (srcID == GTrackID::TPC) { - // unconstrained TPC track, with t0 = TrackTPC.getTime0+0.5*(DeltaFwd-DeltaBwd) and terr = 0.5*(DeltaFwd+DeltaBwd) - if (this->mSkipTPCOnly) { - return true; + if constexpr (isTPCTrack()) { + // unconstrained TPC track, with t0 = TrackTPC.getTime0+0.5*(DeltaFwd-DeltaBwd) and terr = 0.5*(DeltaFwd+DeltaBwd) in TimeBins + if (!this->mSkipTPCOnly) { + this->addTPCSeed(trk, this->tpcTimeBin2MUS(time0), this->tpcTimeBin2MUS(terr), gid, gid.getIndex()); } - tpcGID = _origID; - t0 = this->tpcTimeBin2MUS(t0); // time and error are in TPC bins, convert to \mus - terr = this->tpcTimeBin2MUS(terr); - } else if (srcID == GTrackID::TPCTOF) { - // TPC track is contrained by TOF fit - tpcGID = this->mRecoCont->getTPCContributorGID(_origID); - } else if (srcID == GTrackID::TPCTRD) { - return true; // TODO RS } - addTPCSeed(_tr, t0, terr, _origID, tpcGID.getIndex()); + if constexpr (isTPCTOFTrack()) { + // TPC track constrained by TOF time, time and its error in \mus + this->addTPCSeed(trk, time0, terr, gid, this->mRecoCont->getTPCContributorGID(gid)); + } + if constexpr (isTRDTrack()) { + // TPC track constrained by TRD trigger time, time and its error in \mus + LOG(ERROR) << "Not ready yet for TPC-TRD tracks"; + } + if constexpr (isTPCTRDTOFTrack()) { + // TPC track constrained by TRD and TOF time, time and its error in \mus + LOG(ERROR) << "Not ready yet for TPC-TRD-TOF tracks"; + } return true; }; - - inp.createTracksWithMatchingTimeInfo(creator); + mRecoCont->createTracksVariadic(creator); float maxTime = 0; int nITSROFs = mITSROFTimes.size(); diff --git a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx b/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx index d3de4cb6a7467..f99cfbad9ef2e 100644 --- a/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx +++ b/Detectors/GlobalTrackingWorkflow/src/PrimaryVertexingSpec.cxx @@ -13,6 +13,7 @@ #include #include #include "DataFormatsGlobalTracking/RecoContainer.h" +#include "DataFormatsGlobalTracking/RecoContainerCreateTracksVariadic.h" #include "ReconstructionDataFormats/TrackTPCITS.h" #include "ReconstructionDataFormats/GlobalTrackID.h" #include "DetectorsBase/Propagator.h" @@ -110,24 +111,24 @@ void PrimaryVertexingSpec::run(ProcessingContext& pc) auto halfROFITS = 0.5 * mITSROFrameLengthMUS; auto hw2ErrITS = 2.f / std::sqrt(12.f) * mITSROFrameLengthMUS; // conversion from half-width to error for ITS - auto creator = - [maxTrackTimeError, hw2ErrITS, halfROFITS, &tracks, &gids](const o2::track::TrackParCov& _tr, GTrackID _origID, float t0, float terr) { - if (!_origID.includesDet(DetID::ITS)) { - return true; // just in case this selection was not done on RecoContainer filling level - } - if (_origID.getSource() == GTrackID::ITS) { // error is supplied a half-ROF duration, convert to \mus - t0 += halfROFITS; // ITS time is supplied as beginning of ROF - terr *= hw2ErrITS; - } - if (terr > maxTrackTimeError) { - return true; - } + auto creator = [maxTrackTimeError, hw2ErrITS, halfROFITS, &tracks, &gids](auto& _tr, GTrackID _origID, float t0, float terr) { + if (!_origID.includesDet(DetID::ITS)) { + return true; // just in case this selection was not done on RecoContainer filling level + } + if constexpr (isITSTrack()) { + t0 += halfROFITS; // ITS time is supplied in \mus as beginning of ROF + terr *= hw2ErrITS; // error is supplied as a half-ROF duration, convert to \mus + } + // for all other tracks the time is in \mus with gaussian error + if (terr < maxTrackTimeError) { tracks.emplace_back(TrackWithTimeStamp{_tr, {t0, terr}}); gids.emplace_back(_origID); - return true; - }; + } + return true; + }; + + recoData.createTracksVariadic(creator); // create track sample considered for vertexing - recoData.createTracksWithMatchingTimeInfo(creator); // create track sample considered for vertexing if (mUseMC) { recoData.fillTrackMCLabels(gids, tracksMCInfo); } diff --git a/Detectors/Vertexing/include/DetectorsVertexing/PVertexer.h b/Detectors/Vertexing/include/DetectorsVertexing/PVertexer.h index a97523cef8fef..ab1cf231d5176 100644 --- a/Detectors/Vertexing/include/DetectorsVertexing/PVertexer.h +++ b/Detectors/Vertexing/include/DetectorsVertexing/PVertexer.h @@ -197,7 +197,6 @@ void PVertexer::createTracksPool(const TR& tracks, gsl::spanmTPCBin2MUS; - terr *= this->mTPCBin2MUS; - } else if (_origID.getSource() == GIndex::ITS) { // error is supplied a half-ROF duration, convert to \mus - t0 += this->mITSROFrameLengthMUS; - terr *= 0.5 * this->mITSROFrameLengthMUS; - } else { - //terr *= this->mMatchParams->nSigmaTError; - } - mTBrackets.emplace_back(TrackTBracket{{t0 - terr, t0 + terr}, _origID}); + auto creator = [this, &vcont](auto& _tr, GIndex _origID, float t0, float terr) { + if (vcont.find(_origID) != vcont.end()) { // track is contributor to vertex, already accounted return true; - }; + } + if constexpr (isTPCTrack()) { + // unconstrained TPC track, with t0 = TrackTPC.getTime0+0.5*(DeltaFwd-DeltaBwd) and terr = 0.5*(DeltaFwd+DeltaBwd) in TimeBins + t0 *= this->mTPCBin2MUS; + terr *= this->mTPCBin2MUS; + } else if (isITSTrack()) { // error is supplied a half-ROF duration, convert to \mus + t0 += this->mITSROFrameLengthMUS; // ITS time is supplied in \mus as beginning of ROF + terr *= 0.5 * this->mITSROFrameLengthMUS; // error is supplied as a half-ROF duration, convert to \mus + } + // for all other tracks the time is in \mus with gaussian error + mTBrackets.emplace_back(TrackTBracket{{t0 - terr, t0 + terr}, _origID}); + return true; + }; - data.createTracksWithMatchingTimeInfo(creator); + data.createTracksVariadic(creator); // sort in increasing min.time std::sort(mTBrackets.begin(), mTBrackets.end(), [](const TrackTBracket& a, const TrackTBracket& b) { return a.tBracket.getMin() < b.tBracket.getMin(); }); From 76ca1e9cc7333ab666198e68c70d9ca29441e0b8 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Sun, 9 May 2021 08:41:55 +0200 Subject: [PATCH 454/770] DPL: Print out Device name of missing input [O2-2317] (#6106) --- Framework/Core/src/WorkflowHelpers.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Framework/Core/src/WorkflowHelpers.cxx b/Framework/Core/src/WorkflowHelpers.cxx index f9bd3c7d134d7..d7f6cf04290c6 100644 --- a/Framework/Core/src/WorkflowHelpers.cxx +++ b/Framework/Core/src/WorkflowHelpers.cxx @@ -657,7 +657,7 @@ void WorkflowHelpers::constructGraph(const WorkflowSpec& workflow, auto input = workflow[ci].inputs[ii]; std::ostringstream str; str << "No matching output found for " - << DataSpecUtils::describe(input) << ". Candidates:\n"; + << DataSpecUtils::describe(input) << " as requested by data processor \"" << workflow[ci].name << "\". Candidates:\n"; for (auto& output : constOutputs) { str << "-" << DataSpecUtils::describe(output) << "\n"; From 1114b047af1cb99075694b7e93caa89a3dcb00e3 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Tue, 4 May 2021 20:07:59 +0200 Subject: [PATCH 455/770] DPL Analysis: improved ratelimiting metrics --- Framework/Core/src/ArrowSupport.cxx | 10 +++++- Framework/Core/src/DataProcessingDevice.cxx | 34 +++------------------ 2 files changed, 13 insertions(+), 31 deletions(-) diff --git a/Framework/Core/src/ArrowSupport.cxx b/Framework/Core/src/ArrowSupport.cxx index 7d5a94e845897..3d6df45627040 100644 --- a/Framework/Core/src/ArrowSupport.cxx +++ b/Framework/Core/src/ArrowSupport.cxx @@ -218,8 +218,16 @@ o2::framework::ServiceSpec ArrowSupport::arrowBackendSpec() static uint64_t now = 0; static uint64_t lastSignal = 0; now = uv_hrtime(); + static RateLimitingState lastReportedState = RateLimitingState::UNKNOWN; + static uint64_t lastReportTime = 0; while (!done) { - stateMetric(driverMetrics, (uint64_t)(currentState), stateTransitions++); +#ifndef NDEBUG + if (currentState != lastReportedState || now - lastReportTime > 1000000000LL) { + stateMetric(driverMetrics, (uint64_t)(currentState), timestamp); + lastReportedState = currentState; + lastReportTime = timestamp; + } +#endif switch (currentState) { case RateLimitingState::UNKNOWN: { for (auto& deviceMetrics : allDeviceMetrics) { diff --git a/Framework/Core/src/DataProcessingDevice.cxx b/Framework/Core/src/DataProcessingDevice.cxx index 08c74657157df..a483a7933ce17 100644 --- a/Framework/Core/src/DataProcessingDevice.cxx +++ b/Framework/Core/src/DataProcessingDevice.cxx @@ -33,6 +33,7 @@ #include "Framework/SourceInfoHeader.h" #include "Framework/Logger.h" #include "Framework/DriverClient.h" +#include "Framework/Monitoring.h" #include "PropertyTreeHelpers.h" #include "DataProcessingStatus.h" #include "DataProcessingHelpers.h" @@ -466,37 +467,10 @@ bool DataProcessingDevice::ConditionalRun() if (NewStatePending()) { shouldNotWait = true; } + TracyPlot("shouldNotWait", (int)shouldNotWait); uv_run(mState.loop, shouldNotWait ? UV_RUN_NOWAIT : UV_RUN_ONCE); - if (mDataProcessorContexes.at(0).state->loopReason & DeviceState::METRICS_MUST_FLUSH) { - LOG(debug) << "New metric to be sent"; - } - if (mDataProcessorContexes.at(0).state->loopReason & DeviceState::SIGNAL_ARRIVED) { - LOG(debug) << "Signal arrived"; - } - if (mDataProcessorContexes.at(0).state->loopReason & DeviceState::DATA_SOCKET_POLLED) { - LOG(debug) << "Socket polled"; - } - if (mDataProcessorContexes.at(0).state->loopReason & DeviceState::DATA_INCOMING) { - LOG(debug) << "Data read"; - } - if (mDataProcessorContexes.at(0).state->loopReason & DeviceState::DATA_OUTGOING) { - LOG(debug) << "Data written"; - } - if (mDataProcessorContexes.at(0).state->loopReason & DeviceState::WS_COMMUNICATION) { - LOG(debug) << "Communication with WS"; - } - if (mDataProcessorContexes.at(0).state->loopReason & DeviceState::TIMER_EXPIRED) { - LOG(debug) << "Timer expired"; - } - if (mDataProcessorContexes.at(0).state->loopReason & DeviceState::WS_CONNECTED) { - LOG(debug) << "WS Connected"; - } - if (shouldNotWait) { - LOG(debug) << "Should not wait"; - } - if ((mDataProcessorContexes.at(0).state->loopReason == DeviceState::NO_REASON) && (shouldNotWait == false)) { - LOG(debug) << "Unknown reason to trigger the loop"; - } + TracyPlot("loopReason", (int64_t)(uint64_t)mState.loopReason); + mDataProcessorContexes.at(0).state->loopReason = DeviceState::NO_REASON; // A new state was requested, we exit. From b6f3b679d0b2519d7b4e96a43fdb6e39ea65a505 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Tue, 4 May 2021 20:08:15 +0200 Subject: [PATCH 456/770] DPL: Introduce resource management in DPL In order to limit the amount of resources used by a DPL workflow, DPL now has the concept of a resource quota that the task can use. The default behavior is to ignore quota, but this will change to a mode where a task can run only if enough CPU quota is available. The actual resource requests for a task are controlled by the matching ResourcePolicy, which can be customised in the usual way. This should also allow improving the behavior of the shared memory based rate limiting, by letting the reader know how much it is allowed to read ahead before pausing to reduce memory pressure (right now there is a race condition due to the fact that the "memory used" memory might come too late, for the driver to be able to stop the reader). --- Framework/Core/CMakeLists.txt | 3 + .../Framework/ComputingQuotaEvaluator.h | 46 +++++++ .../include/Framework/ComputingQuotaOffer.h | 57 ++++++++ .../include/Framework/DataProcessingDevice.h | 43 ++++-- Framework/Core/include/Framework/DeviceSpec.h | 6 + Framework/Core/include/Framework/DriverInfo.h | 5 + .../Core/include/Framework/ResourcePolicy.h | 37 +++++ .../include/Framework/ResourcePolicyHelpers.h | 29 ++++ .../include/Framework/runDataProcessing.h | 19 ++- .../Core/src/ComputingQuotaEvaluator.cxx | 87 ++++++++++++ Framework/Core/src/DataProcessingDevice.cxx | 128 ++++++++++++------ Framework/Core/src/DeviceSpecHelpers.cxx | 12 ++ Framework/Core/src/DeviceSpecHelpers.h | 6 +- Framework/Core/src/ResourcePolicy.cxx | 24 ++++ Framework/Core/src/ResourcePolicyHelpers.cxx | 53 ++++++++ Framework/Core/src/runDataProcessing.cxx | 3 + 16 files changed, 505 insertions(+), 53 deletions(-) create mode 100644 Framework/Core/include/Framework/ComputingQuotaEvaluator.h create mode 100644 Framework/Core/include/Framework/ComputingQuotaOffer.h create mode 100644 Framework/Core/include/Framework/ResourcePolicy.h create mode 100644 Framework/Core/include/Framework/ResourcePolicyHelpers.h create mode 100644 Framework/Core/src/ComputingQuotaEvaluator.cxx create mode 100644 Framework/Core/src/ResourcePolicy.cxx create mode 100644 Framework/Core/src/ResourcePolicyHelpers.cxx diff --git a/Framework/Core/CMakeLists.txt b/Framework/Core/CMakeLists.txt index a47001de8760a..91b2180034665 100644 --- a/Framework/Core/CMakeLists.txt +++ b/Framework/Core/CMakeLists.txt @@ -31,6 +31,7 @@ o2_add_library(Framework src/CommonMessageBackends.cxx src/CompletionPolicy.cxx src/CompletionPolicyHelpers.cxx + src/ComputingQuotaEvaluator.cxx src/ComputingResourceHelpers.cxx src/ConfigContext.cxx src/ControlService.cxx @@ -85,6 +86,8 @@ o2_add_library(Framework src/RCombinedDS.cxx src/ReadoutAdapter.cxx src/ResourcesMonitoringHelper.cxx + src/ResourcePolicy.cxx + src/ResourcePolicyHelpers.cxx src/ServiceRegistry.cxx src/SimpleResourceManager.cxx src/SimpleRawDeviceService.cxx diff --git a/Framework/Core/include/Framework/ComputingQuotaEvaluator.h b/Framework/Core/include/Framework/ComputingQuotaEvaluator.h new file mode 100644 index 0000000000000..41aed693e2fb9 --- /dev/null +++ b/Framework/Core/include/Framework/ComputingQuotaEvaluator.h @@ -0,0 +1,46 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_COMPUTINGQUOTAEVALUATOR_H_ +#define O2_COMPUTINGQUOTAEVALUATOR_H_ + +#include "Framework/ComputingQuotaOffer.h" + +#include +#include +#include + +typedef struct uv_loop_s uv_loop_t; + +namespace o2::framework +{ + + +class ComputingQuotaEvaluator +{ + // Maximum number of offers this evaluator can hold + static constexpr int MAX_INFLIGHT_OFFERS = 16; + + public: + ComputingQuotaEvaluator(uv_loop_t*); + ComputingQuotaOfferRef selectOffer(ComputingQuotaRequest const& request); + + void dispose(ComputingQuotaOfferRef offer); + + /// All the available offerts + std::array mOffers; + /// Information about a given computing offer (e.g. when it was started to be used) + std::array mInfos; + uv_loop_t* mLoop; +}; + +} // namespace o2::framework + +#endif // O2_COMPUTINGQUOTAEVALUATOR_H_ diff --git a/Framework/Core/include/Framework/ComputingQuotaOffer.h b/Framework/Core/include/Framework/ComputingQuotaOffer.h new file mode 100644 index 0000000000000..445c07a0b74d1 --- /dev/null +++ b/Framework/Core/include/Framework/ComputingQuotaOffer.h @@ -0,0 +1,57 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_COMPUTINGQUOTAOFFER_H_ +#define O2_COMPUTINGQUOTAOFFER_H_ + +#include +#include +#include + +namespace o2::framework +{ + +struct ComputingQuotaOfferRef { + int index; +}; + +struct ComputingQuotaOffer { + /// How many cores it can use + int cpu = 0; + /// How much memory it can use + int64_t memory = 0; + /// How much shared memory it can allocate + int64_t sharedMemory = 0; + /// How much runtime it can use before giving back the resource + /// in milliseconds. + int64_t runtime = 0; + /// Whether or not the offer is being used + bool used; + /// Whether or not the offer is valid + bool valid; +}; + +struct ComputingQuotaInfo { + // When the offer was received + size_t received = 0; + // First time it was used + size_t firstUsed = 0; + // Last time it was used + size_t lastUsed = 0; +}; + +/// A request is a function which evaluates to true if the offer +/// is ok for running. The higher the return value, the +/// better match is the given resource for the computation. +using ComputingQuotaRequest = std::function; + +} // namespace o2::framework + +#endif // O2_COMPUTINGQUOTAOFFER_H_ diff --git a/Framework/Core/include/Framework/DataProcessingDevice.h b/Framework/Core/include/Framework/DataProcessingDevice.h index 1091f6816875c..aec931c1b379f 100644 --- a/Framework/Core/include/Framework/DataProcessingDevice.h +++ b/Framework/Core/include/Framework/DataProcessingDevice.h @@ -11,6 +11,8 @@ #define FRAMEWORK_DATAPROCESSING_DEVICE_H #include "Framework/AlgorithmSpec.h" +#include "Framework/ComputingQuotaOffer.h" +#include "Framework/ComputingQuotaEvaluator.h" #include "Framework/ConfigParamRegistry.h" #include "Framework/DataAllocator.h" #include "Framework/DataRelayer.h" @@ -30,12 +32,14 @@ #include #include +#include namespace o2::framework { struct InputChannelInfo; struct DeviceState; +struct ComputingQuotaEvaluator; /// Context associated to a given DataProcessor. /// For the time being everything points to @@ -46,6 +50,18 @@ struct DeviceState; /// per thread and relax the locks. class DataProcessingDevice; +/// Context associated to a device. In principle +/// multiple DataProcessors can run on a Device (even if we +/// do not do it for now). +struct DeviceContext { + // These are pointers to the one owned by the DataProcessingDevice + // and therefore require actual locking + DataProcessingDevice* device = nullptr; + DeviceSpec const* spec = nullptr; + DeviceState* state = nullptr; + ComputingQuotaEvaluator* quotaEvaluator = nullptr; +}; + struct DataProcessorContext { // These are specific of a given context and therefore // not shared by threads. @@ -57,13 +73,7 @@ struct DataProcessorContext { // be accessed without a lock. // FIXME: move stuff here from the list below... ;-) - - // These are pointers to the one owned by the DataProcessingDevice - // and therefore require actual locking - DataProcessingDevice* device = nullptr; - DeviceSpec const* spec = nullptr; - DeviceState* state = nullptr; - + DeviceContext* deviceContext = nullptr; DataRelayer* relayer = nullptr; ServiceRegistry* registry = nullptr; std::vector* completed = nullptr; @@ -77,6 +87,19 @@ struct DataProcessorContext { std::function* errorHandling = nullptr; }; +struct TaskStreamRef { + int index = -1; +}; + +struct TaskStreamInfo { + /// The quota offer to be used for the computation + ComputingQuotaOfferRef offer; + /// The context of the DataProcessor being run by this task + DataProcessorContext* context; + /// Wether or not this task is running + bool running = false; +}; + /// A device actually carrying out all the DPL /// Data Processing needs. class DataProcessingDevice : public FairMQDevice @@ -101,9 +124,10 @@ class DataProcessingDevice : public FairMQDevice protected: void error(const char* msg); - void fillContext(DataProcessorContext& context); + void fillContext(DataProcessorContext& context, DeviceContext& deviceContext); private: + DeviceContext mDeviceContext; /// The specification used to create the initial state of this device DeviceSpec const& mSpec; /// The current internal state of this device. @@ -132,6 +156,9 @@ class DataProcessingDevice : public FairMQDevice std::mutex mRegionInfoMutex; enum TerminationPolicy mErrorPolicy = TerminationPolicy::WAIT; /// What to do when an error arises bool mWasActive = false; /// Whether or not the device was active at last iteration. + std::vector mHandles; /// Handles to use to schedule work. + std::vector mStreams; /// Information about the task running in the associated mHandle. + ComputingQuotaEvaluator mQuotaEvaluator; /// The component which evaluates if the offer can be used to run a task }; } // namespace o2::framework diff --git a/Framework/Core/include/Framework/DeviceSpec.h b/Framework/Core/include/Framework/DeviceSpec.h index 26670a951a492..35de414af2c3c 100644 --- a/Framework/Core/include/Framework/DeviceSpec.h +++ b/Framework/Core/include/Framework/DeviceSpec.h @@ -23,6 +23,7 @@ #include "Framework/OutputRoute.h" #include "Framework/CompletionPolicy.h" #include "Framework/DispatchPolicy.h" +#include "Framework/ResourcePolicy.h" #include "Framework/ServiceSpec.h" #include @@ -36,7 +37,9 @@ namespace o2::framework /// Concrete description of the device which will actually run /// a DataProcessor. struct DeviceSpec { + /// The name of the associated DataProcessorSpec std::string name; + /// The id of the device, including time-pipelining and suffix std::string id; std::string channelPrefix; std::vector inputChannels; @@ -59,6 +62,9 @@ struct DeviceSpec { /// The completion policy to use for this device. CompletionPolicy completionPolicy; DispatchPolicy dispatchPolicy; + /// Policy on when the available resources are enough to run + /// a computation. + ResourcePolicy resourcePolicy; ComputingResource resource; unsigned short resourceMonitoringInterval; }; diff --git a/Framework/Core/include/Framework/DriverInfo.h b/Framework/Core/include/Framework/DriverInfo.h index 9b2a512e4f5e6..539daf691901d 100644 --- a/Framework/Core/include/Framework/DriverInfo.h +++ b/Framework/Core/include/Framework/DriverInfo.h @@ -25,6 +25,7 @@ #include "Framework/DeviceMetricsInfo.h" #include "Framework/LogParsingHelpers.h" #include "DataProcessorInfo.h" +#include "ResourcePolicy.h" namespace o2::framework { @@ -96,6 +97,10 @@ struct DriverInfo { /// These are the policies which can be applied to decide when complete /// objects/messages are sent out std::vector dispatchPolicies; + + /// These are the policies which can be applied to decide when there + /// is enough resources to process data. + std::vector resourcePolicies; /// The argc with which the driver was started. int argc; /// The argv with which the driver was started. diff --git a/Framework/Core/include/Framework/ResourcePolicy.h b/Framework/Core/include/Framework/ResourcePolicy.h new file mode 100644 index 0000000000000..4686a39ad8095 --- /dev/null +++ b/Framework/Core/include/Framework/ResourcePolicy.h @@ -0,0 +1,37 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_FRAMEWORK_RESOURCEPOLICY_H_ +#define O2_FRAMEWORK_RESOURCEPOLICY_H_ + +#include "Framework/ComputingQuotaOffer.h" +#include +#include + +namespace o2::framework +{ +struct DeviceSpec; + +/// A policy which specify how a device matched by +/// @a matcher should react to a given offer by specifying +/// a given @a request. +struct ResourcePolicy { + using Matcher = std::function; + + static std::vector createDefaultPolicies(); + + std::string name; + Matcher matcher; + ComputingQuotaRequest request; +}; + +} // namespace o2::framework + +#endif // O2_FRAMEWORK_RESOURCEPOLICY_H_ diff --git a/Framework/Core/include/Framework/ResourcePolicyHelpers.h b/Framework/Core/include/Framework/ResourcePolicyHelpers.h new file mode 100644 index 0000000000000..990b47b318ea7 --- /dev/null +++ b/Framework/Core/include/Framework/ResourcePolicyHelpers.h @@ -0,0 +1,29 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef O2_FRAMEWORK_RESOURCEPOLICYHELPERS_H_ +#define O2_FRAMEWORK_RESOURCEPOLICYHELPERS_H_ + +#include "Framework/ResourcePolicy.h" +#include +#include + +namespace o2::framework +{ + +struct ResourcePolicyHelpers { + static ResourcePolicy trivialTask(char const* taskMatcher); + static ResourcePolicy cpuBoundTask(char const* taskMatcher, int maxCPUs = 1); + static ResourcePolicy sharedMemoryBoundTask(char const* taskMatcher, int maxMemory); +}; + +} // namespace o2::framework + +#endif // O2_FRAMEWORK_RESOURCEPOLICYHELPERS_H_ diff --git a/Framework/Core/include/Framework/runDataProcessing.h b/Framework/Core/include/Framework/runDataProcessing.h index 1910a11d04c11..61dfc142bc8f7 100644 --- a/Framework/Core/include/Framework/runDataProcessing.h +++ b/Framework/Core/include/Framework/runDataProcessing.h @@ -22,6 +22,7 @@ #include "Framework/CommonServices.h" #include "Framework/WorkflowCustomizationHelpers.h" #include "Framework/RuntimeError.h" +#include "Framework/ResourcePolicyHelpers.h" #include "Framework/Logger.h" #include @@ -71,6 +72,7 @@ void defaultConfiguration(std::vector void defaultConfiguration(std::vector& globalWorkflowOptions) {} void defaultConfiguration(std::vector& completionPolicies) {} void defaultConfiguration(std::vector& dispatchPolicies) {} +void defaultConfiguration(std::vector& resourcePolicies) {} void defaultConfiguration(std::vector& services) { services = o2::framework::CommonServices::defaultServices(); @@ -114,6 +116,7 @@ int doMain(int argc, char** argv, o2::framework::WorkflowSpec const& specs, std::vector const& channelPolicies, std::vector const& completionPolicies, std::vector const& dispatchPolicies, + std::vector const& resourcePolicies, std::vector const& workflowOptions, o2::framework::ConfigContext& configContext); @@ -122,6 +125,15 @@ void doDPLException(o2::framework::RuntimeErrorRef& ref); void doUnknownException(std::string const& s); void doDefaultWorkflowTerminationHook(); +template +std::vector injectCustomizations() +{ + std::vector policies; + UserCustomizationsHelper::userDefinedCustomization(policies, 0); + auto defaultPolicies = T::createDefaultPolicies(); + policies.insert(std::end(policies), std::begin(policies), std::end(policies)); +} + int main(int argc, char** argv) { using namespace o2::framework; @@ -148,6 +160,11 @@ int main(int argc, char** argv) auto defaultDispatchPolicies = DispatchPolicy::createDefaultPolicies(); dispatchPolicies.insert(std::end(dispatchPolicies), std::begin(defaultDispatchPolicies), std::end(defaultDispatchPolicies)); + std::vector resourcePolicies; + UserCustomizationsHelper::userDefinedCustomization(resourcePolicies, 0); + auto defaultResourcePolicies = ResourcePolicy::createDefaultPolicies(); + resourcePolicies.insert(std::end(resourcePolicies), std::begin(defaultResourcePolicies), std::end(defaultResourcePolicies)); + std::vector> retrievers; std::unique_ptr retriever{new BoostOptionsRetriever(true, argc, argv)}; retrievers.emplace_back(std::move(retriever)); @@ -166,7 +183,7 @@ int main(int argc, char** argv) UserCustomizationsHelper::userDefinedCustomization(channelPolicies, 0); auto defaultChannelPolicies = ChannelConfigurationPolicy::createDefaultPolicies(configContext); channelPolicies.insert(std::end(channelPolicies), std::begin(defaultChannelPolicies), std::end(defaultChannelPolicies)); - result = doMain(argc, argv, specs, channelPolicies, completionPolicies, dispatchPolicies, workflowOptions, configContext); + result = doMain(argc, argv, specs, channelPolicies, completionPolicies, dispatchPolicies, resourcePolicies, workflowOptions, configContext); } catch (boost::exception& e) { doBoostException(e); } catch (std::exception const& error) { diff --git a/Framework/Core/src/ComputingQuotaEvaluator.cxx b/Framework/Core/src/ComputingQuotaEvaluator.cxx new file mode 100644 index 0000000000000..36b79b0419d21 --- /dev/null +++ b/Framework/Core/src/ComputingQuotaEvaluator.cxx @@ -0,0 +1,87 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "Framework/ComputingQuotaEvaluator.h" +#include + +namespace o2::framework +{ + +ComputingQuotaEvaluator::ComputingQuotaEvaluator(uv_loop_t* loop) + : mLoop{loop} +{ + // The first offer is valid, but does not contain any resource + // so this will only work with some device which does not require + // any CPU. Notice this will have troubles if a given DPL process + // runs for more than a year. + mOffers[0] = { + 0, + 0, + 0, + -1, + false, + true}; + mInfos[0] = { + uv_now(loop), + 0, + 0}; +} + +ComputingQuotaOfferRef ComputingQuotaEvaluator::selectOffer(ComputingQuotaRequest const& evaluator) +{ + int8_t bestOfferScore = -1; + int bestOfferIndex = -1; + + for (int i = 0; i != mOffers.size(); ++i) { + auto& offer = mOffers[i]; + auto& info = mInfos[i]; + + // Ignore: + // - Invalid offers + // - Used offers + // - Expired offers + if (offer.valid == false) { + continue; + } + if (offer.used == true) { + continue; + } + if (offer.runtime > 0 && offer.runtime + info.received < uv_now(mLoop)) { + continue; + } + int score = evaluator(offer); + if (score > bestOfferScore) { + bestOfferScore = score; + bestOfferIndex = i; + } + if (score == 127) { + break; + } + } + + if (bestOfferScore < 0) { + return ComputingQuotaOfferRef{-1}; + } + auto& selected = mOffers[bestOfferIndex]; + auto& info = mInfos[bestOfferIndex]; + selected.used = true; + if (info.firstUsed == 0) { + info.firstUsed = uv_now(mLoop); + } + info.lastUsed = uv_now(mLoop); + return ComputingQuotaOfferRef{bestOfferIndex}; +} + +void ComputingQuotaEvaluator::dispose(ComputingQuotaOfferRef offer) +{ + mOffers[offer.index].used = false; +} + +} // namespace o2::framework diff --git a/Framework/Core/src/DataProcessingDevice.cxx b/Framework/Core/src/DataProcessingDevice.cxx index a483a7933ce17..a02f8340ec782 100644 --- a/Framework/Core/src/DataProcessingDevice.cxx +++ b/Framework/Core/src/DataProcessingDevice.cxx @@ -14,6 +14,7 @@ #include "Framework/DataProcessingDevice.h" #include "Framework/ChannelMatching.h" #include "Framework/ControlService.h" +#include "Framework/ComputingQuotaEvaluator.h" #include "Framework/DataProcessingHeader.h" #include "Framework/DataProcessor.h" #include "Framework/DataSpecUtils.h" @@ -90,7 +91,8 @@ DataProcessingDevice::DataProcessingDevice(RunningWorkflowInfo const& runningWor mError{mSpec.algorithm.onError}, mConfigRegistry{nullptr}, mAllocator{&mTimingInfo, ®istry, mSpec.outputs}, - mServiceRegistry{registry} + mServiceRegistry{registry}, + mQuotaEvaluator{state.loop} { /// FIXME: move erro handling to a service? if (mError != nullptr) { @@ -120,6 +122,9 @@ DataProcessingDevice::DataProcessingDevice(RunningWorkflowInfo const& runningWor } }; } + // One task for now. + mStreams.resize(1); + mHandles.resize(1); } // Callback to execute the processing. Notice how the data is @@ -128,8 +133,8 @@ DataProcessingDevice::DataProcessingDevice(RunningWorkflowInfo const& runningWor void run_callback(uv_work_t* handle) { ZoneScopedN("run_callback"); - std::vector* contexes = (std::vector*)handle->data; - DataProcessorContext& context = contexes->at(0); + TaskStreamInfo* task = (TaskStreamInfo*)handle->data; + DataProcessorContext& context = *task->context; DataProcessingDevice::doPrepare(context); DataProcessingDevice::doRun(context); // FrameMark; @@ -138,6 +143,10 @@ void run_callback(uv_work_t* handle) // Once the processing in a thread is done, this is executed on the main thread. void run_completion(uv_work_t* handle, int status) { + TaskStreamInfo* task = (TaskStreamInfo*)handle->data; + DataProcessorContext& context = *task->context; + context.deviceContext->quotaEvaluator->dispose(task->offer); + task->running = false; ZoneScopedN("run_completion"); } @@ -413,16 +422,17 @@ void DataProcessingDevice::InitTask() // required parts in the DataProcessorContext. Eventually we should // do so on a per thread basis, with fine grained locks. mDataProcessorContexes.resize(1); - this->fillContext(mDataProcessorContexes.at(0)); + this->fillContext(mDataProcessorContexes.at(0), mDeviceContext); } -void DataProcessingDevice::fillContext(DataProcessorContext& context) +void DataProcessingDevice::fillContext(DataProcessorContext& context, DeviceContext& deviceContext) { context.wasActive = &mWasActive; - context.device = this; - context.spec = &mSpec; - context.state = &mState; + deviceContext.device = this; + deviceContext.spec = &mSpec; + deviceContext.state = &mState; + deviceContext.quotaEvaluator = &mQuotaEvaluator; context.relayer = mRelayer; context.registry = &mServiceRegistry; @@ -433,6 +443,7 @@ void DataProcessingDevice::fillContext(DataProcessorContext& context) context.statefulProcess = &mStatefulProcess; context.statelessProcess = &mStatelessProcess; context.error = &mError; + context.deviceContext = &deviceContext; /// Callback for the error handling context.errorHandling = &mErrorHandling; } @@ -462,8 +473,8 @@ bool DataProcessingDevice::ConditionalRun() TracyPlot("past activity", (int64_t)mWasActive); mServiceRegistry.get().flushPending(); auto shouldNotWait = (mWasActive && - (mDataProcessorContexes.at(0).state->streaming != StreamingState::Idle) && (mState.activeSignals.empty())) || - (mDataProcessorContexes.at(0).state->streaming == StreamingState::EndOfStreaming); + (mState.streaming != StreamingState::Idle) && (mState.activeSignals.empty())) || + (mState.streaming == StreamingState::EndOfStreaming); if (NewStatePending()) { shouldNotWait = true; } @@ -471,7 +482,7 @@ bool DataProcessingDevice::ConditionalRun() uv_run(mState.loop, shouldNotWait ? UV_RUN_NOWAIT : UV_RUN_ONCE); TracyPlot("loopReason", (int64_t)(uint64_t)mState.loopReason); - mDataProcessorContexes.at(0).state->loopReason = DeviceState::NO_REASON; + mState.loopReason = DeviceState::NO_REASON; // A new state was requested, we exit. if (NewStatePending()) { @@ -491,12 +502,43 @@ bool DataProcessingDevice::ConditionalRun() } } } - // Synchronous execution of the callbacks. This will be moved in the - // moved in the on_socket_polled once we have threading in place. - uv_work_t handle; - handle.data = &mDataProcessorContexes; - run_callback(&handle); - run_completion(&handle, 0); + + assert(mStreams.size() == mHandles.size()); + /// Decide which task to use + TaskStreamRef streamRef{-1}; + for (int ti = 0; ti < mStreams.size(); ti++) { + auto& taskInfo = mStreams[ti]; + if (taskInfo.running) { + continue; + } + streamRef.index = ti; + } + // We have an empty stream, let's check if we have enough + // resources for it to run something + if (streamRef.index != -1) { + // Synchronous execution of the callbacks. This will be moved in the + // moved in the on_socket_polled once we have threading in place. + auto& handle = mHandles[streamRef.index]; + auto& stream = mStreams[streamRef.index]; + handle.data = &mStreams[streamRef.index]; + + // Deciding wether to run or not can be done by passing a request to + // the evaluator. In this case, the request is always satisfied and + // we run on whatever resource is available. + ComputingQuotaOfferRef offer = mQuotaEvaluator.selectOffer(mSpec.resourcePolicy.request); + + if (offer.index != -1) { + stream.offer = offer; + stream.running = true; + stream.context = &mDataProcessorContexes.at(0); + run_callback(&handle); + run_completion(&handle, 0); + } else { + mWasActive = false; + } + } else { + mWasActive = false; + } FrameMark; return true; } @@ -519,13 +561,13 @@ void DataProcessingDevice::doPrepare(DataProcessorContext& context) // expect to receive an EndOfStream signal. Thus we do not wait for these // to be completed. In the case of data source devices, as they do not have // real data input channels, they have to signal EndOfStream themselves. - context.allDone = std::any_of(context.state->inputChannelInfos.begin(), context.state->inputChannelInfos.end(), [](const auto& info) { + context.allDone = std::any_of(context.deviceContext->state->inputChannelInfos.begin(), context.deviceContext->state->inputChannelInfos.end(), [](const auto& info) { return info.state != InputChannelState::Pull; }); // Whether or not all the channels are completed - for (size_t ci = 0; ci < context.spec->inputChannels.size(); ++ci) { - auto& channel = context.spec->inputChannels[ci]; - auto& info = context.state->inputChannelInfos[ci]; + for (size_t ci = 0; ci < context.deviceContext->spec->inputChannels.size(); ++ci) { + auto& channel = context.deviceContext->spec->inputChannels[ci]; + auto& info = context.deviceContext->state->inputChannelInfos[ci]; if (info.state != InputChannelState::Completed && info.state != InputChannelState::Pull) { context.allDone = false; @@ -535,7 +577,7 @@ void DataProcessingDevice::doPrepare(DataProcessorContext& context) } int64_t result = -2; if (info.channel == nullptr) { - info.channel = &context.device->GetChannel(channel.name, 0); + info.channel = &context.deviceContext->device->GetChannel(channel.name, 0); } auto& socket = info.channel->GetSocket(); // If we have pending events from a previous iteration, @@ -581,14 +623,14 @@ void DataProcessingDevice::doPrepare(DataProcessorContext& context) void DataProcessingDevice::doRun(DataProcessorContext& context) { - auto switchState = [& registry = context.registry, - &state = context.state](StreamingState newState) { + auto switchState = [®istry = context.registry, + &state = context.deviceContext->state](StreamingState newState) { LOG(debug) << "New state " << (int)newState << " old state " << (int)state->streaming; state->streaming = newState; registry->get().notifyStreamingState(state->streaming); }; - if (context.state->streaming == StreamingState::Idle) { + if (context.deviceContext->state->streaming == StreamingState::Idle) { return; } @@ -613,12 +655,12 @@ void DataProcessingDevice::doRun(DataProcessorContext& context) // callback and return false. Notice that what happens next is actually // dependent on the callback, not something which is controlled by the // framework itself. - if (context.allDone == true && context.state->streaming == StreamingState::Streaming) { + if (context.allDone == true && context.deviceContext->state->streaming == StreamingState::Streaming) { switchState(StreamingState::EndOfStreaming); *context.wasActive = true; } - if (context.state->streaming == StreamingState::EndOfStreaming) { + if (context.deviceContext->state->streaming == StreamingState::EndOfStreaming) { // We keep processing data until we are Idle. // FIXME: not sure this is the correct way to drain the queues, but // I guess we will see. @@ -631,8 +673,8 @@ void DataProcessingDevice::doRun(DataProcessorContext& context) context.registry->get()(CallbackService::Id::EndOfStream, eosContext); context.registry->postEOSCallbacks(eosContext); - for (auto& channel : context.spec->outputChannels) { - DataProcessingHelpers::sendEndOfStream(*context.device, channel); + for (auto& channel : context.deviceContext->spec->outputChannels) { + DataProcessingHelpers::sendEndOfStream(*context.deviceContext->device, channel); } // This is needed because the transport is deleted before the device. context.relayer->clear(); @@ -656,12 +698,12 @@ void DataProcessingDevice::ResetTask() void DataProcessingDevice::handleData(DataProcessorContext& context, FairMQParts& parts, InputChannelInfo& info) { ZoneScopedN("DataProcessingDevice::handleData"); - assert(context.spec->inputChannels.empty() == false); + assert(context.deviceContext->spec->inputChannels.empty() == false); assert(parts.Size() > 0); // Initial part. Let's hide all the unnecessary and have // simple lambdas for each of the steps I am planning to have. - assert(!context.spec->inputs.empty()); + assert(!context.deviceContext->spec->inputs.empty()); enum struct InputType { Invalid, @@ -842,8 +884,8 @@ bool DataProcessingDevice::tryDispatchComputation(DataProcessorContext& context, // This is needed to convert from a pair of pointers to an actual DataRef // and to make sure the ownership is moved from the cache in the relayer to // the execution. - auto fillInputs = [& relayer = context.relayer, - &spec = context.spec, + auto fillInputs = [&relayer = context.relayer, + &spec = context.deviceContext->spec, ¤tSetOfInputs](TimesliceSlot slot) -> InputRecord { currentSetOfInputs = std::move(relayer->getInputsForTimeslice(slot)); auto getter = [¤tSetOfInputs](size_t i, size_t partindex) -> DataRef { @@ -924,8 +966,8 @@ bool DataProcessingDevice::tryDispatchComputation(DataProcessorContext& context, // to the next one in the daisy chain. // FIXME: do it in a smarter way than O(N^2) auto forwardInputs = [&reportError, - &spec = context.spec, - &device = context.device, ¤tSetOfInputs](TimesliceSlot slot, InputRecord& record) { + &spec = context.deviceContext->spec, + &device = context.deviceContext->device, ¤tSetOfInputs](TimesliceSlot slot, InputRecord& record) { ZoneScopedN("forward inputs"); assert(record.size() == currentSetOfInputs.size()); // we collect all messages per forward in a map and send them together @@ -997,8 +1039,8 @@ bool DataProcessingDevice::tryDispatchComputation(DataProcessorContext& context, } }; - auto switchState = [& control = context.registry->get(), - &state = context.state](StreamingState newState) { + auto switchState = [&control = context.registry->get(), + &state = context.deviceContext->state](StreamingState newState) { state->streaming = newState; control.notifyStreamingState(state->streaming); }; @@ -1047,7 +1089,7 @@ bool DataProcessingDevice::tryDispatchComputation(DataProcessorContext& context, } if (action.op == CompletionPolicy::CompletionOp::Discard) { context.registry->postDispatchingCallbacks(processContext); - if (context.spec->forwards.empty() == false) { + if (context.deviceContext->spec->forwards.empty() == false) { forwardInputs(action.slot, record); continue; } @@ -1057,7 +1099,7 @@ bool DataProcessingDevice::tryDispatchComputation(DataProcessorContext& context, uint64_t tStart = uv_hrtime(); preUpdateStats(action, record, tStart); try { - if (context.state->quitRequested == false) { + if (context.deviceContext->state->quitRequested == false) { if (*context.statefulProcess) { ZoneScopedN("statefull process"); @@ -1090,7 +1132,7 @@ bool DataProcessingDevice::tryDispatchComputation(DataProcessorContext& context, // we keep them for next message arriving. if (action.op == CompletionPolicy::CompletionOp::Consume) { context.registry->postDispatchingCallbacks(processContext); - if (context.spec->forwards.empty() == false) { + if (context.deviceContext->spec->forwards.empty() == false) { forwardInputs(action.slot, record); } #ifdef TRACY_ENABLE @@ -1101,9 +1143,9 @@ bool DataProcessingDevice::tryDispatchComputation(DataProcessorContext& context, } } // We now broadcast the end of stream if it was requested - if (context.state->streaming == StreamingState::EndOfStreaming) { - for (auto& channel : context.spec->outputChannels) { - DataProcessingHelpers::sendEndOfStream(*context.device, channel); + if (context.deviceContext->state->streaming == StreamingState::EndOfStreaming) { + for (auto& channel : context.deviceContext->spec->outputChannels) { + DataProcessingHelpers::sendEndOfStream(*context.deviceContext->device, channel); } switchState(StreamingState::Idle); } diff --git a/Framework/Core/src/DeviceSpecHelpers.cxx b/Framework/Core/src/DeviceSpecHelpers.cxx index 314007373fcfc..8fa37d78c9d03 100644 --- a/Framework/Core/src/DeviceSpecHelpers.cxx +++ b/Framework/Core/src/DeviceSpecHelpers.cxx @@ -737,6 +737,7 @@ void DeviceSpecHelpers::dataProcessorSpecs2DeviceSpecs(const WorkflowSpec& workf std::vector const& channelPolicies, std::vector const& completionPolicies, std::vector const& dispatchPolicies, + std::vector const& resourcePolicies, std::vector& devices, ResourceManager& resourceManager, std::string const& uniqueWorkflowId, @@ -816,6 +817,17 @@ void DeviceSpecHelpers::dataProcessorSpecs2DeviceSpecs(const WorkflowSpec& workf break; } } + bool hasPolicy = false; + for (auto& policy : resourcePolicies) { + if (policy.matcher(device) == true) { + device.resourcePolicy = policy; + hasPolicy = true; + break; + } + } + if (hasPolicy == false) { + throw runtime_error_f("Unable to find a resource policy for %s", device.id.c_str()); + } } for (auto& device : devices) { diff --git a/Framework/Core/src/DeviceSpecHelpers.h b/Framework/Core/src/DeviceSpecHelpers.h index 92a3b65ddae4e..61ba0d4a779b1 100644 --- a/Framework/Core/src/DeviceSpecHelpers.h +++ b/Framework/Core/src/DeviceSpecHelpers.h @@ -45,6 +45,7 @@ struct DeviceSpecHelpers { std::vector const& channelPolicies, std::vector const& completionPolicies, std::vector const& dispatchPolicies, + std::vector const& resourcePolicies, std::vector& devices, ResourceManager& resourceManager, std::string const& uniqueWorkflowId, @@ -64,8 +65,11 @@ struct DeviceSpecHelpers { std::string const& channelPrefix = "") { std::vector dispatchPolicies = DispatchPolicy::createDefaultPolicies(); + std::vector resourcePolicies = ResourcePolicy::createDefaultPolicies(); dataProcessorSpecs2DeviceSpecs(workflow, channelPolicies, completionPolicies, - dispatchPolicies, devices, resourceManager, uniqueWorkflowId, optimizeTopology, resourcesMonitoringInterval, channelPrefix); + dispatchPolicies, resourcePolicies, devices, + resourceManager, uniqueWorkflowId, optimizeTopology, + resourcesMonitoringInterval, channelPrefix); } /// Helper to provide the channel configuration string for an input channel diff --git a/Framework/Core/src/ResourcePolicy.cxx b/Framework/Core/src/ResourcePolicy.cxx new file mode 100644 index 0000000000000..7c533dbc535ee --- /dev/null +++ b/Framework/Core/src/ResourcePolicy.cxx @@ -0,0 +1,24 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "Framework/ResourcePolicy.h" +#include "Framework/ResourcePolicyHelpers.h" +#include + +namespace o2::framework +{ + +std::vector ResourcePolicy::createDefaultPolicies() +{ + return { + ResourcePolicyHelpers::trivialTask(".*")}; +} + +} // namespace o2::framework diff --git a/Framework/Core/src/ResourcePolicyHelpers.cxx b/Framework/Core/src/ResourcePolicyHelpers.cxx new file mode 100644 index 0000000000000..a0c5e2d2e8549 --- /dev/null +++ b/Framework/Core/src/ResourcePolicyHelpers.cxx @@ -0,0 +1,53 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "Framework/ResourcePolicyHelpers.h" +#include "Framework/DeviceSpec.h" +#include "ResourcesMonitoringHelper.h" + +#include +#include + +namespace o2::framework +{ + +/// A trivial task is a task which will execute regardless of +/// the resources available. +ResourcePolicy ResourcePolicyHelpers::trivialTask(char const* s) +{ + return ResourcePolicy{ + "trivial", + [matcher = std::regex(s)](DeviceSpec const& spec) -> bool { + return std::regex_match(spec.name, matcher); + }, + [](ComputingQuotaOffer const&) { return 127; }}; +} + +ResourcePolicy ResourcePolicyHelpers::cpuBoundTask(char const* s, int maxCPUs) +{ + return ResourcePolicy{ + "cpu-bound", + [matcher = std::regex(s)](DeviceSpec const& spec) -> bool { + return std::regex_match(spec.name, matcher); + }, + [maxCPUs](ComputingQuotaOffer const& offer) -> int8_t { return offer.cpu >= maxCPUs ? 127 : 0; }}; +} + +ResourcePolicy ResourcePolicyHelpers::sharedMemoryBoundTask(char const* s, int maxSharedMemory) +{ + return ResourcePolicy{ + "shm-bound", + [matcher = std::regex(s)](DeviceSpec const& spec) -> bool { + return std::regex_match(spec.name, matcher); + }, + [maxSharedMemory](ComputingQuotaOffer const& offer) -> int8_t { return offer.sharedMemory >= maxSharedMemory ? 127 : 0; }}; +} + +} // namespace o2::framework diff --git a/Framework/Core/src/runDataProcessing.cxx b/Framework/Core/src/runDataProcessing.cxx index 2d5ae7f567858..5e0940ec3db41 100644 --- a/Framework/Core/src/runDataProcessing.cxx +++ b/Framework/Core/src/runDataProcessing.cxx @@ -1358,6 +1358,7 @@ int runStateMachine(DataProcessorSpecs const& workflow, driverInfo.channelPolicies, driverInfo.completionPolicies, driverInfo.dispatchPolicies, + driverInfo.resourcePolicies, runningWorkflow.devices, *resourceManager, driverInfo.uniqueWorkflowId, @@ -2028,6 +2029,7 @@ int doMain(int argc, char** argv, o2::framework::WorkflowSpec const& workflow, std::vector const& channelPolicies, std::vector const& completionPolicies, std::vector const& dispatchPolicies, + std::vector const& resourcePolicies, std::vector const& currentWorkflowOptions, o2::framework::ConfigContext& configContext) { @@ -2269,6 +2271,7 @@ int doMain(int argc, char** argv, o2::framework::WorkflowSpec const& workflow, driverInfo.channelPolicies = channelPolicies; driverInfo.completionPolicies = completionPolicies; driverInfo.dispatchPolicies = dispatchPolicies; + driverInfo.resourcePolicies = resourcePolicies; driverInfo.argc = argc; driverInfo.argv = argv; driverInfo.batch = varmap["no-batch"].defaulted() ? varmap["batch"].as() : false; From 2d8a93a94d78954389d8fdb0d756dc92d835c95a Mon Sep 17 00:00:00 2001 From: ALICE Builder Date: Sat, 8 May 2021 09:21:33 +0200 Subject: [PATCH 457/770] Please consider the following formatting changes (#84) --- Framework/Core/include/Framework/ComputingQuotaEvaluator.h | 1 - 1 file changed, 1 deletion(-) diff --git a/Framework/Core/include/Framework/ComputingQuotaEvaluator.h b/Framework/Core/include/Framework/ComputingQuotaEvaluator.h index 41aed693e2fb9..3a0928d8633f1 100644 --- a/Framework/Core/include/Framework/ComputingQuotaEvaluator.h +++ b/Framework/Core/include/Framework/ComputingQuotaEvaluator.h @@ -22,7 +22,6 @@ typedef struct uv_loop_s uv_loop_t; namespace o2::framework { - class ComputingQuotaEvaluator { // Maximum number of offers this evaluator can hold From 51a8f468158dee953d4a69c1c3b76f90d65b4f90 Mon Sep 17 00:00:00 2001 From: Antonio FRANCO Date: Sun, 9 May 2021 11:12:17 +0200 Subject: [PATCH 458/770] Fix for HMPID raw to digits stream converter, now works with entropy encoder (#6069) --- Detectors/HMPID/workflow/CMakeLists.txt | 1 + .../include/HMPIDWorkflow/DataDecoderSpec2.h | 54 +++ .../HMPID/workflow/src/DataDecoderSpec2.cxx | 351 ++++++++++++++++++ .../HMPID/workflow/src/DumpDigitsSpec.cxx | 33 +- .../HMPID/workflow/src/WriteRawFileSpec.cxx | 19 +- .../src/raw-to-digits-stream-workflow.cxx | 4 +- 6 files changed, 436 insertions(+), 26 deletions(-) create mode 100644 Detectors/HMPID/workflow/include/HMPIDWorkflow/DataDecoderSpec2.h create mode 100644 Detectors/HMPID/workflow/src/DataDecoderSpec2.cxx diff --git a/Detectors/HMPID/workflow/CMakeLists.txt b/Detectors/HMPID/workflow/CMakeLists.txt index ad101cb219cd4..1eda85c5bc257 100644 --- a/Detectors/HMPID/workflow/CMakeLists.txt +++ b/Detectors/HMPID/workflow/CMakeLists.txt @@ -10,6 +10,7 @@ o2_add_library(HMPIDWorkflow SOURCES src/DataDecoderSpec.cxx + src/DataDecoderSpec2.cxx src/DigitsToRawSpec.cxx src/DumpDigitsSpec.cxx src/PedestalsCalculationSpec.cxx diff --git a/Detectors/HMPID/workflow/include/HMPIDWorkflow/DataDecoderSpec2.h b/Detectors/HMPID/workflow/include/HMPIDWorkflow/DataDecoderSpec2.h new file mode 100644 index 0000000000000..bc87676d9bfcb --- /dev/null +++ b/Detectors/HMPID/workflow/include/HMPIDWorkflow/DataDecoderSpec2.h @@ -0,0 +1,54 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#ifndef DETECTORS_HMPID_WORKFLOW_INCLUDE_HMPIDWORKFLOW_DATADECODERSPEC_H_ +#define DETECTORS_HMPID_WORKFLOW_INCLUDE_HMPIDWORKFLOW_DATADECODERSPEC_H_ + +#include "Framework/DataProcessorSpec.h" +#include "Framework/Task.h" + +#include "DataFormatsHMP/Trigger.h" +#include "HMPIDBase/Common.h" +#include "HMPIDReconstruction/HmpidDecoder2.h" + +namespace o2 +{ +namespace hmpid +{ + +class DataDecoderTask2 : public framework::Task +{ + public: + DataDecoderTask2() = default; + ~DataDecoderTask2() override = default; + void init(framework::InitContext& ic) final; + void run(framework::ProcessingContext& pc) final; + void decodeTF(framework::ProcessingContext& pc); + void decodeReadout(framework::ProcessingContext& pc); + void decodeRawFile(framework::ProcessingContext& pc); + void endOfStream(framework::EndOfStreamContext& ec) override; + void orderTriggers(); + + private: + HmpidDecoder2* mDeco; + long mTotalDigits; + long mTotalFrames; + std::string mRootStatFile; + bool mFastAlgorithm; + + ExecutionTimer mExTimer; + std::vector mTriggers; +}; + +o2::framework::DataProcessorSpec getDecodingSpec2(bool askSTFDist); +} // end namespace hmpid +} // end namespace o2 + +#endif diff --git a/Detectors/HMPID/workflow/src/DataDecoderSpec2.cxx b/Detectors/HMPID/workflow/src/DataDecoderSpec2.cxx new file mode 100644 index 0000000000000..5e0c3f55dcc02 --- /dev/null +++ b/Detectors/HMPID/workflow/src/DataDecoderSpec2.cxx @@ -0,0 +1,351 @@ +// Copyright CERN and copyright holders of ALICE O2. This software is +// distributed under the terms of the GNU General Public License v3 (GPL +// Version 3), copied verbatim in the file "COPYING". +// +// See http://alice-o2.web.cern.ch/license for full licensing information. +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file DataDecoderSpec.cxx +/// \author Antonio Franco - INFN Bari +/// \version 1.0 +/// \date 01 feb 2021 +/// \brief Implementation of a data processor to run the HMPID raw decoding +/// + +#include +#include +#include +#include +#include +#include +#include + +#include "TTree.h" +#include "TFile.h" + +#include + +#include "Framework/CallbackService.h" +#include "Framework/ConfigParamRegistry.h" +#include "Framework/ControlService.h" +#include "Framework/DataProcessorSpec.h" +#include "Framework/Lifetime.h" +#include "Framework/Output.h" +#include "Framework/Task.h" +#include "Framework/WorkflowSpec.h" +#include "Framework/Logger.h" +#include "Framework/InputRecordWalker.h" + +#include "Headers/RAWDataHeader.h" +#include "DetectorsRaw/RDHUtils.h" +#include "DPLUtils/DPLRawParser.h" + +#include "DataFormatsHMP/Digit.h" +#include "DataFormatsHMP/Trigger.h" +#include "HMPIDBase/Geo.h" +#include "HMPIDReconstruction/HmpidDecoder2.h" +#include "HMPIDWorkflow/DataDecoderSpec2.h" + +namespace o2 +{ +namespace hmpid +{ + +using namespace o2; +using namespace o2::framework; +using RDH = o2::header::RDHAny; + +//======================= +// Data decoder +void DataDecoderTask2::init(framework::InitContext& ic) +{ + + LOG(INFO) << "[HMPID Data Decoder - Init] ( create Raw Stream Decoder for " << Geo::MAXEQUIPMENTS << " equipments !"; + + mRootStatFile = ic.options().get("result-file"); + mFastAlgorithm = ic.options().get("fast-decode"); + mDeco = new o2::hmpid::HmpidDecoder2(Geo::MAXEQUIPMENTS); + mDeco->init(); + mTotalDigits = 0; + mTotalFrames = 0; + + mExTimer.start(); + return; +} + +void DataDecoderTask2::run(framework::ProcessingContext& pc) +{ + mDeco->mDigits.clear(); + mTriggers.clear(); + LOG(INFO) << "[HMPID Data Decoder - Run] !"; + + decodeTF(pc); + // TODO: accept other types of Raw Streams ... + // decodeReadout(pc); + // decodeRawFile(pc); + + mExTimer.elapseMes("Decoding... Digits decoded = " + std::to_string(mTotalDigits) + " Frames received = " + std::to_string(mTotalFrames)); + return; +} + +void DataDecoderTask2::endOfStream(framework::EndOfStreamContext& ec) +{ + // Output the Digits/Triggers vector + orderTriggers(); + ec.outputs().snapshot(o2::framework::Output{"HMP", "DIGITS", 0, o2::framework::Lifetime::Timeframe}, mDeco->mDigits); + ec.outputs().snapshot(o2::framework::Output{"HMP", "INTRECORDS", 0, o2::framework::Lifetime::Timeframe}, mTriggers); + + // Records the statistics + float avgEventSize; //[o2::hmpid::Geo::MAXEQUIPMENTS]; + float avgBusyTime; //[o2::hmpid::Geo::MAXEQUIPMENTS]; + float numOfSamples; //[o2::hmpid::Geo::N_MODULES][o2::hmpid::Geo::N_YCOLS][o2::hmpid::Geo::N_XROWS]; + float sumOfCharges; //[o2::hmpid::Geo::N_MODULES][o2::hmpid::Geo::N_YCOLS][o2::hmpid::Geo::N_XROWS]; + float squareOfCharges; //[o2::hmpid::Geo::N_MODULES][o2::hmpid::Geo::N_YCOLS][o2::hmpid::Geo::N_XROWS]; + float xb; + float yb; + + TString filename = TString::Format("%s_stat.root", mRootStatFile.c_str()); + LOG(INFO) << "Create the stat file " << filename.Data(); + TFile mfileOut(TString::Format("%s", filename.Data()), "RECREATE"); + TTree* theObj[Geo::N_MODULES + 1]; + for (int i = 0; i < Geo::N_MODULES; i++) { // Create the TTree array + TString tit = TString::Format("HMPID Data Decoding Statistic results Mod=%d", i); + theObj[i] = new TTree("o2hmp", tit); + theObj[i]->Branch("x", &xb, "s"); + theObj[i]->Branch("y", &yb, "s"); + theObj[i]->Branch("Samples", &numOfSamples, "i"); + theObj[i]->Branch("Sum_of_charges", &sumOfCharges, "l"); + theObj[i]->Branch("Sum_of_square", &squareOfCharges, "l"); + } + theObj[Geo::N_MODULES] = new TTree("o2hmp", "HMPID Data Decoding Statistic results"); + theObj[Geo::N_MODULES]->Branch("Average_Event_Size", &avgEventSize, "F"); + theObj[Geo::N_MODULES]->Branch("Average_Busy_Time", &avgBusyTime, "F"); + + // Update the Stat for the Decoding + int numEqui = mDeco->getNumberOfEquipments(); + // cycle in order to update info for the last event + for (int i = 0; i < numEqui; i++) { + if (mDeco->mTheEquipments[i]->mNumberOfEvents > 0) { + mDeco->updateStatistics(mDeco->mTheEquipments[i]); + } + } + char summaryFileName[254]; + sprintf(summaryFileName, "%s_stat.txt", mRootStatFile.c_str()); + mDeco->writeSummaryFile(summaryFileName); + for (int e = 0; e < numEqui; e++) { + avgEventSize = mDeco->getAverageEventSize(e); + avgBusyTime = mDeco->getAverageBusyTime(e); + theObj[Geo::N_MODULES]->Fill(); + } + for (int m = 0; m < o2::hmpid::Geo::N_MODULES; m++) { + for (int y = 0; y < o2::hmpid::Geo::N_YCOLS; y++) { + for (int x = 0; x < o2::hmpid::Geo::N_XROWS; x++) { + xb = x; + yb = y; + numOfSamples = mDeco->getPadSamples(m, x, y); + sumOfCharges = mDeco->getPadSum(m, x, y); + squareOfCharges = mDeco->getPadSquares(m, x, y); + theObj[m]->Fill(); + } + } + } + for (int i = 0; i <= Geo::N_MODULES; i++) { + theObj[i]->Write(); + } + + mExTimer.logMes("End the Decoding ! Digits decoded = " + std::to_string(mTotalDigits) + " Frames received = " + std::to_string(mTotalFrames)); + mExTimer.stop(); + return; +} +//_________________________________________________________________________________________________ +// the decodeTF() function processes the the messages generated by the (sub)TimeFrame builder +void DataDecoderTask2::decodeTF(framework::ProcessingContext& pc) +{ + LOG(INFO) << "*********** In decodeTF **************"; + + // get the input buffer + auto& inputs = pc.inputs(); + + // if we see requested data type input with 0xDEADBEEF subspec and 0 payload this means that the "delayed message" + // mechanism created it in absence of real data from upstream. Processor should send empty output to not block the workflow + { + std::vector dummy{InputSpec{"dummy", ConcreteDataMatcher{"HMP", "RAWDATA", 0xDEADBEEF}}}; + for (const auto& ref : InputRecordWalker(inputs, dummy)) { + const auto dh = o2::framework::DataRefUtils::getHeader(ref); + if (dh->payloadSize == 0) { + LOGP(WARNING, "Found input [{}/{}/{:#x}] TF#{} 1st_orbit:{} Payload {} : assuming no payload for all links in this TF", + dh->dataOrigin.str, dh->dataDescription.str, dh->subSpecification, dh->tfCounter, dh->firstTForbit, dh->payloadSize); + return; + } + } + } + + DPLRawParser parser(inputs, o2::framework::select("TF:HMP/RAWDATA")); + //mDeco->mDigits.clear(); + for (auto it = parser.begin(), end = parser.end(); it != end; ++it) { + int pointerToTheFirst = mDeco->mDigits.size(); + uint32_t* theBuffer = (uint32_t*)it.raw(); + mDeco->setUpStream(theBuffer, it.size() + it.offset()); + try { + if (mFastAlgorithm) { + mDeco->decodePageFast(&theBuffer); + } else { + mDeco->decodePage(&theBuffer); + } + } catch (int e) { + // The stream end ! + LOG(INFO) << "End Page decoding !"; + } + // std::cout << ">>>>" << pointerToTheFirst << "," << mDeco->mDigits.size() << std::endl; + mTriggers.push_back(o2::hmpid::Trigger(mDeco->mIntReco, pointerToTheFirst, mDeco->mDigits.size() - pointerToTheFirst)); + mTotalFrames++; + } + + //pc.outputs().snapshot(o2::framework::Output{"HMP", "DIGITS", 0, o2::framework::Lifetime::Timeframe}, mDeco->mDigits); + //pc.outputs().snapshot(o2::framework::Output{"HMP", "INTRECORDS", 0, o2::framework::Lifetime::Timeframe}, mDeco->mIntReco); + + mTotalDigits += mDeco->mDigits.size(); + LOG(INFO) << "Writing Digitis=" << mDeco->mDigits.size() << "/" << mTotalDigits << " Frame=" << mTotalFrames << " IntRec " << mDeco->mIntReco; + return; +} + +//_________________________________________________________________________________________________ +// the decodeReadout() function processes the messages generated by o2-mch-cru-page-reader-workflow +// TODO: rearrange, test +void DataDecoderTask2::decodeReadout(framework::ProcessingContext& pc) +{ + LOG(INFO) << "*********** In decode readout **************"; + + // get the input buffer + auto& inputs = pc.inputs(); + DPLRawParser parser(inputs, o2::framework::select("readout:HMP/RAWDATA")); + // DPLRawParser parser(inputs, o2::framework::select("HMP/readout")); + + for (auto it = parser.begin(), end = parser.end(); it != end; ++it) { + uint32_t* theBuffer = (uint32_t*)it.raw(); + mDeco->setUpStream(theBuffer, it.size() + it.offset()); + try { + if (mFastAlgorithm) { + mDeco->decodePageFast(&theBuffer); + } else { + mDeco->decodePage(&theBuffer); + } + } catch (int e) { + // The stream end ! + LOG(DEBUG) << "End Page decoding !"; + } + } + return; +} + +// the decodeReadout() function processes the messages generated by o2-mch-cru-page-reader-workflow +// TODO: rearrange, test +void DataDecoderTask2::decodeRawFile(framework::ProcessingContext& pc) +{ + LOG(INFO) << "*********** In decode rawfile **************"; + + for (auto&& input : pc.inputs()) { + if (input.spec->binding == "file") { + const header::DataHeader* header = o2::header::get(input.header); + if (!header) { + return; + } + + auto const* raw = input.payload; + size_t payloadSize = header->payloadSize; + + LOG(INFO) << " payloadSize=" << payloadSize; + if (payloadSize == 0) { + return; + } + + uint32_t* theBuffer = (uint32_t*)input.payload; + int pagesize = header->payloadSize; + mDeco->setUpStream(theBuffer, pagesize); + try { + if (mFastAlgorithm) { + mDeco->decodePageFast(&theBuffer); + } else { + mDeco->decodePage(&theBuffer); + } + } catch (int e) { + // The stream end ! + LOG(DEBUG) << "End Page decoding !"; + } + } + } + return; +} + +void DataDecoderTask2::orderTriggers() +{ + std::vector dig; + dig.clear(); + std::vector trg; + trg.clear(); + + // first arrange the triggers in chronological order + std::sort(mTriggers.begin(), mTriggers.end()); + // then build a new Digit Vector physically ordered for triggers + int i = 0; + int k = i; + o2::hmpid::Trigger tr; + int count = 0; + int firstEntry; + while (i < mTriggers.size()) { + tr = mTriggers[i]; + count = 0; + firstEntry = dig.size(); + while (k < mTriggers.size() && mTriggers[i].getTriggerID() == mTriggers[k].getTriggerID()) { + for (int j = mTriggers[k].getFirstEntry(); j <= mTriggers[k].getLastEntry(); j++) { + dig.push_back(mDeco->mDigits[j]); + count++; + } + k++; + } + tr.setDataRange(firstEntry, count); + trg.push_back(tr); + i = k; + } + + // then arrange the triggers in chamber order + for (int i = 0; i < trg.size(); i++) { + if (trg[i].getFirstEntry() > trg[i].getLastEntry()) { + continue; + } + std::sort(dig.begin() + trg[i].getFirstEntry(), dig.begin() + trg[i].getLastEntry()); + } + + mTriggers.swap(trg); + mDeco->mDigits.swap(dig); + trg.clear(); + dig.clear(); +} + +//_________________________________________________________________________________________________ +o2::framework::DataProcessorSpec getDecodingSpec2(bool askDISTSTF) +{ + std::vector inputs; + inputs.emplace_back("TF", o2::framework::ConcreteDataTypeMatcher{"HMP", "RAWDATA"}, o2::framework::Lifetime::Optional); + if (askDISTSTF) { + inputs.emplace_back("stdDist", "FLP", "DISTSUBTIMEFRAME", 0, Lifetime::Timeframe); + } + + std::vector outputs; + outputs.emplace_back("HMP", "DIGITS", 0, o2::framework::Lifetime::Timeframe); + outputs.emplace_back("HMP", "INTRECORDS", 0, o2::framework::Lifetime::Timeframe); + + return DataProcessorSpec{ + "HMP-RawStreamDecoder", + inputs, + outputs, + AlgorithmSpec{adaptFromTask()}, + Options{{"result-file", VariantType::String, "/tmp/hmpRawDecodeResults", {"Base name of the decoding results files."}}, + {"fast-decode", VariantType::Bool, false, {"Use the fast algorithm. (error 0.8%)"}}}}; +} + +} // namespace hmpid +} // end namespace o2 diff --git a/Detectors/HMPID/workflow/src/DumpDigitsSpec.cxx b/Detectors/HMPID/workflow/src/DumpDigitsSpec.cxx index f2446b83b65e6..069f5bcac1ce2 100644 --- a/Detectors/HMPID/workflow/src/DumpDigitsSpec.cxx +++ b/Detectors/HMPID/workflow/src/DumpDigitsSpec.cxx @@ -40,6 +40,7 @@ #include "DPLUtils/DPLRawParser.h" #include "DataFormatsHMP/Digit.h" +#include "DataFormatsHMP/Trigger.h" #include "HMPIDBase/Geo.h" #include "HMPIDWorkflow/DumpDigitsSpec.h" @@ -84,34 +85,36 @@ void DumpDigitsTask::init(framework::InitContext& ic) void DumpDigitsTask::run(framework::ProcessingContext& pc) { - LOG(DEBUG) << "[HMPID Dump Digits - run() ] Enter Dump ..."; + LOG(INFO) << "[HMPID Dump Digits - run() ] Enter Dump ..."; + std::vector triggers; + std::vector digits; for (auto const& ref : InputRecordWalker(pc.inputs())) { if (DataRefUtils::match(ref, {"check", ConcreteDataTypeMatcher{gDataOriginHMP, "INTRECORDS"}})) { - o2::InteractionRecord intReco = pc.inputs().get(ref); - if (mPrintDigits) { - std::cout << "Trigger Event Orbit = " << intReco.orbit << " BC = " << intReco.bc << std::endl; - } - if (mIsOutputOnFile) { - mOsFile << "Trigger Event Orbit = " << intReco.orbit << " BC = " << intReco.bc << std::endl; - } + triggers = pc.inputs().get>(ref); + LOG(INFO) << "We receive triggers =" << triggers.size(); } if (DataRefUtils::match(ref, {"check", ConcreteDataTypeMatcher{gDataOriginHMP, "DIGITS"}})) { - std::vector digits = pc.inputs().get>(ref); - LOG(DEBUG) << "The size of the vector =" << digits.size(); + digits = pc.inputs().get>(ref); + LOG(INFO) << "The size of the vector =" << digits.size(); mDigitsReceived += digits.size(); + } + for (int i = 0; i < triggers.size(); i++) { if (mPrintDigits) { - for (o2::hmpid::Digit Dig : digits) { - std::cout << Dig << std::endl; + std::cout << "Trigger Event Orbit = " << triggers[i].getOrbit() << " BC = " << triggers[i].getBc() << std::endl; + for (int j = triggers[i].getFirstEntry(); j <= triggers[i].getLastEntry(); j++) { + std::cout << digits[j] << std::endl; } } if (mIsOutputOnFile) { - for (o2::hmpid::Digit Dig : digits) { - mOsFile << Dig << std::endl; + mOsFile << "Trigger Event Orbit = " << triggers[i].getOrbit() << " BC = " << triggers[i].getBc() << std::endl; + for (int j = triggers[i].getFirstEntry(); j <= triggers[i].getLastEntry(); j++) { + mOsFile << digits[j] << std::endl; } } } } + std::cout << ">>----->>>" << triggers.size() << " " << digits.size() << std::endl; mExTimer.elapseMes("Dumping Digits received = " + std::to_string(mDigitsReceived)); return; } @@ -127,9 +130,7 @@ void DumpDigitsTask::endOfStream(framework::EndOfStreamContext& ec) //_________________________________________________________________________________________________ o2::framework::DataProcessorSpec getDumpDigitsSpec(std::string inputSpec) -//o2::framework::DataPrecessorSpec getDecodingSpec() { - std::vector inputs; inputs.emplace_back("digits", o2::header::gDataOriginHMP, "DIGITS", 0, Lifetime::Timeframe); inputs.emplace_back("intrecord", o2::header::gDataOriginHMP, "INTRECORDS", 0, Lifetime::Timeframe); diff --git a/Detectors/HMPID/workflow/src/WriteRawFileSpec.cxx b/Detectors/HMPID/workflow/src/WriteRawFileSpec.cxx index 74d8dfa6f64d1..15acf78c69513 100644 --- a/Detectors/HMPID/workflow/src/WriteRawFileSpec.cxx +++ b/Detectors/HMPID/workflow/src/WriteRawFileSpec.cxx @@ -81,12 +81,12 @@ void WriteRawFileTask::init(framework::InitContext& ic) void WriteRawFileTask::run(framework::ProcessingContext& pc) { - o2::InteractionRecord intReco; + std::vector triggers; std::vector digits; for (auto const& ref : InputRecordWalker(pc.inputs())) { if (DataRefUtils::match(ref, {"check", ConcreteDataTypeMatcher{gDataOriginHMP, "INTRECORDS"}})) { - intReco = pc.inputs().get(ref); + triggers = pc.inputs().get>(ref); } if (DataRefUtils::match(ref, {"check", ConcreteDataTypeMatcher{gDataOriginHMP, "DIGITS"}})) { digits = pc.inputs().get>(ref); @@ -94,12 +94,15 @@ void WriteRawFileTask::run(framework::ProcessingContext& pc) } } - if (mOrderTheEvents) { - int first = mDigits.size(); - mDigits.insert(mDigits.end(), digits.begin(), digits.end()); - mEvents.push_back({intReco, first, int(mDigits.size() - first)}); - } else { - mCod->codeEventChunkDigits(digits, intReco); + for (int i = 0; i < triggers.size(); i++) { + if (mOrderTheEvents) { + int first = mDigits.size(); + mDigits.insert(mDigits.end(), digits.begin() + triggers[i].getFirstEntry(), digits.begin() + triggers[i].getLastEntry()); + mEvents.push_back({triggers[i].getIr(), first, int(mDigits.size() - first)}); + } else { + std::vector dig = {digits.begin() + triggers[i].getFirstEntry(), digits.begin() + triggers[i].getLastEntry()}; + mCod->codeEventChunkDigits(dig, triggers[i].getIr()); + } } mDigitsReceived += digits.size(); mFramesReceived++; diff --git a/Detectors/HMPID/workflow/src/raw-to-digits-stream-workflow.cxx b/Detectors/HMPID/workflow/src/raw-to-digits-stream-workflow.cxx index 8c3d00d5be0a2..0c0d1278b03ef 100644 --- a/Detectors/HMPID/workflow/src/raw-to-digits-stream-workflow.cxx +++ b/Detectors/HMPID/workflow/src/raw-to-digits-stream-workflow.cxx @@ -53,7 +53,7 @@ void customize(std::vector& workflowOptions) } #include "Framework/runDataProcessing.h" -#include "HMPIDWorkflow/DataDecoderSpec.h" +#include "HMPIDWorkflow/DataDecoderSpec2.h" using namespace o2; using namespace o2::framework; @@ -63,7 +63,7 @@ WorkflowSpec defineDataProcessing(const ConfigContext& cx) WorkflowSpec specs; o2::conf::ConfigurableParam::updateFromString(cx.options().get("configKeyValues")); auto askSTFDist = !cx.options().get("ignore-dist-stf"); - DataProcessorSpec producer = o2::hmpid::getDecodingSpec(askSTFDist); + DataProcessorSpec producer = o2::hmpid::getDecodingSpec2(askSTFDist); specs.push_back(producer); return specs; } From 7cef9bd1b217dd2674604b2131cf4c5d6d052e14 Mon Sep 17 00:00:00 2001 From: shahoian Date: Sun, 9 May 2021 01:57:36 +0200 Subject: [PATCH 459/770] Add PrimaryVertex + related data to RecoContainer --- .../DataFormatsGlobalTracking/RecoContainer.h | 71 ++++++++++++++++++- .../GlobalTracking/src/RecoContainer.cxx | 65 +++++++++++++++++ 2 files changed, 135 insertions(+), 1 deletion(-) diff --git a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h index de4b1ee33fed0..c55aee300eb7d 100644 --- a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h +++ b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/RecoContainer.h @@ -59,6 +59,7 @@ struct DataRequest { std::unordered_map requestMap; void addInput(const o2::framework::InputSpec&& isp); + bool isRequested(const std::string& t) const { return !t.empty() && requestMap.find(t) != requestMap.end(); } void requestTracks(o2::dataformats::GlobalTrackID::mask_t src, bool mc); void requestClusters(o2::dataformats::GlobalTrackID::mask_t src, bool useMC); @@ -75,16 +76,28 @@ struct DataRequest { void requestTPCClusters(bool mc); void requestTOFClusters(bool mc); void requestTRDTracklets(bool mc); + + void requestPrimaryVertertices(bool mc); + void requestPrimaryVerterticesTMP(bool mc); }; struct RecoContainer { RecoContainer(); ~RecoContainer(); + + enum PVTXSlots { PVTX, + PVTX_TRMTC, + PVTX_TRMTCREFS, + PVTX_CONTID, + PVTX_CONTIDREFS, + PVTX_MCTR, + NPVTXSLOTS }; // slots to register primary vertex data + using TracksAccessor = o2::dataformats::GlobalTrackAccessor; using VariaAccessor = o2::dataformats::AbstractRefAccessor; // there is no unique structure, so the default return type is dummy (int) using MCAccessor = o2::dataformats::AbstractRefAccessor; + using PVertexAccessor = o2::dataformats::AbstractRefAccessor; using GTrackID = o2::dataformats::GlobalTrackID; - using GlobalIDSet = std::array; o2::InteractionRecord startIR; // TF start IR @@ -97,6 +110,8 @@ struct RecoContainer { VariaAccessor clustersPool; // container for clusters VariaAccessor miscPool; // container for misc info, e.g. patterns, match info w/o tracks etc. + PVertexAccessor pvtxPool; // containers for primary vertex related objects + std::unique_ptr> mcITSClusters; std::unique_ptr> mcTOFClusters; @@ -128,6 +143,9 @@ struct RecoContainer { void addFT0RecPoints(o2::framework::ProcessingContext& pc, bool mc); + void addPVertices(o2::framework::ProcessingContext& pc, bool mc); + void addPVerticesTMP(o2::framework::ProcessingContext& pc, bool mc); + // custom getters // get contributors from single detectors: return array with sources set to all contributing GTrackIDs @@ -157,6 +175,7 @@ struct RecoContainer { const o2::track::TrackParCov& getTrackParamOut(GTrackID gidx) const; //--- getters: to avoid exposing all headers here, we use templates + // ITS template // o2::its::TrackITS auto getITSTracks() const @@ -324,6 +343,56 @@ struct RecoContainer { { return miscPool.getSpan(GTrackID::FT0); } + + // ==================================================== + // Primary vertices + template // o2::dataformats::PrimaryVertex + auto getPrimaryVertices() const + { + return pvtxPool.getSpan(PVTX); + } + + template // o2::dataformats::PrimaryVertex + auto getPrimaryVertex(int i) const + { + return pvtxPool.get_as(PVTX, i); + } + + template // o2::dataformats::VtxTrackIndex + auto getPrimaryVertexMatchedTracks() const + { + return pvtxPool.getSpan(PVTX_TRMTC); + } + + template // o2::dataformats::VtxTrackIndex + auto getPrimaryVertexContributors() const + { + return pvtxPool.getSpan(PVTX_CONTID); + } + + template // o2::dataformats::VtxTrackRef + auto getPrimaryVertexMatchedTrackRefs() const + { + return pvtxPool.getSpan(PVTX_TRMTCREFS); + } + + template // o2::dataformats::VtxTrackRef + auto getPrimaryVertexContributorsRefs() const + { + return pvtxPool.getSpan(PVTX_CONTIDREFS); + } + + template // o2::MCEventLabel + auto getPrimaryVertexMCLabels() const + { + return pvtxPool.getSpan(PVTX_MCTR); + } + + template // o2::MCEventLabel + auto getPrimaryVertexMCLabel(int i) const + { + return pvtxPool.get_as(PVTX_MCTR, i); + } }; } // namespace globaltracking diff --git a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx index eeb0f1762ba42..c86b0d1028d0c 100644 --- a/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx +++ b/DataFormats/Detectors/GlobalTracking/src/RecoContainer.cxx @@ -15,6 +15,11 @@ #include #include #include "DataFormatsGlobalTracking/RecoContainerCreateTracksVariadic.h" +#include "CommonDataFormat/TimeStamp.h" +#include "ReconstructionDataFormats/VtxTrackIndex.h" +#include "ReconstructionDataFormats/VtxTrackRef.h" +#include "ReconstructionDataFormats/PrimaryVertex.h" +#include "SimulationDataFormat/MCEventLabel.h" using namespace o2::globaltracking; using namespace o2::framework; @@ -155,6 +160,28 @@ void DataRequest::requestFT0RecPoints(bool mc) requestMap["FT0"] = false; } +void DataRequest::requestPrimaryVertertices(bool mc) +{ + addInput({"pvtx", "GLO", "PVTX", 0, Lifetime::Timeframe}); + addInput({"pvtx_trmtc", "GLO", "PVTX_TRMTC", 0, Lifetime::Timeframe}); // global ids of associated tracks + addInput({"pvtx_tref", "GLO", "PVTX_TRMTCREFS", 0, Lifetime::Timeframe}); // vertex - trackID refs + if (mc) { + addInput({"pvtx_mc", "GLO", "PVTX_MCTR", 0, Lifetime::Timeframe}); + } + requestMap["PVertex"] = mc; +} + +void DataRequest::requestPrimaryVerterticesTMP(bool mc) // primary vertices before global vertex-track matching +{ + addInput({"pvtx", "GLO", "PVTX", 0, Lifetime::Timeframe}); + addInput({"pvtx_cont", "GLO", "PVTX_CONTID", 0, Lifetime::Timeframe}); // global ids of contributors + addInput({"pvtx_contref", "GLO", "PVTX_CONTIDREFS", 0, Lifetime::Timeframe}); // vertex - trackID refs of contributors + if (mc) { + addInput({"pvtx_mc", "GLO", "PVTX_MCTR", 0, Lifetime::Timeframe}); + } + requestMap["PVertexTMP"] = mc; +} + void DataRequest::requestTracks(GTrackID::mask_t src, bool useMC) { // request tracks for sources probided by the mask @@ -268,6 +295,44 @@ void RecoContainer::collectData(ProcessingContext& pc, const DataRequest& reques if (req != reqMap.end()) { addTRDTracklets(pc); } + + req = reqMap.find("PVertex"); + if (req != reqMap.end()) { + addPVertices(pc, req->second); + } + + req = reqMap.find("PVertexTMP"); + if (req != reqMap.end()) { + addPVerticesTMP(pc, req->second); + } +} + +//____________________________________________________________ +void RecoContainer::addPVertices(ProcessingContext& pc, bool mc) +{ + if (!pvtxPool.isLoaded(PVTX)) { // in case was loaded via addPVerticesTMP + pvtxPool.registerContainer(pc.inputs().get>("pvtx"), PVTX); + } + pvtxPool.registerContainer(pc.inputs().get>("pvtx_trmtc"), PVTX_TRMTC); + pvtxPool.registerContainer(pc.inputs().get>("pvtx_tref"), PVTX_TRMTCREFS); + + if (mc && !pvtxPool.isLoaded(PVTX_MCTR)) { // in case was loaded via addPVerticesTMP + pvtxPool.registerContainer(pc.inputs().get>("pvtx_mc"), PVTX_MCTR); + } +} + +//____________________________________________________________ +void RecoContainer::addPVerticesTMP(ProcessingContext& pc, bool mc) +{ + if (!pvtxPool.isLoaded(PVTX)) { // in case was loaded via addPVertices + pvtxPool.registerContainer(pc.inputs().get>("pvtx"), PVTX); + } + pvtxPool.registerContainer(pc.inputs().get>("pvtx_cont"), PVTX_CONTID); + pvtxPool.registerContainer(pc.inputs().get>("pvtx_contref"), PVTX_CONTIDREFS); + + if (mc && !pvtxPool.isLoaded(PVTX_MCTR)) { // in case was loaded via addPVertices + pvtxPool.registerContainer(pc.inputs().get>("pvtx_mc"), PVTX_MCTR); + } } //____________________________________________________________ From 9d95fac3b36b21a920861b1ac57cb26a4f440664 Mon Sep 17 00:00:00 2001 From: shahoian Date: Sun, 9 May 2021 01:58:05 +0200 Subject: [PATCH 460/770] Add PrimaryVertexReader to InputHelper --- .../GlobalTrackingWorkflowHelpers/InputHelper.h | 1 + .../helpers/src/InputHelper.cxx | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/Detectors/GlobalTrackingWorkflow/helpers/include/GlobalTrackingWorkflowHelpers/InputHelper.h b/Detectors/GlobalTrackingWorkflow/helpers/include/GlobalTrackingWorkflowHelpers/InputHelper.h index 14ea58ed91811..6d2ecbe63b504 100644 --- a/Detectors/GlobalTrackingWorkflow/helpers/include/GlobalTrackingWorkflowHelpers/InputHelper.h +++ b/Detectors/GlobalTrackingWorkflow/helpers/include/GlobalTrackingWorkflowHelpers/InputHelper.h @@ -30,6 +30,7 @@ class InputHelper // The masks define what data to load in a quite generic way, masks with MC suffix are for the corresponding MC labels. // For matched tracks, maskMatches refers only to the matching information, while the corresponding maskTracks can still be set to load also the refit matched tracks static int addInputSpecs(const o2::framework::ConfigContext& configcontext, o2::framework::WorkflowSpec& specs, GID::mask_t maskClusters, GID::mask_t maskMatches, GID::mask_t maskTracks, bool useMC = true, GID::mask_t maskClustersMC = GID::getSourcesMask(GID::ALL), GID::mask_t maskTracksMC = GID::getSourcesMask(GID::ALL)); + static int addInputSpecsPVertex(const o2::framework::ConfigContext& configcontext, o2::framework::WorkflowSpec& specs, bool mc); }; } // namespace globaltracking diff --git a/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx b/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx index 451b4071cd093..408bffdcf7c52 100644 --- a/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx +++ b/Detectors/GlobalTrackingWorkflow/helpers/src/InputHelper.cxx @@ -18,6 +18,7 @@ #include "TPCReaderWorkflow/ClusterReaderSpec.h" #include "TPCWorkflow/ClusterSharingMapSpec.h" #include "GlobalTrackingWorkflowReaders/TrackTPCITSReaderSpec.h" +#include "GlobalTrackingWorkflowReaders/PrimaryVertexReaderSpec.h" #include "TOFWorkflowUtils/ClusterReaderSpec.h" #include "TOFWorkflow/TOFMatchedReaderSpec.h" #include "FT0Workflow/RecPointReaderSpec.h" @@ -84,3 +85,13 @@ int InputHelper::addInputSpecs(const ConfigContext& configcontext, WorkflowSpec& return 0; } + +// attach primary vertex reader +int InputHelper::addInputSpecsPVertex(const o2::framework::ConfigContext& configcontext, o2::framework::WorkflowSpec& specs, bool mc) +{ + if (configcontext.options().get("disable-root-input")) { + return 0; + } + specs.emplace_back(o2::vertexing::getPrimaryVertexReaderSpec(mc)); + return 0; +} \ No newline at end of file From c26552b5fc90bc8d4c60b4b12fc6024755e10b04 Mon Sep 17 00:00:00 2001 From: shahoian Date: Sun, 9 May 2021 01:59:13 +0200 Subject: [PATCH 461/770] Use PVertex via RecoContainer in the workflows --- .../PrimaryVertexReaderSpec.h | 46 ------------------- .../readers/src/PrimaryVertexReaderSpec.cxx | 43 +++++++++++++++++ .../src/SecondaryVertexingSpec.cxx | 17 ++----- .../src/VertexTrackMatcherSpec.cxx | 39 +++------------- .../src/secondary-vertexing-workflow.cxx | 6 +-- .../include/DetectorsVertexing/SVertexer.h | 7 +-- .../DetectorsVertexing/VertexTrackMatcher.h | 10 +--- Detectors/Vertexing/src/SVertexer.cxx | 20 ++++---- .../Vertexing/src/VertexTrackMatcher.cxx | 13 +++--- 9 files changed, 73 insertions(+), 128 deletions(-) diff --git a/Detectors/GlobalTrackingWorkflow/readers/include/GlobalTrackingWorkflowReaders/PrimaryVertexReaderSpec.h b/Detectors/GlobalTrackingWorkflow/readers/include/GlobalTrackingWorkflowReaders/PrimaryVertexReaderSpec.h index 6a32eb2c537ce..5bec7935d64a1 100644 --- a/Detectors/GlobalTrackingWorkflow/readers/include/GlobalTrackingWorkflowReaders/PrimaryVertexReaderSpec.h +++ b/Detectors/GlobalTrackingWorkflow/readers/include/GlobalTrackingWorkflowReaders/PrimaryVertexReaderSpec.h @@ -13,59 +13,13 @@ #ifndef O2_PRIMARY_VERTEXREADER #define O2_PRIMARY_VERTEXREADER -#include "TFile.h" -#include "TTree.h" - #include "Framework/DataProcessorSpec.h" #include "Framework/Task.h" -#include "CommonDataFormat/TimeStamp.h" -#include "ReconstructionDataFormats/VtxTrackIndex.h" -#include "ReconstructionDataFormats/VtxTrackRef.h" -#include "ReconstructionDataFormats/PrimaryVertex.h" -#include "SimulationDataFormat/MCEventLabel.h" - namespace o2 { namespace vertexing { -// read primary vertices produces by the o2-primary-vertexing-workflow - -class PrimaryVertexReader : public o2::framework::Task -{ - using Label = o2::MCEventLabel; - using V2TRef = o2::dataformats::VtxTrackRef; - using PVertex = o2::dataformats::PrimaryVertex; - using GIndex = o2::dataformats::VtxTrackIndex; - - public: - PrimaryVertexReader(bool useMC) : mUseMC(useMC) {} - ~PrimaryVertexReader() override = default; - void init(o2::framework::InitContext& ic) final; - void run(o2::framework::ProcessingContext& pc) final; - - protected: - void connectTree(); - - bool mVerbose = false; - bool mUseMC = false; - - std::vector mVertices, *mVerticesPtr = &mVertices; - std::vector